ZTWHHH commited on
Commit
ecf320e
·
verified ·
1 Parent(s): 65a2a96

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. videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_ceil_cpu_dispatch.h +24 -0
  2. videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_index_put_impl_meta_dispatch.h +23 -0
  3. videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_shape_as_tensor.h +30 -0
  4. videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_slow_conv2d_backward_cpu_dispatch.h +28 -0
  5. videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/bitwise_or_cuda_dispatch.h +26 -0
  6. videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/cudnn_affine_grid_generator_ops.h +39 -0
  7. videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/cudnn_batch_norm_backward_compositeexplicitautograd_dispatch.h +24 -0
  8. videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/cummax_ops.h +61 -0
  9. videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/mul.h +53 -0
  10. videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/rnn_tanh_ops.h +39 -0
  11. videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/sgn_cpu_dispatch.h +26 -0
  12. videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/sinh_meta.h +27 -0
  13. videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/sparse_coo_tensor_compositeimplicitautograd_dispatch.h +26 -0
  14. videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/sparse_mask_compositeexplicitautograd_dispatch.h +24 -0
  15. videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/special_i0_compositeimplicitautograd_dispatch.h +25 -0
  16. vllm/lib/python3.10/site-packages/transformers/models/emu3/__pycache__/configuration_emu3.cpython-310.pyc +0 -0
  17. vllm/lib/python3.10/site-packages/transformers/models/emu3/__pycache__/image_processing_emu3.cpython-310.pyc +0 -0
  18. vllm/lib/python3.10/site-packages/transformers/models/emu3/__pycache__/modular_emu3.cpython-310.pyc +0 -0
  19. vllm/lib/python3.10/site-packages/transformers/models/emu3/__pycache__/processing_emu3.cpython-310.pyc +0 -0
  20. vllm/lib/python3.10/site-packages/transformers/models/emu3/modeling_emu3.py +2012 -0
  21. vllm/lib/python3.10/site-packages/transformers/models/emu3/modular_emu3.py +1314 -0
  22. vllm/lib/python3.10/site-packages/transformers/models/helium/__pycache__/__init__.cpython-310.pyc +0 -0
  23. vllm/lib/python3.10/site-packages/transformers/models/helium/__pycache__/configuration_helium.cpython-310.pyc +0 -0
  24. vllm/lib/python3.10/site-packages/transformers/models/helium/configuration_helium.py +154 -0
  25. vllm/lib/python3.10/site-packages/transformers/models/helium/modular_helium.py +171 -0
  26. vllm/lib/python3.10/site-packages/transformers/models/mamba2/__init__.py +27 -0
  27. vllm/lib/python3.10/site-packages/transformers/models/mamba2/__pycache__/configuration_mamba2.cpython-310.pyc +0 -0
  28. vllm/lib/python3.10/site-packages/transformers/models/mamba2/configuration_mamba2.py +183 -0
  29. vllm/lib/python3.10/site-packages/transformers/models/mamba2/modeling_mamba2.py +1136 -0
  30. vllm/lib/python3.10/site-packages/transformers/models/mvp/__init__.py +29 -0
  31. vllm/lib/python3.10/site-packages/transformers/models/mvp/__pycache__/__init__.cpython-310.pyc +0 -0
  32. vllm/lib/python3.10/site-packages/transformers/models/mvp/__pycache__/configuration_mvp.cpython-310.pyc +0 -0
  33. vllm/lib/python3.10/site-packages/transformers/models/mvp/__pycache__/modeling_mvp.cpython-310.pyc +0 -0
  34. vllm/lib/python3.10/site-packages/transformers/models/mvp/__pycache__/tokenization_mvp.cpython-310.pyc +0 -0
  35. vllm/lib/python3.10/site-packages/transformers/models/mvp/__pycache__/tokenization_mvp_fast.cpython-310.pyc +0 -0
  36. vllm/lib/python3.10/site-packages/transformers/models/mvp/configuration_mvp.py +183 -0
  37. vllm/lib/python3.10/site-packages/transformers/models/mvp/modeling_mvp.py +1957 -0
  38. vllm/lib/python3.10/site-packages/transformers/models/mvp/tokenization_mvp.py +394 -0
  39. vllm/lib/python3.10/site-packages/transformers/models/mvp/tokenization_mvp_fast.py +274 -0
  40. vllm/lib/python3.10/site-packages/transformers/models/olmo/__pycache__/__init__.cpython-310.pyc +0 -0
  41. vllm/lib/python3.10/site-packages/transformers/models/olmo/__pycache__/modular_olmo.cpython-310.pyc +0 -0
  42. vllm/lib/python3.10/site-packages/transformers/models/olmo2/__init__.py +27 -0
  43. vllm/lib/python3.10/site-packages/transformers/models/olmo2/__pycache__/__init__.cpython-310.pyc +0 -0
  44. vllm/lib/python3.10/site-packages/transformers/models/olmo2/__pycache__/configuration_olmo2.cpython-310.pyc +0 -0
  45. vllm/lib/python3.10/site-packages/transformers/models/olmo2/__pycache__/modeling_olmo2.cpython-310.pyc +0 -0
  46. vllm/lib/python3.10/site-packages/transformers/models/olmo2/__pycache__/modular_olmo2.cpython-310.pyc +0 -0
  47. vllm/lib/python3.10/site-packages/transformers/models/olmo2/configuration_olmo2.py +181 -0
  48. vllm/lib/python3.10/site-packages/transformers/models/olmo2/modeling_olmo2.py +866 -0
  49. vllm/lib/python3.10/site-packages/transformers/models/olmo2/modular_olmo2.py +311 -0
  50. vllm/lib/python3.10/site-packages/transformers/models/roformer/__init__.py +31 -0
videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_ceil_cpu_dispatch.h ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace cpu {
19
+
20
+ TORCH_API ::std::vector<at::Tensor> _foreach_ceil(at::TensorList self);
21
+ TORCH_API void _foreach_ceil_(at::TensorList self);
22
+
23
+ } // namespace cpu
24
+ } // namespace at
videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_index_put_impl_meta_dispatch.h ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace meta {
19
+
20
+ TORCH_API at::Tensor & _index_put_impl_(at::Tensor & self, const c10::List<c10::optional<at::Tensor>> & indices, const at::Tensor & values, bool accumulate=false, bool unsafe=false);
21
+
22
+ } // namespace meta
23
+ } // namespace at
videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_shape_as_tensor.h ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Function.h
4
+
5
+ #include <ATen/Context.h>
6
+ #include <ATen/DeviceGuard.h>
7
+ #include <ATen/TensorUtils.h>
8
+ #include <ATen/TracerMode.h>
9
+ #include <ATen/core/Generator.h>
10
+ #include <ATen/core/Reduction.h>
11
+ #include <ATen/core/Tensor.h>
12
+ #include <c10/core/Scalar.h>
13
+ #include <c10/core/Storage.h>
14
+ #include <c10/core/TensorOptions.h>
15
+ #include <c10/util/Deprecated.h>
16
+ #include <c10/util/Optional.h>
17
+
18
+
19
+
20
+ #include <ATen/ops/_shape_as_tensor_ops.h>
21
+
22
+ namespace at {
23
+
24
+
25
+ // aten::_shape_as_tensor(Tensor self) -> Tensor
26
+ inline at::Tensor _shape_as_tensor(const at::Tensor & self) {
27
+ return at::_ops::_shape_as_tensor::call(self);
28
+ }
29
+
30
+ }
videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_slow_conv2d_backward_cpu_dispatch.h ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace cpu {
19
+
20
+ TORCH_API ::std::tuple<at::Tensor &,at::Tensor &,at::Tensor &> _slow_conv2d_backward_out(at::Tensor & grad_input, at::Tensor & grad_weight, at::Tensor & grad_bias, const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & weight, at::IntArrayRef kernel_size, at::IntArrayRef stride, at::IntArrayRef padding);
21
+ TORCH_API ::std::tuple<at::Tensor &,at::Tensor &,at::Tensor &> _slow_conv2d_backward_outf(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & weight, at::IntArrayRef kernel_size, at::IntArrayRef stride, at::IntArrayRef padding, at::Tensor & grad_input, at::Tensor & grad_weight, at::Tensor & grad_bias);
22
+ TORCH_API ::std::tuple<at::Tensor &,at::Tensor &,at::Tensor &> _slow_conv2d_backward_symint_out(at::Tensor & grad_input, at::Tensor & grad_weight, at::Tensor & grad_bias, const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & weight, c10::SymIntArrayRef kernel_size, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding);
23
+ TORCH_API ::std::tuple<at::Tensor &,at::Tensor &,at::Tensor &> _slow_conv2d_backward_symint_outf(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & weight, c10::SymIntArrayRef kernel_size, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, at::Tensor & grad_input, at::Tensor & grad_weight, at::Tensor & grad_bias);
24
+ TORCH_API ::std::tuple<at::Tensor,at::Tensor,at::Tensor> _slow_conv2d_backward(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & weight, at::IntArrayRef kernel_size, at::IntArrayRef stride, at::IntArrayRef padding, ::std::array<bool,3> output_mask);
25
+ TORCH_API ::std::tuple<at::Tensor,at::Tensor,at::Tensor> _slow_conv2d_backward_symint(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & weight, c10::SymIntArrayRef kernel_size, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, ::std::array<bool,3> output_mask);
26
+
27
+ } // namespace cpu
28
+ } // namespace at
videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/bitwise_or_cuda_dispatch.h ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace cuda {
19
+
20
+ TORCH_API at::Tensor bitwise_or(const at::Tensor & self, const at::Tensor & other);
21
+ TORCH_API at::Tensor & bitwise_or_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & other);
22
+ TORCH_API at::Tensor & bitwise_or_outf(const at::Tensor & self, const at::Tensor & other, at::Tensor & out);
23
+ TORCH_API at::Tensor & bitwise_or_(at::Tensor & self, const at::Tensor & other);
24
+
25
+ } // namespace cuda
26
+ } // namespace at
videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/cudnn_affine_grid_generator_ops.h ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Operator.h
4
+
5
+ #include <tuple>
6
+ #include <vector>
7
+
8
+ // Forward declarations of any types needed in the operator signatures.
9
+ // We can't directly include these classes because it will cause circular include dependencies.
10
+ // This file is included by TensorBody.h, which defines the Tensor class.
11
+ #include <ATen/core/ATen_fwd.h>
12
+
13
+ namespace at {
14
+ namespace _ops {
15
+
16
+
17
+ struct TORCH_API cudnn_affine_grid_generator {
18
+ using schema = at::Tensor (const at::Tensor &, int64_t, int64_t, int64_t, int64_t);
19
+ using ptr_schema = schema*;
20
+ // See Note [static constexpr char* members for windows NVCC]
21
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::cudnn_affine_grid_generator")
22
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
23
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "cudnn_affine_grid_generator(Tensor theta, int N, int C, int H, int W) -> Tensor grid")
24
+ static at::Tensor call(const at::Tensor & theta, int64_t N, int64_t C, int64_t H, int64_t W);
25
+ static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & theta, int64_t N, int64_t C, int64_t H, int64_t W);
26
+ };
27
+
28
+ struct TORCH_API cudnn_affine_grid_generator_out {
29
+ using schema = at::Tensor & (const at::Tensor &, int64_t, int64_t, int64_t, int64_t, at::Tensor &);
30
+ using ptr_schema = schema*;
31
+ // See Note [static constexpr char* members for windows NVCC]
32
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::cudnn_affine_grid_generator")
33
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out")
34
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "cudnn_affine_grid_generator.out(Tensor theta, int N, int C, int H, int W, *, Tensor(a!) out) -> Tensor(a!)")
35
+ static at::Tensor & call(const at::Tensor & theta, int64_t N, int64_t C, int64_t H, int64_t W, at::Tensor & out);
36
+ static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & theta, int64_t N, int64_t C, int64_t H, int64_t W, at::Tensor & out);
37
+ };
38
+
39
+ }} // namespace at::_ops
videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/cudnn_batch_norm_backward_compositeexplicitautograd_dispatch.h ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace compositeexplicitautograd {
19
+
20
+ TORCH_API ::std::tuple<at::Tensor &,at::Tensor &,at::Tensor &> cudnn_batch_norm_backward_out(at::Tensor & out0, at::Tensor & out1, at::Tensor & out2, const at::Tensor & input, const at::Tensor & grad_output, const at::Tensor & weight, const c10::optional<at::Tensor> & running_mean, const c10::optional<at::Tensor> & running_var, const c10::optional<at::Tensor> & save_mean, const c10::optional<at::Tensor> & save_var, double epsilon, const at::Tensor & reserveSpace);
21
+ TORCH_API ::std::tuple<at::Tensor &,at::Tensor &,at::Tensor &> cudnn_batch_norm_backward_outf(const at::Tensor & input, const at::Tensor & grad_output, const at::Tensor & weight, const c10::optional<at::Tensor> & running_mean, const c10::optional<at::Tensor> & running_var, const c10::optional<at::Tensor> & save_mean, const c10::optional<at::Tensor> & save_var, double epsilon, const at::Tensor & reserveSpace, at::Tensor & out0, at::Tensor & out1, at::Tensor & out2);
22
+
23
+ } // namespace compositeexplicitautograd
24
+ } // namespace at
videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/cummax_ops.h ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Operator.h
4
+
5
+ #include <tuple>
6
+ #include <vector>
7
+
8
+ // Forward declarations of any types needed in the operator signatures.
9
+ // We can't directly include these classes because it will cause circular include dependencies.
10
+ // This file is included by TensorBody.h, which defines the Tensor class.
11
+ #include <ATen/core/ATen_fwd.h>
12
+
13
+ namespace at {
14
+ namespace _ops {
15
+
16
+
17
+ struct TORCH_API cummax {
18
+ using schema = ::std::tuple<at::Tensor,at::Tensor> (const at::Tensor &, int64_t);
19
+ using ptr_schema = schema*;
20
+ // See Note [static constexpr char* members for windows NVCC]
21
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::cummax")
22
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
23
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "cummax(Tensor self, int dim) -> (Tensor values, Tensor indices)")
24
+ static ::std::tuple<at::Tensor,at::Tensor> call(const at::Tensor & self, int64_t dim);
25
+ static ::std::tuple<at::Tensor,at::Tensor> redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, int64_t dim);
26
+ };
27
+
28
+ struct TORCH_API cummax_out {
29
+ using schema = ::std::tuple<at::Tensor &,at::Tensor &> (const at::Tensor &, int64_t, at::Tensor &, at::Tensor &);
30
+ using ptr_schema = schema*;
31
+ // See Note [static constexpr char* members for windows NVCC]
32
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::cummax")
33
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out")
34
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "cummax.out(Tensor self, int dim, *, Tensor(a!) values, Tensor(b!) indices) -> (Tensor(a!) values, Tensor(b!) indices)")
35
+ static ::std::tuple<at::Tensor &,at::Tensor &> call(const at::Tensor & self, int64_t dim, at::Tensor & values, at::Tensor & indices);
36
+ static ::std::tuple<at::Tensor &,at::Tensor &> redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, int64_t dim, at::Tensor & values, at::Tensor & indices);
37
+ };
38
+
39
+ struct TORCH_API cummax_dimname {
40
+ using schema = ::std::tuple<at::Tensor,at::Tensor> (const at::Tensor &, at::Dimname);
41
+ using ptr_schema = schema*;
42
+ // See Note [static constexpr char* members for windows NVCC]
43
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::cummax")
44
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "dimname")
45
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "cummax.dimname(Tensor self, Dimname dim) -> (Tensor values, Tensor indices)")
46
+ static ::std::tuple<at::Tensor,at::Tensor> call(const at::Tensor & self, at::Dimname dim);
47
+ static ::std::tuple<at::Tensor,at::Tensor> redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::Dimname dim);
48
+ };
49
+
50
+ struct TORCH_API cummax_dimname_out {
51
+ using schema = ::std::tuple<at::Tensor &,at::Tensor &> (const at::Tensor &, at::Dimname, at::Tensor &, at::Tensor &);
52
+ using ptr_schema = schema*;
53
+ // See Note [static constexpr char* members for windows NVCC]
54
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::cummax")
55
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "dimname_out")
56
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "cummax.dimname_out(Tensor self, Dimname dim, *, Tensor(a!) values, Tensor(b!) indices) -> (Tensor(a!) values, Tensor(b!) indices)")
57
+ static ::std::tuple<at::Tensor &,at::Tensor &> call(const at::Tensor & self, at::Dimname dim, at::Tensor & values, at::Tensor & indices);
58
+ static ::std::tuple<at::Tensor &,at::Tensor &> redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::Dimname dim, at::Tensor & values, at::Tensor & indices);
59
+ };
60
+
61
+ }} // namespace at::_ops
videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/mul.h ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Function.h
4
+
5
+ #include <ATen/Context.h>
6
+ #include <ATen/DeviceGuard.h>
7
+ #include <ATen/TensorUtils.h>
8
+ #include <ATen/TracerMode.h>
9
+ #include <ATen/core/Generator.h>
10
+ #include <ATen/core/Reduction.h>
11
+ #include <ATen/core/Tensor.h>
12
+ #include <c10/core/Scalar.h>
13
+ #include <c10/core/Storage.h>
14
+ #include <c10/core/TensorOptions.h>
15
+ #include <c10/util/Deprecated.h>
16
+ #include <c10/util/Optional.h>
17
+
18
+
19
+
20
+ #include <ATen/ops/mul_ops.h>
21
+
22
+ namespace at {
23
+
24
+
25
+ // aten::mul.Tensor(Tensor self, Tensor other) -> Tensor
26
+ inline at::Tensor mul(const at::Tensor & self, const at::Tensor & other) {
27
+ return at::_ops::mul_Tensor::call(self, other);
28
+ }
29
+
30
+ // aten::mul.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
31
+ inline at::Tensor & mul_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & other) {
32
+ return at::_ops::mul_out::call(self, other, out);
33
+ }
34
+ // aten::mul.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
35
+ inline at::Tensor & mul_outf(const at::Tensor & self, const at::Tensor & other, at::Tensor & out) {
36
+ return at::_ops::mul_out::call(self, other, out);
37
+ }
38
+
39
+ // aten::mul.Scalar(Tensor self, Scalar other) -> Tensor
40
+ inline at::Tensor mul(const at::Tensor & self, const at::Scalar & other) {
41
+ return at::_ops::mul_Scalar::call(self, other);
42
+ }
43
+
44
+ // aten::mul.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!)
45
+ inline at::Tensor & mul_out(at::Tensor & out, const at::Tensor & self, const at::Scalar & other) {
46
+ return at::_ops::mul_Scalar_out::call(self, other, out);
47
+ }
48
+ // aten::mul.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!)
49
+ inline at::Tensor & mul_outf(const at::Tensor & self, const at::Scalar & other, at::Tensor & out) {
50
+ return at::_ops::mul_Scalar_out::call(self, other, out);
51
+ }
52
+
53
+ }
videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/rnn_tanh_ops.h ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Operator.h
4
+
5
+ #include <tuple>
6
+ #include <vector>
7
+
8
+ // Forward declarations of any types needed in the operator signatures.
9
+ // We can't directly include these classes because it will cause circular include dependencies.
10
+ // This file is included by TensorBody.h, which defines the Tensor class.
11
+ #include <ATen/core/ATen_fwd.h>
12
+
13
+ namespace at {
14
+ namespace _ops {
15
+
16
+
17
+ struct TORCH_API rnn_tanh_input {
18
+ using schema = ::std::tuple<at::Tensor,at::Tensor> (const at::Tensor &, const at::Tensor &, at::TensorList, bool, int64_t, double, bool, bool, bool);
19
+ using ptr_schema = schema*;
20
+ // See Note [static constexpr char* members for windows NVCC]
21
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::rnn_tanh")
22
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "input")
23
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "rnn_tanh.input(Tensor input, Tensor hx, Tensor[] params, bool has_biases, int num_layers, float dropout, bool train, bool bidirectional, bool batch_first) -> (Tensor, Tensor)")
24
+ static ::std::tuple<at::Tensor,at::Tensor> call(const at::Tensor & input, const at::Tensor & hx, at::TensorList params, bool has_biases, int64_t num_layers, double dropout, bool train, bool bidirectional, bool batch_first);
25
+ static ::std::tuple<at::Tensor,at::Tensor> redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & input, const at::Tensor & hx, at::TensorList params, bool has_biases, int64_t num_layers, double dropout, bool train, bool bidirectional, bool batch_first);
26
+ };
27
+
28
+ struct TORCH_API rnn_tanh_data {
29
+ using schema = ::std::tuple<at::Tensor,at::Tensor> (const at::Tensor &, const at::Tensor &, const at::Tensor &, at::TensorList, bool, int64_t, double, bool, bool);
30
+ using ptr_schema = schema*;
31
+ // See Note [static constexpr char* members for windows NVCC]
32
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::rnn_tanh")
33
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "data")
34
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "rnn_tanh.data(Tensor data, Tensor batch_sizes, Tensor hx, Tensor[] params, bool has_biases, int num_layers, float dropout, bool train, bool bidirectional) -> (Tensor, Tensor)")
35
+ static ::std::tuple<at::Tensor,at::Tensor> call(const at::Tensor & data, const at::Tensor & batch_sizes, const at::Tensor & hx, at::TensorList params, bool has_biases, int64_t num_layers, double dropout, bool train, bool bidirectional);
36
+ static ::std::tuple<at::Tensor,at::Tensor> redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & data, const at::Tensor & batch_sizes, const at::Tensor & hx, at::TensorList params, bool has_biases, int64_t num_layers, double dropout, bool train, bool bidirectional);
37
+ };
38
+
39
+ }} // namespace at::_ops
videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/sgn_cpu_dispatch.h ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace cpu {
19
+
20
+ TORCH_API at::Tensor sgn(const at::Tensor & self);
21
+ TORCH_API at::Tensor & sgn_out(at::Tensor & out, const at::Tensor & self);
22
+ TORCH_API at::Tensor & sgn_outf(const at::Tensor & self, at::Tensor & out);
23
+ TORCH_API at::Tensor & sgn_(at::Tensor & self);
24
+
25
+ } // namespace cpu
26
+ } // namespace at
videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/sinh_meta.h ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from NativeMetaFunction.h
4
+
5
+ #include <c10/core/Scalar.h>
6
+ #include <c10/core/Storage.h>
7
+ #include <c10/core/TensorOptions.h>
8
+ #include <c10/util/Deprecated.h>
9
+ #include <c10/util/Optional.h>
10
+ #include <c10/core/QScheme.h>
11
+ #include <ATen/core/Reduction.h>
12
+ #include <ATen/TensorIterator.h>
13
+ #include <ATen/TensorMeta.h>
14
+ #include <tuple>
15
+ #include <vector>
16
+
17
+ namespace at {
18
+ namespace meta {
19
+
20
+ struct TORCH_API structured_sinh : public TensorIteratorBase {
21
+
22
+
23
+ void meta(const at::Tensor & self);
24
+ };
25
+
26
+ } // namespace native
27
+ } // namespace at
videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/sparse_coo_tensor_compositeimplicitautograd_dispatch.h ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace compositeimplicitautograd {
19
+
20
+ TORCH_API at::Tensor sparse_coo_tensor(const at::Tensor & indices, const at::Tensor & values, at::TensorOptions options={}, c10::optional<bool> is_coalesced=c10::nullopt);
21
+ TORCH_API at::Tensor sparse_coo_tensor(const at::Tensor & indices, const at::Tensor & values, c10::optional<at::ScalarType> dtype, c10::optional<at::Layout> layout, c10::optional<at::Device> device, c10::optional<bool> pin_memory, c10::optional<bool> is_coalesced);
22
+ TORCH_API at::Tensor sparse_coo_tensor(const at::Tensor & indices, const at::Tensor & values, at::IntArrayRef size, at::TensorOptions options={}, c10::optional<bool> is_coalesced=c10::nullopt);
23
+ TORCH_API at::Tensor sparse_coo_tensor(const at::Tensor & indices, const at::Tensor & values, at::IntArrayRef size, c10::optional<at::ScalarType> dtype, c10::optional<at::Layout> layout, c10::optional<at::Device> device, c10::optional<bool> pin_memory, c10::optional<bool> is_coalesced);
24
+
25
+ } // namespace compositeimplicitautograd
26
+ } // namespace at
videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/sparse_mask_compositeexplicitautograd_dispatch.h ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace compositeexplicitautograd {
19
+
20
+ TORCH_API at::Tensor & sparse_mask_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & mask);
21
+ TORCH_API at::Tensor & sparse_mask_outf(const at::Tensor & self, const at::Tensor & mask, at::Tensor & out);
22
+
23
+ } // namespace compositeexplicitautograd
24
+ } // namespace at
videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/special_i0_compositeimplicitautograd_dispatch.h ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace compositeimplicitautograd {
19
+
20
+ TORCH_API at::Tensor special_i0(const at::Tensor & self);
21
+ TORCH_API at::Tensor & special_i0_out(at::Tensor & out, const at::Tensor & self);
22
+ TORCH_API at::Tensor & special_i0_outf(const at::Tensor & self, at::Tensor & out);
23
+
24
+ } // namespace compositeimplicitautograd
25
+ } // namespace at
vllm/lib/python3.10/site-packages/transformers/models/emu3/__pycache__/configuration_emu3.cpython-310.pyc ADDED
Binary file (14.8 kB). View file
 
vllm/lib/python3.10/site-packages/transformers/models/emu3/__pycache__/image_processing_emu3.cpython-310.pyc ADDED
Binary file (23 kB). View file
 
vllm/lib/python3.10/site-packages/transformers/models/emu3/__pycache__/modular_emu3.cpython-310.pyc ADDED
Binary file (46.7 kB). View file
 
vllm/lib/python3.10/site-packages/transformers/models/emu3/__pycache__/processing_emu3.cpython-310.pyc ADDED
Binary file (8.59 kB). View file
 
vllm/lib/python3.10/site-packages/transformers/models/emu3/modeling_emu3.py ADDED
@@ -0,0 +1,2012 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/emu3/modular_emu3.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_emu3.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # coding=utf-8
8
+ # Copyright 2024 HuggingFace Inc. team. All rights reserved.
9
+ #
10
+ #
11
+ # Licensed under the Apache License, Version 2.0 (the "License");
12
+ # you may not use this file except in compliance with the License.
13
+ # You may obtain a copy of the License at
14
+ #
15
+ # http://www.apache.org/licenses/LICENSE-2.0
16
+ #
17
+ # Unless required by applicable law or agreed to in writing, software
18
+ # distributed under the License is distributed on an "AS IS" BASIS,
19
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20
+ # See the License for the specific language governing permissions and
21
+ # limitations under the License.
22
+
23
+ import math
24
+ from functools import cached_property
25
+ from typing import Callable, List, Optional, Tuple, Union
26
+
27
+ import torch
28
+ import torch.nn as nn
29
+ import torch.nn.functional as F
30
+
31
+ from ...activations import ACT2FN
32
+ from ...cache_utils import Cache, DynamicCache, StaticCache
33
+ from ...generation import GenerationMixin
34
+ from ...modeling_attn_mask_utils import AttentionMaskConverter
35
+ from ...modeling_flash_attention_utils import FlashAttentionKwargs
36
+ from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
37
+ from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS
38
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
39
+ from ...processing_utils import Unpack
40
+ from ...utils import (
41
+ LossKwargs,
42
+ add_start_docstrings,
43
+ add_start_docstrings_to_model_forward,
44
+ is_torch_flex_attn_available,
45
+ logging,
46
+ replace_return_docstrings,
47
+ )
48
+ from ...utils.deprecation import deprecate_kwarg
49
+ from .configuration_emu3 import Emu3Config, Emu3TextConfig, Emu3VQVAEConfig
50
+
51
+
52
+ if is_torch_flex_attn_available():
53
+ from torch.nn.attention.flex_attention import BlockMask
54
+
55
+ from ...integrations.flex_attention import make_flex_block_causal_mask
56
+
57
+
58
+ logger = logging.get_logger(__name__)
59
+
60
+
61
+ _CONFIG_FOR_DOC = "Emu3Config"
62
+
63
+
64
+ class Emu3RMSNorm(nn.Module):
65
+ def __init__(self, hidden_size, eps=1e-6):
66
+ """
67
+ Emu3RMSNorm is equivalent to T5LayerNorm
68
+ """
69
+ super().__init__()
70
+ self.weight = nn.Parameter(torch.ones(hidden_size))
71
+ self.variance_epsilon = eps
72
+
73
+ def forward(self, hidden_states):
74
+ input_dtype = hidden_states.dtype
75
+ hidden_states = hidden_states.to(torch.float32)
76
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
77
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
78
+ return self.weight * hidden_states.to(input_dtype)
79
+
80
+ def extra_repr(self):
81
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
82
+
83
+
84
+ class Emu3MLP(nn.Module):
85
+ def __init__(self, config):
86
+ super().__init__()
87
+ self.config = config
88
+ self.hidden_size = config.hidden_size
89
+ self.intermediate_size = config.intermediate_size
90
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
91
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
92
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)
93
+ self.act_fn = ACT2FN[config.hidden_act]
94
+
95
+ def forward(self, x):
96
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
97
+ return down_proj
98
+
99
+
100
+ def rotate_half(x):
101
+ """Rotates half the hidden dims of the input."""
102
+ x1 = x[..., : x.shape[-1] // 2]
103
+ x2 = x[..., x.shape[-1] // 2 :]
104
+ return torch.cat((-x2, x1), dim=-1)
105
+
106
+
107
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
108
+ """Applies Rotary Position Embedding to the query and key tensors.
109
+
110
+ Args:
111
+ q (`torch.Tensor`): The query tensor.
112
+ k (`torch.Tensor`): The key tensor.
113
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
114
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
115
+ position_ids (`torch.Tensor`, *optional*):
116
+ Deprecated and unused.
117
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
118
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
119
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
120
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
121
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
122
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
123
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
124
+ Returns:
125
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
126
+ """
127
+ cos = cos.unsqueeze(unsqueeze_dim)
128
+ sin = sin.unsqueeze(unsqueeze_dim)
129
+ q_embed = (q * cos) + (rotate_half(q) * sin)
130
+ k_embed = (k * cos) + (rotate_half(k) * sin)
131
+ return q_embed, k_embed
132
+
133
+
134
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
135
+ """
136
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
137
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
138
+ """
139
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
140
+ if n_rep == 1:
141
+ return hidden_states
142
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
143
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
144
+
145
+
146
+ def eager_attention_forward(
147
+ module: nn.Module,
148
+ query: torch.Tensor,
149
+ key: torch.Tensor,
150
+ value: torch.Tensor,
151
+ attention_mask: Optional[torch.Tensor],
152
+ scaling: float,
153
+ dropout: float = 0.0,
154
+ **kwargs,
155
+ ):
156
+ key_states = repeat_kv(key, module.num_key_value_groups)
157
+ value_states = repeat_kv(value, module.num_key_value_groups)
158
+
159
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
160
+ if attention_mask is not None:
161
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
162
+ attn_weights = attn_weights + causal_mask
163
+
164
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
165
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
166
+ attn_output = torch.matmul(attn_weights, value_states)
167
+ attn_output = attn_output.transpose(1, 2).contiguous()
168
+
169
+ return attn_output, attn_weights
170
+
171
+
172
+ class Emu3Attention(nn.Module):
173
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
174
+
175
+ def __init__(self, config: Emu3Config, layer_idx: int):
176
+ super().__init__()
177
+ self.config = config
178
+ self.layer_idx = layer_idx
179
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
180
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
181
+ self.scaling = self.head_dim**-0.5
182
+ self.attention_dropout = config.attention_dropout
183
+ self.is_causal = True
184
+
185
+ self.q_proj = nn.Linear(
186
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
187
+ )
188
+ self.k_proj = nn.Linear(
189
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
190
+ )
191
+ self.v_proj = nn.Linear(
192
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
193
+ )
194
+ self.o_proj = nn.Linear(
195
+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
196
+ )
197
+
198
+ def forward(
199
+ self,
200
+ hidden_states: torch.Tensor,
201
+ position_embeddings: Tuple[torch.Tensor, torch.Tensor],
202
+ attention_mask: Optional[torch.Tensor],
203
+ past_key_value: Optional[Cache] = None,
204
+ cache_position: Optional[torch.LongTensor] = None,
205
+ **kwargs: Unpack[FlashAttentionKwargs],
206
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
207
+ input_shape = hidden_states.shape[:-1]
208
+ hidden_shape = (*input_shape, -1, self.head_dim)
209
+
210
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
211
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
212
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
213
+
214
+ cos, sin = position_embeddings
215
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
216
+
217
+ if past_key_value is not None:
218
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
219
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
220
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
221
+
222
+ attention_interface: Callable = eager_attention_forward
223
+ if self.config._attn_implementation != "eager":
224
+ if self.config._attn_implementation == "sdpa" and kwargs.get("output_attentions", False):
225
+ logger.warning_once(
226
+ "`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to "
227
+ 'eager attention. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
228
+ )
229
+ else:
230
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
231
+
232
+ attn_output, attn_weights = attention_interface(
233
+ self,
234
+ query_states,
235
+ key_states,
236
+ value_states,
237
+ attention_mask,
238
+ dropout=0.0 if not self.training else self.attention_dropout,
239
+ scaling=self.scaling,
240
+ **kwargs,
241
+ )
242
+
243
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
244
+ attn_output = self.o_proj(attn_output)
245
+ return attn_output, attn_weights
246
+
247
+
248
+ class Emu3DecoderLayer(nn.Module):
249
+ def __init__(self, config: Emu3Config, layer_idx: int):
250
+ super().__init__()
251
+ self.hidden_size = config.hidden_size
252
+
253
+ self.self_attn = Emu3Attention(config=config, layer_idx=layer_idx)
254
+
255
+ self.mlp = Emu3MLP(config)
256
+ self.input_layernorm = Emu3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
257
+ self.post_attention_layernorm = Emu3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
258
+ self.dropout = nn.Dropout(config.attention_dropout)
259
+
260
+ def forward(
261
+ self,
262
+ hidden_states: torch.Tensor,
263
+ attention_mask: Optional[torch.Tensor] = None,
264
+ position_ids: Optional[torch.LongTensor] = None,
265
+ past_key_value: Optional[Cache] = None,
266
+ output_attentions: Optional[bool] = False,
267
+ use_cache: Optional[bool] = False,
268
+ cache_position: Optional[torch.LongTensor] = None,
269
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
270
+ **kwargs,
271
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
272
+ """
273
+ Args:
274
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
275
+ attention_mask (`torch.FloatTensor`, *optional*):
276
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
277
+ query_sequence_length, key_sequence_length)` if default attention is used.
278
+ output_attentions (`bool`, *optional*):
279
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
280
+ returned tensors for more detail.
281
+ use_cache (`bool`, *optional*):
282
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
283
+ (see `past_key_values`).
284
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
285
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
286
+ Indices depicting the position of the input sequence tokens in the sequence
287
+ kwargs (`dict`, *optional*):
288
+ Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
289
+ into the model
290
+ """
291
+ residual = hidden_states
292
+
293
+ hidden_states = self.input_layernorm(hidden_states)
294
+
295
+ # Self Attention
296
+ hidden_states, self_attn_weights = self.self_attn(
297
+ hidden_states=hidden_states,
298
+ attention_mask=attention_mask,
299
+ position_ids=position_ids,
300
+ past_key_value=past_key_value,
301
+ output_attentions=output_attentions,
302
+ use_cache=use_cache,
303
+ cache_position=cache_position,
304
+ position_embeddings=position_embeddings,
305
+ **kwargs,
306
+ )
307
+ hidden_states = residual + self.dropout(hidden_states)
308
+
309
+ # Fully Connected
310
+ residual = hidden_states
311
+ hidden_states = self.post_attention_layernorm(hidden_states)
312
+ hidden_states = self.mlp(hidden_states)
313
+ hidden_states = residual + self.dropout(hidden_states)
314
+
315
+ outputs = (hidden_states,)
316
+
317
+ if output_attentions:
318
+ outputs += (self_attn_weights,)
319
+
320
+ return outputs
321
+
322
+
323
+ class Emu3VQVAEVectorQuantizer(nn.Module):
324
+ """
325
+ A module for vector quantization using learned embedding vectors.
326
+
327
+ This module implements the quantization process similar to te one described in
328
+ the VQ-VAE (Vector Quantized Variational AutoEncoder) paper. It quantizes continuous
329
+ input vectors into discrete codebook vectors, which are learned during training.
330
+ Current implementation improves over previous ones by avoiding costly matrix multiplications
331
+ and allowing for post-hoc remapping of indices.
332
+ """
333
+
334
+ def __init__(self, config: Emu3VQVAEConfig):
335
+ super().__init__()
336
+ self.embedding = nn.Embedding(config.codebook_size, config.embed_dim)
337
+ self.embedding.weight.data.uniform_(-1.0 / config.codebook_size, 1.0 / config.codebook_size)
338
+
339
+ def forward(self, hidden_state: torch.Tensor):
340
+ batch_size, temporal, channels, height, width = hidden_state.shape
341
+ hidden_state = hidden_state.permute(0, 1, 3, 4, 2).contiguous()
342
+ hidden_state_flattened = hidden_state.view(-1, channels)
343
+
344
+ # distances from z to embeddings e_j (z - e)^2 = z^2 + e^2 - 2 e * z
345
+ hidden_state_sum = torch.sum(hidden_state_flattened**2, dim=1, keepdim=True)
346
+ embedding_sum = torch.sum(self.embedding.weight**2, dim=1)
347
+
348
+ # "bd,dn->bn",
349
+ distances = 2 * torch.matmul(hidden_state_flattened, self.embedding.weight.transpose(0, 1))
350
+ distances = hidden_state_sum + embedding_sum - distances
351
+
352
+ min_encoding_indices = torch.argmin(distances, dim=1)
353
+ min_encoding_indices = min_encoding_indices.view(batch_size, temporal, height, width)
354
+ return min_encoding_indices
355
+
356
+
357
+ class Emu3VQVAEEncoderConvDownsample(nn.Module):
358
+ def __init__(self, in_channels):
359
+ super().__init__()
360
+ self.conv = nn.Conv2d(in_channels, in_channels, kernel_size=3, stride=2, padding=0)
361
+
362
+ def forward(self, hidden_states):
363
+ # no asymmetric padding in torch conv, must do it ourselves
364
+ hidden_states = F.pad(hidden_states, pad=(0, 1, 0, 1), mode="constant", value=0)
365
+ hidden_states = self.conv(hidden_states)
366
+ return hidden_states
367
+
368
+
369
+ class Emu3VQVAEEncoderConvUpsample(nn.Module):
370
+ def __init__(self, in_channels):
371
+ super().__init__()
372
+ self.conv = nn.Conv2d(in_channels, in_channels, kernel_size=3, stride=1, padding=1)
373
+
374
+ def forward(self, hidden_states):
375
+ hidden_states = F.interpolate(hidden_states, scale_factor=2.0, mode="nearest")
376
+ hidden_states = self.conv(hidden_states)
377
+ return hidden_states
378
+
379
+
380
+ class Emu3VQVAEConv3d(nn.Module):
381
+ def __init__(
382
+ self,
383
+ in_channel: int,
384
+ out_channel: int,
385
+ kernel_size: Tuple[int],
386
+ stride: Tuple[int],
387
+ ):
388
+ super().__init__()
389
+
390
+ padding_sizes = [one_kernel - one_stride for one_kernel, one_stride in zip(kernel_size[1:], stride[1:])]
391
+ self.padding = ()
392
+ for pad_size in padding_sizes[::-1]:
393
+ self.padding += (pad_size // 2 + pad_size % 2, pad_size // 2)
394
+ self.padding += (2, 0)
395
+
396
+ self.conv = nn.Conv3d(
397
+ in_channel,
398
+ out_channel,
399
+ kernel_size,
400
+ stride=stride,
401
+ )
402
+
403
+ def forward(self, hidden_states: torch.Tensor):
404
+ hidden_states = F.pad(hidden_states, self.padding)
405
+ hidden_states = self.conv(hidden_states)
406
+ return hidden_states
407
+
408
+
409
+ class Emu3VQVAESpatialNorm(nn.Module):
410
+ def __init__(
411
+ self,
412
+ in_channels: int,
413
+ out_channels: int,
414
+ ):
415
+ super().__init__()
416
+ self.norm_layer = nn.GroupNorm(
417
+ num_channels=out_channels,
418
+ num_groups=32,
419
+ eps=1e-6,
420
+ affine=True,
421
+ )
422
+
423
+ self.conv_y = nn.Conv2d(
424
+ in_channels,
425
+ out_channels,
426
+ kernel_size=1,
427
+ stride=1,
428
+ padding=0,
429
+ )
430
+ self.conv_b = nn.Conv2d(
431
+ in_channels,
432
+ out_channels,
433
+ kernel_size=1,
434
+ stride=1,
435
+ padding=0,
436
+ )
437
+
438
+ def forward(self, hidden_states: torch.Tensor, quant_states: torch.Tensor):
439
+ quant_states = F.interpolate(quant_states, size=hidden_states.shape[-2:], mode="nearest")
440
+ hidden_states = self.norm_layer(hidden_states)
441
+ hidden_states = hidden_states * self.conv_y(quant_states) + self.conv_b(quant_states)
442
+ return hidden_states
443
+
444
+
445
+ class Emu3VQVAETemporalUpsample(nn.Module):
446
+ def __init__(
447
+ self,
448
+ in_channel: int,
449
+ out_channel: int,
450
+ ):
451
+ super().__init__()
452
+ self.conv = Emu3VQVAEConv3d(
453
+ in_channel,
454
+ out_channel,
455
+ kernel_size=(3, 3, 3),
456
+ stride=(1, 1, 1),
457
+ )
458
+
459
+ def forward(self, hidden_states: torch.Tensor):
460
+ batch_size, channels, temporal, height, width = hidden_states.shape
461
+ hidden_states = hidden_states.permute(0, 1, 3, 4, 2).contiguous().view(batch_size, -1, temporal)
462
+ hidden_states = F.interpolate(hidden_states, scale_factor=2.0, mode="nearest")
463
+ hidden_states = hidden_states.view(batch_size, channels, height, width, -1).permute(0, 1, 4, 2, 3).contiguous()
464
+ hidden_states = self.conv(hidden_states)
465
+ return hidden_states
466
+
467
+
468
+ class Emu3VQVAETemporalDownsample(nn.Module):
469
+ def __init__(
470
+ self,
471
+ in_channel: int,
472
+ out_channel: int,
473
+ ):
474
+ super().__init__()
475
+ self.conv = Emu3VQVAEConv3d(
476
+ in_channel,
477
+ out_channel,
478
+ kernel_size=(4, 3, 3),
479
+ stride=(2, 1, 1),
480
+ )
481
+
482
+ def forward(self, hidden_states: torch.Tensor):
483
+ hidden_states = self.conv(hidden_states)
484
+ return hidden_states
485
+
486
+
487
+ class Emu3VQVAETemporalResnetBlock(nn.Module):
488
+ def __init__(
489
+ self,
490
+ in_channels,
491
+ out_channels=None,
492
+ ):
493
+ super().__init__()
494
+ self.in_channels = in_channels
495
+ self.out_channels = in_channels if out_channels is None else out_channels
496
+
497
+ self.norm1 = nn.BatchNorm3d(in_channels)
498
+ self.conv1 = Emu3VQVAEConv3d(
499
+ in_channels,
500
+ out_channels,
501
+ kernel_size=(3, 3, 3),
502
+ stride=(1, 1, 1),
503
+ )
504
+ self.norm2 = nn.BatchNorm3d(out_channels)
505
+ self.conv2 = Emu3VQVAEConv3d(
506
+ out_channels,
507
+ out_channels,
508
+ kernel_size=(3, 3, 3),
509
+ stride=(1, 1, 1),
510
+ )
511
+ if self.in_channels != self.out_channels:
512
+ self.nin_shortcut = nn.Conv3d(
513
+ in_channels,
514
+ out_channels,
515
+ kernel_size=1,
516
+ stride=1,
517
+ padding=0,
518
+ )
519
+
520
+ def forward(self, hidden_states):
521
+ residual = hidden_states
522
+ hidden_states = self.norm1(hidden_states)
523
+ hidden_states *= torch.sigmoid(hidden_states)
524
+ hidden_states = self.conv1(hidden_states)
525
+
526
+ hidden_states = self.norm2(hidden_states)
527
+ hidden_states *= torch.sigmoid(hidden_states)
528
+ hidden_states = self.conv2(hidden_states)
529
+
530
+ if self.in_channels != self.out_channels:
531
+ residual = self.nin_shortcut(residual)
532
+
533
+ return residual + hidden_states
534
+
535
+
536
+ class Emu3VQVAEResnetBlock(nn.Module):
537
+ def __init__(
538
+ self,
539
+ in_channels: int,
540
+ out_channels: Optional[int] = None,
541
+ quant_channels: Optional[int] = None,
542
+ ):
543
+ super().__init__()
544
+ self.in_channels = in_channels
545
+ out_channels = in_channels if out_channels is None else out_channels
546
+ self.out_channels = out_channels
547
+ self.quant_channels = quant_channels
548
+
549
+ if quant_channels is None:
550
+ self.norm1 = nn.GroupNorm(num_channels=in_channels, num_groups=32, eps=1e-6, affine=True)
551
+ self.norm2 = nn.GroupNorm(num_channels=out_channels, num_groups=32, eps=1e-6, affine=True)
552
+ else:
553
+ self.norm1 = Emu3VQVAESpatialNorm(quant_channels, in_channels)
554
+ self.norm2 = Emu3VQVAESpatialNorm(quant_channels, out_channels)
555
+
556
+ self.conv1 = nn.Conv2d(
557
+ in_channels,
558
+ out_channels,
559
+ kernel_size=3,
560
+ stride=1,
561
+ padding=1,
562
+ )
563
+
564
+ self.conv2 = nn.Conv2d(
565
+ out_channels,
566
+ out_channels,
567
+ kernel_size=3,
568
+ stride=1,
569
+ padding=1,
570
+ )
571
+
572
+ if self.in_channels != self.out_channels:
573
+ self.nin_shortcut = nn.Conv2d(
574
+ in_channels,
575
+ out_channels,
576
+ kernel_size=1,
577
+ stride=1,
578
+ padding=0,
579
+ )
580
+
581
+ def forward(self, hidden_states: torch.Tensor, quant_channels: Optional[torch.Tensor] = None):
582
+ norm_args = () if self.quant_channels is None else (quant_channels,)
583
+
584
+ residual = hidden_states
585
+ hidden_states = self.norm1(hidden_states, *norm_args)
586
+ hidden_states *= torch.sigmoid(hidden_states)
587
+ hidden_states = self.conv1(hidden_states)
588
+
589
+ hidden_states = self.norm2(hidden_states, *norm_args)
590
+ hidden_states *= torch.sigmoid(hidden_states)
591
+ hidden_states = self.conv2(hidden_states)
592
+
593
+ if self.in_channels != self.out_channels:
594
+ residual = self.nin_shortcut(residual)
595
+
596
+ return residual + hidden_states
597
+
598
+
599
+ class Emu3VQVAEAttentionBlock(nn.Module):
600
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
601
+
602
+ def __init__(self, config):
603
+ super().__init__()
604
+ self.config = config
605
+ self.embed_dim = config.hidden_size
606
+ self.num_heads = config.num_attention_heads
607
+ self.head_dim = self.embed_dim // self.num_heads
608
+ if self.head_dim * self.num_heads != self.embed_dim:
609
+ raise ValueError(
610
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
611
+ f" {self.num_heads})."
612
+ )
613
+ self.scale = self.head_dim**-0.5
614
+ self.dropout = config.attention_dropout
615
+
616
+ self.k_proj = nn.Linear(self.embed_dim, self.embed_dim)
617
+ self.v_proj = nn.Linear(self.embed_dim, self.embed_dim)
618
+ self.q_proj = nn.Linear(self.embed_dim, self.embed_dim)
619
+ self.out_proj = nn.Linear(self.embed_dim, self.embed_dim)
620
+
621
+ def forward(
622
+ self,
623
+ hidden_states: torch.Tensor,
624
+ attention_mask: Optional[torch.Tensor] = None,
625
+ output_attentions: Optional[bool] = False,
626
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
627
+ """Input shape: Batch x Time x Channel"""
628
+
629
+ batch_size, q_len, _ = hidden_states.size()
630
+
631
+ query_states = self.q_proj(hidden_states)
632
+ key_states = self.k_proj(hidden_states)
633
+ value_states = self.v_proj(hidden_states)
634
+
635
+ query_states = query_states.view(batch_size, q_len, self.num_heads, self.head_dim).transpose(1, 2)
636
+ key_states = key_states.view(batch_size, q_len, self.num_heads, self.head_dim).transpose(1, 2)
637
+ value_states = value_states.view(batch_size, q_len, self.num_heads, self.head_dim).transpose(1, 2)
638
+
639
+ k_v_seq_len = key_states.shape[-2]
640
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) * self.scale
641
+
642
+ if attn_weights.size() != (batch_size, self.num_heads, q_len, k_v_seq_len):
643
+ raise ValueError(
644
+ f"Attention weights should be of size {(batch_size, self.num_heads, q_len, k_v_seq_len)}, but is"
645
+ f" {attn_weights.size()}"
646
+ )
647
+
648
+ if attention_mask is not None:
649
+ if attention_mask.size() != (batch_size, 1, q_len, k_v_seq_len):
650
+ raise ValueError(
651
+ f"Attention mask should be of size {(batch_size, 1, q_len, k_v_seq_len)}, but is {attention_mask.size()}"
652
+ )
653
+ attn_weights = attn_weights + attention_mask
654
+
655
+ # upcast attention to fp32
656
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
657
+ attn_weights = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
658
+ attn_output = torch.matmul(attn_weights, value_states)
659
+
660
+ if attn_output.size() != (batch_size, self.num_heads, q_len, self.head_dim):
661
+ raise ValueError(
662
+ f"`attn_output` should be of size {(batch_size, self.num_heads, q_len, self.head_dim)}, but is"
663
+ f" {attn_output.size()}"
664
+ )
665
+
666
+ attn_output = attn_output.transpose(1, 2).contiguous()
667
+ attn_output = attn_output.reshape(batch_size, q_len, self.embed_dim)
668
+
669
+ attn_output = self.out_proj(attn_output)
670
+
671
+ return attn_output, attn_weights
672
+
673
+
674
+ class Emu3VQVAEGroupNorm(nn.GroupNorm):
675
+ """
676
+ Same as the torch GroupNorm with the only difference that this ones accepts
677
+ an optional kwarg `quant_states` which is not used. This class makes it easier to
678
+ use SpatialNorm or GroupNorm without conditionals
679
+ """
680
+
681
+ def __init__(self, **kwargs):
682
+ super().__init__(**kwargs)
683
+
684
+ def forward(self, input, quant_states=None):
685
+ return F.group_norm(input, self.num_groups, self.weight, self.bias, self.eps)
686
+
687
+
688
+ class Emu3VQVAEMiddleBlock(nn.Module):
689
+ def __init__(self, config, in_channels, quant_channels=None):
690
+ super().__init__()
691
+
692
+ self.block_1 = Emu3VQVAEResnetBlock(
693
+ in_channels=in_channels,
694
+ out_channels=in_channels,
695
+ quant_channels=quant_channels,
696
+ )
697
+ self.attn_1 = Emu3VQVAEAttentionBlock(config)
698
+ if quant_channels is None:
699
+ self.attn_norm = Emu3VQVAEGroupNorm(num_channels=in_channels, num_groups=32, eps=1e-6, affine=True)
700
+ else:
701
+ self.attn_norm = Emu3VQVAESpatialNorm(quant_channels, in_channels)
702
+
703
+ self.block_2 = Emu3VQVAEResnetBlock(
704
+ in_channels=in_channels,
705
+ out_channels=in_channels,
706
+ quant_channels=quant_channels,
707
+ )
708
+
709
+ def forward(self, hidden_states: torch.FloatTensor, quant_states: torch.FloatTensor = None):
710
+ hidden_states = self.block_1(hidden_states, quant_states)
711
+ residual = hidden_states
712
+ hidden_states = self.attn_norm(hidden_states, quant_states)
713
+ batch_size, channels, height, width = hidden_states.shape
714
+ hidden_states = hidden_states.view(batch_size, channels, height * width).transpose(1, 2)
715
+ hidden_states = self.attn_1(hidden_states)[0]
716
+ hidden_states = hidden_states.reshape(batch_size, height, width, channels).permute(0, 3, 1, 2)
717
+ hidden_states = residual + hidden_states
718
+ hidden_states = self.block_2(hidden_states, quant_states)
719
+ return hidden_states
720
+
721
+
722
+ class Emu3VQVAEDownBlock(nn.Module):
723
+ def __init__(self, config):
724
+ super().__init__()
725
+
726
+ self.num_resolutions = len(config.channel_multiplier)
727
+ self.num_res_blocks = config.num_res_blocks
728
+ base_channels = config.base_channels
729
+ channel_multiplier = config.channel_multiplier
730
+
731
+ in_channel_multiplier = (1,) + tuple(channel_multiplier)
732
+ self.in_channel_multiplier = in_channel_multiplier
733
+ self.down = nn.ModuleList()
734
+ for i_level in range(self.num_resolutions):
735
+ block = nn.ModuleList()
736
+ attn = nn.ModuleList()
737
+ attn_norms = nn.ModuleList()
738
+ block_in = base_channels * in_channel_multiplier[i_level]
739
+ block_out = base_channels * channel_multiplier[i_level]
740
+ for i_block in range(self.num_res_blocks):
741
+ block.append(
742
+ Emu3VQVAEResnetBlock(
743
+ in_channels=block_in,
744
+ out_channels=block_out,
745
+ )
746
+ )
747
+ block_in = block_out
748
+ if config.attn_resolutions is not None and i_level in config.attn_resolutions:
749
+ attn.append(Emu3VQVAEAttentionBlock(config))
750
+ attn_norms.append(nn.GroupNorm(num_channels=block_in, num_groups=32, eps=1e-6, affine=True))
751
+
752
+ down = nn.Module()
753
+ down.block = block
754
+ down.attn = attn
755
+ down.attn_norms = attn_norms
756
+ if i_level != self.num_resolutions - 1:
757
+ down.downsample = Emu3VQVAEEncoderConvDownsample(block_in)
758
+ self.down.append(down)
759
+
760
+ def forward(self, hidden_states: torch.FloatTensor):
761
+ for i_level, blocks in enumerate(self.down):
762
+ for i_block in range(self.num_res_blocks):
763
+ hidden_states = blocks.block[i_block](hidden_states)
764
+ if len(blocks.attn) > 0:
765
+ residual = hidden_states
766
+ hidden_states = blocks.attn_norms[i_block](hidden_states)
767
+
768
+ batch_size, channels, height, width = hidden_states.shape
769
+ hidden_states = hidden_states.view(batch_size, channels, height * width).transpose(1, 2)
770
+ hidden_states = blocks.attn[i_block](hidden_states)[0]
771
+
772
+ hidden_states = hidden_states.reshape(batch_size, height, width, channels).permute(0, 3, 1, 2)
773
+ hidden_states = residual + hidden_states
774
+
775
+ if i_level != self.num_resolutions - 1:
776
+ hidden_states = blocks.downsample(hidden_states)
777
+
778
+ return hidden_states
779
+
780
+
781
+ class Emu3VQVAEUpBlock(nn.Module):
782
+ def __init__(self, config):
783
+ super().__init__()
784
+
785
+ self.num_resolutions = len(config.channel_multiplier)
786
+ self.num_res_blocks = config.num_res_blocks
787
+
788
+ quant_channels = config.embed_dim
789
+ block_in = config.base_channels * config.channel_multiplier[-1]
790
+
791
+ self.up = nn.ModuleList()
792
+ for i_level in reversed(range(self.num_resolutions)):
793
+ block = nn.ModuleList()
794
+ attn = nn.ModuleList()
795
+ attn_norms = nn.ModuleList()
796
+ block_out = config.base_channels * config.channel_multiplier[i_level]
797
+ for i_block in range(self.num_res_blocks + 1):
798
+ block.append(
799
+ Emu3VQVAEResnetBlock(
800
+ in_channels=block_in,
801
+ out_channels=block_out,
802
+ quant_channels=quant_channels,
803
+ )
804
+ )
805
+ block_in = block_out
806
+ if i_level in config.attn_resolutions:
807
+ attn.append(Emu3VQVAEAttentionBlock(config))
808
+ attn_norms.append(Emu3VQVAESpatialNorm(quant_channels, block_in))
809
+
810
+ up = nn.Module()
811
+ up.block = block
812
+ up.attn = attn
813
+ up.attn_norms = attn_norms
814
+ if i_level != 0:
815
+ up.upsample = Emu3VQVAEEncoderConvUpsample(block_in)
816
+
817
+ self.up.insert(0, up)
818
+
819
+ def forward(self, hidden_states: torch.FloatTensor, quant_states: torch.FloatTensor):
820
+ for i_level, blocks in enumerate(self.up[::-1]):
821
+ for i_block in range(self.num_res_blocks + 1):
822
+ hidden_states = blocks.block[i_block](hidden_states, quant_states)
823
+ if len(blocks.attn) > 0:
824
+ residual = hidden_states
825
+ hidden_states = blocks.attn_norms[i_block](hidden_states, quant_states)
826
+
827
+ batch_size, channels, height, width = hidden_states.shape
828
+ hidden_states = hidden_states.view(batch_size, channels, height * width).transpose(1, 2)
829
+ hidden_states = blocks.attn[i_block](hidden_states)[0]
830
+
831
+ hidden_states = hidden_states.reshape(batch_size, height, width, channels).permute(0, 3, 1, 2)
832
+ hidden_states = residual + hidden_states
833
+ if i_level != len(self.up) - 1:
834
+ hidden_states = blocks.upsample(hidden_states)
835
+
836
+ return hidden_states
837
+
838
+
839
+ class Emu3VQVAEEncoder(nn.Module):
840
+ def __init__(self, config):
841
+ super().__init__()
842
+
843
+ base_channels = config.base_channels
844
+ in_channels = config.in_channels
845
+ double_latent = config.double_latent
846
+ latent_channels = config.latent_channels
847
+ channel_multiplier = config.channel_multiplier
848
+ out_channels = 2 * latent_channels if double_latent else latent_channels
849
+ block_in = base_channels * channel_multiplier[-1]
850
+
851
+ self.conv_in = torch.nn.Conv2d(in_channels, base_channels, kernel_size=3, stride=1, padding=1)
852
+ self.down_block = Emu3VQVAEDownBlock(config)
853
+ self.middle_block = Emu3VQVAEMiddleBlock(config, block_in)
854
+
855
+ self.norm_out = torch.nn.GroupNorm(num_groups=32, num_channels=block_in, eps=1e-6, affine=True)
856
+ self.conv_out = torch.nn.Conv2d(
857
+ block_in,
858
+ out_channels,
859
+ kernel_size=3,
860
+ stride=1,
861
+ padding=1,
862
+ )
863
+
864
+ temporal_down_blocks = int(math.log2(config.temporal_downsample_factor))
865
+ self.time_conv = nn.ModuleList()
866
+ self.time_res_stack = nn.ModuleList()
867
+
868
+ for i in range(temporal_down_blocks):
869
+ conv = Emu3VQVAETemporalDownsample(out_channels, out_channels)
870
+ self.time_conv.append(conv)
871
+
872
+ for _ in range(config.num_res_blocks):
873
+ time_res_conv = Emu3VQVAETemporalResnetBlock(
874
+ in_channels=out_channels,
875
+ out_channels=out_channels,
876
+ )
877
+ self.time_res_stack.append(time_res_conv)
878
+
879
+ def forward(self, pixel_values: torch.LongTensor):
880
+ temporal_dim = pixel_values.shape[1]
881
+ pixel_values = pixel_values.reshape(-1, *pixel_values.shape[2:])
882
+
883
+ # downsampling & middle
884
+ hidden_states = self.conv_in(pixel_values)
885
+ hidden_states = self.down_block(hidden_states)
886
+ hidden_states = self.middle_block(hidden_states)
887
+
888
+ # end
889
+ hidden_states = self.norm_out(hidden_states)
890
+ hidden_states *= torch.sigmoid(hidden_states)
891
+ hidden_states = self.conv_out(hidden_states)
892
+
893
+ hidden_states = hidden_states.reshape(-1, temporal_dim, *hidden_states.shape[1:])
894
+ hidden_states = hidden_states.permute(0, 2, 1, 3, 4)
895
+
896
+ # temporal convs
897
+ for conv in self.time_conv:
898
+ hidden_states = conv(hidden_states)
899
+ hidden_states *= torch.sigmoid(hidden_states)
900
+
901
+ for layer in self.time_res_stack:
902
+ hidden_states = layer(hidden_states)
903
+
904
+ hidden_states = hidden_states.permute(0, 2, 1, 3, 4)
905
+
906
+ return hidden_states
907
+
908
+
909
+ class Emu3VQVAEDecoder(nn.Module):
910
+ def __init__(self, config: Emu3VQVAEConfig):
911
+ super().__init__()
912
+
913
+ quant_channels = config.embed_dim
914
+ block_in = config.base_channels * config.channel_multiplier[-1]
915
+ self.time_res_stack = nn.ModuleList()
916
+ for _ in range(config.num_res_blocks):
917
+ time_res_conv = Emu3VQVAETemporalResnetBlock(
918
+ in_channels=config.latent_channels, out_channels=config.latent_channels
919
+ )
920
+ self.time_res_stack.append(time_res_conv)
921
+
922
+ temp_upsample_block_num = int(math.log2(config.temporal_downsample_factor))
923
+ self.time_conv = nn.ModuleList()
924
+ for i in range(temp_upsample_block_num):
925
+ conv = Emu3VQVAETemporalUpsample(config.latent_channels, config.latent_channels)
926
+ self.time_conv.append(conv)
927
+
928
+ self.conv_in = nn.Conv2d(
929
+ config.latent_channels,
930
+ block_in,
931
+ kernel_size=3,
932
+ stride=1,
933
+ padding=1,
934
+ )
935
+
936
+ self.middle_block = Emu3VQVAEMiddleBlock(config, block_in, quant_channels=quant_channels)
937
+ self.up_block = Emu3VQVAEUpBlock(config)
938
+
939
+ block_in = config.base_channels * config.channel_multiplier[0]
940
+ self.norm_out = Emu3VQVAESpatialNorm(quant_channels, block_in)
941
+ self.conv_out = nn.Conv2d(
942
+ block_in,
943
+ config.out_channels,
944
+ kernel_size=3,
945
+ stride=1,
946
+ padding=1,
947
+ )
948
+
949
+ def forward(self, hidden_states: torch.Tensor, quant_states: torch.Tensor):
950
+ hidden_quant_states = torch.cat((hidden_states, quant_states), dim=0)
951
+ hidden_quant_states = hidden_quant_states.permute(0, 2, 1, 3, 4)
952
+
953
+ # temporal convs
954
+ for layer in self.time_res_stack:
955
+ hidden_quant_states = layer(hidden_quant_states)
956
+
957
+ for layer in self.time_conv:
958
+ hidden_quant_states = layer(hidden_quant_states)
959
+ hidden_quant_states *= torch.sigmoid(hidden_quant_states)
960
+
961
+ hidden_quant_states = hidden_quant_states.permute(0, 2, 1, 3, 4)
962
+ hidden_states, quant_states = torch.chunk(hidden_quant_states, 2, dim=0)
963
+ hidden_states = hidden_states.reshape(-1, *hidden_states.shape[2:])
964
+ quant_states = quant_states.reshape(-1, *quant_states.shape[2:])
965
+
966
+ hidden_states = self.conv_in(hidden_states)
967
+
968
+ # middle & upsampling
969
+ hidden_states = self.middle_block(hidden_states, quant_states)
970
+ hidden_states = self.up_block(hidden_states, quant_states)
971
+
972
+ hidden_states = self.norm_out(hidden_states, quant_states)
973
+ hidden_states *= torch.sigmoid(hidden_states)
974
+ hidden_states = self.conv_out(hidden_states)
975
+
976
+ return hidden_states
977
+
978
+
979
+ EMU3_VQ_START_DOCSTRING = r"""
980
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
981
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
982
+ etc.)
983
+
984
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
985
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
986
+ and behavior.
987
+
988
+ Parameters:
989
+ config ([`Emu3VQVAEConfig`]):
990
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
991
+ load the weights associated with the model, only the configuration. Check out the
992
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
993
+ """
994
+
995
+
996
+ @add_start_docstrings(
997
+ """The VQ-VAE model used in Emu3 for encoding/decoding images into discrete tokens.
998
+ This model follows the "Make-a-scene: Scene-based text-to-image generation with human priors" paper from
999
+ [ Oran Gafni, Adam Polyak, Oron Ashual, Shelly Sheynin, Devi Parikh, and Yaniv Taigman](https://arxiv.org/abs/2203.13131).
1000
+ """,
1001
+ EMU3_VQ_START_DOCSTRING,
1002
+ )
1003
+ class Emu3VQVAE(PreTrainedModel):
1004
+ config_class = Emu3VQVAEConfig
1005
+ base_model_prefix = "emuvideovq"
1006
+ main_input_name = "pixel_values"
1007
+ _no_split_modules = [
1008
+ "Emu3VQVAETemporalResnetBlock",
1009
+ "Emu3VQVAEAttentionBlock",
1010
+ "Emu3VQVAEResnetBlock",
1011
+ "Emu3VQVAEVectorQuantizer",
1012
+ ]
1013
+
1014
+ def _init_weights(self, module):
1015
+ if isinstance(module, (nn.Conv2d, nn.Conv3d)):
1016
+ nn.init.kaiming_normal_(module.weight, mode="fan_out", nonlinearity="relu")
1017
+ elif isinstance(module, nn.Linear):
1018
+ nn.init.kaiming_uniform_(module.weight, a=math.sqrt(5))
1019
+ if module.bias is not None:
1020
+ fan_in, _ = nn.init._calculate_fan_in_and_fan_out(module.weight)
1021
+ bound = 1 / math.sqrt(fan_in) if fan_in > 0 else 0
1022
+ nn.init.uniform_(module.bias, -bound, bound)
1023
+ elif isinstance(module, (nn.BatchNorm2d, nn.BatchNorm3d, nn.GroupNorm)):
1024
+ nn.init.constant_(module.weight, 1)
1025
+ nn.init.constant_(module.bias, 0)
1026
+
1027
+ def __init__(self, config: Emu3VQVAEConfig):
1028
+ super().__init__(config)
1029
+
1030
+ self.config = config
1031
+
1032
+ self.encoder = Emu3VQVAEEncoder(config)
1033
+ self.decoder = Emu3VQVAEDecoder(config)
1034
+ self.quantize = Emu3VQVAEVectorQuantizer(config)
1035
+ self.vision_spatial_factor = 2 ** (len(config.channel_multiplier) - 1)
1036
+
1037
+ self.quant_conv = Emu3VQVAEConv3d(
1038
+ config.latent_channels, config.embed_dim, kernel_size=(3, 1, 1), stride=(1, 1, 1)
1039
+ )
1040
+ self.post_quant_conv = Emu3VQVAEConv3d(
1041
+ config.embed_dim, config.latent_channels, kernel_size=(3, 1, 1), stride=(1, 1, 1)
1042
+ )
1043
+ self.spatial_scale_factor = 2 ** (len(config.channel_multiplier) - 1)
1044
+ self.eval() # Emu3's VQ model is frozen
1045
+
1046
+ self.post_init()
1047
+
1048
+ def encode(self, pixel_values: torch.Tensor, image_sizes: torch.Tensor):
1049
+ is_image = pixel_values.ndim == 4
1050
+ if is_image:
1051
+ temporal = self.config.temporal_downsample_factor
1052
+ batch_size, channels, height, width = pixel_values.shape
1053
+ pixel_values = pixel_values.unsqueeze(1).repeat(1, temporal, 1, 1, 1)
1054
+ else:
1055
+ batch_size, temporal, channels, height, width = pixel_values.shape
1056
+
1057
+ hidden_states = self.encoder(pixel_values)
1058
+
1059
+ # b t c h w -> b c t h w
1060
+ hidden_states = hidden_states.permute(0, 2, 1, 3, 4)
1061
+ hidden_states = self.quant_conv(hidden_states)
1062
+
1063
+ # b c t h w -> b t c h w
1064
+ hidden_states = hidden_states.permute(0, 2, 1, 3, 4)
1065
+ codes = self.quantize(hidden_states)
1066
+
1067
+ image_tokens = codes.squeeze(1) if is_image else codes
1068
+
1069
+ image_tokens = [
1070
+ single_image[: int(size[0] / self.vision_spatial_factor), : int(size[1] / self.vision_spatial_factor)]
1071
+ for single_image, size in zip(image_tokens, image_sizes)
1072
+ ]
1073
+
1074
+ return image_tokens
1075
+
1076
+ def decode(self, hidden_states: torch.Tensor):
1077
+ is_image = hidden_states.ndim == 3
1078
+ if is_image:
1079
+ hidden_states = hidden_states.unsqueeze(1)
1080
+
1081
+ batch_size, temporal, height, width = hidden_states.shape
1082
+ quant = self.quantize.embedding(hidden_states.flatten())
1083
+
1084
+ channels = quant.shape[-1]
1085
+ quant = quant.view(batch_size, temporal, height, width, channels).permute(0, 4, 1, 2, 3).contiguous()
1086
+ post_quant = self.post_quant_conv(quant)
1087
+
1088
+ quant = quant.permute(0, 2, 1, 3, 4)
1089
+ post_quant = post_quant.permute(0, 2, 1, 3, 4)
1090
+
1091
+ video = self.decoder(post_quant, quant)
1092
+ video = video.reshape(
1093
+ batch_size,
1094
+ temporal * self.config.temporal_downsample_factor,
1095
+ self.config.out_channels,
1096
+ height * self.spatial_scale_factor,
1097
+ width * self.spatial_scale_factor,
1098
+ )
1099
+ return video[:, 0] if is_image else video
1100
+
1101
+
1102
+ class Emu3ImageVocabularyMapping:
1103
+ """
1104
+ A class for mapping discrete image tokens from VQGAN to BPE tokens.
1105
+ """
1106
+
1107
+ def __init__(self, vocab_map):
1108
+ self.vocab_map = vocab_map
1109
+ self.eol_token_id = vocab_map.get("<|extra_200|>")
1110
+ self.image_token_id = vocab_map.get("<image>")
1111
+
1112
+ @cached_property
1113
+ def image_tokens(self):
1114
+ return sorted([val for name, val in self.vocab_map.items() if name.startswith("<|visual token")])
1115
+
1116
+ @cached_property
1117
+ def image_tokens_str(self):
1118
+ return sorted([name for name, val in self.vocab_map.items() if name.startswith("<|visual token")])
1119
+
1120
+ @cached_property
1121
+ def img2bpe(self):
1122
+ return {int(token[-8:-2]): self.vocab_map[token] for token in self.image_tokens_str}
1123
+
1124
+ @cached_property
1125
+ def bpe2img(self):
1126
+ return {v: k for k, v in self.img2bpe.items()}
1127
+
1128
+ @cached_property
1129
+ def bpe2img_mapping_tensor(self):
1130
+ mapping = torch.zeros(max(self.bpe2img.keys()) + 1, dtype=torch.int)
1131
+ for k, v in self.bpe2img.items():
1132
+ mapping[k] = v
1133
+ return mapping
1134
+
1135
+ @cached_property
1136
+ def img2bpe_mapping_tensor(self):
1137
+ mapping = torch.zeros(max(self.img2bpe.keys()) + 1, dtype=torch.int)
1138
+ for k, v in self.img2bpe.items():
1139
+ mapping[k] = v
1140
+ return mapping
1141
+
1142
+ def convert_img2bpe(self, img_batch: List[torch.Tensor]) -> torch.Tensor:
1143
+ device = img_batch.device
1144
+ eol_row = torch.ones((img_batch.shape[0], 1), dtype=torch.int) * self.eol_token_id
1145
+ img_tokens = self.img2bpe_mapping_tensor[img_batch.to("cpu")]
1146
+ img_tokens = torch.cat([img_tokens, eol_row], dim=-1)
1147
+ return img_tokens.to(device)
1148
+
1149
+ def convert_bpe2img(self, img_batch: torch.Tensor) -> torch.Tensor:
1150
+ device = img_batch.device
1151
+ img_batch = img_batch[..., :-1] # remove last row of EOL tokens
1152
+ img_tokens = self.bpe2img_mapping_tensor[img_batch.to("cpu")]
1153
+ return img_tokens.to(device)
1154
+
1155
+
1156
+ EMU3_START_DOCSTRING = r"""
1157
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
1158
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
1159
+ etc.)
1160
+
1161
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
1162
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
1163
+ and behavior.
1164
+
1165
+ Parameters:
1166
+ config ([`Emu3Config`]):
1167
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
1168
+ load the weights associated with the model, only the configuration. Check out the
1169
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
1170
+ """
1171
+
1172
+
1173
+ @add_start_docstrings(
1174
+ "The bare emu3 Model outputting raw hidden-states without any specific head on top.",
1175
+ EMU3_START_DOCSTRING,
1176
+ )
1177
+ class Emu3PreTrainedModel(PreTrainedModel):
1178
+ config_class = Emu3Config
1179
+ base_model_prefix = "model"
1180
+ supports_gradient_checkpointing = True
1181
+ _no_split_modules = [
1182
+ "Emu3DecoderLayer",
1183
+ ]
1184
+ _skip_keys_device_placement = ["past_key_values", "causal_mask"]
1185
+ _supports_flash_attn_2 = True
1186
+ _supports_sdpa = True
1187
+ _supports_quantized_cache = True
1188
+ _supports_cache_class = True
1189
+ _supports_static_cache = True
1190
+ _supports_param_buffer_assignment = False
1191
+ _supports_flex_attn = True
1192
+
1193
+ def _init_weights(self, module):
1194
+ std = self.config.get_text_config().initializer_range
1195
+ if isinstance(module, Emu3VQVAE):
1196
+ module.apply(module._init_weights)
1197
+ elif isinstance(module, (nn.Linear, nn.Conv2d)):
1198
+ module.weight.data.normal_(mean=0.0, std=std)
1199
+ if module.bias is not None:
1200
+ module.bias.data.zero_()
1201
+ elif isinstance(module, nn.Embedding):
1202
+ module.weight.data.normal_(mean=0.0, std=std)
1203
+ if module.padding_idx is not None:
1204
+ module.weight.data[module.padding_idx].zero_()
1205
+
1206
+
1207
+ class Emu3RotaryEmbedding(nn.Module):
1208
+ def __init__(self, config: Emu3Config, device=None):
1209
+ super().__init__()
1210
+ # BC: "rope_type" was originally "type"
1211
+ if hasattr(config, "rope_scaling") and config.rope_scaling is not None:
1212
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
1213
+ else:
1214
+ self.rope_type = "default"
1215
+ self.max_seq_len_cached = config.max_position_embeddings
1216
+ self.original_max_seq_len = config.max_position_embeddings
1217
+
1218
+ self.config = config
1219
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
1220
+
1221
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
1222
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
1223
+ self.original_inv_freq = self.inv_freq
1224
+
1225
+ def _dynamic_frequency_update(self, position_ids, device):
1226
+ """
1227
+ dynamic RoPE layers should recompute `inv_freq` in the following situations:
1228
+ 1 - growing beyond the cached sequence length (allow scaling)
1229
+ 2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
1230
+ """
1231
+ seq_len = torch.max(position_ids) + 1
1232
+ if seq_len > self.max_seq_len_cached: # growth
1233
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device, seq_len=seq_len)
1234
+ self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: may break with compilation
1235
+ self.max_seq_len_cached = seq_len
1236
+
1237
+ if seq_len < self.original_max_seq_len and self.max_seq_len_cached > self.original_max_seq_len: # reset
1238
+ # This .to() is needed if the model has been moved to a device after being initialized (because
1239
+ # the buffer is automatically moved, but not the original copy)
1240
+ self.original_inv_freq = self.original_inv_freq.to(device)
1241
+ self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)
1242
+ self.max_seq_len_cached = self.original_max_seq_len
1243
+
1244
+ @torch.no_grad()
1245
+ def forward(self, x, position_ids):
1246
+ if "dynamic" in self.rope_type:
1247
+ self._dynamic_frequency_update(position_ids, device=x.device)
1248
+
1249
+ # Core RoPE block
1250
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
1251
+ position_ids_expanded = position_ids[:, None, :].float()
1252
+ # Force float32 (see https://github.com/huggingface/transformers/pull/29285)
1253
+ device_type = x.device.type
1254
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
1255
+ with torch.autocast(device_type=device_type, enabled=False):
1256
+ freqs = (inv_freq_expanded.float().to(x.device) @ position_ids_expanded.float()).transpose(1, 2)
1257
+ emb = torch.cat((freqs, freqs), dim=-1)
1258
+ cos = emb.cos()
1259
+ sin = emb.sin()
1260
+
1261
+ # Advanced RoPE types (e.g. yarn) apply a post-processing scaling factor, equivalent to scaling attention
1262
+ cos = cos * self.attention_scaling
1263
+ sin = sin * self.attention_scaling
1264
+
1265
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
1266
+
1267
+
1268
+ EMU3_TEXT_INPUTS_DOCSTRING = r"""
1269
+ Args:
1270
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1271
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
1272
+ it.
1273
+
1274
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1275
+ [`PreTrainedTokenizer.__call__`] for details.
1276
+
1277
+ [What are input IDs?](../glossary#input-ids)
1278
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1279
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1280
+
1281
+ - 1 for tokens that are **not masked**,
1282
+ - 0 for tokens that are **masked**.
1283
+
1284
+ [What are attention masks?](../glossary#attention-mask)
1285
+
1286
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1287
+ [`PreTrainedTokenizer.__call__`] for details.
1288
+
1289
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
1290
+ `past_key_values`).
1291
+
1292
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
1293
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
1294
+ information on the default strategy.
1295
+
1296
+ - 1 indicates the head is **not masked**,
1297
+ - 0 indicates the head is **masked**.
1298
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1299
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
1300
+ config.n_positions - 1]`.
1301
+
1302
+ [What are position IDs?](../glossary#position-ids)
1303
+ past_key_values (`Cache`, *optional*):
1304
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
1305
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
1306
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
1307
+
1308
+ Has to be an instance of [`~cache_utils.Cache`] instance, see our
1309
+ [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
1310
+
1311
+ The model will output the same cache type that is fed as input. If no `past_key_values` are passed, the
1312
+ legacy cache format will be returned.
1313
+
1314
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
1315
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
1316
+ of shape `(batch_size, sequence_length)`.
1317
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1318
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1319
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1320
+ model's internal embedding lookup matrix.
1321
+ use_cache (`bool`, *optional*):
1322
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1323
+ `past_key_values`).
1324
+ output_attentions (`bool`, *optional*):
1325
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1326
+ tensors for more detail.
1327
+ output_hidden_states (`bool`, *optional*):
1328
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1329
+ more detail.
1330
+ return_dict (`bool`, *optional*):
1331
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1332
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
1333
+ Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
1334
+ this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
1335
+ the complete sequence length.
1336
+ """
1337
+
1338
+
1339
+ @add_start_docstrings(
1340
+ "The bare Emu3Text Model outputting raw hidden-states without any specific head on top.",
1341
+ EMU3_START_DOCSTRING,
1342
+ )
1343
+ class Emu3TextModel(Emu3PreTrainedModel):
1344
+ """
1345
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`Emu3TextDecoderLayer`]
1346
+
1347
+ Args:
1348
+ config: Emu3TextConfig
1349
+ """
1350
+
1351
+ def __init__(self, config: Emu3Config):
1352
+ super().__init__(config)
1353
+ self.padding_idx = config.pad_token_id
1354
+ self.vocab_size = config.vocab_size
1355
+
1356
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
1357
+ self.layers = nn.ModuleList(
1358
+ [Emu3DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
1359
+ )
1360
+ self.norm = Emu3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1361
+ self.rotary_emb = Emu3RotaryEmbedding(config=config)
1362
+ self.gradient_checkpointing = False
1363
+
1364
+ # Initialize weights and apply final processing
1365
+ self.post_init()
1366
+
1367
+ def get_input_embeddings(self):
1368
+ return self.embed_tokens
1369
+
1370
+ def set_input_embeddings(self, value):
1371
+ self.embed_tokens = value
1372
+
1373
+ @add_start_docstrings_to_model_forward(EMU3_TEXT_INPUTS_DOCSTRING)
1374
+ def forward(
1375
+ self,
1376
+ input_ids: torch.LongTensor = None,
1377
+ attention_mask: Optional[torch.Tensor] = None,
1378
+ position_ids: Optional[torch.LongTensor] = None,
1379
+ past_key_values: Optional[Cache] = None,
1380
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1381
+ use_cache: Optional[bool] = None,
1382
+ output_attentions: Optional[bool] = None,
1383
+ output_hidden_states: Optional[bool] = None,
1384
+ return_dict: Optional[bool] = None,
1385
+ cache_position: Optional[torch.LongTensor] = None,
1386
+ **flash_attn_kwargs: Unpack[FlashAttentionKwargs],
1387
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
1388
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1389
+ output_hidden_states = (
1390
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1391
+ )
1392
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1393
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1394
+
1395
+ if (input_ids is None) ^ (inputs_embeds is not None):
1396
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
1397
+
1398
+ if self.gradient_checkpointing and self.training and use_cache:
1399
+ logger.warning_once(
1400
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
1401
+ )
1402
+ use_cache = False
1403
+
1404
+ if inputs_embeds is None:
1405
+ inputs_embeds = self.embed_tokens(input_ids)
1406
+
1407
+ if use_cache and past_key_values is None:
1408
+ past_key_values = DynamicCache()
1409
+
1410
+ if cache_position is None:
1411
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
1412
+ cache_position = torch.arange(
1413
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
1414
+ )
1415
+
1416
+ if position_ids is None:
1417
+ position_ids = cache_position.unsqueeze(0)
1418
+
1419
+ causal_mask = self._update_causal_mask(
1420
+ attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
1421
+ )
1422
+
1423
+ hidden_states = inputs_embeds
1424
+
1425
+ # create position embeddings to be shared across the decoder layers
1426
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
1427
+
1428
+ # decoder layers
1429
+ all_hidden_states = () if output_hidden_states else None
1430
+ all_self_attns = () if output_attentions else None
1431
+
1432
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
1433
+ if output_hidden_states:
1434
+ all_hidden_states += (hidden_states,)
1435
+
1436
+ if self.gradient_checkpointing and self.training:
1437
+ layer_outputs = self._gradient_checkpointing_func(
1438
+ decoder_layer.__call__,
1439
+ hidden_states,
1440
+ causal_mask,
1441
+ position_ids,
1442
+ past_key_values,
1443
+ output_attentions,
1444
+ use_cache,
1445
+ cache_position,
1446
+ position_embeddings,
1447
+ )
1448
+ else:
1449
+ layer_outputs = decoder_layer(
1450
+ hidden_states,
1451
+ attention_mask=causal_mask,
1452
+ position_ids=position_ids,
1453
+ past_key_value=past_key_values,
1454
+ output_attentions=output_attentions,
1455
+ use_cache=use_cache,
1456
+ cache_position=cache_position,
1457
+ position_embeddings=position_embeddings,
1458
+ **flash_attn_kwargs,
1459
+ )
1460
+
1461
+ hidden_states = layer_outputs[0]
1462
+
1463
+ if output_attentions:
1464
+ all_self_attns += (layer_outputs[1],)
1465
+
1466
+ hidden_states = self.norm(hidden_states)
1467
+
1468
+ # add hidden states from the last decoder layer
1469
+ if output_hidden_states:
1470
+ all_hidden_states += (hidden_states,)
1471
+
1472
+ output = BaseModelOutputWithPast(
1473
+ last_hidden_state=hidden_states,
1474
+ past_key_values=past_key_values if use_cache else None,
1475
+ hidden_states=all_hidden_states,
1476
+ attentions=all_self_attns,
1477
+ )
1478
+ return output if return_dict else output.to_tuple()
1479
+
1480
+ def _update_causal_mask(
1481
+ self,
1482
+ attention_mask: torch.Tensor,
1483
+ input_tensor: torch.Tensor,
1484
+ cache_position: torch.Tensor,
1485
+ past_key_values: Cache,
1486
+ output_attentions: bool = False,
1487
+ ):
1488
+ if self.config._attn_implementation == "flash_attention_2":
1489
+ if attention_mask is not None and (attention_mask == 0.0).any():
1490
+ return attention_mask
1491
+ return None
1492
+ if self.config._attn_implementation == "flex_attention":
1493
+ if isinstance(attention_mask, torch.Tensor):
1494
+ attention_mask = make_flex_block_causal_mask(attention_mask)
1495
+ if isinstance(attention_mask, BlockMask):
1496
+ return attention_mask
1497
+
1498
+ # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
1499
+ # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
1500
+ # to infer the attention mask.
1501
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
1502
+ using_static_cache = isinstance(past_key_values, StaticCache)
1503
+
1504
+ # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
1505
+ if self.config._attn_implementation == "sdpa" and not using_static_cache and not output_attentions:
1506
+ if AttentionMaskConverter._ignore_causal_mask_sdpa(
1507
+ attention_mask,
1508
+ inputs_embeds=input_tensor,
1509
+ past_key_values_length=past_seen_tokens,
1510
+ is_training=self.training,
1511
+ ):
1512
+ return None
1513
+
1514
+ dtype, device = input_tensor.dtype, input_tensor.device
1515
+ sequence_length = input_tensor.shape[1]
1516
+ if using_static_cache:
1517
+ target_length = past_key_values.get_max_cache_shape()
1518
+ else:
1519
+ target_length = (
1520
+ attention_mask.shape[-1]
1521
+ if isinstance(attention_mask, torch.Tensor)
1522
+ else past_seen_tokens + sequence_length + 1
1523
+ )
1524
+
1525
+ # In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
1526
+ causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
1527
+ attention_mask,
1528
+ sequence_length=sequence_length,
1529
+ target_length=target_length,
1530
+ dtype=dtype,
1531
+ device=device,
1532
+ cache_position=cache_position,
1533
+ batch_size=input_tensor.shape[0],
1534
+ )
1535
+
1536
+ if (
1537
+ self.config._attn_implementation == "sdpa"
1538
+ and attention_mask is not None
1539
+ and attention_mask.device.type in ["cuda", "xpu"]
1540
+ and not output_attentions
1541
+ ):
1542
+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
1543
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
1544
+ # Details: https://github.com/pytorch/pytorch/issues/110213
1545
+ min_dtype = torch.finfo(dtype).min
1546
+ causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
1547
+
1548
+ return causal_mask
1549
+
1550
+ @staticmethod
1551
+ def _prepare_4d_causal_attention_mask_with_cache_position(
1552
+ attention_mask: torch.Tensor,
1553
+ sequence_length: int,
1554
+ target_length: int,
1555
+ dtype: torch.dtype,
1556
+ device: torch.device,
1557
+ cache_position: torch.Tensor,
1558
+ batch_size: int,
1559
+ **kwargs,
1560
+ ):
1561
+ """
1562
+ Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
1563
+ `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
1564
+
1565
+ Args:
1566
+ attention_mask (`torch.Tensor`):
1567
+ A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
1568
+ `(batch_size, 1, query_length, key_value_length)`.
1569
+ sequence_length (`int`):
1570
+ The sequence length being processed.
1571
+ target_length (`int`):
1572
+ The target length: when generating with static cache, the mask should be as long as the static cache,
1573
+ to account for the 0 padding, the part of the cache that is not filled yet.
1574
+ dtype (`torch.dtype`):
1575
+ The dtype to use for the 4D attention mask.
1576
+ device (`torch.device`):
1577
+ The device to place the 4D attention mask on.
1578
+ cache_position (`torch.Tensor`):
1579
+ Indices depicting the position of the input sequence tokens in the sequence.
1580
+ batch_size (`torch.Tensor`):
1581
+ Batch size.
1582
+ """
1583
+ if attention_mask is not None and attention_mask.dim() == 4:
1584
+ # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
1585
+ causal_mask = attention_mask
1586
+ else:
1587
+ min_dtype = torch.finfo(dtype).min
1588
+ causal_mask = torch.full(
1589
+ (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device
1590
+ )
1591
+ if sequence_length != 1:
1592
+ causal_mask = torch.triu(causal_mask, diagonal=1)
1593
+ causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
1594
+ causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
1595
+ if attention_mask is not None:
1596
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
1597
+ mask_length = attention_mask.shape[-1]
1598
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :].to(
1599
+ causal_mask.device
1600
+ )
1601
+ padding_mask = padding_mask == 0
1602
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
1603
+ padding_mask, min_dtype
1604
+ )
1605
+
1606
+ return causal_mask
1607
+
1608
+
1609
+ class KwargsForCausalLM(FlashAttentionKwargs, LossKwargs): ...
1610
+
1611
+
1612
+ class Emu3ForCausalLM(Emu3PreTrainedModel, GenerationMixin):
1613
+ _tied_weights_keys = ["lm_head.weight"]
1614
+ _tp_plan = {"lm_head": "colwise_rep"}
1615
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
1616
+ config_class = Emu3TextConfig
1617
+
1618
+ def __init__(self, config):
1619
+ super().__init__(config)
1620
+ self.model = Emu3TextModel(config)
1621
+ self.vocab_size = config.vocab_size
1622
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1623
+
1624
+ # Initialize weights and apply final processing
1625
+ self.post_init()
1626
+
1627
+ def get_input_embeddings(self):
1628
+ return self.model.embed_tokens
1629
+
1630
+ def set_input_embeddings(self, value):
1631
+ self.model.embed_tokens = value
1632
+
1633
+ def get_output_embeddings(self):
1634
+ return self.lm_head
1635
+
1636
+ def set_output_embeddings(self, new_embeddings):
1637
+ self.lm_head = new_embeddings
1638
+
1639
+ def set_decoder(self, decoder):
1640
+ self.model = decoder
1641
+
1642
+ def get_decoder(self):
1643
+ return self.model
1644
+
1645
+ @deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep")
1646
+ @add_start_docstrings_to_model_forward(EMU3_TEXT_INPUTS_DOCSTRING)
1647
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class="Emu3TextConfig")
1648
+ def forward(
1649
+ self,
1650
+ input_ids: torch.LongTensor = None,
1651
+ attention_mask: Optional[torch.Tensor] = None,
1652
+ position_ids: Optional[torch.LongTensor] = None,
1653
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
1654
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1655
+ labels: Optional[torch.LongTensor] = None,
1656
+ use_cache: Optional[bool] = None,
1657
+ output_attentions: Optional[bool] = None,
1658
+ output_hidden_states: Optional[bool] = None,
1659
+ return_dict: Optional[bool] = None,
1660
+ cache_position: Optional[torch.LongTensor] = None,
1661
+ logits_to_keep: Union[int, torch.Tensor] = 0,
1662
+ **kwargs: Unpack[KwargsForCausalLM],
1663
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1664
+ r"""
1665
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1666
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1667
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1668
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1669
+
1670
+ logits_to_keep (`int` or `torch.Tensor`, *optional*):
1671
+ If an `int`, compute logits for the last `logits_to_keep` tokens. If `0`, calculate logits for all
1672
+ `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
1673
+ token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
1674
+ If a `torch.Tensor`, must be 1D corresponding to the indices to keep in the sequence length dimension.
1675
+ This is useful when using packed tensor format (single dimension for batch and sequence length).
1676
+
1677
+ Returns:
1678
+
1679
+ Example:
1680
+
1681
+ ```python
1682
+ >>> from transformers import Emu3Processor, Emu3ForConditionalGeneration
1683
+ >>> import torch
1684
+ >>> import requests
1685
+ >>> from PIL import Image
1686
+
1687
+ >>> model = Emu3ForCausalLM.from_pretrained("BAAI/Emu3-Chat-hf", torch_dtype=torch.bfloat16)
1688
+ >>> processor = Emu3Processor.from_pretrained("BAAI/Emu3-Chat-hf")
1689
+
1690
+ >>> inputs = processor(text=["Can you write me a poem about winter."], return_tensors="pt").to(model.device)
1691
+
1692
+ >>> generated_ids = model.generate(**inputs, max_new_tokens=100, do_sample=False)
1693
+ >>> processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
1694
+ ```"""
1695
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1696
+ output_hidden_states = (
1697
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1698
+ )
1699
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1700
+
1701
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1702
+ outputs = self.model(
1703
+ input_ids=input_ids,
1704
+ attention_mask=attention_mask,
1705
+ position_ids=position_ids,
1706
+ past_key_values=past_key_values,
1707
+ inputs_embeds=inputs_embeds,
1708
+ use_cache=use_cache,
1709
+ output_attentions=output_attentions,
1710
+ output_hidden_states=output_hidden_states,
1711
+ return_dict=return_dict,
1712
+ cache_position=cache_position,
1713
+ **kwargs,
1714
+ )
1715
+
1716
+ hidden_states = outputs[0]
1717
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
1718
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
1719
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
1720
+
1721
+ loss = None
1722
+ if labels is not None:
1723
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
1724
+
1725
+ if not return_dict:
1726
+ output = (logits,) + outputs[1:]
1727
+ return (loss,) + output if loss is not None else output
1728
+
1729
+ return CausalLMOutputWithPast(
1730
+ loss=loss,
1731
+ logits=logits,
1732
+ past_key_values=outputs.past_key_values,
1733
+ hidden_states=outputs.hidden_states,
1734
+ attentions=outputs.attentions,
1735
+ )
1736
+
1737
+
1738
+ EMU3_INPUTS_DOCSTRING = r"""
1739
+ Args:
1740
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1741
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
1742
+ it.
1743
+
1744
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1745
+ [`PreTrainedTokenizer.__call__`] for details.
1746
+
1747
+ [What are input IDs?](../glossary#input-ids)
1748
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, max_num_images, max_num_tiles, channels, image_size, image_size)):
1749
+ The tensors corresponding to the input images. Pixel values can be obtained using
1750
+ [`AutoImageProcessor`]. See [`Emu3ImageProcessor.__call__`] for details ([]`Emu3Processor`] uses
1751
+ [`Emu3ImageProcessor`] for processing images).
1752
+ image_sizes (`torch.LongTensor` of shape `(batch_size, 2)`):
1753
+ The sizes of the images in the batch, being (height, width) for each image. Image sizes can be obtained using
1754
+ [`AutoImageProcessor`]. See [`Emu3ImageProcessor.__call__`] for details ([]`Emu3Processor`] uses
1755
+ [`Emu3ImageProcessor`] for processing images).
1756
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1757
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1758
+
1759
+ - 1 for tokens that are **not masked**,
1760
+ - 0 for tokens that are **masked**.
1761
+
1762
+ [What are attention masks?](../glossary#attention-mask)
1763
+
1764
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1765
+ [`PreTrainedTokenizer.__call__`] for details.
1766
+
1767
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
1768
+ `past_key_values`).
1769
+
1770
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
1771
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
1772
+ information on the default strategy.
1773
+
1774
+ - 1 indicates the head is **not masked**,
1775
+ - 0 indicates the head is **masked**.
1776
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1777
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
1778
+ config.n_positions - 1]`.
1779
+
1780
+ [What are position IDs?](../glossary#position-ids)
1781
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
1782
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
1783
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
1784
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
1785
+
1786
+ Has to be an instance of [`~cache_utils.Cache`] instance, see our
1787
+ [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
1788
+
1789
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
1790
+ legacy cache format will be returned.
1791
+
1792
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
1793
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
1794
+ of shape `(batch_size, sequence_length)`.
1795
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1796
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1797
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1798
+ model's internal embedding lookup matrix.
1799
+ use_cache (`bool`, *optional*):
1800
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1801
+ `past_key_values`).
1802
+ output_attentions (`bool`, *optional*):
1803
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1804
+ tensors for more detail.
1805
+ output_hidden_states (`bool`, *optional*):
1806
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1807
+ more detail.
1808
+ return_dict (`bool`, *optional*):
1809
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1810
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
1811
+ Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
1812
+ this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
1813
+ the complete sequence length.
1814
+ """
1815
+
1816
+
1817
+ class Emu3ForConditionalGeneration(Emu3PreTrainedModel, GenerationMixin):
1818
+ _tied_weights_keys = ["text_model.lm_head.weight"]
1819
+ _supports_static_cache = False # `get_image_tokens()`, called when `pixel_values` is passed, is not compileable
1820
+
1821
+ def __init__(self, config):
1822
+ super().__init__(config)
1823
+ self.text_model = Emu3ForCausalLM._from_config(config.text_config)
1824
+ self.vqmodel = Emu3VQVAE(config.vq_config)
1825
+ self.vocabulary_mapping = Emu3ImageVocabularyMapping(config.vocabulary_map)
1826
+
1827
+ # Initialize weights and apply final processing
1828
+ self.post_init()
1829
+
1830
+ def get_input_embeddings(self):
1831
+ return self.text_model.get_input_embeddings()
1832
+
1833
+ def set_input_embeddings(self, value):
1834
+ self.text_model.set_input_embeddings(value)
1835
+
1836
+ def get_image_tokens(self, pixel_values: torch.FloatTensor, image_sizes: torch.LongTensor):
1837
+ """
1838
+ Tokenizes images into discrete tokens with VQGAN module. Converts
1839
+ obtained image tokens into BPE tokens and wraps with "boi" and "eoi"
1840
+ special tokens.
1841
+
1842
+ Args:
1843
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`):
1844
+ The tensors corresponding to the input images.
1845
+ image_sizes (`torch.LongTensor` of shape `(batch_size, 2)`):
1846
+ The sizes of the images in the batch, being (height, width) for each image.
1847
+ """
1848
+ image_tokens_list = self.vqmodel.encode(pixel_values, image_sizes)
1849
+ bpe_tokens_list = [self.vocabulary_mapping.convert_img2bpe(tokens).flatten() for tokens in image_tokens_list]
1850
+ bpe_tokens = torch.cat(bpe_tokens_list)
1851
+ return bpe_tokens
1852
+
1853
+ @torch.no_grad
1854
+ def decode_image_tokens(self, image_tokens: torch.LongTensor, height: int, width: int):
1855
+ """
1856
+ Decodes generated image tokens from language model to continuous pixel values
1857
+ with VQGAN module via upsampling.
1858
+
1859
+ Args:
1860
+ image_tokens (`torch.LongTensor` of shape `(batch_size, num_of_tokens)`):
1861
+ The tensors corresponding to the input images.
1862
+ height (`int`):
1863
+ Height of the generated image before upsampling.
1864
+ width (`int`):
1865
+ Width of the generated image before upsampling.
1866
+ """
1867
+ sequences = image_tokens[:, :-3].view(-1, height, width + 1)
1868
+ image_tokens = self.vocabulary_mapping.convert_bpe2img(sequences)
1869
+ image = self.vqmodel.decode(image_tokens)
1870
+ return image
1871
+
1872
+ @add_start_docstrings_to_model_forward(EMU3_INPUTS_DOCSTRING)
1873
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1874
+ def forward(
1875
+ self,
1876
+ input_ids: torch.LongTensor = None,
1877
+ pixel_values: torch.FloatTensor = None,
1878
+ image_sizes: torch.Tensor = None,
1879
+ attention_mask: Optional[torch.Tensor] = None,
1880
+ position_ids: Optional[torch.LongTensor] = None,
1881
+ past_key_values: Optional[Cache] = None,
1882
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1883
+ use_cache: Optional[bool] = None,
1884
+ output_attentions: Optional[bool] = None,
1885
+ output_hidden_states: Optional[bool] = None,
1886
+ return_dict: Optional[bool] = None,
1887
+ cache_position: Optional[torch.LongTensor] = None,
1888
+ labels: Optional[torch.LongTensor] = None,
1889
+ logits_to_keep: Union[int, torch.Tensor] = 0,
1890
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1891
+ r"""
1892
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1893
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1894
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1895
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1896
+
1897
+ logits_to_keep (`int` or `torch.Tensor`, *optional*):
1898
+ If an `int`, compute logits for the last `logits_to_keep` tokens. If `0`, calculate logits for all
1899
+ `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
1900
+ token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
1901
+ If a `torch.Tensor`, must be 1D corresponding to the indices to keep in the sequence length dimension.
1902
+ This is useful when using packed tensor format (single dimension for batch and sequence length).
1903
+
1904
+ Returns:
1905
+
1906
+ Example:
1907
+
1908
+ ```python
1909
+ >>> from transformers import Emu3Processor, Emu3ForConditionalGeneration
1910
+ >>> import torch
1911
+ >>> import requests
1912
+ >>> from PIL import Image
1913
+
1914
+ >>> model = Emu3ForConditionalGeneration.from_pretrained("BAAI/Emu3-Chat-hf", torch_dtype=torch.bfloat16)
1915
+ >>> processor = Emu3Processor.from_pretrained("BAAI/Emu3-Chat-hf")
1916
+
1917
+ >>> conversation = [
1918
+ ... {
1919
+ ... "role": "system",
1920
+ ... "content": [
1921
+ ... {"type": "text", "text": "You are a helpful assistant."},
1922
+ ... ],
1923
+ ... },
1924
+ ... {
1925
+ ... "role": "user",
1926
+ ... "content": [
1927
+ ... {"type": "image"},
1928
+ ... {"type": "text", "text": "Please describe the image."},
1929
+ ... ],
1930
+ ... },
1931
+ ... ]
1932
+
1933
+ >>> prompt = processor.apply_chat_template(conversation, add_generation_prompt=True)
1934
+ >>> image = Image.open(requests.get("https://www.ilankelman.org/stopsigns/australia.jpg", stream=True).raw)
1935
+
1936
+ >>> inputs = processor(images=[image], text=[prompt], return_tensors="pt").to(model.device, torch.bfloat16)
1937
+
1938
+ >>> generated_ids = model.generate(**inputs, max_new_tokens=100, do_sample=False)
1939
+ >>> processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
1940
+ ```"""
1941
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1942
+ output_hidden_states = (
1943
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1944
+ )
1945
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1946
+
1947
+ if (input_ids is None) ^ (inputs_embeds is not None):
1948
+ raise ValueError(
1949
+ "You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one"
1950
+ )
1951
+
1952
+ if pixel_values is not None and inputs_embeds is not None:
1953
+ raise ValueError(
1954
+ "You cannot specify both pixel_values and inputs_embeds at the same time, and must specify either one"
1955
+ )
1956
+
1957
+ if pixel_values is not None:
1958
+ image_tokens = self.get_image_tokens(pixel_values, image_sizes)
1959
+ special_image_mask = input_ids == self.vocabulary_mapping.image_token_id
1960
+ image_tokens = image_tokens.to(input_ids.device, input_ids.dtype)
1961
+ input_ids = input_ids.masked_scatter(special_image_mask, image_tokens)
1962
+
1963
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1964
+ outputs = self.text_model(
1965
+ input_ids=input_ids,
1966
+ attention_mask=attention_mask,
1967
+ position_ids=position_ids,
1968
+ past_key_values=past_key_values,
1969
+ inputs_embeds=inputs_embeds,
1970
+ use_cache=use_cache,
1971
+ output_attentions=output_attentions,
1972
+ output_hidden_states=output_hidden_states,
1973
+ return_dict=return_dict,
1974
+ cache_position=cache_position,
1975
+ logits_to_keep=logits_to_keep,
1976
+ )
1977
+
1978
+ return outputs
1979
+
1980
+ def prepare_inputs_for_generation(
1981
+ self,
1982
+ input_ids,
1983
+ past_key_values=None,
1984
+ attention_mask=None,
1985
+ inputs_embeds=None,
1986
+ cache_position=None,
1987
+ position_ids=None,
1988
+ use_cache=True,
1989
+ pixel_values=None,
1990
+ **kwargs,
1991
+ ):
1992
+ # Overwritten -- in specific circumstances we don't want to forward image inputs to the model
1993
+
1994
+ model_inputs = super().prepare_inputs_for_generation(
1995
+ input_ids,
1996
+ past_key_values=past_key_values,
1997
+ attention_mask=attention_mask,
1998
+ inputs_embeds=inputs_embeds,
1999
+ cache_position=cache_position,
2000
+ position_ids=position_ids,
2001
+ pixel_values=pixel_values,
2002
+ use_cache=use_cache,
2003
+ **kwargs,
2004
+ )
2005
+
2006
+ if cache_position[0] != 0:
2007
+ model_inputs["pixel_values"] = None
2008
+
2009
+ return model_inputs
2010
+
2011
+
2012
+ __all__ = ["Emu3ForConditionalGeneration", "Emu3ForCausalLM", "Emu3TextModel", "Emu3PreTrainedModel", "Emu3VQVAE"]
vllm/lib/python3.10/site-packages/transformers/models/emu3/modular_emu3.py ADDED
@@ -0,0 +1,1314 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ import math
18
+ from functools import cached_property
19
+ from typing import List, Optional, Tuple, Union
20
+
21
+ import torch
22
+ import torch.nn as nn
23
+ import torch.nn.functional as F
24
+ import torch.utils.checkpoint
25
+
26
+ from ...cache_utils import Cache
27
+ from ...generation import GenerationMixin
28
+ from ...modeling_outputs import (
29
+ CausalLMOutputWithPast,
30
+ )
31
+ from ...modeling_utils import PreTrainedModel
32
+ from ...utils import (
33
+ add_start_docstrings,
34
+ add_start_docstrings_to_model_forward,
35
+ is_flash_attn_2_available,
36
+ logging,
37
+ replace_return_docstrings,
38
+ )
39
+ from ...utils.deprecation import deprecate_kwarg
40
+ from ..chameleon.modeling_chameleon import (
41
+ ChameleonPreTrainedModel,
42
+ ChameleonVQVAEEncoderConvDownsample,
43
+ )
44
+ from ..llama.modeling_llama import (
45
+ LlamaDecoderLayer,
46
+ LlamaForCausalLM,
47
+ LlamaModel,
48
+ )
49
+ from ..siglip.modeling_siglip import SiglipAttention
50
+ from .configuration_emu3 import Emu3Config, Emu3TextConfig, Emu3VQVAEConfig
51
+
52
+
53
+ if is_flash_attn_2_available():
54
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
55
+
56
+
57
+ _CONFIG_FOR_DOC = "Emu3Config"
58
+ _CHECKPOINT_FOR_DOC = "BAAI/Emu3-Chat-hf"
59
+
60
+ logger = logging.get_logger(__name__)
61
+
62
+
63
+ # Has extra dropout which no other model in the library has
64
+ class Emu3DecoderLayer(LlamaDecoderLayer):
65
+ def __init__(self, config: Emu3Config, layer_idx: int):
66
+ super().__init__(config, layer_idx)
67
+ self.dropout = nn.Dropout(config.attention_dropout)
68
+
69
+ def forward(
70
+ self,
71
+ hidden_states: torch.Tensor,
72
+ attention_mask: Optional[torch.Tensor] = None,
73
+ position_ids: Optional[torch.LongTensor] = None,
74
+ past_key_value: Optional[Cache] = None,
75
+ output_attentions: Optional[bool] = False,
76
+ use_cache: Optional[bool] = False,
77
+ cache_position: Optional[torch.LongTensor] = None,
78
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
79
+ **kwargs,
80
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
81
+ """
82
+ Args:
83
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
84
+ attention_mask (`torch.FloatTensor`, *optional*):
85
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
86
+ query_sequence_length, key_sequence_length)` if default attention is used.
87
+ output_attentions (`bool`, *optional*):
88
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
89
+ returned tensors for more detail.
90
+ use_cache (`bool`, *optional*):
91
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
92
+ (see `past_key_values`).
93
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
94
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
95
+ Indices depicting the position of the input sequence tokens in the sequence
96
+ kwargs (`dict`, *optional*):
97
+ Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
98
+ into the model
99
+ """
100
+ residual = hidden_states
101
+
102
+ hidden_states = self.input_layernorm(hidden_states)
103
+
104
+ # Self Attention
105
+ hidden_states, self_attn_weights = self.self_attn(
106
+ hidden_states=hidden_states,
107
+ attention_mask=attention_mask,
108
+ position_ids=position_ids,
109
+ past_key_value=past_key_value,
110
+ output_attentions=output_attentions,
111
+ use_cache=use_cache,
112
+ cache_position=cache_position,
113
+ position_embeddings=position_embeddings,
114
+ **kwargs,
115
+ )
116
+ hidden_states = residual + self.dropout(hidden_states)
117
+
118
+ # Fully Connected
119
+ residual = hidden_states
120
+ hidden_states = self.post_attention_layernorm(hidden_states)
121
+ hidden_states = self.mlp(hidden_states)
122
+ hidden_states = residual + self.dropout(hidden_states)
123
+
124
+ outputs = (hidden_states,)
125
+
126
+ if output_attentions:
127
+ outputs += (self_attn_weights,)
128
+
129
+ return outputs
130
+
131
+
132
+ class Emu3VQVAEVectorQuantizer(nn.Module):
133
+ """
134
+ A module for vector quantization using learned embedding vectors.
135
+
136
+ This module implements the quantization process similar to te one described in
137
+ the VQ-VAE (Vector Quantized Variational AutoEncoder) paper. It quantizes continuous
138
+ input vectors into discrete codebook vectors, which are learned during training.
139
+ Current implementation improves over previous ones by avoiding costly matrix multiplications
140
+ and allowing for post-hoc remapping of indices.
141
+ """
142
+
143
+ def __init__(self, config: Emu3VQVAEConfig):
144
+ super().__init__()
145
+ self.embedding = nn.Embedding(config.codebook_size, config.embed_dim)
146
+ self.embedding.weight.data.uniform_(-1.0 / config.codebook_size, 1.0 / config.codebook_size)
147
+
148
+ def forward(self, hidden_state: torch.Tensor):
149
+ batch_size, temporal, channels, height, width = hidden_state.shape
150
+ hidden_state = hidden_state.permute(0, 1, 3, 4, 2).contiguous()
151
+ hidden_state_flattened = hidden_state.view(-1, channels)
152
+
153
+ # distances from z to embeddings e_j (z - e)^2 = z^2 + e^2 - 2 e * z
154
+ hidden_state_sum = torch.sum(hidden_state_flattened**2, dim=1, keepdim=True)
155
+ embedding_sum = torch.sum(self.embedding.weight**2, dim=1)
156
+
157
+ # "bd,dn->bn",
158
+ distances = 2 * torch.matmul(hidden_state_flattened, self.embedding.weight.transpose(0, 1))
159
+ distances = hidden_state_sum + embedding_sum - distances
160
+
161
+ min_encoding_indices = torch.argmin(distances, dim=1)
162
+ min_encoding_indices = min_encoding_indices.view(batch_size, temporal, height, width)
163
+ return min_encoding_indices
164
+
165
+
166
+ class Emu3VQVAEEncoderConvDownsample(ChameleonVQVAEEncoderConvDownsample):
167
+ pass
168
+
169
+
170
+ class Emu3VQVAEEncoderConvUpsample(nn.Module):
171
+ def __init__(self, in_channels):
172
+ super().__init__()
173
+ self.conv = nn.Conv2d(in_channels, in_channels, kernel_size=3, stride=1, padding=1)
174
+
175
+ def forward(self, hidden_states):
176
+ hidden_states = F.interpolate(hidden_states, scale_factor=2.0, mode="nearest")
177
+ hidden_states = self.conv(hidden_states)
178
+ return hidden_states
179
+
180
+
181
+ class Emu3VQVAEConv3d(nn.Module):
182
+ def __init__(
183
+ self,
184
+ in_channel: int,
185
+ out_channel: int,
186
+ kernel_size: Tuple[int],
187
+ stride: Tuple[int],
188
+ ):
189
+ super().__init__()
190
+
191
+ padding_sizes = [one_kernel - one_stride for one_kernel, one_stride in zip(kernel_size[1:], stride[1:])]
192
+ self.padding = ()
193
+ for pad_size in padding_sizes[::-1]:
194
+ self.padding += (pad_size // 2 + pad_size % 2, pad_size // 2)
195
+ self.padding += (2, 0)
196
+
197
+ self.conv = nn.Conv3d(
198
+ in_channel,
199
+ out_channel,
200
+ kernel_size,
201
+ stride=stride,
202
+ )
203
+
204
+ def forward(self, hidden_states: torch.Tensor):
205
+ hidden_states = F.pad(hidden_states, self.padding)
206
+ hidden_states = self.conv(hidden_states)
207
+ return hidden_states
208
+
209
+
210
+ class Emu3VQVAESpatialNorm(nn.Module):
211
+ def __init__(
212
+ self,
213
+ in_channels: int,
214
+ out_channels: int,
215
+ ):
216
+ super().__init__()
217
+ self.norm_layer = nn.GroupNorm(
218
+ num_channels=out_channels,
219
+ num_groups=32,
220
+ eps=1e-6,
221
+ affine=True,
222
+ )
223
+
224
+ self.conv_y = nn.Conv2d(
225
+ in_channels,
226
+ out_channels,
227
+ kernel_size=1,
228
+ stride=1,
229
+ padding=0,
230
+ )
231
+ self.conv_b = nn.Conv2d(
232
+ in_channels,
233
+ out_channels,
234
+ kernel_size=1,
235
+ stride=1,
236
+ padding=0,
237
+ )
238
+
239
+ def forward(self, hidden_states: torch.Tensor, quant_states: torch.Tensor):
240
+ quant_states = F.interpolate(quant_states, size=hidden_states.shape[-2:], mode="nearest")
241
+ hidden_states = self.norm_layer(hidden_states)
242
+ hidden_states = hidden_states * self.conv_y(quant_states) + self.conv_b(quant_states)
243
+ return hidden_states
244
+
245
+
246
+ class Emu3VQVAETemporalUpsample(nn.Module):
247
+ def __init__(
248
+ self,
249
+ in_channel: int,
250
+ out_channel: int,
251
+ ):
252
+ super().__init__()
253
+ self.conv = Emu3VQVAEConv3d(
254
+ in_channel,
255
+ out_channel,
256
+ kernel_size=(3, 3, 3),
257
+ stride=(1, 1, 1),
258
+ )
259
+
260
+ def forward(self, hidden_states: torch.Tensor):
261
+ batch_size, channels, temporal, height, width = hidden_states.shape
262
+ hidden_states = hidden_states.permute(0, 1, 3, 4, 2).contiguous().view(batch_size, -1, temporal)
263
+ hidden_states = F.interpolate(hidden_states, scale_factor=2.0, mode="nearest")
264
+ hidden_states = hidden_states.view(batch_size, channels, height, width, -1).permute(0, 1, 4, 2, 3).contiguous()
265
+ hidden_states = self.conv(hidden_states)
266
+ return hidden_states
267
+
268
+
269
+ class Emu3VQVAETemporalDownsample(nn.Module):
270
+ def __init__(
271
+ self,
272
+ in_channel: int,
273
+ out_channel: int,
274
+ ):
275
+ super().__init__()
276
+ self.conv = Emu3VQVAEConv3d(
277
+ in_channel,
278
+ out_channel,
279
+ kernel_size=(4, 3, 3),
280
+ stride=(2, 1, 1),
281
+ )
282
+
283
+ def forward(self, hidden_states: torch.Tensor):
284
+ hidden_states = self.conv(hidden_states)
285
+ return hidden_states
286
+
287
+
288
+ class Emu3VQVAETemporalResnetBlock(nn.Module):
289
+ def __init__(
290
+ self,
291
+ in_channels,
292
+ out_channels=None,
293
+ ):
294
+ super().__init__()
295
+ self.in_channels = in_channels
296
+ self.out_channels = in_channels if out_channels is None else out_channels
297
+
298
+ self.norm1 = nn.BatchNorm3d(in_channels)
299
+ self.conv1 = Emu3VQVAEConv3d(
300
+ in_channels,
301
+ out_channels,
302
+ kernel_size=(3, 3, 3),
303
+ stride=(1, 1, 1),
304
+ )
305
+ self.norm2 = nn.BatchNorm3d(out_channels)
306
+ self.conv2 = Emu3VQVAEConv3d(
307
+ out_channels,
308
+ out_channels,
309
+ kernel_size=(3, 3, 3),
310
+ stride=(1, 1, 1),
311
+ )
312
+ if self.in_channels != self.out_channels:
313
+ self.nin_shortcut = nn.Conv3d(
314
+ in_channels,
315
+ out_channels,
316
+ kernel_size=1,
317
+ stride=1,
318
+ padding=0,
319
+ )
320
+
321
+ def forward(self, hidden_states):
322
+ residual = hidden_states
323
+ hidden_states = self.norm1(hidden_states)
324
+ hidden_states *= torch.sigmoid(hidden_states)
325
+ hidden_states = self.conv1(hidden_states)
326
+
327
+ hidden_states = self.norm2(hidden_states)
328
+ hidden_states *= torch.sigmoid(hidden_states)
329
+ hidden_states = self.conv2(hidden_states)
330
+
331
+ if self.in_channels != self.out_channels:
332
+ residual = self.nin_shortcut(residual)
333
+
334
+ return residual + hidden_states
335
+
336
+
337
+ class Emu3VQVAEResnetBlock(nn.Module):
338
+ def __init__(
339
+ self,
340
+ in_channels: int,
341
+ out_channels: Optional[int] = None,
342
+ quant_channels: Optional[int] = None,
343
+ ):
344
+ super().__init__()
345
+ self.in_channels = in_channels
346
+ out_channels = in_channels if out_channels is None else out_channels
347
+ self.out_channels = out_channels
348
+ self.quant_channels = quant_channels
349
+
350
+ if quant_channels is None:
351
+ self.norm1 = nn.GroupNorm(num_channels=in_channels, num_groups=32, eps=1e-6, affine=True)
352
+ self.norm2 = nn.GroupNorm(num_channels=out_channels, num_groups=32, eps=1e-6, affine=True)
353
+ else:
354
+ self.norm1 = Emu3VQVAESpatialNorm(quant_channels, in_channels)
355
+ self.norm2 = Emu3VQVAESpatialNorm(quant_channels, out_channels)
356
+
357
+ self.conv1 = nn.Conv2d(
358
+ in_channels,
359
+ out_channels,
360
+ kernel_size=3,
361
+ stride=1,
362
+ padding=1,
363
+ )
364
+
365
+ self.conv2 = nn.Conv2d(
366
+ out_channels,
367
+ out_channels,
368
+ kernel_size=3,
369
+ stride=1,
370
+ padding=1,
371
+ )
372
+
373
+ if self.in_channels != self.out_channels:
374
+ self.nin_shortcut = nn.Conv2d(
375
+ in_channels,
376
+ out_channels,
377
+ kernel_size=1,
378
+ stride=1,
379
+ padding=0,
380
+ )
381
+
382
+ def forward(self, hidden_states: torch.Tensor, quant_channels: Optional[torch.Tensor] = None):
383
+ norm_args = () if self.quant_channels is None else (quant_channels,)
384
+
385
+ residual = hidden_states
386
+ hidden_states = self.norm1(hidden_states, *norm_args)
387
+ hidden_states *= torch.sigmoid(hidden_states)
388
+ hidden_states = self.conv1(hidden_states)
389
+
390
+ hidden_states = self.norm2(hidden_states, *norm_args)
391
+ hidden_states *= torch.sigmoid(hidden_states)
392
+ hidden_states = self.conv2(hidden_states)
393
+
394
+ if self.in_channels != self.out_channels:
395
+ residual = self.nin_shortcut(residual)
396
+
397
+ return residual + hidden_states
398
+
399
+
400
+ class Emu3VQVAEAttentionBlock(SiglipAttention):
401
+ pass
402
+
403
+
404
+ class Emu3VQVAEGroupNorm(nn.GroupNorm):
405
+ """
406
+ Same as the torch GroupNorm with the only difference that this ones accepts
407
+ an optional kwarg `quant_states` which is not used. This class makes it easier to
408
+ use SpatialNorm or GroupNorm without conditionals
409
+ """
410
+
411
+ def __init__(self, **kwargs):
412
+ super().__init__(**kwargs)
413
+
414
+ def forward(self, input, quant_states=None):
415
+ return F.group_norm(input, self.num_groups, self.weight, self.bias, self.eps)
416
+
417
+
418
+ class Emu3VQVAEMiddleBlock(nn.Module):
419
+ def __init__(self, config, in_channels, quant_channels=None):
420
+ super().__init__()
421
+
422
+ self.block_1 = Emu3VQVAEResnetBlock(
423
+ in_channels=in_channels,
424
+ out_channels=in_channels,
425
+ quant_channels=quant_channels,
426
+ )
427
+ self.attn_1 = Emu3VQVAEAttentionBlock(config)
428
+ if quant_channels is None:
429
+ self.attn_norm = Emu3VQVAEGroupNorm(num_channels=in_channels, num_groups=32, eps=1e-6, affine=True)
430
+ else:
431
+ self.attn_norm = Emu3VQVAESpatialNorm(quant_channels, in_channels)
432
+
433
+ self.block_2 = Emu3VQVAEResnetBlock(
434
+ in_channels=in_channels,
435
+ out_channels=in_channels,
436
+ quant_channels=quant_channels,
437
+ )
438
+
439
+ def forward(self, hidden_states: torch.FloatTensor, quant_states: torch.FloatTensor = None):
440
+ hidden_states = self.block_1(hidden_states, quant_states)
441
+ residual = hidden_states
442
+ hidden_states = self.attn_norm(hidden_states, quant_states)
443
+ batch_size, channels, height, width = hidden_states.shape
444
+ hidden_states = hidden_states.view(batch_size, channels, height * width).transpose(1, 2)
445
+ hidden_states = self.attn_1(hidden_states)[0]
446
+ hidden_states = hidden_states.reshape(batch_size, height, width, channels).permute(0, 3, 1, 2)
447
+ hidden_states = residual + hidden_states
448
+ hidden_states = self.block_2(hidden_states, quant_states)
449
+ return hidden_states
450
+
451
+
452
+ class Emu3VQVAEDownBlock(nn.Module):
453
+ def __init__(self, config):
454
+ super().__init__()
455
+
456
+ self.num_resolutions = len(config.channel_multiplier)
457
+ self.num_res_blocks = config.num_res_blocks
458
+ base_channels = config.base_channels
459
+ channel_multiplier = config.channel_multiplier
460
+
461
+ in_channel_multiplier = (1,) + tuple(channel_multiplier)
462
+ self.in_channel_multiplier = in_channel_multiplier
463
+ self.down = nn.ModuleList()
464
+ for i_level in range(self.num_resolutions):
465
+ block = nn.ModuleList()
466
+ attn = nn.ModuleList()
467
+ attn_norms = nn.ModuleList()
468
+ block_in = base_channels * in_channel_multiplier[i_level]
469
+ block_out = base_channels * channel_multiplier[i_level]
470
+ for i_block in range(self.num_res_blocks):
471
+ block.append(
472
+ Emu3VQVAEResnetBlock(
473
+ in_channels=block_in,
474
+ out_channels=block_out,
475
+ )
476
+ )
477
+ block_in = block_out
478
+ if config.attn_resolutions is not None and i_level in config.attn_resolutions:
479
+ attn.append(Emu3VQVAEAttentionBlock(config))
480
+ attn_norms.append(nn.GroupNorm(num_channels=block_in, num_groups=32, eps=1e-6, affine=True))
481
+
482
+ down = nn.Module()
483
+ down.block = block
484
+ down.attn = attn
485
+ down.attn_norms = attn_norms
486
+ if i_level != self.num_resolutions - 1:
487
+ down.downsample = Emu3VQVAEEncoderConvDownsample(block_in)
488
+ self.down.append(down)
489
+
490
+ def forward(self, hidden_states: torch.FloatTensor):
491
+ for i_level, blocks in enumerate(self.down):
492
+ for i_block in range(self.num_res_blocks):
493
+ hidden_states = blocks.block[i_block](hidden_states)
494
+ if len(blocks.attn) > 0:
495
+ residual = hidden_states
496
+ hidden_states = blocks.attn_norms[i_block](hidden_states)
497
+
498
+ batch_size, channels, height, width = hidden_states.shape
499
+ hidden_states = hidden_states.view(batch_size, channels, height * width).transpose(1, 2)
500
+ hidden_states = blocks.attn[i_block](hidden_states)[0]
501
+
502
+ hidden_states = hidden_states.reshape(batch_size, height, width, channels).permute(0, 3, 1, 2)
503
+ hidden_states = residual + hidden_states
504
+
505
+ if i_level != self.num_resolutions - 1:
506
+ hidden_states = blocks.downsample(hidden_states)
507
+
508
+ return hidden_states
509
+
510
+
511
+ class Emu3VQVAEUpBlock(nn.Module):
512
+ def __init__(self, config):
513
+ super().__init__()
514
+
515
+ self.num_resolutions = len(config.channel_multiplier)
516
+ self.num_res_blocks = config.num_res_blocks
517
+
518
+ quant_channels = config.embed_dim
519
+ block_in = config.base_channels * config.channel_multiplier[-1]
520
+
521
+ self.up = nn.ModuleList()
522
+ for i_level in reversed(range(self.num_resolutions)):
523
+ block = nn.ModuleList()
524
+ attn = nn.ModuleList()
525
+ attn_norms = nn.ModuleList()
526
+ block_out = config.base_channels * config.channel_multiplier[i_level]
527
+ for i_block in range(self.num_res_blocks + 1):
528
+ block.append(
529
+ Emu3VQVAEResnetBlock(
530
+ in_channels=block_in,
531
+ out_channels=block_out,
532
+ quant_channels=quant_channels,
533
+ )
534
+ )
535
+ block_in = block_out
536
+ if i_level in config.attn_resolutions:
537
+ attn.append(Emu3VQVAEAttentionBlock(config))
538
+ attn_norms.append(Emu3VQVAESpatialNorm(quant_channels, block_in))
539
+
540
+ up = nn.Module()
541
+ up.block = block
542
+ up.attn = attn
543
+ up.attn_norms = attn_norms
544
+ if i_level != 0:
545
+ up.upsample = Emu3VQVAEEncoderConvUpsample(block_in)
546
+
547
+ self.up.insert(0, up)
548
+
549
+ def forward(self, hidden_states: torch.FloatTensor, quant_states: torch.FloatTensor):
550
+ for i_level, blocks in enumerate(self.up[::-1]):
551
+ for i_block in range(self.num_res_blocks + 1):
552
+ hidden_states = blocks.block[i_block](hidden_states, quant_states)
553
+ if len(blocks.attn) > 0:
554
+ residual = hidden_states
555
+ hidden_states = blocks.attn_norms[i_block](hidden_states, quant_states)
556
+
557
+ batch_size, channels, height, width = hidden_states.shape
558
+ hidden_states = hidden_states.view(batch_size, channels, height * width).transpose(1, 2)
559
+ hidden_states = blocks.attn[i_block](hidden_states)[0]
560
+
561
+ hidden_states = hidden_states.reshape(batch_size, height, width, channels).permute(0, 3, 1, 2)
562
+ hidden_states = residual + hidden_states
563
+ if i_level != len(self.up) - 1:
564
+ hidden_states = blocks.upsample(hidden_states)
565
+
566
+ return hidden_states
567
+
568
+
569
+ class Emu3VQVAEEncoder(nn.Module):
570
+ def __init__(self, config):
571
+ super().__init__()
572
+
573
+ base_channels = config.base_channels
574
+ in_channels = config.in_channels
575
+ double_latent = config.double_latent
576
+ latent_channels = config.latent_channels
577
+ channel_multiplier = config.channel_multiplier
578
+ out_channels = 2 * latent_channels if double_latent else latent_channels
579
+ block_in = base_channels * channel_multiplier[-1]
580
+
581
+ self.conv_in = torch.nn.Conv2d(in_channels, base_channels, kernel_size=3, stride=1, padding=1)
582
+ self.down_block = Emu3VQVAEDownBlock(config)
583
+ self.middle_block = Emu3VQVAEMiddleBlock(config, block_in)
584
+
585
+ self.norm_out = torch.nn.GroupNorm(num_groups=32, num_channels=block_in, eps=1e-6, affine=True)
586
+ self.conv_out = torch.nn.Conv2d(
587
+ block_in,
588
+ out_channels,
589
+ kernel_size=3,
590
+ stride=1,
591
+ padding=1,
592
+ )
593
+
594
+ temporal_down_blocks = int(math.log2(config.temporal_downsample_factor))
595
+ self.time_conv = nn.ModuleList()
596
+ self.time_res_stack = nn.ModuleList()
597
+
598
+ for i in range(temporal_down_blocks):
599
+ conv = Emu3VQVAETemporalDownsample(out_channels, out_channels)
600
+ self.time_conv.append(conv)
601
+
602
+ for _ in range(config.num_res_blocks):
603
+ time_res_conv = Emu3VQVAETemporalResnetBlock(
604
+ in_channels=out_channels,
605
+ out_channels=out_channels,
606
+ )
607
+ self.time_res_stack.append(time_res_conv)
608
+
609
+ def forward(self, pixel_values: torch.LongTensor):
610
+ temporal_dim = pixel_values.shape[1]
611
+ pixel_values = pixel_values.reshape(-1, *pixel_values.shape[2:])
612
+
613
+ # downsampling & middle
614
+ hidden_states = self.conv_in(pixel_values)
615
+ hidden_states = self.down_block(hidden_states)
616
+ hidden_states = self.middle_block(hidden_states)
617
+
618
+ # end
619
+ hidden_states = self.norm_out(hidden_states)
620
+ hidden_states *= torch.sigmoid(hidden_states)
621
+ hidden_states = self.conv_out(hidden_states)
622
+
623
+ hidden_states = hidden_states.reshape(-1, temporal_dim, *hidden_states.shape[1:])
624
+ hidden_states = hidden_states.permute(0, 2, 1, 3, 4)
625
+
626
+ # temporal convs
627
+ for conv in self.time_conv:
628
+ hidden_states = conv(hidden_states)
629
+ hidden_states *= torch.sigmoid(hidden_states)
630
+
631
+ for layer in self.time_res_stack:
632
+ hidden_states = layer(hidden_states)
633
+
634
+ hidden_states = hidden_states.permute(0, 2, 1, 3, 4)
635
+
636
+ return hidden_states
637
+
638
+
639
+ class Emu3VQVAEDecoder(nn.Module):
640
+ def __init__(self, config: Emu3VQVAEConfig):
641
+ super().__init__()
642
+
643
+ quant_channels = config.embed_dim
644
+ block_in = config.base_channels * config.channel_multiplier[-1]
645
+ self.time_res_stack = nn.ModuleList()
646
+ for _ in range(config.num_res_blocks):
647
+ time_res_conv = Emu3VQVAETemporalResnetBlock(
648
+ in_channels=config.latent_channels, out_channels=config.latent_channels
649
+ )
650
+ self.time_res_stack.append(time_res_conv)
651
+
652
+ temp_upsample_block_num = int(math.log2(config.temporal_downsample_factor))
653
+ self.time_conv = nn.ModuleList()
654
+ for i in range(temp_upsample_block_num):
655
+ conv = Emu3VQVAETemporalUpsample(config.latent_channels, config.latent_channels)
656
+ self.time_conv.append(conv)
657
+
658
+ self.conv_in = nn.Conv2d(
659
+ config.latent_channels,
660
+ block_in,
661
+ kernel_size=3,
662
+ stride=1,
663
+ padding=1,
664
+ )
665
+
666
+ self.middle_block = Emu3VQVAEMiddleBlock(config, block_in, quant_channels=quant_channels)
667
+ self.up_block = Emu3VQVAEUpBlock(config)
668
+
669
+ block_in = config.base_channels * config.channel_multiplier[0]
670
+ self.norm_out = Emu3VQVAESpatialNorm(quant_channels, block_in)
671
+ self.conv_out = nn.Conv2d(
672
+ block_in,
673
+ config.out_channels,
674
+ kernel_size=3,
675
+ stride=1,
676
+ padding=1,
677
+ )
678
+
679
+ def forward(self, hidden_states: torch.Tensor, quant_states: torch.Tensor):
680
+ hidden_quant_states = torch.cat((hidden_states, quant_states), dim=0)
681
+ hidden_quant_states = hidden_quant_states.permute(0, 2, 1, 3, 4)
682
+
683
+ # temporal convs
684
+ for layer in self.time_res_stack:
685
+ hidden_quant_states = layer(hidden_quant_states)
686
+
687
+ for layer in self.time_conv:
688
+ hidden_quant_states = layer(hidden_quant_states)
689
+ hidden_quant_states *= torch.sigmoid(hidden_quant_states)
690
+
691
+ hidden_quant_states = hidden_quant_states.permute(0, 2, 1, 3, 4)
692
+ hidden_states, quant_states = torch.chunk(hidden_quant_states, 2, dim=0)
693
+ hidden_states = hidden_states.reshape(-1, *hidden_states.shape[2:])
694
+ quant_states = quant_states.reshape(-1, *quant_states.shape[2:])
695
+
696
+ hidden_states = self.conv_in(hidden_states)
697
+
698
+ # middle & upsampling
699
+ hidden_states = self.middle_block(hidden_states, quant_states)
700
+ hidden_states = self.up_block(hidden_states, quant_states)
701
+
702
+ hidden_states = self.norm_out(hidden_states, quant_states)
703
+ hidden_states *= torch.sigmoid(hidden_states)
704
+ hidden_states = self.conv_out(hidden_states)
705
+
706
+ return hidden_states
707
+
708
+
709
+ EMU3_VQ_START_DOCSTRING = r"""
710
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
711
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
712
+ etc.)
713
+
714
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
715
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
716
+ and behavior.
717
+
718
+ Parameters:
719
+ config ([`Emu3VQVAEConfig`]):
720
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
721
+ load the weights associated with the model, only the configuration. Check out the
722
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
723
+ """
724
+
725
+
726
+ @add_start_docstrings(
727
+ """The VQ-VAE model used in Emu3 for encoding/decoding images into discrete tokens.
728
+ This model follows the "Make-a-scene: Scene-based text-to-image generation with human priors" paper from
729
+ [ Oran Gafni, Adam Polyak, Oron Ashual, Shelly Sheynin, Devi Parikh, and Yaniv Taigman](https://arxiv.org/abs/2203.13131).
730
+ """,
731
+ EMU3_VQ_START_DOCSTRING,
732
+ )
733
+ class Emu3VQVAE(PreTrainedModel):
734
+ config_class = Emu3VQVAEConfig
735
+ base_model_prefix = "emuvideovq"
736
+ main_input_name = "pixel_values"
737
+ _no_split_modules = [
738
+ "Emu3VQVAETemporalResnetBlock",
739
+ "Emu3VQVAEAttentionBlock",
740
+ "Emu3VQVAEResnetBlock",
741
+ "Emu3VQVAEVectorQuantizer",
742
+ ]
743
+
744
+ def _init_weights(self, module):
745
+ if isinstance(module, (nn.Conv2d, nn.Conv3d)):
746
+ nn.init.kaiming_normal_(module.weight, mode="fan_out", nonlinearity="relu")
747
+ elif isinstance(module, nn.Linear):
748
+ nn.init.kaiming_uniform_(module.weight, a=math.sqrt(5))
749
+ if module.bias is not None:
750
+ fan_in, _ = nn.init._calculate_fan_in_and_fan_out(module.weight)
751
+ bound = 1 / math.sqrt(fan_in) if fan_in > 0 else 0
752
+ nn.init.uniform_(module.bias, -bound, bound)
753
+ elif isinstance(module, (nn.BatchNorm2d, nn.BatchNorm3d, nn.GroupNorm)):
754
+ nn.init.constant_(module.weight, 1)
755
+ nn.init.constant_(module.bias, 0)
756
+
757
+ def __init__(self, config: Emu3VQVAEConfig):
758
+ super().__init__(config)
759
+
760
+ self.config = config
761
+
762
+ self.encoder = Emu3VQVAEEncoder(config)
763
+ self.decoder = Emu3VQVAEDecoder(config)
764
+ self.quantize = Emu3VQVAEVectorQuantizer(config)
765
+ self.vision_spatial_factor = 2 ** (len(config.channel_multiplier) - 1)
766
+
767
+ self.quant_conv = Emu3VQVAEConv3d(
768
+ config.latent_channels, config.embed_dim, kernel_size=(3, 1, 1), stride=(1, 1, 1)
769
+ )
770
+ self.post_quant_conv = Emu3VQVAEConv3d(
771
+ config.embed_dim, config.latent_channels, kernel_size=(3, 1, 1), stride=(1, 1, 1)
772
+ )
773
+ self.spatial_scale_factor = 2 ** (len(config.channel_multiplier) - 1)
774
+ self.eval() # Emu3's VQ model is frozen
775
+
776
+ self.post_init()
777
+
778
+ def encode(self, pixel_values: torch.Tensor, image_sizes: torch.Tensor):
779
+ is_image = pixel_values.ndim == 4
780
+ if is_image:
781
+ temporal = self.config.temporal_downsample_factor
782
+ batch_size, channels, height, width = pixel_values.shape
783
+ pixel_values = pixel_values.unsqueeze(1).repeat(1, temporal, 1, 1, 1)
784
+ else:
785
+ batch_size, temporal, channels, height, width = pixel_values.shape
786
+
787
+ hidden_states = self.encoder(pixel_values)
788
+
789
+ # b t c h w -> b c t h w
790
+ hidden_states = hidden_states.permute(0, 2, 1, 3, 4)
791
+ hidden_states = self.quant_conv(hidden_states)
792
+
793
+ # b c t h w -> b t c h w
794
+ hidden_states = hidden_states.permute(0, 2, 1, 3, 4)
795
+ codes = self.quantize(hidden_states)
796
+
797
+ image_tokens = codes.squeeze(1) if is_image else codes
798
+
799
+ image_tokens = [
800
+ single_image[: int(size[0] / self.vision_spatial_factor), : int(size[1] / self.vision_spatial_factor)]
801
+ for single_image, size in zip(image_tokens, image_sizes)
802
+ ]
803
+
804
+ return image_tokens
805
+
806
+ def decode(self, hidden_states: torch.Tensor):
807
+ is_image = hidden_states.ndim == 3
808
+ if is_image:
809
+ hidden_states = hidden_states.unsqueeze(1)
810
+
811
+ batch_size, temporal, height, width = hidden_states.shape
812
+ quant = self.quantize.embedding(hidden_states.flatten())
813
+
814
+ channels = quant.shape[-1]
815
+ quant = quant.view(batch_size, temporal, height, width, channels).permute(0, 4, 1, 2, 3).contiguous()
816
+ post_quant = self.post_quant_conv(quant)
817
+
818
+ quant = quant.permute(0, 2, 1, 3, 4)
819
+ post_quant = post_quant.permute(0, 2, 1, 3, 4)
820
+
821
+ video = self.decoder(post_quant, quant)
822
+ video = video.reshape(
823
+ batch_size,
824
+ temporal * self.config.temporal_downsample_factor,
825
+ self.config.out_channels,
826
+ height * self.spatial_scale_factor,
827
+ width * self.spatial_scale_factor,
828
+ )
829
+ return video[:, 0] if is_image else video
830
+
831
+
832
+ class Emu3ImageVocabularyMapping:
833
+ """
834
+ A class for mapping discrete image tokens from VQGAN to BPE tokens.
835
+ """
836
+
837
+ def __init__(self, vocab_map):
838
+ self.vocab_map = vocab_map
839
+ self.eol_token_id = vocab_map.get("<|extra_200|>")
840
+ self.image_token_id = vocab_map.get("<image>")
841
+
842
+ @cached_property
843
+ def image_tokens(self):
844
+ return sorted([val for name, val in self.vocab_map.items() if name.startswith("<|visual token")])
845
+
846
+ @cached_property
847
+ def image_tokens_str(self):
848
+ return sorted([name for name, val in self.vocab_map.items() if name.startswith("<|visual token")])
849
+
850
+ @cached_property
851
+ def img2bpe(self):
852
+ return {int(token[-8:-2]): self.vocab_map[token] for token in self.image_tokens_str}
853
+
854
+ @cached_property
855
+ def bpe2img(self):
856
+ return {v: k for k, v in self.img2bpe.items()}
857
+
858
+ @cached_property
859
+ def bpe2img_mapping_tensor(self):
860
+ mapping = torch.zeros(max(self.bpe2img.keys()) + 1, dtype=torch.int)
861
+ for k, v in self.bpe2img.items():
862
+ mapping[k] = v
863
+ return mapping
864
+
865
+ @cached_property
866
+ def img2bpe_mapping_tensor(self):
867
+ mapping = torch.zeros(max(self.img2bpe.keys()) + 1, dtype=torch.int)
868
+ for k, v in self.img2bpe.items():
869
+ mapping[k] = v
870
+ return mapping
871
+
872
+ def convert_img2bpe(self, img_batch: List[torch.Tensor]) -> torch.Tensor:
873
+ device = img_batch.device
874
+ eol_row = torch.ones((img_batch.shape[0], 1), dtype=torch.int) * self.eol_token_id
875
+ img_tokens = self.img2bpe_mapping_tensor[img_batch.to("cpu")]
876
+ img_tokens = torch.cat([img_tokens, eol_row], dim=-1)
877
+ return img_tokens.to(device)
878
+
879
+ def convert_bpe2img(self, img_batch: torch.Tensor) -> torch.Tensor:
880
+ device = img_batch.device
881
+ img_batch = img_batch[..., :-1] # remove last row of EOL tokens
882
+ img_tokens = self.bpe2img_mapping_tensor[img_batch.to("cpu")]
883
+ return img_tokens.to(device)
884
+
885
+
886
+ class Emu3PreTrainedModel(ChameleonPreTrainedModel, Emu3VQVAE):
887
+ _no_split_modules = [
888
+ "Emu3DecoderLayer",
889
+ ]
890
+ _supports_flex_attn = True
891
+
892
+ def _init_weights(self, module):
893
+ std = self.config.get_text_config().initializer_range
894
+ if isinstance(module, Emu3VQVAE):
895
+ module.apply(module._init_weights)
896
+ elif isinstance(module, (nn.Linear, nn.Conv2d)):
897
+ module.weight.data.normal_(mean=0.0, std=std)
898
+ if module.bias is not None:
899
+ module.bias.data.zero_()
900
+ elif isinstance(module, nn.Embedding):
901
+ module.weight.data.normal_(mean=0.0, std=std)
902
+ if module.padding_idx is not None:
903
+ module.weight.data[module.padding_idx].zero_()
904
+
905
+
906
+ EMU3_TEXT_INPUTS_DOCSTRING = r"""
907
+ Args:
908
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
909
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
910
+ it.
911
+
912
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
913
+ [`PreTrainedTokenizer.__call__`] for details.
914
+
915
+ [What are input IDs?](../glossary#input-ids)
916
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
917
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
918
+
919
+ - 1 for tokens that are **not masked**,
920
+ - 0 for tokens that are **masked**.
921
+
922
+ [What are attention masks?](../glossary#attention-mask)
923
+
924
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
925
+ [`PreTrainedTokenizer.__call__`] for details.
926
+
927
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
928
+ `past_key_values`).
929
+
930
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
931
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
932
+ information on the default strategy.
933
+
934
+ - 1 indicates the head is **not masked**,
935
+ - 0 indicates the head is **masked**.
936
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
937
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
938
+ config.n_positions - 1]`.
939
+
940
+ [What are position IDs?](../glossary#position-ids)
941
+ past_key_values (`Cache`, *optional*):
942
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
943
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
944
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
945
+
946
+ Has to be an instance of [`~cache_utils.Cache`] instance, see our
947
+ [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
948
+
949
+ The model will output the same cache type that is fed as input. If no `past_key_values` are passed, the
950
+ legacy cache format will be returned.
951
+
952
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
953
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
954
+ of shape `(batch_size, sequence_length)`.
955
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
956
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
957
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
958
+ model's internal embedding lookup matrix.
959
+ use_cache (`bool`, *optional*):
960
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
961
+ `past_key_values`).
962
+ output_attentions (`bool`, *optional*):
963
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
964
+ tensors for more detail.
965
+ output_hidden_states (`bool`, *optional*):
966
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
967
+ more detail.
968
+ return_dict (`bool`, *optional*):
969
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
970
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
971
+ Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
972
+ this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
973
+ the complete sequence length.
974
+ """
975
+
976
+
977
+ EMU3_INPUTS_DOCSTRING = r"""
978
+ Args:
979
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
980
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
981
+ it.
982
+
983
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
984
+ [`PreTrainedTokenizer.__call__`] for details.
985
+
986
+ [What are input IDs?](../glossary#input-ids)
987
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, max_num_images, max_num_tiles, channels, image_size, image_size)):
988
+ The tensors corresponding to the input images. Pixel values can be obtained using
989
+ [`AutoImageProcessor`]. See [`Emu3ImageProcessor.__call__`] for details ([]`Emu3Processor`] uses
990
+ [`Emu3ImageProcessor`] for processing images).
991
+ image_sizes (`torch.LongTensor` of shape `(batch_size, 2)`):
992
+ The sizes of the images in the batch, being (height, width) for each image. Image sizes can be obtained using
993
+ [`AutoImageProcessor`]. See [`Emu3ImageProcessor.__call__`] for details ([]`Emu3Processor`] uses
994
+ [`Emu3ImageProcessor`] for processing images).
995
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
996
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
997
+
998
+ - 1 for tokens that are **not masked**,
999
+ - 0 for tokens that are **masked**.
1000
+
1001
+ [What are attention masks?](../glossary#attention-mask)
1002
+
1003
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1004
+ [`PreTrainedTokenizer.__call__`] for details.
1005
+
1006
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
1007
+ `past_key_values`).
1008
+
1009
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
1010
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
1011
+ information on the default strategy.
1012
+
1013
+ - 1 indicates the head is **not masked**,
1014
+ - 0 indicates the head is **masked**.
1015
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1016
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
1017
+ config.n_positions - 1]`.
1018
+
1019
+ [What are position IDs?](../glossary#position-ids)
1020
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
1021
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
1022
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
1023
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
1024
+
1025
+ Has to be an instance of [`~cache_utils.Cache`] instance, see our
1026
+ [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
1027
+
1028
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
1029
+ legacy cache format will be returned.
1030
+
1031
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
1032
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
1033
+ of shape `(batch_size, sequence_length)`.
1034
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1035
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1036
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1037
+ model's internal embedding lookup matrix.
1038
+ use_cache (`bool`, *optional*):
1039
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1040
+ `past_key_values`).
1041
+ output_attentions (`bool`, *optional*):
1042
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1043
+ tensors for more detail.
1044
+ output_hidden_states (`bool`, *optional*):
1045
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1046
+ more detail.
1047
+ return_dict (`bool`, *optional*):
1048
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1049
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
1050
+ Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
1051
+ this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
1052
+ the complete sequence length.
1053
+ """
1054
+
1055
+
1056
+ class Emu3TextModel(LlamaModel, Emu3PreTrainedModel):
1057
+ def __init__(self, config: Emu3Config):
1058
+ super().__init__(config)
1059
+ self.layers = nn.ModuleList(
1060
+ [Emu3DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
1061
+ )
1062
+
1063
+ @add_start_docstrings_to_model_forward(EMU3_TEXT_INPUTS_DOCSTRING)
1064
+ def forward(self, **super_kwargs):
1065
+ super().forward(**super_kwargs)
1066
+
1067
+
1068
+ class Emu3ForCausalLM(LlamaForCausalLM, Emu3PreTrainedModel, GenerationMixin):
1069
+ config_class = Emu3TextConfig
1070
+
1071
+ def __init__(self, config):
1072
+ super().__init__(config)
1073
+ self.model = Emu3TextModel(config)
1074
+
1075
+ @deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep")
1076
+ @add_start_docstrings_to_model_forward(EMU3_TEXT_INPUTS_DOCSTRING)
1077
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class="Emu3TextConfig")
1078
+ def forward(**super_kwargs):
1079
+ r"""
1080
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1081
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1082
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1083
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1084
+
1085
+ logits_to_keep (`int` or `torch.Tensor`, *optional*):
1086
+ If an `int`, compute logits for the last `logits_to_keep` tokens. If `0`, calculate logits for all
1087
+ `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
1088
+ token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
1089
+ If a `torch.Tensor`, must be 1D corresponding to the indices to keep in the sequence length dimension.
1090
+ This is useful when using packed tensor format (single dimension for batch and sequence length).
1091
+
1092
+ Returns:
1093
+
1094
+ Example:
1095
+
1096
+ ```python
1097
+ >>> from transformers import Emu3Processor, Emu3ForConditionalGeneration
1098
+ >>> import torch
1099
+ >>> import requests
1100
+ >>> from PIL import Image
1101
+
1102
+ >>> model = Emu3ForCausalLM.from_pretrained("BAAI/Emu3-Chat-hf", torch_dtype=torch.bfloat16)
1103
+ >>> processor = Emu3Processor.from_pretrained("BAAI/Emu3-Chat-hf")
1104
+
1105
+ >>> inputs = processor(text=["Can you write me a poem about winter."], return_tensors="pt").to(model.device)
1106
+
1107
+ >>> generated_ids = model.generate(**inputs, max_new_tokens=100, do_sample=False)
1108
+ >>> processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
1109
+ ```"""
1110
+ super().forward()
1111
+
1112
+
1113
+ class Emu3ForConditionalGeneration(Emu3PreTrainedModel, GenerationMixin):
1114
+ _tied_weights_keys = ["text_model.lm_head.weight"]
1115
+ _supports_static_cache = False # `get_image_tokens()`, called when `pixel_values` is passed, is not compileable
1116
+
1117
+ def __init__(self, config):
1118
+ super().__init__(config)
1119
+ self.text_model = Emu3ForCausalLM._from_config(config.text_config)
1120
+ self.vqmodel = Emu3VQVAE(config.vq_config)
1121
+ self.vocabulary_mapping = Emu3ImageVocabularyMapping(config.vocabulary_map)
1122
+
1123
+ # Initialize weights and apply final processing
1124
+ self.post_init()
1125
+
1126
+ def get_input_embeddings(self):
1127
+ return self.text_model.get_input_embeddings()
1128
+
1129
+ def set_input_embeddings(self, value):
1130
+ self.text_model.set_input_embeddings(value)
1131
+
1132
+ def get_image_tokens(self, pixel_values: torch.FloatTensor, image_sizes: torch.LongTensor):
1133
+ """
1134
+ Tokenizes images into discrete tokens with VQGAN module. Converts
1135
+ obtained image tokens into BPE tokens and wraps with "boi" and "eoi"
1136
+ special tokens.
1137
+
1138
+ Args:
1139
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`):
1140
+ The tensors corresponding to the input images.
1141
+ image_sizes (`torch.LongTensor` of shape `(batch_size, 2)`):
1142
+ The sizes of the images in the batch, being (height, width) for each image.
1143
+ """
1144
+ image_tokens_list = self.vqmodel.encode(pixel_values, image_sizes)
1145
+ bpe_tokens_list = [self.vocabulary_mapping.convert_img2bpe(tokens).flatten() for tokens in image_tokens_list]
1146
+ bpe_tokens = torch.cat(bpe_tokens_list)
1147
+ return bpe_tokens
1148
+
1149
+ @torch.no_grad
1150
+ def decode_image_tokens(self, image_tokens: torch.LongTensor, height: int, width: int):
1151
+ """
1152
+ Decodes generated image tokens from language model to continuous pixel values
1153
+ with VQGAN module via upsampling.
1154
+
1155
+ Args:
1156
+ image_tokens (`torch.LongTensor` of shape `(batch_size, num_of_tokens)`):
1157
+ The tensors corresponding to the input images.
1158
+ height (`int`):
1159
+ Height of the generated image before upsampling.
1160
+ width (`int`):
1161
+ Width of the generated image before upsampling.
1162
+ """
1163
+ sequences = image_tokens[:, :-3].view(-1, height, width + 1)
1164
+ image_tokens = self.vocabulary_mapping.convert_bpe2img(sequences)
1165
+ image = self.vqmodel.decode(image_tokens)
1166
+ return image
1167
+
1168
+ @add_start_docstrings_to_model_forward(EMU3_INPUTS_DOCSTRING)
1169
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1170
+ def forward(
1171
+ self,
1172
+ input_ids: torch.LongTensor = None,
1173
+ pixel_values: torch.FloatTensor = None,
1174
+ image_sizes: torch.Tensor = None,
1175
+ attention_mask: Optional[torch.Tensor] = None,
1176
+ position_ids: Optional[torch.LongTensor] = None,
1177
+ past_key_values: Optional[Cache] = None,
1178
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1179
+ use_cache: Optional[bool] = None,
1180
+ output_attentions: Optional[bool] = None,
1181
+ output_hidden_states: Optional[bool] = None,
1182
+ return_dict: Optional[bool] = None,
1183
+ cache_position: Optional[torch.LongTensor] = None,
1184
+ labels: Optional[torch.LongTensor] = None,
1185
+ logits_to_keep: Union[int, torch.Tensor] = 0,
1186
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1187
+ r"""
1188
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1189
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1190
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1191
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1192
+
1193
+ logits_to_keep (`int` or `torch.Tensor`, *optional*):
1194
+ If an `int`, compute logits for the last `logits_to_keep` tokens. If `0`, calculate logits for all
1195
+ `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
1196
+ token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
1197
+ If a `torch.Tensor`, must be 1D corresponding to the indices to keep in the sequence length dimension.
1198
+ This is useful when using packed tensor format (single dimension for batch and sequence length).
1199
+
1200
+ Returns:
1201
+
1202
+ Example:
1203
+
1204
+ ```python
1205
+ >>> from transformers import Emu3Processor, Emu3ForConditionalGeneration
1206
+ >>> import torch
1207
+ >>> import requests
1208
+ >>> from PIL import Image
1209
+
1210
+ >>> model = Emu3ForConditionalGeneration.from_pretrained("BAAI/Emu3-Chat-hf", torch_dtype=torch.bfloat16)
1211
+ >>> processor = Emu3Processor.from_pretrained("BAAI/Emu3-Chat-hf")
1212
+
1213
+ >>> conversation = [
1214
+ ... {
1215
+ ... "role": "system",
1216
+ ... "content": [
1217
+ ... {"type": "text", "text": "You are a helpful assistant."},
1218
+ ... ],
1219
+ ... },
1220
+ ... {
1221
+ ... "role": "user",
1222
+ ... "content": [
1223
+ ... {"type": "image"},
1224
+ ... {"type": "text", "text": "Please describe the image."},
1225
+ ... ],
1226
+ ... },
1227
+ ... ]
1228
+
1229
+ >>> prompt = processor.apply_chat_template(conversation, add_generation_prompt=True)
1230
+ >>> image = Image.open(requests.get("https://www.ilankelman.org/stopsigns/australia.jpg", stream=True).raw)
1231
+
1232
+ >>> inputs = processor(images=[image], text=[prompt], return_tensors="pt").to(model.device, torch.bfloat16)
1233
+
1234
+ >>> generated_ids = model.generate(**inputs, max_new_tokens=100, do_sample=False)
1235
+ >>> processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
1236
+ ```"""
1237
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1238
+ output_hidden_states = (
1239
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1240
+ )
1241
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1242
+
1243
+ if (input_ids is None) ^ (inputs_embeds is not None):
1244
+ raise ValueError(
1245
+ "You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one"
1246
+ )
1247
+
1248
+ if pixel_values is not None and inputs_embeds is not None:
1249
+ raise ValueError(
1250
+ "You cannot specify both pixel_values and inputs_embeds at the same time, and must specify either one"
1251
+ )
1252
+
1253
+ if pixel_values is not None:
1254
+ image_tokens = self.get_image_tokens(pixel_values, image_sizes)
1255
+ special_image_mask = input_ids == self.vocabulary_mapping.image_token_id
1256
+ image_tokens = image_tokens.to(input_ids.device, input_ids.dtype)
1257
+ input_ids = input_ids.masked_scatter(special_image_mask, image_tokens)
1258
+
1259
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1260
+ outputs = self.text_model(
1261
+ input_ids=input_ids,
1262
+ attention_mask=attention_mask,
1263
+ position_ids=position_ids,
1264
+ past_key_values=past_key_values,
1265
+ inputs_embeds=inputs_embeds,
1266
+ use_cache=use_cache,
1267
+ output_attentions=output_attentions,
1268
+ output_hidden_states=output_hidden_states,
1269
+ return_dict=return_dict,
1270
+ cache_position=cache_position,
1271
+ logits_to_keep=logits_to_keep,
1272
+ )
1273
+
1274
+ return outputs
1275
+
1276
+ def prepare_inputs_for_generation(
1277
+ self,
1278
+ input_ids,
1279
+ past_key_values=None,
1280
+ attention_mask=None,
1281
+ inputs_embeds=None,
1282
+ cache_position=None,
1283
+ position_ids=None,
1284
+ use_cache=True,
1285
+ pixel_values=None,
1286
+ **kwargs,
1287
+ ):
1288
+ # Overwritten -- in specific circumstances we don't want to forward image inputs to the model
1289
+
1290
+ model_inputs = super().prepare_inputs_for_generation(
1291
+ input_ids,
1292
+ past_key_values=past_key_values,
1293
+ attention_mask=attention_mask,
1294
+ inputs_embeds=inputs_embeds,
1295
+ cache_position=cache_position,
1296
+ position_ids=position_ids,
1297
+ pixel_values=pixel_values,
1298
+ use_cache=use_cache,
1299
+ **kwargs,
1300
+ )
1301
+
1302
+ if cache_position[0] != 0:
1303
+ model_inputs["pixel_values"] = None
1304
+
1305
+ return model_inputs
1306
+
1307
+
1308
+ __all__ = [
1309
+ "Emu3ForConditionalGeneration",
1310
+ "Emu3ForCausalLM",
1311
+ "Emu3TextModel",
1312
+ "Emu3PreTrainedModel",
1313
+ "Emu3VQVAE",
1314
+ ]
vllm/lib/python3.10/site-packages/transformers/models/helium/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (536 Bytes). View file
 
vllm/lib/python3.10/site-packages/transformers/models/helium/__pycache__/configuration_helium.cpython-310.pyc ADDED
Binary file (6.33 kB). View file
 
vllm/lib/python3.10/site-packages/transformers/models/helium/configuration_helium.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The Kyutai and HuggingFace Inc. teams. All rights reserved.
3
+ #
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ from ...configuration_utils import PretrainedConfig
18
+
19
+
20
+ class HeliumConfig(PretrainedConfig):
21
+ r"""
22
+ This is the configuration class to store the configuration of a [`HeliumModel`]. It is used to instantiate an Helium
23
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
24
+ defaults will yield a similar configuration to that of the Helium 2b model.
25
+ e.g. [kyutai/helium-2b](https://huggingface.co/kyutai/helium-2b)
26
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
27
+ documentation from [`PretrainedConfig`] for more information.
28
+ Args:
29
+ vocab_size (`int`, *optional*, defaults to 48000):
30
+ Vocabulary size of the Helium model. Defines the number of different tokens that can be represented by the
31
+ `inputs_ids` passed when calling [`HeliumModel`]
32
+ hidden_size (`int`, *optional*, defaults to 2560):
33
+ Dimension of the hidden representations.
34
+ intermediate_size (`int`, *optional*, defaults to 7040):
35
+ Dimension of the MLP representations.
36
+ num_hidden_layers (`int`, *optional*, defaults to 24):
37
+ Number of hidden layers in the Transformer decoder.
38
+ num_attention_heads (`int`, *optional*, defaults to 20):
39
+ Number of attention heads for each attention layer in the Transformer decoder.
40
+ num_key_value_heads (`int`, *optional*, defaults to 20):
41
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
42
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
43
+ `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
44
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
45
+ by meanpooling all the original heads within that group. For more details checkout [this
46
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
47
+ `num_attention_heads`.
48
+ head_dim (`int`, *optional*, defaults to 128):
49
+ The attention head dimension.
50
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
51
+ The legacy activation function. It is overwritten by the `hidden_activation`.
52
+ attention_dropout (`float`, *optional*, defaults to 0.0):
53
+ The dropout ratio for the attention probabilities.
54
+ max_position_embeddings (`int`, *optional*, defaults to 4096):
55
+ The maximum sequence length that this model might ever be used with.
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-08):
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
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
64
+ Whether to tie weight embeddings
65
+ rope_theta (`float`, *optional*, defaults to 100000.0):
66
+ The base period of the RoPE embeddings.
67
+ pad_token_id (`int`, *optional*, defaults to 3):
68
+ Padding token id.
69
+ eos_token_id (`int` | `list`, *optional*, defaults to 2):
70
+ End of stream token id.
71
+ bos_token_id (`int`, *optional*, defaults to 1):
72
+ Beginning of stream token id.
73
+ attention_bias (`bool`, *optional*, defaults to `False`):
74
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
75
+ mlp_bias (`bool`, *optional*, defaults to `False`):
76
+ Whether to use a bias in up_proj, down_proj and gate_proj layers in the MLP layers.
77
+ ```python
78
+ >>> from transformers import HeliumModel, HeliumConfig
79
+ >>> # Initializing a Helium 2b style configuration
80
+ >>> configuration = HeliumConfig()
81
+ >>> # Initializing a model from the Helium 2b style configuration
82
+ >>> model = HeliumModel(configuration)
83
+ >>> # Accessing the model configuration
84
+ >>> configuration = model.config
85
+ ```"""
86
+
87
+ model_type = "helium"
88
+ keys_to_ignore_at_inference = ["past_key_values"]
89
+ base_model_tp_plan = {
90
+ "layers.*.self_attn.q_proj": "colwise",
91
+ "layers.*.self_attn.k_proj": "colwise",
92
+ "layers.*.self_attn.v_proj": "colwise",
93
+ "layers.*.self_attn.o_proj": "rowwise",
94
+ "layers.*.mlp.gate_proj": "colwise",
95
+ "layers.*.mlp.up_proj": "colwise",
96
+ "layers.*.mlp.down_proj": "rowwise",
97
+ }
98
+ base_model_pp_plan = {
99
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
100
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
101
+ "norm": (["hidden_states"], ["hidden_states"]),
102
+ }
103
+
104
+ def __init__(
105
+ self,
106
+ vocab_size=48000,
107
+ hidden_size=2560,
108
+ intermediate_size=7040,
109
+ num_hidden_layers=24,
110
+ num_attention_heads=20,
111
+ num_key_value_heads=20,
112
+ head_dim=128,
113
+ hidden_act="silu",
114
+ attention_dropout=0.0,
115
+ max_position_embeddings=4096,
116
+ initializer_range=0.02,
117
+ rms_norm_eps=1e-8,
118
+ use_cache=True,
119
+ tie_word_embeddings=False,
120
+ rope_theta=100000.0,
121
+ pad_token_id=3,
122
+ eos_token_id=2,
123
+ bos_token_id=1,
124
+ attention_bias=False,
125
+ mlp_bias=False,
126
+ **kwargs,
127
+ ):
128
+ self.vocab_size = vocab_size
129
+ self.max_position_embeddings = max_position_embeddings
130
+ self.hidden_size = hidden_size
131
+ self.intermediate_size = intermediate_size
132
+ self.num_hidden_layers = num_hidden_layers
133
+ self.num_attention_heads = num_attention_heads
134
+ self.num_key_value_heads = num_key_value_heads
135
+ self.head_dim = head_dim
136
+ self.hidden_act = hidden_act
137
+ self.initializer_range = initializer_range
138
+ self.rms_norm_eps = rms_norm_eps
139
+ self.use_cache = use_cache
140
+ self.rope_theta = rope_theta
141
+ self.attention_bias = attention_bias
142
+ self.attention_dropout = attention_dropout
143
+ self.mlp_bias = mlp_bias
144
+
145
+ super().__init__(
146
+ pad_token_id=pad_token_id,
147
+ bos_token_id=bos_token_id,
148
+ eos_token_id=eos_token_id,
149
+ tie_word_embeddings=tie_word_embeddings,
150
+ **kwargs,
151
+ )
152
+
153
+
154
+ __all__ = ["HeliumConfig"]
vllm/lib/python3.10/site-packages/transformers/models/helium/modular_helium.py ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The Kyutai and HuggingFace Inc. teams. All rights reserved.
3
+ #
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ import math
17
+ from typing import Optional
18
+
19
+ import torch
20
+ import torch.nn as nn
21
+ import torch.utils.checkpoint
22
+
23
+ from ...utils import logging
24
+ from ..gemma.modeling_gemma import (
25
+ GemmaForCausalLM,
26
+ GemmaForSequenceClassification,
27
+ GemmaForTokenClassification,
28
+ )
29
+ from ..granite.modeling_granite import (
30
+ GraniteAttention,
31
+ )
32
+ from ..llama.modeling_llama import (
33
+ LlamaDecoderLayer,
34
+ LlamaMLP,
35
+ LlamaModel,
36
+ LlamaPreTrainedModel,
37
+ LlamaRotaryEmbedding,
38
+ )
39
+ from .configuration_helium import HeliumConfig
40
+
41
+
42
+ logger = logging.get_logger(__name__)
43
+
44
+
45
+ class HeliumRMSNorm(nn.Module):
46
+ def __init__(self, hidden_size, eps=1e-6):
47
+ super().__init__()
48
+ self.weight = nn.Parameter(torch.ones(hidden_size))
49
+ self.variance_epsilon = eps
50
+
51
+ def forward(self, hidden_states):
52
+ input_dtype = hidden_states.dtype
53
+ hidden_states = hidden_states.to(torch.float32)
54
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
55
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
56
+ return (self.weight.to(torch.float32) * hidden_states).to(input_dtype)
57
+
58
+ def extra_repr(self):
59
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
60
+
61
+
62
+ class HeliumRotaryEmbedding(LlamaRotaryEmbedding):
63
+ pass
64
+
65
+
66
+ class HeliumMLP(LlamaMLP):
67
+ pass
68
+
69
+
70
+ def rotate_half(x):
71
+ """Rotates half the hidden dims of the input."""
72
+ x1 = x[..., 0::2]
73
+ x2 = x[..., 1::2]
74
+ return torch.stack((-x2, x1), dim=-1).flatten(-2)
75
+
76
+
77
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
78
+ """Applies Rotary Position Embedding to the query and key tensors.
79
+
80
+ Args:
81
+ q (`torch.Tensor`): The query tensor.
82
+ k (`torch.Tensor`): The key tensor.
83
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
84
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
85
+ position_ids (`torch.Tensor`, *optional*):
86
+ Deprecated and unused.
87
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
88
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
89
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
90
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
91
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
92
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
93
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
94
+ Returns:
95
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
96
+ """
97
+ cos = cos.unsqueeze(unsqueeze_dim)
98
+ sin = sin.unsqueeze(unsqueeze_dim)
99
+
100
+ # Interleave them instead of usual shape
101
+ cos = cos[..., : cos.shape[-1] // 2].repeat_interleave(2, dim=-1)
102
+ sin = sin[..., : sin.shape[-1] // 2].repeat_interleave(2, dim=-1)
103
+
104
+ q_embed = (q * cos) + (rotate_half(q) * sin)
105
+ k_embed = (k * cos) + (rotate_half(k) * sin)
106
+
107
+ return q_embed, k_embed
108
+
109
+
110
+ class HeliumAttention(GraniteAttention):
111
+ def __init__(self, config: HeliumConfig, layer_idx: Optional[int] = None):
112
+ super().__init__(config, layer_idx)
113
+ self.o_proj = nn.Linear(config.hidden_size, config.hidden_size, bias=False)
114
+ self.scaling = 1 / math.sqrt(self.head_dim)
115
+
116
+
117
+ class HeliumDecoderLayer(LlamaDecoderLayer):
118
+ def __init__(self, config: HeliumConfig, layer_idx: Optional[int] = None):
119
+ super().__init__()
120
+
121
+ self.mlp = HeliumMLP(config)
122
+ self.input_layernorm = HeliumRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
123
+ self.post_attention_layernorm = HeliumRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
124
+
125
+
126
+ class HeliumPreTrainedModel(LlamaPreTrainedModel):
127
+ pass
128
+
129
+
130
+ class HeliumModel(HeliumPreTrainedModel, LlamaModel):
131
+ def __init__(self, config: HeliumConfig):
132
+ super().__init__(config)
133
+ self.layers = nn.ModuleList(
134
+ [HeliumDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
135
+ )
136
+ self.norm = HeliumRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
137
+ self.rotary_emb = HeliumRotaryEmbedding(config)
138
+ self.gradient_checkpointing = False
139
+
140
+ # Initialize weights and apply final processing
141
+ self.post_init()
142
+
143
+
144
+ class HeliumForCausalLM(GemmaForCausalLM):
145
+ def __init__(self, config: HeliumConfig):
146
+ super().__init__(config)
147
+ self.model = HeliumModel(config)
148
+ self.post_init()
149
+
150
+
151
+ class HeliumForSequenceClassification(GemmaForSequenceClassification):
152
+ def __init__(self, config: HeliumConfig):
153
+ super().__init__(config)
154
+ self.model = HeliumModel(config)
155
+ self.post_init()
156
+
157
+
158
+ class HeliumForTokenClassification(GemmaForTokenClassification):
159
+ def __init__(self, config: HeliumConfig):
160
+ super().__init__(config)
161
+ self.model = HeliumModel(config)
162
+ self.post_init()
163
+
164
+
165
+ __all__ = [
166
+ "HeliumPreTrainedModel",
167
+ "HeliumModel",
168
+ "HeliumForCausalLM",
169
+ "HeliumForSequenceClassification",
170
+ "HeliumForTokenClassification",
171
+ ]
vllm/lib/python3.10/site-packages/transformers/models/mamba2/__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_mamba2 import *
22
+ from .modeling_mamba2 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__)
vllm/lib/python3.10/site-packages/transformers/models/mamba2/__pycache__/configuration_mamba2.cpython-310.pyc ADDED
Binary file (6.62 kB). View file
 
vllm/lib/python3.10/site-packages/transformers/models/mamba2/configuration_mamba2.py ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """MAMBA2 configuration"""
16
+
17
+ import math
18
+
19
+ from ...configuration_utils import PretrainedConfig
20
+ from ...utils import logging
21
+
22
+
23
+ logger = logging.get_logger(__name__)
24
+
25
+
26
+ class Mamba2Config(PretrainedConfig):
27
+ """
28
+ This is the configuration class to store the configuration of a [`Mamba2Model`]. It is used to instantiate a MAMBA2
29
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
30
+ defaults will yield a similar configuration to that of the MAMBA2
31
+ [state-spaces/mamba2-2.8b](https://huggingface.co/state-spaces/mamba2-2.8b) architecture.
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_heads (`int`, *optional*, defaults to 128):
39
+ Number of heads for the evolution matrices of mamba 2.
40
+ head_dim (`int`, *optional*, defaults to 64):
41
+ Dimension of each head.
42
+ vocab_size (`int`, *optional*, defaults to 32768):
43
+ Vocabulary size of the MAMBA2 model. Defines the number of different tokens that can be represented by the
44
+ `inputs_ids` passed when calling [`Mamba2Model`].
45
+ hidden_size (`int`, *optional*, defaults to 4096):
46
+ Dimensionality of the embeddings and hidden states.
47
+ state_size (`int`, *optional*, defaults to 128): shape of the state space latents.
48
+ num_hidden_layers (`int`, *optional*, defaults to 64):
49
+ Number of hidden layers in the model.
50
+ layer_norm_epsilon (`float`, *optional*, defaults to 1e-05):
51
+ The epsilon to use in the layer normalization layers.
52
+ pad_token_id (`int`, *optional*, defaults to 1):
53
+ Padding token id.
54
+ bos_token_id (`int`, *optional*, defaults to 0):
55
+ The id of the beginning of sentence token in the vocabulary.
56
+ eos_token_id (`int`, *optional*, defaults to 2):
57
+ The id of the end of sentence token in the vocabulary.
58
+ expand (`int`, *optional*, defaults to 2): Expanding factor used to determine the intermediate size.
59
+ conv_kernel (`int`, *optional*, defaults to 4): Size of the convolution kernel.
60
+ n_groups (`int`, *optional*, defaults to 8):
61
+ Number of groups for the evolution matrices of mamba 2.
62
+ use_bias (`bool`, *optional*, defaults to `False`):
63
+ Whether or not to use bias in ["in_proj", "out_proj"] of the mixer block
64
+ use_conv_bias (`bool`, *optional*, defaults to `True`):
65
+ Whether or not to use bias in the convolution layer of the mixer block.
66
+ hidden_act (`str`, *optional*, defaults to `"silu"`):
67
+ The non-linear activation function (function or string) in the decoder.
68
+ initializer_range (`float`, *optional*, defaults to 0.1):
69
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
70
+ residual_in_fp32 (`bool`, *optional*, defaults to `True`):
71
+ Whether or not residuals should be in `float32`. If set to `False` residuals will keep the same `dtype` as the rest of the model
72
+ time_step_rank (`Union[int,str]`, *optional*, defaults to `"auto"`):
73
+ Rank of the discretization projection matrix. `"auto"` means that it will default to `math.ceil(self.hidden_size / 16)`
74
+ time_step_min (`float`, *optional*, defaults to 0.001):
75
+ Minimum `time_step` used to bound `dt_proj.bias`.
76
+ time_step_max (`float`, *optional*, defaults to 0.1):
77
+ Maximum `time_step` used to bound `dt_proj.bias`.
78
+ time_step_floor (`float`, *optional*, defaults to 0.0001):
79
+ Minimum clamping value of the `dt_proj.bias` layer initialization.
80
+ time_step_limit (`tuple`, *optional*, defaults to `(0.0, inf)`):
81
+ Accepted range of time step values.
82
+ rescale_prenorm_residual (`bool`, *optional*, defaults to `False`):
83
+ Whether or not to rescale `out_proj` weights when initializing.
84
+ use_cache (`bool`, *optional*, defaults to `True`):
85
+ Whether or not the cache should be used.
86
+ rms_norm (`bool`, *optional*, defaults to `True`):
87
+ Whether to use RMS norm or not.
88
+ chunk_size (`int`, *optional*, defaults to 256):
89
+ Size of the chunks that will comprise the sequence.
90
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
91
+ Whether to tie word embeddings or not.
92
+
93
+
94
+ Example:
95
+
96
+ ```python
97
+ >>> from transformers import Mamba2Config, Mamba2Model
98
+
99
+ >>> # Initializing a Mamba2 configuration
100
+ >>> configuration = Mamba2Config()
101
+
102
+ >>> # Initializing a model (with random weights) from the configuration
103
+ >>> model = Mamba2Model(configuration)
104
+
105
+ >>> # Accessing the model configuration
106
+ >>> configuration = model.config
107
+ ```"""
108
+
109
+ model_type = "mamba2"
110
+
111
+ def __init__(
112
+ self,
113
+ num_heads=128,
114
+ head_dim=64,
115
+ vocab_size=32768,
116
+ hidden_size=4096,
117
+ state_size=128,
118
+ num_hidden_layers=64,
119
+ layer_norm_epsilon=1e-5,
120
+ pad_token_id=1,
121
+ bos_token_id=0,
122
+ eos_token_id=2,
123
+ expand=2,
124
+ conv_kernel=4,
125
+ n_groups=8,
126
+ use_bias=False,
127
+ use_conv_bias=True,
128
+ hidden_act="silu",
129
+ initializer_range=0.1,
130
+ residual_in_fp32=True,
131
+ time_step_rank="auto",
132
+ time_step_min=0.001,
133
+ time_step_max=0.1,
134
+ time_step_floor=1e-4,
135
+ time_step_limit=(0.0, float("inf")),
136
+ rescale_prenorm_residual=False,
137
+ use_cache=True,
138
+ rms_norm=True,
139
+ chunk_size=256,
140
+ tie_word_embeddings=False,
141
+ **kwargs,
142
+ ):
143
+ self.vocab_size = vocab_size
144
+ self.hidden_size = hidden_size
145
+ self.state_size = state_size
146
+ self.num_hidden_layers = num_hidden_layers
147
+ self.layer_norm_epsilon = layer_norm_epsilon
148
+ self.conv_kernel = conv_kernel
149
+ self.expand = expand
150
+
151
+ self.bos_token_id = bos_token_id
152
+ self.eos_token_id = eos_token_id
153
+ self.pad_token_id = pad_token_id
154
+ self.use_bias = use_bias
155
+ self.use_conv_bias = use_conv_bias
156
+ self.hidden_act = hidden_act
157
+ self.initializer_range = initializer_range
158
+ self.time_step_rank = math.ceil(self.hidden_size / 16) if time_step_rank == "auto" else time_step_rank
159
+ self.time_step_min = time_step_min
160
+ self.time_step_max = time_step_max
161
+ self.time_step_floor = time_step_floor
162
+ self.rescale_prenorm_residual = rescale_prenorm_residual
163
+ self.residual_in_fp32 = residual_in_fp32
164
+ self.use_cache = use_cache
165
+ self.n_groups = n_groups
166
+ self.num_heads = num_heads
167
+ self.head_dim = head_dim
168
+ self.rms_norm = rms_norm
169
+ self.state_size = state_size
170
+ self.chunk_size = chunk_size
171
+ self.time_step_limit = time_step_limit
172
+ self.tie_word_embeddings = tie_word_embeddings
173
+
174
+ super().__init__(
175
+ bos_token_id=bos_token_id,
176
+ eos_token_id=eos_token_id,
177
+ pad_token_id=pad_token_id,
178
+ tie_word_embeddings=tie_word_embeddings,
179
+ **kwargs,
180
+ )
181
+
182
+
183
+ __all__ = ["Mamba2Config"]
vllm/lib/python3.10/site-packages/transformers/models/mamba2/modeling_mamba2.py ADDED
@@ -0,0 +1,1136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 state-spaces/mamba2 org and HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """PyTorch MAMBA2 model."""
16
+
17
+ import math
18
+ from dataclasses import dataclass
19
+ from typing import Optional, Tuple, Union
20
+
21
+ import torch
22
+ import torch.utils.checkpoint
23
+ from torch import nn
24
+ from torch.nn import CrossEntropyLoss
25
+
26
+ from ...activations import ACT2FN
27
+ from ...generation import GenerationMixin
28
+ from ...modeling_utils import PreTrainedModel
29
+ from ...utils import (
30
+ ModelOutput,
31
+ add_code_sample_docstrings,
32
+ add_start_docstrings,
33
+ add_start_docstrings_to_model_forward,
34
+ logging,
35
+ )
36
+ from ...utils.import_utils import is_causal_conv1d_available, is_mamba_2_ssm_available
37
+ from .configuration_mamba2 import Mamba2Config
38
+
39
+
40
+ logger = logging.get_logger(__name__)
41
+
42
+
43
+ if is_mamba_2_ssm_available():
44
+ from mamba_ssm.ops.triton.selective_state_update import selective_state_update
45
+ from mamba_ssm.ops.triton.ssd_combined import mamba_chunk_scan_combined, mamba_split_conv1d_scan_combined
46
+ else:
47
+ mamba_chunk_scan_combined, mamba_split_conv1d_scan_combined, selective_state_update = None, None, None
48
+
49
+ if is_causal_conv1d_available():
50
+ from causal_conv1d import causal_conv1d_fn, causal_conv1d_update
51
+ else:
52
+ causal_conv1d_update, causal_conv1d_fn = None, None
53
+
54
+ is_fast_path_available = all(
55
+ (
56
+ selective_state_update,
57
+ mamba_chunk_scan_combined,
58
+ mamba_split_conv1d_scan_combined,
59
+ causal_conv1d_fn,
60
+ causal_conv1d_update,
61
+ )
62
+ )
63
+
64
+ _CHECKPOINT_FOR_DOC = "mistralai/mamba-codestral-7B-v0.1"
65
+ _CONFIG_FOR_DOC = "Mamba2Config"
66
+
67
+
68
+ # Helper methods for segment sum computation
69
+
70
+
71
+ def pad_tensor_by_size(input_tensor: torch.Tensor, pad_size: int):
72
+ """
73
+ Padding x tensor with `pad_size` on the seq_len dim (dim=1)
74
+
75
+ Assumes that we only have tensors of either size 4 or 3
76
+ """
77
+ pad_shape = (0, 0, 0, 0, 0, pad_size, 0, 0) if len(input_tensor.shape) == 4 else (0, 0, 0, pad_size, 0, 0)
78
+
79
+ return torch.nn.functional.pad(input_tensor, pad_shape, mode="constant", value=0)
80
+
81
+
82
+ def reshape_into_chunks(input_tensor, pad_size, chunk_size):
83
+ """
84
+ Padding input_tensor with `pad_size` on the seq_len dim (dim=1) and
85
+ simultaneously splitting it into chunk sequences.
86
+
87
+ Assumes that we only have tensors of either size 4 or 3
88
+ """
89
+ # [bsz, seq_len, ...] -> [bsz, seq_len multiple of chunk_size, ...]
90
+ input_tensor = pad_tensor_by_size(input_tensor, pad_size)
91
+
92
+ if len(input_tensor.shape) == 3:
93
+ # [bsz, seq_len multiple of chunk_size, num_heads] -> [bsz, -1, chunk_size, num_heads]
94
+ return input_tensor.reshape(input_tensor.shape[0], -1, chunk_size, input_tensor.shape[2])
95
+ else:
96
+ # [bsz, seq_len multiple of chunk_size, num_heads, head_dim or state_size] -> [bsz, -1, chunk_size, num_heads, head_dim or state_size]
97
+ return input_tensor.reshape(
98
+ input_tensor.shape[0], -1, chunk_size, input_tensor.shape[2], input_tensor.shape[3]
99
+ )
100
+
101
+
102
+ def segment_sum(input_tensor):
103
+ """
104
+ More stable segment sum calculation. Uses cumulative sums and masking instead of direct subtractions.
105
+ """
106
+ chunk_size = input_tensor.size(-1)
107
+ # 1. expand input tensor to have an additional dimension and repeat along that dimension
108
+ # [..., chunk_size] -> [..., chunk_size, chunk_size]
109
+ input_tensor = input_tensor[..., None].expand(*input_tensor.size(), chunk_size)
110
+ # 2. create a lower triangular mask with the diagonal set to 0 to 0 out elements above diag
111
+ mask = torch.tril(torch.ones(chunk_size, chunk_size, device=input_tensor.device, dtype=torch.bool), diagonal=-1)
112
+ input_tensor = input_tensor.masked_fill(~mask, 0)
113
+ # 3. compute actual cumsum
114
+ tensor_segsum = torch.cumsum(input_tensor, dim=-2)
115
+
116
+ # 4. apply mask to keep only the lower triangular part of the cumulative sum result (incl diagonal this time)
117
+ mask = torch.tril(torch.ones(chunk_size, chunk_size, device=input_tensor.device, dtype=torch.bool), diagonal=0)
118
+ tensor_segsum = tensor_segsum.masked_fill(~mask, -torch.inf)
119
+ return tensor_segsum
120
+
121
+
122
+ def apply_mask_to_padding_states(hidden_states, attention_mask):
123
+ """
124
+ Tunes out the hidden states for padding tokens, see https://github.com/state-spaces/mamba/issues/66
125
+ """
126
+ if attention_mask is not None and attention_mask.shape[1] > 1 and attention_mask.shape[0] > 1:
127
+ dtype = hidden_states.dtype
128
+ hidden_states = (hidden_states * attention_mask[:, :, None]).to(dtype)
129
+
130
+ return hidden_states
131
+
132
+
133
+ class Mamba2Cache:
134
+ """
135
+ Arguments:
136
+ config: Mamba2Config
137
+ batch_size: int
138
+ dtype: torch.dtype
139
+ device: torch.device
140
+
141
+ Attributes:
142
+ dtype: (`torch.dtype`):
143
+ The default `dtype` used to initializing the cache.
144
+ conv_kernel_size: (`int`):
145
+ Model's convolution kernel size taken from config.
146
+ n_groups: (`int`):
147
+ Model's number of groups taken from the config - similar to tensor parallel in Transformer.
148
+ state_size: (`int`):
149
+ Model's SSM state size taken from config.
150
+ num_heads: (`int`):
151
+ The number of heads used in the linear attention / SSM.
152
+ head_dim: (`int`):
153
+ The respective dimension of the heads used in the linear attention / SSM.
154
+ intermediate_size: (`int`):
155
+ Model's intermediate_size based on (expand * hidden_dim) from config.
156
+ conv_states: (`torch.Tensor`):
157
+ A tensor of shape `[num_layers, batch_size, conv_kernel_size, intermediate_size + 2 * n_groups * state_size]` that holds convolutional states.
158
+ ssm_states: (`torch.Tensor`):
159
+ A tensor of shape `[num_layers, batch_size, num_heads, head_dim, state_size]` that holds ssm states.
160
+ """
161
+
162
+ def __init__(
163
+ self, config: Mamba2Config, batch_size: int, dtype: torch.dtype = torch.float16, device: Optional[str] = None
164
+ ):
165
+ self.dtype = dtype
166
+ self.conv_kernel_size = config.conv_kernel
167
+ self.n_groups = config.n_groups
168
+ self.state_size = config.state_size
169
+ self.num_heads = config.num_heads
170
+ self.head_dim = config.head_dim
171
+ self.intermediate_size = int(config.expand * config.hidden_size)
172
+
173
+ self.conv_states = torch.zeros(
174
+ config.num_hidden_layers,
175
+ batch_size,
176
+ self.intermediate_size + 2 * self.n_groups * self.state_size,
177
+ self.conv_kernel_size,
178
+ device=device,
179
+ dtype=dtype,
180
+ )
181
+ self.ssm_states = torch.zeros(
182
+ config.num_hidden_layers,
183
+ batch_size,
184
+ self.num_heads,
185
+ self.head_dim,
186
+ self.state_size,
187
+ device=device,
188
+ dtype=dtype,
189
+ )
190
+
191
+ def update_conv_state(
192
+ self, layer_idx: int, new_conv_state: torch.Tensor, cache_init: bool = False
193
+ ) -> torch.Tensor:
194
+ if cache_init:
195
+ self.conv_states[layer_idx] = new_conv_state.to(self.conv_states.device)
196
+ else:
197
+ self.conv_states[layer_idx] = self.conv_states[layer_idx].roll(shifts=-1, dims=-1)
198
+ self.conv_states[layer_idx][:, :, -1] = new_conv_state[:, 0, :].to(self.conv_states.device)
199
+ return self.conv_states[layer_idx]
200
+
201
+ def update_ssm_state(self, layer_idx: int, new_ssm_state: torch.Tensor):
202
+ self.ssm_states[layer_idx] = new_ssm_state.to(self.ssm_states.device)
203
+ return self.ssm_states[layer_idx]
204
+
205
+ def reset(self):
206
+ self.conv_states.zero_()
207
+ self.ssm_states.zero_()
208
+
209
+
210
+ class MambaRMSNormGated(torch.nn.Module):
211
+ def __init__(self, hidden_size, eps=1e-6):
212
+ super().__init__()
213
+ self.weight = nn.Parameter(torch.ones(hidden_size))
214
+ self.variance_epsilon = eps
215
+
216
+ def forward(self, hidden_states, gate=None):
217
+ input_dtype = hidden_states.dtype
218
+ hidden_states = hidden_states.to(torch.float32)
219
+
220
+ if gate is not None:
221
+ hidden_states = hidden_states * nn.functional.silu(gate.to(torch.float32))
222
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
223
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
224
+
225
+ return self.weight * hidden_states.to(input_dtype)
226
+
227
+
228
+ class Mamba2Mixer(nn.Module):
229
+ """
230
+ Compute ∆, A, B, C, and D the state space parameters and compute the `contextualized_states`.
231
+ A, D are input independent (see Mamba paper [1] Section 3.5.2 "Interpretation of A" for why A isn't selective)
232
+ ∆, B, C are input-dependent (this is a key difference between Mamba and the linear time invariant S4,
233
+ and is why Mamba is called **selective** state spaces)
234
+ """
235
+
236
+ def __init__(self, config: Mamba2Config, layer_idx: int):
237
+ super().__init__()
238
+ self.num_heads = config.num_heads
239
+ self.hidden_size = config.hidden_size
240
+ self.ssm_state_size = config.state_size
241
+ self.conv_kernel_size = config.conv_kernel
242
+ self.intermediate_size = int(config.expand * self.hidden_size)
243
+ self.time_step_rank = int(config.time_step_rank)
244
+ self.layer_idx = layer_idx
245
+ self.use_conv_bias = config.use_conv_bias
246
+ self.activation = config.hidden_act
247
+ self.act = ACT2FN[config.hidden_act]
248
+
249
+ self.layer_norm_epsilon = config.layer_norm_epsilon
250
+ self.rms_norm = config.rms_norm
251
+
252
+ self.n_groups = config.n_groups
253
+ self.head_dim = config.head_dim
254
+ self.chunk_size = config.chunk_size
255
+
256
+ self.time_step_limit = config.time_step_limit
257
+ self.time_step_min = config.time_step_min
258
+ self.time_step_max = config.time_step_max
259
+
260
+ self.conv_dim = self.intermediate_size + 2 * self.n_groups * self.ssm_state_size
261
+ self.conv1d = nn.Conv1d(
262
+ in_channels=self.conv_dim,
263
+ out_channels=self.conv_dim,
264
+ bias=config.use_conv_bias,
265
+ kernel_size=config.conv_kernel,
266
+ groups=self.conv_dim,
267
+ padding=config.conv_kernel - 1,
268
+ )
269
+
270
+ # projection of the input hidden states
271
+ projection_size = self.intermediate_size + self.conv_dim + self.num_heads
272
+ self.in_proj = nn.Linear(
273
+ self.hidden_size,
274
+ projection_size,
275
+ bias=config.use_bias,
276
+ )
277
+ # selective projection used to make dt, B and C input dependant
278
+
279
+ # time step projection (discretization)
280
+ # instantiate once and copy inv_dt in init_weights of PretrainedModel
281
+ self.dt_bias = nn.Parameter(torch.ones(self.num_heads))
282
+
283
+ # S4D real initialization. These are not discretized!
284
+ # The core is to load them, compute the discrete states, then write the updated state. Keeps the memory bounded
285
+ A = torch.arange(1, self.num_heads + 1)
286
+ self.A_log = nn.Parameter(torch.log(A))
287
+ self.A_log._no_weight_decay = True
288
+ self.norm = MambaRMSNormGated(self.intermediate_size, eps=self.layer_norm_epsilon)
289
+ self.D = nn.Parameter(torch.ones(self.num_heads))
290
+ self.D._no_weight_decay = True
291
+
292
+ self.out_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.use_bias)
293
+ self.use_bias = config.use_bias
294
+
295
+ if not is_fast_path_available:
296
+ logger.warning_once(
297
+ "The fast path is not available because on of `(selective_state_update, causal_conv1d_fn, causal_conv1d_update)`"
298
+ " is None. Falling back to the naive implementation. To install follow https://github.com/state-spaces/mamba/#installation and"
299
+ " https://github.com/Dao-AILab/causal-conv1d"
300
+ )
301
+
302
+ def cuda_kernels_forward(
303
+ self,
304
+ hidden_states: torch.Tensor,
305
+ cache_params: Optional[Mamba2Cache] = None,
306
+ cache_position: Optional[torch.LongTensor] = None,
307
+ attention_mask: Optional[torch.Tensor] = None,
308
+ ):
309
+ # 1. Gated MLP's linear projection
310
+ hidden_states = apply_mask_to_padding_states(hidden_states, attention_mask)
311
+ projected_states = self.in_proj(hidden_states)
312
+
313
+ # Set up dimensions for reshapes later
314
+ batch_size, seq_len, _ = hidden_states.shape
315
+ groups_time_state_size = self.n_groups * self.ssm_state_size
316
+ d_mlp = (
317
+ projected_states.shape[-1]
318
+ - 2 * self.intermediate_size
319
+ - 2 * self.n_groups * self.ssm_state_size
320
+ - self.num_heads
321
+ ) // 2
322
+
323
+ # Single step calculations via cache
324
+ if cache_params is not None and cache_position is not None and cache_position[0] > 0:
325
+ _, _, gate, hidden_states_B_C, dt = projected_states.squeeze(1).split(
326
+ [d_mlp, d_mlp, self.intermediate_size, self.conv_dim, self.num_heads], dim=-1
327
+ )
328
+
329
+ # 2. Convolution sequence transformation
330
+ hidden_states_B_C = causal_conv1d_update(
331
+ hidden_states_B_C,
332
+ cache_params.conv_states[self.layer_idx],
333
+ self.conv1d.weight.squeeze(1),
334
+ self.conv1d.bias,
335
+ self.activation,
336
+ )
337
+
338
+ hidden_states, B, C = torch.split(
339
+ hidden_states_B_C,
340
+ [self.intermediate_size, groups_time_state_size, groups_time_state_size],
341
+ dim=-1,
342
+ )
343
+
344
+ # 3. SSM transformation
345
+ A = -torch.exp(self.A_log.float()) # (nheads,)
346
+ A = A[:, None, ...][:, :, None].expand(-1, self.head_dim, self.ssm_state_size).to(dtype=torch.float32)
347
+ dt = dt[:, :, None].expand(-1, -1, self.head_dim)
348
+ dt_bias = self.dt_bias[:, None, ...].expand(-1, self.head_dim)
349
+ D = self.D[:, None, ...].expand(-1, self.head_dim)
350
+ B = B.view(batch_size, self.n_groups, B.shape[1] // self.n_groups)
351
+ C = C.view(batch_size, self.n_groups, C.shape[1] // self.n_groups)
352
+ hidden_states_reshaped = hidden_states.view(batch_size, self.num_heads, self.head_dim)
353
+ hidden_states = selective_state_update(
354
+ cache_params.ssm_states[self.layer_idx],
355
+ hidden_states_reshaped,
356
+ dt,
357
+ A,
358
+ B,
359
+ C,
360
+ D,
361
+ z=None,
362
+ dt_bias=dt_bias,
363
+ dt_softplus=True,
364
+ )
365
+ hidden_states = hidden_states.view(batch_size, self.num_heads * self.head_dim)
366
+ hidden_states = self.norm(hidden_states, gate)
367
+
368
+ # 4. Final linear projection
369
+ out = self.out_proj(hidden_states)[:, None, ...]
370
+
371
+ # Fused calculations or step by step if no initialized cache is found
372
+ else:
373
+ A = -torch.exp(self.A_log.float()) # (num_heads) or (intermediate_size, state_size)
374
+ dt_limit_kwargs = {} if self.time_step_limit == (0.0, float("inf")) else {"dt_limit": self.time_step_limit}
375
+
376
+ # 2-4. Fused kernel for conv1d, SSM, and the final projection
377
+ if self.training and cache_params is None:
378
+ out = mamba_split_conv1d_scan_combined(
379
+ projected_states,
380
+ self.conv1d.weight.squeeze(1),
381
+ self.conv1d.bias,
382
+ self.dt_bias,
383
+ A,
384
+ D=self.D,
385
+ chunk_size=self.chunk_size,
386
+ seq_idx=None, # was seq_idx
387
+ activation=self.activation,
388
+ rmsnorm_weight=self.norm.weight,
389
+ rmsnorm_eps=self.norm.variance_epsilon,
390
+ outproj_weight=self.out_proj.weight,
391
+ outproj_bias=self.out_proj.bias,
392
+ headdim=self.head_dim,
393
+ ngroups=self.n_groups,
394
+ norm_before_gate=False,
395
+ return_final_states=False,
396
+ **dt_limit_kwargs,
397
+ )
398
+
399
+ else:
400
+ _, _, gate, hidden_states_B_C, dt = projected_states.split(
401
+ [d_mlp, d_mlp, self.intermediate_size, self.conv_dim, self.num_heads], dim=-1
402
+ )
403
+
404
+ # 2. Convolution sequence transformation
405
+ # Init cache
406
+ if cache_params is not None:
407
+ hidden_states_B_C_transposed = hidden_states_B_C.transpose(1, 2)
408
+ conv_states = nn.functional.pad(
409
+ hidden_states_B_C_transposed,
410
+ (cache_params.conv_kernel_size - hidden_states_B_C_transposed.shape[-1], 0),
411
+ )
412
+ cache_params.update_conv_state(
413
+ layer_idx=self.layer_idx, new_conv_state=conv_states, cache_init=True
414
+ )
415
+
416
+ if self.activation not in ["silu", "swish"]:
417
+ hidden_states_B_C = self.act(
418
+ self.conv1d(hidden_states_B_C.transpose(1, 2))[..., :seq_len].transpose(1, 2)
419
+ )
420
+ else:
421
+ hidden_states_B_C = causal_conv1d_fn(
422
+ x=hidden_states_B_C.transpose(1, 2),
423
+ weight=self.conv1d.weight.squeeze(1),
424
+ bias=self.conv1d.bias,
425
+ activation=self.activation,
426
+ ).transpose(1, 2)
427
+
428
+ hidden_states_B_C = apply_mask_to_padding_states(hidden_states_B_C, attention_mask)
429
+ hidden_states, B, C = torch.split(
430
+ hidden_states_B_C,
431
+ [self.intermediate_size, groups_time_state_size, groups_time_state_size],
432
+ dim=-1,
433
+ )
434
+
435
+ # 3. SSM transformation
436
+ scan_output, ssm_state = mamba_chunk_scan_combined(
437
+ hidden_states.view(batch_size, seq_len, -1, self.head_dim),
438
+ dt,
439
+ A,
440
+ B.view(batch_size, seq_len, self.n_groups, -1),
441
+ C.view(batch_size, seq_len, self.n_groups, -1),
442
+ chunk_size=self.chunk_size,
443
+ D=self.D,
444
+ z=None,
445
+ seq_idx=None,
446
+ return_final_states=True,
447
+ dt_bias=self.dt_bias,
448
+ dt_softplus=True,
449
+ **dt_limit_kwargs,
450
+ )
451
+
452
+ # Init cache
453
+ if ssm_state is not None and cache_params is not None:
454
+ cache_params.update_ssm_state(layer_idx=self.layer_idx, new_ssm_state=ssm_state)
455
+
456
+ scan_output = scan_output.view(batch_size, seq_len, -1)
457
+ # Multiply "gate" branch and apply extra normalization layer
458
+ scan_output = self.norm(scan_output, gate)
459
+
460
+ # 4. Final linear projection
461
+ out = self.out_proj(scan_output)
462
+ return out
463
+
464
+ # fmt: off
465
+ def torch_forward(self, input_states, cache_params: Optional[Mamba2Cache]=None, cache_position:Optional[torch.LongTensor]=None, attention_mask: Optional[torch.Tensor]=None):
466
+ batch_size, seq_len, _ = input_states.shape
467
+ dtype = input_states.dtype
468
+
469
+ # 1. Gated MLP's linear projection
470
+ input_states = apply_mask_to_padding_states(input_states, attention_mask)
471
+ projected_states = self.in_proj(input_states)
472
+ d_mlp = (projected_states.shape[-1] - 2 * self.intermediate_size - 2 * self.n_groups * self.ssm_state_size-self.num_heads) // 2
473
+ _, _, gate, hidden_states_B_C, dt = projected_states.split(
474
+ [d_mlp, d_mlp, self.intermediate_size, self.conv_dim, self.num_heads], dim=-1
475
+ )
476
+
477
+ # 2. Convolution sequence transformation
478
+ if cache_params is not None and cache_position is not None and cache_position[0] > 0:
479
+ cache_params.update_conv_state(layer_idx=self.layer_idx, new_conv_state=hidden_states_B_C, cache_init=False)
480
+
481
+ # We need to guarantee that anything regarding the cache is on the same device
482
+ conv_states = cache_params.conv_states[self.layer_idx].to(device=self.conv1d.weight.device)
483
+
484
+ hidden_states_B_C = torch.sum(
485
+ conv_states * self.conv1d.weight.squeeze(1), dim=-1
486
+ )
487
+ if self.use_conv_bias:
488
+ hidden_states_B_C = hidden_states_B_C + self.conv1d.bias
489
+ hidden_states_B_C = self.act(hidden_states_B_C)
490
+ else:
491
+ # Init cache
492
+ if cache_params is not None:
493
+ hidden_states_B_C_transposed = hidden_states_B_C.transpose(1, 2)
494
+ conv_states = nn.functional.pad(
495
+ hidden_states_B_C_transposed, (cache_params.conv_kernel_size - hidden_states_B_C_transposed.shape[-1], 0)
496
+ )
497
+ cache_params.update_conv_state(layer_idx=self.layer_idx, new_conv_state=conv_states, cache_init=True)
498
+
499
+ hidden_states_B_C = self.act(self.conv1d(hidden_states_B_C.transpose(1, 2))[..., :seq_len].transpose(1, 2))
500
+
501
+ hidden_states_B_C = apply_mask_to_padding_states(hidden_states_B_C, attention_mask)
502
+ hidden_states, B, C = torch.split(
503
+ hidden_states_B_C,
504
+ [self.intermediate_size, self.n_groups * self.ssm_state_size, self.n_groups * self.ssm_state_size],
505
+ dim=-1
506
+ )
507
+
508
+ # 3. SSM transformation
509
+ A = -torch.exp(self.A_log.float()) # [num_heads]
510
+ if cache_params is not None and cache_position is not None and cache_position[0] > 0:
511
+ # We need to guarantee that anything regarding the cache is on the same device
512
+ cache_device = cache_params.ssm_states.device
513
+
514
+ # Note: there is no need to pad parameter matrices here, as there is just one new token
515
+ # for batched generation
516
+ dt = dt[:, 0, :][:, None, ...]
517
+ dt = dt.transpose(1, 2).expand(batch_size, dt.shape[-1], self.head_dim)
518
+ # [num_heads] -> [num_heads, head_dim]
519
+ dt_bias = self.dt_bias[..., None].expand(self.dt_bias.shape[0], self.head_dim)
520
+
521
+ dt = torch.nn.functional.softplus(dt + dt_bias.to(dt.dtype))
522
+ dt = torch.clamp(dt, self.time_step_limit[0], self.time_step_limit[1])
523
+ A = A[..., None, None].expand(self.num_heads, self.head_dim, self.ssm_state_size).to(dtype=torch.float32)
524
+ # [bsz, num_heads, head_dim, state_size]
525
+ dA = (torch.exp(dt[..., None] * A)).to(device=cache_device)
526
+
527
+ # Discretize B
528
+ # [bsz, n_groups * state_size] -> [bsz, n_groups, 1, state_size] ->
529
+ # -> [bsz, n_groups, group to head repetition factor, state_size] -> [bsz, num_heads, state_size]
530
+ B = B.reshape(batch_size, self.n_groups, -1)[..., None, :]
531
+ B = B.expand(batch_size, self.n_groups, self.num_heads // self.n_groups, B.shape[-1]).contiguous()
532
+ B = B.reshape(batch_size, -1, B.shape[-1])
533
+ # [bsz, num_heads, head_dim, state_size]
534
+ dB = dt[..., None] * B[..., None, :]
535
+
536
+ # Discretize x into dB
537
+ # [bsz, intermediate_size] -> [bsz, num_heads, head_dim]
538
+ hidden_states = hidden_states.reshape(batch_size, -1, self.head_dim)
539
+ dBx = (dB * hidden_states[..., None]).to(device=cache_device)
540
+
541
+ # State calculation
542
+ cache_params.update_ssm_state(
543
+ layer_idx=self.layer_idx,
544
+ new_ssm_state=cache_params.ssm_states[self.layer_idx] * dA + dBx
545
+ )
546
+
547
+ # Subsequent output
548
+ # [bsz, n_groups * state_size] -> [bsz, num_heads, state_size]
549
+ C = C.reshape(batch_size, self.n_groups, -1)[..., None, :]
550
+ C = C.expand(batch_size, self.n_groups, self.num_heads // self.n_groups, C.shape[-1]).contiguous()
551
+ C = C.reshape(batch_size, -1, C.shape[-1])
552
+ # [bsz, num_heads, head_dim]
553
+
554
+ ssm_states = cache_params.ssm_states[self.layer_idx].to(device=C.device, dtype=C.dtype) # Shape: [b, h, d, n]
555
+ # Reshape ssm_states to merge the first two dimensions
556
+ ssm_states_reshaped = ssm_states.view(batch_size * self.num_heads, self.head_dim, self.ssm_state_size) # Shape: [b*h, d, n]
557
+ C_reshaped = C.view(batch_size * self.num_heads, self.ssm_state_size, 1) # Shape: [b*h, n, 1]
558
+ y = torch.bmm(ssm_states_reshaped, C_reshaped)
559
+ y = y.view(batch_size, self.num_heads, self.head_dim)
560
+
561
+ # D skip connection
562
+ # [num_heads] -> [num_heads, head_dim]
563
+ D = self.D[..., None].expand(self.D.shape[0], self.head_dim)
564
+ y = (y + hidden_states * D).to(y.dtype)
565
+
566
+ # [bsz, num_heads, head_dim] -> [bsz, 1, intermediate_size]
567
+ y = y.reshape(batch_size, -1)[:, None, ...]
568
+ else:
569
+ # begin ssd naive implementation without einsums
570
+ dt = nn.functional.softplus(dt + self.dt_bias)
571
+ dt = torch.clamp(dt, self.time_step_limit[0], self.time_step_limit[1])
572
+ hidden_states = hidden_states.reshape(batch_size, seq_len, -1, self.head_dim).float()
573
+ B = B.reshape(batch_size, seq_len, -1, self.ssm_state_size).float()
574
+ C = C.reshape(batch_size, seq_len, -1, self.ssm_state_size).float()
575
+ B = B.repeat(1, 1, self.num_heads // self.n_groups, 1)
576
+ C = C.repeat(1, 1, self.num_heads // self.n_groups, 1)
577
+ pad_size = (self.chunk_size - seq_len % self.chunk_size) % self.chunk_size
578
+
579
+ D_residual = self.D[..., None] * pad_tensor_by_size(hidden_states, pad_size)
580
+
581
+ # Discretize x and A
582
+ hidden_states = hidden_states * dt[..., None]
583
+ A = A.to(hidden_states.dtype) * dt
584
+
585
+ # Rearrange into blocks/chunks
586
+ hidden_states, A, B, C = [reshape_into_chunks(t, pad_size, self.chunk_size) for t in (hidden_states, A, B, C)]
587
+
588
+ # [bsz, -1, chunk_size, num_heads] -> [bsz, num_heads, -1, chunk_size]
589
+ A = A.permute(0, 3, 1, 2)
590
+ A_cumsum = torch.cumsum(A, dim=-1)
591
+
592
+ # 1. Compute the output for each intra-chunk (diagonal blocks)
593
+ # This is the analog of a causal mask
594
+ L = torch.exp(segment_sum(A))
595
+
596
+ # Contraction of C and B to get G (attention-weights like)
597
+ G_intermediate = C[:, :, :, None, :, :] * B[:, :, None, :, :, :] # shape: (b, c, l, s, h, n)
598
+ G = G_intermediate.sum(dim=-1) # shape: (b, c, l, s, h)
599
+
600
+ # Compute M, equivalent to applying attention mask to weights
601
+ M_intermediate = G[..., None] * L.permute(0, 2, 3, 4, 1)[..., None]
602
+ M = M_intermediate.sum(dim=-1)
603
+
604
+ # Compute Y_diag (apply to values)
605
+ Y_diag = (M[..., None] * hidden_states[:, :, None]).sum(dim=3)
606
+
607
+ # 2. Compute the state for each intra-chunk
608
+ # (right term of low-rank factorization of off-diagonal blocks; B terms)
609
+ decay_states = torch.exp((A_cumsum[:, :, :, -1:] - A_cumsum))
610
+ B_decay = B * decay_states.permute(0, -2, -1, 1)[..., None]
611
+ states = (B_decay[..., None, :] * hidden_states[..., None]).sum(dim=2)
612
+
613
+ # 3. Compute the inter-chunk SSM recurrence; produces correct SSM states at chunk boundaries
614
+ # (middle term of factorization of off-diag blocks; A terms)
615
+ if cache_params is not None and cache_position is not None and cache_position[0] > 0:
616
+ previous_states = cache_params.ssm_states[self.layer_idx][:, None, ...].to(device=states.device)
617
+ else:
618
+ previous_states = torch.zeros_like(states[:, :1])
619
+ states = torch.cat([previous_states, states], dim=1)
620
+ decay_chunk = torch.exp(segment_sum(nn.functional.pad(A_cumsum[:, :, :, -1], (1, 0))))
621
+ decay_chunk = decay_chunk.transpose(1, 3)
622
+ new_states = (decay_chunk[..., None, None] * states[:, :, None, ...]).sum(dim=1)
623
+ states, ssm_state = new_states[:, :-1], new_states[:, -1]
624
+
625
+ # 4. Compute state -> output conversion per chunk
626
+ # (left term of low-rank factorization of off-diagonal blocks; C terms)
627
+ state_decay_out = torch.exp(A_cumsum)
628
+ C_times_states = (C[..., None, :] * states[:, :, None, ...])
629
+ state_decay_out_permuted = state_decay_out.permute(0, 2, 3, 1)
630
+ Y_off = (C_times_states.sum(-1) * state_decay_out_permuted[..., None])
631
+
632
+ # Add output of intra-chunk and inter-chunk terms (diagonal and off-diagonal blocks)
633
+ y = Y_diag + Y_off
634
+ # [bsz, -1, self.chunk_size, num_heads, head_dim] -> [bsz, (padded) seq_len, num_heads, head_dim]
635
+ y = y.reshape(batch_size, -1, self.num_heads, self.head_dim)
636
+
637
+ y = y + D_residual
638
+ # Cutting off padded chunks
639
+ if pad_size > 0:
640
+ y = y[:, :seq_len, :, :]
641
+ y = y.reshape(batch_size, seq_len, -1)
642
+
643
+ # Init cache
644
+ if ssm_state is not None and cache_params is not None:
645
+ cache_params.update_ssm_state(layer_idx=self.layer_idx, new_ssm_state=ssm_state)
646
+
647
+ scan_output = self.norm(y, gate)
648
+
649
+ # end ssd naive
650
+
651
+ # 4. Final linear projection
652
+ contextualized_states = self.out_proj(scan_output.to(dtype)) # [batch, seq_len, hidden_size]
653
+ return contextualized_states
654
+ # fmt: on
655
+
656
+ def forward(
657
+ self,
658
+ hidden_states,
659
+ cache_params: Optional[Mamba2Cache] = None,
660
+ cache_position: Optional[torch.LongTensor] = None,
661
+ attention_mask: Optional[torch.Tensor] = None,
662
+ ):
663
+ if is_fast_path_available and "cuda" in self.in_proj.weight.device.type:
664
+ return self.cuda_kernels_forward(hidden_states, cache_params, cache_position, attention_mask)
665
+ dtype = hidden_states.dtype
666
+ if attention_mask is not None and attention_mask.shape[1] > 1 and attention_mask.shape[0] > 1:
667
+ # tune out hidden states for pad tokens, see https://github.com/state-spaces/mamba/issues/66
668
+ hidden_states = (hidden_states * attention_mask[:, :, None]).to(dtype)
669
+
670
+ return self.torch_forward(hidden_states, cache_params, cache_position, attention_mask)
671
+
672
+
673
+ class Mamba2RMSNorm(nn.Module):
674
+ def __init__(self, hidden_size, eps=1e-6):
675
+ """
676
+ Mamba2RMSNorm is equivalent to T5LayerNorm and LlamaRMSNorm
677
+ """
678
+ super().__init__()
679
+ self.weight = nn.Parameter(torch.ones(hidden_size))
680
+ self.variance_epsilon = eps
681
+
682
+ def forward(self, hidden_states):
683
+ input_dtype = hidden_states.dtype
684
+ hidden_states = hidden_states.to(torch.float32)
685
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
686
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
687
+ return self.weight * hidden_states.to(input_dtype)
688
+
689
+
690
+ class Mamba2Block(nn.Module):
691
+ def __init__(self, config, layer_idx):
692
+ super().__init__()
693
+ self.config = config
694
+ self.layer_idx = layer_idx
695
+ self.residual_in_fp32 = config.residual_in_fp32
696
+ self.norm = Mamba2RMSNorm(config.hidden_size, eps=config.layer_norm_epsilon)
697
+ self.mixer = Mamba2Mixer(config, layer_idx=layer_idx)
698
+
699
+ def forward(
700
+ self,
701
+ hidden_states,
702
+ cache_params: Optional[Mamba2Cache] = None,
703
+ cache_position: Optional[torch.LongTensor] = None,
704
+ attention_mask: Optional[torch.Tensor] = None,
705
+ ):
706
+ residual = hidden_states
707
+ hidden_states = self.norm(hidden_states.to(dtype=self.norm.weight.dtype))
708
+ if self.residual_in_fp32:
709
+ residual = residual.to(torch.float32)
710
+
711
+ hidden_states = self.mixer(
712
+ hidden_states, cache_params=cache_params, cache_position=cache_position, attention_mask=attention_mask
713
+ )
714
+ hidden_states = residual + hidden_states
715
+ return hidden_states
716
+
717
+
718
+ class Mamba2PreTrainedModel(PreTrainedModel):
719
+ """
720
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
721
+ models.
722
+ """
723
+
724
+ config_class = Mamba2Config
725
+ base_model_prefix = "backbone"
726
+ _no_split_modules = ["Mamba2Block"]
727
+ supports_gradient_checkpointing = True
728
+ _is_stateful = True
729
+
730
+ def _init_weights(self, module):
731
+ """Initialize the weights."""
732
+ if isinstance(module, Mamba2Mixer):
733
+ module.A_log._no_weight_decay = True
734
+ module.D._no_weight_decay = True
735
+
736
+ dt = torch.exp(
737
+ torch.rand(self.config.num_heads)
738
+ * (math.log(self.config.time_step_max) - math.log(self.config.time_step_min))
739
+ + math.log(self.config.time_step_min)
740
+ ).clamp(min=self.config.time_step_floor)
741
+
742
+ # # Inverse of softplus: https://github.com/pytorch/pytorch/issues/72759
743
+ inv_dt = dt + torch.log(-torch.expm1(-dt))
744
+ with torch.no_grad():
745
+ module.dt_bias.copy_(inv_dt)
746
+ module.dt_bias._no_reinit = True
747
+
748
+ if isinstance(module, nn.Linear):
749
+ if module.bias is not None:
750
+ if not getattr(module.bias, "_no_reinit", False):
751
+ nn.init.zeros_(module.bias)
752
+ elif isinstance(module, nn.Embedding):
753
+ nn.init.normal_(module.weight, std=self.config.initializer_range)
754
+
755
+ if self.config.rescale_prenorm_residual:
756
+ # Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme:
757
+ # > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale
758
+ # > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers.
759
+ # > -- GPT-2 :: https://openai.com/blog/better-language-models/
760
+ #
761
+ # Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py
762
+ for name, p in module.named_parameters():
763
+ if name in ["out_proj.weight"]:
764
+ # Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block
765
+ # Following Pytorch init, except scale by 1/sqrt(2 * n_layer)
766
+ # We need to reinit p since this code could be called multiple times
767
+ # Having just p *= scale would repeatedly scale it down
768
+ nn.init.kaiming_uniform_(p, a=math.sqrt(5))
769
+ with torch.no_grad():
770
+ p /= math.sqrt(self.config.num_hidden_layers)
771
+
772
+
773
+ @dataclass
774
+ # Copied from transformers.models.mamba.modeling_mamba.MambaOutput with MAMBA->MAMBA2,Mamba->Mamba2
775
+ class Mamba2Output(ModelOutput):
776
+ """
777
+ Class for the MAMBA2 model outputs.
778
+
779
+ Args:
780
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
781
+ Sequence of hidden-states at the output of the last layer of the model.
782
+ cache_params (`Mamba2Cache`):
783
+ The state of the model at the last time step. Can be used in a forward method with the next `input_ids` to
784
+ avoid providing the old `input_ids`.
785
+
786
+ Includes both the State space model state matrices after the selective scan, and the Convolutional states
787
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
788
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
789
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
790
+
791
+ Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
792
+ """
793
+
794
+ last_hidden_state: Optional[torch.FloatTensor] = None
795
+ cache_params: Optional[Mamba2Cache] = None
796
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
797
+
798
+
799
+ @dataclass
800
+ # Copied from transformers.models.mamba.modeling_mamba.MambaCausalLMOutput with Mamba->Mamba2
801
+ class Mamba2CausalLMOutput(ModelOutput):
802
+ """
803
+ Base class for causal language model (or autoregressive) outputs.
804
+
805
+ Args:
806
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
807
+ Language modeling loss (for next-token prediction).
808
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
809
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
810
+ cache_params (`Mamba2Cache`):
811
+ The state of the model at the last time step. Can be used in a forward method with the next `input_ids` to
812
+ avoid providing the old `input_ids`.
813
+
814
+ Includes both the State space model state matrices after the selective scan, and the Convolutional states
815
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
816
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
817
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
818
+
819
+ Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
820
+ """
821
+
822
+ loss: Optional[torch.FloatTensor] = None
823
+ logits: Optional[torch.FloatTensor] = None
824
+ cache_params: Optional[Mamba2Cache] = None
825
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
826
+
827
+
828
+ MAMBA2_START_DOCSTRING = r"""
829
+
830
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
831
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
832
+ etc.)
833
+
834
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
835
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
836
+ and behavior.
837
+
838
+ Parameters:
839
+ config ([`Mamba2Config`]): Model configuration class with all the parameters of the model.
840
+ Initializing with a config file does not load the weights associated with the model, only the
841
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
842
+ """
843
+
844
+ MAMBA2_INPUTS_DOCSTRING = r"""
845
+ Args:
846
+ input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`):
847
+ Indices of input sequence tokens in the vocabulary.
848
+
849
+ If `cache_params.seqlen_offset>0`, only `input_ids` that do not have their past calculated should be passed as
850
+ `input_ids`.
851
+
852
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
853
+ [`PreTrainedTokenizer.__call__`] for details.
854
+
855
+ [What are input IDs?](../glossary#input-ids)
856
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
857
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
858
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
859
+ model's internal embedding lookup matrix.
860
+ cache_params (`Mamba2Cache`, *optional*):
861
+ If passed along, the model uses the previous state in all the blocks (which will give the output for the
862
+ `input_ids` provided as if the model add `state_input_ids + input_ids` as context).
863
+ use_cache (`bool`, *optional*):
864
+ If set to `True`, the `cache_params` is returned and can be used to quickly generate the next logits.
865
+ output_hidden_states (`bool`, *optional*):
866
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
867
+ more detail.
868
+ return_dict (`bool`, *optional*):
869
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
870
+ cache_position (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
871
+ The position of the current input in the cache. This is used to ensure that the cache is correctly updated.
872
+ If `cache_params` is passed, `cache_position` should also be passed.
873
+ attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
874
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
875
+
876
+ - 1 for tokens that are **not masked**,
877
+ - 0 for tokens that are **masked**.
878
+
879
+ [What are attention masks?](../glossary#attention-mask)
880
+ """
881
+
882
+
883
+ @add_start_docstrings(
884
+ "The bare MAMBA2 Model transformer outputting raw hidden-states without any specific head on top.",
885
+ MAMBA2_START_DOCSTRING,
886
+ )
887
+ class Mamba2Model(Mamba2PreTrainedModel):
888
+ def __init__(self, config):
889
+ super().__init__(config)
890
+
891
+ self.embeddings = nn.Embedding(config.vocab_size, config.hidden_size)
892
+ self.layers = nn.ModuleList([Mamba2Block(config, layer_idx=idx) for idx in range(config.num_hidden_layers)])
893
+
894
+ self.gradient_checkpointing = False
895
+ self.norm_f = Mamba2RMSNorm(config.hidden_size, eps=config.layer_norm_epsilon)
896
+ # Initialize weights and apply final processing
897
+ self._register_load_state_dict_pre_hook(self.load_hook)
898
+ self.post_init()
899
+
900
+ def load_hook(self, state_dict, prefix, *args):
901
+ for k in state_dict:
902
+ if "embedding." in k:
903
+ state_dict[k.replace("embedding.", "embeddings.")] = state_dict.pop(k)
904
+ break
905
+
906
+ def get_input_embeddings(self):
907
+ return self.embeddings
908
+
909
+ def set_input_embeddings(self, new_embeddings):
910
+ self.embeddings = new_embeddings
911
+
912
+ @add_start_docstrings_to_model_forward(MAMBA2_INPUTS_DOCSTRING)
913
+ @add_code_sample_docstrings(
914
+ checkpoint=_CHECKPOINT_FOR_DOC,
915
+ output_type=Mamba2Output,
916
+ config_class=_CONFIG_FOR_DOC,
917
+ )
918
+ def forward(
919
+ self,
920
+ input_ids: Optional[torch.LongTensor] = None,
921
+ inputs_embeds: Optional[torch.LongTensor] = None,
922
+ cache_params: Optional[Mamba2Cache] = None,
923
+ use_cache: Optional[bool] = None,
924
+ output_hidden_states: Optional[bool] = None,
925
+ return_dict: Optional[bool] = None,
926
+ cache_position: Optional[torch.LongTensor] = None,
927
+ attention_mask: Optional[torch.Tensor] = None,
928
+ **kwargs,
929
+ ) -> Union[Tuple, Mamba2Output]:
930
+ output_hidden_states = (
931
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
932
+ )
933
+ use_cache = use_cache if use_cache is not None else (self.config.use_cache if not self.training else False)
934
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
935
+
936
+ if (input_ids is None) ^ (inputs_embeds is not None): # ^ is python for xor
937
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
938
+
939
+ if inputs_embeds is None:
940
+ inputs_embeds = self.embeddings(input_ids)
941
+
942
+ if self.gradient_checkpointing and self.training and use_cache:
943
+ use_cache = False
944
+
945
+ if use_cache:
946
+ if cache_params is None:
947
+ cache_params = Mamba2Cache(
948
+ self.config, inputs_embeds.size(0), device=inputs_embeds.device, dtype=inputs_embeds.dtype
949
+ )
950
+ cache_position = torch.arange(0, self.config.conv_kernel, device=inputs_embeds.device)
951
+ elif cache_position is None:
952
+ # cases when we do manual forward instead of using `model.generate` which will initiate
953
+ # `cache_position` and makes sure it is not None, throw error here instead of doing some
954
+ # hack to conjecture the current cache position
955
+ raise ValueError(
956
+ "You have to specify the `cache_position` manually when `use_cache=True` and `cache_params` is passed, "
957
+ "you don't have to pass a `cache_params` if you are in prefilling stage because in that case it will "
958
+ "be initialized for you automatically"
959
+ )
960
+ else:
961
+ cache_params = None
962
+
963
+ hidden_states = inputs_embeds
964
+ all_hidden_states = () if output_hidden_states else None
965
+ for mixer_block in self.layers:
966
+ if self.gradient_checkpointing and self.training:
967
+ hidden_states = self._gradient_checkpointing_func(
968
+ mixer_block.__call__, hidden_states, cache_params, cache_position, attention_mask
969
+ )
970
+ else:
971
+ hidden_states = mixer_block(
972
+ hidden_states,
973
+ cache_params=cache_params,
974
+ cache_position=cache_position,
975
+ attention_mask=attention_mask,
976
+ )
977
+
978
+ if output_hidden_states:
979
+ all_hidden_states = all_hidden_states + (hidden_states,)
980
+
981
+ hidden_states = self.norm_f(hidden_states)
982
+
983
+ if output_hidden_states:
984
+ all_hidden_states = all_hidden_states + (hidden_states,)
985
+
986
+ if not return_dict:
987
+ return tuple(v for v in [hidden_states, cache_params, all_hidden_states] if v is not None)
988
+
989
+ return Mamba2Output(
990
+ last_hidden_state=hidden_states,
991
+ cache_params=cache_params if use_cache else None,
992
+ hidden_states=all_hidden_states,
993
+ )
994
+
995
+
996
+ @add_start_docstrings(
997
+ """
998
+ The MAMBA2 Model transformer with a language modeling head on top (linear layer with weights not tied to the input
999
+ embeddings).
1000
+ """,
1001
+ MAMBA2_START_DOCSTRING,
1002
+ )
1003
+ class Mamba2ForCausalLM(Mamba2PreTrainedModel, GenerationMixin):
1004
+ _tied_weights_keys = []
1005
+
1006
+ def __init__(self, config):
1007
+ super().__init__(config)
1008
+ self.backbone = Mamba2Model(config)
1009
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1010
+ # Initialize weights and apply final processing
1011
+ self.post_init()
1012
+
1013
+ def get_output_embeddings(self):
1014
+ return self.lm_head
1015
+
1016
+ def set_output_embeddings(self, new_embeddings):
1017
+ self.lm_head = new_embeddings
1018
+
1019
+ def get_input_embeddings(self):
1020
+ return self.backbone.get_input_embeddings()
1021
+
1022
+ def set_input_embeddings(self, new_embeddings):
1023
+ return self.backbone.set_input_embeddings(new_embeddings)
1024
+
1025
+ def prepare_inputs_for_generation(
1026
+ self,
1027
+ input_ids,
1028
+ inputs_embeds=None,
1029
+ use_cache=None,
1030
+ cache_params: Optional[Mamba2Cache] = None,
1031
+ cache_position: Optional[torch.LongTensor] = None,
1032
+ attention_mask: Optional[torch.Tensor] = None,
1033
+ **kwargs,
1034
+ ):
1035
+ # Overwitten -- uses `cache_params` as opposed to `past_key_values`
1036
+
1037
+ if use_cache:
1038
+ # `cache_position` should have been initialized in `generate`
1039
+ if cache_position is None:
1040
+ raise ValueError(
1041
+ "`cache_position` should not be None as it should have been initialized in "
1042
+ "`model.generate`, you are responsible for passing in a valid `cache_position` if "
1043
+ "you are calling `prepare_inputs_for_generation` directly with `use_cache=True`"
1044
+ )
1045
+ if cache_position[0] > 0:
1046
+ input_ids = input_ids[:, -1][..., None]
1047
+
1048
+ if attention_mask is not None:
1049
+ attention_mask = None
1050
+ else:
1051
+ # we initialize the `cache_position` to full size of `conv_states` at prefill stage
1052
+ # considering padding will be applied when input length is shorter, and truncation
1053
+ # will be applied when it is longer, so it will be equivalent to always have it match
1054
+ # the length of `cache_params.conv_states`, which is `config.conv_kernel`
1055
+ cache_position = torch.arange(0, self.config.conv_kernel, device=input_ids.device)
1056
+
1057
+ if inputs_embeds is not None and cache_params is None:
1058
+ model_inputs = {"inputs_embeds": inputs_embeds}
1059
+ else:
1060
+ model_inputs = {"input_ids": input_ids}
1061
+
1062
+ model_inputs.update(
1063
+ {
1064
+ "attention_mask": attention_mask,
1065
+ "cache_params": cache_params,
1066
+ "use_cache": use_cache,
1067
+ "cache_position": cache_position,
1068
+ }
1069
+ )
1070
+ return model_inputs
1071
+
1072
+ @add_start_docstrings_to_model_forward(MAMBA2_INPUTS_DOCSTRING)
1073
+ @add_code_sample_docstrings(
1074
+ checkpoint=_CHECKPOINT_FOR_DOC,
1075
+ output_type=Mamba2CausalLMOutput,
1076
+ config_class=_CONFIG_FOR_DOC,
1077
+ )
1078
+ def forward(
1079
+ self,
1080
+ input_ids: Optional[torch.LongTensor] = None,
1081
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1082
+ cache_params: Optional[Mamba2Cache] = None,
1083
+ labels: Optional[torch.LongTensor] = None,
1084
+ output_hidden_states: Optional[bool] = None,
1085
+ return_dict: Optional[bool] = None,
1086
+ use_cache: Optional[bool] = None,
1087
+ cache_position: Optional[torch.Tensor] = None,
1088
+ attention_mask: Optional[torch.Tensor] = None,
1089
+ **kwargs, # for now we need this for generation
1090
+ ) -> Union[Tuple, Mamba2CausalLMOutput]:
1091
+ r"""
1092
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1093
+ Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
1094
+ `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
1095
+ are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
1096
+ """
1097
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1098
+
1099
+ mamba2_outputs = self.backbone(
1100
+ input_ids,
1101
+ cache_params=cache_params,
1102
+ inputs_embeds=inputs_embeds,
1103
+ output_hidden_states=output_hidden_states,
1104
+ return_dict=return_dict,
1105
+ use_cache=use_cache,
1106
+ cache_position=cache_position,
1107
+ attention_mask=attention_mask,
1108
+ )
1109
+ hidden_states = mamba2_outputs[0]
1110
+
1111
+ logits = self.lm_head(hidden_states.to(self.lm_head.weight.dtype)).float()
1112
+
1113
+ loss = None
1114
+ if labels is not None:
1115
+ # move labels to correct device to enable model parallelism
1116
+ labels = labels.to(logits.device)
1117
+ # Shift so that tokens < n predict n
1118
+ shift_logits = logits[..., :-1, :].contiguous()
1119
+ shift_labels = labels[..., 1:].contiguous()
1120
+ # Flatten the tokens
1121
+ loss_fct = CrossEntropyLoss()
1122
+ loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
1123
+
1124
+ if not return_dict:
1125
+ output = (logits,) + mamba2_outputs[1:]
1126
+ return ((loss,) + output) if loss is not None else output
1127
+
1128
+ return Mamba2CausalLMOutput(
1129
+ loss=loss,
1130
+ logits=logits,
1131
+ cache_params=mamba2_outputs.cache_params,
1132
+ hidden_states=mamba2_outputs.hidden_states,
1133
+ )
1134
+
1135
+
1136
+ __all__ = ["Mamba2ForCausalLM", "Mamba2Model", "Mamba2PreTrainedModel"]
vllm/lib/python3.10/site-packages/transformers/models/mvp/__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 .configuration_mvp import *
22
+ from .modeling_mvp import *
23
+ from .tokenization_mvp import *
24
+ from .tokenization_mvp_fast 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__)
vllm/lib/python3.10/site-packages/transformers/models/mvp/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (588 Bytes). View file
 
vllm/lib/python3.10/site-packages/transformers/models/mvp/__pycache__/configuration_mvp.cpython-310.pyc ADDED
Binary file (7.02 kB). View file
 
vllm/lib/python3.10/site-packages/transformers/models/mvp/__pycache__/modeling_mvp.cpython-310.pyc ADDED
Binary file (63.5 kB). View file
 
vllm/lib/python3.10/site-packages/transformers/models/mvp/__pycache__/tokenization_mvp.cpython-310.pyc ADDED
Binary file (15.1 kB). View file
 
vllm/lib/python3.10/site-packages/transformers/models/mvp/__pycache__/tokenization_mvp_fast.cpython-310.pyc ADDED
Binary file (9.39 kB). View file
 
vllm/lib/python3.10/site-packages/transformers/models/mvp/configuration_mvp.py ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 The Fairseq Authors and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """MVP model configuration"""
16
+
17
+ import warnings
18
+
19
+ from ...configuration_utils import PretrainedConfig
20
+ from ...utils import logging
21
+
22
+
23
+ logger = logging.get_logger(__name__)
24
+
25
+
26
+ class MvpConfig(PretrainedConfig):
27
+ r"""
28
+ This is the configuration class to store the configuration of a [`MvpModel`]. It is used to instantiate a MVP model
29
+ according to the specified arguments, defining the model architecture. Instantiating a configuration with the
30
+ defaults will yield a similar configuration to that of the MVP [RUCAIBox/mvp](https://huggingface.co/RUCAIBox/mvp)
31
+ architecture.
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
+ vocab_size (`int`, *optional*, defaults to 50267):
39
+ Vocabulary size of the MVP model. Defines the number of different tokens that can be represented by the
40
+ `inputs_ids` passed when calling [`MvpModel`].
41
+ d_model (`int`, *optional*, defaults to 1024):
42
+ Dimensionality of the layers and the pooler layer.
43
+ encoder_layers (`int`, *optional*, defaults to 12):
44
+ Number of encoder layers.
45
+ decoder_layers (`int`, *optional*, defaults to 12):
46
+ Number of decoder layers.
47
+ encoder_attention_heads (`int`, *optional*, defaults to 16):
48
+ Number of attention heads for each attention layer in the Transformer encoder.
49
+ decoder_attention_heads (`int`, *optional*, defaults to 16):
50
+ Number of attention heads for each attention layer in the Transformer decoder.
51
+ decoder_ffn_dim (`int`, *optional*, defaults to 4096):
52
+ Dimensionality of the "intermediate" (often named feed-forward) layer in decoder.
53
+ encoder_ffn_dim (`int`, *optional*, defaults to 4096):
54
+ Dimensionality of the "intermediate" (often named feed-forward) layer in decoder.
55
+ activation_function (`str` or `function`, *optional*, defaults to `"gelu"`):
56
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
57
+ `"relu"`, `"silu"` and `"gelu_new"` are supported.
58
+ dropout (`float`, *optional*, defaults to 0.1):
59
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
60
+ attention_dropout (`float`, *optional*, defaults to 0.0):
61
+ The dropout ratio for the attention probabilities.
62
+ activation_dropout (`float`, *optional*, defaults to 0.0):
63
+ The dropout ratio for activations inside the fully connected layer.
64
+ classifier_dropout (`float`, *optional*, defaults to 0.0):
65
+ The dropout ratio for classifier.
66
+ max_position_embeddings (`int`, *optional*, defaults to 1024):
67
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
68
+ just in case (e.g., 512 or 1024 or 2048).
69
+ init_std (`float`, *optional*, defaults to 0.02):
70
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
71
+ encoder_layerdrop (`float`, *optional*, defaults to 0.0):
72
+ The LayerDrop probability for the encoder. See the [LayerDrop paper](see https://arxiv.org/abs/1909.11556)
73
+ for more details.
74
+ decoder_layerdrop (`float`, *optional*, defaults to 0.0):
75
+ The LayerDrop probability for the decoder. See the [LayerDrop paper](see https://arxiv.org/abs/1909.11556)
76
+ for more details.
77
+ scale_embedding (`bool`, *optional*, defaults to `False`):
78
+ Scale embeddings by diving by sqrt(d_model).
79
+ use_cache (`bool`, *optional*, defaults to `True`):
80
+ Whether or not the model should return the last key/values attentions (not used by all models).
81
+ forced_eos_token_id (`int`, *optional*, defaults to 2):
82
+ The id of the token to force as the last generated token when `max_length` is reached. Usually set to
83
+ `eos_token_id`.
84
+ use_prompt (`bool`, *optional*, defaults to `False`):
85
+ Whether or not to use prompt.
86
+ prompt_length (`int`, *optional*, defaults to 100):
87
+ The length of prompt.
88
+ prompt_mid_dim (`int`, *optional*, defaults to 800):
89
+ Dimensionality of the "intermediate" layer in prompt.
90
+ Example:
91
+
92
+ ```python
93
+ >>> from transformers import MvpConfig, MvpModel
94
+
95
+ >>> # Initializing a MVP RUCAIBox/mvp style configuration
96
+ >>> configuration = MvpConfig()
97
+
98
+ >>> # Initializing a model (with random weights) from the RUCAIBox/mvp style configuration
99
+ >>> model = MvpModel(configuration)
100
+
101
+ >>> # Accessing the model configuration
102
+ >>> configuration = model.config
103
+ ```"""
104
+
105
+ model_type = "mvp"
106
+ keys_to_ignore_at_inference = ["past_key_values"]
107
+ attribute_map = {"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"}
108
+
109
+ def __init__(
110
+ self,
111
+ vocab_size=50267,
112
+ max_position_embeddings=1024,
113
+ encoder_layers=12,
114
+ encoder_ffn_dim=4096,
115
+ encoder_attention_heads=16,
116
+ decoder_layers=12,
117
+ decoder_ffn_dim=4096,
118
+ decoder_attention_heads=16,
119
+ encoder_layerdrop=0.0,
120
+ decoder_layerdrop=0.0,
121
+ activation_function="gelu",
122
+ d_model=1024,
123
+ dropout=0.1,
124
+ attention_dropout=0.0,
125
+ activation_dropout=0.0,
126
+ init_std=0.02,
127
+ classifier_dropout=0.0,
128
+ scale_embedding=False,
129
+ use_cache=True,
130
+ pad_token_id=1,
131
+ bos_token_id=0,
132
+ eos_token_id=2,
133
+ is_encoder_decoder=True,
134
+ decoder_start_token_id=2,
135
+ forced_eos_token_id=2,
136
+ use_prompt=False,
137
+ prompt_length=100,
138
+ prompt_mid_dim=800,
139
+ **kwargs,
140
+ ):
141
+ self.vocab_size = vocab_size
142
+ self.max_position_embeddings = max_position_embeddings
143
+ self.d_model = d_model
144
+ self.encoder_ffn_dim = encoder_ffn_dim
145
+ self.encoder_layers = encoder_layers
146
+ self.encoder_attention_heads = encoder_attention_heads
147
+ self.decoder_ffn_dim = decoder_ffn_dim
148
+ self.decoder_layers = decoder_layers
149
+ self.decoder_attention_heads = decoder_attention_heads
150
+ self.dropout = dropout
151
+ self.attention_dropout = attention_dropout
152
+ self.activation_dropout = activation_dropout
153
+ self.activation_function = activation_function
154
+ self.init_std = init_std
155
+ self.encoder_layerdrop = encoder_layerdrop
156
+ self.decoder_layerdrop = decoder_layerdrop
157
+ self.classifier_dropout = classifier_dropout
158
+ self.use_cache = use_cache
159
+ self.num_hidden_layers = encoder_layers
160
+ self.scale_embedding = scale_embedding # scale factor will be sqrt(d_model) if True
161
+ self.use_prompt = use_prompt
162
+ self.prompt_length = prompt_length
163
+ self.prompt_mid_dim = prompt_mid_dim
164
+
165
+ super().__init__(
166
+ pad_token_id=pad_token_id,
167
+ bos_token_id=bos_token_id,
168
+ eos_token_id=eos_token_id,
169
+ is_encoder_decoder=is_encoder_decoder,
170
+ decoder_start_token_id=decoder_start_token_id,
171
+ forced_eos_token_id=forced_eos_token_id,
172
+ **kwargs,
173
+ )
174
+
175
+ if self.forced_bos_token_id is None and kwargs.get("force_bos_token_to_be_generated", False):
176
+ self.forced_bos_token_id = self.bos_token_id
177
+ warnings.warn(
178
+ f"Please make sure the config includes `forced_bos_token_id={self.bos_token_id}` in future versions. "
179
+ "The config can simply be saved and uploaded again to be fixed."
180
+ )
181
+
182
+
183
+ __all__ = ["MvpConfig"]
vllm/lib/python3.10/site-packages/transformers/models/mvp/modeling_mvp.py ADDED
@@ -0,0 +1,1957 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 The Fairseq Authors and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """PyTorch MVP model."""
16
+
17
+ import copy
18
+ import math
19
+ from typing import List, Optional, Tuple, Union
20
+
21
+ import torch
22
+ import torch.utils.checkpoint
23
+ from torch import nn
24
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
25
+
26
+ from ...activations import ACT2FN
27
+ from ...generation import GenerationMixin
28
+ from ...modeling_attn_mask_utils import _prepare_4d_attention_mask, _prepare_4d_causal_attention_mask
29
+ from ...modeling_outputs import (
30
+ BaseModelOutput,
31
+ BaseModelOutputWithPastAndCrossAttentions,
32
+ CausalLMOutputWithCrossAttentions,
33
+ Seq2SeqLMOutput,
34
+ Seq2SeqModelOutput,
35
+ Seq2SeqQuestionAnsweringModelOutput,
36
+ Seq2SeqSequenceClassifierOutput,
37
+ )
38
+ from ...modeling_utils import PreTrainedModel
39
+ from ...utils import (
40
+ add_code_sample_docstrings,
41
+ add_end_docstrings,
42
+ add_start_docstrings,
43
+ add_start_docstrings_to_model_forward,
44
+ logging,
45
+ replace_return_docstrings,
46
+ )
47
+ from .configuration_mvp import MvpConfig
48
+
49
+
50
+ logger = logging.get_logger(__name__)
51
+
52
+ _CHECKPOINT_FOR_DOC = "RUCAIBox/mvp"
53
+ _CONFIG_FOR_DOC = "MvpConfig"
54
+
55
+ # Base model docstring
56
+ _EXPECTED_OUTPUT_SHAPE = [1, 8, 1024]
57
+
58
+
59
+ # Copied from transformers.models.bart.modeling_bart.shift_tokens_right
60
+ def shift_tokens_right(input_ids: torch.Tensor, pad_token_id: int, decoder_start_token_id: int):
61
+ """
62
+ Shift input ids one token to the right.
63
+ """
64
+ shifted_input_ids = input_ids.new_zeros(input_ids.shape)
65
+ shifted_input_ids[:, 1:] = input_ids[:, :-1].clone()
66
+ shifted_input_ids[:, 0] = decoder_start_token_id
67
+
68
+ if pad_token_id is None:
69
+ raise ValueError("self.model.config.pad_token_id has to be defined.")
70
+ # replace possible -100 values in labels by `pad_token_id`
71
+ shifted_input_ids.masked_fill_(shifted_input_ids == -100, pad_token_id)
72
+
73
+ return shifted_input_ids
74
+
75
+
76
+ # Copied from transformers.models.bart.modeling_bart.BartLearnedPositionalEmbedding with Bart->MVP
77
+ class MvpLearnedPositionalEmbedding(nn.Embedding):
78
+ """
79
+ This module learns positional embeddings up to a fixed maximum size.
80
+ """
81
+
82
+ def __init__(self, num_embeddings: int, embedding_dim: int):
83
+ # MVP is set up so that if padding_idx is specified then offset the embedding ids by 2
84
+ # and adjust num_embeddings appropriately. Other models don't have this hack
85
+ self.offset = 2
86
+ super().__init__(num_embeddings + self.offset, embedding_dim)
87
+
88
+ def forward(self, input_ids: torch.Tensor, past_key_values_length: int = 0):
89
+ """`input_ids' shape is expected to be [bsz x seqlen]."""
90
+
91
+ bsz, seq_len = input_ids.shape[:2]
92
+ positions = torch.arange(
93
+ past_key_values_length, past_key_values_length + seq_len, dtype=torch.long, device=self.weight.device
94
+ ).expand(bsz, -1)
95
+
96
+ return super().forward(positions + self.offset)
97
+
98
+
99
+ class MvpAttention(nn.Module):
100
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
101
+
102
+ def __init__(
103
+ self,
104
+ embed_dim: int,
105
+ num_heads: int,
106
+ dropout: float = 0.0,
107
+ is_decoder: bool = False,
108
+ bias: bool = True,
109
+ ):
110
+ super().__init__()
111
+ self.embed_dim = embed_dim
112
+ self.num_heads = num_heads
113
+ self.dropout = dropout
114
+ self.head_dim = embed_dim // num_heads
115
+
116
+ if (self.head_dim * num_heads) != self.embed_dim:
117
+ raise ValueError(
118
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
119
+ f" and `num_heads`: {num_heads})."
120
+ )
121
+ self.scaling = self.head_dim**-0.5
122
+ self.is_decoder = is_decoder
123
+
124
+ self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
125
+ self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
126
+ self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
127
+ self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
128
+
129
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
130
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
131
+
132
+ def forward(
133
+ self,
134
+ hidden_states: torch.Tensor,
135
+ key_value_states: Optional[torch.Tensor] = None,
136
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
137
+ attention_mask: Optional[torch.Tensor] = None,
138
+ layer_head_mask: Optional[torch.Tensor] = None,
139
+ attn_prompt: Optional[torch.Tensor] = None,
140
+ output_attentions: bool = False,
141
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
142
+ """Input shape: Batch x Time x Channel"""
143
+
144
+ # if key_value_states are provided this layer is used as a cross-attention layer
145
+ # for the decoder
146
+ is_cross_attention = key_value_states is not None
147
+
148
+ bsz, tgt_len, _ = hidden_states.size()
149
+
150
+ # get query proj
151
+ query_states = self.q_proj(hidden_states) * self.scaling
152
+ # get key, value proj
153
+ if is_cross_attention and past_key_value is not None:
154
+ # reuse k,v, cross_attentions
155
+ key_states = past_key_value[0]
156
+ value_states = past_key_value[1]
157
+ elif is_cross_attention:
158
+ # cross_attentions
159
+ key_states = self._shape(self.k_proj(key_value_states), -1, bsz)
160
+ value_states = self._shape(self.v_proj(key_value_states), -1, bsz)
161
+ elif past_key_value is not None:
162
+ # reuse k, v, self_attention
163
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
164
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
165
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
166
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
167
+ else:
168
+ # self_attention
169
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
170
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
171
+
172
+ if self.is_decoder:
173
+ # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
174
+ # Further calls to cross_attention layer can then reuse all cross-attention
175
+ # key/value_states (first "if" case)
176
+ # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
177
+ # all previous decoder key/value_states. Further calls to uni-directional self-attention
178
+ # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
179
+ # if encoder bi-directional self-attention `past_key_value` is always `None`
180
+ past_key_value = (key_states, value_states)
181
+
182
+ if attn_prompt is not None:
183
+ key_states = torch.cat([attn_prompt[0].expand(bsz, -1, -1, -1), key_states], dim=2)
184
+ value_states = torch.cat([attn_prompt[1].expand(bsz, -1, -1, -1), value_states], dim=2)
185
+ if attention_mask is not None:
186
+ prompt_mask = torch.zeros(bsz, 1, tgt_len, attn_prompt[0].size(1)).to(attention_mask.device)
187
+ attention_mask = torch.cat([prompt_mask, attention_mask], dim=(-1))
188
+
189
+ proj_shape = (bsz * self.num_heads, -1, self.head_dim)
190
+ query_states = self._shape(query_states, tgt_len, bsz).view(*proj_shape)
191
+ key_states = key_states.view(*proj_shape)
192
+ value_states = value_states.view(*proj_shape)
193
+
194
+ src_len = key_states.size(1)
195
+ attn_weights = torch.bmm(query_states, key_states.transpose(1, 2))
196
+
197
+ if attn_weights.size() != (bsz * self.num_heads, tgt_len, src_len):
198
+ raise ValueError(
199
+ f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is"
200
+ f" {attn_weights.size()}"
201
+ )
202
+
203
+ if attention_mask is not None:
204
+ if attention_mask.size() != (bsz, 1, tgt_len, src_len):
205
+ raise ValueError(
206
+ f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {attention_mask.size()}"
207
+ )
208
+ attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attention_mask
209
+ attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
210
+
211
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
212
+
213
+ if layer_head_mask is not None:
214
+ if layer_head_mask.size() != (self.num_heads,):
215
+ raise ValueError(
216
+ f"Head mask for a single layer should be of size {(self.num_heads,)}, but is"
217
+ f" {layer_head_mask.size()}"
218
+ )
219
+ attn_weights = layer_head_mask.view(1, -1, 1, 1) * attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
220
+ attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
221
+
222
+ if output_attentions:
223
+ # this operation is a bit awkward, but it's required to
224
+ # make sure that attn_weights keeps its gradient.
225
+ # In order to do so, attn_weights have to be reshaped
226
+ # twice and have to be reused in the following
227
+ attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
228
+ attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len)
229
+ else:
230
+ attn_weights_reshaped = None
231
+
232
+ attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
233
+
234
+ attn_output = torch.bmm(attn_probs, value_states)
235
+
236
+ if attn_output.size() != (bsz * self.num_heads, tgt_len, self.head_dim):
237
+ raise ValueError(
238
+ f"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is"
239
+ f" {attn_output.size()}"
240
+ )
241
+
242
+ attn_output = attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim)
243
+ attn_output = attn_output.transpose(1, 2)
244
+
245
+ # Use the `embed_dim` from the config (stored in the class) rather than `hidden_state` because `attn_output` can be
246
+ # partitioned aross GPUs when using tensor-parallelism.
247
+ attn_output = attn_output.reshape(bsz, tgt_len, self.embed_dim)
248
+
249
+ attn_output = self.out_proj(attn_output)
250
+
251
+ return attn_output, attn_weights_reshaped, past_key_value
252
+
253
+
254
+ class MvpEncoderLayer(nn.Module):
255
+ def __init__(self, config: MvpConfig):
256
+ super().__init__()
257
+ self.embed_dim = config.d_model
258
+ self.self_attn = MvpAttention(
259
+ embed_dim=self.embed_dim,
260
+ num_heads=config.encoder_attention_heads,
261
+ dropout=config.attention_dropout,
262
+ )
263
+ self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
264
+ self.dropout = config.dropout
265
+ self.activation_fn = ACT2FN[config.activation_function]
266
+ self.activation_dropout = config.activation_dropout
267
+ self.fc1 = nn.Linear(self.embed_dim, config.encoder_ffn_dim)
268
+ self.fc2 = nn.Linear(config.encoder_ffn_dim, self.embed_dim)
269
+ self.final_layer_norm = nn.LayerNorm(self.embed_dim)
270
+
271
+ def forward(
272
+ self,
273
+ hidden_states: torch.FloatTensor,
274
+ attention_mask: torch.FloatTensor,
275
+ layer_head_mask: torch.FloatTensor,
276
+ self_attn_prompt: torch.FloatTensor,
277
+ output_attentions: Optional[bool] = False,
278
+ ) -> Tuple[torch.FloatTensor, Optional[torch.FloatTensor]]:
279
+ """
280
+ Args:
281
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
282
+ attention_mask (`torch.FloatTensor`): attention mask of size
283
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
284
+ layer_head_mask (`torch.FloatTensor`): mask for attention heads in a given layer of size
285
+ `(encoder_attention_heads,)`.
286
+ self_attn_prompt (`torch.FloatTensor`): prompt of self attention of shape
287
+ `(2, encoder_attention_heads, pro_len, head_dim)`.
288
+ output_attentions (`bool`, *optional*):
289
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
290
+ returned tensors for more detail.
291
+ """
292
+ residual = hidden_states
293
+ hidden_states, attn_weights, _ = self.self_attn(
294
+ hidden_states=hidden_states,
295
+ attention_mask=attention_mask,
296
+ layer_head_mask=layer_head_mask,
297
+ attn_prompt=self_attn_prompt,
298
+ output_attentions=output_attentions,
299
+ )
300
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
301
+ hidden_states = residual + hidden_states
302
+ hidden_states = self.self_attn_layer_norm(hidden_states)
303
+
304
+ residual = hidden_states
305
+ hidden_states = self.activation_fn(self.fc1(hidden_states))
306
+ hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
307
+ hidden_states = self.fc2(hidden_states)
308
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
309
+ hidden_states = residual + hidden_states
310
+ hidden_states = self.final_layer_norm(hidden_states)
311
+
312
+ if hidden_states.dtype == torch.float16 and (
313
+ torch.isinf(hidden_states).any() or torch.isnan(hidden_states).any()
314
+ ):
315
+ clamp_value = torch.finfo(hidden_states.dtype).max - 1000
316
+ hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)
317
+
318
+ outputs = (hidden_states,)
319
+
320
+ if output_attentions:
321
+ outputs += (attn_weights,)
322
+
323
+ return outputs
324
+
325
+
326
+ class MvpDecoderLayer(nn.Module):
327
+ def __init__(self, config: MvpConfig):
328
+ super().__init__()
329
+ self.embed_dim = config.d_model
330
+
331
+ self.self_attn = MvpAttention(
332
+ embed_dim=self.embed_dim,
333
+ num_heads=config.decoder_attention_heads,
334
+ dropout=config.attention_dropout,
335
+ is_decoder=True,
336
+ )
337
+ self.dropout = config.dropout
338
+ self.activation_fn = ACT2FN[config.activation_function]
339
+ self.activation_dropout = config.activation_dropout
340
+
341
+ self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
342
+ self.encoder_attn = MvpAttention(
343
+ self.embed_dim,
344
+ config.decoder_attention_heads,
345
+ dropout=config.attention_dropout,
346
+ is_decoder=True,
347
+ )
348
+ self.encoder_attn_layer_norm = nn.LayerNorm(self.embed_dim)
349
+ self.fc1 = nn.Linear(self.embed_dim, config.decoder_ffn_dim)
350
+ self.fc2 = nn.Linear(config.decoder_ffn_dim, self.embed_dim)
351
+ self.final_layer_norm = nn.LayerNorm(self.embed_dim)
352
+
353
+ def forward(
354
+ self,
355
+ hidden_states: torch.Tensor,
356
+ attention_mask: Optional[torch.Tensor] = None,
357
+ encoder_hidden_states: Optional[torch.Tensor] = None,
358
+ encoder_attention_mask: Optional[torch.Tensor] = None,
359
+ layer_head_mask: Optional[torch.Tensor] = None,
360
+ cross_attn_layer_head_mask: Optional[torch.Tensor] = None,
361
+ self_attn_prompt: Optional[torch.Tensor] = None,
362
+ cross_attn_prompt: Optional[torch.Tensor] = None,
363
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
364
+ output_attentions: Optional[bool] = False,
365
+ use_cache: Optional[bool] = True,
366
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
367
+ """
368
+ Args:
369
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
370
+ attention_mask (`torch.FloatTensor`): attention mask of size
371
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
372
+ encoder_hidden_states (`torch.FloatTensor`):
373
+ cross attention input to the layer of shape `(batch, seq_len, embed_dim)`
374
+ encoder_attention_mask (`torch.FloatTensor`): encoder attention mask of size
375
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
376
+ layer_head_mask (`torch.FloatTensor`): mask for attention heads in a given layer of size
377
+ `(encoder_attention_heads,)`.
378
+ cross_attn_layer_head_mask (`torch.FloatTensor`): mask for cross-attention heads in a given layer of
379
+ size `(decoder_attention_heads,)`.
380
+ self_attn_prompt (`torch.FloatTensor`): prompt of self attention of shape
381
+ `(2, decoder_attention_heads, pro_len, head_dim)`.
382
+ cross_attn_prompt (`torch.FloatTensor`): prompt of cross attention of shape
383
+ `(2, decoder_attention_heads, pro_len, head_dim)`.
384
+ past_key_value (`Tuple(torch.FloatTensor)`): cached past key and value projection states
385
+ output_attentions (`bool`, *optional*):
386
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
387
+ returned tensors for more detail.
388
+ """
389
+ residual = hidden_states
390
+
391
+ # Self Attention
392
+ # decoder uni-directional self-attention cached key/values tuple is at positions 1,2
393
+ self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
394
+ # add present self-attn cache to positions 1,2 of present_key_value tuple
395
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
396
+ hidden_states=hidden_states,
397
+ past_key_value=self_attn_past_key_value,
398
+ attention_mask=attention_mask,
399
+ layer_head_mask=layer_head_mask,
400
+ attn_prompt=self_attn_prompt,
401
+ output_attentions=output_attentions,
402
+ )
403
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
404
+ hidden_states = residual + hidden_states
405
+ hidden_states = self.self_attn_layer_norm(hidden_states)
406
+
407
+ # Cross-Attention Block
408
+ cross_attn_present_key_value = None
409
+ cross_attn_weights = None
410
+ if encoder_hidden_states is not None:
411
+ residual = hidden_states
412
+
413
+ # cross_attn cached key/values tuple is at positions 3,4 of present_key_value tuple
414
+ cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None
415
+ hidden_states, cross_attn_weights, cross_attn_present_key_value = self.encoder_attn(
416
+ hidden_states=hidden_states,
417
+ key_value_states=encoder_hidden_states,
418
+ attention_mask=encoder_attention_mask,
419
+ layer_head_mask=cross_attn_layer_head_mask,
420
+ attn_prompt=cross_attn_prompt,
421
+ past_key_value=cross_attn_past_key_value,
422
+ output_attentions=output_attentions,
423
+ )
424
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
425
+ hidden_states = residual + hidden_states
426
+ hidden_states = self.encoder_attn_layer_norm(hidden_states)
427
+
428
+ # add cross-attn to positions 3,4 of present_key_value tuple
429
+ present_key_value = present_key_value + cross_attn_present_key_value
430
+
431
+ # Fully Connected
432
+ residual = hidden_states
433
+ hidden_states = self.activation_fn(self.fc1(hidden_states))
434
+ hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
435
+ hidden_states = self.fc2(hidden_states)
436
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
437
+ hidden_states = residual + hidden_states
438
+ hidden_states = self.final_layer_norm(hidden_states)
439
+
440
+ outputs = (hidden_states,)
441
+
442
+ if output_attentions:
443
+ outputs += (self_attn_weights, cross_attn_weights)
444
+
445
+ if use_cache:
446
+ outputs += (present_key_value,)
447
+
448
+ return outputs
449
+
450
+
451
+ # Copied from transformers.models.bart.modeling_bart.BartClassificationHead with Bart->MVP
452
+ class MvpClassificationHead(nn.Module):
453
+ """Head for sentence-level classification tasks."""
454
+
455
+ def __init__(
456
+ self,
457
+ input_dim: int,
458
+ inner_dim: int,
459
+ num_classes: int,
460
+ pooler_dropout: float,
461
+ ):
462
+ super().__init__()
463
+ self.dense = nn.Linear(input_dim, inner_dim)
464
+ self.dropout = nn.Dropout(p=pooler_dropout)
465
+ self.out_proj = nn.Linear(inner_dim, num_classes)
466
+
467
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
468
+ hidden_states = self.dropout(hidden_states)
469
+ hidden_states = self.dense(hidden_states)
470
+ hidden_states = torch.tanh(hidden_states)
471
+ hidden_states = self.dropout(hidden_states)
472
+ hidden_states = self.out_proj(hidden_states)
473
+ return hidden_states
474
+
475
+
476
+ class MvpPrompt(nn.Module):
477
+ """Layer-wise prompt for encoder or decoder."""
478
+
479
+ def __init__(self, config, num_layers, num_heads):
480
+ super().__init__()
481
+ self.prompt_length = config.prompt_length
482
+ self.num_layers = num_layers
483
+ self.num_heads = num_heads
484
+ self.head_dim = config.d_model // num_heads
485
+ self.dropout = nn.Dropout(p=config.dropout)
486
+ self.prompt_embedding = nn.Embedding(config.prompt_length, config.d_model)
487
+ self.prompt_trans = nn.Sequential(
488
+ nn.Linear(config.d_model, config.prompt_mid_dim),
489
+ nn.GELU(),
490
+ nn.Linear(config.prompt_mid_dim, num_layers * 2 * config.d_model),
491
+ )
492
+
493
+ def forward(self, prompt_ids: torch.Tensor) -> Tuple[torch.Tensor]:
494
+ prompt = self.prompt_trans(self.prompt_embedding(prompt_ids))
495
+ prompt = prompt.view(self.prompt_length, self.num_layers * 2, self.num_heads, self.head_dim)
496
+ prompt = self.dropout(prompt)
497
+ prompt = prompt.permute([1, 2, 0, 3]).split(2)
498
+ return prompt
499
+
500
+
501
+ class MvpPreTrainedModel(PreTrainedModel):
502
+ config_class = MvpConfig
503
+ base_model_prefix = "model"
504
+ supports_gradient_checkpointing = True
505
+
506
+ def _init_weights(self, module):
507
+ std = self.config.init_std
508
+ if isinstance(module, nn.Linear):
509
+ module.weight.data.normal_(mean=0.0, std=std)
510
+ if module.bias is not None:
511
+ module.bias.data.zero_()
512
+ elif isinstance(module, nn.Embedding):
513
+ module.weight.data.normal_(mean=0.0, std=std)
514
+ if module.padding_idx is not None:
515
+ module.weight.data[module.padding_idx].zero_()
516
+
517
+ @property
518
+ def dummy_inputs(self):
519
+ pad_token = self.config.pad_token_id
520
+ input_ids = torch.tensor([[0, 6, 10, 4, 2], [0, 8, 12, 2, pad_token]], device=self.device)
521
+ dummy_inputs = {
522
+ "attention_mask": input_ids.ne(pad_token),
523
+ "input_ids": input_ids,
524
+ }
525
+ return dummy_inputs
526
+
527
+
528
+ MVP_START_DOCSTRING = r"""
529
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
530
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
531
+ etc.)
532
+
533
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
534
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
535
+ and behavior.
536
+
537
+ Parameters:
538
+ config ([`MvpConfig`]):
539
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
540
+ load the weights associated with the model, only the configuration. Check out the
541
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
542
+ """
543
+
544
+ MVP_INPUTS_DOCSTRING = r"""
545
+ Args:
546
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
547
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
548
+ it.
549
+
550
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
551
+ [`PreTrainedTokenizer.__call__`] for details.
552
+
553
+ [What are input IDs?](../glossary#input-ids)
554
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
555
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
556
+
557
+ - 1 for tokens that are **not masked**,
558
+ - 0 for tokens that are **masked**.
559
+
560
+ [What are attention masks?](../glossary#attention-mask)
561
+ decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
562
+ Indices of decoder input sequence tokens in the vocabulary.
563
+
564
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
565
+ [`PreTrainedTokenizer.__call__`] for details.
566
+
567
+ [What are decoder input IDs?](../glossary#decoder-input-ids)
568
+
569
+ Mvp uses the `eos_token_id` as the starting token for `decoder_input_ids` generation. If `past_key_values`
570
+ is used, optionally only the last `decoder_input_ids` have to be input (see `past_key_values`).
571
+
572
+ For translation and summarization training, `decoder_input_ids` should be provided. If no
573
+ `decoder_input_ids` is provided, the model will create this tensor by shifting the `input_ids` to the right
574
+ for denoising pre-training following the paper.
575
+ decoder_attention_mask (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
576
+ Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
577
+ be used by default.
578
+
579
+ If you want to change padding behavior, you should read [`modeling_mvp._prepare_decoder_attention_mask`]
580
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
581
+ information on the default strategy.
582
+ head_mask (`torch.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, *optional*):
583
+ Mask to nullify selected heads of the attention modules in the encoder. Mask values selected in `[0, 1]`:
584
+
585
+ - 1 indicates the head is **not masked**,
586
+ - 0 indicates the head is **masked**.
587
+
588
+ decoder_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
589
+ Mask to nullify selected heads of the attention modules in the decoder. Mask values selected in `[0, 1]`:
590
+
591
+ - 1 indicates the head is **not masked**,
592
+ - 0 indicates the head is **masked**.
593
+
594
+ cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
595
+ Mask to nullify selected heads of the cross-attention modules in the decoder. Mask values selected in `[0,
596
+ 1]`:
597
+
598
+ - 1 indicates the head is **not masked**,
599
+ - 0 indicates the head is **masked**.
600
+
601
+ encoder_outputs (`tuple(tuple(torch.FloatTensor)`, *optional*):
602
+ Tuple consists of (`last_hidden_state`, *optional*: `hidden_states`, *optional*: `attentions`)
603
+ `last_hidden_state` of shape `(batch_size, sequence_length, hidden_size)`, *optional*) is a sequence of
604
+ hidden-states at the output of the last layer of the encoder. Used in the cross-attention of the decoder.
605
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
606
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
607
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
608
+ `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
609
+
610
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
611
+ blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
612
+
613
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
614
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
615
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
616
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
617
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
618
+ This is useful if you want more control over how to convert `input_ids` indices into associated vectors
619
+ than the model's internal embedding lookup matrix.
620
+ decoder_inputs_embeds (`torch.FloatTensor` of shape `(batch_size, target_sequence_length, hidden_size)`, *optional*):
621
+ Optionally, instead of passing `decoder_input_ids` you can choose to directly pass an embedded
622
+ representation. If `past_key_values` is used, optionally only the last `decoder_inputs_embeds` have to be
623
+ input (see `past_key_values`). This is useful if you want more control over how to convert
624
+ `decoder_input_ids` indices into associated vectors than the model's internal embedding lookup matrix.
625
+
626
+ If `decoder_input_ids` and `decoder_inputs_embeds` are both unset, `decoder_inputs_embeds` takes the value
627
+ of `inputs_embeds`.
628
+ use_cache (`bool`, *optional*):
629
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
630
+ `past_key_values`).
631
+ output_attentions (`bool`, *optional*):
632
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
633
+ tensors for more detail.
634
+ output_hidden_states (`bool`, *optional*):
635
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
636
+ more detail.
637
+ return_dict (`bool`, *optional*):
638
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
639
+ """
640
+
641
+ MVP_CONDITIONAL_GENERATION_EXAMPLE = r"""
642
+ Example of summarization:
643
+
644
+ Fine-tuning a model
645
+ ```python
646
+ >>> import torch
647
+ >>> from transformers import AutoTokenizer, MvpForConditionalGeneration
648
+
649
+ >>> tokenizer = AutoTokenizer.from_pretrained("RUCAIBox/mvp")
650
+ >>> model = MvpForConditionalGeneration.from_pretrained("RUCAIBox/mvp")
651
+
652
+ >>> inputs = tokenizer(
653
+ ... "Summarize: You may want to stick it to your boss and leave your job, but don't do it if these are your reasons.",
654
+ ... return_tensors="pt",
655
+ ... )
656
+ >>> labels = tokenizer("Bad Reasons To Quit Your Job", return_tensors="pt")["input_ids"]
657
+
658
+ >>> loss = model(**inputs, labels=labels).loss
659
+ >>> loss.backward()
660
+ ```
661
+
662
+ Inference after the model fine-tuned
663
+ ```python
664
+ >>> with torch.no_grad():
665
+ ... generated_ids = model.generate(**inputs)
666
+
667
+ >>> generated_text = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)
668
+ ```
669
+ """
670
+
671
+ MVP_SEQUENCE_CLASSIFICATION_SAMPLE = r"""
672
+ Example of single-label classification:
673
+
674
+ Fine-tuning a model on `num_labels` classes
675
+ ```python
676
+ >>> import torch
677
+ >>> from transformers import AutoTokenizer, MvpForSequenceClassification
678
+
679
+ >>> num_labels = 2 # for example, this is a binary classification task
680
+ >>> tokenizer = AutoTokenizer.from_pretrained("RUCAIBox/mvp")
681
+ >>> model = MvpForSequenceClassification.from_pretrained("RUCAIBox/mvp", num_labels=num_labels)
682
+
683
+ >>> inputs = tokenizer("Classify: Hello, my dog is cute", return_tensors="pt")
684
+ >>> labels = torch.tensor(1) # the real label for inputs
685
+
686
+ >>> loss = model(**inputs, labels=labels).loss
687
+ >>> loss.backward()
688
+ ```
689
+
690
+ Inference after the model fine-tuned
691
+ ```python
692
+ >>> with torch.no_grad():
693
+ ... logits = model(**inputs).logits
694
+
695
+ >>> predicted_class_id = logits.argmax()
696
+ ```
697
+ """
698
+
699
+ MVP_QUESTION_ANSWERING_SAMPLE = r"""
700
+ Example:
701
+
702
+ Fine-tuning a model for extrative question answering, and our model also supports generative question answering
703
+ using `BartForConditionalGeneration`
704
+ ```python
705
+ >>> import torch
706
+ >>> from transformers import AutoTokenizer, MvpForQuestionAnswering
707
+
708
+ >>> tokenizer = AutoTokenizer.from_pretrained("RUCAIBox/mvp")
709
+ >>> model = MvpForQuestionAnswering.from_pretrained("RUCAIBox/mvp")
710
+
711
+ >>> inputs = tokenizer(
712
+ ... "Answer the following question: Who was Jim Henson? [SEP] Jim Henson was a nice puppet",
713
+ ... return_tensors="pt",
714
+ ... )
715
+ >>> target_start_index = torch.tensor([18])
716
+ >>> target_end_index = torch.tensor([19])
717
+
718
+ >>> loss = model(**inputs, start_positions=target_start_index, end_positions=target_end_index).loss
719
+ >>> loss.backward()
720
+ ```
721
+
722
+ Inference after the model fine-tuned
723
+ ```python
724
+ >>> with torch.no_grad():
725
+ ... outputs = model(**inputs)
726
+
727
+ >>> answer_start_index = outputs.start_logits.argmax()
728
+ >>> answer_end_index = outputs.end_logits.argmax()
729
+
730
+ >>> predict_answer_tokens = inputs.input_ids[0, answer_start_index : answer_end_index + 1]
731
+ >>> predict_answer = tokenizer.decode(predict_answer_tokens)
732
+ ```
733
+ """
734
+
735
+
736
+ class MvpEncoder(MvpPreTrainedModel):
737
+ """
738
+ Transformer encoder consisting of *config.encoder_layers* self attention layers. Each layer is a
739
+ [`MvpEncoderLayer`].
740
+
741
+ Args:
742
+ config: MvpConfig
743
+ embed_tokens (nn.Embedding): output embedding
744
+ use_prompt (bool): whether to use prompt
745
+ """
746
+
747
+ def __init__(
748
+ self, config: MvpConfig, embed_tokens: Optional[nn.Embedding] = None, use_prompt: Optional[bool] = False
749
+ ):
750
+ super().__init__(config)
751
+
752
+ self.dropout = config.dropout
753
+ self.layerdrop = config.encoder_layerdrop
754
+
755
+ embed_dim = config.d_model
756
+ self.padding_idx = config.pad_token_id
757
+ self.max_source_positions = config.max_position_embeddings
758
+ self.embed_scale = math.sqrt(embed_dim) if config.scale_embedding else 1.0
759
+
760
+ if embed_tokens is not None:
761
+ self.embed_tokens = embed_tokens
762
+ else:
763
+ self.embed_tokens = nn.Embedding(config.vocab_size, embed_dim, self.padding_idx)
764
+
765
+ self.embed_positions = MvpLearnedPositionalEmbedding(
766
+ config.max_position_embeddings,
767
+ embed_dim,
768
+ )
769
+ self.layers = nn.ModuleList([MvpEncoderLayer(config) for _ in range(config.encoder_layers)])
770
+ self.layernorm_embedding = nn.LayerNorm(embed_dim)
771
+
772
+ self.use_prompt = use_prompt
773
+ if use_prompt:
774
+ self.prompt_length = config.prompt_length
775
+ self.self_attn_prompt = MvpPrompt(
776
+ config,
777
+ config.encoder_layers,
778
+ config.encoder_attention_heads,
779
+ )
780
+
781
+ self.gradient_checkpointing = False
782
+ # Initialize weights and apply final processing
783
+ self.post_init()
784
+
785
+ def get_input_embeddings(self):
786
+ return self.embed_tokens
787
+
788
+ def set_input_embeddings(self, value):
789
+ self.embed_tokens = value
790
+
791
+ def forward(
792
+ self,
793
+ input_ids: torch.LongTensor = None,
794
+ attention_mask: Optional[torch.Tensor] = None,
795
+ head_mask: Optional[torch.Tensor] = None,
796
+ inputs_embeds: Optional[torch.FloatTensor] = None,
797
+ output_attentions: Optional[bool] = None,
798
+ output_hidden_states: Optional[bool] = None,
799
+ return_dict: Optional[bool] = None,
800
+ ) -> Union[Tuple, BaseModelOutput]:
801
+ r"""
802
+ Args:
803
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
804
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
805
+ provide it.
806
+
807
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
808
+ [`PreTrainedTokenizer.__call__`] for details.
809
+
810
+ [What are input IDs?](../glossary#input-ids)
811
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
812
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
813
+
814
+ - 1 for tokens that are **not masked**,
815
+ - 0 for tokens that are **masked**.
816
+
817
+ [What are attention masks?](../glossary#attention-mask)
818
+ head_mask (`torch.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, *optional*):
819
+ Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
820
+
821
+ - 1 indicates the head is **not masked**,
822
+ - 0 indicates the head is **masked**.
823
+
824
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
825
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
826
+ This is useful if you want more control over how to convert `input_ids` indices into associated vectors
827
+ than the model's internal embedding lookup matrix.
828
+ output_attentions (`bool`, *optional*):
829
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
830
+ returned tensors for more detail.
831
+ output_hidden_states (`bool`, *optional*):
832
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
833
+ for more detail.
834
+ return_dict (`bool`, *optional*):
835
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
836
+ """
837
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
838
+ output_hidden_states = (
839
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
840
+ )
841
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
842
+
843
+ # retrieve input_ids and inputs_embeds
844
+ if input_ids is not None and inputs_embeds is not None:
845
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
846
+ elif input_ids is not None:
847
+ input = input_ids
848
+ input_shape = input.shape
849
+ input_ids = input_ids.view(-1, input_shape[-1])
850
+ elif inputs_embeds is not None:
851
+ input_shape = inputs_embeds.size()[:-1]
852
+ input = inputs_embeds[:, :, -1]
853
+ else:
854
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
855
+
856
+ if inputs_embeds is None:
857
+ inputs_embeds = self.embed_tokens(input_ids) * self.embed_scale
858
+
859
+ embed_pos = self.embed_positions(input)
860
+
861
+ hidden_states = inputs_embeds + embed_pos
862
+ hidden_states = self.layernorm_embedding(hidden_states)
863
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
864
+
865
+ # layer-wise prompt
866
+ if self.use_prompt:
867
+ prompt_ids = torch.arange(self.prompt_length).to(self.device)
868
+ self_attn_prompt = self.self_attn_prompt(prompt_ids)
869
+
870
+ # expand attention_mask
871
+ if attention_mask is not None:
872
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
873
+ attention_mask = _prepare_4d_attention_mask(attention_mask, inputs_embeds.dtype)
874
+
875
+ encoder_states = () if output_hidden_states else None
876
+ all_attentions = () if output_attentions else None
877
+
878
+ # check if head_mask has a correct number of layers specified if desired
879
+ if head_mask is not None:
880
+ if head_mask.size()[0] != (len(self.layers)):
881
+ raise ValueError(
882
+ f"The head_mask should be specified for {len(self.layers)} layers, but it is for"
883
+ f" {head_mask.size()[0]}."
884
+ )
885
+
886
+ for idx, encoder_layer in enumerate(self.layers):
887
+ if output_hidden_states:
888
+ encoder_states = encoder_states + (hidden_states,)
889
+ # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
890
+ to_drop = False
891
+ if self.training:
892
+ dropout_probability = torch.rand([])
893
+ if dropout_probability < self.layerdrop: # skip the layer
894
+ to_drop = True
895
+
896
+ if to_drop:
897
+ layer_outputs = (None, None)
898
+ else:
899
+ if self.gradient_checkpointing and self.training:
900
+ layer_outputs = self._gradient_checkpointing_func(
901
+ encoder_layer.__call__,
902
+ hidden_states,
903
+ attention_mask,
904
+ (head_mask[idx] if head_mask is not None else None),
905
+ (self_attn_prompt[idx] if self.use_prompt else None),
906
+ output_attentions,
907
+ )
908
+ else:
909
+ layer_outputs = encoder_layer(
910
+ hidden_states,
911
+ attention_mask,
912
+ layer_head_mask=(head_mask[idx] if head_mask is not None else None),
913
+ self_attn_prompt=(self_attn_prompt[idx] if self.use_prompt else None),
914
+ output_attentions=output_attentions,
915
+ )
916
+
917
+ hidden_states = layer_outputs[0]
918
+
919
+ if output_attentions:
920
+ all_attentions = all_attentions + (layer_outputs[1],)
921
+
922
+ if output_hidden_states:
923
+ encoder_states = encoder_states + (hidden_states,)
924
+
925
+ if not return_dict:
926
+ return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
927
+ return BaseModelOutput(
928
+ last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions
929
+ )
930
+
931
+
932
+ class MvpDecoder(MvpPreTrainedModel):
933
+ """
934
+ Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a [`MvpDecoderLayer`]
935
+
936
+ Args:
937
+ config: MvpConfig
938
+ embed_tokens (nn.Embedding): output embedding
939
+ use_prompt (bool): whether to use prompt
940
+ """
941
+
942
+ def __init__(
943
+ self, config: MvpConfig, embed_tokens: Optional[nn.Embedding] = None, use_prompt: Optional[bool] = False
944
+ ):
945
+ super().__init__(config)
946
+ self.dropout = config.dropout
947
+ self.layerdrop = config.decoder_layerdrop
948
+ self.padding_idx = config.pad_token_id
949
+ self.max_target_positions = config.max_position_embeddings
950
+ self.embed_scale = math.sqrt(config.d_model) if config.scale_embedding else 1.0
951
+
952
+ if embed_tokens is not None:
953
+ self.embed_tokens = embed_tokens
954
+ else:
955
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.d_model, self.padding_idx)
956
+
957
+ self.embed_positions = MvpLearnedPositionalEmbedding(
958
+ config.max_position_embeddings,
959
+ config.d_model,
960
+ )
961
+ self.layers = nn.ModuleList([MvpDecoderLayer(config) for _ in range(config.decoder_layers)])
962
+ self.layernorm_embedding = nn.LayerNorm(config.d_model)
963
+
964
+ self.use_prompt = use_prompt
965
+ if use_prompt:
966
+ self.prompt_length = config.prompt_length
967
+ self.self_attn_prompt = MvpPrompt(
968
+ config,
969
+ config.decoder_layers,
970
+ config.decoder_attention_heads,
971
+ )
972
+ self.cross_attn_prompt = MvpPrompt(
973
+ config,
974
+ config.decoder_layers,
975
+ config.decoder_attention_heads,
976
+ )
977
+
978
+ self.gradient_checkpointing = False
979
+ # Initialize weights and apply final processing
980
+ self.post_init()
981
+
982
+ def get_input_embeddings(self):
983
+ return self.embed_tokens
984
+
985
+ def set_input_embeddings(self, value):
986
+ self.embed_tokens = value
987
+
988
+ def forward(
989
+ self,
990
+ input_ids: torch.LongTensor = None,
991
+ attention_mask: Optional[torch.Tensor] = None,
992
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
993
+ encoder_attention_mask: Optional[torch.LongTensor] = None,
994
+ head_mask: Optional[torch.Tensor] = None,
995
+ cross_attn_head_mask: Optional[torch.Tensor] = None,
996
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
997
+ inputs_embeds: Optional[torch.FloatTensor] = None,
998
+ use_cache: Optional[bool] = None,
999
+ output_attentions: Optional[bool] = None,
1000
+ output_hidden_states: Optional[bool] = None,
1001
+ return_dict: Optional[bool] = None,
1002
+ ) -> Union[Tuple, BaseModelOutputWithPastAndCrossAttentions]:
1003
+ r"""
1004
+ Args:
1005
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1006
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
1007
+ provide it.
1008
+
1009
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1010
+ [`PreTrainedTokenizer.__call__`] for details.
1011
+
1012
+ [What are input IDs?](../glossary#input-ids)
1013
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1014
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1015
+
1016
+ - 1 for tokens that are **not masked**,
1017
+ - 0 for tokens that are **masked**.
1018
+
1019
+ [What are attention masks?](../glossary#attention-mask)
1020
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*):
1021
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
1022
+ of the decoder.
1023
+ encoder_attention_mask (`torch.LongTensor` of shape `(batch_size, encoder_sequence_length)`, *optional*):
1024
+ Mask to avoid performing cross-attention on padding tokens indices of encoder input_ids. Mask values
1025
+ selected in `[0, 1]`:
1026
+
1027
+ - 1 for tokens that are **not masked**,
1028
+ - 0 for tokens that are **masked**.
1029
+
1030
+ [What are attention masks?](../glossary#attention-mask)
1031
+ head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
1032
+ Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
1033
+
1034
+ - 1 indicates the head is **not masked**,
1035
+ - 0 indicates the head is **masked**.
1036
+
1037
+ cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
1038
+ Mask to nullify selected heads of the cross-attention modules in the decoder to avoid performing
1039
+ cross-attention on hidden heads. Mask values selected in `[0, 1]`:
1040
+
1041
+ - 1 indicates the head is **not masked**,
1042
+ - 0 indicates the head is **masked**.
1043
+
1044
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
1045
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
1046
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of
1047
+ shape `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
1048
+
1049
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the
1050
+ cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
1051
+
1052
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those
1053
+ that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of
1054
+ all `decoder_input_ids` of shape `(batch_size, sequence_length)`.
1055
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1056
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
1057
+ This is useful if you want more control over how to convert `input_ids` indices into associated vectors
1058
+ than the model's internal embedding lookup matrix.
1059
+ output_attentions (`bool`, *optional*):
1060
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
1061
+ returned tensors for more detail.
1062
+ output_hidden_states (`bool`, *optional*):
1063
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
1064
+ for more detail.
1065
+ return_dict (`bool`, *optional*):
1066
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1067
+ """
1068
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1069
+ output_hidden_states = (
1070
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1071
+ )
1072
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1073
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1074
+
1075
+ # retrieve input_ids and inputs_embeds
1076
+ if input_ids is not None and inputs_embeds is not None:
1077
+ raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
1078
+ elif input_ids is not None:
1079
+ input = input_ids
1080
+ input_shape = input_ids.shape
1081
+ input_ids = input_ids.view(-1, input_shape[-1])
1082
+ elif inputs_embeds is not None:
1083
+ input_shape = inputs_embeds.size()[:-1]
1084
+ input = inputs_embeds[:, :, -1]
1085
+ else:
1086
+ raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
1087
+
1088
+ # past_key_values_length
1089
+ past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0
1090
+
1091
+ if inputs_embeds is None:
1092
+ inputs_embeds = self.embed_tokens(input_ids) * self.embed_scale
1093
+
1094
+ attention_mask = _prepare_4d_causal_attention_mask(
1095
+ attention_mask, input_shape, inputs_embeds, past_key_values_length
1096
+ )
1097
+
1098
+ # expand encoder attention mask
1099
+ if encoder_hidden_states is not None and encoder_attention_mask is not None:
1100
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
1101
+ encoder_attention_mask = _prepare_4d_attention_mask(
1102
+ encoder_attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]
1103
+ )
1104
+
1105
+ # embed positions
1106
+ positions = self.embed_positions(input, past_key_values_length)
1107
+
1108
+ hidden_states = inputs_embeds + positions
1109
+ hidden_states = self.layernorm_embedding(hidden_states)
1110
+
1111
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
1112
+
1113
+ # layer-wise prompt
1114
+ if self.use_prompt:
1115
+ prompt_ids = torch.arange(self.prompt_length).to(self.device)
1116
+ self_attn_prompt = self.self_attn_prompt(prompt_ids)
1117
+ cross_attn_prompt = self.cross_attn_prompt(prompt_ids)
1118
+
1119
+ if self.gradient_checkpointing and self.training:
1120
+ if use_cache:
1121
+ logger.warning_once(
1122
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
1123
+ )
1124
+ use_cache = False
1125
+
1126
+ # decoder layers
1127
+ all_hidden_states = () if output_hidden_states else None
1128
+ all_self_attns = () if output_attentions else None
1129
+ all_cross_attentions = () if (output_attentions and encoder_hidden_states is not None) else None
1130
+ next_decoder_cache = () if use_cache else None
1131
+
1132
+ # check if head_mask/cross_attn_head_mask has a correct number of layers specified if desired
1133
+ for attn_mask, mask_name in zip([head_mask, cross_attn_head_mask], ["head_mask", "cross_attn_head_mask"]):
1134
+ if attn_mask is not None:
1135
+ if attn_mask.size()[0] != (len(self.layers)):
1136
+ raise ValueError(
1137
+ f"The `{mask_name}` should be specified for {len(self.layers)} layers, but it is for"
1138
+ f" {head_mask.size()[0]}."
1139
+ )
1140
+
1141
+ for idx, decoder_layer in enumerate(self.layers):
1142
+ # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
1143
+ if output_hidden_states:
1144
+ all_hidden_states += (hidden_states,)
1145
+ if self.training:
1146
+ dropout_probability = torch.rand([])
1147
+ if dropout_probability < self.layerdrop:
1148
+ continue
1149
+
1150
+ past_key_value = past_key_values[idx] if past_key_values is not None else None
1151
+
1152
+ if self.gradient_checkpointing and self.training:
1153
+ layer_outputs = self._gradient_checkpointing_func(
1154
+ decoder_layer.__call__,
1155
+ hidden_states,
1156
+ attention_mask,
1157
+ encoder_hidden_states,
1158
+ encoder_attention_mask,
1159
+ head_mask[idx] if head_mask is not None else None,
1160
+ cross_attn_head_mask[idx] if cross_attn_head_mask is not None else None,
1161
+ self_attn_prompt[idx] if self.use_prompt else None,
1162
+ cross_attn_prompt[idx] if self.use_prompt else None,
1163
+ None,
1164
+ output_attentions,
1165
+ use_cache,
1166
+ )
1167
+ else:
1168
+ layer_outputs = decoder_layer(
1169
+ hidden_states,
1170
+ attention_mask=attention_mask,
1171
+ encoder_hidden_states=encoder_hidden_states,
1172
+ encoder_attention_mask=encoder_attention_mask,
1173
+ layer_head_mask=(head_mask[idx] if head_mask is not None else None),
1174
+ cross_attn_layer_head_mask=(
1175
+ cross_attn_head_mask[idx] if cross_attn_head_mask is not None else None
1176
+ ),
1177
+ self_attn_prompt=(self_attn_prompt[idx] if self.use_prompt else None),
1178
+ cross_attn_prompt=(cross_attn_prompt[idx] if self.use_prompt else None),
1179
+ past_key_value=past_key_value,
1180
+ output_attentions=output_attentions,
1181
+ use_cache=use_cache,
1182
+ )
1183
+ hidden_states = layer_outputs[0]
1184
+
1185
+ if use_cache:
1186
+ next_decoder_cache += (layer_outputs[3 if output_attentions else 1],)
1187
+
1188
+ if output_attentions:
1189
+ all_self_attns += (layer_outputs[1],)
1190
+
1191
+ if encoder_hidden_states is not None:
1192
+ all_cross_attentions += (layer_outputs[2],)
1193
+
1194
+ # add hidden states from the last decoder layer
1195
+ if output_hidden_states:
1196
+ all_hidden_states += (hidden_states,)
1197
+
1198
+ next_cache = next_decoder_cache if use_cache else None
1199
+ if not return_dict:
1200
+ return tuple(
1201
+ v
1202
+ for v in [hidden_states, next_cache, all_hidden_states, all_self_attns, all_cross_attentions]
1203
+ if v is not None
1204
+ )
1205
+ return BaseModelOutputWithPastAndCrossAttentions(
1206
+ last_hidden_state=hidden_states,
1207
+ past_key_values=next_cache,
1208
+ hidden_states=all_hidden_states,
1209
+ attentions=all_self_attns,
1210
+ cross_attentions=all_cross_attentions,
1211
+ )
1212
+
1213
+
1214
+ @add_start_docstrings(
1215
+ "The bare MVP Model outputting raw hidden-states without any specific head on top.",
1216
+ MVP_START_DOCSTRING,
1217
+ )
1218
+ class MvpModel(MvpPreTrainedModel):
1219
+ _keys_to_ignore_on_load_unexpected = ["final_logits_bias"]
1220
+ _tied_weights_keys = ["encoder.embed_tokens.weight", "decoder.embed_tokens.weight"]
1221
+
1222
+ def __init__(self, config: MvpConfig):
1223
+ super().__init__(config)
1224
+
1225
+ padding_idx, vocab_size = config.pad_token_id, config.vocab_size
1226
+ self.use_prompt = config.use_prompt
1227
+ self.shared = nn.Embedding(vocab_size, config.d_model, padding_idx)
1228
+
1229
+ self.encoder = MvpEncoder(config, self.shared, config.use_prompt)
1230
+ self.decoder = MvpDecoder(config, self.shared, config.use_prompt)
1231
+
1232
+ # Initialize weights and apply final processing
1233
+ self.post_init()
1234
+
1235
+ def get_input_embeddings(self):
1236
+ return self.shared
1237
+
1238
+ def set_input_embeddings(self, value):
1239
+ self.shared = value
1240
+ self.encoder.embed_tokens = self.shared
1241
+ self.decoder.embed_tokens = self.shared
1242
+
1243
+ def get_encoder(self):
1244
+ return self.encoder
1245
+
1246
+ def get_decoder(self):
1247
+ return self.decoder
1248
+
1249
+ def set_lightweight_tuning(self):
1250
+ assert self.use_prompt, "If you want to use lightweight tuning, make sure that `use_prompt=True`."
1251
+
1252
+ self.requires_grad_(False)
1253
+ self.encoder.self_attn_prompt.requires_grad_(True)
1254
+ self.decoder.self_attn_prompt.requires_grad_(True)
1255
+ self.decoder.cross_attn_prompt.requires_grad_(True)
1256
+
1257
+ @add_start_docstrings_to_model_forward(MVP_INPUTS_DOCSTRING)
1258
+ @add_code_sample_docstrings(
1259
+ checkpoint=_CHECKPOINT_FOR_DOC,
1260
+ output_type=Seq2SeqModelOutput,
1261
+ config_class=_CONFIG_FOR_DOC,
1262
+ expected_output=_EXPECTED_OUTPUT_SHAPE,
1263
+ )
1264
+ def forward(
1265
+ self,
1266
+ input_ids: torch.LongTensor = None,
1267
+ attention_mask: Optional[torch.Tensor] = None,
1268
+ decoder_input_ids: Optional[torch.LongTensor] = None,
1269
+ decoder_attention_mask: Optional[torch.LongTensor] = None,
1270
+ head_mask: Optional[torch.Tensor] = None,
1271
+ decoder_head_mask: Optional[torch.Tensor] = None,
1272
+ cross_attn_head_mask: Optional[torch.Tensor] = None,
1273
+ encoder_outputs: Optional[List[torch.FloatTensor]] = None,
1274
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1275
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1276
+ decoder_inputs_embeds: Optional[torch.FloatTensor] = None,
1277
+ use_cache: Optional[bool] = None,
1278
+ output_attentions: Optional[bool] = None,
1279
+ output_hidden_states: Optional[bool] = None,
1280
+ return_dict: Optional[bool] = None,
1281
+ ) -> Union[Tuple, Seq2SeqModelOutput]:
1282
+ # different to other models, Mvp automatically creates decoder_input_ids from
1283
+ # input_ids if no decoder_input_ids are provided
1284
+ if decoder_input_ids is None and decoder_inputs_embeds is None:
1285
+ if input_ids is None:
1286
+ raise ValueError(
1287
+ "If no `decoder_input_ids` or `decoder_inputs_embeds` are "
1288
+ "passed, `input_ids` cannot be `None`. Please pass either "
1289
+ "`input_ids` or `decoder_input_ids` or `decoder_inputs_embeds`."
1290
+ )
1291
+
1292
+ decoder_input_ids = shift_tokens_right(
1293
+ input_ids, self.config.pad_token_id, self.config.decoder_start_token_id
1294
+ )
1295
+
1296
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1297
+ output_hidden_states = (
1298
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1299
+ )
1300
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1301
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1302
+
1303
+ if encoder_outputs is None:
1304
+ encoder_outputs = self.encoder(
1305
+ input_ids=input_ids,
1306
+ attention_mask=attention_mask,
1307
+ head_mask=head_mask,
1308
+ inputs_embeds=inputs_embeds,
1309
+ output_attentions=output_attentions,
1310
+ output_hidden_states=output_hidden_states,
1311
+ return_dict=return_dict,
1312
+ )
1313
+ # If the user passed a tuple for encoder_outputs, we wrap it in a BaseModelOutput when return_dict=True
1314
+ elif return_dict and not isinstance(encoder_outputs, BaseModelOutput):
1315
+ encoder_outputs = BaseModelOutput(
1316
+ last_hidden_state=encoder_outputs[0],
1317
+ hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
1318
+ attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
1319
+ )
1320
+
1321
+ # decoder outputs consists of (dec_features, past_key_value, dec_hidden, dec_attn)
1322
+ decoder_outputs = self.decoder(
1323
+ input_ids=decoder_input_ids,
1324
+ attention_mask=decoder_attention_mask,
1325
+ encoder_hidden_states=encoder_outputs[0],
1326
+ encoder_attention_mask=attention_mask,
1327
+ head_mask=decoder_head_mask,
1328
+ cross_attn_head_mask=cross_attn_head_mask,
1329
+ past_key_values=past_key_values,
1330
+ inputs_embeds=decoder_inputs_embeds,
1331
+ use_cache=use_cache,
1332
+ output_attentions=output_attentions,
1333
+ output_hidden_states=output_hidden_states,
1334
+ return_dict=return_dict,
1335
+ )
1336
+
1337
+ if not return_dict:
1338
+ return decoder_outputs + encoder_outputs
1339
+
1340
+ return Seq2SeqModelOutput(
1341
+ last_hidden_state=decoder_outputs.last_hidden_state,
1342
+ past_key_values=decoder_outputs.past_key_values,
1343
+ decoder_hidden_states=decoder_outputs.hidden_states,
1344
+ decoder_attentions=decoder_outputs.attentions,
1345
+ cross_attentions=decoder_outputs.cross_attentions,
1346
+ encoder_last_hidden_state=encoder_outputs.last_hidden_state,
1347
+ encoder_hidden_states=encoder_outputs.hidden_states,
1348
+ encoder_attentions=encoder_outputs.attentions,
1349
+ )
1350
+
1351
+
1352
+ @add_start_docstrings(
1353
+ "The MVP Model with a language modeling head. Can be used for various text generation tasks.", MVP_START_DOCSTRING
1354
+ )
1355
+ class MvpForConditionalGeneration(MvpPreTrainedModel, GenerationMixin):
1356
+ _tied_weights_keys = ["encoder.embed_tokens.weight", "decoder.embed_tokens.weight", "lm_head.weight"]
1357
+
1358
+ def __init__(self, config: MvpConfig):
1359
+ super().__init__(config)
1360
+ self.model = MvpModel(config)
1361
+ self.register_buffer("final_logits_bias", torch.zeros((1, self.model.shared.num_embeddings)))
1362
+ self.lm_head = nn.Linear(config.d_model, self.model.shared.num_embeddings, bias=False)
1363
+
1364
+ # Initialize weights and apply final processing
1365
+ self.post_init()
1366
+
1367
+ def get_encoder(self):
1368
+ return self.model.get_encoder()
1369
+
1370
+ def get_decoder(self):
1371
+ return self.model.get_decoder()
1372
+
1373
+ def resize_token_embeddings(
1374
+ self, new_num_tokens: int, pad_to_multiple_of: Optional[int] = None, mean_resizing: bool = True
1375
+ ) -> nn.Embedding:
1376
+ new_embeddings = super().resize_token_embeddings(new_num_tokens, pad_to_multiple_of, mean_resizing)
1377
+ self._resize_final_logits_bias(new_num_tokens)
1378
+ return new_embeddings
1379
+
1380
+ def _resize_final_logits_bias(self, new_num_tokens: int) -> None:
1381
+ old_num_tokens = self.final_logits_bias.shape[-1]
1382
+ if new_num_tokens <= old_num_tokens:
1383
+ new_bias = self.final_logits_bias[:, :new_num_tokens]
1384
+ else:
1385
+ extra_bias = torch.zeros((1, new_num_tokens - old_num_tokens), device=self.final_logits_bias.device)
1386
+ new_bias = torch.cat([self.final_logits_bias, extra_bias], dim=1)
1387
+ self.register_buffer("final_logits_bias", new_bias)
1388
+
1389
+ def get_output_embeddings(self):
1390
+ return self.lm_head
1391
+
1392
+ def set_output_embeddings(self, new_embeddings):
1393
+ self.lm_head = new_embeddings
1394
+
1395
+ def set_lightweight_tuning(self):
1396
+ self.model.set_lightweight_tuning()
1397
+ self.lm_head.requires_grad_(False)
1398
+
1399
+ @add_start_docstrings_to_model_forward(MVP_INPUTS_DOCSTRING)
1400
+ @replace_return_docstrings(output_type=Seq2SeqLMOutput, config_class=_CONFIG_FOR_DOC)
1401
+ @add_end_docstrings(MVP_CONDITIONAL_GENERATION_EXAMPLE)
1402
+ def forward(
1403
+ self,
1404
+ input_ids: torch.LongTensor = None,
1405
+ attention_mask: Optional[torch.Tensor] = None,
1406
+ decoder_input_ids: Optional[torch.LongTensor] = None,
1407
+ decoder_attention_mask: Optional[torch.LongTensor] = None,
1408
+ head_mask: Optional[torch.Tensor] = None,
1409
+ decoder_head_mask: Optional[torch.Tensor] = None,
1410
+ cross_attn_head_mask: Optional[torch.Tensor] = None,
1411
+ encoder_outputs: Optional[List[torch.FloatTensor]] = None,
1412
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1413
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1414
+ decoder_inputs_embeds: Optional[torch.FloatTensor] = None,
1415
+ labels: Optional[torch.LongTensor] = None,
1416
+ use_cache: Optional[bool] = None,
1417
+ output_attentions: Optional[bool] = None,
1418
+ output_hidden_states: Optional[bool] = None,
1419
+ return_dict: Optional[bool] = None,
1420
+ ) -> Union[Tuple, Seq2SeqLMOutput]:
1421
+ r"""
1422
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1423
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1424
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1425
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1426
+
1427
+ Returns:
1428
+ """
1429
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1430
+
1431
+ if labels is not None:
1432
+ if use_cache:
1433
+ logger.warning("The `use_cache` argument is changed to `False` since `labels` is provided.")
1434
+ use_cache = False
1435
+ if decoder_input_ids is None and decoder_inputs_embeds is None:
1436
+ decoder_input_ids = shift_tokens_right(
1437
+ labels, self.config.pad_token_id, self.config.decoder_start_token_id
1438
+ )
1439
+
1440
+ outputs = self.model(
1441
+ input_ids,
1442
+ attention_mask=attention_mask,
1443
+ decoder_input_ids=decoder_input_ids,
1444
+ encoder_outputs=encoder_outputs,
1445
+ decoder_attention_mask=decoder_attention_mask,
1446
+ head_mask=head_mask,
1447
+ decoder_head_mask=decoder_head_mask,
1448
+ cross_attn_head_mask=cross_attn_head_mask,
1449
+ past_key_values=past_key_values,
1450
+ inputs_embeds=inputs_embeds,
1451
+ decoder_inputs_embeds=decoder_inputs_embeds,
1452
+ use_cache=use_cache,
1453
+ output_attentions=output_attentions,
1454
+ output_hidden_states=output_hidden_states,
1455
+ return_dict=return_dict,
1456
+ )
1457
+ lm_logits = self.lm_head(outputs[0]) + self.final_logits_bias
1458
+
1459
+ masked_lm_loss = None
1460
+ if labels is not None:
1461
+ loss_fct = CrossEntropyLoss()
1462
+ masked_lm_loss = loss_fct(lm_logits.view(-1, self.config.vocab_size), labels.view(-1))
1463
+
1464
+ if not return_dict:
1465
+ output = (lm_logits,) + outputs[1:]
1466
+ return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
1467
+
1468
+ return Seq2SeqLMOutput(
1469
+ loss=masked_lm_loss,
1470
+ logits=lm_logits,
1471
+ past_key_values=outputs.past_key_values,
1472
+ decoder_hidden_states=outputs.decoder_hidden_states,
1473
+ decoder_attentions=outputs.decoder_attentions,
1474
+ cross_attentions=outputs.cross_attentions,
1475
+ encoder_last_hidden_state=outputs.encoder_last_hidden_state,
1476
+ encoder_hidden_states=outputs.encoder_hidden_states,
1477
+ encoder_attentions=outputs.encoder_attentions,
1478
+ )
1479
+
1480
+ def prepare_decoder_input_ids_from_labels(self, labels: torch.Tensor):
1481
+ return shift_tokens_right(labels, self.config.pad_token_id, self.config.decoder_start_token_id)
1482
+
1483
+ @staticmethod
1484
+ def _reorder_cache(past_key_values, beam_idx):
1485
+ reordered_past = ()
1486
+ for layer_past in past_key_values:
1487
+ # cached cross_attention states don't have to be reordered -> they are always the same
1488
+ reordered_past += (
1489
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past[:2])
1490
+ + layer_past[2:],
1491
+ )
1492
+ return reordered_past
1493
+
1494
+
1495
+ @add_start_docstrings(
1496
+ """
1497
+ Mvp model with a sequence classification/head on top (a linear layer on top of the pooled output) e.g. for GLUE
1498
+ tasks.
1499
+ """,
1500
+ MVP_START_DOCSTRING,
1501
+ )
1502
+ class MvpForSequenceClassification(MvpPreTrainedModel):
1503
+ _tied_weights_keys = ["encoder.embed_tokens.weight", "decoder.embed_tokens.weight"]
1504
+
1505
+ def __init__(self, config: MvpConfig, **kwargs):
1506
+ super().__init__(config, **kwargs)
1507
+ self.model = MvpModel(config)
1508
+ self.classification_head = MvpClassificationHead(
1509
+ config.d_model,
1510
+ config.d_model,
1511
+ config.num_labels,
1512
+ config.classifier_dropout,
1513
+ )
1514
+
1515
+ # Initialize weights and apply final processing
1516
+ self.post_init()
1517
+
1518
+ def set_lightweight_tuning(self):
1519
+ self.model.set_lightweight_tuning()
1520
+ self.classification_head.requires_grad_(False)
1521
+
1522
+ @add_start_docstrings_to_model_forward(MVP_INPUTS_DOCSTRING)
1523
+ @add_end_docstrings(MVP_SEQUENCE_CLASSIFICATION_SAMPLE)
1524
+ def forward(
1525
+ self,
1526
+ input_ids: torch.LongTensor = None,
1527
+ attention_mask: Optional[torch.Tensor] = None,
1528
+ decoder_input_ids: Optional[torch.LongTensor] = None,
1529
+ decoder_attention_mask: Optional[torch.LongTensor] = None,
1530
+ head_mask: Optional[torch.Tensor] = None,
1531
+ decoder_head_mask: Optional[torch.Tensor] = None,
1532
+ cross_attn_head_mask: Optional[torch.Tensor] = None,
1533
+ encoder_outputs: Optional[List[torch.FloatTensor]] = None,
1534
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1535
+ decoder_inputs_embeds: Optional[torch.FloatTensor] = None,
1536
+ labels: Optional[torch.LongTensor] = None,
1537
+ use_cache: Optional[bool] = None,
1538
+ output_attentions: Optional[bool] = None,
1539
+ output_hidden_states: Optional[bool] = None,
1540
+ return_dict: Optional[bool] = None,
1541
+ ) -> Union[Tuple, Seq2SeqSequenceClassifierOutput]:
1542
+ r"""
1543
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1544
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1545
+ config.num_labels - 1]`. If `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1546
+ """
1547
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1548
+ if labels is not None:
1549
+ use_cache = False
1550
+
1551
+ if input_ids is None and inputs_embeds is not None:
1552
+ raise NotImplementedError(
1553
+ f"Passing input embeddings is currently not supported for {self.__class__.__name__}"
1554
+ )
1555
+
1556
+ outputs = self.model(
1557
+ input_ids,
1558
+ attention_mask=attention_mask,
1559
+ decoder_input_ids=decoder_input_ids,
1560
+ decoder_attention_mask=decoder_attention_mask,
1561
+ head_mask=head_mask,
1562
+ decoder_head_mask=decoder_head_mask,
1563
+ cross_attn_head_mask=cross_attn_head_mask,
1564
+ encoder_outputs=encoder_outputs,
1565
+ inputs_embeds=inputs_embeds,
1566
+ decoder_inputs_embeds=decoder_inputs_embeds,
1567
+ use_cache=use_cache,
1568
+ output_attentions=output_attentions,
1569
+ output_hidden_states=output_hidden_states,
1570
+ return_dict=return_dict,
1571
+ )
1572
+ hidden_states = outputs[0] # last hidden state
1573
+
1574
+ eos_mask = input_ids.eq(self.config.eos_token_id).to(hidden_states.device)
1575
+
1576
+ if len(torch.unique_consecutive(eos_mask.sum(1))) > 1:
1577
+ raise ValueError("All examples must have the same number of <eos> tokens.")
1578
+ sentence_representation = hidden_states[eos_mask, :].view(hidden_states.size(0), -1, hidden_states.size(-1))[
1579
+ :, -1, :
1580
+ ]
1581
+ logits = self.classification_head(sentence_representation)
1582
+
1583
+ loss = None
1584
+ if labels is not None:
1585
+ if self.config.problem_type is None:
1586
+ if self.config.num_labels == 1:
1587
+ self.config.problem_type = "regression"
1588
+ elif self.config.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1589
+ self.config.problem_type = "single_label_classification"
1590
+ else:
1591
+ self.config.problem_type = "multi_label_classification"
1592
+
1593
+ if self.config.problem_type == "regression":
1594
+ loss_fct = MSELoss()
1595
+ if self.config.num_labels == 1:
1596
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
1597
+ else:
1598
+ loss = loss_fct(logits, labels)
1599
+ elif self.config.problem_type == "single_label_classification":
1600
+ loss_fct = CrossEntropyLoss()
1601
+ loss = loss_fct(logits.view(-1, self.config.num_labels), labels.view(-1))
1602
+ elif self.config.problem_type == "multi_label_classification":
1603
+ loss_fct = BCEWithLogitsLoss()
1604
+ loss = loss_fct(logits, labels)
1605
+ if not return_dict:
1606
+ output = (logits,) + outputs[1:]
1607
+ return ((loss,) + output) if loss is not None else output
1608
+
1609
+ return Seq2SeqSequenceClassifierOutput(
1610
+ loss=loss,
1611
+ logits=logits,
1612
+ past_key_values=outputs.past_key_values,
1613
+ decoder_hidden_states=outputs.decoder_hidden_states,
1614
+ decoder_attentions=outputs.decoder_attentions,
1615
+ cross_attentions=outputs.cross_attentions,
1616
+ encoder_last_hidden_state=outputs.encoder_last_hidden_state,
1617
+ encoder_hidden_states=outputs.encoder_hidden_states,
1618
+ encoder_attentions=outputs.encoder_attentions,
1619
+ )
1620
+
1621
+
1622
+ @add_start_docstrings(
1623
+ """
1624
+ MVP Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear layer
1625
+ on top of the hidden-states output to compute `span start logits` and `span end logits`).
1626
+ """,
1627
+ MVP_START_DOCSTRING,
1628
+ )
1629
+ class MvpForQuestionAnswering(MvpPreTrainedModel):
1630
+ _tied_weights_keys = ["encoder.embed_tokens.weight", "decoder.embed_tokens.weight"]
1631
+
1632
+ def __init__(self, config):
1633
+ super().__init__(config)
1634
+
1635
+ config.num_labels = 2
1636
+ self.num_labels = config.num_labels
1637
+
1638
+ self.model = MvpModel(config)
1639
+ self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
1640
+
1641
+ # Initialize weights and apply final processing
1642
+ self.post_init()
1643
+
1644
+ def set_lightweight_tuning(self):
1645
+ self.model.set_lightweight_tuning()
1646
+ self.qa_outputs.requires_grad_(False)
1647
+
1648
+ @add_start_docstrings_to_model_forward(MVP_INPUTS_DOCSTRING)
1649
+ @add_end_docstrings(MVP_QUESTION_ANSWERING_SAMPLE)
1650
+ def forward(
1651
+ self,
1652
+ input_ids: torch.Tensor = None,
1653
+ attention_mask: Optional[torch.Tensor] = None,
1654
+ decoder_input_ids: Optional[torch.LongTensor] = None,
1655
+ decoder_attention_mask: Optional[torch.LongTensor] = None,
1656
+ head_mask: Optional[torch.Tensor] = None,
1657
+ decoder_head_mask: Optional[torch.Tensor] = None,
1658
+ cross_attn_head_mask: Optional[torch.Tensor] = None,
1659
+ encoder_outputs: Optional[List[torch.FloatTensor]] = None,
1660
+ start_positions: Optional[torch.LongTensor] = None,
1661
+ end_positions: Optional[torch.LongTensor] = None,
1662
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1663
+ decoder_inputs_embeds: Optional[torch.FloatTensor] = None,
1664
+ use_cache: Optional[bool] = None,
1665
+ output_attentions: Optional[bool] = None,
1666
+ output_hidden_states: Optional[bool] = None,
1667
+ return_dict: Optional[bool] = None,
1668
+ ) -> Union[Tuple, Seq2SeqQuestionAnsweringModelOutput]:
1669
+ r"""
1670
+ start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1671
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
1672
+ Positions are clamped to the length of the sequence (*sequence_length*). Position outside of the sequence
1673
+ are not taken into account for computing the loss.
1674
+ end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1675
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
1676
+ Positions are clamped to the length of the sequence (*sequence_length*). Position outside of the sequence
1677
+ are not taken into account for computing the loss.
1678
+ """
1679
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1680
+ if start_positions is not None and end_positions is not None:
1681
+ use_cache = False
1682
+
1683
+ outputs = self.model(
1684
+ input_ids,
1685
+ attention_mask=attention_mask,
1686
+ decoder_input_ids=decoder_input_ids,
1687
+ decoder_attention_mask=decoder_attention_mask,
1688
+ head_mask=head_mask,
1689
+ decoder_head_mask=decoder_head_mask,
1690
+ cross_attn_head_mask=cross_attn_head_mask,
1691
+ encoder_outputs=encoder_outputs,
1692
+ inputs_embeds=inputs_embeds,
1693
+ decoder_inputs_embeds=decoder_inputs_embeds,
1694
+ use_cache=use_cache,
1695
+ output_attentions=output_attentions,
1696
+ output_hidden_states=output_hidden_states,
1697
+ return_dict=return_dict,
1698
+ )
1699
+
1700
+ sequence_output = outputs[0]
1701
+
1702
+ logits = self.qa_outputs(sequence_output)
1703
+ start_logits, end_logits = logits.split(1, dim=-1)
1704
+ start_logits = start_logits.squeeze(-1).contiguous()
1705
+ end_logits = end_logits.squeeze(-1).contiguous()
1706
+
1707
+ total_loss = None
1708
+ if start_positions is not None and end_positions is not None:
1709
+ # If we are on multi-GPU, split add a dimension
1710
+ if len(start_positions.size()) > 1:
1711
+ start_positions = start_positions.squeeze(-1)
1712
+ if len(end_positions.size()) > 1:
1713
+ end_positions = end_positions.squeeze(-1)
1714
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
1715
+ ignored_index = start_logits.size(1)
1716
+ start_positions = start_positions.clamp(0, ignored_index)
1717
+ end_positions = end_positions.clamp(0, ignored_index)
1718
+
1719
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
1720
+ start_loss = loss_fct(start_logits, start_positions)
1721
+ end_loss = loss_fct(end_logits, end_positions)
1722
+ total_loss = (start_loss + end_loss) / 2
1723
+
1724
+ if not return_dict:
1725
+ output = (
1726
+ start_logits,
1727
+ end_logits,
1728
+ ) + outputs[1:]
1729
+ return ((total_loss,) + output) if total_loss is not None else output
1730
+
1731
+ return Seq2SeqQuestionAnsweringModelOutput(
1732
+ loss=total_loss,
1733
+ start_logits=start_logits,
1734
+ end_logits=end_logits,
1735
+ past_key_values=outputs.past_key_values,
1736
+ decoder_hidden_states=outputs.decoder_hidden_states,
1737
+ decoder_attentions=outputs.decoder_attentions,
1738
+ cross_attentions=outputs.cross_attentions,
1739
+ encoder_last_hidden_state=outputs.encoder_last_hidden_state,
1740
+ encoder_hidden_states=outputs.encoder_hidden_states,
1741
+ encoder_attentions=outputs.encoder_attentions,
1742
+ )
1743
+
1744
+
1745
+ # Copied from transformers.models.bart.modeling_bart.BartDecoderWrapper with Bart->Mvp
1746
+ class MvpDecoderWrapper(MvpPreTrainedModel):
1747
+ """
1748
+ This wrapper class is a helper class to correctly load pretrained checkpoints when the causal language model is
1749
+ used in combination with the [`EncoderDecoderModel`] framework.
1750
+ """
1751
+
1752
+ def __init__(self, config):
1753
+ super().__init__(config)
1754
+ self.decoder = MvpDecoder(config)
1755
+
1756
+ def forward(self, *args, **kwargs):
1757
+ return self.decoder(*args, **kwargs)
1758
+
1759
+
1760
+ class MvpForCausalLM(MvpPreTrainedModel, GenerationMixin):
1761
+ _tied_weights_keys = ["lm_head.weight"]
1762
+
1763
+ def __init__(self, config):
1764
+ config = copy.deepcopy(config)
1765
+ config.is_decoder = True
1766
+ config.is_encoder_decoder = False
1767
+ super().__init__(config)
1768
+ self.model = MvpDecoderWrapper(config)
1769
+
1770
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1771
+
1772
+ # Initialize weights and apply final processing
1773
+ self.post_init()
1774
+
1775
+ def get_input_embeddings(self):
1776
+ return self.model.decoder.embed_tokens
1777
+
1778
+ def set_input_embeddings(self, value):
1779
+ self.model.decoder.embed_tokens = value
1780
+
1781
+ def get_output_embeddings(self):
1782
+ return self.lm_head
1783
+
1784
+ def set_output_embeddings(self, new_embeddings):
1785
+ self.lm_head = new_embeddings
1786
+
1787
+ def set_decoder(self, decoder):
1788
+ self.model.decoder = decoder
1789
+
1790
+ def get_decoder(self):
1791
+ return self.model.decoder
1792
+
1793
+ def set_lightweight_tuning(self):
1794
+ self.model.set_lightweight_tuning()
1795
+ self.lm_head.requires_grad_(False)
1796
+
1797
+ @replace_return_docstrings(output_type=CausalLMOutputWithCrossAttentions, config_class=_CONFIG_FOR_DOC)
1798
+ def forward(
1799
+ self,
1800
+ input_ids: torch.LongTensor = None,
1801
+ attention_mask: Optional[torch.Tensor] = None,
1802
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
1803
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
1804
+ head_mask: Optional[torch.Tensor] = None,
1805
+ cross_attn_head_mask: Optional[torch.Tensor] = None,
1806
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1807
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1808
+ labels: Optional[torch.LongTensor] = None,
1809
+ use_cache: Optional[bool] = None,
1810
+ output_attentions: Optional[bool] = None,
1811
+ output_hidden_states: Optional[bool] = None,
1812
+ return_dict: Optional[bool] = None,
1813
+ ) -> Union[Tuple, CausalLMOutputWithCrossAttentions]:
1814
+ r"""
1815
+ Args:
1816
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1817
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
1818
+ provide it.
1819
+
1820
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1821
+ [`PreTrainedTokenizer.__call__`] for details.
1822
+
1823
+ [What are input IDs?](../glossary#input-ids)
1824
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1825
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1826
+
1827
+ - 1 for tokens that are **not masked**,
1828
+ - 0 for tokens that are **masked**.
1829
+
1830
+ [What are attention masks?](../glossary#attention-mask)
1831
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1832
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
1833
+ if the model is configured as a decoder.
1834
+ encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
1835
+ Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used
1836
+ in the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
1837
+ head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
1838
+ Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
1839
+
1840
+ - 1 indicates the head is **not masked**,
1841
+ - 0 indicates the head is **masked**.
1842
+
1843
+ cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
1844
+ Mask to nullify selected heads of the cross-attention modules. Mask values selected in `[0, 1]`:
1845
+
1846
+ - 1 indicates the head is **not masked**,
1847
+ - 0 indicates the head is **masked**.
1848
+
1849
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
1850
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
1851
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of
1852
+ shape `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. The two additional
1853
+ tensors are only required when the model is used as a decoder in a Sequence to Sequence model.
1854
+
1855
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the
1856
+ cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
1857
+
1858
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those
1859
+ that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of
1860
+ all `decoder_input_ids` of shape `(batch_size, sequence_length)`.
1861
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1862
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1863
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1864
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1865
+ use_cache (`bool`, *optional*):
1866
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
1867
+ (see `past_key_values`).
1868
+
1869
+ - 1 for tokens that are **not masked**,
1870
+ - 0 for tokens that are **masked**.
1871
+ output_attentions (`bool`, *optional*):
1872
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
1873
+ returned tensors for more detail.
1874
+ output_hidden_states (`bool`, *optional*):
1875
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
1876
+ for more detail.
1877
+ return_dict (`bool`, *optional*):
1878
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1879
+
1880
+ Returns:
1881
+
1882
+ Example:
1883
+
1884
+ ```python
1885
+ >>> from transformers import AutoTokenizer, MvpForCausalLM
1886
+
1887
+ >>> tokenizer = AutoTokenizer.from_pretrained("RUCAIBox/mvp")
1888
+ >>> model = MvpForCausalLM.from_pretrained("RUCAIBox/mvp", add_cross_attention=False)
1889
+
1890
+ >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
1891
+ >>> outputs = model(**inputs)
1892
+
1893
+ >>> logits = outputs.logits
1894
+ >>> list(logits.shape)
1895
+ [1, 8, 50267]
1896
+ ```"""
1897
+
1898
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1899
+ output_hidden_states = (
1900
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1901
+ )
1902
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1903
+
1904
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1905
+ outputs = self.model.decoder(
1906
+ input_ids=input_ids,
1907
+ attention_mask=attention_mask,
1908
+ encoder_hidden_states=encoder_hidden_states,
1909
+ encoder_attention_mask=encoder_attention_mask,
1910
+ head_mask=head_mask,
1911
+ cross_attn_head_mask=cross_attn_head_mask,
1912
+ past_key_values=past_key_values,
1913
+ inputs_embeds=inputs_embeds,
1914
+ use_cache=use_cache,
1915
+ output_attentions=output_attentions,
1916
+ output_hidden_states=output_hidden_states,
1917
+ return_dict=return_dict,
1918
+ )
1919
+
1920
+ logits = self.lm_head(outputs[0])
1921
+
1922
+ loss = None
1923
+ if labels is not None:
1924
+ loss_fct = CrossEntropyLoss()
1925
+ loss = loss_fct(logits.view(-1, self.config.vocab_size), labels.view(-1))
1926
+
1927
+ if not return_dict:
1928
+ output = (logits,) + outputs[1:]
1929
+ return (loss,) + output if loss is not None else output
1930
+
1931
+ return CausalLMOutputWithCrossAttentions(
1932
+ loss=loss,
1933
+ logits=logits,
1934
+ past_key_values=outputs.past_key_values,
1935
+ hidden_states=outputs.hidden_states,
1936
+ attentions=outputs.attentions,
1937
+ cross_attentions=outputs.cross_attentions,
1938
+ )
1939
+
1940
+ @staticmethod
1941
+ def _reorder_cache(past_key_values, beam_idx):
1942
+ reordered_past = ()
1943
+ for layer_past in past_key_values:
1944
+ reordered_past += (
1945
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1946
+ )
1947
+ return reordered_past
1948
+
1949
+
1950
+ __all__ = [
1951
+ "MvpForCausalLM",
1952
+ "MvpForConditionalGeneration",
1953
+ "MvpForQuestionAnswering",
1954
+ "MvpForSequenceClassification",
1955
+ "MvpModel",
1956
+ "MvpPreTrainedModel",
1957
+ ]
vllm/lib/python3.10/site-packages/transformers/models/mvp/tokenization_mvp.py ADDED
@@ -0,0 +1,394 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 The Facebook AI Research Team Authors and The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import json
17
+ import os
18
+ from functools import lru_cache
19
+ from typing import List, Optional, Tuple
20
+
21
+ import regex as re
22
+
23
+ from ...tokenization_utils import AddedToken, PreTrainedTokenizer
24
+ from ...utils import logging
25
+
26
+
27
+ logger = logging.get_logger(__name__)
28
+
29
+
30
+ VOCAB_FILES_NAMES = {"vocab_file": "vocab.json", "merges_file": "merges.txt"}
31
+
32
+ # See all MVP models at https://huggingface.co/models?filter=mvp
33
+
34
+
35
+ @lru_cache()
36
+ def bytes_to_unicode():
37
+ """
38
+ Returns list of utf-8 byte and a mapping to unicode strings. We specifically avoids mapping to whitespace/control
39
+ characters the bpe code barfs on.
40
+
41
+ The reversible bpe codes work on unicode strings. This means you need a large # of unicode characters in your vocab
42
+ if you want to avoid UNKs. When you're at something like a 10B token dataset you end up needing around 5K for
43
+ decent coverage. This is a significant percentage of your normal, say, 32K bpe vocab. To avoid that, we want lookup
44
+ tables between utf-8 bytes and unicode strings.
45
+ """
46
+ bs = (
47
+ list(range(ord("!"), ord("~") + 1)) + list(range(ord("¡"), ord("¬") + 1)) + list(range(ord("®"), ord("ÿ") + 1))
48
+ )
49
+ cs = bs[:]
50
+ n = 0
51
+ for b in range(2**8):
52
+ if b not in bs:
53
+ bs.append(b)
54
+ cs.append(2**8 + n)
55
+ n += 1
56
+ cs = [chr(n) for n in cs]
57
+ return dict(zip(bs, cs))
58
+
59
+
60
+ def get_pairs(word):
61
+ """
62
+ Return set of symbol pairs in a word.
63
+
64
+ Word is represented as tuple of symbols (symbols being variable-length strings).
65
+ """
66
+ pairs = set()
67
+ prev_char = word[0]
68
+ for char in word[1:]:
69
+ pairs.add((prev_char, char))
70
+ prev_char = char
71
+ return pairs
72
+
73
+
74
+ class MvpTokenizer(PreTrainedTokenizer):
75
+ """
76
+ Constructs a MVP tokenizer, which is smilar to the RoBERTa tokenizer, using byte-level Byte-Pair-Encoding.
77
+
78
+ This tokenizer has been trained to treat spaces like parts of the tokens (a bit like sentencepiece) so a word will
79
+ be encoded differently whether it is at the beginning of the sentence (without space) or not:
80
+
81
+ ```python
82
+ >>> from transformers import MvpTokenizer
83
+
84
+ >>> tokenizer = MvpTokenizer.from_pretrained("RUCAIBox/mvp")
85
+ >>> tokenizer("Hello world")["input_ids"]
86
+ [0, 31414, 232, 2]
87
+
88
+ >>> tokenizer(" Hello world")["input_ids"]
89
+ [0, 20920, 232, 2]
90
+ ```
91
+
92
+ You can get around that behavior by passing `add_prefix_space=True` when instantiating this tokenizer or when you
93
+ call it on some text, but since the model was not pretrained this way, it might yield a decrease in performance.
94
+
95
+ <Tip>
96
+
97
+ When used with `is_split_into_words=True`, this tokenizer will add a space before each word (even the first one).
98
+
99
+ </Tip>
100
+
101
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
102
+ this superclass for more information regarding those methods.
103
+
104
+ Args:
105
+ vocab_file (`str`):
106
+ Path to the vocabulary file.
107
+ merges_file (`str`):
108
+ Path to the merges file.
109
+ errors (`str`, *optional*, defaults to `"replace"`):
110
+ Paradigm to follow when decoding bytes to UTF-8. See
111
+ [bytes.decode](https://docs.python.org/3/library/stdtypes.html#bytes.decode) for more information.
112
+ bos_token (`str`, *optional*, defaults to `"<s>"`):
113
+ The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
114
+
115
+ <Tip>
116
+
117
+ When building a sequence using special tokens, this is not the token that is used for the beginning of
118
+ sequence. The token used is the `cls_token`.
119
+
120
+ </Tip>
121
+
122
+ eos_token (`str`, *optional*, defaults to `"</s>"`):
123
+ The end of sequence token.
124
+
125
+ <Tip>
126
+
127
+ When building a sequence using special tokens, this is not the token that is used for the end of sequence.
128
+ The token used is the `sep_token`.
129
+
130
+ </Tip>
131
+
132
+ sep_token (`str`, *optional*, defaults to `"</s>"`):
133
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
134
+ sequence classification or for a text and a question for question answering. It is also used as the last
135
+ token of a sequence built with special tokens.
136
+ cls_token (`str`, *optional*, defaults to `"<s>"`):
137
+ The classifier token which is used when doing sequence classification (classification of the whole sequence
138
+ instead of per-token classification). It is the first token of the sequence when built with special tokens.
139
+ unk_token (`str`, *optional*, defaults to `"<unk>"`):
140
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
141
+ token instead.
142
+ pad_token (`str`, *optional*, defaults to `"<pad>"`):
143
+ The token used for padding, for example when batching sequences of different lengths.
144
+ mask_token (`str`, *optional*, defaults to `"<mask>"`):
145
+ The token used for masking values. This is the token used when training this model with masked language
146
+ modeling. This is the token which the model will try to predict.
147
+ add_prefix_space (`bool`, *optional*, defaults to `False`):
148
+ Whether or not to add an initial space to the input. This allows to treat the leading word just as any
149
+ other word. (MVP tokenizer detect beginning of words by the preceding space).
150
+ """
151
+
152
+ vocab_files_names = VOCAB_FILES_NAMES
153
+ model_input_names = ["input_ids", "attention_mask"]
154
+
155
+ def __init__(
156
+ self,
157
+ vocab_file,
158
+ merges_file,
159
+ errors="replace",
160
+ bos_token="<s>",
161
+ eos_token="</s>",
162
+ sep_token="</s>",
163
+ cls_token="<s>",
164
+ unk_token="<unk>",
165
+ pad_token="<pad>",
166
+ mask_token="<mask>",
167
+ add_prefix_space=False,
168
+ **kwargs,
169
+ ):
170
+ bos_token = AddedToken(bos_token, special=True) if isinstance(bos_token, str) else bos_token
171
+ eos_token = AddedToken(eos_token, special=True) if isinstance(eos_token, str) else eos_token
172
+ sep_token = AddedToken(sep_token, special=True) if isinstance(sep_token, str) else sep_token
173
+ cls_token = AddedToken(cls_token, special=True) if isinstance(cls_token, str) else cls_token
174
+ unk_token = AddedToken(unk_token, special=True) if isinstance(unk_token, str) else unk_token
175
+ pad_token = AddedToken(pad_token, special=True) if isinstance(pad_token, str) else pad_token
176
+
177
+ # Mask token behave like a normal word, i.e. include the space before it
178
+ mask_token = AddedToken(mask_token, lstrip=True, special=True) if isinstance(mask_token, str) else mask_token
179
+ with open(vocab_file, encoding="utf-8") as vocab_handle:
180
+ self.encoder = json.load(vocab_handle)
181
+ self.decoder = {v: k for k, v in self.encoder.items()}
182
+ self.errors = errors # how to handle errors in decoding
183
+ self.byte_encoder = bytes_to_unicode()
184
+ self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
185
+ with open(merges_file, encoding="utf-8") as merges_handle:
186
+ bpe_merges = merges_handle.read().split("\n")[1:-1]
187
+ bpe_merges = [tuple(merge.split()) for merge in bpe_merges]
188
+ self.bpe_ranks = dict(zip(bpe_merges, range(len(bpe_merges))))
189
+ self.cache = {}
190
+ self.add_prefix_space = add_prefix_space
191
+
192
+ # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions
193
+ self.pat = re.compile(r"""'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+""")
194
+
195
+ super().__init__(
196
+ errors=errors,
197
+ bos_token=bos_token,
198
+ eos_token=eos_token,
199
+ unk_token=unk_token,
200
+ sep_token=sep_token,
201
+ cls_token=cls_token,
202
+ pad_token=pad_token,
203
+ mask_token=mask_token,
204
+ add_prefix_space=add_prefix_space,
205
+ **kwargs,
206
+ )
207
+
208
+ @property
209
+ def vocab_size(self):
210
+ return len(self.encoder)
211
+
212
+ def get_vocab(self):
213
+ vocab = self.encoder.copy()
214
+ vocab.update(self.added_tokens_encoder)
215
+ return vocab
216
+
217
+ def bpe(self, token):
218
+ if token in self.cache:
219
+ return self.cache[token]
220
+ word = tuple(token)
221
+ pairs = get_pairs(word)
222
+
223
+ if not pairs:
224
+ return token
225
+
226
+ while True:
227
+ bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
228
+ if bigram not in self.bpe_ranks:
229
+ break
230
+ first, second = bigram
231
+ new_word = []
232
+ i = 0
233
+ while i < len(word):
234
+ try:
235
+ j = word.index(first, i)
236
+ except ValueError:
237
+ new_word.extend(word[i:])
238
+ break
239
+ else:
240
+ new_word.extend(word[i:j])
241
+ i = j
242
+
243
+ if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
244
+ new_word.append(first + second)
245
+ i += 2
246
+ else:
247
+ new_word.append(word[i])
248
+ i += 1
249
+ new_word = tuple(new_word)
250
+ word = new_word
251
+ if len(word) == 1:
252
+ break
253
+ else:
254
+ pairs = get_pairs(word)
255
+ word = " ".join(word)
256
+ self.cache[token] = word
257
+ return word
258
+
259
+ def _tokenize(self, text):
260
+ """Tokenize a string."""
261
+ bpe_tokens = []
262
+ for token in re.findall(self.pat, text):
263
+ token = "".join(
264
+ self.byte_encoder[b] for b in token.encode("utf-8")
265
+ ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
266
+ bpe_tokens.extend(bpe_token for bpe_token in self.bpe(token).split(" "))
267
+ return bpe_tokens
268
+
269
+ def _convert_token_to_id(self, token):
270
+ """Converts a token (str) in an id using the vocab."""
271
+ return self.encoder.get(token, self.encoder.get(self.unk_token))
272
+
273
+ def _convert_id_to_token(self, index):
274
+ """Converts an index (integer) in a token (str) using the vocab."""
275
+ return self.decoder.get(index)
276
+
277
+ def convert_tokens_to_string(self, tokens):
278
+ """Converts a sequence of tokens (string) in a single string."""
279
+ text = "".join(tokens)
280
+ text = bytearray([self.byte_decoder[c] for c in text]).decode("utf-8", errors=self.errors)
281
+ return text
282
+
283
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
284
+ if not os.path.isdir(save_directory):
285
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
286
+ return
287
+ vocab_file = os.path.join(
288
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
289
+ )
290
+ merge_file = os.path.join(
291
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]
292
+ )
293
+
294
+ with open(vocab_file, "w", encoding="utf-8") as f:
295
+ f.write(json.dumps(self.encoder, indent=2, sort_keys=True, ensure_ascii=False) + "\n")
296
+
297
+ index = 0
298
+ with open(merge_file, "w", encoding="utf-8") as writer:
299
+ writer.write("#version: 0.2\n")
300
+ for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda kv: kv[1]):
301
+ if index != token_index:
302
+ logger.warning(
303
+ f"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."
304
+ " Please check that the tokenizer is not corrupted!"
305
+ )
306
+ index = token_index
307
+ writer.write(" ".join(bpe_tokens) + "\n")
308
+ index += 1
309
+
310
+ return vocab_file, merge_file
311
+
312
+ def build_inputs_with_special_tokens(
313
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
314
+ ) -> List[int]:
315
+ """
316
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
317
+ adding special tokens. A MVP sequence has the following format:
318
+
319
+ - single sequence: `<s> X </s>`
320
+ - pair of sequences: `<s> A </s></s> B </s>`
321
+
322
+ Args:
323
+ token_ids_0 (`List[int]`):
324
+ List of IDs to which the special tokens will be added.
325
+ token_ids_1 (`List[int]`, *optional*):
326
+ Optional second list of IDs for sequence pairs.
327
+
328
+ Returns:
329
+ `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
330
+ """
331
+ if token_ids_1 is None:
332
+ return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
333
+ cls = [self.cls_token_id]
334
+ sep = [self.sep_token_id]
335
+ return cls + token_ids_0 + sep + sep + token_ids_1 + sep
336
+
337
+ def get_special_tokens_mask(
338
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
339
+ ) -> List[int]:
340
+ """
341
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
342
+ special tokens using the tokenizer `prepare_for_model` method.
343
+
344
+ Args:
345
+ token_ids_0 (`List[int]`):
346
+ List of IDs.
347
+ token_ids_1 (`List[int]`, *optional*):
348
+ Optional second list of IDs for sequence pairs.
349
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
350
+ Whether or not the token list is already formatted with special tokens for the model.
351
+
352
+ Returns:
353
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
354
+ """
355
+ if already_has_special_tokens:
356
+ return super().get_special_tokens_mask(
357
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
358
+ )
359
+
360
+ if token_ids_1 is None:
361
+ return [1] + ([0] * len(token_ids_0)) + [1]
362
+ return [1] + ([0] * len(token_ids_0)) + [1, 1] + ([0] * len(token_ids_1)) + [1]
363
+
364
+ def create_token_type_ids_from_sequences(
365
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
366
+ ) -> List[int]:
367
+ """
368
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task. MVP does not
369
+ make use of token type ids, therefore a list of zeros is returned.
370
+
371
+ Args:
372
+ token_ids_0 (`List[int]`):
373
+ List of IDs.
374
+ token_ids_1 (`List[int]`, *optional*):
375
+ Optional second list of IDs for sequence pairs.
376
+
377
+ Returns:
378
+ `List[int]`: List of zeros.
379
+ """
380
+ sep = [self.sep_token_id]
381
+ cls = [self.cls_token_id]
382
+
383
+ if token_ids_1 is None:
384
+ return len(cls + token_ids_0 + sep) * [0]
385
+ return len(cls + token_ids_0 + sep + sep + token_ids_1 + sep) * [0]
386
+
387
+ def prepare_for_tokenization(self, text, is_split_into_words=False, **kwargs):
388
+ add_prefix_space = kwargs.pop("add_prefix_space", self.add_prefix_space)
389
+ if (is_split_into_words or add_prefix_space) and (len(text) > 0 and not text[0].isspace()):
390
+ text = " " + text
391
+ return (text, kwargs)
392
+
393
+
394
+ __all__ = ["MvpTokenizer"]
vllm/lib/python3.10/site-packages/transformers/models/mvp/tokenization_mvp_fast.py ADDED
@@ -0,0 +1,274 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 The Facebook AI Research Team Authors and The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import json
17
+ from typing import List, Optional, Tuple
18
+
19
+ from tokenizers import processors
20
+
21
+ from ...tokenization_utils_base import AddedToken, BatchEncoding
22
+ from ...tokenization_utils_fast import PreTrainedTokenizerFast
23
+ from ...utils import logging
24
+ from .tokenization_mvp import MvpTokenizer
25
+
26
+
27
+ logger = logging.get_logger(__name__)
28
+
29
+
30
+ VOCAB_FILES_NAMES = {"vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_file": "tokenizer.json"}
31
+
32
+ # See all MVP models at https://huggingface.co/models?filter=mvp
33
+
34
+
35
+ class MvpTokenizerFast(PreTrainedTokenizerFast):
36
+ r"""
37
+ Construct a "fast" MVP tokenizer (backed by HuggingFace's *tokenizers* library), derived from the GPT-2 tokenizer,
38
+ using byte-level Byte-Pair-Encoding.
39
+
40
+ This tokenizer has been trained to treat spaces like parts of the tokens (a bit like sentencepiece) so a word will
41
+ be encoded differently whether it is at the beginning of the sentence (without space) or not:
42
+
43
+ ```python
44
+ >>> from transformers import MvpTokenizerFast
45
+
46
+ >>> tokenizer = MvpTokenizerFast.from_pretrained("RUCAIBox/mvp")
47
+ >>> tokenizer("Hello world")["input_ids"]
48
+ [0, 31414, 232, 2]
49
+
50
+ >>> tokenizer(" Hello world")["input_ids"]
51
+ [0, 20920, 232, 2]
52
+ ```
53
+
54
+ You can get around that behavior by passing `add_prefix_space=True` when instantiating this tokenizer or when you
55
+ call it on some text, but since the model was not pretrained this way, it might yield a decrease in performance.
56
+
57
+ <Tip>
58
+
59
+ When used with `is_split_into_words=True`, this tokenizer needs to be instantiated with `add_prefix_space=True`.
60
+
61
+ </Tip>
62
+
63
+ This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should
64
+ refer to this superclass for more information regarding those methods.
65
+
66
+ Args:
67
+ vocab_file (`str`):
68
+ Path to the vocabulary file.
69
+ merges_file (`str`):
70
+ Path to the merges file.
71
+ errors (`str`, *optional*, defaults to `"replace"`):
72
+ Paradigm to follow when decoding bytes to UTF-8. See
73
+ [bytes.decode](https://docs.python.org/3/library/stdtypes.html#bytes.decode) for more information.
74
+ bos_token (`str`, *optional*, defaults to `"<s>"`):
75
+ The beginning of sequence token that was used during pretraining. Can be used a sequence classifier 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 sequence.
90
+ The token used is the `sep_token`.
91
+
92
+ </Tip>
93
+
94
+ sep_token (`str`, *optional*, defaults to `"</s>"`):
95
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
96
+ sequence classification or for a text and a question for question answering. It is also used as the last
97
+ token of a sequence built with special tokens.
98
+ cls_token (`str`, *optional*, defaults to `"<s>"`):
99
+ The classifier token which is used when doing sequence classification (classification of the whole sequence
100
+ instead of per-token classification). It is the first token of the sequence when built with special tokens.
101
+ unk_token (`str`, *optional*, defaults to `"<unk>"`):
102
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
103
+ token instead.
104
+ pad_token (`str`, *optional*, defaults to `"<pad>"`):
105
+ The token used for padding, for example when batching sequences of different lengths.
106
+ mask_token (`str`, *optional*, defaults to `"<mask>"`):
107
+ The token used for masking values. This is the token used when training this model with masked language
108
+ modeling. This is the token which the model will try to predict.
109
+ add_prefix_space (`bool`, *optional*, defaults to `False`):
110
+ Whether or not to add an initial space to the input. This allows to treat the leading word just as any
111
+ other word. (MVP tokenizer detect beginning of words by the preceding space).
112
+ trim_offsets (`bool`, *optional*, defaults to `True`):
113
+ Whether the post processing step should trim offsets to avoid including whitespaces.
114
+ """
115
+
116
+ vocab_files_names = VOCAB_FILES_NAMES
117
+ model_input_names = ["input_ids", "attention_mask"]
118
+ slow_tokenizer_class = MvpTokenizer
119
+
120
+ def __init__(
121
+ self,
122
+ vocab_file=None,
123
+ merges_file=None,
124
+ tokenizer_file=None,
125
+ errors="replace",
126
+ bos_token="<s>",
127
+ eos_token="</s>",
128
+ sep_token="</s>",
129
+ cls_token="<s>",
130
+ unk_token="<unk>",
131
+ pad_token="<pad>",
132
+ mask_token="<mask>",
133
+ add_prefix_space=False,
134
+ trim_offsets=True,
135
+ **kwargs,
136
+ ):
137
+ bos_token = AddedToken(bos_token, lstrip=False, rstrip=False) if isinstance(bos_token, str) else bos_token
138
+ eos_token = AddedToken(eos_token, lstrip=False, rstrip=False) if isinstance(eos_token, str) else eos_token
139
+ sep_token = AddedToken(sep_token, lstrip=False, rstrip=False) if isinstance(sep_token, str) else sep_token
140
+ cls_token = AddedToken(cls_token, lstrip=False, rstrip=False) if isinstance(cls_token, str) else cls_token
141
+ unk_token = AddedToken(unk_token, lstrip=False, rstrip=False) if isinstance(unk_token, str) else unk_token
142
+ pad_token = AddedToken(pad_token, lstrip=False, rstrip=False) if isinstance(pad_token, str) else pad_token
143
+
144
+ # Mask token behave like a normal word, i.e. include the space before it
145
+ mask_token = AddedToken(mask_token, lstrip=True, rstrip=False) if isinstance(mask_token, str) else mask_token
146
+ super().__init__(
147
+ vocab_file,
148
+ merges_file,
149
+ tokenizer_file=tokenizer_file,
150
+ errors=errors,
151
+ bos_token=bos_token,
152
+ eos_token=eos_token,
153
+ sep_token=sep_token,
154
+ cls_token=cls_token,
155
+ unk_token=unk_token,
156
+ pad_token=pad_token,
157
+ mask_token=mask_token,
158
+ add_prefix_space=add_prefix_space,
159
+ trim_offsets=trim_offsets,
160
+ **kwargs,
161
+ )
162
+
163
+ # the pre_tokenizer is already updated in the GPT2TokenizerFast `__init__`
164
+ tokenizer_component = "post_processor"
165
+ tokenizer_component_instance = getattr(self.backend_tokenizer, tokenizer_component, None)
166
+ if tokenizer_component_instance:
167
+ state = json.loads(tokenizer_component_instance.__getstate__())
168
+
169
+ # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class`
170
+ if "sep" in state:
171
+ state["sep"] = tuple(state["sep"])
172
+ if "cls" in state:
173
+ state["cls"] = tuple(state["cls"])
174
+
175
+ changes_to_apply = False
176
+
177
+ if state.get("add_prefix_space", add_prefix_space) != add_prefix_space:
178
+ state["add_prefix_space"] = add_prefix_space
179
+ changes_to_apply = True
180
+
181
+ if state.get("trim_offsets", trim_offsets) != trim_offsets:
182
+ state["trim_offsets"] = trim_offsets
183
+ changes_to_apply = True
184
+
185
+ if changes_to_apply:
186
+ component_class = getattr(processors, state.pop("type"))
187
+ new_value = component_class(**state)
188
+ setattr(self.backend_tokenizer, tokenizer_component, new_value)
189
+
190
+ @property
191
+ def mask_token(self) -> str:
192
+ """
193
+ `str`: Mask token, to use when training a model with masked-language modeling. Log an error if used while not
194
+ having been set.
195
+
196
+ MVP tokenizer has a special mask token to be usable in the fill-mask pipeline. The mask token will greedily
197
+ comprise the space before the *<mask>*.
198
+ """
199
+ if self._mask_token is None:
200
+ if self.verbose:
201
+ logger.error("Using mask_token, but it is not set yet.")
202
+ return None
203
+ return str(self._mask_token)
204
+
205
+ @mask_token.setter
206
+ def mask_token(self, value):
207
+ """
208
+ Overriding the default behavior of the mask token to have it eat the space before it.
209
+
210
+ This is needed to preserve backward compatibility with all the previously used models based on Mvp.
211
+ """
212
+ # Mask token behave like a normal word, i.e. include the space before it
213
+ # So we set lstrip to True
214
+ value = AddedToken(value, lstrip=True, rstrip=False) if isinstance(value, str) else value
215
+ self._mask_token = value
216
+
217
+ def _batch_encode_plus(self, *args, **kwargs) -> BatchEncoding:
218
+ is_split_into_words = kwargs.get("is_split_into_words", False)
219
+
220
+ if is_split_into_words and not self.add_prefix_space:
221
+ raise ValueError(
222
+ f"You need to instantiate {self.__class__.__name__} with add_prefix_space=True "
223
+ "to use it with pretokenized inputs."
224
+ )
225
+
226
+ return super()._batch_encode_plus(*args, **kwargs)
227
+
228
+ def _encode_plus(self, *args, **kwargs) -> BatchEncoding:
229
+ is_split_into_words = kwargs.get("is_split_into_words", False)
230
+
231
+ if is_split_into_words and not self.add_prefix_space:
232
+ raise ValueError(
233
+ f"You need to instantiate {self.__class__.__name__} with add_prefix_space=True "
234
+ "to use it with pretokenized inputs."
235
+ )
236
+
237
+ return super()._encode_plus(*args, **kwargs)
238
+
239
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
240
+ files = self._tokenizer.model.save(save_directory, name=filename_prefix)
241
+ return tuple(files)
242
+
243
+ def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
244
+ output = [self.bos_token_id] + token_ids_0 + [self.eos_token_id]
245
+ if token_ids_1 is None:
246
+ return output
247
+
248
+ return output + [self.eos_token_id] + token_ids_1 + [self.eos_token_id]
249
+
250
+ def create_token_type_ids_from_sequences(
251
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
252
+ ) -> List[int]:
253
+ """
254
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task. MVP does not
255
+ make use of token type ids, therefore a list of zeros is returned.
256
+
257
+ Args:
258
+ token_ids_0 (`List[int]`):
259
+ List of IDs.
260
+ token_ids_1 (`List[int]`, *optional*):
261
+ Optional second list of IDs for sequence pairs.
262
+
263
+ Returns:
264
+ `List[int]`: List of zeros.
265
+ """
266
+ sep = [self.sep_token_id]
267
+ cls = [self.cls_token_id]
268
+
269
+ if token_ids_1 is None:
270
+ return len(cls + token_ids_0 + sep) * [0]
271
+ return len(cls + token_ids_0 + sep + sep + token_ids_1 + sep) * [0]
272
+
273
+
274
+ __all__ = ["MvpTokenizerFast"]
vllm/lib/python3.10/site-packages/transformers/models/olmo/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (848 Bytes). View file
 
vllm/lib/python3.10/site-packages/transformers/models/olmo/__pycache__/modular_olmo.cpython-310.pyc ADDED
Binary file (4.96 kB). View file
 
vllm/lib/python3.10/site-packages/transformers/models/olmo2/__init__.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 EleutherAI 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
+ 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_olmo2 import *
22
+ from .modeling_olmo2 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__)
vllm/lib/python3.10/site-packages/transformers/models/olmo2/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (533 Bytes). View file
 
vllm/lib/python3.10/site-packages/transformers/models/olmo2/__pycache__/configuration_olmo2.cpython-310.pyc ADDED
Binary file (7.54 kB). View file
 
vllm/lib/python3.10/site-packages/transformers/models/olmo2/__pycache__/modeling_olmo2.cpython-310.pyc ADDED
Binary file (29.5 kB). View file
 
vllm/lib/python3.10/site-packages/transformers/models/olmo2/__pycache__/modular_olmo2.cpython-310.pyc ADDED
Binary file (11.4 kB). View file
 
vllm/lib/python3.10/site-packages/transformers/models/olmo2/configuration_olmo2.py ADDED
@@ -0,0 +1,181 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/olmo2/modular_olmo2.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_olmo2.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+
8
+
9
+ from ...configuration_utils import PretrainedConfig
10
+
11
+
12
+ class Olmo2Config(PretrainedConfig):
13
+ r"""
14
+ This is the configuration class to store the configuration of a [`Olmo2Model`]. It is used to instantiate an OLMo2
15
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
16
+ defaults will yield a similar configuration to that of the [allenai/Olmo2-7B-1124-hf](https://huggingface.co/allenai/Olmo2-7B-1124-hf).
17
+
18
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
19
+ documentation from [`PretrainedConfig`] for more information.
20
+
21
+
22
+ Args:
23
+ vocab_size (`int`, *optional*, defaults to 50304):
24
+ Vocabulary size of the Olmo2 model. Defines the number of different tokens that can be represented by the
25
+ `inputs_ids` passed when calling [`Olmo2Model`]
26
+ hidden_size (`int`, *optional*, defaults to 4096):
27
+ Dimension of the hidden representations.
28
+ intermediate_size (`int`, *optional*, defaults to 11008):
29
+ Dimension of the MLP representations.
30
+ num_hidden_layers (`int`, *optional*, defaults to 32):
31
+ Number of hidden layers in the Transformer decoder.
32
+ num_attention_heads (`int`, *optional*, defaults to 32):
33
+ Number of attention heads for each attention layer in the Transformer decoder.
34
+ num_key_value_heads (`int`, *optional*):
35
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
36
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
37
+ `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
38
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
39
+ by meanpooling all the original heads within that group. For more details checkout [this
40
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
41
+ `num_attention_heads`.
42
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
43
+ The non-linear activation function (function or string) in the decoder.
44
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
45
+ The maximum sequence length that this model might ever be used with.
46
+ initializer_range (`float`, *optional*, defaults to 0.02):
47
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
48
+ use_cache (`bool`, *optional*, defaults to `True`):
49
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
50
+ relevant if `config.is_decoder=True`.
51
+ pad_token_id (`int`, *optional*, defaults to 1):
52
+ Padding token id.
53
+ bos_token_id (`int`, *optional*):
54
+ Beginning of stream token id.
55
+ eos_token_id (`int`, *optional*, defaults to 50279):
56
+ End of stream token id.
57
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
58
+ Whether to tie weight embeddings
59
+ rope_theta (`float`, *optional*, defaults to 10000.0):
60
+ The base period of the RoPE embeddings.
61
+ rope_scaling (`Dict`, *optional*):
62
+ Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
63
+ strategies: linear and dynamic. Their scaling factor must be a float greater than 1. The expected format is
64
+ `{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
65
+ `max_position_embeddings` to the expected new maximum. See the following thread for more information on how
66
+ these scaling strategies behave:
67
+ https://www.reddit.com/r/LocalLLaMA/comments/14mrgpr/dynamically_scaled_rope_further_increases/. This is an
68
+ experimental feature, subject to breaking API changes in future versions.
69
+ attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
70
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
71
+ attention_dropout (`float`, *optional*, defaults to 0.0):
72
+ The dropout ratio for the attention probabilities.
73
+ rms_norm_eps (`float`, *optional*, defaults to 1e-05):
74
+ The epsilon used by the rms normalization layers.
75
+
76
+ ```python
77
+ >>> from transformers import Olmo2Model, Olmo2Config
78
+
79
+ >>> # Initializing a Olmo2 7B style configuration
80
+ >>> configuration = Olmo2Config()
81
+
82
+ >>> # Initializing a model from the Olmo2 7B style configuration
83
+ >>> model = Olmo2Model(configuration)
84
+
85
+ >>> # Accessing the model configuration
86
+ >>> configuration = model.config
87
+ ```
88
+ """
89
+
90
+ model_type = "olmo2"
91
+ keys_to_ignore_at_inference = ["past_key_values"]
92
+ base_model_tp_plan = {
93
+ "layers.*.self_attn.q_proj": "colwise_rep", # we need to replicate here due to the added norm on q and k
94
+ "layers.*.self_attn.k_proj": "colwise_rep", # we need to replicate here due to the added norm on q and k
95
+ "layers.*.self_attn.v_proj": "colwise_rep", # we need to replicate here due to the added norm on q and k
96
+ "layers.*.self_attn.o_proj": "rowwise_rep", # we need to replicate here due to the added norm on q and k
97
+ "layers.*.mlp.gate_proj": "colwise",
98
+ "layers.*.mlp.up_proj": "colwise",
99
+ "layers.*.mlp.down_proj": "rowwise",
100
+ }
101
+ base_model_pp_plan = {
102
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
103
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
104
+ "norm": (["hidden_states"], ["hidden_states"]),
105
+ }
106
+
107
+ def __init__(
108
+ self,
109
+ vocab_size=50304,
110
+ hidden_size=4096,
111
+ intermediate_size=11008,
112
+ num_hidden_layers=32,
113
+ num_attention_heads=32,
114
+ num_key_value_heads=None,
115
+ hidden_act="silu",
116
+ max_position_embeddings=2048,
117
+ initializer_range=0.02,
118
+ use_cache=True,
119
+ pad_token_id=1,
120
+ bos_token_id=None,
121
+ eos_token_id=50279,
122
+ tie_word_embeddings=False,
123
+ rope_theta=10000.0,
124
+ rope_scaling=None,
125
+ attention_bias=False,
126
+ attention_dropout=0.0,
127
+ rms_norm_eps=1e-5,
128
+ **kwargs,
129
+ ):
130
+ super().__init__(
131
+ pad_token_id=pad_token_id,
132
+ bos_token_id=bos_token_id,
133
+ eos_token_id=eos_token_id,
134
+ tie_word_embeddings=tie_word_embeddings,
135
+ **kwargs,
136
+ )
137
+ self.vocab_size = vocab_size
138
+ self.max_position_embeddings = max_position_embeddings
139
+ self.hidden_size = hidden_size
140
+ self.intermediate_size = intermediate_size
141
+ self.num_hidden_layers = num_hidden_layers
142
+ self.num_attention_heads = num_attention_heads
143
+
144
+ # for backward compatibility
145
+ if num_key_value_heads is None:
146
+ num_key_value_heads = num_attention_heads
147
+
148
+ self.num_key_value_heads = num_key_value_heads
149
+ self.hidden_act = hidden_act
150
+ self.initializer_range = initializer_range
151
+ self.use_cache = use_cache
152
+ self.rope_theta = rope_theta
153
+ self.rope_scaling = rope_scaling
154
+ self._rope_scaling_validation()
155
+ self.attention_bias = attention_bias
156
+ self.attention_dropout = attention_dropout
157
+
158
+ self.rms_norm_eps = rms_norm_eps
159
+
160
+ def _rope_scaling_validation(self):
161
+ """
162
+ Validate the `rope_scaling` configuration.
163
+ """
164
+ if self.rope_scaling is None:
165
+ return
166
+
167
+ if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
168
+ raise ValueError(
169
+ f"`rope_scaling` must be a dictionary with two fields, `type` and `factor`, got {self.rope_scaling}"
170
+ )
171
+ rope_scaling_type = self.rope_scaling.get("type", None)
172
+ rope_scaling_factor = self.rope_scaling.get("factor", None)
173
+ if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
174
+ raise ValueError(
175
+ f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
176
+ )
177
+ if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float) or rope_scaling_factor <= 1.0:
178
+ raise ValueError(f"`rope_scaling`'s factor field must be a float > 1, got {rope_scaling_factor}")
179
+
180
+
181
+ __all__ = ["Olmo2Config"]
vllm/lib/python3.10/site-packages/transformers/models/olmo2/modeling_olmo2.py ADDED
@@ -0,0 +1,866 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/olmo2/modular_olmo2.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_olmo2.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ from typing import Callable, List, Optional, Tuple, Union
8
+
9
+ import torch
10
+ import torch.nn as nn
11
+
12
+ from ...activations import ACT2FN
13
+ from ...cache_utils import Cache, DynamicCache, StaticCache
14
+ from ...generation import GenerationMixin
15
+ from ...modeling_attn_mask_utils import AttentionMaskConverter
16
+ from ...modeling_flash_attention_utils import FlashAttentionKwargs
17
+ from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
18
+ from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS
19
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
20
+ from ...processing_utils import Unpack
21
+ from ...utils import (
22
+ LossKwargs,
23
+ add_start_docstrings,
24
+ add_start_docstrings_to_model_forward,
25
+ is_torch_flex_attn_available,
26
+ logging,
27
+ replace_return_docstrings,
28
+ )
29
+ from ...utils.deprecation import deprecate_kwarg
30
+ from .configuration_olmo2 import Olmo2Config
31
+
32
+
33
+ if is_torch_flex_attn_available():
34
+ from torch.nn.attention.flex_attention import BlockMask
35
+
36
+ from ...integrations.flex_attention import make_flex_block_causal_mask
37
+
38
+
39
+ logger = logging.get_logger(__name__)
40
+ _CONFIG_FOR_DOC = "Olmo2Config"
41
+
42
+
43
+ class Olmo2RMSNorm(nn.Module):
44
+ def __init__(self, hidden_size, eps=1e-6):
45
+ """
46
+ Olmo2RMSNorm is equivalent to T5LayerNorm
47
+ """
48
+ super().__init__()
49
+ self.weight = nn.Parameter(torch.ones(hidden_size))
50
+ self.variance_epsilon = eps
51
+
52
+ def forward(self, hidden_states):
53
+ input_dtype = hidden_states.dtype
54
+ hidden_states = hidden_states.to(torch.float32)
55
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
56
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
57
+ return self.weight * hidden_states.to(input_dtype)
58
+
59
+ def extra_repr(self):
60
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
61
+
62
+
63
+ def rotate_half(x):
64
+ """Rotates half the hidden dims of the input."""
65
+ x1 = x[..., : x.shape[-1] // 2]
66
+ x2 = x[..., x.shape[-1] // 2 :]
67
+ return torch.cat((-x2, x1), dim=-1)
68
+
69
+
70
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
71
+ """Applies Rotary Position Embedding to the query and key tensors.
72
+
73
+ Args:
74
+ q (`torch.Tensor`): The query tensor.
75
+ k (`torch.Tensor`): The key tensor.
76
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
77
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
78
+ position_ids (`torch.Tensor`, *optional*):
79
+ Deprecated and unused.
80
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
81
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
82
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
83
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
84
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
85
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
86
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
87
+ Returns:
88
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
89
+ """
90
+ cos = cos.unsqueeze(unsqueeze_dim)
91
+ sin = sin.unsqueeze(unsqueeze_dim)
92
+ q_embed = (q * cos) + (rotate_half(q) * sin)
93
+ k_embed = (k * cos) + (rotate_half(k) * sin)
94
+ return q_embed, k_embed
95
+
96
+
97
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
98
+ """
99
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
100
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
101
+ """
102
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
103
+ if n_rep == 1:
104
+ return hidden_states
105
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
106
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
107
+
108
+
109
+ def eager_attention_forward(
110
+ module: nn.Module,
111
+ query: torch.Tensor,
112
+ key: torch.Tensor,
113
+ value: torch.Tensor,
114
+ attention_mask: Optional[torch.Tensor],
115
+ scaling: float,
116
+ dropout: float = 0.0,
117
+ **kwargs,
118
+ ):
119
+ key_states = repeat_kv(key, module.num_key_value_groups)
120
+ value_states = repeat_kv(value, module.num_key_value_groups)
121
+
122
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
123
+ if attention_mask is not None:
124
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
125
+ attn_weights = attn_weights + causal_mask
126
+
127
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
128
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
129
+ attn_output = torch.matmul(attn_weights, value_states)
130
+ attn_output = attn_output.transpose(1, 2).contiguous()
131
+
132
+ return attn_output, attn_weights
133
+
134
+
135
+ class Olmo2Attention(nn.Module):
136
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
137
+
138
+ def __init__(self, config: Olmo2Config, layer_idx: Optional[int] = None):
139
+ super().__init__()
140
+ self.config = config
141
+ self.layer_idx = layer_idx
142
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
143
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
144
+ self.scaling = self.head_dim**-0.5
145
+ self.attention_dropout = config.attention_dropout
146
+ self.is_causal = True
147
+
148
+ self.q_proj = nn.Linear(
149
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
150
+ )
151
+ self.k_proj = nn.Linear(
152
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
153
+ )
154
+ self.v_proj = nn.Linear(
155
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
156
+ )
157
+ self.o_proj = nn.Linear(
158
+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
159
+ )
160
+ self.q_norm = Olmo2RMSNorm(config.num_attention_heads * self.head_dim, config.rms_norm_eps)
161
+ self.k_norm = Olmo2RMSNorm(config.num_key_value_heads * self.head_dim, config.rms_norm_eps)
162
+
163
+ def forward(
164
+ self,
165
+ hidden_states: torch.Tensor,
166
+ position_embeddings: Tuple[torch.Tensor, torch.Tensor],
167
+ attention_mask: Optional[torch.Tensor],
168
+ past_key_value: Optional[Cache] = None,
169
+ cache_position: Optional[torch.LongTensor] = None,
170
+ **kwargs,
171
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
172
+ input_shape = hidden_states.shape[:-1]
173
+ hidden_shape = (*input_shape, -1, self.head_dim)
174
+
175
+ query_states = self.q_norm(self.q_proj(hidden_states))
176
+ key_states = self.k_norm(self.k_proj(hidden_states))
177
+ value_states = self.v_proj(hidden_states)
178
+
179
+ query_states = query_states.view(hidden_shape).transpose(1, 2)
180
+ key_states = key_states.view(hidden_shape).transpose(1, 2)
181
+ value_states = value_states.view(hidden_shape).transpose(1, 2)
182
+
183
+ cos, sin = position_embeddings
184
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
185
+
186
+ if past_key_value is not None:
187
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
188
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
189
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
190
+
191
+ attention_interface: Callable = eager_attention_forward
192
+ if self.config._attn_implementation != "eager":
193
+ if self.config._attn_implementation == "sdpa" and kwargs.get("output_attentions", False):
194
+ logger.warning_once(
195
+ "`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to "
196
+ 'eager attention. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
197
+ )
198
+ else:
199
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
200
+
201
+ attn_output, attn_weights = attention_interface(
202
+ self,
203
+ query_states,
204
+ key_states,
205
+ value_states,
206
+ attention_mask,
207
+ dropout=0.0 if not self.training else self.attention_dropout,
208
+ scaling=self.scaling,
209
+ **kwargs,
210
+ )
211
+
212
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
213
+ attn_output = self.o_proj(attn_output)
214
+ return attn_output, attn_weights
215
+
216
+
217
+ class Olmo2MLP(nn.Module):
218
+ def __init__(self, config):
219
+ super().__init__()
220
+ self.config = config
221
+ self.hidden_size = config.hidden_size
222
+ self.intermediate_size = config.intermediate_size
223
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
224
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
225
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
226
+ self.act_fn = ACT2FN[config.hidden_act]
227
+
228
+ def forward(self, x):
229
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
230
+ return down_proj
231
+
232
+
233
+ class Olmo2DecoderLayer(nn.Module):
234
+ def __init__(self, config: Olmo2Config, layer_idx: int):
235
+ super().__init__()
236
+ self.hidden_size = config.hidden_size
237
+ self.self_attn = Olmo2Attention(config=config, layer_idx=layer_idx)
238
+
239
+ self.mlp = Olmo2MLP(config)
240
+ self.post_attention_layernorm = Olmo2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
241
+ self.post_feedforward_layernorm = Olmo2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
242
+
243
+ def forward(
244
+ self,
245
+ hidden_states: torch.Tensor,
246
+ attention_mask: Optional[torch.Tensor] = None,
247
+ position_ids: Optional[torch.LongTensor] = None,
248
+ past_key_value: Optional[Cache] = None,
249
+ output_attentions: Optional[bool] = False,
250
+ use_cache: Optional[bool] = False,
251
+ cache_position: Optional[torch.LongTensor] = None,
252
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
253
+ **kwargs,
254
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
255
+ residual = hidden_states
256
+
257
+ # Self Attention
258
+ hidden_states, self_attn_weights = self.self_attn(
259
+ hidden_states=hidden_states,
260
+ attention_mask=attention_mask,
261
+ position_ids=position_ids,
262
+ past_key_value=past_key_value,
263
+ output_attentions=output_attentions,
264
+ use_cache=use_cache,
265
+ cache_position=cache_position,
266
+ position_embeddings=position_embeddings,
267
+ **kwargs,
268
+ )
269
+ hidden_states = self.post_attention_layernorm(hidden_states)
270
+ hidden_states = residual + hidden_states
271
+
272
+ # Fully Connected
273
+ residual = hidden_states
274
+ hidden_states = self.mlp(hidden_states)
275
+ hidden_states = self.post_feedforward_layernorm(hidden_states)
276
+ hidden_states = residual + hidden_states
277
+
278
+ outputs = (hidden_states,)
279
+ if output_attentions:
280
+ outputs += (self_attn_weights,)
281
+
282
+ return outputs
283
+
284
+
285
+ class Olmo2RotaryEmbedding(nn.Module):
286
+ def __init__(self, config: Olmo2Config, device=None):
287
+ super().__init__()
288
+ # BC: "rope_type" was originally "type"
289
+ if hasattr(config, "rope_scaling") and config.rope_scaling is not None:
290
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
291
+ else:
292
+ self.rope_type = "default"
293
+ self.max_seq_len_cached = config.max_position_embeddings
294
+ self.original_max_seq_len = config.max_position_embeddings
295
+
296
+ self.config = config
297
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
298
+
299
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
300
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
301
+ self.original_inv_freq = self.inv_freq
302
+
303
+ def _dynamic_frequency_update(self, position_ids, device):
304
+ """
305
+ dynamic RoPE layers should recompute `inv_freq` in the following situations:
306
+ 1 - growing beyond the cached sequence length (allow scaling)
307
+ 2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
308
+ """
309
+ seq_len = torch.max(position_ids) + 1
310
+ if seq_len > self.max_seq_len_cached: # growth
311
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device, seq_len=seq_len)
312
+ self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: may break with compilation
313
+ self.max_seq_len_cached = seq_len
314
+
315
+ if seq_len < self.original_max_seq_len and self.max_seq_len_cached > self.original_max_seq_len: # reset
316
+ # This .to() is needed if the model has been moved to a device after being initialized (because
317
+ # the buffer is automatically moved, but not the original copy)
318
+ self.original_inv_freq = self.original_inv_freq.to(device)
319
+ self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)
320
+ self.max_seq_len_cached = self.original_max_seq_len
321
+
322
+ @torch.no_grad()
323
+ def forward(self, x, position_ids):
324
+ if "dynamic" in self.rope_type:
325
+ self._dynamic_frequency_update(position_ids, device=x.device)
326
+
327
+ # Core RoPE block
328
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
329
+ position_ids_expanded = position_ids[:, None, :].float()
330
+ # Force float32 (see https://github.com/huggingface/transformers/pull/29285)
331
+ device_type = x.device.type
332
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
333
+ with torch.autocast(device_type=device_type, enabled=False):
334
+ freqs = (inv_freq_expanded.float().to(x.device) @ position_ids_expanded.float()).transpose(1, 2)
335
+ emb = torch.cat((freqs, freqs), dim=-1)
336
+ cos = emb.cos()
337
+ sin = emb.sin()
338
+
339
+ # Advanced RoPE types (e.g. yarn) apply a post-processing scaling factor, equivalent to scaling attention
340
+ cos = cos * self.attention_scaling
341
+ sin = sin * self.attention_scaling
342
+
343
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
344
+
345
+
346
+ OLMO2_START_DOCSTRING = r"""
347
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
348
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
349
+ etc.)
350
+
351
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
352
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
353
+ and behavior.
354
+
355
+ Parameters:
356
+ config ([`Olmo2Config`]):
357
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
358
+ load the weights associated with the model, only the configuration. Check out the
359
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
360
+ """
361
+
362
+
363
+ @add_start_docstrings(
364
+ "The bare Olmo2 Model outputting raw hidden-states without any specific head on top.",
365
+ OLMO2_START_DOCSTRING,
366
+ )
367
+ class Olmo2PreTrainedModel(PreTrainedModel):
368
+ config_class = Olmo2Config
369
+ base_model_prefix = "model"
370
+ supports_gradient_checkpointing = True
371
+ _no_split_modules = ["Olmo2DecoderLayer"]
372
+ _skip_keys_device_placement = ["past_key_values"]
373
+ _supports_flash_attn_2 = True
374
+ _supports_sdpa = True
375
+ _supports_flex_attn = True
376
+ _supports_cache_class = True
377
+ _supports_quantized_cache = True
378
+ _supports_static_cache = True
379
+ _supports_attention_backend = True
380
+
381
+ def _init_weights(self, module):
382
+ std = self.config.initializer_range
383
+ if isinstance(module, nn.Linear):
384
+ module.weight.data.normal_(mean=0.0, std=std)
385
+ if module.bias is not None:
386
+ module.bias.data.zero_()
387
+ elif isinstance(module, nn.Embedding):
388
+ module.weight.data.normal_(mean=0.0, std=std)
389
+ if module.padding_idx is not None:
390
+ module.weight.data[module.padding_idx].zero_()
391
+
392
+
393
+ OLMO2_INPUTS_DOCSTRING = r"""
394
+ Args:
395
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
396
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
397
+ it.
398
+
399
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
400
+ [`PreTrainedTokenizer.__call__`] for details.
401
+
402
+ [What are input IDs?](../glossary#input-ids)
403
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
404
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
405
+
406
+ - 1 for tokens that are **not masked**,
407
+ - 0 for tokens that are **masked**.
408
+
409
+ [What are attention masks?](../glossary#attention-mask)
410
+
411
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
412
+ [`PreTrainedTokenizer.__call__`] for details.
413
+
414
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
415
+ `past_key_values`).
416
+
417
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
418
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
419
+ information on the default strategy.
420
+
421
+ - 1 indicates the head is **not masked**,
422
+ - 0 indicates the head is **masked**.
423
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
424
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
425
+ config.n_positions - 1]`.
426
+
427
+ [What are position IDs?](../glossary#position-ids)
428
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
429
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
430
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
431
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
432
+
433
+ Two formats are allowed:
434
+ - a [`~cache_utils.Cache`] instance, see our
435
+ [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache);
436
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
437
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
438
+ cache format.
439
+
440
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
441
+ legacy cache format will be returned.
442
+
443
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
444
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
445
+ of shape `(batch_size, sequence_length)`.
446
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
447
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
448
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
449
+ model's internal embedding lookup matrix.
450
+ use_cache (`bool`, *optional*):
451
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
452
+ `past_key_values`).
453
+ output_attentions (`bool`, *optional*):
454
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
455
+ tensors for more detail.
456
+ output_hidden_states (`bool`, *optional*):
457
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
458
+ more detail.
459
+ return_dict (`bool`, *optional*):
460
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
461
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
462
+ Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
463
+ this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
464
+ the complete sequence length.
465
+ """
466
+
467
+
468
+ @add_start_docstrings(
469
+ "The bare Olmo2 Model outputting raw hidden-states without any specific head on top.",
470
+ OLMO2_START_DOCSTRING,
471
+ )
472
+ class Olmo2Model(Olmo2PreTrainedModel):
473
+ """
474
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`Olmo2DecoderLayer`]
475
+
476
+ Args:
477
+ config: Olmo2Config
478
+ """
479
+
480
+ def __init__(self, config: Olmo2Config):
481
+ super().__init__(config)
482
+ self.padding_idx = config.pad_token_id
483
+ self.vocab_size = config.vocab_size
484
+
485
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
486
+ self.layers = nn.ModuleList(
487
+ [Olmo2DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
488
+ )
489
+ self.norm = Olmo2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
490
+ self.rotary_emb = Olmo2RotaryEmbedding(config=config)
491
+ self.gradient_checkpointing = False
492
+
493
+ # Initialize weights and apply final processing
494
+ self.post_init()
495
+
496
+ def get_input_embeddings(self):
497
+ return self.embed_tokens
498
+
499
+ def set_input_embeddings(self, value):
500
+ self.embed_tokens = value
501
+
502
+ @add_start_docstrings_to_model_forward(OLMO2_INPUTS_DOCSTRING)
503
+ def forward(
504
+ self,
505
+ input_ids: torch.LongTensor = None,
506
+ attention_mask: Optional[torch.Tensor] = None,
507
+ position_ids: Optional[torch.LongTensor] = None,
508
+ past_key_values: Optional[Cache] = None,
509
+ inputs_embeds: Optional[torch.FloatTensor] = None,
510
+ use_cache: Optional[bool] = None,
511
+ output_attentions: Optional[bool] = None,
512
+ output_hidden_states: Optional[bool] = None,
513
+ return_dict: Optional[bool] = None,
514
+ cache_position: Optional[torch.LongTensor] = None,
515
+ **flash_attn_kwargs: Unpack[FlashAttentionKwargs],
516
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
517
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
518
+ output_hidden_states = (
519
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
520
+ )
521
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
522
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
523
+
524
+ if (input_ids is None) ^ (inputs_embeds is not None):
525
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
526
+
527
+ if self.gradient_checkpointing and self.training and use_cache:
528
+ logger.warning_once(
529
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
530
+ )
531
+ use_cache = False
532
+
533
+ if inputs_embeds is None:
534
+ inputs_embeds = self.embed_tokens(input_ids)
535
+
536
+ if use_cache and past_key_values is None:
537
+ past_key_values = DynamicCache()
538
+
539
+ if cache_position is None:
540
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
541
+ cache_position = torch.arange(
542
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
543
+ )
544
+
545
+ if position_ids is None:
546
+ position_ids = cache_position.unsqueeze(0)
547
+
548
+ causal_mask = self._update_causal_mask(
549
+ attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
550
+ )
551
+
552
+ hidden_states = inputs_embeds
553
+
554
+ # create position embeddings to be shared across the decoder layers
555
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
556
+
557
+ # decoder layers
558
+ all_hidden_states = () if output_hidden_states else None
559
+ all_self_attns = () if output_attentions else None
560
+
561
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
562
+ if output_hidden_states:
563
+ all_hidden_states += (hidden_states,)
564
+
565
+ if self.gradient_checkpointing and self.training:
566
+ layer_outputs = self._gradient_checkpointing_func(
567
+ decoder_layer.__call__,
568
+ hidden_states,
569
+ causal_mask,
570
+ position_ids,
571
+ past_key_values,
572
+ output_attentions,
573
+ use_cache,
574
+ cache_position,
575
+ position_embeddings,
576
+ )
577
+ else:
578
+ layer_outputs = decoder_layer(
579
+ hidden_states,
580
+ attention_mask=causal_mask,
581
+ position_ids=position_ids,
582
+ past_key_value=past_key_values,
583
+ output_attentions=output_attentions,
584
+ use_cache=use_cache,
585
+ cache_position=cache_position,
586
+ position_embeddings=position_embeddings,
587
+ **flash_attn_kwargs,
588
+ )
589
+
590
+ hidden_states = layer_outputs[0]
591
+
592
+ if output_attentions:
593
+ all_self_attns += (layer_outputs[1],)
594
+
595
+ hidden_states = self.norm(hidden_states)
596
+
597
+ # add hidden states from the last decoder layer
598
+ if output_hidden_states:
599
+ all_hidden_states += (hidden_states,)
600
+
601
+ output = BaseModelOutputWithPast(
602
+ last_hidden_state=hidden_states,
603
+ past_key_values=past_key_values if use_cache else None,
604
+ hidden_states=all_hidden_states,
605
+ attentions=all_self_attns,
606
+ )
607
+ return output if return_dict else output.to_tuple()
608
+
609
+ def _update_causal_mask(
610
+ self,
611
+ attention_mask: torch.Tensor,
612
+ input_tensor: torch.Tensor,
613
+ cache_position: torch.Tensor,
614
+ past_key_values: Cache,
615
+ output_attentions: bool = False,
616
+ ):
617
+ if self.config._attn_implementation == "flash_attention_2":
618
+ if attention_mask is not None and (attention_mask == 0.0).any():
619
+ return attention_mask
620
+ return None
621
+ if self.config._attn_implementation == "flex_attention":
622
+ if isinstance(attention_mask, torch.Tensor):
623
+ attention_mask = make_flex_block_causal_mask(attention_mask)
624
+ if isinstance(attention_mask, BlockMask):
625
+ return attention_mask
626
+
627
+ # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
628
+ # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
629
+ # to infer the attention mask.
630
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
631
+ using_static_cache = isinstance(past_key_values, StaticCache)
632
+
633
+ # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
634
+ if self.config._attn_implementation == "sdpa" and not using_static_cache and not output_attentions:
635
+ if AttentionMaskConverter._ignore_causal_mask_sdpa(
636
+ attention_mask,
637
+ inputs_embeds=input_tensor,
638
+ past_key_values_length=past_seen_tokens,
639
+ is_training=self.training,
640
+ ):
641
+ return None
642
+
643
+ dtype, device = input_tensor.dtype, input_tensor.device
644
+ sequence_length = input_tensor.shape[1]
645
+ if using_static_cache:
646
+ target_length = past_key_values.get_max_cache_shape()
647
+ else:
648
+ target_length = (
649
+ attention_mask.shape[-1]
650
+ if isinstance(attention_mask, torch.Tensor)
651
+ else past_seen_tokens + sequence_length + 1
652
+ )
653
+
654
+ # In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
655
+ causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
656
+ attention_mask,
657
+ sequence_length=sequence_length,
658
+ target_length=target_length,
659
+ dtype=dtype,
660
+ device=device,
661
+ cache_position=cache_position,
662
+ batch_size=input_tensor.shape[0],
663
+ )
664
+
665
+ if (
666
+ self.config._attn_implementation == "sdpa"
667
+ and attention_mask is not None
668
+ and attention_mask.device.type in ["cuda", "xpu"]
669
+ and not output_attentions
670
+ ):
671
+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
672
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
673
+ # Details: https://github.com/pytorch/pytorch/issues/110213
674
+ min_dtype = torch.finfo(dtype).min
675
+ causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
676
+
677
+ return causal_mask
678
+
679
+ @staticmethod
680
+ def _prepare_4d_causal_attention_mask_with_cache_position(
681
+ attention_mask: torch.Tensor,
682
+ sequence_length: int,
683
+ target_length: int,
684
+ dtype: torch.dtype,
685
+ device: torch.device,
686
+ cache_position: torch.Tensor,
687
+ batch_size: int,
688
+ **kwargs,
689
+ ):
690
+ """
691
+ Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
692
+ `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
693
+
694
+ Args:
695
+ attention_mask (`torch.Tensor`):
696
+ A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
697
+ `(batch_size, 1, query_length, key_value_length)`.
698
+ sequence_length (`int`):
699
+ The sequence length being processed.
700
+ target_length (`int`):
701
+ The target length: when generating with static cache, the mask should be as long as the static cache,
702
+ to account for the 0 padding, the part of the cache that is not filled yet.
703
+ dtype (`torch.dtype`):
704
+ The dtype to use for the 4D attention mask.
705
+ device (`torch.device`):
706
+ The device to place the 4D attention mask on.
707
+ cache_position (`torch.Tensor`):
708
+ Indices depicting the position of the input sequence tokens in the sequence.
709
+ batch_size (`torch.Tensor`):
710
+ Batch size.
711
+ """
712
+ if attention_mask is not None and attention_mask.dim() == 4:
713
+ # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
714
+ causal_mask = attention_mask
715
+ else:
716
+ min_dtype = torch.finfo(dtype).min
717
+ causal_mask = torch.full(
718
+ (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device
719
+ )
720
+ if sequence_length != 1:
721
+ causal_mask = torch.triu(causal_mask, diagonal=1)
722
+ causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
723
+ causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
724
+ if attention_mask is not None:
725
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
726
+ mask_length = attention_mask.shape[-1]
727
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :].to(
728
+ causal_mask.device
729
+ )
730
+ padding_mask = padding_mask == 0
731
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
732
+ padding_mask, min_dtype
733
+ )
734
+
735
+ return causal_mask
736
+
737
+
738
+ class KwargsForCausalLM(FlashAttentionKwargs, LossKwargs): ...
739
+
740
+
741
+ class Olmo2ForCausalLM(Olmo2PreTrainedModel, GenerationMixin):
742
+ _tied_weights_keys = ["lm_head.weight"]
743
+ _tp_plan = {"lm_head": "colwise_rep"}
744
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
745
+
746
+ def __init__(self, config):
747
+ super().__init__(config)
748
+ self.model = Olmo2Model(config)
749
+ self.vocab_size = config.vocab_size
750
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
751
+
752
+ # Initialize weights and apply final processing
753
+ self.post_init()
754
+
755
+ def get_input_embeddings(self):
756
+ return self.model.embed_tokens
757
+
758
+ def set_input_embeddings(self, value):
759
+ self.model.embed_tokens = value
760
+
761
+ def get_output_embeddings(self):
762
+ return self.lm_head
763
+
764
+ def set_output_embeddings(self, new_embeddings):
765
+ self.lm_head = new_embeddings
766
+
767
+ def set_decoder(self, decoder):
768
+ self.model = decoder
769
+
770
+ def get_decoder(self):
771
+ return self.model
772
+
773
+ @deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep")
774
+ @add_start_docstrings_to_model_forward(OLMO2_INPUTS_DOCSTRING)
775
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
776
+ def forward(
777
+ self,
778
+ input_ids: torch.LongTensor = None,
779
+ attention_mask: Optional[torch.Tensor] = None,
780
+ position_ids: Optional[torch.LongTensor] = None,
781
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
782
+ inputs_embeds: Optional[torch.FloatTensor] = None,
783
+ labels: Optional[torch.LongTensor] = None,
784
+ use_cache: Optional[bool] = None,
785
+ output_attentions: Optional[bool] = None,
786
+ output_hidden_states: Optional[bool] = None,
787
+ return_dict: Optional[bool] = None,
788
+ cache_position: Optional[torch.LongTensor] = None,
789
+ logits_to_keep: Union[int, torch.Tensor] = 0,
790
+ **kwargs: Unpack[KwargsForCausalLM],
791
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
792
+ r"""
793
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
794
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
795
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
796
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
797
+
798
+ logits_to_keep (`int` or `torch.Tensor`, *optional*):
799
+ If an `int`, compute logits for the last `logits_to_keep` tokens. If `0`, calculate logits for all
800
+ `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
801
+ token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
802
+ If a `torch.Tensor`, must be 1D corresponding to the indices to keep in the sequence length dimension.
803
+ This is useful when using packed tensor format (single dimension for batch and sequence length).
804
+
805
+ Returns:
806
+
807
+ Example:
808
+
809
+ ```python
810
+ >>> from transformers import AutoTokenizer, Olmo2ForCausalLM
811
+
812
+ >>> model = Olmo2ForCausalLM.from_pretrained("meta-olmo2/Olmo2-2-7b-hf")
813
+ >>> tokenizer = AutoTokenizer.from_pretrained("meta-olmo2/Olmo2-2-7b-hf")
814
+
815
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
816
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
817
+
818
+ >>> # Generate
819
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
820
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
821
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
822
+ ```"""
823
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
824
+ output_hidden_states = (
825
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
826
+ )
827
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
828
+
829
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
830
+ outputs = self.model(
831
+ input_ids=input_ids,
832
+ attention_mask=attention_mask,
833
+ position_ids=position_ids,
834
+ past_key_values=past_key_values,
835
+ inputs_embeds=inputs_embeds,
836
+ use_cache=use_cache,
837
+ output_attentions=output_attentions,
838
+ output_hidden_states=output_hidden_states,
839
+ return_dict=return_dict,
840
+ cache_position=cache_position,
841
+ **kwargs,
842
+ )
843
+
844
+ hidden_states = outputs[0]
845
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
846
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
847
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
848
+
849
+ loss = None
850
+ if labels is not None:
851
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
852
+
853
+ if not return_dict:
854
+ output = (logits,) + outputs[1:]
855
+ return (loss,) + output if loss is not None else output
856
+
857
+ return CausalLMOutputWithPast(
858
+ loss=loss,
859
+ logits=logits,
860
+ past_key_values=outputs.past_key_values,
861
+ hidden_states=outputs.hidden_states,
862
+ attentions=outputs.attentions,
863
+ )
864
+
865
+
866
+ __all__ = ["Olmo2ForCausalLM", "Olmo2Model", "Olmo2PreTrainedModel"]
vllm/lib/python3.10/site-packages/transformers/models/olmo2/modular_olmo2.py ADDED
@@ -0,0 +1,311 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Callable, Optional, Tuple
2
+
3
+ import torch
4
+ from torch import nn
5
+
6
+ from ...cache_utils import Cache
7
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS
8
+ from ...pytorch_utils import ALL_LAYERNORM_LAYERS
9
+ from ...utils import logging
10
+ from ..llama.modeling_llama import LlamaRMSNorm, eager_attention_forward
11
+ from ..olmo.configuration_olmo import OlmoConfig
12
+ from ..olmo.modeling_olmo import (
13
+ OlmoAttention,
14
+ OlmoDecoderLayer,
15
+ OlmoForCausalLM,
16
+ OlmoModel,
17
+ apply_rotary_pos_emb,
18
+ )
19
+
20
+
21
+ logger = logging.get_logger(__name__)
22
+
23
+
24
+ class Olmo2Config(OlmoConfig):
25
+ r"""
26
+ This is the configuration class to store the configuration of a [`Olmo2Model`]. It is used to instantiate an OLMo2
27
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
28
+ defaults will yield a similar configuration to that of the [allenai/Olmo2-7B-1124-hf](https://huggingface.co/allenai/Olmo2-7B-1124-hf).
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 50304):
36
+ Vocabulary size of the Olmo2 model. Defines the number of different tokens that can be represented by the
37
+ `inputs_ids` passed when calling [`Olmo2Model`]
38
+ hidden_size (`int`, *optional*, defaults to 4096):
39
+ Dimension of the hidden representations.
40
+ intermediate_size (`int`, *optional*, defaults to 11008):
41
+ Dimension of the MLP representations.
42
+ num_hidden_layers (`int`, *optional*, defaults to 32):
43
+ Number of hidden layers in the Transformer decoder.
44
+ num_attention_heads (`int`, *optional*, defaults to 32):
45
+ Number of attention heads for each attention layer in the Transformer decoder.
46
+ num_key_value_heads (`int`, *optional*):
47
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
48
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
49
+ `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
50
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
51
+ by meanpooling all the original heads within that group. For more details checkout [this
52
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
53
+ `num_attention_heads`.
54
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
55
+ The non-linear activation function (function or string) in the decoder.
56
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
57
+ The maximum sequence length that this model might ever be used with.
58
+ initializer_range (`float`, *optional*, defaults to 0.02):
59
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
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*, defaults to 1):
64
+ Padding token id.
65
+ bos_token_id (`int`, *optional*):
66
+ Beginning of stream token id.
67
+ eos_token_id (`int`, *optional*, defaults to 50279):
68
+ End of stream token id.
69
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
70
+ Whether to tie weight embeddings
71
+ rope_theta (`float`, *optional*, defaults to 10000.0):
72
+ The base period of the RoPE embeddings.
73
+ rope_scaling (`Dict`, *optional*):
74
+ Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
75
+ strategies: linear and dynamic. Their scaling factor must be a float greater than 1. The expected format is
76
+ `{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
77
+ `max_position_embeddings` to the expected new maximum. See the following thread for more information on how
78
+ these scaling strategies behave:
79
+ https://www.reddit.com/r/LocalLLaMA/comments/14mrgpr/dynamically_scaled_rope_further_increases/. This is an
80
+ experimental feature, subject to breaking API changes in future versions.
81
+ attention_bias (`bool`, defaults to `False`, *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
+ rms_norm_eps (`float`, *optional*, defaults to 1e-05):
86
+ The epsilon used by the rms normalization layers.
87
+
88
+ ```python
89
+ >>> from transformers import Olmo2Model, Olmo2Config
90
+
91
+ >>> # Initializing a Olmo2 7B style configuration
92
+ >>> configuration = Olmo2Config()
93
+
94
+ >>> # Initializing a model from the Olmo2 7B style configuration
95
+ >>> model = Olmo2Model(configuration)
96
+
97
+ >>> # Accessing the model configuration
98
+ >>> configuration = model.config
99
+ ```
100
+ """
101
+
102
+ model_type = "olmo2"
103
+ base_model_tp_plan = {
104
+ "layers.*.self_attn.q_proj": "colwise_rep", # we need to replicate here due to the added norm on q and k
105
+ "layers.*.self_attn.k_proj": "colwise_rep", # we need to replicate here due to the added norm on q and k
106
+ "layers.*.self_attn.v_proj": "colwise_rep", # we need to replicate here due to the added norm on q and k
107
+ "layers.*.self_attn.o_proj": "rowwise_rep", # we need to replicate here due to the added norm on q and k
108
+ "layers.*.mlp.gate_proj": "colwise",
109
+ "layers.*.mlp.up_proj": "colwise",
110
+ "layers.*.mlp.down_proj": "rowwise",
111
+ }
112
+ base_model_pp_plan = {
113
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
114
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
115
+ "norm": (["hidden_states"], ["hidden_states"]),
116
+ }
117
+
118
+ def __init__(
119
+ self,
120
+ vocab_size=50304,
121
+ hidden_size=4096,
122
+ intermediate_size=11008,
123
+ num_hidden_layers=32,
124
+ num_attention_heads=32,
125
+ num_key_value_heads=None,
126
+ hidden_act="silu",
127
+ max_position_embeddings=2048,
128
+ initializer_range=0.02,
129
+ use_cache=True,
130
+ pad_token_id=1,
131
+ bos_token_id=None,
132
+ eos_token_id=50279,
133
+ tie_word_embeddings=False,
134
+ rope_theta=10000.0,
135
+ rope_scaling=None,
136
+ attention_bias=False,
137
+ attention_dropout=0.0,
138
+ rms_norm_eps=1e-5,
139
+ **kwargs,
140
+ ):
141
+ super().__init__(
142
+ vocab_size=vocab_size,
143
+ hidden_size=hidden_size,
144
+ intermediate_size=intermediate_size,
145
+ num_hidden_layers=num_hidden_layers,
146
+ num_attention_heads=num_attention_heads,
147
+ num_key_value_heads=num_key_value_heads,
148
+ hidden_act=hidden_act,
149
+ max_position_embeddings=max_position_embeddings,
150
+ initializer_range=initializer_range,
151
+ use_cache=use_cache,
152
+ pad_token_id=pad_token_id,
153
+ bos_token_id=bos_token_id,
154
+ eos_token_id=eos_token_id,
155
+ tie_word_embeddings=tie_word_embeddings,
156
+ rope_theta=rope_theta,
157
+ rope_scaling=rope_scaling,
158
+ attention_bias=attention_bias,
159
+ attention_dropout=attention_dropout,
160
+ **kwargs,
161
+ )
162
+
163
+ self.rms_norm_eps = rms_norm_eps
164
+ del self.clip_qkv
165
+
166
+
167
+ class Olmo2RMSNorm(LlamaRMSNorm):
168
+ pass
169
+
170
+
171
+ ALL_LAYERNORM_LAYERS.append(Olmo2RMSNorm)
172
+
173
+
174
+ # Olmo2 attention is identical to OLMo attention except:
175
+ # - Norm is applied to attention queries and keys.
176
+ # - No qkv clipping.
177
+ class Olmo2Attention(OlmoAttention):
178
+ def __init__(self, config: Olmo2Config, layer_idx: Optional[int] = None):
179
+ super().__init__(config, layer_idx=layer_idx)
180
+ self.q_norm = Olmo2RMSNorm(config.num_attention_heads * self.head_dim, config.rms_norm_eps)
181
+ self.k_norm = Olmo2RMSNorm(config.num_key_value_heads * self.head_dim, config.rms_norm_eps)
182
+
183
+ def forward(
184
+ self,
185
+ hidden_states: torch.Tensor,
186
+ position_embeddings: Tuple[torch.Tensor, torch.Tensor],
187
+ attention_mask: Optional[torch.Tensor],
188
+ past_key_value: Optional[Cache] = None,
189
+ cache_position: Optional[torch.LongTensor] = None,
190
+ **kwargs,
191
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
192
+ input_shape = hidden_states.shape[:-1]
193
+ hidden_shape = (*input_shape, -1, self.head_dim)
194
+
195
+ query_states = self.q_norm(self.q_proj(hidden_states))
196
+ key_states = self.k_norm(self.k_proj(hidden_states))
197
+ value_states = self.v_proj(hidden_states)
198
+
199
+ query_states = query_states.view(hidden_shape).transpose(1, 2)
200
+ key_states = key_states.view(hidden_shape).transpose(1, 2)
201
+ value_states = value_states.view(hidden_shape).transpose(1, 2)
202
+
203
+ cos, sin = position_embeddings
204
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
205
+
206
+ if past_key_value is not None:
207
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
208
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
209
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
210
+
211
+ attention_interface: Callable = eager_attention_forward
212
+ if self.config._attn_implementation != "eager":
213
+ if self.config._attn_implementation == "sdpa" and kwargs.get("output_attentions", False):
214
+ logger.warning_once(
215
+ "`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to "
216
+ 'eager attention. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
217
+ )
218
+ else:
219
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
220
+
221
+ attn_output, attn_weights = attention_interface(
222
+ self,
223
+ query_states,
224
+ key_states,
225
+ value_states,
226
+ attention_mask,
227
+ dropout=0.0 if not self.training else self.attention_dropout,
228
+ scaling=self.scaling,
229
+ **kwargs,
230
+ )
231
+
232
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
233
+ attn_output = self.o_proj(attn_output)
234
+ return attn_output, attn_weights
235
+
236
+
237
+ # The OLMo2 layers are identical to those of the OLMo model except:
238
+ # - RMSNorm is used instead of standard layer norm.
239
+ # - Norm is applied after attention/feedforward rather than before.
240
+ class Olmo2DecoderLayer(OlmoDecoderLayer):
241
+ def __init__(self, config: Olmo2Config, layer_idx: int):
242
+ super().__init__(config, layer_idx=layer_idx)
243
+ self.post_attention_layernorm = Olmo2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
244
+ self.post_feedforward_layernorm = Olmo2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
245
+ self.self_attn = Olmo2Attention(config=config, layer_idx=layer_idx)
246
+ del self.input_layernorm
247
+
248
+ def forward(
249
+ self,
250
+ hidden_states: torch.Tensor,
251
+ attention_mask: Optional[torch.Tensor] = None,
252
+ position_ids: Optional[torch.LongTensor] = None,
253
+ past_key_value: Optional[Cache] = None,
254
+ output_attentions: Optional[bool] = False,
255
+ use_cache: Optional[bool] = False,
256
+ cache_position: Optional[torch.LongTensor] = None,
257
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
258
+ **kwargs,
259
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
260
+ residual = hidden_states
261
+
262
+ # Self Attention
263
+ hidden_states, self_attn_weights = self.self_attn(
264
+ hidden_states=hidden_states,
265
+ attention_mask=attention_mask,
266
+ position_ids=position_ids,
267
+ past_key_value=past_key_value,
268
+ output_attentions=output_attentions,
269
+ use_cache=use_cache,
270
+ cache_position=cache_position,
271
+ position_embeddings=position_embeddings,
272
+ **kwargs,
273
+ )
274
+ hidden_states = self.post_attention_layernorm(hidden_states)
275
+ hidden_states = residual + hidden_states
276
+
277
+ # Fully Connected
278
+ residual = hidden_states
279
+ hidden_states = self.mlp(hidden_states)
280
+ hidden_states = self.post_feedforward_layernorm(hidden_states)
281
+ hidden_states = residual + hidden_states
282
+
283
+ outputs = (hidden_states,)
284
+ if output_attentions:
285
+ outputs += (self_attn_weights,)
286
+
287
+ return outputs
288
+
289
+
290
+ # The OLMo2 model is identical to the OLMo model, except RMSNorm is used instead of
291
+ # standard layer norm for the output norm.
292
+ class Olmo2Model(OlmoModel):
293
+ def __init__(self, config: Olmo2Config):
294
+ super().__init__(config)
295
+ self.norm = Olmo2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
296
+ self.layers = nn.ModuleList(
297
+ [Olmo2DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
298
+ )
299
+
300
+
301
+ # The heads now only need to redefine the model inside to the correct `RobertaModel`
302
+ class Olmo2ForCausalLM(OlmoForCausalLM):
303
+ pass
304
+
305
+
306
+ __all__ = [
307
+ "Olmo2Config",
308
+ "Olmo2ForCausalLM",
309
+ "Olmo2Model",
310
+ "Olmo2PreTrainedModel", # noqa: F822
311
+ ]
vllm/lib/python3.10/site-packages/transformers/models/roformer/__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_roformer import *
22
+ from .modeling_flax_roformer import *
23
+ from .modeling_roformer import *
24
+ from .modeling_tf_roformer import *
25
+ from .tokenization_roformer import *
26
+ from .tokenization_roformer_fast 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__)