jasonfan commited on
Commit
5570451
·
verified ·
1 Parent(s): 5f14d18

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/conditional_detr/modeling_conditional_detr.py +1847 -0
  2. miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/conditional_detr/modular_conditional_detr.py +978 -0
  3. miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/convbert/__init__.py +29 -0
  4. miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/convbert/configuration_convbert.py +142 -0
  5. miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/convbert/modeling_convbert.py +1148 -0
  6. miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/convbert/tokenization_convbert.py +30 -0
  7. miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/convnext/__init__.py +30 -0
  8. miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/convnext/configuration_convnext.py +117 -0
  9. miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/convnext/image_processing_convnext.py +329 -0
  10. miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/convnext/image_processing_convnext_fast.py +165 -0
  11. miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/convnext/modeling_convnext.py +410 -0
  12. miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/convnextv2/__init__.py +27 -0
  13. miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/convnextv2/configuration_convnextv2.py +115 -0
  14. miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/convnextv2/modeling_convnextv2.py +433 -0
  15. miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/cpm/__init__.py +26 -0
  16. miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/cpm/tokenization_cpm.py +336 -0
  17. miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/cpm/tokenization_cpm_fast.py +232 -0
  18. miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/cpmant/__init__.py +28 -0
  19. miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/cpmant/configuration_cpmant.py +125 -0
  20. miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/cpmant/modeling_cpmant.py +785 -0
  21. miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/cpmant/tokenization_cpmant.py +232 -0
  22. miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/csm/__init__.py +28 -0
  23. miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/csm/configuration_csm.py +359 -0
  24. miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/csm/generation_csm.py +488 -0
  25. miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/csm/modeling_csm.py +1117 -0
  26. miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/csm/modular_csm.py +767 -0
  27. miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/csm/processing_csm.py +322 -0
  28. miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/ctrl/__init__.py +28 -0
  29. miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/ctrl/configuration_ctrl.py +131 -0
  30. miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/ctrl/modeling_ctrl.py +688 -0
  31. miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/ctrl/tokenization_ctrl.py +226 -0
  32. miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/cvt/__init__.py +27 -0
  33. miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/cvt/configuration_cvt.py +145 -0
  34. miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/cvt/modeling_cvt.py +641 -0
  35. miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/cwm/__init__.py +28 -0
  36. miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/cwm/configuration_cwm.py +187 -0
  37. miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/cwm/modeling_cwm.py +515 -0
  38. miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/cwm/modular_cwm.py +295 -0
  39. miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/d_fine/__init__.py +29 -0
  40. miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/d_fine/configuration_d_fine.py +354 -0
  41. miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/d_fine/modeling_d_fine.py +2063 -0
  42. miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/d_fine/modular_d_fine.py +1141 -0
  43. miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/dab_detr/__init__.py +28 -0
  44. miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/dab_detr/configuration_dab_detr.py +235 -0
  45. miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/dab_detr/modeling_dab_detr.py +1598 -0
  46. miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/dac/__init__.py +28 -0
  47. miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/dac/configuration_dac.py +113 -0
  48. miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/dac/feature_extraction_dac.py +170 -0
  49. miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/dac/modeling_dac.py +689 -0
  50. miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/data2vec/__init__.py +31 -0
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/conditional_detr/modeling_conditional_detr.py ADDED
@@ -0,0 +1,1847 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/conditional_detr/modular_conditional_detr.py.
3
+ # Do NOT edit this file manually as any edits will be overwritten by the generation of
4
+ # the file from the modular. If any change should be done, please apply the change to the
5
+ # modular_conditional_detr.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # Copyright 2022 Microsoft Research Asia and The HuggingFace Inc. team. All rights reserved.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ import math
21
+ from collections.abc import Callable
22
+ from dataclasses import dataclass
23
+
24
+ import torch
25
+ from torch import nn
26
+
27
+ from ... import initialization as init
28
+ from ...activations import ACT2FN
29
+ from ...backbone_utils import load_backbone
30
+ from ...masking_utils import create_bidirectional_mask
31
+ from ...modeling_layers import GradientCheckpointingLayer
32
+ from ...modeling_outputs import BaseModelOutput, BaseModelOutputWithCrossAttentions, Seq2SeqModelOutput
33
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
34
+ from ...processing_utils import Unpack
35
+ from ...pytorch_utils import compile_compatible_method_lru_cache
36
+ from ...utils import ModelOutput, TransformersKwargs, auto_docstring
37
+ from ...utils.generic import can_return_tuple, merge_with_config_defaults
38
+ from ...utils.output_capturing import OutputRecorder, capture_outputs
39
+ from .configuration_conditional_detr import ConditionalDetrConfig
40
+
41
+
42
+ @dataclass
43
+ @auto_docstring(
44
+ custom_intro="""
45
+ Base class for outputs of the CONDITIONAL_DETR decoder. This class adds one attribute to BaseModelOutputWithCrossAttentions,
46
+ namely an optional stack of intermediate decoder activations, i.e. the output of each decoder layer, each of them
47
+ gone through a layernorm. This is useful when training the model with auxiliary decoding losses.
48
+ """
49
+ )
50
+ class ConditionalDetrDecoderOutput(BaseModelOutputWithCrossAttentions):
51
+ r"""
52
+ cross_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` and `config.add_cross_attention=True` is passed or when `config.output_attentions=True`):
53
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
54
+ sequence_length)`. Attentions weights of the decoder's cross-attention layer, after the attention softmax,
55
+ used to compute the weighted average in the cross-attention heads.
56
+ intermediate_hidden_states (`torch.FloatTensor` of shape `(config.decoder_layers, batch_size, num_queries, hidden_size)`, *optional*, returned when `config.auxiliary_loss=True`):
57
+ Intermediate decoder activations, i.e. the output of each decoder layer, each of them gone through a
58
+ layernorm.
59
+ reference_points (`torch.FloatTensor` of shape `(config.decoder_layers, batch_size, num_queries, 2 (anchor points))`):
60
+ Reference points (reference points of each layer of the decoder).
61
+ """
62
+
63
+ intermediate_hidden_states: torch.FloatTensor | None = None
64
+
65
+ reference_points: tuple[torch.FloatTensor] | None = None
66
+
67
+
68
+ @dataclass
69
+ @auto_docstring(
70
+ custom_intro="""
71
+ Base class for outputs of the CONDITIONAL_DETR encoder-decoder model. This class adds one attribute to Seq2SeqModelOutput,
72
+ namely an optional stack of intermediate decoder activations, i.e. the output of each decoder layer, each of them
73
+ gone through a layernorm. This is useful when training the model with auxiliary decoding losses.
74
+ """
75
+ )
76
+ class ConditionalDetrModelOutput(Seq2SeqModelOutput):
77
+ r"""
78
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
79
+ Sequence of hidden-states at the output of the last layer of the decoder of the model.
80
+ intermediate_hidden_states (`torch.FloatTensor` of shape `(config.decoder_layers, batch_size, sequence_length, hidden_size)`, *optional*, returned when `config.auxiliary_loss=True`):
81
+ Intermediate decoder activations, i.e. the output of each decoder layer, each of them gone through a
82
+ layernorm.
83
+ reference_points (`torch.FloatTensor` of shape `(config.decoder_layers, batch_size, num_queries, 2 (anchor points))`):
84
+ Reference points (reference points of each layer of the decoder).
85
+ """
86
+
87
+ intermediate_hidden_states: torch.FloatTensor | None = None
88
+
89
+ reference_points: tuple[torch.FloatTensor] | None = None
90
+
91
+
92
+ @dataclass
93
+ @auto_docstring(
94
+ custom_intro="""
95
+ Output type of [`ConditionalDetrForObjectDetection`].
96
+ """
97
+ )
98
+ class ConditionalDetrObjectDetectionOutput(ModelOutput):
99
+ r"""
100
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` are provided)):
101
+ Total loss as a linear combination of a negative log-likehood (cross-entropy) for class prediction and a
102
+ bounding box loss. The latter is defined as a linear combination of the L1 loss and the generalized
103
+ scale-invariant IoU loss.
104
+ loss_dict (`Dict`, *optional*):
105
+ A dictionary containing the individual losses. Useful for logging.
106
+ logits (`torch.FloatTensor` of shape `(batch_size, num_queries, num_classes + 1)`):
107
+ Classification logits (including no-object) for all queries.
108
+ pred_boxes (`torch.FloatTensor` of shape `(batch_size, num_queries, 4)`):
109
+ Normalized boxes coordinates for all queries, represented as (center_x, center_y, width, height). These
110
+ values are normalized in [0, 1], relative to the size of each individual image in the batch (disregarding
111
+ possible padding). You can use [`~ConditionalDetrImageProcessor.post_process_object_detection`] to retrieve the
112
+ unnormalized bounding boxes.
113
+ auxiliary_outputs (`list[Dict]`, *optional*):
114
+ Optional, only returned when auxiliary losses are activated (i.e. `config.auxiliary_loss` is set to `True`)
115
+ and labels are provided. It is a list of dictionaries containing the two above keys (`logits` and
116
+ `pred_boxes`) for each decoder layer.
117
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
118
+ Sequence of hidden-states at the output of the last layer of the decoder of the model.
119
+ """
120
+
121
+ loss: torch.FloatTensor | None = None
122
+ loss_dict: dict | None = None
123
+ logits: torch.FloatTensor | None = None
124
+ pred_boxes: torch.FloatTensor | None = None
125
+ auxiliary_outputs: list[dict] | None = None
126
+ last_hidden_state: torch.FloatTensor | None = None
127
+ decoder_hidden_states: tuple[torch.FloatTensor] | None = None
128
+ decoder_attentions: tuple[torch.FloatTensor] | None = None
129
+ cross_attentions: tuple[torch.FloatTensor] | None = None
130
+ encoder_last_hidden_state: torch.FloatTensor | None = None
131
+ encoder_hidden_states: tuple[torch.FloatTensor] | None = None
132
+ encoder_attentions: tuple[torch.FloatTensor] | None = None
133
+
134
+
135
+ @dataclass
136
+ @auto_docstring(
137
+ custom_intro="""
138
+ Output type of [`ConditionalDetrForSegmentation`].
139
+ """
140
+ )
141
+ class ConditionalDetrSegmentationOutput(ModelOutput):
142
+ r"""
143
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` are provided)):
144
+ Total loss as a linear combination of a negative log-likehood (cross-entropy) for class prediction and a
145
+ bounding box loss. The latter is defined as a linear combination of the L1 loss and the generalized
146
+ scale-invariant IoU loss.
147
+ loss_dict (`Dict`, *optional*):
148
+ A dictionary containing the individual losses. Useful for logging.
149
+ logits (`torch.FloatTensor` of shape `(batch_size, num_queries, num_classes + 1)`):
150
+ Classification logits (including no-object) for all queries.
151
+ pred_boxes (`torch.FloatTensor` of shape `(batch_size, num_queries, 4)`):
152
+ Normalized boxes coordinates for all queries, represented as (center_x, center_y, width, height). These
153
+ values are normalized in [0, 1], relative to the size of each individual image in the batch (disregarding
154
+ possible padding). You can use [`~ConditionalDetrImageProcessor.post_process_object_detection`] to retrieve the
155
+ unnormalized bounding boxes.
156
+ pred_masks (`torch.FloatTensor` of shape `(batch_size, num_queries, height/4, width/4)`):
157
+ Segmentation masks logits for all queries. See also
158
+ [`~ConditionalDetrImageProcessor.post_process_semantic_segmentation`] or
159
+ [`~ConditionalDetrImageProcessor.post_process_instance_segmentation`]
160
+ [`~ConditionalDetrImageProcessor.post_process_panoptic_segmentation`] to evaluate semantic, instance and panoptic
161
+ segmentation masks respectively.
162
+ auxiliary_outputs (`list[Dict]`, *optional*):
163
+ Optional, only returned when auxiliary losses are activated (i.e. `config.auxiliary_loss` is set to `True`)
164
+ and labels are provided. It is a list of dictionaries containing the two above keys (`logits` and
165
+ `pred_boxes`) for each decoder layer.
166
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
167
+ Sequence of hidden-states at the output of the last layer of the decoder of the model.
168
+ """
169
+
170
+ loss: torch.FloatTensor | None = None
171
+ loss_dict: dict | None = None
172
+ logits: torch.FloatTensor | None = None
173
+ pred_boxes: torch.FloatTensor | None = None
174
+ pred_masks: torch.FloatTensor | None = None
175
+ auxiliary_outputs: list[dict] | None = None
176
+ last_hidden_state: torch.FloatTensor | None = None
177
+ decoder_hidden_states: tuple[torch.FloatTensor] | None = None
178
+ decoder_attentions: tuple[torch.FloatTensor] | None = None
179
+ cross_attentions: tuple[torch.FloatTensor] | None = None
180
+ encoder_last_hidden_state: torch.FloatTensor | None = None
181
+ encoder_hidden_states: tuple[torch.FloatTensor] | None = None
182
+ encoder_attentions: tuple[torch.FloatTensor] | None = None
183
+
184
+
185
+ class ConditionalDetrFrozenBatchNorm2d(nn.Module):
186
+ """
187
+ BatchNorm2d where the batch statistics and the affine parameters are fixed.
188
+
189
+ Copy-paste from torchvision.misc.ops with added eps before rqsrt, without which any other models than
190
+ torchvision.models.resnet[18,34,50,101] produce nans.
191
+ """
192
+
193
+ def __init__(self, n):
194
+ super().__init__()
195
+ self.register_buffer("weight", torch.ones(n))
196
+ self.register_buffer("bias", torch.zeros(n))
197
+ self.register_buffer("running_mean", torch.zeros(n))
198
+ self.register_buffer("running_var", torch.ones(n))
199
+
200
+ def _load_from_state_dict(
201
+ self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs
202
+ ):
203
+ num_batches_tracked_key = prefix + "num_batches_tracked"
204
+ if num_batches_tracked_key in state_dict:
205
+ del state_dict[num_batches_tracked_key]
206
+
207
+ super()._load_from_state_dict(
208
+ state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs
209
+ )
210
+
211
+ def forward(self, x):
212
+ # move reshapes to the beginning
213
+ # to make it user-friendly
214
+ weight = self.weight.reshape(1, -1, 1, 1)
215
+ bias = self.bias.reshape(1, -1, 1, 1)
216
+ running_var = self.running_var.reshape(1, -1, 1, 1)
217
+ running_mean = self.running_mean.reshape(1, -1, 1, 1)
218
+ epsilon = 1e-5
219
+ scale = weight * (running_var + epsilon).rsqrt()
220
+ bias = bias - running_mean * scale
221
+ return x * scale + bias
222
+
223
+
224
+ def replace_batch_norm(model):
225
+ r"""
226
+ Recursively replace all `torch.nn.BatchNorm2d` with `ConditionalDetrFrozenBatchNorm2d`.
227
+
228
+ Args:
229
+ model (torch.nn.Module):
230
+ input model
231
+ """
232
+ for name, module in model.named_children():
233
+ if isinstance(module, nn.BatchNorm2d):
234
+ new_module = ConditionalDetrFrozenBatchNorm2d(module.num_features)
235
+
236
+ if module.weight.device != torch.device("meta"):
237
+ new_module.weight.copy_(module.weight)
238
+ new_module.bias.copy_(module.bias)
239
+ new_module.running_mean.copy_(module.running_mean)
240
+ new_module.running_var.copy_(module.running_var)
241
+
242
+ model._modules[name] = new_module
243
+
244
+ if len(list(module.children())) > 0:
245
+ replace_batch_norm(module)
246
+
247
+
248
+ class ConditionalDetrConvEncoder(nn.Module):
249
+ """
250
+ Convolutional backbone, using either the AutoBackbone API or one from the timm library.
251
+
252
+ nn.BatchNorm2d layers are replaced by ConditionalDetrFrozenBatchNorm2d as defined above.
253
+
254
+ """
255
+
256
+ def __init__(self, config):
257
+ super().__init__()
258
+
259
+ self.config = config
260
+
261
+ backbone = load_backbone(config)
262
+ self.intermediate_channel_sizes = backbone.channels
263
+
264
+ # replace batch norm by frozen batch norm
265
+ with torch.no_grad():
266
+ replace_batch_norm(backbone)
267
+
268
+ # We used to load with timm library directly instead of the AutoBackbone API
269
+ # so we need to unwrap the `backbone._backbone` module to load weights without mismatch
270
+ is_timm_model = False
271
+ if hasattr(backbone, "_backbone"):
272
+ backbone = backbone._backbone
273
+ is_timm_model = True
274
+ self.model = backbone
275
+
276
+ backbone_model_type = config.backbone_config.model_type
277
+ if "resnet" in backbone_model_type:
278
+ for name, parameter in self.model.named_parameters():
279
+ if is_timm_model:
280
+ if "layer2" not in name and "layer3" not in name and "layer4" not in name:
281
+ parameter.requires_grad_(False)
282
+ else:
283
+ if "stage.1" not in name and "stage.2" not in name and "stage.3" not in name:
284
+ parameter.requires_grad_(False)
285
+
286
+ def forward(self, pixel_values: torch.Tensor, pixel_mask: torch.Tensor):
287
+ # send pixel_values through the model to get list of feature maps
288
+ features = self.model(pixel_values)
289
+ if isinstance(features, dict):
290
+ features = features.feature_maps
291
+
292
+ out = []
293
+ for feature_map in features:
294
+ # downsample pixel_mask to match shape of corresponding feature_map
295
+ mask = nn.functional.interpolate(pixel_mask[None].float(), size=feature_map.shape[-2:]).to(torch.bool)[0]
296
+ out.append((feature_map, mask))
297
+ return out
298
+
299
+
300
+ class ConditionalDetrSinePositionEmbedding(nn.Module):
301
+ """
302
+ This is a more standard version of the position embedding, very similar to the one used by the Attention is all you
303
+ need paper, generalized to work on images.
304
+ """
305
+
306
+ def __init__(
307
+ self,
308
+ num_position_features: int = 64,
309
+ temperature: int = 10000,
310
+ normalize: bool = False,
311
+ scale: float | None = None,
312
+ ):
313
+ super().__init__()
314
+ if scale is not None and normalize is False:
315
+ raise ValueError("normalize should be True if scale is passed")
316
+ self.num_position_features = num_position_features
317
+ self.temperature = temperature
318
+ self.normalize = normalize
319
+ self.scale = 2 * math.pi if scale is None else scale
320
+
321
+ @compile_compatible_method_lru_cache(maxsize=1)
322
+ def forward(
323
+ self,
324
+ shape: torch.Size,
325
+ device: torch.device | str,
326
+ dtype: torch.dtype,
327
+ mask: torch.Tensor | None = None,
328
+ ) -> torch.Tensor:
329
+ if mask is None:
330
+ mask = torch.zeros((shape[0], shape[2], shape[3]), device=device, dtype=torch.bool)
331
+ y_embed = mask.cumsum(1, dtype=dtype)
332
+ x_embed = mask.cumsum(2, dtype=dtype)
333
+ if self.normalize:
334
+ eps = 1e-6
335
+ y_embed = y_embed / (y_embed[:, -1:, :] + eps) * self.scale
336
+ x_embed = x_embed / (x_embed[:, :, -1:] + eps) * self.scale
337
+
338
+ dim_t = torch.arange(self.num_position_features, dtype=torch.int64, device=device).to(dtype)
339
+ dim_t = self.temperature ** (2 * torch.div(dim_t, 2, rounding_mode="floor") / self.num_position_features)
340
+
341
+ pos_x = x_embed[:, :, :, None] / dim_t
342
+ pos_y = y_embed[:, :, :, None] / dim_t
343
+ pos_x = torch.stack((pos_x[:, :, :, 0::2].sin(), pos_x[:, :, :, 1::2].cos()), dim=4).flatten(3)
344
+ pos_y = torch.stack((pos_y[:, :, :, 0::2].sin(), pos_y[:, :, :, 1::2].cos()), dim=4).flatten(3)
345
+ pos = torch.cat((pos_y, pos_x), dim=3).permute(0, 3, 1, 2)
346
+ # Flatten spatial dimensions and permute to (batch_size, sequence_length, hidden_size) format
347
+ # expected by the encoder
348
+ pos = pos.flatten(2).permute(0, 2, 1)
349
+ return pos
350
+
351
+
352
+ class ConditionalDetrLearnedPositionEmbedding(nn.Module):
353
+ """
354
+ This module learns positional embeddings up to a fixed maximum size.
355
+ """
356
+
357
+ def __init__(self, embedding_dim=256):
358
+ super().__init__()
359
+ self.row_embeddings = nn.Embedding(50, embedding_dim)
360
+ self.column_embeddings = nn.Embedding(50, embedding_dim)
361
+
362
+ @compile_compatible_method_lru_cache(maxsize=1)
363
+ def forward(
364
+ self,
365
+ shape: torch.Size,
366
+ device: torch.device | str,
367
+ dtype: torch.dtype,
368
+ mask: torch.Tensor | None = None,
369
+ ):
370
+ height, width = shape[-2:]
371
+ width_values = torch.arange(width, device=device)
372
+ height_values = torch.arange(height, device=device)
373
+ x_emb = self.column_embeddings(width_values)
374
+ y_emb = self.row_embeddings(height_values)
375
+ pos = torch.cat([x_emb.unsqueeze(0).repeat(height, 1, 1), y_emb.unsqueeze(1).repeat(1, width, 1)], dim=-1)
376
+ pos = pos.permute(2, 0, 1)
377
+ pos = pos.unsqueeze(0)
378
+ pos = pos.repeat(shape[0], 1, 1, 1)
379
+ # Flatten spatial dimensions and permute to (batch_size, sequence_length, hidden_size) format
380
+ # expected by the encoder
381
+ pos = pos.flatten(2).permute(0, 2, 1)
382
+ return pos
383
+
384
+
385
+ def eager_attention_forward(
386
+ module: nn.Module,
387
+ query: torch.Tensor,
388
+ key: torch.Tensor,
389
+ value: torch.Tensor,
390
+ attention_mask: torch.Tensor | None,
391
+ scaling: float | None = None,
392
+ dropout: float = 0.0,
393
+ **kwargs: Unpack[TransformersKwargs],
394
+ ):
395
+ if scaling is None:
396
+ scaling = query.size(-1) ** -0.5
397
+
398
+ # Take the dot product between "query" and "key" to get the raw attention scores.
399
+ attn_weights = torch.matmul(query, key.transpose(2, 3)) * scaling
400
+
401
+ if attention_mask is not None:
402
+ attn_weights = attn_weights + attention_mask
403
+
404
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
405
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
406
+
407
+ attn_output = torch.matmul(attn_weights, value)
408
+ attn_output = attn_output.transpose(1, 2).contiguous()
409
+
410
+ return attn_output, attn_weights
411
+
412
+
413
+ class ConditionalDetrSelfAttention(nn.Module):
414
+ """
415
+ Multi-headed self-attention from 'Attention Is All You Need' paper.
416
+
417
+ In CONDITIONAL_DETR, position embeddings are added to both queries and keys (but not values) in self-attention.
418
+ """
419
+
420
+ def __init__(
421
+ self,
422
+ config: ConditionalDetrConfig,
423
+ hidden_size: int,
424
+ num_attention_heads: int,
425
+ dropout: float = 0.0,
426
+ bias: bool = True,
427
+ ):
428
+ super().__init__()
429
+ self.config = config
430
+ self.head_dim = hidden_size // num_attention_heads
431
+ self.scaling = self.head_dim**-0.5
432
+ self.attention_dropout = dropout
433
+ self.is_causal = False
434
+
435
+ self.k_proj = nn.Linear(hidden_size, hidden_size, bias=bias)
436
+ self.v_proj = nn.Linear(hidden_size, hidden_size, bias=bias)
437
+ self.q_proj = nn.Linear(hidden_size, hidden_size, bias=bias)
438
+ self.o_proj = nn.Linear(hidden_size, hidden_size, bias=bias)
439
+
440
+ def forward(
441
+ self,
442
+ hidden_states: torch.Tensor,
443
+ attention_mask: torch.Tensor | None = None,
444
+ position_embeddings: torch.Tensor | None = None,
445
+ **kwargs: Unpack[TransformersKwargs],
446
+ ) -> tuple[torch.Tensor, torch.Tensor]:
447
+ """
448
+ Position embeddings are added to both queries and keys (but not values).
449
+ """
450
+ input_shape = hidden_states.shape[:-1]
451
+ hidden_shape = (*input_shape, -1, self.head_dim)
452
+
453
+ query_key_input = hidden_states + position_embeddings if position_embeddings is not None else hidden_states
454
+
455
+ query_states = self.q_proj(query_key_input).view(hidden_shape).transpose(1, 2)
456
+ key_states = self.k_proj(query_key_input).view(hidden_shape).transpose(1, 2)
457
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
458
+
459
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
460
+ self.config._attn_implementation, eager_attention_forward
461
+ )
462
+
463
+ attn_output, attn_weights = attention_interface(
464
+ self,
465
+ query_states,
466
+ key_states,
467
+ value_states,
468
+ attention_mask,
469
+ dropout=0.0 if not self.training else self.attention_dropout,
470
+ scaling=self.scaling,
471
+ **kwargs,
472
+ )
473
+
474
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
475
+ attn_output = self.o_proj(attn_output)
476
+ return attn_output, attn_weights
477
+
478
+
479
+ class ConditionalDetrDecoderSelfAttention(nn.Module):
480
+ """
481
+ Multi-headed self-attention for Conditional DETR decoder layers.
482
+
483
+ This attention module handles separate content and position projections, which are then combined
484
+ before applying standard self-attention. Position embeddings are added to both queries and keys.
485
+ """
486
+
487
+ def __init__(
488
+ self,
489
+ config: ConditionalDetrConfig,
490
+ hidden_size: int,
491
+ num_attention_heads: int,
492
+ dropout: float = 0.0,
493
+ ):
494
+ super().__init__()
495
+ self.config = config
496
+ self.hidden_size = hidden_size
497
+ self.head_dim = hidden_size // num_attention_heads
498
+ self.scaling = self.head_dim**-0.5
499
+ self.attention_dropout = dropout
500
+ self.is_causal = False
501
+
502
+ # Content and position projections
503
+ self.q_content_proj = nn.Linear(hidden_size, hidden_size)
504
+ self.q_pos_proj = nn.Linear(hidden_size, hidden_size)
505
+ self.k_content_proj = nn.Linear(hidden_size, hidden_size)
506
+ self.k_pos_proj = nn.Linear(hidden_size, hidden_size)
507
+ self.v_proj = nn.Linear(hidden_size, hidden_size)
508
+ self.o_proj = nn.Linear(hidden_size, hidden_size)
509
+
510
+ def forward(
511
+ self,
512
+ hidden_states: torch.Tensor,
513
+ query_position_embeddings: torch.Tensor,
514
+ attention_mask: torch.Tensor | None = None,
515
+ **kwargs: Unpack[TransformersKwargs],
516
+ ) -> tuple[torch.Tensor, torch.Tensor]:
517
+ """
518
+ Args:
519
+ hidden_states (`torch.Tensor` of shape `(batch_size, num_queries, hidden_size)`):
520
+ Input hidden states from the decoder layer.
521
+ query_position_embeddings (`torch.Tensor` of shape `(batch_size, num_queries, hidden_size)`):
522
+ Position embeddings for queries and keys. Required (unlike standard attention). Processed through
523
+ separate position projections (`q_pos_proj`, `k_pos_proj`) and added to content projections.
524
+ attention_mask (`torch.Tensor` of shape `(batch_size, 1, num_queries, num_queries)`, *optional*):
525
+ Attention mask to avoid attending to padding tokens.
526
+ """
527
+ input_shape = hidden_states.shape[:-1]
528
+ hidden_shape = (*input_shape, -1, self.head_dim)
529
+
530
+ query_states = (
531
+ (self.q_content_proj(hidden_states) + self.q_pos_proj(query_position_embeddings))
532
+ .view(hidden_shape)
533
+ .transpose(1, 2)
534
+ )
535
+ key_states = (
536
+ (self.k_content_proj(hidden_states) + self.k_pos_proj(query_position_embeddings))
537
+ .view(hidden_shape)
538
+ .transpose(1, 2)
539
+ )
540
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
541
+
542
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
543
+ self.config._attn_implementation, eager_attention_forward
544
+ )
545
+
546
+ attn_output, attn_weights = attention_interface(
547
+ self,
548
+ query_states,
549
+ key_states,
550
+ value_states,
551
+ attention_mask,
552
+ dropout=0.0 if not self.training else self.attention_dropout,
553
+ scaling=self.scaling,
554
+ **kwargs,
555
+ )
556
+
557
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
558
+ attn_output = self.o_proj(attn_output)
559
+ return attn_output, attn_weights
560
+
561
+
562
+ class ConditionalDetrDecoderCrossAttention(nn.Module):
563
+ """
564
+ Multi-headed cross-attention for Conditional DETR decoder layers.
565
+
566
+ This attention module handles the special cross-attention logic in Conditional DETR:
567
+ - Separate content and position projections for queries and keys
568
+ - Concatenation of query sine embeddings with queries (doubling query dimension)
569
+ - Concatenation of key position embeddings with keys (doubling key dimension)
570
+ - Output dimension remains hidden_size despite doubled input dimensions
571
+ """
572
+
573
+ def __init__(
574
+ self,
575
+ config: ConditionalDetrConfig,
576
+ hidden_size: int,
577
+ num_attention_heads: int,
578
+ dropout: float = 0.0,
579
+ ):
580
+ super().__init__()
581
+ self.config = config
582
+ self.hidden_size = hidden_size
583
+ self.num_attention_heads = num_attention_heads
584
+ self.head_dim = hidden_size // num_attention_heads
585
+ self.attention_dropout = dropout
586
+ self.is_causal = False
587
+
588
+ # Content and position projections
589
+ self.q_content_proj = nn.Linear(hidden_size, hidden_size)
590
+ self.q_pos_proj = nn.Linear(hidden_size, hidden_size)
591
+ self.k_content_proj = nn.Linear(hidden_size, hidden_size)
592
+ self.k_pos_proj = nn.Linear(hidden_size, hidden_size)
593
+ self.v_proj = nn.Linear(hidden_size, hidden_size)
594
+ self.q_pos_sine_proj = nn.Linear(hidden_size, hidden_size)
595
+
596
+ # Output projection: input is hidden_size * 2 (from concatenated q/k), output is hidden_size
597
+ self.o_proj = nn.Linear(hidden_size, hidden_size)
598
+
599
+ # Compute scaling for expanded head_dim (q and k have doubled dimensions after concatenation)
600
+ # This matches the original Conditional DETR implementation where embed_dim * 2 is used
601
+ expanded_head_dim = (hidden_size * 2) // num_attention_heads
602
+ self.scaling = expanded_head_dim**-0.5
603
+
604
+ def forward(
605
+ self,
606
+ hidden_states: torch.Tensor,
607
+ encoder_hidden_states: torch.Tensor,
608
+ query_sine_embed: torch.Tensor,
609
+ encoder_position_embeddings: torch.Tensor,
610
+ query_position_embeddings: torch.Tensor | None = None,
611
+ attention_mask: torch.Tensor | None = None,
612
+ **kwargs: Unpack[TransformersKwargs],
613
+ ) -> tuple[torch.Tensor, torch.Tensor]:
614
+ """
615
+ Args:
616
+ hidden_states (`torch.Tensor` of shape `(batch_size, num_queries, hidden_size)`):
617
+ Decoder hidden states (queries).
618
+ encoder_hidden_states (`torch.Tensor` of shape `(batch_size, encoder_seq_len, hidden_size)`):
619
+ Encoder output hidden states (keys and values).
620
+ query_sine_embed (`torch.Tensor` of shape `(batch_size, num_queries, hidden_size)`):
621
+ Sine position embeddings for queries. **Concatenated** (not added) with query content,
622
+ doubling the query dimension.
623
+ encoder_position_embeddings (`torch.Tensor` of shape `(batch_size, encoder_seq_len, hidden_size)`):
624
+ Position embeddings for keys. **Concatenated** (not added) with key content, doubling the key dimension.
625
+ query_position_embeddings (`torch.Tensor` of shape `(batch_size, num_queries, hidden_size)`, *optional*):
626
+ Additional position embeddings. When provided (first layer only), **added** to query content
627
+ before concatenation with `query_sine_embed`. Also causes `encoder_position_embeddings` to be
628
+ added to key content before concatenation.
629
+ attention_mask (`torch.Tensor` of shape `(batch_size, 1, num_queries, encoder_seq_len)`, *optional*):
630
+ Attention mask to avoid attending to padding tokens.
631
+ """
632
+ query_input_shape = hidden_states.shape[:-1]
633
+ kv_input_shape = encoder_hidden_states.shape[:-1]
634
+ query_hidden_shape = (*query_input_shape, self.num_attention_heads, self.head_dim)
635
+ kv_hidden_shape = (*kv_input_shape, self.num_attention_heads, self.head_dim)
636
+
637
+ # Apply content and position projections
638
+ query_input = self.q_content_proj(hidden_states)
639
+ key_input = self.k_content_proj(encoder_hidden_states)
640
+ value_states = self.v_proj(encoder_hidden_states)
641
+ key_pos = self.k_pos_proj(encoder_position_embeddings)
642
+
643
+ # Combine content and position embeddings
644
+ if query_position_embeddings is not None:
645
+ query_input = query_input + self.q_pos_proj(query_position_embeddings)
646
+ key_input = key_input + key_pos
647
+
648
+ # Reshape and concatenate position embeddings (doubling head_dim)
649
+ query_input = query_input.view(query_hidden_shape)
650
+ key_input = key_input.view(kv_hidden_shape)
651
+ query_sine_embed = self.q_pos_sine_proj(query_sine_embed).view(query_hidden_shape)
652
+ key_pos = key_pos.view(kv_hidden_shape)
653
+
654
+ query_states = torch.cat([query_input, query_sine_embed], dim=-1).view(*query_input_shape, -1)
655
+ key_states = torch.cat([key_input, key_pos], dim=-1).view(*kv_input_shape, -1)
656
+
657
+ # Reshape for attention computation
658
+ expanded_head_dim = query_states.shape[-1] // self.num_attention_heads
659
+ query_states = query_states.view(*query_input_shape, self.num_attention_heads, expanded_head_dim).transpose(
660
+ 1, 2
661
+ )
662
+ key_states = key_states.view(*kv_input_shape, self.num_attention_heads, expanded_head_dim).transpose(1, 2)
663
+ value_states = value_states.view(kv_hidden_shape).transpose(1, 2)
664
+
665
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
666
+ self.config._attn_implementation, eager_attention_forward
667
+ )
668
+
669
+ attn_output, attn_weights = attention_interface(
670
+ self,
671
+ query_states,
672
+ key_states,
673
+ value_states,
674
+ attention_mask,
675
+ dropout=0.0 if not self.training else self.attention_dropout,
676
+ scaling=self.scaling,
677
+ **kwargs,
678
+ )
679
+
680
+ attn_output = attn_output.reshape(*query_input_shape, -1).contiguous()
681
+ attn_output = self.o_proj(attn_output)
682
+ return attn_output, attn_weights
683
+
684
+
685
+ class ConditionalDetrMLP(nn.Module):
686
+ def __init__(self, config: ConditionalDetrConfig, hidden_size: int, intermediate_size: int):
687
+ super().__init__()
688
+ self.fc1 = nn.Linear(hidden_size, intermediate_size)
689
+ self.fc2 = nn.Linear(intermediate_size, hidden_size)
690
+ self.activation_fn = ACT2FN[config.activation_function]
691
+ self.activation_dropout = config.activation_dropout
692
+ self.dropout = config.dropout
693
+
694
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
695
+ hidden_states = self.activation_fn(self.fc1(hidden_states))
696
+ hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
697
+ hidden_states = self.fc2(hidden_states)
698
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
699
+ return hidden_states
700
+
701
+
702
+ class ConditionalDetrEncoderLayer(GradientCheckpointingLayer):
703
+ def __init__(self, config: ConditionalDetrConfig):
704
+ super().__init__()
705
+ self.hidden_size = config.d_model
706
+ self.self_attn = ConditionalDetrSelfAttention(
707
+ config=config,
708
+ hidden_size=self.hidden_size,
709
+ num_attention_heads=config.encoder_attention_heads,
710
+ dropout=config.attention_dropout,
711
+ )
712
+ self.self_attn_layer_norm = nn.LayerNorm(self.hidden_size)
713
+ self.dropout = config.dropout
714
+ self.mlp = ConditionalDetrMLP(config, self.hidden_size, config.encoder_ffn_dim)
715
+ self.final_layer_norm = nn.LayerNorm(self.hidden_size)
716
+
717
+ def forward(
718
+ self,
719
+ hidden_states: torch.Tensor,
720
+ attention_mask: torch.Tensor,
721
+ spatial_position_embeddings: torch.Tensor | None = None,
722
+ **kwargs: Unpack[TransformersKwargs],
723
+ ) -> torch.Tensor:
724
+ """
725
+ Args:
726
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, hidden_size)`
727
+ attention_mask (`torch.FloatTensor`): attention mask of size
728
+ `(batch, 1, target_len, source_len)` where padding elements are indicated by very large negative
729
+ values.
730
+ spatial_position_embeddings (`torch.FloatTensor`, *optional*):
731
+ Spatial position embeddings (2D positional encodings of image locations), to be added to both
732
+ the queries and keys in self-attention (but not to values).
733
+ """
734
+ residual = hidden_states
735
+ hidden_states, _ = self.self_attn(
736
+ hidden_states=hidden_states,
737
+ attention_mask=attention_mask,
738
+ position_embeddings=spatial_position_embeddings,
739
+ **kwargs,
740
+ )
741
+
742
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
743
+ hidden_states = residual + hidden_states
744
+ hidden_states = self.self_attn_layer_norm(hidden_states)
745
+
746
+ residual = hidden_states
747
+ hidden_states = self.mlp(hidden_states)
748
+ hidden_states = residual + hidden_states
749
+ hidden_states = self.final_layer_norm(hidden_states)
750
+
751
+ if self.training:
752
+ if not torch.isfinite(hidden_states).all():
753
+ clamp_value = torch.finfo(hidden_states.dtype).max - 1000
754
+ hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)
755
+
756
+ return hidden_states
757
+
758
+
759
+ class ConditionalDetrDecoderLayer(GradientCheckpointingLayer):
760
+ def __init__(self, config: ConditionalDetrConfig):
761
+ super().__init__()
762
+ self.hidden_size = config.d_model
763
+ self.self_attn = ConditionalDetrDecoderSelfAttention(
764
+ config=config,
765
+ hidden_size=self.hidden_size,
766
+ num_attention_heads=config.decoder_attention_heads,
767
+ dropout=config.attention_dropout,
768
+ )
769
+ self.dropout = config.dropout
770
+
771
+ self.self_attn_layer_norm = nn.LayerNorm(self.hidden_size)
772
+ self.encoder_attn = ConditionalDetrDecoderCrossAttention(
773
+ config=config,
774
+ hidden_size=self.hidden_size,
775
+ num_attention_heads=config.decoder_attention_heads,
776
+ dropout=config.attention_dropout,
777
+ )
778
+ self.encoder_attn_layer_norm = nn.LayerNorm(self.hidden_size)
779
+ self.mlp = ConditionalDetrMLP(config, self.hidden_size, config.decoder_ffn_dim)
780
+ self.final_layer_norm = nn.LayerNorm(self.hidden_size)
781
+
782
+ def forward(
783
+ self,
784
+ hidden_states: torch.Tensor,
785
+ attention_mask: torch.Tensor | None = None,
786
+ spatial_position_embeddings: torch.Tensor | None = None,
787
+ query_position_embeddings: torch.Tensor | None = None,
788
+ query_sine_embed: torch.Tensor | None = None,
789
+ encoder_hidden_states: torch.Tensor | None = None,
790
+ encoder_attention_mask: torch.Tensor | None = None,
791
+ is_first: bool | None = False,
792
+ **kwargs: Unpack[TransformersKwargs],
793
+ ) -> torch.Tensor:
794
+ """
795
+ Args:
796
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(seq_len, batch, embed_dim)`
797
+ attention_mask (`torch.FloatTensor`): attention mask of size
798
+ `(batch, 1, target_len, source_len)` where padding elements are indicated by very large negative
799
+ values.
800
+ spatial_position_embeddings (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
801
+ Spatial position embeddings (2D positional encodings) that are added to the queries and keys in each self-attention layer.
802
+ query_position_embeddings (`torch.FloatTensor`, *optional*):
803
+ object_queries that are added to the queries and keys
804
+ in the self-attention layer.
805
+ encoder_hidden_states (`torch.FloatTensor`):
806
+ cross attention input to the layer of shape `(seq_len, batch, embed_dim)`
807
+ encoder_attention_mask (`torch.FloatTensor`): encoder attention mask of size
808
+ `(batch, 1, target_len, source_len)` where padding elements are indicated by very large negative
809
+ values.
810
+ output_attentions (`bool`, *optional*):
811
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
812
+ returned tensors for more detail.
813
+ """
814
+ residual = hidden_states
815
+
816
+ hidden_states, _ = self.self_attn(
817
+ hidden_states=hidden_states,
818
+ query_position_embeddings=query_position_embeddings,
819
+ attention_mask=attention_mask,
820
+ **kwargs,
821
+ )
822
+
823
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
824
+ hidden_states = residual + hidden_states
825
+ hidden_states = self.self_attn_layer_norm(hidden_states)
826
+
827
+ if encoder_hidden_states is not None:
828
+ residual = hidden_states
829
+
830
+ hidden_states, _ = self.encoder_attn(
831
+ hidden_states=hidden_states,
832
+ encoder_hidden_states=encoder_hidden_states,
833
+ attention_mask=encoder_attention_mask,
834
+ query_sine_embed=query_sine_embed,
835
+ encoder_position_embeddings=spatial_position_embeddings,
836
+ # Only pass query_position_embeddings for the first layer
837
+ query_position_embeddings=query_position_embeddings if is_first else None,
838
+ **kwargs,
839
+ )
840
+
841
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
842
+ hidden_states = residual + hidden_states
843
+ hidden_states = self.encoder_attn_layer_norm(hidden_states)
844
+
845
+ # Fully Connected
846
+ residual = hidden_states
847
+ hidden_states = self.mlp(hidden_states)
848
+ hidden_states = residual + hidden_states
849
+ hidden_states = self.final_layer_norm(hidden_states)
850
+
851
+ return hidden_states
852
+
853
+
854
+ class ConditionalDetrMLPPredictionHead(nn.Module):
855
+ """
856
+ Very simple multi-layer perceptron (MLP, also called FFN), used to predict the normalized center coordinates,
857
+ height and width of a bounding box w.r.t. an image.
858
+
859
+ """
860
+
861
+ def __init__(self, input_dim, hidden_dim, output_dim, num_layers):
862
+ super().__init__()
863
+ self.num_layers = num_layers
864
+ h = [hidden_dim] * (num_layers - 1)
865
+ self.layers = nn.ModuleList(nn.Linear(n, k) for n, k in zip([input_dim] + h, h + [output_dim]))
866
+
867
+ def forward(self, x):
868
+ for i, layer in enumerate(self.layers):
869
+ x = nn.functional.relu(layer(x)) if i < self.num_layers - 1 else layer(x)
870
+ return x
871
+
872
+
873
+ class ConditionalDetrConvBlock(nn.Module):
874
+ """Basic conv block: Conv3x3 -> GroupNorm -> Activation."""
875
+
876
+ def __init__(self, in_channels: int, out_channels: int, activation: str = "relu"):
877
+ super().__init__()
878
+ self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1)
879
+ self.norm = nn.GroupNorm(min(8, out_channels), out_channels)
880
+ self.activation = ACT2FN[activation]
881
+
882
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
883
+ return self.activation(self.norm(self.conv(x)))
884
+
885
+
886
+ class ConditionalDetrFPNFusionStage(nn.Module):
887
+ """Single FPN fusion stage combining low-resolution features with high-resolution FPN features."""
888
+
889
+ def __init__(self, fpn_channels: int, current_channels: int, output_channels: int, activation: str = "relu"):
890
+ super().__init__()
891
+ self.fpn_adapter = nn.Conv2d(fpn_channels, current_channels, kernel_size=1)
892
+ self.refine = ConditionalDetrConvBlock(current_channels, output_channels, activation)
893
+
894
+ def forward(self, features: torch.Tensor, fpn_features: torch.Tensor) -> torch.Tensor:
895
+ """
896
+ Args:
897
+ features: Current features to upsample, shape (B*Q, current_channels, H_in, W_in)
898
+ fpn_features: FPN features at target resolution, shape (B*Q, fpn_channels, H_out, W_out)
899
+
900
+ Returns:
901
+ Fused and refined features, shape (B*Q, output_channels, H_out, W_out)
902
+ """
903
+ fpn_features = self.fpn_adapter(fpn_features)
904
+ features = nn.functional.interpolate(features, size=fpn_features.shape[-2:], mode="nearest")
905
+ return self.refine(fpn_features + features)
906
+
907
+
908
+ class ConditionalDetrMaskHeadSmallConv(nn.Module):
909
+ """
910
+ Segmentation mask head that generates per-query masks using FPN-based progressive upsampling.
911
+
912
+ Combines attention maps (spatial localization) with encoder features (semantics) and progressively
913
+ upsamples through multiple scales, fusing with FPN features for high-resolution detail.
914
+ """
915
+
916
+ def __init__(
917
+ self,
918
+ input_channels: int,
919
+ fpn_channels: list[int],
920
+ hidden_size: int,
921
+ activation_function: str = "relu",
922
+ ):
923
+ super().__init__()
924
+ if input_channels % 8 != 0:
925
+ raise ValueError(f"input_channels must be divisible by 8, got {input_channels}")
926
+
927
+ self.conv1 = ConditionalDetrConvBlock(input_channels, input_channels, activation_function)
928
+ self.conv2 = ConditionalDetrConvBlock(input_channels, hidden_size // 2, activation_function)
929
+
930
+ # Progressive channel reduction: /2 -> /4 -> /8 -> /16
931
+ self.fpn_stages = nn.ModuleList(
932
+ [
933
+ ConditionalDetrFPNFusionStage(
934
+ fpn_channels[0], hidden_size // 2, hidden_size // 4, activation_function
935
+ ),
936
+ ConditionalDetrFPNFusionStage(
937
+ fpn_channels[1], hidden_size // 4, hidden_size // 8, activation_function
938
+ ),
939
+ ConditionalDetrFPNFusionStage(
940
+ fpn_channels[2], hidden_size // 8, hidden_size // 16, activation_function
941
+ ),
942
+ ]
943
+ )
944
+
945
+ self.output_conv = nn.Conv2d(hidden_size // 16, 1, kernel_size=3, padding=1)
946
+
947
+ def forward(
948
+ self,
949
+ features: torch.Tensor,
950
+ attention_masks: torch.Tensor,
951
+ fpn_features: list[torch.Tensor],
952
+ ) -> torch.Tensor:
953
+ """
954
+ Args:
955
+ features: Encoder output features, shape (batch_size, hidden_size, H, W)
956
+ attention_masks: Cross-attention maps from decoder, shape (batch_size, num_queries, num_heads, H, W)
957
+ fpn_features: List of 3 FPN features from low to high resolution, each (batch_size, C, H, W)
958
+
959
+ Returns:
960
+ Predicted masks, shape (batch_size * num_queries, 1, output_H, output_W)
961
+ """
962
+ num_queries = attention_masks.shape[1]
963
+
964
+ # Expand to (batch_size * num_queries) dimension
965
+ features = features.unsqueeze(1).expand(-1, num_queries, -1, -1, -1).flatten(0, 1)
966
+ attention_masks = attention_masks.flatten(0, 1)
967
+ fpn_features = [
968
+ fpn_feat.unsqueeze(1).expand(-1, num_queries, -1, -1, -1).flatten(0, 1) for fpn_feat in fpn_features
969
+ ]
970
+
971
+ hidden_states = torch.cat([features, attention_masks], dim=1)
972
+ hidden_states = self.conv1(hidden_states)
973
+ hidden_states = self.conv2(hidden_states)
974
+
975
+ for fpn_stage, fpn_feat in zip(self.fpn_stages, fpn_features):
976
+ hidden_states = fpn_stage(hidden_states, fpn_feat)
977
+
978
+ return self.output_conv(hidden_states)
979
+
980
+
981
+ class ConditionalDetrMHAttentionMap(nn.Module):
982
+ """This is a 2D attention module, which only returns the attention softmax (no multiplication by value)"""
983
+
984
+ def __init__(
985
+ self,
986
+ hidden_size: int,
987
+ num_attention_heads: int,
988
+ dropout: float = 0.0,
989
+ bias: bool = True,
990
+ ):
991
+ super().__init__()
992
+ self.head_dim = hidden_size // num_attention_heads
993
+ self.scaling = self.head_dim**-0.5
994
+ self.attention_dropout = dropout
995
+
996
+ self.q_proj = nn.Linear(hidden_size, hidden_size, bias=bias)
997
+ self.k_proj = nn.Linear(hidden_size, hidden_size, bias=bias)
998
+
999
+ def forward(
1000
+ self, query_states: torch.Tensor, key_states: torch.Tensor, attention_mask: torch.Tensor | None = None
1001
+ ):
1002
+ query_hidden_shape = (*query_states.shape[:-1], -1, self.head_dim)
1003
+ key_hidden_shape = (key_states.shape[0], -1, self.head_dim, *key_states.shape[-2:])
1004
+
1005
+ query_states = self.q_proj(query_states).view(query_hidden_shape)
1006
+ key_states = nn.functional.conv2d(
1007
+ key_states, self.k_proj.weight.unsqueeze(-1).unsqueeze(-1), self.k_proj.bias
1008
+ ).view(key_hidden_shape)
1009
+
1010
+ batch_size, num_queries, num_heads, head_dim = query_states.shape
1011
+ _, _, _, height, width = key_states.shape
1012
+ query_shape = (batch_size * num_heads, num_queries, head_dim)
1013
+ key_shape = (batch_size * num_heads, height * width, head_dim)
1014
+ attn_weights_shape = (batch_size, num_heads, num_queries, height, width)
1015
+
1016
+ query = query_states.transpose(1, 2).contiguous().view(query_shape)
1017
+ key = key_states.permute(0, 1, 3, 4, 2).contiguous().view(key_shape)
1018
+
1019
+ attn_weights = (
1020
+ (torch.matmul(query * self.scaling, key.transpose(1, 2))).view(attn_weights_shape).transpose(1, 2)
1021
+ )
1022
+
1023
+ if attention_mask is not None:
1024
+ attn_weights = attn_weights + attention_mask
1025
+
1026
+ attn_weights = nn.functional.softmax(attn_weights.flatten(2), dim=-1).view(attn_weights.size())
1027
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
1028
+
1029
+ return attn_weights
1030
+
1031
+
1032
+ @auto_docstring
1033
+ class ConditionalDetrPreTrainedModel(PreTrainedModel):
1034
+ config: ConditionalDetrConfig
1035
+ base_model_prefix = "model"
1036
+ main_input_name = "pixel_values"
1037
+ input_modalities = ("image",)
1038
+ _no_split_modules = [r"ConditionalDetrConvEncoder", r"ConditionalDetrEncoderLayer", r"ConditionalDetrDecoderLayer"]
1039
+ supports_gradient_checkpointing = True
1040
+ _supports_sdpa = True
1041
+ _supports_flash_attn = True
1042
+ _supports_attention_backend = True
1043
+ _supports_flex_attn = True # Uses create_bidirectional_masks for attention masking
1044
+ _keys_to_ignore_on_load_unexpected = [
1045
+ r"detr\.model\.backbone\.model\.layer\d+\.0\.downsample\.1\.num_batches_tracked"
1046
+ ]
1047
+
1048
+ @torch.no_grad()
1049
+ def _init_weights(self, module):
1050
+ std = self.config.init_std
1051
+ xavier_std = self.config.init_xavier_std
1052
+
1053
+ if isinstance(module, ConditionalDetrMaskHeadSmallConv):
1054
+ # ConditionalDetrMaskHeadSmallConv uses kaiming initialization for all its Conv2d layers
1055
+ for m in module.modules():
1056
+ if isinstance(m, nn.Conv2d):
1057
+ init.kaiming_uniform_(m.weight, a=1)
1058
+ if m.bias is not None:
1059
+ init.constant_(m.bias, 0)
1060
+ elif isinstance(module, ConditionalDetrMHAttentionMap):
1061
+ init.zeros_(module.k_proj.bias)
1062
+ init.zeros_(module.q_proj.bias)
1063
+ init.xavier_uniform_(module.k_proj.weight, gain=xavier_std)
1064
+ init.xavier_uniform_(module.q_proj.weight, gain=xavier_std)
1065
+ elif isinstance(module, ConditionalDetrLearnedPositionEmbedding):
1066
+ init.uniform_(module.row_embeddings.weight)
1067
+ init.uniform_(module.column_embeddings.weight)
1068
+ elif isinstance(module, (nn.Linear, nn.Conv2d)):
1069
+ init.normal_(module.weight, mean=0.0, std=std)
1070
+ if module.bias is not None:
1071
+ init.zeros_(module.bias)
1072
+ elif isinstance(module, nn.Embedding):
1073
+ init.normal_(module.weight, mean=0.0, std=std)
1074
+ # Here we need the check explicitly, as we slice the weight in the `zeros_` call, so it looses the flag
1075
+ if module.padding_idx is not None and not getattr(module.weight, "_is_hf_initialized", False):
1076
+ init.zeros_(module.weight[module.padding_idx])
1077
+ elif isinstance(module, (nn.LayerNorm, nn.GroupNorm)):
1078
+ init.ones_(module.weight)
1079
+ init.zeros_(module.bias)
1080
+
1081
+
1082
+ class ConditionalDetrEncoder(ConditionalDetrPreTrainedModel):
1083
+ """
1084
+ Transformer encoder that processes a flattened feature map from a vision backbone, composed of a stack of
1085
+ [`ConditionalDetrEncoderLayer`] modules.
1086
+
1087
+ Args:
1088
+ config (`ConditionalDetrConfig`): Model configuration object.
1089
+ """
1090
+
1091
+ _can_record_outputs = {"hidden_states": ConditionalDetrEncoderLayer, "attentions": ConditionalDetrSelfAttention}
1092
+
1093
+ def __init__(self, config: ConditionalDetrConfig):
1094
+ super().__init__(config)
1095
+
1096
+ self.dropout = config.dropout
1097
+ self.layers = nn.ModuleList([ConditionalDetrEncoderLayer(config) for _ in range(config.encoder_layers)])
1098
+
1099
+ # Initialize weights and apply final processing
1100
+ self.post_init()
1101
+
1102
+ @merge_with_config_defaults
1103
+ @capture_outputs
1104
+ def forward(
1105
+ self,
1106
+ inputs_embeds=None,
1107
+ attention_mask=None,
1108
+ spatial_position_embeddings=None,
1109
+ **kwargs: Unpack[TransformersKwargs],
1110
+ ) -> BaseModelOutput:
1111
+ r"""
1112
+ Args:
1113
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
1114
+ Flattened feature map (output of the backbone + projection layer) that is passed to the encoder.
1115
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1116
+ Mask to avoid performing attention on padding pixel features. Mask values selected in `[0, 1]`:
1117
+
1118
+ - 1 for pixel features that are real (i.e. **not masked**),
1119
+ - 0 for pixel features that are padding (i.e. **masked**).
1120
+
1121
+ [What are attention masks?](../glossary#attention-mask)
1122
+ spatial_position_embeddings (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
1123
+ Spatial position embeddings (2D positional encodings) that are added to the queries and keys in each self-attention layer.
1124
+ """
1125
+ hidden_states = inputs_embeds
1126
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
1127
+
1128
+ attention_mask = create_bidirectional_mask(
1129
+ config=self.config,
1130
+ inputs_embeds=inputs_embeds,
1131
+ attention_mask=attention_mask,
1132
+ )
1133
+
1134
+ for encoder_layer in self.layers:
1135
+ # we add spatial_position_embeddings as extra input to the encoder_layer
1136
+ hidden_states = encoder_layer(
1137
+ hidden_states, attention_mask, spatial_position_embeddings=spatial_position_embeddings, **kwargs
1138
+ )
1139
+
1140
+ return BaseModelOutput(last_hidden_state=hidden_states)
1141
+
1142
+
1143
+ # function to generate sine positional embedding for 2d coordinates
1144
+ def gen_sine_position_embeddings(pos_tensor, d_model):
1145
+ scale = 2 * math.pi
1146
+ dim = d_model // 2
1147
+ dim_t = torch.arange(dim, dtype=torch.float32, device=pos_tensor.device)
1148
+ dim_t = 10000 ** (2 * torch.div(dim_t, 2, rounding_mode="floor") / dim)
1149
+ x_embed = pos_tensor[:, :, 0] * scale
1150
+ y_embed = pos_tensor[:, :, 1] * scale
1151
+ pos_x = x_embed[:, :, None] / dim_t
1152
+ pos_y = y_embed[:, :, None] / dim_t
1153
+ pos_x = torch.stack((pos_x[:, :, 0::2].sin(), pos_x[:, :, 1::2].cos()), dim=3).flatten(2)
1154
+ pos_y = torch.stack((pos_y[:, :, 0::2].sin(), pos_y[:, :, 1::2].cos()), dim=3).flatten(2)
1155
+ pos = torch.cat((pos_y, pos_x), dim=2)
1156
+ return pos.to(pos_tensor.dtype)
1157
+
1158
+
1159
+ class ConditionalDetrDecoder(ConditionalDetrPreTrainedModel):
1160
+ """
1161
+ Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a [`ConditionalDetrDecoderLayer`].
1162
+
1163
+ The decoder updates the query embeddings through multiple self-attention and cross-attention layers.
1164
+
1165
+ Some small tweaks for Conditional DETR:
1166
+
1167
+ - object_queries and query_position_embeddings are added to the forward pass.
1168
+ - if self.config.auxiliary_loss is set to True, also returns a stack of activations from all decoding layers.
1169
+
1170
+ Args:
1171
+ config: ConditionalDetrConfig
1172
+ """
1173
+
1174
+ _can_record_outputs = {
1175
+ "hidden_states": ConditionalDetrDecoderLayer,
1176
+ "attentions": OutputRecorder(ConditionalDetrDecoderSelfAttention, layer_name="self_attn", index=1),
1177
+ "cross_attentions": OutputRecorder(ConditionalDetrDecoderCrossAttention, layer_name="encoder_attn", index=1),
1178
+ }
1179
+
1180
+ def __init__(self, config: ConditionalDetrConfig):
1181
+ super().__init__(config)
1182
+ self.hidden_size = config.d_model
1183
+
1184
+ self.dropout = config.dropout
1185
+ self.layerdrop = config.decoder_layerdrop
1186
+
1187
+ self.layers = nn.ModuleList([ConditionalDetrDecoderLayer(config) for _ in range(config.decoder_layers)])
1188
+ # in Conditional DETR, the decoder uses layernorm after the last decoder layer output
1189
+ self.layernorm = nn.LayerNorm(config.d_model)
1190
+
1191
+ # query_scale is the FFN applied on f to generate transformation T
1192
+ self.query_scale = ConditionalDetrMLPPredictionHead(self.hidden_size, self.hidden_size, self.hidden_size, 2)
1193
+ self.ref_point_head = ConditionalDetrMLPPredictionHead(self.hidden_size, self.hidden_size, 2, 2)
1194
+ for layer_id in range(config.decoder_layers - 1):
1195
+ # Set q_pos_proj to None for layers after the first (only first layer uses query position embeddings)
1196
+ self.layers[layer_id + 1].encoder_attn.q_pos_proj = None
1197
+
1198
+ # Initialize weights and apply final processing
1199
+ self.post_init()
1200
+
1201
+ @merge_with_config_defaults
1202
+ @capture_outputs
1203
+ def forward(
1204
+ self,
1205
+ inputs_embeds=None,
1206
+ attention_mask=None,
1207
+ encoder_hidden_states=None,
1208
+ encoder_attention_mask=None,
1209
+ spatial_position_embeddings=None,
1210
+ object_queries_position_embeddings=None,
1211
+ **kwargs: Unpack[TransformersKwargs],
1212
+ ) -> ConditionalDetrDecoderOutput:
1213
+ r"""
1214
+ Args:
1215
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
1216
+ The query embeddings that are passed into the decoder.
1217
+
1218
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1219
+ Mask to avoid performing attention on certain queries. Mask values selected in `[0, 1]`:
1220
+
1221
+ - 1 for queries that are **not masked**,
1222
+ - 0 for queries that are **masked**.
1223
+
1224
+ [What are attention masks?](../glossary#attention-mask)
1225
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*):
1226
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
1227
+ of the decoder.
1228
+ encoder_attention_mask (`torch.LongTensor` of shape `(batch_size, encoder_sequence_length)`, *optional*):
1229
+ Mask to avoid performing cross-attention on padding pixel_values of the encoder. Mask values selected
1230
+ in `[0, 1]`:
1231
+
1232
+ - 1 for pixels that are real (i.e. **not masked**),
1233
+ - 0 for pixels that are padding (i.e. **masked**).
1234
+
1235
+ spatial_position_embeddings (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1236
+ Spatial position embeddings that are added to the queries and keys in each cross-attention layer.
1237
+ object_queries_position_embeddings (`torch.FloatTensor` of shape `(batch_size, num_queries, hidden_size)`):
1238
+ , *optional*): Position embeddings that are added to the queries and keys in each self-attention layer.
1239
+ """
1240
+ if inputs_embeds is not None:
1241
+ hidden_states = inputs_embeds
1242
+
1243
+ # expand encoder attention mask
1244
+ if encoder_hidden_states is not None and encoder_attention_mask is not None:
1245
+ # [batch_size, seq_len] -> [batch_size, 1, target_seq_len, source_seq_len]
1246
+ encoder_attention_mask = create_bidirectional_mask(
1247
+ self.config,
1248
+ inputs_embeds,
1249
+ encoder_attention_mask,
1250
+ )
1251
+
1252
+ # optional intermediate hidden states
1253
+ intermediate = () if self.config.auxiliary_loss else None
1254
+
1255
+ reference_points_before_sigmoid = self.ref_point_head(
1256
+ object_queries_position_embeddings
1257
+ ) # [num_queries, batch_size, 2]
1258
+ reference_points = reference_points_before_sigmoid.sigmoid().transpose(0, 1)
1259
+ obj_center = reference_points[..., :2].transpose(0, 1)
1260
+ # get sine embedding for the query vector
1261
+ query_sine_embed_before_transformation = gen_sine_position_embeddings(obj_center, self.config.d_model)
1262
+
1263
+ for idx, decoder_layer in enumerate(self.layers):
1264
+ if self.training:
1265
+ dropout_probability = torch.rand([])
1266
+ if dropout_probability < self.layerdrop:
1267
+ continue
1268
+ if idx == 0:
1269
+ pos_transformation = 1
1270
+ else:
1271
+ pos_transformation = self.query_scale(hidden_states)
1272
+ # apply transformation
1273
+ query_sine_embed = query_sine_embed_before_transformation * pos_transformation
1274
+
1275
+ hidden_states = decoder_layer(
1276
+ hidden_states,
1277
+ None,
1278
+ spatial_position_embeddings,
1279
+ object_queries_position_embeddings,
1280
+ query_sine_embed,
1281
+ encoder_hidden_states, # as a positional argument for gradient checkpointing
1282
+ encoder_attention_mask=encoder_attention_mask,
1283
+ is_first=(idx == 0),
1284
+ **kwargs,
1285
+ )
1286
+
1287
+ if self.config.auxiliary_loss:
1288
+ hidden_states = self.layernorm(hidden_states)
1289
+ intermediate += (hidden_states,)
1290
+
1291
+ # finally, apply layernorm
1292
+ hidden_states = self.layernorm(hidden_states)
1293
+
1294
+ # stack intermediate decoder activations
1295
+ if self.config.auxiliary_loss:
1296
+ intermediate = torch.stack(intermediate)
1297
+
1298
+ return ConditionalDetrDecoderOutput(
1299
+ last_hidden_state=hidden_states,
1300
+ intermediate_hidden_states=intermediate,
1301
+ reference_points=reference_points,
1302
+ )
1303
+
1304
+
1305
+ @auto_docstring(
1306
+ custom_intro="""
1307
+ The bare CONDITIONAL_DETR Model (consisting of a backbone and encoder-decoder Transformer) outputting raw hidden-states without
1308
+ any specific head on top.
1309
+ """
1310
+ )
1311
+ class ConditionalDetrModel(ConditionalDetrPreTrainedModel):
1312
+ def __init__(self, config: ConditionalDetrConfig):
1313
+ super().__init__(config)
1314
+
1315
+ self.backbone = ConditionalDetrConvEncoder(config)
1316
+
1317
+ if config.position_embedding_type == "sine":
1318
+ self.position_embedding = ConditionalDetrSinePositionEmbedding(config.d_model // 2, normalize=True)
1319
+ elif config.position_embedding_type == "learned":
1320
+ self.position_embedding = ConditionalDetrLearnedPositionEmbedding(config.d_model // 2)
1321
+ else:
1322
+ raise ValueError(f"Not supported {config.position_embedding_type}")
1323
+ self.query_position_embeddings = nn.Embedding(config.num_queries, config.d_model)
1324
+ self.input_projection = nn.Conv2d(self.backbone.intermediate_channel_sizes[-1], config.d_model, kernel_size=1)
1325
+
1326
+ self.encoder = ConditionalDetrEncoder(config)
1327
+ self.decoder = ConditionalDetrDecoder(config)
1328
+
1329
+ # Initialize weights and apply final processing
1330
+ self.post_init()
1331
+
1332
+ def freeze_backbone(self):
1333
+ for _, param in self.backbone.model.named_parameters():
1334
+ param.requires_grad_(False)
1335
+
1336
+ def unfreeze_backbone(self):
1337
+ for _, param in self.backbone.model.named_parameters():
1338
+ param.requires_grad_(True)
1339
+
1340
+ @auto_docstring
1341
+ @can_return_tuple
1342
+ def forward(
1343
+ self,
1344
+ pixel_values: torch.FloatTensor,
1345
+ pixel_mask: torch.LongTensor | None = None,
1346
+ decoder_attention_mask: torch.LongTensor | None = None,
1347
+ encoder_outputs: torch.FloatTensor | None = None,
1348
+ inputs_embeds: torch.FloatTensor | None = None,
1349
+ decoder_inputs_embeds: torch.FloatTensor | None = None,
1350
+ **kwargs: Unpack[TransformersKwargs],
1351
+ ) -> ConditionalDetrModelOutput:
1352
+ r"""
1353
+ decoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, num_queries)`, *optional*):
1354
+ Not used by default. Can be used to mask object queries.
1355
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1356
+ Optionally, instead of passing the flattened feature map (output of the backbone + projection layer), you
1357
+ can choose to directly pass a flattened representation of an image.
1358
+ decoder_inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_queries, hidden_size)`, *optional*):
1359
+ Optionally, instead of initializing the queries with a tensor of zeros, you can choose to directly pass an
1360
+ embedded representation.
1361
+
1362
+ Examples:
1363
+
1364
+ ```python
1365
+ >>> from transformers import AutoImageProcessor, AutoModel
1366
+ >>> from PIL import Image
1367
+ >>> import requests
1368
+
1369
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
1370
+ >>> image = Image.open(requests.get(url, stream=True).raw)
1371
+
1372
+ >>> image_processor = AutoImageProcessor.from_pretrained("microsoft/conditional-detr-resnet-50")
1373
+ >>> model = AutoModel.from_pretrained("microsoft/conditional-detr-resnet-50")
1374
+
1375
+ >>> # prepare image for the model
1376
+ >>> inputs = image_processor(images=image, return_tensors="pt")
1377
+
1378
+ >>> # forward pass
1379
+ >>> outputs = model(**inputs)
1380
+
1381
+ >>> # the last hidden states are the final query embeddings of the Transformer decoder
1382
+ >>> # these are of shape (batch_size, num_queries, hidden_size)
1383
+ >>> last_hidden_states = outputs.last_hidden_state
1384
+ >>> list(last_hidden_states.shape)
1385
+ [1, 300, 256]
1386
+ ```"""
1387
+ batch_size, num_channels, height, width = pixel_values.shape
1388
+ device = pixel_values.device
1389
+
1390
+ if pixel_mask is None:
1391
+ pixel_mask = torch.ones(((batch_size, height, width)), device=device)
1392
+
1393
+ # First, sent pixel_values + pixel_mask through Backbone to obtain the features
1394
+ # pixel_values should be of shape (batch_size, num_channels, height, width)
1395
+ # pixel_mask should be of shape (batch_size, height, width)
1396
+ features = self.backbone(pixel_values, pixel_mask)
1397
+
1398
+ # get final feature map and downsampled mask
1399
+ feature_map, mask = features[-1]
1400
+
1401
+ if mask is None:
1402
+ raise ValueError("Backbone does not return downsampled pixel mask")
1403
+
1404
+ # Second, apply 1x1 convolution to reduce the channel dimension to d_model (256 by default)
1405
+ projected_feature_map = self.input_projection(feature_map)
1406
+
1407
+ # Generate position embeddings
1408
+ spatial_position_embeddings = self.position_embedding(
1409
+ shape=feature_map.shape, device=device, dtype=pixel_values.dtype, mask=mask
1410
+ )
1411
+
1412
+ # Third, flatten the feature map of shape NxCxHxW to NxCxHW, and permute it to NxHWxC
1413
+ # In other words, turn their shape into (batch_size, sequence_length, hidden_size)
1414
+ flattened_features = projected_feature_map.flatten(2).permute(0, 2, 1)
1415
+
1416
+ flattened_mask = mask.flatten(1)
1417
+
1418
+ # Fourth, sent flattened_features + flattened_mask + spatial_position_embeddings through encoder
1419
+ # flattened_features is a Tensor of shape (batch_size, height*width, hidden_size)
1420
+ # flattened_mask is a Tensor of shape (batch_size, height*width)
1421
+ if encoder_outputs is None:
1422
+ encoder_outputs = self.encoder(
1423
+ inputs_embeds=flattened_features,
1424
+ attention_mask=flattened_mask,
1425
+ spatial_position_embeddings=spatial_position_embeddings,
1426
+ **kwargs,
1427
+ )
1428
+ # If the user passed a tuple for encoder_outputs, we wrap it in a BaseModelOutput
1429
+ elif not isinstance(encoder_outputs, BaseModelOutput):
1430
+ encoder_outputs = BaseModelOutput(
1431
+ last_hidden_state=encoder_outputs[0],
1432
+ hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
1433
+ attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
1434
+ )
1435
+
1436
+ # Fifth, sent query embeddings through the decoder (which is conditioned on the encoder output)
1437
+ object_queries_position_embeddings = self.query_position_embeddings.weight.unsqueeze(0).repeat(
1438
+ batch_size, 1, 1
1439
+ )
1440
+ queries = torch.zeros_like(object_queries_position_embeddings)
1441
+
1442
+ # decoder outputs consists of (dec_features, dec_hidden, dec_attn)
1443
+ decoder_outputs = self.decoder(
1444
+ inputs_embeds=queries,
1445
+ attention_mask=None,
1446
+ spatial_position_embeddings=spatial_position_embeddings,
1447
+ object_queries_position_embeddings=object_queries_position_embeddings,
1448
+ encoder_hidden_states=encoder_outputs.last_hidden_state,
1449
+ encoder_attention_mask=flattened_mask,
1450
+ **kwargs,
1451
+ )
1452
+
1453
+ return ConditionalDetrModelOutput(
1454
+ last_hidden_state=decoder_outputs.last_hidden_state,
1455
+ decoder_hidden_states=decoder_outputs.hidden_states,
1456
+ decoder_attentions=decoder_outputs.attentions,
1457
+ cross_attentions=decoder_outputs.cross_attentions,
1458
+ encoder_last_hidden_state=encoder_outputs.last_hidden_state,
1459
+ encoder_hidden_states=encoder_outputs.hidden_states,
1460
+ encoder_attentions=encoder_outputs.attentions,
1461
+ intermediate_hidden_states=decoder_outputs.intermediate_hidden_states,
1462
+ reference_points=decoder_outputs.reference_points,
1463
+ )
1464
+
1465
+
1466
+ def inverse_sigmoid(x, eps=1e-5):
1467
+ x = x.clamp(min=0, max=1)
1468
+ x1 = x.clamp(min=eps)
1469
+ x2 = (1 - x).clamp(min=eps)
1470
+ return torch.log(x1 / x2)
1471
+
1472
+
1473
+ @auto_docstring(
1474
+ custom_intro="""
1475
+ CONDITIONAL_DETR Model (consisting of a backbone and encoder-decoder Transformer) with object detection heads on top, for tasks
1476
+ such as COCO detection.
1477
+ """
1478
+ )
1479
+ class ConditionalDetrForObjectDetection(ConditionalDetrPreTrainedModel):
1480
+ def __init__(self, config: ConditionalDetrConfig):
1481
+ super().__init__(config)
1482
+
1483
+ # CONDITIONAL_DETR encoder-decoder model
1484
+ self.model = ConditionalDetrModel(config)
1485
+ self.class_labels_classifier = nn.Linear(config.d_model, config.num_labels)
1486
+ self.bbox_predictor = ConditionalDetrMLPPredictionHead(
1487
+ input_dim=config.d_model, hidden_dim=config.d_model, output_dim=4, num_layers=3
1488
+ )
1489
+
1490
+ # Initialize weights and apply final processing
1491
+ self.post_init()
1492
+
1493
+ @auto_docstring
1494
+ @can_return_tuple
1495
+ def forward(
1496
+ self,
1497
+ pixel_values: torch.FloatTensor,
1498
+ pixel_mask: torch.LongTensor | None = None,
1499
+ decoder_attention_mask: torch.LongTensor | None = None,
1500
+ encoder_outputs: torch.FloatTensor | None = None,
1501
+ inputs_embeds: torch.FloatTensor | None = None,
1502
+ decoder_inputs_embeds: torch.FloatTensor | None = None,
1503
+ labels: list[dict] | None = None,
1504
+ **kwargs: Unpack[TransformersKwargs],
1505
+ ) -> ConditionalDetrObjectDetectionOutput:
1506
+ r"""
1507
+ decoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, num_queries)`, *optional*):
1508
+ Not used by default. Can be used to mask object queries.
1509
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1510
+ Optionally, instead of passing the flattened feature map (output of the backbone + projection layer), you
1511
+ can choose to directly pass a flattened representation of an image.
1512
+ decoder_inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_queries, hidden_size)`, *optional*):
1513
+ Optionally, instead of initializing the queries with a tensor of zeros, you can choose to directly pass an
1514
+ embedded representation.
1515
+ labels (`list[Dict]` of len `(batch_size,)`, *optional*):
1516
+ Labels for computing the bipartite matching loss. List of dicts, each dictionary containing at least the
1517
+ following 2 keys: 'class_labels' and 'boxes' (the class labels and bounding boxes of an image in the batch
1518
+ respectively). The class labels themselves should be a `torch.LongTensor` of len `(number of bounding boxes
1519
+ in the image,)` and the boxes a `torch.FloatTensor` of shape `(number of bounding boxes in the image, 4)`.
1520
+
1521
+ Examples:
1522
+
1523
+ ```python
1524
+ >>> from transformers import AutoImageProcessor, AutoModelForObjectDetection
1525
+ >>> from PIL import Image
1526
+ >>> import requests
1527
+
1528
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
1529
+ >>> image = Image.open(requests.get(url, stream=True).raw)
1530
+
1531
+ >>> image_processor = AutoImageProcessor.from_pretrained("microsoft/conditional-detr-resnet-50")
1532
+ >>> model = AutoModelForObjectDetection.from_pretrained("microsoft/conditional-detr-resnet-50")
1533
+
1534
+ >>> inputs = image_processor(images=image, return_tensors="pt")
1535
+
1536
+ >>> outputs = model(**inputs)
1537
+
1538
+ >>> # convert outputs (bounding boxes and class logits) to Pascal VOC format (xmin, ymin, xmax, ymax)
1539
+ >>> target_sizes = torch.tensor([image.size[::-1]])
1540
+ >>> results = image_processor.post_process_object_detection(outputs, threshold=0.5, target_sizes=target_sizes)[
1541
+ ... 0
1542
+ ... ]
1543
+ >>> for score, label, box in zip(results["scores"], results["labels"], results["boxes"]):
1544
+ ... box = [round(i, 2) for i in box.tolist()]
1545
+ ... print(
1546
+ ... f"Detected {model.config.id2label[label.item()]} with confidence "
1547
+ ... f"{round(score.item(), 3)} at location {box}"
1548
+ ... )
1549
+ Detected remote with confidence 0.833 at location [38.31, 72.1, 177.63, 118.45]
1550
+ Detected cat with confidence 0.831 at location [9.2, 51.38, 321.13, 469.0]
1551
+ Detected cat with confidence 0.804 at location [340.3, 16.85, 642.93, 370.95]
1552
+ Detected remote with confidence 0.683 at location [334.48, 73.49, 366.37, 190.01]
1553
+ Detected couch with confidence 0.535 at location [0.52, 1.19, 640.35, 475.1]
1554
+ ```"""
1555
+ # First, sent images through CONDITIONAL_DETR base model to obtain encoder + decoder outputs
1556
+ outputs = self.model(
1557
+ pixel_values,
1558
+ pixel_mask=pixel_mask,
1559
+ decoder_attention_mask=decoder_attention_mask,
1560
+ encoder_outputs=encoder_outputs,
1561
+ inputs_embeds=inputs_embeds,
1562
+ decoder_inputs_embeds=decoder_inputs_embeds,
1563
+ **kwargs,
1564
+ )
1565
+
1566
+ sequence_output = outputs[0]
1567
+
1568
+ # class logits + predicted bounding boxes
1569
+ logits = self.class_labels_classifier(sequence_output)
1570
+
1571
+ reference = outputs.reference_points
1572
+ reference_before_sigmoid = inverse_sigmoid(reference).transpose(0, 1)
1573
+
1574
+ hs = sequence_output
1575
+ tmp = self.bbox_predictor(hs)
1576
+ tmp[..., :2] += reference_before_sigmoid
1577
+ pred_boxes = tmp.sigmoid()
1578
+ # pred_boxes = self.bbox_predictor(sequence_output).sigmoid()
1579
+
1580
+ loss, loss_dict, auxiliary_outputs = None, None, None
1581
+ if labels is not None:
1582
+ outputs_class, outputs_coord = None, None
1583
+ if self.config.auxiliary_loss:
1584
+ outputs_coords = []
1585
+ intermediate = outputs.intermediate_hidden_states
1586
+ outputs_class = self.class_labels_classifier(intermediate)
1587
+ for lvl in range(intermediate.shape[0]):
1588
+ tmp = self.bbox_predictor(intermediate[lvl])
1589
+ tmp[..., :2] += reference_before_sigmoid
1590
+ outputs_coord = tmp.sigmoid()
1591
+ outputs_coords.append(outputs_coord)
1592
+ outputs_coord = torch.stack(outputs_coords)
1593
+ loss, loss_dict, auxiliary_outputs = self.loss_function(
1594
+ logits, labels, self.device, pred_boxes, self.config, outputs_class, outputs_coord
1595
+ )
1596
+
1597
+ return ConditionalDetrObjectDetectionOutput(
1598
+ loss=loss,
1599
+ loss_dict=loss_dict,
1600
+ logits=logits,
1601
+ pred_boxes=pred_boxes,
1602
+ auxiliary_outputs=auxiliary_outputs,
1603
+ last_hidden_state=outputs.last_hidden_state,
1604
+ decoder_hidden_states=outputs.decoder_hidden_states,
1605
+ decoder_attentions=outputs.decoder_attentions,
1606
+ cross_attentions=outputs.cross_attentions,
1607
+ encoder_last_hidden_state=outputs.encoder_last_hidden_state,
1608
+ encoder_hidden_states=outputs.encoder_hidden_states,
1609
+ encoder_attentions=outputs.encoder_attentions,
1610
+ )
1611
+
1612
+ # taken from https://github.com/Atten4Vis/conditionalDETR/blob/master/models/conditional_detr.py
1613
+ def _set_aux_loss(self, outputs_class, outputs_coord):
1614
+ return [{"logits": a, "pred_boxes": b} for a, b in zip(outputs_class[:-1], outputs_coord[:-1])]
1615
+
1616
+
1617
+ @auto_docstring(
1618
+ custom_intro="""
1619
+ CONDITIONAL_DETR Model (consisting of a backbone and encoder-decoder Transformer) with a segmentation head on top, for tasks
1620
+ such as COCO panoptic.
1621
+ """
1622
+ )
1623
+ class ConditionalDetrForSegmentation(ConditionalDetrPreTrainedModel):
1624
+ _checkpoint_conversion_mapping = {
1625
+ "bbox_attention.q_linear": "bbox_attention.q_proj",
1626
+ "bbox_attention.k_linear": "bbox_attention.k_proj",
1627
+ # Mask head refactor
1628
+ "mask_head.lay1": "mask_head.conv1.conv",
1629
+ "mask_head.gn1": "mask_head.conv1.norm",
1630
+ "mask_head.lay2": "mask_head.conv2.conv",
1631
+ "mask_head.gn2": "mask_head.conv2.norm",
1632
+ "mask_head.adapter1": "mask_head.fpn_stages.0.fpn_adapter",
1633
+ "mask_head.lay3": "mask_head.fpn_stages.0.refine.conv",
1634
+ "mask_head.gn3": "mask_head.fpn_stages.0.refine.norm",
1635
+ "mask_head.adapter2": "mask_head.fpn_stages.1.fpn_adapter",
1636
+ "mask_head.lay4": "mask_head.fpn_stages.1.refine.conv",
1637
+ "mask_head.gn4": "mask_head.fpn_stages.1.refine.norm",
1638
+ "mask_head.adapter3": "mask_head.fpn_stages.2.fpn_adapter",
1639
+ "mask_head.lay5": "mask_head.fpn_stages.2.refine.conv",
1640
+ "mask_head.gn5": "mask_head.fpn_stages.2.refine.norm",
1641
+ "mask_head.out_lay": "mask_head.output_conv",
1642
+ }
1643
+
1644
+ def __init__(self, config: ConditionalDetrConfig):
1645
+ super().__init__(config)
1646
+
1647
+ # object detection model
1648
+ self.conditional_detr = ConditionalDetrForObjectDetection(config)
1649
+
1650
+ # segmentation head
1651
+ hidden_size, number_of_heads = config.d_model, config.encoder_attention_heads
1652
+ intermediate_channel_sizes = self.conditional_detr.model.backbone.intermediate_channel_sizes
1653
+
1654
+ self.mask_head = ConditionalDetrMaskHeadSmallConv(
1655
+ input_channels=hidden_size + number_of_heads,
1656
+ fpn_channels=intermediate_channel_sizes[::-1][-3:],
1657
+ hidden_size=hidden_size,
1658
+ activation_function=config.activation_function,
1659
+ )
1660
+
1661
+ self.bbox_attention = ConditionalDetrMHAttentionMap(hidden_size, number_of_heads, dropout=0.0)
1662
+ # Initialize weights and apply final processing
1663
+ self.post_init()
1664
+
1665
+ @auto_docstring
1666
+ @can_return_tuple
1667
+ def forward(
1668
+ self,
1669
+ pixel_values: torch.FloatTensor,
1670
+ pixel_mask: torch.LongTensor | None = None,
1671
+ decoder_attention_mask: torch.FloatTensor | None = None,
1672
+ encoder_outputs: torch.FloatTensor | None = None,
1673
+ inputs_embeds: torch.FloatTensor | None = None,
1674
+ decoder_inputs_embeds: torch.FloatTensor | None = None,
1675
+ labels: list[dict] | None = None,
1676
+ **kwargs: Unpack[TransformersKwargs],
1677
+ ) -> tuple[torch.FloatTensor] | ConditionalDetrSegmentationOutput:
1678
+ r"""
1679
+ decoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, num_queries)`, *optional*):
1680
+ Mask to avoid performing attention on certain object queries in the decoder. Mask values selected in `[0, 1]`:
1681
+
1682
+ - 1 for queries that are **not masked**,
1683
+ - 0 for queries that are **masked**.
1684
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1685
+ Kept for backward compatibility, but cannot be used for segmentation, as segmentation requires
1686
+ multi-scale features from the backbone that are not available when bypassing it with inputs_embeds.
1687
+ decoder_inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_queries, hidden_size)`, *optional*):
1688
+ Optionally, instead of initializing the queries with a tensor of zeros, you can choose to directly pass an
1689
+ embedded representation. Useful for tasks that require custom query initialization.
1690
+ labels (`list[Dict]` of len `(batch_size,)`, *optional*):
1691
+ Labels for computing the bipartite matching loss, DICE/F-1 loss and Focal loss. List of dicts, each
1692
+ dictionary containing at least the following 3 keys: 'class_labels', 'boxes' and 'masks' (the class labels,
1693
+ bounding boxes and segmentation masks of an image in the batch respectively). The class labels themselves
1694
+ should be a `torch.LongTensor` of len `(number of bounding boxes in the image,)`, the boxes a
1695
+ `torch.FloatTensor` of shape `(number of bounding boxes in the image, 4)` and the masks a
1696
+ `torch.FloatTensor` of shape `(number of bounding boxes in the image, height, width)`.
1697
+
1698
+ Examples:
1699
+
1700
+ ```python
1701
+ >>> import io
1702
+ >>> import httpx
1703
+ >>> from io import BytesIO
1704
+ >>> from PIL import Image
1705
+ >>> import torch
1706
+ >>> import numpy
1707
+
1708
+ >>> from transformers import AutoImageProcessor, ConditionalDetrForSegmentation
1709
+ >>> from transformers.image_transforms import rgb_to_id
1710
+
1711
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
1712
+ >>> with httpx.stream("GET", url) as response:
1713
+ ... image = Image.open(BytesIO(response.read()))
1714
+
1715
+ >>> image_processor = AutoImageProcessor.from_pretrained("facebook/conditional_detr-resnet-50-panoptic")
1716
+ >>> model = ConditionalDetrForSegmentation.from_pretrained("facebook/conditional_detr-resnet-50-panoptic")
1717
+
1718
+ >>> # prepare image for the model
1719
+ >>> inputs = image_processor(images=image, return_tensors="pt")
1720
+
1721
+ >>> # forward pass
1722
+ >>> outputs = model(**inputs)
1723
+
1724
+ >>> # Use the `post_process_panoptic_segmentation` method of the `image_processor` to retrieve post-processed panoptic segmentation maps
1725
+ >>> # Segmentation results are returned as a list of dictionaries
1726
+ >>> result = image_processor.post_process_panoptic_segmentation(outputs, target_sizes=[(300, 500)])
1727
+
1728
+ >>> # A tensor of shape (height, width) where each value denotes a segment id, filled with -1 if no segment is found
1729
+ >>> panoptic_seg = result[0]["segmentation"]
1730
+ >>> panoptic_seg.shape
1731
+ torch.Size([300, 500])
1732
+ >>> # Get prediction score and segment_id to class_id mapping of each segment
1733
+ >>> panoptic_segments_info = result[0]["segments_info"]
1734
+ >>> len(panoptic_segments_info)
1735
+ 5
1736
+ ```"""
1737
+
1738
+ batch_size, num_channels, height, width = pixel_values.shape
1739
+ device = pixel_values.device
1740
+
1741
+ if pixel_mask is None:
1742
+ pixel_mask = torch.ones((batch_size, height, width), device=device)
1743
+
1744
+ vision_features = self.conditional_detr.model.backbone(pixel_values, pixel_mask)
1745
+ feature_map, mask = vision_features[-1]
1746
+
1747
+ # Apply 1x1 conv to map (batch_size, C, H, W) -> (batch_size, hidden_size, H, W), then flatten to (batch_size, HW, hidden_size)
1748
+ projected_feature_map = self.conditional_detr.model.input_projection(feature_map)
1749
+ flattened_features = projected_feature_map.flatten(2).permute(0, 2, 1)
1750
+ spatial_position_embeddings = self.conditional_detr.model.position_embedding(
1751
+ shape=feature_map.shape, device=device, dtype=pixel_values.dtype, mask=mask
1752
+ )
1753
+ flattened_mask = mask.flatten(1)
1754
+
1755
+ if encoder_outputs is None:
1756
+ encoder_outputs = self.conditional_detr.model.encoder(
1757
+ inputs_embeds=flattened_features,
1758
+ attention_mask=flattened_mask,
1759
+ spatial_position_embeddings=spatial_position_embeddings,
1760
+ **kwargs,
1761
+ )
1762
+
1763
+ object_queries_position_embeddings = self.conditional_detr.model.query_position_embeddings.weight.unsqueeze(
1764
+ 0
1765
+ ).repeat(batch_size, 1, 1)
1766
+
1767
+ # Use decoder_inputs_embeds as queries if provided, otherwise initialize with zeros
1768
+ if decoder_inputs_embeds is not None:
1769
+ queries = decoder_inputs_embeds
1770
+ else:
1771
+ queries = torch.zeros_like(object_queries_position_embeddings)
1772
+
1773
+ decoder_outputs = self.conditional_detr.model.decoder(
1774
+ inputs_embeds=queries,
1775
+ attention_mask=decoder_attention_mask,
1776
+ spatial_position_embeddings=spatial_position_embeddings,
1777
+ object_queries_position_embeddings=object_queries_position_embeddings,
1778
+ encoder_hidden_states=encoder_outputs.last_hidden_state,
1779
+ encoder_attention_mask=flattened_mask,
1780
+ **kwargs,
1781
+ )
1782
+
1783
+ sequence_output = decoder_outputs[0]
1784
+
1785
+ logits = self.conditional_detr.class_labels_classifier(sequence_output)
1786
+ pred_boxes = self.conditional_detr.bbox_predictor(sequence_output).sigmoid()
1787
+
1788
+ height, width = feature_map.shape[-2:]
1789
+ memory = encoder_outputs.last_hidden_state.permute(0, 2, 1).view(
1790
+ batch_size, self.config.d_model, height, width
1791
+ )
1792
+ attention_mask = flattened_mask.view(batch_size, height, width)
1793
+
1794
+ if attention_mask is not None:
1795
+ min_dtype = torch.finfo(memory.dtype).min
1796
+ attention_mask = torch.where(
1797
+ attention_mask.unsqueeze(1).unsqueeze(1),
1798
+ torch.tensor(0.0, device=memory.device, dtype=memory.dtype),
1799
+ min_dtype,
1800
+ )
1801
+
1802
+ bbox_mask = self.bbox_attention(sequence_output, memory, attention_mask=attention_mask)
1803
+
1804
+ seg_masks = self.mask_head(
1805
+ features=projected_feature_map,
1806
+ attention_masks=bbox_mask,
1807
+ fpn_features=[vision_features[2][0], vision_features[1][0], vision_features[0][0]],
1808
+ )
1809
+
1810
+ pred_masks = seg_masks.view(
1811
+ batch_size, self.conditional_detr.config.num_queries, seg_masks.shape[-2], seg_masks.shape[-1]
1812
+ )
1813
+
1814
+ loss, loss_dict, auxiliary_outputs = None, None, None
1815
+ if labels is not None:
1816
+ outputs_class, outputs_coord = None, None
1817
+ if self.config.auxiliary_loss:
1818
+ intermediate = decoder_outputs.intermediate_hidden_states
1819
+ outputs_class = self.conditional_detr.class_labels_classifier(intermediate)
1820
+ outputs_coord = self.conditional_detr.bbox_predictor(intermediate).sigmoid()
1821
+ loss, loss_dict, auxiliary_outputs = self.loss_function(
1822
+ logits, labels, device, pred_boxes, pred_masks, self.config, outputs_class, outputs_coord
1823
+ )
1824
+
1825
+ return ConditionalDetrSegmentationOutput(
1826
+ loss=loss,
1827
+ loss_dict=loss_dict,
1828
+ logits=logits,
1829
+ pred_boxes=pred_boxes,
1830
+ pred_masks=pred_masks,
1831
+ auxiliary_outputs=auxiliary_outputs,
1832
+ last_hidden_state=decoder_outputs.last_hidden_state,
1833
+ decoder_hidden_states=decoder_outputs.hidden_states,
1834
+ decoder_attentions=decoder_outputs.attentions,
1835
+ cross_attentions=decoder_outputs.cross_attentions,
1836
+ encoder_last_hidden_state=encoder_outputs.last_hidden_state,
1837
+ encoder_hidden_states=encoder_outputs.hidden_states,
1838
+ encoder_attentions=encoder_outputs.attentions,
1839
+ )
1840
+
1841
+
1842
+ __all__ = [
1843
+ "ConditionalDetrForObjectDetection",
1844
+ "ConditionalDetrForSegmentation",
1845
+ "ConditionalDetrModel",
1846
+ "ConditionalDetrPreTrainedModel",
1847
+ ]
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/conditional_detr/modular_conditional_detr.py ADDED
@@ -0,0 +1,978 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 Microsoft Research Asia and 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
+ import math
15
+ from collections.abc import Callable
16
+
17
+ import torch
18
+ from torch import nn
19
+
20
+ from ...image_transforms import (
21
+ center_to_corners_format,
22
+ )
23
+ from ...masking_utils import create_bidirectional_mask
24
+ from ...modeling_outputs import (
25
+ BaseModelOutput,
26
+ )
27
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS
28
+ from ...processing_utils import Unpack
29
+ from ...utils import (
30
+ TensorType,
31
+ TransformersKwargs,
32
+ auto_docstring,
33
+ logging,
34
+ )
35
+ from ...utils.generic import can_return_tuple, merge_with_config_defaults
36
+ from ...utils.output_capturing import OutputRecorder, capture_outputs
37
+ from ..deformable_detr.modeling_deformable_detr import inverse_sigmoid
38
+ from ..detr.image_processing_detr_fast import DetrImageProcessorFast
39
+ from ..detr.modeling_detr import (
40
+ DetrConvEncoder,
41
+ DetrDecoderLayer,
42
+ DetrDecoderOutput,
43
+ DetrEncoder,
44
+ DetrEncoderLayer,
45
+ DetrForObjectDetection,
46
+ DetrForSegmentation,
47
+ DetrLearnedPositionEmbedding,
48
+ DetrMLP,
49
+ DetrMLPPredictionHead,
50
+ DetrModel,
51
+ DetrModelOutput,
52
+ DetrObjectDetectionOutput,
53
+ DetrPreTrainedModel,
54
+ DetrSegmentationOutput,
55
+ DetrSelfAttention,
56
+ DetrSinePositionEmbedding,
57
+ eager_attention_forward,
58
+ )
59
+ from .configuration_conditional_detr import ConditionalDetrConfig
60
+
61
+
62
+ logger = logging.get_logger(__name__)
63
+
64
+
65
+ class ConditionalDetrImageProcessorFast(DetrImageProcessorFast):
66
+ def post_process_object_detection(
67
+ self, outputs, threshold: float = 0.5, target_sizes: TensorType | list[tuple] = None, top_k: int = 100
68
+ ):
69
+ """
70
+ Converts the raw output of [`ConditionalDetrForObjectDetection`] into final bounding boxes in (top_left_x,
71
+ top_left_y, bottom_right_x, bottom_right_y) format. Only supports PyTorch.
72
+
73
+ Args:
74
+ outputs ([`ConditionalDetrObjectDetectionOutput`]):
75
+ Raw outputs of the model.
76
+ threshold (`float`, *optional*):
77
+ Score threshold to keep object detection predictions.
78
+ target_sizes (`torch.Tensor` or `list[tuple[int, int]]`, *optional*):
79
+ Tensor of shape `(batch_size, 2)` or list of tuples (`tuple[int, int]`) containing the target size
80
+ (height, width) of each image in the batch. If left to None, predictions will not be resized.
81
+ top_k (`int`, *optional*, defaults to 100):
82
+ Keep only top k bounding boxes before filtering by thresholding.
83
+
84
+ Returns:
85
+ `list[Dict]`: A list of dictionaries, each dictionary containing the scores, labels and boxes for an image
86
+ in the batch as predicted by the model.
87
+ """
88
+ out_logits, out_bbox = outputs.logits, outputs.pred_boxes
89
+
90
+ if target_sizes is not None:
91
+ if len(out_logits) != len(target_sizes):
92
+ raise ValueError(
93
+ "Make sure that you pass in as many target sizes as the batch dimension of the logits"
94
+ )
95
+
96
+ prob = out_logits.sigmoid()
97
+ prob = prob.view(out_logits.shape[0], -1)
98
+ k_value = min(top_k, prob.size(1))
99
+ topk_values, topk_indexes = torch.topk(prob, k_value, dim=1)
100
+ scores = topk_values
101
+ topk_boxes = torch.div(topk_indexes, out_logits.shape[2], rounding_mode="floor")
102
+ labels = topk_indexes % out_logits.shape[2]
103
+ boxes = center_to_corners_format(out_bbox)
104
+ boxes = torch.gather(boxes, 1, topk_boxes.unsqueeze(-1).repeat(1, 1, 4))
105
+
106
+ # and from relative [0, 1] to absolute [0, height] coordinates
107
+ if target_sizes is not None:
108
+ if isinstance(target_sizes, list):
109
+ img_h = torch.Tensor([i[0] for i in target_sizes])
110
+ img_w = torch.Tensor([i[1] for i in target_sizes])
111
+ else:
112
+ img_h, img_w = target_sizes.unbind(1)
113
+ scale_fct = torch.stack([img_w, img_h, img_w, img_h], dim=1).to(boxes.device)
114
+ boxes = boxes * scale_fct[:, None, :]
115
+
116
+ results = []
117
+ for s, l, b in zip(scores, labels, boxes):
118
+ score = s[s > threshold]
119
+ label = l[s > threshold]
120
+ box = b[s > threshold]
121
+ results.append({"scores": score, "labels": label, "boxes": box})
122
+
123
+ return results
124
+
125
+ def post_process_semantic_segmentation(self, outputs, target_sizes: list[tuple[int, int]] | None = None):
126
+ """
127
+ Converts the output of [`ConditionalDetrForSegmentation`] into semantic segmentation maps. Only supports PyTorch.
128
+
129
+ Args:
130
+ outputs ([`ConditionalDetrForSegmentation`]):
131
+ Raw outputs of the model.
132
+ target_sizes (`list[tuple[int, int]]`, *optional*):
133
+ A list of tuples (`tuple[int, int]`) containing the target size (height, width) of each image in the
134
+ batch. If unset, predictions will not be resized.
135
+ Returns:
136
+ `list[torch.Tensor]`:
137
+ A list of length `batch_size`, where each item is a semantic segmentation map of shape (height, width)
138
+ corresponding to the target_sizes entry (if `target_sizes` is specified). Each entry of each
139
+ `torch.Tensor` correspond to a semantic class id.
140
+ """
141
+ class_queries_logits = outputs.logits # [batch_size, num_queries, num_classes]
142
+ masks_queries_logits = outputs.pred_masks # [batch_size, num_queries, height, width]
143
+
144
+ # Conditional DETR does not have a null class, so we use all classes
145
+ masks_classes = class_queries_logits.softmax(dim=-1)
146
+ masks_probs = masks_queries_logits.sigmoid() # [batch_size, num_queries, height, width]
147
+
148
+ # Semantic segmentation logits of shape (batch_size, num_classes, height, width)
149
+ segmentation = torch.einsum("bqc, bqhw -> bchw", masks_classes, masks_probs)
150
+ batch_size = class_queries_logits.shape[0]
151
+
152
+ # Resize logits and compute semantic segmentation maps
153
+ if target_sizes is not None:
154
+ if batch_size != len(target_sizes):
155
+ raise ValueError(
156
+ "Make sure that you pass in as many target sizes as the batch dimension of the logits"
157
+ )
158
+
159
+ semantic_segmentation = []
160
+ for idx in range(batch_size):
161
+ resized_logits = nn.functional.interpolate(
162
+ segmentation[idx].unsqueeze(dim=0), size=target_sizes[idx], mode="bilinear", align_corners=False
163
+ )
164
+ semantic_map = resized_logits[0].argmax(dim=0)
165
+ semantic_segmentation.append(semantic_map)
166
+ else:
167
+ semantic_segmentation = segmentation.argmax(dim=1)
168
+ semantic_segmentation = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0])]
169
+
170
+ return semantic_segmentation
171
+
172
+
173
+ class ConditionalDetrDecoderOutput(DetrDecoderOutput):
174
+ r"""
175
+ cross_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` and `config.add_cross_attention=True` is passed or when `config.output_attentions=True`):
176
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
177
+ sequence_length)`. Attentions weights of the decoder's cross-attention layer, after the attention softmax,
178
+ used to compute the weighted average in the cross-attention heads.
179
+ intermediate_hidden_states (`torch.FloatTensor` of shape `(config.decoder_layers, batch_size, num_queries, hidden_size)`, *optional*, returned when `config.auxiliary_loss=True`):
180
+ Intermediate decoder activations, i.e. the output of each decoder layer, each of them gone through a
181
+ layernorm.
182
+ reference_points (`torch.FloatTensor` of shape `(config.decoder_layers, batch_size, num_queries, 2 (anchor points))`):
183
+ Reference points (reference points of each layer of the decoder).
184
+ """
185
+
186
+ reference_points: tuple[torch.FloatTensor] | None = None
187
+
188
+
189
+ class ConditionalDetrModelOutput(DetrModelOutput):
190
+ r"""
191
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
192
+ Sequence of hidden-states at the output of the last layer of the decoder of the model.
193
+ intermediate_hidden_states (`torch.FloatTensor` of shape `(config.decoder_layers, batch_size, sequence_length, hidden_size)`, *optional*, returned when `config.auxiliary_loss=True`):
194
+ Intermediate decoder activations, i.e. the output of each decoder layer, each of them gone through a
195
+ layernorm.
196
+ reference_points (`torch.FloatTensor` of shape `(config.decoder_layers, batch_size, num_queries, 2 (anchor points))`):
197
+ Reference points (reference points of each layer of the decoder).
198
+ """
199
+
200
+ reference_points: tuple[torch.FloatTensor] | None = None
201
+
202
+
203
+ # function to generate sine positional embedding for 2d coordinates
204
+ def gen_sine_position_embeddings(pos_tensor, d_model):
205
+ scale = 2 * math.pi
206
+ dim = d_model // 2
207
+ dim_t = torch.arange(dim, dtype=torch.float32, device=pos_tensor.device)
208
+ dim_t = 10000 ** (2 * torch.div(dim_t, 2, rounding_mode="floor") / dim)
209
+ x_embed = pos_tensor[:, :, 0] * scale
210
+ y_embed = pos_tensor[:, :, 1] * scale
211
+ pos_x = x_embed[:, :, None] / dim_t
212
+ pos_y = y_embed[:, :, None] / dim_t
213
+ pos_x = torch.stack((pos_x[:, :, 0::2].sin(), pos_x[:, :, 1::2].cos()), dim=3).flatten(2)
214
+ pos_y = torch.stack((pos_y[:, :, 0::2].sin(), pos_y[:, :, 1::2].cos()), dim=3).flatten(2)
215
+ pos = torch.cat((pos_y, pos_x), dim=2)
216
+ return pos.to(pos_tensor.dtype)
217
+
218
+
219
+ class ConditionalDetrObjectDetectionOutput(DetrObjectDetectionOutput):
220
+ pass
221
+
222
+
223
+ class ConditionalDetrSegmentationOutput(DetrSegmentationOutput):
224
+ pass
225
+
226
+
227
+ class ConditionalDetrConvEncoder(DetrConvEncoder):
228
+ pass
229
+
230
+
231
+ class ConditionalDetrSinePositionEmbedding(DetrSinePositionEmbedding):
232
+ pass
233
+
234
+
235
+ class ConditionalDetrLearnedPositionEmbedding(DetrLearnedPositionEmbedding):
236
+ pass
237
+
238
+
239
+ class ConditionalDetrSelfAttention(DetrSelfAttention):
240
+ pass
241
+
242
+
243
+ class ConditionalDetrDecoderSelfAttention(nn.Module):
244
+ """
245
+ Multi-headed self-attention for Conditional DETR decoder layers.
246
+
247
+ This attention module handles separate content and position projections, which are then combined
248
+ before applying standard self-attention. Position embeddings are added to both queries and keys.
249
+ """
250
+
251
+ def __init__(
252
+ self,
253
+ config: ConditionalDetrConfig,
254
+ hidden_size: int,
255
+ num_attention_heads: int,
256
+ dropout: float = 0.0,
257
+ ):
258
+ super().__init__()
259
+ self.config = config
260
+ self.hidden_size = hidden_size
261
+ self.head_dim = hidden_size // num_attention_heads
262
+ self.scaling = self.head_dim**-0.5
263
+ self.attention_dropout = dropout
264
+ self.is_causal = False
265
+
266
+ # Content and position projections
267
+ self.q_content_proj = nn.Linear(hidden_size, hidden_size)
268
+ self.q_pos_proj = nn.Linear(hidden_size, hidden_size)
269
+ self.k_content_proj = nn.Linear(hidden_size, hidden_size)
270
+ self.k_pos_proj = nn.Linear(hidden_size, hidden_size)
271
+ self.v_proj = nn.Linear(hidden_size, hidden_size)
272
+ self.o_proj = nn.Linear(hidden_size, hidden_size)
273
+
274
+ def forward(
275
+ self,
276
+ hidden_states: torch.Tensor,
277
+ query_position_embeddings: torch.Tensor,
278
+ attention_mask: torch.Tensor | None = None,
279
+ **kwargs: Unpack[TransformersKwargs],
280
+ ) -> tuple[torch.Tensor, torch.Tensor]:
281
+ """
282
+ Args:
283
+ hidden_states (`torch.Tensor` of shape `(batch_size, num_queries, hidden_size)`):
284
+ Input hidden states from the decoder layer.
285
+ query_position_embeddings (`torch.Tensor` of shape `(batch_size, num_queries, hidden_size)`):
286
+ Position embeddings for queries and keys. Required (unlike standard attention). Processed through
287
+ separate position projections (`q_pos_proj`, `k_pos_proj`) and added to content projections.
288
+ attention_mask (`torch.Tensor` of shape `(batch_size, 1, num_queries, num_queries)`, *optional*):
289
+ Attention mask to avoid attending to padding tokens.
290
+ """
291
+ input_shape = hidden_states.shape[:-1]
292
+ hidden_shape = (*input_shape, -1, self.head_dim)
293
+
294
+ query_states = (
295
+ (self.q_content_proj(hidden_states) + self.q_pos_proj(query_position_embeddings))
296
+ .view(hidden_shape)
297
+ .transpose(1, 2)
298
+ )
299
+ key_states = (
300
+ (self.k_content_proj(hidden_states) + self.k_pos_proj(query_position_embeddings))
301
+ .view(hidden_shape)
302
+ .transpose(1, 2)
303
+ )
304
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
305
+
306
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
307
+ self.config._attn_implementation, eager_attention_forward
308
+ )
309
+
310
+ attn_output, attn_weights = attention_interface(
311
+ self,
312
+ query_states,
313
+ key_states,
314
+ value_states,
315
+ attention_mask,
316
+ dropout=0.0 if not self.training else self.attention_dropout,
317
+ scaling=self.scaling,
318
+ **kwargs,
319
+ )
320
+
321
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
322
+ attn_output = self.o_proj(attn_output)
323
+ return attn_output, attn_weights
324
+
325
+
326
+ class ConditionalDetrDecoderCrossAttention(nn.Module):
327
+ """
328
+ Multi-headed cross-attention for Conditional DETR decoder layers.
329
+
330
+ This attention module handles the special cross-attention logic in Conditional DETR:
331
+ - Separate content and position projections for queries and keys
332
+ - Concatenation of query sine embeddings with queries (doubling query dimension)
333
+ - Concatenation of key position embeddings with keys (doubling key dimension)
334
+ - Output dimension remains hidden_size despite doubled input dimensions
335
+ """
336
+
337
+ def __init__(
338
+ self,
339
+ config: ConditionalDetrConfig,
340
+ hidden_size: int,
341
+ num_attention_heads: int,
342
+ dropout: float = 0.0,
343
+ ):
344
+ super().__init__()
345
+ self.config = config
346
+ self.hidden_size = hidden_size
347
+ self.num_attention_heads = num_attention_heads
348
+ self.head_dim = hidden_size // num_attention_heads
349
+ self.attention_dropout = dropout
350
+ self.is_causal = False
351
+
352
+ # Content and position projections
353
+ self.q_content_proj = nn.Linear(hidden_size, hidden_size)
354
+ self.q_pos_proj = nn.Linear(hidden_size, hidden_size)
355
+ self.k_content_proj = nn.Linear(hidden_size, hidden_size)
356
+ self.k_pos_proj = nn.Linear(hidden_size, hidden_size)
357
+ self.v_proj = nn.Linear(hidden_size, hidden_size)
358
+ self.q_pos_sine_proj = nn.Linear(hidden_size, hidden_size)
359
+
360
+ # Output projection: input is hidden_size * 2 (from concatenated q/k), output is hidden_size
361
+ self.o_proj = nn.Linear(hidden_size, hidden_size)
362
+
363
+ # Compute scaling for expanded head_dim (q and k have doubled dimensions after concatenation)
364
+ # This matches the original Conditional DETR implementation where embed_dim * 2 is used
365
+ expanded_head_dim = (hidden_size * 2) // num_attention_heads
366
+ self.scaling = expanded_head_dim**-0.5
367
+
368
+ def forward(
369
+ self,
370
+ hidden_states: torch.Tensor,
371
+ encoder_hidden_states: torch.Tensor,
372
+ query_sine_embed: torch.Tensor,
373
+ encoder_position_embeddings: torch.Tensor,
374
+ query_position_embeddings: torch.Tensor | None = None,
375
+ attention_mask: torch.Tensor | None = None,
376
+ **kwargs: Unpack[TransformersKwargs],
377
+ ) -> tuple[torch.Tensor, torch.Tensor]:
378
+ """
379
+ Args:
380
+ hidden_states (`torch.Tensor` of shape `(batch_size, num_queries, hidden_size)`):
381
+ Decoder hidden states (queries).
382
+ encoder_hidden_states (`torch.Tensor` of shape `(batch_size, encoder_seq_len, hidden_size)`):
383
+ Encoder output hidden states (keys and values).
384
+ query_sine_embed (`torch.Tensor` of shape `(batch_size, num_queries, hidden_size)`):
385
+ Sine position embeddings for queries. **Concatenated** (not added) with query content,
386
+ doubling the query dimension.
387
+ encoder_position_embeddings (`torch.Tensor` of shape `(batch_size, encoder_seq_len, hidden_size)`):
388
+ Position embeddings for keys. **Concatenated** (not added) with key content, doubling the key dimension.
389
+ query_position_embeddings (`torch.Tensor` of shape `(batch_size, num_queries, hidden_size)`, *optional*):
390
+ Additional position embeddings. When provided (first layer only), **added** to query content
391
+ before concatenation with `query_sine_embed`. Also causes `encoder_position_embeddings` to be
392
+ added to key content before concatenation.
393
+ attention_mask (`torch.Tensor` of shape `(batch_size, 1, num_queries, encoder_seq_len)`, *optional*):
394
+ Attention mask to avoid attending to padding tokens.
395
+ """
396
+ query_input_shape = hidden_states.shape[:-1]
397
+ kv_input_shape = encoder_hidden_states.shape[:-1]
398
+ query_hidden_shape = (*query_input_shape, self.num_attention_heads, self.head_dim)
399
+ kv_hidden_shape = (*kv_input_shape, self.num_attention_heads, self.head_dim)
400
+
401
+ # Apply content and position projections
402
+ query_input = self.q_content_proj(hidden_states)
403
+ key_input = self.k_content_proj(encoder_hidden_states)
404
+ value_states = self.v_proj(encoder_hidden_states)
405
+ key_pos = self.k_pos_proj(encoder_position_embeddings)
406
+
407
+ # Combine content and position embeddings
408
+ if query_position_embeddings is not None:
409
+ query_input = query_input + self.q_pos_proj(query_position_embeddings)
410
+ key_input = key_input + key_pos
411
+
412
+ # Reshape and concatenate position embeddings (doubling head_dim)
413
+ query_input = query_input.view(query_hidden_shape)
414
+ key_input = key_input.view(kv_hidden_shape)
415
+ query_sine_embed = self.q_pos_sine_proj(query_sine_embed).view(query_hidden_shape)
416
+ key_pos = key_pos.view(kv_hidden_shape)
417
+
418
+ query_states = torch.cat([query_input, query_sine_embed], dim=-1).view(*query_input_shape, -1)
419
+ key_states = torch.cat([key_input, key_pos], dim=-1).view(*kv_input_shape, -1)
420
+
421
+ # Reshape for attention computation
422
+ expanded_head_dim = query_states.shape[-1] // self.num_attention_heads
423
+ query_states = query_states.view(*query_input_shape, self.num_attention_heads, expanded_head_dim).transpose(
424
+ 1, 2
425
+ )
426
+ key_states = key_states.view(*kv_input_shape, self.num_attention_heads, expanded_head_dim).transpose(1, 2)
427
+ value_states = value_states.view(kv_hidden_shape).transpose(1, 2)
428
+
429
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
430
+ self.config._attn_implementation, eager_attention_forward
431
+ )
432
+
433
+ attn_output, attn_weights = attention_interface(
434
+ self,
435
+ query_states,
436
+ key_states,
437
+ value_states,
438
+ attention_mask,
439
+ dropout=0.0 if not self.training else self.attention_dropout,
440
+ scaling=self.scaling,
441
+ **kwargs,
442
+ )
443
+
444
+ attn_output = attn_output.reshape(*query_input_shape, -1).contiguous()
445
+ attn_output = self.o_proj(attn_output)
446
+ return attn_output, attn_weights
447
+
448
+
449
+ class ConditionalDetrMLP(DetrMLP):
450
+ pass
451
+
452
+
453
+ class ConditionalDetrEncoderLayer(DetrEncoderLayer):
454
+ pass
455
+
456
+
457
+ class ConditionalDetrDecoderLayer(DetrDecoderLayer):
458
+ def __init__(self, config: ConditionalDetrConfig):
459
+ super().__init__()
460
+ self.self_attn = ConditionalDetrDecoderSelfAttention(
461
+ config=config,
462
+ hidden_size=self.hidden_size,
463
+ num_attention_heads=config.decoder_attention_heads,
464
+ dropout=config.attention_dropout,
465
+ )
466
+ self.encoder_attn = ConditionalDetrDecoderCrossAttention(
467
+ config=config,
468
+ hidden_size=self.hidden_size,
469
+ num_attention_heads=config.decoder_attention_heads,
470
+ dropout=config.attention_dropout,
471
+ )
472
+
473
+ def forward(
474
+ self,
475
+ hidden_states: torch.Tensor,
476
+ attention_mask: torch.Tensor | None = None,
477
+ spatial_position_embeddings: torch.Tensor | None = None,
478
+ query_position_embeddings: torch.Tensor | None = None,
479
+ query_sine_embed: torch.Tensor | None = None,
480
+ encoder_hidden_states: torch.Tensor | None = None,
481
+ encoder_attention_mask: torch.Tensor | None = None,
482
+ is_first: bool | None = False,
483
+ **kwargs: Unpack[TransformersKwargs],
484
+ ) -> torch.Tensor:
485
+ """
486
+ Args:
487
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(seq_len, batch, embed_dim)`
488
+ attention_mask (`torch.FloatTensor`): attention mask of size
489
+ `(batch, 1, target_len, source_len)` where padding elements are indicated by very large negative
490
+ values.
491
+ spatial_position_embeddings (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
492
+ Spatial position embeddings (2D positional encodings) that are added to the queries and keys in each self-attention layer.
493
+ query_position_embeddings (`torch.FloatTensor`, *optional*):
494
+ object_queries that are added to the queries and keys
495
+ in the self-attention layer.
496
+ encoder_hidden_states (`torch.FloatTensor`):
497
+ cross attention input to the layer of shape `(seq_len, batch, embed_dim)`
498
+ encoder_attention_mask (`torch.FloatTensor`): encoder attention mask of size
499
+ `(batch, 1, target_len, source_len)` where padding elements are indicated by very large negative
500
+ values.
501
+ output_attentions (`bool`, *optional*):
502
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
503
+ returned tensors for more detail.
504
+ """
505
+ residual = hidden_states
506
+
507
+ hidden_states, _ = self.self_attn(
508
+ hidden_states=hidden_states,
509
+ query_position_embeddings=query_position_embeddings,
510
+ attention_mask=attention_mask,
511
+ **kwargs,
512
+ )
513
+
514
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
515
+ hidden_states = residual + hidden_states
516
+ hidden_states = self.self_attn_layer_norm(hidden_states)
517
+
518
+ if encoder_hidden_states is not None:
519
+ residual = hidden_states
520
+
521
+ hidden_states, _ = self.encoder_attn(
522
+ hidden_states=hidden_states,
523
+ encoder_hidden_states=encoder_hidden_states,
524
+ attention_mask=encoder_attention_mask,
525
+ query_sine_embed=query_sine_embed,
526
+ encoder_position_embeddings=spatial_position_embeddings,
527
+ # Only pass query_position_embeddings for the first layer
528
+ query_position_embeddings=query_position_embeddings if is_first else None,
529
+ **kwargs,
530
+ )
531
+
532
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
533
+ hidden_states = residual + hidden_states
534
+ hidden_states = self.encoder_attn_layer_norm(hidden_states)
535
+
536
+ # Fully Connected
537
+ residual = hidden_states
538
+ hidden_states = self.mlp(hidden_states)
539
+ hidden_states = residual + hidden_states
540
+ hidden_states = self.final_layer_norm(hidden_states)
541
+
542
+ return hidden_states
543
+
544
+
545
+ class ConditionalDetrMLPPredictionHead(DetrMLPPredictionHead):
546
+ pass
547
+
548
+
549
+ class ConditionalDetrPreTrainedModel(DetrPreTrainedModel):
550
+ _keys_to_ignore_on_load_unexpected = [
551
+ r"detr\.model\.backbone\.model\.layer\d+\.0\.downsample\.1\.num_batches_tracked"
552
+ ]
553
+
554
+
555
+ class ConditionalDetrEncoder(DetrEncoder):
556
+ pass
557
+
558
+
559
+ class ConditionalDetrDecoder(ConditionalDetrPreTrainedModel):
560
+ """
561
+ Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a [`ConditionalDetrDecoderLayer`].
562
+
563
+ The decoder updates the query embeddings through multiple self-attention and cross-attention layers.
564
+
565
+ Some small tweaks for Conditional DETR:
566
+
567
+ - object_queries and query_position_embeddings are added to the forward pass.
568
+ - if self.config.auxiliary_loss is set to True, also returns a stack of activations from all decoding layers.
569
+
570
+ Args:
571
+ config: ConditionalDetrConfig
572
+ """
573
+
574
+ _can_record_outputs = {
575
+ "hidden_states": ConditionalDetrDecoderLayer,
576
+ "attentions": OutputRecorder(ConditionalDetrDecoderSelfAttention, layer_name="self_attn", index=1),
577
+ "cross_attentions": OutputRecorder(ConditionalDetrDecoderCrossAttention, layer_name="encoder_attn", index=1),
578
+ }
579
+
580
+ def __init__(self, config: ConditionalDetrConfig):
581
+ super().__init__(config)
582
+ self.hidden_size = config.d_model
583
+
584
+ self.dropout = config.dropout
585
+ self.layerdrop = config.decoder_layerdrop
586
+
587
+ self.layers = nn.ModuleList([ConditionalDetrDecoderLayer(config) for _ in range(config.decoder_layers)])
588
+ # in Conditional DETR, the decoder uses layernorm after the last decoder layer output
589
+ self.layernorm = nn.LayerNorm(config.d_model)
590
+
591
+ # query_scale is the FFN applied on f to generate transformation T
592
+ self.query_scale = ConditionalDetrMLPPredictionHead(self.hidden_size, self.hidden_size, self.hidden_size, 2)
593
+ self.ref_point_head = ConditionalDetrMLPPredictionHead(self.hidden_size, self.hidden_size, 2, 2)
594
+ for layer_id in range(config.decoder_layers - 1):
595
+ # Set q_pos_proj to None for layers after the first (only first layer uses query position embeddings)
596
+ self.layers[layer_id + 1].encoder_attn.q_pos_proj = None
597
+
598
+ # Initialize weights and apply final processing
599
+ self.post_init()
600
+
601
+ @merge_with_config_defaults
602
+ @capture_outputs
603
+ def forward(
604
+ self,
605
+ inputs_embeds=None,
606
+ attention_mask=None,
607
+ encoder_hidden_states=None,
608
+ encoder_attention_mask=None,
609
+ spatial_position_embeddings=None,
610
+ object_queries_position_embeddings=None,
611
+ **kwargs: Unpack[TransformersKwargs],
612
+ ) -> ConditionalDetrDecoderOutput:
613
+ r"""
614
+ Args:
615
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
616
+ The query embeddings that are passed into the decoder.
617
+
618
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
619
+ Mask to avoid performing attention on certain queries. Mask values selected in `[0, 1]`:
620
+
621
+ - 1 for queries that are **not masked**,
622
+ - 0 for queries that are **masked**.
623
+
624
+ [What are attention masks?](../glossary#attention-mask)
625
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*):
626
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
627
+ of the decoder.
628
+ encoder_attention_mask (`torch.LongTensor` of shape `(batch_size, encoder_sequence_length)`, *optional*):
629
+ Mask to avoid performing cross-attention on padding pixel_values of the encoder. Mask values selected
630
+ in `[0, 1]`:
631
+
632
+ - 1 for pixels that are real (i.e. **not masked**),
633
+ - 0 for pixels that are padding (i.e. **masked**).
634
+
635
+ spatial_position_embeddings (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
636
+ Spatial position embeddings that are added to the queries and keys in each cross-attention layer.
637
+ object_queries_position_embeddings (`torch.FloatTensor` of shape `(batch_size, num_queries, hidden_size)`):
638
+ , *optional*): Position embeddings that are added to the queries and keys in each self-attention layer.
639
+ """
640
+ if inputs_embeds is not None:
641
+ hidden_states = inputs_embeds
642
+
643
+ # expand encoder attention mask
644
+ if encoder_hidden_states is not None and encoder_attention_mask is not None:
645
+ # [batch_size, seq_len] -> [batch_size, 1, target_seq_len, source_seq_len]
646
+ encoder_attention_mask = create_bidirectional_mask(
647
+ self.config,
648
+ inputs_embeds,
649
+ encoder_attention_mask,
650
+ )
651
+
652
+ # optional intermediate hidden states
653
+ intermediate = () if self.config.auxiliary_loss else None
654
+
655
+ reference_points_before_sigmoid = self.ref_point_head(
656
+ object_queries_position_embeddings
657
+ ) # [num_queries, batch_size, 2]
658
+ reference_points = reference_points_before_sigmoid.sigmoid().transpose(0, 1)
659
+ obj_center = reference_points[..., :2].transpose(0, 1)
660
+ # get sine embedding for the query vector
661
+ query_sine_embed_before_transformation = gen_sine_position_embeddings(obj_center, self.config.d_model)
662
+
663
+ for idx, decoder_layer in enumerate(self.layers):
664
+ if self.training:
665
+ dropout_probability = torch.rand([])
666
+ if dropout_probability < self.layerdrop:
667
+ continue
668
+ if idx == 0:
669
+ pos_transformation = 1
670
+ else:
671
+ pos_transformation = self.query_scale(hidden_states)
672
+ # apply transformation
673
+ query_sine_embed = query_sine_embed_before_transformation * pos_transformation
674
+
675
+ hidden_states = decoder_layer(
676
+ hidden_states,
677
+ None,
678
+ spatial_position_embeddings,
679
+ object_queries_position_embeddings,
680
+ query_sine_embed,
681
+ encoder_hidden_states, # as a positional argument for gradient checkpointing
682
+ encoder_attention_mask=encoder_attention_mask,
683
+ is_first=(idx == 0),
684
+ **kwargs,
685
+ )
686
+
687
+ if self.config.auxiliary_loss:
688
+ hidden_states = self.layernorm(hidden_states)
689
+ intermediate += (hidden_states,)
690
+
691
+ # finally, apply layernorm
692
+ hidden_states = self.layernorm(hidden_states)
693
+
694
+ # stack intermediate decoder activations
695
+ if self.config.auxiliary_loss:
696
+ intermediate = torch.stack(intermediate)
697
+
698
+ return ConditionalDetrDecoderOutput(
699
+ last_hidden_state=hidden_states,
700
+ intermediate_hidden_states=intermediate,
701
+ reference_points=reference_points,
702
+ )
703
+
704
+
705
+ class ConditionalDetrModel(DetrModel):
706
+ def __init__(self, config: ConditionalDetrConfig):
707
+ super().__init__(config)
708
+ self.query_position_embeddings = nn.Embedding(config.num_queries, config.d_model)
709
+
710
+ # Initialize weights and apply final processing
711
+ self.post_init()
712
+
713
+ @auto_docstring
714
+ @can_return_tuple
715
+ def forward(
716
+ self,
717
+ pixel_values: torch.FloatTensor,
718
+ pixel_mask: torch.LongTensor | None = None,
719
+ decoder_attention_mask: torch.LongTensor | None = None,
720
+ encoder_outputs: torch.FloatTensor | None = None,
721
+ inputs_embeds: torch.FloatTensor | None = None,
722
+ decoder_inputs_embeds: torch.FloatTensor | None = None,
723
+ **kwargs: Unpack[TransformersKwargs],
724
+ ) -> ConditionalDetrModelOutput:
725
+ r"""
726
+ decoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, num_queries)`, *optional*):
727
+ Not used by default. Can be used to mask object queries.
728
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
729
+ Optionally, instead of passing the flattened feature map (output of the backbone + projection layer), you
730
+ can choose to directly pass a flattened representation of an image.
731
+ decoder_inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_queries, hidden_size)`, *optional*):
732
+ Optionally, instead of initializing the queries with a tensor of zeros, you can choose to directly pass an
733
+ embedded representation.
734
+
735
+ Examples:
736
+
737
+ ```python
738
+ >>> from transformers import AutoImageProcessor, AutoModel
739
+ >>> from PIL import Image
740
+ >>> import requests
741
+
742
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
743
+ >>> image = Image.open(requests.get(url, stream=True).raw)
744
+
745
+ >>> image_processor = AutoImageProcessor.from_pretrained("microsoft/conditional-detr-resnet-50")
746
+ >>> model = AutoModel.from_pretrained("microsoft/conditional-detr-resnet-50")
747
+
748
+ >>> # prepare image for the model
749
+ >>> inputs = image_processor(images=image, return_tensors="pt")
750
+
751
+ >>> # forward pass
752
+ >>> outputs = model(**inputs)
753
+
754
+ >>> # the last hidden states are the final query embeddings of the Transformer decoder
755
+ >>> # these are of shape (batch_size, num_queries, hidden_size)
756
+ >>> last_hidden_states = outputs.last_hidden_state
757
+ >>> list(last_hidden_states.shape)
758
+ [1, 300, 256]
759
+ ```"""
760
+ batch_size, num_channels, height, width = pixel_values.shape
761
+ device = pixel_values.device
762
+
763
+ if pixel_mask is None:
764
+ pixel_mask = torch.ones(((batch_size, height, width)), device=device)
765
+
766
+ # First, sent pixel_values + pixel_mask through Backbone to obtain the features
767
+ # pixel_values should be of shape (batch_size, num_channels, height, width)
768
+ # pixel_mask should be of shape (batch_size, height, width)
769
+ features = self.backbone(pixel_values, pixel_mask)
770
+
771
+ # get final feature map and downsampled mask
772
+ feature_map, mask = features[-1]
773
+
774
+ if mask is None:
775
+ raise ValueError("Backbone does not return downsampled pixel mask")
776
+
777
+ # Second, apply 1x1 convolution to reduce the channel dimension to d_model (256 by default)
778
+ projected_feature_map = self.input_projection(feature_map)
779
+
780
+ # Generate position embeddings
781
+ spatial_position_embeddings = self.position_embedding(
782
+ shape=feature_map.shape, device=device, dtype=pixel_values.dtype, mask=mask
783
+ )
784
+
785
+ # Third, flatten the feature map of shape NxCxHxW to NxCxHW, and permute it to NxHWxC
786
+ # In other words, turn their shape into (batch_size, sequence_length, hidden_size)
787
+ flattened_features = projected_feature_map.flatten(2).permute(0, 2, 1)
788
+
789
+ flattened_mask = mask.flatten(1)
790
+
791
+ # Fourth, sent flattened_features + flattened_mask + spatial_position_embeddings through encoder
792
+ # flattened_features is a Tensor of shape (batch_size, height*width, hidden_size)
793
+ # flattened_mask is a Tensor of shape (batch_size, height*width)
794
+ if encoder_outputs is None:
795
+ encoder_outputs = self.encoder(
796
+ inputs_embeds=flattened_features,
797
+ attention_mask=flattened_mask,
798
+ spatial_position_embeddings=spatial_position_embeddings,
799
+ **kwargs,
800
+ )
801
+ # If the user passed a tuple for encoder_outputs, we wrap it in a BaseModelOutput
802
+ elif not isinstance(encoder_outputs, BaseModelOutput):
803
+ encoder_outputs = BaseModelOutput(
804
+ last_hidden_state=encoder_outputs[0],
805
+ hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
806
+ attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
807
+ )
808
+
809
+ # Fifth, sent query embeddings through the decoder (which is conditioned on the encoder output)
810
+ object_queries_position_embeddings = self.query_position_embeddings.weight.unsqueeze(0).repeat(
811
+ batch_size, 1, 1
812
+ )
813
+ queries = torch.zeros_like(object_queries_position_embeddings)
814
+
815
+ # decoder outputs consists of (dec_features, dec_hidden, dec_attn)
816
+ decoder_outputs = self.decoder(
817
+ inputs_embeds=queries,
818
+ attention_mask=None,
819
+ spatial_position_embeddings=spatial_position_embeddings,
820
+ object_queries_position_embeddings=object_queries_position_embeddings,
821
+ encoder_hidden_states=encoder_outputs.last_hidden_state,
822
+ encoder_attention_mask=flattened_mask,
823
+ **kwargs,
824
+ )
825
+
826
+ return ConditionalDetrModelOutput(
827
+ last_hidden_state=decoder_outputs.last_hidden_state,
828
+ decoder_hidden_states=decoder_outputs.hidden_states,
829
+ decoder_attentions=decoder_outputs.attentions,
830
+ cross_attentions=decoder_outputs.cross_attentions,
831
+ encoder_last_hidden_state=encoder_outputs.last_hidden_state,
832
+ encoder_hidden_states=encoder_outputs.hidden_states,
833
+ encoder_attentions=encoder_outputs.attentions,
834
+ intermediate_hidden_states=decoder_outputs.intermediate_hidden_states,
835
+ reference_points=decoder_outputs.reference_points,
836
+ )
837
+
838
+
839
+ class ConditionalDetrForObjectDetection(DetrForObjectDetection):
840
+ def __init__(self, config: ConditionalDetrConfig):
841
+ super().__init__(config)
842
+ self.class_labels_classifier = nn.Linear(config.d_model, config.num_labels)
843
+
844
+ # taken from https://github.com/Atten4Vis/conditionalDETR/blob/master/models/conditional_detr.py
845
+ def _set_aux_loss(self, outputs_class, outputs_coord):
846
+ return [{"logits": a, "pred_boxes": b} for a, b in zip(outputs_class[:-1], outputs_coord[:-1])]
847
+
848
+ @auto_docstring
849
+ @can_return_tuple
850
+ def forward(
851
+ self,
852
+ pixel_values: torch.FloatTensor,
853
+ pixel_mask: torch.LongTensor | None = None,
854
+ decoder_attention_mask: torch.LongTensor | None = None,
855
+ encoder_outputs: torch.FloatTensor | None = None,
856
+ inputs_embeds: torch.FloatTensor | None = None,
857
+ decoder_inputs_embeds: torch.FloatTensor | None = None,
858
+ labels: list[dict] | None = None,
859
+ **kwargs: Unpack[TransformersKwargs],
860
+ ) -> ConditionalDetrObjectDetectionOutput:
861
+ r"""
862
+ decoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, num_queries)`, *optional*):
863
+ Not used by default. Can be used to mask object queries.
864
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
865
+ Optionally, instead of passing the flattened feature map (output of the backbone + projection layer), you
866
+ can choose to directly pass a flattened representation of an image.
867
+ decoder_inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_queries, hidden_size)`, *optional*):
868
+ Optionally, instead of initializing the queries with a tensor of zeros, you can choose to directly pass an
869
+ embedded representation.
870
+ labels (`list[Dict]` of len `(batch_size,)`, *optional*):
871
+ Labels for computing the bipartite matching loss. List of dicts, each dictionary containing at least the
872
+ following 2 keys: 'class_labels' and 'boxes' (the class labels and bounding boxes of an image in the batch
873
+ respectively). The class labels themselves should be a `torch.LongTensor` of len `(number of bounding boxes
874
+ in the image,)` and the boxes a `torch.FloatTensor` of shape `(number of bounding boxes in the image, 4)`.
875
+
876
+ Examples:
877
+
878
+ ```python
879
+ >>> from transformers import AutoImageProcessor, AutoModelForObjectDetection
880
+ >>> from PIL import Image
881
+ >>> import requests
882
+
883
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
884
+ >>> image = Image.open(requests.get(url, stream=True).raw)
885
+
886
+ >>> image_processor = AutoImageProcessor.from_pretrained("microsoft/conditional-detr-resnet-50")
887
+ >>> model = AutoModelForObjectDetection.from_pretrained("microsoft/conditional-detr-resnet-50")
888
+
889
+ >>> inputs = image_processor(images=image, return_tensors="pt")
890
+
891
+ >>> outputs = model(**inputs)
892
+
893
+ >>> # convert outputs (bounding boxes and class logits) to Pascal VOC format (xmin, ymin, xmax, ymax)
894
+ >>> target_sizes = torch.tensor([image.size[::-1]])
895
+ >>> results = image_processor.post_process_object_detection(outputs, threshold=0.5, target_sizes=target_sizes)[
896
+ ... 0
897
+ ... ]
898
+ >>> for score, label, box in zip(results["scores"], results["labels"], results["boxes"]):
899
+ ... box = [round(i, 2) for i in box.tolist()]
900
+ ... print(
901
+ ... f"Detected {model.config.id2label[label.item()]} with confidence "
902
+ ... f"{round(score.item(), 3)} at location {box}"
903
+ ... )
904
+ Detected remote with confidence 0.833 at location [38.31, 72.1, 177.63, 118.45]
905
+ Detected cat with confidence 0.831 at location [9.2, 51.38, 321.13, 469.0]
906
+ Detected cat with confidence 0.804 at location [340.3, 16.85, 642.93, 370.95]
907
+ Detected remote with confidence 0.683 at location [334.48, 73.49, 366.37, 190.01]
908
+ Detected couch with confidence 0.535 at location [0.52, 1.19, 640.35, 475.1]
909
+ ```"""
910
+ # First, sent images through CONDITIONAL_DETR base model to obtain encoder + decoder outputs
911
+ outputs = self.model(
912
+ pixel_values,
913
+ pixel_mask=pixel_mask,
914
+ decoder_attention_mask=decoder_attention_mask,
915
+ encoder_outputs=encoder_outputs,
916
+ inputs_embeds=inputs_embeds,
917
+ decoder_inputs_embeds=decoder_inputs_embeds,
918
+ **kwargs,
919
+ )
920
+
921
+ sequence_output = outputs[0]
922
+
923
+ # class logits + predicted bounding boxes
924
+ logits = self.class_labels_classifier(sequence_output)
925
+
926
+ reference = outputs.reference_points
927
+ reference_before_sigmoid = inverse_sigmoid(reference).transpose(0, 1)
928
+
929
+ hs = sequence_output
930
+ tmp = self.bbox_predictor(hs)
931
+ tmp[..., :2] += reference_before_sigmoid
932
+ pred_boxes = tmp.sigmoid()
933
+ # pred_boxes = self.bbox_predictor(sequence_output).sigmoid()
934
+
935
+ loss, loss_dict, auxiliary_outputs = None, None, None
936
+ if labels is not None:
937
+ outputs_class, outputs_coord = None, None
938
+ if self.config.auxiliary_loss:
939
+ outputs_coords = []
940
+ intermediate = outputs.intermediate_hidden_states
941
+ outputs_class = self.class_labels_classifier(intermediate)
942
+ for lvl in range(intermediate.shape[0]):
943
+ tmp = self.bbox_predictor(intermediate[lvl])
944
+ tmp[..., :2] += reference_before_sigmoid
945
+ outputs_coord = tmp.sigmoid()
946
+ outputs_coords.append(outputs_coord)
947
+ outputs_coord = torch.stack(outputs_coords)
948
+ loss, loss_dict, auxiliary_outputs = self.loss_function(
949
+ logits, labels, self.device, pred_boxes, self.config, outputs_class, outputs_coord
950
+ )
951
+
952
+ return ConditionalDetrObjectDetectionOutput(
953
+ loss=loss,
954
+ loss_dict=loss_dict,
955
+ logits=logits,
956
+ pred_boxes=pred_boxes,
957
+ auxiliary_outputs=auxiliary_outputs,
958
+ last_hidden_state=outputs.last_hidden_state,
959
+ decoder_hidden_states=outputs.decoder_hidden_states,
960
+ decoder_attentions=outputs.decoder_attentions,
961
+ cross_attentions=outputs.cross_attentions,
962
+ encoder_last_hidden_state=outputs.encoder_last_hidden_state,
963
+ encoder_hidden_states=outputs.encoder_hidden_states,
964
+ encoder_attentions=outputs.encoder_attentions,
965
+ )
966
+
967
+
968
+ class ConditionalDetrForSegmentation(DetrForSegmentation):
969
+ pass
970
+
971
+
972
+ __all__ = [
973
+ "ConditionalDetrImageProcessorFast",
974
+ "ConditionalDetrForObjectDetection",
975
+ "ConditionalDetrForSegmentation",
976
+ "ConditionalDetrModel",
977
+ "ConditionalDetrPreTrainedModel",
978
+ ]
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/convbert/__init__.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from ..bert.tokenization_bert import BertTokenizer as ConvBertTokenizerFast
22
+ from .configuration_convbert import *
23
+ from .modeling_convbert import *
24
+ from .tokenization_convbert import *
25
+ else:
26
+ import sys
27
+
28
+ _file = globals()["__file__"]
29
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/convbert/configuration_convbert.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 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
+ """ConvBERT model configuration"""
15
+
16
+ from ...configuration_utils import PreTrainedConfig
17
+ from ...utils import logging
18
+
19
+
20
+ logger = logging.get_logger(__name__)
21
+
22
+
23
+ class ConvBertConfig(PreTrainedConfig):
24
+ r"""
25
+ This is the configuration class to store the configuration of a [`ConvBertModel`]. It is used to instantiate an
26
+ ConvBERT model according to the specified arguments, defining the model architecture. Instantiating a configuration
27
+ with the defaults will yield a similar configuration to that of the ConvBERT
28
+ [YituTech/conv-bert-base](https://huggingface.co/YituTech/conv-bert-base) architecture.
29
+
30
+ Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the
31
+ documentation from [`PreTrainedConfig`] for more information.
32
+
33
+
34
+ Args:
35
+ vocab_size (`int`, *optional*, defaults to 30522):
36
+ Vocabulary size of the ConvBERT model. Defines the number of different tokens that can be represented by
37
+ the `inputs_ids` passed when calling [`ConvBertModel`].
38
+ hidden_size (`int`, *optional*, defaults to 768):
39
+ Dimensionality of the encoder layers and the pooler layer.
40
+ num_hidden_layers (`int`, *optional*, defaults to 12):
41
+ Number of hidden layers in the Transformer encoder.
42
+ num_attention_heads (`int`, *optional*, defaults to 12):
43
+ Number of attention heads for each attention layer in the Transformer encoder.
44
+ intermediate_size (`int`, *optional*, defaults to 3072):
45
+ Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
46
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
47
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
48
+ `"relu"`, `"selu"` and `"gelu_new"` are supported.
49
+ hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
50
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
51
+ attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
52
+ The dropout ratio for the attention probabilities.
53
+ max_position_embeddings (`int`, *optional*, defaults to 512):
54
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
55
+ just in case (e.g., 512 or 1024 or 2048).
56
+ type_vocab_size (`int`, *optional*, defaults to 2):
57
+ The vocabulary size of the `token_type_ids` passed when calling [`ConvBertModel`].
58
+ initializer_range (`float`, *optional*, defaults to 0.02):
59
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
60
+ layer_norm_eps (`float`, *optional*, defaults to 1e-12):
61
+ The epsilon used by the layer normalization layers.
62
+ head_ratio (`int`, *optional*, defaults to 2):
63
+ Ratio gamma to reduce the number of attention heads.
64
+ num_groups (`int`, *optional*, defaults to 1):
65
+ The number of groups for grouped linear layers for ConvBert model
66
+ conv_kernel_size (`int`, *optional*, defaults to 9):
67
+ The size of the convolutional kernel.
68
+ classifier_dropout (`float`, *optional*):
69
+ The dropout ratio for the classification head.
70
+
71
+ Example:
72
+
73
+ ```python
74
+ >>> from transformers import ConvBertConfig, ConvBertModel
75
+
76
+ >>> # Initializing a ConvBERT convbert-base-uncased style configuration
77
+ >>> configuration = ConvBertConfig()
78
+
79
+ >>> # Initializing a model (with random weights) from the convbert-base-uncased style configuration
80
+ >>> model = ConvBertModel(configuration)
81
+
82
+ >>> # Accessing the model configuration
83
+ >>> configuration = model.config
84
+ ```"""
85
+
86
+ model_type = "convbert"
87
+
88
+ def __init__(
89
+ self,
90
+ vocab_size=30522,
91
+ hidden_size=768,
92
+ num_hidden_layers=12,
93
+ num_attention_heads=12,
94
+ intermediate_size=3072,
95
+ hidden_act="gelu",
96
+ hidden_dropout_prob=0.1,
97
+ attention_probs_dropout_prob=0.1,
98
+ max_position_embeddings=512,
99
+ type_vocab_size=2,
100
+ initializer_range=0.02,
101
+ layer_norm_eps=1e-12,
102
+ pad_token_id=1,
103
+ bos_token_id=0,
104
+ eos_token_id=2,
105
+ embedding_size=768,
106
+ head_ratio=2,
107
+ conv_kernel_size=9,
108
+ num_groups=1,
109
+ classifier_dropout=None,
110
+ is_decoder=False,
111
+ add_cross_attention=False,
112
+ tie_word_embeddings=True,
113
+ **kwargs,
114
+ ):
115
+ super().__init__(**kwargs)
116
+ self.pad_token_id = pad_token_id
117
+ self.bos_token_id = bos_token_id
118
+ self.eos_token_id = eos_token_id
119
+ self.tie_word_embeddings = tie_word_embeddings
120
+
121
+ self.is_decoder = is_decoder
122
+ self.add_cross_attention = add_cross_attention
123
+ self.vocab_size = vocab_size
124
+ self.hidden_size = hidden_size
125
+ self.num_hidden_layers = num_hidden_layers
126
+ self.num_attention_heads = num_attention_heads
127
+ self.intermediate_size = intermediate_size
128
+ self.hidden_act = hidden_act
129
+ self.hidden_dropout_prob = hidden_dropout_prob
130
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
131
+ self.max_position_embeddings = max_position_embeddings
132
+ self.type_vocab_size = type_vocab_size
133
+ self.initializer_range = initializer_range
134
+ self.layer_norm_eps = layer_norm_eps
135
+ self.embedding_size = embedding_size
136
+ self.head_ratio = head_ratio
137
+ self.conv_kernel_size = conv_kernel_size
138
+ self.num_groups = num_groups
139
+ self.classifier_dropout = classifier_dropout
140
+
141
+
142
+ __all__ = ["ConvBertConfig"]
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/convbert/modeling_convbert.py ADDED
@@ -0,0 +1,1148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 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
+ """PyTorch ConvBERT model."""
15
+
16
+ import math
17
+ from collections.abc import Callable
18
+
19
+ import torch
20
+ from torch import nn
21
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
22
+
23
+ from ... import initialization as init
24
+ from ...activations import ACT2FN, get_activation
25
+ from ...modeling_layers import GradientCheckpointingLayer
26
+ from ...modeling_outputs import (
27
+ BaseModelOutputWithCrossAttentions,
28
+ MaskedLMOutput,
29
+ MultipleChoiceModelOutput,
30
+ QuestionAnsweringModelOutput,
31
+ SequenceClassifierOutput,
32
+ TokenClassifierOutput,
33
+ )
34
+ from ...modeling_utils import PreTrainedModel
35
+ from ...pytorch_utils import apply_chunking_to_forward
36
+ from ...utils import (
37
+ auto_docstring,
38
+ logging,
39
+ )
40
+ from .configuration_convbert import ConvBertConfig
41
+
42
+
43
+ logger = logging.get_logger(__name__)
44
+
45
+
46
+ class ConvBertEmbeddings(nn.Module):
47
+ """Construct the embeddings from word, position and token_type embeddings."""
48
+
49
+ def __init__(self, config):
50
+ super().__init__()
51
+ self.word_embeddings = nn.Embedding(config.vocab_size, config.embedding_size, padding_idx=config.pad_token_id)
52
+ self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.embedding_size)
53
+ self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.embedding_size)
54
+
55
+ self.LayerNorm = nn.LayerNorm(config.embedding_size, eps=config.layer_norm_eps)
56
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
57
+ # position_ids (1, len position emb) is contiguous in memory and exported when serialized
58
+ self.register_buffer(
59
+ "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
60
+ )
61
+ self.register_buffer(
62
+ "token_type_ids", torch.zeros(self.position_ids.size(), dtype=torch.long), persistent=False
63
+ )
64
+
65
+ def forward(
66
+ self,
67
+ input_ids: torch.LongTensor | None = None,
68
+ token_type_ids: torch.LongTensor | None = None,
69
+ position_ids: torch.LongTensor | None = None,
70
+ inputs_embeds: torch.FloatTensor | None = None,
71
+ ) -> torch.LongTensor:
72
+ if input_ids is not None:
73
+ input_shape = input_ids.size()
74
+ else:
75
+ input_shape = inputs_embeds.size()[:-1]
76
+
77
+ seq_length = input_shape[1]
78
+
79
+ if position_ids is None:
80
+ position_ids = self.position_ids[:, :seq_length]
81
+
82
+ # Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs
83
+ # when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves
84
+ # issue #5664
85
+ if token_type_ids is None:
86
+ if hasattr(self, "token_type_ids"):
87
+ buffered_token_type_ids = self.token_type_ids[:, :seq_length]
88
+ buffered_token_type_ids_expanded = buffered_token_type_ids.expand(input_shape[0], seq_length)
89
+ token_type_ids = buffered_token_type_ids_expanded
90
+ else:
91
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
92
+
93
+ if inputs_embeds is None:
94
+ inputs_embeds = self.word_embeddings(input_ids)
95
+ position_embeddings = self.position_embeddings(position_ids)
96
+ token_type_embeddings = self.token_type_embeddings(token_type_ids)
97
+
98
+ embeddings = inputs_embeds + position_embeddings + token_type_embeddings
99
+ embeddings = self.LayerNorm(embeddings)
100
+ embeddings = self.dropout(embeddings)
101
+ return embeddings
102
+
103
+
104
+ @auto_docstring
105
+ class ConvBertPreTrainedModel(PreTrainedModel):
106
+ config: ConvBertConfig
107
+ base_model_prefix = "convbert"
108
+ supports_gradient_checkpointing = True
109
+
110
+ @torch.no_grad()
111
+ def _init_weights(self, module):
112
+ """Initialize the weights"""
113
+ super()._init_weights(module)
114
+ if isinstance(module, SeparableConv1D):
115
+ init.zeros_(module.bias)
116
+ elif isinstance(module, GroupedLinearLayer):
117
+ init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
118
+ init.zeros_(module.bias)
119
+ elif isinstance(module, ConvBertEmbeddings):
120
+ init.copy_(module.position_ids, torch.arange(module.position_ids.shape[-1]).expand((1, -1)))
121
+ init.zeros_(module.token_type_ids)
122
+
123
+
124
+ class SeparableConv1D(nn.Module):
125
+ """This class implements separable convolution, i.e. a depthwise and a pointwise layer"""
126
+
127
+ def __init__(self, config, input_filters, output_filters, kernel_size, **kwargs):
128
+ super().__init__()
129
+ self.depthwise = nn.Conv1d(
130
+ input_filters,
131
+ input_filters,
132
+ kernel_size=kernel_size,
133
+ groups=input_filters,
134
+ padding=kernel_size // 2,
135
+ bias=False,
136
+ )
137
+ self.pointwise = nn.Conv1d(input_filters, output_filters, kernel_size=1, bias=False)
138
+ self.bias = nn.Parameter(torch.zeros(output_filters, 1))
139
+
140
+ self.depthwise.weight.data.normal_(mean=0.0, std=config.initializer_range)
141
+ self.pointwise.weight.data.normal_(mean=0.0, std=config.initializer_range)
142
+
143
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
144
+ x = self.depthwise(hidden_states)
145
+ x = self.pointwise(x)
146
+ x += self.bias
147
+ return x
148
+
149
+
150
+ class ConvBertSelfAttention(nn.Module):
151
+ def __init__(self, config):
152
+ super().__init__()
153
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
154
+ raise ValueError(
155
+ f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
156
+ f"heads ({config.num_attention_heads})"
157
+ )
158
+
159
+ new_num_attention_heads = config.num_attention_heads // config.head_ratio
160
+ if new_num_attention_heads < 1:
161
+ self.head_ratio = config.num_attention_heads
162
+ self.num_attention_heads = 1
163
+ else:
164
+ self.num_attention_heads = new_num_attention_heads
165
+ self.head_ratio = config.head_ratio
166
+
167
+ self.conv_kernel_size = config.conv_kernel_size
168
+ if config.hidden_size % self.num_attention_heads != 0:
169
+ raise ValueError("hidden_size should be divisible by num_attention_heads")
170
+
171
+ self.attention_head_size = (config.hidden_size // self.num_attention_heads) // 2
172
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
173
+
174
+ self.query = nn.Linear(config.hidden_size, self.all_head_size)
175
+ self.key = nn.Linear(config.hidden_size, self.all_head_size)
176
+ self.value = nn.Linear(config.hidden_size, self.all_head_size)
177
+
178
+ self.key_conv_attn_layer = SeparableConv1D(
179
+ config, config.hidden_size, self.all_head_size, self.conv_kernel_size
180
+ )
181
+ self.conv_kernel_layer = nn.Linear(self.all_head_size, self.num_attention_heads * self.conv_kernel_size)
182
+ self.conv_out_layer = nn.Linear(config.hidden_size, self.all_head_size)
183
+
184
+ self.unfold = nn.Unfold(
185
+ kernel_size=[self.conv_kernel_size, 1], padding=[int((self.conv_kernel_size - 1) / 2), 0]
186
+ )
187
+
188
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
189
+
190
+ def forward(
191
+ self,
192
+ hidden_states: torch.Tensor,
193
+ attention_mask: torch.FloatTensor | None = None,
194
+ encoder_hidden_states: torch.Tensor | None = None,
195
+ output_attentions: bool | None = False,
196
+ ) -> tuple[torch.Tensor, torch.Tensor | None]:
197
+ batch_size, seq_length, _ = hidden_states.shape
198
+ # If this is instantiated as a cross-attention module, the keys
199
+ # and values come from an encoder; the attention mask needs to be
200
+ # such that the encoder's padding tokens are not attended to.
201
+ if encoder_hidden_states is not None:
202
+ mixed_key_layer = self.key(encoder_hidden_states)
203
+ mixed_value_layer = self.value(encoder_hidden_states)
204
+ else:
205
+ mixed_key_layer = self.key(hidden_states)
206
+ mixed_value_layer = self.value(hidden_states)
207
+
208
+ mixed_key_conv_attn_layer = self.key_conv_attn_layer(hidden_states.transpose(1, 2))
209
+ mixed_key_conv_attn_layer = mixed_key_conv_attn_layer.transpose(1, 2)
210
+
211
+ mixed_query_layer = self.query(hidden_states)
212
+ query_layer = mixed_query_layer.view(
213
+ batch_size, -1, self.num_attention_heads, self.attention_head_size
214
+ ).transpose(1, 2)
215
+ key_layer = mixed_key_layer.view(batch_size, -1, self.num_attention_heads, self.attention_head_size).transpose(
216
+ 1, 2
217
+ )
218
+ value_layer = mixed_value_layer.view(
219
+ batch_size, -1, self.num_attention_heads, self.attention_head_size
220
+ ).transpose(1, 2)
221
+ conv_attn_layer = torch.multiply(mixed_key_conv_attn_layer, mixed_query_layer)
222
+
223
+ conv_kernel_layer = self.conv_kernel_layer(conv_attn_layer)
224
+ conv_kernel_layer = torch.reshape(conv_kernel_layer, [-1, self.conv_kernel_size, 1])
225
+ conv_kernel_layer = torch.softmax(conv_kernel_layer, dim=1)
226
+
227
+ conv_out_layer = self.conv_out_layer(hidden_states)
228
+ conv_out_layer = torch.reshape(conv_out_layer, [batch_size, -1, self.all_head_size])
229
+ conv_out_layer = conv_out_layer.transpose(1, 2).contiguous().unsqueeze(-1)
230
+ conv_out_layer = nn.functional.unfold(
231
+ conv_out_layer,
232
+ kernel_size=[self.conv_kernel_size, 1],
233
+ dilation=1,
234
+ padding=[(self.conv_kernel_size - 1) // 2, 0],
235
+ stride=1,
236
+ )
237
+ conv_out_layer = conv_out_layer.transpose(1, 2).reshape(
238
+ batch_size, -1, self.all_head_size, self.conv_kernel_size
239
+ )
240
+ conv_out_layer = torch.reshape(conv_out_layer, [-1, self.attention_head_size, self.conv_kernel_size])
241
+ conv_out_layer = torch.matmul(conv_out_layer, conv_kernel_layer)
242
+ conv_out_layer = torch.reshape(conv_out_layer, [-1, self.all_head_size])
243
+
244
+ # Take the dot product between "query" and "key" to get the raw attention scores.
245
+ attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
246
+ attention_scores = attention_scores / math.sqrt(self.attention_head_size)
247
+ if attention_mask is not None:
248
+ # Apply the attention mask is (precomputed for all layers in ConvBertModel forward() function)
249
+ attention_scores = attention_scores + attention_mask
250
+
251
+ # Normalize the attention scores to probabilities.
252
+ attention_probs = nn.functional.softmax(attention_scores, dim=-1)
253
+
254
+ # This is actually dropping out entire tokens to attend to, which might
255
+ # seem a bit unusual, but is taken from the original Transformer paper.
256
+ attention_probs = self.dropout(attention_probs)
257
+
258
+ context_layer = torch.matmul(attention_probs, value_layer)
259
+ context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
260
+
261
+ conv_out = torch.reshape(conv_out_layer, [batch_size, -1, self.num_attention_heads, self.attention_head_size])
262
+ context_layer = torch.cat([context_layer, conv_out], 2)
263
+
264
+ # conv and context
265
+ new_context_layer_shape = context_layer.size()[:-2] + (
266
+ self.num_attention_heads * self.attention_head_size * 2,
267
+ )
268
+ context_layer = context_layer.view(*new_context_layer_shape)
269
+
270
+ outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
271
+ return outputs
272
+
273
+
274
+ class ConvBertSelfOutput(nn.Module):
275
+ def __init__(self, config):
276
+ super().__init__()
277
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
278
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
279
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
280
+
281
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
282
+ hidden_states = self.dense(hidden_states)
283
+ hidden_states = self.dropout(hidden_states)
284
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
285
+ return hidden_states
286
+
287
+
288
+ class ConvBertAttention(nn.Module):
289
+ def __init__(self, config):
290
+ super().__init__()
291
+ self.self = ConvBertSelfAttention(config)
292
+ self.output = ConvBertSelfOutput(config)
293
+
294
+ def forward(
295
+ self,
296
+ hidden_states: torch.Tensor,
297
+ attention_mask: torch.FloatTensor | None = None,
298
+ encoder_hidden_states: torch.Tensor | None = None,
299
+ output_attentions: bool | None = False,
300
+ ) -> tuple[torch.Tensor, torch.FloatTensor | None]:
301
+ self_outputs = self.self(
302
+ hidden_states,
303
+ attention_mask,
304
+ encoder_hidden_states,
305
+ output_attentions,
306
+ )
307
+ attention_output = self.output(self_outputs[0], hidden_states)
308
+ outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
309
+ return outputs
310
+
311
+
312
+ class GroupedLinearLayer(nn.Module):
313
+ def __init__(self, input_size, output_size, num_groups):
314
+ super().__init__()
315
+ self.input_size = input_size
316
+ self.output_size = output_size
317
+ self.num_groups = num_groups
318
+ self.group_in_dim = self.input_size // self.num_groups
319
+ self.group_out_dim = self.output_size // self.num_groups
320
+ self.weight = nn.Parameter(torch.empty(self.num_groups, self.group_in_dim, self.group_out_dim))
321
+ self.bias = nn.Parameter(torch.empty(output_size))
322
+
323
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
324
+ batch_size = list(hidden_states.size())[0]
325
+ x = torch.reshape(hidden_states, [-1, self.num_groups, self.group_in_dim])
326
+ x = x.permute(1, 0, 2)
327
+ x = torch.matmul(x, self.weight)
328
+ x = x.permute(1, 0, 2)
329
+ x = torch.reshape(x, [batch_size, -1, self.output_size])
330
+ x = x + self.bias
331
+ return x
332
+
333
+
334
+ class ConvBertIntermediate(nn.Module):
335
+ def __init__(self, config):
336
+ super().__init__()
337
+ if config.num_groups == 1:
338
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
339
+ else:
340
+ self.dense = GroupedLinearLayer(
341
+ input_size=config.hidden_size, output_size=config.intermediate_size, num_groups=config.num_groups
342
+ )
343
+ if isinstance(config.hidden_act, str):
344
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
345
+ else:
346
+ self.intermediate_act_fn = config.hidden_act
347
+
348
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
349
+ hidden_states = self.dense(hidden_states)
350
+ hidden_states = self.intermediate_act_fn(hidden_states)
351
+ return hidden_states
352
+
353
+
354
+ class ConvBertOutput(nn.Module):
355
+ def __init__(self, config):
356
+ super().__init__()
357
+ if config.num_groups == 1:
358
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
359
+ else:
360
+ self.dense = GroupedLinearLayer(
361
+ input_size=config.intermediate_size, output_size=config.hidden_size, num_groups=config.num_groups
362
+ )
363
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
364
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
365
+
366
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
367
+ hidden_states = self.dense(hidden_states)
368
+ hidden_states = self.dropout(hidden_states)
369
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
370
+ return hidden_states
371
+
372
+
373
+ class ConvBertLayer(GradientCheckpointingLayer):
374
+ def __init__(self, config):
375
+ super().__init__()
376
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
377
+ self.seq_len_dim = 1
378
+ self.attention = ConvBertAttention(config)
379
+ self.is_decoder = config.is_decoder
380
+ self.add_cross_attention = config.add_cross_attention
381
+ if self.add_cross_attention:
382
+ if not self.is_decoder:
383
+ raise TypeError(f"{self} should be used as a decoder model if cross attention is added")
384
+ self.crossattention = ConvBertAttention(config)
385
+ self.intermediate = ConvBertIntermediate(config)
386
+ self.output = ConvBertOutput(config)
387
+
388
+ def forward(
389
+ self,
390
+ hidden_states: torch.Tensor,
391
+ attention_mask: torch.FloatTensor | None = None,
392
+ encoder_hidden_states: torch.Tensor | None = None,
393
+ encoder_attention_mask: torch.Tensor | None = None,
394
+ output_attentions: bool | None = False,
395
+ ) -> tuple[torch.Tensor, torch.FloatTensor | None]:
396
+ self_attention_outputs = self.attention(
397
+ hidden_states,
398
+ attention_mask,
399
+ output_attentions=output_attentions,
400
+ )
401
+ attention_output = self_attention_outputs[0]
402
+ outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
403
+
404
+ if self.is_decoder and encoder_hidden_states is not None:
405
+ if not hasattr(self, "crossattention"):
406
+ raise AttributeError(
407
+ f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers"
408
+ " by setting `config.add_cross_attention=True`"
409
+ )
410
+ cross_attention_outputs = self.crossattention(
411
+ attention_output,
412
+ encoder_attention_mask,
413
+ encoder_hidden_states,
414
+ output_attentions,
415
+ )
416
+ attention_output = cross_attention_outputs[0]
417
+ outputs = outputs + cross_attention_outputs[1:] # add cross attentions if we output attention weights
418
+
419
+ layer_output = apply_chunking_to_forward(
420
+ self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output
421
+ )
422
+ outputs = (layer_output,) + outputs
423
+ return outputs
424
+
425
+ def feed_forward_chunk(self, attention_output):
426
+ intermediate_output = self.intermediate(attention_output)
427
+ layer_output = self.output(intermediate_output, attention_output)
428
+ return layer_output
429
+
430
+
431
+ class ConvBertEncoder(nn.Module):
432
+ def __init__(self, config):
433
+ super().__init__()
434
+ self.config = config
435
+ self.layer = nn.ModuleList([ConvBertLayer(config) for _ in range(config.num_hidden_layers)])
436
+ self.gradient_checkpointing = False
437
+
438
+ def forward(
439
+ self,
440
+ hidden_states: torch.Tensor,
441
+ attention_mask: torch.FloatTensor | None = None,
442
+ encoder_hidden_states: torch.Tensor | None = None,
443
+ encoder_attention_mask: torch.Tensor | None = None,
444
+ output_attentions: bool | None = False,
445
+ output_hidden_states: bool | None = False,
446
+ return_dict: bool | None = True,
447
+ ) -> tuple | BaseModelOutputWithCrossAttentions:
448
+ all_hidden_states = () if output_hidden_states else None
449
+ all_self_attentions = () if output_attentions else None
450
+ all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None
451
+ for i, layer_module in enumerate(self.layer):
452
+ if output_hidden_states:
453
+ all_hidden_states = all_hidden_states + (hidden_states,)
454
+
455
+ layer_outputs = layer_module(
456
+ hidden_states,
457
+ attention_mask,
458
+ encoder_hidden_states,
459
+ encoder_attention_mask,
460
+ output_attentions,
461
+ )
462
+ hidden_states = layer_outputs[0]
463
+ if output_attentions:
464
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
465
+ if self.config.add_cross_attention:
466
+ all_cross_attentions = all_cross_attentions + (layer_outputs[2],)
467
+
468
+ if output_hidden_states:
469
+ all_hidden_states = all_hidden_states + (hidden_states,)
470
+
471
+ if not return_dict:
472
+ return tuple(
473
+ v
474
+ for v in [hidden_states, all_hidden_states, all_self_attentions, all_cross_attentions]
475
+ if v is not None
476
+ )
477
+ return BaseModelOutputWithCrossAttentions(
478
+ last_hidden_state=hidden_states,
479
+ hidden_states=all_hidden_states,
480
+ attentions=all_self_attentions,
481
+ cross_attentions=all_cross_attentions,
482
+ )
483
+
484
+
485
+ class ConvBertPredictionHeadTransform(nn.Module):
486
+ def __init__(self, config):
487
+ super().__init__()
488
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
489
+ if isinstance(config.hidden_act, str):
490
+ self.transform_act_fn = ACT2FN[config.hidden_act]
491
+ else:
492
+ self.transform_act_fn = config.hidden_act
493
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
494
+
495
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
496
+ hidden_states = self.dense(hidden_states)
497
+ hidden_states = self.transform_act_fn(hidden_states)
498
+ hidden_states = self.LayerNorm(hidden_states)
499
+ return hidden_states
500
+
501
+
502
+ # Copied from transformers.models.xlm.modeling_xlm.XLMSequenceSummary with XLM->ConvBert
503
+ class ConvBertSequenceSummary(nn.Module):
504
+ r"""
505
+ Compute a single vector summary of a sequence hidden states.
506
+
507
+ Args:
508
+ config ([`ConvBertConfig`]):
509
+ The config used by the model. Relevant arguments in the config class of the model are (refer to the actual
510
+ config class of your model for the default values it uses):
511
+
512
+ - **summary_type** (`str`) -- The method to use to make this summary. Accepted values are:
513
+
514
+ - `"last"` -- Take the last token hidden state (like XLNet)
515
+ - `"first"` -- Take the first token hidden state (like Bert)
516
+ - `"mean"` -- Take the mean of all tokens hidden states
517
+ - `"cls_index"` -- Supply a Tensor of classification token position (GPT/GPT-2)
518
+ - `"attn"` -- Not implemented now, use multi-head attention
519
+
520
+ - **summary_use_proj** (`bool`) -- Add a projection after the vector extraction.
521
+ - **summary_proj_to_labels** (`bool`) -- If `True`, the projection outputs to `config.num_labels` classes
522
+ (otherwise to `config.hidden_size`).
523
+ - **summary_activation** (`Optional[str]`) -- Set to `"tanh"` to add a tanh activation to the output,
524
+ another string or `None` will add no activation.
525
+ - **summary_first_dropout** (`float`) -- Optional dropout probability before the projection and activation.
526
+ - **summary_last_dropout** (`float`)-- Optional dropout probability after the projection and activation.
527
+ """
528
+
529
+ def __init__(self, config: ConvBertConfig):
530
+ super().__init__()
531
+
532
+ self.summary_type = getattr(config, "summary_type", "last")
533
+ if self.summary_type == "attn":
534
+ # We should use a standard multi-head attention module with absolute positional embedding for that.
535
+ # Cf. https://github.com/zihangdai/xlnet/blob/master/modeling.py#L253-L276
536
+ # We can probably just use the multi-head attention module of PyTorch >=1.1.0
537
+ raise NotImplementedError
538
+
539
+ self.summary = nn.Identity()
540
+ if hasattr(config, "summary_use_proj") and config.summary_use_proj:
541
+ if hasattr(config, "summary_proj_to_labels") and config.summary_proj_to_labels and config.num_labels > 0:
542
+ num_classes = config.num_labels
543
+ else:
544
+ num_classes = config.hidden_size
545
+ self.summary = nn.Linear(config.hidden_size, num_classes)
546
+
547
+ activation_string = getattr(config, "summary_activation", None)
548
+ self.activation: Callable = get_activation(activation_string) if activation_string else nn.Identity()
549
+
550
+ self.first_dropout = nn.Identity()
551
+ if hasattr(config, "summary_first_dropout") and config.summary_first_dropout > 0:
552
+ self.first_dropout = nn.Dropout(config.summary_first_dropout)
553
+
554
+ self.last_dropout = nn.Identity()
555
+ if hasattr(config, "summary_last_dropout") and config.summary_last_dropout > 0:
556
+ self.last_dropout = nn.Dropout(config.summary_last_dropout)
557
+
558
+ def forward(
559
+ self, hidden_states: torch.FloatTensor, cls_index: torch.LongTensor | None = None
560
+ ) -> torch.FloatTensor:
561
+ """
562
+ Compute a single vector summary of a sequence hidden states.
563
+
564
+ Args:
565
+ hidden_states (`torch.FloatTensor` of shape `[batch_size, seq_len, hidden_size]`):
566
+ The hidden states of the last layer.
567
+ cls_index (`torch.LongTensor` of shape `[batch_size]` or `[batch_size, ...]` where ... are optional leading dimensions of `hidden_states`, *optional*):
568
+ Used if `summary_type == "cls_index"` and takes the last token of the sequence as classification token.
569
+
570
+ Returns:
571
+ `torch.FloatTensor`: The summary of the sequence hidden states.
572
+ """
573
+ if self.summary_type == "last":
574
+ output = hidden_states[:, -1]
575
+ elif self.summary_type == "first":
576
+ output = hidden_states[:, 0]
577
+ elif self.summary_type == "mean":
578
+ output = hidden_states.mean(dim=1)
579
+ elif self.summary_type == "cls_index":
580
+ if cls_index is None:
581
+ cls_index = torch.full_like(
582
+ hidden_states[..., :1, :],
583
+ hidden_states.shape[-2] - 1,
584
+ dtype=torch.long,
585
+ )
586
+ else:
587
+ cls_index = cls_index.unsqueeze(-1).unsqueeze(-1)
588
+ cls_index = cls_index.expand((-1,) * (cls_index.dim() - 1) + (hidden_states.size(-1),))
589
+ # shape of cls_index: (bsz, XX, 1, hidden_size) where XX are optional leading dim of hidden_states
590
+ output = hidden_states.gather(-2, cls_index).squeeze(-2) # shape (bsz, XX, hidden_size)
591
+ elif self.summary_type == "attn":
592
+ raise NotImplementedError
593
+
594
+ output = self.first_dropout(output)
595
+ output = self.summary(output)
596
+ output = self.activation(output)
597
+ output = self.last_dropout(output)
598
+
599
+ return output
600
+
601
+
602
+ @auto_docstring
603
+ class ConvBertModel(ConvBertPreTrainedModel):
604
+ def __init__(self, config):
605
+ super().__init__(config)
606
+ self.embeddings = ConvBertEmbeddings(config)
607
+
608
+ if config.embedding_size != config.hidden_size:
609
+ self.embeddings_project = nn.Linear(config.embedding_size, config.hidden_size)
610
+
611
+ self.encoder = ConvBertEncoder(config)
612
+ self.config = config
613
+ # Initialize weights and apply final processing
614
+ self.post_init()
615
+
616
+ def get_input_embeddings(self):
617
+ return self.embeddings.word_embeddings
618
+
619
+ def set_input_embeddings(self, value):
620
+ self.embeddings.word_embeddings = value
621
+
622
+ @auto_docstring
623
+ def forward(
624
+ self,
625
+ input_ids: torch.LongTensor | None = None,
626
+ attention_mask: torch.FloatTensor | None = None,
627
+ token_type_ids: torch.LongTensor | None = None,
628
+ position_ids: torch.LongTensor | None = None,
629
+ inputs_embeds: torch.FloatTensor | None = None,
630
+ output_attentions: bool | None = None,
631
+ output_hidden_states: bool | None = None,
632
+ return_dict: bool | None = None,
633
+ **kwargs,
634
+ ) -> tuple | BaseModelOutputWithCrossAttentions:
635
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
636
+ output_hidden_states = (
637
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
638
+ )
639
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
640
+
641
+ if input_ids is not None and inputs_embeds is not None:
642
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
643
+ elif input_ids is not None:
644
+ self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
645
+ input_shape = input_ids.size()
646
+ elif inputs_embeds is not None:
647
+ input_shape = inputs_embeds.size()[:-1]
648
+ else:
649
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
650
+
651
+ batch_size, seq_length = input_shape
652
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
653
+
654
+ if attention_mask is None:
655
+ attention_mask = torch.ones(input_shape, device=device)
656
+ if token_type_ids is None:
657
+ if hasattr(self.embeddings, "token_type_ids"):
658
+ buffered_token_type_ids = self.embeddings.token_type_ids[:, :seq_length]
659
+ buffered_token_type_ids_expanded = buffered_token_type_ids.expand(batch_size, seq_length)
660
+ token_type_ids = buffered_token_type_ids_expanded
661
+ else:
662
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
663
+
664
+ extended_attention_mask = self.get_extended_attention_mask(attention_mask, input_shape)
665
+
666
+ hidden_states = self.embeddings(
667
+ input_ids=input_ids, position_ids=position_ids, token_type_ids=token_type_ids, inputs_embeds=inputs_embeds
668
+ )
669
+
670
+ if hasattr(self, "embeddings_project"):
671
+ hidden_states = self.embeddings_project(hidden_states)
672
+
673
+ hidden_states = self.encoder(
674
+ hidden_states,
675
+ attention_mask=extended_attention_mask,
676
+ output_attentions=output_attentions,
677
+ output_hidden_states=output_hidden_states,
678
+ return_dict=return_dict,
679
+ )
680
+
681
+ return hidden_states
682
+
683
+
684
+ class ConvBertGeneratorPredictions(nn.Module):
685
+ """Prediction module for the generator, made up of two dense layers."""
686
+
687
+ def __init__(self, config):
688
+ super().__init__()
689
+
690
+ self.activation = get_activation("gelu")
691
+ self.LayerNorm = nn.LayerNorm(config.embedding_size, eps=config.layer_norm_eps)
692
+ self.dense = nn.Linear(config.hidden_size, config.embedding_size)
693
+
694
+ def forward(self, generator_hidden_states: torch.FloatTensor) -> torch.FloatTensor:
695
+ hidden_states = self.dense(generator_hidden_states)
696
+ hidden_states = self.activation(hidden_states)
697
+ hidden_states = self.LayerNorm(hidden_states)
698
+
699
+ return hidden_states
700
+
701
+
702
+ @auto_docstring
703
+ class ConvBertForMaskedLM(ConvBertPreTrainedModel):
704
+ _tied_weights_keys = {"generator_lm_head.weight": "convbert.embeddings.word_embeddings.weight"}
705
+
706
+ def __init__(self, config):
707
+ super().__init__(config)
708
+
709
+ self.convbert = ConvBertModel(config)
710
+ self.generator_predictions = ConvBertGeneratorPredictions(config)
711
+
712
+ self.generator_lm_head = nn.Linear(config.embedding_size, config.vocab_size)
713
+ # Initialize weights and apply final processing
714
+ self.post_init()
715
+
716
+ def get_output_embeddings(self):
717
+ return self.generator_lm_head
718
+
719
+ def set_output_embeddings(self, word_embeddings):
720
+ self.generator_lm_head = word_embeddings
721
+
722
+ @auto_docstring
723
+ def forward(
724
+ self,
725
+ input_ids: torch.LongTensor | None = None,
726
+ attention_mask: torch.FloatTensor | None = None,
727
+ token_type_ids: torch.LongTensor | None = None,
728
+ position_ids: torch.LongTensor | None = None,
729
+ inputs_embeds: torch.FloatTensor | None = None,
730
+ labels: torch.LongTensor | None = None,
731
+ output_attentions: bool | None = None,
732
+ output_hidden_states: bool | None = None,
733
+ return_dict: bool | None = None,
734
+ **kwargs,
735
+ ) -> tuple | MaskedLMOutput:
736
+ r"""
737
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
738
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
739
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
740
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
741
+ """
742
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
743
+
744
+ generator_hidden_states = self.convbert(
745
+ input_ids,
746
+ attention_mask,
747
+ token_type_ids,
748
+ position_ids,
749
+ inputs_embeds,
750
+ output_attentions,
751
+ output_hidden_states,
752
+ return_dict,
753
+ )
754
+ generator_sequence_output = generator_hidden_states[0]
755
+
756
+ prediction_scores = self.generator_predictions(generator_sequence_output)
757
+ prediction_scores = self.generator_lm_head(prediction_scores)
758
+
759
+ loss = None
760
+ # Masked language modeling softmax layer
761
+ if labels is not None:
762
+ loss_fct = nn.CrossEntropyLoss() # -100 index = padding token
763
+ loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
764
+
765
+ if not return_dict:
766
+ output = (prediction_scores,) + generator_hidden_states[1:]
767
+ return ((loss,) + output) if loss is not None else output
768
+
769
+ return MaskedLMOutput(
770
+ loss=loss,
771
+ logits=prediction_scores,
772
+ hidden_states=generator_hidden_states.hidden_states,
773
+ attentions=generator_hidden_states.attentions,
774
+ )
775
+
776
+
777
+ class ConvBertClassificationHead(nn.Module):
778
+ """Head for sentence-level classification tasks."""
779
+
780
+ def __init__(self, config):
781
+ super().__init__()
782
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
783
+ classifier_dropout = (
784
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
785
+ )
786
+ self.dropout = nn.Dropout(classifier_dropout)
787
+ self.out_proj = nn.Linear(config.hidden_size, config.num_labels)
788
+
789
+ self.config = config
790
+
791
+ def forward(self, hidden_states: torch.Tensor, **kwargs) -> torch.Tensor:
792
+ x = hidden_states[:, 0, :] # take <s> token (equiv. to [CLS])
793
+ x = self.dropout(x)
794
+ x = self.dense(x)
795
+ x = ACT2FN[self.config.hidden_act](x)
796
+ x = self.dropout(x)
797
+ x = self.out_proj(x)
798
+ return x
799
+
800
+
801
+ @auto_docstring(
802
+ custom_intro="""
803
+ ConvBERT Model transformer with a sequence classification/regression head on top (a linear layer on top of the
804
+ pooled output) e.g. for GLUE tasks.
805
+ """
806
+ )
807
+ class ConvBertForSequenceClassification(ConvBertPreTrainedModel):
808
+ def __init__(self, config):
809
+ super().__init__(config)
810
+ self.num_labels = config.num_labels
811
+ self.config = config
812
+ self.convbert = ConvBertModel(config)
813
+ self.classifier = ConvBertClassificationHead(config)
814
+
815
+ # Initialize weights and apply final processing
816
+ self.post_init()
817
+
818
+ @auto_docstring
819
+ def forward(
820
+ self,
821
+ input_ids: torch.LongTensor | None = None,
822
+ attention_mask: torch.FloatTensor | None = None,
823
+ token_type_ids: torch.LongTensor | None = None,
824
+ position_ids: torch.LongTensor | None = None,
825
+ inputs_embeds: torch.FloatTensor | None = None,
826
+ labels: torch.LongTensor | None = None,
827
+ output_attentions: bool | None = None,
828
+ output_hidden_states: bool | None = None,
829
+ return_dict: bool | None = None,
830
+ **kwargs,
831
+ ) -> tuple | SequenceClassifierOutput:
832
+ r"""
833
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
834
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
835
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
836
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
837
+ """
838
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
839
+
840
+ outputs = self.convbert(
841
+ input_ids,
842
+ attention_mask=attention_mask,
843
+ token_type_ids=token_type_ids,
844
+ position_ids=position_ids,
845
+ inputs_embeds=inputs_embeds,
846
+ output_attentions=output_attentions,
847
+ output_hidden_states=output_hidden_states,
848
+ return_dict=return_dict,
849
+ )
850
+
851
+ sequence_output = outputs[0]
852
+ logits = self.classifier(sequence_output)
853
+
854
+ loss = None
855
+ if labels is not None:
856
+ if self.config.problem_type is None:
857
+ if self.num_labels == 1:
858
+ self.config.problem_type = "regression"
859
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
860
+ self.config.problem_type = "single_label_classification"
861
+ else:
862
+ self.config.problem_type = "multi_label_classification"
863
+
864
+ if self.config.problem_type == "regression":
865
+ loss_fct = MSELoss()
866
+ if self.num_labels == 1:
867
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
868
+ else:
869
+ loss = loss_fct(logits, labels)
870
+ elif self.config.problem_type == "single_label_classification":
871
+ loss_fct = CrossEntropyLoss()
872
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
873
+ elif self.config.problem_type == "multi_label_classification":
874
+ loss_fct = BCEWithLogitsLoss()
875
+ loss = loss_fct(logits, labels)
876
+
877
+ if not return_dict:
878
+ output = (logits,) + outputs[1:]
879
+ return ((loss,) + output) if loss is not None else output
880
+
881
+ return SequenceClassifierOutput(
882
+ loss=loss,
883
+ logits=logits,
884
+ hidden_states=outputs.hidden_states,
885
+ attentions=outputs.attentions,
886
+ )
887
+
888
+
889
+ @auto_docstring
890
+ class ConvBertForMultipleChoice(ConvBertPreTrainedModel):
891
+ def __init__(self, config):
892
+ super().__init__(config)
893
+
894
+ self.convbert = ConvBertModel(config)
895
+ self.sequence_summary = ConvBertSequenceSummary(config)
896
+ self.classifier = nn.Linear(config.hidden_size, 1)
897
+
898
+ # Initialize weights and apply final processing
899
+ self.post_init()
900
+
901
+ @auto_docstring
902
+ def forward(
903
+ self,
904
+ input_ids: torch.LongTensor | None = None,
905
+ attention_mask: torch.FloatTensor | None = None,
906
+ token_type_ids: torch.LongTensor | None = None,
907
+ position_ids: torch.LongTensor | None = None,
908
+ inputs_embeds: torch.FloatTensor | None = None,
909
+ labels: torch.LongTensor | None = None,
910
+ output_attentions: bool | None = None,
911
+ output_hidden_states: bool | None = None,
912
+ return_dict: bool | None = None,
913
+ **kwargs,
914
+ ) -> tuple | MultipleChoiceModelOutput:
915
+ r"""
916
+ input_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`):
917
+ Indices of input sequence tokens in the vocabulary.
918
+
919
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
920
+ [`PreTrainedTokenizer.__call__`] for details.
921
+
922
+ [What are input IDs?](../glossary#input-ids)
923
+ token_type_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
924
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
925
+ 1]`:
926
+
927
+
928
+ - 0 corresponds to a *sentence A* token,
929
+ - 1 corresponds to a *sentence B* token.
930
+
931
+ [What are token type IDs?](../glossary#token-type-ids)
932
+ position_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
933
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
934
+ config.max_position_embeddings - 1]`.
935
+
936
+ [What are position IDs?](../glossary#position-ids)
937
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_choices, sequence_length, hidden_size)`, *optional*):
938
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
939
+ is useful if you want more control over how to convert *input_ids* indices into associated vectors than the
940
+ model's internal embedding lookup matrix.
941
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
942
+ Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
943
+ num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
944
+ `input_ids` above)
945
+ """
946
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
947
+ num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
948
+
949
+ input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
950
+ attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
951
+ token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None
952
+ position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None
953
+ inputs_embeds = (
954
+ inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
955
+ if inputs_embeds is not None
956
+ else None
957
+ )
958
+
959
+ outputs = self.convbert(
960
+ input_ids,
961
+ attention_mask=attention_mask,
962
+ token_type_ids=token_type_ids,
963
+ position_ids=position_ids,
964
+ inputs_embeds=inputs_embeds,
965
+ output_attentions=output_attentions,
966
+ output_hidden_states=output_hidden_states,
967
+ return_dict=return_dict,
968
+ )
969
+
970
+ sequence_output = outputs[0]
971
+
972
+ pooled_output = self.sequence_summary(sequence_output)
973
+ logits = self.classifier(pooled_output)
974
+ reshaped_logits = logits.view(-1, num_choices)
975
+
976
+ loss = None
977
+ if labels is not None:
978
+ loss_fct = CrossEntropyLoss()
979
+ loss = loss_fct(reshaped_logits, labels)
980
+
981
+ if not return_dict:
982
+ output = (reshaped_logits,) + outputs[1:]
983
+ return ((loss,) + output) if loss is not None else output
984
+
985
+ return MultipleChoiceModelOutput(
986
+ loss=loss,
987
+ logits=reshaped_logits,
988
+ hidden_states=outputs.hidden_states,
989
+ attentions=outputs.attentions,
990
+ )
991
+
992
+
993
+ @auto_docstring
994
+ class ConvBertForTokenClassification(ConvBertPreTrainedModel):
995
+ def __init__(self, config):
996
+ super().__init__(config)
997
+ self.num_labels = config.num_labels
998
+
999
+ self.convbert = ConvBertModel(config)
1000
+ classifier_dropout = (
1001
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
1002
+ )
1003
+ self.dropout = nn.Dropout(classifier_dropout)
1004
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1005
+
1006
+ # Initialize weights and apply final processing
1007
+ self.post_init()
1008
+
1009
+ @auto_docstring
1010
+ def forward(
1011
+ self,
1012
+ input_ids: torch.LongTensor | None = None,
1013
+ attention_mask: torch.FloatTensor | None = None,
1014
+ token_type_ids: torch.LongTensor | None = None,
1015
+ position_ids: torch.LongTensor | None = None,
1016
+ inputs_embeds: torch.FloatTensor | None = None,
1017
+ labels: torch.LongTensor | None = None,
1018
+ output_attentions: bool | None = None,
1019
+ output_hidden_states: bool | None = None,
1020
+ return_dict: bool | None = None,
1021
+ **kwargs,
1022
+ ) -> tuple | TokenClassifierOutput:
1023
+ r"""
1024
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1025
+ Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
1026
+ """
1027
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1028
+
1029
+ outputs = self.convbert(
1030
+ input_ids,
1031
+ attention_mask=attention_mask,
1032
+ token_type_ids=token_type_ids,
1033
+ position_ids=position_ids,
1034
+ inputs_embeds=inputs_embeds,
1035
+ output_attentions=output_attentions,
1036
+ output_hidden_states=output_hidden_states,
1037
+ return_dict=return_dict,
1038
+ )
1039
+
1040
+ sequence_output = outputs[0]
1041
+
1042
+ sequence_output = self.dropout(sequence_output)
1043
+ logits = self.classifier(sequence_output)
1044
+
1045
+ loss = None
1046
+ if labels is not None:
1047
+ loss_fct = CrossEntropyLoss()
1048
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1049
+
1050
+ if not return_dict:
1051
+ output = (logits,) + outputs[1:]
1052
+ return ((loss,) + output) if loss is not None else output
1053
+
1054
+ return TokenClassifierOutput(
1055
+ loss=loss,
1056
+ logits=logits,
1057
+ hidden_states=outputs.hidden_states,
1058
+ attentions=outputs.attentions,
1059
+ )
1060
+
1061
+
1062
+ @auto_docstring
1063
+ class ConvBertForQuestionAnswering(ConvBertPreTrainedModel):
1064
+ def __init__(self, config):
1065
+ super().__init__(config)
1066
+
1067
+ self.num_labels = config.num_labels
1068
+ self.convbert = ConvBertModel(config)
1069
+ self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
1070
+
1071
+ # Initialize weights and apply final processing
1072
+ self.post_init()
1073
+
1074
+ @auto_docstring
1075
+ def forward(
1076
+ self,
1077
+ input_ids: torch.LongTensor | None = None,
1078
+ attention_mask: torch.FloatTensor | None = None,
1079
+ token_type_ids: torch.LongTensor | None = None,
1080
+ position_ids: torch.LongTensor | None = None,
1081
+ inputs_embeds: torch.FloatTensor | None = None,
1082
+ start_positions: torch.LongTensor | None = None,
1083
+ end_positions: torch.LongTensor | None = None,
1084
+ output_attentions: bool | None = None,
1085
+ output_hidden_states: bool | None = None,
1086
+ return_dict: bool | None = None,
1087
+ **kwargs,
1088
+ ) -> tuple | QuestionAnsweringModelOutput:
1089
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1090
+
1091
+ outputs = self.convbert(
1092
+ input_ids,
1093
+ attention_mask=attention_mask,
1094
+ token_type_ids=token_type_ids,
1095
+ position_ids=position_ids,
1096
+ inputs_embeds=inputs_embeds,
1097
+ output_attentions=output_attentions,
1098
+ output_hidden_states=output_hidden_states,
1099
+ return_dict=return_dict,
1100
+ )
1101
+
1102
+ sequence_output = outputs[0]
1103
+
1104
+ logits = self.qa_outputs(sequence_output)
1105
+ start_logits, end_logits = logits.split(1, dim=-1)
1106
+ start_logits = start_logits.squeeze(-1).contiguous()
1107
+ end_logits = end_logits.squeeze(-1).contiguous()
1108
+
1109
+ total_loss = None
1110
+ if start_positions is not None and end_positions is not None:
1111
+ # If we are on multi-GPU, split add a dimension
1112
+ if len(start_positions.size()) > 1:
1113
+ start_positions = start_positions.squeeze(-1)
1114
+ if len(end_positions.size()) > 1:
1115
+ end_positions = end_positions.squeeze(-1)
1116
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
1117
+ ignored_index = start_logits.size(1)
1118
+ start_positions = start_positions.clamp(0, ignored_index)
1119
+ end_positions = end_positions.clamp(0, ignored_index)
1120
+
1121
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
1122
+ start_loss = loss_fct(start_logits, start_positions)
1123
+ end_loss = loss_fct(end_logits, end_positions)
1124
+ total_loss = (start_loss + end_loss) / 2
1125
+
1126
+ if not return_dict:
1127
+ output = (start_logits, end_logits) + outputs[1:]
1128
+ return ((total_loss,) + output) if total_loss is not None else output
1129
+
1130
+ return QuestionAnsweringModelOutput(
1131
+ loss=total_loss,
1132
+ start_logits=start_logits,
1133
+ end_logits=end_logits,
1134
+ hidden_states=outputs.hidden_states,
1135
+ attentions=outputs.attentions,
1136
+ )
1137
+
1138
+
1139
+ __all__ = [
1140
+ "ConvBertForMaskedLM",
1141
+ "ConvBertForMultipleChoice",
1142
+ "ConvBertForQuestionAnswering",
1143
+ "ConvBertForSequenceClassification",
1144
+ "ConvBertForTokenClassification",
1145
+ "ConvBertLayer",
1146
+ "ConvBertModel",
1147
+ "ConvBertPreTrainedModel",
1148
+ ]
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/convbert/tokenization_convbert.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 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
+ """Tokenization classes for ConvBERT."""
15
+
16
+ from ...models.bert.tokenization_bert import BertTokenizer
17
+
18
+
19
+ class ConvBertTokenizer(BertTokenizer):
20
+ r"""
21
+ Construct a ConvBERT tokenizer (backed by HuggingFace's tokenizers library). Based on WordPiece.
22
+
23
+ This tokenizer inherits from [`BertTokenizer`] which contains most of the main methods. Users should
24
+ refer to this superclass for more information regarding those methods.
25
+ """
26
+
27
+ pass
28
+
29
+
30
+ __all__ = ["ConvBertTokenizer"]
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/convnext/__init__.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_convnext import *
22
+ from .feature_extraction_convnext import *
23
+ from .image_processing_convnext import *
24
+ from .image_processing_convnext_fast import *
25
+ from .modeling_convnext import *
26
+ else:
27
+ import sys
28
+
29
+ _file = globals()["__file__"]
30
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/convnext/configuration_convnext.py ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 Meta Platforms, Inc. and 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
+ """ConvNeXT model configuration"""
15
+
16
+ from ...backbone_utils import BackboneConfigMixin
17
+ from ...configuration_utils import PreTrainedConfig
18
+ from ...utils import logging
19
+
20
+
21
+ logger = logging.get_logger(__name__)
22
+
23
+
24
+ class ConvNextConfig(BackboneConfigMixin, PreTrainedConfig):
25
+ r"""
26
+ This is the configuration class to store the configuration of a [`ConvNextModel`]. It is used to instantiate an
27
+ ConvNeXT model according to the specified arguments, defining the model architecture. Instantiating a configuration
28
+ with the defaults will yield a similar configuration to that of the ConvNeXT
29
+ [facebook/convnext-tiny-224](https://huggingface.co/facebook/convnext-tiny-224) architecture.
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
+ num_channels (`int`, *optional*, defaults to 3):
36
+ The number of input channels.
37
+ patch_size (`int`, *optional*, defaults to 4):
38
+ Patch size to use in the patch embedding layer.
39
+ num_stages (`int`, *optional*, defaults to 4):
40
+ The number of stages in the model.
41
+ hidden_sizes (`list[int]`, *optional*, defaults to [96, 192, 384, 768]):
42
+ Dimensionality (hidden size) at each stage.
43
+ depths (`list[int]`, *optional*, defaults to [3, 3, 9, 3]):
44
+ Depth (number of blocks) for each stage.
45
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
46
+ The non-linear activation function (function or string) in each block. If string, `"gelu"`, `"relu"`,
47
+ `"selu"` and `"gelu_new"` are supported.
48
+ initializer_range (`float`, *optional*, defaults to 0.02):
49
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
50
+ layer_norm_eps (`float`, *optional*, defaults to 1e-12):
51
+ The epsilon used by the layer normalization layers.
52
+ layer_scale_init_value (`float`, *optional*, defaults to 1e-6):
53
+ The initial value for the layer scale.
54
+ drop_path_rate (`float`, *optional*, defaults to 0.0):
55
+ The drop rate for stochastic depth.
56
+ out_features (`list[str]`, *optional*):
57
+ If used as backbone, list of features to output. Can be any of `"stem"`, `"stage1"`, `"stage2"`, etc.
58
+ (depending on how many stages the model has). If unset and `out_indices` is set, will default to the
59
+ corresponding stages. If unset and `out_indices` is unset, will default to the last stage. Must be in the
60
+ same order as defined in the `stage_names` attribute.
61
+ out_indices (`list[int]`, *optional*):
62
+ If used as backbone, list of indices of features to output. Can be any of 0, 1, 2, etc. (depending on how
63
+ many stages the model has). If unset and `out_features` is set, will default to the corresponding stages.
64
+ If unset and `out_features` is unset, will default to the last stage. Must be in the
65
+ same order as defined in the `stage_names` attribute.
66
+
67
+ Example:
68
+ ```python
69
+ >>> from transformers import ConvNextConfig, ConvNextModel
70
+
71
+ >>> # Initializing a ConvNext convnext-tiny-224 style configuration
72
+ >>> configuration = ConvNextConfig()
73
+
74
+ >>> # Initializing a model (with random weights) from the convnext-tiny-224 style configuration
75
+ >>> model = ConvNextModel(configuration)
76
+
77
+ >>> # Accessing the model configuration
78
+ >>> configuration = model.config
79
+ ```"""
80
+
81
+ model_type = "convnext"
82
+
83
+ def __init__(
84
+ self,
85
+ num_channels=3,
86
+ patch_size=4,
87
+ num_stages=4,
88
+ hidden_sizes=None,
89
+ depths=None,
90
+ hidden_act="gelu",
91
+ initializer_range=0.02,
92
+ layer_norm_eps=1e-12,
93
+ layer_scale_init_value=1e-6,
94
+ drop_path_rate=0.0,
95
+ image_size=224,
96
+ out_features=None,
97
+ out_indices=None,
98
+ **kwargs,
99
+ ):
100
+ super().__init__(**kwargs)
101
+
102
+ self.num_channels = num_channels
103
+ self.patch_size = patch_size
104
+ self.num_stages = num_stages
105
+ self.hidden_sizes = [96, 192, 384, 768] if hidden_sizes is None else hidden_sizes
106
+ self.depths = [3, 3, 9, 3] if depths is None else depths
107
+ self.hidden_act = hidden_act
108
+ self.initializer_range = initializer_range
109
+ self.layer_norm_eps = layer_norm_eps
110
+ self.layer_scale_init_value = layer_scale_init_value
111
+ self.drop_path_rate = drop_path_rate
112
+ self.image_size = image_size
113
+ self.stage_names = ["stem"] + [f"stage{idx}" for idx in range(1, len(self.depths) + 1)]
114
+ self.set_output_features_output_indices(out_indices=out_indices, out_features=out_features)
115
+
116
+
117
+ __all__ = ["ConvNextConfig"]
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/convnext/image_processing_convnext.py ADDED
@@ -0,0 +1,329 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 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
+ """Image processor class for ConvNeXT."""
15
+
16
+ import numpy as np
17
+
18
+ from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
19
+ from ...image_transforms import (
20
+ center_crop,
21
+ get_resize_output_image_size,
22
+ resize,
23
+ to_channel_dimension_format,
24
+ )
25
+ from ...image_utils import (
26
+ IMAGENET_STANDARD_MEAN,
27
+ IMAGENET_STANDARD_STD,
28
+ ChannelDimension,
29
+ ImageInput,
30
+ PILImageResampling,
31
+ infer_channel_dimension_format,
32
+ is_scaled_image,
33
+ make_flat_list_of_images,
34
+ to_numpy_array,
35
+ valid_images,
36
+ validate_preprocess_arguments,
37
+ )
38
+ from ...processing_utils import ImagesKwargs
39
+ from ...utils import TensorType, filter_out_non_signature_kwargs, is_vision_available, logging
40
+ from ...utils.import_utils import requires
41
+
42
+
43
+ if is_vision_available():
44
+ import PIL
45
+
46
+
47
+ logger = logging.get_logger(__name__)
48
+
49
+
50
+ class ConvNextImageProcessorKwargs(ImagesKwargs, total=False):
51
+ """
52
+ crop_pct (`float`, *optional*):
53
+ Percentage of the image to crop. Only has an effect if size < 384. Can be
54
+ overridden by `crop_pct` in the`preprocess` method.
55
+ """
56
+
57
+ crop_pct: float
58
+
59
+
60
+ @requires(backends=("vision",))
61
+ class ConvNextImageProcessor(BaseImageProcessor):
62
+ r"""
63
+ Constructs a ConvNeXT image processor.
64
+
65
+ Args:
66
+ do_resize (`bool`, *optional*, defaults to `True`):
67
+ Controls whether to resize the image's (height, width) dimensions to the specified `size`. Can be overridden
68
+ by `do_resize` in the `preprocess` method.
69
+ size (`dict[str, int]` *optional*, defaults to `{"shortest_edge": 384}`):
70
+ Resolution of the output image after `resize` is applied. If `size["shortest_edge"]` >= 384, the image is
71
+ resized to `(size["shortest_edge"], size["shortest_edge"])`. Otherwise, the smaller edge of the image will
72
+ be matched to `int(size["shortest_edge"]/crop_pct)`, after which the image is cropped to
73
+ `(size["shortest_edge"], size["shortest_edge"])`. Only has an effect if `do_resize` is set to `True`. Can
74
+ be overridden by `size` in the `preprocess` method.
75
+ crop_pct (`float` *optional*, defaults to 224 / 256):
76
+ Percentage of the image to crop. Only has an effect if `do_resize` is `True` and size < 384. Can be
77
+ overridden by `crop_pct` in the `preprocess` method.
78
+ resample (`PILImageResampling`, *optional*, defaults to `Resampling.BICUBIC`):
79
+ Resampling filter to use if resizing the image. Can be overridden by `resample` in the `preprocess` method.
80
+ do_rescale (`bool`, *optional*, defaults to `True`):
81
+ Whether to rescale the image by the specified scale `rescale_factor`. Can be overridden by `do_rescale` in
82
+ the `preprocess` method.
83
+ rescale_factor (`int` or `float`, *optional*, defaults to `1/255`):
84
+ Scale factor to use if rescaling the image. Can be overridden by `rescale_factor` in the `preprocess`
85
+ method.
86
+ do_normalize (`bool`, *optional*, defaults to `True`):
87
+ Whether to normalize the image. Can be overridden by the `do_normalize` parameter in the `preprocess`
88
+ method.
89
+ image_mean (`float` or `list[float]`, *optional*, defaults to `IMAGENET_STANDARD_MEAN`):
90
+ Mean to use if normalizing the image. This is a float or list of floats the length of the number of
91
+ channels in the image. Can be overridden by the `image_mean` parameter in the `preprocess` method.
92
+ image_std (`float` or `list[float]`, *optional*, defaults to `IMAGENET_STANDARD_STD`):
93
+ Standard deviation to use if normalizing the image. This is a float or list of floats the length of the
94
+ number of channels in the image. Can be overridden by the `image_std` parameter in the `preprocess` method.
95
+ """
96
+
97
+ model_input_names = ["pixel_values"]
98
+ valid_kwargs = ConvNextImageProcessorKwargs
99
+
100
+ def __init__(
101
+ self,
102
+ do_resize: bool = True,
103
+ size: dict[str, int] | None = None,
104
+ crop_pct: float | None = None,
105
+ resample: PILImageResampling = PILImageResampling.BICUBIC,
106
+ do_rescale: bool = True,
107
+ rescale_factor: int | float = 1 / 255,
108
+ do_normalize: bool = True,
109
+ image_mean: float | list[float] | None = None,
110
+ image_std: float | list[float] | None = None,
111
+ **kwargs,
112
+ ) -> None:
113
+ super().__init__(**kwargs)
114
+ size = size if size is not None else {"shortest_edge": 384}
115
+ size = get_size_dict(size, default_to_square=False)
116
+
117
+ self.do_resize = do_resize
118
+ self.size = size
119
+ # Default value set here for backwards compatibility where the value in config is None
120
+ self.crop_pct = crop_pct if crop_pct is not None else 224 / 256
121
+ self.resample = resample
122
+ self.do_rescale = do_rescale
123
+ self.rescale_factor = rescale_factor
124
+ self.do_normalize = do_normalize
125
+ self.image_mean = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
126
+ self.image_std = image_std if image_std is not None else IMAGENET_STANDARD_STD
127
+
128
+ def resize(
129
+ self,
130
+ image: np.ndarray,
131
+ size: dict[str, int],
132
+ crop_pct: float,
133
+ resample: PILImageResampling = PILImageResampling.BICUBIC,
134
+ data_format: str | ChannelDimension | None = None,
135
+ input_data_format: str | ChannelDimension | None = None,
136
+ **kwargs,
137
+ ) -> np.ndarray:
138
+ """
139
+ Resize an image.
140
+
141
+ Args:
142
+ image (`np.ndarray`):
143
+ Image to resize.
144
+ size (`dict[str, int]`):
145
+ Dictionary of the form `{"shortest_edge": int}`, specifying the size of the output image. If
146
+ `size["shortest_edge"]` >= 384 image is resized to `(size["shortest_edge"], size["shortest_edge"])`.
147
+ Otherwise, the smaller edge of the image will be matched to `int(size["shortest_edge"] / crop_pct)`,
148
+ after which the image is cropped to `(size["shortest_edge"], size["shortest_edge"])`.
149
+ crop_pct (`float`):
150
+ Percentage of the image to crop. Only has an effect if size < 384.
151
+ resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BICUBIC`):
152
+ Resampling filter to use when resizing the image.
153
+ data_format (`str` or `ChannelDimension`, *optional*):
154
+ The channel dimension format of the image. If not provided, it will be the same as the input image.
155
+ input_data_format (`ChannelDimension` or `str`, *optional*):
156
+ The channel dimension format of the input image. If not provided, it will be inferred from the input
157
+ image.
158
+ """
159
+ size = get_size_dict(size, default_to_square=False)
160
+ if "shortest_edge" not in size:
161
+ raise ValueError(f"Size dictionary must contain 'shortest_edge' key. Got {size.keys()}")
162
+ shortest_edge = size["shortest_edge"]
163
+
164
+ if shortest_edge < 384:
165
+ # maintain same ratio, resizing shortest edge to shortest_edge/crop_pct
166
+ resize_shortest_edge = int(shortest_edge / crop_pct)
167
+ resize_size = get_resize_output_image_size(
168
+ image, size=resize_shortest_edge, default_to_square=False, input_data_format=input_data_format
169
+ )
170
+ image = resize(
171
+ image=image,
172
+ size=resize_size,
173
+ resample=resample,
174
+ data_format=data_format,
175
+ input_data_format=input_data_format,
176
+ **kwargs,
177
+ )
178
+ # then crop to (shortest_edge, shortest_edge)
179
+ return center_crop(
180
+ image=image,
181
+ size=(shortest_edge, shortest_edge),
182
+ data_format=data_format,
183
+ input_data_format=input_data_format,
184
+ **kwargs,
185
+ )
186
+ else:
187
+ # warping (no cropping) when evaluated at 384 or larger
188
+ return resize(
189
+ image,
190
+ size=(shortest_edge, shortest_edge),
191
+ resample=resample,
192
+ data_format=data_format,
193
+ input_data_format=input_data_format,
194
+ **kwargs,
195
+ )
196
+
197
+ @filter_out_non_signature_kwargs()
198
+ def preprocess(
199
+ self,
200
+ images: ImageInput,
201
+ do_resize: bool | None = None,
202
+ size: dict[str, int] | None = None,
203
+ crop_pct: float | None = None,
204
+ resample: PILImageResampling | None = None,
205
+ do_rescale: bool | None = None,
206
+ rescale_factor: float | None = None,
207
+ do_normalize: bool | None = None,
208
+ image_mean: float | list[float] | None = None,
209
+ image_std: float | list[float] | None = None,
210
+ return_tensors: str | TensorType | None = None,
211
+ data_format: ChannelDimension = ChannelDimension.FIRST,
212
+ input_data_format: str | ChannelDimension | None = None,
213
+ ) -> PIL.Image.Image:
214
+ """
215
+ Preprocess an image or batch of images.
216
+
217
+ Args:
218
+ images (`ImageInput`):
219
+ Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
220
+ passing in images with pixel values between 0 and 1, set `do_rescale=False`.
221
+ do_resize (`bool`, *optional*, defaults to `self.do_resize`):
222
+ Whether to resize the image.
223
+ size (`dict[str, int]`, *optional*, defaults to `self.size`):
224
+ Size of the output image after `resize` has been applied. If `size["shortest_edge"]` >= 384, the image
225
+ is resized to `(size["shortest_edge"], size["shortest_edge"])`. Otherwise, the smaller edge of the
226
+ image will be matched to `int(size["shortest_edge"]/ crop_pct)`, after which the image is cropped to
227
+ `(size["shortest_edge"], size["shortest_edge"])`. Only has an effect if `do_resize` is set to `True`.
228
+ crop_pct (`float`, *optional*, defaults to `self.crop_pct`):
229
+ Percentage of the image to crop if size < 384.
230
+ resample (`int`, *optional*, defaults to `self.resample`):
231
+ Resampling filter to use if resizing the image. This can be one of `PILImageResampling`, filters. Only
232
+ has an effect if `do_resize` is set to `True`.
233
+ do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
234
+ Whether to rescale the image values between [0 - 1].
235
+ rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
236
+ Rescale factor to rescale the image by if `do_rescale` is set to `True`.
237
+ do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
238
+ Whether to normalize the image.
239
+ image_mean (`float` or `list[float]`, *optional*, defaults to `self.image_mean`):
240
+ Image mean.
241
+ image_std (`float` or `list[float]`, *optional*, defaults to `self.image_std`):
242
+ Image standard deviation.
243
+ return_tensors (`str` or `TensorType`, *optional*):
244
+ The type of tensors to return. Can be one of:
245
+ - Unset: Return a list of `np.ndarray`.
246
+ - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
247
+ - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
248
+ data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
249
+ The channel dimension format for the output image. Can be one of:
250
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
251
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
252
+ - Unset: Use the channel dimension format of the input image.
253
+ input_data_format (`ChannelDimension` or `str`, *optional*):
254
+ The channel dimension format for the input image. If unset, the channel dimension format is inferred
255
+ from the input image. Can be one of:
256
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
257
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
258
+ - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
259
+ """
260
+ do_resize = do_resize if do_resize is not None else self.do_resize
261
+ crop_pct = crop_pct if crop_pct is not None else self.crop_pct
262
+ resample = resample if resample is not None else self.resample
263
+ do_rescale = do_rescale if do_rescale is not None else self.do_rescale
264
+ rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
265
+ do_normalize = do_normalize if do_normalize is not None else self.do_normalize
266
+ image_mean = image_mean if image_mean is not None else self.image_mean
267
+ image_std = image_std if image_std is not None else self.image_std
268
+
269
+ size = size if size is not None else self.size
270
+ size = get_size_dict(size, default_to_square=False)
271
+
272
+ images = make_flat_list_of_images(images)
273
+
274
+ if not valid_images(images):
275
+ raise ValueError("Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, or torch.Tensor")
276
+
277
+ validate_preprocess_arguments(
278
+ do_rescale=do_rescale,
279
+ rescale_factor=rescale_factor,
280
+ do_normalize=do_normalize,
281
+ image_mean=image_mean,
282
+ image_std=image_std,
283
+ do_resize=do_resize,
284
+ size=size,
285
+ resample=resample,
286
+ )
287
+
288
+ # All transformations expect numpy arrays.
289
+ images = [to_numpy_array(image) for image in images]
290
+
291
+ if do_rescale and is_scaled_image(images[0]):
292
+ logger.warning_once(
293
+ "It looks like you are trying to rescale already rescaled images. If the input"
294
+ " images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again."
295
+ )
296
+
297
+ if input_data_format is None:
298
+ # We assume that all images have the same channel dimension format.
299
+ input_data_format = infer_channel_dimension_format(images[0])
300
+
301
+ if do_resize:
302
+ images = [
303
+ self.resize(
304
+ image=image, size=size, crop_pct=crop_pct, resample=resample, input_data_format=input_data_format
305
+ )
306
+ for image in images
307
+ ]
308
+
309
+ if do_rescale:
310
+ images = [
311
+ self.rescale(image=image, scale=rescale_factor, input_data_format=input_data_format)
312
+ for image in images
313
+ ]
314
+
315
+ if do_normalize:
316
+ images = [
317
+ self.normalize(image=image, mean=image_mean, std=image_std, input_data_format=input_data_format)
318
+ for image in images
319
+ ]
320
+
321
+ images = [
322
+ to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format) for image in images
323
+ ]
324
+
325
+ data = {"pixel_values": images}
326
+ return BatchFeature(data=data, tensor_type=return_tensors)
327
+
328
+
329
+ __all__ = ["ConvNextImageProcessor"]
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/convnext/image_processing_convnext_fast.py ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """Fast Image processor class for ConvNeXT."""
15
+
16
+ from typing import Optional
17
+
18
+ import torch
19
+ import torchvision.transforms.v2.functional as tvF
20
+
21
+ from ...image_processing_utils import BatchFeature
22
+ from ...image_processing_utils_fast import BaseImageProcessorFast, group_images_by_shape, reorder_images
23
+ from ...image_transforms import get_resize_output_image_size
24
+ from ...image_utils import (
25
+ IMAGENET_STANDARD_MEAN,
26
+ IMAGENET_STANDARD_STD,
27
+ ChannelDimension,
28
+ ImageInput,
29
+ PILImageResampling,
30
+ SizeDict,
31
+ )
32
+ from ...processing_utils import Unpack
33
+ from ...utils import (
34
+ TensorType,
35
+ auto_docstring,
36
+ )
37
+ from .image_processing_convnext import ConvNextImageProcessorKwargs
38
+
39
+
40
+ @auto_docstring
41
+ class ConvNextImageProcessorFast(BaseImageProcessorFast):
42
+ resample = PILImageResampling.BICUBIC
43
+ image_mean = IMAGENET_STANDARD_MEAN
44
+ image_std = IMAGENET_STANDARD_STD
45
+ size = {"shortest_edge": 384}
46
+ default_to_square = False
47
+ do_resize = True
48
+ do_rescale = True
49
+ do_normalize = True
50
+ crop_pct = 224 / 256
51
+ valid_kwargs = ConvNextImageProcessorKwargs
52
+
53
+ def __init__(self, **kwargs: Unpack[ConvNextImageProcessorKwargs]):
54
+ super().__init__(**kwargs)
55
+
56
+ @auto_docstring
57
+ def preprocess(self, images: ImageInput, **kwargs: Unpack[ConvNextImageProcessorKwargs]) -> BatchFeature:
58
+ return super().preprocess(images, **kwargs)
59
+
60
+ def resize(
61
+ self,
62
+ image: "torch.Tensor",
63
+ size: dict[str, int],
64
+ crop_pct: float,
65
+ interpolation: PILImageResampling = PILImageResampling.BICUBIC,
66
+ **kwargs,
67
+ ) -> "torch.Tensor":
68
+ """
69
+ Resize an image.
70
+
71
+ Args:
72
+ image (`torch.Tensor`):
73
+ Image to resize.
74
+ size (`dict[str, int]`):
75
+ Dictionary of the form `{"shortest_edge": int}`, specifying the size of the output image. If
76
+ `size["shortest_edge"]` >= 384 image is resized to `(size["shortest_edge"], size["shortest_edge"])`.
77
+ Otherwise, the smaller edge of the image will be matched to `int(size["shortest_edge"] / crop_pct)`,
78
+ after which the image is cropped to `(size["shortest_edge"], size["shortest_edge"])`.
79
+ crop_pct (`float`):
80
+ Percentage of the image to crop. Only has an effect if size < 384.
81
+ resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BICUBIC`):
82
+ Resampling filter to use when resizing the image.
83
+
84
+ Returns:
85
+ `torch.Tensor`: Resized image.
86
+ """
87
+ if not size.shortest_edge:
88
+ raise ValueError(f"Size dictionary must contain 'shortest_edge' key. Got {size.keys()}")
89
+ shortest_edge = size["shortest_edge"]
90
+
91
+ if shortest_edge < 384:
92
+ # maintain same ratio, resizing shortest edge to shortest_edge/crop_pct
93
+ resize_shortest_edge = int(shortest_edge / crop_pct)
94
+ resize_size = get_resize_output_image_size(
95
+ image, size=resize_shortest_edge, default_to_square=False, input_data_format=ChannelDimension.FIRST
96
+ )
97
+ image = super().resize(
98
+ image,
99
+ SizeDict(height=resize_size[0], width=resize_size[1]),
100
+ interpolation=interpolation,
101
+ **kwargs,
102
+ )
103
+ # then crop to (shortest_edge, shortest_edge)
104
+ return self.center_crop(
105
+ image,
106
+ SizeDict(height=shortest_edge, width=shortest_edge),
107
+ **kwargs,
108
+ )
109
+ else:
110
+ # warping (no cropping) when evaluated at 384 or larger
111
+ return super().resize(
112
+ image,
113
+ SizeDict(height=shortest_edge, width=shortest_edge),
114
+ interpolation=interpolation,
115
+ **kwargs,
116
+ )
117
+
118
+ def _preprocess(
119
+ self,
120
+ images: list["torch.Tensor"],
121
+ do_resize: bool,
122
+ size: dict[str, int],
123
+ crop_pct: float,
124
+ interpolation: Optional["tvF.InterpolationMode"],
125
+ do_center_crop: bool,
126
+ crop_size: int,
127
+ do_rescale: bool,
128
+ rescale_factor: float,
129
+ do_normalize: bool,
130
+ image_mean: float | list[float] | None,
131
+ image_std: float | list[float] | None,
132
+ disable_grouping: bool | None,
133
+ return_tensors: str | TensorType | None,
134
+ **kwargs,
135
+ ) -> BatchFeature:
136
+ # Group images by size for batched resizing
137
+ grouped_images, grouped_images_index = group_images_by_shape(images, disable_grouping=disable_grouping)
138
+ resized_images_grouped = {}
139
+ for shape, stacked_images in grouped_images.items():
140
+ if do_resize:
141
+ stacked_images = self.resize(
142
+ image=stacked_images, size=size, crop_pct=crop_pct, interpolation=interpolation
143
+ )
144
+ resized_images_grouped[shape] = stacked_images
145
+ resized_images = reorder_images(resized_images_grouped, grouped_images_index)
146
+
147
+ # Group images by size for further processing
148
+ # Needed in case do_resize is False, or resize returns images with different sizes
149
+ grouped_images, grouped_images_index = group_images_by_shape(resized_images, disable_grouping=disable_grouping)
150
+ processed_images_grouped = {}
151
+ for shape, stacked_images in grouped_images.items():
152
+ if do_center_crop:
153
+ stacked_images = self.center_crop(stacked_images, crop_size)
154
+ # Fused rescale and normalize
155
+ stacked_images = self.rescale_and_normalize(
156
+ stacked_images, do_rescale, rescale_factor, do_normalize, image_mean, image_std
157
+ )
158
+ processed_images_grouped[shape] = stacked_images
159
+
160
+ processed_images = reorder_images(processed_images_grouped, grouped_images_index)
161
+
162
+ return BatchFeature(data={"pixel_values": processed_images}, tensor_type=return_tensors)
163
+
164
+
165
+ __all__ = ["ConvNextImageProcessorFast"]
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/convnext/modeling_convnext.py ADDED
@@ -0,0 +1,410 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 Meta Platforms, Inc. and 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
+ """PyTorch ConvNext model."""
15
+
16
+ import torch
17
+ from torch import nn
18
+
19
+ from ... import initialization as init
20
+ from ...activations import ACT2FN
21
+ from ...backbone_utils import BackboneMixin
22
+ from ...modeling_outputs import (
23
+ BackboneOutput,
24
+ BaseModelOutputWithNoAttention,
25
+ BaseModelOutputWithPoolingAndNoAttention,
26
+ ImageClassifierOutputWithNoAttention,
27
+ )
28
+ from ...modeling_utils import PreTrainedModel
29
+ from ...utils import auto_docstring, logging
30
+ from ...utils.generic import can_return_tuple
31
+ from .configuration_convnext import ConvNextConfig
32
+
33
+
34
+ logger = logging.get_logger(__name__)
35
+
36
+
37
+ # Copied from transformers.models.beit.modeling_beit.drop_path
38
+ def drop_path(input: torch.Tensor, drop_prob: float = 0.0, training: bool = False) -> torch.Tensor:
39
+ """
40
+ Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
41
+
42
+ """
43
+ if drop_prob == 0.0 or not training:
44
+ return input
45
+ keep_prob = 1 - drop_prob
46
+ shape = (input.shape[0],) + (1,) * (input.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
47
+ random_tensor = keep_prob + torch.rand(shape, dtype=input.dtype, device=input.device)
48
+ random_tensor.floor_() # binarize
49
+ output = input.div(keep_prob) * random_tensor
50
+ return output
51
+
52
+
53
+ # Copied from transformers.models.beit.modeling_beit.BeitDropPath with Beit->ConvNext
54
+ class ConvNextDropPath(nn.Module):
55
+ """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
56
+
57
+ def __init__(self, drop_prob: float | None = None) -> None:
58
+ super().__init__()
59
+ self.drop_prob = drop_prob
60
+
61
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
62
+ return drop_path(hidden_states, self.drop_prob, self.training)
63
+
64
+ def extra_repr(self) -> str:
65
+ return f"p={self.drop_prob}"
66
+
67
+
68
+ class ConvNextLayerNorm(nn.LayerNorm):
69
+ r"""LayerNorm that supports two data formats: channels_last (default) or channels_first.
70
+ The ordering of the dimensions in the inputs. channels_last corresponds to inputs with shape (batch_size, height,
71
+ width, channels) while channels_first corresponds to inputs with shape (batch_size, channels, height, width).
72
+ """
73
+
74
+ def __init__(self, normalized_shape, *, eps=1e-6, data_format="channels_last", **kwargs):
75
+ super().__init__(normalized_shape, eps=eps, **kwargs)
76
+ if data_format not in ["channels_last", "channels_first"]:
77
+ raise NotImplementedError(f"Unsupported data format: {data_format}")
78
+ self.data_format = data_format
79
+
80
+ def forward(self, features: torch.Tensor) -> torch.Tensor:
81
+ """
82
+ Args:
83
+ features: Tensor of shape (batch_size, channels, height, width) OR (batch_size, height, width, channels)
84
+ """
85
+ if self.data_format == "channels_first":
86
+ features = features.permute(0, 2, 3, 1)
87
+ features = super().forward(features)
88
+ features = features.permute(0, 3, 1, 2)
89
+ else:
90
+ features = super().forward(features)
91
+ return features
92
+
93
+
94
+ class ConvNextEmbeddings(nn.Module):
95
+ """This class is comparable to (and inspired by) the SwinEmbeddings class
96
+ found in src/transformers/models/swin/modeling_swin.py.
97
+ """
98
+
99
+ def __init__(self, config):
100
+ super().__init__()
101
+ self.patch_embeddings = nn.Conv2d(
102
+ config.num_channels, config.hidden_sizes[0], kernel_size=config.patch_size, stride=config.patch_size
103
+ )
104
+ self.layernorm = ConvNextLayerNorm(config.hidden_sizes[0], eps=1e-6, data_format="channels_first")
105
+ self.num_channels = config.num_channels
106
+
107
+ def forward(self, pixel_values: torch.FloatTensor) -> torch.Tensor:
108
+ num_channels = pixel_values.shape[1]
109
+ if num_channels != self.num_channels:
110
+ raise ValueError(
111
+ "Make sure that the channel dimension of the pixel values match with the one set in the configuration."
112
+ )
113
+ embeddings = self.patch_embeddings(pixel_values)
114
+ embeddings = self.layernorm(embeddings)
115
+ return embeddings
116
+
117
+
118
+ class ConvNextLayer(nn.Module):
119
+ """This corresponds to the `Block` class in the original implementation.
120
+
121
+ There are two equivalent implementations: [DwConv, LayerNorm (channels_first), Conv, GELU,1x1 Conv]; all in (N, C,
122
+ H, W) (2) [DwConv, Permute to (N, H, W, C), LayerNorm (channels_last), Linear, GELU, Linear]; Permute back
123
+
124
+ The authors used (2) as they find it slightly faster in PyTorch.
125
+
126
+ Args:
127
+ config ([`ConvNextConfig`]): Model configuration class.
128
+ dim (`int`): Number of input channels.
129
+ drop_path (`float`): Stochastic depth rate. Default: 0.0.
130
+ """
131
+
132
+ def __init__(self, config, dim, drop_path=0):
133
+ super().__init__()
134
+ self.dwconv = nn.Conv2d(dim, dim, kernel_size=7, padding=3, groups=dim) # depthwise conv
135
+ self.layernorm = ConvNextLayerNorm(dim, eps=1e-6)
136
+ self.pwconv1 = nn.Linear(dim, 4 * dim) # pointwise/1x1 convs, implemented with linear layers
137
+ self.act = ACT2FN[config.hidden_act]
138
+ self.pwconv2 = nn.Linear(4 * dim, dim)
139
+ self.layer_scale_parameter = (
140
+ nn.Parameter(config.layer_scale_init_value * torch.ones(dim), requires_grad=True)
141
+ if config.layer_scale_init_value > 0
142
+ else None
143
+ )
144
+ self.drop_path = ConvNextDropPath(drop_path) if drop_path > 0.0 else nn.Identity()
145
+
146
+ def forward(self, features: torch.Tensor) -> torch.Tensor:
147
+ residual = features
148
+ features = self.dwconv(features)
149
+ features = features.permute(0, 2, 3, 1) # (N, C, H, W) -> (N, H, W, C)
150
+ features = self.layernorm(features)
151
+ features = self.pwconv1(features)
152
+ features = self.act(features)
153
+ features = self.pwconv2(features)
154
+ if self.layer_scale_parameter is not None:
155
+ features = self.layer_scale_parameter * features
156
+ features = features.permute(0, 3, 1, 2) # (N, H, W, C) -> (N, C, H, W)
157
+ features = residual + self.drop_path(features)
158
+ return features
159
+
160
+
161
+ class ConvNextStage(nn.Module):
162
+ """ConvNeXT stage, consisting of an optional downsampling layer + multiple residual blocks.
163
+
164
+ Args:
165
+ config ([`ConvNextConfig`]): Model configuration class.
166
+ in_channels (`int`): Number of input channels.
167
+ out_channels (`int`): Number of output channels.
168
+ depth (`int`): Number of residual blocks.
169
+ drop_path_rates(`list[float]`): Stochastic depth rates for each layer.
170
+ """
171
+
172
+ def __init__(self, config, in_channels, out_channels, kernel_size=2, stride=2, depth=2, drop_path_rates=None):
173
+ super().__init__()
174
+
175
+ if in_channels != out_channels or stride > 1:
176
+ self.downsampling_layer = nn.ModuleList(
177
+ [
178
+ ConvNextLayerNorm(in_channels, eps=1e-6, data_format="channels_first"),
179
+ nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size, stride=stride),
180
+ ]
181
+ )
182
+ else:
183
+ self.downsampling_layer = nn.ModuleList()
184
+ drop_path_rates = drop_path_rates or [0.0] * depth
185
+ self.layers = nn.ModuleList(
186
+ [ConvNextLayer(config, dim=out_channels, drop_path=drop_path_rates[j]) for j in range(depth)]
187
+ )
188
+
189
+ def forward(self, features: torch.Tensor) -> torch.Tensor:
190
+ for layer in self.downsampling_layer:
191
+ features = layer(features)
192
+ for layer in self.layers:
193
+ features = layer(features)
194
+ return features
195
+
196
+
197
+ class ConvNextEncoder(nn.Module):
198
+ def __init__(self, config):
199
+ super().__init__()
200
+ self.stages = nn.ModuleList()
201
+ drop_path_rates = [
202
+ x.tolist()
203
+ for x in torch.linspace(0, config.drop_path_rate, sum(config.depths), device="cpu").split(config.depths)
204
+ ]
205
+ prev_chs = config.hidden_sizes[0]
206
+ for i in range(config.num_stages):
207
+ out_chs = config.hidden_sizes[i]
208
+ stage = ConvNextStage(
209
+ config,
210
+ in_channels=prev_chs,
211
+ out_channels=out_chs,
212
+ stride=2 if i > 0 else 1,
213
+ depth=config.depths[i],
214
+ drop_path_rates=drop_path_rates[i],
215
+ )
216
+ self.stages.append(stage)
217
+ prev_chs = out_chs
218
+
219
+ def forward(
220
+ self, hidden_states: torch.Tensor, output_hidden_states: bool | None = False
221
+ ) -> BaseModelOutputWithNoAttention:
222
+ all_hidden_states = [hidden_states] if output_hidden_states else None
223
+
224
+ for layer_module in self.stages:
225
+ hidden_states = layer_module(hidden_states)
226
+ if all_hidden_states is not None:
227
+ all_hidden_states.append(hidden_states)
228
+
229
+ return BaseModelOutputWithNoAttention(last_hidden_state=hidden_states, hidden_states=all_hidden_states)
230
+
231
+
232
+ @auto_docstring
233
+ class ConvNextPreTrainedModel(PreTrainedModel):
234
+ config: ConvNextConfig
235
+ base_model_prefix = "convnext"
236
+ main_input_name = "pixel_values"
237
+ input_modalities = ("image",)
238
+ _no_split_modules = ["ConvNextLayer"]
239
+ _can_record_outputs = {} # hidden states are collected explicitly
240
+
241
+ @torch.no_grad()
242
+ def _init_weights(self, module):
243
+ """Initialize the weights"""
244
+ super()._init_weights(module)
245
+ if isinstance(module, ConvNextLayer):
246
+ if module.layer_scale_parameter is not None:
247
+ init.constant_(module.layer_scale_parameter, self.config.layer_scale_init_value)
248
+
249
+
250
+ @auto_docstring
251
+ class ConvNextModel(ConvNextPreTrainedModel):
252
+ def __init__(self, config):
253
+ super().__init__(config)
254
+ self.config = config
255
+
256
+ self.embeddings = ConvNextEmbeddings(config)
257
+ self.encoder = ConvNextEncoder(config)
258
+
259
+ # final layernorm layer
260
+ self.layernorm = nn.LayerNorm(config.hidden_sizes[-1], eps=config.layer_norm_eps)
261
+
262
+ # Initialize weights and apply final processing
263
+ self.post_init()
264
+
265
+ @can_return_tuple
266
+ @auto_docstring
267
+ def forward(
268
+ self, pixel_values: torch.FloatTensor | None = None, output_hidden_states: bool | None = None, **kwargs
269
+ ) -> BaseModelOutputWithPoolingAndNoAttention:
270
+ if output_hidden_states is None:
271
+ output_hidden_states = self.config.output_hidden_states
272
+
273
+ if pixel_values is None:
274
+ raise ValueError("You have to specify pixel_values")
275
+
276
+ embedding_output = self.embeddings(pixel_values)
277
+ encoder_outputs: BaseModelOutputWithNoAttention = self.encoder(
278
+ embedding_output, output_hidden_states=output_hidden_states
279
+ )
280
+ last_hidden_state = encoder_outputs.last_hidden_state
281
+
282
+ # global average pooling, (N, C, H, W) -> (N, C)
283
+ pooled_output = self.layernorm(last_hidden_state.mean([-2, -1]))
284
+
285
+ return BaseModelOutputWithPoolingAndNoAttention(
286
+ last_hidden_state=last_hidden_state,
287
+ pooler_output=pooled_output,
288
+ hidden_states=encoder_outputs.hidden_states,
289
+ )
290
+
291
+
292
+ @auto_docstring(
293
+ custom_intro="""
294
+ ConvNext Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for
295
+ ImageNet.
296
+ """
297
+ )
298
+ class ConvNextForImageClassification(ConvNextPreTrainedModel):
299
+ accepts_loss_kwargs = False
300
+
301
+ def __init__(self, config):
302
+ super().__init__(config)
303
+
304
+ self.num_labels = config.num_labels
305
+ self.convnext = ConvNextModel(config)
306
+
307
+ # Classifier head
308
+ if config.num_labels > 0:
309
+ self.classifier = nn.Linear(config.hidden_sizes[-1], config.num_labels)
310
+ else:
311
+ self.classifier = nn.Identity()
312
+
313
+ # Initialize weights and apply final processing
314
+ self.post_init()
315
+
316
+ @can_return_tuple
317
+ @auto_docstring
318
+ def forward(
319
+ self, pixel_values: torch.FloatTensor | None = None, labels: torch.LongTensor | None = None, **kwargs
320
+ ) -> ImageClassifierOutputWithNoAttention:
321
+ r"""
322
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
323
+ Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
324
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
325
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
326
+ """
327
+ outputs: BaseModelOutputWithPoolingAndNoAttention = self.convnext(pixel_values, **kwargs)
328
+ pooled_output = outputs.pooler_output
329
+ logits = self.classifier(pooled_output)
330
+
331
+ loss = None
332
+ if labels is not None:
333
+ loss = self.loss_function(labels=labels, pooled_logits=logits, config=self.config)
334
+
335
+ return ImageClassifierOutputWithNoAttention(
336
+ loss=loss,
337
+ logits=logits,
338
+ hidden_states=outputs.hidden_states,
339
+ )
340
+
341
+
342
+ @auto_docstring(
343
+ custom_intro="""
344
+ ConvNeXt backbone, to be used with frameworks like DETR and MaskFormer.
345
+ """
346
+ )
347
+ class ConvNextBackbone(BackboneMixin, ConvNextPreTrainedModel):
348
+ has_attentions = False
349
+
350
+ def __init__(self, config):
351
+ super().__init__(config)
352
+
353
+ self.embeddings = ConvNextEmbeddings(config)
354
+ self.encoder = ConvNextEncoder(config)
355
+ self.num_features = [config.hidden_sizes[0]] + config.hidden_sizes
356
+
357
+ # Add layer norms to hidden states of out_features
358
+ hidden_states_norms = {}
359
+ for stage, num_channels in zip(self.out_features, self.channels):
360
+ hidden_states_norms[stage] = ConvNextLayerNorm(num_channels, data_format="channels_first")
361
+ self.hidden_states_norms = nn.ModuleDict(hidden_states_norms)
362
+
363
+ # initialize weights and apply final processing
364
+ self.post_init()
365
+
366
+ @can_return_tuple
367
+ @auto_docstring
368
+ def forward(
369
+ self, pixel_values: torch.Tensor, output_hidden_states: bool | None = None, **kwargs
370
+ ) -> BackboneOutput:
371
+ r"""
372
+ Examples:
373
+
374
+ ```python
375
+ >>> from transformers import AutoImageProcessor, AutoBackbone
376
+ >>> import torch
377
+ >>> from PIL import Image
378
+ >>> import httpx
379
+ >>> from io import BytesIO
380
+
381
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
382
+ >>> with httpx.stream("GET", url) as response:
383
+ ... image = Image.open(BytesIO(response.read()))
384
+
385
+ >>> processor = AutoImageProcessor.from_pretrained("facebook/convnext-tiny-224")
386
+ >>> model = AutoBackbone.from_pretrained("facebook/convnext-tiny-224")
387
+
388
+ >>> inputs = processor(image, return_tensors="pt")
389
+ >>> outputs = model(**inputs)
390
+ ```"""
391
+ if output_hidden_states is None:
392
+ output_hidden_states = self.config.output_hidden_states
393
+
394
+ embedding_output = self.embeddings(pixel_values)
395
+ outputs: BaseModelOutputWithPoolingAndNoAttention = self.encoder(embedding_output, output_hidden_states=True)
396
+ hidden_states = outputs.hidden_states
397
+
398
+ feature_maps = []
399
+ for stage, hidden_state in zip(self.stage_names, hidden_states):
400
+ if stage in self.out_features:
401
+ hidden_state = self.hidden_states_norms[stage](hidden_state)
402
+ feature_maps.append(hidden_state)
403
+
404
+ return BackboneOutput(
405
+ feature_maps=tuple(feature_maps),
406
+ hidden_states=hidden_states if output_hidden_states else None,
407
+ )
408
+
409
+
410
+ __all__ = ["ConvNextForImageClassification", "ConvNextModel", "ConvNextPreTrainedModel", "ConvNextBackbone"]
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/convnextv2/__init__.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_convnextv2 import *
22
+ from .modeling_convnextv2 import *
23
+ else:
24
+ import sys
25
+
26
+ _file = globals()["__file__"]
27
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/convnextv2/configuration_convnextv2.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 Meta Platforms, Inc. and 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
+ """ConvNeXTV2 model configuration"""
15
+
16
+ from ...backbone_utils import BackboneConfigMixin
17
+ from ...configuration_utils import PreTrainedConfig
18
+ from ...utils import logging
19
+
20
+
21
+ logger = logging.get_logger(__name__)
22
+
23
+
24
+ class ConvNextV2Config(BackboneConfigMixin, PreTrainedConfig):
25
+ r"""
26
+ This is the configuration class to store the configuration of a [`ConvNextV2Model`]. It is used to instantiate an
27
+ ConvNeXTV2 model according to the specified arguments, defining the model architecture. Instantiating a
28
+ configuration with the defaults will yield a similar configuration to that of the ConvNeXTV2
29
+ [facebook/convnextv2-tiny-1k-224](https://huggingface.co/facebook/convnextv2-tiny-1k-224) architecture.
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
+ num_channels (`int`, *optional*, defaults to 3):
36
+ The number of input channels.
37
+ patch_size (`int`, *optional*, defaults to 4):
38
+ Patch size to use in the patch embedding layer.
39
+ num_stages (`int`, *optional*, defaults to 4):
40
+ The number of stages in the model.
41
+ hidden_sizes (`list[int]`, *optional*, defaults to `[96, 192, 384, 768]`):
42
+ Dimensionality (hidden size) at each stage.
43
+ depths (`list[int]`, *optional*, defaults to `[3, 3, 9, 3]`):
44
+ Depth (number of blocks) for each stage.
45
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
46
+ The non-linear activation function (function or string) in each block. If string, `"gelu"`, `"relu"`,
47
+ `"selu"` and `"gelu_new"` are supported.
48
+ initializer_range (`float`, *optional*, defaults to 0.02):
49
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
50
+ layer_norm_eps (`float`, *optional*, defaults to 1e-12):
51
+ The epsilon used by the layer normalization layers.
52
+ drop_path_rate (`float`, *optional*, defaults to 0.0):
53
+ The drop rate for stochastic depth.
54
+ image_size (`int`, *optional*, defaults to 224):
55
+ The size (resolution) of each image.
56
+ out_features (`list[str]`, *optional*):
57
+ If used as backbone, list of features to output. Can be any of `"stem"`, `"stage1"`, `"stage2"`, etc.
58
+ (depending on how many stages the model has). If unset and `out_indices` is set, will default to the
59
+ corresponding stages. If unset and `out_indices` is unset, will default to the last stage. Must be in the
60
+ same order as defined in the `stage_names` attribute.
61
+ out_indices (`list[int]`, *optional*):
62
+ If used as backbone, list of indices of features to output. Can be any of 0, 1, 2, etc. (depending on how
63
+ many stages the model has). If unset and `out_features` is set, will default to the corresponding stages.
64
+ If unset and `out_features` is unset, will default to the last stage. Must be in the
65
+ same order as defined in the `stage_names` attribute.
66
+
67
+ Example:
68
+ ```python
69
+ >>> from transformers import ConvNeXTV2Config, ConvNextV2Model
70
+
71
+ >>> # Initializing a ConvNeXTV2 convnextv2-tiny-1k-224 style configuration
72
+ >>> configuration = ConvNeXTV2Config()
73
+
74
+ >>> # Initializing a model (with random weights) from the convnextv2-tiny-1k-224 style configuration
75
+ >>> model = ConvNextV2Model(configuration)
76
+
77
+ >>> # Accessing the model configuration
78
+ >>> configuration = model.config
79
+ ```"""
80
+
81
+ model_type = "convnextv2"
82
+
83
+ def __init__(
84
+ self,
85
+ num_channels=3,
86
+ patch_size=4,
87
+ num_stages=4,
88
+ hidden_sizes=None,
89
+ depths=None,
90
+ hidden_act="gelu",
91
+ initializer_range=0.02,
92
+ layer_norm_eps=1e-12,
93
+ drop_path_rate=0.0,
94
+ image_size=224,
95
+ out_features=None,
96
+ out_indices=None,
97
+ **kwargs,
98
+ ):
99
+ super().__init__(**kwargs)
100
+
101
+ self.num_channels = num_channels
102
+ self.patch_size = patch_size
103
+ self.num_stages = num_stages
104
+ self.hidden_sizes = [96, 192, 384, 768] if hidden_sizes is None else hidden_sizes
105
+ self.depths = [3, 3, 9, 3] if depths is None else depths
106
+ self.hidden_act = hidden_act
107
+ self.initializer_range = initializer_range
108
+ self.layer_norm_eps = layer_norm_eps
109
+ self.drop_path_rate = drop_path_rate
110
+ self.image_size = image_size
111
+ self.stage_names = ["stem"] + [f"stage{idx}" for idx in range(1, len(self.depths) + 1)]
112
+ self.set_output_features_output_indices(out_indices=out_indices, out_features=out_features)
113
+
114
+
115
+ __all__ = ["ConvNextV2Config"]
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/convnextv2/modeling_convnextv2.py ADDED
@@ -0,0 +1,433 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 Meta Platforms, Inc. and 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
+ """PyTorch ConvNextV2 model."""
15
+
16
+ import torch
17
+ from torch import nn
18
+
19
+ from ... import initialization as init
20
+ from ...activations import ACT2FN
21
+ from ...backbone_utils import BackboneMixin
22
+ from ...modeling_outputs import (
23
+ BackboneOutput,
24
+ BaseModelOutputWithNoAttention,
25
+ BaseModelOutputWithPoolingAndNoAttention,
26
+ ImageClassifierOutputWithNoAttention,
27
+ )
28
+ from ...modeling_utils import PreTrainedModel
29
+ from ...utils import auto_docstring, logging
30
+ from ...utils.generic import can_return_tuple
31
+ from .configuration_convnextv2 import ConvNextV2Config
32
+
33
+
34
+ logger = logging.get_logger(__name__)
35
+
36
+
37
+ # Copied from transformers.models.beit.modeling_beit.drop_path
38
+ def drop_path(input: torch.Tensor, drop_prob: float = 0.0, training: bool = False) -> torch.Tensor:
39
+ """
40
+ Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
41
+
42
+ """
43
+ if drop_prob == 0.0 or not training:
44
+ return input
45
+ keep_prob = 1 - drop_prob
46
+ shape = (input.shape[0],) + (1,) * (input.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
47
+ random_tensor = keep_prob + torch.rand(shape, dtype=input.dtype, device=input.device)
48
+ random_tensor.floor_() # binarize
49
+ output = input.div(keep_prob) * random_tensor
50
+ return output
51
+
52
+
53
+ # Copied from transformers.models.beit.modeling_beit.BeitDropPath with Beit->ConvNextV2
54
+ class ConvNextV2DropPath(nn.Module):
55
+ """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
56
+
57
+ def __init__(self, drop_prob: float | None = None) -> None:
58
+ super().__init__()
59
+ self.drop_prob = drop_prob
60
+
61
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
62
+ return drop_path(hidden_states, self.drop_prob, self.training)
63
+
64
+ def extra_repr(self) -> str:
65
+ return f"p={self.drop_prob}"
66
+
67
+
68
+ class ConvNextV2GRN(nn.Module):
69
+ """GRN (Global Response Normalization) layer"""
70
+
71
+ def __init__(self, dim: int):
72
+ super().__init__()
73
+ self.weight = nn.Parameter(torch.zeros(1, 1, 1, dim))
74
+ self.bias = nn.Parameter(torch.zeros(1, 1, 1, dim))
75
+
76
+ def forward(self, hidden_states: torch.FloatTensor) -> torch.FloatTensor:
77
+ # Compute and normalize global spatial feature maps
78
+ global_features = torch.linalg.vector_norm(hidden_states, ord=2, dim=(1, 2), keepdim=True)
79
+ norm_features = global_features / (global_features.mean(dim=-1, keepdim=True) + 1e-6)
80
+ hidden_states = self.weight * (hidden_states * norm_features) + self.bias + hidden_states
81
+
82
+ return hidden_states
83
+
84
+
85
+ # Copied from transformers.models.convnext.modeling_convnext.ConvNextLayerNorm with ConvNext->ConvNextV2
86
+ class ConvNextV2LayerNorm(nn.LayerNorm):
87
+ r"""LayerNorm that supports two data formats: channels_last (default) or channels_first.
88
+ The ordering of the dimensions in the inputs. channels_last corresponds to inputs with shape (batch_size, height,
89
+ width, channels) while channels_first corresponds to inputs with shape (batch_size, channels, height, width).
90
+ """
91
+
92
+ def __init__(self, normalized_shape, *, eps=1e-6, data_format="channels_last", **kwargs):
93
+ super().__init__(normalized_shape, eps=eps, **kwargs)
94
+ if data_format not in ["channels_last", "channels_first"]:
95
+ raise NotImplementedError(f"Unsupported data format: {data_format}")
96
+ self.data_format = data_format
97
+
98
+ def forward(self, features: torch.Tensor) -> torch.Tensor:
99
+ """
100
+ Args:
101
+ features: Tensor of shape (batch_size, channels, height, width) OR (batch_size, height, width, channels)
102
+ """
103
+ if self.data_format == "channels_first":
104
+ features = features.permute(0, 2, 3, 1)
105
+ features = super().forward(features)
106
+ features = features.permute(0, 3, 1, 2)
107
+ else:
108
+ features = super().forward(features)
109
+ return features
110
+
111
+
112
+ # Copied from transformers.models.convnext.modeling_convnext.ConvNextEmbeddings with ConvNext->ConvNextV2
113
+ class ConvNextV2Embeddings(nn.Module):
114
+ """This class is comparable to (and inspired by) the SwinEmbeddings class
115
+ found in src/transformers/models/swin/modeling_swin.py.
116
+ """
117
+
118
+ def __init__(self, config):
119
+ super().__init__()
120
+ self.patch_embeddings = nn.Conv2d(
121
+ config.num_channels, config.hidden_sizes[0], kernel_size=config.patch_size, stride=config.patch_size
122
+ )
123
+ self.layernorm = ConvNextV2LayerNorm(config.hidden_sizes[0], eps=1e-6, data_format="channels_first")
124
+ self.num_channels = config.num_channels
125
+
126
+ def forward(self, pixel_values: torch.FloatTensor) -> torch.Tensor:
127
+ num_channels = pixel_values.shape[1]
128
+ if num_channels != self.num_channels:
129
+ raise ValueError(
130
+ "Make sure that the channel dimension of the pixel values match with the one set in the configuration."
131
+ )
132
+ embeddings = self.patch_embeddings(pixel_values)
133
+ embeddings = self.layernorm(embeddings)
134
+ return embeddings
135
+
136
+
137
+ class ConvNextV2Layer(nn.Module):
138
+ """This corresponds to the `Block` class in the original implementation.
139
+
140
+ There are two equivalent implementations: [DwConv, LayerNorm (channels_first), Conv, GELU,1x1 Conv]; all in (N, C,
141
+ H, W) (2) [DwConv, Permute to (N, H, W, C), LayerNorm (channels_last), Linear, GELU, Linear]; Permute back
142
+
143
+ The authors used (2) as they find it slightly faster in PyTorch.
144
+
145
+ Args:
146
+ config ([`ConvNextV2Config`]): Model configuration class.
147
+ dim (`int`): Number of input channels.
148
+ drop_path (`float`): Stochastic depth rate. Default: 0.0.
149
+ """
150
+
151
+ def __init__(self, config, dim, drop_path=0):
152
+ super().__init__()
153
+ # depthwise conv
154
+ self.dwconv = nn.Conv2d(dim, dim, kernel_size=7, padding=3, groups=dim)
155
+ self.layernorm = ConvNextV2LayerNorm(dim, eps=1e-6)
156
+ # pointwise/1x1 convs, implemented with linear layers
157
+ self.pwconv1 = nn.Linear(dim, 4 * dim)
158
+ self.act = ACT2FN[config.hidden_act]
159
+ self.grn = ConvNextV2GRN(4 * dim)
160
+ self.pwconv2 = nn.Linear(4 * dim, dim)
161
+ self.drop_path = ConvNextV2DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
162
+
163
+ def forward(self, features: torch.Tensor) -> torch.Tensor:
164
+ residual = features
165
+ features = self.dwconv(features)
166
+ # (batch_size, num_channels, height, width) -> (batch_size, height, width, num_channels)
167
+ features = features.permute(0, 2, 3, 1)
168
+ features = self.layernorm(features)
169
+ features = self.pwconv1(features)
170
+ features = self.act(features)
171
+ features = self.grn(features)
172
+ features = self.pwconv2(features)
173
+ # (batch_size, height, width, num_channels) -> (batch_size, num_channels, height, width)
174
+ features = features.permute(0, 3, 1, 2)
175
+
176
+ features = residual + self.drop_path(features)
177
+ return features
178
+
179
+
180
+ # Copied from transformers.models.convnext.modeling_convnext.ConvNextStage with ConvNeXT->ConvNeXTV2, ConvNext->ConvNextV2
181
+ class ConvNextV2Stage(nn.Module):
182
+ """ConvNeXTV2 stage, consisting of an optional downsampling layer + multiple residual blocks.
183
+
184
+ Args:
185
+ config ([`ConvNextV2Config`]): Model configuration class.
186
+ in_channels (`int`): Number of input channels.
187
+ out_channels (`int`): Number of output channels.
188
+ depth (`int`): Number of residual blocks.
189
+ drop_path_rates(`list[float]`): Stochastic depth rates for each layer.
190
+ """
191
+
192
+ def __init__(self, config, in_channels, out_channels, kernel_size=2, stride=2, depth=2, drop_path_rates=None):
193
+ super().__init__()
194
+
195
+ if in_channels != out_channels or stride > 1:
196
+ self.downsampling_layer = nn.ModuleList(
197
+ [
198
+ ConvNextV2LayerNorm(in_channels, eps=1e-6, data_format="channels_first"),
199
+ nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size, stride=stride),
200
+ ]
201
+ )
202
+ else:
203
+ self.downsampling_layer = nn.ModuleList()
204
+ drop_path_rates = drop_path_rates or [0.0] * depth
205
+ self.layers = nn.ModuleList(
206
+ [ConvNextV2Layer(config, dim=out_channels, drop_path=drop_path_rates[j]) for j in range(depth)]
207
+ )
208
+
209
+ def forward(self, features: torch.Tensor) -> torch.Tensor:
210
+ for layer in self.downsampling_layer:
211
+ features = layer(features)
212
+ for layer in self.layers:
213
+ features = layer(features)
214
+ return features
215
+
216
+
217
+ # Copied from transformers.models.convnext.modeling_convnext.ConvNextEncoder with ConvNext->ConvNextV2
218
+ class ConvNextV2Encoder(nn.Module):
219
+ def __init__(self, config):
220
+ super().__init__()
221
+ self.stages = nn.ModuleList()
222
+ drop_path_rates = [
223
+ x.tolist()
224
+ for x in torch.linspace(0, config.drop_path_rate, sum(config.depths), device="cpu").split(config.depths)
225
+ ]
226
+ prev_chs = config.hidden_sizes[0]
227
+ for i in range(config.num_stages):
228
+ out_chs = config.hidden_sizes[i]
229
+ stage = ConvNextV2Stage(
230
+ config,
231
+ in_channels=prev_chs,
232
+ out_channels=out_chs,
233
+ stride=2 if i > 0 else 1,
234
+ depth=config.depths[i],
235
+ drop_path_rates=drop_path_rates[i],
236
+ )
237
+ self.stages.append(stage)
238
+ prev_chs = out_chs
239
+
240
+ def forward(
241
+ self, hidden_states: torch.Tensor, output_hidden_states: bool | None = False
242
+ ) -> BaseModelOutputWithNoAttention:
243
+ all_hidden_states = [hidden_states] if output_hidden_states else None
244
+
245
+ for layer_module in self.stages:
246
+ hidden_states = layer_module(hidden_states)
247
+ if all_hidden_states is not None:
248
+ all_hidden_states.append(hidden_states)
249
+
250
+ return BaseModelOutputWithNoAttention(last_hidden_state=hidden_states, hidden_states=all_hidden_states)
251
+
252
+
253
+ @auto_docstring
254
+ class ConvNextV2PreTrainedModel(PreTrainedModel):
255
+ config: ConvNextV2Config
256
+ base_model_prefix = "convnextv2"
257
+ main_input_name = "pixel_values"
258
+ input_modalities = ("image",)
259
+ _no_split_modules = ["ConvNextV2Layer"]
260
+
261
+ @torch.no_grad()
262
+ def _init_weights(self, module):
263
+ """Initialize the weights"""
264
+ super()._init_weights(module)
265
+ if isinstance(module, ConvNextV2GRN):
266
+ init.zeros_(module.weight)
267
+ init.zeros_(module.bias)
268
+
269
+
270
+ @auto_docstring
271
+ # Copied from transformers.models.convnext.modeling_convnext.ConvNextModel with CONVNEXT->CONVNEXTV2, ConvNext->ConvNextV2
272
+ class ConvNextV2Model(ConvNextV2PreTrainedModel):
273
+ def __init__(self, config):
274
+ super().__init__(config)
275
+ self.config = config
276
+
277
+ self.embeddings = ConvNextV2Embeddings(config)
278
+ self.encoder = ConvNextV2Encoder(config)
279
+
280
+ # final layernorm layer
281
+ self.layernorm = nn.LayerNorm(config.hidden_sizes[-1], eps=config.layer_norm_eps)
282
+
283
+ # Initialize weights and apply final processing
284
+ self.post_init()
285
+
286
+ @can_return_tuple
287
+ @auto_docstring
288
+ def forward(
289
+ self, pixel_values: torch.FloatTensor | None = None, output_hidden_states: bool | None = None, **kwargs
290
+ ) -> BaseModelOutputWithPoolingAndNoAttention:
291
+ if output_hidden_states is None:
292
+ output_hidden_states = self.config.output_hidden_states
293
+
294
+ if pixel_values is None:
295
+ raise ValueError("You have to specify pixel_values")
296
+
297
+ embedding_output = self.embeddings(pixel_values)
298
+ encoder_outputs: BaseModelOutputWithNoAttention = self.encoder(
299
+ embedding_output, output_hidden_states=output_hidden_states
300
+ )
301
+ last_hidden_state = encoder_outputs.last_hidden_state
302
+
303
+ # global average pooling, (N, C, H, W) -> (N, C)
304
+ pooled_output = self.layernorm(last_hidden_state.mean([-2, -1]))
305
+
306
+ return BaseModelOutputWithPoolingAndNoAttention(
307
+ last_hidden_state=last_hidden_state,
308
+ pooler_output=pooled_output,
309
+ hidden_states=encoder_outputs.hidden_states,
310
+ )
311
+
312
+
313
+ @auto_docstring(
314
+ custom_intro="""
315
+ ConvNextV2 Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for
316
+ ImageNet.
317
+ """
318
+ )
319
+ # Copied from transformers.models.convnext.modeling_convnext.ConvNextForImageClassification with CONVNEXT->CONVNEXTV2,ConvNext->ConvNextV2,convnext->convnextv2
320
+ class ConvNextV2ForImageClassification(ConvNextV2PreTrainedModel):
321
+ accepts_loss_kwargs = False
322
+
323
+ def __init__(self, config):
324
+ super().__init__(config)
325
+
326
+ self.num_labels = config.num_labels
327
+ self.convnextv2 = ConvNextV2Model(config)
328
+
329
+ # Classifier head
330
+ if config.num_labels > 0:
331
+ self.classifier = nn.Linear(config.hidden_sizes[-1], config.num_labels)
332
+ else:
333
+ self.classifier = nn.Identity()
334
+
335
+ # Initialize weights and apply final processing
336
+ self.post_init()
337
+
338
+ @can_return_tuple
339
+ @auto_docstring
340
+ def forward(
341
+ self, pixel_values: torch.FloatTensor | None = None, labels: torch.LongTensor | None = None, **kwargs
342
+ ) -> ImageClassifierOutputWithNoAttention:
343
+ r"""
344
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
345
+ Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
346
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
347
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
348
+ """
349
+ outputs: BaseModelOutputWithPoolingAndNoAttention = self.convnextv2(pixel_values, **kwargs)
350
+ pooled_output = outputs.pooler_output
351
+ logits = self.classifier(pooled_output)
352
+
353
+ loss = None
354
+ if labels is not None:
355
+ loss = self.loss_function(labels=labels, pooled_logits=logits, config=self.config)
356
+
357
+ return ImageClassifierOutputWithNoAttention(
358
+ loss=loss,
359
+ logits=logits,
360
+ hidden_states=outputs.hidden_states,
361
+ )
362
+
363
+
364
+ @auto_docstring(
365
+ custom_intro="""
366
+ ConvNeXT V2 backbone, to be used with frameworks like DETR and MaskFormer.
367
+ """
368
+ )
369
+ # Copied from transformers.models.convnext.modeling_convnext.ConvNextBackbone with CONVNEXT->CONVNEXTV2,ConvNext->ConvNextV2,facebook/convnext-tiny-224->facebook/convnextv2-tiny-1k-224
370
+ class ConvNextV2Backbone(BackboneMixin, ConvNextV2PreTrainedModel):
371
+ has_attentions = False
372
+
373
+ def __init__(self, config):
374
+ super().__init__(config)
375
+
376
+ self.embeddings = ConvNextV2Embeddings(config)
377
+ self.encoder = ConvNextV2Encoder(config)
378
+ self.num_features = [config.hidden_sizes[0]] + config.hidden_sizes
379
+
380
+ # Add layer norms to hidden states of out_features
381
+ hidden_states_norms = {}
382
+ for stage, num_channels in zip(self.out_features, self.channels):
383
+ hidden_states_norms[stage] = ConvNextV2LayerNorm(num_channels, data_format="channels_first")
384
+ self.hidden_states_norms = nn.ModuleDict(hidden_states_norms)
385
+
386
+ # initialize weights and apply final processing
387
+ self.post_init()
388
+
389
+ @can_return_tuple
390
+ @auto_docstring
391
+ def forward(
392
+ self, pixel_values: torch.Tensor, output_hidden_states: bool | None = None, **kwargs
393
+ ) -> BackboneOutput:
394
+ r"""
395
+ Examples:
396
+
397
+ ```python
398
+ >>> from transformers import AutoImageProcessor, AutoBackbone
399
+ >>> import torch
400
+ >>> from PIL import Image
401
+ >>> import httpx
402
+ >>> from io import BytesIO
403
+
404
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
405
+ >>> with httpx.stream("GET", url) as response:
406
+ ... image = Image.open(BytesIO(response.read()))
407
+
408
+ >>> processor = AutoImageProcessor.from_pretrained("facebook/convnextv2-tiny-1k-224")
409
+ >>> model = AutoBackbone.from_pretrained("facebook/convnextv2-tiny-1k-224")
410
+
411
+ >>> inputs = processor(image, return_tensors="pt")
412
+ >>> outputs = model(**inputs)
413
+ ```"""
414
+ if output_hidden_states is None:
415
+ output_hidden_states = self.config.output_hidden_states
416
+
417
+ embedding_output = self.embeddings(pixel_values)
418
+ outputs: BaseModelOutputWithPoolingAndNoAttention = self.encoder(embedding_output, output_hidden_states=True)
419
+ hidden_states = outputs.hidden_states
420
+
421
+ feature_maps = []
422
+ for stage, hidden_state in zip(self.stage_names, hidden_states):
423
+ if stage in self.out_features:
424
+ hidden_state = self.hidden_states_norms[stage](hidden_state)
425
+ feature_maps.append(hidden_state)
426
+
427
+ return BackboneOutput(
428
+ feature_maps=tuple(feature_maps),
429
+ hidden_states=hidden_states if output_hidden_states else None,
430
+ )
431
+
432
+
433
+ __all__ = ["ConvNextV2ForImageClassification", "ConvNextV2Model", "ConvNextV2PreTrainedModel", "ConvNextV2Backbone"]
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/cpm/__init__.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .tokenization_cpm import *
22
+ else:
23
+ import sys
24
+
25
+ _file = globals()["__file__"]
26
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/cpm/tokenization_cpm.py ADDED
@@ -0,0 +1,336 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2018 The Google AI Language Team Authors and 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
+ """Tokenization classes."""
15
+
16
+ import os
17
+ import unicodedata
18
+ from shutil import copyfile
19
+ from typing import Any
20
+
21
+ import sentencepiece as spm
22
+
23
+ from ...tokenization_python import AddedToken, PreTrainedTokenizer
24
+ from ...utils import SPIECE_UNDERLINE, logging
25
+ from ...utils.import_utils import requires
26
+
27
+
28
+ logger = logging.get_logger(__name__)
29
+
30
+ VOCAB_FILES_NAMES = {"vocab_file": "spiece.model"}
31
+
32
+
33
+ @requires(backends=("sentencepiece",))
34
+ class CpmTokenizer(PreTrainedTokenizer):
35
+ """Runs pre-tokenization with Jieba-RS segmentation tool. It is used in CPM models."""
36
+
37
+ vocab_files_names = VOCAB_FILES_NAMES
38
+
39
+ def __init__(
40
+ self,
41
+ vocab_file,
42
+ do_lower_case=False,
43
+ remove_space=True,
44
+ keep_accents=False,
45
+ bos_token="<s>",
46
+ eos_token="</s>",
47
+ unk_token="<unk>",
48
+ sep_token="<sep>",
49
+ pad_token="<pad>",
50
+ cls_token="<cls>",
51
+ mask_token="<mask>",
52
+ additional_special_tokens=["<eop>", "<eod>"],
53
+ sp_model_kwargs: dict[str, Any] | None = None,
54
+ **kwargs,
55
+ ) -> None:
56
+ """
57
+ Construct a CPM tokenizer. Based on [Jieba-RS](https://pypi.org/project/rjieba/) and
58
+ [SentencePiece](https://github.com/google/sentencepiece).
59
+
60
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should
61
+ refer to this superclass for more information regarding those methods.
62
+
63
+ Args:
64
+ vocab_file (`str`):
65
+ [SentencePiece](https://github.com/google/sentencepiece) file (generally has a .spm extension) that
66
+ contains the vocabulary necessary to instantiate a tokenizer.
67
+ do_lower_case (`bool`, *optional*, defaults to `True`):
68
+ Whether to lowercase the input when tokenizing.
69
+ remove_space (`bool`, *optional*, defaults to `True`):
70
+ Whether to strip the text when tokenizing (removing excess spaces before and after the string).
71
+ keep_accents (`bool`, *optional*, defaults to `False`):
72
+ Whether to keep accents when tokenizing.
73
+ bos_token (`str`, *optional*, defaults to `"<s>"`):
74
+ The beginning of sequence token that was used during pretraining. Can be used a sequence classifier
75
+ token.
76
+
77
+ <Tip>
78
+
79
+ When building a sequence using special tokens, this is not the token that is used for the beginning of
80
+ sequence. The token used is the `cls_token`.
81
+
82
+ </Tip>
83
+
84
+ eos_token (`str`, *optional*, defaults to `"</s>"`):
85
+ The end of sequence token.
86
+
87
+ <Tip>
88
+
89
+ When building a sequence using special tokens, this is not the token that is used for the end of
90
+ sequence. The token used is the `sep_token`.
91
+
92
+ </Tip>
93
+
94
+ unk_token (`str`, *optional*, defaults to `"<unk>"`):
95
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be
96
+ this token instead.
97
+ sep_token (`str`, *optional*, defaults to `"<sep>"`):
98
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences
99
+ for sequence classification or for a text and a question for question answering. It is also used as the
100
+ last token of a sequence built with special tokens.
101
+ pad_token (`str`, *optional*, defaults to `"<pad>"`):
102
+ The token used for padding, for example when batching sequences of different lengths.
103
+ cls_token (`str`, *optional*, defaults to `"<cls>"`):
104
+ The classifier token which is used when doing sequence classification (classification of the whole
105
+ sequence instead of per-token classification). It is the first token of the sequence when built with
106
+ special tokens.
107
+ mask_token (`str`, *optional*, defaults to `"<mask>"`):
108
+ The token used for masking values. This is the token used when training this model with masked language
109
+ modeling. This is the token which the model will try to predict.
110
+ additional_special_tokens (`list[str]`, *optional*, defaults to `["<eop>", "<eod>"]`):
111
+ Additional special tokens used by the tokenizer.
112
+
113
+ Attributes:
114
+ sp_model (`SentencePieceProcessor`):
115
+ The *SentencePiece* processor that is used for every conversion (string, tokens and IDs).
116
+ """
117
+ # Mask token behave like a normal word, i.e. include the space before it
118
+ mask_token = AddedToken(mask_token, lstrip=True, rstrip=False) if isinstance(mask_token, str) else mask_token
119
+
120
+ self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
121
+
122
+ self.do_lower_case = do_lower_case
123
+ self.remove_space = remove_space
124
+ self.keep_accents = keep_accents
125
+ self.vocab_file = vocab_file
126
+
127
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
128
+ self.sp_model.Load(vocab_file)
129
+
130
+ try:
131
+ import rjieba
132
+ except ModuleNotFoundError as error:
133
+ raise error.__class__(
134
+ "You need to install rjieba to use CpmTokenizer or CpmTokenizerFast. "
135
+ "See https://pypi.org/project/rjieba/ for installation."
136
+ )
137
+ self.jieba = rjieba
138
+ self.translator = str.maketrans(" \n", "\u2582\u2583")
139
+
140
+ super().__init__(
141
+ do_lower_case=do_lower_case,
142
+ remove_space=remove_space,
143
+ keep_accents=keep_accents,
144
+ bos_token=bos_token,
145
+ eos_token=eos_token,
146
+ unk_token=unk_token,
147
+ sep_token=sep_token,
148
+ pad_token=pad_token,
149
+ cls_token=cls_token,
150
+ mask_token=mask_token,
151
+ additional_special_tokens=additional_special_tokens,
152
+ sp_model_kwargs=self.sp_model_kwargs,
153
+ **kwargs,
154
+ )
155
+
156
+ self._pad_token_type_id = 3
157
+
158
+ @property
159
+ def vocab_size(self):
160
+ return len(self.sp_model)
161
+
162
+ def get_vocab(self):
163
+ vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
164
+ vocab.update(self.added_tokens_encoder)
165
+ return vocab
166
+
167
+ def __getstate__(self):
168
+ state = self.__dict__.copy()
169
+ state["sp_model"] = None
170
+ return state
171
+
172
+ def __setstate__(self, d):
173
+ self.__dict__ = d
174
+
175
+ # for backward compatibility
176
+ if not hasattr(self, "sp_model_kwargs"):
177
+ self.sp_model_kwargs = {}
178
+
179
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
180
+ self.sp_model.Load(self.vocab_file)
181
+
182
+ def preprocess_text(self, inputs):
183
+ if self.remove_space:
184
+ outputs = " ".join(inputs.strip().split())
185
+ else:
186
+ outputs = inputs
187
+ outputs = outputs.replace("``", '"').replace("''", '"')
188
+
189
+ if not self.keep_accents:
190
+ outputs = unicodedata.normalize("NFKD", outputs)
191
+ outputs = "".join([c for c in outputs if not unicodedata.combining(c)])
192
+ if self.do_lower_case:
193
+ outputs = outputs.lower()
194
+
195
+ return outputs
196
+
197
+ def _tokenize(self, text: str) -> list[str]:
198
+ """Tokenize a string."""
199
+ text = self.preprocess_text(text)
200
+ pieces = self.sp_model.encode(text, out_type=str)
201
+ new_pieces = []
202
+ for piece in pieces:
203
+ if len(piece) > 1 and piece[-1] == "," and piece[-2].isdigit():
204
+ cur_pieces = self.sp_model.EncodeAsPieces(piece[:-1].replace(SPIECE_UNDERLINE, ""))
205
+ if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE:
206
+ if len(cur_pieces[0]) == 1:
207
+ cur_pieces = cur_pieces[1:]
208
+ else:
209
+ cur_pieces[0] = cur_pieces[0][1:]
210
+ cur_pieces.append(piece[-1])
211
+ new_pieces.extend(cur_pieces)
212
+ else:
213
+ new_pieces.append(piece)
214
+
215
+ return new_pieces
216
+
217
+ def _convert_token_to_id(self, token):
218
+ """Converts a token (str) in an id using the vocab."""
219
+ return self.sp_model.PieceToId(token)
220
+
221
+ def _convert_id_to_token(self, index):
222
+ """Converts an index (integer) in a token (str) using the vocab."""
223
+ return self.sp_model.IdToPiece(index)
224
+
225
+ def convert_tokens_to_string(self, tokens):
226
+ """Converts a sequence of tokens (strings for sub-words) in a single string."""
227
+ out_string = "".join(tokens).replace(SPIECE_UNDERLINE, " ").strip()
228
+ return out_string
229
+
230
+ def build_inputs_with_special_tokens(
231
+ self, token_ids_0: list[int], token_ids_1: list[int] | None = None
232
+ ) -> list[int]:
233
+ """
234
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
235
+ adding special tokens. An XLNet sequence has the following format:
236
+
237
+ - single sequence: `X <sep> <cls>`
238
+ - pair of sequences: `A <sep> B <sep> <cls>`
239
+
240
+ Args:
241
+ token_ids_0 (`list[int]`):
242
+ List of IDs to which the special tokens will be added.
243
+ token_ids_1 (`list[int]`, *optional*):
244
+ Optional second list of IDs for sequence pairs.
245
+
246
+ Returns:
247
+ `list[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
248
+ """
249
+ sep = [self.sep_token_id]
250
+ cls = [self.cls_token_id]
251
+ if token_ids_1 is None:
252
+ return token_ids_0 + sep + cls
253
+ return token_ids_0 + sep + token_ids_1 + sep + cls
254
+
255
+ def get_special_tokens_mask(
256
+ self, token_ids_0: list[int], token_ids_1: list[int] | None = None, already_has_special_tokens: bool = False
257
+ ) -> list[int]:
258
+ """
259
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
260
+ special tokens using the tokenizer `prepare_for_model` method.
261
+
262
+ Args:
263
+ token_ids_0 (`list[int]`):
264
+ List of IDs.
265
+ token_ids_1 (`list[int]`, *optional*):
266
+ Optional second list of IDs for sequence pairs.
267
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
268
+ Whether or not the token list is already formatted with special tokens for the model.
269
+
270
+ Returns:
271
+ `list[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
272
+ """
273
+
274
+ if already_has_special_tokens:
275
+ return super().get_special_tokens_mask(
276
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
277
+ )
278
+
279
+ if token_ids_1 is not None:
280
+ return ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1, 1]
281
+ return ([0] * len(token_ids_0)) + [1, 1]
282
+
283
+ def create_token_type_ids_from_sequences(
284
+ self, token_ids_0: list[int], token_ids_1: list[int] | None = None
285
+ ) -> list[int]:
286
+ """
287
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task. An XLNet
288
+ sequence pair mask has the following format:
289
+
290
+ ```
291
+ 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
292
+ | first sequence | second sequence |
293
+ ```
294
+
295
+ If `token_ids_1` is `None`, this method only returns the first portion of the mask (0s).
296
+
297
+ Args:
298
+ token_ids_0 (`list[int]`):
299
+ List of IDs.
300
+ token_ids_1 (`list[int]`, *optional*):
301
+ Optional second list of IDs for sequence pairs.
302
+
303
+ Returns:
304
+ `list[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
305
+ """
306
+ sep = [self.sep_token_id]
307
+ cls_segment_id = [2]
308
+
309
+ if token_ids_1 is None:
310
+ return len(token_ids_0 + sep) * [0] + cls_segment_id
311
+ return len(token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1] + cls_segment_id
312
+
313
+ def save_vocabulary(self, save_directory: str, filename_prefix: str | None = None) -> tuple[str]:
314
+ if not os.path.isdir(save_directory):
315
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
316
+ return
317
+ out_vocab_file = os.path.join(
318
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
319
+ )
320
+
321
+ if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
322
+ copyfile(self.vocab_file, out_vocab_file)
323
+ elif not os.path.isfile(self.vocab_file):
324
+ with open(out_vocab_file, "wb") as fi:
325
+ content_spiece_model = self.sp_model.serialized_model_proto()
326
+ fi.write(content_spiece_model)
327
+
328
+ return (out_vocab_file,)
329
+
330
+ def _decode(self, *args, **kwargs):
331
+ text = super()._decode(*args, **kwargs)
332
+ text = text.replace(" ", "").replace("\u2582", " ").replace("\u2583", "\n")
333
+ return text
334
+
335
+
336
+ __all__ = ["CpmTokenizer"]
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/cpm/tokenization_cpm_fast.py ADDED
@@ -0,0 +1,232 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2018 The Google AI Language Team Authors and 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
+ """Tokenization classes."""
15
+
16
+ import os
17
+ from shutil import copyfile
18
+
19
+ from ...tokenization_utils_tokenizers import AddedToken, PreTrainedTokenizerFast
20
+ from ...utils import logging
21
+
22
+
23
+ logger = logging.get_logger(__name__)
24
+
25
+ VOCAB_FILES_NAMES = {"vocab_file": "spiece.model", "tokenizer_file": "tokenizer.json"}
26
+
27
+
28
+ class CpmTokenizerFast(PreTrainedTokenizerFast):
29
+ """Runs pre-tokenization with Jieba-RS segmentation tool. It is used in CPM models."""
30
+
31
+ def __init__(
32
+ self,
33
+ vocab_file=None,
34
+ tokenizer_file=None,
35
+ do_lower_case=False,
36
+ remove_space=True,
37
+ keep_accents=False,
38
+ bos_token="<s>",
39
+ eos_token="</s>",
40
+ unk_token="<unk>",
41
+ sep_token="<sep>",
42
+ pad_token="<pad>",
43
+ cls_token="<cls>",
44
+ mask_token="<mask>",
45
+ additional_special_tokens=["<eop>", "<eod>"],
46
+ **kwargs,
47
+ ):
48
+ """
49
+ Construct a CPM tokenizer. Based on [Jieba-RS](https://pypi.org/project/rjieba/) and
50
+ [SentencePiece](https://github.com/google/sentencepiece).
51
+
52
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should
53
+ refer to this superclass for more information regarding those methods.
54
+
55
+ Args:
56
+ vocab_file (`str`):
57
+ [SentencePiece](https://github.com/google/sentencepiece) file (generally has a .spm extension) that
58
+ contains the vocabulary necessary to instantiate a tokenizer.
59
+ do_lower_case (`bool`, *optional*, defaults to `True`):
60
+ Whether to lowercase the input when tokenizing.
61
+ remove_space (`bool`, *optional*, defaults to `True`):
62
+ Whether to strip the text when tokenizing (removing excess spaces before and after the string).
63
+ keep_accents (`bool`, *optional*, defaults to `False`):
64
+ Whether to keep accents when tokenizing.
65
+ bos_token (`str`, *optional*, defaults to `"<s>"`):
66
+ The beginning of sequence token that was used during pretraining. Can be used a sequence classifier
67
+ token.
68
+
69
+ <Tip>
70
+
71
+ When building a sequence using special tokens, this is not the token that is used for the beginning of
72
+ sequence. The token used is the `cls_token`.
73
+
74
+ </Tip>
75
+
76
+ eos_token (`str`, *optional*, defaults to `"</s>"`):
77
+ The end of sequence token.
78
+
79
+ <Tip>
80
+
81
+ When building a sequence using special tokens, this is not the token that is used for the end of
82
+ sequence. The token used is the `sep_token`.
83
+
84
+ </Tip>
85
+
86
+ unk_token (`str`, *optional*, defaults to `"<unk>"`):
87
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be
88
+ this token instead.
89
+ sep_token (`str`, *optional*, defaults to `"<sep>"`):
90
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences
91
+ for sequence classification or for a text and a question for question answering. It is also used as the
92
+ last token of a sequence built with special tokens.
93
+ pad_token (`str`, *optional*, defaults to `"<pad>"`):
94
+ The token used for padding, for example when batching sequences of different lengths.
95
+ cls_token (`str`, *optional*, defaults to `"<cls>"`):
96
+ The classifier token which is used when doing sequence classification (classification of the whole
97
+ sequence instead of per-token classification). It is the first token of the sequence when built with
98
+ special tokens.
99
+ mask_token (`str`, *optional*, defaults to `"<mask>"`):
100
+ The token used for masking values. This is the token used when training this model with masked language
101
+ modeling. This is the token which the model will try to predict.
102
+ additional_special_tokens (`list[str]`, *optional*, defaults to `["<eop>", "<eod>"]`):
103
+ Additional special tokens used by the tokenizer.
104
+
105
+ Attributes:
106
+ sp_model (`SentencePieceProcessor`):
107
+ The *SentencePiece* processor that is used for every conversion (string, tokens and IDs).
108
+ """
109
+ # Mask token behave like a normal word, i.e. include the space before it
110
+ mask_token = AddedToken(mask_token, lstrip=True, rstrip=False) if isinstance(mask_token, str) else mask_token
111
+
112
+ super().__init__(
113
+ vocab_file=vocab_file,
114
+ tokenizer_file=tokenizer_file,
115
+ do_lower_case=do_lower_case,
116
+ remove_space=remove_space,
117
+ keep_accents=keep_accents,
118
+ bos_token=bos_token,
119
+ eos_token=eos_token,
120
+ unk_token=unk_token,
121
+ sep_token=sep_token,
122
+ pad_token=pad_token,
123
+ cls_token=cls_token,
124
+ mask_token=mask_token,
125
+ additional_special_tokens=additional_special_tokens,
126
+ **kwargs,
127
+ )
128
+
129
+ self._pad_token_type_id = 3
130
+ self.do_lower_case = do_lower_case
131
+ self.remove_space = remove_space
132
+ self.keep_accents = keep_accents
133
+ self.vocab_file = vocab_file
134
+
135
+ try:
136
+ import rjieba
137
+ except ModuleNotFoundError as error:
138
+ raise error.__class__(
139
+ "You need to install rjieba to use CpmTokenizer or CpmTokenizerFast. "
140
+ "See https://pypi.org/project/rjieba/ for installation."
141
+ )
142
+ self.jieba = rjieba
143
+ self.translator = str.maketrans(" \n", "\u2582\u2583")
144
+
145
+ def build_inputs_with_special_tokens(
146
+ self, token_ids_0: list[int], token_ids_1: list[int] | None = None
147
+ ) -> list[int]:
148
+ """
149
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
150
+ adding special tokens. An XLNet sequence has the following format:
151
+
152
+ - single sequence: `X <sep> <cls>`
153
+ - pair of sequences: `A <sep> B <sep> <cls>`
154
+
155
+ Args:
156
+ token_ids_0 (`list[int]`):
157
+ List of IDs to which the special tokens will be added.
158
+ token_ids_1 (`list[int]`, *optional*):
159
+ Optional second list of IDs for sequence pairs.
160
+
161
+ Returns:
162
+ `list[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
163
+ """
164
+ sep = [self.sep_token_id]
165
+ cls = [self.cls_token_id]
166
+ if token_ids_1 is None:
167
+ return token_ids_0 + sep + cls
168
+ return token_ids_0 + sep + token_ids_1 + sep + cls
169
+
170
+ def create_token_type_ids_from_sequences(
171
+ self, token_ids_0: list[int], token_ids_1: list[int] | None = None
172
+ ) -> list[int]:
173
+ """
174
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task. An XLNet
175
+ sequence pair mask has the following format:
176
+
177
+ ```
178
+ 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
179
+ | first sequence | second sequence |
180
+ ```
181
+
182
+ If `token_ids_1` is `None`, this method only returns the first portion of the mask (0s).
183
+
184
+ Args:
185
+ token_ids_0 (`list[int]`):
186
+ List of IDs.
187
+ token_ids_1 (`list[int]`, *optional*):
188
+ Optional second list of IDs for sequence pairs.
189
+
190
+ Returns:
191
+ `list[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
192
+ """
193
+ sep = [self.sep_token_id]
194
+ cls_segment_id = [2]
195
+
196
+ if token_ids_1 is None:
197
+ return len(token_ids_0 + sep) * [0] + cls_segment_id
198
+ return len(token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1] + cls_segment_id
199
+
200
+ def save_vocabulary(self, save_directory: str, filename_prefix: str | None = None) -> tuple[str]:
201
+ if not self.can_save_slow_tokenizer:
202
+ raise ValueError(
203
+ "Your fast tokenizer does not have the necessary information to save the vocabulary for a slow "
204
+ "tokenizer."
205
+ )
206
+
207
+ if not os.path.isdir(save_directory):
208
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
209
+ return
210
+ out_vocab_file = os.path.join(
211
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
212
+ )
213
+
214
+ if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file):
215
+ copyfile(self.vocab_file, out_vocab_file)
216
+
217
+ return (out_vocab_file,)
218
+
219
+ def _batch_encode_plus(self, batch_text_or_text_pairs, *args, **kwargs):
220
+ batch_text_or_text_pairs = [
221
+ " ".join([x.translate(self.translator) for x in self.jieba.cut(text, False)])
222
+ for text in batch_text_or_text_pairs
223
+ ]
224
+ return super()._batch_encode_plus(batch_text_or_text_pairs, *args, **kwargs)
225
+
226
+ def _decode(self, *args, **kwargs):
227
+ text = super()._decode(*args, **kwargs)
228
+ text = text.replace(" ", "").replace("\u2582", " ").replace("\u2583", "\n")
229
+ return text
230
+
231
+
232
+ __all__ = ["CpmTokenizerFast"]
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/cpmant/__init__.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_cpmant import *
22
+ from .modeling_cpmant import *
23
+ from .tokenization_cpmant import *
24
+ else:
25
+ import sys
26
+
27
+ _file = globals()["__file__"]
28
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/cpmant/configuration_cpmant.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The OpenBMB Team and 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
+ """CPMAnt model configuration"""
15
+
16
+ from ...configuration_utils import PreTrainedConfig
17
+ from ...utils import logging
18
+
19
+
20
+ logger = logging.get_logger(__name__)
21
+
22
+
23
+ class CpmAntConfig(PreTrainedConfig):
24
+ r"""
25
+ This is the configuration class to store the configuration of a [`CpmAntModel`]. It is used to instantiate an
26
+ CPMAnt model according to the specified arguments, defining the model architecture. Instantiating a configuration
27
+ with the defaults will yield a similar configuration to that of the CPMAnt
28
+ [openbmb/cpm-ant-10b](https://huggingface.co/openbmb/cpm-ant-10b) architecture.
29
+
30
+ Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the
31
+ documentation from [`PreTrainedConfig`] for more information.
32
+
33
+ Args:
34
+ vocab_size (`int`, *optional*, defaults to 30720):
35
+ Vocabulary size of the CPMAnt model. Defines the number of different tokens that can be represented by the
36
+ `input` passed when calling [`CpmAntModel`].
37
+ hidden_size (`int`, *optional*, defaults to 4096):
38
+ Dimension of the encoder layers.
39
+ num_attention_heads (`int`, *optional*, defaults to 32):
40
+ Number of attention heads in the Transformer encoder.
41
+ dim_head (`int`, *optional*, defaults to 128):
42
+ Dimension of attention heads for each attention layer in the Transformer encoder.
43
+ dim_ff (`int`, *optional*, defaults to 10240):
44
+ Dimension of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
45
+ num_hidden_layers (`int`, *optional*, defaults to 48):
46
+ Number of layers of the Transformer encoder.
47
+ dropout_p (`float`, *optional*, defaults to 0.0):
48
+ The dropout probability for all fully connected layers in the embeddings, encoder.
49
+ position_bias_num_buckets (`int`, *optional*, defaults to 512):
50
+ The number of position_bias buckets.
51
+ position_bias_max_distance (`int`, *optional*, defaults to 2048):
52
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
53
+ just in case (e.g., 512 or 1024 or 2048).
54
+ eps (`float`, *optional*, defaults to 1e-06):
55
+ The epsilon used by the layer normalization layers.
56
+ init_std (`float`, *optional*, defaults to 1.0):
57
+ Initialize parameters with std = init_std.
58
+ prompt_types (`int`, *optional*, defaults to 32):
59
+ The type of prompt.
60
+ prompt_length (`int`, *optional*, defaults to 32):
61
+ The length of prompt.
62
+ segment_types (`int`, *optional*, defaults to 32):
63
+ The type of segment.
64
+ use_cache (`bool`, *optional*, defaults to `True`):
65
+ Whether to use cache.
66
+ tie_word_embeddings (`bool`, *optional*, defaults to `True`):
67
+ Whether to tie weight embeddings
68
+
69
+ Example:
70
+
71
+ ```python
72
+ >>> from transformers import CpmAntModel, CpmAntConfig
73
+
74
+ >>> # Initializing a CPMAnt cpm-ant-10b style configuration
75
+ >>> configuration = CpmAntConfig()
76
+
77
+ >>> # Initializing a model from the cpm-ant-10b style configuration
78
+ >>> model = CpmAntModel(configuration)
79
+
80
+ >>> # Accessing the model configuration
81
+ >>> configuration = model.config
82
+ ```"""
83
+
84
+ model_type = "cpmant"
85
+
86
+ def __init__(
87
+ self,
88
+ vocab_size: int = 30720,
89
+ hidden_size: int = 4096,
90
+ num_attention_heads: int = 32,
91
+ dim_head: int = 128,
92
+ dim_ff: int = 10240,
93
+ num_hidden_layers: int = 48,
94
+ dropout_p: int = 0.0,
95
+ position_bias_num_buckets: int = 512,
96
+ position_bias_max_distance: int = 2048,
97
+ eps: int = 1e-6,
98
+ init_std: float = 1.0,
99
+ prompt_types: int = 32,
100
+ prompt_length: int = 32,
101
+ segment_types: int = 32,
102
+ use_cache: bool = True,
103
+ tie_word_embeddings=True,
104
+ **kwargs,
105
+ ):
106
+ super().__init__(**kwargs)
107
+ self.tie_word_embeddings = tie_word_embeddings
108
+ self.prompt_types = prompt_types
109
+ self.prompt_length = prompt_length
110
+ self.segment_types = segment_types
111
+ self.hidden_size = hidden_size
112
+ self.num_attention_heads = num_attention_heads
113
+ self.dim_head = dim_head
114
+ self.dim_ff = dim_ff
115
+ self.num_hidden_layers = num_hidden_layers
116
+ self.position_bias_num_buckets = position_bias_num_buckets
117
+ self.position_bias_max_distance = position_bias_max_distance
118
+ self.dropout_p = dropout_p
119
+ self.eps = eps
120
+ self.use_cache = use_cache
121
+ self.vocab_size = vocab_size
122
+ self.init_std = init_std
123
+
124
+
125
+ __all__ = ["CpmAntConfig"]
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/cpmant/modeling_cpmant.py ADDED
@@ -0,0 +1,785 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The OpenBMB Team and 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
+ """PyTorch CPMAnt"""
15
+
16
+ import math
17
+
18
+ import torch
19
+ import torch.nn.functional as F
20
+ from torch import nn
21
+ from torch.nn import CrossEntropyLoss
22
+
23
+ from ... import initialization as init
24
+ from ...activations import ACT2FN
25
+ from ...cache_utils import Cache, DynamicCache
26
+ from ...generation import GenerationMixin
27
+ from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
28
+ from ...modeling_utils import PreTrainedModel
29
+ from ...utils import auto_docstring, logging
30
+ from .configuration_cpmant import CpmAntConfig
31
+
32
+
33
+ logger = logging.get_logger(__name__)
34
+
35
+
36
+ class CpmAntLayerNorm(nn.Module):
37
+ """
38
+ We use Root Mean Square (RMS) Layer Normalization, please see https://huggingface.co/papers/1910.07467 for details."
39
+ """
40
+
41
+ def __init__(self, config: CpmAntConfig):
42
+ super().__init__()
43
+
44
+ self.eps = config.eps
45
+ self.dim_norm = config.hidden_size
46
+ self.weight = nn.Parameter(torch.empty(config.hidden_size))
47
+
48
+ def forward(self, hidden_states: torch.Tensor):
49
+ """
50
+ Args:
51
+ hidden_states (`torch.Tensor` of shape `(batch, seq_len, dim_in)`)
52
+ """
53
+ if hidden_states.size(-1) != self.dim_norm:
54
+ raise AssertionError("hidden_states.size(-1) != self.dim_norm")
55
+ old_dtype = hidden_states.dtype
56
+ variance = hidden_states.to(torch.float32).pow(2).mean(dim=-1, keepdim=True)
57
+ hidden_states = (hidden_states * torch.rsqrt(variance + self.eps)).to(old_dtype) * self.weight
58
+ return hidden_states
59
+
60
+
61
+ class CpmAntAttention(nn.Module):
62
+ def __init__(self, config: CpmAntConfig, layer_idx=None):
63
+ super().__init__()
64
+ self.dim_model = config.hidden_size
65
+ self.num_heads = config.num_attention_heads
66
+ self.dim_head = config.dim_head
67
+ self.layer_idx = layer_idx
68
+
69
+ self.project_q = nn.Linear(self.dim_model, self.num_heads * self.dim_head, bias=False)
70
+ self.project_k = nn.Linear(self.dim_model, self.num_heads * self.dim_head, bias=False)
71
+ self.project_v = nn.Linear(self.dim_model, self.num_heads * self.dim_head, bias=False)
72
+
73
+ self.attention_out = nn.Linear(self.num_heads * self.dim_head, self.dim_model, bias=False)
74
+
75
+ self.softmax = torch.nn.Softmax(dim=-1)
76
+
77
+ if config.dropout_p is not None:
78
+ self.dropout = torch.nn.Dropout(p=config.dropout_p)
79
+ else:
80
+ self.dropout = None
81
+
82
+ def forward(
83
+ self,
84
+ hidden_q: torch.Tensor,
85
+ hidden_kv: torch.Tensor,
86
+ attention_mask: torch.BoolTensor,
87
+ position_bias: torch.Tensor,
88
+ output_attentions: bool | None = False,
89
+ past_key_values: Cache | None = None,
90
+ use_cache: bool | None = None,
91
+ cache_position: torch.Tensor | None = None,
92
+ ):
93
+ """
94
+ Args:
95
+ hidden_q (`torch.Tensor`):
96
+ Input of transformer block(self-attention block). It can be the raw embedding of a batch of sequences.
97
+ hidden_kv (`torch.Tensor` of shape `(batch, len_k, dim_model)`)):
98
+ Tensor *key_value* and *query* of shape `(batch, len_k, dim_model)`
99
+ attention_mask (`torch.Tensor` of shape `(batch, len_seq, len_seq)`):
100
+ Avoid invalid areas to participate in the calculation of self-attention.
101
+ position_bias (`torch.Tensor` of shape `(batch, len_seq, len_seq)`):
102
+ Provide positional information to self-attention block.
103
+ output_attentions (`bool`, *optional*):
104
+ Whether or not to return the attentions tensors of all attention layers.
105
+ past_key_values (`Cache`, *optional*):
106
+ Cached past key and value projection states.
107
+ use_cache (`bool`, *optional*):
108
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
109
+ (see `past_key_values`).
110
+ """
111
+ batch_size = hidden_q.size(0)
112
+ len_q = hidden_q.size(1)
113
+ len_k = hidden_kv.size(1)
114
+
115
+ query = self.project_q(hidden_q)
116
+ key = self.project_k(hidden_kv)
117
+ value = self.project_v(hidden_kv)
118
+
119
+ query = query.view(batch_size, len_q, self.num_heads, self.dim_head).permute(0, 2, 1, 3)
120
+ key = key.view(batch_size, len_k, self.num_heads, self.dim_head).permute(0, 2, 1, 3)
121
+ value = value.view(batch_size, len_k, self.num_heads, self.dim_head).permute(0, 2, 1, 3)
122
+
123
+ if past_key_values is not None:
124
+ key, value = past_key_values.update(key, value, self.layer_idx, {"cache_position": cache_position})
125
+ len_k = key.size(-2)
126
+
127
+ # (batch_size, num_heads, len_q, dim_head) @ (batch_size, num_heads, dim_head, len_k) -> (batch_size, num_heads, len_q, len_k)
128
+ score = torch.matmul(query, key.transpose(-1, -2)) / math.sqrt(self.dim_head)
129
+ score = score + position_bias
130
+
131
+ score = torch.masked_fill(
132
+ score,
133
+ attention_mask.view(batch_size, 1, len_q, len_k) == torch.tensor(False),
134
+ torch.scalar_tensor(float("-inf"), device=score.device, dtype=score.dtype),
135
+ )
136
+ score = self.softmax(score)
137
+
138
+ score = torch.masked_fill(
139
+ score,
140
+ attention_mask.view(batch_size, 1, len_q, len_k) == torch.tensor(False),
141
+ torch.scalar_tensor(0, device=score.device, dtype=score.dtype),
142
+ )
143
+ if output_attentions:
144
+ attn_weights = score
145
+ else:
146
+ attn_weights = None
147
+
148
+ if self.dropout is not None:
149
+ score = self.dropout(score)
150
+
151
+ # (batch_size, num_heads, len_q, len_k) @ (batch_size, num_heads, len_k, dim_head) -> (batch_size, num_heads, len_q, dim_head)
152
+ score = torch.matmul(score, value)
153
+
154
+ score = score.view(batch_size, self.num_heads, len_q, self.dim_head).permute(0, 2, 1, 3)
155
+ score = score.contiguous().view(batch_size, len_q, self.num_heads * self.dim_head)
156
+
157
+ score = self.attention_out(score)
158
+
159
+ return score, attn_weights
160
+
161
+
162
+ class CpmAntSelfAttentionBlock(nn.Module):
163
+ def __init__(self, config: CpmAntConfig, layer_idx=None):
164
+ super().__init__()
165
+ self.layernorm_before_attention = CpmAntLayerNorm(config)
166
+ self.self_attention = CpmAntAttention(config, layer_idx=layer_idx)
167
+ if config.dropout_p:
168
+ self.dropout = torch.nn.Dropout(config.dropout_p)
169
+ else:
170
+ self.dropout = None
171
+
172
+ def forward(
173
+ self,
174
+ hidden_states: torch.Tensor,
175
+ attention_mask: torch.Tensor,
176
+ position_bias: torch.Tensor | None = None,
177
+ output_attentions: bool | None = False,
178
+ past_key_values: Cache | None = None,
179
+ use_cache: bool | None = None,
180
+ cache_position: torch.Tensor | None = None,
181
+ ):
182
+ """
183
+ Args:
184
+ hidden_states (`torch.Tensor` of shape `(batch, len_seq, dim_model)`):
185
+ Input of transformer block(self-attention block). It can be the raw embedding of a batch of sequences.
186
+ attention_mask (`torch.Tensor` of shape `(batch, len_seq, len_seq)`):
187
+ Avoid invalid areas to participate in the calculation of self-attention.
188
+ position_bias (`torch.Tensor` of shape `(batch, len_seq, len_seq)`):
189
+ Provide positional information to self-attention block.
190
+ output_attentions (`bool`, *optional*):
191
+ Whether or not to return the attentions tensors of all attention layers.
192
+ past_key_values (`Cache`, *optional*):
193
+ Cached past key and value projection states.
194
+ use_cache (`bool`, *optional*):
195
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
196
+ (see `past_key_values`).
197
+ """
198
+ outputs = self.layernorm_before_attention(hidden_states)
199
+ outputs, attn_weights = self.self_attention(
200
+ outputs,
201
+ outputs,
202
+ attention_mask,
203
+ position_bias,
204
+ output_attentions,
205
+ past_key_values,
206
+ use_cache,
207
+ cache_position,
208
+ )
209
+
210
+ if self.dropout is not None:
211
+ outputs = self.dropout(outputs)
212
+ hidden_states = hidden_states + outputs
213
+
214
+ return hidden_states, attn_weights
215
+
216
+
217
+ class CpmAntDenseGatedACT(nn.Module):
218
+ def __init__(self, config: CpmAntConfig):
219
+ super().__init__()
220
+ self.w_0 = nn.Linear(config.hidden_size, config.dim_ff, bias=False)
221
+ self.w_1 = nn.Linear(config.hidden_size, config.dim_ff, bias=False)
222
+ self.act = torch.nn.GELU()
223
+
224
+ def forward(self, hidden_states: torch.Tensor):
225
+ """Transform an input tensor from one feature space to another via a nonlinear operation
226
+
227
+ Args:
228
+ hidden_states (`torch.Tensor` of shape `(batch, seq_len, dim_in)`)
229
+ """
230
+ gate_score = self.act(self.w_0(hidden_states))
231
+ hidden_states = self.w_1(hidden_states)
232
+
233
+ hidden_states = gate_score * hidden_states
234
+ return hidden_states
235
+
236
+
237
+ class CpmAntFeedForward(nn.Module):
238
+ def __init__(self, config: CpmAntConfig):
239
+ super().__init__()
240
+ self.w_in = CpmAntDenseGatedACT(config)
241
+ if config.dropout_p is not None:
242
+ self.dropout = torch.nn.Dropout(config.dropout_p)
243
+ else:
244
+ self.dropout = None
245
+
246
+ self.w_out = nn.Linear(config.dim_ff, config.hidden_size, bias=False)
247
+
248
+ def forward(self, hidden_states: torch.Tensor):
249
+ """
250
+ Args:
251
+ hidden_states (`torch.Tensor` of shape `(batch, seq_len, dim_in)`)
252
+ """
253
+ hidden_states = self.w_in(hidden_states)
254
+
255
+ if self.dropout is not None:
256
+ hidden_states = self.dropout(hidden_states)
257
+
258
+ hidden_states = self.w_out(hidden_states)
259
+
260
+ return hidden_states
261
+
262
+
263
+ class CpmAntFFNBlock(nn.Module):
264
+ def __init__(self, config: CpmAntConfig):
265
+ super().__init__()
266
+ self.layernorm_before_ffn = CpmAntLayerNorm(config)
267
+ self.ffn = CpmAntFeedForward(config)
268
+ if config.dropout_p:
269
+ self.dropout = torch.nn.Dropout(config.dropout_p)
270
+ else:
271
+ self.dropout = None
272
+
273
+ def forward(
274
+ self,
275
+ hidden_states: torch.Tensor,
276
+ ):
277
+ """
278
+ Args:
279
+ hidden_states (`torch.Tensor` of shape `(batch, len_seq, dim_model)`):
280
+ Hidden states before feed forward layer.
281
+ """
282
+ ln_outputs = self.layernorm_before_ffn(hidden_states)
283
+ outputs = self.ffn(ln_outputs)
284
+ if self.dropout is not None:
285
+ outputs = self.dropout(outputs)
286
+ hidden_states = hidden_states + outputs
287
+ return hidden_states
288
+
289
+
290
+ class CpmAntTransformerBlock(nn.Module):
291
+ def __init__(self, config: CpmAntConfig, layer_idx=None):
292
+ super().__init__()
293
+ self.self_att = CpmAntSelfAttentionBlock(config, layer_idx=layer_idx)
294
+ self.ffn = CpmAntFFNBlock(config)
295
+
296
+ def forward(
297
+ self,
298
+ hidden_states: torch.Tensor,
299
+ attention_mask: torch.Tensor,
300
+ position_bias: torch.Tensor | None = None,
301
+ output_attentions: bool | None = False,
302
+ past_key_values: Cache | None = None,
303
+ use_cache: bool | None = None,
304
+ cache_position: torch.Tensor | None = None,
305
+ ):
306
+ """
307
+ Args:
308
+ hidden_states (`torch.Tensor`):
309
+ Input to the layer of shape `(batch, seq_len, dim_model)`
310
+ attention_mask (`torch.Tensor`):
311
+ Avoid invalid areas to participate in the calculation of shape `(batch, seq_len, seq_len)`
312
+ position_bias (`torch.Tensor`):
313
+ Provides position information to attention mechanism of shape `(num_heads, seq_len, seq_len)`
314
+ output_attentions (`bool`, *optional*):
315
+ Whether or not to return the attentions tensors of all attention layers.
316
+ past_key_values (`Cache`, *optional*):
317
+ Cached past key and value projection states
318
+ use_cache (`bool`, *optional*):
319
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
320
+ (see `past_key_values`).
321
+ """
322
+ hidden_states, attn_weights = self.self_att(
323
+ hidden_states,
324
+ attention_mask=attention_mask,
325
+ position_bias=position_bias,
326
+ output_attentions=output_attentions,
327
+ past_key_values=past_key_values,
328
+ use_cache=use_cache,
329
+ cache_position=cache_position,
330
+ )
331
+
332
+ hidden_states = self.ffn(hidden_states)
333
+ return hidden_states, attn_weights
334
+
335
+
336
+ class CpmAntEncoder(nn.Module):
337
+ def __init__(self, config: CpmAntConfig):
338
+ super().__init__()
339
+ self.num_layers = config.num_hidden_layers
340
+ self.layers = nn.ModuleList([CpmAntTransformerBlock(config, layer_idx=i) for i in range(self.num_layers)])
341
+
342
+ self.output_layernorm = CpmAntLayerNorm(config)
343
+
344
+ def forward(
345
+ self,
346
+ hidden_states: torch.Tensor,
347
+ attention_mask: torch.Tensor,
348
+ position_bias: torch.Tensor,
349
+ output_attentions: bool | None = None,
350
+ output_hidden_states: bool | None = None,
351
+ past_key_values: Cache | None = None,
352
+ use_cache: bool | None = None,
353
+ cache_position: torch.Tensor | None = None,
354
+ ):
355
+ """
356
+ Args:
357
+ hidden_states (`torch.Tensor`):
358
+ Input to the layer of shape `(batch, seq_len, dim_model)`
359
+ attention_mask (`torch.Tensor`):
360
+ Avoid invalid areas to participate in the calculation of shape `(batch, seq_len, seq_len)`
361
+ position_bias (`torch.Tensor`):
362
+ Provides position information to attention mechanism of shape `(num_heads, seq_len, seq_len)`
363
+ output_attentions (`bool`, *optional*):
364
+ Whether or not to return the attentions tensors of all attention layers.
365
+ output_hidden_states (`bool`, *optional*):
366
+ Whether or not to return the hidden states of all layers.
367
+ past_key_values (`Cache`, *optional*):
368
+ Cached past key and value projection states
369
+ use_cache (`bool`, *optional*):
370
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
371
+ (see `past_key_values`).
372
+ """
373
+ all_hidden_states = () if output_hidden_states else None
374
+ all_self_attns = () if output_attentions else None
375
+
376
+ for i, layer in enumerate(self.layers):
377
+ if output_hidden_states:
378
+ all_hidden_states += (hidden_states,)
379
+ layer_outputs = layer(
380
+ hidden_states,
381
+ attention_mask,
382
+ position_bias,
383
+ output_attentions=output_attentions,
384
+ past_key_values=past_key_values,
385
+ use_cache=use_cache,
386
+ )
387
+ hidden_states, attn_weights = layer_outputs
388
+ if output_attentions:
389
+ all_self_attns += (attn_weights,)
390
+
391
+ hidden_states = self.output_layernorm(hidden_states)
392
+
393
+ if output_hidden_states:
394
+ all_hidden_states += (hidden_states,)
395
+
396
+ return hidden_states, all_hidden_states, all_self_attns
397
+
398
+
399
+ # Copied from transformers.models.bert.modeling_bert.BertIntermediate with Bert->CPMAnt
400
+ class CpmAntIntermediate(nn.Module):
401
+ def __init__(self, config):
402
+ super().__init__()
403
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
404
+ if isinstance(config.hidden_act, str):
405
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
406
+ else:
407
+ self.intermediate_act_fn = config.hidden_act
408
+
409
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
410
+ hidden_states = self.dense(hidden_states)
411
+ hidden_states = self.intermediate_act_fn(hidden_states)
412
+ return hidden_states
413
+
414
+
415
+ class CpmAntSegmentPositionEmbedding(nn.Module):
416
+ def __init__(self, config: CpmAntConfig):
417
+ super().__init__()
418
+
419
+ self.num_heads = config.num_attention_heads
420
+ self.num_buckets = config.position_bias_num_buckets
421
+ self.max_distance = config.position_bias_max_distance
422
+ self.num_segments = config.segment_types
423
+
424
+ self.relative_attention_bias = nn.Parameter(
425
+ torch.empty(
426
+ config.segment_types * config.segment_types + config.position_bias_num_buckets,
427
+ config.num_attention_heads,
428
+ )
429
+ )
430
+
431
+ def forward(
432
+ self,
433
+ key_pos: torch.Tensor,
434
+ query_pos: torch.Tensor,
435
+ key_segment: torch.Tensor,
436
+ query_segment: torch.Tensor,
437
+ ):
438
+ with torch.no_grad():
439
+ batch = key_pos.size(0)
440
+ keylen = key_pos.size(1)
441
+ querylen = query_pos.size(1)
442
+
443
+ if key_pos.size(0) != query_pos.size(0):
444
+ raise AssertionError(
445
+ f"key_pos.size(0) should be equal to query_pos.size(0), but got {key_pos.size(0)} and {query_pos.size(0)}!"
446
+ )
447
+ if keylen != key_segment.size(1) or querylen != query_segment.size(1):
448
+ raise AssertionError(
449
+ f"keylen should be equal to key_segment.size(1), but got {keylen} and {key_segment.size(1)}!"
450
+ )
451
+ if querylen != query_segment.size(1):
452
+ raise AssertionError(
453
+ f"querylen should be equal to query_segment.size(1), but got {querylen} and {query_segment.size(1)}!"
454
+ )
455
+
456
+ key_pos = key_pos.view(batch, -1, keylen)
457
+ query_pos = query_pos.view(batch, querylen, -1)
458
+ key_segment = key_segment.view(batch, -1, keylen)
459
+ query_segment = query_segment.view(batch, querylen, -1)
460
+
461
+ relative_position_bucket = self._segment_relative_position_bucket(query_segment, key_segment)
462
+ relative_position_bucket = relative_position_bucket + self.num_buckets
463
+
464
+ # (batch, len_q, len_k)
465
+ absolute_position_bucket = self._position_bucket(
466
+ torch.arange(keylen, dtype=torch.int32, device=relative_position_bucket.device)[None, :]
467
+ - torch.arange(querylen, dtype=torch.int32, device=relative_position_bucket.device)[:, None],
468
+ num_buckets=self.num_buckets,
469
+ max_distance=self.max_distance,
470
+ )
471
+ relative_position_bucket = torch.where(
472
+ (key_segment == query_segment),
473
+ absolute_position_bucket[None, :, :],
474
+ relative_position_bucket,
475
+ )
476
+
477
+ # (batch, len_q, len_k, num_heads)
478
+ embeds = F.embedding(relative_position_bucket, self.relative_attention_bias)
479
+ # (batch, num_heads, len_q, len_k)
480
+ embeds = embeds.permute(0, 3, 1, 2).contiguous()
481
+ return embeds
482
+
483
+ def _segment_relative_position_bucket(self, query_segment, key_segment):
484
+ return query_segment * self.num_segments + key_segment
485
+
486
+ def _position_bucket(self, relative_position, num_buckets=32, max_distance=128):
487
+ relative_buckets = 0
488
+ # always bidirectional in CPMAnt
489
+ num_buckets //= 2
490
+ relative_buckets = (relative_position > 0).to(torch.int32) * num_buckets
491
+ relative_position = torch.abs(relative_position)
492
+ max_exact = num_buckets // 2
493
+ is_small = relative_position < max_exact
494
+ relative_position_if_large = max_exact + (
495
+ torch.log(relative_position.float() / max_exact)
496
+ / math.log(max_distance / max_exact)
497
+ * (num_buckets - max_exact)
498
+ ).to(torch.int32)
499
+ relative_position_if_large = torch.min(
500
+ relative_position_if_large,
501
+ torch.full_like(relative_position_if_large, num_buckets - 1),
502
+ )
503
+ relative_buckets += torch.where(is_small, relative_position.to(torch.int32), relative_position_if_large)
504
+ return relative_buckets
505
+
506
+
507
+ # Copied from transformers.models.bert.modeling_bert.BertOutput with Bert->CPMAnt
508
+ class CpmAntOutput(nn.Module):
509
+ def __init__(self, config):
510
+ super().__init__()
511
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
512
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
513
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
514
+
515
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
516
+ hidden_states = self.dense(hidden_states)
517
+ hidden_states = self.dropout(hidden_states)
518
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
519
+ return hidden_states
520
+
521
+
522
+ @auto_docstring
523
+ class CpmAntPreTrainedModel(PreTrainedModel):
524
+ config: CpmAntConfig
525
+ base_model_prefix = "cpmant"
526
+
527
+ @torch.no_grad()
528
+ def _init_weights(self, module):
529
+ """Initialize the weights"""
530
+ super()._init_weights(module)
531
+ if isinstance(module, CpmAntLayerNorm):
532
+ init.ones_(module.weight)
533
+ elif isinstance(module, CpmAntSegmentPositionEmbedding):
534
+ init.normal_(module.relative_attention_bias, mean=0.0, std=self.config.init_std)
535
+
536
+
537
+ @auto_docstring
538
+ class CpmAntModel(CpmAntPreTrainedModel):
539
+ def __init__(self, config: CpmAntConfig):
540
+ super().__init__(config)
541
+ self.encoder = CpmAntEncoder(config)
542
+ self.segment_embedding = nn.Embedding(config.segment_types, config.hidden_size)
543
+ self.input_embedding = nn.Embedding(
544
+ config.vocab_size + config.prompt_types * config.prompt_length, config.hidden_size
545
+ )
546
+ self.position_bias = CpmAntSegmentPositionEmbedding(config)
547
+ self.prompt_length = config.prompt_length
548
+ self.vocab_size = config.vocab_size
549
+
550
+ self.post_init()
551
+
552
+ def get_input_embeddings(self):
553
+ return self.input_embedding
554
+
555
+ def set_input_embeddings(self, embeddings, **kwargs):
556
+ self.input_embedding = embeddings
557
+
558
+ def _prepare_attention_mask(self, input_ids, span, context, length):
559
+ batch = input_ids.size(0)
560
+ seqlen = input_ids.size(1)
561
+ device = input_ids.device
562
+ directional_mask_2d = torch.arange(seqlen, device=device) <= torch.arange(seqlen, device=device).view(-1, 1)
563
+ attention_mask = context[:, None, :] | (
564
+ context[:, :, None].logical_not() & directional_mask_2d.view(1, seqlen, seqlen)
565
+ )
566
+ attention_mask = attention_mask & (span[:, None, :] == span[:, :, None])
567
+ # mask for left padding
568
+ mask_1d = (
569
+ torch.tensor(list(range(seqlen - self.prompt_length))[::-1], device=device)[None, :].repeat(batch, 1)
570
+ < length[:, None]
571
+ )
572
+ mask_1d = torch.cat((torch.ones(batch, self.prompt_length, device=device).bool(), mask_1d), dim=1)
573
+ attention_mask = mask_1d.view(batch, seqlen, 1) & mask_1d.view(batch, 1, seqlen) & attention_mask
574
+ return attention_mask
575
+
576
+ @auto_docstring
577
+ def forward(
578
+ self,
579
+ input_ids: torch.Tensor | None = None,
580
+ output_attentions: bool | None = None,
581
+ output_hidden_states: bool | None = None,
582
+ past_key_values: Cache | None = None,
583
+ use_cache: bool | None = None,
584
+ return_dict: bool | None = None,
585
+ cache_position: torch.Tensor | None = None,
586
+ **kwargs,
587
+ ) -> tuple[torch.Tensor] | BaseModelOutputWithPast:
588
+ r"""
589
+ input_ids (`torch.Tensor` of shape `(batch_size, seq_len)`):
590
+ Indices of input sequence tokens in the vocabulary.
591
+
592
+ Indices can be obtained using [`CPMAntTokenizer`]. See [`PreTrainedTokenizer.encode`] and
593
+ [`PreTrainedTokenizer.__call__`] for details.
594
+
595
+ [What are input IDs?](../glossary#input-ids)
596
+ """
597
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
598
+ output_hidden_states = (
599
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
600
+ )
601
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
602
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
603
+
604
+ # add prompts ahead
605
+ if input_ids.dtype != torch.int32:
606
+ input_ids = input_ids.to(torch.int32)
607
+ dtype, device = input_ids.dtype, input_ids.device
608
+ segment = torch.where(input_ids != 0, 2, 0).to(dtype=dtype, device=device)
609
+ length = (segment != 0).sum(-1).to(dtype=dtype, device=device)
610
+ input_ids = torch.cat(
611
+ (
612
+ torch.arange(
613
+ self.prompt_length * 2 + self.vocab_size,
614
+ self.prompt_length * 3 + self.vocab_size,
615
+ dtype=dtype,
616
+ device=device,
617
+ ).repeat(input_ids.size(0), 1),
618
+ input_ids,
619
+ ),
620
+ dim=1,
621
+ )
622
+ batch, seq_length = input_ids.size()
623
+ segment = torch.cat((torch.zeros(batch, self.prompt_length, dtype=dtype, device=device), segment), dim=1)
624
+ context = torch.full((batch, seq_length), 1, dtype=dtype, device=device)
625
+ position = torch.arange(seq_length, dtype=dtype, device=device).repeat(batch, 1)
626
+ span = torch.full((batch, seq_length), 0, dtype=dtype, device=device)
627
+
628
+ if use_cache and past_key_values is None:
629
+ past_key_values = DynamicCache(config=self.config)
630
+
631
+ past_length = past_key_values.get_seq_length() if past_key_values is not None else 0
632
+ input_ids = input_ids.contiguous()
633
+ hidden_states = self.input_embedding(input_ids)
634
+ segment_states = self.segment_embedding(segment)
635
+ if past_length != 0:
636
+ segment_states = segment_states[:, -1:, :]
637
+
638
+ hidden_states = hidden_states + segment_states
639
+
640
+ attention_mask = self._prepare_attention_mask(input_ids, span, context, length)
641
+ position_bias = self.position_bias(position, position, segment, segment)
642
+
643
+ attention_mask = attention_mask[:, past_length:, :]
644
+ position_bias = position_bias[:, :, past_length:, :]
645
+ hidden_states = hidden_states[:, past_length:, :]
646
+
647
+ hidden_states, all_hidden_states, all_attentions = self.encoder(
648
+ hidden_states,
649
+ attention_mask,
650
+ position_bias,
651
+ output_attentions,
652
+ output_hidden_states,
653
+ past_key_values,
654
+ use_cache,
655
+ cache_position,
656
+ )
657
+
658
+ if past_length == 0:
659
+ hidden_states = hidden_states[:, self.prompt_length :, :]
660
+ # drop the prompt
661
+ if all_attentions is not None:
662
+ new_attentions = ()
663
+ for attention in all_attentions:
664
+ new_attentions += (attention[:, :, self.prompt_length :, self.prompt_length :],)
665
+ all_attentions = new_attentions
666
+ if all_hidden_states is not None:
667
+ new_hidden_states = ()
668
+ for hidden_state in all_hidden_states:
669
+ new_hidden_states += (hidden_state[:, self.prompt_length :, :],)
670
+ all_hidden_states = new_hidden_states
671
+
672
+ if not return_dict:
673
+ return tuple(
674
+ v for v in [hidden_states, past_key_values, all_hidden_states, all_attentions] if v is not None
675
+ )
676
+
677
+ return BaseModelOutputWithPast(
678
+ last_hidden_state=hidden_states,
679
+ past_key_values=past_key_values,
680
+ hidden_states=all_hidden_states,
681
+ attentions=all_attentions,
682
+ )
683
+
684
+
685
+ @auto_docstring(
686
+ custom_intro="""
687
+ The CPMAnt Model with a language modeling head on top (linear layer with weights tied to the input embeddings).
688
+ """
689
+ )
690
+ class CpmAntForCausalLM(CpmAntPreTrainedModel, GenerationMixin):
691
+ _tied_weights_keys = {"lm_head.weight": "cpmant.input_embedding.weight"}
692
+
693
+ def __init__(self, config: CpmAntConfig):
694
+ super().__init__(config)
695
+ self.cpmant = CpmAntModel(config)
696
+
697
+ # lm_head.weight is tied to cpmant.input_embedding.weight
698
+ self.lm_head = nn.Linear(
699
+ config.hidden_size, config.vocab_size + config.prompt_types * config.prompt_length, bias=False
700
+ )
701
+ self.post_init()
702
+
703
+ @auto_docstring
704
+ def forward(
705
+ self,
706
+ input_ids: torch.Tensor | None = None,
707
+ past_key_values: Cache | None = None,
708
+ use_cache: bool | None = None,
709
+ output_attentions: bool | None = None,
710
+ output_hidden_states: bool | None = None,
711
+ labels: torch.Tensor | None = None,
712
+ return_dict: bool | None = None,
713
+ attention_mask: torch.Tensor | None = None, # dummy parameter for text-generation pipeline
714
+ cache_position: torch.Tensor | None = None,
715
+ logits_to_keep: int | torch.Tensor = 0,
716
+ **kwargs,
717
+ ) -> tuple | CausalLMOutputWithPast:
718
+ r"""
719
+ input_ids (`torch.Tensor` of shape `(batch_size, seq_len)`):
720
+ Indices of input sequence tokens in the vocabulary.
721
+
722
+ Indices can be obtained using [`CPMAntTokenizer`]. See [`PreTrainedTokenizer.encode`] and
723
+ [`PreTrainedTokenizer.__call__`] for details.
724
+
725
+ [What are input IDs?](../glossary#input-ids)
726
+ labels (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
727
+ Labels for computing the masked language modeling loss.
728
+
729
+ Example:
730
+
731
+ Text Generation with CpmAntForCausalLM.
732
+ ```python
733
+ >>> from transformers import CPMAntTokenizer, CpmAntForCausalLM
734
+
735
+ >>> texts = "今天天气不错,"
736
+ >>> model = CpmAntForCausalLM.from_pretrained("openbmb/cpm-ant-10b")
737
+ >>> tokenizer = CPMAntTokenizer.from_pretrained("openbmb/cpm-ant-10b")
738
+ >>> input_ids = tokenizer(texts, return_tensors="pt")
739
+ >>> outputs = model.generate(**input_ids)
740
+ >>> output_texts = tokenizer.batch_decode(outputs)
741
+ >>> print(output_texts)
742
+ ['今天天气不错,阳光明媚,我和妈妈一起去超市买东西。\n在超市里,我看到了一个很好玩的玩具,它的名字叫“机器人”。它有一个圆圆的脑袋,两只圆圆的眼睛,还有一个圆圆的']
743
+ ```
744
+ """
745
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
746
+
747
+ model_output = self.cpmant(
748
+ input_ids,
749
+ output_attentions,
750
+ output_hidden_states,
751
+ past_key_values,
752
+ use_cache,
753
+ return_dict,
754
+ cache_position,
755
+ )
756
+ hidden_states = model_output.last_hidden_state if return_dict else model_output[0]
757
+ # Only compute necessary logits
758
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
759
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
760
+
761
+ loss = None
762
+ if labels is not None:
763
+ loss_func = CrossEntropyLoss()
764
+ loss = loss_func(logits.view(-1, logits.size(-1)), labels.view(-1))
765
+
766
+ if not return_dict:
767
+ output = (logits,) + model_output[1:]
768
+ return ((loss,) + output) if loss is not None else output
769
+
770
+ return CausalLMOutputWithPast(
771
+ loss=loss,
772
+ logits=logits,
773
+ past_key_values=model_output.past_key_values,
774
+ hidden_states=model_output.hidden_states,
775
+ attentions=model_output.attentions,
776
+ )
777
+
778
+ def get_input_embeddings(self):
779
+ return self.cpmant.input_embedding
780
+
781
+ def set_input_embeddings(self, embeddings):
782
+ self.cpmant.input_embedding = embeddings
783
+
784
+
785
+ __all__ = ["CpmAntForCausalLM", "CpmAntModel", "CpmAntPreTrainedModel"]
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/cpmant/tokenization_cpmant.py ADDED
@@ -0,0 +1,232 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The OpenBMB Team and 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
+ """Tokenization classes for CPMAnt."""
15
+
16
+ import collections
17
+ import os
18
+
19
+ from transformers.utils import is_rjieba_available, requires_backends
20
+
21
+
22
+ if is_rjieba_available():
23
+ import rjieba
24
+
25
+ from ...tokenization_python import PreTrainedTokenizer
26
+ from ...utils import logging
27
+
28
+
29
+ logger = logging.get_logger(__name__)
30
+
31
+ VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt"}
32
+
33
+
34
+ def load_vocab(vocab_file):
35
+ """Loads a vocabulary file into a dictionary."""
36
+ vocab = collections.OrderedDict()
37
+ with open(vocab_file, "r", encoding="utf-8") as reader:
38
+ tokens = reader.readlines()
39
+ for index, token in enumerate(tokens):
40
+ token = token.rstrip("\n")
41
+ vocab[token] = index
42
+ return vocab
43
+
44
+
45
+ class WordpieceTokenizer:
46
+ def __init__(self, vocab, unk_token="<unk>", max_input_chars_per_word=200):
47
+ self.vocab = vocab
48
+ self.unk_token = unk_token
49
+ self.max_input_chars_per_word = max_input_chars_per_word
50
+
51
+ def tokenize(self, token):
52
+ chars = list(token)
53
+ if len(chars) > self.max_input_chars_per_word:
54
+ return [self.unk_token]
55
+
56
+ start = 0
57
+ sub_tokens = []
58
+ while start < len(chars):
59
+ end = len(chars)
60
+ cur_substr = None
61
+ while start < end:
62
+ substr = "".join(chars[start:end])
63
+ if substr in self.vocab:
64
+ cur_substr = substr
65
+ break
66
+ end -= 1
67
+ if cur_substr is None:
68
+ sub_tokens.append(self.unk_token)
69
+ start += 1
70
+ else:
71
+ sub_tokens.append(cur_substr)
72
+ start = end
73
+
74
+ return sub_tokens
75
+
76
+
77
+ class CpmAntTokenizer(PreTrainedTokenizer):
78
+ """
79
+ Construct a CPMAnt tokenizer. Based on byte-level Byte-Pair-Encoding.
80
+
81
+ Args:
82
+ vocab_file (`str`):
83
+ Path to the vocabulary file.
84
+ bod_token (`str`, *optional*, defaults to `"<d>"`):
85
+ The beginning of document token.
86
+ eod_token (`str`, *optional*, defaults to `"</d>"`):
87
+ The end of document token.
88
+ bos_token (`str`, *optional*, defaults to `"<s>"`):
89
+ The beginning of sequence token.
90
+ eos_token (`str`, *optional*, defaults to `"</s>"`):
91
+ The end of sequence token.
92
+ pad_token (`str`, *optional*, defaults to `"<pad>"`):
93
+ The token used for padding.
94
+ unk_token (`str`, *optional*, defaults to `"<unk>"`):
95
+ The unknown token.
96
+ line_token (`str`, *optional*, defaults to `"</n>"`):
97
+ The line token.
98
+ space_token (`str`, *optional*, defaults to `"</_>"`):
99
+ The space token.
100
+ """
101
+
102
+ vocab_files_names = VOCAB_FILES_NAMES
103
+ model_input_names = ["input_ids", "attention_mask"]
104
+ add_prefix_space = False
105
+
106
+ def __init__(
107
+ self,
108
+ vocab_file,
109
+ bod_token="<d>",
110
+ eod_token="</d>",
111
+ bos_token="<s>",
112
+ eos_token="</s>",
113
+ pad_token="<pad>",
114
+ unk_token="<unk>",
115
+ line_token="</n>",
116
+ space_token="</_>",
117
+ padding_side="left",
118
+ **kwargs,
119
+ ):
120
+ requires_backends(self, ["rjieba"])
121
+ self.bod_token = bod_token
122
+ self.eod_token = eod_token
123
+ self.encoder = load_vocab(vocab_file)
124
+ self.encoder[" "] = self.encoder[space_token]
125
+ self.encoder["\n"] = self.encoder[line_token]
126
+
127
+ del self.encoder[space_token]
128
+ del self.encoder[line_token]
129
+
130
+ self.encoder = collections.OrderedDict(sorted(self.encoder.items(), key=lambda x: x[1]))
131
+ self.decoder = {v: k for k, v in self.encoder.items()}
132
+
133
+ self.wordpiece_tokenizer = WordpieceTokenizer(vocab=self.encoder, unk_token=unk_token)
134
+
135
+ super().__init__(
136
+ bod_token=bod_token,
137
+ eod_token=eod_token,
138
+ bos_token=bos_token,
139
+ eos_token=eos_token,
140
+ pad_token=pad_token,
141
+ unk_token=unk_token,
142
+ line_token=line_token,
143
+ space_token=space_token,
144
+ padding_side=padding_side,
145
+ token_type_ids_pattern="all_zeros",
146
+ token_type_ids_include_special_tokens=True,
147
+ special_tokens_pattern="bos",
148
+ **kwargs,
149
+ )
150
+ for special_token in [space_token, line_token]:
151
+ token_id = self.added_tokens_encoder.pop(special_token, None)
152
+ if token_id is not None:
153
+ self._added_tokens_decoder.pop(token_id, None)
154
+ self._update_total_vocab_size()
155
+
156
+ @property
157
+ def bod_token_id(self):
158
+ return self.encoder[self.bod_token]
159
+
160
+ @property
161
+ def eod_token_id(self):
162
+ return self.encoder[self.eod_token]
163
+
164
+ @property
165
+ def newline_id(self):
166
+ return self.encoder["\n"]
167
+
168
+ @property
169
+ def vocab_size(self) -> int:
170
+ return len(self.encoder)
171
+
172
+ def get_vocab(self):
173
+ return dict(self.encoder, **self.added_tokens_encoder)
174
+
175
+ def _tokenize(self, text):
176
+ """Tokenize a string."""
177
+ output_tokens = []
178
+ for x in rjieba.cut(text, False):
179
+ output_tokens.extend(self.wordpiece_tokenizer.tokenize(x))
180
+ return output_tokens
181
+
182
+ def _decode(self, token_ids, **kwargs):
183
+ """Decode ids into a string."""
184
+ token_ids = [i for i in token_ids if i >= 0]
185
+ token_ids = [
186
+ x for x in token_ids if x != self.pad_token_id and x != self.eos_token_id and x != self.bos_token_id
187
+ ]
188
+ return super()._decode(token_ids, **kwargs)
189
+
190
+ def check(self, token):
191
+ return token in self.encoder
192
+
193
+ def convert_tokens_to_string(self, tokens: list[str]) -> str:
194
+ return "".join(tokens)
195
+
196
+ def _convert_token_to_id(self, token):
197
+ """Converts a token (str) in an id using the vocab."""
198
+ return self.encoder.get(token, self.encoder.get(self.unk_token))
199
+
200
+ def _convert_id_to_token(self, index):
201
+ """Converts an index (integer) in a token (str) using the vocab."""
202
+ return self.decoder.get(index, self.unk_token)
203
+
204
+ def save_vocabulary(self, save_directory: str, filename_prefix: str | None = None) -> tuple[str]:
205
+ if os.path.isdir(save_directory):
206
+ vocab_file = os.path.join(
207
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
208
+ )
209
+ else:
210
+ vocab_file = (filename_prefix + "-" if filename_prefix else "") + save_directory
211
+ index = 0
212
+ if " " in self.encoder:
213
+ self.encoder["</_>"] = self.encoder[" "]
214
+ del self.encoder[" "]
215
+ if "\n" in self.encoder:
216
+ self.encoder["</n>"] = self.encoder["\n"]
217
+ del self.encoder["\n"]
218
+ self.encoder = collections.OrderedDict(sorted(self.encoder.items(), key=lambda x: x[1]))
219
+ with open(vocab_file, "w", encoding="utf-8") as writer:
220
+ for token, token_index in self.encoder.items():
221
+ if index != token_index:
222
+ logger.warning(
223
+ f"Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive."
224
+ " Please check that the vocabulary is not corrupted!"
225
+ )
226
+ index = token_index
227
+ writer.write(token + "\n")
228
+ index += 1
229
+ return (vocab_file,)
230
+
231
+
232
+ __all__ = ["CpmAntTokenizer"]
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/csm/__init__.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_csm import *
22
+ from .modeling_csm import *
23
+ from .processing_csm import *
24
+ else:
25
+ import sys
26
+
27
+ _file = globals()["__file__"]
28
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/csm/configuration_csm.py ADDED
@@ -0,0 +1,359 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 Sesame and 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
+
15
+
16
+ from ...configuration_utils import PreTrainedConfig
17
+ from ...modeling_rope_utils import RopeParameters
18
+ from ...utils import logging
19
+ from ..auto.configuration_auto import AutoConfig
20
+
21
+
22
+ logger = logging.get_logger(__name__)
23
+
24
+
25
+ class CsmDepthDecoderConfig(PreTrainedConfig):
26
+ r"""
27
+ This is the configuration class to store the configuration of a [`CsmDepthDecoderModel`]. It is used to instantiate an CSM depth decoder
28
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield
29
+ a similar configuration to that of the csm-1b.
30
+
31
+ e.g. [sesame/csm-1b](https://huggingface.co/sesame/csm-1b)
32
+
33
+ Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the
34
+ documentation from [`PreTrainedConfig`] for more information.
35
+
36
+
37
+ Args:
38
+ num_codebooks (`int`, *optional*, defaults to 32):
39
+ Number of codebooks used in the underlying codec model responsible for tokenizing the audio.
40
+ backbone_hidden_size (`int`, *optional*, defaults to 2048):
41
+ Dimension of the hidden representations of the backbone model used with this depth decoder.
42
+ vocab_size (`int`, *optional*, defaults to 2051):
43
+ Vocabulary size of the CsmDepthDecoder model. Defines the number of different audio tokens that can be represented by each codebook.
44
+ hidden_size (`int`, *optional*, defaults to 1024):
45
+ Dimension of the hidden representations.
46
+ intermediate_size (`int`, *optional*, defaults to 8192):
47
+ Dimension of the MLP representations.
48
+ num_hidden_layers (`int`, *optional*, defaults to 4):
49
+ Number of hidden layers in the Transformer decoder.
50
+ num_attention_heads (`int`, *optional*, defaults to 8):
51
+ Number of attention heads for each attention layer in the Transformer decoder.
52
+ num_key_value_heads (`int`, *optional*, defaults to 2):
53
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
54
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
55
+ `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
56
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
57
+ by meanpooling all the original heads within that group. For more details, check out [this
58
+ paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to
59
+ `num_attention_heads`.
60
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
61
+ The non-linear activation function (function or string) in the decoder.
62
+ max_position_embeddings (`int`, *optional*, defaults to 33):
63
+ The maximum sequence length that this model might ever be used with.
64
+ initializer_range (`float`, *optional*, defaults to 0.02):
65
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
66
+ rms_norm_eps (`float`, *optional*, defaults to 1e-05):
67
+ The epsilon used by the rms normalization layers.
68
+ use_cache (`bool`, *optional*, defaults to `True`):
69
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
70
+ relevant if `config.is_decoder=True`.
71
+ pad_token_id (`int`, *optional*, defaults to 2050):
72
+ Padding token id.
73
+ bos_token_id (`int`, *optional*):
74
+ Beginning of stream token id.
75
+ eos_token_id (`int`, *optional*):
76
+ End of stream token id.
77
+ rope_parameters (`RopeParameters`, *optional*):
78
+ Dictionary containing the configuration parameters for the RoPE embeddings. The dictionary should contain
79
+ a value for `rope_theta` and optionally parameters used for scaling in case you want to use RoPE
80
+ with longer `max_position_embeddings`.
81
+ attention_bias (`bool`, *optional*, defaults to `False`):
82
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
83
+ attention_dropout (`float`, *optional*, defaults to 0.0):
84
+ The dropout ratio for the attention probabilities.
85
+ mlp_bias (`bool`, *optional*, defaults to `False`):
86
+ Whether to use a bias in up_proj, down_proj and gate_proj layers in the MLP layers.
87
+ head_dim (`int`, *optional*):
88
+ The attention head dimension. If None, it will default to hidden_size // num_attention_heads
89
+
90
+ ```python
91
+ >>> from transformers import CsmDepthDecoder, CsmDepthDecoderConfig
92
+
93
+ >>> # Initializing a CsmDepthDecoder
94
+ >>> configuration = CsmDepthDecoderConfig()
95
+ >>> model = CsmDepthDecoderModel(configuration)
96
+
97
+ >>> # Accessing the model configuration
98
+ >>> configuration = model.config
99
+ ```"""
100
+
101
+ model_type = "csm_depth_decoder_model"
102
+ base_config_key = "depth_decoder_config"
103
+ keys_to_ignore_at_inference = ["past_key_values"]
104
+ attribute_map = {
105
+ "codebook_size": "vocab_size",
106
+ }
107
+ default_theta = 500000.0
108
+
109
+ def __init__(
110
+ self,
111
+ num_codebooks: int | None = 32,
112
+ backbone_hidden_size: int | None = 2048,
113
+ vocab_size: int | None = 2051,
114
+ hidden_size: int | None = 1024,
115
+ intermediate_size: int | None = 8192,
116
+ num_hidden_layers: int | None = 4,
117
+ num_attention_heads: int | None = 8,
118
+ num_key_value_heads: int | None = 2,
119
+ hidden_act: int | None = "silu",
120
+ max_position_embeddings: int | None = 33,
121
+ initializer_range: float | None = 0.02,
122
+ rms_norm_eps: int | None = 1e-5,
123
+ use_cache: bool | None = True,
124
+ pad_token_id: int | None = None,
125
+ bos_token_id: int | None = None,
126
+ eos_token_id: int | None = None,
127
+ rope_parameters: RopeParameters | dict[str, RopeParameters] | None = None,
128
+ attention_bias: bool | None = False,
129
+ attention_dropout: float | None = 0.0,
130
+ mlp_bias: bool | None = False,
131
+ head_dim: int | None = None,
132
+ **kwargs,
133
+ ):
134
+ if kwargs.pop("tie_word_embeddings", False):
135
+ raise ValueError("`tie_word_embeddings=True` is not supported for CsmDepthDecoderConfig")
136
+
137
+ self.pad_token_id = pad_token_id
138
+ self.bos_token_id = bos_token_id
139
+ self.eos_token_id = eos_token_id
140
+ self.num_codebooks = num_codebooks
141
+ self.vocab_size = vocab_size
142
+ self.backbone_hidden_size = backbone_hidden_size
143
+ self.max_position_embeddings = max_position_embeddings
144
+ self.hidden_size = hidden_size
145
+ self.intermediate_size = intermediate_size
146
+ self.num_hidden_layers = num_hidden_layers
147
+ self.num_attention_heads = num_attention_heads
148
+
149
+ # for backward compatibility
150
+ if num_key_value_heads is None:
151
+ num_key_value_heads = num_attention_heads
152
+
153
+ self.num_key_value_heads = num_key_value_heads
154
+ self.hidden_act = hidden_act
155
+ self.initializer_range = initializer_range
156
+ self.rms_norm_eps = rms_norm_eps
157
+ self.use_cache = use_cache
158
+ self.attention_bias = attention_bias
159
+ self.attention_dropout = attention_dropout
160
+ self.mlp_bias = mlp_bias
161
+ self.head_dim = head_dim if head_dim is not None else self.hidden_size // self.num_attention_heads
162
+ self.rope_parameters = rope_parameters
163
+ super().__init__(**kwargs)
164
+
165
+
166
+ class CsmConfig(PreTrainedConfig):
167
+ r"""
168
+ This is the configuration class to store the configuration of a [`CsmForConditionalGeneration`]. It is used to instantiate an CSM
169
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration
170
+ with the defaults will yield a similar configuration to that of the csm-1b.
171
+
172
+ e.g. [sesame/csm-1b](https://huggingface.co/sesame/csm-1b)
173
+
174
+ Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the
175
+ documentation from [`PreTrainedConfig`] for more information.
176
+
177
+ Args:
178
+ num_codebooks (`int`, *optional*, defaults to 32):
179
+ Number of codebooks used in the underlying codec model responsible for tokenizing the audio.
180
+ vocab_size (`int`, *optional*, defaults to 2051):
181
+ Vocabulary size of the Csm model. Defines the number of different audio tokens that can be represented by each codebook.
182
+ text_vocab_size (`int`, *optional*, defaults to 128256):
183
+ Vocabulary size of the text input for the Csm model. Defines the number of different text tokens that can be represented.
184
+ hidden_size (`int`, *optional*, defaults to 2048):
185
+ Dimension of the hidden representations of the backbone model.
186
+ intermediate_size (`int`, *optional*, defaults to 8192):
187
+ Dimension of the MLP representations of the backbone model.
188
+ num_hidden_layers (`int`, *optional*, defaults to 16):
189
+ Number of hidden layers in the backbone model Transformer decoder.
190
+ num_attention_heads (`int`, *optional*, defaults to 32):
191
+ Number of attention heads for each attention layer in the backbone model Transformer decoder.
192
+ num_key_value_heads (`int`, *optional*, defaults to 8):
193
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
194
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
195
+ `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
196
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
197
+ by meanpooling all the original heads within that group. For more details, check out [this
198
+ paper](https://huggingface.co/papers/2305.13245).
199
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
200
+ The non-linear activation function (function or string) in the backbone model Transformer decoder.
201
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
202
+ The maximum sequence length that this model might ever be used with.
203
+ initializer_range (`float`, *optional*, defaults to 0.02):
204
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
205
+ rms_norm_eps (`float`, *optional*, defaults to 1e-05):
206
+ The epsilon used by the rms normalization layers.
207
+ use_cache (`bool`, *optional*, defaults to `True`):
208
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
209
+ relevant if `config.is_decoder=True`.
210
+ pad_token_id (`int`, *optional*, defaults to 128002):
211
+ Padding token id.
212
+ codebook_pad_token_id (`int`, *optional*, defaults to 2050):
213
+ Padding token id for codebook tokens.
214
+ codebook_eos_token_id (`int`, *optional*, defaults to 0):
215
+ End of stream token id for codebook tokens.
216
+ bos_token_id (`int`, *optional*, defaults to 128000):
217
+ Beginning of stream token id.
218
+ eos_token_id (`int`, *optional*):
219
+ End of stream token id.
220
+ audio_token_id (`int`, *optional*, defaults to 128002):
221
+ Audio token id in the text input.
222
+ audio_eos_token_id (`int`, *optional*, defaults to 128003):
223
+ End of stream token id for audio in the text input.
224
+ rope_parameters (`RopeParameters`, *optional*):
225
+ Dictionary containing the configuration parameters for the RoPE embeddings. The dictionary should contain
226
+ a value for `rope_theta` and optionally parameters used for scaling in case you want to use RoPE
227
+ with longer `max_position_embeddings`.
228
+ attention_bias (`bool`, *optional*, defaults to `False`):
229
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
230
+ attention_dropout (`float`, *optional*, defaults to 0.0):
231
+ The dropout ratio for the attention probabilities.
232
+ mlp_bias (`bool`, *optional*, defaults to `False`):
233
+ Whether to use a bias in up_proj, down_proj and gate_proj layers in the MLP layers.
234
+ head_dim (`int`, *optional*):
235
+ The attention head dimension. If None, it will default to hidden_size // num_attention_heads
236
+ tie_codebooks_embeddings (`bool`, *optional*, defaults to `True`):
237
+ Whether to tie the codebook tokens embeddings of the backbone model to the codebook tokens embeddings of the depth decoder.
238
+ depth_decoder_config (`CsmDepthDecoderConfig`, *optional*):
239
+ Configuration for the depth decoder.
240
+ codec_config (`PreTrainedConfig`, *optional*):
241
+ Configuration for the codec.
242
+
243
+ ```python
244
+ >>> from transformers import CsmForConditionalGeneration, CsmConfig
245
+
246
+ >>> # Initializing a CsmConfig
247
+ >>> configuration = CsmConfig()
248
+
249
+ >>> # Initializing a model
250
+ >>> model = CsmForConditionalGeneration(configuration)
251
+
252
+ >>> # Accessing the model configuration
253
+ >>> configuration = model.config
254
+ ```"""
255
+
256
+ model_type = "csm"
257
+ base_config_key = "csm_config"
258
+ keys_to_ignore_at_inference = ["past_key_values"]
259
+ default_theta = 500000.0
260
+ sub_configs = {
261
+ "codec_config": AutoConfig,
262
+ "depth_decoder_config": CsmDepthDecoderConfig,
263
+ }
264
+ attribute_map = {
265
+ "codebook_size": "vocab_size",
266
+ }
267
+
268
+ def __init__(
269
+ self,
270
+ num_codebooks: int | None = 32,
271
+ vocab_size: int | None = 2051,
272
+ text_vocab_size: int | None = 128256,
273
+ hidden_size: int | None = 2048,
274
+ intermediate_size: int | None = 8192,
275
+ num_hidden_layers: int | None = 16,
276
+ num_attention_heads: int | None = 32,
277
+ num_key_value_heads: int | None = 8,
278
+ hidden_act: str | None = "silu",
279
+ max_position_embeddings: int | None = 2048,
280
+ initializer_range: float | None = 0.02,
281
+ rms_norm_eps: int | None = 1e-5,
282
+ use_cache: bool | None = True,
283
+ pad_token_id: int | None = 128002,
284
+ codebook_pad_token_id: int | None = 2050,
285
+ codebook_eos_token_id: int | None = 0,
286
+ bos_token_id: int | None = 128000,
287
+ eos_token_id: int | None = None,
288
+ audio_token_id: int | None = 128002,
289
+ audio_eos_token_id: int | None = 128003,
290
+ rope_parameters: RopeParameters | dict[str, RopeParameters] | None = None,
291
+ attention_bias: bool | None = False,
292
+ attention_dropout: float | None = 0.0,
293
+ mlp_bias: bool | None = False,
294
+ head_dim: int | None = None,
295
+ tie_codebooks_embeddings: bool | None = True,
296
+ depth_decoder_config: dict | None = None,
297
+ codec_config: dict | None = None,
298
+ **kwargs,
299
+ ):
300
+ if kwargs.pop("tie_word_embeddings", False):
301
+ raise ValueError("`tie_word_embeddings=True` is not supported for CsmConfig")
302
+
303
+ if depth_decoder_config is None:
304
+ self.depth_decoder_config = CsmDepthDecoderConfig()
305
+ logger.info("depth_decoder_config is None, using default depth decoder config.")
306
+ elif isinstance(depth_decoder_config, dict):
307
+ self.depth_decoder_config = CsmDepthDecoderConfig(**depth_decoder_config)
308
+ elif isinstance(depth_decoder_config, CsmDepthDecoderConfig):
309
+ self.depth_decoder_config = depth_decoder_config
310
+
311
+ if codec_config is None:
312
+ self.codec_config = AutoConfig.for_model("mimi")
313
+ logger.info("codec_config is None, using default audio encoder config.")
314
+ elif isinstance(codec_config, dict):
315
+ self.codec_config = AutoConfig.for_model(**codec_config)
316
+ elif isinstance(codec_config, PreTrainedConfig):
317
+ self.codec_config = codec_config
318
+
319
+ self.text_vocab_size = text_vocab_size
320
+ self.num_codebooks = num_codebooks
321
+ self.audio_token_id = audio_token_id
322
+ self.audio_eos_token_id = audio_eos_token_id
323
+ self.codebook_pad_token_id = codebook_pad_token_id
324
+ self.codebook_eos_token_id = codebook_eos_token_id
325
+ self.tie_codebooks_embeddings = tie_codebooks_embeddings
326
+
327
+ self.vocab_size = vocab_size
328
+ self.max_position_embeddings = max_position_embeddings
329
+ self.hidden_size = hidden_size
330
+ self.intermediate_size = intermediate_size
331
+ self.num_hidden_layers = num_hidden_layers
332
+ self.num_attention_heads = num_attention_heads
333
+
334
+ # for backward compatibility
335
+ if num_key_value_heads is None:
336
+ num_key_value_heads = num_attention_heads
337
+
338
+ self.num_key_value_heads = num_key_value_heads
339
+ self.hidden_act = hidden_act
340
+ self.initializer_range = initializer_range
341
+ self.rms_norm_eps = rms_norm_eps
342
+ self.use_cache = use_cache
343
+ self.attention_bias = attention_bias
344
+ self.attention_dropout = attention_dropout
345
+ self.mlp_bias = mlp_bias
346
+ self.head_dim = head_dim if head_dim is not None else self.hidden_size // self.num_attention_heads
347
+ self.rope_parameters = rope_parameters
348
+
349
+ self.pad_token_id = pad_token_id
350
+ self.bos_token_id = bos_token_id
351
+ self.eos_token_id = eos_token_id
352
+ self.tie_word_embeddings = False
353
+ super().__init__(**kwargs)
354
+
355
+
356
+ __all__ = [
357
+ "CsmDepthDecoderConfig",
358
+ "CsmConfig",
359
+ ]
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/csm/generation_csm.py ADDED
@@ -0,0 +1,488 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 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
+
15
+ from dataclasses import dataclass
16
+ from typing import TYPE_CHECKING, Any, Optional
17
+
18
+ import torch
19
+ import torch.nn as nn
20
+
21
+ from ...generation import (
22
+ GenerateDecoderOnlyOutput,
23
+ GenerationConfig,
24
+ GenerationMixin,
25
+ GenerationMode,
26
+ )
27
+ from ...generation.logits_process import LogitsProcessorList
28
+ from ...generation.stopping_criteria import MaxLengthCriteria, StoppingCriteriaList
29
+ from ...generation.utils import GenerateNonBeamOutput
30
+ from ...utils import logging
31
+
32
+
33
+ if TYPE_CHECKING:
34
+ from ...generation.streamers import BaseStreamer
35
+
36
+
37
+ logger = logging.get_logger(__name__)
38
+
39
+
40
+ @dataclass
41
+ class CsmGenerateOutput(GenerateDecoderOnlyOutput):
42
+ """
43
+ Outputs of CsmForConditionalGeneration.generate.
44
+
45
+ Args:
46
+ sequences (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
47
+ The generated sequences. The second dimension (sequence_length) is either equal to `max_length` or shorter
48
+ if all batches finished early due to the `eos_token_id`.
49
+ scores (`tuple(torch.FloatTensor)` *optional*, returned when `output_scores=True`):
50
+ Processed prediction scores of the language modeling head (scores for each vocabulary token before SoftMax)
51
+ at each generation step. Tuple of `torch.FloatTensor` with up to `max_new_tokens` elements (one element for
52
+ each generated token), with each tensor of shape `(batch_size, config.vocab_size)`.
53
+ logits (`tuple(torch.FloatTensor)` *optional*, returned when `output_logits=True`):
54
+ Unprocessed prediction scores of the language modeling head (scores for each vocabulary token before SoftMax)
55
+ at each generation step. Tuple of `torch.FloatTensor` with up to `max_new_tokens` elements (one element for
56
+ each generated token), with each tensor of shape `(batch_size, config.vocab_size)`.
57
+ attentions (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_attentions=True`):
58
+ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
59
+ `torch.FloatTensor` of shape `(batch_size, num_heads, generated_length, sequence_length)`.
60
+ hidden_states (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_hidden_states=True`):
61
+ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
62
+ `torch.FloatTensor` of shape `(batch_size, generated_length, hidden_size)`.
63
+ past_key_values (`Cache`, *optional*, returned when `use_cache=True`):
64
+ Returns the model cache, used to speed up decoding. Different models have a different cache format, check
65
+ audio (`list(torch.FloatTensor)` of length `batch_size`):
66
+ The generated audio.
67
+ """
68
+
69
+ audio: list[torch.Tensor] | None = None
70
+
71
+
72
+ class CsmGenerationMixin(GenerationMixin):
73
+ def _get_stopping_criteria(
74
+ self,
75
+ *args,
76
+ **kwargs,
77
+ ) -> StoppingCriteriaList:
78
+ criteria = super()._get_stopping_criteria(*args, **kwargs)
79
+
80
+ kept_criteria = StoppingCriteriaList()
81
+ for criterion in criteria:
82
+ if not isinstance(criterion, MaxLengthCriteria):
83
+ logger.warning(
84
+ f"Csm does not support {criterion.__class__.__name__} stopping criteria, it will be ignored."
85
+ )
86
+ else:
87
+ kept_criteria.append(criterion)
88
+ return kept_criteria
89
+
90
+ def _prepare_generation_config(
91
+ self, generation_config: GenerationConfig | None, **kwargs: Any
92
+ ) -> tuple[GenerationConfig, dict]:
93
+ """
94
+ This method overrides [~generation.utils.GenerationMixin._prepare_generation_config].
95
+ It ensures that the depth decoder generation config is initialized and that passed args as depth_decoder_* are properly handled.
96
+ """
97
+ # extract depth decoder kwargs and remove them from the main kwargs
98
+ depth_decoder_kwargs = {
99
+ k[len("depth_decoder_") :]: v for k, v in kwargs.items() if k.startswith("depth_decoder_")
100
+ }
101
+
102
+ # remove the depth decoder keys from the original kwargs
103
+ kwargs = {k: v for k, v in kwargs.items() if not k.startswith("depth_decoder_")}
104
+
105
+ # initialize the generation config
106
+ generation_config, model_kwargs = super()._prepare_generation_config(generation_config, **kwargs)
107
+ self.depth_decoder.generation_config.update(**depth_decoder_kwargs)
108
+
109
+ # ensure the depth decoder generation config is valid
110
+ depth_decoder_min_new_tokens = getattr(self.depth_decoder.generation_config, "min_new_tokens") or (
111
+ self.config.num_codebooks - 1
112
+ )
113
+ depth_decoder_max_new_tokens = getattr(self.depth_decoder.generation_config, "max_new_tokens") or (
114
+ self.config.num_codebooks - 1
115
+ )
116
+
117
+ if {depth_decoder_min_new_tokens, depth_decoder_max_new_tokens} != {self.config.num_codebooks - 1}:
118
+ raise ValueError(
119
+ f"depth_decoder_generation_config's min_new_tokens ({depth_decoder_min_new_tokens}) and max_new_tokens ({depth_decoder_max_new_tokens}) must be equal to self.config.num_codebooks - 1 ({self.config.num_codebooks - 1})"
120
+ )
121
+ elif self.depth_decoder.generation_config.return_dict_in_generate:
122
+ logger.warning(
123
+ "depth_decoder_generation_config.return_dict_in_generate is set to True, but this will be ignored as the depth decoder model does not return a dictionary in generate"
124
+ )
125
+ self.depth_decoder.generation_config.return_dict_in_generate = False
126
+
127
+ self.depth_decoder.generation_config.min_new_tokens = depth_decoder_min_new_tokens
128
+ self.depth_decoder.generation_config.max_new_tokens = depth_decoder_max_new_tokens
129
+
130
+ # Monkey patch the get_generation_mode method to support CSM model
131
+ original_get_generation_mode = generation_config.get_generation_mode
132
+
133
+ def patched_get_generation_mode(assistant_model=None):
134
+ generation_mode = original_get_generation_mode(assistant_model)
135
+ if generation_mode not in [GenerationMode.GREEDY_SEARCH, GenerationMode.SAMPLE]:
136
+ raise ValueError(
137
+ f"Generation mode {generation_mode} is not supported for CSM model. Please set generation parameters to use greedy or sampling generation."
138
+ )
139
+
140
+ return generation_mode
141
+
142
+ generation_config.get_generation_mode = patched_get_generation_mode
143
+
144
+ return generation_config, model_kwargs
145
+
146
+ def _sample(
147
+ self,
148
+ input_ids: torch.LongTensor,
149
+ logits_processor: LogitsProcessorList,
150
+ stopping_criteria: StoppingCriteriaList,
151
+ generation_config: GenerationConfig,
152
+ synced_gpus: bool = False,
153
+ streamer: Optional["BaseStreamer"] = None,
154
+ **model_kwargs,
155
+ ) -> GenerateNonBeamOutput | torch.LongTensor:
156
+ """
157
+ This method overrides [~generation.utils.GenerationMixin._sample].
158
+ To ease maintenance, modifications are marked with the comment "Csm specific".
159
+
160
+ Indeed, Csm model requires a custom generation sampling step:
161
+ 1. Infer the backbone model to sample the first codebook token
162
+ 2. Call generate on the depth decoder with the first codebook token as input_ids to sample the next codebook tokens
163
+ 3. Use these generated codebook tokens as input_ids to sample the next first codebook token using the backbone model
164
+ 4. Repeat until stopping criteria is met
165
+
166
+ Csm supports two stopping criteria:
167
+ - stop when the generated sequence is at max_length
168
+ - stop when all the generated codebook tokens are the codebook_eos_token_id
169
+ """
170
+ # init values
171
+ # *************** Csm specific ***************
172
+ pad_token_id = self.config.codebook_pad_token_id
173
+ has_eos_stopping_criteria = generation_config._eos_token_tensor is not None
174
+ # ============================================
175
+ output_attentions = generation_config.output_attentions
176
+ output_hidden_states = generation_config.output_hidden_states
177
+ output_scores = generation_config.output_scores
178
+ output_logits = generation_config.output_logits
179
+ return_dict_in_generate = generation_config.return_dict_in_generate
180
+ do_sample = generation_config.do_sample
181
+
182
+ # init attention / hidden states / scores tuples
183
+ scores = () if (return_dict_in_generate and output_scores) else None
184
+ raw_logits = () if (return_dict_in_generate and output_logits) else None
185
+ decoder_attentions = () if (return_dict_in_generate and output_attentions) else None
186
+ decoder_hidden_states = () if (return_dict_in_generate and output_hidden_states) else None
187
+
188
+ # keep track of which sequences are already finished
189
+ batch_size, cur_len = input_ids.shape[:2]
190
+ this_peer_finished = False
191
+ unfinished_sequences = torch.ones(batch_size, dtype=torch.long, device=input_ids.device)
192
+ model_kwargs = self._get_initial_cache_position(cur_len, input_ids.device, model_kwargs)
193
+
194
+ # *************** Csm specific ***************
195
+ if input_ids.ndim == 2 and model_kwargs.get("inputs_embeds") is None:
196
+ # in the case where the passed input_ids correspond to text tokens, i.e. don't have a third dimension for codebook ids,
197
+ # we need to remove the input length to the MaxLengthCriteria stopping criteria has such input are not returned
198
+ for criterion in stopping_criteria:
199
+ if isinstance(criterion, MaxLengthCriteria):
200
+ criterion.max_length -= cur_len
201
+ # ============================================
202
+
203
+ model_forward = (
204
+ self.get_compiled_call(generation_config.compile_config)
205
+ if self._valid_auto_compile_criteria(model_kwargs, generation_config)
206
+ else self.__call__
207
+ )
208
+
209
+ # *************** Csm specific ***************
210
+ model_kwargs.update({"output_hidden_states": True})
211
+
212
+ prefill_consumed = False
213
+ outputs = self._prefill(
214
+ input_ids,
215
+ generation_config,
216
+ model_kwargs,
217
+ is_first_iteration=not generation_config.is_assistant,
218
+ )
219
+
220
+ while self._has_unfinished_sequences(this_peer_finished, synced_gpus, device=input_ids.device):
221
+ if prefill_consumed:
222
+ next_sequence_length = 1 if model_kwargs["use_cache"] else None
223
+ model_inputs = self.prepare_inputs_for_generation(
224
+ input_ids, next_sequence_length=next_sequence_length, **model_kwargs
225
+ )
226
+ # prepare variable output controls (note: some models won't accept all output controls)
227
+ model_inputs.update({"output_attentions": output_attentions} if output_attentions else {})
228
+ outputs = model_forward(**model_inputs, return_dict=True)
229
+ prefill_consumed = True
230
+
231
+ # synced_gpus: don't waste resources running the code we don't need; kwargs must be updated before skipping
232
+ model_kwargs = self._update_model_kwargs_for_generation(
233
+ outputs,
234
+ model_kwargs,
235
+ )
236
+ if synced_gpus and this_peer_finished:
237
+ continue
238
+
239
+ # Clone is needed to avoid keeping a hanging ref to outputs.logits which may be very large for first iteration
240
+ # (the clone itself is always small)
241
+ next_token_logits = outputs.logits[:, -1, :].clone().float()
242
+ next_token_logits = next_token_logits.to(input_ids.device)
243
+
244
+ # pre-process distribution
245
+ next_token_scores = logits_processor(input_ids, next_token_logits)
246
+
247
+ # Store scores, attentions and hidden_states when required
248
+ if return_dict_in_generate:
249
+ if output_scores:
250
+ scores += (next_token_scores,)
251
+ if output_logits:
252
+ raw_logits += (next_token_logits,)
253
+ if output_attentions:
254
+ decoder_attentions += (outputs.attentions,)
255
+
256
+ if output_hidden_states:
257
+ decoder_hidden_states += (outputs.hidden_states,)
258
+
259
+ # token selection
260
+ if do_sample:
261
+ probs = nn.functional.softmax(next_token_scores, dim=-1)
262
+ # TODO (joao): this OP throws "skipping cudagraphs due to ['incompatible ops']", find solution
263
+ next_tokens = torch.multinomial(probs, num_samples=1).squeeze(1)
264
+ else:
265
+ next_tokens = torch.argmax(next_token_scores, dim=-1)
266
+
267
+ # *************** Csm specific ***************
268
+ # infer the depth decoder
269
+ first_codebook_ids = next_tokens[:, None]
270
+ # adds place holder in position 0 that will be replaced by the backbone_last_hidden_state
271
+ depth_decoder_input_ids = nn.functional.pad(first_codebook_ids, (1, 0), value=0)
272
+ backbone_last_hidden_state = outputs.hidden_states[-1][:, -1, :]
273
+
274
+ depth_decoder_outputs = self.depth_decoder.generate(
275
+ input_ids=depth_decoder_input_ids, backbone_last_hidden_state=backbone_last_hidden_state.clone()
276
+ )
277
+ codebook_ids = (
278
+ depth_decoder_outputs
279
+ if isinstance(depth_decoder_outputs, torch.Tensor)
280
+ else depth_decoder_outputs.sequences
281
+ )
282
+ # remove the place holder in position 0
283
+ codebook_ids = codebook_ids[:, 1:]
284
+ next_tokens = codebook_ids
285
+
286
+ # finished sentences should have their next token be a padding token
287
+ if has_eos_stopping_criteria:
288
+ next_tokens = next_tokens * unfinished_sequences.unsqueeze(-1) + pad_token_id * (
289
+ 1 - unfinished_sequences.unsqueeze(-1)
290
+ )
291
+
292
+ # update generated ids, model inputs, and length for next step
293
+ if input_ids.ndim == 2:
294
+ input_ids = next_tokens[:, None, :]
295
+ else:
296
+ input_ids = torch.cat([input_ids, next_tokens[:, None, :]], dim=1)
297
+ # ============================================
298
+
299
+ if streamer is not None:
300
+ streamer.put(next_tokens.cpu())
301
+
302
+ # *************** Csm specific ***************
303
+ # for the eos stopping criteria, is it expected that the eos token is the same for each codebook !!!!
304
+ unfinished_sequences = unfinished_sequences & ~(
305
+ input_ids[:, -1, :-1] == self.config.codebook_eos_token_id
306
+ ).all(-1)
307
+ # ============================================
308
+ unfinished_sequences = unfinished_sequences & ~stopping_criteria(input_ids, scores)
309
+ this_peer_finished = unfinished_sequences.max() == 0
310
+ cur_len += 1
311
+
312
+ # This is needed to properly delete outputs.logits which may be very large for first iteration
313
+ # Otherwise a reference to outputs is kept which keeps the logits alive in the next iteration
314
+ del outputs
315
+
316
+ # *************** Csm specific ***************
317
+ del depth_decoder_outputs
318
+ # ============================================
319
+
320
+ if streamer is not None:
321
+ streamer.end()
322
+
323
+ if return_dict_in_generate:
324
+ return GenerateDecoderOnlyOutput(
325
+ sequences=input_ids,
326
+ scores=scores,
327
+ logits=raw_logits,
328
+ attentions=decoder_attentions,
329
+ hidden_states=decoder_hidden_states,
330
+ past_key_values=model_kwargs.get("past_key_values"),
331
+ )
332
+ else:
333
+ return input_ids
334
+
335
+ def generate(
336
+ self,
337
+ input_ids: torch.Tensor | None = None,
338
+ input_values: torch.Tensor | None = None,
339
+ input_values_cutoffs: torch.Tensor | None = None,
340
+ generation_config: GenerationConfig | None = None,
341
+ logits_processor: LogitsProcessorList | None = None,
342
+ stopping_criteria: StoppingCriteriaList | None = None,
343
+ synced_gpus: bool | None = None,
344
+ streamer: Optional["BaseStreamer"] = None,
345
+ output_audio: bool | None = False,
346
+ **kwargs,
347
+ ) -> GenerateNonBeamOutput | torch.LongTensor:
348
+ r"""
349
+ This method overrides [`~generation.utils.GenerationMixin.generate`] to match the specifics of the Csm model.
350
+ Indeed, Csm model requires a custom generation sampling step:
351
+ 1. Infer the backbone model to sample the first codebook token
352
+ 2. Call generate on the depth decoder with the first codebook token as `input_ids` to sample the next codebook tokens
353
+ 3. Use these generated codebook tokens as `input_ids` to sample the next first codebook token using the backbone model
354
+ 4. Repeat until stopping criteria is met
355
+
356
+ <Tip warning={true}>
357
+
358
+ Most generation-controlling parameters are set in `generation_config` which, if not passed, will be set to the
359
+ model's default generation configuration. You can override any `generation_config` by passing the corresponding
360
+ parameters to generate(), e.g. `.generate(inputs, do_sample=True)`.
361
+ </Tip>
362
+
363
+ Parameters:
364
+ inputs_ids (`torch.Tensor` of shape (batch_size, seq_length), *optional*):
365
+ The sequence used as a prompt for the backbone model.
366
+ input_values (`torch.Tensor` of shape (batch_size, channels, max_concatenated_audio_length), *optional*):
367
+ The batched audio input values, where each batch entry contains the concatenation of all audio segments for that entry.
368
+ These values will be encoded into codebook tokens using the codec model and merged with the text input ids provided in `input_ids`.
369
+ input_values_cutoffs (`torch.Tensor` of shape (batch_size, max_num_audio), *optional*):
370
+ Specify the end positions of audio segments within each batch entry, relative to the concatenated audio input.
371
+ If a batch entry has fewer segments than the maximum, it is padded with -1. For example, in a batch of 2 sequences
372
+ where the first contains 2 audio segments of length l1, and the second contains 1 audio segment of length l2,
373
+ the input_values_cutoffs would be: [[l1, 2 * l1], [l2, -1]].
374
+ generation_config ([`~generation.GenerationConfig`], *optional*):
375
+ The generation configuration to be used as base parametrization for the generation call. `**kwargs`
376
+ passed to generate matching the attributes of `generation_config` will override them. If
377
+ `generation_config` is not provided, the default will be used, which has the following loading
378
+ priority: 1) from the `generation_config.json` model file, if it exists; 2) from the model
379
+ configuration. Please note that unspecified parameters will inherit [`~generation.GenerationConfig`]'s
380
+ default values, whose documentation should be checked to parameterize generation.
381
+ logits_processor (`LogitsProcessorList`, *optional*):
382
+ Custom logits processors that complement the default logits processors built from arguments and
383
+ generation config. If a logit processor is passed that is already created with the arguments or a
384
+ generation config an error is thrown. This feature is intended for advanced users.
385
+ stopping_criteria (`StoppingCriteriaList`, *optional*):
386
+ Custom stopping criteria that complements the default stopping criteria built from arguments and a
387
+ generation config. If a stopping criteria is passed that is already created with the arguments or a
388
+ generation config an error is thrown. If your stopping criteria depends on the `scores` input, make
389
+ sure you pass `return_dict_in_generate=True, output_scores=True` to `generate`. This feature is
390
+ intended for advanced users.
391
+ synced_gpus (`bool`, *optional*):
392
+ Whether to continue running the while loop until max_length. Unless overridden, this flag will be set
393
+ to `True` if using `FullyShardedDataParallel` or DeepSpeed ZeRO Stage 3 with multiple GPUs to avoid
394
+ deadlocking if one GPU finishes generating before other GPUs. Otherwise, defaults to `False`.
395
+ streamer (`BaseStreamer`, *optional*):
396
+ Streamer object that will be used to stream the generated sequences. Generated tokens are passed
397
+ through `streamer.put(token_ids)` and the streamer is responsible for any further processing.
398
+ output_audio (`bool`, *optional*):
399
+ Whether to return the generated audio.
400
+ kwargs (`dict[str, Any]`, *optional*):
401
+ Ad hoc parametrization of `generation_config` and/or additional model-specific kwargs that will be
402
+ forwarded to the `forward` function of the model. Depth decoder specific kwargs should be prefixed with *depth_decoder_*.
403
+
404
+ Return:
405
+ [`CsmGenerateOutput`] or `torch.LongTensor` or `list[torch.FloatTensor]`: A [`CsmGenerateOutput`]
406
+ (if `return_dict_in_generate=True` or when `config.return_dict_in_generate=True`) or a `torch.LongTensor` when `output_audio=False`
407
+ or a `list[torch.FloatTensor]` otherwise.
408
+
409
+ Example:
410
+
411
+ ```python
412
+ >>> from transformers import CsmProcessor, CsmForConditionalGeneration
413
+ >>> from datasets import load_dataset, Audio
414
+
415
+ >>> model_id = "sesame/csm-1b"
416
+ >>> torch_device = "cuda" if torch.cuda.is_available() else "cpu"
417
+
418
+ >>> processor = AutoProcessor.from_pretrained(model_id)
419
+
420
+ >>> ds = load_dataset("hf-internal-testing/dailytalk-dummy", split="train")
421
+ >>> # ensure the audio is 24kHz
422
+ >>> ds = ds.cast_column("audio", Audio(sampling_rate=24000))
423
+
424
+ >>> conversation = []
425
+ >>> # prepare a conversation with text and corresponding audio
426
+ >>> for text, audio, speaker_id in zip(ds[:4]["text"], ds[:4]["audio"], ds[:4]["speaker_id"]):
427
+ ... conversation.append(
428
+ ... {
429
+ ... "role": f"{speaker_id}",
430
+ ... "content": [{"type": "text", "text": text}, {"type": "audio", "path": audio["array"]}],
431
+ ... }
432
+ ... )
433
+
434
+ >>> # text prompt
435
+ >>> conversation.append({"role": f"{ds[4]['speaker_id']}", "content": [{"type": "text", "text": ds[4]["text"]}]})
436
+
437
+ >>> inputs = processor.apply_chat_template(
438
+ ... conversation,
439
+ ... tokenize=True,
440
+ ... return_dict=True,
441
+ ... ).to(torch_device)
442
+
443
+ >>> model = CsmForConditionalGeneration.from_pretrained(model_id, device_map=torch_device)
444
+ >>> audio = model.generate(**inputs, output_audio=True)
445
+ >>> processor.save_audio(audio, "output.wav")
446
+ ```
447
+ """
448
+ generate_output = super().generate(
449
+ input_ids=input_ids,
450
+ input_values=input_values,
451
+ input_values_cutoffs=input_values_cutoffs,
452
+ generation_config=generation_config,
453
+ logits_processor=logits_processor,
454
+ stopping_criteria=stopping_criteria,
455
+ synced_gpus=synced_gpus,
456
+ streamer=streamer,
457
+ **kwargs,
458
+ )
459
+
460
+ generate_returned_dict = not isinstance(generate_output, torch.Tensor)
461
+ audio = None
462
+ if output_audio:
463
+ generated_audio_codes = generate_output.sequences if generate_returned_dict else generate_output
464
+
465
+ # infer the codec model
466
+ audio = []
467
+ with torch.no_grad():
468
+ # =======================================
469
+ # TODO: @eustlb, this should be batched !!!
470
+ # but requires making sure batched inference of the codec model works as intended
471
+ for audio_codes_batch in generated_audio_codes:
472
+ eos_idxs = (audio_codes_batch == self.config.codebook_eos_token_id).all(dim=-1).nonzero()
473
+ if eos_idxs.numel() != 0:
474
+ cutoff_idx = eos_idxs.min()
475
+ else:
476
+ cutoff_idx = audio_codes_batch.shape[0]
477
+
478
+ audio_codes_batch = audio_codes_batch[:cutoff_idx]
479
+ codec_decode_output = self.codec_model.decode(audio_codes_batch.transpose(0, 1).unsqueeze(0))
480
+ audio.append(codec_decode_output.audio_values[0, 0])
481
+ # =======================================
482
+
483
+ if generate_returned_dict:
484
+ return CsmGenerateOutput(audio=audio, **generate_output)
485
+ elif output_audio:
486
+ return audio
487
+ else:
488
+ return generate_output
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/csm/modeling_csm.py ADDED
@@ -0,0 +1,1117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/csm/modular_csm.py.
3
+ # Do NOT edit this file manually as any edits will be overwritten by the generation of
4
+ # the file from the modular. If any change should be done, please apply the change to the
5
+ # modular_csm.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # Copyright 2025 Sesame and The HuggingFace Inc. team. All rights reserved.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+
21
+ from collections.abc import Callable
22
+ from dataclasses import dataclass
23
+ from typing import Optional
24
+
25
+ import torch
26
+ import torch.nn as nn
27
+
28
+ from ... import initialization as init
29
+ from ...activations import ACT2FN
30
+ from ...cache_utils import Cache, DynamicCache
31
+ from ...generation import GenerationMixin
32
+ from ...integrations import use_kernel_forward_from_hub, use_kernel_func_from_hub, use_kernelized_func
33
+ from ...masking_utils import create_causal_mask
34
+ from ...modeling_layers import GradientCheckpointingLayer
35
+ from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
36
+ from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
37
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
38
+ from ...processing_utils import Unpack
39
+ from ...utils import ModelOutput, TransformersKwargs, auto_docstring, can_return_tuple, logging
40
+ from ...utils.generic import maybe_autocast, merge_with_config_defaults
41
+ from ...utils.import_utils import is_torchdynamo_compiling
42
+ from ...utils.output_capturing import capture_outputs
43
+ from ..auto import AutoModel
44
+ from .configuration_csm import CsmConfig, CsmDepthDecoderConfig
45
+ from .generation_csm import CsmGenerationMixin
46
+
47
+
48
+ logger = logging.get_logger(__name__)
49
+
50
+
51
+ @dataclass
52
+ @auto_docstring(
53
+ custom_intro="""
54
+ Base class for the model autoregressive outputs.
55
+ """
56
+ )
57
+ class CsmOutputWithPast(ModelOutput):
58
+ r"""
59
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
60
+ Language modeling loss (for next-token prediction).
61
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
62
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
63
+ past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
64
+ It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
65
+
66
+ Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
67
+ `past_key_values` input) to speed up sequential decoding.
68
+ depth_decoder_loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
69
+ Language modeling loss (for next-token prediction) of the depth decoder model.
70
+ depth_decoder_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
71
+ Prediction scores of the depth decoder (scores for each vocabulary token before SoftMax).
72
+ depth_decoder_past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
73
+ It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
74
+ depth_decoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
75
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
76
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
77
+
78
+ Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
79
+ depth_decoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
80
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
81
+ sequence_length)`.
82
+ backbone_loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
83
+ Language modeling loss (for next-token prediction) of the backbone model.
84
+ """
85
+
86
+ loss: torch.FloatTensor | None = None
87
+ logits: torch.FloatTensor | None = None
88
+ past_key_values: Cache | None = None
89
+ hidden_states: tuple[torch.FloatTensor, ...] | None = None
90
+ attentions: tuple[torch.FloatTensor, ...] | None = None
91
+ depth_decoder_loss: torch.FloatTensor | None = None
92
+ depth_decoder_logits: torch.FloatTensor | None = None
93
+ depth_decoder_past_key_values: Cache | None = None
94
+ depth_decoder_hidden_states: tuple[torch.FloatTensor, ...] | None = None
95
+ depth_decoder_attentions: tuple[torch.FloatTensor, ...] | None = None
96
+ backbone_loss: torch.FloatTensor | None = None
97
+
98
+
99
+ @use_kernel_forward_from_hub("RMSNorm")
100
+ class CsmRMSNorm(nn.Module):
101
+ def __init__(self, hidden_size, eps: float = 1e-6) -> None:
102
+ """
103
+ CsmRMSNorm is equivalent to T5LayerNorm
104
+ """
105
+ super().__init__()
106
+ self.weight = nn.Parameter(torch.ones(hidden_size))
107
+ self.variance_epsilon = eps
108
+
109
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
110
+ input_dtype = hidden_states.dtype
111
+ hidden_states = hidden_states.to(torch.float32)
112
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
113
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
114
+ return self.weight * hidden_states.to(input_dtype)
115
+
116
+ def extra_repr(self):
117
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
118
+
119
+
120
+ class CsmRotaryEmbedding(nn.Module):
121
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
122
+
123
+ def __init__(self, config: CsmConfig, device=None):
124
+ super().__init__()
125
+ self.max_seq_len_cached = config.max_position_embeddings
126
+ self.original_max_seq_len = config.max_position_embeddings
127
+
128
+ self.config = config
129
+
130
+ self.rope_type = self.config.rope_parameters["rope_type"]
131
+ rope_init_fn: Callable = self.compute_default_rope_parameters
132
+ if self.rope_type != "default":
133
+ rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
134
+ inv_freq, self.attention_scaling = rope_init_fn(self.config, device)
135
+
136
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
137
+ self.register_buffer("original_inv_freq", inv_freq.clone(), persistent=False)
138
+
139
+ @staticmethod
140
+ def compute_default_rope_parameters(
141
+ config: CsmConfig | None = None,
142
+ device: Optional["torch.device"] = None,
143
+ seq_len: int | None = None,
144
+ ) -> tuple["torch.Tensor", float]:
145
+ """
146
+ Computes the inverse frequencies according to the original RoPE implementation
147
+ Args:
148
+ config ([`~transformers.PreTrainedConfig`]):
149
+ The model configuration.
150
+ device (`torch.device`):
151
+ The device to use for initialization of the inverse frequencies.
152
+ seq_len (`int`, *optional*):
153
+ The current sequence length. Unused for this type of RoPE.
154
+ Returns:
155
+ Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
156
+ post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
157
+ """
158
+ base = config.rope_parameters["rope_theta"]
159
+ dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
160
+
161
+ attention_factor = 1.0 # Unused in this type of RoPE
162
+
163
+ # Compute the inverse frequencies
164
+ inv_freq = 1.0 / (
165
+ base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
166
+ )
167
+ return inv_freq, attention_factor
168
+
169
+ @torch.no_grad()
170
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
171
+ def forward(self, x, position_ids):
172
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
173
+ position_ids_expanded = position_ids[:, None, :].float()
174
+
175
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
176
+ with maybe_autocast(device_type=device_type, enabled=False): # Force float32
177
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
178
+ emb = torch.cat((freqs, freqs), dim=-1)
179
+ cos = emb.cos() * self.attention_scaling
180
+ sin = emb.sin() * self.attention_scaling
181
+
182
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
183
+
184
+
185
+ class CsmMLP(nn.Module):
186
+ def __init__(self, config):
187
+ super().__init__()
188
+ self.config = config
189
+ self.hidden_size = config.hidden_size
190
+ self.intermediate_size = config.intermediate_size
191
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
192
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
193
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)
194
+ self.act_fn = ACT2FN[config.hidden_act]
195
+
196
+ def forward(self, x):
197
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
198
+ return down_proj
199
+
200
+
201
+ def rotate_half(x):
202
+ """Rotates half the hidden dims of the input."""
203
+ x1 = x[..., : x.shape[-1] // 2]
204
+ x2 = x[..., x.shape[-1] // 2 :]
205
+ return torch.cat((-x2, x1), dim=-1)
206
+
207
+
208
+ @use_kernel_func_from_hub("rotary_pos_emb")
209
+ def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
210
+ """Applies Rotary Position Embedding to the query and key tensors.
211
+
212
+ Args:
213
+ q (`torch.Tensor`): The query tensor.
214
+ k (`torch.Tensor`): The key tensor.
215
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
216
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
217
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
218
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
219
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
220
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
221
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
222
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
223
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
224
+ Returns:
225
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
226
+ """
227
+ cos = cos.unsqueeze(unsqueeze_dim)
228
+ sin = sin.unsqueeze(unsqueeze_dim)
229
+ q_embed = (q * cos) + (rotate_half(q) * sin)
230
+ k_embed = (k * cos) + (rotate_half(k) * sin)
231
+ return q_embed, k_embed
232
+
233
+
234
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
235
+ """
236
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
237
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
238
+ """
239
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
240
+ if n_rep == 1:
241
+ return hidden_states
242
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
243
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
244
+
245
+
246
+ def eager_attention_forward(
247
+ module: nn.Module,
248
+ query: torch.Tensor,
249
+ key: torch.Tensor,
250
+ value: torch.Tensor,
251
+ attention_mask: torch.Tensor | None,
252
+ scaling: float,
253
+ dropout: float = 0.0,
254
+ **kwargs: Unpack[TransformersKwargs],
255
+ ):
256
+ key_states = repeat_kv(key, module.num_key_value_groups)
257
+ value_states = repeat_kv(value, module.num_key_value_groups)
258
+
259
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
260
+ if attention_mask is not None:
261
+ attn_weights = attn_weights + attention_mask
262
+
263
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
264
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
265
+ attn_output = torch.matmul(attn_weights, value_states)
266
+ attn_output = attn_output.transpose(1, 2).contiguous()
267
+
268
+ return attn_output, attn_weights
269
+
270
+
271
+ @use_kernelized_func(apply_rotary_pos_emb)
272
+ class CsmAttention(nn.Module):
273
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
274
+
275
+ def __init__(self, config: CsmConfig, layer_idx: int):
276
+ super().__init__()
277
+ self.config = config
278
+ self.layer_idx = layer_idx
279
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
280
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
281
+ self.scaling = self.head_dim**-0.5
282
+ self.attention_dropout = config.attention_dropout
283
+ self.is_causal = True
284
+
285
+ self.q_proj = nn.Linear(
286
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
287
+ )
288
+ self.k_proj = nn.Linear(
289
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
290
+ )
291
+ self.v_proj = nn.Linear(
292
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
293
+ )
294
+ self.o_proj = nn.Linear(
295
+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
296
+ )
297
+
298
+ def forward(
299
+ self,
300
+ hidden_states: torch.Tensor,
301
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
302
+ attention_mask: torch.Tensor | None = None,
303
+ past_key_values: Cache | None = None,
304
+ cache_position: torch.LongTensor | None = None,
305
+ **kwargs: Unpack[TransformersKwargs],
306
+ ) -> tuple[torch.Tensor, torch.Tensor]:
307
+ input_shape = hidden_states.shape[:-1]
308
+ hidden_shape = (*input_shape, -1, self.head_dim)
309
+
310
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
311
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
312
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
313
+
314
+ cos, sin = position_embeddings
315
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
316
+
317
+ if past_key_values is not None:
318
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
319
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
320
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
321
+
322
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
323
+ self.config._attn_implementation, eager_attention_forward
324
+ )
325
+
326
+ attn_output, attn_weights = attention_interface(
327
+ self,
328
+ query_states,
329
+ key_states,
330
+ value_states,
331
+ attention_mask,
332
+ dropout=0.0 if not self.training else self.attention_dropout,
333
+ scaling=self.scaling,
334
+ **kwargs,
335
+ )
336
+
337
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
338
+ attn_output = self.o_proj(attn_output)
339
+ return attn_output, attn_weights
340
+
341
+
342
+ class CsmDecoderLayer(GradientCheckpointingLayer):
343
+ def __init__(self, config: CsmConfig, layer_idx: int):
344
+ super().__init__()
345
+ self.hidden_size = config.hidden_size
346
+
347
+ self.self_attn = CsmAttention(config=config, layer_idx=layer_idx)
348
+
349
+ self.mlp = CsmMLP(config)
350
+ self.input_layernorm = CsmRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
351
+ self.post_attention_layernorm = CsmRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
352
+
353
+ def forward(
354
+ self,
355
+ hidden_states: torch.Tensor,
356
+ attention_mask: torch.Tensor | None = None,
357
+ position_ids: torch.LongTensor | None = None,
358
+ past_key_values: Cache | None = None,
359
+ use_cache: bool | None = False,
360
+ cache_position: torch.LongTensor | None = None,
361
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
362
+ **kwargs: Unpack[TransformersKwargs],
363
+ ) -> torch.Tensor:
364
+ residual = hidden_states
365
+ hidden_states = self.input_layernorm(hidden_states)
366
+ # Self Attention
367
+ hidden_states, _ = self.self_attn(
368
+ hidden_states=hidden_states,
369
+ attention_mask=attention_mask,
370
+ position_ids=position_ids,
371
+ past_key_values=past_key_values,
372
+ use_cache=use_cache,
373
+ cache_position=cache_position,
374
+ position_embeddings=position_embeddings,
375
+ **kwargs,
376
+ )
377
+ hidden_states = residual + hidden_states
378
+
379
+ # Fully Connected
380
+ residual = hidden_states
381
+ hidden_states = self.post_attention_layernorm(hidden_states)
382
+ hidden_states = self.mlp(hidden_states)
383
+ hidden_states = residual + hidden_states
384
+ return hidden_states
385
+
386
+
387
+ @auto_docstring(
388
+ custom_intro="""
389
+ The bare Csm Model outputting raw hidden-states without any specific head on top.
390
+ """
391
+ )
392
+ @auto_docstring
393
+ class CsmPreTrainedModel(PreTrainedModel):
394
+ config: CsmConfig
395
+ base_model_prefix = "model"
396
+ input_modalities = ("audio", "text")
397
+ supports_gradient_checkpointing = True
398
+ _no_split_modules = ["CsmDecoderLayer"]
399
+ _skip_keys_device_placement = ["past_key_values"]
400
+ _supports_flash_attn = True
401
+ _supports_sdpa = True
402
+ # does not because of Mimi codec model
403
+ # _supports_flex_attn = True
404
+
405
+ _can_compile_fullgraph = True
406
+ _supports_attention_backend = True
407
+ _can_record_outputs = {
408
+ "hidden_states": CsmDecoderLayer,
409
+ "attentions": CsmAttention,
410
+ }
411
+
412
+ @torch.no_grad()
413
+ def _init_weights(self, module):
414
+ super()._init_weights(module)
415
+ if isinstance(module, CsmCodebooksHead):
416
+ num_codebooks = module.num_codebooks
417
+ for i in range(num_codebooks - 1):
418
+ init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
419
+ elif isinstance(module, CsmBackboneModelEmbeddings):
420
+ init.copy_(module.audio_tokens_offsets, torch.arange(self.config.num_codebooks) * self.config.vocab_size)
421
+
422
+
423
+ @auto_docstring
424
+ class CsmDepthDecoderModel(CsmPreTrainedModel):
425
+ config: CsmDepthDecoderConfig
426
+
427
+ def __init__(self, config):
428
+ super().__init__(config)
429
+ self.padding_idx = config.pad_token_id
430
+ self.vocab_size = config.vocab_size
431
+ self.embed_tokens = nn.Embedding((config.num_codebooks * config.vocab_size), config.backbone_hidden_size)
432
+ self.layers = nn.ModuleList(
433
+ [CsmDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
434
+ )
435
+ self.norm = CsmRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
436
+ self.rotary_emb = CsmRotaryEmbedding(config=config)
437
+ self.gradient_checkpointing = False
438
+ self.inputs_embeds_projector = nn.Linear(config.backbone_hidden_size, config.hidden_size, bias=False)
439
+
440
+ # Initialize weights and apply final processing
441
+ self.post_init()
442
+
443
+ @merge_with_config_defaults
444
+ @capture_outputs
445
+ @auto_docstring
446
+ def forward(
447
+ self,
448
+ input_ids: torch.LongTensor | None = None,
449
+ backbone_last_hidden_state: torch.FloatTensor | None = None,
450
+ attention_mask: torch.Tensor | None = None,
451
+ position_ids: torch.LongTensor | None = None,
452
+ past_key_values: Cache | None = None,
453
+ inputs_embeds: torch.FloatTensor | None = None,
454
+ use_cache: bool | None = None,
455
+ cache_position: torch.LongTensor | None = None,
456
+ **kwargs: Unpack[TransformersKwargs],
457
+ ) -> tuple | BaseModelOutputWithPast:
458
+ r"""
459
+ backbone_last_hidden_state (`torch.FloatTensor` of shape `(batch_size, backbone_hidden_size)`, *optional*):
460
+ The last hidden state of the backbone model. Such input is required when the first codebook token (the one generated by the backbone model)
461
+ is provided in the `input_ids` argument.
462
+ """
463
+ if position_ids is not None and not is_torchdynamo_compiling():
464
+ logger.warning_once(
465
+ "Custom `position_ids` were provided but will be ignored. CSM depth decoder automatically determines position_ids "
466
+ "from `cache_position` and as it requires them to be identical across the batch, the provided position_ids will be ignored."
467
+ )
468
+ position_ids = None
469
+ if (input_ids is None) ^ (inputs_embeds is not None):
470
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds.")
471
+
472
+ if use_cache and past_key_values is None:
473
+ past_key_values = DynamicCache(config=self.config)
474
+
475
+ if cache_position is None:
476
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
477
+ inputs_seq_length = inputs_embeds.shape[1] if inputs_embeds is not None else input_ids.shape[1]
478
+ device = inputs_embeds.device if inputs_embeds is not None else input_ids.device
479
+ cache_position = torch.arange(past_seen_tokens, past_seen_tokens + inputs_seq_length, device=device)
480
+
481
+ if inputs_embeds is None:
482
+ codebook_idxs = torch.clamp(cache_position - 1, min=0)
483
+ offset = codebook_idxs * self.vocab_size
484
+ inputs_embeds = self.embed_tokens(input_ids + offset)
485
+
486
+ input_ids_are_first_codebook = cache_position[0] == 0
487
+ if backbone_last_hidden_state is not None:
488
+ inputs_embeds[:, 0] = backbone_last_hidden_state
489
+ else:
490
+ if not is_torchdynamo_compiling() and input_ids_are_first_codebook:
491
+ logger.warning(
492
+ "When the first codebook token is provided, `backbone_last_hidden_state` should also be provided for correct inference."
493
+ )
494
+
495
+ inputs_embeds = self.inputs_embeds_projector(inputs_embeds)
496
+
497
+ causal_mask = create_causal_mask(
498
+ config=self.config,
499
+ inputs_embeds=inputs_embeds,
500
+ attention_mask=attention_mask,
501
+ cache_position=cache_position,
502
+ past_key_values=past_key_values,
503
+ position_ids=position_ids,
504
+ )
505
+
506
+ hidden_states = inputs_embeds
507
+
508
+ # create position embeddings to be shared across the decoder layers
509
+ position_ids = cache_position.unsqueeze(0)
510
+ position_embeddings = self.rotary_emb(hidden_states, position_ids=position_ids)
511
+
512
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
513
+ hidden_states = decoder_layer(
514
+ hidden_states,
515
+ attention_mask=causal_mask,
516
+ position_ids=position_ids,
517
+ past_key_values=past_key_values,
518
+ use_cache=use_cache,
519
+ cache_position=cache_position,
520
+ position_embeddings=position_embeddings,
521
+ **kwargs,
522
+ )
523
+
524
+ hidden_states = self.norm(hidden_states)
525
+ return BaseModelOutputWithPast(
526
+ last_hidden_state=hidden_states,
527
+ past_key_values=past_key_values if use_cache else None,
528
+ )
529
+
530
+
531
+ class CsmCodebooksHead(nn.Module):
532
+ def __init__(self, hidden_size, num_codebooks, vocab_size):
533
+ super().__init__()
534
+ self.num_codebooks = num_codebooks
535
+ self.weight = nn.Parameter(torch.empty(self.num_codebooks - 1, hidden_size, vocab_size))
536
+
537
+ def forward(self, hidden_states, cache_position=None):
538
+ if cache_position is None:
539
+ seq_length = hidden_states.shape[1]
540
+ codebook_weight = self.weight[torch.arange(seq_length)]
541
+ else:
542
+ codebook_idxs = cache_position - 1
543
+ codebook_weight = self.weight[codebook_idxs]
544
+
545
+ hidden_states = [
546
+ nn.functional.linear(hidden_states[:, codebook_idx, :], codebook_weight[codebook_idx].T)
547
+ for codebook_idx in range(codebook_weight.shape[0])
548
+ ]
549
+ hidden_states = torch.stack(hidden_states, dim=1)
550
+
551
+ return hidden_states
552
+
553
+
554
+ @auto_docstring(
555
+ custom_intro="""
556
+ The CsmDepthDecoder Model transformer, with a [`CsmCodebooksHead`] on top,
557
+ which can be seen a position-specific language modeling head, allowing to use a different linear layer for each codebook
558
+ (e.g. position 0 is the first codebook and uses the first codebook head, etc.)
559
+ """
560
+ )
561
+ class CsmDepthDecoderForCausalLM(CsmPreTrainedModel, GenerationMixin):
562
+ _tied_weights_keys = None
563
+ _tp_plan = None
564
+ _pp_plan = None
565
+
566
+ def __init__(self, config):
567
+ super().__init__(config)
568
+ self.model = CsmDepthDecoderModel(config)
569
+ self.vocab_size = config.vocab_size
570
+ self.codebooks_head = CsmCodebooksHead(config.hidden_size, config.num_codebooks, config.vocab_size)
571
+
572
+ # Initialize weights and apply final processing
573
+ self.post_init()
574
+
575
+ @can_return_tuple
576
+ @auto_docstring
577
+ def forward(
578
+ self,
579
+ input_ids: torch.LongTensor | None = None,
580
+ backbone_last_hidden_state: torch.FloatTensor | None = None,
581
+ attention_mask: torch.Tensor | None = None,
582
+ position_ids: torch.LongTensor | None = None,
583
+ past_key_values: Cache | None = None,
584
+ inputs_embeds: torch.FloatTensor | None = None,
585
+ labels: torch.LongTensor | None = None,
586
+ use_cache: bool | None = None,
587
+ cache_position: torch.LongTensor | None = None,
588
+ logits_to_keep: int | torch.Tensor = 0,
589
+ **kwargs: Unpack[TransformersKwargs],
590
+ ) -> tuple | CausalLMOutputWithPast:
591
+ r"""
592
+ backbone_last_hidden_state (`torch.FloatTensor` of shape `(batch_size, backbone_hidden_size)`, *optional*):
593
+ The last hidden state of the backbone model. Such input is required when the first codebook token (the one generated by the backbone model)
594
+ is provided in the `input_ids` argument.
595
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
596
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
597
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
598
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
599
+ """
600
+ outputs = self.model(
601
+ input_ids=input_ids,
602
+ backbone_last_hidden_state=backbone_last_hidden_state,
603
+ attention_mask=attention_mask,
604
+ position_ids=position_ids,
605
+ past_key_values=past_key_values,
606
+ inputs_embeds=inputs_embeds,
607
+ use_cache=use_cache,
608
+ cache_position=cache_position,
609
+ **kwargs,
610
+ )
611
+
612
+ hidden_states = outputs[0]
613
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
614
+ if isinstance(logits_to_keep, int):
615
+ if logits_to_keep == 0:
616
+ # skip idx 0 logits since it's for the concatenated backbone last hidden state
617
+ slice_indices = slice(1, None)
618
+ else:
619
+ slice_indices = slice(-logits_to_keep, None)
620
+ else:
621
+ slice_indices = logits_to_keep
622
+
623
+ logits = self.codebooks_head(
624
+ hidden_states[:, slice_indices, :], cache_position[slice_indices] if cache_position is not None else None
625
+ )
626
+ logits = logits.contiguous()
627
+
628
+ loss = None
629
+ if labels is not None:
630
+ shift_labels = labels[..., 1:].contiguous()
631
+ loss = self.loss_function(
632
+ logits=logits, labels=None, vocab_size=self.config.vocab_size, shift_labels=shift_labels, **kwargs
633
+ )
634
+
635
+ return CausalLMOutputWithPast(
636
+ loss=loss,
637
+ logits=logits,
638
+ past_key_values=outputs.past_key_values,
639
+ hidden_states=outputs.hidden_states,
640
+ attentions=outputs.attentions,
641
+ )
642
+
643
+ def prepare_inputs_for_generation(
644
+ self,
645
+ input_ids: torch.LongTensor,
646
+ next_sequence_length: int | None = None,
647
+ past_key_values: Cache | None = None,
648
+ attention_mask: torch.LongTensor | None = None,
649
+ inputs_embeds: torch.FloatTensor | None = None,
650
+ cache_position: torch.LongTensor | None = None,
651
+ **kwargs,
652
+ ):
653
+ model_inputs = super().prepare_inputs_for_generation(
654
+ input_ids, next_sequence_length, past_key_values, attention_mask, inputs_embeds, cache_position, **kwargs
655
+ )
656
+
657
+ is_first_generation_step = model_inputs["cache_position"][0] == 0
658
+ if not is_first_generation_step:
659
+ model_inputs.pop("backbone_last_hidden_state")
660
+
661
+ # csm depth decoder does not use position_ids
662
+ model_inputs.pop("position_ids")
663
+
664
+ return model_inputs
665
+
666
+
667
+ class CsmBackboneModelEmbeddings(nn.Module):
668
+ def __init__(self, config):
669
+ super().__init__()
670
+ self.embed_audio_tokens = nn.Embedding((config.num_codebooks * config.codebook_size), config.hidden_size)
671
+ self.register_buffer(
672
+ "audio_tokens_offsets", torch.arange(config.num_codebooks) * config.codebook_size, persistent=False
673
+ )
674
+
675
+ def forward(self, input_ids):
676
+ inputs_embeds = self.embed_audio_tokens(input_ids + self.audio_tokens_offsets)
677
+ inputs_embeds = inputs_embeds.sum(dim=2)
678
+ return inputs_embeds
679
+
680
+
681
+ @auto_docstring
682
+ class CsmBackboneModel(CsmPreTrainedModel):
683
+ def __init__(self, config):
684
+ super().__init__(config)
685
+ self.padding_idx = config.pad_token_id
686
+ self.vocab_size = config.vocab_size
687
+ self.embed_tokens = CsmBackboneModelEmbeddings(config)
688
+ self.layers = nn.ModuleList(
689
+ [CsmDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
690
+ )
691
+ self.norm = CsmRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
692
+ self.rotary_emb = CsmRotaryEmbedding(config=config)
693
+ self.gradient_checkpointing = False
694
+
695
+ # Initialize weights and apply final processing
696
+ self.post_init()
697
+
698
+ @merge_with_config_defaults
699
+ @capture_outputs
700
+ @auto_docstring
701
+ def forward(
702
+ self,
703
+ input_ids: torch.LongTensor | None = None,
704
+ attention_mask: torch.Tensor | None = None,
705
+ position_ids: torch.LongTensor | None = None,
706
+ past_key_values: Cache | None = None,
707
+ inputs_embeds: torch.FloatTensor | None = None,
708
+ cache_position: torch.LongTensor | None = None,
709
+ use_cache: bool | None = None,
710
+ **kwargs: Unpack[TransformersKwargs],
711
+ ) -> BaseModelOutputWithPast:
712
+ r"""
713
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length, num_codebooks) or (batch_size, sequence_length)`):
714
+ 1. (batch_size, sequence_length): corresponds to the input sequence prepared with the processor from the text prompt. Such input
715
+ requires `input_values` to be provided so that audio can be encoded in codebook tokens and then merged with the text tokens.
716
+
717
+ 2. (batch_size, sequence_length, num_codebooks): codebook tokens generated during the autoregressive decoding. Such input is not meant to be used by end users.
718
+
719
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
720
+ [`PreTrainedTokenizer.__call__`] for details.
721
+
722
+ [What are input IDs?](../glossary#input-ids)
723
+ """
724
+ if (input_ids is None) ^ (inputs_embeds is not None):
725
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
726
+
727
+ if inputs_embeds is None:
728
+ inputs_embeds: torch.Tensor = self.embed_tokens(input_ids)
729
+
730
+ if use_cache and past_key_values is None:
731
+ past_key_values = DynamicCache(config=self.config)
732
+
733
+ if cache_position is None:
734
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
735
+ cache_position: torch.Tensor = (
736
+ torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens
737
+ )
738
+
739
+ if position_ids is None:
740
+ position_ids = cache_position.unsqueeze(0)
741
+
742
+ causal_mask = create_causal_mask(
743
+ config=self.config,
744
+ inputs_embeds=inputs_embeds,
745
+ attention_mask=attention_mask,
746
+ cache_position=cache_position,
747
+ past_key_values=past_key_values,
748
+ position_ids=position_ids,
749
+ )
750
+
751
+ hidden_states = inputs_embeds
752
+ position_embeddings = self.rotary_emb(hidden_states, position_ids=position_ids)
753
+
754
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
755
+ hidden_states = decoder_layer(
756
+ hidden_states,
757
+ attention_mask=causal_mask,
758
+ position_embeddings=position_embeddings,
759
+ position_ids=position_ids,
760
+ past_key_values=past_key_values,
761
+ use_cache=use_cache,
762
+ cache_position=cache_position,
763
+ **kwargs,
764
+ )
765
+
766
+ hidden_states = self.norm(hidden_states)
767
+ return BaseModelOutputWithPast(
768
+ last_hidden_state=hidden_states,
769
+ past_key_values=past_key_values,
770
+ )
771
+
772
+
773
+ @auto_docstring(
774
+ custom_intro="""
775
+ The Csm model consists of two llama-like auto-regressive transformer models: a backbone model that predicts the first codebook token and a depth decoder that predicts the other codebook tokens.
776
+ """
777
+ )
778
+ class CsmForConditionalGeneration(CsmPreTrainedModel, CsmGenerationMixin):
779
+ _tied_weights_keys = {
780
+ "backbone_model.embed_tokens.embed_audio_tokens.weight": "depth_decoder.model.embed_tokens.weight"
781
+ }
782
+
783
+ def __init__(self, config):
784
+ super().__init__(config)
785
+ self.vocab_size = config.vocab_size
786
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
787
+ self.embed_text_tokens = nn.Embedding(config.text_vocab_size, config.hidden_size)
788
+ self.backbone_model = CsmBackboneModel._from_config(config)
789
+ self.depth_decoder = CsmDepthDecoderForCausalLM._from_config(config.depth_decoder_config)
790
+ self.codec_model = AutoModel.from_config(config.codec_config)
791
+ self.post_init()
792
+
793
+ def get_input_embeddings(self):
794
+ return self.backbone_model.embed_tokens
795
+
796
+ def set_input_embeddings(self, value):
797
+ self.backbone_model.embed_tokens = value
798
+
799
+ @classmethod
800
+ def from_pretrained(cls, *args, **kwargs):
801
+ if kwargs.get("output_loading_info", False):
802
+ model, loading_info = super().from_pretrained(*args, **kwargs)
803
+ else:
804
+ model = super().from_pretrained(*args, **kwargs)
805
+
806
+ # copy depth decoder generation conf attr to the depth decoder generation config
807
+ prefix = "depth_decoder_"
808
+ prefix_len = len(prefix)
809
+ depth_decoder_attrs = {
810
+ attr[prefix_len:]: value
811
+ for attr, value in vars(model.generation_config).items()
812
+ if attr.startswith(prefix)
813
+ }
814
+
815
+ vars(model.depth_decoder.generation_config).update({"_from_model_config": False, **depth_decoder_attrs})
816
+
817
+ # remove the depth decoder generation conf attr from the model generation config
818
+ for attr in depth_decoder_attrs:
819
+ delattr(model.generation_config, prefix + attr)
820
+
821
+ if "output_loading_info" in kwargs:
822
+ return model, loading_info
823
+ else:
824
+ return model
825
+
826
+ def save_pretrained(self, *args, **kwargs):
827
+ # copy the depth decoder generation config attributes to the model generation config
828
+ prefix = "depth_decoder_"
829
+ depth_decoder_attrs = self.depth_decoder.generation_config.to_diff_dict()
830
+ depth_decoder_attrs.pop("transformers_version", None)
831
+ for attr, value in depth_decoder_attrs.items():
832
+ setattr(self.generation_config, prefix + attr, value)
833
+
834
+ super().save_pretrained(*args, **kwargs)
835
+
836
+ def _merge_input_ids_with_input_values(
837
+ self,
838
+ input_ids: torch.Tensor | None = None,
839
+ input_values: torch.Tensor | None = None,
840
+ input_values_cutoffs: torch.Tensor | None = None,
841
+ labels: torch.Tensor | None = None,
842
+ ) -> torch.Tensor | None:
843
+ """
844
+ Merges the input_ids and input_values to produce a single inputs_embeds tensor:
845
+ 1 - Infers the codec model on the input_values to retrieve codebook token.
846
+ 2 - Embeds codebook tokens and places them at the correct positions in the inputs_embeds tensor.
847
+ 3 - If labels are provided, expands them to match codebook dimensions and position the target codebook tokens in the inputs_embeds tensor.
848
+
849
+ Args:
850
+ input_ids (`torch.Tensor` of shape `(batch_size, sequence_length)`):
851
+ The input ids to embed.
852
+ input_values (`torch.Tensor` of shape `(batch_size, channels, audio_sequence_length)`):
853
+ The audio input values to embed.
854
+ input_values_cutoffs (`torch.Tensor` of shape `(batch_size, max_num_audio)`):
855
+ The cutoffs of the audio input values relative to its batch index, padded with -1 when no audio.
856
+ """
857
+ inputs_embeds = self.embed_text_tokens(input_ids)
858
+
859
+ if input_values is not None:
860
+ # infer input_values_mask
861
+ input_values_cutoffs = nn.functional.pad(input_values_cutoffs, (1, 0))
862
+ audio_lengths = input_values_cutoffs[input_values_cutoffs >= 0].diff()
863
+ audio_lengths = audio_lengths[audio_lengths > 0]
864
+ input_values_mask = torch.arange(input_values_cutoffs.max(), device=input_values.device).expand(
865
+ len(audio_lengths), -1
866
+ )
867
+ input_values_mask = input_values_mask < audio_lengths.unsqueeze(1)
868
+
869
+ # =======================================
870
+ # TODO: @eustlb, this should be batched !!!
871
+ # but requires making sure batched inference of the codec model works as intended
872
+ with torch.no_grad():
873
+ audio_tokens_list = []
874
+ for batch_input_values, batch_input_values_cutoffs in zip(input_values, input_values_cutoffs):
875
+ batch_input_values_cutoffs = batch_input_values_cutoffs[batch_input_values_cutoffs >= 0]
876
+ for i in range(batch_input_values_cutoffs.shape[0] - 1):
877
+ start_idx = batch_input_values_cutoffs[i]
878
+ end_idx = batch_input_values_cutoffs[i + 1]
879
+ audio_batch = batch_input_values[..., start_idx:end_idx]
880
+ codec_outputs = self.codec_model.encode(audio_batch.unsqueeze(0))
881
+ codebook_ids = codec_outputs.audio_codes.transpose(1, -1)
882
+ audio_tokens_list.append(codebook_ids[0])
883
+
884
+ max_audio_frames = max(el.shape[0] for el in audio_tokens_list)
885
+ batched_audio_token_ids = torch.stack(
886
+ [nn.functional.pad(el, (0, 0, 0, max_audio_frames - el.shape[0])) for el in audio_tokens_list]
887
+ )
888
+ audio_codes_mask = self.codec_model.get_audio_codes_mask(input_values_mask)
889
+ # =======================================
890
+ audio_token_id = self.config.audio_token_id
891
+ audio_token_mask = input_ids == audio_token_id
892
+
893
+ audio_embeds = self.backbone_model.embed_tokens(batched_audio_token_ids)
894
+ inputs_embeds[audio_token_mask] = audio_embeds[audio_codes_mask]
895
+
896
+ # same for the audio eos token
897
+ audio_eos_frame_ids = (
898
+ torch.ones((1, 1, self.config.num_codebooks), device=input_ids.device, dtype=torch.long)
899
+ * self.config.codebook_eos_token_id
900
+ )
901
+ audio_eos_embeds = self.backbone_model.embed_tokens(audio_eos_frame_ids).squeeze(1)
902
+
903
+ audio_eos_token_mask = input_ids == self.config.audio_eos_token_id
904
+ inputs_embeds[audio_eos_token_mask] = audio_eos_embeds.repeat(audio_eos_token_mask.sum(), 1)
905
+
906
+ # if the labels are provided, we need to expand the labels to (batch_size, seq_length, num_codebooks)
907
+ if labels is not None:
908
+ labels_expanded = labels.unsqueeze(-1).repeat(1, 1, self.config.num_codebooks)
909
+ labels_expanded[audio_token_mask] = batched_audio_token_ids[audio_codes_mask]
910
+ labels_expanded[audio_eos_token_mask] = audio_eos_frame_ids
911
+ # mask depth decoder
912
+ depth_decoder_ignore_frames_idxs = (labels == -101).nonzero(as_tuple=True)
913
+ labels_expanded[depth_decoder_ignore_frames_idxs[0], depth_decoder_ignore_frames_idxs[1], 1:] = -100
914
+ labels = labels_expanded
915
+
916
+ return {"inputs_embeds": inputs_embeds, "labels": labels}
917
+
918
+ def prepare_inputs_for_generation(
919
+ self,
920
+ input_ids: torch.LongTensor,
921
+ next_sequence_length: int | None = None,
922
+ past_key_values: Cache | None = None,
923
+ attention_mask: torch.LongTensor | None = None,
924
+ inputs_embeds: torch.FloatTensor | None = None,
925
+ cache_position: torch.LongTensor | None = None,
926
+ **kwargs,
927
+ ):
928
+ model_inputs = super().prepare_inputs_for_generation(
929
+ input_ids=input_ids,
930
+ next_sequence_length=next_sequence_length,
931
+ past_key_values=past_key_values,
932
+ attention_mask=attention_mask,
933
+ inputs_embeds=inputs_embeds,
934
+ cache_position=cache_position,
935
+ **kwargs,
936
+ )
937
+
938
+ if input_ids is not None and input_ids.ndim == 2 and model_inputs.get("inputs_embeds") is None:
939
+ merged_inputs = self._merge_input_ids_with_input_values(
940
+ input_ids=input_ids,
941
+ input_values=kwargs.get("input_values"),
942
+ input_values_cutoffs=kwargs.get("input_values_cutoffs"),
943
+ labels=kwargs.get("labels"),
944
+ )
945
+ model_inputs.update(
946
+ {"inputs_embeds": merged_inputs["inputs_embeds"], "labels": merged_inputs["labels"], "input_ids": None}
947
+ )
948
+
949
+ return model_inputs
950
+
951
+ @can_return_tuple
952
+ @auto_docstring
953
+ def forward(
954
+ self,
955
+ input_ids: torch.LongTensor | None = None,
956
+ input_values: torch.Tensor | None = None,
957
+ attention_mask: torch.Tensor | None = None,
958
+ input_values_cutoffs: torch.Tensor | None = None,
959
+ position_ids: torch.LongTensor | None = None,
960
+ past_key_values: Cache | None = None,
961
+ inputs_embeds: torch.FloatTensor | None = None,
962
+ labels: torch.LongTensor | None = None,
963
+ use_cache: bool | None = None,
964
+ cache_position: torch.LongTensor | None = None,
965
+ logits_to_keep: int | torch.Tensor = 0,
966
+ **kwargs: Unpack[TransformersKwargs],
967
+ ) -> tuple | CsmOutputWithPast:
968
+ r"""
969
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length, num_codebooks) or (batch_size, sequence_length)`):
970
+ 1. (batch_size, sequence_length): corresponds to the input sequence prepared with the processor from the text prompt. Such input
971
+ requires `input_values` to be provided so that audio can be encoded in codebook tokens and then merged with the text tokens.
972
+
973
+ 2. (batch_size, sequence_length, num_codebooks): codebook tokens generated during the autoregressive decoding. Such input is not meant to be used by end users.
974
+
975
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
976
+ [`PreTrainedTokenizer.__call__`] for details.
977
+
978
+ [What are input IDs?](../glossary#input-ids)
979
+ input_values_cutoffs (`torch.Tensor` of shape `(batch_size, max_num_audio)`, *optional*):
980
+ Specify the end positions of audio segments within each batch entry, relative to the concatenated audio input.
981
+ If a batch entry has fewer segments than the maximum, it is padded with -1. For example, in a batch of 2 sequences
982
+ where the first contains 2 audio segments of length l1, and the second contains 1 audio segment of length l2,
983
+ the input_values_cutoffs would be: [[l1, 2 * l1], [l2, -1]].
984
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
985
+ Labels for computing the masked language modeling loss. Indices should be in `[config.audio_token_id, -100, -101]`.
986
+ Requires targeted `input_values` to be provided as audio tokens will be inferred from it using the `codec_model`.
987
+ - `config.audio_token_id` indicates an audio frames (considering sequence length elements as frames)
988
+ - `-100` will be ignored in the loss computation
989
+ - `-101` indicates the audio frame will be used only for the backbone model (using the first codebook token as labels)
990
+
991
+ Such labels can be prepared using `output_labels=True` when calling [`CsmProcessor`].
992
+ logits_to_keep (`int` or `torch.Tensor`, *optional*):
993
+ Kept for compatibility. Does not support another value than:
994
+ 1. `0`, which is equivalent to keeping all logits, used in the training regime
995
+ 2. `1`, which is equivalent to keeping only the last logit, used in the generation regime
996
+
997
+ Example:
998
+
999
+ ```python
1000
+ >>> import torch
1001
+ >>> from transformers import CsmForConditionalGeneration, AutoProcessor
1002
+ >>> from datasets import load_dataset, Audio
1003
+
1004
+ >>> model_id = "sesame/csm-1b"
1005
+ >>> torch_device = "cuda" if torch.cuda.is_available() else "cpu"
1006
+
1007
+ >>> processor = AutoProcessor.from_pretrained(model_id)
1008
+
1009
+ >>> ds = load_dataset("hf-internal-testing/dailytalk-dummy", split="train")
1010
+ >>> # ensure the audio is 24kHz
1011
+ >>> ds = ds.cast_column("audio", Audio(sampling_rate=24000))
1012
+
1013
+ >>> conversation = []
1014
+ >>> # prepare a conversation with text and corresponding audio
1015
+ >>> for text, audio, speaker_id in zip(ds[:4]["text"], ds[:4]["audio"], ds[:4]["speaker_id"]):
1016
+ ... conversation.append(
1017
+ ... {
1018
+ ... "role": f"{speaker_id}",
1019
+ ... "content": [{"type": "text", "text": text}, {"type": "audio", "path": audio["array"]}],
1020
+ ... }
1021
+ ... )
1022
+
1023
+ >>> inputs = processor.apply_chat_template(
1024
+ ... conversation,
1025
+ ... tokenize=True,
1026
+ ... return_dict=True,
1027
+ ... output_labels=True,
1028
+ ... ).to(torch_device)
1029
+
1030
+ >>> model = CsmForConditionalGeneration.from_pretrained(model_id, device_map=torch_device)
1031
+ >>> output = model(**inputs)
1032
+ >>> output.loss.backward()
1033
+ ```"""
1034
+ if input_ids is not None and input_ids.ndim == 2:
1035
+ merged_inputs = self._merge_input_ids_with_input_values(
1036
+ input_ids, input_values, input_values_cutoffs, labels
1037
+ )
1038
+ inputs_embeds = merged_inputs["inputs_embeds"]
1039
+ labels = merged_inputs["labels"]
1040
+ input_ids = None
1041
+
1042
+ backbone_outputs = self.backbone_model(
1043
+ input_ids=input_ids,
1044
+ attention_mask=attention_mask,
1045
+ position_ids=position_ids,
1046
+ past_key_values=past_key_values,
1047
+ inputs_embeds=inputs_embeds,
1048
+ use_cache=use_cache,
1049
+ cache_position=cache_position,
1050
+ **kwargs,
1051
+ )
1052
+
1053
+ backbone_hidden_states = backbone_outputs[0]
1054
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
1055
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
1056
+ backbone_logits = self.lm_head(backbone_hidden_states[:, slice_indices, :])
1057
+
1058
+ loss = None
1059
+ backbone_loss = None
1060
+ depth_decoder_loss = None
1061
+ depth_decoder_outputs = None
1062
+ if labels is not None:
1063
+ # select first codebook as labels for the backbone model
1064
+ backbone_labels = labels[:, :, 0]
1065
+ backbone_loss = self.loss_function(
1066
+ logits=backbone_logits, labels=backbone_labels, vocab_size=self.config.vocab_size, **kwargs
1067
+ )
1068
+
1069
+ # for the depth decoder, we need to select the frames to train on
1070
+ # those are frames where the label is not uniformly `ignore_index` along the codebook dimension
1071
+ train_mask = ~(labels[:, :, 1:] == -100).all(dim=-1)
1072
+ depth_decoder_input_ids = labels[train_mask][..., : self.config.num_codebooks - 1]
1073
+ # add place holder in position 0 that will be replaced by the backbone_last_hidden_state
1074
+ depth_decoder_input_ids = nn.functional.pad(depth_decoder_input_ids, (1, 0), value=0)
1075
+
1076
+ train_idxs = train_mask.nonzero(as_tuple=True)
1077
+ backbone_last_hidden_states = backbone_hidden_states[train_idxs[0], train_idxs[1] - 1, :]
1078
+ depth_decoder_labels = labels[train_mask]
1079
+
1080
+ depth_decoder_outputs = self.depth_decoder(
1081
+ input_ids=depth_decoder_input_ids,
1082
+ backbone_last_hidden_state=backbone_last_hidden_states,
1083
+ use_cache=use_cache,
1084
+ return_dict=True,
1085
+ labels=depth_decoder_labels,
1086
+ **kwargs,
1087
+ )
1088
+
1089
+ depth_decoder_loss = depth_decoder_outputs.loss
1090
+ loss = backbone_loss + depth_decoder_loss
1091
+
1092
+ return CsmOutputWithPast(
1093
+ loss=loss,
1094
+ backbone_loss=backbone_loss,
1095
+ depth_decoder_loss=depth_decoder_loss,
1096
+ logits=backbone_logits,
1097
+ past_key_values=backbone_outputs.past_key_values,
1098
+ hidden_states=backbone_outputs.hidden_states,
1099
+ attentions=backbone_outputs.attentions,
1100
+ depth_decoder_logits=depth_decoder_outputs.logits if depth_decoder_outputs is not None else None,
1101
+ depth_decoder_past_key_values=depth_decoder_outputs.past_key_values
1102
+ if depth_decoder_outputs is not None
1103
+ else None,
1104
+ depth_decoder_hidden_states=depth_decoder_outputs.hidden_states
1105
+ if depth_decoder_outputs is not None
1106
+ else None,
1107
+ depth_decoder_attentions=depth_decoder_outputs.attentions if depth_decoder_outputs is not None else None,
1108
+ )
1109
+
1110
+
1111
+ __all__ = [
1112
+ "CsmPreTrainedModel",
1113
+ "CsmBackboneModel",
1114
+ "CsmDepthDecoderModel",
1115
+ "CsmDepthDecoderForCausalLM",
1116
+ "CsmForConditionalGeneration",
1117
+ ]
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/csm/modular_csm.py ADDED
@@ -0,0 +1,767 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 Sesame and 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
+
15
+ from dataclasses import dataclass
16
+
17
+ import torch
18
+ import torch.nn as nn
19
+
20
+ from ... import initialization as init
21
+ from ...cache_utils import Cache, DynamicCache
22
+ from ...generation import GenerationMixin
23
+ from ...masking_utils import create_causal_mask
24
+ from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
25
+ from ...modeling_utils import PreTrainedModel
26
+ from ...processing_utils import Unpack
27
+ from ...utils import ModelOutput, auto_docstring, can_return_tuple, logging
28
+ from ...utils.generic import merge_with_config_defaults
29
+ from ...utils.import_utils import is_torchdynamo_compiling
30
+ from ...utils.output_capturing import capture_outputs
31
+ from ..auto import AutoModel
32
+ from ..llama.modeling_llama import (
33
+ LlamaAttention,
34
+ LlamaDecoderLayer,
35
+ LlamaForCausalLM,
36
+ LlamaMLP,
37
+ LlamaModel,
38
+ LlamaRMSNorm,
39
+ LlamaRotaryEmbedding,
40
+ TransformersKwargs,
41
+ )
42
+ from .configuration_csm import CsmConfig, CsmDepthDecoderConfig
43
+ from .generation_csm import CsmGenerationMixin
44
+
45
+
46
+ logger = logging.get_logger(__name__)
47
+
48
+
49
+ @dataclass
50
+ @auto_docstring(
51
+ custom_intro="""
52
+ Base class for the model autoregressive outputs.
53
+ """
54
+ )
55
+ class CsmOutputWithPast(ModelOutput):
56
+ r"""
57
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
58
+ Language modeling loss (for next-token prediction).
59
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
60
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
61
+ past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
62
+ It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
63
+
64
+ Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
65
+ `past_key_values` input) to speed up sequential decoding.
66
+ depth_decoder_loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
67
+ Language modeling loss (for next-token prediction) of the depth decoder model.
68
+ depth_decoder_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
69
+ Prediction scores of the depth decoder (scores for each vocabulary token before SoftMax).
70
+ depth_decoder_past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
71
+ It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
72
+ depth_decoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
73
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
74
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
75
+
76
+ Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
77
+ depth_decoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
78
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
79
+ sequence_length)`.
80
+ backbone_loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
81
+ Language modeling loss (for next-token prediction) of the backbone model.
82
+ """
83
+
84
+ loss: torch.FloatTensor | None = None
85
+ logits: torch.FloatTensor | None = None
86
+ past_key_values: Cache | None = None
87
+ hidden_states: tuple[torch.FloatTensor, ...] | None = None
88
+ attentions: tuple[torch.FloatTensor, ...] | None = None
89
+ depth_decoder_loss: torch.FloatTensor | None = None
90
+ depth_decoder_logits: torch.FloatTensor | None = None
91
+ depth_decoder_past_key_values: Cache | None = None
92
+ depth_decoder_hidden_states: tuple[torch.FloatTensor, ...] | None = None
93
+ depth_decoder_attentions: tuple[torch.FloatTensor, ...] | None = None
94
+ backbone_loss: torch.FloatTensor | None = None
95
+
96
+
97
+ # manually specify names for correct naming when converting from modular
98
+ class CsmRMSNorm(LlamaRMSNorm):
99
+ pass
100
+
101
+
102
+ class CsmRotaryEmbedding(LlamaRotaryEmbedding):
103
+ pass
104
+
105
+
106
+ class CsmMLP(LlamaMLP):
107
+ pass
108
+
109
+
110
+ class CsmAttention(LlamaAttention):
111
+ pass
112
+
113
+
114
+ class CsmDecoderLayer(LlamaDecoderLayer):
115
+ pass
116
+
117
+
118
+ @auto_docstring(
119
+ custom_intro="""
120
+ The bare Csm Model outputting raw hidden-states without any specific head on top.
121
+ """
122
+ )
123
+ @auto_docstring
124
+ class CsmPreTrainedModel(PreTrainedModel):
125
+ config: CsmConfig
126
+ base_model_prefix = "model"
127
+ input_modalities = ("audio", "text")
128
+ supports_gradient_checkpointing = True
129
+ _no_split_modules = ["CsmDecoderLayer"]
130
+ _skip_keys_device_placement = ["past_key_values"]
131
+ _supports_flash_attn = True
132
+ _supports_sdpa = True
133
+ # does not because of Mimi codec model
134
+ # _supports_flex_attn = True
135
+
136
+ _can_compile_fullgraph = True
137
+ _supports_attention_backend = True
138
+ _can_record_outputs = {
139
+ "hidden_states": CsmDecoderLayer,
140
+ "attentions": CsmAttention,
141
+ }
142
+
143
+ @torch.no_grad()
144
+ def _init_weights(self, module):
145
+ super()._init_weights(module)
146
+ if isinstance(module, CsmCodebooksHead):
147
+ num_codebooks = module.num_codebooks
148
+ for i in range(num_codebooks - 1):
149
+ init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
150
+ elif isinstance(module, CsmBackboneModelEmbeddings):
151
+ init.copy_(module.audio_tokens_offsets, torch.arange(self.config.num_codebooks) * self.config.vocab_size)
152
+
153
+
154
+ @auto_docstring
155
+ class CsmDepthDecoderModel(LlamaModel, CsmPreTrainedModel):
156
+ config: CsmDepthDecoderConfig
157
+
158
+ def __init__(self, config):
159
+ super().__init__(config)
160
+ self.embed_tokens = nn.Embedding((config.num_codebooks * config.vocab_size), config.backbone_hidden_size)
161
+ self.inputs_embeds_projector = nn.Linear(config.backbone_hidden_size, config.hidden_size, bias=False)
162
+
163
+ @merge_with_config_defaults
164
+ @capture_outputs
165
+ @auto_docstring
166
+ def forward(
167
+ self,
168
+ input_ids: torch.LongTensor | None = None,
169
+ backbone_last_hidden_state: torch.FloatTensor | None = None,
170
+ attention_mask: torch.Tensor | None = None,
171
+ position_ids: torch.LongTensor | None = None,
172
+ past_key_values: Cache | None = None,
173
+ inputs_embeds: torch.FloatTensor | None = None,
174
+ use_cache: bool | None = None,
175
+ cache_position: torch.LongTensor | None = None,
176
+ **kwargs: Unpack[TransformersKwargs],
177
+ ) -> tuple | BaseModelOutputWithPast:
178
+ r"""
179
+ backbone_last_hidden_state (`torch.FloatTensor` of shape `(batch_size, backbone_hidden_size)`, *optional*):
180
+ The last hidden state of the backbone model. Such input is required when the first codebook token (the one generated by the backbone model)
181
+ is provided in the `input_ids` argument.
182
+ """
183
+ if position_ids is not None and not is_torchdynamo_compiling():
184
+ logger.warning_once(
185
+ "Custom `position_ids` were provided but will be ignored. CSM depth decoder automatically determines position_ids "
186
+ "from `cache_position` and as it requires them to be identical across the batch, the provided position_ids will be ignored."
187
+ )
188
+ position_ids = None
189
+ if (input_ids is None) ^ (inputs_embeds is not None):
190
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds.")
191
+
192
+ if use_cache and past_key_values is None:
193
+ past_key_values = DynamicCache(config=self.config)
194
+
195
+ if cache_position is None:
196
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
197
+ inputs_seq_length = inputs_embeds.shape[1] if inputs_embeds is not None else input_ids.shape[1]
198
+ device = inputs_embeds.device if inputs_embeds is not None else input_ids.device
199
+ cache_position = torch.arange(past_seen_tokens, past_seen_tokens + inputs_seq_length, device=device)
200
+
201
+ if inputs_embeds is None:
202
+ codebook_idxs = torch.clamp(cache_position - 1, min=0)
203
+ offset = codebook_idxs * self.vocab_size
204
+ inputs_embeds = self.embed_tokens(input_ids + offset)
205
+
206
+ input_ids_are_first_codebook = cache_position[0] == 0
207
+ if backbone_last_hidden_state is not None:
208
+ inputs_embeds[:, 0] = backbone_last_hidden_state
209
+ else:
210
+ if not is_torchdynamo_compiling() and input_ids_are_first_codebook:
211
+ logger.warning(
212
+ "When the first codebook token is provided, `backbone_last_hidden_state` should also be provided for correct inference."
213
+ )
214
+
215
+ inputs_embeds = self.inputs_embeds_projector(inputs_embeds)
216
+
217
+ causal_mask = create_causal_mask(
218
+ config=self.config,
219
+ inputs_embeds=inputs_embeds,
220
+ attention_mask=attention_mask,
221
+ cache_position=cache_position,
222
+ past_key_values=past_key_values,
223
+ position_ids=position_ids,
224
+ )
225
+
226
+ hidden_states = inputs_embeds
227
+
228
+ # create position embeddings to be shared across the decoder layers
229
+ position_ids = cache_position.unsqueeze(0)
230
+ position_embeddings = self.rotary_emb(hidden_states, position_ids=position_ids)
231
+
232
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
233
+ hidden_states = decoder_layer(
234
+ hidden_states,
235
+ attention_mask=causal_mask,
236
+ position_ids=position_ids,
237
+ past_key_values=past_key_values,
238
+ use_cache=use_cache,
239
+ cache_position=cache_position,
240
+ position_embeddings=position_embeddings,
241
+ **kwargs,
242
+ )
243
+
244
+ hidden_states = self.norm(hidden_states)
245
+ return BaseModelOutputWithPast(
246
+ last_hidden_state=hidden_states,
247
+ past_key_values=past_key_values if use_cache else None,
248
+ )
249
+
250
+
251
+ class CsmCodebooksHead(nn.Module):
252
+ def __init__(self, hidden_size, num_codebooks, vocab_size):
253
+ super().__init__()
254
+ self.num_codebooks = num_codebooks
255
+ self.weight = nn.Parameter(torch.empty(self.num_codebooks - 1, hidden_size, vocab_size))
256
+
257
+ def forward(self, hidden_states, cache_position=None):
258
+ if cache_position is None:
259
+ seq_length = hidden_states.shape[1]
260
+ codebook_weight = self.weight[torch.arange(seq_length)]
261
+ else:
262
+ codebook_idxs = cache_position - 1
263
+ codebook_weight = self.weight[codebook_idxs]
264
+
265
+ hidden_states = [
266
+ nn.functional.linear(hidden_states[:, codebook_idx, :], codebook_weight[codebook_idx].T)
267
+ for codebook_idx in range(codebook_weight.shape[0])
268
+ ]
269
+ hidden_states = torch.stack(hidden_states, dim=1)
270
+
271
+ return hidden_states
272
+
273
+
274
+ @auto_docstring(
275
+ custom_intro="""
276
+ The CsmDepthDecoder Model transformer, with a [`CsmCodebooksHead`] on top,
277
+ which can be seen a position-specific language modeling head, allowing to use a different linear layer for each codebook
278
+ (e.g. position 0 is the first codebook and uses the first codebook head, etc.)
279
+ """
280
+ )
281
+ class CsmDepthDecoderForCausalLM(LlamaForCausalLM, GenerationMixin):
282
+ _tied_weights_keys = None
283
+ _tp_plan = None
284
+ _pp_plan = None
285
+
286
+ def __init__(self, config):
287
+ super().__init__(config)
288
+ del self.lm_head
289
+ self.codebooks_head = CsmCodebooksHead(config.hidden_size, config.num_codebooks, config.vocab_size)
290
+ self.model = CsmDepthDecoderModel(config)
291
+
292
+ def prepare_inputs_for_generation(
293
+ self,
294
+ input_ids: torch.LongTensor,
295
+ next_sequence_length: int | None = None,
296
+ past_key_values: Cache | None = None,
297
+ attention_mask: torch.LongTensor | None = None,
298
+ inputs_embeds: torch.FloatTensor | None = None,
299
+ cache_position: torch.LongTensor | None = None,
300
+ **kwargs,
301
+ ):
302
+ model_inputs = super().prepare_inputs_for_generation(
303
+ input_ids, next_sequence_length, past_key_values, attention_mask, inputs_embeds, cache_position, **kwargs
304
+ )
305
+
306
+ is_first_generation_step = model_inputs["cache_position"][0] == 0
307
+ if not is_first_generation_step:
308
+ model_inputs.pop("backbone_last_hidden_state")
309
+
310
+ # csm depth decoder does not use position_ids
311
+ model_inputs.pop("position_ids")
312
+
313
+ return model_inputs
314
+
315
+ @can_return_tuple
316
+ @auto_docstring
317
+ def forward(
318
+ self,
319
+ input_ids: torch.LongTensor | None = None,
320
+ backbone_last_hidden_state: torch.FloatTensor | None = None,
321
+ attention_mask: torch.Tensor | None = None,
322
+ position_ids: torch.LongTensor | None = None,
323
+ past_key_values: Cache | None = None,
324
+ inputs_embeds: torch.FloatTensor | None = None,
325
+ labels: torch.LongTensor | None = None,
326
+ use_cache: bool | None = None,
327
+ cache_position: torch.LongTensor | None = None,
328
+ logits_to_keep: int | torch.Tensor = 0,
329
+ **kwargs: Unpack[TransformersKwargs],
330
+ ) -> tuple | CausalLMOutputWithPast:
331
+ r"""
332
+ backbone_last_hidden_state (`torch.FloatTensor` of shape `(batch_size, backbone_hidden_size)`, *optional*):
333
+ The last hidden state of the backbone model. Such input is required when the first codebook token (the one generated by the backbone model)
334
+ is provided in the `input_ids` argument.
335
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
336
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
337
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
338
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
339
+ """
340
+ outputs = self.model(
341
+ input_ids=input_ids,
342
+ backbone_last_hidden_state=backbone_last_hidden_state,
343
+ attention_mask=attention_mask,
344
+ position_ids=position_ids,
345
+ past_key_values=past_key_values,
346
+ inputs_embeds=inputs_embeds,
347
+ use_cache=use_cache,
348
+ cache_position=cache_position,
349
+ **kwargs,
350
+ )
351
+
352
+ hidden_states = outputs[0]
353
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
354
+ if isinstance(logits_to_keep, int):
355
+ if logits_to_keep == 0:
356
+ # skip idx 0 logits since it's for the concatenated backbone last hidden state
357
+ slice_indices = slice(1, None)
358
+ else:
359
+ slice_indices = slice(-logits_to_keep, None)
360
+ else:
361
+ slice_indices = logits_to_keep
362
+
363
+ logits = self.codebooks_head(
364
+ hidden_states[:, slice_indices, :], cache_position[slice_indices] if cache_position is not None else None
365
+ )
366
+ logits = logits.contiguous()
367
+
368
+ loss = None
369
+ if labels is not None:
370
+ shift_labels = labels[..., 1:].contiguous()
371
+ loss = self.loss_function(
372
+ logits=logits, labels=None, vocab_size=self.config.vocab_size, shift_labels=shift_labels, **kwargs
373
+ )
374
+
375
+ return CausalLMOutputWithPast(
376
+ loss=loss,
377
+ logits=logits,
378
+ past_key_values=outputs.past_key_values,
379
+ hidden_states=outputs.hidden_states,
380
+ attentions=outputs.attentions,
381
+ )
382
+
383
+
384
+ class CsmBackboneModelEmbeddings(nn.Module):
385
+ def __init__(self, config):
386
+ super().__init__()
387
+ self.embed_audio_tokens = nn.Embedding((config.num_codebooks * config.codebook_size), config.hidden_size)
388
+ self.register_buffer(
389
+ "audio_tokens_offsets", torch.arange(config.num_codebooks) * config.codebook_size, persistent=False
390
+ )
391
+
392
+ def forward(self, input_ids):
393
+ inputs_embeds = self.embed_audio_tokens(input_ids + self.audio_tokens_offsets)
394
+ inputs_embeds = inputs_embeds.sum(dim=2)
395
+ return inputs_embeds
396
+
397
+
398
+ @auto_docstring
399
+ class CsmBackboneModel(LlamaModel):
400
+ def __init__(self, config):
401
+ super().__init__(config)
402
+ self.embed_tokens = CsmBackboneModelEmbeddings(config)
403
+
404
+ @merge_with_config_defaults
405
+ @capture_outputs
406
+ @auto_docstring
407
+ def forward(self, **super_kwargs):
408
+ r"""
409
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length, num_codebooks) or (batch_size, sequence_length)`):
410
+ 1. (batch_size, sequence_length): corresponds to the input sequence prepared with the processor from the text prompt. Such input
411
+ requires `input_values` to be provided so that audio can be encoded in codebook tokens and then merged with the text tokens.
412
+
413
+ 2. (batch_size, sequence_length, num_codebooks): codebook tokens generated during the autoregressive decoding. Such input is not meant to be used by end users.
414
+
415
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
416
+ [`PreTrainedTokenizer.__call__`] for details.
417
+
418
+ [What are input IDs?](../glossary#input-ids)
419
+ """
420
+ return super().forward(**super_kwargs)
421
+
422
+
423
+ @auto_docstring(
424
+ custom_intro="""
425
+ The Csm model consists of two llama-like auto-regressive transformer models: a backbone model that predicts the first codebook token and a depth decoder that predicts the other codebook tokens.
426
+ """
427
+ )
428
+ class CsmForConditionalGeneration(CsmPreTrainedModel, CsmGenerationMixin):
429
+ _tied_weights_keys = {
430
+ "backbone_model.embed_tokens.embed_audio_tokens.weight": "depth_decoder.model.embed_tokens.weight"
431
+ }
432
+
433
+ def __init__(self, config):
434
+ super().__init__(config)
435
+ self.vocab_size = config.vocab_size
436
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
437
+ self.embed_text_tokens = nn.Embedding(config.text_vocab_size, config.hidden_size)
438
+ self.backbone_model = CsmBackboneModel._from_config(config)
439
+ self.depth_decoder = CsmDepthDecoderForCausalLM._from_config(config.depth_decoder_config)
440
+ self.codec_model = AutoModel.from_config(config.codec_config)
441
+ self.post_init()
442
+
443
+ def get_input_embeddings(self):
444
+ return self.backbone_model.embed_tokens
445
+
446
+ def set_input_embeddings(self, value):
447
+ self.backbone_model.embed_tokens = value
448
+
449
+ @classmethod
450
+ def from_pretrained(cls, *args, **kwargs):
451
+ if kwargs.get("output_loading_info", False):
452
+ model, loading_info = super().from_pretrained(*args, **kwargs)
453
+ else:
454
+ model = super().from_pretrained(*args, **kwargs)
455
+
456
+ # copy depth decoder generation conf attr to the depth decoder generation config
457
+ prefix = "depth_decoder_"
458
+ prefix_len = len(prefix)
459
+ depth_decoder_attrs = {
460
+ attr[prefix_len:]: value
461
+ for attr, value in vars(model.generation_config).items()
462
+ if attr.startswith(prefix)
463
+ }
464
+
465
+ vars(model.depth_decoder.generation_config).update({"_from_model_config": False, **depth_decoder_attrs})
466
+
467
+ # remove the depth decoder generation conf attr from the model generation config
468
+ for attr in depth_decoder_attrs:
469
+ delattr(model.generation_config, prefix + attr)
470
+
471
+ if "output_loading_info" in kwargs:
472
+ return model, loading_info
473
+ else:
474
+ return model
475
+
476
+ def save_pretrained(self, *args, **kwargs):
477
+ # copy the depth decoder generation config attributes to the model generation config
478
+ prefix = "depth_decoder_"
479
+ depth_decoder_attrs = self.depth_decoder.generation_config.to_diff_dict()
480
+ depth_decoder_attrs.pop("transformers_version", None)
481
+ for attr, value in depth_decoder_attrs.items():
482
+ setattr(self.generation_config, prefix + attr, value)
483
+
484
+ super().save_pretrained(*args, **kwargs)
485
+
486
+ def _merge_input_ids_with_input_values(
487
+ self,
488
+ input_ids: torch.Tensor | None = None,
489
+ input_values: torch.Tensor | None = None,
490
+ input_values_cutoffs: torch.Tensor | None = None,
491
+ labels: torch.Tensor | None = None,
492
+ ) -> torch.Tensor | None:
493
+ """
494
+ Merges the input_ids and input_values to produce a single inputs_embeds tensor:
495
+ 1 - Infers the codec model on the input_values to retrieve codebook token.
496
+ 2 - Embeds codebook tokens and places them at the correct positions in the inputs_embeds tensor.
497
+ 3 - If labels are provided, expands them to match codebook dimensions and position the target codebook tokens in the inputs_embeds tensor.
498
+
499
+ Args:
500
+ input_ids (`torch.Tensor` of shape `(batch_size, sequence_length)`):
501
+ The input ids to embed.
502
+ input_values (`torch.Tensor` of shape `(batch_size, channels, audio_sequence_length)`):
503
+ The audio input values to embed.
504
+ input_values_cutoffs (`torch.Tensor` of shape `(batch_size, max_num_audio)`):
505
+ The cutoffs of the audio input values relative to its batch index, padded with -1 when no audio.
506
+ """
507
+ inputs_embeds = self.embed_text_tokens(input_ids)
508
+
509
+ if input_values is not None:
510
+ # infer input_values_mask
511
+ input_values_cutoffs = nn.functional.pad(input_values_cutoffs, (1, 0))
512
+ audio_lengths = input_values_cutoffs[input_values_cutoffs >= 0].diff()
513
+ audio_lengths = audio_lengths[audio_lengths > 0]
514
+ input_values_mask = torch.arange(input_values_cutoffs.max(), device=input_values.device).expand(
515
+ len(audio_lengths), -1
516
+ )
517
+ input_values_mask = input_values_mask < audio_lengths.unsqueeze(1)
518
+
519
+ # =======================================
520
+ # TODO: @eustlb, this should be batched !!!
521
+ # but requires making sure batched inference of the codec model works as intended
522
+ with torch.no_grad():
523
+ audio_tokens_list = []
524
+ for batch_input_values, batch_input_values_cutoffs in zip(input_values, input_values_cutoffs):
525
+ batch_input_values_cutoffs = batch_input_values_cutoffs[batch_input_values_cutoffs >= 0]
526
+ for i in range(batch_input_values_cutoffs.shape[0] - 1):
527
+ start_idx = batch_input_values_cutoffs[i]
528
+ end_idx = batch_input_values_cutoffs[i + 1]
529
+ audio_batch = batch_input_values[..., start_idx:end_idx]
530
+ codec_outputs = self.codec_model.encode(audio_batch.unsqueeze(0))
531
+ codebook_ids = codec_outputs.audio_codes.transpose(1, -1)
532
+ audio_tokens_list.append(codebook_ids[0])
533
+
534
+ max_audio_frames = max(el.shape[0] for el in audio_tokens_list)
535
+ batched_audio_token_ids = torch.stack(
536
+ [nn.functional.pad(el, (0, 0, 0, max_audio_frames - el.shape[0])) for el in audio_tokens_list]
537
+ )
538
+ audio_codes_mask = self.codec_model.get_audio_codes_mask(input_values_mask)
539
+ # =======================================
540
+ audio_token_id = self.config.audio_token_id
541
+ audio_token_mask = input_ids == audio_token_id
542
+
543
+ audio_embeds = self.backbone_model.embed_tokens(batched_audio_token_ids)
544
+ inputs_embeds[audio_token_mask] = audio_embeds[audio_codes_mask]
545
+
546
+ # same for the audio eos token
547
+ audio_eos_frame_ids = (
548
+ torch.ones((1, 1, self.config.num_codebooks), device=input_ids.device, dtype=torch.long)
549
+ * self.config.codebook_eos_token_id
550
+ )
551
+ audio_eos_embeds = self.backbone_model.embed_tokens(audio_eos_frame_ids).squeeze(1)
552
+
553
+ audio_eos_token_mask = input_ids == self.config.audio_eos_token_id
554
+ inputs_embeds[audio_eos_token_mask] = audio_eos_embeds.repeat(audio_eos_token_mask.sum(), 1)
555
+
556
+ # if the labels are provided, we need to expand the labels to (batch_size, seq_length, num_codebooks)
557
+ if labels is not None:
558
+ labels_expanded = labels.unsqueeze(-1).repeat(1, 1, self.config.num_codebooks)
559
+ labels_expanded[audio_token_mask] = batched_audio_token_ids[audio_codes_mask]
560
+ labels_expanded[audio_eos_token_mask] = audio_eos_frame_ids
561
+ # mask depth decoder
562
+ depth_decoder_ignore_frames_idxs = (labels == -101).nonzero(as_tuple=True)
563
+ labels_expanded[depth_decoder_ignore_frames_idxs[0], depth_decoder_ignore_frames_idxs[1], 1:] = -100
564
+ labels = labels_expanded
565
+
566
+ return {"inputs_embeds": inputs_embeds, "labels": labels}
567
+
568
+ def prepare_inputs_for_generation(
569
+ self,
570
+ input_ids: torch.LongTensor,
571
+ next_sequence_length: int | None = None,
572
+ past_key_values: Cache | None = None,
573
+ attention_mask: torch.LongTensor | None = None,
574
+ inputs_embeds: torch.FloatTensor | None = None,
575
+ cache_position: torch.LongTensor | None = None,
576
+ **kwargs,
577
+ ):
578
+ model_inputs = super().prepare_inputs_for_generation(
579
+ input_ids=input_ids,
580
+ next_sequence_length=next_sequence_length,
581
+ past_key_values=past_key_values,
582
+ attention_mask=attention_mask,
583
+ inputs_embeds=inputs_embeds,
584
+ cache_position=cache_position,
585
+ **kwargs,
586
+ )
587
+
588
+ if input_ids is not None and input_ids.ndim == 2 and model_inputs.get("inputs_embeds") is None:
589
+ merged_inputs = self._merge_input_ids_with_input_values(
590
+ input_ids=input_ids,
591
+ input_values=kwargs.get("input_values"),
592
+ input_values_cutoffs=kwargs.get("input_values_cutoffs"),
593
+ labels=kwargs.get("labels"),
594
+ )
595
+ model_inputs.update(
596
+ {"inputs_embeds": merged_inputs["inputs_embeds"], "labels": merged_inputs["labels"], "input_ids": None}
597
+ )
598
+
599
+ return model_inputs
600
+
601
+ @can_return_tuple
602
+ @auto_docstring
603
+ def forward(
604
+ self,
605
+ input_ids: torch.LongTensor | None = None,
606
+ input_values: torch.Tensor | None = None,
607
+ attention_mask: torch.Tensor | None = None,
608
+ input_values_cutoffs: torch.Tensor | None = None,
609
+ position_ids: torch.LongTensor | None = None,
610
+ past_key_values: Cache | None = None,
611
+ inputs_embeds: torch.FloatTensor | None = None,
612
+ labels: torch.LongTensor | None = None,
613
+ use_cache: bool | None = None,
614
+ cache_position: torch.LongTensor | None = None,
615
+ logits_to_keep: int | torch.Tensor = 0,
616
+ **kwargs: Unpack[TransformersKwargs],
617
+ ) -> tuple | CsmOutputWithPast:
618
+ r"""
619
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length, num_codebooks) or (batch_size, sequence_length)`):
620
+ 1. (batch_size, sequence_length): corresponds to the input sequence prepared with the processor from the text prompt. Such input
621
+ requires `input_values` to be provided so that audio can be encoded in codebook tokens and then merged with the text tokens.
622
+
623
+ 2. (batch_size, sequence_length, num_codebooks): codebook tokens generated during the autoregressive decoding. Such input is not meant to be used by end users.
624
+
625
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
626
+ [`PreTrainedTokenizer.__call__`] for details.
627
+
628
+ [What are input IDs?](../glossary#input-ids)
629
+ input_values_cutoffs (`torch.Tensor` of shape `(batch_size, max_num_audio)`, *optional*):
630
+ Specify the end positions of audio segments within each batch entry, relative to the concatenated audio input.
631
+ If a batch entry has fewer segments than the maximum, it is padded with -1. For example, in a batch of 2 sequences
632
+ where the first contains 2 audio segments of length l1, and the second contains 1 audio segment of length l2,
633
+ the input_values_cutoffs would be: [[l1, 2 * l1], [l2, -1]].
634
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
635
+ Labels for computing the masked language modeling loss. Indices should be in `[config.audio_token_id, -100, -101]`.
636
+ Requires targeted `input_values` to be provided as audio tokens will be inferred from it using the `codec_model`.
637
+ - `config.audio_token_id` indicates an audio frames (considering sequence length elements as frames)
638
+ - `-100` will be ignored in the loss computation
639
+ - `-101` indicates the audio frame will be used only for the backbone model (using the first codebook token as labels)
640
+
641
+ Such labels can be prepared using `output_labels=True` when calling [`CsmProcessor`].
642
+ logits_to_keep (`int` or `torch.Tensor`, *optional*):
643
+ Kept for compatibility. Does not support another value than:
644
+ 1. `0`, which is equivalent to keeping all logits, used in the training regime
645
+ 2. `1`, which is equivalent to keeping only the last logit, used in the generation regime
646
+
647
+ Example:
648
+
649
+ ```python
650
+ >>> import torch
651
+ >>> from transformers import CsmForConditionalGeneration, AutoProcessor
652
+ >>> from datasets import load_dataset, Audio
653
+
654
+ >>> model_id = "sesame/csm-1b"
655
+ >>> torch_device = "cuda" if torch.cuda.is_available() else "cpu"
656
+
657
+ >>> processor = AutoProcessor.from_pretrained(model_id)
658
+
659
+ >>> ds = load_dataset("hf-internal-testing/dailytalk-dummy", split="train")
660
+ >>> # ensure the audio is 24kHz
661
+ >>> ds = ds.cast_column("audio", Audio(sampling_rate=24000))
662
+
663
+ >>> conversation = []
664
+ >>> # prepare a conversation with text and corresponding audio
665
+ >>> for text, audio, speaker_id in zip(ds[:4]["text"], ds[:4]["audio"], ds[:4]["speaker_id"]):
666
+ ... conversation.append(
667
+ ... {
668
+ ... "role": f"{speaker_id}",
669
+ ... "content": [{"type": "text", "text": text}, {"type": "audio", "path": audio["array"]}],
670
+ ... }
671
+ ... )
672
+
673
+ >>> inputs = processor.apply_chat_template(
674
+ ... conversation,
675
+ ... tokenize=True,
676
+ ... return_dict=True,
677
+ ... output_labels=True,
678
+ ... ).to(torch_device)
679
+
680
+ >>> model = CsmForConditionalGeneration.from_pretrained(model_id, device_map=torch_device)
681
+ >>> output = model(**inputs)
682
+ >>> output.loss.backward()
683
+ ```"""
684
+ if input_ids is not None and input_ids.ndim == 2:
685
+ merged_inputs = self._merge_input_ids_with_input_values(
686
+ input_ids, input_values, input_values_cutoffs, labels
687
+ )
688
+ inputs_embeds = merged_inputs["inputs_embeds"]
689
+ labels = merged_inputs["labels"]
690
+ input_ids = None
691
+
692
+ backbone_outputs = self.backbone_model(
693
+ input_ids=input_ids,
694
+ attention_mask=attention_mask,
695
+ position_ids=position_ids,
696
+ past_key_values=past_key_values,
697
+ inputs_embeds=inputs_embeds,
698
+ use_cache=use_cache,
699
+ cache_position=cache_position,
700
+ **kwargs,
701
+ )
702
+
703
+ backbone_hidden_states = backbone_outputs[0]
704
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
705
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
706
+ backbone_logits = self.lm_head(backbone_hidden_states[:, slice_indices, :])
707
+
708
+ loss = None
709
+ backbone_loss = None
710
+ depth_decoder_loss = None
711
+ depth_decoder_outputs = None
712
+ if labels is not None:
713
+ # select first codebook as labels for the backbone model
714
+ backbone_labels = labels[:, :, 0]
715
+ backbone_loss = self.loss_function(
716
+ logits=backbone_logits, labels=backbone_labels, vocab_size=self.config.vocab_size, **kwargs
717
+ )
718
+
719
+ # for the depth decoder, we need to select the frames to train on
720
+ # those are frames where the label is not uniformly `ignore_index` along the codebook dimension
721
+ train_mask = ~(labels[:, :, 1:] == -100).all(dim=-1)
722
+ depth_decoder_input_ids = labels[train_mask][..., : self.config.num_codebooks - 1]
723
+ # add place holder in position 0 that will be replaced by the backbone_last_hidden_state
724
+ depth_decoder_input_ids = nn.functional.pad(depth_decoder_input_ids, (1, 0), value=0)
725
+
726
+ train_idxs = train_mask.nonzero(as_tuple=True)
727
+ backbone_last_hidden_states = backbone_hidden_states[train_idxs[0], train_idxs[1] - 1, :]
728
+ depth_decoder_labels = labels[train_mask]
729
+
730
+ depth_decoder_outputs = self.depth_decoder(
731
+ input_ids=depth_decoder_input_ids,
732
+ backbone_last_hidden_state=backbone_last_hidden_states,
733
+ use_cache=use_cache,
734
+ return_dict=True,
735
+ labels=depth_decoder_labels,
736
+ **kwargs,
737
+ )
738
+
739
+ depth_decoder_loss = depth_decoder_outputs.loss
740
+ loss = backbone_loss + depth_decoder_loss
741
+
742
+ return CsmOutputWithPast(
743
+ loss=loss,
744
+ backbone_loss=backbone_loss,
745
+ depth_decoder_loss=depth_decoder_loss,
746
+ logits=backbone_logits,
747
+ past_key_values=backbone_outputs.past_key_values,
748
+ hidden_states=backbone_outputs.hidden_states,
749
+ attentions=backbone_outputs.attentions,
750
+ depth_decoder_logits=depth_decoder_outputs.logits if depth_decoder_outputs is not None else None,
751
+ depth_decoder_past_key_values=depth_decoder_outputs.past_key_values
752
+ if depth_decoder_outputs is not None
753
+ else None,
754
+ depth_decoder_hidden_states=depth_decoder_outputs.hidden_states
755
+ if depth_decoder_outputs is not None
756
+ else None,
757
+ depth_decoder_attentions=depth_decoder_outputs.attentions if depth_decoder_outputs is not None else None,
758
+ )
759
+
760
+
761
+ __all__ = [
762
+ "CsmPreTrainedModel",
763
+ "CsmBackboneModel",
764
+ "CsmDepthDecoderModel",
765
+ "CsmDepthDecoderForCausalLM",
766
+ "CsmForConditionalGeneration",
767
+ ]
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/csm/processing_csm.py ADDED
@@ -0,0 +1,322 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 Sesame and 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
+
15
+ import math
16
+ from pathlib import Path
17
+ from typing import Any
18
+
19
+ import numpy as np
20
+
21
+ from ...utils import auto_docstring, is_soundfile_available, is_torch_available
22
+
23
+
24
+ if is_torch_available():
25
+ import torch
26
+
27
+ if is_soundfile_available():
28
+ import soundfile as sf
29
+
30
+ from ...audio_utils import AudioInput, make_list_of_audio
31
+ from ...feature_extraction_utils import BatchFeature
32
+ from ...processing_utils import AudioKwargs, ProcessingKwargs, ProcessorMixin, Unpack
33
+ from ...tokenization_utils_base import PreTokenizedInput, TextInput
34
+
35
+
36
+ class CsmAudioKwargs(AudioKwargs, total=False):
37
+ """
38
+ encoded_length_kwargs (`dict[str, Any]`, *optional*):
39
+ Dictionary of keyword arguments used to compute the encoded audio sequence length. This includes parameters
40
+ such as `kernel_sizes`, `strides`, `dilations`, and `use_causal_conv` that define the convolutional layers
41
+ used in audio encoding. The encoded length is used to determine how many audio tokens to generate for each
42
+ audio input in the text sequence.
43
+ """
44
+
45
+ encoded_length_kwargs: dict[str, Any] | None
46
+
47
+
48
+ class CsmProcessorKwargs(ProcessingKwargs, total=False):
49
+ audio_kwargs: CsmAudioKwargs
50
+ _defaults = {
51
+ "text_kwargs": {
52
+ "padding": True,
53
+ "padding_side": "left",
54
+ "add_special_tokens": False,
55
+ },
56
+ "audio_kwargs": {
57
+ "encoded_length_kwargs": {
58
+ "kernel_sizes": [7, 3, 1, 8, 3, 1, 10, 3, 1, 12, 3, 1, 16, 3, 4],
59
+ "strides": [1, 1, 1, 4, 1, 1, 5, 1, 1, 6, 1, 1, 8, 1, 2],
60
+ "dilations": [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
61
+ "use_causal_conv": True,
62
+ },
63
+ "sampling_rate": 24000,
64
+ },
65
+ "common_kwargs": {"return_tensors": "pt"},
66
+ }
67
+
68
+
69
+ @auto_docstring
70
+ class CsmProcessor(ProcessorMixin):
71
+ def __init__(
72
+ self,
73
+ feature_extractor,
74
+ tokenizer,
75
+ chat_template=None,
76
+ ):
77
+ if not hasattr(tokenizer, "audio_token"):
78
+ self.audio_token = "<|AUDIO|>"
79
+ self.audio_token_id = tokenizer.convert_tokens_to_ids(self.audio_token)
80
+ else:
81
+ self.audio_token = tokenizer.audio_token
82
+ self.audio_token_id = tokenizer.audio_token_id
83
+
84
+ if not hasattr(tokenizer, "audio_eos_token"):
85
+ self.audio_eos_token = "<|audio_eos|>"
86
+ self.audio_eos_token_id = tokenizer.convert_tokens_to_ids(self.audio_eos_token)
87
+ else:
88
+ self.audio_eos_token = tokenizer.audio_eos_token
89
+ self.audio_eos_token_id = tokenizer.audio_eos_token_id
90
+
91
+ super().__init__(feature_extractor, tokenizer, chat_template=chat_template)
92
+
93
+ @staticmethod
94
+ def _get_encoded_length(audio_length, kernel_sizes=None, strides=None, dilations=None, use_causal_conv=None):
95
+ """
96
+ Compute the length of the encoded audio sequence.
97
+
98
+ Args:
99
+ audio_length (int): The length of the audio sequence.
100
+ kernel_sizes (list[int]): The kernel sizes for the convolutional layers.
101
+ strides (list[int]): The strides for the convolutional layers.
102
+ use_causal_conv (bool): Whether to use causal convolutions.
103
+ """
104
+ cur_length = audio_length
105
+
106
+ if kernel_sizes is None or strides is None or dilations is None or use_causal_conv is None:
107
+ return cur_length
108
+
109
+ for kernel_size, stride, dilation in zip(kernel_sizes, strides, dilations):
110
+ effective_kernel_size = (kernel_size - 1) * dilation + 1
111
+ padding_total = kernel_size - stride
112
+ padding_right = padding_total // 2
113
+ padding_left = padding_total - padding_right
114
+
115
+ n_frames = (cur_length - effective_kernel_size + padding_total) / stride + 1
116
+ n_frames = math.ceil(n_frames) - 1
117
+ ideal_length = n_frames * stride + kernel_size - padding_total
118
+ extra_padding = ideal_length - cur_length
119
+
120
+ if use_causal_conv:
121
+ padding_left = padding_total
122
+ padding_right = extra_padding
123
+ else:
124
+ padding_right = padding_right + extra_padding
125
+
126
+ cur_length = cur_length + padding_left + padding_right
127
+ cur_length = (cur_length - dilation * (kernel_size - 1) - 1) // stride + 1
128
+
129
+ return cur_length
130
+
131
+ def save_audio(
132
+ self,
133
+ audio: AudioInput,
134
+ saving_path: str | Path | list[str | Path],
135
+ **kwargs: Unpack[CsmProcessorKwargs],
136
+ ):
137
+ # TODO: @eustlb, this should be in AudioProcessor
138
+ if not is_soundfile_available():
139
+ raise ImportError("Please install `soundfile` to save audio files.")
140
+
141
+ # ensure correct audio input
142
+ audio = make_list_of_audio(audio)
143
+
144
+ # ensure correct saving path
145
+ if isinstance(saving_path, (str, Path)):
146
+ saving_path = [saving_path]
147
+ elif not (isinstance(saving_path, (list, tuple)) and all(isinstance(p, (str, Path)) for p in saving_path)):
148
+ raise ValueError("Invalid input path. Please provide a string, or a list of strings")
149
+
150
+ if len(audio) != len(saving_path):
151
+ raise ValueError("The number of audio and saving paths must be the same")
152
+
153
+ output_kwargs = self._merge_kwargs(
154
+ CsmProcessorKwargs,
155
+ **kwargs,
156
+ )
157
+ audio_kwargs = output_kwargs["audio_kwargs"]
158
+ sampling_rate = audio_kwargs["sampling_rate"]
159
+
160
+ for audio_value, p in zip(audio, saving_path):
161
+ if isinstance(audio_value, torch.Tensor):
162
+ audio_value = audio_value.cpu().float().numpy()
163
+ sf.write(p, audio_value, sampling_rate)
164
+
165
+ @auto_docstring
166
+ def __call__(
167
+ self,
168
+ text: TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput] | None,
169
+ audio: AudioInput | None = None,
170
+ output_labels: bool | None = False,
171
+ depth_decoder_labels_ratio: float | None = 1.0,
172
+ **kwargs: Unpack[CsmProcessorKwargs],
173
+ ):
174
+ r"""
175
+ output_labels (bool, *optional*, default=False):
176
+ Whether to return labels for training. Indices will be in `[config.audio_token_id, -100, -101]`.
177
+ - `config.audio_token_id` indicates an audio frame (considering sequence length elements as frames)
178
+ - `-100` will be ignored in the loss computation
179
+ - `-101` indicates the audio frame will be used only for the backbone model (using the first codebook token as labels)
180
+ depth_decoder_labels_ratio (float, *optional*, default=1.0):
181
+ The ratio of audio frames to keep for the depth decoder labels.
182
+
183
+ Returns:
184
+ [`BatchFeature`]: A [`BatchFeature`] with the following fields:
185
+
186
+ - **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
187
+ - **input_values** -- List of audio values to be fed to a model. Returned when `audio` is not `None`.
188
+ - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
189
+ `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
190
+ `None`).
191
+ - **labels** -- List of labels for the audio frames. Returned when `output_labels=True`.
192
+ """
193
+
194
+ output_kwargs = self._merge_kwargs(
195
+ CsmProcessorKwargs,
196
+ tokenizer_init_kwargs=self.tokenizer.init_kwargs,
197
+ **kwargs,
198
+ )
199
+
200
+ text_kwargs = output_kwargs["text_kwargs"]
201
+ audio_kwargs = output_kwargs["audio_kwargs"]
202
+ return_tensors = text_kwargs.get("return_tensors", None)
203
+ if return_tensors != "pt":
204
+ raise ValueError(f"{self.__class__.__name__} only supports `return_tensors='pt'`.")
205
+
206
+ if isinstance(text, str):
207
+ text = [text]
208
+ elif not (isinstance(text, (list, tuple)) and all(isinstance(t, str) for t in text)):
209
+ raise ValueError("Invalid input text. Please provide a string, or a list of strings")
210
+ n_audio_in_text = [t.count(self.audio_token) for t in text]
211
+
212
+ n_audio = 0
213
+ if audio is not None:
214
+ audio = make_list_of_audio(audio)
215
+ n_audio = len(audio)
216
+
217
+ if sum(n_audio_in_text) > 0 and n_audio != sum(n_audio_in_text):
218
+ if audio is None:
219
+ raise ValueError("No audio were provided, but there are audio tokens in the prompt")
220
+ else:
221
+ raise ValueError(
222
+ f"The number of audio tokens in each text ({n_audio_in_text}) should be the same as the "
223
+ f"number of provided audios ({n_audio})."
224
+ )
225
+
226
+ if audio is not None:
227
+ encoded_length_kwargs = audio_kwargs.pop("encoded_length_kwargs", {})
228
+ num_audio_tokens_list = [
229
+ self._get_encoded_length(audio_array.shape[-1], **encoded_length_kwargs) for audio_array in audio
230
+ ]
231
+ num_audio_tokens_list_copy = num_audio_tokens_list.copy()
232
+
233
+ # expand the text to repeat the audio token for the corresponding number of frames
234
+ expanded_text = []
235
+ for sample in text:
236
+ replace_str = []
237
+ while self.audio_token in sample:
238
+ num_audio_tokens = num_audio_tokens_list_copy.pop(0)
239
+ expanded_audio_token = self.audio_token * num_audio_tokens
240
+
241
+ replace_str.append(expanded_audio_token)
242
+ sample = sample.replace(self.audio_token, "<placeholder>", 1)
243
+
244
+ while "<placeholder>" in sample:
245
+ sample = sample.replace("<placeholder>", replace_str.pop(0), 1)
246
+ expanded_text.append(sample)
247
+
248
+ text = expanded_text
249
+
250
+ encoding = self.tokenizer(text, **text_kwargs)
251
+ data = {}
252
+ data.update(encoding)
253
+
254
+ if audio is not None:
255
+ audio_kwargs.pop("return_attention_mask", None) # not supported by the feature extractor
256
+
257
+ concatenated_audio, input_values_cutoffs = [], []
258
+ offset = 0
259
+ for n_audio in n_audio_in_text:
260
+ if n_audio == 0:
261
+ concatenated_audio.append(np.zeros(0))
262
+ input_values_cutoffs.append(torch.tensor([-1]))
263
+ else:
264
+ concatenated_audio.append(
265
+ np.concatenate(
266
+ [
267
+ el.cpu().numpy() if isinstance(el, torch.Tensor) else el
268
+ for el in audio[offset : offset + n_audio]
269
+ ],
270
+ axis=-1,
271
+ )
272
+ )
273
+ input_values_cutoffs.append(
274
+ torch.tensor([el.shape[-1] for el in audio[offset : offset + n_audio]]).cumsum(dim=-1)
275
+ )
276
+ offset += n_audio
277
+
278
+ audio_inputs = self.feature_extractor(concatenated_audio, **audio_kwargs)
279
+ audio_inputs.pop("padding_mask", None) # not applicable here
280
+ data.update(audio_inputs)
281
+
282
+ # pad and stack the audio cut idxs
283
+ max_len = max(cut_idxs.shape[-1] for cut_idxs in input_values_cutoffs)
284
+ input_values_cutoffs = [
285
+ torch.nn.functional.pad(cut_idxs, (0, max_len - cut_idxs.shape[-1]), value=-1)
286
+ for cut_idxs in input_values_cutoffs
287
+ ]
288
+ data["input_values_cutoffs"] = torch.stack(input_values_cutoffs, dim=0)
289
+
290
+ if output_labels:
291
+ audio_frame_idxs = (data["input_ids"] == self.audio_token_id).nonzero()
292
+ n_audio_frames = audio_frame_idxs.shape[0]
293
+
294
+ if depth_decoder_labels_ratio <= 1.0:
295
+ rand_idxs = torch.randperm(n_audio_frames)[: int(n_audio_frames * (1 - depth_decoder_labels_ratio))]
296
+ skip_frames_idxs = audio_frame_idxs[rand_idxs]
297
+ else:
298
+ skip_frames_idxs = audio_frame_idxs
299
+
300
+ labels = torch.where(
301
+ (data["input_ids"] == self.audio_token_id) | (data["input_ids"] == self.audio_eos_token_id),
302
+ data["input_ids"],
303
+ -100,
304
+ )
305
+ labels[skip_frames_idxs[:, 0], skip_frames_idxs[:, 1]] = -101
306
+
307
+ data["labels"] = labels
308
+
309
+ return BatchFeature(data=data, tensor_type=return_tensors)
310
+
311
+ @property
312
+ def model_input_names(self):
313
+ tokenizer_input_names = self.tokenizer.model_input_names
314
+ feature_extractor_input_names = self.feature_extractor.model_input_names
315
+
316
+ # Remove `padding_mask`, it is popped and not used when processing. Make a copy of list when removing
317
+ # otherwise `self.feature_extractor.model_input_names` is also modified
318
+ feature_extractor_input_names = [name for name in feature_extractor_input_names if name != "padding_mask"]
319
+ return list(tokenizer_input_names + feature_extractor_input_names + ["input_values_cutoffs"])
320
+
321
+
322
+ __all__ = ["CsmProcessor"]
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/ctrl/__init__.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_ctrl import *
22
+ from .modeling_ctrl import *
23
+ from .tokenization_ctrl import *
24
+ else:
25
+ import sys
26
+
27
+ _file = globals()["__file__"]
28
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/ctrl/configuration_ctrl.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2018 Salesforce and HuggingFace Inc. team.
2
+ # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
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
+ """Salesforce CTRL configuration"""
15
+
16
+ from ...configuration_utils import PreTrainedConfig
17
+ from ...utils import logging
18
+
19
+
20
+ logger = logging.get_logger(__name__)
21
+
22
+
23
+ class CTRLConfig(PreTrainedConfig):
24
+ """
25
+ This is the configuration class to store the configuration of a [`CTRLModel`]. It is used to
26
+ instantiate a CTRL model according to the specified arguments, defining the model architecture. Instantiating a
27
+ configuration with the defaults will yield a similar configuration to that of the
28
+ [Salesforce/ctrl](https://huggingface.co/Salesforce/ctrl) architecture from SalesForce.
29
+
30
+ Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the
31
+ documentation from [`PreTrainedConfig`] for more information.
32
+
33
+ Args:
34
+ vocab_size (`int`, *optional*, defaults to 246534):
35
+ Vocabulary size of the CTRL model. Defines the number of different tokens that can be represented by the
36
+ `inputs_ids` passed when calling [`CTRLModel`].
37
+ n_positions (`int`, *optional*, defaults to 256):
38
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
39
+ just in case (e.g., 512 or 1024 or 2048).
40
+ n_embd (`int`, *optional*, defaults to 1280):
41
+ Dimensionality of the embeddings and hidden states.
42
+ dff (`int`, *optional*, defaults to 8192):
43
+ Dimensionality of the inner dimension of the feed forward networks (FFN).
44
+ n_layer (`int`, *optional*, defaults to 48):
45
+ Number of hidden layers in the Transformer encoder.
46
+ n_head (`int`, *optional*, defaults to 16):
47
+ Number of attention heads for each attention layer in the Transformer encoder.
48
+ resid_pdrop (`float`, *optional*, defaults to 0.1):
49
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
50
+ embd_pdrop (`int`, *optional*, defaults to 0.1):
51
+ The dropout ratio for the embeddings.
52
+ layer_norm_epsilon (`float`, *optional*, defaults to 1e-06):
53
+ The epsilon to use in the layer normalization layers
54
+ initializer_range (`float`, *optional*, defaults to 0.02):
55
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
56
+ use_cache (`bool`, *optional*, defaults to `True`):
57
+ Whether or not the model should return the last key/values attentions (not used by all models).
58
+ pad_token_id (`int`, *optional*):
59
+ Padding token id.
60
+ bos_token_id (`int`, *optional*):
61
+ Beginning of stream token id.
62
+ eos_token_id (`int`, *optional*):
63
+ End of stream token id.
64
+ tie_word_embeddings (`bool`, *optional*, defaults to `True`):
65
+ Whether to tie weight embeddings
66
+
67
+
68
+ Examples:
69
+
70
+ ```python
71
+ >>> from transformers import CTRLConfig, CTRLModel
72
+
73
+ >>> # Initializing a CTRL configuration
74
+ >>> configuration = CTRLConfig()
75
+
76
+ >>> # Initializing a model (with random weights) from the configuration
77
+ >>> model = CTRLModel(configuration)
78
+
79
+ >>> # Accessing the model configuration
80
+ >>> configuration = model.config
81
+ ```"""
82
+
83
+ model_type = "ctrl"
84
+ keys_to_ignore_at_inference = ["past_key_values"]
85
+ attribute_map = {
86
+ "max_position_embeddings": "n_positions",
87
+ "hidden_size": "n_embd",
88
+ "num_attention_heads": "n_head",
89
+ "num_hidden_layers": "n_layer",
90
+ }
91
+
92
+ def __init__(
93
+ self,
94
+ vocab_size=246534,
95
+ n_positions=256,
96
+ n_embd=1280,
97
+ dff=8192,
98
+ n_layer=48,
99
+ n_head=16,
100
+ resid_pdrop=0.1,
101
+ embd_pdrop=0.1,
102
+ layer_norm_epsilon=1e-6,
103
+ initializer_range=0.02,
104
+ use_cache=True,
105
+ pad_token_id=None,
106
+ bos_token_id=None,
107
+ eos_token_id=None,
108
+ tie_word_embeddings=True,
109
+ **kwargs,
110
+ ):
111
+ self.vocab_size = vocab_size
112
+ self.n_positions = n_positions
113
+ self.n_embd = n_embd
114
+ self.n_layer = n_layer
115
+ self.n_head = n_head
116
+ self.dff = dff
117
+ self.resid_pdrop = resid_pdrop
118
+ self.embd_pdrop = embd_pdrop
119
+ self.layer_norm_epsilon = layer_norm_epsilon
120
+ self.initializer_range = initializer_range
121
+ self.pad_token_id = pad_token_id
122
+ self.bos_token_id = bos_token_id
123
+ self.eos_token_id = eos_token_id
124
+ self.tie_word_embeddings = tie_word_embeddings
125
+
126
+ self.use_cache = use_cache
127
+
128
+ super().__init__(**kwargs)
129
+
130
+
131
+ __all__ = ["CTRLConfig"]
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/ctrl/modeling_ctrl.py ADDED
@@ -0,0 +1,688 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2018 Salesforce and HuggingFace Inc. team.
2
+ # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """PyTorch CTRL model."""
16
+
17
+ import numpy as np
18
+ import torch
19
+ from torch import nn
20
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
21
+
22
+ from ... import initialization as init
23
+ from ...cache_utils import Cache, DynamicCache
24
+ from ...generation import GenerationMixin
25
+ from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutput
26
+ from ...modeling_utils import PreTrainedModel
27
+ from ...utils import (
28
+ auto_docstring,
29
+ logging,
30
+ )
31
+ from .configuration_ctrl import CTRLConfig
32
+
33
+
34
+ logger = logging.get_logger(__name__)
35
+
36
+
37
+ def angle_defn(pos, i, d_model_size):
38
+ angle_rates = 1 / torch.pow(10000, (2 * (i // 2)) / d_model_size)
39
+ return pos * angle_rates
40
+
41
+
42
+ def positional_encoding(position, d_model_size, dtype):
43
+ # create the sinusoidal pattern for the positional encoding
44
+ angle_rads = angle_defn(
45
+ torch.arange(position, dtype=torch.int64).to(dtype).unsqueeze(1),
46
+ torch.arange(d_model_size, dtype=torch.int64).to(dtype).unsqueeze(0),
47
+ d_model_size,
48
+ )
49
+
50
+ sines = torch.sin(angle_rads[:, 0::2])
51
+ cosines = torch.cos(angle_rads[:, 1::2])
52
+
53
+ pos_encoding = torch.cat([sines, cosines], dim=-1)
54
+ return pos_encoding
55
+
56
+
57
+ def scaled_dot_product_attention(q, k, v, mask, attention_mask=None):
58
+ # calculate attention
59
+ matmul_qk = torch.matmul(q, k.permute(0, 1, 3, 2))
60
+
61
+ dk = k.shape[-1]
62
+ scaled_attention_logits = matmul_qk / np.sqrt(dk)
63
+
64
+ if mask is not None:
65
+ nd, ns = scaled_attention_logits.size(-2), scaled_attention_logits.size(-1)
66
+ scaled_attention_logits += mask[ns - nd : ns, :ns] * -1e4
67
+
68
+ if attention_mask is not None:
69
+ # Apply the attention mask
70
+ scaled_attention_logits = scaled_attention_logits + attention_mask
71
+
72
+ attention_weights = torch.softmax(scaled_attention_logits, dim=-1)
73
+
74
+ output = torch.matmul(attention_weights, v)
75
+
76
+ return output, attention_weights
77
+
78
+
79
+ class MultiHeadAttention(nn.Module):
80
+ def __init__(self, d_model_size, num_heads, layer_idx=None):
81
+ super().__init__()
82
+ self.num_heads = num_heads
83
+ self.d_model_size = d_model_size
84
+ self.layer_idx = layer_idx
85
+
86
+ self.depth = int(d_model_size / self.num_heads)
87
+
88
+ self.Wq = nn.Linear(d_model_size, d_model_size)
89
+ self.Wk = nn.Linear(d_model_size, d_model_size)
90
+ self.Wv = nn.Linear(d_model_size, d_model_size)
91
+
92
+ self.dense = nn.Linear(d_model_size, d_model_size)
93
+
94
+ def split_into_heads(self, x, batch_size):
95
+ x = x.reshape(batch_size, -1, self.num_heads, self.depth)
96
+ return x.permute([0, 2, 1, 3])
97
+
98
+ def forward(
99
+ self,
100
+ v,
101
+ k,
102
+ q,
103
+ mask,
104
+ layer_past=None,
105
+ attention_mask=None,
106
+ use_cache=False,
107
+ output_attentions=False,
108
+ cache_position=None,
109
+ ):
110
+ batch_size = q.shape[0]
111
+
112
+ q = self.Wq(q)
113
+ k = self.Wk(k)
114
+ v = self.Wv(v)
115
+
116
+ q = self.split_into_heads(q, batch_size)
117
+ k = self.split_into_heads(k, batch_size)
118
+ v = self.split_into_heads(v, batch_size)
119
+
120
+ if layer_past is not None:
121
+ k, v = layer_past.update(k, v, self.layer_idx, {"cache_position": cache_position})
122
+
123
+ output = scaled_dot_product_attention(q, k, v, mask, attention_mask)
124
+ scaled_attention = output[0].permute([0, 2, 1, 3])
125
+ attn = output[1]
126
+ original_size_attention = scaled_attention.reshape(batch_size, -1, self.d_model_size)
127
+ output = self.dense(original_size_attention)
128
+ return output, attn
129
+
130
+
131
+ def point_wise_feed_forward_network(d_model_size, dff):
132
+ return nn.Sequential(nn.Linear(d_model_size, dff), nn.ReLU(), nn.Linear(dff, d_model_size))
133
+
134
+
135
+ class EncoderLayer(nn.Module):
136
+ def __init__(self, d_model_size, num_heads, dff, rate=0.1, layer_idx=None):
137
+ super().__init__()
138
+
139
+ self.multi_head_attention = MultiHeadAttention(d_model_size, num_heads, layer_idx=layer_idx)
140
+ self.ffn = point_wise_feed_forward_network(d_model_size, dff)
141
+
142
+ self.layernorm1 = nn.LayerNorm(d_model_size, eps=1e-6)
143
+ self.layernorm2 = nn.LayerNorm(d_model_size, eps=1e-6)
144
+
145
+ self.dropout1 = nn.Dropout(rate)
146
+ self.dropout2 = nn.Dropout(rate)
147
+
148
+ def forward(
149
+ self,
150
+ x,
151
+ mask,
152
+ layer_past=None,
153
+ attention_mask=None,
154
+ use_cache=False,
155
+ output_attentions=False,
156
+ cache_position=None,
157
+ ):
158
+ normed = self.layernorm1(x)
159
+ attn_outputs = self.multi_head_attention(
160
+ normed,
161
+ normed,
162
+ normed,
163
+ mask,
164
+ layer_past=layer_past,
165
+ attention_mask=attention_mask,
166
+ use_cache=use_cache,
167
+ output_attentions=output_attentions,
168
+ cache_position=cache_position,
169
+ )
170
+ attn_output = attn_outputs[0]
171
+ attn_output = self.dropout1(attn_output)
172
+ out1 = x + attn_output
173
+
174
+ out2 = self.layernorm2(out1)
175
+ ffn_output = self.ffn(out2)
176
+ ffn_output = self.dropout2(ffn_output)
177
+ out2 = out1 + ffn_output
178
+
179
+ outputs = (out2,) + attn_outputs[1:]
180
+ return outputs
181
+
182
+
183
+ @auto_docstring
184
+ class CTRLPreTrainedModel(PreTrainedModel):
185
+ config: CTRLConfig
186
+ base_model_prefix = "transformer"
187
+
188
+ def _init_weights(self, module):
189
+ super()._init_weights(module)
190
+ if isinstance(module, CTRLModel):
191
+ init.copy_(
192
+ module.pos_encoding, positional_encoding(module.config.n_positions, module.d_model_size, torch.float)
193
+ )
194
+
195
+
196
+ @auto_docstring
197
+ class CTRLModel(CTRLPreTrainedModel):
198
+ def __init__(self, config):
199
+ super().__init__(config)
200
+
201
+ self.d_model_size = config.n_embd
202
+ self.num_layers = config.n_layer
203
+
204
+ self.w = nn.Embedding(config.vocab_size, config.n_embd)
205
+
206
+ self.dropout = nn.Dropout(config.embd_pdrop)
207
+ self.h = nn.ModuleList(
208
+ [
209
+ EncoderLayer(config.n_embd, config.n_head, config.dff, config.resid_pdrop, layer_idx=i)
210
+ for i in range(config.n_layer)
211
+ ]
212
+ )
213
+ self.layernorm = nn.LayerNorm(config.n_embd, eps=config.layer_norm_epsilon)
214
+
215
+ self.register_buffer(
216
+ "pos_encoding", positional_encoding(config.n_positions, self.d_model_size, torch.float), persistent=False
217
+ )
218
+
219
+ # Initialize weights and apply final processing
220
+ self.post_init()
221
+
222
+ def get_input_embeddings(self):
223
+ return self.w
224
+
225
+ def set_input_embeddings(self, new_embeddings):
226
+ self.w = new_embeddings
227
+
228
+ @auto_docstring
229
+ def forward(
230
+ self,
231
+ input_ids: torch.LongTensor | None = None,
232
+ past_key_values: Cache | None = None,
233
+ attention_mask: torch.FloatTensor | None = None,
234
+ token_type_ids: torch.LongTensor | None = None,
235
+ position_ids: torch.LongTensor | None = None,
236
+ inputs_embeds: torch.FloatTensor | None = None,
237
+ use_cache: bool | None = None,
238
+ output_attentions: bool | None = None,
239
+ output_hidden_states: bool | None = None,
240
+ return_dict: bool | None = None,
241
+ cache_position: torch.Tensor | None = None,
242
+ **kwargs, # NOOP kwargs, for now
243
+ ) -> tuple[torch.Tensor] | BaseModelOutputWithPast:
244
+ r"""
245
+ Example:
246
+
247
+ ```python
248
+ >>> from transformers import AutoTokenizer, CTRLModel
249
+ >>> import torch
250
+
251
+ >>> tokenizer = AutoTokenizer.from_pretrained("Salesforce/ctrl")
252
+ >>> model = CTRLModel.from_pretrained("Salesforce/ctrl")
253
+
254
+ >>> # CTRL was trained with control codes as the first token
255
+ >>> inputs = tokenizer("Opinion My dog is cute", return_tensors="pt")
256
+ >>> assert inputs["input_ids"][0, 0].item() in tokenizer.control_codes.values()
257
+
258
+ >>> outputs = model(**inputs)
259
+
260
+ >>> last_hidden_states = outputs.last_hidden_state
261
+ >>> list(last_hidden_states.shape)
262
+ [1, 5, 1280]
263
+ ```"""
264
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
265
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
266
+ output_hidden_states = (
267
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
268
+ )
269
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
270
+
271
+ if input_ids is not None and inputs_embeds is not None:
272
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
273
+ elif input_ids is not None:
274
+ self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
275
+ input_shape = input_ids.size()
276
+ input_ids = input_ids.view(-1, input_shape[-1])
277
+ batch_size = input_ids.shape[0]
278
+ elif inputs_embeds is not None:
279
+ input_shape = inputs_embeds.size()[:-1]
280
+ batch_size = inputs_embeds.shape[0]
281
+ else:
282
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
283
+
284
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
285
+
286
+ if use_cache and past_key_values is None:
287
+ past_key_values = DynamicCache(config=self.config)
288
+
289
+ past_length = past_key_values.get_seq_length() if past_key_values is not None else 0
290
+ if position_ids is None:
291
+ position_ids = torch.arange(past_length, input_shape[-1] + past_length, dtype=torch.long, device=device)
292
+ position_ids = position_ids.unsqueeze(0)
293
+
294
+ # Attention mask.
295
+ if attention_mask is not None:
296
+ if batch_size <= 0:
297
+ raise ValueError("batch_size has to be defined and > 0")
298
+ attention_mask = attention_mask.view(batch_size, -1)
299
+ # We create a 3D attention mask from a 2D tensor mask.
300
+ # Sizes are [batch_size, 1, 1, to_seq_length]
301
+ # So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length]
302
+ # this attention mask is more simple than the triangular masking of causal attention
303
+ # used in OpenAI GPT, we just need to prepare the broadcast dimension here.
304
+ attention_mask = attention_mask.unsqueeze(1).unsqueeze(2)
305
+
306
+ # Since attention_mask is 1.0 for positions we want to attend and 0.0 for
307
+ # masked positions, this operation will create a tensor which is 0.0 for
308
+ # positions we want to attend and the dtype's smallest value for masked positions.
309
+ # Since we are adding it to the raw scores before the softmax, this is
310
+ # effectively the same as removing these entirely.
311
+ attention_mask = attention_mask.to(dtype=self.dtype) # fp16 compatibility
312
+ attention_mask = (1.0 - attention_mask) * torch.finfo(self.dtype).min
313
+
314
+ if token_type_ids is not None:
315
+ token_type_ids = token_type_ids.view(-1, input_shape[-1])
316
+ token_type_embeds = self.w(token_type_ids)
317
+ token_type_embeds *= np.sqrt(self.d_model_size)
318
+ else:
319
+ token_type_embeds = 0
320
+
321
+ if inputs_embeds is None:
322
+ inputs_embeds = self.w(input_ids)
323
+ # inputs_embeds = embedded.unsqueeze(0) if len(input_ids.shape)<2 else embedded
324
+ seq_len = input_shape[-1]
325
+ mask = torch.triu(torch.ones(seq_len + past_length, seq_len + past_length), 1).to(device)
326
+
327
+ inputs_embeds *= np.sqrt(self.d_model_size)
328
+
329
+ # `self.pos_encoding` won't be sent to the correct device along the model, so we do it manually.
330
+ self.pos_encoding = self.pos_encoding.to(device)
331
+ pos_embeds = self.pos_encoding[position_ids, :]
332
+
333
+ hidden_states = inputs_embeds + pos_embeds + token_type_embeds
334
+
335
+ hidden_states = self.dropout(hidden_states)
336
+
337
+ all_hidden_states = () if output_hidden_states else None
338
+ all_attentions = () if output_attentions else None
339
+ for i, h in enumerate(self.h):
340
+ if output_hidden_states:
341
+ all_hidden_states = all_hidden_states + (hidden_states,)
342
+ outputs = h(
343
+ hidden_states,
344
+ mask,
345
+ layer_past=past_key_values,
346
+ attention_mask=attention_mask,
347
+ use_cache=use_cache,
348
+ output_attentions=output_attentions,
349
+ cache_position=cache_position,
350
+ )
351
+ hidden_states = outputs[0]
352
+ if output_attentions:
353
+ all_attentions += (outputs[1],)
354
+
355
+ hidden_states = self.layernorm(hidden_states)
356
+ if output_hidden_states:
357
+ all_hidden_states = all_hidden_states + (hidden_states,)
358
+
359
+ if not return_dict:
360
+ return tuple(
361
+ v for v in [hidden_states, past_key_values, all_hidden_states, all_attentions] if v is not None
362
+ )
363
+
364
+ return BaseModelOutputWithPast(
365
+ last_hidden_state=hidden_states,
366
+ past_key_values=past_key_values,
367
+ hidden_states=all_hidden_states,
368
+ attentions=all_attentions,
369
+ )
370
+
371
+
372
+ @auto_docstring(
373
+ custom_intro="""
374
+ The CTRL Model transformer with a language modeling head on top (linear layer with weights tied to the input
375
+ embeddings).
376
+ """
377
+ )
378
+ class CTRLLMHeadModel(CTRLPreTrainedModel, GenerationMixin):
379
+ _tied_weights_keys = {"lm_head.weight": "transformer.w.weight"}
380
+
381
+ def __init__(self, config):
382
+ super().__init__(config)
383
+ self.transformer = CTRLModel(config)
384
+ self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=True)
385
+
386
+ # Initialize weights and apply final processing
387
+ self.post_init()
388
+
389
+ @auto_docstring
390
+ def forward(
391
+ self,
392
+ input_ids: torch.LongTensor | None = None,
393
+ past_key_values: Cache | None = None,
394
+ attention_mask: torch.FloatTensor | None = None,
395
+ token_type_ids: torch.LongTensor | None = None,
396
+ position_ids: torch.LongTensor | None = None,
397
+ inputs_embeds: torch.FloatTensor | None = None,
398
+ labels: torch.LongTensor | None = None,
399
+ use_cache: bool | None = None,
400
+ output_attentions: bool | None = None,
401
+ output_hidden_states: bool | None = None,
402
+ return_dict: bool | None = None,
403
+ cache_position: torch.Tensor | None = None,
404
+ logits_to_keep: int | torch.Tensor = 0,
405
+ **kwargs,
406
+ ) -> tuple[torch.Tensor] | CausalLMOutputWithPast:
407
+ r"""
408
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
409
+ Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
410
+ `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
411
+ are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
412
+
413
+ Example:
414
+
415
+ ```python
416
+ >>> import torch
417
+ >>> from transformers import AutoTokenizer, CTRLLMHeadModel
418
+
419
+ >>> tokenizer = AutoTokenizer.from_pretrained("Salesforce/ctrl")
420
+ >>> model = CTRLLMHeadModel.from_pretrained("Salesforce/ctrl")
421
+
422
+ >>> # CTRL was trained with control codes as the first token
423
+ >>> inputs = tokenizer("Wikipedia The llama is", return_tensors="pt")
424
+ >>> assert inputs["input_ids"][0, 0].item() in tokenizer.control_codes.values()
425
+
426
+ >>> sequence_ids = model.generate(inputs["input_ids"])
427
+ >>> sequences = tokenizer.batch_decode(sequence_ids)
428
+ >>> sequences
429
+ ['Wikipedia The llama is a member of the family Bovidae. It is native to the Andes of Peru,']
430
+
431
+ >>> outputs = model(**inputs, labels=inputs["input_ids"])
432
+ >>> round(outputs.loss.item(), 2)
433
+ 9.21
434
+
435
+ >>> list(outputs.logits.shape)
436
+ [1, 5, 246534]
437
+ ```"""
438
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
439
+
440
+ transformer_outputs = self.transformer(
441
+ input_ids,
442
+ past_key_values=past_key_values,
443
+ attention_mask=attention_mask,
444
+ token_type_ids=token_type_ids,
445
+ position_ids=position_ids,
446
+ inputs_embeds=inputs_embeds,
447
+ use_cache=use_cache,
448
+ output_attentions=output_attentions,
449
+ output_hidden_states=output_hidden_states,
450
+ return_dict=return_dict,
451
+ cache_position=cache_position,
452
+ )
453
+
454
+ hidden_states = transformer_outputs[0]
455
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
456
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
457
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
458
+
459
+ loss = None
460
+ if labels is not None:
461
+ loss = self.loss_function(
462
+ logits,
463
+ labels,
464
+ vocab_size=self.config.vocab_size,
465
+ **kwargs,
466
+ )
467
+
468
+ if not return_dict:
469
+ output = (logits,) + transformer_outputs[1:]
470
+ return ((loss,) + output) if loss is not None else output
471
+
472
+ return CausalLMOutputWithPast(
473
+ loss=loss,
474
+ logits=logits,
475
+ past_key_values=transformer_outputs.past_key_values,
476
+ hidden_states=transformer_outputs.hidden_states,
477
+ attentions=transformer_outputs.attentions,
478
+ )
479
+
480
+ def prepare_inputs_for_generation(
481
+ self, input_ids, past_key_values=None, use_cache=None, is_first_iteration=False, **kwargs
482
+ ):
483
+ # Overwritten -- `token_type_ids` are created in custom way inside model`
484
+
485
+ model_inputs = super().prepare_inputs_for_generation(
486
+ input_ids,
487
+ past_key_values=past_key_values,
488
+ use_cache=use_cache,
489
+ is_first_iteration=is_first_iteration,
490
+ **kwargs,
491
+ )
492
+
493
+ # token_type_ids are computed on CTRLModel.forward()
494
+ model_inputs.pop("token_type_ids", None)
495
+
496
+ return model_inputs
497
+
498
+
499
+ @auto_docstring(
500
+ custom_intro="""
501
+ The CTRL Model transformer with a sequence classification head on top (linear layer).
502
+ [`CTRLForSequenceClassification`] uses the last token in order to do the classification, as other causal models
503
+ (e.g. GPT-2) do. Since it does classification on the last token, it requires to know the position of the last
504
+ token. If a `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in
505
+ each row. If no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot
506
+ guess the padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last
507
+ value in each row of the batch).
508
+ """
509
+ )
510
+ class CTRLForSequenceClassification(CTRLPreTrainedModel):
511
+ def __init__(self, config):
512
+ super().__init__(config)
513
+ self.num_labels = config.num_labels
514
+ self.transformer = CTRLModel(config)
515
+ self.classifier = nn.Linear(config.n_embd, self.num_labels, bias=False)
516
+
517
+ # Initialize weights and apply final processing
518
+ self.post_init()
519
+
520
+ @auto_docstring
521
+ def forward(
522
+ self,
523
+ input_ids: torch.LongTensor | None = None,
524
+ past_key_values: Cache | None = None,
525
+ attention_mask: torch.FloatTensor | None = None,
526
+ token_type_ids: torch.LongTensor | None = None,
527
+ position_ids: torch.LongTensor | None = None,
528
+ inputs_embeds: torch.FloatTensor | None = None,
529
+ labels: torch.LongTensor | None = None,
530
+ use_cache: bool | None = None,
531
+ output_attentions: bool | None = None,
532
+ output_hidden_states: bool | None = None,
533
+ return_dict: bool | None = None,
534
+ **kwargs,
535
+ ) -> tuple[torch.Tensor] | SequenceClassifierOutput:
536
+ r"""
537
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
538
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
539
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
540
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
541
+
542
+ Example of single-label classification:
543
+
544
+ ```python
545
+ >>> import torch
546
+ >>> from transformers import AutoTokenizer, CTRLForSequenceClassification
547
+
548
+ >>> tokenizer = AutoTokenizer.from_pretrained("Salesforce/ctrl")
549
+ >>> model = CTRLForSequenceClassification.from_pretrained("Salesforce/ctrl")
550
+
551
+ >>> # CTRL was trained with control codes as the first token
552
+ >>> inputs = tokenizer("Opinion My dog is cute", return_tensors="pt")
553
+ >>> assert inputs["input_ids"][0, 0].item() in tokenizer.control_codes.values()
554
+
555
+ >>> with torch.no_grad():
556
+ ... logits = model(**inputs).logits
557
+
558
+ >>> predicted_class_id = logits.argmax().item()
559
+ >>> model.config.id2label[predicted_class_id]
560
+ 'LABEL_0'
561
+ ```
562
+
563
+ ```python
564
+ >>> import torch
565
+
566
+ >>> torch.manual_seed(42) # doctest: +IGNORE_RESULT
567
+ >>> # To train a model on `num_labels` classes, you can pass `num_labels=num_labels` to `.from_pretrained(...)`
568
+ >>> num_labels = len(model.config.id2label)
569
+ >>> model = CTRLForSequenceClassification.from_pretrained("Salesforce/ctrl", num_labels=num_labels)
570
+
571
+ >>> labels = torch.tensor(1)
572
+ >>> loss = model(**inputs, labels=labels).loss
573
+ >>> round(loss.item(), 2)
574
+ 0.93
575
+ ```
576
+
577
+ Example of multi-label classification:
578
+
579
+ ```python
580
+ >>> import torch
581
+ >>> from transformers import AutoTokenizer, CTRLForSequenceClassification
582
+
583
+ >>> tokenizer = AutoTokenizer.from_pretrained("Salesforce/ctrl")
584
+ >>> model = CTRLForSequenceClassification.from_pretrained(
585
+ ... "Salesforce/ctrl", problem_type="multi_label_classification"
586
+ ... )
587
+
588
+ >>> # CTRL was trained with control codes as the first token
589
+ >>> inputs = tokenizer("Opinion My dog is cute", return_tensors="pt")
590
+ >>> assert inputs["input_ids"][0, 0].item() in tokenizer.control_codes.values()
591
+
592
+ >>> with torch.no_grad():
593
+ ... logits = model(**inputs).logits
594
+
595
+ >>> predicted_class_id = logits.argmax().item()
596
+ >>> model.config.id2label[predicted_class_id]
597
+ 'LABEL_0'
598
+ ```
599
+
600
+ ```python
601
+ >>> # To train a model on `num_labels` classes, you can pass `num_labels=num_labels` to `.from_pretrained(...)`
602
+ >>> num_labels = len(model.config.id2label)
603
+ >>> model = CTRLForSequenceClassification.from_pretrained("Salesforce/ctrl", num_labels=num_labels)
604
+
605
+ >>> num_labels = len(model.config.id2label)
606
+ >>> labels = torch.nn.functional.one_hot(torch.tensor([predicted_class_id]), num_classes=num_labels).to(
607
+ ... torch.float
608
+ ... )
609
+ >>> loss = model(**inputs, labels=labels).loss
610
+ >>> loss.backward() # doctest: +IGNORE_RESULT
611
+ ```"""
612
+
613
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
614
+
615
+ transformer_outputs = self.transformer(
616
+ input_ids,
617
+ past_key_values=past_key_values,
618
+ attention_mask=attention_mask,
619
+ token_type_ids=token_type_ids,
620
+ position_ids=position_ids,
621
+ inputs_embeds=inputs_embeds,
622
+ use_cache=use_cache,
623
+ output_attentions=output_attentions,
624
+ output_hidden_states=output_hidden_states,
625
+ return_dict=return_dict,
626
+ )
627
+
628
+ hidden_states = transformer_outputs[0]
629
+ logits = self.classifier(hidden_states)
630
+
631
+ if input_ids is not None:
632
+ batch_size, sequence_length = input_ids.shape[:2]
633
+ else:
634
+ batch_size, sequence_length = inputs_embeds.shape[:2]
635
+
636
+ if self.config.pad_token_id is None and batch_size != 1:
637
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
638
+ if self.config.pad_token_id is None:
639
+ last_non_pad_token = -1
640
+ elif input_ids is not None:
641
+ # To handle both left- and right- padding, we take the rightmost token that is not equal to pad_token_id
642
+ non_pad_mask = (input_ids != self.config.pad_token_id).to(logits.device, torch.int32)
643
+ token_indices = torch.arange(input_ids.shape[-1], device=logits.device, dtype=torch.int32)
644
+ last_non_pad_token = (token_indices * non_pad_mask).argmax(-1)
645
+ else:
646
+ last_non_pad_token = -1
647
+ logger.warning_once(
648
+ f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
649
+ "unexpected if using padding tokens in conjunction with `inputs_embeds.`"
650
+ )
651
+
652
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), last_non_pad_token]
653
+
654
+ loss = None
655
+ if labels is not None:
656
+ if self.config.problem_type is None:
657
+ if self.num_labels == 1:
658
+ self.config.problem_type = "regression"
659
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
660
+ self.config.problem_type = "single_label_classification"
661
+ else:
662
+ self.config.problem_type = "multi_label_classification"
663
+
664
+ if self.config.problem_type == "regression":
665
+ loss_fct = MSELoss()
666
+ if self.num_labels == 1:
667
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
668
+ else:
669
+ loss = loss_fct(pooled_logits, labels)
670
+ elif self.config.problem_type == "single_label_classification":
671
+ loss_fct = CrossEntropyLoss()
672
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
673
+ elif self.config.problem_type == "multi_label_classification":
674
+ loss_fct = BCEWithLogitsLoss()
675
+ loss = loss_fct(pooled_logits, labels)
676
+ if not return_dict:
677
+ output = (pooled_logits,) + transformer_outputs[2:]
678
+ return ((loss,) + output) if loss is not None else output
679
+
680
+ return SequenceClassifierOutput(
681
+ loss=loss,
682
+ logits=pooled_logits,
683
+ hidden_states=transformer_outputs.hidden_states,
684
+ attentions=transformer_outputs.attentions,
685
+ )
686
+
687
+
688
+ __all__ = ["CTRLForSequenceClassification", "CTRLLMHeadModel", "CTRLModel", "CTRLPreTrainedModel"]
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/ctrl/tokenization_ctrl.py ADDED
@@ -0,0 +1,226 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2018 Salesforce and 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
+ """Tokenization classes for Salesforce CTRL."""
15
+
16
+ import json
17
+
18
+ import regex as re
19
+
20
+ from ...tokenization_python import PreTrainedTokenizer
21
+ from ...utils import logging
22
+
23
+
24
+ logger = logging.get_logger(__name__)
25
+
26
+ VOCAB_FILES_NAMES = {
27
+ "vocab_file": "vocab.json",
28
+ "merges_file": "merges.txt",
29
+ }
30
+
31
+
32
+ CONTROL_CODES = {
33
+ "Pregnancy": 168629,
34
+ "Christianity": 7675,
35
+ "Explain": 106423,
36
+ "Fitness": 63440,
37
+ "Saving": 63163,
38
+ "Ask": 27171,
39
+ "Ass": 95985,
40
+ "Joke": 163509,
41
+ "Questions": 45622,
42
+ "Thoughts": 49605,
43
+ "Retail": 52342,
44
+ "Feminism": 164338,
45
+ "Writing": 11992,
46
+ "Atheism": 192263,
47
+ "Netflix": 48616,
48
+ "Computing": 39639,
49
+ "Opinion": 43213,
50
+ "Alone": 44967,
51
+ "Funny": 58917,
52
+ "Gaming": 40358,
53
+ "Human": 4088,
54
+ "India": 1331,
55
+ "Joker": 77138,
56
+ "Diet": 36206,
57
+ "Legal": 11859,
58
+ "Norman": 4939,
59
+ "Tip": 72689,
60
+ "Weight": 52343,
61
+ "Movies": 46273,
62
+ "Running": 23425,
63
+ "Science": 2090,
64
+ "Horror": 37793,
65
+ "Confession": 60572,
66
+ "Finance": 12250,
67
+ "Politics": 16360,
68
+ "Scary": 191985,
69
+ "Support": 12654,
70
+ "Technologies": 32516,
71
+ "Teenage": 66160,
72
+ "Event": 32769,
73
+ "Learned": 67460,
74
+ "Notion": 182770,
75
+ "Wikipedia": 37583,
76
+ "Books": 6665,
77
+ "Extract": 76050,
78
+ "Confessions": 102701,
79
+ "Conspiracy": 75932,
80
+ "Links": 63674,
81
+ "Narcissus": 150425,
82
+ "Relationship": 54766,
83
+ "Relationships": 134796,
84
+ "Reviews": 41671,
85
+ "News": 4256,
86
+ "Translation": 26820,
87
+ "multilingual": 128406,
88
+ }
89
+
90
+
91
+ def get_pairs(word):
92
+ """
93
+ Return set of symbol pairs in a word.
94
+
95
+ Word is represented as tuple of symbols (symbols being variable-length strings).
96
+ """
97
+ pairs = set()
98
+ prev_char = word[0]
99
+ for char in word[1:]:
100
+ pairs.add((prev_char, char))
101
+ prev_char = char
102
+
103
+ pairs = set(pairs)
104
+ return pairs
105
+
106
+
107
+ class CTRLTokenizer(PreTrainedTokenizer):
108
+ """
109
+ Construct a CTRL tokenizer. Based on Byte-Pair-Encoding.
110
+
111
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
112
+ this superclass for more information regarding those methods.
113
+
114
+ Args:
115
+ vocab_file (`str`):
116
+ Path to the vocabulary file.
117
+ merges_file (`str`):
118
+ Path to the merges file.
119
+ unk_token (`str`, *optional*, defaults to `"<unk>"`):
120
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
121
+ token instead.
122
+ """
123
+
124
+ vocab_files_names = VOCAB_FILES_NAMES
125
+ control_codes = CONTROL_CODES
126
+
127
+ def __init__(self, vocab_file, merges_file, unk_token="<unk>", **kwargs):
128
+ with open(vocab_file, encoding="utf-8") as vocab_handle:
129
+ self.encoder = json.load(vocab_handle)
130
+ self.decoder = {v: k for k, v in self.encoder.items()}
131
+ with open(merges_file, encoding="utf-8") as merges_handle:
132
+ merges = merges_handle.read().split("\n")[1:-1]
133
+ merges = [tuple(merge.split()) for merge in merges]
134
+ self.bpe_ranks = dict(zip(merges, range(len(merges))))
135
+ self.cache = {}
136
+ self.add_bpe_version_header = True
137
+ super().__init__(
138
+ unk_token=unk_token,
139
+ token_type_ids_pattern="all_zeros",
140
+ token_type_ids_include_special_tokens=True,
141
+ special_tokens_pattern="none",
142
+ **kwargs,
143
+ )
144
+
145
+ @property
146
+ def vocab_size(self):
147
+ return len(self.encoder)
148
+
149
+ def get_vocab(self):
150
+ return dict(self.encoder, **self.added_tokens_encoder)
151
+
152
+ def bpe(self, token):
153
+ if token in self.cache:
154
+ return self.cache[token]
155
+ word = tuple(token)
156
+ word = tuple(list(word[:-1]) + [word[-1] + "</w>"])
157
+ pairs = get_pairs(word)
158
+
159
+ if not pairs:
160
+ return token
161
+
162
+ while True:
163
+ bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
164
+ if bigram not in self.bpe_ranks:
165
+ break
166
+ first, second = bigram
167
+ new_word = []
168
+ i = 0
169
+ while i < len(word):
170
+ try:
171
+ j = word.index(first, i)
172
+ except ValueError:
173
+ new_word.extend(word[i:])
174
+ break
175
+ else:
176
+ new_word.extend(word[i:j])
177
+ i = j
178
+
179
+ if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
180
+ new_word.append(first + second)
181
+ i += 2
182
+ else:
183
+ new_word.append(word[i])
184
+ i += 1
185
+ new_word = tuple(new_word)
186
+ word = new_word
187
+ if len(word) == 1:
188
+ break
189
+ else:
190
+ pairs = get_pairs(word)
191
+ word = "@@ ".join(word)
192
+ word = word[:-4]
193
+ self.cache[token] = word
194
+ return word
195
+
196
+ def _tokenize(self, text):
197
+ """Tokenize a string."""
198
+ split_tokens = []
199
+
200
+ words = re.findall(r"\S+\n?", text)
201
+
202
+ for token in words:
203
+ split_tokens.extend(list(self.bpe(token).split(" ")))
204
+ return split_tokens
205
+
206
+ def _convert_token_to_id(self, token):
207
+ """Converts a token (str) in an id using the vocab."""
208
+ return self.encoder.get(token, self.encoder.get(self.unk_token))
209
+
210
+ def _convert_id_to_token(self, index):
211
+ """Converts an index (integer) in a token (str) using the vocab."""
212
+ return self.decoder.get(index, self.unk_token)
213
+
214
+ def convert_tokens_to_string(self, tokens):
215
+ """Converts a sequence of tokens (string) in a single string."""
216
+ out_string = " ".join(tokens).replace("@@ ", "").strip()
217
+ return out_string
218
+
219
+ # def decode(self, token_ids, skip_special_tokens=False, clean_up_tokenization_spaces=True):
220
+ # filtered_tokens = ' '.join(self.convert_ids_to_tokens(token_ids, skip_special_tokens=skip_special_tokens))
221
+ # tokens_generated_so_far = re.sub('(@@ )', '', string=filtered_tokens)
222
+ # tokens_generated_so_far = re.sub('(@@ ?$)', '', string=tokens_generated_so_far)
223
+ # return ''.join(tokens_generated_so_far)
224
+
225
+
226
+ __all__ = ["CTRLTokenizer"]
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/cvt/__init__.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_cvt import *
22
+ from .modeling_cvt import *
23
+ else:
24
+ import sys
25
+
26
+ _file = globals()["__file__"]
27
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/cvt/configuration_cvt.py ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 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
+ """CvT model configuration"""
15
+
16
+ from ...configuration_utils import PreTrainedConfig
17
+ from ...utils import logging
18
+
19
+
20
+ logger = logging.get_logger(__name__)
21
+
22
+
23
+ class CvtConfig(PreTrainedConfig):
24
+ r"""
25
+ This is the configuration class to store the configuration of a [`CvtModel`]. It is used to instantiate a CvT model
26
+ according to the specified arguments, defining the model architecture. Instantiating a configuration with the
27
+ defaults will yield a similar configuration to that of the CvT
28
+ [microsoft/cvt-13](https://huggingface.co/microsoft/cvt-13) architecture.
29
+
30
+ Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the
31
+ documentation from [`PreTrainedConfig`] for more information.
32
+
33
+ Args:
34
+ num_channels (`int`, *optional*, defaults to 3):
35
+ The number of input channels.
36
+ patch_sizes (`list[int]`, *optional*, defaults to `[7, 3, 3]`):
37
+ The kernel size of each encoder's patch embedding.
38
+ patch_stride (`list[int]`, *optional*, defaults to `[4, 2, 2]`):
39
+ The stride size of each encoder's patch embedding.
40
+ patch_padding (`list[int]`, *optional*, defaults to `[2, 1, 1]`):
41
+ The padding size of each encoder's patch embedding.
42
+ embed_dim (`list[int]`, *optional*, defaults to `[64, 192, 384]`):
43
+ Dimension of each of the encoder blocks.
44
+ num_heads (`list[int]`, *optional*, defaults to `[1, 3, 6]`):
45
+ Number of attention heads for each attention layer in each block of the Transformer encoder.
46
+ depth (`list[int]`, *optional*, defaults to `[1, 2, 10]`):
47
+ The number of layers in each encoder block.
48
+ mlp_ratios (`list[float]`, *optional*, defaults to `[4.0, 4.0, 4.0, 4.0]`):
49
+ Ratio of the size of the hidden layer compared to the size of the input layer of the Mix FFNs in the
50
+ encoder blocks.
51
+ attention_drop_rate (`list[float]`, *optional*, defaults to `[0.0, 0.0, 0.0]`):
52
+ The dropout ratio for the attention probabilities.
53
+ drop_rate (`list[float]`, *optional*, defaults to `[0.0, 0.0, 0.0]`):
54
+ The dropout ratio for the patch embeddings probabilities.
55
+ drop_path_rate (`list[float]`, *optional*, defaults to `[0.0, 0.0, 0.1]`):
56
+ The dropout probability for stochastic depth, used in the blocks of the Transformer encoder.
57
+ qkv_bias (`list[bool]`, *optional*, defaults to `[True, True, True]`):
58
+ The bias bool for query, key and value in attentions
59
+ cls_token (`list[bool]`, *optional*, defaults to `[False, False, True]`):
60
+ Whether or not to add a classification token to the output of each of the last 3 stages.
61
+ qkv_projection_method (`list[string]`, *optional*, defaults to ["dw_bn", "dw_bn", "dw_bn"]`):
62
+ The projection method for query, key and value Default is depth-wise convolutions with batch norm. For
63
+ Linear projection use "avg".
64
+ kernel_qkv (`list[int]`, *optional*, defaults to `[3, 3, 3]`):
65
+ The kernel size for query, key and value in attention layer
66
+ padding_kv (`list[int]`, *optional*, defaults to `[1, 1, 1]`):
67
+ The padding size for key and value in attention layer
68
+ stride_kv (`list[int]`, *optional*, defaults to `[2, 2, 2]`):
69
+ The stride size for key and value in attention layer
70
+ padding_q (`list[int]`, *optional*, defaults to `[1, 1, 1]`):
71
+ The padding size for query in attention layer
72
+ stride_q (`list[int]`, *optional*, defaults to `[1, 1, 1]`):
73
+ The stride size for query in attention layer
74
+ initializer_range (`float`, *optional*, defaults to 0.02):
75
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
76
+ layer_norm_eps (`float`, *optional*, defaults to 1e-6):
77
+ The epsilon used by the layer normalization layers.
78
+
79
+ Example:
80
+
81
+ ```python
82
+ >>> from transformers import CvtConfig, CvtModel
83
+
84
+ >>> # Initializing a Cvt msft/cvt style configuration
85
+ >>> configuration = CvtConfig()
86
+
87
+ >>> # Initializing a model (with random weights) from the msft/cvt style configuration
88
+ >>> model = CvtModel(configuration)
89
+
90
+ >>> # Accessing the model configuration
91
+ >>> configuration = model.config
92
+ ```"""
93
+
94
+ model_type = "cvt"
95
+
96
+ def __init__(
97
+ self,
98
+ num_channels=3,
99
+ patch_sizes=[7, 3, 3],
100
+ patch_stride=[4, 2, 2],
101
+ patch_padding=[2, 1, 1],
102
+ embed_dim=[64, 192, 384],
103
+ num_heads=[1, 3, 6],
104
+ depth=[1, 2, 10],
105
+ mlp_ratio=[4.0, 4.0, 4.0],
106
+ attention_drop_rate=[0.0, 0.0, 0.0],
107
+ drop_rate=[0.0, 0.0, 0.0],
108
+ drop_path_rate=[0.0, 0.0, 0.1],
109
+ qkv_bias=[True, True, True],
110
+ cls_token=[False, False, True],
111
+ qkv_projection_method=["dw_bn", "dw_bn", "dw_bn"],
112
+ kernel_qkv=[3, 3, 3],
113
+ padding_kv=[1, 1, 1],
114
+ stride_kv=[2, 2, 2],
115
+ padding_q=[1, 1, 1],
116
+ stride_q=[1, 1, 1],
117
+ initializer_range=0.02,
118
+ layer_norm_eps=1e-12,
119
+ **kwargs,
120
+ ):
121
+ super().__init__(**kwargs)
122
+ self.num_channels = num_channels
123
+ self.patch_sizes = patch_sizes
124
+ self.patch_stride = patch_stride
125
+ self.patch_padding = patch_padding
126
+ self.embed_dim = embed_dim
127
+ self.num_heads = num_heads
128
+ self.depth = depth
129
+ self.mlp_ratio = mlp_ratio
130
+ self.attention_drop_rate = attention_drop_rate
131
+ self.drop_rate = drop_rate
132
+ self.drop_path_rate = drop_path_rate
133
+ self.qkv_bias = qkv_bias
134
+ self.cls_token = cls_token
135
+ self.qkv_projection_method = qkv_projection_method
136
+ self.kernel_qkv = kernel_qkv
137
+ self.padding_kv = padding_kv
138
+ self.stride_kv = stride_kv
139
+ self.padding_q = padding_q
140
+ self.stride_q = stride_q
141
+ self.initializer_range = initializer_range
142
+ self.layer_norm_eps = layer_norm_eps
143
+
144
+
145
+ __all__ = ["CvtConfig"]
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/cvt/modeling_cvt.py ADDED
@@ -0,0 +1,641 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 Microsoft Research and 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
+ """PyTorch CvT model."""
15
+
16
+ import collections.abc
17
+ from dataclasses import dataclass
18
+
19
+ import torch
20
+ from torch import nn
21
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
22
+
23
+ from ... import initialization as init
24
+ from ...modeling_outputs import ImageClassifierOutputWithNoAttention, ModelOutput
25
+ from ...modeling_utils import PreTrainedModel
26
+ from ...utils import auto_docstring, logging
27
+ from .configuration_cvt import CvtConfig
28
+
29
+
30
+ logger = logging.get_logger(__name__)
31
+
32
+
33
+ @dataclass
34
+ @auto_docstring(
35
+ custom_intro="""
36
+ Base class for model's outputs, with potential hidden states and attentions.
37
+ """
38
+ )
39
+ class BaseModelOutputWithCLSToken(ModelOutput):
40
+ r"""
41
+ cls_token_value (`torch.FloatTensor` of shape `(batch_size, 1, hidden_size)`):
42
+ Classification token at the output of the last layer of the model.
43
+ """
44
+
45
+ last_hidden_state: torch.FloatTensor | None = None
46
+ cls_token_value: torch.FloatTensor | None = None
47
+ hidden_states: tuple[torch.FloatTensor, ...] | None = None
48
+
49
+
50
+ # Copied from transformers.models.beit.modeling_beit.drop_path
51
+ def drop_path(input: torch.Tensor, drop_prob: float = 0.0, training: bool = False) -> torch.Tensor:
52
+ """
53
+ Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
54
+
55
+ """
56
+ if drop_prob == 0.0 or not training:
57
+ return input
58
+ keep_prob = 1 - drop_prob
59
+ shape = (input.shape[0],) + (1,) * (input.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
60
+ random_tensor = keep_prob + torch.rand(shape, dtype=input.dtype, device=input.device)
61
+ random_tensor.floor_() # binarize
62
+ output = input.div(keep_prob) * random_tensor
63
+ return output
64
+
65
+
66
+ # Copied from transformers.models.beit.modeling_beit.BeitDropPath
67
+ class CvtDropPath(nn.Module):
68
+ """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
69
+
70
+ def __init__(self, drop_prob: float | None = None) -> None:
71
+ super().__init__()
72
+ self.drop_prob = drop_prob
73
+
74
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
75
+ return drop_path(hidden_states, self.drop_prob, self.training)
76
+
77
+ def extra_repr(self) -> str:
78
+ return f"p={self.drop_prob}"
79
+
80
+
81
+ class CvtEmbeddings(nn.Module):
82
+ """
83
+ Construct the CvT embeddings.
84
+ """
85
+
86
+ def __init__(self, patch_size, num_channels, embed_dim, stride, padding, dropout_rate):
87
+ super().__init__()
88
+ self.convolution_embeddings = CvtConvEmbeddings(
89
+ patch_size=patch_size, num_channels=num_channels, embed_dim=embed_dim, stride=stride, padding=padding
90
+ )
91
+ self.dropout = nn.Dropout(dropout_rate)
92
+
93
+ def forward(self, pixel_values):
94
+ hidden_state = self.convolution_embeddings(pixel_values)
95
+ hidden_state = self.dropout(hidden_state)
96
+ return hidden_state
97
+
98
+
99
+ class CvtConvEmbeddings(nn.Module):
100
+ """
101
+ Image to Conv Embedding.
102
+ """
103
+
104
+ def __init__(self, patch_size, num_channels, embed_dim, stride, padding):
105
+ super().__init__()
106
+ patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size)
107
+ self.patch_size = patch_size
108
+ self.projection = nn.Conv2d(num_channels, embed_dim, kernel_size=patch_size, stride=stride, padding=padding)
109
+ self.normalization = nn.LayerNorm(embed_dim)
110
+
111
+ def forward(self, pixel_values):
112
+ pixel_values = self.projection(pixel_values)
113
+ batch_size, num_channels, height, width = pixel_values.shape
114
+ hidden_size = height * width
115
+ # rearrange "b c h w -> b (h w) c"
116
+ pixel_values = pixel_values.view(batch_size, num_channels, hidden_size).permute(0, 2, 1)
117
+ if self.normalization:
118
+ pixel_values = self.normalization(pixel_values)
119
+ # rearrange "b (h w) c" -> b c h w"
120
+ pixel_values = pixel_values.permute(0, 2, 1).view(batch_size, num_channels, height, width)
121
+ return pixel_values
122
+
123
+
124
+ class CvtSelfAttentionConvProjection(nn.Module):
125
+ def __init__(self, embed_dim, kernel_size, padding, stride):
126
+ super().__init__()
127
+ self.convolution = nn.Conv2d(
128
+ embed_dim,
129
+ embed_dim,
130
+ kernel_size=kernel_size,
131
+ padding=padding,
132
+ stride=stride,
133
+ bias=False,
134
+ groups=embed_dim,
135
+ )
136
+ self.normalization = nn.BatchNorm2d(embed_dim)
137
+
138
+ def forward(self, hidden_state):
139
+ hidden_state = self.convolution(hidden_state)
140
+ hidden_state = self.normalization(hidden_state)
141
+ return hidden_state
142
+
143
+
144
+ class CvtSelfAttentionLinearProjection(nn.Module):
145
+ def forward(self, hidden_state):
146
+ batch_size, num_channels, height, width = hidden_state.shape
147
+ hidden_size = height * width
148
+ # rearrange " b c h w -> b (h w) c"
149
+ hidden_state = hidden_state.view(batch_size, num_channels, hidden_size).permute(0, 2, 1)
150
+ return hidden_state
151
+
152
+
153
+ class CvtSelfAttentionProjection(nn.Module):
154
+ def __init__(self, embed_dim, kernel_size, padding, stride, projection_method="dw_bn"):
155
+ super().__init__()
156
+ if projection_method == "dw_bn":
157
+ self.convolution_projection = CvtSelfAttentionConvProjection(embed_dim, kernel_size, padding, stride)
158
+ self.linear_projection = CvtSelfAttentionLinearProjection()
159
+
160
+ def forward(self, hidden_state):
161
+ hidden_state = self.convolution_projection(hidden_state)
162
+ hidden_state = self.linear_projection(hidden_state)
163
+ return hidden_state
164
+
165
+
166
+ class CvtSelfAttention(nn.Module):
167
+ def __init__(
168
+ self,
169
+ num_heads,
170
+ embed_dim,
171
+ kernel_size,
172
+ padding_q,
173
+ padding_kv,
174
+ stride_q,
175
+ stride_kv,
176
+ qkv_projection_method,
177
+ qkv_bias,
178
+ attention_drop_rate,
179
+ with_cls_token=True,
180
+ **kwargs,
181
+ ):
182
+ super().__init__()
183
+ self.scale = embed_dim**-0.5
184
+ self.with_cls_token = with_cls_token
185
+ self.embed_dim = embed_dim
186
+ self.num_heads = num_heads
187
+
188
+ self.convolution_projection_query = CvtSelfAttentionProjection(
189
+ embed_dim,
190
+ kernel_size,
191
+ padding_q,
192
+ stride_q,
193
+ projection_method="linear" if qkv_projection_method == "avg" else qkv_projection_method,
194
+ )
195
+ self.convolution_projection_key = CvtSelfAttentionProjection(
196
+ embed_dim, kernel_size, padding_kv, stride_kv, projection_method=qkv_projection_method
197
+ )
198
+ self.convolution_projection_value = CvtSelfAttentionProjection(
199
+ embed_dim, kernel_size, padding_kv, stride_kv, projection_method=qkv_projection_method
200
+ )
201
+
202
+ self.projection_query = nn.Linear(embed_dim, embed_dim, bias=qkv_bias)
203
+ self.projection_key = nn.Linear(embed_dim, embed_dim, bias=qkv_bias)
204
+ self.projection_value = nn.Linear(embed_dim, embed_dim, bias=qkv_bias)
205
+
206
+ self.dropout = nn.Dropout(attention_drop_rate)
207
+
208
+ def rearrange_for_multi_head_attention(self, hidden_state):
209
+ batch_size, hidden_size, _ = hidden_state.shape
210
+ head_dim = self.embed_dim // self.num_heads
211
+ # rearrange 'b t (h d) -> b h t d'
212
+ return hidden_state.view(batch_size, hidden_size, self.num_heads, head_dim).permute(0, 2, 1, 3)
213
+
214
+ def forward(self, hidden_state, height, width):
215
+ if self.with_cls_token:
216
+ cls_token, hidden_state = torch.split(hidden_state, [1, height * width], 1)
217
+ batch_size, hidden_size, num_channels = hidden_state.shape
218
+ # rearrange "b (h w) c -> b c h w"
219
+ hidden_state = hidden_state.permute(0, 2, 1).view(batch_size, num_channels, height, width)
220
+
221
+ key = self.convolution_projection_key(hidden_state)
222
+ query = self.convolution_projection_query(hidden_state)
223
+ value = self.convolution_projection_value(hidden_state)
224
+
225
+ if self.with_cls_token:
226
+ query = torch.cat((cls_token, query), dim=1)
227
+ key = torch.cat((cls_token, key), dim=1)
228
+ value = torch.cat((cls_token, value), dim=1)
229
+
230
+ head_dim = self.embed_dim // self.num_heads
231
+
232
+ query = self.rearrange_for_multi_head_attention(self.projection_query(query))
233
+ key = self.rearrange_for_multi_head_attention(self.projection_key(key))
234
+ value = self.rearrange_for_multi_head_attention(self.projection_value(value))
235
+
236
+ attention_score = torch.einsum("bhlk,bhtk->bhlt", [query, key]) * self.scale
237
+ attention_probs = torch.nn.functional.softmax(attention_score, dim=-1)
238
+ attention_probs = self.dropout(attention_probs)
239
+
240
+ context = torch.einsum("bhlt,bhtv->bhlv", [attention_probs, value])
241
+ # rearrange"b h t d -> b t (h d)"
242
+ _, _, hidden_size, _ = context.shape
243
+ context = context.permute(0, 2, 1, 3).contiguous().view(batch_size, hidden_size, self.num_heads * head_dim)
244
+ return context
245
+
246
+
247
+ class CvtSelfOutput(nn.Module):
248
+ """
249
+ The residual connection is defined in CvtLayer instead of here (as is the case with other models), due to the
250
+ layernorm applied before each block.
251
+ """
252
+
253
+ def __init__(self, embed_dim, drop_rate):
254
+ super().__init__()
255
+ self.dense = nn.Linear(embed_dim, embed_dim)
256
+ self.dropout = nn.Dropout(drop_rate)
257
+
258
+ def forward(self, hidden_state, input_tensor):
259
+ hidden_state = self.dense(hidden_state)
260
+ hidden_state = self.dropout(hidden_state)
261
+ return hidden_state
262
+
263
+
264
+ class CvtAttention(nn.Module):
265
+ def __init__(
266
+ self,
267
+ num_heads,
268
+ embed_dim,
269
+ kernel_size,
270
+ padding_q,
271
+ padding_kv,
272
+ stride_q,
273
+ stride_kv,
274
+ qkv_projection_method,
275
+ qkv_bias,
276
+ attention_drop_rate,
277
+ drop_rate,
278
+ with_cls_token=True,
279
+ ):
280
+ super().__init__()
281
+ self.attention = CvtSelfAttention(
282
+ num_heads,
283
+ embed_dim,
284
+ kernel_size,
285
+ padding_q,
286
+ padding_kv,
287
+ stride_q,
288
+ stride_kv,
289
+ qkv_projection_method,
290
+ qkv_bias,
291
+ attention_drop_rate,
292
+ with_cls_token,
293
+ )
294
+ self.output = CvtSelfOutput(embed_dim, drop_rate)
295
+
296
+ def forward(self, hidden_state, height, width):
297
+ self_output = self.attention(hidden_state, height, width)
298
+ attention_output = self.output(self_output, hidden_state)
299
+ return attention_output
300
+
301
+
302
+ class CvtIntermediate(nn.Module):
303
+ def __init__(self, embed_dim, mlp_ratio):
304
+ super().__init__()
305
+ self.dense = nn.Linear(embed_dim, int(embed_dim * mlp_ratio))
306
+ self.activation = nn.GELU()
307
+
308
+ def forward(self, hidden_state):
309
+ hidden_state = self.dense(hidden_state)
310
+ hidden_state = self.activation(hidden_state)
311
+ return hidden_state
312
+
313
+
314
+ class CvtOutput(nn.Module):
315
+ def __init__(self, embed_dim, mlp_ratio, drop_rate):
316
+ super().__init__()
317
+ self.dense = nn.Linear(int(embed_dim * mlp_ratio), embed_dim)
318
+ self.dropout = nn.Dropout(drop_rate)
319
+
320
+ def forward(self, hidden_state, input_tensor):
321
+ hidden_state = self.dense(hidden_state)
322
+ hidden_state = self.dropout(hidden_state)
323
+ hidden_state = hidden_state + input_tensor
324
+ return hidden_state
325
+
326
+
327
+ class CvtLayer(nn.Module):
328
+ """
329
+ CvtLayer composed by attention layers, normalization and multi-layer perceptrons (mlps).
330
+ """
331
+
332
+ def __init__(
333
+ self,
334
+ num_heads,
335
+ embed_dim,
336
+ kernel_size,
337
+ padding_q,
338
+ padding_kv,
339
+ stride_q,
340
+ stride_kv,
341
+ qkv_projection_method,
342
+ qkv_bias,
343
+ attention_drop_rate,
344
+ drop_rate,
345
+ mlp_ratio,
346
+ drop_path_rate,
347
+ with_cls_token=True,
348
+ ):
349
+ super().__init__()
350
+ self.attention = CvtAttention(
351
+ num_heads,
352
+ embed_dim,
353
+ kernel_size,
354
+ padding_q,
355
+ padding_kv,
356
+ stride_q,
357
+ stride_kv,
358
+ qkv_projection_method,
359
+ qkv_bias,
360
+ attention_drop_rate,
361
+ drop_rate,
362
+ with_cls_token,
363
+ )
364
+
365
+ self.intermediate = CvtIntermediate(embed_dim, mlp_ratio)
366
+ self.output = CvtOutput(embed_dim, mlp_ratio, drop_rate)
367
+ self.drop_path = CvtDropPath(drop_prob=drop_path_rate) if drop_path_rate > 0.0 else nn.Identity()
368
+ self.layernorm_before = nn.LayerNorm(embed_dim)
369
+ self.layernorm_after = nn.LayerNorm(embed_dim)
370
+
371
+ def forward(self, hidden_state, height, width):
372
+ self_attention_output = self.attention(
373
+ self.layernorm_before(hidden_state), # in Cvt, layernorm is applied before self-attention
374
+ height,
375
+ width,
376
+ )
377
+ attention_output = self_attention_output
378
+ attention_output = self.drop_path(attention_output)
379
+
380
+ # first residual connection
381
+ hidden_state = attention_output + hidden_state
382
+
383
+ # in Cvt, layernorm is also applied after self-attention
384
+ layer_output = self.layernorm_after(hidden_state)
385
+ layer_output = self.intermediate(layer_output)
386
+
387
+ # second residual connection is done here
388
+ layer_output = self.output(layer_output, hidden_state)
389
+ layer_output = self.drop_path(layer_output)
390
+ return layer_output
391
+
392
+
393
+ class CvtStage(nn.Module):
394
+ def __init__(self, config, stage):
395
+ super().__init__()
396
+ self.config = config
397
+ self.stage = stage
398
+ if self.config.cls_token[self.stage]:
399
+ self.cls_token = nn.Parameter(torch.randn(1, 1, self.config.embed_dim[-1]))
400
+
401
+ self.embedding = CvtEmbeddings(
402
+ patch_size=config.patch_sizes[self.stage],
403
+ stride=config.patch_stride[self.stage],
404
+ num_channels=config.num_channels if self.stage == 0 else config.embed_dim[self.stage - 1],
405
+ embed_dim=config.embed_dim[self.stage],
406
+ padding=config.patch_padding[self.stage],
407
+ dropout_rate=config.drop_rate[self.stage],
408
+ )
409
+
410
+ drop_path_rates = [
411
+ x.item() for x in torch.linspace(0, config.drop_path_rate[self.stage], config.depth[stage], device="cpu")
412
+ ]
413
+
414
+ self.layers = nn.Sequential(
415
+ *[
416
+ CvtLayer(
417
+ num_heads=config.num_heads[self.stage],
418
+ embed_dim=config.embed_dim[self.stage],
419
+ kernel_size=config.kernel_qkv[self.stage],
420
+ padding_q=config.padding_q[self.stage],
421
+ padding_kv=config.padding_kv[self.stage],
422
+ stride_kv=config.stride_kv[self.stage],
423
+ stride_q=config.stride_q[self.stage],
424
+ qkv_projection_method=config.qkv_projection_method[self.stage],
425
+ qkv_bias=config.qkv_bias[self.stage],
426
+ attention_drop_rate=config.attention_drop_rate[self.stage],
427
+ drop_rate=config.drop_rate[self.stage],
428
+ drop_path_rate=drop_path_rates[self.stage],
429
+ mlp_ratio=config.mlp_ratio[self.stage],
430
+ with_cls_token=config.cls_token[self.stage],
431
+ )
432
+ for _ in range(config.depth[self.stage])
433
+ ]
434
+ )
435
+
436
+ def forward(self, hidden_state):
437
+ cls_token = None
438
+ hidden_state = self.embedding(hidden_state)
439
+ batch_size, num_channels, height, width = hidden_state.shape
440
+ # rearrange b c h w -> b (h w) c"
441
+ hidden_state = hidden_state.view(batch_size, num_channels, height * width).permute(0, 2, 1)
442
+ if self.config.cls_token[self.stage]:
443
+ cls_token = self.cls_token.expand(batch_size, -1, -1)
444
+ hidden_state = torch.cat((cls_token, hidden_state), dim=1)
445
+
446
+ for layer in self.layers:
447
+ layer_outputs = layer(hidden_state, height, width)
448
+ hidden_state = layer_outputs
449
+
450
+ if self.config.cls_token[self.stage]:
451
+ cls_token, hidden_state = torch.split(hidden_state, [1, height * width], 1)
452
+ hidden_state = hidden_state.permute(0, 2, 1).view(batch_size, num_channels, height, width)
453
+ return hidden_state, cls_token
454
+
455
+
456
+ class CvtEncoder(nn.Module):
457
+ def __init__(self, config):
458
+ super().__init__()
459
+ self.config = config
460
+ self.stages = nn.ModuleList([])
461
+ for stage_idx in range(len(config.depth)):
462
+ self.stages.append(CvtStage(config, stage_idx))
463
+
464
+ def forward(self, pixel_values, output_hidden_states=False, return_dict=True):
465
+ all_hidden_states = () if output_hidden_states else None
466
+ hidden_state = pixel_values
467
+
468
+ cls_token = None
469
+ for _, (stage_module) in enumerate(self.stages):
470
+ hidden_state, cls_token = stage_module(hidden_state)
471
+ if output_hidden_states:
472
+ all_hidden_states = all_hidden_states + (hidden_state,)
473
+
474
+ if not return_dict:
475
+ return tuple(v for v in [hidden_state, cls_token, all_hidden_states] if v is not None)
476
+
477
+ return BaseModelOutputWithCLSToken(
478
+ last_hidden_state=hidden_state,
479
+ cls_token_value=cls_token,
480
+ hidden_states=all_hidden_states,
481
+ )
482
+
483
+
484
+ @auto_docstring
485
+ class CvtPreTrainedModel(PreTrainedModel):
486
+ config: CvtConfig
487
+ base_model_prefix = "cvt"
488
+ main_input_name = "pixel_values"
489
+ _no_split_modules = ["CvtLayer"]
490
+
491
+ @torch.no_grad()
492
+ def _init_weights(self, module):
493
+ """Initialize the weights"""
494
+ if isinstance(module, (nn.Linear, nn.Conv2d)):
495
+ init.trunc_normal_(module.weight, mean=0.0, std=self.config.initializer_range)
496
+ if module.bias is not None:
497
+ init.zeros_(module.bias)
498
+ elif isinstance(module, (nn.LayerNorm, nn.BatchNorm2d)):
499
+ init.zeros_(module.bias)
500
+ init.ones_(module.weight)
501
+ if getattr(module, "running_mean", None) is not None:
502
+ init.zeros_(module.running_mean)
503
+ init.ones_(module.running_var)
504
+ init.zeros_(module.num_batches_tracked)
505
+ elif isinstance(module, CvtStage):
506
+ if self.config.cls_token[module.stage]:
507
+ init.trunc_normal_(module.cls_token, mean=0.0, std=self.config.initializer_range)
508
+
509
+
510
+ @auto_docstring
511
+ class CvtModel(CvtPreTrainedModel):
512
+ def __init__(self, config, add_pooling_layer=True):
513
+ r"""
514
+ add_pooling_layer (bool, *optional*, defaults to `True`):
515
+ Whether to add a pooling layer
516
+ """
517
+ super().__init__(config)
518
+ self.config = config
519
+ self.encoder = CvtEncoder(config)
520
+ self.post_init()
521
+
522
+ @auto_docstring
523
+ def forward(
524
+ self,
525
+ pixel_values: torch.Tensor | None = None,
526
+ output_hidden_states: bool | None = None,
527
+ return_dict: bool | None = None,
528
+ **kwargs,
529
+ ) -> tuple | BaseModelOutputWithCLSToken:
530
+ output_hidden_states = (
531
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
532
+ )
533
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
534
+
535
+ if pixel_values is None:
536
+ raise ValueError("You have to specify pixel_values")
537
+
538
+ encoder_outputs = self.encoder(
539
+ pixel_values,
540
+ output_hidden_states=output_hidden_states,
541
+ return_dict=return_dict,
542
+ )
543
+ sequence_output = encoder_outputs[0]
544
+
545
+ if not return_dict:
546
+ return (sequence_output,) + encoder_outputs[1:]
547
+
548
+ return BaseModelOutputWithCLSToken(
549
+ last_hidden_state=sequence_output,
550
+ cls_token_value=encoder_outputs.cls_token_value,
551
+ hidden_states=encoder_outputs.hidden_states,
552
+ )
553
+
554
+
555
+ @auto_docstring(
556
+ custom_intro="""
557
+ Cvt Model transformer with an image classification head on top (a linear layer on top of the final hidden state of
558
+ the [CLS] token) e.g. for ImageNet.
559
+ """
560
+ )
561
+ class CvtForImageClassification(CvtPreTrainedModel):
562
+ def __init__(self, config):
563
+ super().__init__(config)
564
+
565
+ self.num_labels = config.num_labels
566
+ self.cvt = CvtModel(config, add_pooling_layer=False)
567
+ self.layernorm = nn.LayerNorm(config.embed_dim[-1])
568
+ # Classifier head
569
+ self.classifier = (
570
+ nn.Linear(config.embed_dim[-1], config.num_labels) if config.num_labels > 0 else nn.Identity()
571
+ )
572
+
573
+ # Initialize weights and apply final processing
574
+ self.post_init()
575
+
576
+ @auto_docstring
577
+ def forward(
578
+ self,
579
+ pixel_values: torch.Tensor | None = None,
580
+ labels: torch.Tensor | None = None,
581
+ output_hidden_states: bool | None = None,
582
+ return_dict: bool | None = None,
583
+ **kwargs,
584
+ ) -> tuple | ImageClassifierOutputWithNoAttention:
585
+ r"""
586
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
587
+ Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
588
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
589
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
590
+ """
591
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
592
+ outputs = self.cvt(
593
+ pixel_values,
594
+ output_hidden_states=output_hidden_states,
595
+ return_dict=return_dict,
596
+ )
597
+
598
+ sequence_output = outputs[0]
599
+ cls_token = outputs[1]
600
+ if self.config.cls_token[-1]:
601
+ sequence_output = self.layernorm(cls_token)
602
+ else:
603
+ batch_size, num_channels, height, width = sequence_output.shape
604
+ # rearrange "b c h w -> b (h w) c"
605
+ sequence_output = sequence_output.view(batch_size, num_channels, height * width).permute(0, 2, 1)
606
+ sequence_output = self.layernorm(sequence_output)
607
+
608
+ sequence_output_mean = sequence_output.mean(dim=1)
609
+ logits = self.classifier(sequence_output_mean)
610
+
611
+ loss = None
612
+ if labels is not None:
613
+ if self.config.problem_type is None:
614
+ if self.config.num_labels == 1:
615
+ self.config.problem_type = "regression"
616
+ elif self.config.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
617
+ self.config.problem_type = "single_label_classification"
618
+ else:
619
+ self.config.problem_type = "multi_label_classification"
620
+
621
+ if self.config.problem_type == "regression":
622
+ loss_fct = MSELoss()
623
+ if self.config.num_labels == 1:
624
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
625
+ else:
626
+ loss = loss_fct(logits, labels)
627
+ elif self.config.problem_type == "single_label_classification":
628
+ loss_fct = CrossEntropyLoss()
629
+ loss = loss_fct(logits.view(-1, self.config.num_labels), labels.view(-1))
630
+ elif self.config.problem_type == "multi_label_classification":
631
+ loss_fct = BCEWithLogitsLoss()
632
+ loss = loss_fct(logits, labels)
633
+
634
+ if not return_dict:
635
+ output = (logits,) + outputs[2:]
636
+ return ((loss,) + output) if loss is not None else output
637
+
638
+ return ImageClassifierOutputWithNoAttention(loss=loss, logits=logits, hidden_states=outputs.hidden_states)
639
+
640
+
641
+ __all__ = ["CvtForImageClassification", "CvtModel", "CvtPreTrainedModel"]
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/cwm/__init__.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from typing import TYPE_CHECKING
16
+
17
+ from ...utils import _LazyModule
18
+ from ...utils.import_utils import define_import_structure
19
+
20
+
21
+ if TYPE_CHECKING:
22
+ from .configuration_cwm import *
23
+ from .modeling_cwm import *
24
+ else:
25
+ import sys
26
+
27
+ _file = globals()["__file__"]
28
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/cwm/configuration_cwm.py ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/cwm/modular_cwm.py.
3
+ # Do NOT edit this file manually as any edits will be overwritten by the generation of
4
+ # the file from the modular. If any change should be done, please apply the change to the
5
+ # modular_cwm.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # Copyright 2025
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+
21
+
22
+ from ...configuration_utils import PreTrainedConfig, layer_type_validation
23
+
24
+
25
+ class CwmConfig(PreTrainedConfig):
26
+ """
27
+ Configuration for Code World Model (CWM).
28
+ This is an inherited Llama3-compatible configuration with layer-interleaved
29
+ sliding-window attention. Configures a `CwmModel`. Designed to yield a configuration mirroring the model in the
30
+ [facebook/cwm](https://huggingface.co/facebook/cwm) architecture by default. Other models include:
31
+ - [facebook/cwm-sft](https://huggingface.co/facebook/cwm-sft)
32
+ - [facebook/cwm-pretrain](https://huggingface.co/facebook/cwm-pretrain)
33
+
34
+ Args:
35
+ vocab_size (`int`, *optional*, defaults to 128256):
36
+ Vocabulary size of the CWM model. Defines the number of different tokens that can be represented by the
37
+ `inputs_ids` passed when calling [`CwmModel`]
38
+ hidden_size (`int`, *optional*, defaults to 6144):
39
+ Dimension of the hidden representations
40
+ intermediate_size (`int`, *optional*, defaults to 21504):
41
+ Dimension of the MLP representations
42
+ num_hidden_layers (`int`, *optional*, defaults to 64):
43
+ Number of hidden layers in the Transformer decoder
44
+ num_attention_heads (`int`, *optional*, defaults to 48):
45
+ Number of attention heads for each attention layer in the Transformer decoder
46
+ num_key_value_heads (`int`, *optional*, defaults to 8):
47
+ This is the number of key_value heads that should be used to implement Grouped Query Attention (GQA).
48
+ If it is not specified, will default to `num_attention_heads`.
49
+ head_dim (`int`, *optional*, defaults to 128):
50
+ The attention head dimension.
51
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
52
+ The non-linear activation function (function or string) in the decoder.
53
+ max_position_embeddings (`int`, *optional*, defaults to 131072):
54
+ The maximum sequence length that this model might ever be used with. CWM's attention allows sequence
55
+ lengths up to 131072 tokens.
56
+ initializer_range (`float`, *optional*, defaults to 0.02):
57
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
58
+ rms_norm_eps (`float`, *optional*, defaults to 1e-05):
59
+ The epsilon used by the rms normalization layers.
60
+ use_cache (`bool`, *optional*, defaults to `True`):
61
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
62
+ relevant if `config.is_decoder=True`.
63
+ pad_token_id (`int`, *optional*):
64
+ Padding token id.
65
+ eos_token_id (`int` or `list[int]`, *optional*, defaults to `[128001, 128008, 128009]`):
66
+ The id of the *end-of-sequence* token. Optionally, use a list to set multiple *end-of-sequence* tokens.
67
+ bos_token_id (`int`, *optional*, defaults to 128000):
68
+ The id of the *beginning-of-sequence* token.
69
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
70
+ Whether to tie weight embeddings
71
+ attention_dropout (`float`, *optional*, defaults to 0.0):
72
+ The dropout ratio for the attention probabilities.
73
+ pretraining_tp (`int`, *optional*, defaults to 1):
74
+ Tensor parallelism degree used during pretraining. See [this
75
+ document](https://huggingface.co/docs/transformers/parallelism) and [this
76
+ issue](https://github.com/pytorch/pytorch/issues/76232).
77
+ mlp_bias (`bool`, *optional*, defaults to `False`):
78
+ Whether to use a bias in up_proj, down_proj and gate_proj layers in the MLP layers.
79
+ rope_parameters (`RopeParameters`, *optional*):
80
+ Dictionary containing the configuration parameters for the RoPE embeddings. The dictionary should contain
81
+ a value for `rope_theta` and optionally parameters used for scaling in case you want to use RoPE
82
+ with longer `max_position_embeddings`.
83
+ sliding_window (`int`, *optional*, defaults to 8192):
84
+ Sliding window attention window size.
85
+ layer_types (`List[str]`, *optional*):
86
+ List of layer types for each layer. Each element should be either "full_attention" or "sliding_attention".
87
+ If not specified, will default to alternating pattern based on the provided window pattern.
88
+ """
89
+
90
+ model_type = "cwm"
91
+ keys_to_ignore_at_inference = ["past_key_values"]
92
+ # Default tensor parallel plan for base model `CwmModel`
93
+ base_model_tp_plan = {
94
+ "layers.*.self_attn.q_proj": "colwise",
95
+ "layers.*.self_attn.k_proj": "colwise",
96
+ "layers.*.self_attn.v_proj": "colwise",
97
+ "layers.*.self_attn.o_proj": "rowwise",
98
+ "layers.*.mlp.gate_proj": "colwise",
99
+ "layers.*.mlp.up_proj": "colwise",
100
+ "layers.*.mlp.down_proj": "rowwise",
101
+ }
102
+ base_model_pp_plan = {
103
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
104
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
105
+ "norm": (["hidden_states"], ["hidden_states"]),
106
+ }
107
+ default_theta = 1_000_000.0
108
+
109
+ def __init__(
110
+ self,
111
+ vocab_size: int = 128256,
112
+ hidden_size: int = 6144,
113
+ intermediate_size: int = 21504,
114
+ num_hidden_layers: int = 64,
115
+ num_attention_heads: int = 48,
116
+ num_key_value_heads: int = 8,
117
+ head_dim: int = 128,
118
+ hidden_act: str = "silu",
119
+ max_position_embeddings: int = 131072,
120
+ initializer_range: float = 0.02,
121
+ rms_norm_eps: float = 1e-5,
122
+ use_cache: bool = True,
123
+ pad_token_id: int | None = None,
124
+ eos_token_id=[128001, 128008, 128009],
125
+ bos_token_id: int = 128000,
126
+ tie_word_embeddings: bool = False,
127
+ attention_dropout: float = 0.0,
128
+ pretraining_tp: int = 1,
129
+ mlp_bias: bool = False,
130
+ rope_parameters: dict | None = None,
131
+ # CWM interleaved sliding window fields
132
+ sliding_window: int = 8192,
133
+ layer_types: list[str] | None = None, # ["full_attention"|"sliding_attention"] per layer
134
+ **kwargs,
135
+ ):
136
+ if rope_parameters is None:
137
+ rope_parameters = {
138
+ "rope_theta": 1_000_000.0,
139
+ "factor": 16.0,
140
+ "high_freq_factor": 4.0,
141
+ "low_freq_factor": 1.0,
142
+ "original_max_position_embeddings": 8192,
143
+ "rope_type": "llama3",
144
+ }
145
+
146
+ if layer_types is None:
147
+ # Default pattern: every 4th layer uses full attention, others use sliding attention
148
+ window_pattern = 4
149
+ layer_types = [
150
+ ("full_attention" if (i % window_pattern == 0) else "sliding_attention")
151
+ for i in range(num_hidden_layers)
152
+ ]
153
+ else:
154
+ layer_type_validation(layer_types, num_hidden_layers)
155
+
156
+ self.sliding_window = int(sliding_window) if sliding_window else None
157
+ self.layer_types = list(layer_types)
158
+ self.vocab_size = vocab_size
159
+ self.max_position_embeddings = max_position_embeddings
160
+ self.hidden_size = hidden_size
161
+ self.intermediate_size = intermediate_size
162
+ self.num_hidden_layers = num_hidden_layers
163
+ self.num_attention_heads = num_attention_heads
164
+
165
+ # for backward compatibility
166
+ if num_key_value_heads is None:
167
+ num_key_value_heads = num_attention_heads
168
+
169
+ self.num_key_value_heads = num_key_value_heads
170
+ self.hidden_act = hidden_act
171
+ self.initializer_range = initializer_range
172
+ self.rms_norm_eps = rms_norm_eps
173
+ self.pretraining_tp = pretraining_tp
174
+ self.use_cache = use_cache
175
+ self.attention_dropout = attention_dropout
176
+ self.mlp_bias = mlp_bias
177
+ self.head_dim = head_dim if head_dim is not None else self.hidden_size // self.num_attention_heads
178
+ self.rope_parameters = rope_parameters
179
+
180
+ self.tie_word_embeddings = tie_word_embeddings
181
+ self.pad_token_id = pad_token_id
182
+ self.bos_token_id = bos_token_id
183
+ self.eos_token_id = eos_token_id
184
+ super().__init__(**kwargs)
185
+
186
+
187
+ __all__ = ["CwmConfig"]
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/cwm/modeling_cwm.py ADDED
@@ -0,0 +1,515 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/cwm/modular_cwm.py.
3
+ # Do NOT edit this file manually as any edits will be overwritten by the generation of
4
+ # the file from the modular. If any change should be done, please apply the change to the
5
+ # modular_cwm.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # Copyright 2025
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+
21
+
22
+ from collections.abc import Callable
23
+ from typing import Optional
24
+
25
+ import torch
26
+ from torch import nn
27
+
28
+ from ...activations import ACT2FN
29
+ from ...cache_utils import Cache, DynamicCache
30
+ from ...generation import GenerationMixin
31
+ from ...integrations import use_kernel_forward_from_hub, use_kernel_func_from_hub, use_kernelized_func
32
+ from ...masking_utils import create_causal_mask, create_sliding_window_causal_mask
33
+ from ...modeling_flash_attention_utils import FlashAttentionKwargs
34
+ from ...modeling_layers import GradientCheckpointingLayer
35
+ from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
36
+ from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
37
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
38
+ from ...processing_utils import Unpack
39
+ from ...utils import TransformersKwargs, auto_docstring, can_return_tuple
40
+ from ...utils.generic import maybe_autocast, merge_with_config_defaults
41
+ from ...utils.output_capturing import capture_outputs
42
+ from .configuration_cwm import CwmConfig
43
+
44
+
45
+ class CwmRotaryEmbedding(nn.Module):
46
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
47
+
48
+ def __init__(self, config: CwmConfig, device=None):
49
+ super().__init__()
50
+ self.max_seq_len_cached = config.max_position_embeddings
51
+ self.original_max_seq_len = config.max_position_embeddings
52
+
53
+ self.config = config
54
+
55
+ self.rope_type = self.config.rope_parameters["rope_type"]
56
+ rope_init_fn: Callable = self.compute_default_rope_parameters
57
+ if self.rope_type != "default":
58
+ rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
59
+ inv_freq, self.attention_scaling = rope_init_fn(self.config, device)
60
+
61
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
62
+ self.register_buffer("original_inv_freq", inv_freq.clone(), persistent=False)
63
+
64
+ @staticmethod
65
+ def compute_default_rope_parameters(
66
+ config: CwmConfig | None = None,
67
+ device: Optional["torch.device"] = None,
68
+ seq_len: int | None = None,
69
+ ) -> tuple["torch.Tensor", float]:
70
+ """
71
+ Computes the inverse frequencies according to the original RoPE implementation
72
+ Args:
73
+ config ([`~transformers.PreTrainedConfig`]):
74
+ The model configuration.
75
+ device (`torch.device`):
76
+ The device to use for initialization of the inverse frequencies.
77
+ seq_len (`int`, *optional*):
78
+ The current sequence length. Unused for this type of RoPE.
79
+ Returns:
80
+ Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
81
+ post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
82
+ """
83
+ base = config.rope_parameters["rope_theta"]
84
+ dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
85
+
86
+ attention_factor = 1.0 # Unused in this type of RoPE
87
+
88
+ # Compute the inverse frequencies
89
+ inv_freq = 1.0 / (
90
+ base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
91
+ )
92
+ return inv_freq, attention_factor
93
+
94
+ @torch.no_grad()
95
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
96
+ def forward(self, x, position_ids):
97
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
98
+ position_ids_expanded = position_ids[:, None, :].float()
99
+
100
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
101
+ with maybe_autocast(device_type=device_type, enabled=False): # Force float32
102
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
103
+ emb = torch.cat((freqs, freqs), dim=-1)
104
+ cos = emb.cos() * self.attention_scaling
105
+ sin = emb.sin() * self.attention_scaling
106
+
107
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
108
+
109
+
110
+ def rotate_half(x):
111
+ """Rotates half the hidden dims of the input."""
112
+ x1 = x[..., : x.shape[-1] // 2]
113
+ x2 = x[..., x.shape[-1] // 2 :]
114
+ return torch.cat((-x2, x1), dim=-1)
115
+
116
+
117
+ @use_kernel_func_from_hub("rotary_pos_emb")
118
+ def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
119
+ """Applies Rotary Position Embedding to the query and key tensors.
120
+
121
+ Args:
122
+ q (`torch.Tensor`): The query tensor.
123
+ k (`torch.Tensor`): The key tensor.
124
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
125
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
126
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
127
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
128
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
129
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
130
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
131
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
132
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
133
+ Returns:
134
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
135
+ """
136
+ cos = cos.unsqueeze(unsqueeze_dim)
137
+ sin = sin.unsqueeze(unsqueeze_dim)
138
+ q_embed = (q * cos) + (rotate_half(q) * sin)
139
+ k_embed = (k * cos) + (rotate_half(k) * sin)
140
+ return q_embed, k_embed
141
+
142
+
143
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
144
+ """
145
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
146
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
147
+ """
148
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
149
+ if n_rep == 1:
150
+ return hidden_states
151
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
152
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
153
+
154
+
155
+ def eager_attention_forward(
156
+ module: nn.Module,
157
+ query: torch.Tensor,
158
+ key: torch.Tensor,
159
+ value: torch.Tensor,
160
+ attention_mask: torch.Tensor | None,
161
+ scaling: float,
162
+ dropout: float = 0.0,
163
+ **kwargs: Unpack[TransformersKwargs],
164
+ ):
165
+ key_states = repeat_kv(key, module.num_key_value_groups)
166
+ value_states = repeat_kv(value, module.num_key_value_groups)
167
+
168
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
169
+ if attention_mask is not None:
170
+ attn_weights = attn_weights + attention_mask
171
+
172
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
173
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
174
+ attn_output = torch.matmul(attn_weights, value_states)
175
+ attn_output = attn_output.transpose(1, 2).contiguous()
176
+
177
+ return attn_output, attn_weights
178
+
179
+
180
+ @use_kernelized_func(apply_rotary_pos_emb)
181
+ class CwmAttention(nn.Module):
182
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
183
+
184
+ def __init__(self, config: CwmConfig, layer_idx: int):
185
+ super().__init__()
186
+ self.layer_type = config.layer_types[layer_idx] if hasattr(config, "layer_types") else None
187
+ self.config = config
188
+ self.layer_idx = layer_idx
189
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
190
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
191
+ self.scaling = self.head_dim**-0.5
192
+ self.attention_dropout = config.attention_dropout
193
+ self.is_causal = True
194
+ self.q_proj = torch.nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim, bias=False)
195
+ self.k_proj = torch.nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=False)
196
+ self.v_proj = torch.nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=False)
197
+ self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=False)
198
+ self.sliding_window = config.sliding_window if self.layer_type == "sliding_attention" else None
199
+
200
+ def forward(
201
+ self,
202
+ hidden_states: torch.Tensor,
203
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
204
+ attention_mask: torch.Tensor | None,
205
+ past_key_values: Cache | None = None,
206
+ cache_position: torch.LongTensor | None = None,
207
+ **kwargs: Unpack[FlashAttentionKwargs],
208
+ ) -> tuple[torch.Tensor, torch.Tensor | None]:
209
+ input_shape = hidden_states.shape[:-1]
210
+ hidden_shape = (*input_shape, -1, self.head_dim)
211
+
212
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
213
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
214
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
215
+
216
+ cos, sin = position_embeddings
217
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
218
+
219
+ if past_key_values is not None:
220
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
221
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
222
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
223
+
224
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
225
+ self.config._attn_implementation, eager_attention_forward
226
+ )
227
+
228
+ attn_output, attn_weights = attention_interface(
229
+ self,
230
+ query_states,
231
+ key_states,
232
+ value_states,
233
+ attention_mask,
234
+ dropout=0.0 if not self.training else self.attention_dropout,
235
+ scaling=self.scaling,
236
+ sliding_window=self.sliding_window, # main diff with Llama
237
+ **kwargs,
238
+ )
239
+
240
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
241
+ attn_output = self.o_proj(attn_output)
242
+ return attn_output, attn_weights
243
+
244
+
245
+ @use_kernel_forward_from_hub("RMSNorm")
246
+ class CwmRMSNorm(nn.Module):
247
+ def __init__(self, hidden_size, eps: float = 1e-6) -> None:
248
+ """
249
+ CwmRMSNorm is equivalent to T5LayerNorm
250
+ """
251
+ super().__init__()
252
+ self.weight = nn.Parameter(torch.ones(hidden_size))
253
+ self.variance_epsilon = eps
254
+
255
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
256
+ input_dtype = hidden_states.dtype
257
+ hidden_states = hidden_states.to(torch.float32)
258
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
259
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
260
+ return self.weight * hidden_states.to(input_dtype)
261
+
262
+ def extra_repr(self):
263
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
264
+
265
+
266
+ class CwmMLP(nn.Module):
267
+ def __init__(self, config):
268
+ super().__init__()
269
+ self.config = config
270
+ self.hidden_size = config.hidden_size
271
+ self.intermediate_size = config.intermediate_size
272
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
273
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
274
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)
275
+ self.act_fn = ACT2FN[config.hidden_act]
276
+
277
+ def forward(self, x):
278
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
279
+ return down_proj
280
+
281
+
282
+ class CwmDecoderLayer(GradientCheckpointingLayer):
283
+ def __init__(self, config: CwmConfig, layer_idx: int):
284
+ super().__init__()
285
+ self.hidden_size = config.hidden_size
286
+ self.self_attn = CwmAttention(config=config, layer_idx=layer_idx)
287
+
288
+ self.mlp = CwmMLP(config)
289
+ self.input_layernorm = CwmRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
290
+ self.post_attention_layernorm = CwmRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
291
+ self.attention_type = config.layer_types[layer_idx]
292
+
293
+ def forward(
294
+ self,
295
+ hidden_states: torch.Tensor,
296
+ attention_mask: torch.Tensor | None = None,
297
+ position_ids: torch.LongTensor | None = None,
298
+ past_key_values: Cache | None = None,
299
+ use_cache: bool | None = False,
300
+ cache_position: torch.LongTensor | None = None,
301
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
302
+ **kwargs: Unpack[TransformersKwargs],
303
+ ) -> torch.Tensor:
304
+ residual = hidden_states
305
+ hidden_states = self.input_layernorm(hidden_states)
306
+ # Self Attention
307
+ hidden_states, _ = self.self_attn(
308
+ hidden_states=hidden_states,
309
+ attention_mask=attention_mask,
310
+ position_ids=position_ids,
311
+ past_key_values=past_key_values,
312
+ use_cache=use_cache,
313
+ cache_position=cache_position,
314
+ position_embeddings=position_embeddings,
315
+ **kwargs,
316
+ )
317
+ hidden_states = residual + hidden_states
318
+
319
+ # Fully Connected
320
+ residual = hidden_states
321
+ hidden_states = self.post_attention_layernorm(hidden_states)
322
+ hidden_states = self.mlp(hidden_states)
323
+ hidden_states = residual + hidden_states
324
+ return hidden_states
325
+
326
+
327
+ @auto_docstring
328
+ class CwmPreTrainedModel(PreTrainedModel):
329
+ config: CwmConfig
330
+ base_model_prefix = "model"
331
+ supports_gradient_checkpointing = True
332
+ _no_split_modules = ["CwmDecoderLayer"]
333
+ _skip_keys_device_placement = ["past_key_values"]
334
+ _supports_flash_attn = True
335
+ _supports_sdpa = True
336
+ _supports_flex_attn = True
337
+
338
+ _can_compile_fullgraph = True
339
+ _supports_attention_backend = True
340
+ _can_record_outputs = {
341
+ "hidden_states": CwmDecoderLayer,
342
+ "attentions": CwmAttention,
343
+ }
344
+
345
+
346
+ class CwmModelOutputWithPast(BaseModelOutputWithPast):
347
+ pass
348
+
349
+
350
+ @auto_docstring
351
+ class CwmModel(CwmPreTrainedModel):
352
+ config_class = CwmConfig
353
+
354
+ def __init__(self, config: CwmConfig):
355
+ super().__init__(config)
356
+ self.padding_idx = config.pad_token_id
357
+ self.vocab_size = config.vocab_size
358
+
359
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
360
+ self.layers = torch.nn.ModuleList(
361
+ [CwmDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
362
+ )
363
+ self.norm = CwmRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
364
+ self.rotary_emb = CwmRotaryEmbedding(config=config)
365
+ self.gradient_checkpointing = False
366
+
367
+ # Initialize weights and apply final processing
368
+ self.post_init()
369
+
370
+ @merge_with_config_defaults
371
+ @capture_outputs
372
+ @auto_docstring
373
+ def forward(
374
+ self,
375
+ input_ids: torch.LongTensor | None = None,
376
+ attention_mask: torch.Tensor | None = None,
377
+ position_ids: torch.LongTensor | None = None,
378
+ past_key_values: Cache | None = None,
379
+ inputs_embeds: torch.FloatTensor | None = None,
380
+ cache_position: torch.LongTensor | None = None,
381
+ use_cache: bool | None = None,
382
+ **kwargs: Unpack[TransformersKwargs],
383
+ ) -> CwmModelOutputWithPast:
384
+ if (input_ids is None) ^ (inputs_embeds is not None):
385
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
386
+
387
+ if inputs_embeds is None:
388
+ inputs_embeds: torch.Tensor = self.embed_tokens(input_ids)
389
+
390
+ if use_cache and past_key_values is None:
391
+ past_key_values = DynamicCache(config=self.config)
392
+
393
+ if cache_position is None:
394
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
395
+ cache_position: torch.Tensor = (
396
+ torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens
397
+ )
398
+
399
+ if position_ids is None:
400
+ position_ids = cache_position.unsqueeze(0)
401
+
402
+ if not isinstance(causal_mask_mapping := attention_mask, dict):
403
+ mask_kwargs = {
404
+ "config": self.config,
405
+ "inputs_embeds": inputs_embeds,
406
+ "attention_mask": attention_mask,
407
+ "cache_position": cache_position,
408
+ "past_key_values": past_key_values,
409
+ "position_ids": position_ids,
410
+ }
411
+ sliding_mask_kwargs = mask_kwargs.copy()
412
+
413
+ causal_mask_mapping = {
414
+ "full_attention": create_causal_mask(**mask_kwargs),
415
+ "sliding_attention": create_sliding_window_causal_mask(**sliding_mask_kwargs),
416
+ }
417
+
418
+ hidden_states = inputs_embeds
419
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
420
+
421
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
422
+ hidden_states = decoder_layer(
423
+ hidden_states,
424
+ attention_mask=causal_mask_mapping[decoder_layer.attention_type],
425
+ position_ids=position_ids,
426
+ past_key_values=past_key_values,
427
+ cache_position=cache_position,
428
+ position_embeddings=position_embeddings,
429
+ **kwargs,
430
+ )
431
+
432
+ hidden_states = self.norm(hidden_states)
433
+ return CwmModelOutputWithPast(
434
+ last_hidden_state=hidden_states,
435
+ past_key_values=past_key_values,
436
+ )
437
+
438
+
439
+ @auto_docstring
440
+ class CwmForCausalLM(CwmPreTrainedModel, GenerationMixin):
441
+ _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
442
+ _tp_plan = {"lm_head": "colwise_gather_output"}
443
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
444
+
445
+ def __init__(self, config):
446
+ super().__init__(config)
447
+ self.model = CwmModel(config)
448
+ self.vocab_size = config.vocab_size
449
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
450
+
451
+ # Initialize weights and apply final processing
452
+ self.post_init()
453
+
454
+ @can_return_tuple
455
+ @auto_docstring
456
+ def forward(
457
+ self,
458
+ input_ids: torch.LongTensor | None = None,
459
+ attention_mask: torch.Tensor | None = None,
460
+ position_ids: torch.LongTensor | None = None,
461
+ past_key_values: Cache | None = None,
462
+ inputs_embeds: torch.FloatTensor | None = None,
463
+ labels: torch.LongTensor | None = None,
464
+ use_cache: bool | None = None,
465
+ cache_position: torch.LongTensor | None = None,
466
+ logits_to_keep: int | torch.Tensor = 0,
467
+ **kwargs: Unpack[TransformersKwargs],
468
+ ) -> CausalLMOutputWithPast:
469
+ r"""
470
+ Example:
471
+
472
+ ```python
473
+ >>> from transformers import AutoTokenizer, CwmForCausalLM
474
+
475
+ >>> model = CwmForCausalLM.from_pretrained("meta-cwm/Cwm-2-7b-hf")
476
+ >>> tokenizer = AutoTokenizer.from_pretrained("meta-cwm/Cwm-2-7b-hf")
477
+
478
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
479
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
480
+
481
+ >>> # Generate
482
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
483
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
484
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
485
+ ```"""
486
+ outputs: BaseModelOutputWithPast = self.model(
487
+ input_ids=input_ids,
488
+ attention_mask=attention_mask,
489
+ position_ids=position_ids,
490
+ past_key_values=past_key_values,
491
+ inputs_embeds=inputs_embeds,
492
+ use_cache=use_cache,
493
+ cache_position=cache_position,
494
+ **kwargs,
495
+ )
496
+
497
+ hidden_states = outputs.last_hidden_state
498
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
499
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
500
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
501
+
502
+ loss = None
503
+ if labels is not None:
504
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
505
+
506
+ return CausalLMOutputWithPast(
507
+ loss=loss,
508
+ logits=logits,
509
+ past_key_values=outputs.past_key_values,
510
+ hidden_states=outputs.hidden_states,
511
+ attentions=outputs.attentions,
512
+ )
513
+
514
+
515
+ __all__ = ["CwmPreTrainedModel", "CwmModel", "CwmForCausalLM"]
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/cwm/modular_cwm.py ADDED
@@ -0,0 +1,295 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025
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
+
16
+ import torch
17
+
18
+ from ...cache_utils import Cache, DynamicCache
19
+ from ...configuration_utils import layer_type_validation
20
+ from ...masking_utils import create_causal_mask, create_sliding_window_causal_mask
21
+ from ...modeling_outputs import BaseModelOutputWithPast
22
+ from ...processing_utils import Unpack
23
+ from ...utils import TransformersKwargs, logging
24
+ from ..llama.configuration_llama import LlamaConfig
25
+ from ..llama.modeling_llama import (
26
+ LlamaDecoderLayer,
27
+ LlamaForCausalLM,
28
+ LlamaModel,
29
+ LlamaPreTrainedModel,
30
+ )
31
+ from ..qwen2.modeling_qwen2 import Qwen2Attention, Qwen2RotaryEmbedding
32
+
33
+
34
+ logger = logging.get_logger(__name__)
35
+
36
+
37
+ class CwmConfig(LlamaConfig):
38
+ """
39
+ Configuration for Code World Model (CWM).
40
+ This is an inherited Llama3-compatible configuration with layer-interleaved
41
+ sliding-window attention. Configures a `CwmModel`. Designed to yield a configuration mirroring the model in the
42
+ [facebook/cwm](https://huggingface.co/facebook/cwm) architecture by default. Other models include:
43
+ - [facebook/cwm-sft](https://huggingface.co/facebook/cwm-sft)
44
+ - [facebook/cwm-pretrain](https://huggingface.co/facebook/cwm-pretrain)
45
+
46
+ Args:
47
+ vocab_size (`int`, *optional*, defaults to 128256):
48
+ Vocabulary size of the CWM model. Defines the number of different tokens that can be represented by the
49
+ `inputs_ids` passed when calling [`CwmModel`]
50
+ hidden_size (`int`, *optional*, defaults to 6144):
51
+ Dimension of the hidden representations
52
+ intermediate_size (`int`, *optional*, defaults to 21504):
53
+ Dimension of the MLP representations
54
+ num_hidden_layers (`int`, *optional*, defaults to 64):
55
+ Number of hidden layers in the Transformer decoder
56
+ num_attention_heads (`int`, *optional*, defaults to 48):
57
+ Number of attention heads for each attention layer in the Transformer decoder
58
+ num_key_value_heads (`int`, *optional*, defaults to 8):
59
+ This is the number of key_value heads that should be used to implement Grouped Query Attention (GQA).
60
+ If it is not specified, will default to `num_attention_heads`.
61
+ head_dim (`int`, *optional*, defaults to 128):
62
+ The attention head dimension.
63
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
64
+ The non-linear activation function (function or string) in the decoder.
65
+ max_position_embeddings (`int`, *optional*, defaults to 131072):
66
+ The maximum sequence length that this model might ever be used with. CWM's attention allows sequence
67
+ lengths up to 131072 tokens.
68
+ initializer_range (`float`, *optional*, defaults to 0.02):
69
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
70
+ rms_norm_eps (`float`, *optional*, defaults to 1e-05):
71
+ The epsilon used by the rms normalization layers.
72
+ use_cache (`bool`, *optional*, defaults to `True`):
73
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
74
+ relevant if `config.is_decoder=True`.
75
+ pad_token_id (`int`, *optional*):
76
+ Padding token id.
77
+ eos_token_id (`int` or `list[int]`, *optional*, defaults to `[128001, 128008, 128009]`):
78
+ The id of the *end-of-sequence* token. Optionally, use a list to set multiple *end-of-sequence* tokens.
79
+ bos_token_id (`int`, *optional*, defaults to 128000):
80
+ The id of the *beginning-of-sequence* token.
81
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
82
+ Whether to tie weight embeddings
83
+ attention_dropout (`float`, *optional*, defaults to 0.0):
84
+ The dropout ratio for the attention probabilities.
85
+ pretraining_tp (`int`, *optional*, defaults to 1):
86
+ Tensor parallelism degree used during pretraining. See [this
87
+ document](https://huggingface.co/docs/transformers/parallelism) and [this
88
+ issue](https://github.com/pytorch/pytorch/issues/76232).
89
+ mlp_bias (`bool`, *optional*, defaults to `False`):
90
+ Whether to use a bias in up_proj, down_proj and gate_proj layers in the MLP layers.
91
+ rope_parameters (`RopeParameters`, *optional*):
92
+ Dictionary containing the configuration parameters for the RoPE embeddings. The dictionary should contain
93
+ a value for `rope_theta` and optionally parameters used for scaling in case you want to use RoPE
94
+ with longer `max_position_embeddings`.
95
+ sliding_window (`int`, *optional*, defaults to 8192):
96
+ Sliding window attention window size.
97
+ layer_types (`List[str]`, *optional*):
98
+ List of layer types for each layer. Each element should be either "full_attention" or "sliding_attention".
99
+ If not specified, will default to alternating pattern based on the provided window pattern.
100
+ """
101
+
102
+ model_type = "cwm"
103
+ default_theta = 1_000_000.0
104
+
105
+ def __init__(
106
+ self,
107
+ vocab_size: int = 128256,
108
+ hidden_size: int = 6144,
109
+ intermediate_size: int = 21504,
110
+ num_hidden_layers: int = 64,
111
+ num_attention_heads: int = 48,
112
+ num_key_value_heads: int = 8,
113
+ head_dim: int = 128,
114
+ hidden_act: str = "silu",
115
+ max_position_embeddings: int = 131072,
116
+ initializer_range: float = 0.02,
117
+ rms_norm_eps: float = 1e-5,
118
+ use_cache: bool = True,
119
+ pad_token_id: int | None = None,
120
+ eos_token_id=[128001, 128008, 128009],
121
+ bos_token_id: int = 128000,
122
+ tie_word_embeddings: bool = False,
123
+ attention_dropout: float = 0.0,
124
+ pretraining_tp: int = 1,
125
+ mlp_bias: bool = False,
126
+ rope_parameters: dict | None = None,
127
+ # CWM interleaved sliding window fields
128
+ sliding_window: int = 8192,
129
+ layer_types: list[str] | None = None, # ["full_attention"|"sliding_attention"] per layer
130
+ **kwargs,
131
+ ):
132
+ if rope_parameters is None:
133
+ rope_parameters = {
134
+ "rope_theta": 1_000_000.0,
135
+ "factor": 16.0,
136
+ "high_freq_factor": 4.0,
137
+ "low_freq_factor": 1.0,
138
+ "original_max_position_embeddings": 8192,
139
+ "rope_type": "llama3",
140
+ }
141
+
142
+ if layer_types is None:
143
+ # Default pattern: every 4th layer uses full attention, others use sliding attention
144
+ window_pattern = 4
145
+ layer_types = [
146
+ ("full_attention" if (i % window_pattern == 0) else "sliding_attention")
147
+ for i in range(num_hidden_layers)
148
+ ]
149
+ else:
150
+ layer_type_validation(layer_types, num_hidden_layers)
151
+
152
+ self.sliding_window = int(sliding_window) if sliding_window else None
153
+ self.layer_types = list(layer_types)
154
+
155
+ super().__init__(
156
+ vocab_size=vocab_size,
157
+ hidden_size=hidden_size,
158
+ intermediate_size=intermediate_size,
159
+ num_hidden_layers=num_hidden_layers,
160
+ num_attention_heads=num_attention_heads,
161
+ num_key_value_heads=num_key_value_heads,
162
+ head_dim=head_dim,
163
+ hidden_act=hidden_act,
164
+ max_position_embeddings=max_position_embeddings,
165
+ initializer_range=initializer_range,
166
+ rms_norm_eps=rms_norm_eps,
167
+ use_cache=use_cache,
168
+ pad_token_id=pad_token_id,
169
+ eos_token_id=list(eos_token_id),
170
+ bos_token_id=bos_token_id,
171
+ tie_word_embeddings=tie_word_embeddings,
172
+ attention_bias=False,
173
+ attention_dropout=attention_dropout,
174
+ rope_parameters=rope_parameters,
175
+ pretraining_tp=pretraining_tp,
176
+ mlp_bias=mlp_bias,
177
+ **kwargs,
178
+ )
179
+
180
+ # CWM models don't use attention bias, remove it from config
181
+ del self.attention_bias
182
+
183
+
184
+ class CwmRotaryEmbedding(Qwen2RotaryEmbedding):
185
+ pass
186
+
187
+
188
+ class CwmAttention(Qwen2Attention):
189
+ def __init__(self, config: CwmConfig, layer_idx: int):
190
+ super().__init__(config=config, layer_idx=layer_idx)
191
+ self.q_proj = torch.nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim, bias=False)
192
+ self.k_proj = torch.nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=False)
193
+ self.v_proj = torch.nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=False)
194
+
195
+
196
+ class CwmDecoderLayer(LlamaDecoderLayer):
197
+ def __init__(self, config: CwmConfig, layer_idx: int):
198
+ super().__init__(config=config, layer_idx=layer_idx)
199
+ self.attention_type = config.layer_types[layer_idx]
200
+ self.self_attn = CwmAttention(config=config, layer_idx=layer_idx)
201
+
202
+
203
+ class CwmPreTrainedModel(LlamaPreTrainedModel):
204
+ pass
205
+
206
+
207
+ class CwmModelOutputWithPast(BaseModelOutputWithPast):
208
+ pass
209
+
210
+
211
+ class CwmModel(LlamaModel):
212
+ config_class = CwmConfig
213
+
214
+ def __init__(self, config: CwmConfig):
215
+ super().__init__(config)
216
+ self.layers = torch.nn.ModuleList(
217
+ [CwmDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
218
+ )
219
+
220
+ def forward(
221
+ self,
222
+ input_ids: torch.LongTensor | None = None,
223
+ attention_mask: torch.Tensor | None = None,
224
+ position_ids: torch.LongTensor | None = None,
225
+ past_key_values: Cache | None = None,
226
+ inputs_embeds: torch.FloatTensor | None = None,
227
+ cache_position: torch.LongTensor | None = None,
228
+ use_cache: bool | None = None,
229
+ **kwargs: Unpack[TransformersKwargs],
230
+ ) -> CwmModelOutputWithPast:
231
+ if (input_ids is None) ^ (inputs_embeds is not None):
232
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
233
+
234
+ if inputs_embeds is None:
235
+ inputs_embeds: torch.Tensor = self.embed_tokens(input_ids)
236
+
237
+ if use_cache and past_key_values is None:
238
+ past_key_values = DynamicCache(config=self.config)
239
+
240
+ if cache_position is None:
241
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
242
+ cache_position: torch.Tensor = (
243
+ torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens
244
+ )
245
+
246
+ if position_ids is None:
247
+ position_ids = cache_position.unsqueeze(0)
248
+
249
+ if not isinstance(causal_mask_mapping := attention_mask, dict):
250
+ mask_kwargs = {
251
+ "config": self.config,
252
+ "inputs_embeds": inputs_embeds,
253
+ "attention_mask": attention_mask,
254
+ "cache_position": cache_position,
255
+ "past_key_values": past_key_values,
256
+ "position_ids": position_ids,
257
+ }
258
+ sliding_mask_kwargs = mask_kwargs.copy()
259
+
260
+ causal_mask_mapping = {
261
+ "full_attention": create_causal_mask(**mask_kwargs),
262
+ "sliding_attention": create_sliding_window_causal_mask(**sliding_mask_kwargs),
263
+ }
264
+
265
+ hidden_states = inputs_embeds
266
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
267
+
268
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
269
+ hidden_states = decoder_layer(
270
+ hidden_states,
271
+ attention_mask=causal_mask_mapping[decoder_layer.attention_type],
272
+ position_ids=position_ids,
273
+ past_key_values=past_key_values,
274
+ cache_position=cache_position,
275
+ position_embeddings=position_embeddings,
276
+ **kwargs,
277
+ )
278
+
279
+ hidden_states = self.norm(hidden_states)
280
+ return CwmModelOutputWithPast(
281
+ last_hidden_state=hidden_states,
282
+ past_key_values=past_key_values,
283
+ )
284
+
285
+
286
+ class CwmForCausalLM(LlamaForCausalLM):
287
+ pass
288
+
289
+
290
+ __all__ = [
291
+ "CwmConfig",
292
+ "CwmPreTrainedModel",
293
+ "CwmModel",
294
+ "CwmForCausalLM",
295
+ ]
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/d_fine/__init__.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
16
+ from typing import TYPE_CHECKING
17
+
18
+ from ...utils import _LazyModule
19
+ from ...utils.import_utils import define_import_structure
20
+
21
+
22
+ if TYPE_CHECKING:
23
+ from .configuration_d_fine import *
24
+ from .modeling_d_fine import *
25
+ else:
26
+ import sys
27
+
28
+ _file = globals()["__file__"]
29
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/d_fine/configuration_d_fine.py ADDED
@@ -0,0 +1,354 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/d_fine/modular_d_fine.py.
3
+ # Do NOT edit this file manually as any edits will be overwritten by the generation of
4
+ # the file from the modular. If any change should be done, please apply the change to the
5
+ # modular_d_fine.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # Copyright 2025 Baidu Inc and The HuggingFace Inc. team.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ from ...backbone_utils import consolidate_backbone_kwargs_to_config
21
+ from ...configuration_utils import PreTrainedConfig
22
+ from ..auto import AutoConfig
23
+
24
+
25
+ # TODO: Attribute map assignment logic should be fixed in modular
26
+ # as well as super() call parsing because otherwise we cannot re-write args after initialization
27
+ class DFineConfig(PreTrainedConfig):
28
+ """
29
+ This is the configuration class to store the configuration of a [`DFineModel`]. It is used to instantiate a D-FINE
30
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
31
+ defaults will yield a similar configuration to that of D-FINE-X-COCO "[ustc-community/dfine-xlarge-coco"](https://huggingface.co/ustc-community/dfine-xlarge-coco").
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
+ initializer_range (`float`, *optional*, defaults to 0.01):
37
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
38
+ initializer_bias_prior_prob (`float`, *optional*):
39
+ The prior probability used by the bias initializer to initialize biases for `enc_score_head` and `class_embed`.
40
+ If `None`, `prior_prob` computed as `prior_prob = 1 / (num_labels + 1)` while initializing model weights.
41
+ layer_norm_eps (`float`, *optional*, defaults to 1e-05):
42
+ The epsilon used by the layer normalization layers.
43
+ batch_norm_eps (`float`, *optional*, defaults to 1e-05):
44
+ The epsilon used by the batch normalization layers.
45
+ backbone_config (`Union[dict, "PreTrainedConfig"]`, *optional*, defaults to `HGNetV2Config()`):
46
+ The configuration of the backbone model.
47
+ freeze_backbone_batch_norms (`bool`, *optional*, defaults to `True`):
48
+ Whether to freeze the batch normalization layers in the backbone.
49
+ encoder_hidden_dim (`int`, *optional*, defaults to 256):
50
+ Dimension of the layers in hybrid encoder.
51
+ encoder_in_channels (`list`, *optional*, defaults to `[512, 1024, 2048]`):
52
+ Multi level features input for encoder.
53
+ feat_strides (`list[int]`, *optional*, defaults to `[8, 16, 32]`):
54
+ Strides used in each feature map.
55
+ encoder_layers (`int`, *optional*, defaults to 1):
56
+ Total of layers to be used by the encoder.
57
+ encoder_ffn_dim (`int`, *optional*, defaults to 1024):
58
+ Dimension of the "intermediate" (often named feed-forward) layer in decoder.
59
+ encoder_attention_heads (`int`, *optional*, defaults to 8):
60
+ Number of attention heads for each attention layer in the Transformer encoder.
61
+ dropout (`float`, *optional*, defaults to 0.0):
62
+ The ratio for all dropout layers.
63
+ activation_dropout (`float`, *optional*, defaults to 0.0):
64
+ The dropout ratio for activations inside the fully connected layer.
65
+ encode_proj_layers (`list[int]`, *optional*, defaults to `[2]`):
66
+ Indexes of the projected layers to be used in the encoder.
67
+ positional_encoding_temperature (`int`, *optional*, defaults to 10000):
68
+ The temperature parameter used to create the positional encodings.
69
+ encoder_activation_function (`str`, *optional*, defaults to `"gelu"`):
70
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
71
+ `"relu"`, `"silu"` and `"gelu_new"` are supported.
72
+ activation_function (`str`, *optional*, defaults to `"silu"`):
73
+ The non-linear activation function (function or string) in the general layer. If string, `"gelu"`,
74
+ `"relu"`, `"silu"` and `"gelu_new"` are supported.
75
+ eval_size (`tuple[int, int]`, *optional*):
76
+ Height and width used to computes the effective height and width of the position embeddings after taking
77
+ into account the stride.
78
+ normalize_before (`bool`, *optional*, defaults to `False`):
79
+ Determine whether to apply layer normalization in the transformer encoder layer before self-attention and
80
+ feed-forward modules.
81
+ hidden_expansion (`float`, *optional*, defaults to 1.0):
82
+ Expansion ratio to enlarge the dimension size of RepVGGBlock and CSPRepLayer.
83
+ d_model (`int`, *optional*, defaults to 256):
84
+ Dimension of the layers exclude hybrid encoder.
85
+ num_queries (`int`, *optional*, defaults to 300):
86
+ Number of object queries.
87
+ decoder_in_channels (`list`, *optional*, defaults to `[256, 256, 256]`):
88
+ Multi level features dimension for decoder
89
+ decoder_ffn_dim (`int`, *optional*, defaults to 1024):
90
+ Dimension of the "intermediate" (often named feed-forward) layer in decoder.
91
+ num_feature_levels (`int`, *optional*, defaults to 3):
92
+ The number of input feature levels.
93
+ decoder_n_points (`int`, *optional*, defaults to 4):
94
+ The number of sampled keys in each feature level for each attention head in the decoder.
95
+ decoder_layers (`int`, *optional*, defaults to 6):
96
+ Number of decoder layers.
97
+ decoder_attention_heads (`int`, *optional*, defaults to 8):
98
+ Number of attention heads for each attention layer in the Transformer decoder.
99
+ decoder_activation_function (`str`, *optional*, defaults to `"relu"`):
100
+ The non-linear activation function (function or string) in the decoder. If string, `"gelu"`,
101
+ `"relu"`, `"silu"` and `"gelu_new"` are supported.
102
+ attention_dropout (`float`, *optional*, defaults to 0.0):
103
+ The dropout ratio for the attention probabilities.
104
+ num_denoising (`int`, *optional*, defaults to 100):
105
+ The total number of denoising tasks or queries to be used for contrastive denoising.
106
+ label_noise_ratio (`float`, *optional*, defaults to 0.5):
107
+ The fraction of denoising labels to which random noise should be added.
108
+ box_noise_scale (`float`, *optional*, defaults to 1.0):
109
+ Scale or magnitude of noise to be added to the bounding boxes.
110
+ learn_initial_query (`bool`, *optional*, defaults to `False`):
111
+ Indicates whether the initial query embeddings for the decoder should be learned during training
112
+ anchor_image_size (`tuple[int, int]`, *optional*):
113
+ Height and width of the input image used during evaluation to generate the bounding box anchors. If None, automatic generate anchor is applied.
114
+ with_box_refine (`bool`, *optional*, defaults to `True`):
115
+ Whether to apply iterative bounding box refinement, where each decoder layer refines the bounding boxes
116
+ based on the predictions from the previous layer.
117
+ is_encoder_decoder (`bool`, *optional*, defaults to `True`):
118
+ Whether the architecture has an encoder decoder structure.
119
+ matcher_alpha (`float`, *optional*, defaults to 0.25):
120
+ Parameter alpha used by the Hungarian Matcher.
121
+ matcher_gamma (`float`, *optional*, defaults to 2.0):
122
+ Parameter gamma used by the Hungarian Matcher.
123
+ matcher_class_cost (`float`, *optional*, defaults to 2.0):
124
+ The relative weight of the class loss used by the Hungarian Matcher.
125
+ matcher_bbox_cost (`float`, *optional*, defaults to 5.0):
126
+ The relative weight of the bounding box loss used by the Hungarian Matcher.
127
+ matcher_giou_cost (`float`, *optional*, defaults to 2.0):
128
+ The relative weight of the giou loss of used by the Hungarian Matcher.
129
+ use_focal_loss (`bool`, *optional*, defaults to `True`):
130
+ Parameter informing if focal focal should be used.
131
+ auxiliary_loss (`bool`, *optional*, defaults to `True`):
132
+ Whether auxiliary decoding losses (loss at each decoder layer) are to be used.
133
+ focal_loss_alpha (`float`, *optional*, defaults to 0.75):
134
+ Parameter alpha used to compute the focal loss.
135
+ focal_loss_gamma (`float`, *optional*, defaults to 2.0):
136
+ Parameter gamma used to compute the focal loss.
137
+ weight_loss_vfl (`float`, *optional*, defaults to 1.0):
138
+ Relative weight of the varifocal loss in the object detection loss.
139
+ weight_loss_bbox (`float`, *optional*, defaults to 5.0):
140
+ Relative weight of the L1 bounding box loss in the object detection loss.
141
+ weight_loss_giou (`float`, *optional*, defaults to 2.0):
142
+ Relative weight of the generalized IoU loss in the object detection loss.
143
+ weight_loss_fgl (`float`, *optional*, defaults to 0.15):
144
+ Relative weight of the fine-grained localization loss in the object detection loss.
145
+ weight_loss_ddf (`float`, *optional*, defaults to 1.5):
146
+ Relative weight of the decoupled distillation focal loss in the object detection loss.
147
+ eos_coefficient (`float`, *optional*, defaults to 0.0001):
148
+ Relative classification weight of the 'no-object' class in the object detection loss.
149
+ eval_idx (`int`, *optional*, defaults to -1):
150
+ Index of the decoder layer to use for evaluation. If negative, counts from the end
151
+ (e.g., -1 means use the last layer). This allows for early prediction in the decoder
152
+ stack while still training later layers.
153
+ layer_scale (`float`, *optional*, defaults to `1.0`):
154
+ Scaling factor for the hidden dimension in later decoder layers. Used to adjust the
155
+ model capacity after the evaluation layer.
156
+ max_num_bins (`int`, *optional*, defaults to 32):
157
+ Maximum number of bins for the distribution-guided bounding box refinement.
158
+ Higher values allow for more fine-grained localization but increase computation.
159
+ reg_scale (`float`, *optional*, defaults to 4.0):
160
+ Scale factor for the regression distribution. Controls the range and granularity
161
+ of the bounding box refinement process.
162
+ depth_mult (`float`, *optional*, defaults to 1.0):
163
+ Multiplier for the number of blocks in RepNCSPELAN4 layers. Used to scale the model's
164
+ depth while maintaining its architecture.
165
+ top_prob_values (`int`, *optional*, defaults to 4):
166
+ Number of top probability values to consider from each corner's distribution.
167
+ lqe_hidden_dim (`int`, *optional*, defaults to 64):
168
+ Hidden dimension size for the Location Quality Estimator (LQE) network.
169
+ lqe_layers (`int`, *optional*, defaults to 2):
170
+ Number of layers in the Location Quality Estimator MLP.
171
+ decoder_offset_scale (`float`, *optional*, defaults to 0.5):
172
+ Offset scale used in deformable attention.
173
+ decoder_method (`str`, *optional*, defaults to `"default"`):
174
+ The method to use for the decoder: `"default"` or `"discrete"`.
175
+ up (`float`, *optional*, defaults to 0.5):
176
+ Controls the upper bounds of the Weighting Function.
177
+ tie_word_embeddings (`bool`, *optional*, defaults to `True`):
178
+ Whether to tie weight embeddings
179
+ """
180
+
181
+ model_type = "d_fine"
182
+ sub_configs = {"backbone_config": AutoConfig}
183
+ layer_types = ["basic", "bottleneck"]
184
+ attribute_map = {
185
+ "hidden_size": "d_model",
186
+ "num_attention_heads": "encoder_attention_heads",
187
+ }
188
+
189
+ def __init__(
190
+ self,
191
+ initializer_range=0.01,
192
+ initializer_bias_prior_prob=None,
193
+ layer_norm_eps=1e-5,
194
+ batch_norm_eps=1e-5,
195
+ # backbone
196
+ backbone_config=None,
197
+ freeze_backbone_batch_norms=True,
198
+ # encoder HybridEncoder
199
+ encoder_hidden_dim=256,
200
+ encoder_in_channels=[512, 1024, 2048],
201
+ feat_strides=[8, 16, 32],
202
+ encoder_layers=1,
203
+ encoder_ffn_dim=1024,
204
+ encoder_attention_heads=8,
205
+ dropout=0.0,
206
+ activation_dropout=0.0,
207
+ encode_proj_layers=[2],
208
+ positional_encoding_temperature=10000,
209
+ encoder_activation_function="gelu",
210
+ activation_function="silu",
211
+ eval_size=None,
212
+ normalize_before=False,
213
+ hidden_expansion=1.0,
214
+ # decoder DFineTransformer
215
+ d_model=256,
216
+ num_queries=300,
217
+ decoder_in_channels=[256, 256, 256],
218
+ decoder_ffn_dim=1024,
219
+ num_feature_levels=3,
220
+ decoder_n_points=4,
221
+ decoder_layers=6,
222
+ decoder_attention_heads=8,
223
+ decoder_activation_function="relu",
224
+ attention_dropout=0.0,
225
+ num_denoising=100,
226
+ label_noise_ratio=0.5,
227
+ box_noise_scale=1.0,
228
+ learn_initial_query=False,
229
+ anchor_image_size=None,
230
+ with_box_refine=True,
231
+ is_encoder_decoder=True,
232
+ # Loss
233
+ matcher_alpha=0.25,
234
+ matcher_gamma=2.0,
235
+ matcher_class_cost=2.0,
236
+ matcher_bbox_cost=5.0,
237
+ matcher_giou_cost=2.0,
238
+ use_focal_loss=True,
239
+ auxiliary_loss=True,
240
+ focal_loss_alpha=0.75,
241
+ focal_loss_gamma=2.0,
242
+ weight_loss_vfl=1.0,
243
+ weight_loss_bbox=5.0,
244
+ weight_loss_giou=2.0,
245
+ weight_loss_fgl=0.15,
246
+ weight_loss_ddf=1.5,
247
+ eos_coefficient=1e-4,
248
+ eval_idx=-1,
249
+ layer_scale=1,
250
+ max_num_bins=32,
251
+ reg_scale=4.0,
252
+ depth_mult=1.0,
253
+ top_prob_values=4,
254
+ lqe_hidden_dim=64,
255
+ lqe_layers=2,
256
+ decoder_offset_scale=0.5,
257
+ decoder_method="default",
258
+ up=0.5,
259
+ tie_word_embeddings=True,
260
+ **kwargs,
261
+ ):
262
+ self.initializer_range = initializer_range
263
+ self.initializer_bias_prior_prob = initializer_bias_prior_prob
264
+ self.layer_norm_eps = layer_norm_eps
265
+ self.batch_norm_eps = batch_norm_eps
266
+
267
+ backbone_config, kwargs = consolidate_backbone_kwargs_to_config(
268
+ backbone_config=backbone_config,
269
+ default_config_type="hgnet_v2",
270
+ default_config_kwargs={"out_indices": [2, 3, 4]},
271
+ **kwargs,
272
+ )
273
+
274
+ self.backbone_config = backbone_config
275
+ self.freeze_backbone_batch_norms = freeze_backbone_batch_norms
276
+ # encoder
277
+ self.encoder_hidden_dim = encoder_hidden_dim
278
+ self.encoder_in_channels = encoder_in_channels
279
+ self.feat_strides = feat_strides
280
+ self.encoder_attention_heads = encoder_attention_heads
281
+ self.encoder_ffn_dim = encoder_ffn_dim
282
+ self.dropout = dropout
283
+ self.activation_dropout = activation_dropout
284
+ self.encode_proj_layers = encode_proj_layers
285
+ self.encoder_layers = encoder_layers
286
+ self.positional_encoding_temperature = positional_encoding_temperature
287
+ self.eval_size = eval_size
288
+ self.normalize_before = normalize_before
289
+ self.encoder_activation_function = encoder_activation_function
290
+ self.activation_function = activation_function
291
+ self.hidden_expansion = hidden_expansion
292
+ # decoder
293
+ self.d_model = d_model
294
+ self.num_queries = num_queries
295
+ self.decoder_ffn_dim = decoder_ffn_dim
296
+ self.decoder_in_channels = decoder_in_channels
297
+ self.num_feature_levels = num_feature_levels
298
+ self.decoder_n_points = decoder_n_points
299
+ self.decoder_layers = decoder_layers
300
+ self.decoder_attention_heads = decoder_attention_heads
301
+ self.decoder_activation_function = decoder_activation_function
302
+ self.attention_dropout = attention_dropout
303
+ self.num_denoising = num_denoising
304
+ self.label_noise_ratio = label_noise_ratio
305
+ self.box_noise_scale = box_noise_scale
306
+ self.learn_initial_query = learn_initial_query
307
+ self.anchor_image_size = anchor_image_size
308
+ self.auxiliary_loss = auxiliary_loss
309
+ self.with_box_refine = with_box_refine
310
+ # Loss
311
+ self.matcher_alpha = matcher_alpha
312
+ self.matcher_gamma = matcher_gamma
313
+ self.matcher_class_cost = matcher_class_cost
314
+ self.matcher_bbox_cost = matcher_bbox_cost
315
+ self.matcher_giou_cost = matcher_giou_cost
316
+ self.use_focal_loss = use_focal_loss
317
+ self.focal_loss_alpha = focal_loss_alpha
318
+ self.focal_loss_gamma = focal_loss_gamma
319
+ self.weight_loss_vfl = weight_loss_vfl
320
+ self.weight_loss_bbox = weight_loss_bbox
321
+ self.weight_loss_giou = weight_loss_giou
322
+ self.weight_loss_fgl = weight_loss_fgl
323
+ self.weight_loss_ddf = weight_loss_ddf
324
+ self.eos_coefficient = eos_coefficient
325
+ # add the new attributes with the given values or defaults
326
+ self.eval_idx = eval_idx
327
+ self.layer_scale = layer_scale
328
+ self.max_num_bins = max_num_bins
329
+ self.reg_scale = reg_scale
330
+ self.depth_mult = depth_mult
331
+ self.decoder_offset_scale = decoder_offset_scale
332
+ self.decoder_method = decoder_method
333
+ self.top_prob_values = top_prob_values
334
+ self.lqe_hidden_dim = lqe_hidden_dim
335
+ self.lqe_layers = lqe_layers
336
+ self.up = up
337
+ self.tie_word_embeddings = tie_word_embeddings
338
+
339
+ if isinstance(self.decoder_n_points, list):
340
+ if len(self.decoder_n_points) != self.num_feature_levels:
341
+ raise ValueError(
342
+ f"Length of decoder_n_points list ({len(self.decoder_n_points)}) must match num_feature_levels ({self.num_feature_levels})."
343
+ )
344
+
345
+ head_dim = self.d_model // self.decoder_attention_heads
346
+ if head_dim * self.decoder_attention_heads != self.d_model:
347
+ raise ValueError(
348
+ f"Embedded dimension {self.d_model} must be divisible by decoder_attention_heads {self.decoder_attention_heads}"
349
+ )
350
+
351
+ super().__init__(is_encoder_decoder=is_encoder_decoder, **kwargs)
352
+
353
+
354
+ __all__ = ["DFineConfig"]
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/d_fine/modeling_d_fine.py ADDED
@@ -0,0 +1,2063 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/d_fine/modular_d_fine.py.
3
+ # Do NOT edit this file manually as any edits will be overwritten by the generation of
4
+ # the file from the modular. If any change should be done, please apply the change to the
5
+ # modular_d_fine.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # Copyright 2025 Baidu Inc and The HuggingFace Inc. team.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ import math
21
+ from collections.abc import Callable
22
+ from dataclasses import dataclass
23
+
24
+ import torch
25
+ import torch.nn as nn
26
+ import torch.nn.functional as F
27
+ from torch import Tensor
28
+
29
+ from ... import initialization as init
30
+ from ...activations import ACT2CLS
31
+ from ...backbone_utils import load_backbone
32
+ from ...image_transforms import center_to_corners_format, corners_to_center_format
33
+ from ...modeling_outputs import BaseModelOutput
34
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
35
+ from ...processing_utils import Unpack
36
+ from ...pytorch_utils import compile_compatible_method_lru_cache
37
+ from ...utils import ModelOutput, TransformersKwargs, auto_docstring, torch_compilable_check, torch_int
38
+ from ...utils.generic import can_return_tuple, merge_with_config_defaults
39
+ from ...utils.output_capturing import capture_outputs
40
+ from .configuration_d_fine import DFineConfig
41
+
42
+
43
+ @dataclass
44
+ @auto_docstring(
45
+ custom_intro="""
46
+ Base class for outputs of the DFineDecoder. This class adds two attributes to
47
+ BaseModelOutputWithCrossAttentions, namely:
48
+ - a stacked tensor of intermediate decoder hidden states (i.e. the output of each decoder layer)
49
+ - a stacked tensor of intermediate reference points.
50
+ """
51
+ )
52
+ class DFineDecoderOutput(ModelOutput):
53
+ r"""
54
+ intermediate_hidden_states (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, num_queries, hidden_size)`):
55
+ Stacked intermediate hidden states (output of each layer of the decoder).
56
+ intermediate_logits (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, sequence_length, config.num_labels)`):
57
+ Stacked intermediate logits (logits of each layer of the decoder).
58
+ intermediate_reference_points (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, sequence_length, hidden_size)`):
59
+ Stacked intermediate reference points (reference points of each layer of the decoder).
60
+ intermediate_predicted_corners (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, num_queries, 4)`):
61
+ Stacked intermediate predicted corners (predicted corners of each layer of the decoder).
62
+ initial_reference_points (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, num_queries, 4)`):
63
+ Stacked initial reference points (initial reference points of each layer of the decoder).
64
+ cross_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` and `config.add_cross_attention=True` is passed or when `config.output_attentions=True`):
65
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
66
+ sequence_length)`. Attentions weights of the decoder's cross-attention layer, after the attention softmax,
67
+ used to compute the weighted average in the cross-attention heads.
68
+ """
69
+
70
+ last_hidden_state: torch.FloatTensor | None = None
71
+ intermediate_hidden_states: torch.FloatTensor | None = None
72
+ intermediate_logits: torch.FloatTensor | None = None
73
+ intermediate_reference_points: torch.FloatTensor | None = None
74
+ intermediate_predicted_corners: torch.FloatTensor | None = None
75
+ initial_reference_points: torch.FloatTensor | None = None
76
+ hidden_states: tuple[torch.FloatTensor] | None = None
77
+ attentions: tuple[torch.FloatTensor] | None = None
78
+ cross_attentions: tuple[torch.FloatTensor] | None = None
79
+
80
+
81
+ class DFineMLP(nn.Module):
82
+ def __init__(self, input_dim: int, hidden_dim: int, output_dim: int, num_layers: int, act: str = "relu"):
83
+ super().__init__()
84
+ self.num_layers = num_layers
85
+ hidden_dims = [hidden_dim] * (num_layers - 1)
86
+ input_dims = [input_dim] + hidden_dims
87
+ output_dims = hidden_dims + [output_dim]
88
+ self.layers = nn.ModuleList(nn.Linear(in_dim, out_dim) for in_dim, out_dim in zip(input_dims, output_dims))
89
+ self.act = ACT2CLS[act]()
90
+
91
+ def forward(self, stat_features: torch.Tensor) -> torch.Tensor:
92
+ for i, layer in enumerate(self.layers):
93
+ stat_features = self.act(layer(stat_features)) if i < self.num_layers - 1 else layer(stat_features)
94
+ return stat_features
95
+
96
+
97
+ class DFineGate(nn.Module):
98
+ def __init__(self, d_model: int):
99
+ super().__init__()
100
+ self.gate = nn.Linear(2 * d_model, 2 * d_model)
101
+ self.norm = nn.LayerNorm(d_model)
102
+
103
+ def forward(self, second_residual: torch.Tensor, hidden_states: torch.Tensor) -> torch.Tensor:
104
+ gate_input = torch.cat([second_residual, hidden_states], dim=-1)
105
+ gates = torch.sigmoid(self.gate(gate_input))
106
+ gate1, gate2 = gates.chunk(2, dim=-1)
107
+ hidden_states = self.norm(gate1 * second_residual + gate2 * hidden_states)
108
+ return hidden_states
109
+
110
+
111
+ class DFineFrozenBatchNorm2d(nn.Module):
112
+ """
113
+ BatchNorm2d where the batch statistics and the affine parameters are fixed.
114
+
115
+ Copy-paste from torchvision.misc.ops with added eps before rqsrt, without which any other models than
116
+ torchvision.models.resnet[18,34,50,101] produce nans.
117
+ """
118
+
119
+ def __init__(self, n):
120
+ super().__init__()
121
+ self.register_buffer("weight", torch.ones(n))
122
+ self.register_buffer("bias", torch.zeros(n))
123
+ self.register_buffer("running_mean", torch.zeros(n))
124
+ self.register_buffer("running_var", torch.ones(n))
125
+
126
+ def _load_from_state_dict(
127
+ self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs
128
+ ):
129
+ num_batches_tracked_key = prefix + "num_batches_tracked"
130
+ if num_batches_tracked_key in state_dict:
131
+ del state_dict[num_batches_tracked_key]
132
+
133
+ super()._load_from_state_dict(
134
+ state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs
135
+ )
136
+
137
+ def forward(self, x):
138
+ # move reshapes to the beginning
139
+ # to make it user-friendly
140
+ weight = self.weight.reshape(1, -1, 1, 1)
141
+ bias = self.bias.reshape(1, -1, 1, 1)
142
+ running_var = self.running_var.reshape(1, -1, 1, 1)
143
+ running_mean = self.running_mean.reshape(1, -1, 1, 1)
144
+ epsilon = 1e-5
145
+ scale = weight * (running_var + epsilon).rsqrt()
146
+ bias = bias - running_mean * scale
147
+ return x * scale + bias
148
+
149
+
150
+ def multi_scale_deformable_attention_v2(
151
+ value: Tensor,
152
+ value_spatial_shapes: Tensor,
153
+ sampling_locations: Tensor,
154
+ attention_weights: Tensor,
155
+ num_points_list: list[int],
156
+ method="default",
157
+ ) -> Tensor:
158
+ batch_size, _, num_heads, hidden_dim = value.shape
159
+ _, num_queries, num_heads, num_levels, num_points = sampling_locations.shape
160
+ value_list = (
161
+ value.permute(0, 2, 3, 1)
162
+ .flatten(0, 1)
163
+ .split([height * width for height, width in value_spatial_shapes], dim=-1)
164
+ )
165
+ # sampling_offsets [8, 480, 8, 12, 2]
166
+ if method == "default":
167
+ sampling_grids = 2 * sampling_locations - 1
168
+ elif method == "discrete":
169
+ sampling_grids = sampling_locations
170
+ sampling_grids = sampling_grids.permute(0, 2, 1, 3, 4).flatten(0, 1)
171
+ sampling_grids = sampling_grids.split(num_points_list, dim=-2)
172
+ sampling_value_list = []
173
+ for level_id, (height, width) in enumerate(value_spatial_shapes):
174
+ # batch_size, height*width, num_heads, hidden_dim
175
+ # -> batch_size, height*width, num_heads*hidden_dim
176
+ # -> batch_size, num_heads*hidden_dim, height*width
177
+ # -> batch_size*num_heads, hidden_dim, height, width
178
+ value_l_ = value_list[level_id].reshape(batch_size * num_heads, hidden_dim, height, width)
179
+ # batch_size, num_queries, num_heads, num_points, 2
180
+ # -> batch_size, num_heads, num_queries, num_points, 2
181
+ # -> batch_size*num_heads, num_queries, num_points, 2
182
+ sampling_grid_l_ = sampling_grids[level_id]
183
+ # batch_size*num_heads, hidden_dim, num_queries, num_points
184
+ if method == "default":
185
+ sampling_value_l_ = nn.functional.grid_sample(
186
+ value_l_, sampling_grid_l_, mode="bilinear", padding_mode="zeros", align_corners=False
187
+ )
188
+ elif method == "discrete":
189
+ sampling_coord = (sampling_grid_l_ * torch.tensor([[width, height]], device=value.device) + 0.5).to(
190
+ torch.int64
191
+ )
192
+
193
+ # Separate clamping for x and y coordinates
194
+ sampling_coord_x = sampling_coord[..., 0].clamp(0, width - 1)
195
+ sampling_coord_y = sampling_coord[..., 1].clamp(0, height - 1)
196
+
197
+ # Combine the clamped coordinates
198
+ sampling_coord = torch.stack([sampling_coord_x, sampling_coord_y], dim=-1)
199
+ sampling_coord = sampling_coord.reshape(batch_size * num_heads, num_queries * num_points_list[level_id], 2)
200
+ sampling_idx = (
201
+ torch.arange(sampling_coord.shape[0], device=value.device)
202
+ .unsqueeze(-1)
203
+ .repeat(1, sampling_coord.shape[1])
204
+ )
205
+ sampling_value_l_ = value_l_[sampling_idx, :, sampling_coord[..., 1], sampling_coord[..., 0]]
206
+ sampling_value_l_ = sampling_value_l_.permute(0, 2, 1).reshape(
207
+ batch_size * num_heads, hidden_dim, num_queries, num_points_list[level_id]
208
+ )
209
+ sampling_value_list.append(sampling_value_l_)
210
+ # (batch_size, num_queries, num_heads, num_levels, num_points)
211
+ # -> (batch_size, num_heads, num_queries, num_levels, num_points)
212
+ # -> (batch_size, num_heads, 1, num_queries, num_levels*num_points)
213
+ attention_weights = attention_weights.permute(0, 2, 1, 3).reshape(
214
+ batch_size * num_heads, 1, num_queries, sum(num_points_list)
215
+ )
216
+ output = (
217
+ (torch.concat(sampling_value_list, dim=-1) * attention_weights)
218
+ .sum(-1)
219
+ .view(batch_size, num_heads * hidden_dim, num_queries)
220
+ )
221
+ return output.transpose(1, 2).contiguous()
222
+
223
+
224
+ class DFineMultiscaleDeformableAttention(nn.Module):
225
+ def __init__(self, config: DFineConfig):
226
+ """
227
+ D-Fine version of multiscale deformable attention
228
+ """
229
+ super().__init__()
230
+ self.d_model = config.d_model
231
+ self.n_heads = config.decoder_attention_heads
232
+ self.n_levels = config.num_feature_levels
233
+ self.offset_scale = config.decoder_offset_scale
234
+ self.decoder_method = config.decoder_method
235
+ self.n_points = config.decoder_n_points
236
+
237
+ if isinstance(self.n_points, list):
238
+ num_points_list = self.n_points
239
+ else:
240
+ num_points_list = [self.n_points for _ in range(self.n_levels)]
241
+
242
+ self.num_points_list = num_points_list
243
+ num_points_scale = [1 / n for n in self.num_points_list for _ in range(n)]
244
+ self.register_buffer("num_points_scale", torch.tensor(num_points_scale, dtype=torch.float32))
245
+
246
+ self.total_points = self.n_heads * sum(self.num_points_list)
247
+
248
+ self.sampling_offsets = nn.Linear(self.d_model, self.total_points * 2)
249
+ self.attention_weights = nn.Linear(self.d_model, self.total_points)
250
+
251
+ self.ms_deformable_attn_core = multi_scale_deformable_attention_v2
252
+
253
+ def forward(
254
+ self,
255
+ hidden_states: torch.Tensor,
256
+ attention_mask: torch.Tensor | None = None,
257
+ reference_points=None,
258
+ encoder_hidden_states=None,
259
+ spatial_shapes=None,
260
+ spatial_shapes_list=None,
261
+ **kwargs: Unpack[TransformersKwargs],
262
+ ) -> tuple[torch.Tensor, torch.Tensor]:
263
+ batch_size, num_queries, _ = hidden_states.shape
264
+ batch_size, sequence_length, _ = encoder_hidden_states.shape
265
+
266
+ torch_compilable_check(
267
+ (spatial_shapes[:, 0] * spatial_shapes[:, 1]).sum() == sequence_length,
268
+ "Make sure to align the spatial shapes with the sequence length of the encoder hidden states",
269
+ )
270
+
271
+ # Reshape for multi-head attention
272
+ value = encoder_hidden_states.reshape(batch_size, sequence_length, self.n_heads, self.d_model // self.n_heads)
273
+ if attention_mask is not None:
274
+ value = value.masked_fill(~attention_mask[..., None], float(0))
275
+
276
+ sampling_offsets: torch.Tensor = self.sampling_offsets(hidden_states)
277
+ sampling_offsets = sampling_offsets.reshape(
278
+ batch_size, num_queries, self.n_heads, sum(self.num_points_list), 2
279
+ )
280
+
281
+ attention_weights = self.attention_weights(hidden_states).reshape(
282
+ batch_size, num_queries, self.n_heads, sum(self.num_points_list)
283
+ )
284
+ attention_weights = F.softmax(attention_weights, dim=-1)
285
+
286
+ if reference_points.shape[-1] == 2:
287
+ offset_normalizer = torch.tensor(spatial_shapes)
288
+ offset_normalizer = offset_normalizer.flip([1]).reshape(1, 1, 1, self.n_levels, 1, 2)
289
+ sampling_locations = (
290
+ reference_points.reshape(batch_size, sequence_length, 1, self.n_levels, 1, 2)
291
+ + sampling_offsets / offset_normalizer
292
+ )
293
+ elif reference_points.shape[-1] == 4:
294
+ # reference_points [8, 480, None, 1, 4]
295
+ # sampling_offsets [8, 480, 8, 12, 2]
296
+ num_points_scale = self.num_points_scale.to(dtype=hidden_states.dtype).unsqueeze(-1)
297
+ offset = sampling_offsets * num_points_scale * reference_points[:, :, None, :, 2:] * self.offset_scale
298
+ sampling_locations = reference_points[:, :, None, :, :2] + offset
299
+ else:
300
+ raise ValueError(
301
+ f"Last dim of reference_points must be 2 or 4, but get {reference_points.shape[-1]} instead."
302
+ )
303
+
304
+ output = self.ms_deformable_attn_core(
305
+ value,
306
+ spatial_shapes_list,
307
+ sampling_locations,
308
+ attention_weights,
309
+ self.num_points_list,
310
+ self.decoder_method,
311
+ )
312
+
313
+ return output, attention_weights
314
+
315
+
316
+ class DFineConvNormLayer(nn.Module):
317
+ def __init__(
318
+ self,
319
+ config: DFineConfig,
320
+ in_channels: int,
321
+ out_channels: int,
322
+ kernel_size: int,
323
+ stride: int,
324
+ groups: int = 1,
325
+ padding: int | None = None,
326
+ activation: str | None = None,
327
+ ):
328
+ super().__init__()
329
+ self.conv = nn.Conv2d(
330
+ in_channels,
331
+ out_channels,
332
+ kernel_size,
333
+ stride,
334
+ groups=groups,
335
+ padding=(kernel_size - 1) // 2 if padding is None else padding,
336
+ bias=False,
337
+ )
338
+ self.norm = nn.BatchNorm2d(out_channels, config.batch_norm_eps)
339
+ self.activation = nn.Identity() if activation is None else ACT2CLS[activation]()
340
+
341
+ def forward(self, hidden_state):
342
+ hidden_state = self.conv(hidden_state)
343
+ hidden_state = self.norm(hidden_state)
344
+ hidden_state = self.activation(hidden_state)
345
+ return hidden_state
346
+
347
+
348
+ class DFineRepVggBlock(nn.Module):
349
+ """
350
+ RepVGG architecture block introduced by the work "RepVGG: Making VGG-style ConvNets Great Again".
351
+ """
352
+
353
+ def __init__(self, config: DFineConfig, in_channels: int, out_channels: int):
354
+ super().__init__()
355
+
356
+ activation = config.activation_function
357
+ hidden_channels = in_channels
358
+ self.conv1 = DFineConvNormLayer(config, hidden_channels, out_channels, 3, 1, padding=1)
359
+ self.conv2 = DFineConvNormLayer(config, hidden_channels, out_channels, 1, 1, padding=0)
360
+ self.activation = nn.Identity() if activation is None else ACT2CLS[activation]()
361
+
362
+ def forward(self, x):
363
+ y = self.conv1(x) + self.conv2(x)
364
+ return self.activation(y)
365
+
366
+
367
+ class DFineCSPRepLayer(nn.Module):
368
+ """
369
+ Cross Stage Partial (CSP) network layer with RepVGG blocks.
370
+ """
371
+
372
+ def __init__(
373
+ self, config: DFineConfig, in_channels: int, out_channels: int, num_blocks: int, expansion: float = 1.0
374
+ ):
375
+ super().__init__()
376
+ activation = config.activation_function
377
+
378
+ hidden_channels = int(out_channels * expansion)
379
+ self.conv1 = DFineConvNormLayer(config, in_channels, hidden_channels, 1, 1, activation=activation)
380
+ self.conv2 = DFineConvNormLayer(config, in_channels, hidden_channels, 1, 1, activation=activation)
381
+ self.bottlenecks = nn.ModuleList(
382
+ [DFineRepVggBlock(config, hidden_channels, hidden_channels) for _ in range(num_blocks)]
383
+ )
384
+ if hidden_channels != out_channels:
385
+ self.conv3 = DFineConvNormLayer(config, hidden_channels, out_channels, 1, 1, activation=activation)
386
+ else:
387
+ self.conv3 = nn.Identity()
388
+
389
+ def forward(self, hidden_state: torch.Tensor) -> torch.Tensor:
390
+ hidden_state_1 = self.conv1(hidden_state)
391
+ for bottleneck in self.bottlenecks:
392
+ hidden_state_1 = bottleneck(hidden_state_1)
393
+ hidden_state_2 = self.conv2(hidden_state)
394
+ hidden_state_3 = self.conv3(hidden_state_1 + hidden_state_2)
395
+ return hidden_state_3
396
+
397
+
398
+ class DFineRepNCSPELAN4(nn.Module):
399
+ def __init__(self, config: DFineConfig, act: str = "silu", numb_blocks: int = 3):
400
+ super().__init__()
401
+ conv1_dim = config.encoder_hidden_dim * 2
402
+ conv2_dim = config.encoder_hidden_dim
403
+ conv3_dim = config.encoder_hidden_dim * 2
404
+ conv4_dim = round(config.hidden_expansion * config.encoder_hidden_dim // 2)
405
+ self.conv_dim = conv3_dim // 2
406
+ self.conv1 = DFineConvNormLayer(config, conv1_dim, conv3_dim, 1, 1, activation=act)
407
+ self.csp_rep1 = DFineCSPRepLayer(config, conv3_dim // 2, conv4_dim, num_blocks=numb_blocks)
408
+ self.conv2 = DFineConvNormLayer(config, conv4_dim, conv4_dim, 3, 1, activation=act)
409
+ self.csp_rep2 = DFineCSPRepLayer(config, conv4_dim, conv4_dim, num_blocks=numb_blocks)
410
+ self.conv3 = DFineConvNormLayer(config, conv4_dim, conv4_dim, 3, 1, activation=act)
411
+ self.conv4 = DFineConvNormLayer(config, conv3_dim + (2 * conv4_dim), conv2_dim, 1, 1, activation=act)
412
+
413
+ def forward(self, input_features: torch.Tensor) -> torch.Tensor:
414
+ # Split initial features into two branches after first convolution
415
+ split_features = list(self.conv1(input_features).split((self.conv_dim, self.conv_dim), 1))
416
+
417
+ # Process branches sequentially
418
+ branch1 = self.csp_rep1(split_features[-1])
419
+ branch1 = self.conv2(branch1)
420
+ branch2 = self.csp_rep2(branch1)
421
+ branch2 = self.conv3(branch2)
422
+
423
+ split_features.extend([branch1, branch2])
424
+ merged_features = torch.cat(split_features, 1)
425
+ merged_features = self.conv4(merged_features)
426
+ return merged_features
427
+
428
+
429
+ class DFineSCDown(nn.Module):
430
+ def __init__(self, config: DFineConfig, kernel_size: int, stride: int):
431
+ super().__init__()
432
+ self.conv1 = DFineConvNormLayer(config, config.encoder_hidden_dim, config.encoder_hidden_dim, 1, 1)
433
+ self.conv2 = DFineConvNormLayer(
434
+ config,
435
+ config.encoder_hidden_dim,
436
+ config.encoder_hidden_dim,
437
+ kernel_size,
438
+ stride,
439
+ config.encoder_hidden_dim,
440
+ )
441
+
442
+ def forward(self, input_features: torch.Tensor) -> torch.Tensor:
443
+ input_features = self.conv1(input_features)
444
+ input_features = self.conv2(input_features)
445
+ return input_features
446
+
447
+
448
+ def eager_attention_forward(
449
+ module: nn.Module,
450
+ query: torch.Tensor,
451
+ key: torch.Tensor,
452
+ value: torch.Tensor,
453
+ attention_mask: torch.Tensor | None,
454
+ scaling: float | None = None,
455
+ dropout: float = 0.0,
456
+ **kwargs: Unpack[TransformersKwargs],
457
+ ):
458
+ if scaling is None:
459
+ scaling = query.size(-1) ** -0.5
460
+
461
+ # Take the dot product between "query" and "key" to get the raw attention scores.
462
+ attn_weights = torch.matmul(query, key.transpose(2, 3)) * scaling
463
+
464
+ if attention_mask is not None:
465
+ attn_weights = attn_weights + attention_mask
466
+
467
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
468
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
469
+
470
+ attn_output = torch.matmul(attn_weights, value)
471
+ attn_output = attn_output.transpose(1, 2).contiguous()
472
+
473
+ return attn_output, attn_weights
474
+
475
+
476
+ class DFineSelfAttention(nn.Module):
477
+ """
478
+ Multi-headed self-attention from 'Attention Is All You Need' paper.
479
+
480
+ In D_FINE, position embeddings are added to both queries and keys (but not values) in self-attention.
481
+ """
482
+
483
+ def __init__(
484
+ self,
485
+ config: DFineConfig,
486
+ hidden_size: int,
487
+ num_attention_heads: int,
488
+ dropout: float = 0.0,
489
+ bias: bool = True,
490
+ ):
491
+ super().__init__()
492
+ self.config = config
493
+ self.head_dim = hidden_size // num_attention_heads
494
+ self.scaling = self.head_dim**-0.5
495
+ self.attention_dropout = dropout
496
+ self.is_causal = False
497
+
498
+ self.k_proj = nn.Linear(hidden_size, hidden_size, bias=bias)
499
+ self.v_proj = nn.Linear(hidden_size, hidden_size, bias=bias)
500
+ self.q_proj = nn.Linear(hidden_size, hidden_size, bias=bias)
501
+ self.o_proj = nn.Linear(hidden_size, hidden_size, bias=bias)
502
+
503
+ def forward(
504
+ self,
505
+ hidden_states: torch.Tensor,
506
+ attention_mask: torch.Tensor | None = None,
507
+ position_embeddings: torch.Tensor | None = None,
508
+ **kwargs: Unpack[TransformersKwargs],
509
+ ) -> tuple[torch.Tensor, torch.Tensor]:
510
+ """
511
+ Position embeddings are added to both queries and keys (but not values).
512
+ """
513
+ input_shape = hidden_states.shape[:-1]
514
+ hidden_shape = (*input_shape, -1, self.head_dim)
515
+
516
+ query_key_input = hidden_states + position_embeddings if position_embeddings is not None else hidden_states
517
+
518
+ query_states = self.q_proj(query_key_input).view(hidden_shape).transpose(1, 2)
519
+ key_states = self.k_proj(query_key_input).view(hidden_shape).transpose(1, 2)
520
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
521
+
522
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
523
+ self.config._attn_implementation, eager_attention_forward
524
+ )
525
+
526
+ attn_output, attn_weights = attention_interface(
527
+ self,
528
+ query_states,
529
+ key_states,
530
+ value_states,
531
+ attention_mask,
532
+ dropout=0.0 if not self.training else self.attention_dropout,
533
+ scaling=self.scaling,
534
+ **kwargs,
535
+ )
536
+
537
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
538
+ attn_output = self.o_proj(attn_output)
539
+ return attn_output, attn_weights
540
+
541
+
542
+ class DFineEncoderLayer(nn.Module):
543
+ def __init__(self, config: DFineConfig):
544
+ super().__init__()
545
+ self.normalize_before = config.normalize_before
546
+ self.hidden_size = config.encoder_hidden_dim
547
+
548
+ # self-attention
549
+ self.self_attn = DFineSelfAttention(
550
+ config=config,
551
+ hidden_size=self.hidden_size,
552
+ num_attention_heads=config.num_attention_heads,
553
+ dropout=config.dropout,
554
+ )
555
+ self.self_attn_layer_norm = nn.LayerNorm(self.hidden_size, eps=config.layer_norm_eps)
556
+ self.dropout = config.dropout
557
+ self.mlp = DFineMLP(
558
+ self.hidden_size, config.encoder_ffn_dim, self.hidden_size, 2, config.encoder_activation_function
559
+ )
560
+ self.final_layer_norm = nn.LayerNorm(self.hidden_size, eps=config.layer_norm_eps)
561
+
562
+ def forward(
563
+ self,
564
+ hidden_states: torch.Tensor,
565
+ attention_mask: torch.Tensor,
566
+ spatial_position_embeddings: torch.Tensor | None = None,
567
+ **kwargs: Unpack[TransformersKwargs],
568
+ ) -> torch.Tensor:
569
+ """
570
+ Args:
571
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, hidden_size)`
572
+ attention_mask (`torch.FloatTensor`): attention mask of size
573
+ `(batch, 1, target_len, source_len)` where padding elements are indicated by very large negative
574
+ values.
575
+ spatial_position_embeddings (`torch.FloatTensor`, *optional*):
576
+ Spatial position embeddings (2D positional encodings of image locations), to be added to both
577
+ the queries and keys in self-attention (but not to values).
578
+ """
579
+ residual = hidden_states
580
+ if self.normalize_before:
581
+ hidden_states = self.self_attn_layer_norm(hidden_states)
582
+
583
+ hidden_states, _ = self.self_attn(
584
+ hidden_states=hidden_states,
585
+ attention_mask=attention_mask,
586
+ position_embeddings=spatial_position_embeddings,
587
+ **kwargs,
588
+ )
589
+
590
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
591
+ hidden_states = residual + hidden_states
592
+ if not self.normalize_before:
593
+ hidden_states = self.self_attn_layer_norm(hidden_states)
594
+
595
+ if self.normalize_before:
596
+ hidden_states = self.final_layer_norm(hidden_states)
597
+ residual = hidden_states
598
+
599
+ hidden_states = self.mlp(hidden_states)
600
+
601
+ hidden_states = residual + hidden_states
602
+ if not self.normalize_before:
603
+ hidden_states = self.final_layer_norm(hidden_states)
604
+
605
+ if self.training:
606
+ if not torch.isfinite(hidden_states).all():
607
+ clamp_value = torch.finfo(hidden_states.dtype).max - 1000
608
+ hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)
609
+
610
+ return hidden_states
611
+
612
+
613
+ class DFineSinePositionEmbedding(nn.Module):
614
+ """
615
+ 2D sinusoidal position embedding used in RT-DETR hybrid encoder.
616
+ """
617
+
618
+ def __init__(self, embed_dim: int = 256, temperature: int = 10000):
619
+ super().__init__()
620
+ self.embed_dim = embed_dim
621
+ self.temperature = temperature
622
+
623
+ @compile_compatible_method_lru_cache(maxsize=32)
624
+ def forward(
625
+ self,
626
+ width: int,
627
+ height: int,
628
+ device: torch.device | str,
629
+ dtype: torch.dtype,
630
+ ) -> torch.Tensor:
631
+ """
632
+ Generate 2D sinusoidal position embeddings.
633
+
634
+ Returns:
635
+ Position embeddings of shape (1, height*width, embed_dim)
636
+ """
637
+ grid_w = torch.arange(torch_int(width), device=device).to(dtype)
638
+ grid_h = torch.arange(torch_int(height), device=device).to(dtype)
639
+ grid_w, grid_h = torch.meshgrid(grid_w, grid_h, indexing="xy")
640
+ if self.embed_dim % 4 != 0:
641
+ raise ValueError("Embed dimension must be divisible by 4 for 2D sin-cos position embedding")
642
+ pos_dim = self.embed_dim // 4
643
+ omega = torch.arange(pos_dim, device=device).to(dtype) / pos_dim
644
+ omega = 1.0 / (self.temperature**omega)
645
+
646
+ out_w = grid_w.flatten()[..., None] @ omega[None]
647
+ out_h = grid_h.flatten()[..., None] @ omega[None]
648
+
649
+ return torch.concat([out_h.sin(), out_h.cos(), out_w.sin(), out_w.cos()], dim=1)[None, :, :]
650
+
651
+
652
+ class DFineAIFILayer(nn.Module):
653
+ """
654
+ AIFI (Attention-based Intra-scale Feature Interaction) layer used in RT-DETR hybrid encoder.
655
+ """
656
+
657
+ def __init__(self, config: DFineConfig):
658
+ super().__init__()
659
+ self.config = config
660
+ self.encoder_hidden_dim = config.encoder_hidden_dim
661
+ self.eval_size = config.eval_size
662
+
663
+ self.position_embedding = DFineSinePositionEmbedding(
664
+ embed_dim=self.encoder_hidden_dim,
665
+ temperature=config.positional_encoding_temperature,
666
+ )
667
+ self.layers = nn.ModuleList([DFineEncoderLayer(config) for _ in range(config.encoder_layers)])
668
+
669
+ def forward(
670
+ self,
671
+ hidden_states: torch.Tensor,
672
+ **kwargs: Unpack[TransformersKwargs],
673
+ ) -> torch.Tensor:
674
+ """
675
+ Args:
676
+ hidden_states (`torch.FloatTensor` of shape `(batch_size, channels, height, width)`):
677
+ Feature map to process.
678
+ """
679
+ batch_size = hidden_states.shape[0]
680
+ height, width = hidden_states.shape[2:]
681
+
682
+ hidden_states = hidden_states.flatten(2).permute(0, 2, 1)
683
+
684
+ if self.training or self.eval_size is None:
685
+ pos_embed = self.position_embedding(
686
+ width=width,
687
+ height=height,
688
+ device=hidden_states.device,
689
+ dtype=hidden_states.dtype,
690
+ )
691
+ else:
692
+ pos_embed = None
693
+
694
+ for layer in self.layers:
695
+ hidden_states = layer(
696
+ hidden_states,
697
+ attention_mask=None,
698
+ spatial_position_embeddings=pos_embed,
699
+ **kwargs,
700
+ )
701
+
702
+ hidden_states = (
703
+ hidden_states.permute(0, 2, 1).reshape(batch_size, self.encoder_hidden_dim, height, width).contiguous()
704
+ )
705
+
706
+ return hidden_states
707
+
708
+
709
+ class DFineIntegral(nn.Module):
710
+ """
711
+ A static layer that calculates integral results from a distribution.
712
+
713
+ This layer computes the target location using the formula: `sum{Pr(n) * W(n)}`,
714
+ where Pr(n) is the softmax probability vector representing the discrete
715
+ distribution, and W(n) is the non-uniform Weighting Function.
716
+
717
+ Args:
718
+ max_num_bins (int): Max number of the discrete bins. Default is 32.
719
+ It can be adjusted based on the dataset or task requirements.
720
+ """
721
+
722
+ def __init__(self, config: DFineConfig):
723
+ super().__init__()
724
+ self.max_num_bins = config.max_num_bins
725
+
726
+ def forward(self, pred_corners: torch.Tensor, project: torch.Tensor) -> torch.Tensor:
727
+ batch_size, num_queries, _ = pred_corners.shape
728
+ pred_corners = F.softmax(pred_corners.reshape(-1, self.max_num_bins + 1), dim=1)
729
+ pred_corners = F.linear(pred_corners, project.to(pred_corners.device)).reshape(-1, 4)
730
+ pred_corners = pred_corners.reshape(batch_size, num_queries, -1)
731
+ return pred_corners
732
+
733
+
734
+ class DFineLQE(nn.Module):
735
+ def __init__(self, config: DFineConfig):
736
+ super().__init__()
737
+ self.top_prob_values = config.top_prob_values
738
+ self.max_num_bins = config.max_num_bins
739
+ self.reg_conf = DFineMLP(4 * (self.top_prob_values + 1), config.lqe_hidden_dim, 1, config.lqe_layers)
740
+
741
+ def forward(self, scores: torch.Tensor, pred_corners: torch.Tensor) -> torch.Tensor:
742
+ batch_size, length, _ = pred_corners.size()
743
+ prob = F.softmax(pred_corners.reshape(batch_size, length, 4, self.max_num_bins + 1), dim=-1)
744
+ prob_topk, _ = prob.topk(self.top_prob_values, dim=-1)
745
+ stat = torch.cat([prob_topk, prob_topk.mean(dim=-1, keepdim=True)], dim=-1)
746
+ quality_score = self.reg_conf(stat.reshape(batch_size, length, -1))
747
+ scores = scores + quality_score
748
+ return scores
749
+
750
+
751
+ class DFineDecoderLayer(nn.Module):
752
+ def __init__(self, config: DFineConfig):
753
+ super().__init__()
754
+ self.hidden_size = config.d_model
755
+
756
+ # self-attention
757
+ self.self_attn = DFineSelfAttention(
758
+ config=config,
759
+ hidden_size=self.hidden_size,
760
+ num_attention_heads=config.decoder_attention_heads,
761
+ dropout=config.attention_dropout,
762
+ )
763
+ self.dropout = config.dropout
764
+
765
+ self.self_attn_layer_norm = nn.LayerNorm(self.hidden_size, eps=config.layer_norm_eps)
766
+
767
+ # override the encoder attention module with d-fine version
768
+ self.encoder_attn = DFineMultiscaleDeformableAttention(config=config)
769
+ self.mlp = DFineMLP(
770
+ self.hidden_size, config.decoder_ffn_dim, self.hidden_size, 2, config.decoder_activation_function
771
+ )
772
+ self.final_layer_norm = nn.LayerNorm(self.hidden_size, eps=config.layer_norm_eps)
773
+ # gate
774
+ self.gateway = DFineGate(config.d_model)
775
+
776
+ def forward(
777
+ self,
778
+ hidden_states: torch.Tensor,
779
+ position_embeddings: torch.Tensor | None = None,
780
+ reference_points=None,
781
+ spatial_shapes=None,
782
+ spatial_shapes_list=None,
783
+ encoder_hidden_states: torch.Tensor | None = None,
784
+ encoder_attention_mask: torch.Tensor | None = None,
785
+ **kwargs: Unpack[TransformersKwargs],
786
+ ) -> torch.Tensor:
787
+ """
788
+ Args:
789
+ hidden_states (`torch.FloatTensor`):
790
+ Input to the layer of shape `(batch, seq_len, hidden_size)`.
791
+ object_queries_position_embeddings (`torch.FloatTensor`, *optional*):
792
+ Position embeddings for the object query slots. These are added to both queries and keys
793
+ in the self-attention layer (not values).
794
+ reference_points (`torch.FloatTensor`, *optional*):
795
+ Reference points.
796
+ spatial_shapes (`torch.LongTensor`, *optional*):
797
+ Spatial shapes.
798
+ level_start_index (`torch.LongTensor`, *optional*):
799
+ Level start index.
800
+ encoder_hidden_states (`torch.FloatTensor`):
801
+ cross attention input to the layer of shape `(batch, seq_len, hidden_size)`
802
+ encoder_attention_mask (`torch.FloatTensor`): encoder attention mask of size
803
+ `(batch, 1, target_len, source_len)` where padding elements are indicated by very large negative
804
+ values.
805
+ """
806
+ residual = hidden_states
807
+
808
+ # Self Attention
809
+ hidden_states, _ = self.self_attn(
810
+ hidden_states=hidden_states,
811
+ attention_mask=encoder_attention_mask,
812
+ position_embeddings=position_embeddings,
813
+ **kwargs,
814
+ )
815
+
816
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
817
+ hidden_states = residual + hidden_states
818
+ hidden_states = self.self_attn_layer_norm(hidden_states)
819
+
820
+ residual = hidden_states
821
+
822
+ # Cross-Attention
823
+ hidden_states = hidden_states if position_embeddings is None else hidden_states + position_embeddings
824
+ hidden_states, _ = self.encoder_attn(
825
+ hidden_states=hidden_states,
826
+ encoder_hidden_states=encoder_hidden_states,
827
+ reference_points=reference_points,
828
+ spatial_shapes=spatial_shapes,
829
+ spatial_shapes_list=spatial_shapes_list,
830
+ )
831
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
832
+ hidden_states = self.gateway(residual, hidden_states)
833
+
834
+ # Fully Connected
835
+ residual = hidden_states
836
+ hidden_states = self.mlp(hidden_states)
837
+ hidden_states = residual + hidden_states
838
+ hidden_states = self.final_layer_norm(hidden_states.clamp(min=-65504, max=65504))
839
+
840
+ return hidden_states
841
+
842
+
843
+ class DFineMLPPredictionHead(nn.Module):
844
+ """
845
+ Very simple multi-layer perceptron (MLP, also called FFN), used to predict the normalized center coordinates,
846
+ height and width of a bounding box w.r.t. an image.
847
+
848
+ """
849
+
850
+ def __init__(self, input_dim, hidden_dim, output_dim, num_layers):
851
+ super().__init__()
852
+ self.num_layers = num_layers
853
+ h = [hidden_dim] * (num_layers - 1)
854
+ self.layers = nn.ModuleList(nn.Linear(n, k) for n, k in zip([input_dim] + h, h + [output_dim]))
855
+
856
+ def forward(self, x):
857
+ for i, layer in enumerate(self.layers):
858
+ x = nn.functional.relu(layer(x)) if i < self.num_layers - 1 else layer(x)
859
+ return x
860
+
861
+
862
+ @auto_docstring
863
+ class DFinePreTrainedModel(PreTrainedModel):
864
+ config: DFineConfig
865
+ base_model_prefix = "d_fine"
866
+ main_input_name = "pixel_values"
867
+ input_modalities = ("image",)
868
+ _no_split_modules = [r"DFineHybridEncoder", r"DFineDecoderLayer"]
869
+ _supports_sdpa = True
870
+ _supports_flash_attn = True
871
+ _supports_attention_backend = True
872
+ _supports_flex_attn = True
873
+
874
+ @torch.no_grad()
875
+ def _init_weights(self, module):
876
+ """Initialize the weights"""
877
+ # initialize linear layer bias value according to a given probability value.
878
+ if isinstance(module, (DFineForObjectDetection, DFineDecoder)):
879
+ if module.class_embed is not None:
880
+ for layer in module.class_embed:
881
+ prior_prob = self.config.initializer_bias_prior_prob or 1 / (self.config.num_labels + 1)
882
+ bias = float(-math.log((1 - prior_prob) / prior_prob))
883
+ init.xavier_uniform_(layer.weight)
884
+ init.constant_(layer.bias, bias)
885
+
886
+ if module.bbox_embed is not None:
887
+ for layer in module.bbox_embed:
888
+ init.constant_(layer.layers[-1].weight, 0)
889
+ init.constant_(layer.layers[-1].bias, 0)
890
+
891
+ if hasattr(module, "reg_scale"):
892
+ init.constant_(module.reg_scale, self.config.reg_scale)
893
+
894
+ if hasattr(module, "up"):
895
+ init.constant_(module.up, self.config.up)
896
+
897
+ if isinstance(module, DFineMultiscaleDeformableAttention):
898
+ init.constant_(module.sampling_offsets.weight, 0.0)
899
+ default_dtype = torch.get_default_dtype()
900
+ thetas = torch.arange(module.n_heads, dtype=torch.int64).to(default_dtype) * (
901
+ 2.0 * math.pi / module.n_heads
902
+ )
903
+ grid_init = torch.stack([thetas.cos(), thetas.sin()], -1)
904
+ grid_init = grid_init / grid_init.abs().max(-1, keepdim=True).values
905
+ grid_init = grid_init.reshape(module.n_heads, 1, 2).tile([1, sum(module.num_points_list), 1])
906
+ scaling = torch.concat([torch.arange(1, n + 1) for n in module.num_points_list]).reshape(1, -1, 1)
907
+ grid_init *= scaling
908
+ init.copy_(module.sampling_offsets.bias, grid_init.flatten())
909
+
910
+ init.constant_(module.attention_weights.weight, 0.0)
911
+ init.constant_(module.attention_weights.bias, 0.0)
912
+
913
+ num_points_scale = [1 / n for n in module.num_points_list for _ in range(n)]
914
+ init.copy_(module.num_points_scale, torch.tensor(num_points_scale, dtype=torch.float32))
915
+
916
+ if isinstance(module, DFineModel):
917
+ prior_prob = self.config.initializer_bias_prior_prob or 1 / (self.config.num_labels + 1)
918
+ bias = float(-math.log((1 - prior_prob) / prior_prob))
919
+ init.xavier_uniform_(module.enc_score_head.weight)
920
+ init.constant_(module.enc_score_head.bias, bias)
921
+
922
+ if isinstance(module, (nn.Linear, nn.Conv2d, nn.BatchNorm2d)):
923
+ init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
924
+ if module.bias is not None:
925
+ init.zeros_(module.bias)
926
+ if getattr(module, "running_mean", None) is not None:
927
+ init.zeros_(module.running_mean)
928
+ init.ones_(module.running_var)
929
+ init.zeros_(module.num_batches_tracked)
930
+
931
+ if isinstance(module, DFineGate):
932
+ bias = float(-math.log((1 - 0.5) / 0.5))
933
+ init.constant_(module.gate.bias, bias)
934
+ init.constant_(module.gate.weight, 0)
935
+
936
+ if isinstance(module, DFineLQE):
937
+ init.constant_(module.reg_conf.layers[-1].bias, 0)
938
+ init.constant_(module.reg_conf.layers[-1].weight, 0)
939
+
940
+ if isinstance(module, nn.LayerNorm):
941
+ init.ones_(module.weight)
942
+ init.zeros_(module.bias)
943
+
944
+ if hasattr(module, "weight_embedding") and self.config.learn_initial_query:
945
+ init.xavier_uniform_(module.weight_embedding.weight)
946
+ if hasattr(module, "denoising_class_embed") and self.config.num_denoising > 0:
947
+ init.xavier_uniform_(module.denoising_class_embed.weight)
948
+
949
+
950
+ class DFineHybridEncoder(DFinePreTrainedModel):
951
+ """
952
+ Hybrid encoder consisting of AIFI (Attention-based Intra-scale Feature Interaction) layers,
953
+ a top-down Feature Pyramid Network (FPN) and a bottom-up Path Aggregation Network (PAN).
954
+ More details on the paper: https://huggingface.co/papers/2304.08069
955
+
956
+ Args:
957
+ config: DFineConfig
958
+ """
959
+
960
+ _can_record_outputs = {
961
+ "hidden_states": DFineAIFILayer,
962
+ "attentions": DFineSelfAttention,
963
+ }
964
+
965
+ def __init__(self, config: DFineConfig):
966
+ super().__init__(config)
967
+ self.config = config
968
+ self.in_channels = config.encoder_in_channels
969
+ self.num_fpn_stages = len(self.in_channels) - 1
970
+ self.feat_strides = config.feat_strides
971
+ self.encoder_hidden_dim = config.encoder_hidden_dim
972
+ self.encode_proj_layers = config.encode_proj_layers
973
+ self.positional_encoding_temperature = config.positional_encoding_temperature
974
+ self.eval_size = config.eval_size
975
+ self.out_channels = [self.encoder_hidden_dim for _ in self.in_channels]
976
+ self.out_strides = self.feat_strides
977
+
978
+ # AIFI (Attention-based Intra-scale Feature Interaction) layers
979
+ self.aifi = nn.ModuleList([DFineAIFILayer(config) for _ in range(len(self.encode_proj_layers))])
980
+
981
+ # top-down fpn
982
+ self.lateral_convs = nn.ModuleList()
983
+ self.fpn_blocks = nn.ModuleList()
984
+ for _ in range(len(self.in_channels) - 1, 0, -1):
985
+ lateral_layer = DFineConvNormLayer(config, self.encoder_hidden_dim, self.encoder_hidden_dim, 1, 1)
986
+ self.lateral_convs.append(lateral_layer)
987
+ num_blocks = round(3 * config.depth_mult)
988
+ fpn_layer = DFineRepNCSPELAN4(config, numb_blocks=num_blocks)
989
+ self.fpn_blocks.append(fpn_layer)
990
+
991
+ # bottom-up pan
992
+ self.downsample_convs = nn.ModuleList()
993
+ self.pan_blocks = nn.ModuleList()
994
+ for _ in range(len(self.in_channels) - 1):
995
+ self.downsample_convs.append(DFineSCDown(config, 3, 2))
996
+ num_blocks = round(3 * config.depth_mult)
997
+ self.pan_blocks.append(DFineRepNCSPELAN4(config, numb_blocks=num_blocks))
998
+
999
+ self.post_init()
1000
+
1001
+ @merge_with_config_defaults
1002
+ @capture_outputs(tie_last_hidden_states=False)
1003
+ def forward(
1004
+ self,
1005
+ inputs_embeds=None,
1006
+ **kwargs: Unpack[TransformersKwargs],
1007
+ ) -> BaseModelOutput:
1008
+ r"""
1009
+ Args:
1010
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
1011
+ Flattened feature map (output of the backbone + projection layer) that is passed to the encoder.
1012
+ """
1013
+ feature_maps = inputs_embeds
1014
+
1015
+ # AIFI: Apply transformer encoder to specified feature levels
1016
+ if self.config.encoder_layers > 0:
1017
+ for i, enc_ind in enumerate(self.encode_proj_layers):
1018
+ feature_maps[enc_ind] = self.aifi[i](feature_maps[enc_ind], **kwargs)
1019
+
1020
+ # top-down FPN
1021
+ fpn_feature_maps = [feature_maps[-1]]
1022
+ for idx, (lateral_conv, fpn_block) in enumerate(zip(self.lateral_convs, self.fpn_blocks)):
1023
+ backbone_feature_map = feature_maps[self.num_fpn_stages - idx - 1]
1024
+ top_fpn_feature_map = fpn_feature_maps[-1]
1025
+ # apply lateral block
1026
+ top_fpn_feature_map = lateral_conv(top_fpn_feature_map)
1027
+ fpn_feature_maps[-1] = top_fpn_feature_map
1028
+ # apply fpn block
1029
+ top_fpn_feature_map = F.interpolate(top_fpn_feature_map, scale_factor=2.0, mode="nearest")
1030
+ fused_feature_map = torch.concat([top_fpn_feature_map, backbone_feature_map], dim=1)
1031
+ new_fpn_feature_map = fpn_block(fused_feature_map)
1032
+ fpn_feature_maps.append(new_fpn_feature_map)
1033
+
1034
+ fpn_feature_maps.reverse()
1035
+
1036
+ # bottom-up PAN
1037
+ pan_feature_maps = [fpn_feature_maps[0]]
1038
+ for idx, (downsample_conv, pan_block) in enumerate(zip(self.downsample_convs, self.pan_blocks)):
1039
+ top_pan_feature_map = pan_feature_maps[-1]
1040
+ fpn_feature_map = fpn_feature_maps[idx + 1]
1041
+ downsampled_feature_map = downsample_conv(top_pan_feature_map)
1042
+ fused_feature_map = torch.concat([downsampled_feature_map, fpn_feature_map], dim=1)
1043
+ new_pan_feature_map = pan_block(fused_feature_map)
1044
+ pan_feature_maps.append(new_pan_feature_map)
1045
+
1046
+ return BaseModelOutput(last_hidden_state=pan_feature_maps)
1047
+
1048
+
1049
+ def inverse_sigmoid(x, eps=1e-5):
1050
+ x = x.clamp(min=0, max=1)
1051
+ x1 = x.clamp(min=eps)
1052
+ x2 = (1 - x).clamp(min=eps)
1053
+ return torch.log(x1 / x2)
1054
+
1055
+
1056
+ def weighting_function(max_num_bins: int, up: torch.Tensor, reg_scale: int) -> torch.Tensor:
1057
+ """
1058
+ Generates the non-uniform Weighting Function W(n) for bounding box regression.
1059
+
1060
+ Args:
1061
+ max_num_bins (int): Max number of the discrete bins.
1062
+ up (Tensor): Controls upper bounds of the sequence,
1063
+ where maximum offset is ±up * H / W.
1064
+ reg_scale (float): Controls the curvature of the Weighting Function.
1065
+ Larger values result in flatter weights near the central axis W(max_num_bins/2)=0
1066
+ and steeper weights at both ends.
1067
+ Returns:
1068
+ Tensor: Sequence of Weighting Function.
1069
+ """
1070
+ upper_bound1 = abs(up[0]) * abs(reg_scale)
1071
+ upper_bound2 = abs(up[0]) * abs(reg_scale) * 2
1072
+ step = (upper_bound1 + 1) ** (2 / (max_num_bins - 2))
1073
+ left_values = [-((step) ** i) + 1 for i in range(max_num_bins // 2 - 1, 0, -1)]
1074
+ right_values = [(step) ** i - 1 for i in range(1, max_num_bins // 2)]
1075
+ values = [-upper_bound2] + left_values + [torch.zeros_like(up[0][None])] + right_values + [upper_bound2]
1076
+ values = torch.cat(values, 0)
1077
+ return values
1078
+
1079
+
1080
+ def distance2bbox(points, distance: torch.Tensor, reg_scale: float) -> torch.Tensor:
1081
+ """
1082
+ Decodes edge-distances into bounding box coordinates.
1083
+
1084
+ Args:
1085
+ points (`torch.Tensor`):
1086
+ (batch_size, num_boxes, 4) or (num_boxes, 4) format, representing [x_center, y_center, width, height]
1087
+ distance (`torch.Tensor`):
1088
+ (batch_size, num_boxes, 4) or (num_boxes, 4), representing distances from the point to the left, top, right, and bottom boundaries.
1089
+ reg_scale (`float`):
1090
+ Controls the curvature of the Weighting Function.
1091
+ Returns:
1092
+ `torch.Tensor`: Bounding boxes in (batch_size, num_boxes, 4) or (num_boxes, 4) format, representing [x_center, y_center, width, height]
1093
+ """
1094
+ reg_scale = abs(reg_scale)
1095
+ top_left_x = points[..., 0] - (0.5 * reg_scale + distance[..., 0]) * (points[..., 2] / reg_scale)
1096
+ top_left_y = points[..., 1] - (0.5 * reg_scale + distance[..., 1]) * (points[..., 3] / reg_scale)
1097
+ bottom_right_x = points[..., 0] + (0.5 * reg_scale + distance[..., 2]) * (points[..., 2] / reg_scale)
1098
+ bottom_right_y = points[..., 1] + (0.5 * reg_scale + distance[..., 3]) * (points[..., 3] / reg_scale)
1099
+
1100
+ bboxes = torch.stack([top_left_x, top_left_y, bottom_right_x, bottom_right_y], -1)
1101
+
1102
+ return corners_to_center_format(bboxes)
1103
+
1104
+
1105
+ class DFineDecoder(DFinePreTrainedModel):
1106
+ """
1107
+ D-FINE Decoder implementing Fine-grained Distribution Refinement (FDR).
1108
+
1109
+ This decoder refines object detection predictions through iterative updates across multiple layers,
1110
+ utilizing attention mechanisms, location quality estimators, and distribution refinement techniques
1111
+ to improve bounding box accuracy and robustness.
1112
+ """
1113
+
1114
+ _can_record_outputs = {
1115
+ "hidden_states": DFineDecoderLayer,
1116
+ "attentions": DFineSelfAttention,
1117
+ "cross_attentions": DFineMultiscaleDeformableAttention,
1118
+ }
1119
+
1120
+ def __init__(self, config: DFineConfig):
1121
+ super().__init__(config)
1122
+ self.eval_idx = config.eval_idx if config.eval_idx >= 0 else config.decoder_layers + config.eval_idx
1123
+
1124
+ self.dropout = config.dropout
1125
+ self.layers = nn.ModuleList(
1126
+ [DFineDecoderLayer(config) for _ in range(config.decoder_layers)]
1127
+ + [DFineDecoderLayer(config) for _ in range(config.decoder_layers - self.eval_idx - 1)]
1128
+ )
1129
+ self.query_pos_head = DFineMLPPredictionHead(4, 2 * config.d_model, config.d_model, num_layers=2)
1130
+
1131
+ # hack implementation for iterative bounding box refinement and two-stage Deformable DETR
1132
+ self.bbox_embed = None
1133
+ self.class_embed = None
1134
+ self.reg_scale = nn.Parameter(torch.tensor([config.reg_scale]), requires_grad=False)
1135
+ self.max_num_bins = config.max_num_bins
1136
+ self.d_model = config.d_model
1137
+ self.layer_scale = config.layer_scale
1138
+ self.pre_bbox_head = DFineMLP(config.hidden_size, config.hidden_size, 4, 3)
1139
+ self.integral = DFineIntegral(config)
1140
+ self.num_head = config.decoder_attention_heads
1141
+ self.up = nn.Parameter(torch.tensor([config.up]), requires_grad=False)
1142
+ self.lqe_layers = nn.ModuleList([DFineLQE(config) for _ in range(config.decoder_layers)])
1143
+
1144
+ # Initialize weights and apply final processing
1145
+ self.post_init()
1146
+
1147
+ @merge_with_config_defaults
1148
+ @capture_outputs
1149
+ def forward(
1150
+ self,
1151
+ encoder_hidden_states: torch.Tensor,
1152
+ reference_points: torch.Tensor,
1153
+ inputs_embeds: torch.Tensor,
1154
+ spatial_shapes,
1155
+ level_start_index=None,
1156
+ spatial_shapes_list=None,
1157
+ encoder_attention_mask=None,
1158
+ memory_mask=None,
1159
+ **kwargs: Unpack[TransformersKwargs],
1160
+ ) -> DFineDecoderOutput:
1161
+ r"""
1162
+ Args:
1163
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_queries, hidden_size)`):
1164
+ The query embeddings that are passed into the decoder.
1165
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1166
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
1167
+ of the decoder.
1168
+ encoder_attention_mask (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1169
+ Mask to avoid performing cross-attention on padding pixel_values of the encoder. Mask values selected
1170
+ in `[0, 1]`:
1171
+ - 1 for pixels that are real (i.e. **not masked**),
1172
+ - 0 for pixels that are padding (i.e. **masked**).
1173
+ reference_points (`torch.FloatTensor` of shape `(batch_size, num_queries, 4)` is `as_two_stage` else `(batch_size, num_queries, 2)` or , *optional*):
1174
+ Reference point in range `[0, 1]`, top-left (0,0), bottom-right (1, 1), including padding area.
1175
+ spatial_shapes (`torch.FloatTensor` of shape `(num_feature_levels, 2)`):
1176
+ Spatial shapes of the feature maps.
1177
+ level_start_index (`torch.LongTensor` of shape `(num_feature_levels)`, *optional*):
1178
+ Indexes for the start of each feature level. In range `[0, sequence_length]`.
1179
+ """
1180
+ if inputs_embeds is not None:
1181
+ hidden_states = inputs_embeds
1182
+
1183
+ # decoder layers
1184
+ intermediate = ()
1185
+ intermediate_reference_points = ()
1186
+ intermediate_logits = ()
1187
+ intermediate_predicted_corners = ()
1188
+ initial_reference_points = ()
1189
+
1190
+ output_detach = pred_corners_undetach = 0
1191
+
1192
+ project = weighting_function(self.max_num_bins, self.up, self.reg_scale)
1193
+ ref_points_detach = F.sigmoid(reference_points)
1194
+
1195
+ for i, decoder_layer in enumerate(self.layers):
1196
+ ref_points_input = ref_points_detach.unsqueeze(2)
1197
+ query_pos_embed = self.query_pos_head(ref_points_detach).clamp(min=-10, max=10)
1198
+
1199
+ hidden_states = decoder_layer(
1200
+ hidden_states,
1201
+ position_embeddings=query_pos_embed,
1202
+ reference_points=ref_points_input,
1203
+ spatial_shapes=spatial_shapes,
1204
+ spatial_shapes_list=spatial_shapes_list,
1205
+ encoder_hidden_states=encoder_hidden_states,
1206
+ encoder_attention_mask=encoder_attention_mask,
1207
+ **kwargs,
1208
+ )
1209
+
1210
+ if i == 0:
1211
+ # Initial bounding box predictions with inverse sigmoid refinement
1212
+ new_reference_points = F.sigmoid(
1213
+ self.pre_bbox_head(hidden_states) + inverse_sigmoid(ref_points_detach)
1214
+ )
1215
+ ref_points_initial = new_reference_points.detach()
1216
+
1217
+ # Refine bounding box corners using FDR, integrating previous layer's corrections
1218
+ if self.bbox_embed is not None:
1219
+ pred_corners = self.bbox_embed[i](hidden_states + output_detach) + pred_corners_undetach
1220
+ inter_ref_bbox = distance2bbox(
1221
+ ref_points_initial, self.integral(pred_corners, project), self.reg_scale
1222
+ )
1223
+ pred_corners_undetach = pred_corners
1224
+ ref_points_detach = inter_ref_bbox.detach()
1225
+
1226
+ output_detach = hidden_states.detach()
1227
+
1228
+ intermediate += (hidden_states,)
1229
+
1230
+ if self.class_embed is not None and (self.training or i == self.eval_idx):
1231
+ scores = self.class_embed[i](hidden_states)
1232
+ # Add initial logits and reference points with pre-bbox head
1233
+ if i == 0:
1234
+ intermediate_logits += (scores,)
1235
+ intermediate_reference_points += (new_reference_points,)
1236
+ # Lqe does not affect the performance here.
1237
+ scores = self.lqe_layers[i](scores, pred_corners)
1238
+ intermediate_logits += (scores,)
1239
+ intermediate_reference_points += (inter_ref_bbox,)
1240
+ initial_reference_points += (ref_points_initial,)
1241
+ intermediate_predicted_corners += (pred_corners,)
1242
+
1243
+ # Keep batch_size as first dimension
1244
+ intermediate = torch.stack(intermediate)
1245
+ if self.class_embed is not None and self.bbox_embed is not None:
1246
+ intermediate_logits = torch.stack(intermediate_logits, dim=1)
1247
+ intermediate_predicted_corners = torch.stack(intermediate_predicted_corners, dim=1)
1248
+ initial_reference_points = torch.stack(initial_reference_points, dim=1)
1249
+ intermediate_reference_points = torch.stack(intermediate_reference_points, dim=1)
1250
+
1251
+ return DFineDecoderOutput(
1252
+ last_hidden_state=hidden_states,
1253
+ intermediate_hidden_states=intermediate,
1254
+ intermediate_logits=intermediate_logits,
1255
+ intermediate_reference_points=intermediate_reference_points,
1256
+ intermediate_predicted_corners=intermediate_predicted_corners,
1257
+ initial_reference_points=initial_reference_points,
1258
+ )
1259
+
1260
+
1261
+ @dataclass
1262
+ @auto_docstring(
1263
+ custom_intro="""
1264
+ Base class for outputs of the RT-DETR encoder-decoder model.
1265
+ """
1266
+ )
1267
+ class DFineModelOutput(ModelOutput):
1268
+ r"""
1269
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, num_queries, hidden_size)`):
1270
+ Sequence of hidden-states at the output of the last layer of the decoder of the model.
1271
+ intermediate_hidden_states (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, num_queries, hidden_size)`):
1272
+ Stacked intermediate hidden states (output of each layer of the decoder).
1273
+ intermediate_logits (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, sequence_length, config.num_labels)`):
1274
+ Stacked intermediate logits (logits of each layer of the decoder).
1275
+ intermediate_reference_points (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, num_queries, 4)`):
1276
+ Stacked intermediate reference points (reference points of each layer of the decoder).
1277
+ intermediate_predicted_corners (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, num_queries, 4)`):
1278
+ Stacked intermediate predicted corners (predicted corners of each layer of the decoder).
1279
+ initial_reference_points (`torch.FloatTensor` of shape `(batch_size, num_queries, 4)`):
1280
+ Initial reference points used for the first decoder layer.
1281
+ init_reference_points (`torch.FloatTensor` of shape `(batch_size, num_queries, 4)`):
1282
+ Initial reference points sent through the Transformer decoder.
1283
+ enc_topk_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.num_labels)`):
1284
+ Predicted bounding boxes scores where the top `config.two_stage_num_proposals` scoring bounding boxes are
1285
+ picked as region proposals in the encoder stage. Output of bounding box binary classification (i.e.
1286
+ foreground and background).
1287
+ enc_topk_bboxes (`torch.FloatTensor` of shape `(batch_size, sequence_length, 4)`):
1288
+ Logits of predicted bounding boxes coordinates in the encoder stage.
1289
+ enc_outputs_class (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.num_labels)`, *optional*, returned when `config.with_box_refine=True` and `config.two_stage=True`):
1290
+ Predicted bounding boxes scores where the top `config.two_stage_num_proposals` scoring bounding boxes are
1291
+ picked as region proposals in the first stage. Output of bounding box binary classification (i.e.
1292
+ foreground and background).
1293
+ enc_outputs_coord_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, 4)`, *optional*, returned when `config.with_box_refine=True` and `config.two_stage=True`):
1294
+ Logits of predicted bounding boxes coordinates in the first stage.
1295
+ denoising_meta_values (`dict`):
1296
+ Extra dictionary for the denoising related values.
1297
+ """
1298
+
1299
+ last_hidden_state: torch.FloatTensor | None = None
1300
+ intermediate_hidden_states: torch.FloatTensor | None = None
1301
+ intermediate_logits: torch.FloatTensor | None = None
1302
+ intermediate_reference_points: torch.FloatTensor | None = None
1303
+ intermediate_predicted_corners: torch.FloatTensor | None = None
1304
+ initial_reference_points: torch.FloatTensor | None = None
1305
+ decoder_hidden_states: tuple[torch.FloatTensor] | None = None
1306
+ decoder_attentions: tuple[torch.FloatTensor] | None = None
1307
+ cross_attentions: tuple[torch.FloatTensor] | None = None
1308
+ encoder_last_hidden_state: torch.FloatTensor | None = None
1309
+ encoder_hidden_states: tuple[torch.FloatTensor] | None = None
1310
+ encoder_attentions: tuple[torch.FloatTensor] | None = None
1311
+ init_reference_points: torch.FloatTensor | None = None
1312
+ enc_topk_logits: torch.FloatTensor | None = None
1313
+ enc_topk_bboxes: torch.FloatTensor | None = None
1314
+ enc_outputs_class: torch.FloatTensor | None = None
1315
+ enc_outputs_coord_logits: torch.FloatTensor | None = None
1316
+ denoising_meta_values: dict | None = None
1317
+
1318
+
1319
+ def replace_batch_norm(model):
1320
+ r"""
1321
+ Recursively replace all `torch.nn.BatchNorm2d` with `DFineFrozenBatchNorm2d`.
1322
+
1323
+ Args:
1324
+ model (torch.nn.Module):
1325
+ input model
1326
+ """
1327
+ for name, module in model.named_children():
1328
+ if isinstance(module, nn.BatchNorm2d):
1329
+ new_module = DFineFrozenBatchNorm2d(module.num_features)
1330
+
1331
+ if module.weight.device != torch.device("meta"):
1332
+ new_module.weight.copy_(module.weight)
1333
+ new_module.bias.copy_(module.bias)
1334
+ new_module.running_mean.copy_(module.running_mean)
1335
+ new_module.running_var.copy_(module.running_var)
1336
+
1337
+ model._modules[name] = new_module
1338
+
1339
+ if len(list(module.children())) > 0:
1340
+ replace_batch_norm(module)
1341
+
1342
+
1343
+ class DFineConvEncoder(nn.Module):
1344
+ """
1345
+ Convolutional backbone using the modeling_d_fine_resnet.py.
1346
+
1347
+ nn.BatchNorm2d layers are replaced by DFineFrozenBatchNorm2d as defined above.
1348
+ https://github.com/lyuwenyu/RT-DETR/blob/main/DFine_pytorch/src/nn/backbone/presnet.py#L142
1349
+ """
1350
+
1351
+ def __init__(self, config):
1352
+ super().__init__()
1353
+
1354
+ backbone = load_backbone(config)
1355
+
1356
+ if config.freeze_backbone_batch_norms:
1357
+ # replace batch norm by frozen batch norm
1358
+ with torch.no_grad():
1359
+ replace_batch_norm(backbone)
1360
+ self.model = backbone
1361
+ self.intermediate_channel_sizes = self.model.channels
1362
+
1363
+ def forward(self, pixel_values: torch.Tensor, pixel_mask: torch.Tensor):
1364
+ # send pixel_values through the model to get list of feature maps
1365
+ features = self.model(pixel_values).feature_maps
1366
+
1367
+ out = []
1368
+ for feature_map in features:
1369
+ # downsample pixel_mask to match shape of corresponding feature_map
1370
+ mask = nn.functional.interpolate(pixel_mask[None].float(), size=feature_map.shape[-2:]).to(torch.bool)[0]
1371
+ out.append((feature_map, mask))
1372
+ return out
1373
+
1374
+
1375
+ def get_contrastive_denoising_training_group(
1376
+ targets,
1377
+ num_classes,
1378
+ num_queries,
1379
+ class_embed,
1380
+ num_denoising_queries=100,
1381
+ label_noise_ratio=0.5,
1382
+ box_noise_scale=1.0,
1383
+ ):
1384
+ """
1385
+ Creates a contrastive denoising training group using ground-truth samples. It adds noise to labels and boxes.
1386
+
1387
+ Args:
1388
+ targets (`list[dict]`):
1389
+ The target objects, each containing 'class_labels' and 'boxes' for objects in an image.
1390
+ num_classes (`int`):
1391
+ Total number of classes in the dataset.
1392
+ num_queries (`int`):
1393
+ Number of query slots in the transformer.
1394
+ class_embed (`callable`):
1395
+ A function or a model layer to embed class labels.
1396
+ num_denoising_queries (`int`, *optional*, defaults to 100):
1397
+ Number of denoising queries.
1398
+ label_noise_ratio (`float`, *optional*, defaults to 0.5):
1399
+ Ratio of noise applied to labels.
1400
+ box_noise_scale (`float`, *optional*, defaults to 1.0):
1401
+ Scale of noise applied to bounding boxes.
1402
+ Returns:
1403
+ `tuple` comprising various elements:
1404
+ - **input_query_class** (`torch.FloatTensor`) --
1405
+ Class queries with applied label noise.
1406
+ - **input_query_bbox** (`torch.FloatTensor`) --
1407
+ Bounding box queries with applied box noise.
1408
+ - **attn_mask** (`torch.FloatTensor`) --
1409
+ Attention mask for separating denoising and reconstruction queries.
1410
+ - **denoising_meta_values** (`dict`) --
1411
+ Metadata including denoising positive indices, number of groups, and split sizes.
1412
+ """
1413
+
1414
+ if num_denoising_queries <= 0:
1415
+ return None, None, None, None
1416
+
1417
+ num_ground_truths = [len(t["class_labels"]) for t in targets]
1418
+ device = targets[0]["class_labels"].device
1419
+
1420
+ max_gt_num = max(num_ground_truths)
1421
+ if max_gt_num == 0:
1422
+ return None, None, None, None
1423
+
1424
+ num_groups_denoising_queries = num_denoising_queries // max_gt_num
1425
+ num_groups_denoising_queries = 1 if num_groups_denoising_queries == 0 else num_groups_denoising_queries
1426
+ # pad gt to max_num of a batch
1427
+ batch_size = len(num_ground_truths)
1428
+
1429
+ input_query_class = torch.full([batch_size, max_gt_num], num_classes, dtype=torch.int32, device=device)
1430
+ input_query_bbox = torch.zeros([batch_size, max_gt_num, 4], device=device)
1431
+ pad_gt_mask = torch.zeros([batch_size, max_gt_num], dtype=torch.bool, device=device)
1432
+
1433
+ for i in range(batch_size):
1434
+ num_gt = num_ground_truths[i]
1435
+ if num_gt > 0:
1436
+ input_query_class[i, :num_gt] = targets[i]["class_labels"]
1437
+ input_query_bbox[i, :num_gt] = targets[i]["boxes"]
1438
+ pad_gt_mask[i, :num_gt] = 1
1439
+ # each group has positive and negative queries.
1440
+ input_query_class = input_query_class.tile([1, 2 * num_groups_denoising_queries])
1441
+ input_query_bbox = input_query_bbox.tile([1, 2 * num_groups_denoising_queries, 1])
1442
+ pad_gt_mask = pad_gt_mask.tile([1, 2 * num_groups_denoising_queries])
1443
+ # positive and negative mask
1444
+ negative_gt_mask = torch.zeros([batch_size, max_gt_num * 2, 1], device=device)
1445
+ negative_gt_mask[:, max_gt_num:] = 1
1446
+ negative_gt_mask = negative_gt_mask.tile([1, num_groups_denoising_queries, 1])
1447
+ positive_gt_mask = 1 - negative_gt_mask
1448
+ # contrastive denoising training positive index
1449
+ positive_gt_mask = positive_gt_mask.squeeze(-1) * pad_gt_mask
1450
+ denoise_positive_idx = torch.nonzero(positive_gt_mask)[:, 1]
1451
+ denoise_positive_idx = torch.split(
1452
+ denoise_positive_idx, [n * num_groups_denoising_queries for n in num_ground_truths]
1453
+ )
1454
+ # total denoising queries
1455
+ num_denoising_queries = torch_int(max_gt_num * 2 * num_groups_denoising_queries)
1456
+
1457
+ if label_noise_ratio > 0:
1458
+ mask = torch.rand_like(input_query_class, dtype=torch.float) < (label_noise_ratio * 0.5)
1459
+ # randomly put a new one here
1460
+ new_label = torch.randint_like(mask, 0, num_classes, dtype=input_query_class.dtype)
1461
+ input_query_class = torch.where(mask & pad_gt_mask, new_label, input_query_class)
1462
+
1463
+ if box_noise_scale > 0:
1464
+ known_bbox = center_to_corners_format(input_query_bbox)
1465
+ diff = torch.tile(input_query_bbox[..., 2:] * 0.5, [1, 1, 2]) * box_noise_scale
1466
+ rand_sign = torch.randint_like(input_query_bbox, 0, 2) * 2.0 - 1.0
1467
+ rand_part = torch.rand_like(input_query_bbox)
1468
+ rand_part = (rand_part + 1.0) * negative_gt_mask + rand_part * (1 - negative_gt_mask)
1469
+ rand_part *= rand_sign
1470
+ known_bbox += rand_part * diff
1471
+ known_bbox.clip_(min=0.0, max=1.0)
1472
+ input_query_bbox = corners_to_center_format(known_bbox)
1473
+ input_query_bbox = inverse_sigmoid(input_query_bbox)
1474
+
1475
+ input_query_class = class_embed(input_query_class)
1476
+
1477
+ target_size = num_denoising_queries + num_queries
1478
+ attn_mask = torch.full([target_size, target_size], 0, dtype=torch.float, device=device)
1479
+ # match query cannot see the reconstruction
1480
+ attn_mask[num_denoising_queries:, :num_denoising_queries] = -torch.inf
1481
+
1482
+ # reconstructions cannot see each other
1483
+ for i in range(num_groups_denoising_queries):
1484
+ idx_block_start = max_gt_num * 2 * i
1485
+ idx_block_end = max_gt_num * 2 * (i + 1)
1486
+ attn_mask[idx_block_start:idx_block_end, :idx_block_start] = -torch.inf
1487
+ attn_mask[idx_block_start:idx_block_end, idx_block_end:num_denoising_queries] = -torch.inf
1488
+
1489
+ denoising_meta_values = {
1490
+ "dn_positive_idx": denoise_positive_idx,
1491
+ "dn_num_group": num_groups_denoising_queries,
1492
+ "dn_num_split": [num_denoising_queries, num_queries],
1493
+ }
1494
+
1495
+ return input_query_class, input_query_bbox, attn_mask, denoising_meta_values
1496
+
1497
+
1498
+ @auto_docstring(
1499
+ custom_intro="""
1500
+ RT-DETR Model (consisting of a backbone and encoder-decoder) outputting raw hidden states without any head on top.
1501
+ """
1502
+ )
1503
+ class DFineModel(DFinePreTrainedModel):
1504
+ def __init__(self, config: DFineConfig):
1505
+ super().__init__(config)
1506
+
1507
+ # Create backbone
1508
+ self.backbone = DFineConvEncoder(config)
1509
+ intermediate_channel_sizes = self.backbone.intermediate_channel_sizes
1510
+ num_backbone_outs = len(config.decoder_in_channels)
1511
+ encoder_input_proj_list = []
1512
+ for i in range(num_backbone_outs):
1513
+ in_channels = intermediate_channel_sizes[i]
1514
+ encoder_input_proj_list.append(
1515
+ nn.Sequential(
1516
+ nn.Conv2d(in_channels, config.encoder_hidden_dim, kernel_size=1, bias=False),
1517
+ nn.BatchNorm2d(config.encoder_hidden_dim),
1518
+ )
1519
+ )
1520
+ self.encoder_input_proj = nn.ModuleList(encoder_input_proj_list)
1521
+ self.encoder = DFineHybridEncoder(config=config)
1522
+
1523
+ # denoising part
1524
+ if config.num_denoising > 0:
1525
+ self.denoising_class_embed = nn.Embedding(
1526
+ config.num_labels + 1, config.d_model, padding_idx=config.num_labels
1527
+ )
1528
+
1529
+ # decoder embedding
1530
+ if config.learn_initial_query:
1531
+ self.weight_embedding = nn.Embedding(config.num_queries, config.d_model)
1532
+
1533
+ # encoder head
1534
+ self.enc_output = nn.Sequential(
1535
+ nn.Linear(config.d_model, config.d_model),
1536
+ nn.LayerNorm(config.d_model, eps=config.layer_norm_eps),
1537
+ )
1538
+ self.enc_score_head = nn.Linear(config.d_model, config.num_labels)
1539
+ self.enc_bbox_head = DFineMLPPredictionHead(config.d_model, config.d_model, 4, num_layers=3)
1540
+
1541
+ # init encoder output anchors and valid_mask
1542
+ if config.anchor_image_size:
1543
+ self.anchors, self.valid_mask = self.generate_anchors(dtype=self.dtype)
1544
+ num_backbone_outs = len(config.decoder_in_channels)
1545
+ decoder_input_proj_list = []
1546
+ for i in range(num_backbone_outs):
1547
+ in_channels = config.decoder_in_channels[i]
1548
+ decoder_input_proj_list.append(
1549
+ nn.Sequential(
1550
+ nn.Conv2d(in_channels, config.d_model, kernel_size=1, bias=False),
1551
+ nn.BatchNorm2d(config.d_model, config.batch_norm_eps),
1552
+ )
1553
+ )
1554
+ for _ in range(config.num_feature_levels - num_backbone_outs):
1555
+ decoder_input_proj_list.append(
1556
+ nn.Sequential(
1557
+ nn.Conv2d(in_channels, config.d_model, kernel_size=3, stride=2, padding=1, bias=False),
1558
+ nn.BatchNorm2d(config.d_model, config.batch_norm_eps),
1559
+ )
1560
+ )
1561
+ in_channels = config.d_model
1562
+ self.decoder = DFineDecoder(config)
1563
+ decoder_input_proj = []
1564
+ in_channels = config.decoder_in_channels[-1]
1565
+ for _ in range(num_backbone_outs):
1566
+ if config.hidden_size == config.decoder_in_channels[-1]:
1567
+ decoder_input_proj.append(nn.Identity())
1568
+ else:
1569
+ conv = nn.Conv2d(in_channels, config.d_model, kernel_size=1, bias=False)
1570
+ batchnorm = nn.BatchNorm2d(config.d_model, config.batch_norm_eps)
1571
+ decoder_input_proj.append(nn.Sequential(conv, batchnorm))
1572
+ for _ in range(config.num_feature_levels - num_backbone_outs):
1573
+ if config.hidden_size == config.decoder_in_channels[-1]:
1574
+ decoder_input_proj.append(nn.Identity())
1575
+ else:
1576
+ conv = nn.Conv2d(in_channels, config.d_model, kernel_size=3, stride=2, padding=1, bias=False)
1577
+ batchnorm = nn.BatchNorm2d(config.d_model, config.batch_norm_eps)
1578
+ decoder_input_proj.append(nn.Sequential(conv, batchnorm))
1579
+ self.decoder_input_proj = nn.ModuleList(decoder_input_proj)
1580
+
1581
+ self.post_init()
1582
+
1583
+ def freeze_backbone(self):
1584
+ for param in self.backbone.parameters():
1585
+ param.requires_grad_(False)
1586
+
1587
+ def unfreeze_backbone(self):
1588
+ for param in self.backbone.parameters():
1589
+ param.requires_grad_(True)
1590
+
1591
+ @compile_compatible_method_lru_cache(maxsize=32)
1592
+ def generate_anchors(self, spatial_shapes=None, grid_size=0.05, device="cpu", dtype=torch.float32):
1593
+ if spatial_shapes is None:
1594
+ spatial_shapes = [
1595
+ [int(self.config.anchor_image_size[0] / s), int(self.config.anchor_image_size[1] / s)]
1596
+ for s in self.config.feat_strides
1597
+ ]
1598
+ anchors = []
1599
+ for level, (height, width) in enumerate(spatial_shapes):
1600
+ grid_y, grid_x = torch.meshgrid(
1601
+ torch.arange(end=height, device=device).to(dtype),
1602
+ torch.arange(end=width, device=device).to(dtype),
1603
+ indexing="ij",
1604
+ )
1605
+ grid_xy = torch.stack([grid_x, grid_y], -1)
1606
+ grid_xy = grid_xy.unsqueeze(0) + 0.5
1607
+ grid_xy[..., 0] /= width
1608
+ grid_xy[..., 1] /= height
1609
+ wh = torch.ones_like(grid_xy) * grid_size * (2.0**level)
1610
+ anchors.append(torch.concat([grid_xy, wh], -1).reshape(-1, height * width, 4))
1611
+ # define the valid range for anchor coordinates
1612
+ eps = 1e-2
1613
+ anchors = torch.concat(anchors, 1)
1614
+ valid_mask = ((anchors > eps) * (anchors < 1 - eps)).all(-1, keepdim=True)
1615
+ anchors = torch.log(anchors / (1 - anchors))
1616
+ anchors = torch.where(valid_mask, anchors, torch.tensor(torch.finfo(dtype).max, dtype=dtype, device=device))
1617
+
1618
+ return anchors, valid_mask
1619
+
1620
+ @auto_docstring
1621
+ @can_return_tuple
1622
+ def forward(
1623
+ self,
1624
+ pixel_values: torch.FloatTensor,
1625
+ pixel_mask: torch.LongTensor | None = None,
1626
+ encoder_outputs: torch.FloatTensor | None = None,
1627
+ inputs_embeds: torch.FloatTensor | None = None,
1628
+ labels: list[dict] | None = None,
1629
+ **kwargs: Unpack[TransformersKwargs],
1630
+ ) -> tuple[torch.FloatTensor] | DFineModelOutput:
1631
+ r"""
1632
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1633
+ Optionally, instead of passing the flattened feature map (output of the backbone + projection layer), you
1634
+ can choose to directly pass a flattened representation of an image.
1635
+ labels (`list[Dict]` of len `(batch_size,)`, *optional*):
1636
+ Labels for computing the bipartite matching loss. List of dicts, each dictionary containing at least the
1637
+ following 2 keys: 'class_labels' and 'boxes' (the class labels and bounding boxes of an image in the batch
1638
+ respectively). The class labels themselves should be a `torch.LongTensor` of len `(number of bounding boxes
1639
+ in the image,)` and the boxes a `torch.FloatTensor` of shape `(number of bounding boxes in the image, 4)`.
1640
+
1641
+ Examples:
1642
+
1643
+ ```python
1644
+ >>> from transformers import AutoImageProcessor, DFineModel
1645
+ >>> from PIL import Image
1646
+ >>> import requests
1647
+
1648
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
1649
+ >>> image = Image.open(requests.get(url, stream=True).raw)
1650
+
1651
+ >>> image_processor = AutoImageProcessor.from_pretrained("PekingU/DFine_r50vd")
1652
+ >>> model = DFineModel.from_pretrained("PekingU/DFine_r50vd")
1653
+
1654
+ >>> inputs = image_processor(images=image, return_tensors="pt")
1655
+
1656
+ >>> outputs = model(**inputs)
1657
+
1658
+ >>> last_hidden_states = outputs.last_hidden_state
1659
+ >>> list(last_hidden_states.shape)
1660
+ [1, 300, 256]
1661
+ ```"""
1662
+ if pixel_values is None and inputs_embeds is None:
1663
+ raise ValueError("You have to specify either pixel_values or inputs_embeds")
1664
+
1665
+ if inputs_embeds is None:
1666
+ batch_size, num_channels, height, width = pixel_values.shape
1667
+ device = pixel_values.device
1668
+ if pixel_mask is None:
1669
+ pixel_mask = torch.ones(((batch_size, height, width)), device=device)
1670
+ features = self.backbone(pixel_values, pixel_mask)
1671
+ proj_feats = [self.encoder_input_proj[level](source) for level, (source, mask) in enumerate(features)]
1672
+ else:
1673
+ batch_size = inputs_embeds.shape[0]
1674
+ device = inputs_embeds.device
1675
+ proj_feats = inputs_embeds
1676
+
1677
+ if encoder_outputs is None:
1678
+ encoder_outputs = self.encoder(
1679
+ proj_feats,
1680
+ **kwargs,
1681
+ )
1682
+ # If the user passed a tuple for encoder_outputs, we wrap it in a BaseModelOutput
1683
+ elif not isinstance(encoder_outputs, BaseModelOutput):
1684
+ encoder_outputs = BaseModelOutput(
1685
+ last_hidden_state=encoder_outputs[0],
1686
+ hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
1687
+ attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
1688
+ )
1689
+
1690
+ # Equivalent to def _get_encoder_input
1691
+ # https://github.com/lyuwenyu/RT-DETR/blob/94f5e16708329d2f2716426868ec89aa774af016/DFine_pytorch/src/zoo/DFine/DFine_decoder.py#L412
1692
+ sources = []
1693
+ for level, source in enumerate(encoder_outputs.last_hidden_state):
1694
+ sources.append(self.decoder_input_proj[level](source))
1695
+
1696
+ # Lowest resolution feature maps are obtained via 3x3 stride 2 convolutions on the final stage
1697
+ if self.config.num_feature_levels > len(sources):
1698
+ _len_sources = len(sources)
1699
+ sources.append(self.decoder_input_proj[_len_sources](encoder_outputs.last_hidden_state)[-1])
1700
+ for i in range(_len_sources + 1, self.config.num_feature_levels):
1701
+ sources.append(self.decoder_input_proj[i](encoder_outputs.last_hidden_state[-1]))
1702
+
1703
+ # Prepare encoder inputs (by flattening)
1704
+ source_flatten = []
1705
+ spatial_shapes_list = []
1706
+ spatial_shapes = torch.empty((len(sources), 2), device=device, dtype=torch.long)
1707
+ for level, source in enumerate(sources):
1708
+ height, width = source.shape[-2:]
1709
+ spatial_shapes[level, 0] = height
1710
+ spatial_shapes[level, 1] = width
1711
+ spatial_shapes_list.append((height, width))
1712
+ source = source.flatten(2).transpose(1, 2)
1713
+ source_flatten.append(source)
1714
+ source_flatten = torch.cat(source_flatten, 1)
1715
+ level_start_index = torch.cat((spatial_shapes.new_zeros((1,)), spatial_shapes.prod(1).cumsum(0)[:-1]))
1716
+
1717
+ # prepare denoising training
1718
+ if self.training and self.config.num_denoising > 0 and labels is not None:
1719
+ (
1720
+ denoising_class,
1721
+ denoising_bbox_unact,
1722
+ attention_mask,
1723
+ denoising_meta_values,
1724
+ ) = get_contrastive_denoising_training_group(
1725
+ targets=labels,
1726
+ num_classes=self.config.num_labels,
1727
+ num_queries=self.config.num_queries,
1728
+ class_embed=self.denoising_class_embed,
1729
+ num_denoising_queries=self.config.num_denoising,
1730
+ label_noise_ratio=self.config.label_noise_ratio,
1731
+ box_noise_scale=self.config.box_noise_scale,
1732
+ )
1733
+ else:
1734
+ denoising_class, denoising_bbox_unact, attention_mask, denoising_meta_values = None, None, None, None
1735
+
1736
+ batch_size = len(source_flatten)
1737
+ device = source_flatten.device
1738
+ dtype = source_flatten.dtype
1739
+
1740
+ # prepare input for decoder
1741
+ if self.training or self.config.anchor_image_size is None:
1742
+ # Pass spatial_shapes as tuple to make it hashable and make sure
1743
+ # lru_cache is working for generate_anchors()
1744
+ spatial_shapes_tuple = tuple(spatial_shapes_list)
1745
+ anchors, valid_mask = self.generate_anchors(spatial_shapes_tuple, device=device, dtype=dtype)
1746
+ else:
1747
+ anchors, valid_mask = self.anchors, self.valid_mask
1748
+ anchors, valid_mask = anchors.to(device, dtype), valid_mask.to(device, dtype)
1749
+
1750
+ # use the valid_mask to selectively retain values in the feature map where the mask is `True`
1751
+ memory = valid_mask.to(source_flatten.dtype) * source_flatten
1752
+
1753
+ output_memory = self.enc_output(memory)
1754
+
1755
+ enc_outputs_class = self.enc_score_head(output_memory)
1756
+ enc_outputs_coord_logits = self.enc_bbox_head(output_memory) + anchors
1757
+
1758
+ _, topk_ind = torch.topk(enc_outputs_class.max(-1).values, self.config.num_queries, dim=1)
1759
+
1760
+ reference_points_unact = enc_outputs_coord_logits.gather(
1761
+ dim=1, index=topk_ind.unsqueeze(-1).repeat(1, 1, enc_outputs_coord_logits.shape[-1])
1762
+ )
1763
+
1764
+ enc_topk_bboxes = F.sigmoid(reference_points_unact)
1765
+ if denoising_bbox_unact is not None:
1766
+ reference_points_unact = torch.concat([denoising_bbox_unact, reference_points_unact], 1)
1767
+
1768
+ enc_topk_logits = enc_outputs_class.gather(
1769
+ dim=1, index=topk_ind.unsqueeze(-1).repeat(1, 1, enc_outputs_class.shape[-1])
1770
+ )
1771
+
1772
+ # extract region features
1773
+ if self.config.learn_initial_query:
1774
+ target = self.weight_embedding.tile([batch_size, 1, 1])
1775
+ else:
1776
+ target = output_memory.gather(dim=1, index=topk_ind.unsqueeze(-1).repeat(1, 1, output_memory.shape[-1]))
1777
+ target = target.detach()
1778
+
1779
+ if denoising_class is not None:
1780
+ target = torch.concat([denoising_class, target], 1)
1781
+
1782
+ init_reference_points = reference_points_unact.detach()
1783
+
1784
+ # decoder
1785
+ decoder_outputs = self.decoder(
1786
+ inputs_embeds=target,
1787
+ encoder_hidden_states=source_flatten,
1788
+ encoder_attention_mask=attention_mask,
1789
+ reference_points=init_reference_points,
1790
+ spatial_shapes=spatial_shapes,
1791
+ spatial_shapes_list=spatial_shapes_list,
1792
+ level_start_index=level_start_index,
1793
+ **kwargs,
1794
+ )
1795
+
1796
+ return DFineModelOutput(
1797
+ last_hidden_state=decoder_outputs.last_hidden_state,
1798
+ intermediate_hidden_states=decoder_outputs.intermediate_hidden_states,
1799
+ intermediate_logits=decoder_outputs.intermediate_logits,
1800
+ intermediate_reference_points=decoder_outputs.intermediate_reference_points,
1801
+ intermediate_predicted_corners=decoder_outputs.intermediate_predicted_corners,
1802
+ initial_reference_points=decoder_outputs.initial_reference_points,
1803
+ decoder_hidden_states=decoder_outputs.hidden_states,
1804
+ decoder_attentions=decoder_outputs.attentions,
1805
+ cross_attentions=decoder_outputs.cross_attentions,
1806
+ encoder_last_hidden_state=encoder_outputs.last_hidden_state,
1807
+ encoder_hidden_states=encoder_outputs.hidden_states,
1808
+ encoder_attentions=encoder_outputs.attentions,
1809
+ init_reference_points=init_reference_points,
1810
+ enc_topk_logits=enc_topk_logits,
1811
+ enc_topk_bboxes=enc_topk_bboxes,
1812
+ enc_outputs_class=enc_outputs_class,
1813
+ enc_outputs_coord_logits=enc_outputs_coord_logits,
1814
+ denoising_meta_values=denoising_meta_values,
1815
+ )
1816
+
1817
+
1818
+ @dataclass
1819
+ @auto_docstring(
1820
+ custom_intro="""
1821
+ Output type of [`DFineForObjectDetection`].
1822
+ """
1823
+ )
1824
+ class DFineObjectDetectionOutput(ModelOutput):
1825
+ r"""
1826
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` are provided)):
1827
+ Total loss as a linear combination of a negative log-likehood (cross-entropy) for class prediction and a
1828
+ bounding box loss. The latter is defined as a linear combination of the L1 loss and the generalized
1829
+ scale-invariant IoU loss.
1830
+ loss_dict (`Dict`, *optional*):
1831
+ A dictionary containing the individual losses. Useful for logging.
1832
+ logits (`torch.FloatTensor` of shape `(batch_size, num_queries, num_classes + 1)`):
1833
+ Classification logits (including no-object) for all queries.
1834
+ pred_boxes (`torch.FloatTensor` of shape `(batch_size, num_queries, 4)`):
1835
+ Normalized boxes coordinates for all queries, represented as (center_x, center_y, width, height). These
1836
+ values are normalized in [0, 1], relative to the size of each individual image in the batch (disregarding
1837
+ possible padding). You can use [`~DFineImageProcessor.post_process_object_detection`] to retrieve the
1838
+ unnormalized (absolute) bounding boxes.
1839
+ auxiliary_outputs (`list[Dict]`, *optional*):
1840
+ Optional, only returned when auxiliary losses are activated (i.e. `config.auxiliary_loss` is set to `True`)
1841
+ and labels are provided. It is a list of dictionaries containing the two above keys (`logits` and
1842
+ `pred_boxes`) for each decoder layer.
1843
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, num_queries, hidden_size)`):
1844
+ Sequence of hidden-states at the output of the last layer of the decoder of the model.
1845
+ intermediate_hidden_states (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, num_queries, hidden_size)`):
1846
+ Stacked intermediate hidden states (output of each layer of the decoder).
1847
+ intermediate_logits (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, num_queries, config.num_labels)`):
1848
+ Stacked intermediate logits (logits of each layer of the decoder).
1849
+ intermediate_reference_points (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, num_queries, 4)`):
1850
+ Stacked intermediate reference points (reference points of each layer of the decoder).
1851
+ intermediate_predicted_corners (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, num_queries, 4)`):
1852
+ Stacked intermediate predicted corners (predicted corners of each layer of the decoder).
1853
+ initial_reference_points (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, num_queries, 4)`):
1854
+ Stacked initial reference points (initial reference points of each layer of the decoder).
1855
+ init_reference_points (`torch.FloatTensor` of shape `(batch_size, num_queries, 4)`):
1856
+ Initial reference points sent through the Transformer decoder.
1857
+ enc_topk_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.num_labels)`, *optional*, returned when `config.with_box_refine=True` and `config.two_stage=True`):
1858
+ Logits of predicted bounding boxes coordinates in the encoder.
1859
+ enc_topk_bboxes (`torch.FloatTensor` of shape `(batch_size, sequence_length, 4)`, *optional*, returned when `config.with_box_refine=True` and `config.two_stage=True`):
1860
+ Logits of predicted bounding boxes coordinates in the encoder.
1861
+ enc_outputs_class (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.num_labels)`, *optional*, returned when `config.with_box_refine=True` and `config.two_stage=True`):
1862
+ Predicted bounding boxes scores where the top `config.two_stage_num_proposals` scoring bounding boxes are
1863
+ picked as region proposals in the first stage. Output of bounding box binary classification (i.e.
1864
+ foreground and background).
1865
+ enc_outputs_coord_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, 4)`, *optional*, returned when `config.with_box_refine=True` and `config.two_stage=True`):
1866
+ Logits of predicted bounding boxes coordinates in the first stage.
1867
+ denoising_meta_values (`dict`):
1868
+ Extra dictionary for the denoising related values
1869
+ """
1870
+
1871
+ loss: torch.FloatTensor | None = None
1872
+ loss_dict: dict | None = None
1873
+ logits: torch.FloatTensor | None = None
1874
+ pred_boxes: torch.FloatTensor | None = None
1875
+ auxiliary_outputs: list[dict] | None = None
1876
+ last_hidden_state: torch.FloatTensor | None = None
1877
+ intermediate_hidden_states: torch.FloatTensor | None = None
1878
+ intermediate_logits: torch.FloatTensor | None = None
1879
+ intermediate_reference_points: torch.FloatTensor | None = None
1880
+ intermediate_predicted_corners: torch.FloatTensor | None = None
1881
+ initial_reference_points: torch.FloatTensor | None = None
1882
+ decoder_hidden_states: tuple[torch.FloatTensor] | None = None
1883
+ decoder_attentions: tuple[torch.FloatTensor] | None = None
1884
+ cross_attentions: tuple[torch.FloatTensor] | None = None
1885
+ encoder_last_hidden_state: torch.FloatTensor | None = None
1886
+ encoder_hidden_states: tuple[torch.FloatTensor] | None = None
1887
+ encoder_attentions: tuple[torch.FloatTensor] | None = None
1888
+ init_reference_points: tuple[torch.FloatTensor] | None = None
1889
+ enc_topk_logits: torch.FloatTensor | None = None
1890
+ enc_topk_bboxes: torch.FloatTensor | None = None
1891
+ enc_outputs_class: torch.FloatTensor | None = None
1892
+ enc_outputs_coord_logits: torch.FloatTensor | None = None
1893
+ denoising_meta_values: dict | None = None
1894
+
1895
+
1896
+ @auto_docstring(
1897
+ custom_intro="""
1898
+ RT-DETR Model (consisting of a backbone and encoder-decoder) outputting bounding boxes and logits to be further
1899
+ decoded into scores and classes.
1900
+ """
1901
+ )
1902
+ class DFineForObjectDetection(DFinePreTrainedModel):
1903
+ # When using clones, all layers > 0 will be clones, but layer 0 *is* required
1904
+ # We can't initialize the model on meta device as some weights are modified during the initialization
1905
+ _no_split_modules = None
1906
+ _tied_weights_keys = {
1907
+ r"bbox_embed.(?![0])\d+": r"bbox_embed.0",
1908
+ r"class_embed.(?![0])\d+": r"^class_embed.0",
1909
+ "class_embed": "model.decoder.class_embed",
1910
+ "bbox_embed": "model.decoder.bbox_embed",
1911
+ }
1912
+
1913
+ def __init__(self, config: DFineConfig):
1914
+ super().__init__(config)
1915
+
1916
+ # D-FINE encoder-decoder model
1917
+ self.eval_idx = config.eval_idx if config.eval_idx >= 0 else config.decoder_layers + config.eval_idx
1918
+ self.model = DFineModel(config)
1919
+ scaled_dim = round(config.layer_scale * config.hidden_size)
1920
+ num_pred = config.decoder_layers
1921
+ self.class_embed = nn.ModuleList([nn.Linear(config.d_model, config.num_labels) for _ in range(num_pred)])
1922
+ self.bbox_embed = nn.ModuleList(
1923
+ [
1924
+ DFineMLP(config.hidden_size, config.hidden_size, 4 * (config.max_num_bins + 1), 3)
1925
+ for _ in range(self.eval_idx + 1)
1926
+ ]
1927
+ + [
1928
+ DFineMLP(scaled_dim, scaled_dim, 4 * (config.max_num_bins + 1), 3)
1929
+ for _ in range(config.decoder_layers - self.eval_idx - 1)
1930
+ ]
1931
+ )
1932
+
1933
+ self.model.decoder.class_embed = self.class_embed
1934
+ self.model.decoder.bbox_embed = self.bbox_embed
1935
+ # Initialize weights and apply final processing
1936
+ self.post_init()
1937
+
1938
+ def _set_aux_loss(self, outputs_class, outputs_coord):
1939
+ return [{"logits": a, "pred_boxes": b} for a, b in zip(outputs_class, outputs_coord)]
1940
+
1941
+ @auto_docstring
1942
+ @can_return_tuple
1943
+ def forward(
1944
+ self,
1945
+ pixel_values: torch.FloatTensor,
1946
+ pixel_mask: torch.LongTensor | None = None,
1947
+ encoder_outputs: torch.FloatTensor | None = None,
1948
+ inputs_embeds: torch.FloatTensor | None = None,
1949
+ labels: list[dict] | None = None,
1950
+ **kwargs: Unpack[TransformersKwargs],
1951
+ ) -> tuple[torch.FloatTensor] | DFineObjectDetectionOutput:
1952
+ r"""
1953
+ Example:
1954
+
1955
+ ```python
1956
+ >>> import torch
1957
+ >>> from transformers.image_utils import load_image
1958
+ >>> from transformers import AutoImageProcessor, DFineForObjectDetection
1959
+
1960
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
1961
+ >>> image = load_image(url)
1962
+
1963
+ >>> image_processor = AutoImageProcessor.from_pretrained("ustc-community/dfine-xlarge-coco")
1964
+ >>> model = DFineForObjectDetection.from_pretrained("ustc-community/dfine-xlarge-coco")
1965
+
1966
+ >>> # prepare image for the model
1967
+ >>> inputs = image_processor(images=image, return_tensors="pt")
1968
+
1969
+ >>> # forward pass
1970
+ >>> outputs = model(**inputs)
1971
+
1972
+ >>> logits = outputs.logits
1973
+ >>> list(logits.shape)
1974
+ [1, 300, 80]
1975
+
1976
+ >>> boxes = outputs.pred_boxes
1977
+ >>> list(boxes.shape)
1978
+ [1, 300, 4]
1979
+
1980
+ >>> # convert outputs (bounding boxes and class logits) to Pascal VOC format (xmin, ymin, xmax, ymax)
1981
+ >>> target_sizes = torch.tensor([image.size[::-1]])
1982
+ >>> results = image_processor.post_process_object_detection(outputs, threshold=0.9, target_sizes=target_sizes)
1983
+ >>> result = results[0] # first image in batch
1984
+
1985
+ >>> for score, label, box in zip(result["scores"], result["labels"], result["boxes"]):
1986
+ ... box = [round(i, 2) for i in box.tolist()]
1987
+ ... print(
1988
+ ... f"Detected {model.config.id2label[label.item()]} with confidence "
1989
+ ... f"{round(score.item(), 3)} at location {box}"
1990
+ ... )
1991
+ Detected cat with confidence 0.958 at location [344.49, 23.4, 639.84, 374.27]
1992
+ Detected cat with confidence 0.956 at location [11.71, 53.52, 316.64, 472.33]
1993
+ Detected remote with confidence 0.947 at location [40.46, 73.7, 175.62, 117.57]
1994
+ Detected sofa with confidence 0.918 at location [0.59, 1.88, 640.25, 474.74]
1995
+ ```
1996
+ """
1997
+ outputs = self.model(
1998
+ pixel_values,
1999
+ pixel_mask=pixel_mask,
2000
+ encoder_outputs=encoder_outputs,
2001
+ inputs_embeds=inputs_embeds,
2002
+ labels=labels,
2003
+ **kwargs,
2004
+ )
2005
+
2006
+ denoising_meta_values = outputs.denoising_meta_values if self.training else None
2007
+
2008
+ outputs_class = outputs.intermediate_logits
2009
+ outputs_coord = outputs.intermediate_reference_points
2010
+ predicted_corners = outputs.intermediate_predicted_corners
2011
+ initial_reference_points = outputs.initial_reference_points
2012
+
2013
+ logits = outputs_class[:, -1]
2014
+ pred_boxes = outputs_coord[:, -1]
2015
+
2016
+ loss, loss_dict, auxiliary_outputs, enc_topk_logits, enc_topk_bboxes = None, None, None, None, None
2017
+ if labels is not None:
2018
+ enc_topk_logits = outputs.enc_topk_logits
2019
+ enc_topk_bboxes = outputs.enc_topk_bboxes
2020
+ loss, loss_dict, auxiliary_outputs = self.loss_function(
2021
+ logits,
2022
+ labels,
2023
+ self.device,
2024
+ pred_boxes,
2025
+ self.config,
2026
+ outputs_class,
2027
+ outputs_coord,
2028
+ enc_topk_logits=enc_topk_logits,
2029
+ enc_topk_bboxes=enc_topk_bboxes,
2030
+ denoising_meta_values=denoising_meta_values,
2031
+ predicted_corners=predicted_corners,
2032
+ initial_reference_points=initial_reference_points,
2033
+ **kwargs,
2034
+ )
2035
+
2036
+ return DFineObjectDetectionOutput(
2037
+ loss=loss,
2038
+ loss_dict=loss_dict,
2039
+ logits=logits,
2040
+ pred_boxes=pred_boxes,
2041
+ auxiliary_outputs=auxiliary_outputs,
2042
+ last_hidden_state=outputs.last_hidden_state,
2043
+ intermediate_hidden_states=outputs.intermediate_hidden_states,
2044
+ intermediate_logits=outputs.intermediate_logits,
2045
+ intermediate_reference_points=outputs.intermediate_reference_points,
2046
+ intermediate_predicted_corners=outputs.intermediate_predicted_corners,
2047
+ initial_reference_points=outputs.initial_reference_points,
2048
+ decoder_hidden_states=outputs.decoder_hidden_states,
2049
+ decoder_attentions=outputs.decoder_attentions,
2050
+ cross_attentions=outputs.cross_attentions,
2051
+ encoder_last_hidden_state=outputs.encoder_last_hidden_state,
2052
+ encoder_hidden_states=outputs.encoder_hidden_states,
2053
+ encoder_attentions=outputs.encoder_attentions,
2054
+ init_reference_points=outputs.init_reference_points,
2055
+ enc_topk_logits=outputs.enc_topk_logits,
2056
+ enc_topk_bboxes=outputs.enc_topk_bboxes,
2057
+ enc_outputs_class=outputs.enc_outputs_class,
2058
+ enc_outputs_coord_logits=outputs.enc_outputs_coord_logits,
2059
+ denoising_meta_values=outputs.denoising_meta_values,
2060
+ )
2061
+
2062
+
2063
+ __all__ = ["DFineModel", "DFinePreTrainedModel", "DFineForObjectDetection"]
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/d_fine/modular_d_fine.py ADDED
@@ -0,0 +1,1141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 Baidu Inc and 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
+ import math
15
+
16
+ import torch
17
+ import torch.nn as nn
18
+ import torch.nn.functional as F
19
+
20
+ from ... import initialization as init
21
+ from ...activations import ACT2CLS
22
+ from ...backbone_utils import consolidate_backbone_kwargs_to_config
23
+ from ...configuration_utils import PreTrainedConfig
24
+ from ...image_transforms import corners_to_center_format
25
+ from ...processing_utils import Unpack
26
+ from ...utils import TransformersKwargs, logging, torch_compilable_check
27
+ from ..auto import AutoConfig
28
+ from ..rt_detr.modeling_rt_detr import (
29
+ RTDetrAIFILayer,
30
+ RTDetrConvNormLayer,
31
+ RTDetrDecoder,
32
+ RTDetrDecoderLayer,
33
+ RTDetrDecoderOutput,
34
+ RTDetrEncoderLayer,
35
+ RTDetrForObjectDetection,
36
+ RTDetrFrozenBatchNorm2d,
37
+ RTDetrHybridEncoder,
38
+ RTDetrMLPPredictionHead,
39
+ RTDetrModel,
40
+ RTDetrPreTrainedModel,
41
+ RTDetrRepVggBlock,
42
+ inverse_sigmoid,
43
+ )
44
+ from ..rt_detr_v2.modeling_rt_detr_v2 import multi_scale_deformable_attention_v2
45
+
46
+
47
+ logger = logging.get_logger(__name__)
48
+
49
+
50
+ # TODO: Attribute map assignment logic should be fixed in modular
51
+ # as well as super() call parsing because otherwise we cannot re-write args after initialization
52
+ class DFineConfig(PreTrainedConfig):
53
+ """
54
+ This is the configuration class to store the configuration of a [`DFineModel`]. It is used to instantiate a D-FINE
55
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
56
+ defaults will yield a similar configuration to that of D-FINE-X-COCO "[ustc-community/dfine-xlarge-coco"](https://huggingface.co/ustc-community/dfine-xlarge-coco").
57
+ Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the
58
+ documentation from [`PreTrainedConfig`] for more information.
59
+
60
+ Args:
61
+ initializer_range (`float`, *optional*, defaults to 0.01):
62
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
63
+ initializer_bias_prior_prob (`float`, *optional*):
64
+ The prior probability used by the bias initializer to initialize biases for `enc_score_head` and `class_embed`.
65
+ If `None`, `prior_prob` computed as `prior_prob = 1 / (num_labels + 1)` while initializing model weights.
66
+ layer_norm_eps (`float`, *optional*, defaults to 1e-05):
67
+ The epsilon used by the layer normalization layers.
68
+ batch_norm_eps (`float`, *optional*, defaults to 1e-05):
69
+ The epsilon used by the batch normalization layers.
70
+ backbone_config (`Union[dict, "PreTrainedConfig"]`, *optional*, defaults to `HGNetV2Config()`):
71
+ The configuration of the backbone model.
72
+ freeze_backbone_batch_norms (`bool`, *optional*, defaults to `True`):
73
+ Whether to freeze the batch normalization layers in the backbone.
74
+ encoder_hidden_dim (`int`, *optional*, defaults to 256):
75
+ Dimension of the layers in hybrid encoder.
76
+ encoder_in_channels (`list`, *optional*, defaults to `[512, 1024, 2048]`):
77
+ Multi level features input for encoder.
78
+ feat_strides (`list[int]`, *optional*, defaults to `[8, 16, 32]`):
79
+ Strides used in each feature map.
80
+ encoder_layers (`int`, *optional*, defaults to 1):
81
+ Total of layers to be used by the encoder.
82
+ encoder_ffn_dim (`int`, *optional*, defaults to 1024):
83
+ Dimension of the "intermediate" (often named feed-forward) layer in decoder.
84
+ encoder_attention_heads (`int`, *optional*, defaults to 8):
85
+ Number of attention heads for each attention layer in the Transformer encoder.
86
+ dropout (`float`, *optional*, defaults to 0.0):
87
+ The ratio for all dropout layers.
88
+ activation_dropout (`float`, *optional*, defaults to 0.0):
89
+ The dropout ratio for activations inside the fully connected layer.
90
+ encode_proj_layers (`list[int]`, *optional*, defaults to `[2]`):
91
+ Indexes of the projected layers to be used in the encoder.
92
+ positional_encoding_temperature (`int`, *optional*, defaults to 10000):
93
+ The temperature parameter used to create the positional encodings.
94
+ encoder_activation_function (`str`, *optional*, defaults to `"gelu"`):
95
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
96
+ `"relu"`, `"silu"` and `"gelu_new"` are supported.
97
+ activation_function (`str`, *optional*, defaults to `"silu"`):
98
+ The non-linear activation function (function or string) in the general layer. If string, `"gelu"`,
99
+ `"relu"`, `"silu"` and `"gelu_new"` are supported.
100
+ eval_size (`tuple[int, int]`, *optional*):
101
+ Height and width used to computes the effective height and width of the position embeddings after taking
102
+ into account the stride.
103
+ normalize_before (`bool`, *optional*, defaults to `False`):
104
+ Determine whether to apply layer normalization in the transformer encoder layer before self-attention and
105
+ feed-forward modules.
106
+ hidden_expansion (`float`, *optional*, defaults to 1.0):
107
+ Expansion ratio to enlarge the dimension size of RepVGGBlock and CSPRepLayer.
108
+ d_model (`int`, *optional*, defaults to 256):
109
+ Dimension of the layers exclude hybrid encoder.
110
+ num_queries (`int`, *optional*, defaults to 300):
111
+ Number of object queries.
112
+ decoder_in_channels (`list`, *optional*, defaults to `[256, 256, 256]`):
113
+ Multi level features dimension for decoder
114
+ decoder_ffn_dim (`int`, *optional*, defaults to 1024):
115
+ Dimension of the "intermediate" (often named feed-forward) layer in decoder.
116
+ num_feature_levels (`int`, *optional*, defaults to 3):
117
+ The number of input feature levels.
118
+ decoder_n_points (`int`, *optional*, defaults to 4):
119
+ The number of sampled keys in each feature level for each attention head in the decoder.
120
+ decoder_layers (`int`, *optional*, defaults to 6):
121
+ Number of decoder layers.
122
+ decoder_attention_heads (`int`, *optional*, defaults to 8):
123
+ Number of attention heads for each attention layer in the Transformer decoder.
124
+ decoder_activation_function (`str`, *optional*, defaults to `"relu"`):
125
+ The non-linear activation function (function or string) in the decoder. If string, `"gelu"`,
126
+ `"relu"`, `"silu"` and `"gelu_new"` are supported.
127
+ attention_dropout (`float`, *optional*, defaults to 0.0):
128
+ The dropout ratio for the attention probabilities.
129
+ num_denoising (`int`, *optional*, defaults to 100):
130
+ The total number of denoising tasks or queries to be used for contrastive denoising.
131
+ label_noise_ratio (`float`, *optional*, defaults to 0.5):
132
+ The fraction of denoising labels to which random noise should be added.
133
+ box_noise_scale (`float`, *optional*, defaults to 1.0):
134
+ Scale or magnitude of noise to be added to the bounding boxes.
135
+ learn_initial_query (`bool`, *optional*, defaults to `False`):
136
+ Indicates whether the initial query embeddings for the decoder should be learned during training
137
+ anchor_image_size (`tuple[int, int]`, *optional*):
138
+ Height and width of the input image used during evaluation to generate the bounding box anchors. If None, automatic generate anchor is applied.
139
+ with_box_refine (`bool`, *optional*, defaults to `True`):
140
+ Whether to apply iterative bounding box refinement, where each decoder layer refines the bounding boxes
141
+ based on the predictions from the previous layer.
142
+ is_encoder_decoder (`bool`, *optional*, defaults to `True`):
143
+ Whether the architecture has an encoder decoder structure.
144
+ matcher_alpha (`float`, *optional*, defaults to 0.25):
145
+ Parameter alpha used by the Hungarian Matcher.
146
+ matcher_gamma (`float`, *optional*, defaults to 2.0):
147
+ Parameter gamma used by the Hungarian Matcher.
148
+ matcher_class_cost (`float`, *optional*, defaults to 2.0):
149
+ The relative weight of the class loss used by the Hungarian Matcher.
150
+ matcher_bbox_cost (`float`, *optional*, defaults to 5.0):
151
+ The relative weight of the bounding box loss used by the Hungarian Matcher.
152
+ matcher_giou_cost (`float`, *optional*, defaults to 2.0):
153
+ The relative weight of the giou loss of used by the Hungarian Matcher.
154
+ use_focal_loss (`bool`, *optional*, defaults to `True`):
155
+ Parameter informing if focal focal should be used.
156
+ auxiliary_loss (`bool`, *optional*, defaults to `True`):
157
+ Whether auxiliary decoding losses (loss at each decoder layer) are to be used.
158
+ focal_loss_alpha (`float`, *optional*, defaults to 0.75):
159
+ Parameter alpha used to compute the focal loss.
160
+ focal_loss_gamma (`float`, *optional*, defaults to 2.0):
161
+ Parameter gamma used to compute the focal loss.
162
+ weight_loss_vfl (`float`, *optional*, defaults to 1.0):
163
+ Relative weight of the varifocal loss in the object detection loss.
164
+ weight_loss_bbox (`float`, *optional*, defaults to 5.0):
165
+ Relative weight of the L1 bounding box loss in the object detection loss.
166
+ weight_loss_giou (`float`, *optional*, defaults to 2.0):
167
+ Relative weight of the generalized IoU loss in the object detection loss.
168
+ weight_loss_fgl (`float`, *optional*, defaults to 0.15):
169
+ Relative weight of the fine-grained localization loss in the object detection loss.
170
+ weight_loss_ddf (`float`, *optional*, defaults to 1.5):
171
+ Relative weight of the decoupled distillation focal loss in the object detection loss.
172
+ eos_coefficient (`float`, *optional*, defaults to 0.0001):
173
+ Relative classification weight of the 'no-object' class in the object detection loss.
174
+ eval_idx (`int`, *optional*, defaults to -1):
175
+ Index of the decoder layer to use for evaluation. If negative, counts from the end
176
+ (e.g., -1 means use the last layer). This allows for early prediction in the decoder
177
+ stack while still training later layers.
178
+ layer_scale (`float`, *optional*, defaults to `1.0`):
179
+ Scaling factor for the hidden dimension in later decoder layers. Used to adjust the
180
+ model capacity after the evaluation layer.
181
+ max_num_bins (`int`, *optional*, defaults to 32):
182
+ Maximum number of bins for the distribution-guided bounding box refinement.
183
+ Higher values allow for more fine-grained localization but increase computation.
184
+ reg_scale (`float`, *optional*, defaults to 4.0):
185
+ Scale factor for the regression distribution. Controls the range and granularity
186
+ of the bounding box refinement process.
187
+ depth_mult (`float`, *optional*, defaults to 1.0):
188
+ Multiplier for the number of blocks in RepNCSPELAN4 layers. Used to scale the model's
189
+ depth while maintaining its architecture.
190
+ top_prob_values (`int`, *optional*, defaults to 4):
191
+ Number of top probability values to consider from each corner's distribution.
192
+ lqe_hidden_dim (`int`, *optional*, defaults to 64):
193
+ Hidden dimension size for the Location Quality Estimator (LQE) network.
194
+ lqe_layers (`int`, *optional*, defaults to 2):
195
+ Number of layers in the Location Quality Estimator MLP.
196
+ decoder_offset_scale (`float`, *optional*, defaults to 0.5):
197
+ Offset scale used in deformable attention.
198
+ decoder_method (`str`, *optional*, defaults to `"default"`):
199
+ The method to use for the decoder: `"default"` or `"discrete"`.
200
+ up (`float`, *optional*, defaults to 0.5):
201
+ Controls the upper bounds of the Weighting Function.
202
+ tie_word_embeddings (`bool`, *optional*, defaults to `True`):
203
+ Whether to tie weight embeddings
204
+ """
205
+
206
+ model_type = "d_fine"
207
+ sub_configs = {"backbone_config": AutoConfig}
208
+ layer_types = ["basic", "bottleneck"]
209
+ attribute_map = {
210
+ "hidden_size": "d_model",
211
+ "num_attention_heads": "encoder_attention_heads",
212
+ }
213
+
214
+ def __init__(
215
+ self,
216
+ initializer_range=0.01,
217
+ initializer_bias_prior_prob=None,
218
+ layer_norm_eps=1e-5,
219
+ batch_norm_eps=1e-5,
220
+ # backbone
221
+ backbone_config=None,
222
+ freeze_backbone_batch_norms=True,
223
+ # encoder HybridEncoder
224
+ encoder_hidden_dim=256,
225
+ encoder_in_channels=[512, 1024, 2048],
226
+ feat_strides=[8, 16, 32],
227
+ encoder_layers=1,
228
+ encoder_ffn_dim=1024,
229
+ encoder_attention_heads=8,
230
+ dropout=0.0,
231
+ activation_dropout=0.0,
232
+ encode_proj_layers=[2],
233
+ positional_encoding_temperature=10000,
234
+ encoder_activation_function="gelu",
235
+ activation_function="silu",
236
+ eval_size=None,
237
+ normalize_before=False,
238
+ hidden_expansion=1.0,
239
+ # decoder DFineTransformer
240
+ d_model=256,
241
+ num_queries=300,
242
+ decoder_in_channels=[256, 256, 256],
243
+ decoder_ffn_dim=1024,
244
+ num_feature_levels=3,
245
+ decoder_n_points=4,
246
+ decoder_layers=6,
247
+ decoder_attention_heads=8,
248
+ decoder_activation_function="relu",
249
+ attention_dropout=0.0,
250
+ num_denoising=100,
251
+ label_noise_ratio=0.5,
252
+ box_noise_scale=1.0,
253
+ learn_initial_query=False,
254
+ anchor_image_size=None,
255
+ with_box_refine=True,
256
+ is_encoder_decoder=True,
257
+ # Loss
258
+ matcher_alpha=0.25,
259
+ matcher_gamma=2.0,
260
+ matcher_class_cost=2.0,
261
+ matcher_bbox_cost=5.0,
262
+ matcher_giou_cost=2.0,
263
+ use_focal_loss=True,
264
+ auxiliary_loss=True,
265
+ focal_loss_alpha=0.75,
266
+ focal_loss_gamma=2.0,
267
+ weight_loss_vfl=1.0,
268
+ weight_loss_bbox=5.0,
269
+ weight_loss_giou=2.0,
270
+ weight_loss_fgl=0.15,
271
+ weight_loss_ddf=1.5,
272
+ eos_coefficient=1e-4,
273
+ eval_idx=-1,
274
+ layer_scale=1,
275
+ max_num_bins=32,
276
+ reg_scale=4.0,
277
+ depth_mult=1.0,
278
+ top_prob_values=4,
279
+ lqe_hidden_dim=64,
280
+ lqe_layers=2,
281
+ decoder_offset_scale=0.5,
282
+ decoder_method="default",
283
+ up=0.5,
284
+ tie_word_embeddings=True,
285
+ **kwargs,
286
+ ):
287
+ self.initializer_range = initializer_range
288
+ self.initializer_bias_prior_prob = initializer_bias_prior_prob
289
+ self.layer_norm_eps = layer_norm_eps
290
+ self.batch_norm_eps = batch_norm_eps
291
+
292
+ backbone_config, kwargs = consolidate_backbone_kwargs_to_config(
293
+ backbone_config=backbone_config,
294
+ default_config_type="hgnet_v2",
295
+ default_config_kwargs={"out_indices": [2, 3, 4]},
296
+ **kwargs,
297
+ )
298
+
299
+ self.backbone_config = backbone_config
300
+ self.freeze_backbone_batch_norms = freeze_backbone_batch_norms
301
+ # encoder
302
+ self.encoder_hidden_dim = encoder_hidden_dim
303
+ self.encoder_in_channels = encoder_in_channels
304
+ self.feat_strides = feat_strides
305
+ self.encoder_attention_heads = encoder_attention_heads
306
+ self.encoder_ffn_dim = encoder_ffn_dim
307
+ self.dropout = dropout
308
+ self.activation_dropout = activation_dropout
309
+ self.encode_proj_layers = encode_proj_layers
310
+ self.encoder_layers = encoder_layers
311
+ self.positional_encoding_temperature = positional_encoding_temperature
312
+ self.eval_size = eval_size
313
+ self.normalize_before = normalize_before
314
+ self.encoder_activation_function = encoder_activation_function
315
+ self.activation_function = activation_function
316
+ self.hidden_expansion = hidden_expansion
317
+ # decoder
318
+ self.d_model = d_model
319
+ self.num_queries = num_queries
320
+ self.decoder_ffn_dim = decoder_ffn_dim
321
+ self.decoder_in_channels = decoder_in_channels
322
+ self.num_feature_levels = num_feature_levels
323
+ self.decoder_n_points = decoder_n_points
324
+ self.decoder_layers = decoder_layers
325
+ self.decoder_attention_heads = decoder_attention_heads
326
+ self.decoder_activation_function = decoder_activation_function
327
+ self.attention_dropout = attention_dropout
328
+ self.num_denoising = num_denoising
329
+ self.label_noise_ratio = label_noise_ratio
330
+ self.box_noise_scale = box_noise_scale
331
+ self.learn_initial_query = learn_initial_query
332
+ self.anchor_image_size = anchor_image_size
333
+ self.auxiliary_loss = auxiliary_loss
334
+ self.with_box_refine = with_box_refine
335
+ # Loss
336
+ self.matcher_alpha = matcher_alpha
337
+ self.matcher_gamma = matcher_gamma
338
+ self.matcher_class_cost = matcher_class_cost
339
+ self.matcher_bbox_cost = matcher_bbox_cost
340
+ self.matcher_giou_cost = matcher_giou_cost
341
+ self.use_focal_loss = use_focal_loss
342
+ self.focal_loss_alpha = focal_loss_alpha
343
+ self.focal_loss_gamma = focal_loss_gamma
344
+ self.weight_loss_vfl = weight_loss_vfl
345
+ self.weight_loss_bbox = weight_loss_bbox
346
+ self.weight_loss_giou = weight_loss_giou
347
+ self.weight_loss_fgl = weight_loss_fgl
348
+ self.weight_loss_ddf = weight_loss_ddf
349
+ self.eos_coefficient = eos_coefficient
350
+ # add the new attributes with the given values or defaults
351
+ self.eval_idx = eval_idx
352
+ self.layer_scale = layer_scale
353
+ self.max_num_bins = max_num_bins
354
+ self.reg_scale = reg_scale
355
+ self.depth_mult = depth_mult
356
+ self.decoder_offset_scale = decoder_offset_scale
357
+ self.decoder_method = decoder_method
358
+ self.top_prob_values = top_prob_values
359
+ self.lqe_hidden_dim = lqe_hidden_dim
360
+ self.lqe_layers = lqe_layers
361
+ self.up = up
362
+ self.tie_word_embeddings = tie_word_embeddings
363
+
364
+ if isinstance(self.decoder_n_points, list):
365
+ if len(self.decoder_n_points) != self.num_feature_levels:
366
+ raise ValueError(
367
+ f"Length of decoder_n_points list ({len(self.decoder_n_points)}) must match num_feature_levels ({self.num_feature_levels})."
368
+ )
369
+
370
+ head_dim = self.d_model // self.decoder_attention_heads
371
+ if head_dim * self.decoder_attention_heads != self.d_model:
372
+ raise ValueError(
373
+ f"Embedded dimension {self.d_model} must be divisible by decoder_attention_heads {self.decoder_attention_heads}"
374
+ )
375
+
376
+ super().__init__(is_encoder_decoder=is_encoder_decoder, **kwargs)
377
+
378
+
379
+ class DFineDecoderOutput(RTDetrDecoderOutput):
380
+ pass
381
+
382
+
383
+ def weighting_function(max_num_bins: int, up: torch.Tensor, reg_scale: int) -> torch.Tensor:
384
+ """
385
+ Generates the non-uniform Weighting Function W(n) for bounding box regression.
386
+
387
+ Args:
388
+ max_num_bins (int): Max number of the discrete bins.
389
+ up (Tensor): Controls upper bounds of the sequence,
390
+ where maximum offset is ±up * H / W.
391
+ reg_scale (float): Controls the curvature of the Weighting Function.
392
+ Larger values result in flatter weights near the central axis W(max_num_bins/2)=0
393
+ and steeper weights at both ends.
394
+ Returns:
395
+ Tensor: Sequence of Weighting Function.
396
+ """
397
+ upper_bound1 = abs(up[0]) * abs(reg_scale)
398
+ upper_bound2 = abs(up[0]) * abs(reg_scale) * 2
399
+ step = (upper_bound1 + 1) ** (2 / (max_num_bins - 2))
400
+ left_values = [-((step) ** i) + 1 for i in range(max_num_bins // 2 - 1, 0, -1)]
401
+ right_values = [(step) ** i - 1 for i in range(1, max_num_bins // 2)]
402
+ values = [-upper_bound2] + left_values + [torch.zeros_like(up[0][None])] + right_values + [upper_bound2]
403
+ values = torch.cat(values, 0)
404
+ return values
405
+
406
+
407
+ def distance2bbox(points, distance: torch.Tensor, reg_scale: float) -> torch.Tensor:
408
+ """
409
+ Decodes edge-distances into bounding box coordinates.
410
+
411
+ Args:
412
+ points (`torch.Tensor`):
413
+ (batch_size, num_boxes, 4) or (num_boxes, 4) format, representing [x_center, y_center, width, height]
414
+ distance (`torch.Tensor`):
415
+ (batch_size, num_boxes, 4) or (num_boxes, 4), representing distances from the point to the left, top, right, and bottom boundaries.
416
+ reg_scale (`float`):
417
+ Controls the curvature of the Weighting Function.
418
+ Returns:
419
+ `torch.Tensor`: Bounding boxes in (batch_size, num_boxes, 4) or (num_boxes, 4) format, representing [x_center, y_center, width, height]
420
+ """
421
+ reg_scale = abs(reg_scale)
422
+ top_left_x = points[..., 0] - (0.5 * reg_scale + distance[..., 0]) * (points[..., 2] / reg_scale)
423
+ top_left_y = points[..., 1] - (0.5 * reg_scale + distance[..., 1]) * (points[..., 3] / reg_scale)
424
+ bottom_right_x = points[..., 0] + (0.5 * reg_scale + distance[..., 2]) * (points[..., 2] / reg_scale)
425
+ bottom_right_y = points[..., 1] + (0.5 * reg_scale + distance[..., 3]) * (points[..., 3] / reg_scale)
426
+
427
+ bboxes = torch.stack([top_left_x, top_left_y, bottom_right_x, bottom_right_y], -1)
428
+
429
+ return corners_to_center_format(bboxes)
430
+
431
+
432
+ class DFineMLP(nn.Module):
433
+ def __init__(self, input_dim: int, hidden_dim: int, output_dim: int, num_layers: int, act: str = "relu"):
434
+ super().__init__()
435
+ self.num_layers = num_layers
436
+ hidden_dims = [hidden_dim] * (num_layers - 1)
437
+ input_dims = [input_dim] + hidden_dims
438
+ output_dims = hidden_dims + [output_dim]
439
+ self.layers = nn.ModuleList(nn.Linear(in_dim, out_dim) for in_dim, out_dim in zip(input_dims, output_dims))
440
+ self.act = ACT2CLS[act]()
441
+
442
+ def forward(self, stat_features: torch.Tensor) -> torch.Tensor:
443
+ for i, layer in enumerate(self.layers):
444
+ stat_features = self.act(layer(stat_features)) if i < self.num_layers - 1 else layer(stat_features)
445
+ return stat_features
446
+
447
+
448
+ class DFineGate(nn.Module):
449
+ def __init__(self, d_model: int):
450
+ super().__init__()
451
+ self.gate = nn.Linear(2 * d_model, 2 * d_model)
452
+ self.norm = nn.LayerNorm(d_model)
453
+
454
+ def forward(self, second_residual: torch.Tensor, hidden_states: torch.Tensor) -> torch.Tensor:
455
+ gate_input = torch.cat([second_residual, hidden_states], dim=-1)
456
+ gates = torch.sigmoid(self.gate(gate_input))
457
+ gate1, gate2 = gates.chunk(2, dim=-1)
458
+ hidden_states = self.norm(gate1 * second_residual + gate2 * hidden_states)
459
+ return hidden_states
460
+
461
+
462
+ class DFineFrozenBatchNorm2d(RTDetrFrozenBatchNorm2d):
463
+ pass
464
+
465
+
466
+ class DFineMultiscaleDeformableAttention(nn.Module):
467
+ def __init__(self, config: DFineConfig):
468
+ """
469
+ D-Fine version of multiscale deformable attention
470
+ """
471
+ super().__init__()
472
+ self.d_model = config.d_model
473
+ self.n_heads = config.decoder_attention_heads
474
+ self.n_levels = config.num_feature_levels
475
+ self.offset_scale = config.decoder_offset_scale
476
+ self.decoder_method = config.decoder_method
477
+ self.n_points = config.decoder_n_points
478
+
479
+ if isinstance(self.n_points, list):
480
+ num_points_list = self.n_points
481
+ else:
482
+ num_points_list = [self.n_points for _ in range(self.n_levels)]
483
+
484
+ self.num_points_list = num_points_list
485
+ num_points_scale = [1 / n for n in self.num_points_list for _ in range(n)]
486
+ self.register_buffer("num_points_scale", torch.tensor(num_points_scale, dtype=torch.float32))
487
+
488
+ self.total_points = self.n_heads * sum(self.num_points_list)
489
+
490
+ self.sampling_offsets = nn.Linear(self.d_model, self.total_points * 2)
491
+ self.attention_weights = nn.Linear(self.d_model, self.total_points)
492
+
493
+ self.ms_deformable_attn_core = multi_scale_deformable_attention_v2
494
+
495
+ def forward(
496
+ self,
497
+ hidden_states: torch.Tensor,
498
+ attention_mask: torch.Tensor | None = None,
499
+ reference_points=None,
500
+ encoder_hidden_states=None,
501
+ spatial_shapes=None,
502
+ spatial_shapes_list=None,
503
+ **kwargs: Unpack[TransformersKwargs],
504
+ ) -> tuple[torch.Tensor, torch.Tensor]:
505
+ batch_size, num_queries, _ = hidden_states.shape
506
+ batch_size, sequence_length, _ = encoder_hidden_states.shape
507
+
508
+ torch_compilable_check(
509
+ (spatial_shapes[:, 0] * spatial_shapes[:, 1]).sum() == sequence_length,
510
+ "Make sure to align the spatial shapes with the sequence length of the encoder hidden states",
511
+ )
512
+
513
+ # Reshape for multi-head attention
514
+ value = encoder_hidden_states.reshape(batch_size, sequence_length, self.n_heads, self.d_model // self.n_heads)
515
+ if attention_mask is not None:
516
+ value = value.masked_fill(~attention_mask[..., None], float(0))
517
+
518
+ sampling_offsets: torch.Tensor = self.sampling_offsets(hidden_states)
519
+ sampling_offsets = sampling_offsets.reshape(
520
+ batch_size, num_queries, self.n_heads, sum(self.num_points_list), 2
521
+ )
522
+
523
+ attention_weights = self.attention_weights(hidden_states).reshape(
524
+ batch_size, num_queries, self.n_heads, sum(self.num_points_list)
525
+ )
526
+ attention_weights = F.softmax(attention_weights, dim=-1)
527
+
528
+ if reference_points.shape[-1] == 2:
529
+ offset_normalizer = torch.tensor(spatial_shapes)
530
+ offset_normalizer = offset_normalizer.flip([1]).reshape(1, 1, 1, self.n_levels, 1, 2)
531
+ sampling_locations = (
532
+ reference_points.reshape(batch_size, sequence_length, 1, self.n_levels, 1, 2)
533
+ + sampling_offsets / offset_normalizer
534
+ )
535
+ elif reference_points.shape[-1] == 4:
536
+ # reference_points [8, 480, None, 1, 4]
537
+ # sampling_offsets [8, 480, 8, 12, 2]
538
+ num_points_scale = self.num_points_scale.to(dtype=hidden_states.dtype).unsqueeze(-1)
539
+ offset = sampling_offsets * num_points_scale * reference_points[:, :, None, :, 2:] * self.offset_scale
540
+ sampling_locations = reference_points[:, :, None, :, :2] + offset
541
+ else:
542
+ raise ValueError(
543
+ f"Last dim of reference_points must be 2 or 4, but get {reference_points.shape[-1]} instead."
544
+ )
545
+
546
+ output = self.ms_deformable_attn_core(
547
+ value,
548
+ spatial_shapes_list,
549
+ sampling_locations,
550
+ attention_weights,
551
+ self.num_points_list,
552
+ self.decoder_method,
553
+ )
554
+
555
+ return output, attention_weights
556
+
557
+
558
+ class DFineConvNormLayer(RTDetrConvNormLayer):
559
+ def __init__(
560
+ self,
561
+ config: DFineConfig,
562
+ in_channels: int,
563
+ out_channels: int,
564
+ kernel_size: int,
565
+ stride: int,
566
+ groups: int = 1,
567
+ padding: int | None = None,
568
+ activation: str | None = None,
569
+ ):
570
+ super().__init__(config, in_channels, out_channels, kernel_size, stride, padding=None, activation=activation)
571
+ self.conv = nn.Conv2d(
572
+ in_channels,
573
+ out_channels,
574
+ kernel_size,
575
+ stride,
576
+ groups=groups,
577
+ padding=(kernel_size - 1) // 2 if padding is None else padding,
578
+ bias=False,
579
+ )
580
+
581
+
582
+ class DFineRepVggBlock(RTDetrRepVggBlock):
583
+ def __init__(self, config: DFineConfig, in_channels: int, out_channels: int):
584
+ super().__init__(config)
585
+ hidden_channels = in_channels
586
+ self.conv1 = DFineConvNormLayer(config, hidden_channels, out_channels, 3, 1, padding=1)
587
+ self.conv2 = DFineConvNormLayer(config, hidden_channels, out_channels, 1, 1, padding=0)
588
+
589
+
590
+ class DFineCSPRepLayer(nn.Module):
591
+ """
592
+ Cross Stage Partial (CSP) network layer with RepVGG blocks.
593
+ """
594
+
595
+ def __init__(
596
+ self, config: DFineConfig, in_channels: int, out_channels: int, num_blocks: int, expansion: float = 1.0
597
+ ):
598
+ super().__init__()
599
+ activation = config.activation_function
600
+
601
+ hidden_channels = int(out_channels * expansion)
602
+ self.conv1 = DFineConvNormLayer(config, in_channels, hidden_channels, 1, 1, activation=activation)
603
+ self.conv2 = DFineConvNormLayer(config, in_channels, hidden_channels, 1, 1, activation=activation)
604
+ self.bottlenecks = nn.ModuleList(
605
+ [DFineRepVggBlock(config, hidden_channels, hidden_channels) for _ in range(num_blocks)]
606
+ )
607
+ if hidden_channels != out_channels:
608
+ self.conv3 = DFineConvNormLayer(config, hidden_channels, out_channels, 1, 1, activation=activation)
609
+ else:
610
+ self.conv3 = nn.Identity()
611
+
612
+ def forward(self, hidden_state: torch.Tensor) -> torch.Tensor:
613
+ hidden_state_1 = self.conv1(hidden_state)
614
+ for bottleneck in self.bottlenecks:
615
+ hidden_state_1 = bottleneck(hidden_state_1)
616
+ hidden_state_2 = self.conv2(hidden_state)
617
+ hidden_state_3 = self.conv3(hidden_state_1 + hidden_state_2)
618
+ return hidden_state_3
619
+
620
+
621
+ class DFineRepNCSPELAN4(nn.Module):
622
+ def __init__(self, config: DFineConfig, act: str = "silu", numb_blocks: int = 3):
623
+ super().__init__()
624
+ conv1_dim = config.encoder_hidden_dim * 2
625
+ conv2_dim = config.encoder_hidden_dim
626
+ conv3_dim = config.encoder_hidden_dim * 2
627
+ conv4_dim = round(config.hidden_expansion * config.encoder_hidden_dim // 2)
628
+ self.conv_dim = conv3_dim // 2
629
+ self.conv1 = DFineConvNormLayer(config, conv1_dim, conv3_dim, 1, 1, activation=act)
630
+ self.csp_rep1 = DFineCSPRepLayer(config, conv3_dim // 2, conv4_dim, num_blocks=numb_blocks)
631
+ self.conv2 = DFineConvNormLayer(config, conv4_dim, conv4_dim, 3, 1, activation=act)
632
+ self.csp_rep2 = DFineCSPRepLayer(config, conv4_dim, conv4_dim, num_blocks=numb_blocks)
633
+ self.conv3 = DFineConvNormLayer(config, conv4_dim, conv4_dim, 3, 1, activation=act)
634
+ self.conv4 = DFineConvNormLayer(config, conv3_dim + (2 * conv4_dim), conv2_dim, 1, 1, activation=act)
635
+
636
+ def forward(self, input_features: torch.Tensor) -> torch.Tensor:
637
+ # Split initial features into two branches after first convolution
638
+ split_features = list(self.conv1(input_features).split((self.conv_dim, self.conv_dim), 1))
639
+
640
+ # Process branches sequentially
641
+ branch1 = self.csp_rep1(split_features[-1])
642
+ branch1 = self.conv2(branch1)
643
+ branch2 = self.csp_rep2(branch1)
644
+ branch2 = self.conv3(branch2)
645
+
646
+ split_features.extend([branch1, branch2])
647
+ merged_features = torch.cat(split_features, 1)
648
+ merged_features = self.conv4(merged_features)
649
+ return merged_features
650
+
651
+
652
+ class DFineSCDown(nn.Module):
653
+ def __init__(self, config: DFineConfig, kernel_size: int, stride: int):
654
+ super().__init__()
655
+ self.conv1 = DFineConvNormLayer(config, config.encoder_hidden_dim, config.encoder_hidden_dim, 1, 1)
656
+ self.conv2 = DFineConvNormLayer(
657
+ config,
658
+ config.encoder_hidden_dim,
659
+ config.encoder_hidden_dim,
660
+ kernel_size,
661
+ stride,
662
+ config.encoder_hidden_dim,
663
+ )
664
+
665
+ def forward(self, input_features: torch.Tensor) -> torch.Tensor:
666
+ input_features = self.conv1(input_features)
667
+ input_features = self.conv2(input_features)
668
+ return input_features
669
+
670
+
671
+ class DFineEncoderLayer(RTDetrEncoderLayer):
672
+ def __init__(self, config: DFineConfig):
673
+ super().__init__(config)
674
+ self.mlp = DFineMLP(
675
+ self.hidden_size, config.encoder_ffn_dim, self.hidden_size, 2, config.encoder_activation_function
676
+ )
677
+
678
+
679
+ class DFineAIFILayer(RTDetrAIFILayer):
680
+ pass
681
+
682
+
683
+ class DFineIntegral(nn.Module):
684
+ """
685
+ A static layer that calculates integral results from a distribution.
686
+
687
+ This layer computes the target location using the formula: `sum{Pr(n) * W(n)}`,
688
+ where Pr(n) is the softmax probability vector representing the discrete
689
+ distribution, and W(n) is the non-uniform Weighting Function.
690
+
691
+ Args:
692
+ max_num_bins (int): Max number of the discrete bins. Default is 32.
693
+ It can be adjusted based on the dataset or task requirements.
694
+ """
695
+
696
+ def __init__(self, config: DFineConfig):
697
+ super().__init__()
698
+ self.max_num_bins = config.max_num_bins
699
+
700
+ def forward(self, pred_corners: torch.Tensor, project: torch.Tensor) -> torch.Tensor:
701
+ batch_size, num_queries, _ = pred_corners.shape
702
+ pred_corners = F.softmax(pred_corners.reshape(-1, self.max_num_bins + 1), dim=1)
703
+ pred_corners = F.linear(pred_corners, project.to(pred_corners.device)).reshape(-1, 4)
704
+ pred_corners = pred_corners.reshape(batch_size, num_queries, -1)
705
+ return pred_corners
706
+
707
+
708
+ class DFineLQE(nn.Module):
709
+ def __init__(self, config: DFineConfig):
710
+ super().__init__()
711
+ self.top_prob_values = config.top_prob_values
712
+ self.max_num_bins = config.max_num_bins
713
+ self.reg_conf = DFineMLP(4 * (self.top_prob_values + 1), config.lqe_hidden_dim, 1, config.lqe_layers)
714
+
715
+ def forward(self, scores: torch.Tensor, pred_corners: torch.Tensor) -> torch.Tensor:
716
+ batch_size, length, _ = pred_corners.size()
717
+ prob = F.softmax(pred_corners.reshape(batch_size, length, 4, self.max_num_bins + 1), dim=-1)
718
+ prob_topk, _ = prob.topk(self.top_prob_values, dim=-1)
719
+ stat = torch.cat([prob_topk, prob_topk.mean(dim=-1, keepdim=True)], dim=-1)
720
+ quality_score = self.reg_conf(stat.reshape(batch_size, length, -1))
721
+ scores = scores + quality_score
722
+ return scores
723
+
724
+
725
+ class DFineDecoderLayer(RTDetrDecoderLayer):
726
+ def __init__(self, config: DFineConfig):
727
+ super().__init__(config)
728
+
729
+ # override the encoder attention module with d-fine version
730
+ self.encoder_attn = DFineMultiscaleDeformableAttention(config=config)
731
+ # gate
732
+ self.gateway = DFineGate(config.d_model)
733
+ self.mlp = DFineMLP(
734
+ self.hidden_size, config.decoder_ffn_dim, self.hidden_size, 2, config.decoder_activation_function
735
+ )
736
+
737
+ del self.encoder_attn_layer_norm
738
+
739
+ def forward(
740
+ self,
741
+ hidden_states: torch.Tensor,
742
+ position_embeddings: torch.Tensor | None = None,
743
+ reference_points=None,
744
+ spatial_shapes=None,
745
+ spatial_shapes_list=None,
746
+ encoder_hidden_states: torch.Tensor | None = None,
747
+ encoder_attention_mask: torch.Tensor | None = None,
748
+ **kwargs: Unpack[TransformersKwargs],
749
+ ) -> torch.Tensor:
750
+ residual = hidden_states
751
+
752
+ # Self Attention
753
+ hidden_states, _ = self.self_attn(
754
+ hidden_states=hidden_states,
755
+ attention_mask=encoder_attention_mask,
756
+ position_embeddings=position_embeddings,
757
+ **kwargs,
758
+ )
759
+
760
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
761
+ hidden_states = residual + hidden_states
762
+ hidden_states = self.self_attn_layer_norm(hidden_states)
763
+
764
+ residual = hidden_states
765
+
766
+ # Cross-Attention
767
+ hidden_states = hidden_states if position_embeddings is None else hidden_states + position_embeddings
768
+ hidden_states, _ = self.encoder_attn(
769
+ hidden_states=hidden_states,
770
+ encoder_hidden_states=encoder_hidden_states,
771
+ reference_points=reference_points,
772
+ spatial_shapes=spatial_shapes,
773
+ spatial_shapes_list=spatial_shapes_list,
774
+ )
775
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
776
+ hidden_states = self.gateway(residual, hidden_states)
777
+
778
+ # Fully Connected
779
+ residual = hidden_states
780
+ hidden_states = self.mlp(hidden_states)
781
+ hidden_states = residual + hidden_states
782
+ hidden_states = self.final_layer_norm(hidden_states.clamp(min=-65504, max=65504))
783
+
784
+ return hidden_states
785
+
786
+
787
+ class DFineMLPPredictionHead(RTDetrMLPPredictionHead):
788
+ pass
789
+
790
+
791
+ class DFinePreTrainedModel(RTDetrPreTrainedModel):
792
+ @torch.no_grad()
793
+ def _init_weights(self, module):
794
+ """Initialize the weights"""
795
+ # initialize linear layer bias value according to a given probability value.
796
+ if isinstance(module, (DFineForObjectDetection, DFineDecoder)):
797
+ if module.class_embed is not None:
798
+ for layer in module.class_embed:
799
+ prior_prob = self.config.initializer_bias_prior_prob or 1 / (self.config.num_labels + 1)
800
+ bias = float(-math.log((1 - prior_prob) / prior_prob))
801
+ init.xavier_uniform_(layer.weight)
802
+ init.constant_(layer.bias, bias)
803
+
804
+ if module.bbox_embed is not None:
805
+ for layer in module.bbox_embed:
806
+ init.constant_(layer.layers[-1].weight, 0)
807
+ init.constant_(layer.layers[-1].bias, 0)
808
+
809
+ if hasattr(module, "reg_scale"):
810
+ init.constant_(module.reg_scale, self.config.reg_scale)
811
+
812
+ if hasattr(module, "up"):
813
+ init.constant_(module.up, self.config.up)
814
+
815
+ if isinstance(module, DFineMultiscaleDeformableAttention):
816
+ init.constant_(module.sampling_offsets.weight, 0.0)
817
+ default_dtype = torch.get_default_dtype()
818
+ thetas = torch.arange(module.n_heads, dtype=torch.int64).to(default_dtype) * (
819
+ 2.0 * math.pi / module.n_heads
820
+ )
821
+ grid_init = torch.stack([thetas.cos(), thetas.sin()], -1)
822
+ grid_init = grid_init / grid_init.abs().max(-1, keepdim=True).values
823
+ grid_init = grid_init.reshape(module.n_heads, 1, 2).tile([1, sum(module.num_points_list), 1])
824
+ scaling = torch.concat([torch.arange(1, n + 1) for n in module.num_points_list]).reshape(1, -1, 1)
825
+ grid_init *= scaling
826
+ init.copy_(module.sampling_offsets.bias, grid_init.flatten())
827
+
828
+ init.constant_(module.attention_weights.weight, 0.0)
829
+ init.constant_(module.attention_weights.bias, 0.0)
830
+
831
+ num_points_scale = [1 / n for n in module.num_points_list for _ in range(n)]
832
+ init.copy_(module.num_points_scale, torch.tensor(num_points_scale, dtype=torch.float32))
833
+
834
+ if isinstance(module, DFineModel):
835
+ prior_prob = self.config.initializer_bias_prior_prob or 1 / (self.config.num_labels + 1)
836
+ bias = float(-math.log((1 - prior_prob) / prior_prob))
837
+ init.xavier_uniform_(module.enc_score_head.weight)
838
+ init.constant_(module.enc_score_head.bias, bias)
839
+
840
+ if isinstance(module, (nn.Linear, nn.Conv2d, nn.BatchNorm2d)):
841
+ init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
842
+ if module.bias is not None:
843
+ init.zeros_(module.bias)
844
+ if getattr(module, "running_mean", None) is not None:
845
+ init.zeros_(module.running_mean)
846
+ init.ones_(module.running_var)
847
+ init.zeros_(module.num_batches_tracked)
848
+
849
+ if isinstance(module, DFineGate):
850
+ bias = float(-math.log((1 - 0.5) / 0.5))
851
+ init.constant_(module.gate.bias, bias)
852
+ init.constant_(module.gate.weight, 0)
853
+
854
+ if isinstance(module, DFineLQE):
855
+ init.constant_(module.reg_conf.layers[-1].bias, 0)
856
+ init.constant_(module.reg_conf.layers[-1].weight, 0)
857
+
858
+ if isinstance(module, nn.LayerNorm):
859
+ init.ones_(module.weight)
860
+ init.zeros_(module.bias)
861
+
862
+ if hasattr(module, "weight_embedding") and self.config.learn_initial_query:
863
+ init.xavier_uniform_(module.weight_embedding.weight)
864
+ if hasattr(module, "denoising_class_embed") and self.config.num_denoising > 0:
865
+ init.xavier_uniform_(module.denoising_class_embed.weight)
866
+
867
+
868
+ class DFineHybridEncoder(RTDetrHybridEncoder):
869
+ def __init__(self, config: DFineConfig):
870
+ DFinePreTrainedModel.__init__(config)
871
+ self.config = config
872
+ self.in_channels = config.encoder_in_channels
873
+ self.num_fpn_stages = len(self.in_channels) - 1
874
+ self.feat_strides = config.feat_strides
875
+ self.encoder_hidden_dim = config.encoder_hidden_dim
876
+ self.encode_proj_layers = config.encode_proj_layers
877
+ self.positional_encoding_temperature = config.positional_encoding_temperature
878
+ self.eval_size = config.eval_size
879
+ self.out_channels = [self.encoder_hidden_dim for _ in self.in_channels]
880
+ self.out_strides = self.feat_strides
881
+
882
+ # AIFI (Attention-based Intra-scale Feature Interaction) layers
883
+ self.aifi = nn.ModuleList([DFineAIFILayer(config) for _ in range(len(self.encode_proj_layers))])
884
+
885
+ # top-down fpn
886
+ self.lateral_convs = nn.ModuleList()
887
+ self.fpn_blocks = nn.ModuleList()
888
+ for _ in range(len(self.in_channels) - 1, 0, -1):
889
+ lateral_layer = DFineConvNormLayer(config, self.encoder_hidden_dim, self.encoder_hidden_dim, 1, 1)
890
+ self.lateral_convs.append(lateral_layer)
891
+ num_blocks = round(3 * config.depth_mult)
892
+ fpn_layer = DFineRepNCSPELAN4(config, numb_blocks=num_blocks)
893
+ self.fpn_blocks.append(fpn_layer)
894
+
895
+ # bottom-up pan
896
+ self.downsample_convs = nn.ModuleList()
897
+ self.pan_blocks = nn.ModuleList()
898
+ for _ in range(len(self.in_channels) - 1):
899
+ self.downsample_convs.append(DFineSCDown(config, 3, 2))
900
+ num_blocks = round(3 * config.depth_mult)
901
+ self.pan_blocks.append(DFineRepNCSPELAN4(config, numb_blocks=num_blocks))
902
+
903
+ self.post_init()
904
+
905
+
906
+ class DFineDecoder(RTDetrDecoder):
907
+ """
908
+ D-FINE Decoder implementing Fine-grained Distribution Refinement (FDR).
909
+
910
+ This decoder refines object detection predictions through iterative updates across multiple layers,
911
+ utilizing attention mechanisms, location quality estimators, and distribution refinement techniques
912
+ to improve bounding box accuracy and robustness.
913
+ """
914
+
915
+ def __init__(self, config: DFineConfig):
916
+ self.eval_idx = config.eval_idx if config.eval_idx >= 0 else config.decoder_layers + config.eval_idx
917
+ super().__init__(config=config)
918
+ self.reg_scale = nn.Parameter(torch.tensor([config.reg_scale]), requires_grad=False)
919
+ self.max_num_bins = config.max_num_bins
920
+ self.d_model = config.d_model
921
+ self.layer_scale = config.layer_scale
922
+ self.pre_bbox_head = DFineMLP(config.hidden_size, config.hidden_size, 4, 3)
923
+ self.integral = DFineIntegral(config)
924
+ self.num_head = config.decoder_attention_heads
925
+ self.up = nn.Parameter(torch.tensor([config.up]), requires_grad=False)
926
+ self.lqe_layers = nn.ModuleList([DFineLQE(config) for _ in range(config.decoder_layers)])
927
+ self.layers = nn.ModuleList(
928
+ [DFineDecoderLayer(config) for _ in range(config.decoder_layers)]
929
+ + [DFineDecoderLayer(config) for _ in range(config.decoder_layers - self.eval_idx - 1)]
930
+ )
931
+
932
+ def forward(
933
+ self,
934
+ encoder_hidden_states: torch.Tensor,
935
+ reference_points: torch.Tensor,
936
+ inputs_embeds: torch.Tensor,
937
+ spatial_shapes,
938
+ level_start_index=None,
939
+ spatial_shapes_list=None,
940
+ encoder_attention_mask=None,
941
+ memory_mask=None,
942
+ **kwargs: Unpack[TransformersKwargs],
943
+ ) -> DFineDecoderOutput:
944
+ if inputs_embeds is not None:
945
+ hidden_states = inputs_embeds
946
+
947
+ # decoder layers
948
+ intermediate = ()
949
+ intermediate_reference_points = ()
950
+ intermediate_logits = ()
951
+ intermediate_predicted_corners = ()
952
+ initial_reference_points = ()
953
+
954
+ output_detach = pred_corners_undetach = 0
955
+
956
+ project = weighting_function(self.max_num_bins, self.up, self.reg_scale)
957
+ ref_points_detach = F.sigmoid(reference_points)
958
+
959
+ for i, decoder_layer in enumerate(self.layers):
960
+ ref_points_input = ref_points_detach.unsqueeze(2)
961
+ query_pos_embed = self.query_pos_head(ref_points_detach).clamp(min=-10, max=10)
962
+
963
+ hidden_states = decoder_layer(
964
+ hidden_states,
965
+ position_embeddings=query_pos_embed,
966
+ reference_points=ref_points_input,
967
+ spatial_shapes=spatial_shapes,
968
+ spatial_shapes_list=spatial_shapes_list,
969
+ encoder_hidden_states=encoder_hidden_states,
970
+ encoder_attention_mask=encoder_attention_mask,
971
+ **kwargs,
972
+ )
973
+
974
+ if i == 0:
975
+ # Initial bounding box predictions with inverse sigmoid refinement
976
+ new_reference_points = F.sigmoid(
977
+ self.pre_bbox_head(hidden_states) + inverse_sigmoid(ref_points_detach)
978
+ )
979
+ ref_points_initial = new_reference_points.detach()
980
+
981
+ # Refine bounding box corners using FDR, integrating previous layer's corrections
982
+ if self.bbox_embed is not None:
983
+ pred_corners = self.bbox_embed[i](hidden_states + output_detach) + pred_corners_undetach
984
+ inter_ref_bbox = distance2bbox(
985
+ ref_points_initial, self.integral(pred_corners, project), self.reg_scale
986
+ )
987
+ pred_corners_undetach = pred_corners
988
+ ref_points_detach = inter_ref_bbox.detach()
989
+
990
+ output_detach = hidden_states.detach()
991
+
992
+ intermediate += (hidden_states,)
993
+
994
+ if self.class_embed is not None and (self.training or i == self.eval_idx):
995
+ scores = self.class_embed[i](hidden_states)
996
+ # Add initial logits and reference points with pre-bbox head
997
+ if i == 0:
998
+ intermediate_logits += (scores,)
999
+ intermediate_reference_points += (new_reference_points,)
1000
+ # Lqe does not affect the performance here.
1001
+ scores = self.lqe_layers[i](scores, pred_corners)
1002
+ intermediate_logits += (scores,)
1003
+ intermediate_reference_points += (inter_ref_bbox,)
1004
+ initial_reference_points += (ref_points_initial,)
1005
+ intermediate_predicted_corners += (pred_corners,)
1006
+
1007
+ # Keep batch_size as first dimension
1008
+ intermediate = torch.stack(intermediate)
1009
+ if self.class_embed is not None and self.bbox_embed is not None:
1010
+ intermediate_logits = torch.stack(intermediate_logits, dim=1)
1011
+ intermediate_predicted_corners = torch.stack(intermediate_predicted_corners, dim=1)
1012
+ initial_reference_points = torch.stack(initial_reference_points, dim=1)
1013
+ intermediate_reference_points = torch.stack(intermediate_reference_points, dim=1)
1014
+
1015
+ return DFineDecoderOutput(
1016
+ last_hidden_state=hidden_states,
1017
+ intermediate_hidden_states=intermediate,
1018
+ intermediate_logits=intermediate_logits,
1019
+ intermediate_reference_points=intermediate_reference_points,
1020
+ intermediate_predicted_corners=intermediate_predicted_corners,
1021
+ initial_reference_points=initial_reference_points,
1022
+ )
1023
+
1024
+
1025
+ class DFineModel(RTDetrModel):
1026
+ def __init__(self, config: DFineConfig):
1027
+ super().__init__(config)
1028
+ del self.decoder_input_proj
1029
+ self.encoder = DFineHybridEncoder(config=config)
1030
+ num_backbone_outs = len(config.decoder_in_channels)
1031
+ decoder_input_proj = []
1032
+ in_channels = config.decoder_in_channels[-1]
1033
+ for _ in range(num_backbone_outs):
1034
+ if config.hidden_size == config.decoder_in_channels[-1]:
1035
+ decoder_input_proj.append(nn.Identity())
1036
+ else:
1037
+ conv = nn.Conv2d(in_channels, config.d_model, kernel_size=1, bias=False)
1038
+ batchnorm = nn.BatchNorm2d(config.d_model, config.batch_norm_eps)
1039
+ decoder_input_proj.append(nn.Sequential(conv, batchnorm))
1040
+ for _ in range(config.num_feature_levels - num_backbone_outs):
1041
+ if config.hidden_size == config.decoder_in_channels[-1]:
1042
+ decoder_input_proj.append(nn.Identity())
1043
+ else:
1044
+ conv = nn.Conv2d(in_channels, config.d_model, kernel_size=3, stride=2, padding=1, bias=False)
1045
+ batchnorm = nn.BatchNorm2d(config.d_model, config.batch_norm_eps)
1046
+ decoder_input_proj.append(nn.Sequential(conv, batchnorm))
1047
+ self.decoder_input_proj = nn.ModuleList(decoder_input_proj)
1048
+ self.decoder = DFineDecoder(config)
1049
+
1050
+
1051
+ class DFineForObjectDetection(RTDetrForObjectDetection):
1052
+ # When using clones, all layers > 0 will be clones, but layer 0 *is* required
1053
+ # We can't initialize the model on meta device as some weights are modified during the initialization
1054
+ _no_split_modules = None
1055
+ _tied_weights_keys = {
1056
+ r"bbox_embed.(?![0])\d+": r"bbox_embed.0",
1057
+ r"class_embed.(?![0])\d+": r"^class_embed.0",
1058
+ "class_embed": "model.decoder.class_embed",
1059
+ "bbox_embed": "model.decoder.bbox_embed",
1060
+ }
1061
+
1062
+ def __init__(self, config: DFineConfig):
1063
+ DFinePreTrainedModel.__init__(self, config)
1064
+
1065
+ # D-FINE encoder-decoder model
1066
+ self.eval_idx = config.eval_idx if config.eval_idx >= 0 else config.decoder_layers + config.eval_idx
1067
+ self.model = DFineModel(config)
1068
+ scaled_dim = round(config.layer_scale * config.hidden_size)
1069
+ num_pred = config.decoder_layers
1070
+ self.class_embed = nn.ModuleList([nn.Linear(config.d_model, config.num_labels) for _ in range(num_pred)])
1071
+ self.bbox_embed = nn.ModuleList(
1072
+ [
1073
+ DFineMLP(config.hidden_size, config.hidden_size, 4 * (config.max_num_bins + 1), 3)
1074
+ for _ in range(self.eval_idx + 1)
1075
+ ]
1076
+ + [
1077
+ DFineMLP(scaled_dim, scaled_dim, 4 * (config.max_num_bins + 1), 3)
1078
+ for _ in range(config.decoder_layers - self.eval_idx - 1)
1079
+ ]
1080
+ )
1081
+
1082
+ self.model.decoder.class_embed = self.class_embed
1083
+ self.model.decoder.bbox_embed = self.bbox_embed
1084
+ # Initialize weights and apply final processing
1085
+ self.post_init()
1086
+
1087
+ def forward(**super_kwargs):
1088
+ r"""
1089
+ Example:
1090
+
1091
+ ```python
1092
+ >>> import torch
1093
+ >>> from transformers.image_utils import load_image
1094
+ >>> from transformers import AutoImageProcessor, DFineForObjectDetection
1095
+
1096
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
1097
+ >>> image = load_image(url)
1098
+
1099
+ >>> image_processor = AutoImageProcessor.from_pretrained("ustc-community/dfine-xlarge-coco")
1100
+ >>> model = DFineForObjectDetection.from_pretrained("ustc-community/dfine-xlarge-coco")
1101
+
1102
+ >>> # prepare image for the model
1103
+ >>> inputs = image_processor(images=image, return_tensors="pt")
1104
+
1105
+ >>> # forward pass
1106
+ >>> outputs = model(**inputs)
1107
+
1108
+ >>> logits = outputs.logits
1109
+ >>> list(logits.shape)
1110
+ [1, 300, 80]
1111
+
1112
+ >>> boxes = outputs.pred_boxes
1113
+ >>> list(boxes.shape)
1114
+ [1, 300, 4]
1115
+
1116
+ >>> # convert outputs (bounding boxes and class logits) to Pascal VOC format (xmin, ymin, xmax, ymax)
1117
+ >>> target_sizes = torch.tensor([image.size[::-1]])
1118
+ >>> results = image_processor.post_process_object_detection(outputs, threshold=0.9, target_sizes=target_sizes)
1119
+ >>> result = results[0] # first image in batch
1120
+
1121
+ >>> for score, label, box in zip(result["scores"], result["labels"], result["boxes"]):
1122
+ ... box = [round(i, 2) for i in box.tolist()]
1123
+ ... print(
1124
+ ... f"Detected {model.config.id2label[label.item()]} with confidence "
1125
+ ... f"{round(score.item(), 3)} at location {box}"
1126
+ ... )
1127
+ Detected cat with confidence 0.958 at location [344.49, 23.4, 639.84, 374.27]
1128
+ Detected cat with confidence 0.956 at location [11.71, 53.52, 316.64, 472.33]
1129
+ Detected remote with confidence 0.947 at location [40.46, 73.7, 175.62, 117.57]
1130
+ Detected sofa with confidence 0.918 at location [0.59, 1.88, 640.25, 474.74]
1131
+ ```
1132
+ """
1133
+ super().forward(**super_kwargs)
1134
+
1135
+
1136
+ __all__ = [
1137
+ "DFineConfig",
1138
+ "DFineModel",
1139
+ "DFinePreTrainedModel",
1140
+ "DFineForObjectDetection",
1141
+ ]
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/dab_detr/__init__.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 typing import TYPE_CHECKING
16
+
17
+ from ...utils import _LazyModule
18
+ from ...utils.import_utils import define_import_structure
19
+
20
+
21
+ if TYPE_CHECKING:
22
+ from .configuration_dab_detr import *
23
+ from .modeling_dab_detr import *
24
+ else:
25
+ import sys
26
+
27
+ _file = globals()["__file__"]
28
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/dab_detr/configuration_dab_detr.py ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """DAB-DETR model configuration"""
15
+
16
+ from ...backbone_utils import consolidate_backbone_kwargs_to_config
17
+ from ...configuration_utils import PreTrainedConfig
18
+ from ...utils import logging
19
+ from ..auto import AutoConfig
20
+
21
+
22
+ logger = logging.get_logger(__name__)
23
+
24
+
25
+ class DabDetrConfig(PreTrainedConfig):
26
+ r"""
27
+ This is the configuration class to store the configuration of a [`DabDetrModel`]. It is used to instantiate
28
+ a DAB-DETR model according to the specified arguments, defining the model architecture. Instantiating a
29
+ configuration with the defaults will yield a similar configuration to that of the DAB-DETR
30
+ [IDEA-Research/dab_detr-base](https://huggingface.co/IDEA-Research/dab_detr-base) architecture.
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
+ backbone_config (`Union[dict, "PreTrainedConfig"]`, *optional*, defaults to `ResNetConfig()`):
37
+ The configuration of the backbone model. Only used in case `use_timm_backbone` is set to `False` in which
38
+ case it will default to `ResNetConfig()`.
39
+ num_queries (`int`, *optional*, defaults to 300):
40
+ Number of object queries, i.e. detection slots. This is the maximal number of objects
41
+ [`DabDetrModel`] can detect in a single image. For COCO, we recommend 100 queries.
42
+ encoder_layers (`int`, *optional*, defaults to 6):
43
+ Number of encoder layers.
44
+ encoder_ffn_dim (`int`, *optional*, defaults to 2048):
45
+ Dimension of the "intermediate" (often named feed-forward) layer in encoder.
46
+ encoder_attention_heads (`int`, *optional*, defaults to 8):
47
+ Number of attention heads for each attention layer in the Transformer encoder.
48
+ decoder_layers (`int`, *optional*, defaults to 6):
49
+ Number of decoder layers.
50
+ decoder_ffn_dim (`int`, *optional*, defaults to 2048):
51
+ Dimension of the "intermediate" (often named feed-forward) layer in decoder.
52
+ decoder_attention_heads (`int`, *optional*, defaults to 8):
53
+ Number of attention heads for each attention layer in the Transformer decoder.
54
+ is_encoder_decoder (`bool`, *optional*, defaults to `True`):
55
+ Indicates whether the transformer model architecture is an encoder-decoder or not.
56
+ activation_function (`str` or `function`, *optional*, defaults to `"prelu"`):
57
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
58
+ `"relu"`, `"silu"` and `"gelu_new"` are supported.
59
+ hidden_size (`int`, *optional*, defaults to 256):
60
+ This parameter is a general dimension parameter, defining dimensions for components such as the encoder layer and projection parameters in the decoder layer, among others.
61
+ dropout (`float`, *optional*, defaults to 0.1):
62
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
63
+ attention_dropout (`float`, *optional*, defaults to 0.0):
64
+ The dropout ratio for the attention probabilities.
65
+ activation_dropout (`float`, *optional*, defaults to 0.0):
66
+ The dropout ratio for activations inside the fully connected layer.
67
+ init_std (`float`, *optional*, defaults to 0.02):
68
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
69
+ init_xavier_std (`float`, *optional*, defaults to 1.0):
70
+ The scaling factor used for the Xavier initialization gain in the HM Attention map module.
71
+ auxiliary_loss (`bool`, *optional*, defaults to `False`):
72
+ Whether auxiliary decoding losses (loss at each decoder layer) are to be used.
73
+ dilation (`bool`, *optional*, defaults to `False`):
74
+ Whether to replace stride with dilation in the last convolutional block (DC5). Only supported when `use_timm_backbone` = `True`.
75
+ class_cost (`float`, *optional*, defaults to 2):
76
+ Relative weight of the classification error in the Hungarian matching cost.
77
+ bbox_cost (`float`, *optional*, defaults to 5):
78
+ Relative weight of the L1 error of the bounding box coordinates in the Hungarian matching cost.
79
+ giou_cost (`float`, *optional*, defaults to 2):
80
+ Relative weight of the generalized IoU loss of the bounding box in the Hungarian matching cost.
81
+ cls_loss_coefficient (`float`, *optional*, defaults to 2):
82
+ Relative weight of the classification loss in the object detection loss function.
83
+ bbox_loss_coefficient (`float`, *optional*, defaults to 5):
84
+ Relative weight of the L1 bounding box loss in the object detection loss.
85
+ giou_loss_coefficient (`float`, *optional*, defaults to 2):
86
+ Relative weight of the generalized IoU loss in the object detection loss.
87
+ focal_alpha (`float`, *optional*, defaults to 0.25):
88
+ Alpha parameter in the focal loss.
89
+ temperature_height (`int`, *optional*, defaults to 20):
90
+ Temperature parameter to tune the flatness of positional attention (HEIGHT)
91
+ temperature_width (`int`, *optional*, defaults to 20):
92
+ Temperature parameter to tune the flatness of positional attention (WIDTH)
93
+ query_dim (`int`, *optional*, defaults to 4):
94
+ Query dimension parameter represents the size of the output vector.
95
+ random_refpoints_xy (`bool`, *optional*, defaults to `False`):
96
+ Whether to fix the x and y coordinates of the anchor boxes with random initialization.
97
+ keep_query_pos (`bool`, *optional*, defaults to `False`):
98
+ Whether to concatenate the projected positional embedding from the object query into the original query (key) in every decoder layer.
99
+ num_patterns (`int`, *optional*, defaults to 0):
100
+ Number of pattern embeddings.
101
+ normalize_before (`bool`, *optional*, defaults to `False`):
102
+ Whether we use a normalization layer in the Encoder or not.
103
+ sine_position_embedding_scale (`float`, *optional*, defaults to 'None'):
104
+ Scaling factor applied to the normalized positional encodings.
105
+ initializer_bias_prior_prob (`float`, *optional*):
106
+ The prior probability used by the bias initializer to initialize biases for `enc_score_head` and `class_embed`.
107
+ If `None`, `prior_prob` computed as `prior_prob = 1 / (num_labels + 1)` while initializing model weights.
108
+ tie_word_embeddings (`bool`, *optional*, defaults to `True`):
109
+ Whether to tie weight embeddings
110
+
111
+
112
+ Examples:
113
+
114
+ ```python
115
+ >>> from transformers import DabDetrConfig, DabDetrModel
116
+
117
+ >>> # Initializing a DAB-DETR IDEA-Research/dab_detr-base style configuration
118
+ >>> configuration = DabDetrConfig()
119
+
120
+ >>> # Initializing a model (with random weights) from the IDEA-Research/dab_detr-base style configuration
121
+ >>> model = DabDetrModel(configuration)
122
+
123
+ >>> # Accessing the model configuration
124
+ >>> configuration = model.config
125
+ ```"""
126
+
127
+ model_type = "dab-detr"
128
+ sub_configs = {"backbone_config": AutoConfig}
129
+ keys_to_ignore_at_inference = ["past_key_values"]
130
+ attribute_map = {
131
+ "num_attention_heads": "encoder_attention_heads",
132
+ }
133
+
134
+ def __init__(
135
+ self,
136
+ backbone_config=None,
137
+ num_queries=300,
138
+ encoder_layers=6,
139
+ encoder_ffn_dim=2048,
140
+ encoder_attention_heads=8,
141
+ decoder_layers=6,
142
+ decoder_ffn_dim=2048,
143
+ decoder_attention_heads=8,
144
+ is_encoder_decoder=True,
145
+ activation_function="prelu",
146
+ hidden_size=256,
147
+ dropout=0.1,
148
+ attention_dropout=0.0,
149
+ activation_dropout=0.0,
150
+ init_std=0.02,
151
+ init_xavier_std=1.0,
152
+ auxiliary_loss=False,
153
+ dilation=False,
154
+ class_cost=2,
155
+ bbox_cost=5,
156
+ giou_cost=2,
157
+ cls_loss_coefficient=2,
158
+ bbox_loss_coefficient=5,
159
+ giou_loss_coefficient=2,
160
+ focal_alpha=0.25,
161
+ temperature_height=20,
162
+ temperature_width=20,
163
+ query_dim=4,
164
+ random_refpoints_xy=False,
165
+ keep_query_pos=False,
166
+ num_patterns=0,
167
+ normalize_before=False,
168
+ sine_position_embedding_scale=None,
169
+ initializer_bias_prior_prob=None,
170
+ tie_word_embeddings=True,
171
+ **kwargs,
172
+ ):
173
+ if query_dim != 4:
174
+ raise ValueError("The query dimensions has to be 4.")
175
+
176
+ # Init timm backbone with hardcoded values for BC
177
+ timm_default_kwargs = {
178
+ "num_channels": 3,
179
+ "features_only": True,
180
+ "use_pretrained_backbone": False,
181
+ "out_indices": [1, 2, 3, 4],
182
+ }
183
+ if dilation:
184
+ timm_default_kwargs["output_stride"] = 16
185
+
186
+ backbone_config, kwargs = consolidate_backbone_kwargs_to_config(
187
+ backbone_config=backbone_config,
188
+ default_backbone="resnet50",
189
+ default_config_type="resnet50",
190
+ default_config_kwargs={"out_features": ["stage4"]},
191
+ timm_default_kwargs=timm_default_kwargs,
192
+ **kwargs,
193
+ )
194
+
195
+ self.backbone_config = backbone_config
196
+ self.num_queries = num_queries
197
+ self.hidden_size = hidden_size
198
+ self.encoder_ffn_dim = encoder_ffn_dim
199
+ self.encoder_layers = encoder_layers
200
+ self.encoder_attention_heads = encoder_attention_heads
201
+ self.decoder_ffn_dim = decoder_ffn_dim
202
+ self.decoder_layers = decoder_layers
203
+ self.decoder_attention_heads = decoder_attention_heads
204
+ self.dropout = dropout
205
+ self.attention_dropout = attention_dropout
206
+ self.activation_dropout = activation_dropout
207
+ self.activation_function = activation_function
208
+ self.init_std = init_std
209
+ self.init_xavier_std = init_xavier_std
210
+ self.num_hidden_layers = encoder_layers
211
+ self.auxiliary_loss = auxiliary_loss
212
+ # Hungarian matcher
213
+ self.class_cost = class_cost
214
+ self.bbox_cost = bbox_cost
215
+ self.giou_cost = giou_cost
216
+ # Loss coefficients
217
+ self.cls_loss_coefficient = cls_loss_coefficient
218
+ self.bbox_loss_coefficient = bbox_loss_coefficient
219
+ self.giou_loss_coefficient = giou_loss_coefficient
220
+ self.focal_alpha = focal_alpha
221
+ self.query_dim = query_dim
222
+ self.random_refpoints_xy = random_refpoints_xy
223
+ self.keep_query_pos = keep_query_pos
224
+ self.num_patterns = num_patterns
225
+ self.normalize_before = normalize_before
226
+ self.temperature_width = temperature_width
227
+ self.temperature_height = temperature_height
228
+ self.sine_position_embedding_scale = sine_position_embedding_scale
229
+ self.initializer_bias_prior_prob = initializer_bias_prior_prob
230
+ self.tie_word_embeddings = tie_word_embeddings
231
+
232
+ super().__init__(is_encoder_decoder=is_encoder_decoder, **kwargs)
233
+
234
+
235
+ __all__ = ["DabDetrConfig"]
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/dab_detr/modeling_dab_detr.py ADDED
@@ -0,0 +1,1598 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 IDEA Research and 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
+ """PyTorch DAB-DETR model."""
15
+
16
+ import math
17
+ from dataclasses import dataclass
18
+
19
+ import torch
20
+ from torch import Tensor, nn
21
+
22
+ from ... import initialization as init
23
+ from ...activations import ACT2FN
24
+ from ...backbone_utils import load_backbone
25
+ from ...masking_utils import create_bidirectional_mask
26
+ from ...modeling_layers import GradientCheckpointingLayer
27
+ from ...modeling_outputs import BaseModelOutput, BaseModelOutputWithCrossAttentions, Seq2SeqModelOutput
28
+ from ...modeling_utils import PreTrainedModel
29
+ from ...utils import (
30
+ ModelOutput,
31
+ auto_docstring,
32
+ logging,
33
+ )
34
+ from .configuration_dab_detr import DabDetrConfig
35
+
36
+
37
+ logger = logging.get_logger(__name__)
38
+
39
+
40
+ @dataclass
41
+ @auto_docstring(
42
+ custom_intro="""
43
+ Base class for outputs of the Conditional DETR decoder. This class adds one attribute to
44
+ BaseModelOutputWithCrossAttentions, namely an optional stack of intermediate decoder activations, i.e. the output
45
+ of each decoder layer, each of them gone through a layernorm. This is useful when training the model with auxiliary
46
+ decoding losses.
47
+ """
48
+ )
49
+ # Copied from transformers.models.conditional_detr.modeling_conditional_detr.ConditionalDetrDecoderOutput with ConditionalDetr->DabDetr,Conditional DETR->DAB-DETR,2 (anchor points)->4 (anchor points)
50
+ class DabDetrDecoderOutput(BaseModelOutputWithCrossAttentions):
51
+ r"""
52
+ cross_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` and `config.add_cross_attention=True` is passed or when `config.output_attentions=True`):
53
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
54
+ sequence_length)`. Attentions weights of the decoder's cross-attention layer, after the attention softmax,
55
+ used to compute the weighted average in the cross-attention heads.
56
+ intermediate_hidden_states (`torch.FloatTensor` of shape `(config.decoder_layers, batch_size, num_queries, hidden_size)`, *optional*, returned when `config.auxiliary_loss=True`):
57
+ Intermediate decoder activations, i.e. the output of each decoder layer, each of them gone through a
58
+ layernorm.
59
+ reference_points (`torch.FloatTensor` of shape `(config.decoder_layers, batch_size, num_queries, 2 (anchor points))`):
60
+ Reference points (reference points of each layer of the decoder).
61
+ """
62
+
63
+ intermediate_hidden_states: torch.FloatTensor | None = None
64
+ reference_points: tuple[torch.FloatTensor] | None = None
65
+
66
+
67
+ @dataclass
68
+ @auto_docstring(
69
+ custom_intro="""
70
+ Base class for outputs of the Conditional DETR encoder-decoder model. This class adds one attribute to
71
+ Seq2SeqModelOutput, namely an optional stack of intermediate decoder activations, i.e. the output of each decoder
72
+ layer, each of them gone through a layernorm. This is useful when training the model with auxiliary decoding
73
+ losses.
74
+ """
75
+ )
76
+ # Copied from transformers.models.conditional_detr.modeling_conditional_detr.ConditionalDetrModelOutput with ConditionalDetr->DabDetr,Conditional DETR->DAB-DETR,2 (anchor points)->4 (anchor points)
77
+ class DabDetrModelOutput(Seq2SeqModelOutput):
78
+ r"""
79
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
80
+ Sequence of hidden-states at the output of the last layer of the decoder of the model.
81
+ intermediate_hidden_states (`torch.FloatTensor` of shape `(config.decoder_layers, batch_size, sequence_length, hidden_size)`, *optional*, returned when `config.auxiliary_loss=True`):
82
+ Intermediate decoder activations, i.e. the output of each decoder layer, each of them gone through a
83
+ layernorm.
84
+ reference_points (`torch.FloatTensor` of shape `(config.decoder_layers, batch_size, num_queries, 2 (anchor points))`):
85
+ Reference points (reference points of each layer of the decoder).
86
+ """
87
+
88
+ intermediate_hidden_states: torch.FloatTensor | None = None
89
+ reference_points: tuple[torch.FloatTensor] | None = None
90
+
91
+
92
+ @dataclass
93
+ @auto_docstring(
94
+ custom_intro="""
95
+ Output type of [`DabDetrForObjectDetection`].
96
+ """
97
+ )
98
+ # Copied from transformers.models.detr.modeling_detr.DetrObjectDetectionOutput with Detr->DabDetr
99
+ class DabDetrObjectDetectionOutput(ModelOutput):
100
+ r"""
101
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` are provided)):
102
+ Total loss as a linear combination of a negative log-likehood (cross-entropy) for class prediction and a
103
+ bounding box loss. The latter is defined as a linear combination of the L1 loss and the generalized
104
+ scale-invariant IoU loss.
105
+ loss_dict (`Dict`, *optional*):
106
+ A dictionary containing the individual losses. Useful for logging.
107
+ logits (`torch.FloatTensor` of shape `(batch_size, num_queries, num_classes + 1)`):
108
+ Classification logits (including no-object) for all queries.
109
+ pred_boxes (`torch.FloatTensor` of shape `(batch_size, num_queries, 4)`):
110
+ Normalized boxes coordinates for all queries, represented as (center_x, center_y, width, height). These
111
+ values are normalized in [0, 1], relative to the size of each individual image in the batch (disregarding
112
+ possible padding). You can use [`~DabDetrImageProcessor.post_process_object_detection`] to retrieve the
113
+ unnormalized bounding boxes.
114
+ auxiliary_outputs (`list[Dict]`, *optional*):
115
+ Optional, only returned when auxiliary losses are activated (i.e. `config.auxiliary_loss` is set to `True`)
116
+ and labels are provided. It is a list of dictionaries containing the two above keys (`logits` and
117
+ `pred_boxes`) for each decoder layer.
118
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
119
+ Sequence of hidden-states at the output of the last layer of the decoder of the model.
120
+ """
121
+
122
+ loss: torch.FloatTensor | None = None
123
+ loss_dict: dict | None = None
124
+ logits: torch.FloatTensor | None = None
125
+ pred_boxes: torch.FloatTensor | None = None
126
+ auxiliary_outputs: list[dict] | None = None
127
+ last_hidden_state: torch.FloatTensor | None = None
128
+ decoder_hidden_states: tuple[torch.FloatTensor] | None = None
129
+ decoder_attentions: tuple[torch.FloatTensor] | None = None
130
+ cross_attentions: tuple[torch.FloatTensor] | None = None
131
+ encoder_last_hidden_state: torch.FloatTensor | None = None
132
+ encoder_hidden_states: tuple[torch.FloatTensor] | None = None
133
+ encoder_attentions: tuple[torch.FloatTensor] | None = None
134
+
135
+
136
+ # Copied from transformers.models.detr.modeling_detr.DetrFrozenBatchNorm2d with Detr->DabDetr
137
+ class DabDetrFrozenBatchNorm2d(nn.Module):
138
+ """
139
+ BatchNorm2d where the batch statistics and the affine parameters are fixed.
140
+
141
+ Copy-paste from torchvision.misc.ops with added eps before rqsrt, without which any other models than
142
+ torchvision.models.resnet[18,34,50,101] produce nans.
143
+ """
144
+
145
+ def __init__(self, n):
146
+ super().__init__()
147
+ self.register_buffer("weight", torch.ones(n))
148
+ self.register_buffer("bias", torch.zeros(n))
149
+ self.register_buffer("running_mean", torch.zeros(n))
150
+ self.register_buffer("running_var", torch.ones(n))
151
+
152
+ def _load_from_state_dict(
153
+ self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs
154
+ ):
155
+ num_batches_tracked_key = prefix + "num_batches_tracked"
156
+ if num_batches_tracked_key in state_dict:
157
+ del state_dict[num_batches_tracked_key]
158
+
159
+ super()._load_from_state_dict(
160
+ state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs
161
+ )
162
+
163
+ def forward(self, x):
164
+ # move reshapes to the beginning
165
+ # to make it user-friendly
166
+ weight = self.weight.reshape(1, -1, 1, 1)
167
+ bias = self.bias.reshape(1, -1, 1, 1)
168
+ running_var = self.running_var.reshape(1, -1, 1, 1)
169
+ running_mean = self.running_mean.reshape(1, -1, 1, 1)
170
+ epsilon = 1e-5
171
+ scale = weight * (running_var + epsilon).rsqrt()
172
+ bias = bias - running_mean * scale
173
+ return x * scale + bias
174
+
175
+
176
+ # Copied from transformers.models.detr.modeling_detr.replace_batch_norm with Detr->DabDetr
177
+ def replace_batch_norm(model):
178
+ r"""
179
+ Recursively replace all `torch.nn.BatchNorm2d` with `DabDetrFrozenBatchNorm2d`.
180
+
181
+ Args:
182
+ model (torch.nn.Module):
183
+ input model
184
+ """
185
+ for name, module in model.named_children():
186
+ if isinstance(module, nn.BatchNorm2d):
187
+ new_module = DabDetrFrozenBatchNorm2d(module.num_features)
188
+
189
+ if module.weight.device != torch.device("meta"):
190
+ new_module.weight.copy_(module.weight)
191
+ new_module.bias.copy_(module.bias)
192
+ new_module.running_mean.copy_(module.running_mean)
193
+ new_module.running_var.copy_(module.running_var)
194
+
195
+ model._modules[name] = new_module
196
+
197
+ if len(list(module.children())) > 0:
198
+ replace_batch_norm(module)
199
+
200
+
201
+ # Modified from transformers.models.detr.modeling_detr.DetrConvEncoder with Detr->DabDetr
202
+ class DabDetrConvEncoder(nn.Module):
203
+ """
204
+ Convolutional backbone, using either the AutoBackbone API or one from the timm library.
205
+
206
+ nn.BatchNorm2d layers are replaced by DabDetrFrozenBatchNorm2d as defined above.
207
+
208
+ """
209
+
210
+ def __init__(self, config: DabDetrConfig):
211
+ super().__init__()
212
+
213
+ self.config = config
214
+ backbone = load_backbone(config)
215
+
216
+ # replace batch norm by frozen batch norm
217
+ with torch.no_grad():
218
+ replace_batch_norm(backbone)
219
+ self.model = backbone
220
+ self.intermediate_channel_sizes = self.model.channels
221
+
222
+ def forward(self, pixel_values: torch.Tensor, pixel_mask: torch.Tensor):
223
+ # send pixel_values through the model to get list of feature maps
224
+ features = self.model(pixel_values).feature_maps
225
+
226
+ out = []
227
+ for feature_map in features:
228
+ # downsample pixel_mask to match shape of corresponding feature_map
229
+ mask = nn.functional.interpolate(pixel_mask[None].float(), size=feature_map.shape[-2:]).to(torch.bool)[0]
230
+ out.append((feature_map, mask))
231
+ return out
232
+
233
+
234
+ # TODO: use modular - Copied from transformers.models.detr.modeling_detr.DetrConvModel with Detr->DabDetr
235
+ class DabDetrConvModel(nn.Module):
236
+ """
237
+ This module adds 2D position embeddings to all intermediate feature maps of the convolutional encoder.
238
+ """
239
+
240
+ def __init__(self, conv_encoder, position_embedding):
241
+ super().__init__()
242
+ self.conv_encoder = conv_encoder
243
+ self.position_embedding = position_embedding
244
+
245
+ def forward(self, pixel_values, pixel_mask):
246
+ # send pixel_values and pixel_mask through backbone to get list of (feature_map, pixel_mask) tuples
247
+ out = self.conv_encoder(pixel_values, pixel_mask)
248
+ pos = []
249
+ for feature_map, mask in out:
250
+ # position encoding
251
+ pos.append(self.position_embedding(feature_map, mask).to(feature_map.dtype))
252
+
253
+ return out, pos
254
+
255
+
256
+ # Modified from transformers.models.conditional_detr.modeling_conditional_detr.ConditionalDetrSinePositionEmbedding with ConditionalDetr->DabDetr
257
+ class DabDetrSinePositionEmbedding(nn.Module):
258
+ """
259
+ This is a more standard version of the position embedding, very similar to the one used by the Attention is all you
260
+ need paper, generalized to work on images.
261
+ """
262
+
263
+ def __init__(self, config: DabDetrConfig):
264
+ super().__init__()
265
+ self.config = config
266
+ self.embedding_dim = config.hidden_size / 2
267
+ self.temperature_height = config.temperature_height
268
+ self.temperature_width = config.temperature_width
269
+ scale = config.sine_position_embedding_scale
270
+ if scale is None:
271
+ scale = 2 * math.pi
272
+ self.scale = scale
273
+
274
+ def forward(self, pixel_values, pixel_mask):
275
+ if pixel_mask is None:
276
+ raise ValueError("No pixel mask provided")
277
+ y_embed = pixel_mask.cumsum(1, dtype=torch.float32)
278
+ x_embed = pixel_mask.cumsum(2, dtype=torch.float32)
279
+ y_embed = y_embed / (y_embed[:, -1:, :] + 1e-6) * self.scale
280
+ x_embed = x_embed / (x_embed[:, :, -1:] + 1e-6) * self.scale
281
+
282
+ # We use float32 to ensure reproducibility of the original implementation
283
+ dim_tx = torch.arange(self.embedding_dim, dtype=torch.float32, device=pixel_values.device)
284
+ # Modifying dim_tx in place to avoid extra memory allocation -> dim_tx = self.temperature_width ** (2 * (dim_tx // 2) / self.embedding_dim)
285
+ dim_tx //= 2
286
+ dim_tx.mul_(2 / self.embedding_dim)
287
+ dim_tx.copy_(self.temperature_width**dim_tx)
288
+ pos_x = x_embed[:, :, :, None] / dim_tx
289
+
290
+ # We use float32 to ensure reproducibility of the original implementation
291
+ dim_ty = torch.arange(self.embedding_dim, dtype=torch.float32, device=pixel_values.device)
292
+ # Modifying dim_ty in place to avoid extra memory allocation -> dim_ty = self.temperature_height ** (2 * (dim_ty // 2) / self.embedding_dim)
293
+ dim_ty //= 2
294
+ dim_ty.mul_(2 / self.embedding_dim)
295
+ dim_ty.copy_(self.temperature_height**dim_ty)
296
+ pos_y = y_embed[:, :, :, None] / dim_ty
297
+
298
+ pos_x = torch.stack((pos_x[:, :, :, 0::2].sin(), pos_x[:, :, :, 1::2].cos()), dim=4).flatten(3)
299
+ pos_y = torch.stack((pos_y[:, :, :, 0::2].sin(), pos_y[:, :, :, 1::2].cos()), dim=4).flatten(3)
300
+ pos = torch.cat((pos_y, pos_x), dim=3).permute(0, 3, 1, 2)
301
+ return pos
302
+
303
+
304
+ # function to generate sine positional embedding for 4d coordinates
305
+ def gen_sine_position_embeddings(pos_tensor, hidden_size=256):
306
+ """
307
+ This function computes position embeddings using sine and cosine functions from the input positional tensor,
308
+ which has a shape of (batch_size, num_queries, 4).
309
+ The last dimension of `pos_tensor` represents the following coordinates:
310
+ - 0: x-coord
311
+ - 1: y-coord
312
+ - 2: width
313
+ - 3: height
314
+
315
+ The output shape is (batch_size, num_queries, 512), where final dim (hidden_size*2 = 512) is the total embedding dimension
316
+ achieved by concatenating the sine and cosine values for each coordinate.
317
+ """
318
+ scale = 2 * math.pi
319
+ dim = hidden_size // 2
320
+ dim_t = torch.arange(dim, dtype=torch.float32, device=pos_tensor.device)
321
+ dim_t = 10000 ** (2 * torch.div(dim_t, 2, rounding_mode="floor") / dim)
322
+ x_embed = pos_tensor[:, :, 0] * scale
323
+ y_embed = pos_tensor[:, :, 1] * scale
324
+ pos_x = x_embed[:, :, None] / dim_t
325
+ pos_y = y_embed[:, :, None] / dim_t
326
+ pos_x = torch.stack((pos_x[:, :, 0::2].sin(), pos_x[:, :, 1::2].cos()), dim=3).flatten(2)
327
+ pos_y = torch.stack((pos_y[:, :, 0::2].sin(), pos_y[:, :, 1::2].cos()), dim=3).flatten(2)
328
+ if pos_tensor.size(-1) == 4:
329
+ w_embed = pos_tensor[:, :, 2] * scale
330
+ pos_w = w_embed[:, :, None] / dim_t
331
+ pos_w = torch.stack((pos_w[:, :, 0::2].sin(), pos_w[:, :, 1::2].cos()), dim=3).flatten(2)
332
+
333
+ h_embed = pos_tensor[:, :, 3] * scale
334
+ pos_h = h_embed[:, :, None] / dim_t
335
+ pos_h = torch.stack((pos_h[:, :, 0::2].sin(), pos_h[:, :, 1::2].cos()), dim=3).flatten(2)
336
+
337
+ pos = torch.cat((pos_y, pos_x, pos_w, pos_h), dim=2)
338
+ else:
339
+ raise ValueError(f"Unknown pos_tensor shape(-1):{pos_tensor.size(-1)}")
340
+ return pos.to(pos_tensor.dtype)
341
+
342
+
343
+ def inverse_sigmoid(x, eps=1e-5):
344
+ x = x.clamp(min=0, max=1)
345
+ x1 = x.clamp(min=eps)
346
+ x2 = (1 - x).clamp(min=eps)
347
+ return torch.log(x1 / x2)
348
+
349
+
350
+ # Modified from transformers.models.detr.modeling_detr.DetrAttention
351
+ class DetrAttention(nn.Module):
352
+ """
353
+ Multi-headed attention from 'Attention Is All You Need' paper.
354
+
355
+ Here, we add position embeddings to the queries and keys (as explained in the DETR paper).
356
+ """
357
+
358
+ def __init__(
359
+ self,
360
+ config: DabDetrConfig,
361
+ bias: bool = True,
362
+ ):
363
+ super().__init__()
364
+ self.config = config
365
+ self.hidden_size = config.hidden_size
366
+ self.num_heads = config.encoder_attention_heads
367
+ self.attention_dropout = config.attention_dropout
368
+ self.head_dim = self.hidden_size // self.num_heads
369
+ if self.head_dim * self.num_heads != self.hidden_size:
370
+ raise ValueError(
371
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size} and `num_heads`:"
372
+ f" {self.num_heads})."
373
+ )
374
+ self.scaling = self.head_dim**-0.5
375
+ self.k_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=bias)
376
+ self.v_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=bias)
377
+ self.q_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=bias)
378
+ self.out_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=bias)
379
+
380
+ def forward(
381
+ self,
382
+ hidden_states: torch.Tensor,
383
+ attention_mask: torch.Tensor | None = None,
384
+ object_queries: torch.Tensor | None = None,
385
+ key_value_states: torch.Tensor | None = None,
386
+ output_attentions: bool = False,
387
+ ) -> tuple[torch.Tensor, torch.Tensor | None, tuple[torch.Tensor] | None]:
388
+ """Input shape: Batch x Time x Channel"""
389
+ batch_size, q_len, embed_dim = hidden_states.size()
390
+ # add position embeddings to the hidden states before projecting to queries and keys
391
+ if object_queries is not None:
392
+ hidden_states_original = hidden_states
393
+ hidden_states = hidden_states + object_queries
394
+
395
+ query_states = self.q_proj(hidden_states) * self.scaling
396
+ key_states = self.k_proj(hidden_states)
397
+ value_states = self.v_proj(hidden_states_original)
398
+
399
+ query_states = query_states.view(batch_size, q_len, self.num_heads, self.head_dim).transpose(1, 2)
400
+ key_states = key_states.view(batch_size, -1, self.num_heads, self.head_dim).transpose(1, 2)
401
+ value_states = value_states.view(batch_size, -1, self.num_heads, self.head_dim).transpose(1, 2)
402
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3))
403
+
404
+ if attention_mask is not None:
405
+ attn_weights = attn_weights + attention_mask
406
+
407
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
408
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
409
+ attn_output = torch.matmul(attn_weights, value_states)
410
+
411
+ if attn_output.size() != (batch_size, self.num_heads, q_len, self.head_dim):
412
+ raise ValueError(
413
+ f"`attn_output` should be of size {(batch_size, self.num_heads, q_len, self.head_dim)}, but is"
414
+ f" {attn_output.size()}"
415
+ )
416
+
417
+ attn_output = attn_output.transpose(1, 2).contiguous()
418
+
419
+ attn_output = attn_output.reshape(batch_size, q_len, embed_dim)
420
+ attn_output = self.out_proj(attn_output)
421
+
422
+ if not output_attentions:
423
+ attn_weights = None
424
+
425
+ return attn_output, attn_weights
426
+
427
+
428
+ # Modified from transformers.models.conditional_detr.modeling_conditional_detr.ConditionalDetrAttention with ConditionalDetr->DABDETR,Conditional DETR->DabDetr
429
+ class DabDetrAttention(nn.Module):
430
+ """
431
+ Cross-Attention used in DAB-DETR 'DAB-DETR for Fast Training Convergence' paper.
432
+
433
+ The key q_proj, k_proj, v_proj are defined outside the attention. This attention allows the dim of q, k to be
434
+ different to v.
435
+ """
436
+
437
+ def __init__(self, config: DabDetrConfig, bias: bool = True, is_cross: bool = False):
438
+ super().__init__()
439
+ self.config = config
440
+ self.embed_dim = config.hidden_size * 2 if is_cross else config.hidden_size
441
+ self.output_dim = config.hidden_size
442
+ self.attention_heads = config.decoder_attention_heads
443
+ self.attention_dropout = config.attention_dropout
444
+ self.attention_head_dim = self.embed_dim // self.attention_heads
445
+ if self.attention_head_dim * self.attention_heads != self.embed_dim:
446
+ raise ValueError(
447
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `attention_heads`:"
448
+ f" {self.attention_heads})."
449
+ )
450
+ # head dimension of values
451
+ self.values_head_dim = self.output_dim // self.attention_heads
452
+ if self.values_head_dim * self.attention_heads != self.output_dim:
453
+ raise ValueError(
454
+ f"output_dim must be divisible by attention_heads (got `output_dim`: {self.output_dim} and `attention_heads`: {self.attention_heads})."
455
+ )
456
+ self.scaling = self.attention_head_dim**-0.5
457
+ self.output_proj = nn.Linear(self.output_dim, self.output_dim, bias=bias)
458
+
459
+ def forward(
460
+ self,
461
+ hidden_states: torch.Tensor,
462
+ attention_mask: torch.Tensor | None = None,
463
+ key_states: torch.Tensor | None = None,
464
+ value_states: torch.Tensor | None = None,
465
+ output_attentions: bool | None = None,
466
+ ) -> tuple[torch.Tensor, torch.Tensor | None, tuple[torch.Tensor] | None]:
467
+ """Input shape: Batch x Time x Channel"""
468
+
469
+ batch_size, q_len, _ = hidden_states.size()
470
+
471
+ # scaling query and refactor key-, value states
472
+ query_states = hidden_states * self.scaling
473
+ query_states = query_states.view(batch_size, -1, self.attention_heads, self.attention_head_dim).transpose(1, 2)
474
+ key_states = key_states.view(batch_size, -1, self.attention_heads, self.attention_head_dim).transpose(1, 2)
475
+ value_states = value_states.view(batch_size, -1, self.attention_heads, self.values_head_dim).transpose(1, 2)
476
+
477
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3))
478
+
479
+ if attention_mask is not None:
480
+ attn_weights = attn_weights + attention_mask
481
+
482
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
483
+ attn_probs = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
484
+ attn_output = torch.matmul(attn_probs, value_states)
485
+
486
+ if attn_output.size() != (batch_size, self.attention_heads, q_len, self.values_head_dim):
487
+ raise ValueError(
488
+ f"`attn_output` should be of size {(batch_size, self.attention_heads, q_len, self.values_head_dim)}, but is"
489
+ f" {attn_output.size()}"
490
+ )
491
+
492
+ attn_output = attn_output.transpose(1, 2).contiguous()
493
+
494
+ attn_output = attn_output.reshape(batch_size, q_len, self.output_dim)
495
+ attn_output = self.output_proj(attn_output)
496
+
497
+ if not output_attentions:
498
+ attn_weights = None
499
+
500
+ return attn_output, attn_weights
501
+
502
+
503
+ class DabDetrDecoderLayerSelfAttention(nn.Module):
504
+ def __init__(self, config: DabDetrConfig):
505
+ super().__init__()
506
+ self.dropout = config.dropout
507
+ self.self_attn_query_content_proj = nn.Linear(config.hidden_size, config.hidden_size)
508
+ self.self_attn_query_pos_proj = nn.Linear(config.hidden_size, config.hidden_size)
509
+ self.self_attn_key_content_proj = nn.Linear(config.hidden_size, config.hidden_size)
510
+ self.self_attn_key_pos_proj = nn.Linear(config.hidden_size, config.hidden_size)
511
+ self.self_attn_value_proj = nn.Linear(config.hidden_size, config.hidden_size)
512
+ self.self_attn = DabDetrAttention(config)
513
+ self.self_attn_layer_norm = nn.LayerNorm(config.hidden_size)
514
+
515
+ def forward(
516
+ self,
517
+ hidden_states: torch.Tensor,
518
+ query_position_embeddings: torch.Tensor | None = None,
519
+ attention_mask: torch.Tensor | None = None,
520
+ output_attentions: bool | None = None,
521
+ ):
522
+ residual = hidden_states
523
+ query_content = self.self_attn_query_content_proj(hidden_states)
524
+ query_pos = self.self_attn_query_pos_proj(query_position_embeddings)
525
+ key_content = self.self_attn_key_content_proj(hidden_states)
526
+ key_pos = self.self_attn_key_pos_proj(query_position_embeddings)
527
+ value = self.self_attn_value_proj(hidden_states)
528
+
529
+ query = query_content + query_pos
530
+ key = key_content + key_pos
531
+
532
+ hidden_states, attn_weights = self.self_attn(
533
+ hidden_states=query,
534
+ attention_mask=attention_mask,
535
+ key_states=key,
536
+ value_states=value,
537
+ output_attentions=True,
538
+ )
539
+
540
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
541
+ hidden_states = residual + hidden_states
542
+ hidden_states = self.self_attn_layer_norm(hidden_states)
543
+
544
+ return hidden_states, attn_weights
545
+
546
+
547
+ class DabDetrDecoderLayerCrossAttention(nn.Module):
548
+ def __init__(self, config: DabDetrConfig, is_first: bool = False):
549
+ super().__init__()
550
+ hidden_size = config.hidden_size
551
+ self.cross_attn_query_content_proj = nn.Linear(hidden_size, hidden_size)
552
+ self.cross_attn_query_pos_proj = nn.Linear(hidden_size, hidden_size)
553
+ self.cross_attn_key_content_proj = nn.Linear(hidden_size, hidden_size)
554
+ self.cross_attn_key_pos_proj = nn.Linear(hidden_size, hidden_size)
555
+ self.cross_attn_value_proj = nn.Linear(hidden_size, hidden_size)
556
+ self.cross_attn_query_pos_sine_proj = nn.Linear(hidden_size, hidden_size)
557
+ self.decoder_attention_heads = config.decoder_attention_heads
558
+ self.cross_attn_layer_norm = nn.LayerNorm(hidden_size)
559
+ self.cross_attn = DabDetrAttention(config, is_cross=True)
560
+
561
+ self.keep_query_pos = config.keep_query_pos
562
+
563
+ if not self.keep_query_pos and not is_first:
564
+ self.cross_attn_query_pos_proj = None
565
+
566
+ self.is_first = is_first
567
+ self.dropout = config.dropout
568
+
569
+ def forward(
570
+ self,
571
+ hidden_states: torch.Tensor,
572
+ encoder_hidden_states: torch.Tensor | None = None,
573
+ query_position_embeddings: torch.Tensor | None = None,
574
+ object_queries: torch.Tensor | None = None,
575
+ encoder_attention_mask: torch.Tensor | None = None,
576
+ query_sine_embed: torch.Tensor | None = None,
577
+ output_attentions: bool | None = None,
578
+ ):
579
+ query_content = self.cross_attn_query_content_proj(hidden_states)
580
+ key_content = self.cross_attn_key_content_proj(encoder_hidden_states)
581
+ value = self.cross_attn_value_proj(encoder_hidden_states)
582
+
583
+ batch_size, num_queries, n_model = query_content.shape
584
+ _, height_width, _ = key_content.shape
585
+
586
+ key_pos = self.cross_attn_key_pos_proj(object_queries)
587
+
588
+ # For the first decoder layer, we add the positional embedding predicted from
589
+ # the object query (the positional embedding) into the original query (key) in DETR.
590
+ if self.is_first or self.keep_query_pos:
591
+ query_pos = self.cross_attn_query_pos_proj(query_position_embeddings)
592
+ query = query_content + query_pos
593
+ key = key_content + key_pos
594
+ else:
595
+ query = query_content
596
+ key = key_content
597
+
598
+ query = query.view(
599
+ batch_size, num_queries, self.decoder_attention_heads, n_model // self.decoder_attention_heads
600
+ )
601
+ query_sine_embed = self.cross_attn_query_pos_sine_proj(query_sine_embed)
602
+ query_sine_embed = query_sine_embed.view(
603
+ batch_size, num_queries, self.decoder_attention_heads, n_model // self.decoder_attention_heads
604
+ )
605
+ query = torch.cat([query, query_sine_embed], dim=3).view(batch_size, num_queries, n_model * 2)
606
+ key = key.view(batch_size, height_width, self.decoder_attention_heads, n_model // self.decoder_attention_heads)
607
+ key_pos = key_pos.view(
608
+ batch_size, height_width, self.decoder_attention_heads, n_model // self.decoder_attention_heads
609
+ )
610
+ key = torch.cat([key, key_pos], dim=3).view(batch_size, height_width, n_model * 2)
611
+
612
+ # Cross-Attention Block
613
+ cross_attn_weights = None
614
+ if encoder_hidden_states is not None:
615
+ residual = hidden_states
616
+
617
+ hidden_states, cross_attn_weights = self.cross_attn(
618
+ hidden_states=query,
619
+ attention_mask=encoder_attention_mask,
620
+ key_states=key,
621
+ value_states=value,
622
+ output_attentions=output_attentions,
623
+ )
624
+
625
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
626
+ hidden_states = residual + hidden_states
627
+ hidden_states = self.cross_attn_layer_norm(hidden_states)
628
+
629
+ return hidden_states, cross_attn_weights
630
+
631
+
632
+ class DabDetrDecoderLayerFFN(nn.Module):
633
+ def __init__(self, config: DabDetrConfig):
634
+ super().__init__()
635
+ hidden_size = config.hidden_size
636
+ self.final_layer_norm = nn.LayerNorm(hidden_size)
637
+ self.fc1 = nn.Linear(hidden_size, config.decoder_ffn_dim)
638
+ self.fc2 = nn.Linear(config.decoder_ffn_dim, hidden_size)
639
+ self.activation_fn = ACT2FN[config.activation_function]
640
+ self.dropout = config.dropout
641
+ self.activation_dropout = config.activation_dropout
642
+ self.keep_query_pos = config.keep_query_pos
643
+
644
+ def forward(self, hidden_states: torch.Tensor):
645
+ residual = hidden_states
646
+ hidden_states = self.activation_fn(self.fc1(hidden_states))
647
+ hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
648
+ hidden_states = self.fc2(hidden_states)
649
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
650
+ hidden_states = residual + hidden_states
651
+ hidden_states = self.final_layer_norm(hidden_states)
652
+
653
+ return hidden_states
654
+
655
+
656
+ # Modified from transformers.models.detr.modeling_detr.DetrEncoderLayer with DetrEncoderLayer->DabDetrEncoderLayer,DetrConfig->DabDetrConfig
657
+ class DabDetrEncoderLayer(GradientCheckpointingLayer):
658
+ def __init__(self, config: DabDetrConfig):
659
+ super().__init__()
660
+ self.hidden_size = config.hidden_size
661
+ self.self_attn = DetrAttention(config)
662
+ self.self_attn_layer_norm = nn.LayerNorm(self.hidden_size)
663
+ self.dropout = config.dropout
664
+ self.activation_fn = ACT2FN[config.activation_function]
665
+ self.fc1 = nn.Linear(self.hidden_size, config.encoder_ffn_dim)
666
+ self.fc2 = nn.Linear(config.encoder_ffn_dim, self.hidden_size)
667
+ self.final_layer_norm = nn.LayerNorm(self.hidden_size)
668
+
669
+ def forward(
670
+ self,
671
+ hidden_states: torch.Tensor,
672
+ attention_mask: torch.Tensor,
673
+ object_queries: torch.Tensor,
674
+ output_attentions: bool | None = None,
675
+ ):
676
+ """
677
+ Args:
678
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(seq_len, batch, embed_dim)`
679
+ attention_mask (`torch.FloatTensor`): attention mask of size
680
+ `(batch, source_len)` where padding elements are indicated by very large negative
681
+ values.
682
+ object_queries (`torch.FloatTensor`, *optional*):
683
+ Object queries (also called content embeddings), to be added to the hidden states.
684
+ output_attentions (`bool`, *optional*):
685
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
686
+ returned tensors for more detail.
687
+ """
688
+ residual = hidden_states
689
+ hidden_states, attn_weights = self.self_attn(
690
+ hidden_states=hidden_states,
691
+ attention_mask=attention_mask,
692
+ object_queries=object_queries,
693
+ output_attentions=output_attentions,
694
+ )
695
+
696
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
697
+ hidden_states = residual + hidden_states
698
+ hidden_states = self.self_attn_layer_norm(hidden_states)
699
+
700
+ residual = hidden_states
701
+ hidden_states = self.activation_fn(self.fc1(hidden_states))
702
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
703
+
704
+ hidden_states = self.fc2(hidden_states)
705
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
706
+
707
+ hidden_states = residual + hidden_states
708
+ hidden_states = self.final_layer_norm(hidden_states)
709
+
710
+ outputs = (hidden_states,)
711
+
712
+ if output_attentions:
713
+ outputs += (attn_weights,)
714
+
715
+ return outputs
716
+
717
+
718
+ # Modified from transformers.models.conditional_detr.modeling_conditional_detr.ConditionalDetrDecoderLayer with ConditionalDetr->DabDetr
719
+ class DabDetrDecoderLayer(GradientCheckpointingLayer):
720
+ def __init__(self, config: DabDetrConfig, is_first: bool = False):
721
+ super().__init__()
722
+ self.self_attn = DabDetrDecoderLayerSelfAttention(config)
723
+ self.cross_attn = DabDetrDecoderLayerCrossAttention(config, is_first)
724
+ self.mlp = DabDetrDecoderLayerFFN(config)
725
+
726
+ def forward(
727
+ self,
728
+ hidden_states: torch.Tensor,
729
+ attention_mask: torch.Tensor | None = None,
730
+ object_queries: torch.Tensor | None = None,
731
+ query_position_embeddings: torch.Tensor | None = None,
732
+ query_sine_embed: torch.Tensor | None = None,
733
+ encoder_hidden_states: torch.Tensor | None = None,
734
+ encoder_attention_mask: torch.Tensor | None = None,
735
+ output_attentions: bool | None = None,
736
+ ):
737
+ """
738
+ Args:
739
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(seq_len, batch, embed_dim)`
740
+ attention_mask (`torch.FloatTensor`): attention mask of size
741
+ `(batch, 1, target_len, source_len)` where padding elements are indicated by very large negative
742
+ values.
743
+ object_queries (`torch.FloatTensor`, *optional*):
744
+ object_queries that are added to the queries and keys
745
+ in the cross-attention layer.
746
+ query_position_embeddings (`torch.FloatTensor`, *optional*):
747
+ object_queries that are added to the queries and keys
748
+ in the self-attention layer.
749
+ encoder_hidden_states (`torch.FloatTensor`):
750
+ cross attention input to the layer of shape `(seq_len, batch, embed_dim)`
751
+ encoder_attention_mask (`torch.FloatTensor`): encoder attention mask of size
752
+ `(batch, 1, target_len, source_len)` where padding elements are indicated by very large negative
753
+ values.
754
+ output_attentions (`bool`, *optional*):
755
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
756
+ returned tensors for more detail.
757
+
758
+ """
759
+ hidden_states, self_attn_weights = self.self_attn(
760
+ hidden_states=hidden_states,
761
+ query_position_embeddings=query_position_embeddings,
762
+ attention_mask=attention_mask,
763
+ output_attentions=output_attentions,
764
+ )
765
+
766
+ hidden_states, cross_attn_weights = self.cross_attn(
767
+ hidden_states=hidden_states,
768
+ encoder_hidden_states=encoder_hidden_states,
769
+ query_position_embeddings=query_position_embeddings,
770
+ object_queries=object_queries,
771
+ encoder_attention_mask=encoder_attention_mask,
772
+ query_sine_embed=query_sine_embed,
773
+ output_attentions=output_attentions,
774
+ )
775
+
776
+ hidden_states = self.mlp(hidden_states=hidden_states)
777
+
778
+ outputs = (hidden_states,)
779
+
780
+ if output_attentions:
781
+ outputs += (self_attn_weights, cross_attn_weights)
782
+
783
+ return outputs
784
+
785
+
786
+ # Modified from transformers.models.detr.modeling_detr.DetrMLPPredictionHead with DetrMLPPredictionHead->DabDetrMLP
787
+ class DabDetrMLP(nn.Module):
788
+ """
789
+ Very simple multi-layer perceptron (MLP, also called FFN), used to predict the normalized center coordinates,
790
+ height and width of a bounding box w.r.t. an image.
791
+
792
+ Copied from https://github.com/facebookresearch/detr/blob/master/models/detr.py
793
+
794
+ """
795
+
796
+ def __init__(self, input_dim, hidden_dim, output_dim, num_layers):
797
+ super().__init__()
798
+ self.num_layers = num_layers
799
+ h = [hidden_dim] * (num_layers - 1)
800
+ self.layers = nn.ModuleList(nn.Linear(n, k) for n, k in zip([input_dim] + h, h + [output_dim]))
801
+
802
+ def forward(self, input_tensor):
803
+ for i, layer in enumerate(self.layers):
804
+ input_tensor = nn.functional.relu(layer(input_tensor)) if i < self.num_layers - 1 else layer(input_tensor)
805
+ return input_tensor
806
+
807
+
808
+ # Modified from transformers.models.detr.modeling_detr.DetrPreTrainedModel with Detr->DabDetr
809
+ @auto_docstring
810
+ class DabDetrPreTrainedModel(PreTrainedModel):
811
+ config: DabDetrConfig
812
+ base_model_prefix = "model"
813
+ main_input_name = "pixel_values"
814
+ input_modalities = ("image",)
815
+ _no_split_modules = [r"DabDetrConvEncoder", r"DabDetrEncoderLayer", r"DabDetrDecoderLayer"]
816
+
817
+ @torch.no_grad()
818
+ def _init_weights(self, module):
819
+ std = self.config.init_std
820
+ xavier_std = self.config.init_xavier_std
821
+
822
+ if isinstance(module, DabDetrMHAttentionMap):
823
+ init.zeros_(module.k_linear.bias)
824
+ init.zeros_(module.q_linear.bias)
825
+ init.xavier_uniform_(module.k_linear.weight, gain=xavier_std)
826
+ init.xavier_uniform_(module.q_linear.weight, gain=xavier_std)
827
+ if isinstance(module, (nn.Linear, nn.Conv2d)):
828
+ init.normal_(module.weight, mean=0.0, std=std)
829
+ if module.bias is not None:
830
+ init.zeros_(module.bias)
831
+ elif isinstance(module, nn.LayerNorm):
832
+ init.ones_(module.weight)
833
+ init.zeros_(module.bias)
834
+ elif isinstance(module, nn.Embedding):
835
+ init.normal_(module.weight, mean=0.0, std=std)
836
+ # Here we need the check explicitly, as we slice the weight in the `zeros_` call, so it looses the flag
837
+ if module.padding_idx is not None and not getattr(module.weight, "_is_hf_initialized", False):
838
+ init.zeros_(module.weight[module.padding_idx])
839
+ elif isinstance(module, DabDetrForObjectDetection):
840
+ init.constant_(module.bbox_predictor.layers[-1].weight, 0)
841
+ init.constant_(module.bbox_predictor.layers[-1].bias, 0)
842
+
843
+ # init prior_prob setting for focal loss
844
+ prior_prob = self.config.initializer_bias_prior_prob or 1 / (self.config.num_labels + 1)
845
+ bias_value = -math.log((1 - prior_prob) / prior_prob)
846
+ init.constant_(module.class_embed.bias, bias_value)
847
+ elif isinstance(module, nn.PReLU):
848
+ module.reset_parameters()
849
+
850
+
851
+ # Modified from transformers.models.detr.modeling_detr.DetrEncoder with Detr->DabDetr,DETR->ConditionalDETR
852
+ class DabDetrEncoder(DabDetrPreTrainedModel):
853
+ """
854
+ Transformer encoder consisting of *config.encoder_layers* self attention layers. Each layer is a
855
+ [`DabDetrEncoderLayer`].
856
+
857
+ The encoder updates the flattened feature map through multiple self-attention layers.
858
+
859
+ Small tweak for DAB-DETR:
860
+
861
+ - object_queries are added to the forward pass.
862
+
863
+ Args:
864
+ config: DabDetrConfig
865
+ """
866
+
867
+ def __init__(self, config: DabDetrConfig):
868
+ super().__init__(config)
869
+
870
+ self.dropout = config.dropout
871
+ self.query_scale = DabDetrMLP(config.hidden_size, config.hidden_size, config.hidden_size, 2)
872
+ self.layers = nn.ModuleList([DabDetrEncoderLayer(config) for _ in range(config.encoder_layers)])
873
+ self.norm = nn.LayerNorm(config.hidden_size) if config.normalize_before else None
874
+ self.gradient_checkpointing = False
875
+
876
+ # Initialize weights and apply final processing
877
+ self.post_init()
878
+
879
+ def forward(
880
+ self,
881
+ inputs_embeds,
882
+ attention_mask,
883
+ object_queries,
884
+ output_attentions: bool | None = None,
885
+ output_hidden_states: bool | None = None,
886
+ return_dict: bool | None = None,
887
+ **kwargs,
888
+ ):
889
+ r"""
890
+ Args:
891
+ inputs_embeds (`torch.FloatTensor` of shape `(sequence_length, batch_size, hidden_size)`):
892
+ Flattened feature map (output of the backbone + projection layer) that is passed to the encoder.
893
+
894
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
895
+ Mask to avoid performing attention on padding pixel features. Mask values selected in `[0, 1]`:
896
+
897
+ - 1 for pixel features that are real (i.e. **not masked**),
898
+ - 0 for pixel features that are padding (i.e. **masked**).
899
+
900
+ [What are attention masks?](../glossary#attention-mask)
901
+
902
+ object_queries (`torch.FloatTensor` of shape `(sequence_length, batch_size, hidden_size)`):
903
+ Object queries that are added to the queries in each self-attention layer.
904
+
905
+ output_attentions (`bool`, *optional*):
906
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
907
+ returned tensors for more detail.
908
+ output_hidden_states (`bool`, *optional*):
909
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
910
+ for more detail.
911
+ return_dict (`bool`, *optional*):
912
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
913
+ """
914
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
915
+ output_hidden_states = (
916
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
917
+ )
918
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
919
+
920
+ hidden_states = inputs_embeds
921
+
922
+ attention_mask = create_bidirectional_mask(
923
+ config=self.config,
924
+ inputs_embeds=inputs_embeds,
925
+ attention_mask=attention_mask,
926
+ )
927
+
928
+ encoder_states = () if output_hidden_states else None
929
+ all_attentions = () if output_attentions else None
930
+
931
+ for encoder_layer in self.layers:
932
+ if output_hidden_states:
933
+ encoder_states = encoder_states + (hidden_states,)
934
+ # pos scaler
935
+ pos_scales = self.query_scale(hidden_states)
936
+ # we add object_queries * pos_scaler as extra input to the encoder_layer
937
+ scaled_object_queries = object_queries * pos_scales
938
+
939
+ layer_outputs = encoder_layer(
940
+ hidden_states,
941
+ attention_mask=attention_mask,
942
+ object_queries=scaled_object_queries,
943
+ output_attentions=output_attentions,
944
+ )
945
+
946
+ hidden_states = layer_outputs[0]
947
+
948
+ if output_attentions:
949
+ all_attentions = all_attentions + (layer_outputs[1],)
950
+
951
+ if self.norm:
952
+ hidden_states = self.norm(hidden_states)
953
+
954
+ if output_hidden_states:
955
+ encoder_states = encoder_states + (hidden_states,)
956
+
957
+ if not return_dict:
958
+ return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
959
+ return BaseModelOutput(
960
+ last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions
961
+ )
962
+
963
+
964
+ # Modified from transformers.models.conditional_detr.modeling_conditional_detr.ConditionalDetrDecoder with ConditionalDetr->DabDetr,Conditional DETR->DAB-DETR
965
+ class DabDetrDecoder(DabDetrPreTrainedModel):
966
+ """
967
+ Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a [`DabDetrDecoderLayer`].
968
+
969
+ The decoder updates the query embeddings through multiple self-attention and cross-attention layers.
970
+
971
+ Some small tweaks for DAB-DETR:
972
+
973
+ - object_queries and query_position_embeddings are added to the forward pass.
974
+ - if self.config.auxiliary_loss is set to True, also returns a stack of activations from all decoding layers.
975
+
976
+ Args:
977
+ config: DabDetrConfig
978
+ """
979
+
980
+ def __init__(self, config: DabDetrConfig):
981
+ super().__init__(config)
982
+ self.config = config
983
+ self.dropout = config.dropout
984
+ self.num_layers = config.decoder_layers
985
+ self.gradient_checkpointing = False
986
+
987
+ self.layers = nn.ModuleList(
988
+ [DabDetrDecoderLayer(config, is_first=(layer_id == 0)) for layer_id in range(config.decoder_layers)]
989
+ )
990
+ # in DAB-DETR, the decoder uses layernorm after the last decoder layer output
991
+ self.hidden_size = config.hidden_size
992
+ self.layernorm = nn.LayerNorm(self.hidden_size)
993
+
994
+ # Default cond-elewise
995
+ self.query_scale = DabDetrMLP(self.hidden_size, self.hidden_size, self.hidden_size, 2)
996
+
997
+ self.ref_point_head = DabDetrMLP(
998
+ config.query_dim // 2 * self.hidden_size, self.hidden_size, self.hidden_size, 2
999
+ )
1000
+
1001
+ self.bbox_embed = None
1002
+
1003
+ # Default decoder_modulate_hw_attn is True
1004
+ self.ref_anchor_head = DabDetrMLP(self.hidden_size, self.hidden_size, 2, 2)
1005
+
1006
+ # Initialize weights and apply final processing
1007
+ self.post_init()
1008
+
1009
+ def forward(
1010
+ self,
1011
+ inputs_embeds,
1012
+ encoder_hidden_states,
1013
+ memory_key_padding_mask,
1014
+ object_queries,
1015
+ query_position_embeddings,
1016
+ output_attentions: bool | None = None,
1017
+ output_hidden_states: bool | None = None,
1018
+ return_dict: bool | None = None,
1019
+ **kwargs,
1020
+ ):
1021
+ r"""
1022
+ Args:
1023
+ inputs_embeds (`torch.FloatTensor` of shape `(sequence_length, batch_size, hidden_size)`):
1024
+ The query embeddings that are passed into the decoder.
1025
+ encoder_hidden_states (`torch.FloatTensor` of shape `(encoder_sequence_length, batch_size, hidden_size)`, *optional*):
1026
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
1027
+ of the decoder.
1028
+ memory_key_padding_mask (`torch.Tensor.bool` of shape `(batch_size, sequence_length)`):
1029
+ The memory_key_padding_mask indicates which positions in the memory (encoder outputs) should be ignored during the attention computation,
1030
+ ensuring padding tokens do not influence the attention mechanism.
1031
+ object_queries (`torch.FloatTensor` of shape `(sequence_length, batch_size, hidden_size)`, *optional*):
1032
+ Position embeddings that are added to the queries and keys in each cross-attention layer.
1033
+ query_position_embeddings (`torch.FloatTensor` of shape `(num_queries, batch_size, number_of_anchor_points)`):
1034
+ Position embeddings that are added to the queries and keys in each self-attention layer.
1035
+ output_attentions (`bool`, *optional*):
1036
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
1037
+ returned tensors for more detail.
1038
+ output_hidden_states (`bool`, *optional*):
1039
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
1040
+ for more detail.
1041
+ return_dict (`bool`, *optional*):
1042
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1043
+ """
1044
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1045
+ output_hidden_states = (
1046
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1047
+ )
1048
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1049
+
1050
+ if inputs_embeds is not None:
1051
+ hidden_states = inputs_embeds
1052
+
1053
+ # decoder layers
1054
+ all_hidden_states = () if output_hidden_states else None
1055
+ all_self_attns = () if output_attentions else None
1056
+ all_cross_attentions = () if (output_attentions and encoder_hidden_states is not None) else None
1057
+
1058
+ intermediate = []
1059
+ reference_points = query_position_embeddings.sigmoid()
1060
+ ref_points = [reference_points]
1061
+
1062
+ # expand encoder attention mask
1063
+ if encoder_hidden_states is not None and memory_key_padding_mask is not None:
1064
+ memory_key_padding_mask = create_bidirectional_mask(
1065
+ config=self.config,
1066
+ inputs_embeds=inputs_embeds,
1067
+ attention_mask=memory_key_padding_mask,
1068
+ encoder_hidden_states=encoder_hidden_states,
1069
+ )
1070
+
1071
+ for layer_id, decoder_layer in enumerate(self.layers):
1072
+ if output_hidden_states:
1073
+ all_hidden_states += (hidden_states,)
1074
+
1075
+ obj_center = reference_points[..., : self.config.query_dim]
1076
+ query_sine_embed = gen_sine_position_embeddings(obj_center, self.hidden_size)
1077
+ query_pos = self.ref_point_head(query_sine_embed)
1078
+
1079
+ # For the first decoder layer, we do not apply transformation over p_s
1080
+ pos_transformation = 1 if layer_id == 0 else self.query_scale(hidden_states)
1081
+
1082
+ # apply transformation
1083
+ query_sine_embed = query_sine_embed[..., : self.hidden_size] * pos_transformation
1084
+
1085
+ # modulated Height Width attentions
1086
+ reference_anchor_size = self.ref_anchor_head(hidden_states).sigmoid() # nq, bs, 2
1087
+ query_sine_embed[..., self.hidden_size // 2 :] *= (
1088
+ reference_anchor_size[..., 0] / obj_center[..., 2]
1089
+ ).unsqueeze(-1)
1090
+ query_sine_embed[..., : self.hidden_size // 2] *= (
1091
+ reference_anchor_size[..., 1] / obj_center[..., 3]
1092
+ ).unsqueeze(-1)
1093
+
1094
+ layer_outputs = decoder_layer(
1095
+ hidden_states,
1096
+ None, # attention_mask
1097
+ object_queries,
1098
+ query_pos,
1099
+ query_sine_embed,
1100
+ encoder_hidden_states, # as a positional argument for gradient checkpointing
1101
+ encoder_attention_mask=memory_key_padding_mask,
1102
+ output_attentions=output_attentions,
1103
+ )
1104
+
1105
+ # iter update
1106
+ hidden_states = layer_outputs[0]
1107
+
1108
+ if self.bbox_embed is not None:
1109
+ new_reference_points = self.bbox_embed(hidden_states)
1110
+
1111
+ new_reference_points[..., : self.config.query_dim] += inverse_sigmoid(reference_points)
1112
+ new_reference_points = new_reference_points[..., : self.config.query_dim].sigmoid()
1113
+ if layer_id != self.num_layers - 1:
1114
+ ref_points.append(new_reference_points)
1115
+ reference_points = new_reference_points.detach()
1116
+
1117
+ intermediate.append(self.layernorm(hidden_states))
1118
+
1119
+ if output_attentions:
1120
+ all_self_attns += (layer_outputs[1],)
1121
+
1122
+ if encoder_hidden_states is not None:
1123
+ all_cross_attentions += (layer_outputs[2],)
1124
+
1125
+ # Layer normalization on hidden states
1126
+ hidden_states = self.layernorm(hidden_states)
1127
+
1128
+ if output_hidden_states:
1129
+ all_hidden_states += (hidden_states,)
1130
+
1131
+ output_intermediate_hidden_states = torch.stack(intermediate)
1132
+ output_reference_points = torch.stack(ref_points)
1133
+
1134
+ if not return_dict:
1135
+ return tuple(
1136
+ v
1137
+ for v in [
1138
+ hidden_states,
1139
+ all_hidden_states,
1140
+ all_self_attns,
1141
+ all_cross_attentions,
1142
+ output_intermediate_hidden_states,
1143
+ output_reference_points,
1144
+ ]
1145
+ if v is not None
1146
+ )
1147
+ return DabDetrDecoderOutput(
1148
+ last_hidden_state=hidden_states,
1149
+ hidden_states=all_hidden_states,
1150
+ attentions=all_self_attns,
1151
+ cross_attentions=all_cross_attentions,
1152
+ intermediate_hidden_states=output_intermediate_hidden_states,
1153
+ reference_points=output_reference_points,
1154
+ )
1155
+
1156
+
1157
+ @auto_docstring(
1158
+ custom_intro="""
1159
+ The bare DAB-DETR Model (consisting of a backbone and encoder-decoder Transformer) outputting raw
1160
+ hidden-states, intermediate hidden states, reference points, output coordinates without any specific head on top.
1161
+ """
1162
+ )
1163
+ class DabDetrModel(DabDetrPreTrainedModel):
1164
+ def __init__(self, config: DabDetrConfig):
1165
+ super().__init__(config)
1166
+
1167
+ self.auxiliary_loss = config.auxiliary_loss
1168
+
1169
+ # Create backbone + positional encoding
1170
+ self.backbone = DabDetrConvEncoder(config)
1171
+ object_queries = DabDetrSinePositionEmbedding(config)
1172
+
1173
+ self.query_refpoint_embeddings = nn.Embedding(config.num_queries, config.query_dim)
1174
+ self.random_refpoints_xy = config.random_refpoints_xy
1175
+ if self.random_refpoints_xy:
1176
+ self.query_refpoint_embeddings.weight.data[:, :2].uniform_(0, 1)
1177
+ self.query_refpoint_embeddings.weight.data[:, :2] = inverse_sigmoid(
1178
+ self.query_refpoint_embeddings.weight.data[:, :2]
1179
+ )
1180
+ self.query_refpoint_embeddings.weight.data[:, :2].requires_grad = False
1181
+
1182
+ # Create projection layer
1183
+ self.input_projection = nn.Conv2d(
1184
+ self.backbone.intermediate_channel_sizes[-1], config.hidden_size, kernel_size=1
1185
+ )
1186
+ self.backbone = DabDetrConvModel(self.backbone, object_queries)
1187
+
1188
+ self.encoder = DabDetrEncoder(config)
1189
+ self.decoder = DabDetrDecoder(config)
1190
+
1191
+ # decoder related variables
1192
+ self.hidden_size = config.hidden_size
1193
+ self.num_queries = config.num_queries
1194
+
1195
+ self.num_patterns = config.num_patterns
1196
+ if not isinstance(self.num_patterns, int):
1197
+ logger.warning(f"num_patterns should be int but {type(self.num_patterns)}")
1198
+ self.num_patterns = 0
1199
+ if self.num_patterns > 0:
1200
+ self.patterns = nn.Embedding(self.num_patterns, self.hidden_size)
1201
+
1202
+ self.aux_loss = config.auxiliary_loss
1203
+
1204
+ # Initialize weights and apply final processing
1205
+ self.post_init()
1206
+
1207
+ def freeze_backbone(self):
1208
+ for name, param in self.backbone.conv_encoder.model.named_parameters():
1209
+ param.requires_grad_(False)
1210
+
1211
+ def unfreeze_backbone(self):
1212
+ for name, param in self.backbone.conv_encoder.model.named_parameters():
1213
+ param.requires_grad_(True)
1214
+
1215
+ @auto_docstring
1216
+ def forward(
1217
+ self,
1218
+ pixel_values: torch.FloatTensor,
1219
+ pixel_mask: torch.LongTensor | None = None,
1220
+ decoder_attention_mask: torch.LongTensor | None = None,
1221
+ encoder_outputs: torch.FloatTensor | None = None,
1222
+ inputs_embeds: torch.FloatTensor | None = None,
1223
+ decoder_inputs_embeds: torch.FloatTensor | None = None,
1224
+ output_attentions: bool | None = None,
1225
+ output_hidden_states: bool | None = None,
1226
+ return_dict: bool | None = None,
1227
+ **kwargs,
1228
+ ) -> tuple[torch.FloatTensor] | DabDetrModelOutput:
1229
+ r"""
1230
+ decoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, num_queries)`, *optional*):
1231
+ Not used by default. Can be used to mask object queries.
1232
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1233
+ Optionally, instead of passing the flattened feature map (output of the backbone + projection layer), you
1234
+ can choose to directly pass a flattened representation of an image.
1235
+ decoder_inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_queries, hidden_size)`, *optional*):
1236
+ Optionally, instead of initializing the queries with a tensor of zeros, you can choose to directly pass an
1237
+ embedded representation.
1238
+
1239
+ Examples:
1240
+
1241
+ ```python
1242
+ >>> from transformers import AutoImageProcessor, AutoModel
1243
+ >>> from PIL import Image
1244
+ >>> import httpx
1245
+ >>> from io import BytesIO
1246
+
1247
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
1248
+ >>> with httpx.stream("GET", url) as response:
1249
+ ... image = Image.open(BytesIO(response.read()))
1250
+
1251
+ >>> image_processor = AutoImageProcessor.from_pretrained("IDEA-Research/dab_detr-base")
1252
+ >>> model = AutoModel.from_pretrained("IDEA-Research/dab_detr-base")
1253
+
1254
+ >>> # prepare image for the model
1255
+ >>> inputs = image_processor(images=image, return_tensors="pt")
1256
+
1257
+ >>> # forward pass
1258
+ >>> outputs = model(**inputs)
1259
+
1260
+ >>> # the last hidden states are the final query embeddings of the Transformer decoder
1261
+ >>> # these are of shape (batch_size, num_queries, hidden_size)
1262
+ >>> last_hidden_states = outputs.last_hidden_state
1263
+ >>> list(last_hidden_states.shape)
1264
+ [1, 300, 256]
1265
+ ```"""
1266
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1267
+ output_hidden_states = (
1268
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1269
+ )
1270
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1271
+
1272
+ batch_size, _, height, width = pixel_values.shape
1273
+ device = pixel_values.device
1274
+
1275
+ if pixel_mask is None:
1276
+ pixel_mask = torch.ones(((batch_size, height, width)), device=device)
1277
+
1278
+ # First, sent pixel_values + pixel_mask through Backbone to obtain the features
1279
+ # pixel_values should be of shape (batch_size, num_channels, height, width)
1280
+ # pixel_mask should be of shape (batch_size, height, width)
1281
+ features, object_queries_list = self.backbone(pixel_values, pixel_mask)
1282
+
1283
+ # get final feature map and downsampled mask
1284
+ feature_map, mask = features[-1]
1285
+
1286
+ if mask is None:
1287
+ raise ValueError("Backbone does not return downsampled pixel mask")
1288
+
1289
+ flattened_mask = mask.flatten(1)
1290
+
1291
+ # Second, apply 1x1 convolution to reduce the channel dimension to hidden_size (256 by default)
1292
+ projected_feature_map = self.input_projection(feature_map)
1293
+
1294
+ # Third, flatten the feature map + object_queries of shape NxCxHxW to HWxNxC, and permute it to NxHWxC
1295
+ # In other words, turn their shape into ( sequence_length, batch_size, hidden_size)
1296
+ flattened_features = projected_feature_map.flatten(2).permute(0, 2, 1)
1297
+ object_queries = object_queries_list[-1].flatten(2).permute(0, 2, 1)
1298
+ reference_position_embeddings = self.query_refpoint_embeddings.weight.unsqueeze(0).repeat(batch_size, 1, 1)
1299
+
1300
+ # Fourth, sent flattened_features + flattened_mask + object_queries through encoder
1301
+ # flattened_features is a Tensor of shape (height*width, batch_size, hidden_size)
1302
+ # flattened_mask is a Tensor of shape (batch_size, height*width)
1303
+ if encoder_outputs is None:
1304
+ encoder_outputs = self.encoder(
1305
+ inputs_embeds=flattened_features,
1306
+ attention_mask=flattened_mask,
1307
+ object_queries=object_queries,
1308
+ output_attentions=output_attentions,
1309
+ output_hidden_states=output_hidden_states,
1310
+ return_dict=return_dict,
1311
+ )
1312
+ # If the user passed a tuple for encoder_outputs, we wrap it in a BaseModelOutput when return_dict=True
1313
+ elif return_dict and not isinstance(encoder_outputs, BaseModelOutput):
1314
+ encoder_outputs = BaseModelOutput(
1315
+ last_hidden_state=encoder_outputs[0],
1316
+ hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
1317
+ attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
1318
+ )
1319
+
1320
+ # Fifth, sent query embeddings + object_queries through the decoder (which is conditioned on the encoder output)
1321
+ num_queries = reference_position_embeddings.shape[1]
1322
+ if self.num_patterns == 0:
1323
+ queries = torch.zeros(batch_size, num_queries, self.hidden_size, device=device)
1324
+ else:
1325
+ queries = (
1326
+ self.patterns.weight[:, None, None, :]
1327
+ .repeat(1, self.num_queries, batch_size, 1)
1328
+ .flatten(0, 1)
1329
+ .permute(1, 0, 2)
1330
+ ) # bs, n_q*n_pat, hidden_size
1331
+ reference_position_embeddings = reference_position_embeddings.repeat(
1332
+ 1, self.num_patterns, 1
1333
+ ) # bs, n_q*n_pat, hidden_size
1334
+
1335
+ # decoder outputs consists of (dec_features, dec_hidden, dec_attn)
1336
+ decoder_outputs = self.decoder(
1337
+ inputs_embeds=queries,
1338
+ query_position_embeddings=reference_position_embeddings,
1339
+ object_queries=object_queries,
1340
+ encoder_hidden_states=encoder_outputs[0],
1341
+ memory_key_padding_mask=flattened_mask,
1342
+ output_attentions=output_attentions,
1343
+ output_hidden_states=output_hidden_states,
1344
+ return_dict=return_dict,
1345
+ )
1346
+
1347
+ if not return_dict:
1348
+ # last_hidden_state
1349
+ output = (decoder_outputs[0],)
1350
+ reference_points = decoder_outputs[-1]
1351
+ intermediate_hidden_states = decoder_outputs[-2]
1352
+
1353
+ # it has to follow the order of DABDETRModelOutput that is based on ModelOutput
1354
+ # If we only use one of the variables then the indexing will change.
1355
+ # E.g: if we return everything then 'decoder_attentions' is decoder_outputs[2], if we only use output_attentions then its decoder_outputs[1]
1356
+ if output_hidden_states and output_attentions:
1357
+ output += (
1358
+ decoder_outputs[1],
1359
+ decoder_outputs[2],
1360
+ decoder_outputs[3],
1361
+ encoder_outputs[0],
1362
+ encoder_outputs[1],
1363
+ encoder_outputs[2],
1364
+ )
1365
+ elif output_hidden_states:
1366
+ # decoder_hidden_states, encoder_last_hidden_state, encoder_hidden_states
1367
+ output += (
1368
+ decoder_outputs[1],
1369
+ encoder_outputs[0],
1370
+ encoder_outputs[1],
1371
+ )
1372
+ elif output_attentions:
1373
+ # decoder_self_attention, decoder_cross_attention, encoder_attentions
1374
+ output += (
1375
+ decoder_outputs[1],
1376
+ decoder_outputs[2],
1377
+ encoder_outputs[1],
1378
+ )
1379
+
1380
+ output += (intermediate_hidden_states, reference_points)
1381
+
1382
+ return output
1383
+
1384
+ reference_points = decoder_outputs.reference_points
1385
+ intermediate_hidden_states = decoder_outputs.intermediate_hidden_states
1386
+
1387
+ return DabDetrModelOutput(
1388
+ last_hidden_state=decoder_outputs.last_hidden_state,
1389
+ decoder_hidden_states=decoder_outputs.hidden_states if output_hidden_states else None,
1390
+ decoder_attentions=decoder_outputs.attentions if output_attentions else None,
1391
+ cross_attentions=decoder_outputs.cross_attentions if output_attentions else None,
1392
+ encoder_last_hidden_state=encoder_outputs.last_hidden_state if output_hidden_states else None,
1393
+ encoder_hidden_states=encoder_outputs.hidden_states if output_hidden_states else None,
1394
+ encoder_attentions=encoder_outputs.attentions if output_attentions else None,
1395
+ intermediate_hidden_states=intermediate_hidden_states,
1396
+ reference_points=reference_points,
1397
+ )
1398
+
1399
+
1400
+ # TODO: use modular - Copied from transformers.models.detr.modeling_detr.DetrMHAttentionMap with Detr->DabDetr
1401
+ class DabDetrMHAttentionMap(nn.Module):
1402
+ """This is a 2D attention module, which only returns the attention softmax (no multiplication by value)"""
1403
+
1404
+ def __init__(self, query_dim, hidden_dim, num_heads, dropout=0.0, bias=True, std=None):
1405
+ super().__init__()
1406
+ self.num_heads = num_heads
1407
+ self.hidden_dim = hidden_dim
1408
+ self.dropout = nn.Dropout(dropout)
1409
+
1410
+ self.q_linear = nn.Linear(query_dim, hidden_dim, bias=bias)
1411
+ self.k_linear = nn.Linear(query_dim, hidden_dim, bias=bias)
1412
+
1413
+ self.normalize_fact = float(hidden_dim / self.num_heads) ** -0.5
1414
+
1415
+ def forward(self, q, k, mask: Tensor | None = None):
1416
+ q = self.q_linear(q)
1417
+ k = nn.functional.conv2d(k, self.k_linear.weight.unsqueeze(-1).unsqueeze(-1), self.k_linear.bias)
1418
+ queries_per_head = q.view(q.shape[0], q.shape[1], self.num_heads, self.hidden_dim // self.num_heads)
1419
+ keys_per_head = k.view(k.shape[0], self.num_heads, self.hidden_dim // self.num_heads, k.shape[-2], k.shape[-1])
1420
+ weights = torch.einsum("bqnc,bnchw->bqnhw", queries_per_head * self.normalize_fact, keys_per_head)
1421
+
1422
+ if mask is not None:
1423
+ weights = weights.masked_fill(mask.unsqueeze(1).unsqueeze(1), torch.finfo(weights.dtype).min)
1424
+ weights = nn.functional.softmax(weights.flatten(2), dim=-1).view(weights.size())
1425
+ weights = self.dropout(weights)
1426
+ return weights
1427
+
1428
+
1429
+ @auto_docstring(
1430
+ custom_intro="""
1431
+ DAB_DETR Model (consisting of a backbone and encoder-decoder Transformer) with object detection heads on
1432
+ top, for tasks such as COCO detection.
1433
+ """
1434
+ )
1435
+ class DabDetrForObjectDetection(DabDetrPreTrainedModel):
1436
+ # When using clones, all layers > 0 will be clones, but layer 0 *is* required
1437
+ _tied_weights_keys = {"model.decoder.bbox_embed": "bbox_predictor"}
1438
+
1439
+ def __init__(self, config: DabDetrConfig):
1440
+ super().__init__(config)
1441
+
1442
+ self.config = config
1443
+ self.auxiliary_loss = config.auxiliary_loss
1444
+ self.query_dim = config.query_dim
1445
+ # DAB-DETR encoder-decoder model
1446
+ self.model = DabDetrModel(config)
1447
+
1448
+ # Object detection heads
1449
+ self.class_embed = nn.Linear(config.hidden_size, config.num_labels)
1450
+
1451
+ # Default bbox_embed_diff_each_layer is False
1452
+ self.bbox_predictor = DabDetrMLP(config.hidden_size, config.hidden_size, 4, 3)
1453
+
1454
+ # Default iter_update is True
1455
+ self.model.decoder.bbox_embed = self.bbox_predictor
1456
+
1457
+ # Initialize weights and apply final processing
1458
+ self.post_init()
1459
+
1460
+ # taken from https://github.com/Atten4Vis/conditionalDETR/blob/master/models/dab_detr.py
1461
+ def _set_aux_loss(self, outputs_class, outputs_coord):
1462
+ return [{"logits": a, "pred_boxes": b} for a, b in zip(outputs_class[:-1], outputs_coord[:-1])]
1463
+
1464
+ @auto_docstring
1465
+ def forward(
1466
+ self,
1467
+ pixel_values: torch.FloatTensor,
1468
+ pixel_mask: torch.LongTensor | None = None,
1469
+ decoder_attention_mask: torch.LongTensor | None = None,
1470
+ encoder_outputs: torch.FloatTensor | None = None,
1471
+ inputs_embeds: torch.FloatTensor | None = None,
1472
+ decoder_inputs_embeds: torch.FloatTensor | None = None,
1473
+ labels: list[dict] | None = None,
1474
+ output_attentions: bool | None = None,
1475
+ output_hidden_states: bool | None = None,
1476
+ return_dict: bool | None = None,
1477
+ **kwargs,
1478
+ ) -> tuple[torch.FloatTensor] | DabDetrObjectDetectionOutput:
1479
+ r"""
1480
+ decoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, num_queries)`, *optional*):
1481
+ Not used by default. Can be used to mask object queries.
1482
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1483
+ Optionally, instead of passing the flattened feature map (output of the backbone + projection layer), you
1484
+ can choose to directly pass a flattened representation of an image.
1485
+ decoder_inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_queries, hidden_size)`, *optional*):
1486
+ Optionally, instead of initializing the queries with a tensor of zeros, you can choose to directly pass an
1487
+ embedded representation.
1488
+ labels (`list[Dict]` of len `(batch_size,)`, *optional*):
1489
+ Labels for computing the bipartite matching loss. List of dicts, each dictionary containing at least the
1490
+ following 2 keys: 'class_labels' and 'boxes' (the class labels and bounding boxes of an image in the batch
1491
+ respectively). The class labels themselves should be a `torch.LongTensor` of len `(number of bounding boxes
1492
+ in the image,)` and the boxes a `torch.FloatTensor` of shape `(number of bounding boxes in the image, 4)`.
1493
+
1494
+ Examples:
1495
+
1496
+ ```python
1497
+ >>> from transformers import AutoImageProcessor, AutoModelForObjectDetection
1498
+ >>> from PIL import Image
1499
+ >>> import httpx
1500
+ >>> from io import BytesIO
1501
+
1502
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
1503
+ >>> with httpx.stream("GET", url) as response:
1504
+ ... image = Image.open(BytesIO(response.read()))
1505
+
1506
+ >>> image_processor = AutoImageProcessor.from_pretrained("IDEA-Research/dab-detr-resnet-50")
1507
+ >>> model = AutoModelForObjectDetection.from_pretrained("IDEA-Research/dab-detr-resnet-50")
1508
+
1509
+ >>> inputs = image_processor(images=image, return_tensors="pt")
1510
+
1511
+ >>> with torch.no_grad():
1512
+ >>> outputs = model(**inputs)
1513
+
1514
+ >>> # convert outputs (bounding boxes and class logits) to Pascal VOC format (xmin, ymin, xmax, ymax)
1515
+ >>> target_sizes = torch.tensor([(image.height, image.width)])
1516
+ >>> results = image_processor.post_process_object_detection(outputs, threshold=0.5, target_sizes=target_sizes)[0]
1517
+ >>> for score, label, box in zip(results["scores"], results["labels"], results["boxes"]):
1518
+ ... box = [round(i, 2) for i in box.tolist()]
1519
+ ... print(
1520
+ ... f"Detected {model.config.id2label[label.item()]} with confidence "
1521
+ ... f"{round(score.item(), 3)} at location {box}"
1522
+ ... )
1523
+ Detected remote with confidence 0.833 at location [38.31, 72.1, 177.63, 118.45]
1524
+ Detected cat with confidence 0.831 at location [9.2, 51.38, 321.13, 469.0]
1525
+ Detected cat with confidence 0.804 at location [340.3, 16.85, 642.93, 370.95]
1526
+ Detected remote with confidence 0.683 at location [334.48, 73.49, 366.37, 190.01]
1527
+ Detected couch with confidence 0.535 at location [0.52, 1.19, 640.35, 475.1]
1528
+ ```"""
1529
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1530
+ output_hidden_states = (
1531
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1532
+ )
1533
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1534
+
1535
+ # First, sent images through DAB_DETR base model to obtain encoder + decoder outputs
1536
+ model_outputs = self.model(
1537
+ pixel_values,
1538
+ pixel_mask=pixel_mask,
1539
+ decoder_attention_mask=decoder_attention_mask,
1540
+ encoder_outputs=encoder_outputs,
1541
+ inputs_embeds=inputs_embeds,
1542
+ decoder_inputs_embeds=decoder_inputs_embeds,
1543
+ output_attentions=output_attentions,
1544
+ output_hidden_states=output_hidden_states,
1545
+ return_dict=return_dict,
1546
+ )
1547
+
1548
+ reference_points = model_outputs.reference_points if return_dict else model_outputs[-1]
1549
+ intermediate_hidden_states = model_outputs.intermediate_hidden_states if return_dict else model_outputs[-2]
1550
+
1551
+ # class logits + predicted bounding boxes
1552
+ logits = self.class_embed(intermediate_hidden_states[-1])
1553
+
1554
+ reference_before_sigmoid = inverse_sigmoid(reference_points)
1555
+ bbox_with_refinement = self.bbox_predictor(intermediate_hidden_states)
1556
+ bbox_with_refinement[..., : self.query_dim] += reference_before_sigmoid
1557
+ outputs_coord = bbox_with_refinement.sigmoid()
1558
+
1559
+ pred_boxes = outputs_coord[-1]
1560
+
1561
+ loss, loss_dict, auxiliary_outputs = None, None, None
1562
+ if labels is not None:
1563
+ outputs_class = None
1564
+ if self.config.auxiliary_loss:
1565
+ outputs_class = self.class_embed(intermediate_hidden_states)
1566
+ loss, loss_dict, auxiliary_outputs = self.loss_function(
1567
+ logits, labels, self.device, pred_boxes, self.config, outputs_class, outputs_coord
1568
+ )
1569
+
1570
+ if not return_dict:
1571
+ if auxiliary_outputs is not None:
1572
+ output = (logits, pred_boxes) + auxiliary_outputs + model_outputs
1573
+ else:
1574
+ output = (logits, pred_boxes) + model_outputs
1575
+ # Since DabDetrObjectDetectionOutput doesn't have reference points + intermedieate_hidden_states we cut down.
1576
+ return ((loss, loss_dict) + output) if loss is not None else output[:-2]
1577
+
1578
+ return DabDetrObjectDetectionOutput(
1579
+ loss=loss,
1580
+ loss_dict=loss_dict,
1581
+ logits=logits,
1582
+ pred_boxes=pred_boxes,
1583
+ auxiliary_outputs=auxiliary_outputs,
1584
+ last_hidden_state=model_outputs.last_hidden_state,
1585
+ decoder_hidden_states=model_outputs.decoder_hidden_states if output_hidden_states else None,
1586
+ decoder_attentions=model_outputs.decoder_attentions if output_attentions else None,
1587
+ cross_attentions=model_outputs.cross_attentions if output_attentions else None,
1588
+ encoder_last_hidden_state=model_outputs.encoder_last_hidden_state if output_hidden_states else None,
1589
+ encoder_hidden_states=model_outputs.encoder_hidden_states if output_hidden_states else None,
1590
+ encoder_attentions=model_outputs.encoder_attentions if output_attentions else None,
1591
+ )
1592
+
1593
+
1594
+ __all__ = [
1595
+ "DabDetrForObjectDetection",
1596
+ "DabDetrModel",
1597
+ "DabDetrPreTrainedModel",
1598
+ ]
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/dac/__init__.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_dac import *
22
+ from .feature_extraction_dac import *
23
+ from .modeling_dac import *
24
+ else:
25
+ import sys
26
+
27
+ _file = globals()["__file__"]
28
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/dac/configuration_dac.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Descript and 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
+ """Dac model configuration"""
15
+
16
+ import math
17
+
18
+ import numpy as np
19
+
20
+ from ...configuration_utils import PreTrainedConfig
21
+ from ...utils import logging
22
+
23
+
24
+ logger = logging.get_logger(__name__)
25
+
26
+
27
+ class DacConfig(PreTrainedConfig):
28
+ r"""
29
+ This is the configuration class to store the configuration of an [`DacModel`]. It is used to instantiate a
30
+ Dac model according to the specified arguments, defining the model architecture. Instantiating a configuration
31
+ with the defaults will yield a similar configuration to that of the
32
+ [descript/dac_16khz](https://huggingface.co/descript/dac_16khz) architecture.
33
+
34
+ Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the
35
+ documentation from [`PreTrainedConfig`] for more information.
36
+
37
+ Args:
38
+ encoder_hidden_size (`int`, *optional*, defaults to 64):
39
+ Intermediate representation dimension for the encoder.
40
+ downsampling_ratios (`list[int]`, *optional*, defaults to `[2, 4, 8, 8]`):
41
+ Ratios for downsampling in the encoder. These are used in reverse order for upsampling in the decoder.
42
+ decoder_hidden_size (`int`, *optional*, defaults to 1536):
43
+ Intermediate representation dimension for the decoder.
44
+ n_codebooks (`int`, *optional*, defaults to 9):
45
+ Number of codebooks in the VQVAE.
46
+ codebook_size (`int`, *optional*, defaults to 1024):
47
+ Number of discrete codes in each codebook.
48
+ codebook_dim (`int`, *optional*, defaults to 8):
49
+ Dimension of the codebook vectors. If not defined, uses `encoder_hidden_size`.
50
+ quantizer_dropout (`bool`, *optional*, defaults to 0):
51
+ Whether to apply dropout to the quantizer.
52
+ commitment_loss_weight (float, *optional*, defaults to 0.25):
53
+ Weight of the commitment loss term in the VQVAE loss function.
54
+ codebook_loss_weight (float, *optional*, defaults to 1.0):
55
+ Weight of the codebook loss term in the VQVAE loss function.
56
+ sampling_rate (`int`, *optional*, defaults to 16000):
57
+ The sampling rate at which the audio waveform should be digitalized expressed in hertz (Hz).
58
+ Example:
59
+
60
+ ```python
61
+ >>> from transformers import DacModel, DacConfig
62
+
63
+ >>> # Initializing a "descript/dac_16khz" style configuration
64
+ >>> configuration = DacConfig()
65
+
66
+ >>> # Initializing a model (with random weights) from the "descript/dac_16khz" style configuration
67
+ >>> model = DacModel(configuration)
68
+
69
+ >>> # Accessing the model configuration
70
+ >>> configuration = model.config
71
+ ```"""
72
+
73
+ model_type = "dac"
74
+
75
+ def __init__(
76
+ self,
77
+ encoder_hidden_size=64,
78
+ downsampling_ratios=[2, 4, 8, 8],
79
+ decoder_hidden_size=1536,
80
+ n_codebooks=9,
81
+ codebook_size=1024,
82
+ codebook_dim=8,
83
+ quantizer_dropout=0,
84
+ commitment_loss_weight=0.25,
85
+ codebook_loss_weight=1.0,
86
+ sampling_rate=16000,
87
+ **kwargs,
88
+ ):
89
+ self.encoder_hidden_size = encoder_hidden_size
90
+ self.downsampling_ratios = downsampling_ratios
91
+ self.decoder_hidden_size = decoder_hidden_size
92
+ self.upsampling_ratios = downsampling_ratios[::-1]
93
+ self.n_codebooks = n_codebooks
94
+ self.codebook_size = codebook_size
95
+ self.codebook_dim = codebook_dim
96
+ self.quantizer_dropout = quantizer_dropout
97
+ self.sampling_rate = sampling_rate
98
+
99
+ self.hidden_size = encoder_hidden_size * (2 ** len(downsampling_ratios))
100
+
101
+ self.hop_length = int(np.prod(downsampling_ratios))
102
+ self.commitment_loss_weight = commitment_loss_weight
103
+ self.codebook_loss_weight = codebook_loss_weight
104
+
105
+ super().__init__(**kwargs)
106
+
107
+ @property
108
+ def frame_rate(self) -> int:
109
+ hop_length = np.prod(self.upsampling_ratios)
110
+ return math.ceil(self.sampling_rate / hop_length)
111
+
112
+
113
+ __all__ = ["DacConfig"]
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/dac/feature_extraction_dac.py ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Descript and 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
+ """Feature extractor class for DAC"""
15
+
16
+ import numpy as np
17
+
18
+ from ...feature_extraction_sequence_utils import SequenceFeatureExtractor
19
+ from ...feature_extraction_utils import BatchFeature
20
+ from ...utils import PaddingStrategy, TensorType, logging
21
+
22
+
23
+ logger = logging.get_logger(__name__)
24
+
25
+
26
+ class DacFeatureExtractor(SequenceFeatureExtractor):
27
+ r"""
28
+ Constructs an Dac feature extractor.
29
+
30
+ This feature extractor inherits from [`~feature_extraction_sequence_utils.SequenceFeatureExtractor`] which contains
31
+ most of the main methods. Users should refer to this superclass for more information regarding those methods.
32
+
33
+ Args:
34
+ feature_size (`int`, *optional*, defaults to 1):
35
+ The feature dimension of the extracted features. Use 1 for mono, 2 for stereo.
36
+ sampling_rate (`int`, *optional*, defaults to 16000):
37
+ The sampling rate at which the audio waveform should be digitalized, expressed in hertz (Hz).
38
+ padding_value (`float`, *optional*, defaults to 0.0):
39
+ The value that is used for padding.
40
+ hop_length (`int`, *optional*, defaults to 512):
41
+ Overlap length between successive windows.
42
+ """
43
+
44
+ model_input_names = ["input_values", "n_quantizers"]
45
+
46
+ def __init__(
47
+ self,
48
+ feature_size: int = 1,
49
+ sampling_rate: int = 16000,
50
+ padding_value: float = 0.0,
51
+ hop_length: int = 512,
52
+ **kwargs,
53
+ ):
54
+ super().__init__(feature_size=feature_size, sampling_rate=sampling_rate, padding_value=padding_value, **kwargs)
55
+ self.hop_length = hop_length
56
+
57
+ def __call__(
58
+ self,
59
+ raw_audio: np.ndarray | list[float] | list[np.ndarray] | list[list[float]],
60
+ padding: bool | str | PaddingStrategy | None = None,
61
+ truncation: bool | None = False,
62
+ max_length: int | None = None,
63
+ return_tensors: str | TensorType | None = None,
64
+ sampling_rate: int | None = None,
65
+ ) -> BatchFeature:
66
+ """
67
+ Main method to featurize and prepare for the model one or several sequence(s).
68
+
69
+ Args:
70
+ raw_audio (`np.ndarray`, `list[float]`, `list[np.ndarray]`, `list[list[float]]`):
71
+ The sequence or batch of sequences to be processed. Each sequence can be a numpy array, a list of float
72
+ values, a list of numpy arrays or a list of list of float values. The numpy array must be of shape
73
+ `(num_samples,)` for mono audio (`feature_size = 1`), or `(2, num_samples)` for stereo audio
74
+ (`feature_size = 2`).
75
+ padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `True`):
76
+ Select a strategy to pad the returned sequences (according to the model's padding side and padding
77
+ index) among:
78
+
79
+ - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single
80
+ sequence if provided).
81
+ - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum
82
+ acceptable input length for the model if that argument is not provided.
83
+ - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different
84
+ lengths).
85
+ truncation (`bool`, *optional*, defaults to `False`):
86
+ Activates truncation to cut input sequences longer than `max_length` to `max_length`.
87
+ max_length (`int`, *optional*):
88
+ Maximum length of the returned list and optionally padding length (see above).
89
+ return_tensors (`str` or [`~utils.TensorType`], *optional*, default to 'pt'):
90
+ If set, will return tensors instead of list of python integers. Acceptable values are:
91
+
92
+ - `'pt'`: Return PyTorch `torch.Tensor` objects.
93
+ - `'np'`: Return Numpy `np.ndarray` objects.
94
+ sampling_rate (`int`, *optional*):
95
+ The sampling rate at which the `audio` input was sampled. It is strongly recommended to pass
96
+ `sampling_rate` at the forward call to prevent silent errors.
97
+ """
98
+ if sampling_rate is not None:
99
+ if sampling_rate != self.sampling_rate:
100
+ raise ValueError(
101
+ f"The model corresponding to this feature extractor: {self} was trained using a sampling rate of"
102
+ f" {self.sampling_rate}. Please make sure that the provided audio input was sampled with"
103
+ f" {self.sampling_rate} and not {sampling_rate}."
104
+ )
105
+ else:
106
+ logger.warning(
107
+ f"It is strongly recommended to pass the `sampling_rate` argument to `{self.__class__.__name__}()`. "
108
+ "Failing to do so can result in silent errors that might be hard to debug."
109
+ )
110
+
111
+ if padding and truncation:
112
+ raise ValueError("Both padding and truncation were set. Make sure you only set one.")
113
+ elif padding is None:
114
+ # by default let's pad the inputs
115
+ padding = True
116
+
117
+ is_batched = bool(
118
+ isinstance(raw_audio, (list, tuple)) and (isinstance(raw_audio[0], (np.ndarray, tuple, list)))
119
+ )
120
+
121
+ if is_batched:
122
+ raw_audio = [np.asarray(audio, dtype=np.float32).T for audio in raw_audio]
123
+ elif not is_batched and not isinstance(raw_audio, np.ndarray):
124
+ raw_audio = np.asarray(raw_audio, dtype=np.float32)
125
+ elif isinstance(raw_audio, np.ndarray) and raw_audio.dtype is np.dtype(np.float64):
126
+ raw_audio = raw_audio.astype(np.float32)
127
+
128
+ # always return batch
129
+ if not is_batched:
130
+ raw_audio = [np.asarray(raw_audio).T]
131
+
132
+ # verify inputs are valid
133
+ for idx, example in enumerate(raw_audio):
134
+ if example.ndim > 2:
135
+ raise ValueError(f"Expected input shape (channels, length) but got shape {example.shape}")
136
+ if self.feature_size == 1 and example.ndim != 1:
137
+ raise ValueError(f"Expected mono audio but example has {example.shape[-1]} channels")
138
+ if self.feature_size == 2:
139
+ raise ValueError("Stereo audio isn't supported for now")
140
+
141
+ input_values = BatchFeature({"input_values": raw_audio})
142
+
143
+ # normal padding on batch
144
+ padded_inputs = self.pad(
145
+ input_values,
146
+ max_length=max_length,
147
+ truncation=truncation,
148
+ padding=padding,
149
+ return_attention_mask=padding,
150
+ pad_to_multiple_of=self.hop_length,
151
+ )
152
+ if padding:
153
+ padded_inputs["padding_mask"] = padded_inputs.pop("attention_mask")
154
+ if padding:
155
+ padded_inputs.input_values = padded_inputs.input_values[:, np.newaxis, :]
156
+
157
+ input_values = []
158
+ for example in padded_inputs.pop("input_values"):
159
+ if self.feature_size == 1:
160
+ example = example[..., None]
161
+ input_values.append(example.T)
162
+
163
+ padded_inputs["input_values"] = input_values
164
+ if return_tensors is not None:
165
+ padded_inputs = padded_inputs.convert_to_tensors(return_tensors)
166
+
167
+ return padded_inputs
168
+
169
+
170
+ __all__ = ["DacFeatureExtractor"]
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/dac/modeling_dac.py ADDED
@@ -0,0 +1,689 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Descript and 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
+ """Transformers DAC model."""
15
+
16
+ import math
17
+ from dataclasses import dataclass
18
+
19
+ import numpy as np
20
+ import torch
21
+ import torch.nn as nn
22
+ import torch.nn.functional as F
23
+
24
+ from ... import initialization as init
25
+ from ...modeling_utils import PreTrainedAudioTokenizerBase
26
+ from ...utils import ModelOutput, auto_docstring
27
+ from .configuration_dac import DacConfig
28
+
29
+
30
+ @dataclass
31
+ @auto_docstring
32
+ class DacOutput(ModelOutput):
33
+ r"""
34
+ loss (`torch.Tensor`):
35
+ Loss from the encoder model, comprising the weighted combination of the commitment and codebook losses.
36
+ audio_values (`torch.Tensor` of shape `(batch_size, input_length)`):
37
+ Reconstructed audio data.
38
+ quantized_representation (`torch.Tensor` of shape `(batch_size, dimension, time_steps)`):
39
+ Quantized continuous representation of input.
40
+ audio_codes (`torch.LongTensor` of shape `(batch_size, num_codebooks, time_steps)`):
41
+ Codebook indices for each codebook (quantized discrete representation of input).
42
+ projected_latents (`torch.Tensor` of shape `(batch_size, num_codebooks * dimension, time_steps)`):
43
+ Projected latents (continuous representation of input before quantization).
44
+ """
45
+
46
+ loss: torch.FloatTensor | None = None
47
+ audio_values: torch.FloatTensor | None = None
48
+ quantized_representation: torch.FloatTensor | None = None
49
+ audio_codes: torch.LongTensor | None = None
50
+ projected_latents: torch.FloatTensor | None = None
51
+
52
+
53
+ @dataclass
54
+ @auto_docstring
55
+ class DacEncoderOutput(ModelOutput):
56
+ r"""
57
+ loss (`torch.Tensor`):
58
+ Loss from the encoder model, comprising the weighted combination of the commitment and codebook losses.
59
+ quantized_representation (`torch.Tensor` of shape `(batch_size, dimension, time_steps)`, *optional*):
60
+ Quantized continuous representation of input.
61
+ audio_codes (`torch.Tensor` of shape `(batch_size, num_codebooks, time_steps)`, *optional*):
62
+ Codebook indices for each codebook (quantized discrete representation of input).
63
+ projected_latents (`torch.Tensor` of shape `(batch_size, num_codebooks * dimension, time_steps)`, *optional*):
64
+ Projected latents (continuous representation of input before quantization).
65
+ """
66
+
67
+ loss: torch.FloatTensor | None = None
68
+ quantized_representation: torch.FloatTensor | None = None
69
+ audio_codes: torch.FloatTensor | None = None
70
+ projected_latents: torch.FloatTensor | None = None
71
+
72
+
73
+ @dataclass
74
+ @auto_docstring
75
+ # Copied from transformers.models.encodec.modeling_encodec.EncodecDecoderOutput with Encodec->Dac, segment_length->input_length
76
+ class DacDecoderOutput(ModelOutput):
77
+ r"""
78
+ audio_values (`torch.FloatTensor` of shape `(batch_size, input_length)`, *optional*):
79
+ Decoded audio values, obtained using the decoder part of Dac.
80
+ """
81
+
82
+ audio_values: torch.FloatTensor | None = None
83
+
84
+
85
+ class Snake1d(nn.Module):
86
+ """
87
+ A 1-dimensional Snake activation function module.
88
+ """
89
+
90
+ def __init__(self, hidden_dim):
91
+ super().__init__()
92
+ self.alpha = nn.Parameter(torch.ones(1, hidden_dim, 1))
93
+
94
+ def forward(self, hidden_states):
95
+ shape = hidden_states.shape
96
+ hidden_states = hidden_states.reshape(shape[0], shape[1], -1)
97
+ hidden_states = hidden_states + (self.alpha + 1e-9).reciprocal() * torch.sin(self.alpha * hidden_states).pow(2)
98
+ hidden_states = hidden_states.reshape(shape)
99
+ return hidden_states
100
+
101
+
102
+ class DacVectorQuantize(nn.Module):
103
+ """
104
+ Implementation of VQ similar to Karpathy's repo (https://github.com/karpathy/deep-vector-quantization)
105
+
106
+ Additionally uses following tricks from improved VQGAN
107
+ (https://huggingface.co/papers/2110.04627):
108
+ 1. Factorized codes: Perform nearest neighbor lookup in low-dimensional space
109
+ for improved codebook usage
110
+ 2. l2-normalized codes: Converts euclidean distance to cosine similarity which
111
+ improves training stability
112
+ """
113
+
114
+ def __init__(self, config: DacConfig):
115
+ super().__init__()
116
+
117
+ self.codebook_dim = config.codebook_dim
118
+ self.in_proj = nn.Conv1d(config.hidden_size, config.codebook_dim, kernel_size=1)
119
+ self.out_proj = nn.Conv1d(config.codebook_dim, config.hidden_size, kernel_size=1)
120
+ self.codebook = nn.Embedding(config.codebook_size, config.codebook_dim)
121
+
122
+ def forward(self, hidden_state):
123
+ """
124
+ Quantizes the input tensor using a fixed codebook and returns the corresponding codebook vectors.
125
+
126
+ Args:
127
+ hidden_state (`torch.FloatTensor` of shape `(batch_size, dimension, time_steps)`):
128
+ Input tensor.
129
+
130
+ Returns:
131
+ quantized_representation (`torch.Tensor`of shape `(batch_size, dimension, time_steps)`):
132
+ Quantized continuous representation of input.
133
+ commitment_loss (`torch.FloatTensor`of shape `(1)`):
134
+ Commitment loss to train encoder to predict vectors closer to codebook entries.
135
+ codebook_loss (`torch.FloatTensor`of shape `(1)`):
136
+ Codebook loss to update the codebook.
137
+ audio_codes (`torch.LongTensor` of shape `(batch_size, time_steps)`):
138
+ Codebook indices for each codebook, quantized discrete representation of input.
139
+ projected_latents (torch.FloatTensor of shape `(batch_size, num_codebooks * dimension, time_steps)`):
140
+ Projected latents (continuous representation of input before quantization).
141
+ """
142
+
143
+ projected_latents = self.in_proj(hidden_state)
144
+ quantized_representation, audio_codes = self.decode_latents(projected_latents)
145
+
146
+ commitment_loss = F.mse_loss(projected_latents, quantized_representation.detach(), reduction="mean")
147
+ codebook_loss = F.mse_loss(quantized_representation, projected_latents.detach(), reduction="mean")
148
+ # noop in forward pass, straight-through gradient estimator in backward pass
149
+ quantized_representation = projected_latents + (quantized_representation - projected_latents).detach()
150
+ quantized_representation = self.out_proj(quantized_representation)
151
+
152
+ return quantized_representation, commitment_loss, codebook_loss, audio_codes, projected_latents
153
+
154
+ def decode_latents(self, hidden_states):
155
+ batch_size, hidden_dim, sequence_length = hidden_states.shape
156
+ encodings = hidden_states.permute(0, 2, 1).reshape(batch_size * sequence_length, hidden_dim)
157
+ codebook = self.codebook.weight # codebook: (N x D)
158
+
159
+ # L2 normalize encodings and codebook (ViT-VQGAN)
160
+ encodings = F.normalize(encodings)
161
+ codebook = F.normalize(codebook)
162
+
163
+ # Compute euclidean distance with codebook
164
+ l2_norm = encodings.pow(2).sum(1, keepdim=True)
165
+ dist = -(l2_norm - 2 * encodings @ codebook.t()) + codebook.pow(2).sum(1, keepdim=True).t()
166
+
167
+ indices = dist.max(1)[1]
168
+ indices = indices.reshape(hidden_states.size(0), -1)
169
+ quantized_representation = self.codebook(indices).transpose(1, 2)
170
+ return quantized_representation, indices
171
+
172
+
173
+ class DacResidualUnit(nn.Module):
174
+ """
175
+ A residual unit composed of Snake1d and weight-normalized Conv1d layers with dilations.
176
+ """
177
+
178
+ def __init__(self, dimension: int = 16, dilation: int = 1):
179
+ super().__init__()
180
+ pad = ((7 - 1) * dilation) // 2
181
+
182
+ self.snake1 = Snake1d(dimension)
183
+ self.conv1 = nn.Conv1d(dimension, dimension, kernel_size=7, dilation=dilation, padding=pad)
184
+ self.snake2 = Snake1d(dimension)
185
+ self.conv2 = nn.Conv1d(dimension, dimension, kernel_size=1)
186
+
187
+ def forward(self, hidden_state):
188
+ """
189
+ Forward pass through the residual unit.
190
+
191
+ Args:
192
+ hidden_state (`torch.Tensor` of shape `(batch_size, channels, time_steps)`):
193
+ Input tensor .
194
+
195
+ Returns:
196
+ output_tensor (`torch.Tensor` of shape `(batch_size, channels, time_steps)`):
197
+ Input tensor after passing through the residual unit.
198
+ """
199
+ output_tensor = hidden_state
200
+ output_tensor = self.conv1(self.snake1(output_tensor))
201
+ output_tensor = self.conv2(self.snake2(output_tensor))
202
+
203
+ padding = (hidden_state.shape[-1] - output_tensor.shape[-1]) // 2
204
+ if padding > 0:
205
+ hidden_state = hidden_state[..., padding:-padding]
206
+ output_tensor = hidden_state + output_tensor
207
+ return output_tensor
208
+
209
+
210
+ class DacEncoderBlock(nn.Module):
211
+ """Encoder block used in DAC encoder."""
212
+
213
+ def __init__(self, config: DacConfig, stride: int = 1, stride_index: int = 1):
214
+ super().__init__()
215
+
216
+ dimension = config.encoder_hidden_size * 2**stride_index
217
+ self.res_unit1 = DacResidualUnit(dimension // 2, dilation=1)
218
+ self.res_unit2 = DacResidualUnit(dimension // 2, dilation=3)
219
+ self.res_unit3 = DacResidualUnit(dimension // 2, dilation=9)
220
+ self.snake1 = Snake1d(dimension // 2)
221
+ self.conv1 = nn.Conv1d(
222
+ dimension // 2, dimension, kernel_size=2 * stride, stride=stride, padding=math.ceil(stride / 2)
223
+ )
224
+
225
+ def forward(self, hidden_state):
226
+ hidden_state = self.res_unit1(hidden_state)
227
+ hidden_state = self.res_unit2(hidden_state)
228
+ hidden_state = self.snake1(self.res_unit3(hidden_state))
229
+ hidden_state = self.conv1(hidden_state)
230
+
231
+ return hidden_state
232
+
233
+
234
+ class DacDecoderBlock(nn.Module):
235
+ """Decoder block used in DAC decoder."""
236
+
237
+ def __init__(self, config: DacConfig, stride: int = 1, stride_index: int = 1):
238
+ super().__init__()
239
+
240
+ input_dim = config.decoder_hidden_size // 2**stride_index
241
+ output_dim = config.decoder_hidden_size // 2 ** (stride_index + 1)
242
+ self.snake1 = Snake1d(input_dim)
243
+ self.conv_t1 = nn.ConvTranspose1d(
244
+ input_dim,
245
+ output_dim,
246
+ kernel_size=2 * stride,
247
+ stride=stride,
248
+ padding=math.ceil(stride / 2),
249
+ )
250
+
251
+ self.res_unit1 = DacResidualUnit(output_dim, dilation=1)
252
+ self.res_unit2 = DacResidualUnit(output_dim, dilation=3)
253
+ self.res_unit3 = DacResidualUnit(output_dim, dilation=9)
254
+
255
+ def forward(self, hidden_state):
256
+ hidden_state = self.snake1(hidden_state)
257
+ hidden_state = self.conv_t1(hidden_state)
258
+ hidden_state = self.res_unit1(hidden_state)
259
+ hidden_state = self.res_unit2(hidden_state)
260
+ hidden_state = self.res_unit3(hidden_state)
261
+
262
+ return hidden_state
263
+
264
+
265
+ class DacResidualVectorQuantizer(nn.Module):
266
+ """
267
+ ResidualVectorQuantize block - Introduced in SoundStream: An end2end neural audio codec (https://huggingface.co/papers/2107.03312)
268
+ """
269
+
270
+ def __init__(self, config: DacConfig):
271
+ super().__init__()
272
+
273
+ n_codebooks = config.n_codebooks
274
+ quantizer_dropout = config.quantizer_dropout
275
+
276
+ self.n_codebooks = n_codebooks
277
+
278
+ self.quantizers = nn.ModuleList([DacVectorQuantize(config) for i in range(config.n_codebooks)])
279
+ self.quantizer_dropout = quantizer_dropout
280
+
281
+ def forward(self, hidden_state, n_quantizers: int | None = None):
282
+ """
283
+ Quantizes the input tensor using a fixed set of codebooks and returns corresponding codebook vectors.
284
+ Args:
285
+ hidden_state (`torch.Tensor` of shape `(batch_size, dimension, time_steps)`):
286
+ Input tensor to be quantized.
287
+ n_quantizers (`int`, *optional*):
288
+ Number of quantizers to use. If specified and `self.quantizer_dropout` is True,
289
+ this argument is ignored during training, and a random number of quantizers is used.
290
+
291
+ Returns:
292
+ quantized_representation (`torch.Tensor` of shape `(batch_size, dimension, time_steps)`):
293
+ Quantized continuous representation of input.
294
+ audio_codes (`torch.Tensor` of shape `(batch_size, num_codebooks, time_steps)`):
295
+ Codebook indices for each codebook (quantized discrete representation of input).
296
+ projected_latents (`torch.Tensor` of shape `(batch_size, num_codebooks * dimension, time_steps)`):
297
+ Projected latents (continuous representation of input before quantization).
298
+ commitment_loss (`torch.Tensor` of shape `(1)`):
299
+ Commitment loss to train the encoder to predict vectors closer to codebook entries.
300
+ codebook_loss (`torch.Tensor` of shape `(1)`):
301
+ Codebook loss to update the codebook.
302
+ """
303
+
304
+ quantized_representation = 0
305
+ residual = hidden_state
306
+ commitment_loss = 0
307
+ codebook_loss = 0
308
+
309
+ audio_codes = []
310
+ projected_latents = []
311
+
312
+ n_quantizers = n_quantizers if n_quantizers is not None else self.n_codebooks
313
+ if self.training:
314
+ n_quantizers = torch.ones((hidden_state.shape[0],)) * self.n_codebooks + 1
315
+ dropout = torch.randint(1, self.n_codebooks + 1, (hidden_state.shape[0],))
316
+ n_dropout = int(hidden_state.shape[0] * self.quantizer_dropout)
317
+ n_quantizers[:n_dropout] = dropout[:n_dropout]
318
+ n_quantizers = n_quantizers.to(hidden_state.device)
319
+
320
+ for i, quantizer in enumerate(self.quantizers):
321
+ if self.training is False and i >= n_quantizers:
322
+ break
323
+
324
+ quantized_representation_i, commitment_loss_i, codebook_loss_i, indices_i, projected_latents_i = quantizer(
325
+ residual
326
+ )
327
+
328
+ # Create mask to apply quantizer dropout
329
+ mask = torch.full((hidden_state.shape[0],), i, device=hidden_state.device, dtype=torch.long) < n_quantizers
330
+ quantized_representation = quantized_representation + quantized_representation_i * mask[:, None, None]
331
+ residual = residual - quantized_representation_i
332
+
333
+ # Sum losses
334
+ commitment_loss += commitment_loss_i * mask
335
+ codebook_loss += codebook_loss_i * mask
336
+
337
+ audio_codes.append(indices_i)
338
+ projected_latents.append(projected_latents_i)
339
+
340
+ audio_codes = torch.stack(audio_codes, dim=1)
341
+ projected_latents = torch.cat(projected_latents, dim=1)
342
+
343
+ return quantized_representation, audio_codes, projected_latents, commitment_loss, codebook_loss
344
+
345
+ def from_codes(self, audio_codes: torch.Tensor):
346
+ """
347
+ Reconstructs the continuous representation from quantized codes.
348
+
349
+ Args:
350
+ audio_codes (`torch.Tensor` of shape `(batch_size, num_codebooks, time_steps)`):
351
+ Quantized discrete representation of input.
352
+
353
+ Returns:
354
+ quantized_representation (`torch.Tensor`):
355
+ Quantized continuous representation of input.
356
+ projected_latents (`torch.Tensor`):
357
+ List of projected latents (continuous representations of input before quantization)
358
+ for each codebook.
359
+ audio_codes (`torch.Tensor`):
360
+ Codebook indices for each codebook.
361
+ """
362
+ quantized_representation = 0.0
363
+ projected_latents = []
364
+ n_codebooks = audio_codes.shape[1]
365
+ for i in range(n_codebooks):
366
+ projected_latents_i = self.quantizers[i].codebook(audio_codes[:, i, :]).transpose(1, 2)
367
+ projected_latents.append(projected_latents_i)
368
+ quantized_representation += self.quantizers[i].out_proj(projected_latents_i)
369
+ return quantized_representation, torch.cat(projected_latents, dim=1), audio_codes
370
+
371
+ def from_latents(self, latents: torch.Tensor):
372
+ """Reconstructs the quantized representation from unquantized latents.
373
+
374
+ Args:
375
+ latents (`torch.Tensor` of shape `(batch_size, total_latent_dimension, time_steps)`):
376
+ Continuous representation of input after projection.
377
+
378
+ Returns:
379
+ quantized_representation (`torch.Tensor` of shape `(batch_size, dimension, time_steps)`):
380
+ Quantized representation of the full-projected space.
381
+ quantized_latents (`torch.Tensor` of shape `(batch_size, dimension, time_steps)`):
382
+ Quantized representation of the latent space (continuous representation before quantization).
383
+ """
384
+ quantized_representation = 0
385
+ quantized_latents = []
386
+ codes = []
387
+ codebook_dims_tensor = torch.tensor([0] + [q.codebook_dim for q in self.quantizers])
388
+ dims = torch.cumsum(codebook_dims_tensor, dim=0)
389
+
390
+ n_codebooks = np.where(dims <= latents.shape[1])[0].max(axis=0, keepdims=True)[0]
391
+ for i in range(n_codebooks):
392
+ hidden_dim_j, hidden_dim_k = dims[i], dims[i + 1]
393
+ latent_chunk = latents[:, hidden_dim_j:hidden_dim_k, :]
394
+ quantized_latents_i, codes_i = self.quantizers[i].decode_latents(latent_chunk)
395
+ quantized_latents.append(quantized_latents_i)
396
+ codes.append(codes_i)
397
+
398
+ quantized_with_ste = latent_chunk + (quantized_latents_i - latent_chunk)
399
+ quantized_representation_i = self.quantizers[i].out_proj(quantized_with_ste)
400
+ quantized_representation = quantized_representation + quantized_representation_i
401
+
402
+ return quantized_representation, torch.cat(quantized_latents, dim=1)
403
+
404
+
405
+ class DacDecoder(nn.Module):
406
+ """DAC Decoder"""
407
+
408
+ def __init__(self, config: DacConfig):
409
+ super().__init__()
410
+
411
+ input_channel = config.hidden_size
412
+ channels = config.decoder_hidden_size
413
+ strides = config.upsampling_ratios
414
+
415
+ # Add first conv layer
416
+ self.conv1 = nn.Conv1d(input_channel, channels, kernel_size=7, padding=3)
417
+
418
+ # Add upsampling + MRF blocks
419
+ block = []
420
+ for stride_index, stride in enumerate(strides):
421
+ block += [DacDecoderBlock(config, stride, stride_index)]
422
+
423
+ self.block = nn.ModuleList(block)
424
+ output_dim = config.decoder_hidden_size // 2 ** (stride_index + 1)
425
+ self.snake1 = Snake1d(output_dim)
426
+ self.conv2 = nn.Conv1d(output_dim, 1, kernel_size=7, padding=3)
427
+ self.tanh = nn.Tanh()
428
+
429
+ def forward(self, hidden_state):
430
+ hidden_state = self.conv1(hidden_state)
431
+
432
+ for layer in self.block:
433
+ hidden_state = layer(hidden_state)
434
+
435
+ hidden_state = self.snake1(hidden_state)
436
+ hidden_state = self.conv2(hidden_state)
437
+ hidden_state = self.tanh(hidden_state)
438
+
439
+ return hidden_state
440
+
441
+
442
+ class DacEncoder(nn.Module):
443
+ """DAC Encoder"""
444
+
445
+ def __init__(self, config: DacConfig):
446
+ super().__init__()
447
+
448
+ strides = config.downsampling_ratios
449
+ # Create first convolution
450
+ self.conv1 = nn.Conv1d(1, config.encoder_hidden_size, kernel_size=7, padding=3)
451
+
452
+ self.block = []
453
+ # Create EncoderBlocks that double channels as they downsample by `stride`
454
+ for stride_index, stride in enumerate(strides):
455
+ stride_index = stride_index + 1
456
+ self.block += [DacEncoderBlock(config, stride=stride, stride_index=stride_index)]
457
+
458
+ self.block = nn.ModuleList(self.block)
459
+ d_model = config.encoder_hidden_size * 2**stride_index
460
+ self.snake1 = Snake1d(d_model)
461
+ self.conv2 = nn.Conv1d(d_model, config.hidden_size, kernel_size=3, padding=1)
462
+
463
+ def forward(self, hidden_state):
464
+ hidden_state = self.conv1(hidden_state)
465
+
466
+ for module in self.block:
467
+ hidden_state = module(hidden_state)
468
+
469
+ hidden_state = self.snake1(hidden_state)
470
+ hidden_state = self.conv2(hidden_state)
471
+
472
+ return hidden_state
473
+
474
+
475
+ @auto_docstring
476
+ class DacPreTrainedModel(PreTrainedAudioTokenizerBase):
477
+ config: DacConfig
478
+ base_model_prefix = "dac"
479
+ main_input_name = "input_values"
480
+
481
+ @torch.no_grad()
482
+ def _init_weights(self, module):
483
+ if isinstance(module, nn.Conv1d):
484
+ init.trunc_normal_(module.weight, std=0.02)
485
+ init.constant_(module.bias, 0)
486
+ elif isinstance(module, Snake1d):
487
+ init.ones_(module.alpha)
488
+ elif isinstance(module, nn.ConvTranspose1d):
489
+ module.reset_parameters()
490
+ elif isinstance(module, nn.Embedding):
491
+ init.normal_(module.weight, mean=0.0, std=0.02)
492
+
493
+ def apply_weight_norm(self):
494
+ weight_norm = nn.utils.weight_norm
495
+ if hasattr(nn.utils.parametrizations, "weight_norm"):
496
+ weight_norm = nn.utils.parametrizations.weight_norm
497
+
498
+ for layer in self.quantizer.quantizers:
499
+ weight_norm(layer.in_proj)
500
+ weight_norm(layer.out_proj)
501
+
502
+ weight_norm(self.encoder.conv1)
503
+ weight_norm(self.encoder.conv2)
504
+
505
+ for layer in self.encoder.block:
506
+ weight_norm(layer.conv1)
507
+ weight_norm(layer.res_unit1.conv1)
508
+ weight_norm(layer.res_unit1.conv2)
509
+ weight_norm(layer.res_unit2.conv1)
510
+ weight_norm(layer.res_unit2.conv2)
511
+ weight_norm(layer.res_unit3.conv1)
512
+ weight_norm(layer.res_unit3.conv2)
513
+
514
+ weight_norm(self.decoder.conv1)
515
+ weight_norm(self.decoder.conv2)
516
+
517
+ for layer in self.decoder.block:
518
+ weight_norm(layer.conv_t1)
519
+ weight_norm(layer.res_unit1.conv1)
520
+ weight_norm(layer.res_unit1.conv2)
521
+ weight_norm(layer.res_unit2.conv1)
522
+ weight_norm(layer.res_unit2.conv2)
523
+ weight_norm(layer.res_unit3.conv1)
524
+ weight_norm(layer.res_unit3.conv2)
525
+
526
+ def remove_weight_norm(self):
527
+ for layer in self.quantizer.quantizers:
528
+ nn.utils.remove_weight_norm(layer.in_proj)
529
+ nn.utils.remove_weight_norm(layer.out_proj)
530
+
531
+ nn.utils.remove_weight_norm(self.encoder.conv1)
532
+ nn.utils.remove_weight_norm(self.encoder.conv2)
533
+
534
+ for layer in self.encoder.block:
535
+ nn.utils.remove_weight_norm(layer.conv1)
536
+ nn.utils.remove_weight_norm(layer.res_unit1.conv1)
537
+ nn.utils.remove_weight_norm(layer.res_unit1.conv2)
538
+ nn.utils.remove_weight_norm(layer.res_unit2.conv1)
539
+ nn.utils.remove_weight_norm(layer.res_unit2.conv2)
540
+ nn.utils.remove_weight_norm(layer.res_unit3.conv1)
541
+ nn.utils.remove_weight_norm(layer.res_unit3.conv2)
542
+
543
+ nn.utils.remove_weight_norm(self.decoder.conv1)
544
+ nn.utils.remove_weight_norm(self.decoder.conv2)
545
+
546
+ for layer in self.decoder.block:
547
+ nn.utils.remove_weight_norm(layer.conv_t1)
548
+ nn.utils.remove_weight_norm(layer.res_unit1.conv1)
549
+ nn.utils.remove_weight_norm(layer.res_unit1.conv2)
550
+ nn.utils.remove_weight_norm(layer.res_unit2.conv1)
551
+ nn.utils.remove_weight_norm(layer.res_unit2.conv2)
552
+ nn.utils.remove_weight_norm(layer.res_unit3.conv1)
553
+ nn.utils.remove_weight_norm(layer.res_unit3.conv2)
554
+
555
+
556
+ @auto_docstring(
557
+ custom_intro="""
558
+ The DAC (Descript Audio Codec) model.
559
+ """
560
+ )
561
+ class DacModel(DacPreTrainedModel):
562
+ input_modalities = "audio"
563
+
564
+ def __init__(self, config: DacConfig):
565
+ super().__init__(config)
566
+ self.config = config
567
+
568
+ self.encoder = DacEncoder(config)
569
+ self.decoder = DacDecoder(config)
570
+
571
+ self.quantizer = DacResidualVectorQuantizer(config)
572
+
573
+ self.bits_per_codebook = int(math.log2(self.config.codebook_size))
574
+ if 2**self.bits_per_codebook != self.config.codebook_size:
575
+ raise ValueError("The codebook_size must be a power of 2.")
576
+
577
+ # Initialize weights and apply final processing
578
+ self.post_init()
579
+
580
+ @auto_docstring
581
+ def encode(
582
+ self,
583
+ input_values: torch.Tensor,
584
+ n_quantizers: int | None = None,
585
+ return_dict: bool | None = None,
586
+ ) -> tuple | DacEncoderOutput:
587
+ r"""
588
+ input_values (`torch.Tensor of shape `(batch_size, 1, time_steps)`):
589
+ Input audio data to encode,
590
+ n_quantizers (int, *optional*):
591
+ Number of quantizers to use. If None, all quantizers are used. Default is None.
592
+ """
593
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
594
+
595
+ quantized_representation = self.encoder(input_values)
596
+ quantized_representation, audio_codes, projected_latents, commitment_loss, codebook_loss = self.quantizer(
597
+ quantized_representation, n_quantizers
598
+ )
599
+
600
+ loss = self.config.commitment_loss_weight * commitment_loss + self.config.codebook_loss_weight * codebook_loss
601
+
602
+ if not return_dict:
603
+ return (loss, quantized_representation, audio_codes, projected_latents)
604
+
605
+ return DacEncoderOutput(loss, quantized_representation, audio_codes, projected_latents)
606
+
607
+ @auto_docstring
608
+ def decode(
609
+ self,
610
+ quantized_representation: torch.Tensor | None = None,
611
+ audio_codes: torch.Tensor | None = None,
612
+ return_dict: bool | None = None,
613
+ ) -> tuple | DacDecoderOutput:
614
+ r"""
615
+ quantized_representation (torch.Tensor of shape `(batch_size, dimension, time_steps)`, *optional*):
616
+ Quantized continuous representation of input.
617
+ audio_codes (`torch.Tensor` of shape `(batch_size, num_codebooks, time_steps)`, *optional*):
618
+ The codebook indices for each codebook, representing the quantized discrete
619
+ representation of the input. This parameter should be provided if you want
620
+ to decode directly from the audio codes (it will overwrite quantized_representation).
621
+ return_dict (`bool`, *optional*, defaults to `True`):
622
+ Whether to return a [`DacDecoderOutput`] instead of a plain tuple.
623
+ """
624
+
625
+ if quantized_representation is None and audio_codes is None:
626
+ raise ValueError("Either `quantized_representation` or `audio_codes` must be provided.")
627
+
628
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
629
+
630
+ if audio_codes is not None:
631
+ quantized_representation = self.quantizer.from_codes(audio_codes)[0]
632
+
633
+ audio_values = self.decoder(quantized_representation).squeeze(1)
634
+
635
+ if not return_dict:
636
+ return (audio_values,)
637
+
638
+ return DacDecoderOutput(audio_values)
639
+
640
+ @auto_docstring
641
+ def forward(
642
+ self,
643
+ input_values: torch.Tensor,
644
+ n_quantizers: int | None = None,
645
+ return_dict: bool | None = None,
646
+ ) -> tuple | DacOutput:
647
+ r"""
648
+ input_values (`torch.Tensor` of shape `(batch_size, 1, time_steps)`):
649
+ Audio data to encode.
650
+ n_quantizers (`int`, *optional*):
651
+ Number of quantizers to use. If `None`, all quantizers are used. Default is `None`.
652
+
653
+ Examples:
654
+
655
+ ```python
656
+ >>> from datasets import load_dataset, Audio
657
+ >>> from transformers import DacModel, AutoProcessor
658
+ >>> librispeech_dummy = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
659
+
660
+ >>> model = DacModel.from_pretrained("descript/dac_16khz")
661
+ >>> processor = AutoProcessor.from_pretrained("descript/dac_16khz")
662
+ >>> librispeech_dummy = librispeech_dummy.cast_column("audio", Audio(sampling_rate=processor.sampling_rate))
663
+ >>> audio_sample = librispeech_dummy[-1]["audio"]["array"]
664
+ >>> inputs = processor(raw_audio=audio_sample, sampling_rate=processor.sampling_rate, return_tensors="pt")
665
+
666
+ >>> encoder_outputs = model.encode(inputs["input_values"])
667
+ >>> # Get the intermediate audio codes
668
+ >>> audio_codes = encoder_outputs.audio_codes
669
+ >>> # Reconstruct the audio from its quantized representation
670
+ >>> audio_values = model.decode(encoder_outputs.quantized_representation)
671
+ >>> # or the equivalent with a forward pass
672
+ >>> audio_values = model(inputs["input_values"]).audio_values
673
+ ```"""
674
+
675
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
676
+ length = input_values.shape[-1]
677
+
678
+ loss, quantized_representation, audio_codes, projected_latents = self.encode(
679
+ input_values, n_quantizers, return_dict=False
680
+ )
681
+ audio_values = self.decode(quantized_representation, return_dict=False)[0][..., :length]
682
+
683
+ if not return_dict:
684
+ return (loss, audio_values, quantized_representation, audio_codes, projected_latents)
685
+
686
+ return DacOutput(loss, audio_values, quantized_representation, audio_codes, projected_latents)
687
+
688
+
689
+ __all__ = ["DacModel", "DacPreTrainedModel"]
miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/models/data2vec/__init__.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_data2vec_audio import *
22
+ from .configuration_data2vec_text import *
23
+ from .configuration_data2vec_vision import *
24
+ from .modeling_data2vec_audio import *
25
+ from .modeling_data2vec_text import *
26
+ from .modeling_data2vec_vision import *
27
+ else:
28
+ import sys
29
+
30
+ _file = globals()["__file__"]
31
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)