diff --git a/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/_cast_Char.h b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/_cast_Char.h new file mode 100644 index 0000000000000000000000000000000000000000..01fc2e40b9996c6694e7297d6d5c6dcff9ee02b9 --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/_cast_Char.h @@ -0,0 +1,30 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::_cast_Char(Tensor self, bool non_blocking=False) -> Tensor +inline at::Tensor _cast_Char(const at::Tensor & self, bool non_blocking=false) { + return at::_ops::_cast_Char::call(self, non_blocking); +} + +} diff --git a/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/_cufft_get_plan_cache_max_size_compositeimplicitautograd_dispatch.h b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/_cufft_get_plan_cache_max_size_compositeimplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..6222264b18363d19ce27a23250695ab26836a7b1 --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/_cufft_get_plan_cache_max_size_compositeimplicitautograd_dispatch.h @@ -0,0 +1,23 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeimplicitautograd { + +TORCH_API int64_t _cufft_get_plan_cache_max_size(int64_t device_index); + +} // namespace compositeimplicitautograd +} // namespace at diff --git a/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/_cufft_set_plan_cache_max_size_native.h b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/_cufft_set_plan_cache_max_size_native.h new file mode 100644 index 0000000000000000000000000000000000000000..b160030831ee1fb7146e02bc967f24f25ebfc4a8 --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/_cufft_set_plan_cache_max_size_native.h @@ -0,0 +1,21 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API void _cufft_set_plan_cache_max_size(int64_t device_index, int64_t max_size); +} // namespace native +} // namespace at diff --git a/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/_embedding_bag_forward_only_native.h b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/_embedding_bag_forward_only_native.h new file mode 100644 index 0000000000000000000000000000000000000000..ed70977835f4549fb593ec4e04f6f0a362f11c8c --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/_embedding_bag_forward_only_native.h @@ -0,0 +1,23 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API ::std::tuple _embedding_bag_forward_only_out(const at::Tensor & weight, const at::Tensor & indices, const at::Tensor & offsets, bool scale_grad_by_freq, int64_t mode, bool sparse, const c10::optional & per_sample_weights, bool include_last_offset, int64_t padding_idx, at::Tensor & out0, at::Tensor & out1, at::Tensor & out2, at::Tensor & out3); +TORCH_API ::std::tuple _embedding_bag_forward_only_cpu(const at::Tensor & weight, const at::Tensor & indices, const at::Tensor & offsets, bool scale_grad_by_freq=false, int64_t mode=0, bool sparse=false, const c10::optional & per_sample_weights={}, bool include_last_offset=false, int64_t padding_idx=-1); +TORCH_API ::std::tuple _embedding_bag_forward_only_cuda(const at::Tensor & weight, const at::Tensor & indices, const at::Tensor & offsets, bool scale_grad_by_freq=false, int64_t mode=0, bool sparse=false, const c10::optional & per_sample_weights={}, bool include_last_offset=false, int64_t padding_idx=-1); +} // namespace native +} // namespace at diff --git a/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/_empty_per_channel_affine_quantized.h b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/_empty_per_channel_affine_quantized.h new file mode 100644 index 0000000000000000000000000000000000000000..30ce06eb5849175942238e78f0f801556c80581b --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/_empty_per_channel_affine_quantized.h @@ -0,0 +1,43 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::_empty_per_channel_affine_quantized(int[] size, *, Tensor scales, Tensor zero_points, int axis, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=contiguous_format) -> Tensor +inline at::Tensor _empty_per_channel_affine_quantized(at::IntArrayRef size, const at::Tensor & scales, const at::Tensor & zero_points, int64_t axis, at::TensorOptions options={}, c10::optional memory_format=MemoryFormat::Contiguous) { + return at::_ops::_empty_per_channel_affine_quantized::call(size, scales, zero_points, axis, optTypeMetaToScalarType(options.dtype_opt()), options.layout_opt(), options.device_opt(), options.pinned_memory_opt(), c10::impl::check_tensor_options_and_extract_memory_format(options, memory_format)); +} +// aten::_empty_per_channel_affine_quantized(int[] size, *, Tensor scales, Tensor zero_points, int axis, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=contiguous_format) -> Tensor +inline at::Tensor _empty_per_channel_affine_quantized(at::IntArrayRef size, const at::Tensor & scales, const at::Tensor & zero_points, int64_t axis, c10::optional dtype, c10::optional layout, c10::optional device, c10::optional pin_memory, c10::optional memory_format) { + return at::_ops::_empty_per_channel_affine_quantized::call(size, scales, zero_points, axis, dtype, layout, device, pin_memory, memory_format); +} + +// aten::_empty_per_channel_affine_quantized.out(int[] size, *, Tensor scales, Tensor zero_points, int axis, MemoryFormat? memory_format=contiguous_format, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & _empty_per_channel_affine_quantized_out(at::Tensor & out, at::IntArrayRef size, const at::Tensor & scales, const at::Tensor & zero_points, int64_t axis, c10::optional memory_format=MemoryFormat::Contiguous) { + return at::_ops::_empty_per_channel_affine_quantized_out::call(size, scales, zero_points, axis, memory_format, out); +} +// aten::_empty_per_channel_affine_quantized.out(int[] size, *, Tensor scales, Tensor zero_points, int axis, MemoryFormat? memory_format=contiguous_format, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & _empty_per_channel_affine_quantized_outf(at::IntArrayRef size, const at::Tensor & scales, const at::Tensor & zero_points, int64_t axis, c10::optional memory_format, at::Tensor & out) { + return at::_ops::_empty_per_channel_affine_quantized_out::call(size, scales, zero_points, axis, memory_format, out); +} + +} diff --git a/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_exp_cpu_dispatch.h b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_exp_cpu_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..a77a1aa2707481d9550da92b83e592effe2d3cac --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_exp_cpu_dispatch.h @@ -0,0 +1,24 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cpu { + +TORCH_API ::std::vector _foreach_exp(at::TensorList self); +TORCH_API void _foreach_exp_(at::TensorList self); + +} // namespace cpu +} // namespace at diff --git a/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_frac.h b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_frac.h new file mode 100644 index 0000000000000000000000000000000000000000..1419069fce449f2dc8ed797531aef52421524572 --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_frac.h @@ -0,0 +1,44 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::_foreach_frac(Tensor[] self) -> Tensor[] +inline ::std::vector _foreach_frac(at::TensorList self) { + return at::_ops::_foreach_frac::call(self); +} + +// aten::_foreach_frac_(Tensor(a!)[] self) -> () +inline void _foreach_frac_(at::TensorList self) { + return at::_ops::_foreach_frac_::call(self); +} + +// aten::_foreach_frac.out(Tensor[] self, *, Tensor(a!)[] out) -> () +inline void _foreach_frac_out(at::TensorList out, at::TensorList self) { + return at::_ops::_foreach_frac_out::call(self, out); +} +// aten::_foreach_frac.out(Tensor[] self, *, Tensor(a!)[] out) -> () +inline void _foreach_frac_outf(at::TensorList self, at::TensorList out) { + return at::_ops::_foreach_frac_out::call(self, out); +} + +} diff --git a/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_sin_compositeexplicitautograd_dispatch.h b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_sin_compositeexplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..0cc334a241742652aac1268b99917e736fabaf99 --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_sin_compositeexplicitautograd_dispatch.h @@ -0,0 +1,24 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautograd { + +TORCH_API void _foreach_sin_out(at::TensorList out, at::TensorList self); +TORCH_API void _foreach_sin_outf(at::TensorList self, at::TensorList out); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/_linalg_det_ops.h b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/_linalg_det_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..0f2d261abcb96a560056564fa9b9f388687c9aba --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/_linalg_det_ops.h @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API _linalg_det { + using schema = ::std::tuple (const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_linalg_det") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_linalg_det(Tensor A) -> (Tensor result, Tensor LU, Tensor pivots)") + static ::std::tuple call(const at::Tensor & A); + static ::std::tuple redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & A); +}; + +struct TORCH_API _linalg_det_result { + using schema = ::std::tuple (const at::Tensor &, at::Tensor &, at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_linalg_det") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "result") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_linalg_det.result(Tensor A, *, Tensor(a!) result, Tensor(b!) LU, Tensor(c!) pivots) -> (Tensor(a!) result, Tensor(b!) LU, Tensor(c!) pivots)") + static ::std::tuple call(const at::Tensor & A, at::Tensor & result, at::Tensor & LU, at::Tensor & pivots); + static ::std::tuple redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & A, at::Tensor & result, at::Tensor & LU, at::Tensor & pivots); +}; + +}} // namespace at::_ops diff --git a/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/_linalg_solve_ex_meta.h b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/_linalg_solve_ex_meta.h new file mode 100644 index 0000000000000000000000000000000000000000..288e1b5d032e0aab20fe5f1422b16065a89efb29 --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/_linalg_solve_ex_meta.h @@ -0,0 +1,27 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeMetaFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at { +namespace meta { + +struct TORCH_API structured__linalg_solve_ex : public at::impl::MetaBase { + + + void meta(const at::Tensor & A, const at::Tensor & B, bool left, bool check_errors); +}; + +} // namespace native +} // namespace at diff --git a/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/_logcumsumexp_cuda_dispatch.h b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/_logcumsumexp_cuda_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..73f60b0f34b6324691330cd8e5f94c7ec4909732 --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/_logcumsumexp_cuda_dispatch.h @@ -0,0 +1,25 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cuda { + +TORCH_API at::Tensor _logcumsumexp(const at::Tensor & self, int64_t dim); +TORCH_API at::Tensor & _logcumsumexp_out(at::Tensor & out, const at::Tensor & self, int64_t dim); +TORCH_API at::Tensor & _logcumsumexp_outf(const at::Tensor & self, int64_t dim, at::Tensor & out); + +} // namespace cuda +} // namespace at diff --git a/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/_nested_tensor_from_tensor_list_ops.h b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/_nested_tensor_from_tensor_list_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..b5af539581b805482ab84f4509e6358fd2c01a82 --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/_nested_tensor_from_tensor_list_ops.h @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API _nested_tensor_from_tensor_list { + using schema = at::Tensor (at::TensorList, c10::optional, c10::optional, c10::optional, c10::optional); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_nested_tensor_from_tensor_list") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_nested_tensor_from_tensor_list(Tensor[] list, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor") + static at::Tensor call(at::TensorList list, c10::optional dtype, c10::optional layout, c10::optional device, c10::optional pin_memory); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList list, c10::optional dtype, c10::optional layout, c10::optional device, c10::optional pin_memory); +}; + +struct TORCH_API _nested_tensor_from_tensor_list_out { + using schema = at::Tensor & (at::TensorList, c10::optional, c10::optional, c10::optional, c10::optional, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_nested_tensor_from_tensor_list") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_nested_tensor_from_tensor_list.out(Tensor[] list, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(at::TensorList list, c10::optional dtype, c10::optional layout, c10::optional device, c10::optional pin_memory, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList list, c10::optional dtype, c10::optional layout, c10::optional device, c10::optional pin_memory, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/_sparse_mm_compositeimplicitautograd_dispatch.h b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/_sparse_mm_compositeimplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..4b0a50a789010f82b2d6cb3e51d225ad02de25a6 --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/_sparse_mm_compositeimplicitautograd_dispatch.h @@ -0,0 +1,24 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeimplicitautograd { + +TORCH_API at::Tensor _sparse_mm(const at::Tensor & sparse, const at::Tensor & dense); +TORCH_API at::Tensor _sparse_mm(const at::Tensor & sparse, const at::Tensor & dense, c10::string_view reduce); + +} // namespace compositeimplicitautograd +} // namespace at diff --git a/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/_upsample_bicubic2d_aa_cpu_dispatch.h b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/_upsample_bicubic2d_aa_cpu_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..1ddfafd4877423a911fefe0c09e61089f6647cdd --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/_upsample_bicubic2d_aa_cpu_dispatch.h @@ -0,0 +1,28 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cpu { + +TORCH_API at::Tensor _upsample_bicubic2d_aa(const at::Tensor & self, at::IntArrayRef output_size, bool align_corners, c10::optional scales_h=c10::nullopt, c10::optional scales_w=c10::nullopt); +TORCH_API at::Tensor _upsample_bicubic2d_aa_symint(const at::Tensor & self, c10::SymIntArrayRef output_size, bool align_corners, c10::optional scales_h=c10::nullopt, c10::optional scales_w=c10::nullopt); +TORCH_API at::Tensor & _upsample_bicubic2d_aa_out(at::Tensor & out, const at::Tensor & self, at::IntArrayRef output_size, bool align_corners, c10::optional scales_h=c10::nullopt, c10::optional scales_w=c10::nullopt); +TORCH_API at::Tensor & _upsample_bicubic2d_aa_outf(const at::Tensor & self, at::IntArrayRef output_size, bool align_corners, c10::optional scales_h, c10::optional scales_w, at::Tensor & out); +TORCH_API at::Tensor & _upsample_bicubic2d_aa_symint_out(at::Tensor & out, const at::Tensor & self, c10::SymIntArrayRef output_size, bool align_corners, c10::optional scales_h=c10::nullopt, c10::optional scales_w=c10::nullopt); +TORCH_API at::Tensor & _upsample_bicubic2d_aa_symint_outf(const at::Tensor & self, c10::SymIntArrayRef output_size, bool align_corners, c10::optional scales_h, c10::optional scales_w, at::Tensor & out); + +} // namespace cpu +} // namespace at diff --git a/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/_validate_compressed_sparse_indices_ops.h b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/_validate_compressed_sparse_indices_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..a6d469afdb3dda8e1b171a0dfc634751e3674148 --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/_validate_compressed_sparse_indices_ops.h @@ -0,0 +1,28 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API _validate_compressed_sparse_indices { + using schema = void (bool, const at::Tensor &, const at::Tensor &, int64_t, int64_t, int64_t); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_validate_compressed_sparse_indices") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_validate_compressed_sparse_indices(bool is_crow, Tensor compressed_idx, Tensor plain_idx, int cdim, int dim, int nnz) -> ()") + static void call(bool is_crow, const at::Tensor & compressed_idx, const at::Tensor & plain_idx, int64_t cdim, int64_t dim, int64_t nnz); + static void redispatch(c10::DispatchKeySet dispatchKeySet, bool is_crow, const at::Tensor & compressed_idx, const at::Tensor & plain_idx, int64_t cdim, int64_t dim, int64_t nnz); +}; + +}} // namespace at::_ops diff --git a/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/adaptive_avg_pool3d_native.h b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/adaptive_avg_pool3d_native.h new file mode 100644 index 0000000000000000000000000000000000000000..c0fbf736ce6ee0d45daa5bb2f5ef13161eadbd0a --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/adaptive_avg_pool3d_native.h @@ -0,0 +1,24 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor adaptive_avg_pool3d_symint(const at::Tensor & self, c10::SymIntArrayRef output_size); +TORCH_API at::Tensor & adaptive_avg_pool3d_out_cpu(const at::Tensor & self, at::IntArrayRef output_size, at::Tensor & out); +TORCH_API at::Tensor & adaptive_avg_pool3d_out_cuda(const at::Tensor & self, at::IntArrayRef output_size, at::Tensor & out); +TORCH_API at::Tensor & adaptive_avg_pool3d_out_quantized_cpu(const at::Tensor & self, at::IntArrayRef output_size, at::Tensor & out); +} // namespace native +} // namespace at diff --git a/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/addcdiv_cuda_dispatch.h b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/addcdiv_cuda_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..d5253848a8ebbe0e16d11e1ec1e6b14c1c79c949 --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/addcdiv_cuda_dispatch.h @@ -0,0 +1,26 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cuda { + +TORCH_API at::Tensor addcdiv(const at::Tensor & self, const at::Tensor & tensor1, const at::Tensor & tensor2, const at::Scalar & value=1); +TORCH_API at::Tensor & addcdiv_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & tensor1, const at::Tensor & tensor2, const at::Scalar & value=1); +TORCH_API at::Tensor & addcdiv_outf(const at::Tensor & self, const at::Tensor & tensor1, const at::Tensor & tensor2, const at::Scalar & value, at::Tensor & out); +TORCH_API at::Tensor & addcdiv_(at::Tensor & self, const at::Tensor & tensor1, const at::Tensor & tensor2, const at::Scalar & value=1); + +} // namespace cuda +} // namespace at diff --git a/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/addcmul_cpu_dispatch.h b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/addcmul_cpu_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..42cf40440ed6389404c32ba0acf214e0a2fbe538 --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/addcmul_cpu_dispatch.h @@ -0,0 +1,26 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cpu { + +TORCH_API at::Tensor addcmul(const at::Tensor & self, const at::Tensor & tensor1, const at::Tensor & tensor2, const at::Scalar & value=1); +TORCH_API at::Tensor & addcmul_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & tensor1, const at::Tensor & tensor2, const at::Scalar & value=1); +TORCH_API at::Tensor & addcmul_outf(const at::Tensor & self, const at::Tensor & tensor1, const at::Tensor & tensor2, const at::Scalar & value, at::Tensor & out); +TORCH_API at::Tensor & addcmul_(at::Tensor & self, const at::Tensor & tensor1, const at::Tensor & tensor2, const at::Scalar & value=1); + +} // namespace cpu +} // namespace at diff --git a/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/addcmul_ops.h b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/addcmul_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..6384b01ae714dcebe80661c6bc862552c88e9e47 --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/addcmul_ops.h @@ -0,0 +1,50 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API addcmul_out { + using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, const at::Tensor &, const at::Scalar &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::addcmul") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "addcmul.out(Tensor self, Tensor tensor1, Tensor tensor2, *, Scalar value=1, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, const at::Tensor & tensor1, const at::Tensor & tensor2, const at::Scalar & value, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & tensor1, const at::Tensor & tensor2, const at::Scalar & value, at::Tensor & out); +}; + +struct TORCH_API addcmul { + using schema = at::Tensor (const at::Tensor &, const at::Tensor &, const at::Tensor &, const at::Scalar &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::addcmul") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "addcmul(Tensor self, Tensor tensor1, Tensor tensor2, *, Scalar value=1) -> Tensor") + static at::Tensor call(const at::Tensor & self, const at::Tensor & tensor1, const at::Tensor & tensor2, const at::Scalar & value); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & tensor1, const at::Tensor & tensor2, const at::Scalar & value); +}; + +struct TORCH_API addcmul_ { + using schema = at::Tensor & (at::Tensor &, const at::Tensor &, const at::Tensor &, const at::Scalar &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::addcmul_") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "addcmul_(Tensor(a!) self, Tensor tensor1, Tensor tensor2, *, Scalar value=1) -> Tensor(a!)") + static at::Tensor & call(at::Tensor & self, const at::Tensor & tensor1, const at::Tensor & tensor2, const at::Scalar & value); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self, const at::Tensor & tensor1, const at::Tensor & tensor2, const at::Scalar & value); +}; + +}} // namespace at::_ops diff --git a/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/cartesian_prod_compositeimplicitautograd_dispatch.h b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/cartesian_prod_compositeimplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..3a56ce711a201163c5ab3d643416c4e6008915b2 --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/cartesian_prod_compositeimplicitautograd_dispatch.h @@ -0,0 +1,23 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeimplicitautograd { + +TORCH_API at::Tensor cartesian_prod(at::TensorList tensors); + +} // namespace compositeimplicitautograd +} // namespace at diff --git a/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/combinations_compositeimplicitautograd_dispatch.h b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/combinations_compositeimplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..6f57c07e72733fcbdaacb98be9ffdf164b9f9276 --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/combinations_compositeimplicitautograd_dispatch.h @@ -0,0 +1,23 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeimplicitautograd { + +TORCH_API at::Tensor combinations(const at::Tensor & self, int64_t r=2, bool with_replacement=false); + +} // namespace compositeimplicitautograd +} // namespace at diff --git a/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/convolution_backward.h b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/convolution_backward.h new file mode 100644 index 0000000000000000000000000000000000000000..93081306e6274e6359cfec23ec01a1d97eac197c --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/convolution_backward.h @@ -0,0 +1,91 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::convolution_backward(Tensor grad_output, Tensor input, Tensor weight, SymInt[]? bias_sizes, int[] stride, SymInt[] padding, int[] dilation, bool transposed, SymInt[] output_padding, int groups, bool[3] output_mask) -> (Tensor, Tensor, Tensor) +inline ::std::tuple convolution_backward(const at::Tensor & grad_output, const at::Tensor & input, const at::Tensor & weight, at::OptionalIntArrayRef bias_sizes, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, bool transposed, at::IntArrayRef output_padding, int64_t groups, ::std::array output_mask) { + return at::_ops::convolution_backward::call(grad_output, input, weight, bias_sizes.has_value() ? c10::make_optional(c10::fromIntArrayRefSlow(*bias_sizes)) : c10::nullopt, stride, c10::fromIntArrayRefSlow(padding), dilation, transposed, c10::fromIntArrayRefSlow(output_padding), groups, output_mask); +} +namespace symint { + template ::value>> + ::std::tuple convolution_backward(const at::Tensor & grad_output, const at::Tensor & input, const at::Tensor & weight, at::OptionalIntArrayRef bias_sizes, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, bool transposed, at::IntArrayRef output_padding, int64_t groups, ::std::array output_mask) { + return at::_ops::convolution_backward::call(grad_output, input, weight, bias_sizes.has_value() ? c10::make_optional(c10::fromIntArrayRefSlow(*bias_sizes)) : c10::nullopt, stride, c10::fromIntArrayRefSlow(padding), dilation, transposed, c10::fromIntArrayRefSlow(output_padding), groups, output_mask); + } +} + +// aten::convolution_backward(Tensor grad_output, Tensor input, Tensor weight, SymInt[]? bias_sizes, int[] stride, SymInt[] padding, int[] dilation, bool transposed, SymInt[] output_padding, int groups, bool[3] output_mask) -> (Tensor, Tensor, Tensor) +inline ::std::tuple convolution_backward_symint(const at::Tensor & grad_output, const at::Tensor & input, const at::Tensor & weight, at::OptionalSymIntArrayRef bias_sizes, at::IntArrayRef stride, c10::SymIntArrayRef padding, at::IntArrayRef dilation, bool transposed, c10::SymIntArrayRef output_padding, int64_t groups, ::std::array output_mask) { + return at::_ops::convolution_backward::call(grad_output, input, weight, bias_sizes, stride, padding, dilation, transposed, output_padding, groups, output_mask); +} +namespace symint { + template ::value>> + ::std::tuple convolution_backward(const at::Tensor & grad_output, const at::Tensor & input, const at::Tensor & weight, at::OptionalSymIntArrayRef bias_sizes, at::IntArrayRef stride, c10::SymIntArrayRef padding, at::IntArrayRef dilation, bool transposed, c10::SymIntArrayRef output_padding, int64_t groups, ::std::array output_mask) { + return at::_ops::convolution_backward::call(grad_output, input, weight, bias_sizes, stride, padding, dilation, transposed, output_padding, groups, output_mask); + } +} + +// aten::convolution_backward.out(Tensor grad_output, Tensor input, Tensor weight, SymInt[]? bias_sizes, int[] stride, SymInt[] padding, int[] dilation, bool transposed, SymInt[] output_padding, int groups, bool[3] output_mask, *, Tensor(a!) out0, Tensor(b!) out1, Tensor(c!) out2) -> (Tensor(a!), Tensor(b!), Tensor(c!)) +inline ::std::tuple convolution_backward_out(at::Tensor & out0, at::Tensor & out1, at::Tensor & out2, const at::Tensor & grad_output, const at::Tensor & input, const at::Tensor & weight, at::OptionalIntArrayRef bias_sizes, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, bool transposed, at::IntArrayRef output_padding, int64_t groups, ::std::array output_mask) { + return at::_ops::convolution_backward_out::call(grad_output, input, weight, bias_sizes.has_value() ? c10::make_optional(c10::fromIntArrayRefSlow(*bias_sizes)) : c10::nullopt, stride, c10::fromIntArrayRefSlow(padding), dilation, transposed, c10::fromIntArrayRefSlow(output_padding), groups, output_mask, out0, out1, out2); +} +namespace symint { + template ::value>> + ::std::tuple convolution_backward_out(at::Tensor & out0, at::Tensor & out1, at::Tensor & out2, const at::Tensor & grad_output, const at::Tensor & input, const at::Tensor & weight, at::OptionalIntArrayRef bias_sizes, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, bool transposed, at::IntArrayRef output_padding, int64_t groups, ::std::array output_mask) { + return at::_ops::convolution_backward_out::call(grad_output, input, weight, bias_sizes.has_value() ? c10::make_optional(c10::fromIntArrayRefSlow(*bias_sizes)) : c10::nullopt, stride, c10::fromIntArrayRefSlow(padding), dilation, transposed, c10::fromIntArrayRefSlow(output_padding), groups, output_mask, out0, out1, out2); + } +} + +// aten::convolution_backward.out(Tensor grad_output, Tensor input, Tensor weight, SymInt[]? bias_sizes, int[] stride, SymInt[] padding, int[] dilation, bool transposed, SymInt[] output_padding, int groups, bool[3] output_mask, *, Tensor(a!) out0, Tensor(b!) out1, Tensor(c!) out2) -> (Tensor(a!), Tensor(b!), Tensor(c!)) +inline ::std::tuple convolution_backward_outf(const at::Tensor & grad_output, const at::Tensor & input, const at::Tensor & weight, at::OptionalIntArrayRef bias_sizes, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, bool transposed, at::IntArrayRef output_padding, int64_t groups, ::std::array output_mask, at::Tensor & out0, at::Tensor & out1, at::Tensor & out2) { + return at::_ops::convolution_backward_out::call(grad_output, input, weight, bias_sizes.has_value() ? c10::make_optional(c10::fromIntArrayRefSlow(*bias_sizes)) : c10::nullopt, stride, c10::fromIntArrayRefSlow(padding), dilation, transposed, c10::fromIntArrayRefSlow(output_padding), groups, output_mask, out0, out1, out2); +} +namespace symint { + template ::value>> + ::std::tuple convolution_backward_outf(const at::Tensor & grad_output, const at::Tensor & input, const at::Tensor & weight, at::OptionalIntArrayRef bias_sizes, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, bool transposed, at::IntArrayRef output_padding, int64_t groups, ::std::array output_mask, at::Tensor & out0, at::Tensor & out1, at::Tensor & out2) { + return at::_ops::convolution_backward_out::call(grad_output, input, weight, bias_sizes.has_value() ? c10::make_optional(c10::fromIntArrayRefSlow(*bias_sizes)) : c10::nullopt, stride, c10::fromIntArrayRefSlow(padding), dilation, transposed, c10::fromIntArrayRefSlow(output_padding), groups, output_mask, out0, out1, out2); + } +} + +// aten::convolution_backward.out(Tensor grad_output, Tensor input, Tensor weight, SymInt[]? bias_sizes, int[] stride, SymInt[] padding, int[] dilation, bool transposed, SymInt[] output_padding, int groups, bool[3] output_mask, *, Tensor(a!) out0, Tensor(b!) out1, Tensor(c!) out2) -> (Tensor(a!), Tensor(b!), Tensor(c!)) +inline ::std::tuple convolution_backward_symint_out(at::Tensor & out0, at::Tensor & out1, at::Tensor & out2, const at::Tensor & grad_output, const at::Tensor & input, const at::Tensor & weight, at::OptionalSymIntArrayRef bias_sizes, at::IntArrayRef stride, c10::SymIntArrayRef padding, at::IntArrayRef dilation, bool transposed, c10::SymIntArrayRef output_padding, int64_t groups, ::std::array output_mask) { + return at::_ops::convolution_backward_out::call(grad_output, input, weight, bias_sizes, stride, padding, dilation, transposed, output_padding, groups, output_mask, out0, out1, out2); +} +namespace symint { + template ::value>> + ::std::tuple convolution_backward_out(at::Tensor & out0, at::Tensor & out1, at::Tensor & out2, const at::Tensor & grad_output, const at::Tensor & input, const at::Tensor & weight, at::OptionalSymIntArrayRef bias_sizes, at::IntArrayRef stride, c10::SymIntArrayRef padding, at::IntArrayRef dilation, bool transposed, c10::SymIntArrayRef output_padding, int64_t groups, ::std::array output_mask) { + return at::_ops::convolution_backward_out::call(grad_output, input, weight, bias_sizes, stride, padding, dilation, transposed, output_padding, groups, output_mask, out0, out1, out2); + } +} + +// aten::convolution_backward.out(Tensor grad_output, Tensor input, Tensor weight, SymInt[]? bias_sizes, int[] stride, SymInt[] padding, int[] dilation, bool transposed, SymInt[] output_padding, int groups, bool[3] output_mask, *, Tensor(a!) out0, Tensor(b!) out1, Tensor(c!) out2) -> (Tensor(a!), Tensor(b!), Tensor(c!)) +inline ::std::tuple convolution_backward_symint_outf(const at::Tensor & grad_output, const at::Tensor & input, const at::Tensor & weight, at::OptionalSymIntArrayRef bias_sizes, at::IntArrayRef stride, c10::SymIntArrayRef padding, at::IntArrayRef dilation, bool transposed, c10::SymIntArrayRef output_padding, int64_t groups, ::std::array output_mask, at::Tensor & out0, at::Tensor & out1, at::Tensor & out2) { + return at::_ops::convolution_backward_out::call(grad_output, input, weight, bias_sizes, stride, padding, dilation, transposed, output_padding, groups, output_mask, out0, out1, out2); +} +namespace symint { + template ::value>> + ::std::tuple convolution_backward_outf(const at::Tensor & grad_output, const at::Tensor & input, const at::Tensor & weight, at::OptionalSymIntArrayRef bias_sizes, at::IntArrayRef stride, c10::SymIntArrayRef padding, at::IntArrayRef dilation, bool transposed, c10::SymIntArrayRef output_padding, int64_t groups, ::std::array output_mask, at::Tensor & out0, at::Tensor & out1, at::Tensor & out2) { + return at::_ops::convolution_backward_out::call(grad_output, input, weight, bias_sizes, stride, padding, dilation, transposed, output_padding, groups, output_mask, out0, out1, out2); + } +} + +} diff --git a/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/embedding_renorm_ops.h b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/embedding_renorm_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..9b4b068afbdf1f877b7ee6a1fa230156591fc00f --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/embedding_renorm_ops.h @@ -0,0 +1,50 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API embedding_renorm_ { + using schema = at::Tensor & (at::Tensor &, const at::Tensor &, double, double); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::embedding_renorm_") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "embedding_renorm_(Tensor(a!) self, Tensor indices, float max_norm, float norm_type) -> Tensor(a!)") + static at::Tensor & call(at::Tensor & self, const at::Tensor & indices, double max_norm, double norm_type); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self, const at::Tensor & indices, double max_norm, double norm_type); +}; + +struct TORCH_API embedding_renorm_out { + using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, double, double, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::embedding_renorm") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "embedding_renorm.out(Tensor self, Tensor indices, float max_norm, float norm_type, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, const at::Tensor & indices, double max_norm, double norm_type, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & indices, double max_norm, double norm_type, at::Tensor & out); +}; + +struct TORCH_API embedding_renorm { + using schema = at::Tensor (const at::Tensor &, const at::Tensor &, double, double); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::embedding_renorm") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "embedding_renorm(Tensor self, Tensor indices, float max_norm, float norm_type) -> Tensor") + static at::Tensor call(const at::Tensor & self, const at::Tensor & indices, double max_norm, double norm_type); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & indices, double max_norm, double norm_type); +}; + +}} // namespace at::_ops diff --git a/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/exp_cpu_dispatch.h b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/exp_cpu_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..b6e2df918d750d8abca4d71f3809949694fbd3f0 --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/exp_cpu_dispatch.h @@ -0,0 +1,26 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cpu { + +TORCH_API at::Tensor exp(const at::Tensor & self); +TORCH_API at::Tensor & exp_out(at::Tensor & out, const at::Tensor & self); +TORCH_API at::Tensor & exp_outf(const at::Tensor & self, at::Tensor & out); +TORCH_API at::Tensor & exp_(at::Tensor & self); + +} // namespace cpu +} // namespace at diff --git a/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/fbgemm_linear_fp16_weight_fp32_activation.h b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/fbgemm_linear_fp16_weight_fp32_activation.h new file mode 100644 index 0000000000000000000000000000000000000000..4ae55e5c884910d0354985636b1ef16e29149c1e --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/fbgemm_linear_fp16_weight_fp32_activation.h @@ -0,0 +1,30 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::fbgemm_linear_fp16_weight_fp32_activation(Tensor input, Tensor packed_weight, Tensor bias) -> Tensor +inline at::Tensor fbgemm_linear_fp16_weight_fp32_activation(const at::Tensor & input, const at::Tensor & packed_weight, const at::Tensor & bias) { + return at::_ops::fbgemm_linear_fp16_weight_fp32_activation::call(input, packed_weight, bias); +} + +} diff --git a/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/fft_ihfft2.h b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/fft_ihfft2.h new file mode 100644 index 0000000000000000000000000000000000000000..497a5d1e8659ccdc5b1c9c8cb40796cbf72021c8 --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/fft_ihfft2.h @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::fft_ihfft2(Tensor self, int[1]? s=None, int[1] dim=[-2,-1], str? norm=None) -> Tensor +inline at::Tensor fft_ihfft2(const at::Tensor & self, at::OptionalIntArrayRef s=c10::nullopt, at::IntArrayRef dim={-2,-1}, c10::optional norm=c10::nullopt) { + return at::_ops::fft_ihfft2::call(self, s, dim, norm); +} + +// aten::fft_ihfft2.out(Tensor self, int[1]? s=None, int[1] dim=[-2,-1], str? norm=None, *, Tensor(a!) out) -> Tensor(a!) +inline const at::Tensor & fft_ihfft2_out(const at::Tensor & out, const at::Tensor & self, at::OptionalIntArrayRef s=c10::nullopt, at::IntArrayRef dim={-2,-1}, c10::optional norm=c10::nullopt) { + return at::_ops::fft_ihfft2_out::call(self, s, dim, norm, out); +} +// aten::fft_ihfft2.out(Tensor self, int[1]? s=None, int[1] dim=[-2,-1], str? norm=None, *, Tensor(a!) out) -> Tensor(a!) +inline const at::Tensor & fft_ihfft2_outf(const at::Tensor & self, at::OptionalIntArrayRef s, at::IntArrayRef dim, c10::optional norm, const at::Tensor & out) { + return at::_ops::fft_ihfft2_out::call(self, s, dim, norm, out); +} + +} diff --git a/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/fill_compositeexplicitautograd_dispatch.h b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/fill_compositeexplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..9d1646d329975a1ed4d5932ad221bce6cd75131b --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/fill_compositeexplicitautograd_dispatch.h @@ -0,0 +1,28 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautograd { + +TORCH_API at::Tensor fill(const at::Tensor & self, const at::Scalar & value); +TORCH_API at::Tensor & fill_out(at::Tensor & out, const at::Tensor & self, const at::Scalar & value); +TORCH_API at::Tensor & fill_outf(const at::Tensor & self, const at::Scalar & value, at::Tensor & out); +TORCH_API at::Tensor fill(const at::Tensor & self, const at::Tensor & value); +TORCH_API at::Tensor & fill_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & value); +TORCH_API at::Tensor & fill_outf(const at::Tensor & self, const at::Tensor & value, at::Tensor & out); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/fill_diagonal_native.h b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/fill_diagonal_native.h new file mode 100644 index 0000000000000000000000000000000000000000..bd5d7e93fdf0e2c179c04ff93d80f88d33b691c4 --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/fill_diagonal_native.h @@ -0,0 +1,21 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor & fill_diagonal_(at::Tensor & self, const at::Scalar & fill_value, bool wrap=false); +} // namespace native +} // namespace at diff --git a/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/floor_divide_cuda_dispatch.h b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/floor_divide_cuda_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..df88be22fdad5e1a25076febd2a72810fb6dab06 --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/floor_divide_cuda_dispatch.h @@ -0,0 +1,26 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cuda { + +TORCH_API at::Tensor floor_divide(const at::Tensor & self, const at::Tensor & other); +TORCH_API at::Tensor & floor_divide_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & other); +TORCH_API at::Tensor & floor_divide_outf(const at::Tensor & self, const at::Tensor & other, at::Tensor & out); +TORCH_API at::Tensor & floor_divide_(at::Tensor & self, const at::Tensor & other); + +} // namespace cuda +} // namespace at diff --git a/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/fmax_meta_dispatch.h b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/fmax_meta_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..1c51ba2002c4422ab5f3279397efb82e76e312ad --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/fmax_meta_dispatch.h @@ -0,0 +1,25 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace meta { + +TORCH_API at::Tensor fmax(const at::Tensor & self, const at::Tensor & other); +TORCH_API at::Tensor & fmax_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & other); +TORCH_API at::Tensor & fmax_outf(const at::Tensor & self, const at::Tensor & other, at::Tensor & out); + +} // namespace meta +} // namespace at diff --git a/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/gelu_backward_meta.h b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/gelu_backward_meta.h new file mode 100644 index 0000000000000000000000000000000000000000..6d18a50d910b76d5f6e7a7864a6908d35c6c8d2e --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/gelu_backward_meta.h @@ -0,0 +1,27 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeMetaFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at { +namespace meta { + +struct TORCH_API structured_gelu_backward : public TensorIteratorBase { + + + void meta(const at::Tensor & grad_output, const at::Tensor & self, c10::string_view approximate); +}; + +} // namespace native +} // namespace at diff --git a/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/geqrf_cpu_dispatch.h b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/geqrf_cpu_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..2a6f18f26a9b422ba359fdbf1dbb9e6acfdb5e35 --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/geqrf_cpu_dispatch.h @@ -0,0 +1,25 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cpu { + +TORCH_API ::std::tuple geqrf(const at::Tensor & self); +TORCH_API ::std::tuple geqrf_out(at::Tensor & a, at::Tensor & tau, const at::Tensor & self); +TORCH_API ::std::tuple geqrf_outf(const at::Tensor & self, at::Tensor & a, at::Tensor & tau); + +} // namespace cpu +} // namespace at diff --git a/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/group_norm.h b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/group_norm.h new file mode 100644 index 0000000000000000000000000000000000000000..4fe86d22e6e8179d48c36245ead567dc50cb0938 --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/group_norm.h @@ -0,0 +1,30 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::group_norm(Tensor input, int num_groups, Tensor? weight=None, Tensor? bias=None, float eps=1e-05, bool cudnn_enabled=True) -> Tensor +inline at::Tensor group_norm(const at::Tensor & input, int64_t num_groups, const c10::optional & weight={}, const c10::optional & bias={}, double eps=1e-05, bool cudnn_enabled=true) { + return at::_ops::group_norm::call(input, num_groups, weight, bias, eps, cudnn_enabled); +} + +} diff --git a/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/hardswish.h b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/hardswish.h new file mode 100644 index 0000000000000000000000000000000000000000..92e43ac528eaa40fc8b8525ca9500a73ed2a1874 --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/hardswish.h @@ -0,0 +1,44 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::hardswish.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & hardswish_out(at::Tensor & out, const at::Tensor & self) { + return at::_ops::hardswish_out::call(self, out); +} +// aten::hardswish.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & hardswish_outf(const at::Tensor & self, at::Tensor & out) { + return at::_ops::hardswish_out::call(self, out); +} + +// aten::hardswish(Tensor self) -> Tensor +inline at::Tensor hardswish(const at::Tensor & self) { + return at::_ops::hardswish::call(self); +} + +// aten::hardswish_(Tensor(a!) self) -> Tensor(a!) +inline at::Tensor & hardswish_(at::Tensor & self) { + return at::_ops::hardswish_::call(self); +} + +} diff --git a/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/lift.h b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/lift.h new file mode 100644 index 0000000000000000000000000000000000000000..c8a3fec981b4cc696c4e34b1e84a8f560dabd626 --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/lift.h @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::lift(Tensor self) -> Tensor +inline at::Tensor lift(const at::Tensor & self) { + return at::_ops::lift::call(self); +} + +// aten::lift.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & lift_out(at::Tensor & out, const at::Tensor & self) { + return at::_ops::lift_out::call(self, out); +} +// aten::lift.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & lift_outf(const at::Tensor & self, at::Tensor & out) { + return at::_ops::lift_out::call(self, out); +} + +} diff --git a/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/linalg_lu_factor_native.h b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/linalg_lu_factor_native.h new file mode 100644 index 0000000000000000000000000000000000000000..433779bcb2a67caa830915fcdf9b2738309e14df --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/linalg_lu_factor_native.h @@ -0,0 +1,22 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API ::std::tuple linalg_lu_factor(const at::Tensor & A, bool pivot=true); +TORCH_API ::std::tuple linalg_lu_factor_out(const at::Tensor & A, bool pivot, at::Tensor & LU, at::Tensor & pivots); +} // namespace native +} // namespace at diff --git a/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/logit.h b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/logit.h new file mode 100644 index 0000000000000000000000000000000000000000..eda6e3f2850bba2831adb616e8d14abfa4602141 --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/logit.h @@ -0,0 +1,44 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::logit(Tensor self, float? eps=None) -> Tensor +inline at::Tensor logit(const at::Tensor & self, c10::optional eps=c10::nullopt) { + return at::_ops::logit::call(self, eps); +} + +// aten::logit_(Tensor(a!) self, float? eps=None) -> Tensor(a!) +inline at::Tensor & logit_(at::Tensor & self, c10::optional eps=c10::nullopt) { + return at::_ops::logit_::call(self, eps); +} + +// aten::logit.out(Tensor self, float? eps=None, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & logit_out(at::Tensor & out, const at::Tensor & self, c10::optional eps=c10::nullopt) { + return at::_ops::logit_out::call(self, eps, out); +} +// aten::logit.out(Tensor self, float? eps=None, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & logit_outf(const at::Tensor & self, c10::optional eps, at::Tensor & out) { + return at::_ops::logit_out::call(self, eps, out); +} + +} diff --git a/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/lt_cuda_dispatch.h b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/lt_cuda_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..8ee8178d952a2e0e027d12c27368194b465b7d66 --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/lt_cuda_dispatch.h @@ -0,0 +1,30 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cuda { + +TORCH_API at::Tensor lt(const at::Tensor & self, const at::Scalar & other); +TORCH_API at::Tensor & lt_out(at::Tensor & out, const at::Tensor & self, const at::Scalar & other); +TORCH_API at::Tensor & lt_outf(const at::Tensor & self, const at::Scalar & other, at::Tensor & out); +TORCH_API at::Tensor & lt_(at::Tensor & self, const at::Scalar & other); +TORCH_API at::Tensor lt(const at::Tensor & self, const at::Tensor & other); +TORCH_API at::Tensor & lt_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & other); +TORCH_API at::Tensor & lt_outf(const at::Tensor & self, const at::Tensor & other, at::Tensor & out); +TORCH_API at::Tensor & lt_(at::Tensor & self, const at::Tensor & other); + +} // namespace cuda +} // namespace at diff --git a/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/miopen_rnn_native.h b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/miopen_rnn_native.h new file mode 100644 index 0000000000000000000000000000000000000000..90aa9800cd8ec98ddddcb50dc55bc696e340296b --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/miopen_rnn_native.h @@ -0,0 +1,22 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API ::std::tuple miopen_rnn_out(const at::Tensor & input, at::TensorList weight, int64_t weight_stride0, const at::Tensor & hx, const c10::optional & cx, int64_t mode, int64_t hidden_size, int64_t num_layers, bool batch_first, double dropout, bool train, bool bidirectional, at::IntArrayRef batch_sizes, const c10::optional & dropout_state, at::Tensor & out0, at::Tensor & out1, at::Tensor & out2, at::Tensor & out3, at::Tensor & out4); +TORCH_API ::std::tuple miopen_rnn(const at::Tensor & input, at::TensorList weight, int64_t weight_stride0, const at::Tensor & hx, const c10::optional & cx, int64_t mode, int64_t hidden_size, int64_t num_layers, bool batch_first, double dropout, bool train, bool bidirectional, at::IntArrayRef batch_sizes, const c10::optional & dropout_state); +} // namespace native +} // namespace at diff --git a/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/mul_meta_dispatch.h b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/mul_meta_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..620bb8fd62954006b2d7873d261a5fb463cc601f --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/mul_meta_dispatch.h @@ -0,0 +1,26 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace meta { + +TORCH_API at::Tensor mul(const at::Tensor & self, const at::Tensor & other); +TORCH_API at::Tensor & mul_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & other); +TORCH_API at::Tensor & mul_outf(const at::Tensor & self, const at::Tensor & other, at::Tensor & out); +TORCH_API at::Tensor & mul_(at::Tensor & self, const at::Tensor & other); + +} // namespace meta +} // namespace at diff --git a/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/multinomial_cpu_dispatch.h b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/multinomial_cpu_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..109a7547f4804ac92d0908445b6dd5237c0ff39c --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/multinomial_cpu_dispatch.h @@ -0,0 +1,25 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cpu { + +TORCH_API at::Tensor multinomial(const at::Tensor & self, int64_t num_samples, bool replacement=false, c10::optional generator=c10::nullopt); +TORCH_API at::Tensor & multinomial_out(at::Tensor & out, const at::Tensor & self, int64_t num_samples, bool replacement=false, c10::optional generator=c10::nullopt); +TORCH_API at::Tensor & multinomial_outf(const at::Tensor & self, int64_t num_samples, bool replacement, c10::optional generator, at::Tensor & out); + +} // namespace cpu +} // namespace at diff --git a/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/neg_native.h b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/neg_native.h new file mode 100644 index 0000000000000000000000000000000000000000..1d477ddc402f8eaf3fb19a02cc320852379b6b34 --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/neg_native.h @@ -0,0 +1,31 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at { +namespace native { +struct TORCH_API structured_neg_out : public at::meta::structured_neg { +void impl(const at::Tensor & self, const at::Tensor & out); +}; +TORCH_API at::Tensor NestedTensor_neg(const at::Tensor & self); +TORCH_API at::Tensor & NestedTensor_neg_(at::Tensor & self); +TORCH_API at::Tensor neg_sparse(const at::Tensor & self); +TORCH_API at::Tensor & neg_out_sparse(const at::Tensor & self, at::Tensor & out); +TORCH_API at::Tensor & neg_sparse_(at::Tensor & self); +TORCH_API at::Tensor neg_sparse_csr(const at::Tensor & self); +TORCH_API at::Tensor & neg_sparse_csr_out(const at::Tensor & self, at::Tensor & out); +TORCH_API at::Tensor & neg_sparse_csr_(at::Tensor & self); +} // namespace native +} // namespace at diff --git a/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/new_ones_ops.h b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/new_ones_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..40a409a5ac9f4ff54dbbaac4c26e0b2578939246 --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/new_ones_ops.h @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API new_ones { + using schema = at::Tensor (const at::Tensor &, c10::SymIntArrayRef, c10::optional, c10::optional, c10::optional, c10::optional); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::new_ones") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "new_ones(Tensor self, SymInt[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor") + static at::Tensor call(const at::Tensor & self, c10::SymIntArrayRef size, c10::optional dtype, c10::optional layout, c10::optional device, c10::optional pin_memory); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, c10::SymIntArrayRef size, c10::optional dtype, c10::optional layout, c10::optional device, c10::optional pin_memory); +}; + +struct TORCH_API new_ones_out { + using schema = at::Tensor & (const at::Tensor &, c10::SymIntArrayRef, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::new_ones") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "new_ones.out(Tensor self, SymInt[] size, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, c10::SymIntArrayRef size, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, c10::SymIntArrayRef size, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/outer_compositeimplicitautograd_dispatch.h b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/outer_compositeimplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..003f5504199d476d879abb58e55317a9c07493d8 --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/outer_compositeimplicitautograd_dispatch.h @@ -0,0 +1,25 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeimplicitautograd { + +TORCH_API at::Tensor outer(const at::Tensor & self, const at::Tensor & vec2); +TORCH_API at::Tensor & outer_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & vec2); +TORCH_API at::Tensor & outer_outf(const at::Tensor & self, const at::Tensor & vec2, at::Tensor & out); + +} // namespace compositeimplicitautograd +} // namespace at diff --git a/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/pixel_unshuffle_cpu_dispatch.h b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/pixel_unshuffle_cpu_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..05fc7ecc72be5e21b4accd5f20cc0b5a9364fdf3 --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/pixel_unshuffle_cpu_dispatch.h @@ -0,0 +1,23 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cpu { + +TORCH_API at::Tensor pixel_unshuffle(const at::Tensor & self, int64_t downscale_factor); + +} // namespace cpu +} // namespace at diff --git a/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/quantize_per_tensor_cuda_dispatch.h b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/quantize_per_tensor_cuda_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..bf2635577eb4f024527e298639d848ed21f38437 --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/quantize_per_tensor_cuda_dispatch.h @@ -0,0 +1,24 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cuda { + +TORCH_API at::Tensor quantize_per_tensor(const at::Tensor & self, double scale, int64_t zero_point, at::ScalarType dtype); +TORCH_API at::Tensor quantize_per_tensor(const at::Tensor & self, const at::Tensor & scale, const at::Tensor & zero_point, at::ScalarType dtype); + +} // namespace cuda +} // namespace at diff --git a/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/repeat_interleave.h b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/repeat_interleave.h new file mode 100644 index 0000000000000000000000000000000000000000..88ffe66abdcbcc3e0ce046f73b7b6d312aa1c5cf --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/repeat_interleave.h @@ -0,0 +1,66 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::repeat_interleave.Tensor(Tensor repeats, *, int? output_size=None) -> Tensor +inline at::Tensor repeat_interleave(const at::Tensor & repeats, c10::optional output_size=c10::nullopt) { + return at::_ops::repeat_interleave_Tensor::call(repeats, output_size); +} + +// aten::repeat_interleave.self_Tensor(Tensor self, Tensor repeats, int? dim=None, *, int? output_size=None) -> Tensor +inline at::Tensor repeat_interleave(const at::Tensor & self, const at::Tensor & repeats, c10::optional dim=c10::nullopt, c10::optional output_size=c10::nullopt) { + return at::_ops::repeat_interleave_self_Tensor::call(self, repeats, dim, output_size); +} + +// aten::repeat_interleave.self_int(Tensor self, SymInt repeats, int? dim=None, *, int? output_size=None) -> Tensor +inline at::Tensor repeat_interleave(const at::Tensor & self, int64_t repeats, c10::optional dim=c10::nullopt, c10::optional output_size=c10::nullopt) { + return at::_ops::repeat_interleave_self_int::call(self, repeats, dim, output_size); +} +namespace symint { + template ::value>> + at::Tensor repeat_interleave(const at::Tensor & self, int64_t repeats, c10::optional dim=c10::nullopt, c10::optional output_size=c10::nullopt) { + return at::_ops::repeat_interleave_self_int::call(self, repeats, dim, output_size); + } +} + +// aten::repeat_interleave.self_int(Tensor self, SymInt repeats, int? dim=None, *, int? output_size=None) -> Tensor +inline at::Tensor repeat_interleave_symint(const at::Tensor & self, c10::SymInt repeats, c10::optional dim=c10::nullopt, c10::optional output_size=c10::nullopt) { + return at::_ops::repeat_interleave_self_int::call(self, repeats, dim, output_size); +} +namespace symint { + template ::value>> + at::Tensor repeat_interleave(const at::Tensor & self, c10::SymInt repeats, c10::optional dim=c10::nullopt, c10::optional output_size=c10::nullopt) { + return at::_ops::repeat_interleave_self_int::call(self, repeats, dim, output_size); + } +} + +// aten::repeat_interleave.Tensor_out(Tensor repeats, *, int? output_size=None, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & repeat_interleave_out(at::Tensor & out, const at::Tensor & repeats, c10::optional output_size=c10::nullopt) { + return at::_ops::repeat_interleave_Tensor_out::call(repeats, output_size, out); +} +// aten::repeat_interleave.Tensor_out(Tensor repeats, *, int? output_size=None, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & repeat_interleave_outf(const at::Tensor & repeats, c10::optional output_size, at::Tensor & out) { + return at::_ops::repeat_interleave_Tensor_out::call(repeats, output_size, out); +} + +} diff --git a/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/replication_pad1d_backward_meta.h b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/replication_pad1d_backward_meta.h new file mode 100644 index 0000000000000000000000000000000000000000..a7e30d1eda0df1983ecf8f6962706f11b7c8570a --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/replication_pad1d_backward_meta.h @@ -0,0 +1,27 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeMetaFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at { +namespace meta { + +struct TORCH_API structured_replication_pad1d_backward : public at::impl::MetaBase { + + + void meta(const at::Tensor & grad_output, const at::Tensor & self, at::ArrayRef padding); +}; + +} // namespace native +} // namespace at diff --git a/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/rnn_tanh_cell_native.h b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/rnn_tanh_cell_native.h new file mode 100644 index 0000000000000000000000000000000000000000..b0ee702e895eb6dc0fd65b446511f7ca0f72732f --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/rnn_tanh_cell_native.h @@ -0,0 +1,21 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor rnn_tanh_cell(const at::Tensor & input, const at::Tensor & hx, const at::Tensor & w_ih, const at::Tensor & w_hh, const c10::optional & b_ih={}, const c10::optional & b_hh={}); +} // namespace native +} // namespace at diff --git a/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/rshift.h b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/rshift.h new file mode 100644 index 0000000000000000000000000000000000000000..edb93bd66e6c9c107e8c9ab50caa58f5721c29bf --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/rshift.h @@ -0,0 +1,53 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::__rshift__.Scalar(Tensor self, Scalar other) -> Tensor +inline at::Tensor __rshift__(const at::Tensor & self, const at::Scalar & other) { + return at::_ops::__rshift___Scalar::call(self, other); +} + +// aten::__rshift__.Tensor(Tensor self, Tensor other) -> Tensor +inline at::Tensor __rshift__(const at::Tensor & self, const at::Tensor & other) { + return at::_ops::__rshift___Tensor::call(self, other); +} + +// aten::__rshift__.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & __rshift___out(at::Tensor & out, const at::Tensor & self, const at::Scalar & other) { + return at::_ops::__rshift___Scalar_out::call(self, other, out); +} +// aten::__rshift__.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & __rshift___outf(const at::Tensor & self, const at::Scalar & other, at::Tensor & out) { + return at::_ops::__rshift___Scalar_out::call(self, other, out); +} + +// aten::__rshift__.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & __rshift___out(at::Tensor & out, const at::Tensor & self, const at::Tensor & other) { + return at::_ops::__rshift___Tensor_out::call(self, other, out); +} +// aten::__rshift__.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & __rshift___outf(const at::Tensor & self, const at::Tensor & other, at::Tensor & out) { + return at::_ops::__rshift___Tensor_out::call(self, other, out); +} + +} diff --git a/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/size_native.h b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/size_native.h new file mode 100644 index 0000000000000000000000000000000000000000..094bb83d6e347676db41d567056127a9c9fa1f98 --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/size_native.h @@ -0,0 +1,22 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API int64_t size(const at::Tensor & self, int64_t dim); +TORCH_API int64_t size(const at::Tensor & self, at::Dimname dim); +} // namespace native +} // namespace at diff --git a/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/sparse_bsr_tensor_native.h b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/sparse_bsr_tensor_native.h new file mode 100644 index 0000000000000000000000000000000000000000..970c4625ef121869233fe02a3e34b04cabb0fad1 --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/sparse_bsr_tensor_native.h @@ -0,0 +1,22 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor sparse_bsr_tensor(const at::Tensor & crow_indices, const at::Tensor & col_indices, const at::Tensor & values, at::IntArrayRef size, c10::optional dtype={}, c10::optional layout={}, c10::optional device={}, c10::optional pin_memory={}); +TORCH_API at::Tensor sparse_bsr_tensor(const at::Tensor & crow_indices, const at::Tensor & col_indices, const at::Tensor & values, c10::optional dtype={}, c10::optional layout={}, c10::optional device={}, c10::optional pin_memory={}); +} // namespace native +} // namespace at diff --git a/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/sparse_compressed_tensor.h b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/sparse_compressed_tensor.h new file mode 100644 index 0000000000000000000000000000000000000000..6ed809d600a8c0a54ddd544c711d7b97f06836c5 --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/sparse_compressed_tensor.h @@ -0,0 +1,43 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::sparse_compressed_tensor.comp_plain_value_size(Tensor compressed_indices, Tensor plain_indices, Tensor values, int[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=False) -> Tensor +inline at::Tensor sparse_compressed_tensor(const at::Tensor & compressed_indices, const at::Tensor & plain_indices, const at::Tensor & values, at::IntArrayRef size, at::TensorOptions options) { + return at::_ops::sparse_compressed_tensor_comp_plain_value_size::call(compressed_indices, plain_indices, values, size, optTypeMetaToScalarType(options.dtype_opt()), options.layout_opt(), options.device_opt(), options.pinned_memory_opt()); +} +// aten::sparse_compressed_tensor.comp_plain_value_size(Tensor compressed_indices, Tensor plain_indices, Tensor values, int[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=False) -> Tensor +inline at::Tensor sparse_compressed_tensor(const at::Tensor & compressed_indices, const at::Tensor & plain_indices, const at::Tensor & values, at::IntArrayRef size, c10::optional dtype, c10::optional layout, c10::optional device, c10::optional pin_memory) { + return at::_ops::sparse_compressed_tensor_comp_plain_value_size::call(compressed_indices, plain_indices, values, size, dtype, layout, device, pin_memory); +} + +// aten::sparse_compressed_tensor.comp_plain_value(Tensor compressed_indices, Tensor plain_indices, Tensor values, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=False) -> Tensor +inline at::Tensor sparse_compressed_tensor(const at::Tensor & compressed_indices, const at::Tensor & plain_indices, const at::Tensor & values, at::TensorOptions options) { + return at::_ops::sparse_compressed_tensor_comp_plain_value::call(compressed_indices, plain_indices, values, optTypeMetaToScalarType(options.dtype_opt()), options.layout_opt(), options.device_opt(), options.pinned_memory_opt()); +} +// aten::sparse_compressed_tensor.comp_plain_value(Tensor compressed_indices, Tensor plain_indices, Tensor values, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=False) -> Tensor +inline at::Tensor sparse_compressed_tensor(const at::Tensor & compressed_indices, const at::Tensor & plain_indices, const at::Tensor & values, c10::optional dtype, c10::optional layout, c10::optional device, c10::optional pin_memory) { + return at::_ops::sparse_compressed_tensor_comp_plain_value::call(compressed_indices, plain_indices, values, dtype, layout, device, pin_memory); +} + +} diff --git a/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/sparse_dim_cuda_dispatch.h b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/sparse_dim_cuda_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..afe71efc18e10eff08190b06ad110635f5a0cc97 --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/sparse_dim_cuda_dispatch.h @@ -0,0 +1,23 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cuda { + +TORCH_API int64_t sparse_dim(const at::Tensor & self); + +} // namespace cuda +} // namespace at diff --git a/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/special_bessel_y0_meta.h b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/special_bessel_y0_meta.h new file mode 100644 index 0000000000000000000000000000000000000000..d8251bbcbf0726feb4272a2b91cab267a6a0e75f --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/special_bessel_y0_meta.h @@ -0,0 +1,27 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeMetaFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at { +namespace meta { + +struct TORCH_API structured_special_bessel_y0 : public TensorIteratorBase { + + + void meta(const at::Tensor & self); +}; + +} // namespace native +} // namespace at diff --git a/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/special_erfc_native.h b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/special_erfc_native.h new file mode 100644 index 0000000000000000000000000000000000000000..464e8b2a83f2d67ee74937d996c8e1f88cba5614 --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/special_erfc_native.h @@ -0,0 +1,22 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor special_erfc(const at::Tensor & self); +TORCH_API at::Tensor & special_erfc_out(const at::Tensor & self, at::Tensor & out); +} // namespace native +} // namespace at diff --git a/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/special_modified_bessel_k0_compositeexplicitautogradnonfunctional_dispatch.h b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/special_modified_bessel_k0_compositeexplicitautogradnonfunctional_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..0207b570537da2f4761aa29146312be579cd3cc6 --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/special_modified_bessel_k0_compositeexplicitautogradnonfunctional_dispatch.h @@ -0,0 +1,23 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautogradnonfunctional { + +TORCH_API at::Tensor special_modified_bessel_k0(const at::Tensor & self); + +} // namespace compositeexplicitautogradnonfunctional +} // namespace at diff --git a/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/special_xlog1py_cpu_dispatch.h b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/special_xlog1py_cpu_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..aab514614b0fd695284dcceb50e1b1b9dc537c5f --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/special_xlog1py_cpu_dispatch.h @@ -0,0 +1,25 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cpu { + +TORCH_API at::Tensor special_xlog1py(const at::Tensor & self, const at::Tensor & other); +TORCH_API at::Tensor & special_xlog1py_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & other); +TORCH_API at::Tensor & special_xlog1py_outf(const at::Tensor & self, const at::Tensor & other, at::Tensor & out); + +} // namespace cpu +} // namespace at diff --git a/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/split_with_sizes_copy_ops.h b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/split_with_sizes_copy_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..a5c756bb9dd3d57031787b33210ce791b98aa3ed --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/split_with_sizes_copy_ops.h @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API split_with_sizes_copy { + using schema = ::std::vector (const at::Tensor &, c10::SymIntArrayRef, int64_t); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::split_with_sizes_copy") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "split_with_sizes_copy(Tensor self, SymInt[] split_sizes, int dim=0) -> Tensor[]") + static ::std::vector call(const at::Tensor & self, c10::SymIntArrayRef split_sizes, int64_t dim); + static ::std::vector redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, c10::SymIntArrayRef split_sizes, int64_t dim); +}; + +struct TORCH_API split_with_sizes_copy_out { + using schema = void (const at::Tensor &, c10::SymIntArrayRef, int64_t, at::TensorList); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::split_with_sizes_copy") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "split_with_sizes_copy.out(Tensor self, SymInt[] split_sizes, int dim=0, *, Tensor(a!)[] out) -> ()") + static void call(const at::Tensor & self, c10::SymIntArrayRef split_sizes, int64_t dim, at::TensorList out); + static void redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, c10::SymIntArrayRef split_sizes, int64_t dim, at::TensorList out); +}; + +}} // namespace at::_ops diff --git a/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/to_sparse_cuda_dispatch.h b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/to_sparse_cuda_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..51b29fc3c7cb19c326f024836149b79ca0b8ee0a --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/to_sparse_cuda_dispatch.h @@ -0,0 +1,24 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cuda { + +TORCH_API at::Tensor to_sparse(const at::Tensor & self, int64_t sparse_dim); +TORCH_API at::Tensor to_sparse(const at::Tensor & self, c10::optional layout=c10::nullopt, at::OptionalIntArrayRef blocksize=c10::nullopt, c10::optional dense_dim=c10::nullopt); + +} // namespace cuda +} // namespace at diff --git a/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/tril.h b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/tril.h new file mode 100644 index 0000000000000000000000000000000000000000..03235d1133ab56accc964e0f1c386fa421c29994 --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/tril.h @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::tril.out(Tensor self, int diagonal=0, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & tril_out(at::Tensor & out, const at::Tensor & self, int64_t diagonal=0) { + return at::_ops::tril_out::call(self, diagonal, out); +} +// aten::tril.out(Tensor self, int diagonal=0, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & tril_outf(const at::Tensor & self, int64_t diagonal, at::Tensor & out) { + return at::_ops::tril_out::call(self, diagonal, out); +} + +// aten::tril(Tensor self, int diagonal=0) -> Tensor +inline at::Tensor tril(const at::Tensor & self, int64_t diagonal=0) { + return at::_ops::tril::call(self, diagonal); +} + +} diff --git a/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/unflatten_ops.h b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/unflatten_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..ec053291d95487bf0042c0b98c85961719ddac2e --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/unflatten_ops.h @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API unflatten_int { + using schema = at::Tensor (const at::Tensor &, int64_t, at::IntArrayRef); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::unflatten") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "int") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "unflatten.int(Tensor(a) self, int dim, int[] sizes) -> Tensor(a)") + static at::Tensor call(const at::Tensor & self, int64_t dim, at::IntArrayRef sizes); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, int64_t dim, at::IntArrayRef sizes); +}; + +struct TORCH_API unflatten_Dimname { + using schema = at::Tensor (const at::Tensor &, at::Dimname, at::IntArrayRef, at::DimnameList); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::unflatten") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Dimname") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "unflatten.Dimname(Tensor(a) self, Dimname dim, int[] sizes, Dimname[] names) -> Tensor(a)") + static at::Tensor call(const at::Tensor & self, at::Dimname dim, at::IntArrayRef sizes, at::DimnameList names); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::Dimname dim, at::IntArrayRef sizes, at::DimnameList names); +}; + +}} // namespace at::_ops diff --git a/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/unfold_backward_cuda_dispatch.h b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/unfold_backward_cuda_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..1cc60e3df1507abb4cbd9e14fec6e484540eb44e --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/unfold_backward_cuda_dispatch.h @@ -0,0 +1,24 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cuda { + +TORCH_API at::Tensor unfold_backward(const at::Tensor & grad_in, at::IntArrayRef input_sizes, int64_t dim, int64_t size, int64_t step); +TORCH_API at::Tensor unfold_backward_symint(const at::Tensor & grad_in, c10::SymIntArrayRef input_sizes, int64_t dim, int64_t size, int64_t step); + +} // namespace cuda +} // namespace at diff --git a/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/unfold_ops.h b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/unfold_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..5a22c9c71441ac2cfb17298e96ddf6d95d1efd9f --- /dev/null +++ b/openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/unfold_ops.h @@ -0,0 +1,28 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API unfold { + using schema = at::Tensor (const at::Tensor &, int64_t, int64_t, int64_t); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::unfold") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "unfold(Tensor(a) self, int dimension, int size, int step) -> Tensor(a)") + static at::Tensor call(const at::Tensor & self, int64_t dimension, int64_t size, int64_t step); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, int64_t dimension, int64_t size, int64_t step); +}; + +}} // namespace at::_ops diff --git a/phi4/lib/python3.10/site-packages/transformers/models/mllama/__pycache__/__init__.cpython-310.pyc b/phi4/lib/python3.10/site-packages/transformers/models/mllama/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f0b08a6dc796753aeb1974e9c4ecd1911f482223 Binary files /dev/null and b/phi4/lib/python3.10/site-packages/transformers/models/mllama/__pycache__/__init__.cpython-310.pyc differ diff --git a/phi4/lib/python3.10/site-packages/transformers/models/mllama/__pycache__/configuration_mllama.cpython-310.pyc b/phi4/lib/python3.10/site-packages/transformers/models/mllama/__pycache__/configuration_mllama.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2df621548e8d51866572ba339429b111408cdd2b Binary files /dev/null and b/phi4/lib/python3.10/site-packages/transformers/models/mllama/__pycache__/configuration_mllama.cpython-310.pyc differ diff --git a/phi4/lib/python3.10/site-packages/transformers/models/mllama/__pycache__/image_processing_mllama.cpython-310.pyc b/phi4/lib/python3.10/site-packages/transformers/models/mllama/__pycache__/image_processing_mllama.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3f78e5c47dc127f186fcd1cb853c9944552ea9f2 Binary files /dev/null and b/phi4/lib/python3.10/site-packages/transformers/models/mllama/__pycache__/image_processing_mllama.cpython-310.pyc differ diff --git a/phi4/lib/python3.10/site-packages/transformers/models/mllama/__pycache__/modeling_mllama.cpython-310.pyc b/phi4/lib/python3.10/site-packages/transformers/models/mllama/__pycache__/modeling_mllama.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8c71574d661bd7e4850ca138aae1fd9592d2e244 Binary files /dev/null and b/phi4/lib/python3.10/site-packages/transformers/models/mllama/__pycache__/modeling_mllama.cpython-310.pyc differ diff --git a/phi4/lib/python3.10/site-packages/transformers/models/mllama/__pycache__/processing_mllama.cpython-310.pyc b/phi4/lib/python3.10/site-packages/transformers/models/mllama/__pycache__/processing_mllama.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4b3a2cb7da55c73d7816a18b62fd12866a1c42ba Binary files /dev/null and b/phi4/lib/python3.10/site-packages/transformers/models/mllama/__pycache__/processing_mllama.cpython-310.pyc differ diff --git a/phi4/lib/python3.10/site-packages/transformers/models/mllama/configuration_mllama.py b/phi4/lib/python3.10/site-packages/transformers/models/mllama/configuration_mllama.py new file mode 100644 index 0000000000000000000000000000000000000000..fc655c9944ebd46c71f940a388bf5f87980e1ba8 --- /dev/null +++ b/phi4/lib/python3.10/site-packages/transformers/models/mllama/configuration_mllama.py @@ -0,0 +1,370 @@ +# coding=utf-8 +# Copyright 2024 HuggingFace Inc. team. All rights reserved. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Mllama model configuration""" + +from typing import Dict, List, Optional + +from ...configuration_utils import PretrainedConfig +from ...modeling_rope_utils import rope_config_validation +from ...utils import logging + + +logger = logging.get_logger(__name__) + + +class MllamaVisionConfig(PretrainedConfig): + r""" + This is the configuration class to store the configuration of a [`MllamaVisionModel`]. It is used to instantiate an + Mllama vision model according to the specified arguments, defining the model architecture. Instantiating a configuration + with the defaults will yield a similar configuration to that of the Mllama-11B. + + e.g. [meta-llama/Llama-3.2-11B-Vision](https://huggingface.co/meta-llama/Llama-3.2-11B-Vision) + + Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the + documentation from [`PretrainedConfig`] for more information. + + Args: + hidden_size (`int`, *optional*, defaults to 1280): + Dimensionality of the encoder layers and the pooler layer. + hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`): + The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`, + `"relu"`, `"selu"` and `"gelu_new"` `"quick_gelu"` are supported. + num_hidden_layers (`int`, *optional*, defaults to 32): + Number of hidden layers in the Transformer encoder. + num_global_layers (`int`, *optional*, defaults to 8): + Number of global layers in the Transformer encoder. + Vision model has a second transformer encoder, called global. + num_attention_heads (`int`, *optional*, defaults to 16): + Number of attention heads for each attention layer in the Transformer encoder. + num_channels (`int`, *optional*, defaults to 3): + Number of channels in the input image. + intermediate_size (`int`, *optional*, defaults to 5120): + Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder. + vision_output_dim (`int`, *optional*, defaults to 7680): + Dimensionality of the vision model output. Includes output of transformer + encoder with intermediate layers and global transformer encoder. + image_size (`int`, *optional*, defaults to 448): + The size (resolution) of each image *tile*. + patch_size (`int`, *optional*, defaults to 14): + The size (resolution) of each patch. + norm_eps (`float`, *optional*, defaults to 1e-05): + The epsilon used by the layer normalization layers. + max_num_tiles (`int`, *optional*, defaults to 4): + Maximum number of tiles for image splitting. + intermediate_layers_indices (`List[int]`, *optional*, defaults to [3, 7, 15, 23, 30]): + Indices of intermediate layers of transformer encoder from which to extract and output features. + These output features are concatenated with final hidden state of transformer encoder. + supported_aspect_ratios (`List[List[int]]`, *optional*): + List of supported aspect ratios for image splitting. If not specified, the default supported aspect ratios + are [[1, 1], [1, 2], [1, 3], [1, 4], [2, 1], [2, 2], [3, 1], [4, 1]] for `max_num_tiles=4`. + initializer_range (`float`, *optional*, defaults to 0.02): + The standard deviation of the truncated_normal_initializer for initializing all weight matrices. + + Example: + + ```python + >>> from transformers import MllamaVisionConfig, MllamaVisionModel + + >>> # Initializing a Llama config + >>> config = MllamaVisionConfig() + + >>> # Initializing a vision model from the mllama-11b style configuration + >>> model = MllamaVisionModel(config) + + >>> # Accessing the model configuration + >>> configuration = model.config + ```""" + + model_type = "mllama_vision_model" + base_config_key = "vision_config" + + def __init__( + self, + hidden_size: int = 1280, + hidden_act: str = "gelu", + num_hidden_layers: int = 32, + num_global_layers: int = 8, + num_attention_heads: int = 16, + num_channels: int = 3, + intermediate_size: int = 5120, + vision_output_dim: int = 7680, + image_size: int = 448, + patch_size: int = 14, + norm_eps: float = 1e-5, + max_num_tiles: int = 4, + intermediate_layers_indices: Optional[List[int]] = None, + supported_aspect_ratios: Optional[List[List[int]]] = None, + initializer_range: float = 0.02, + **kwargs, + ): + if supported_aspect_ratios is None: + if max_num_tiles != 4: + raise ValueError("max_num_tiles must be 4 for default supported aspect ratios") + supported_aspect_ratios = [[1, 1], [1, 2], [1, 3], [1, 4], [2, 1], [2, 2], [3, 1], [4, 1]] + + if intermediate_layers_indices is None: + intermediate_layers_indices = [3, 7, 15, 23, 30] + + self.hidden_size = hidden_size + self.hidden_act = hidden_act + self.num_hidden_layers = num_hidden_layers + self.num_channels = num_channels + self.intermediate_size = intermediate_size + self.image_size = image_size + self.vision_output_dim = vision_output_dim + self.patch_size = patch_size + self.intermediate_layers_indices = intermediate_layers_indices + self.num_global_layers = num_global_layers + self.max_num_tiles = max_num_tiles + self.norm_eps = norm_eps + self.attention_heads = num_attention_heads + self.supported_aspect_ratios = supported_aspect_ratios + self.initializer_range = initializer_range + super().__init__(**kwargs) + + @property + def max_aspect_ratio_id(self) -> int: + return len(self.supported_aspect_ratios) + + +class MllamaTextConfig(PretrainedConfig): + r""" + This is the configuration class to store the configuration of a [`MllamaTextModel`]. It is used to instantiate an + Mllama text model according to the specified arguments, defining the model architecture. Instantiating a configuration + with the defaults will yield a similar configuration to that of the Mllama-11B. + + e.g. [meta-llama/Llama-3.2-11B-Vision](https://huggingface.co/meta-llama/Llama-3.2-11B-Vision) + + Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the + documentation from [`PretrainedConfig`] for more information. + + Args: + vocab_size (`int`, *optional*, defaults to 128256): + Vocabulary size of the Mllama text model. Defines the maximum number of different tokens that can be represented + by the `inputs_ids` passed when calling [`MllamaTextModel`]. + hidden_size (`int`, *optional*, defaults to 4096): + Dimensionality of the embeddings and hidden states. + hidden_act (`str` or `Callable`, *optional*, defaults to `"silu"`): + The non-linear activation function (function or string) in the encoder and pooler. + num_hidden_layers (`int`, *optional*, defaults to 40): + Number of hidden layers in the Transformer encoder. + num_attention_heads (`int`, *optional*, defaults to 32): + Number of attention heads for each attention layer in the Transformer encoder. + num_key_value_heads (`int`, *optional*, defaults to 8): + This is the number of key_value heads that should be used to implement Grouped Query Attention. If not + specified, will default to `num_attention_heads`. + intermediate_size (`int`, *optional*, defaults to 14336): + Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder. + rope_theta (`float`, *optional*, defaults to `500000.0`): + The base period of the RoPE embeddings. + rope_scaling (`Dict`, *optional*): + Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type + and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value + accordingly. + Expected contents: + `rope_type` (`str`): + The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope', + 'llama3'], with 'default' being the original RoPE implementation. + `factor` (`float`, *optional*): + Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In + most scaling types, a `factor` of x will enable the model to handle sequences of length x * + original maximum pre-trained length. + `original_max_position_embeddings` (`int`, *optional*): + Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during + pretraining. + `attention_factor` (`float`, *optional*): + Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention + computation. If unspecified, it defaults to value recommended by the implementation, using the + `factor` field to infer the suggested value. + `beta_fast` (`float`, *optional*): + Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear + ramp function. If unspecified, it defaults to 32. + `beta_slow` (`float`, *optional*): + Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear + ramp function. If unspecified, it defaults to 1. + `short_factor` (`List[float]`, *optional*): + Only used with 'longrope'. The scaling factor to be applied to short contexts (< + `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden + size divided by the number of attention heads divided by 2 + `long_factor` (`List[float]`, *optional*): + Only used with 'longrope'. The scaling factor to be applied to long contexts (< + `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden + size divided by the number of attention heads divided by 2 + `low_freq_factor` (`float`, *optional*): + Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE + `high_freq_factor` (`float`, *optional*): + Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE + rms_norm_eps (`float`, *optional*, defaults to 1e-05): + The epsilon used by the rms normalization layers. + max_position_embeddings (`int`, *optional*, defaults to 131072): + The maximum sequence length that this model might ever be used with. + initializer_range (`float`, *optional*, defaults to 0.02): + The standard deviation of the truncated_normal_initializer for initializing all weight matrices. + use_cache (`bool`, *optional*, defaults to `True`): + Whether or not the model should return the last key/values attentions. + tie_word_embeddings (`bool`, *optional*, defaults to `False`): + Whether to tie weight embeddings + cross_attention_layers (`List[int]`, *optional*): + Indices of the cross attention layers. If not specified, will default to [3, 8, 13, 18, 23, 28, 33, 38]. + dropout (`float`, *optional*, defaults to 0): + The dropout probability for self- and cross-attention layers. + bos_token_id (`int`, *optional*, defaults to 128000): + The id of the beginning of sentence token. + eos_token_id (`int`, *optional*, defaults to 128001): + The id of the end of sentence token. + pad_token_id (`int`, *optional*, defaults to 128004): + The id of the padding token. + + Example: + + ```python + >>> from transformers import MllamaTextModel, MllamaTextConfig + + >>> # Initializing a Mllama text config + >>> config = MllamaTextConfig() + + >>> # Initializing a model from the Mllama text configuration + >>> model = MllamaTextModel(config) + + >>> # Accessing the model configuration + >>> configuration = model.config + ```""" + + model_type = "mllama_text_model" + base_config_key = "text_config" + + def __init__( + self, + vocab_size: int = 128256, + hidden_size: int = 4096, + hidden_act: str = "silu", + num_hidden_layers: int = 40, + num_attention_heads: int = 32, + num_key_value_heads: int = 8, + intermediate_size: int = 14_336, + rope_theta: float = 500_000, + rope_scaling: Optional[Dict] = None, + rms_norm_eps: float = 1e-5, + max_position_embeddings: int = 131_072, + initializer_range: float = 0.02, + use_cache: bool = True, + tie_word_embeddings: bool = False, + cross_attention_layers: Optional[List[int]] = None, + dropout: float = 0, + bos_token_id: int = 128000, + eos_token_id: int = 128001, + pad_token_id: Optional[int] = 128004, + **kwargs, + ): + if cross_attention_layers is None: + cross_attention_layers = [3, 8, 13, 18, 23, 28, 33, 38] + + self.vocab_size = vocab_size + self.num_hidden_layers = num_hidden_layers + self.cross_attention_layers = cross_attention_layers + self.hidden_size = hidden_size + self.num_attention_heads = num_attention_heads + self.num_key_value_heads = num_key_value_heads + self.initializer_range = initializer_range + self.use_cache = use_cache + self.rope_theta = rope_theta + self.rms_norm_eps = rms_norm_eps + self.intermediate_size = intermediate_size + self.dropout = dropout + self.hidden_act = hidden_act + self.rope_scaling = rope_scaling + self.max_position_embeddings = max_position_embeddings + rope_config_validation(self) + + super().__init__( + pad_token_id=pad_token_id, + bos_token_id=bos_token_id, + eos_token_id=eos_token_id, + tie_word_embeddings=tie_word_embeddings, + **kwargs, + ) + + +class MllamaConfig(PretrainedConfig): + r""" + This is the configuration class to store the configuration of a [`MllamaForConditionalGeneration`]. It is used to instantiate an + Mllama model according to the specified arguments, defining the model architecture. Instantiating a configuration + with the defaults will yield a similar configuration to that of the Mllama-9B. + + e.g. [meta-llama/Llama-3.2-11B-Vision](https://huggingface.co/meta-llama/Llama-3.2-11B-Vision) + + Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the + documentation from [`PretrainedConfig`] for more information. + + Args: + vision_config (`Union[AutoConfig, dict]`, *optional*, defaults to `MllamaVisionConfig`): + The config object or dictionary of the vision backbone. + text_config (`Union[AutoConfig, dict]`, *optional*, defaults to `MllamaTextConfig`): + The config object or dictionary of the text backbone. + image_token_index (`int`, *optional*, defaults to 128256): + The image token index to encode the image prompt. + + Example: + + ```python + >>> from transformers import MllamaForConditionalGeneration, MllamaConfig, MllamaVisionConfig, MllamaTextConfig + + >>> # Initializing a CLIP-vision config + >>> vision_config = MllamaVisionConfig() + + >>> # Initializing a Llama config + >>> text_config = MllamaTextConfig() + + >>> # Initializing a mllama-11b style configuration + >>> configuration = MllamaConfig(vision_config, text_config) + + >>> # Initializing a model from the mllama-11b style configuration + >>> model = MllamaForConditionalGeneration(configuration) + + >>> # Accessing the model configuration + >>> configuration = model.config + ```""" + + model_type = "mllama" + sub_configs = {"text_config": MllamaTextConfig, "vision_config": MllamaVisionConfig} + + def __init__( + self, + vision_config=None, + text_config=None, + image_token_index=128256, + **kwargs, + ): + if vision_config is None: + self.vision_config = MllamaVisionConfig() + logger.info("vision_config is None, using default mllama vision config") + elif isinstance(vision_config, dict): + self.vision_config = MllamaVisionConfig(**vision_config) + elif isinstance(vision_config, MllamaVisionConfig): + self.vision_config = vision_config + + self.image_token_index = image_token_index + + if text_config is None: + self.text_config = MllamaTextConfig() + logger.info("text_config is None, using default mllama text config") + elif isinstance(text_config, dict): + self.text_config = MllamaTextConfig(**text_config) + elif isinstance(text_config, MllamaTextConfig): + self.text_config = text_config + + super().__init__(**kwargs) + + +__all__ = ["MllamaConfig"] diff --git a/phi4/lib/python3.10/site-packages/transformers/models/mllama/image_processing_mllama.py b/phi4/lib/python3.10/site-packages/transformers/models/mllama/image_processing_mllama.py new file mode 100644 index 0000000000000000000000000000000000000000..3c85258967262571353e1999875e54526920d8bb --- /dev/null +++ b/phi4/lib/python3.10/site-packages/transformers/models/mllama/image_processing_mllama.py @@ -0,0 +1,933 @@ +# coding=utf-8 +# Copyright 2024 The HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import math +from functools import lru_cache +from typing import Dict, List, Optional, Tuple, Union + +import numpy as np + +from ...image_processing_utils import BaseImageProcessor, BatchFeature +from ...image_transforms import ( + PaddingMode, + get_image_size, + pad, + resize, +) +from ...image_utils import ( + IMAGENET_STANDARD_MEAN, + IMAGENET_STANDARD_STD, + ChannelDimension, + ImageInput, + PILImageResampling, + infer_channel_dimension_format, + is_valid_image, + is_vision_available, + to_numpy_array, + validate_preprocess_arguments, +) +from ...utils import TensorType, logging + + +if is_vision_available(): + import PIL + from PIL import Image + + +logger = logging.get_logger(__name__) + + +@lru_cache(maxsize=10) +def get_all_supported_aspect_ratios(max_image_tiles: int) -> List[Tuple[int, int]]: + """ + Computes all allowed aspect ratios for a given maximum number of input tiles. + + This function calculates all possible arrangements of tiles that can be formed + within the constraint of the maximum number of tiles. Each arrangement is + represented by its aspect ratio (width/height) and the corresponding tile configuration. + + Args: + max_image_tiles (`int`): + The maximum number of tiles allowed. + + Returns: + `List[Tuple[int, int]]`: A list of tuples, each tuple representing a valid (width, height) + configuration in terms of number of tiles. + + Example: + >>> get_all_supported_aspect_ratios(4) + [(1, 1), (1, 2), (1, 3), (1, 4), (2, 1), (2, 2), (3, 1), (4, 1)] + + """ + aspect_ratios = [] + for width in range(1, max_image_tiles + 1): + for height in range(1, max_image_tiles + 1): + if width * height <= max_image_tiles: + aspect_ratios.append((width, height)) + return aspect_ratios + + +def get_image_size_fit_to_canvas( + image_height: int, + image_width: int, + canvas_height: int, + canvas_width: int, + tile_size: int, +) -> Tuple[int, int]: + """ + Calculates the new size of an image to fit within a canvas while maintaining aspect ratio. + + This function calculates the optimal size for an image to fit within a canvas defined by + canvas_height and canvas_width, while ensuring that the image dimensions are not smaller than + tile_size. If the image is larger than the canvas, the returned size will fit within the canvas. + If the image already fits within the canvas, the size remains unchanged. + The aspect ratio of the original image is preserved. + + Args: + image_height (`int`): + The height of the original image. + image_width (`int`): + The width of the original image. + canvas_height (`int`): + The height of the canvas. + canvas_width (`int`): + The width of the canvas. + tile_size (`int`): + The tile size. + + Returns: + `Tuple[int, int]`: A tuple containing the new height and width of the image. + + """ + # Set target image size in between `tile_size` and canvas_size + target_width = np.clip(image_width, tile_size, canvas_width) + target_height = np.clip(image_height, tile_size, canvas_height) + + scale_h = target_height / image_height + scale_w = target_width / image_width + + if scale_w < scale_h: + new_width = target_width + new_height = min(math.floor(image_height * scale_w), target_height) + else: + new_height = target_height + new_width = min(math.floor(image_width * scale_h), target_width) + + return new_height, new_width + + +@lru_cache(maxsize=100) +def get_optimal_tiled_canvas( + image_height: int, + image_width: int, + max_image_tiles: int, + tile_size: int, +) -> Tuple[int, int]: + r""" + Determines the best canvas based on image and tile size and maximum number of tiles. + + First, calculates possible resolutions based on the maximum number of tiles and tile size. + For example for max_image_tiles=2, tile_size=100, possible tile arrangements are: + [(1, 1), (1, 2), (2, 1)] and corresponding canvas sizes are: + [(100, 100), (100, 200), (200, 100)] + + For each possible resolution, calculates the scaling factors for + width and height, and selects the smallest one, which is the limiting side. + E.g. to match the canvas you can upscale height by 2x, and width by 1.5x, + therefore, the maximum upscaling you can do is min(2, 1.5) = 1.5. + + If upscaling is possible (any of the scaling factors is greater than 1), + then picks the smallest upscaling factor > 1. + + If upscaling is not possible, then picks the largest scaling factor <= 1, i.e. + reduce downscaling as much as possible. + + If there are multiple resolutions with the same max scale, we pick the one with the lowest area, + to minimize padding. E.g., the same image can be upscaled to 224x224 and 224x448, but the latter + has more padding. + + Example of canvases made from tiles: + + To visualize how the image can fit onto different tile grids, let's try fitting an ASCII cat into the tiles. + + Here's an ASCII cat image you want to fit into the tiles: + + /\_/\ + ( o.o ) + > ^ < + + If `num_tiles=6`, possible tile grids would look like this: + + **2x3 Canvas (2 tiles wide, 3 tiles tall)**: -> total of 6 tiles + +-------+-------+ + | /\_/\ | 0 | <- Cat image split across two tiles horizontally + +-------+-------+ + | > ^ < | 0 | <- Remaining part of the cat occupies the left tile + +-------+-------+ + |( o.o )| 0 | + +-------+-------+ + + **3x2 Canvas (3 tiles wide, 2 tiles tall)**: -> total of 6 tiles + +-------+-------+-------+ + | /\_/\ |( o.o )| 0 | <- Cat image occupies the first two tiles, 1 tile remains empty + +-------+-------+-------+ + | > ^ < | 0 | 0 | <- Remaining part of the cat occupies the left tile + +-------+-------+-------+ + + **1x6 Canvas (1 tile wide, 6 tiles tall)**: -> total of 6 tiles + +-------+ + | /\_/\ | <- Top part of the cat + +-------+ + |( o.o )| <- Middle part of the cat + +-------+ + | > ^ < | <- Bottom part of the cat + +-------+ + | 0 | + +-------+ + | 0 | + +-------+ + | 0 | + +-------+ + + Given that the tiles you get depend on the chosen aspect ratio, you have to add + embedding in the modeling code to help it know if it got a 3x2 or a 1x6 or a 2x3 + aspect ratio. + + The function tests these arrangements to find the smallest canvas where the image fits. + If multiple canvases fit, it selects the one where the dimensions are closest to the image size. + + In this case the first canvas is the closest to the original image. + + You then feed all of the tiles to the model: + + +-------+-------+-------+-------+-------+-------+ + - | /\_/\ |( o.o )| > ^ < | 0 | 0 | 0 | <- Last canvas + +-------+-------+-------+-------+-------+-------+ + + +-------+-------+-------+-------+-------+-------+ + - | /\_/\ | 0 |( o.o )| 0 | > ^ < | 0 | <- First canvas + +-------+-------+-------+-------+-------+-------+ + + +-------+-------+-------+-------+-------+-------+ + - | /\_/\ |( o.o )| 0 | > ^ < | 0 | 0 | <- second canvas + +-------+-------+-------+-------+-------+-------+ + + For each tile, you have num_channels (usually RGB so 3), tile_width, tile_height + + Args: + image_height (`int`): + The height of the image. + image_width (`int`): + The width of the image. + max_image_tiles (`int`): + The maximum number of tiles any image can be split into. + tile_size (`int`): + The tile size. + + Returns: + `Tuple[int, int]`: The best canvas resolution [height, width] for the given image. + """ + possible_tile_arrangements = get_all_supported_aspect_ratios(max_image_tiles) + possible_canvas_sizes = np.array(possible_tile_arrangements) * tile_size + + # get all possible resolutions heights/widths + target_heights, target_widths = np.array(possible_canvas_sizes).T + + # get scaling factors to resize the image without distortion + scale_h = target_heights / image_height + scale_w = target_widths / image_width + + # get the min scale between width and height (limiting side -> no distortion) + scales = np.where(scale_w > scale_h, scale_h, scale_w) + + # filter only scales that allow upscaling + upscaling_options = scales[scales >= 1] + if len(upscaling_options) > 0: + selected_scale = np.min(upscaling_options) + else: + # no upscaling possible, + # get the minimum downscaling (max scale for scales<1) + downscaling_options = scales[scales < 1] + selected_scale = np.max(downscaling_options) + + # get all resolutions that support this scaling factor, + # e.g. you can upscale to 224x224, 224x448, 224x672 without distortion + chosen_canvas = possible_canvas_sizes[scales == selected_scale] + + # if there are multiple resolutions, + # get the one with minimum area to reduce padding + if len(chosen_canvas) > 1: + areas = chosen_canvas[:, 0] * chosen_canvas[:, 1] + optimal_idx = np.argmin(areas) + optimal_canvas = chosen_canvas[optimal_idx] + else: + optimal_canvas = chosen_canvas[0] + + return optimal_canvas + + +def split_to_tiles(image: np.ndarray, num_tiles_height: int, num_tiles_width: int) -> np.ndarray: + """ + Split an image into a specified number of tiles along its width and height dimensions. + + Args: + image (`np.ndarray`): + Input image with shape (num_channels, height, width). + num_tiles_height (`int`): + Number of tiles to split the image into along its height. + num_tiles_width (`int`): + Number of tiles to split the image into along its width. + + Returns: + `np.ndarray`: + Array of image tiles with shape (num_tiles_width * num_tiles_height, num_channels, tile_height, tile_width). + """ + num_channels, height, width = image.shape + tile_height = height // num_tiles_height + tile_width = width // num_tiles_width + + image = image.reshape(num_channels, num_tiles_height, tile_height, num_tiles_width, tile_width) + + # Permute to (num_tiles_height, num_tiles_width, num_channels, tile_height, tile_width) + image = image.transpose(1, 3, 0, 2, 4) + + # Reshape into the desired output shape (num_tiles_width * num_tiles_height, num_channels, tile_height, tile_width) + image = image.reshape(num_tiles_width * num_tiles_height, num_channels, tile_height, tile_width) + + return np.ascontiguousarray(image) + + +def build_aspect_ratio_mask(aspect_ratios: List[List[Tuple[int, int]]], max_image_tiles: int) -> np.ndarray: + """ + Builds a mask for the aspect ratios of the images. + + Args: + aspect_ratios (`List[List[Tuple[int, int]]]`): + A list of lists containing aspect ratios for each image in the batch. + Each aspect ratio is represented as a tuple of (width, height) in terms of number of tiles. + max_image_tiles (`int`): + The maximum number of tiles any image can be split into. + + Returns: + `np.ndarray`: A 3D numpy array of shape (batch_size, max_num_images, max_image_tiles). + The mask contains 1s for valid tiles and 0s for padding. + """ + batch_size = len(aspect_ratios) + max_num_images = max([len(row) for row in aspect_ratios]) + + aspect_ratio_mask = np.zeros((batch_size, max_num_images, max_image_tiles), dtype=np.int64) + + # Set the first tile to 1 for all aspect ratios + # because in original implementation aspect ratios are padded with (1, 1), + # but original code examples are not built to handle batches, so we might remove it later + aspect_ratio_mask[:, :, 0] = 1 + + # Set the aspect ratio mask for the rest of the tiles + for i, sample_aspect_ratios in enumerate(aspect_ratios): + for j, (num_tiles_w, num_tiles_h) in enumerate(sample_aspect_ratios): + aspect_ratio_mask[i, j, : num_tiles_w * num_tiles_h] = 1 + + return aspect_ratio_mask + + +def pack_images( + batch_images: List[List[np.ndarray]], + max_image_tiles: int, +) -> Tuple[np.ndarray, List[List[int]]]: + """ + Stack a list of lists of images with variable lengths into a numpy array, applying zero padding as needed. + Each list in the input represents a batch sample, and each image within a list is expected to be + pre-split into tiles. The resulting array will have a shape of + (batch_size, max_num_images, max_image_tiles, channels, tile_height, tile_width). + + Args: + batch_images (`List[List[np.ndarray]]`): + A list of lists of image tiles. Each inner list represents + a batch sample containing multiple images, where each image is pre-split into tiles. + The shape of each tile array is (num_tiles, channels, tile_height, tile_width). + max_image_tiles (int): + The maximum number of tiles any image was potantially split. + + Returns: + `Tuple[np.ndarray, List[List[int]]]`: A tuple containing: + - stacked_images (`np.ndarray`): + A numpy array of stacked images with shape + (batch_size, max_num_images, max_image_tiles, channels, tile_height, tile_width). + - all_num_tiles (`List[List[int]]`): + A list of lists containing the number of tiles + for each image in each batch sample. + """ + + # Determine output shape + batch_size = len(batch_images) + max_num_images = max([len(images) for images in batch_images]) + shapes = [image.shape for images in batch_images for image in images] + _, channels, tile_height, tile_width = shapes[0] + + # Initialize the stacked images array with zeros + stacked_images = np.zeros( + (batch_size, max_num_images, max_image_tiles, channels, tile_height, tile_width), + dtype=np.float32, + ) + + # Fill the stacked images array with the tiled images from the batch + all_num_tiles = [] + for i, images in enumerate(batch_images): + num_sample_tiles = [] + for j, image in enumerate(images): + num_tiles = image.shape[0] + stacked_images[i, j, :num_tiles] = image + num_sample_tiles.append(num_tiles) + all_num_tiles.append(num_sample_tiles) + + return stacked_images, all_num_tiles + + +def pack_aspect_ratios(aspect_ratios: List[List[Tuple[int, int]]], pad_value: int = 1) -> np.ndarray: + """ + Stack a list of aspect ratios into a numpy array. + + Args: + aspect_ratios (`List[List[Tuple[int, int]]]`): + A list of aspect ratios. + pad_value (`int`, *optional*, defaults to 1): + The value to pad the aspect ratios with. + + Returns: + `np.ndarray`: + The aspect ratios stacked into a numpy array with shape (batch_size, max_num_images, 2). + """ + batch_size = len(aspect_ratios) + max_num_images = max([len(row) for row in aspect_ratios]) + + aspect_ratios_stacked = np.full((batch_size, max_num_images, 2), pad_value, dtype=np.int64) + for i, row in enumerate(aspect_ratios): + if len(row) > 0: + aspect_ratios_stacked[i, : len(row)] = np.array(row) + return aspect_ratios_stacked + + +def convert_aspect_ratios_to_ids(aspect_ratios: List[List[Tuple[int, int]]], max_image_tiles: int) -> np.ndarray: + """ + Convert aspect ratio tuples to unique ids. + + For batch padding we use 0, because there might be different number of images in each batch. + The aspect ratio ids start from 1, with 1 corresponding to the first supported aspect ratio. + + Args: + aspect_ratios (`List[List[Tuple[int, int]]]`): + A list of aspect ratios for each image in the batch. + max_image_tiles (`int`): + The maximum number of tiles any image can be split into. + + Returns: + `np.ndarray`: + The aspect ratios ids as a numpy array with shape (batch_size, max_num_images). + Each id corresponds to the index of the aspect ratio in the list of supported aspect ratios, + offset by 1 (so 0 can be used for padding). + """ + + batch_size = len(aspect_ratios) + max_num_images = max([len(row) for row in aspect_ratios]) + supported_aspect_ratios = get_all_supported_aspect_ratios(max_image_tiles) + + aspect_ratios_ids = np.zeros((batch_size, max_num_images), dtype=np.int64) + for i, sample_aspect_ratios in enumerate(aspect_ratios): + for j, (num_tiles_h, num_tiles_w) in enumerate(sample_aspect_ratios): + aspect_ratios_ids[i, j] = supported_aspect_ratios.index((num_tiles_h, num_tiles_w)) + 1 + return aspect_ratios_ids + + +def to_channel_dimension_format( + image: np.ndarray, + channel_dim: Union[ChannelDimension, str], + input_channel_dim: Optional[Union[ChannelDimension, str]] = None, +) -> np.ndarray: + """ + Converts `image` to the channel dimension format specified by `channel_dim`. + + Args: + image (`numpy.ndarray`): + The image to have its channel dimension set. + channel_dim (`ChannelDimension`): + The channel dimension format to use. + input_channel_dim (`ChannelDimension`, *optional*): + The channel dimension format of the input image. If not provided, it will be inferred from the input image. + + Returns: + `np.ndarray`: + The image with the channel dimension set to `channel_dim`. + """ + if not isinstance(image, np.ndarray): + raise ValueError(f"Input image must be of type np.ndarray, got {type(image)}") + + if input_channel_dim is None: + input_channel_dim = infer_channel_dimension_format(image) + + target_channel_dim = ChannelDimension(channel_dim) + if input_channel_dim == target_channel_dim: + return image + + if target_channel_dim == ChannelDimension.FIRST: + image = image.transpose((2, 0, 1)) + elif target_channel_dim == ChannelDimension.LAST: + image = image.transpose((1, 2, 0)) + else: + raise ValueError("Unsupported channel dimension format: {}".format(channel_dim)) + + return image + + +# Copied from transformers.models.idefics2.image_processing_idefics2.convert_to_rgb +def convert_to_rgb(image: ImageInput) -> ImageInput: + """ + Converts an image to RGB format. Only converts if the image is of type PIL.Image.Image, otherwise returns the image + as is. + Args: + image (Image): + The image to convert. + """ + if not isinstance(image, PIL.Image.Image): + return image + + # `image.convert("RGB")` would only work for .jpg images, as it creates a wrong background + # for transparent images. The call to `alpha_composite` handles this case + if image.mode == "RGB": + return image + + image_rgba = image.convert("RGBA") + background = Image.new("RGBA", image_rgba.size, (255, 255, 255)) + alpha_composite = Image.alpha_composite(background, image_rgba) + alpha_composite = alpha_composite.convert("RGB") + return alpha_composite + + +# Modified from transformers.models.idefics2.image_processing_idefics2.make_list_of_images +def make_list_of_images(images: ImageInput) -> List[List[Optional[np.ndarray]]]: + """ + Convert a single image or a list of images to a list of numpy arrays. + + Args: + images (`ImageInput`): + A single image or a list of images. + + Returns: + A list of numpy arrays. + """ + # If it's a single image, convert it to a list of lists + if is_valid_image(images): + output_images = [[images]] + # If it's a list of images, it's a single batch, so convert it to a list of lists + elif isinstance(images, (list, tuple)) and is_valid_list_of_images(images): + output_images = [images] + # If it's a list of batches, it's already in the right format + elif ( + isinstance(images, (list, tuple)) + and all(isinstance(images_i, (list, tuple)) for images_i in images) + and any(is_valid_list_of_images(images_i) for images_i in images) + ): + output_images = images + else: + raise ValueError( + "Invalid input type. Must be a single image, a list of images, or a list of batches of images." + ) + return output_images + + +def is_valid_list_of_images(images: List): + return images and all(is_valid_image(image) for image in images) + + +def _validate_size(size: Dict[str, int]) -> None: + if not ("height" in size and "width" in size): + raise ValueError(f"Argument `size` must be a dictionary with keys 'height' and 'width'. Got: {size}") + if size["height"] != size["width"]: + raise ValueError(f"Argument `size` must have the same height and width, got {size}") + + +def _validate_mllama_preprocess_arguments(do_resize, size, do_pad, max_image_tiles): + if not do_pad: + raise ValueError("MllamaImageProcessor doesn't support `do_pad=False` mode.") + if not do_resize: + raise ValueError("MllamaImageProcessor doesn't support `do_resize=False` mode.") + if max_image_tiles is None or max_image_tiles <= 0: + raise ValueError(f"MllamaImageProcessor `max_image_tiles` must be a positive integer, got {max_image_tiles}.") + _validate_size(size) + + +class MllamaImageProcessor(BaseImageProcessor): + """ + Constructs a Mllama image processor. + + Args: + do_convert_rgb (`bool`, *optional*, defaults to `True`): + Whether to convert the image to RGB. This is useful if the input image is of a different format e.g. RGBA. + Only has an effect if the input image is in the PIL format. + do_resize (`bool`, *optional*, defaults to `True`): + Whether to resize the image. + size (`Dict[str, int]`, *optional*, defaults to `self.size`): + Size of the image tile. Should be a dictionary containing 'height' and 'width' keys, both with integer values. + The height and width values should be equal. + resample (`int`, *optional*, defaults to `Resampling.BILINEAR`): + Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`. Only + has an effect if `do_resize` is set to `True`. + do_rescale (`bool`, *optional*, defaults to `True`): + Whether to rescale the image. + rescale_factor (`float`, *optional*, defaults to 0.0): + Rescale factor to rescale the image by if `do_rescale` is set to `True`. + do_normalize (`bool`, *optional*, defaults to `True`): + Whether to normalize the image. + image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`): + Image mean to use for normalization. Only has an effect if `do_normalize` is set to `True`. + image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`): + Image standard deviation to use for normalization. Only has an effect if `do_normalize` is set to + `True`. + do_pad (`bool`, *optional*, defaults to `True`): + Whether or not to pad the images to the largest height and width in the batch. + max_image_tiles (`int`, *optional*, defaults to 4): + The maximum number of tiles to split the image into. + """ + + model_input_names = ["pixel_values", "num_tiles", "aspect_ratio_ids", "aspect_ratio_mask"] + + def __init__( + self, + do_convert_rgb: bool = True, + do_resize: bool = True, + size: Optional[Dict[str, int]] = None, + resample: PILImageResampling = PILImageResampling.BILINEAR, + do_rescale: bool = True, + rescale_factor: float = 1 / 255, + do_normalize: bool = True, + image_mean: Optional[Union[float, List[float]]] = None, + image_std: Optional[Union[float, List[float]]] = None, + do_pad: bool = True, + max_image_tiles: int = 4, + **kwargs, + ) -> None: + super().__init__(**kwargs) + self.do_convert_rgb = do_convert_rgb + self.do_resize = do_resize + self.size = size if size is not None else {"height": 224, "width": 224} + self.resample = resample + self.do_rescale = do_rescale + self.rescale_factor = rescale_factor + self.do_normalize = do_normalize + self.image_mean = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN + self.image_std = image_std if image_std is not None else IMAGENET_STANDARD_STD + self.do_pad = do_pad + self.max_image_tiles = max_image_tiles + + _validate_mllama_preprocess_arguments(self.do_resize, self.size, self.do_pad, self.max_image_tiles) + + def preprocess( + self, + images: ImageInput, + do_convert_rgb: Optional[bool] = None, + do_resize: Optional[bool] = None, + size: Optional[Dict[str, int]] = None, + resample: Optional[PILImageResampling] = None, + do_rescale: Optional[bool] = None, + rescale_factor: Optional[float] = None, + do_normalize: Optional[bool] = None, + image_mean: Optional[Union[float, List[float]]] = None, + image_std: Optional[Union[float, List[float]]] = None, + do_pad: Optional[bool] = None, + max_image_tiles: Optional[int] = None, + input_data_format: Optional[Union[str, ChannelDimension]] = None, + return_tensors: Optional[Union[str, TensorType]] = None, + ): + """ + Preprocess a batch of images. + + Args: + images (`ImageInput`): + A list of images to preprocess. + do_convert_rgb (`bool`, *optional*, defaults to `self.do_convert_rgb`): + Whether to convert the image to RGB. + do_resize (`bool`, *optional*, defaults to `self.do_resize`): + Whether to resize the image. + size (`Dict[str, int]`, *optional*, defaults to `self.size`): + Size of the image tile. Should be a dictionary containing 'height' and 'width' keys, both with integer values. + The height and width values should be equal. + resample (`int`, *optional*, defaults to `self.resample`): + Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`. Only + has an effect if `do_resize` is set to `True`. + do_rescale (`bool`, *optional*, defaults to `self.do_rescale`): + Whether to rescale the image. + rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`): + Rescale factor to rescale the image by if `do_rescale` is set to `True`. + do_normalize (`bool`, *optional*, defaults to `self.do_normalize`): + Whether to normalize the image. + image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`): + Image mean to use for normalization. Only has an effect if `do_normalize` is set to `True`. + image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`): + Image standard deviation to use for normalization. Only has an effect if `do_normalize` is set to + `True`. + do_pad (`bool`, *optional*, defaults to `self.do_pad`): + Whether or not to pad the images to the largest height and width in the batch. + max_image_tiles (`int`, *optional*, defaults to `self.max_image_tiles`): + The maximum number of tiles to split the image into. + input_data_format (`ChannelDimension` or `str`, *optional*): + The channel dimension format for the input image. If unset, the channel dimension format is inferred + from the input image. Can be one of: + - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format. + - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format. + - `"none"` or `ChannelDimension.NONE`: image in (height, width) format. + return_tensors (`str` or `TensorType`, *optional*): + The type of tensors to return. Can be one of: + - Unset: Return a list of `np.ndarray`. + - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`. + - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`. + - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`. + - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`. + + Returns: + `BatchFeature` of the following structure: + - **pixel_values** (`TensorType`): The preprocessed pixel values. + - **aspect_ratio_ids** (`TensorType`): The aspect ratio ids of the images. + - **num_tiles** (`List[List[int]]`): The number of tiles for each image in the batch. + """ + do_convert_rgb = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb + do_resize = do_resize if do_resize is not None else self.do_resize + size = size if size is not None else self.size + resample = resample if resample is not None else self.resample + do_rescale = do_rescale if do_rescale is not None else self.do_rescale + rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor + do_normalize = do_normalize if do_normalize is not None else self.do_normalize + image_mean = image_mean if image_mean is not None else self.image_mean + image_std = image_std if image_std is not None else self.image_std + do_pad = do_pad if do_pad is not None else self.do_pad + max_image_tiles = max_image_tiles if max_image_tiles is not None else self.max_image_tiles + + validate_preprocess_arguments( + do_rescale=do_rescale, + rescale_factor=rescale_factor, + do_normalize=do_normalize, + image_mean=image_mean, + image_std=image_std, + do_resize=do_resize, + size=size, + resample=resample, + ) + + # extra validation + _validate_mllama_preprocess_arguments(do_resize, size, do_pad, max_image_tiles) + + images_list = make_list_of_images(images) + + if self.do_convert_rgb: + images_list = [[convert_to_rgb(image) for image in images] for images in images_list] + + images_list = [[to_numpy_array(image) for image in images] for images in images_list] + + batch_images = [] + batch_aspect_ratios = [] + + # iterate over batch samples + for images in images_list: + sample_images = [] + sample_aspect_ratios = [] + + # iterate over images in a batch sample + for image in images: + # convert images to channels first format for faster processing + # LAST is slower for `pad` and not supported by `split_to_tiles` + data_format = ChannelDimension.FIRST + image = to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format) + + # do_resize=False is not supported, validated + image, aspect_ratio = self.resize( + image=image, + size=size, + resample=resample, + max_image_tiles=max_image_tiles, + input_data_format=data_format, + data_format=data_format, + ) + + # do_pad=False is not supported, validated + image = self.pad( + image=image, + size=size, + aspect_ratio=aspect_ratio, + input_data_format=data_format, + data_format=data_format, + ) + + if do_rescale: + image = self.rescale( + image=image, + scale=rescale_factor, + input_data_format=input_data_format, + data_format=data_format, + ) + + if do_normalize: + image = self.normalize( + image=image, + mean=image_mean, + std=image_std, + input_data_format=input_data_format, + data_format=data_format, + ) + + num_tiles_height, num_tiles_width = aspect_ratio + image = split_to_tiles(image, num_tiles_height, num_tiles_width) + + sample_images.append(image) + sample_aspect_ratios.append((num_tiles_height, num_tiles_width)) + + batch_images.append(sample_images) + batch_aspect_ratios.append(sample_aspect_ratios) + + images, num_tiles = pack_images(batch_images, max_image_tiles) + + aspect_ratio_ids = convert_aspect_ratios_to_ids(batch_aspect_ratios, max_image_tiles=max_image_tiles) + aspect_ratio_mask = build_aspect_ratio_mask(batch_aspect_ratios, max_image_tiles=max_image_tiles) + + # images (np.ndarray) with shape (batch_size, max_num_images, max_image_tiles, channels, tile_height, tile_width) + # aspect_ratio_ids (np.ndarray) with shape (batch_size, max_num_images) - aspect ratio ids for each image, padded to max_num_images with 0 + # num_tiles (List[List[int]]) with (batch_size, num_images_in_batch) - real number of tiles for each image, not padded + # aspect_ratio_mask (np.ndarray) with shape (batch_size, max_num_images, max_image_tiles) - number of tiles for each image, padded to max_num_images with 0 + encoded_inputs = BatchFeature( + data={ + "pixel_values": images, + "aspect_ratio_ids": aspect_ratio_ids, + "aspect_ratio_mask": aspect_ratio_mask, + }, + tensor_type=return_tensors, + ) + encoded_inputs["num_tiles"] = num_tiles + + return encoded_inputs + + def pad( + self, + image: np.ndarray, + size: Dict[str, int], + aspect_ratio: Tuple[int, int], + data_format: Optional[Union[str, ChannelDimension]] = None, + input_data_format: Optional[Union[str, ChannelDimension]] = None, + ) -> np.ndarray: + """ + Pad an image to the `size` x `aspect_ratio`. For example, if size is {height: 224, width: 224} and aspect ratio is + (1, 2), the image will be padded to 224x448. + + Args: + image (`np.ndarray`): + Image to resize. + size (`Dict[str, int]`): + Size of the output image. + aspect_ratio (`Tuple[int, int]`): + The aspect ratio of the image. + data_format (`str` or `ChannelDimension`, *optional*): + The channel dimension format of the image. If not provided, it will be the same as the input image. + input_data_format (`ChannelDimension` or `str`, *optional*): + The channel dimension format of the input image. If not provided, it will be inferred. + + Returns: + `np.ndarray`: The padded image. + """ + + _validate_size(size) + + image_height, image_width = get_image_size(image, channel_dim=input_data_format) + num_tiles_height, num_tiles_width = aspect_ratio + padded_height = num_tiles_height * size["height"] + padded_width = num_tiles_width * size["width"] + pad_size = ((0, padded_height - image_height), (0, padded_width - image_width)) + + image = pad( + image, + pad_size, + mode=PaddingMode.CONSTANT, + constant_values=0, + data_format=data_format, + input_data_format=input_data_format, + ) + + return image + + def resize( + self, + image: np.ndarray, + size: Dict[str, int], + max_image_tiles: int, + resample: PILImageResampling = PILImageResampling.BILINEAR, + data_format: Optional[Union[str, ChannelDimension]] = None, + input_data_format: Optional[Union[str, ChannelDimension]] = None, + ) -> Union[np.ndarray, Tuple[int, int]]: + """ + Resizes an image to fit within a tiled canvas while maintaining its aspect ratio. + The optimal canvas size is calculated based on the maximum number of tiles and the tile size. + + The function first determines the best tile arrangement for the image, then resizes the image + to fit within this canvas. The resized image and the number of tiles along the height and width + dimensions are returned. + + Args: + image (`np.ndarray`): + Image to resize. + size (`Dict[str, int]`): + Size of the output image. + max_image_tiles (`int`): + The maximum number of tiles to split the image into. + resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BICUBIC`): + Resampling filter to use when resizing the image. + data_format (`str` or `ChannelDimension`, *optional*): + The channel dimension format of the image. If not provided, it will be the same as the input image. + input_data_format (`ChannelDimension` or `str`, *optional*): + The channel dimension format of the input image. If not provided, it will be inferred. + + Returns: + `Union[np.ndarray, Tuple[int, int]]`: The resized image and a tuple containing the number of tiles + along the height and width dimensions. + """ + + _validate_size(size) + + image_height, image_width = get_image_size(image, channel_dim=input_data_format) + tile_size = size["height"] + + canvas_height, canvas_width = get_optimal_tiled_canvas( + image_height=image_height, + image_width=image_width, + max_image_tiles=max_image_tiles, + tile_size=tile_size, + ) + num_tiles_height = canvas_height // tile_size + num_tiles_width = canvas_width // tile_size + + new_height, new_width = get_image_size_fit_to_canvas( + image_height=image_height, + image_width=image_width, + canvas_height=canvas_height, + canvas_width=canvas_width, + tile_size=tile_size, + ) + + image = resize( + image, + (new_height, new_width), + resample=resample, + data_format=data_format, + input_data_format=input_data_format, + ) + + return image, (num_tiles_height, num_tiles_width) + + +__all__ = ["MllamaImageProcessor"] diff --git a/phi4/lib/python3.10/site-packages/transformers/models/speech_to_text/__init__.py b/phi4/lib/python3.10/site-packages/transformers/models/speech_to_text/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ec094769d4aea356895c219ee6a9b64f347890b8 --- /dev/null +++ b/phi4/lib/python3.10/site-packages/transformers/models/speech_to_text/__init__.py @@ -0,0 +1,31 @@ +# Copyright 2024 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from typing import TYPE_CHECKING + +from ...utils import _LazyModule +from ...utils.import_utils import define_import_structure + + +if TYPE_CHECKING: + from .configuration_speech_to_text import * + from .feature_extraction_speech_to_text import * + from .modeling_speech_to_text import * + from .modeling_tf_speech_to_text import * + from .processing_speech_to_text import * + from .tokenization_speech_to_text import * +else: + import sys + + _file = globals()["__file__"] + sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__) diff --git a/phi4/lib/python3.10/site-packages/transformers/models/speech_to_text/__pycache__/configuration_speech_to_text.cpython-310.pyc b/phi4/lib/python3.10/site-packages/transformers/models/speech_to_text/__pycache__/configuration_speech_to_text.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a69b27f040edc17fe9506baae343e0c74bd6e059 Binary files /dev/null and b/phi4/lib/python3.10/site-packages/transformers/models/speech_to_text/__pycache__/configuration_speech_to_text.cpython-310.pyc differ diff --git a/phi4/lib/python3.10/site-packages/transformers/models/speech_to_text/feature_extraction_speech_to_text.py b/phi4/lib/python3.10/site-packages/transformers/models/speech_to_text/feature_extraction_speech_to_text.py new file mode 100644 index 0000000000000000000000000000000000000000..56a0b859db45949ca668c39d6fda799731318aa7 --- /dev/null +++ b/phi4/lib/python3.10/site-packages/transformers/models/speech_to_text/feature_extraction_speech_to_text.py @@ -0,0 +1,300 @@ +# coding=utf-8 +# Copyright 2021 The HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" +Feature extractor class for Speech2Text +""" + +from typing import List, Optional, Union + +import numpy as np + +from ...audio_utils import mel_filter_bank, spectrogram, window_function +from ...feature_extraction_sequence_utils import SequenceFeatureExtractor +from ...feature_extraction_utils import BatchFeature +from ...utils import PaddingStrategy, TensorType, is_speech_available, logging + + +if is_speech_available(): + import torch + import torchaudio.compliance.kaldi as ta_kaldi + +logger = logging.get_logger(__name__) + + +class Speech2TextFeatureExtractor(SequenceFeatureExtractor): + r""" + Constructs a Speech2Text feature extractor. + + This feature extractor inherits from [`Speech2TextFeatureExtractor`] which contains most of the main methods. Users + should refer to this superclass for more information regarding those methods. + + This class extracts mel-filter bank features from raw speech using TorchAudio if installed or using numpy + otherwise, and applies utterance-level cepstral mean and variance normalization to the extracted features. + + Args: + feature_size (`int`, *optional*, defaults to 80): + The feature dimension of the extracted features. + sampling_rate (`int`, *optional*, defaults to 16000): + The sampling rate at which the audio files should be digitalized expressed in hertz (Hz). + num_mel_bins (`int`, *optional*, defaults to 80): + Number of Mel-frequency bins. + padding_value (`float`, *optional*, defaults to 0.0): + The value that is used to fill the padding vectors. + do_ceptral_normalize (`bool`, *optional*, defaults to `True`): + Whether or not to apply utterance-level cepstral mean and variance normalization to extracted features. + normalize_means (`bool`, *optional*, defaults to `True`): + Whether or not to zero-mean normalize the extracted features. + normalize_vars (`bool`, *optional*, defaults to `True`): + Whether or not to unit-variance normalize the extracted features. + """ + + model_input_names = ["input_features", "attention_mask"] + + def __init__( + self, + feature_size=80, + sampling_rate=16000, + num_mel_bins=80, + padding_value=0.0, + do_ceptral_normalize=True, + normalize_means=True, + normalize_vars=True, + **kwargs, + ): + super().__init__(feature_size=feature_size, sampling_rate=sampling_rate, padding_value=padding_value, **kwargs) + self.num_mel_bins = num_mel_bins + self.do_ceptral_normalize = do_ceptral_normalize + self.normalize_means = normalize_means + self.normalize_vars = normalize_vars + self.return_attention_mask = True + + if not is_speech_available(): + mel_filters = mel_filter_bank( + num_frequency_bins=256, + num_mel_filters=self.num_mel_bins, + min_frequency=20, + max_frequency=sampling_rate // 2, + sampling_rate=sampling_rate, + norm=None, + mel_scale="kaldi", + triangularize_in_mel_space=True, + ) + + self.mel_filters = np.pad(mel_filters, ((0, 1), (0, 0))) + self.window = window_function(400, "povey", periodic=False) + + def _extract_fbank_features( + self, + waveform: np.ndarray, + ) -> np.ndarray: + """ + Get mel-filter bank features using TorchAudio. Note that TorchAudio requires 16-bit signed integers as inputs + and hence the waveform should not be normalized before feature extraction. + """ + waveform = waveform * (2**15) # Kaldi compliance: 16-bit signed integers + if is_speech_available(): + waveform = torch.from_numpy(waveform).unsqueeze(0) + features = ta_kaldi.fbank(waveform, num_mel_bins=self.num_mel_bins, sample_frequency=self.sampling_rate) + features = features.numpy() + else: + waveform = np.squeeze(waveform) + features = spectrogram( + waveform, + self.window, + frame_length=400, + hop_length=160, + fft_length=512, + power=2.0, + center=False, + preemphasis=0.97, + mel_filters=self.mel_filters, + log_mel="log", + mel_floor=1.192092955078125e-07, + remove_dc_offset=True, + ).T + return features + + @staticmethod + def utterance_cmvn( + x: np.ndarray, + input_length: int, + normalize_means: Optional[bool] = True, + normalize_vars: Optional[bool] = True, + padding_value: float = 0.0, + ) -> np.ndarray: + # make sure we normalize float32 arrays + if normalize_means: + mean = x[:input_length].mean(axis=0) + x = np.subtract(x, mean) + if normalize_vars: + std = x[:input_length].std(axis=0) + x = np.divide(x, std) + + if input_length < x.shape[0]: + x[input_length:] = padding_value + + # make sure array is in float32 + x = x.astype(np.float32) + + return x + + def normalize( + self, input_features: List[np.ndarray], attention_mask: Optional[np.ndarray] = None + ) -> List[np.ndarray]: + lengths = attention_mask.sum(-1) if attention_mask is not None else [x.shape[0] for x in input_features] + return [ + self.utterance_cmvn(x, n, self.normalize_means, self.normalize_vars, self.padding_value) + for x, n in zip(input_features, lengths) + ] + + def __call__( + self, + raw_speech: Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]], + padding: Union[bool, str, PaddingStrategy] = False, + max_length: Optional[int] = None, + truncation: bool = False, + pad_to_multiple_of: Optional[int] = None, + return_tensors: Optional[Union[str, TensorType]] = None, + sampling_rate: Optional[int] = None, + return_attention_mask: Optional[bool] = None, + **kwargs, + ) -> BatchFeature: + """ + Main method to featurize and prepare for the model one or several sequence(s). + + Args: + raw_speech (`np.ndarray`, `List[float]`, `List[np.ndarray]`, `List[List[float]]`): + The sequence or batch of sequences to be padded. Each sequence can be a numpy array, a list of float + values, a list of numpy arrays or a list of list of float values. Must be mono channel audio, not + stereo, i.e. single float per timestep. + padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `True`): + Select a strategy to pad the returned sequences (according to the model's padding side and padding + index) among: + + - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single + sequence if provided). + - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum + acceptable input length for the model if that argument is not provided. + - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different + lengths). + max_length (`int`, *optional*): + Maximum length of the returned list and optionally padding length (see above). + truncation (`bool`): + Activates truncation to cut input sequences longer than *max_length* to *max_length*. + pad_to_multiple_of (`int`, *optional*): + If set will pad the sequence to a multiple of the provided value. + + This is especially useful to enable the use of Tensor Cores on NVIDIA hardware with compute capability + `>= 7.5` (Volta), or on TPUs which benefit from having sequence lengths be a multiple of 128. + return_attention_mask (`bool`, *optional*): + Whether to return the attention mask. If left to the default, will return the attention mask according + to the specific feature_extractor's default. + + [What are attention masks?](../glossary#attention-mask) + + + + For Speech2TextTransformer models, `attention_mask` should always be passed for batched inference, to + avoid subtle bugs. + + + + return_tensors (`str` or [`~utils.TensorType`], *optional*): + If set, will return tensors instead of list of python integers. Acceptable values are: + + - `'tf'`: Return TensorFlow `tf.constant` objects. + - `'pt'`: Return PyTorch `torch.Tensor` objects. + - `'np'`: Return Numpy `np.ndarray` objects. + sampling_rate (`int`, *optional*): + The sampling rate at which the `raw_speech` input was sampled. It is strongly recommended to pass + `sampling_rate` at the forward call to prevent silent errors. + padding_value (`float`, *optional*, defaults to 0.0): + The value that is used to fill the padding values / vectors. + """ + + if sampling_rate is not None: + if sampling_rate != self.sampling_rate: + raise ValueError( + f"The model corresponding to this feature extractor: {self} was trained using a sampling rate of" + f" {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled with" + f" {self.sampling_rate} and not {sampling_rate}." + ) + else: + logger.warning( + "It is strongly recommended to pass the `sampling_rate` argument to this function. " + "Failing to do so can result in silent errors that might be hard to debug." + ) + + is_batched_numpy = isinstance(raw_speech, np.ndarray) and len(raw_speech.shape) > 1 + if is_batched_numpy and len(raw_speech.shape) > 2: + raise ValueError(f"Only mono-channel audio is supported for input to {self}") + is_batched = is_batched_numpy or ( + isinstance(raw_speech, (list, tuple)) and (isinstance(raw_speech[0], (np.ndarray, tuple, list))) + ) + + if is_batched: + raw_speech = [np.asarray(speech, dtype=np.float32) for speech in raw_speech] + elif not is_batched and not isinstance(raw_speech, np.ndarray): + raw_speech = np.asarray(raw_speech, dtype=np.float32) + elif isinstance(raw_speech, np.ndarray) and raw_speech.dtype is np.dtype(np.float64): + raw_speech = raw_speech.astype(np.float32) + + # always return batch + if not is_batched: + raw_speech = [raw_speech] + + # extract fbank features + features = [self._extract_fbank_features(waveform) for waveform in raw_speech] + + # convert into correct format for padding + encoded_inputs = BatchFeature({"input_features": features}) + + padded_inputs = self.pad( + encoded_inputs, + padding=padding, + max_length=max_length, + truncation=truncation, + pad_to_multiple_of=pad_to_multiple_of, + return_attention_mask=return_attention_mask, + **kwargs, + ) + + # make sure list is in array format + input_features = padded_inputs.get("input_features") + if isinstance(input_features[0], list): + padded_inputs["input_features"] = [np.asarray(feature, dtype=np.float32) for feature in input_features] + + attention_mask = padded_inputs.get("attention_mask") + if attention_mask is not None: + padded_inputs["attention_mask"] = [np.asarray(array, dtype=np.int32) for array in attention_mask] + + # Utterance-level cepstral mean and variance normalization + if self.do_ceptral_normalize: + attention_mask = ( + np.array(attention_mask, dtype=np.int32) + if self._get_padding_strategies(padding, max_length=max_length) is not PaddingStrategy.DO_NOT_PAD + else None + ) + padded_inputs["input_features"] = self.normalize( + padded_inputs["input_features"], attention_mask=attention_mask + ) + + if return_tensors is not None: + padded_inputs = padded_inputs.convert_to_tensors(return_tensors) + + return padded_inputs + + +__all__ = ["Speech2TextFeatureExtractor"] diff --git a/phi4/lib/python3.10/site-packages/transformers/models/speech_to_text/modeling_tf_speech_to_text.py b/phi4/lib/python3.10/site-packages/transformers/models/speech_to_text/modeling_tf_speech_to_text.py new file mode 100644 index 0000000000000000000000000000000000000000..7a20e462279a90c87c78630b595835c1558dd6fa --- /dev/null +++ b/phi4/lib/python3.10/site-packages/transformers/models/speech_to_text/modeling_tf_speech_to_text.py @@ -0,0 +1,1606 @@ +# coding=utf-8 +# Copyright 2021 The Fairseq Authors and The HuggingFace Inc. team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""TensorFlow Speech2Text model.""" + +from __future__ import annotations + +import random +from typing import Optional, Tuple, Union + +import numpy as np +import tensorflow as tf + +from ...activations_tf import get_tf_activation, glu +from ...modeling_tf_outputs import ( + TFBaseModelOutput, + TFBaseModelOutputWithPastAndCrossAttentions, + TFSeq2SeqLMOutput, + TFSeq2SeqModelOutput, +) +from ...modeling_tf_utils import ( + TFCausalLanguageModelingLoss, + TFModelInputType, + TFPreTrainedModel, + TFSharedEmbeddings, + keras, + keras_serializable, + unpack_inputs, +) +from ...tf_utils import check_embeddings_within_bounds, shape_list, stable_softmax +from ...utils import ( + add_code_sample_docstrings, + add_start_docstrings, + add_start_docstrings_to_model_forward, + logging, + replace_return_docstrings, +) +from .configuration_speech_to_text import Speech2TextConfig + + +logger = logging.get_logger(__name__) + +_CONFIG_FOR_DOC = "Speech2TextConfig" +_CHECKPOINT_FOR_DOC = "facebook/s2t-small-librispeech-asr" + + +LARGE_NEGATIVE = -1e8 + + +# Copied from transformers.models.bart.modeling_tf_bart.shift_tokens_right +def shift_tokens_right(input_ids: tf.Tensor, pad_token_id: int, decoder_start_token_id: int): + pad_token_id = tf.cast(pad_token_id, input_ids.dtype) + decoder_start_token_id = tf.cast(decoder_start_token_id, input_ids.dtype) + start_tokens = tf.fill( + (shape_list(input_ids)[0], 1), tf.convert_to_tensor(decoder_start_token_id, input_ids.dtype) + ) + shifted_input_ids = tf.concat([start_tokens, input_ids[:, :-1]], -1) + # replace possible -100 values in labels by `pad_token_id` + shifted_input_ids = tf.where( + shifted_input_ids == -100, + tf.fill(shape_list(shifted_input_ids), tf.convert_to_tensor(pad_token_id, input_ids.dtype)), + shifted_input_ids, + ) + + # "Verify that `labels` has only positive values and -100" + assert_gte0 = tf.debugging.assert_greater_equal(shifted_input_ids, tf.constant(0, dtype=input_ids.dtype)) + + # Make sure the assertion op is called by wrapping the result in an identity no-op + with tf.control_dependencies([assert_gte0]): + shifted_input_ids = tf.identity(shifted_input_ids) + + return shifted_input_ids + + +# Copied from transformers.models.bart.modeling_tf_bart._make_causal_mask +def _make_causal_mask(input_ids_shape: tf.TensorShape, past_key_values_length: int = 0): + """ + Make causal mask used for bi-directional self-attention. + """ + bsz = input_ids_shape[0] + tgt_len = input_ids_shape[1] + mask = tf.ones((tgt_len, tgt_len)) * LARGE_NEGATIVE + mask_cond = tf.range(shape_list(mask)[-1]) + + mask = tf.where(mask_cond < tf.reshape(mask_cond + 1, (shape_list(mask)[-1], 1)), 0.0, mask) + + if past_key_values_length > 0: + mask = tf.concat([tf.zeros((tgt_len, past_key_values_length)), mask], axis=-1) + + return tf.tile(mask[None, None, :, :], (bsz, 1, 1, 1)) + + +# Copied from transformers.models.bart.modeling_tf_bart._expand_mask +def _expand_mask(mask: tf.Tensor, tgt_len: Optional[int] = None): + """ + Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`. + """ + src_len = shape_list(mask)[1] + tgt_len = tgt_len if tgt_len is not None else src_len + one_cst = tf.constant(1.0) + mask = tf.cast(mask, dtype=one_cst.dtype) + expanded_mask = tf.tile(mask[:, None, None, :], (1, 1, tgt_len, 1)) + + return (one_cst - expanded_mask) * LARGE_NEGATIVE + + +class TFConv1dSubsampler(keras.layers.Layer): + """ + Convolutional subsampler: a stack of 1D convolution (along temporal dimension) followed by non-linear activation + via gated linear units (https://arxiv.org/abs/1911.08460) + """ + + def __init__(self, config: Speech2TextConfig, **kwargs): + super().__init__(**kwargs) + self.config = config + self.num_layers = config.num_conv_layers + self.in_channels = config.input_feat_per_channel * config.input_channels + self.mid_channels = config.conv_channels + self.out_channels = config.d_model + self.kernel_sizes = config.conv_kernel_sizes + + self.conv_layers = [ + keras.layers.Conv1D( + filters=self.mid_channels if i < self.num_layers - 1 else self.out_channels * 2, + kernel_size=k, + strides=2, + name=f"conv_layers.{i}", + ) + for i, k in enumerate(self.kernel_sizes) + ] + + def call(self, input_features: tf.Tensor) -> tf.Tensor: + # TF Conv1D assumes Batch x Time x Channels, same as the input + hidden_states = tf.cast(input_features, tf.float32) + for i, conv in enumerate(self.conv_layers): + # equivalent to `padding=k // 2` on PT's `nn.Conv1d` + pad_len = self.kernel_sizes[i] // 2 + hidden_shapes = shape_list(hidden_states) + hidden_states = tf.concat( + ( + tf.zeros((hidden_shapes[0], pad_len, hidden_shapes[2])), + hidden_states, + tf.zeros((hidden_shapes[0], pad_len, hidden_shapes[2])), + ), + axis=1, + ) + + hidden_states = conv(hidden_states) + hidden_states = glu(hidden_states, axis=2) # GLU over the Channel dimension + return hidden_states + + def build(self, input_shape=None): + if self.built: + return + self.built = True + if getattr(self, "conv_layers", None) is not None: + for i, layer in enumerate(self.conv_layers): + with tf.name_scope(layer.name): + layer.build([None, None, self.in_channels] if i == 0 else [None, None, self.mid_channels // 2]) + + +class TFSpeech2TextSinusoidalPositionalEmbedding(keras.layers.Layer): + """This module produces sinusoidal positional embeddings of any length.""" + + def __init__(self, num_positions: int, embedding_dim: int, padding_idx: Optional[int] = None, **kwargs): + super().__init__(**kwargs) + self.offset = 2 + self.embedding_dim = embedding_dim + self.padding_idx = padding_idx + self.embedding_weights = self._get_embedding(num_positions + self.offset, embedding_dim, padding_idx) + + @staticmethod + def _get_embedding(num_embeddings: int, embedding_dim: int, padding_idx: Optional[int] = None) -> tf.Tensor: + """ + Build sinusoidal embeddings. This matches the implementation in tensor2tensor, but differs slightly from the + description in Section 3.5 of "Attention Is All You Need". + """ + half_dim = embedding_dim // 2 + emb = tf.math.log(10000.0) / (half_dim - 1) + emb = tf.math.exp(tf.range(half_dim, dtype=tf.float32) * -emb) + emb = tf.expand_dims(tf.range(num_embeddings, dtype=tf.float32), axis=1) * tf.expand_dims(emb, axis=0) + emb = tf.reshape(tf.concat([tf.math.sin(emb), tf.math.cos(emb)], axis=1), shape=[num_embeddings, -1]) + if embedding_dim % 2 == 1: + # zero pad + emb = tf.concat([emb, tf.zeros(num_embeddings, 1)], axis=1) + if padding_idx is not None: + emb = tf.concat([emb[:padding_idx, :], tf.zeros((1, tf.shape(emb)[1])), emb[padding_idx + 1 :, :]], axis=0) + return emb + + def call(self, input_ids: tf.Tensor, past_key_values_length: int = 0) -> tf.Tensor: + bsz, seq_len = shape_list(input_ids) + # Create the position ids from the input token ids. Any padded tokens remain padded. + position_ids = self.create_position_ids_from_input_ids(input_ids, self.padding_idx, past_key_values_length) + + # Matt: The PyTorch code does a lot of work to cache the embeddings, setting the cached values as a + # model attribute in the forward pass. This is extremely forbidden in TF, which wants forward calls to be + # idempotent. TF doesn't need that caching anyway, since it can just store constants during compilation, + # so we just remove all of that code. + embeddings = self._get_embedding( + self.padding_idx + 1 + seq_len + self.offset + past_key_values_length, self.embedding_dim, self.padding_idx + ) + return tf.reshape(tf.gather(embeddings, tf.reshape(position_ids, (-1,)), axis=0), (bsz, seq_len, -1)) + + @staticmethod + def create_position_ids_from_input_ids( + input_ids: tf.Tensor, padding_idx: int, past_key_values_length: Optional[int] = 0 + ) -> tf.Tensor: + """ + Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding + symbols are ignored. This is modified from fairseq's `utils.make_positions`. + + Args: + x: tf.Tensor x: + Returns: tf.Tensor + """ + mask = tf.cast(tf.math.not_equal(input_ids, padding_idx), dtype=tf.int32) + incremental_indices = (tf.math.cumsum(mask, axis=1) + past_key_values_length) * mask + return tf.cast(incremental_indices, dtype=tf.int64) + padding_idx + + +# Copied from transformers.models.bart.modeling_tf_bart.TFBartAttention with Bart->Speech2Text +class TFSpeech2TextAttention(keras.layers.Layer): + """Multi-headed attention from "Attention Is All You Need""" + + def __init__( + self, + embed_dim: int, + num_heads: int, + dropout: float = 0.0, + is_decoder: bool = False, + bias: bool = True, + **kwargs, + ): + super().__init__(**kwargs) + self.embed_dim = embed_dim + + self.num_heads = num_heads + self.dropout = keras.layers.Dropout(dropout) + self.head_dim = embed_dim // num_heads + if (self.head_dim * num_heads) != self.embed_dim: + raise ValueError( + f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}" + f" and `num_heads`: {num_heads})." + ) + self.scaling = self.head_dim**-0.5 + self.is_decoder = is_decoder + + self.k_proj = keras.layers.Dense(embed_dim, use_bias=bias, name="k_proj") + self.q_proj = keras.layers.Dense(embed_dim, use_bias=bias, name="q_proj") + self.v_proj = keras.layers.Dense(embed_dim, use_bias=bias, name="v_proj") + self.out_proj = keras.layers.Dense(embed_dim, use_bias=bias, name="out_proj") + + def _shape(self, tensor: tf.Tensor, seq_len: int, bsz: int): + return tf.transpose(tf.reshape(tensor, (bsz, seq_len, self.num_heads, self.head_dim)), (0, 2, 1, 3)) + + def call( + self, + hidden_states: tf.Tensor, + key_value_states: tf.Tensor | None = None, + past_key_value: Tuple[Tuple[tf.Tensor]] | None = None, + attention_mask: tf.Tensor | None = None, + layer_head_mask: tf.Tensor | None = None, + training: Optional[bool] = False, + ) -> Tuple[tf.Tensor, tf.Tensor | None]: + """Input shape: Batch x Time x Channel""" + + # if key_value_states are provided this layer is used as a cross-attention layer + # for the decoder + is_cross_attention = key_value_states is not None + bsz, tgt_len, embed_dim = shape_list(hidden_states) + + # get query proj + query_states = self.q_proj(hidden_states) * self.scaling + # get key, value proj + if is_cross_attention and past_key_value is not None: + # reuse k,v, cross_attentions + key_states = past_key_value[0] + value_states = past_key_value[1] + elif is_cross_attention: + # cross_attentions + key_states = self._shape(self.k_proj(key_value_states), -1, bsz) + value_states = self._shape(self.v_proj(key_value_states), -1, bsz) + elif past_key_value is not None: + # reuse k, v, self_attention + key_states = self._shape(self.k_proj(hidden_states), -1, bsz) + value_states = self._shape(self.v_proj(hidden_states), -1, bsz) + key_states = tf.concat([past_key_value[0], key_states], axis=2) + value_states = tf.concat([past_key_value[1], value_states], axis=2) + else: + # self_attention + key_states = self._shape(self.k_proj(hidden_states), -1, bsz) + value_states = self._shape(self.v_proj(hidden_states), -1, bsz) + + if self.is_decoder: + # if cross_attention save Tuple(tf.Tensor, tf.Tensor) of all cross attention key/value_states. + # Further calls to cross_attention layer can then reuse all cross-attention + # key/value_states (first "if" case) + # if uni-directional self-attention (decoder) save Tuple(tf.Tensor, tf.Tensor) of + # all previous decoder key/value_states. Further calls to uni-directional self-attention + # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case) + # if encoder bi-directional self-attention `past_key_value` is always `None` + past_key_value = (key_states, value_states) + + proj_shape = (bsz * self.num_heads, -1, self.head_dim) + query_states = tf.reshape(self._shape(query_states, tgt_len, bsz), proj_shape) + key_states = tf.reshape(key_states, proj_shape) + value_states = tf.reshape(value_states, proj_shape) + + src_len = shape_list(key_states)[1] + attn_weights = tf.matmul(query_states, key_states, transpose_b=True) + + tf.debugging.assert_equal( + shape_list(attn_weights), + [bsz * self.num_heads, tgt_len, src_len], + message=( + f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is" + f" {shape_list(attn_weights)}" + ), + ) + + if attention_mask is not None: + tf.debugging.assert_equal( + shape_list(attention_mask), + [bsz, 1, tgt_len, src_len], + message=( + f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is" + f" {shape_list(attention_mask)}" + ), + ) + + attention_mask = tf.cast(attention_mask, dtype=attn_weights.dtype) + attn_weights = tf.reshape(attn_weights, (bsz, self.num_heads, tgt_len, src_len)) + attention_mask + attn_weights = tf.reshape(attn_weights, (bsz * self.num_heads, tgt_len, src_len)) + + attn_weights = stable_softmax(attn_weights, axis=-1) + + if layer_head_mask is not None: + tf.debugging.assert_equal( + shape_list(layer_head_mask), + [self.num_heads], + message=( + f"Head mask for a single layer should be of size {(self.num_heads)}, but is" + f" {shape_list(layer_head_mask)}" + ), + ) + + attn_weights = tf.reshape(layer_head_mask, (1, -1, 1, 1)) * tf.reshape( + attn_weights, (bsz, self.num_heads, tgt_len, src_len) + ) + attn_weights = tf.reshape(attn_weights, (bsz * self.num_heads, tgt_len, src_len)) + + attn_probs = self.dropout(attn_weights, training=training) + attn_output = tf.matmul(attn_probs, value_states) + + tf.debugging.assert_equal( + shape_list(attn_output), + [bsz * self.num_heads, tgt_len, self.head_dim], + message=( + f"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is" + f" {shape_list(attn_output)}" + ), + ) + + attn_output = tf.transpose( + tf.reshape(attn_output, (bsz, self.num_heads, tgt_len, self.head_dim)), (0, 2, 1, 3) + ) + attn_output = tf.reshape(attn_output, (bsz, tgt_len, embed_dim)) + + attn_output = self.out_proj(attn_output) + attn_weights: tf.Tensor = tf.reshape(attn_weights, (bsz, self.num_heads, tgt_len, src_len)) + + return attn_output, attn_weights, past_key_value + + def build(self, input_shape=None): + if self.built: + return + self.built = True + if getattr(self, "k_proj", None) is not None: + with tf.name_scope(self.k_proj.name): + self.k_proj.build([None, None, self.embed_dim]) + if getattr(self, "q_proj", None) is not None: + with tf.name_scope(self.q_proj.name): + self.q_proj.build([None, None, self.embed_dim]) + if getattr(self, "v_proj", None) is not None: + with tf.name_scope(self.v_proj.name): + self.v_proj.build([None, None, self.embed_dim]) + if getattr(self, "out_proj", None) is not None: + with tf.name_scope(self.out_proj.name): + self.out_proj.build([None, None, self.embed_dim]) + + +class TFSpeech2TextEncoderLayer(keras.layers.Layer): + def __init__(self, config: Speech2TextConfig, **kwargs): + super().__init__(**kwargs) + self.embed_dim = config.d_model + self.self_attn = TFSpeech2TextAttention( + self.embed_dim, config.encoder_attention_heads, dropout=config.attention_dropout, name="self_attn" + ) + self.self_attn_layer_norm = keras.layers.LayerNormalization(epsilon=1e-5, name="self_attn_layer_norm") + self.dropout = keras.layers.Dropout(config.dropout) + self.activation_fn = get_tf_activation(config.activation_function) + self.activation_dropout = keras.layers.Dropout(config.activation_dropout) + self.fc1 = keras.layers.Dense(config.encoder_ffn_dim, name="fc1") + self.fc2 = keras.layers.Dense(self.embed_dim, name="fc2") + self.final_layer_norm = keras.layers.LayerNormalization(epsilon=1e-5, name="final_layer_norm") + self.config = config + + def call( + self, hidden_states: tf.Tensor, attention_mask: tf.Tensor, layer_head_mask: tf.Tensor, training: bool = False + ): + """ + Args: + hidden_states (`tf.Tensor`): input to the layer of shape `(batch, seq_len, embed_dim)` + attention_mask (`tf.Tensor`): attention mask of size + `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values. + layer_head_mask (`tf.Tensor`): mask for attention heads in a given layer of size + `(encoder_attention_heads,)` + """ + residual = hidden_states + hidden_states = self.self_attn_layer_norm(hidden_states) + hidden_states, self_attn_weights, _ = self.self_attn( + hidden_states=hidden_states, + attention_mask=attention_mask, + layer_head_mask=layer_head_mask, + training=training, + ) + + tf.debugging.assert_equal( + shape_list(hidden_states), + shape_list(residual), + message=f"Self attn modified the shape of query {shape_list(residual)} to {shape_list(hidden_states)}", + ) + + hidden_states = self.dropout(hidden_states, training=training) + hidden_states = residual + hidden_states + + residual = hidden_states + hidden_states = self.final_layer_norm(hidden_states) + hidden_states = self.activation_fn(self.fc1(hidden_states)) + hidden_states = self.activation_dropout(hidden_states, training=training) + hidden_states = self.fc2(hidden_states) + hidden_states = self.dropout(hidden_states, training=training) + hidden_states = residual + hidden_states + + return hidden_states, self_attn_weights + + def build(self, input_shape=None): + if self.built: + return + self.built = True + if getattr(self, "self_attn", None) is not None: + with tf.name_scope(self.self_attn.name): + self.self_attn.build(None) + if getattr(self, "self_attn_layer_norm", None) is not None: + with tf.name_scope(self.self_attn_layer_norm.name): + self.self_attn_layer_norm.build([None, None, self.embed_dim]) + if getattr(self, "fc1", None) is not None: + with tf.name_scope(self.fc1.name): + self.fc1.build([None, None, self.embed_dim]) + if getattr(self, "fc2", None) is not None: + with tf.name_scope(self.fc2.name): + self.fc2.build([None, None, self.config.encoder_ffn_dim]) + if getattr(self, "final_layer_norm", None) is not None: + with tf.name_scope(self.final_layer_norm.name): + self.final_layer_norm.build([None, None, self.embed_dim]) + + +class TFSpeech2TextDecoderLayer(keras.layers.Layer): + def __init__(self, config: Speech2TextConfig, **kwargs): + super().__init__(**kwargs) + self.embed_dim = config.d_model + + self.self_attn = TFSpeech2TextAttention( + embed_dim=self.embed_dim, + num_heads=config.decoder_attention_heads, + dropout=config.attention_dropout, + name="self_attn", + is_decoder=True, + ) + self.dropout = keras.layers.Dropout(config.dropout) + self.activation_fn = get_tf_activation(config.activation_function) + self.activation_dropout = keras.layers.Dropout(config.activation_dropout) + + self.self_attn_layer_norm = keras.layers.LayerNormalization(epsilon=1e-5, name="self_attn_layer_norm") + self.encoder_attn = TFSpeech2TextAttention( + self.embed_dim, + config.decoder_attention_heads, + dropout=config.attention_dropout, + name="encoder_attn", + is_decoder=True, + ) + self.encoder_attn_layer_norm = keras.layers.LayerNormalization(epsilon=1e-5, name="encoder_attn_layer_norm") + self.fc1 = keras.layers.Dense(config.decoder_ffn_dim, name="fc1") + self.fc2 = keras.layers.Dense(self.embed_dim, name="fc2") + self.final_layer_norm = keras.layers.LayerNormalization(epsilon=1e-5, name="final_layer_norm") + self.config = config + + def call( + self, + hidden_states, + attention_mask: tf.Tensor | None = None, + encoder_hidden_states: tf.Tensor | None = None, + encoder_attention_mask: tf.Tensor | None = None, + layer_head_mask: tf.Tensor | None = None, + cross_attn_layer_head_mask: tf.Tensor | None = None, + past_key_value: Tuple[tf.Tensor] | None = None, + training=False, + ) -> Tuple[tf.Tensor, tf.Tensor, Tuple[Tuple[tf.Tensor]]]: + """ + Args: + hidden_states (`tf.Tensor`): input to the layer of shape `(batch, seq_len, embed_dim)` + attention_mask (`tf.Tensor`): attention mask of size + `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values. + encoder_hidden_states (`tf.Tensor`): + cross attention input to the layer of shape `(batch, seq_len, embed_dim)` + encoder_attention_mask (`tf.Tensor`): encoder attention mask of size + `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values. + layer_head_mask (`tf.Tensor`): mask for attention heads in a given layer of size + `(decoder_attention_heads,)` + cross_attn_layer_head_mask (`tf.Tensor`): mask for heads of the cross-attention module. + `(decoder_attention_heads,)` + past_key_value (`Tuple(tf.Tensor)`): cached past key and value projection states + """ + residual = hidden_states + hidden_states = self.self_attn_layer_norm(hidden_states) + + # Self Attention + # decoder uni-directional self-attention cached key/values tuple is at positions 1,2 + self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None + # add present self-attn cache to positions 1,2 of present_key_value tuple + hidden_states, self_attn_weights, present_key_value = self.self_attn( + hidden_states=hidden_states, + past_key_value=self_attn_past_key_value, + attention_mask=attention_mask, + layer_head_mask=layer_head_mask, + training=training, + ) + hidden_states = self.dropout(hidden_states, training=training) + hidden_states = residual + hidden_states + + # Cross-Attention Block + cross_attn_present_key_value = None + cross_attn_weights = None + if encoder_hidden_states is not None: + residual = hidden_states + hidden_states = self.encoder_attn_layer_norm(hidden_states) + + # cross_attn cached key/values tuple is at positions 3,4 of present_key_value tuple + cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None + hidden_states, cross_attn_weights, cross_attn_present_key_value = self.encoder_attn( + hidden_states=hidden_states, + key_value_states=encoder_hidden_states, + attention_mask=encoder_attention_mask, + layer_head_mask=cross_attn_layer_head_mask, + past_key_value=cross_attn_past_key_value, + training=training, + ) + hidden_states = self.dropout(hidden_states, training=training) + hidden_states = residual + hidden_states + + # add cross-attn to positions 3,4 of present_key_value tuple + present_key_value = present_key_value + cross_attn_present_key_value + + # Fully Connected + residual = hidden_states + hidden_states = self.final_layer_norm(hidden_states) + hidden_states = self.activation_fn(self.fc1(hidden_states)) + hidden_states = self.activation_dropout(hidden_states, training=training) + hidden_states = self.fc2(hidden_states) + hidden_states = self.dropout(hidden_states, training=training) + hidden_states = residual + hidden_states + + return ( + hidden_states, + self_attn_weights, + cross_attn_weights, + present_key_value, + ) + + def build(self, input_shape=None): + if self.built: + return + self.built = True + if getattr(self, "self_attn", None) is not None: + with tf.name_scope(self.self_attn.name): + self.self_attn.build(None) + if getattr(self, "self_attn_layer_norm", None) is not None: + with tf.name_scope(self.self_attn_layer_norm.name): + self.self_attn_layer_norm.build([None, None, self.embed_dim]) + if getattr(self, "encoder_attn", None) is not None: + with tf.name_scope(self.encoder_attn.name): + self.encoder_attn.build(None) + if getattr(self, "encoder_attn_layer_norm", None) is not None: + with tf.name_scope(self.encoder_attn_layer_norm.name): + self.encoder_attn_layer_norm.build([None, None, self.embed_dim]) + if getattr(self, "fc1", None) is not None: + with tf.name_scope(self.fc1.name): + self.fc1.build([None, None, self.embed_dim]) + if getattr(self, "fc2", None) is not None: + with tf.name_scope(self.fc2.name): + self.fc2.build([None, None, self.config.decoder_ffn_dim]) + if getattr(self, "final_layer_norm", None) is not None: + with tf.name_scope(self.final_layer_norm.name): + self.final_layer_norm.build([None, None, self.embed_dim]) + + +class TFSpeech2TextPreTrainedModel(TFPreTrainedModel): + config_class = Speech2TextConfig + base_model_prefix = "model" + main_input_name = "input_features" + _keys_to_ignore_on_load_unexpected = [r"encoder.embed_positions.weights"] + + def _get_feat_extract_output_lengths(self, input_lengths: tf.Tensor): + """ + Computes the output length of the convolutional layers + """ + for _ in range(self.config.num_conv_layers): + input_lengths = (input_lengths - 1) // 2 + 1 + + return input_lengths + + @property + def input_signature(self): + return { + "input_features": tf.TensorSpec( + (None, None, self.config.input_feat_per_channel * self.config.input_channels), + tf.float32, + name="input_features", + ), + "attention_mask": tf.TensorSpec((None, None), tf.int32, name="attention_mask"), + "decoder_input_ids": tf.TensorSpec((None, None), tf.int32, name="decoder_input_ids"), + "decoder_attention_mask": tf.TensorSpec((None, None), tf.int32, name="decoder_attention_mask"), + } + + +SPEECH_TO_TEXT_START_DOCSTRING = r""" + This model inherits from [`TFPreTrainedModel`]. Check the superclass documentation for the generic methods the + library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads + etc.) + + This model is also a [keras.Model](https://www.tensorflow.org/api_docs/python/tf/keras/Model) subclass. Use it + as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to general usage and + behavior. + + + + TensorFlow models and layers in `transformers` accept two formats as input: + + - having all inputs as keyword arguments (like PyTorch models), or + - having all inputs as a list, tuple or dict in the first positional argument. + + The reason the second format is supported is that Keras methods prefer this format when passing inputs to models + and layers. Because of this support, when using methods like `model.fit()` things should "just work" for you - just + pass your inputs and labels in any format that `model.fit()` supports! If, however, you want to use the second + format outside of Keras methods like `fit()` and `predict()`, such as when creating your own layers or models with + the Keras `Functional` API, there are three possibilities you can use to gather all the input Tensors in the first + positional argument: + + - a single Tensor with `input_ids` only and nothing else: `model(input_ids)` + - a list of varying length with one or several input Tensors IN THE ORDER given in the docstring: + `model([input_ids, attention_mask])` or `model([input_ids, attention_mask, token_type_ids])` + - a dictionary with one or several input Tensors associated to the input names given in the docstring: + `model({"input_ids": input_ids, "token_type_ids": token_type_ids})` + + Note that when creating models and layers with + [subclassing](https://keras.io/guides/making_new_layers_and_models_via_subclassing/) then you don't need to worry + about any of this, as you can just pass inputs like you would to any other Python function! + + + + Parameters: + config ([`Speech2TextConfig`]): + Model configuration class with all the parameters of the model. Initializing with a config file does not + load the weights associated with the model, only the configuration. Check out the + [`~TFPreTrainedModel.from_pretrained`] method to load the model weights. +""" + + +SPEECH_TO_TEXT_INPUTS_DOCSTRING = r""" + Args: + input_features (`tf.Tensor` of shape `(batch_size, sequence_length, feature_size)`): + Float values of fbank features extracted from the raw speech waveform. Raw speech waveform can be obtained + by loading a `.flac` or `.wav` audio file into an array of type `List[float]` or a `numpy.ndarray`, *e.g.* + via the soundfile library (`pip install soundfile`). To prepare the array into `input_features`, the + [`AutoFeatureExtractor`] should be used for extracting the fbank features, padding and conversion into a + tensor of floats. See [`~Speech2TextFeatureExtractor.__call__`] + attention_mask (`tf.Tensor` of shape `({0})`, *optional*): + Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: + + - 1 for tokens that are **not masked**, + - 0 for tokens that are **masked**. + + [What are attention masks?](../glossary#attention-mask) + decoder_input_ids (`tf.Tensor` of shape `(batch_size, target_sequence_length)`, *optional*): + Indices of decoder input sequence tokens in the vocabulary. + + Indices can be obtained using [`Speech2TextTokenizer`]. See [`PreTrainedTokenizer.encode`] and + [`PreTrainedTokenizer.__call__`] for details. + + [What are decoder input IDs?](../glossary#decoder-input-ids) + + SpeechToText uses the `eos_token_id` as the starting token for `decoder_input_ids` generation. If + `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see + `past_key_values`). + + For translation and summarization training, `decoder_input_ids` should be provided. If no + `decoder_input_ids` is provided, the model will create this tensor by shifting the `input_ids` to the right + for denoising pre-training following the paper. + decoder_attention_mask (`tf.Tensor` of shape `(batch_size, target_sequence_length)`, *optional*): + will be made by default and ignore pad tokens. It is not recommended to set this for most use cases. + head_mask (`tf.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, *optional*): + Mask to nullify selected heads of the attention modules in the encoder. Mask values selected in `[0, 1]`: + + - 1 indicates the head is **not masked**, + - 0 indicates the head is **masked**. + + decoder_head_mask (`tf.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*): + Mask to nullify selected heads of the attention modules in the decoder. Mask values selected in `[0, 1]`: + + - 1 indicates the head is **not masked**, + - 0 indicates the head is **masked**. + + cross_attn_head_mask (`tf.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*): + Mask to nullify selected heads of the cross-attention modules. Mask values selected in `[0, 1]`: + + - 1 indicates the head is **not masked**, + - 0 indicates the head is **masked**. + + encoder_outputs (`tf.FloatTensor`, *optional*): + hidden states at the output of the last layer of the encoder. Used in the cross-attention of the decoder. + of shape `(batch_size, sequence_length, hidden_size)` is a sequence of + past_key_values (`Tuple[Tuple[tf.Tensor]]` of length `config.n_layers`) + contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding. + If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that + don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all + `decoder_input_ids` of shape `(batch_size, sequence_length)`. + decoder_inputs_embeds (`tf.FloatTensor` of shape `(batch_size, target_sequence_length, hidden_size)`, *optional*): + Optionally, instead of passing `decoder_input_ids` you can choose to directly pass an embedded + representation. If `past_key_values` is used, optionally only the last `decoder_inputs_embeds` have to be + input (see `past_key_values`). This is useful if you want more control over how to convert + `decoder_input_ids` indices into associated vectors than the model's internal embedding lookup matrix. + use_cache (`bool`, *optional*): + If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see + `past_key_values`). + output_attentions (`bool`, *optional*): + Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned + tensors for more detail. This argument can be used only in eager mode, in graph mode the value in the + config will be used instead. + output_hidden_states (`bool`, *optional*): + Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for + more detail. This argument can be used only in eager mode, in graph mode the value in the config will be + used instead. + return_dict (`bool`, *optional*): + Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. This argument can be used in + eager mode, in graph mode the value will always be set to True. + training (`bool`, *optional*, defaults to `False`): + Whether or not to use the model in training mode (some modules like dropout modules have different + behaviors between training and evaluation). +""" + + +@keras_serializable +class TFSpeech2TextEncoder(keras.layers.Layer): + config_class = Speech2TextConfig + """ + Transformer encoder consisting of *config.encoder_layers* self attention layers. Each layer is a + [`TFSpeech2TextEncoderLayer`]. + + Args: + config: Speech2TextConfig + """ + + def __init__(self, config: Speech2TextConfig, **kwargs): + super().__init__(**kwargs) + self.config = config + + self.dropout = keras.layers.Dropout(config.dropout) + self.layerdrop = config.encoder_layerdrop + + embed_dim = config.d_model + self.padding_idx = config.pad_token_id + self.max_source_positions = config.max_source_positions + self.embed_scale = tf.math.sqrt(float(embed_dim)) if config.scale_embedding else 1.0 + + self.conv = TFConv1dSubsampler(config, name="conv") + + self.embed_positions = TFSpeech2TextSinusoidalPositionalEmbedding( + num_positions=config.max_source_positions, + embedding_dim=embed_dim, + padding_idx=self.padding_idx, + name="embed_positions", + ) + self.layers = [TFSpeech2TextEncoderLayer(config, name=f"layers.{i}") for i in range(config.encoder_layers)] + self.layer_norm = keras.layers.LayerNormalization(epsilon=1e-5, name="layer_norm") + + def _get_feat_extract_output_lengths(self, input_lengths: tf.Tensor): + """ + Computes the output length of the convolutional layers + """ + for _ in range(self.config.num_conv_layers): + input_lengths = (input_lengths - 1) // 2 + 1 + + return input_lengths + + def _get_feature_vector_attention_mask(self, feature_vector_length, attention_mask): + # generate creates 3D attention mask, because of the shape of input_features + # convert it to 2D if thats the case + if len(attention_mask.shape) > 2: + attention_mask = attention_mask[:, :, -1] + + subsampled_lengths = self._get_feat_extract_output_lengths(tf.math.reduce_sum(attention_mask, -1)) + bsz = shape_list(attention_mask)[0] + indices = tf.concat( + ( + tf.expand_dims(tf.range(bsz, dtype=attention_mask.dtype), -1), + tf.expand_dims(subsampled_lengths - 1, -1), + ), + axis=-1, + ) + attention_mask = tf.scatter_nd(indices=indices, updates=tf.ones(bsz), shape=[bsz, feature_vector_length]) + attention_mask = tf.cast(tf.reverse(tf.math.cumsum(tf.reverse(attention_mask, [-1]), -1), [-1]), tf.int64) + return attention_mask + + @unpack_inputs + def call( + self, + input_features=None, + attention_mask=None, + head_mask=None, + output_attentions=None, + output_hidden_states=None, + return_dict=None, + training=False, + ): + """ + Args: + input_features (`tf.Tensor` of shape `(batch_size, sequence_length, feature_size)`): + Float values of fbank features extracted from the raw speech waveform. Raw speech waveform can be + obtained by loading a `.flac` or `.wav` audio file into an array of type `List[float]` or a + `numpy.ndarray`, *e.g.* via the soundfile library (`pip install soundfile`). To prepare the array into + `input_features`, the [`AutoFeatureExtractor`] should be used for extracting the fbank features, + padding and conversion into a tensor of floats. See [`~Speech2TextFeatureExtractor.__call__`] + attention_mask (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*): + Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: + + - 1 for tokens that are **not masked**, + - 0 for tokens that are **masked**. + + [What are attention masks?](../glossary#attention-mask) + head_mask (`tf.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, `optional): + Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`: + + - 1 indicates the head is **not masked**, + - 0 indicates the head is **masked**. + + output_attentions (`bool`, *optional*): + Whether or not to return the attentions tensors of all attention layers. See `attentions` under + returned tensors for more detail. + output_hidden_states (`bool`, *optional*): + Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors + for more detail. + return_dict (`bool`, *optional*): + Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. + """ + if input_features is None: + raise ValueError("You have to specify input_features") + + inputs_embeds = self.conv(input_features) + inputs_embeds = self.embed_scale * inputs_embeds + + # subsample attention mask if necessary + if attention_mask is not None: + attention_mask = self._get_feature_vector_attention_mask(tf.shape(inputs_embeds)[1], attention_mask) + padding_mask = tf.cast(tf.math.not_equal(attention_mask, 1), tf.int64) + else: + padding_mask = tf.zeros(tf.shape(inputs_embeds)[:-1], dtype=tf.int64) + + embed_pos = self.embed_positions(padding_mask) + + hidden_states = inputs_embeds + embed_pos + hidden_states = self.dropout(hidden_states, training=training) + + # check attention mask and invert + if attention_mask is not None: + # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len] + attention_mask = _expand_mask(attention_mask) + + encoder_states = () if output_hidden_states else None + all_attentions = () if output_attentions else None + + # check if head_mask has a correct number of layers specified if desired + if head_mask is not None: + tf.debugging.assert_equal( + shape_list(head_mask)[0], + len(self.layers), + message=( + f"The head_mask should be specified for {len(self.layers)} layers, but it is for" + f" {shape_list(head_mask)[0]}." + ), + ) + + for idx, encoder_layer in enumerate(self.layers): + if output_hidden_states: + encoder_states = encoder_states + (hidden_states,) + # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description) + dropout_probability = random.uniform(0, 1) + if training and (dropout_probability < self.layerdrop): # skip the layer + continue + + hidden_states, attn = encoder_layer( + hidden_states, + attention_mask, + head_mask[idx] if head_mask is not None else None, + training=training, + ) + + if output_attentions: + all_attentions += (attn,) + + hidden_states = self.layer_norm(hidden_states) + if output_hidden_states: + encoder_states = encoder_states + (hidden_states,) + + if not return_dict: + return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None) + return TFBaseModelOutput( + last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions + ) + + def build(self, input_shape=None): + if self.built: + return + self.built = True + if getattr(self, "conv", None) is not None: + with tf.name_scope(self.conv.name): + self.conv.build(None) + if getattr(self, "embed_positions", None) is not None: + with tf.name_scope(self.embed_positions.name): + self.embed_positions.build(None) + if getattr(self, "layer_norm", None) is not None: + with tf.name_scope(self.layer_norm.name): + self.layer_norm.build([None, None, self.config.d_model]) + if getattr(self, "layers", None) is not None: + for layer in self.layers: + with tf.name_scope(layer.name): + layer.build(None) + + +@keras_serializable +class TFSpeech2TextDecoder(keras.layers.Layer): + config_class = Speech2TextConfig + """ + Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a [`TFSpeech2TextDecoderLayer`] + + Args: + config: Speech2TextConfig + """ + + def __init__(self, config: Speech2TextConfig, **kwargs): + super().__init__(**kwargs) + self.config = config + self.layerdrop = config.decoder_layerdrop + self.padding_idx = config.pad_token_id + self.max_target_positions = config.max_target_positions + self.embed_scale = tf.math.sqrt(float(config.d_model)) if config.scale_embedding else 1.0 + + self.embed_tokens = TFSharedEmbeddings(config.vocab_size, config.d_model, name="embed_tokens") + + self.embed_positions = TFSpeech2TextSinusoidalPositionalEmbedding( + num_positions=config.max_target_positions, + embedding_dim=config.d_model, + padding_idx=self.padding_idx, + name="embed_positions", + ) + + self.layers = [TFSpeech2TextDecoderLayer(config, name=f"layers.{i}") for i in range(config.decoder_layers)] + self.layer_norm = keras.layers.LayerNormalization(epsilon=1e-5, name="layer_norm") + + self.dropout = keras.layers.Dropout(config.dropout) + + def get_embed_tokens(self): + return self.embed_tokens + + def set_embed_tokens(self, embed_tokens): + self.embed_tokens = embed_tokens + + @unpack_inputs + def call( + self, + input_ids=None, + inputs_embeds=None, + attention_mask=None, + encoder_hidden_states=None, + encoder_attention_mask=None, + head_mask=None, + cross_attn_head_mask=None, + past_key_values=None, + use_cache=None, + output_attentions=None, + output_hidden_states=None, + return_dict=None, + training=False, + ): + r""" + Args: + input_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`): + Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you + provide it. + + Indices can be obtained using [`Speech2TextTokenizer`]. See [`PreTrainedTokenizer.encode`] and + [`PreTrainedTokenizer.__call__`] for details. + + [What are input IDs?](../glossary#input-ids) + attention_mask (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*): + Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: + + - 1 for tokens that are **not masked**, + - 0 for tokens that are **masked**. + + [What are attention masks?](../glossary#attention-mask) + encoder_hidden_states (`tf.Tensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*): + Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention + of the decoder. + encoder_attention_mask (`tf.Tensor` of shape `(batch_size, encoder_sequence_length)`, *optional*): + Mask to avoid performing cross-attention on padding tokens indices of encoder input_ids. Mask values + selected in `[0, 1]`: + + - 1 for tokens that are **not masked**, + - 0 for tokens that are **masked**. + + [What are attention masks?](../glossary#attention-mask) + head_mask (`tf.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*): + Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`: + + - 1 indicates the head is **not masked**, + - 0 indicates the head is **masked**. + + cross_attn_head_mask (`tf.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*): + Mask to nullify selected heads of the cross-attention modules. Mask values selected in `[0, 1]`: + + - 1 indicates the head is **not masked**, + - 0 indicates the head is **masked**. + + past_key_values (`Tuple[Tuple[tf.Tensor]]` of length `config.n_layers` with each tuple having 2 tuples each of which has 2 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`): + Contains precomputed key and value hidden-states of the attention blocks. Can be used to speed up + decoding. + + If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those + that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of + all `decoder_input_ids` of shape `(batch_size, sequence_length)`. + inputs_embeds (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*): + Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. + This is useful if you want more control over how to convert `input_ids` indices into associated vectors + than the model's internal embedding lookup matrix. + output_attentions (`bool`, *optional*): + Whether or not to return the attentions tensors of all attention layers. See `attentions` under + returned tensors for more detail. + output_hidden_states (`bool`, *optional*): + Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors + for more detail. + return_dict (`bool`, *optional*): + Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. + """ + + if input_ids is not None and inputs_embeds is not None: + raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time") + elif input_ids is not None: + input_shape = shape_list(input_ids) + elif inputs_embeds is not None: + input_shape = shape_list(inputs_embeds)[:-1] + else: + raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds") + + # past_key_values_length + past_key_values_length = shape_list(past_key_values[0][0])[2] if past_key_values is not None else 0 + + if inputs_embeds is None: + check_embeddings_within_bounds(input_ids, self.embed_tokens.vocab_size) + inputs_embeds = self.embed_tokens(input_ids) * self.embed_scale + else: + inputs_embeds = inputs_embeds + + # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len] + if input_shape[-1] > 1: + combined_attention_mask = _make_causal_mask(input_shape, past_key_values_length=past_key_values_length) + else: + combined_attention_mask = _expand_mask( + tf.ones((input_shape[0], input_shape[1] + past_key_values_length)), tgt_len=input_shape[-1] + ) + + if attention_mask is not None: + combined_attention_mask = combined_attention_mask + _expand_mask(attention_mask, tgt_len=input_shape[-1]) + + # expand encoder attention mask + if encoder_hidden_states is not None and encoder_attention_mask is not None: + # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len] + encoder_attention_mask = _expand_mask(encoder_attention_mask, tgt_len=input_shape[-1]) + + # embed positions + positions = self.embed_positions(input_ids, past_key_values_length=past_key_values_length) + + hidden_states = inputs_embeds + positions + hidden_states = self.dropout(hidden_states, training=training) + + # decoder layers + all_hidden_states = () if output_hidden_states else None + all_self_attns = () if output_attentions else None + all_cross_attns = () if (output_attentions and encoder_hidden_states is not None) else None + next_decoder_cache = () if use_cache else None + + # check if head_mask and cross_attn_head_mask have a correct number of layers specified if desired + for attn_mask_name, attn_mask in [("head_mask", head_mask), ("cross_attn_head_mask", cross_attn_head_mask)]: + if attn_mask is not None: + tf.debugging.assert_equal( + shape_list(attn_mask)[0], + len(self.layers), + message=( + f"The {attn_mask_name} should be specified for {len(self.layers)} layers, but it is for" + f" {shape_list(attn_mask)[0]}." + ), + ) + + for idx, decoder_layer in enumerate(self.layers): + # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description) + if output_hidden_states: + all_hidden_states += (hidden_states,) + dropout_probability = random.uniform(0, 1) + if training and (dropout_probability < self.layerdrop): + continue + + past_key_value = past_key_values[idx] if past_key_values is not None else None + cross_attn_layer_head_mask = cross_attn_head_mask[idx] if cross_attn_head_mask is not None else None + + hidden_states, layer_self_attn, layer_cross_attn, present_key_value = decoder_layer( + hidden_states, + attention_mask=combined_attention_mask, + encoder_hidden_states=encoder_hidden_states, + encoder_attention_mask=encoder_attention_mask, + layer_head_mask=head_mask[idx] if head_mask is not None else None, + cross_attn_layer_head_mask=cross_attn_layer_head_mask, + past_key_value=past_key_value, + ) + + if use_cache: + next_decoder_cache += (present_key_value,) + + if output_attentions: + all_self_attns += (layer_self_attn,) + + if encoder_hidden_states is not None: + all_cross_attns += (layer_cross_attn,) + + hidden_states = self.layer_norm(hidden_states) + if output_hidden_states: + all_hidden_states += (hidden_states,) + + next_cache = next_decoder_cache if use_cache else None + + if not return_dict: + return hidden_states, next_cache, all_hidden_states, all_self_attns, all_cross_attns + else: + return TFBaseModelOutputWithPastAndCrossAttentions( + last_hidden_state=hidden_states, + past_key_values=next_cache, + hidden_states=all_hidden_states, + attentions=all_self_attns, + cross_attentions=all_cross_attns, + ) + + def build(self, input_shape=None): + if self.built: + return + self.built = True + if getattr(self, "embed_tokens", None) is not None: + with tf.name_scope(self.embed_tokens.name): + self.embed_tokens.build(None) + if getattr(self, "embed_positions", None) is not None: + with tf.name_scope(self.embed_positions.name): + self.embed_positions.build(None) + if getattr(self, "layer_norm", None) is not None: + with tf.name_scope(self.layer_norm.name): + self.layer_norm.build([None, None, self.config.d_model]) + if getattr(self, "layers", None) is not None: + for layer in self.layers: + with tf.name_scope(layer.name): + layer.build(None) + + +@keras_serializable +class TFSpeech2TextMainLayer(keras.layers.Layer): + config_class = Speech2TextConfig + + def __init__(self, config: Speech2TextConfig, **kwargs): + super().__init__(**kwargs) + self.config = config + + self.encoder = TFSpeech2TextEncoder(config, name="encoder") + self.decoder = TFSpeech2TextDecoder(config, name="decoder") + + def get_input_embeddings(self): + return self.decoder.embed_tokens + + def set_input_embeddings(self, new_embeddings): + self.decoder.embed_tokens = new_embeddings + + @unpack_inputs + def call( + self, + input_features=None, + attention_mask=None, + decoder_input_ids=None, + decoder_attention_mask=None, + head_mask=None, + decoder_head_mask=None, + cross_attn_head_mask=None, + encoder_outputs=None, + past_key_values=None, + decoder_inputs_embeds=None, + use_cache=None, + output_attentions=None, + output_hidden_states=None, + return_dict=None, + training=False, + **kwargs, + ): + output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions + output_hidden_states = ( + output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states + ) + use_cache = use_cache if use_cache is not None else self.config.use_cache + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + if encoder_outputs is None: + encoder_outputs = self.encoder( + input_features=input_features, + attention_mask=attention_mask, + head_mask=head_mask, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + training=training, + ) + # If the user passed a tuple for encoder_outputs, we wrap it in a TFBaseModelOutput when return_dict=True + elif return_dict and not isinstance(encoder_outputs, TFBaseModelOutput): + encoder_outputs = TFBaseModelOutput( + last_hidden_state=encoder_outputs[0], + hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None, + attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None, + ) + # If the user passed a TFBaseModelOutput for encoder_outputs, we wrap it in a tuple when return_dict=False + elif not return_dict and not isinstance(encoder_outputs, tuple): + encoder_outputs = encoder_outputs.to_tuple() + + # downsample encoder attention mask + if attention_mask is not None: + encoder_attention_mask = self.encoder._get_feature_vector_attention_mask( + tf.shape(encoder_outputs[0])[1], attention_mask + ) + else: + encoder_attention_mask = None + + # decoder outputs consists of (dec_features, past_key_value, dec_hidden, dec_attn) + decoder_outputs = self.decoder( + input_ids=decoder_input_ids, + attention_mask=decoder_attention_mask, + encoder_hidden_states=encoder_outputs[0], + encoder_attention_mask=encoder_attention_mask, + head_mask=decoder_head_mask, + cross_attn_head_mask=cross_attn_head_mask, + past_key_values=past_key_values, + inputs_embeds=decoder_inputs_embeds, + use_cache=use_cache, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + training=training, + ) + + if not return_dict: + return decoder_outputs + encoder_outputs + + return TFSeq2SeqModelOutput( + last_hidden_state=decoder_outputs.last_hidden_state, + past_key_values=decoder_outputs.past_key_values, + decoder_hidden_states=decoder_outputs.hidden_states, + decoder_attentions=decoder_outputs.attentions, + cross_attentions=decoder_outputs.cross_attentions, + encoder_last_hidden_state=encoder_outputs.last_hidden_state, + encoder_hidden_states=encoder_outputs.hidden_states, + encoder_attentions=encoder_outputs.attentions, + ) + + def build(self, input_shape=None): + if self.built: + return + self.built = True + if getattr(self, "encoder", None) is not None: + with tf.name_scope(self.encoder.name): + self.encoder.build(None) + if getattr(self, "decoder", None) is not None: + with tf.name_scope(self.decoder.name): + self.decoder.build(None) + + +@add_start_docstrings( + "The bare Speech2Text Model outputting raw hidden-states without any specific head on top.", + SPEECH_TO_TEXT_START_DOCSTRING, +) +class TFSpeech2TextModel(TFSpeech2TextPreTrainedModel): + def __init__(self, config: Speech2TextConfig, *inputs, **kwargs): + super().__init__(config, *inputs, **kwargs) + + self.model = TFSpeech2TextMainLayer(config, name="model") + + def get_encoder(self): + return self.model.encoder + + def get_decoder(self): + return self.model.decoder + + @unpack_inputs + @add_start_docstrings_to_model_forward(SPEECH_TO_TEXT_INPUTS_DOCSTRING) + @add_code_sample_docstrings( + checkpoint=_CHECKPOINT_FOR_DOC, + output_type=TFSeq2SeqModelOutput, + config_class=_CONFIG_FOR_DOC, + ) + def call( + self, + input_features: TFModelInputType | None = None, + attention_mask: np.ndarray | tf.Tensor | None = None, + decoder_input_ids: np.ndarray | tf.Tensor | None = None, + decoder_attention_mask: np.ndarray | tf.Tensor | None = None, + head_mask: np.ndarray | tf.Tensor | None = None, + decoder_head_mask: np.ndarray | tf.Tensor | None = None, + cross_attn_head_mask: np.ndarray | tf.Tensor | None = None, + encoder_outputs: np.ndarray | tf.Tensor | None = None, + past_key_values: Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]] = None, + decoder_inputs_embeds: np.ndarray | tf.Tensor | None = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + training: bool = False, + **kwargs, + ) -> Union[Tuple, TFSeq2SeqModelOutput]: + outputs = self.model( + input_features=input_features, + attention_mask=attention_mask, + decoder_input_ids=decoder_input_ids, + decoder_attention_mask=decoder_attention_mask, + head_mask=head_mask, + decoder_head_mask=decoder_head_mask, + cross_attn_head_mask=cross_attn_head_mask, + encoder_outputs=encoder_outputs, + past_key_values=past_key_values, + decoder_inputs_embeds=decoder_inputs_embeds, + use_cache=use_cache, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + training=training, + ) + + return outputs + + def serving_output(self, output): + pkv = tf.tuple(output.past_key_values)[1] if self.config.use_cache else None + dec_hs = tf.convert_to_tensor(output.decoder_hidden_states) if self.config.output_hidden_states else None + dec_attns = tf.convert_to_tensor(output.decoder_attentions) if self.config.output_attentions else None + cross_attns = tf.convert_to_tensor(output.cross_attentions) if self.config.output_attentions else None + enc_hs = tf.convert_to_tensor(output.encoder_hidden_states) if self.config.output_hidden_states else None + enc_attns = tf.convert_to_tensor(output.encoder_attentions) if self.config.output_attentions else None + + return TFSeq2SeqModelOutput( + last_hidden_state=output.last_hidden_state, + past_key_values=pkv, + decoder_hidden_states=dec_hs, + decoder_attentions=dec_attns, + cross_attentions=cross_attns, + encoder_last_hidden_state=output.encoder_last_hidden_state, + encoder_hidden_states=enc_hs, + encoder_attentions=enc_attns, + ) + + def build(self, input_shape=None): + if self.built: + return + self.built = True + if getattr(self, "model", None) is not None: + with tf.name_scope(self.model.name): + self.model.build(None) + + +@add_start_docstrings( + "The Speech2Text Model with a language modeling head. Can be used for summarization.", + SPEECH_TO_TEXT_START_DOCSTRING, +) +class TFSpeech2TextForConditionalGeneration(TFSpeech2TextPreTrainedModel, TFCausalLanguageModelingLoss): + def __init__(self, config: Speech2TextConfig): + super().__init__(config) + self.model = TFSpeech2TextMainLayer(config, name="model") + self.lm_head = keras.layers.Dense(self.config.vocab_size, use_bias=False, name="lm_head") + # TODO (Joao): investigate why Speech2Text has numerical issues in XLA generate + self.supports_xla_generation = False + self.config = config + + def get_encoder(self): + return self.model.encoder + + def get_decoder(self): + return self.model.decoder + + def resize_token_embeddings(self, new_num_tokens: int) -> tf.Variable: + new_embeddings = super().resize_token_embeddings(new_num_tokens) + return new_embeddings + + def get_output_embeddings(self): + return self.lm_head + + def set_output_embeddings(self, new_embeddings): + self.lm_head = new_embeddings + + @unpack_inputs + @add_start_docstrings_to_model_forward(SPEECH_TO_TEXT_INPUTS_DOCSTRING) + @replace_return_docstrings(output_type=TFSeq2SeqLMOutput, config_class=_CONFIG_FOR_DOC) + def call( + self, + input_features: TFModelInputType | None = None, + attention_mask: np.ndarray | tf.Tensor | None = None, + decoder_input_ids: np.ndarray | tf.Tensor | None = None, + decoder_attention_mask: np.ndarray | tf.Tensor | None = None, + head_mask: np.ndarray | tf.Tensor | None = None, + decoder_head_mask: np.ndarray | tf.Tensor | None = None, + cross_attn_head_mask: np.ndarray | tf.Tensor | None = None, + encoder_outputs: np.ndarray | tf.Tensor | None = None, + past_key_values: Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]] = None, + decoder_inputs_embeds: np.ndarray | tf.Tensor | None = None, + labels: np.ndarray | tf.Tensor | None = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + training: Optional[bool] = False, + **kwargs, + ) -> Union[Tuple, TFSeq2SeqLMOutput]: + r""" + labels (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*): + Labels for computing the masked language modeling loss. Indices should either be in `[0, ..., + config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored + (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`. + + Returns: + + Example: + + ```python + >>> import tensorflow as tf + >>> from transformers import Speech2TextProcessor, TFSpeech2TextForConditionalGeneration + >>> from datasets import load_dataset + >>> import soundfile as sf + + >>> model = TFSpeech2TextForConditionalGeneration.from_pretrained( + ... "facebook/s2t-small-librispeech-asr", from_pt=True + ... ) + >>> processor = Speech2TextProcessor.from_pretrained("facebook/s2t-small-librispeech-asr") + + + >>> def map_to_array(batch): + ... speech, _ = sf.read(batch["file"]) + ... batch["speech"] = speech + ... return batch + + + >>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") + >>> ds = ds.map(map_to_array) + >>> ds.set_format(type="tf") + + >>> input_features = processor( + ... ds["speech"][0], sampling_rate=16000, return_tensors="tf" + ... ).input_features # Batch size 1 + >>> generated_ids = model.generate(input_features) + + >>> transcription = processor.batch_decode(generated_ids) + ```""" + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + if labels is not None: + if decoder_input_ids is None and decoder_inputs_embeds is None: + decoder_input_ids = shift_tokens_right( + labels, self.config.pad_token_id, self.config.decoder_start_token_id + ) + + outputs = self.model( + input_features=input_features, + attention_mask=attention_mask, + decoder_input_ids=decoder_input_ids, + encoder_outputs=encoder_outputs, + decoder_attention_mask=decoder_attention_mask, + head_mask=head_mask, + decoder_head_mask=decoder_head_mask, + cross_attn_head_mask=cross_attn_head_mask, + past_key_values=past_key_values, + decoder_inputs_embeds=decoder_inputs_embeds, + use_cache=use_cache, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + training=training, + ) + lm_logits = self.lm_head(outputs[0]) + masked_lm_loss = None if labels is None else self.hf_compute_loss(labels, lm_logits) + + if not return_dict: + output = (lm_logits,) + outputs[1:] + return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output + + return TFSeq2SeqLMOutput( + loss=masked_lm_loss, + logits=lm_logits, + past_key_values=outputs.past_key_values, + decoder_hidden_states=outputs.decoder_hidden_states, + decoder_attentions=outputs.decoder_attentions, + cross_attentions=outputs.cross_attentions, + encoder_last_hidden_state=outputs.encoder_last_hidden_state, + encoder_hidden_states=outputs.encoder_hidden_states, + encoder_attentions=outputs.encoder_attentions, + ) + + def serving_output(self, output): + pkv = tf.tuple(output.past_key_values)[1] if self.config.use_cache else None + dec_hs = tf.convert_to_tensor(output.decoder_hidden_states) if self.config.output_hidden_states else None + dec_attns = tf.convert_to_tensor(output.decoder_attentions) if self.config.output_attentions else None + cross_attns = tf.convert_to_tensor(output.cross_attentions) if self.config.output_attentions else None + enc_hs = tf.convert_to_tensor(output.encoder_hidden_states) if self.config.output_hidden_states else None + enc_attns = tf.convert_to_tensor(output.encoder_attentions) if self.config.output_attentions else None + + return TFSeq2SeqLMOutput( + logits=output.logits, + past_key_values=pkv, + decoder_hidden_states=dec_hs, + decoder_attentions=dec_attns, + cross_attentions=cross_attns, + encoder_last_hidden_state=output.encoder_last_hidden_state, + encoder_hidden_states=enc_hs, + encoder_attentions=enc_attns, + ) + + def prepare_inputs_for_generation( + self, + decoder_input_ids, + past_key_values=None, + attention_mask=None, + head_mask=None, + decoder_head_mask=None, + cross_attn_head_mask=None, + use_cache=None, + encoder_outputs=None, + **kwargs, + ): + # cut decoder_input_ids if past is used + if past_key_values is not None: + decoder_input_ids = decoder_input_ids[:, -1:] + + return { + "input_features": None, # needs to be passed to make Keras.layer.__call__ happy + "encoder_outputs": encoder_outputs, + "past_key_values": past_key_values, + "decoder_input_ids": decoder_input_ids, + "attention_mask": attention_mask, + "head_mask": head_mask, + "decoder_head_mask": decoder_head_mask, + "cross_attn_head_mask": cross_attn_head_mask, + "use_cache": use_cache, # change this to avoid caching (presumably for debugging) + } + + def build(self, input_shape=None): + if self.built: + return + self.built = True + if getattr(self, "model", None) is not None: + with tf.name_scope(self.model.name): + self.model.build(None) + if getattr(self, "lm_head", None) is not None: + with tf.name_scope(self.lm_head.name): + self.lm_head.build([None, None, self.config.d_model]) + + def tf_to_pt_weight_rename(self, tf_weight): + if tf_weight == "lm_head.weight": + return tf_weight, "model.decoder.embed_tokens.weight" + else: + return (tf_weight,) + + +__all__ = ["TFSpeech2TextForConditionalGeneration", "TFSpeech2TextModel", "TFSpeech2TextPreTrainedModel"]