diff --git a/.gitattributes b/.gitattributes index 13633e3bf3be3422a53861b781a11c57d92e996e..9cef15336a14ba77bc28ec0f14977fe6b9fedeff 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1436,3 +1436,5 @@ vllm/lib/python3.10/site-packages/wandb/sdk/__pycache__/wandb_run.cpython-310.py parrot/lib/python3.10/site-packages/numpy/fft/_pocketfft_umath.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text parrot/lib/python3.10/site-packages/numpy/_core/tests/__pycache__/test_numeric.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text parrot/lib/python3.10/site-packages/numpy/lib/tests/__pycache__/test_function_base.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text +vllm/lib/python3.10/site-packages/huggingface_hub/inference/_generated/__pycache__/_async_client.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text +vllm/lib/python3.10/site-packages/huggingface_hub/inference/__pycache__/_client.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_dimI_native.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_dimI_native.h new file mode 100644 index 0000000000000000000000000000000000000000..20ffb1592d858f37eb4ebbf530c3b3c8f479383c --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_dimI_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 int64_t sparse_dim_sparse(const at::Tensor & self); +} // namespace native +} // namespace at diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_acos_ops.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_acos_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..1328a65a554e012a2ac6a82b341556e68c12ad00 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_acos_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 _foreach_acos { + using schema = ::std::vector (at::TensorList); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_foreach_acos") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_foreach_acos(Tensor[] self) -> Tensor[]") + static ::std::vector call(at::TensorList self); + static ::std::vector redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self); +}; + +struct TORCH_API _foreach_acos_ { + using schema = void (at::TensorList); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_foreach_acos_") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_foreach_acos_(Tensor(a!)[] self) -> ()") + static void call(at::TensorList self); + static void redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self); +}; + +struct TORCH_API _foreach_acos_out { + using schema = void (at::TensorList, at::TensorList); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_foreach_acos") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_foreach_acos.out(Tensor[] self, *, Tensor(a!)[] out) -> ()") + static void call(at::TensorList self, at::TensorList out); + static void redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self, at::TensorList out); +}; + +}} // namespace at::_ops diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_fused_sdp_choice.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_fused_sdp_choice.h new file mode 100644 index 0000000000000000000000000000000000000000..56a9fc94b935eb83e0f76d9302155bb404cc6069 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_fused_sdp_choice.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::_fused_sdp_choice(Tensor query, Tensor key, Tensor value, Tensor? attn_mask=None, float dropout_p=0.0, bool is_causal=False, *, float? scale=None) -> int +inline int64_t _fused_sdp_choice(const at::Tensor & query, const at::Tensor & key, const at::Tensor & value, const c10::optional & attn_mask={}, double dropout_p=0.0, bool is_causal=false, c10::optional scale=c10::nullopt) { + return at::_ops::_fused_sdp_choice::call(query, key, value, attn_mask, dropout_p, is_causal, scale); +} + +} diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_indices_copy_compositeexplicitautograd_dispatch.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_indices_copy_compositeexplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..a53c293e927239163134ca473472c5d0148a6996 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_indices_copy_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 at::Tensor & _indices_copy_out(at::Tensor & out, const at::Tensor & self); +TORCH_API at::Tensor & _indices_copy_outf(const at::Tensor & self, at::Tensor & out); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_local_scalar_dense_native.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_local_scalar_dense_native.h new file mode 100644 index 0000000000000000000000000000000000000000..f9a174c3b81808c1fc694527fcc85a3a229334c9 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_local_scalar_dense_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::Scalar _local_scalar_dense_cpu(const at::Tensor & self); +TORCH_API at::Scalar _local_scalar_dense_cuda(const at::Tensor & self); +} // namespace native +} // namespace at diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_sobol_engine_scramble.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_sobol_engine_scramble.h new file mode 100644 index 0000000000000000000000000000000000000000..2c7a81ae523c5f1dc089de8e63d7afa7c68d3899 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_sobol_engine_scramble.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::_sobol_engine_scramble_(Tensor(a!) self, Tensor ltm, int dimension) -> Tensor(a!) +inline at::Tensor & _sobol_engine_scramble_(at::Tensor & self, const at::Tensor & ltm, int64_t dimension) { + return at::_ops::_sobol_engine_scramble_::call(self, ltm, dimension); +} + +} diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/and.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/and.h new file mode 100644 index 0000000000000000000000000000000000000000..6d668dc2b5a31170f1959558fb9d7c9b65dc7c29 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/and.h @@ -0,0 +1,35 @@ +#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::__and__.Scalar(Tensor self, Scalar other) -> Tensor +inline at::Tensor __and__(const at::Tensor & self, const at::Scalar & other) { + return at::_ops::__and___Scalar::call(self, other); +} + +// aten::__and__.Tensor(Tensor self, Tensor other) -> Tensor +inline at::Tensor __and__(const at::Tensor & self, const at::Tensor & other) { + return at::_ops::__and___Tensor::call(self, other); +} + +} diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/binary_cross_entropy_cuda_dispatch.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/binary_cross_entropy_cuda_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..667acb87896549237393843f7373d202b8ba045d --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/binary_cross_entropy_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 binary_cross_entropy(const at::Tensor & self, const at::Tensor & target, const c10::optional & weight={}, int64_t reduction=at::Reduction::Mean); +TORCH_API at::Tensor & binary_cross_entropy_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & target, const c10::optional & weight={}, int64_t reduction=at::Reduction::Mean); +TORCH_API at::Tensor & binary_cross_entropy_outf(const at::Tensor & self, const at::Tensor & target, const c10::optional & weight, int64_t reduction, at::Tensor & out); + +} // namespace cuda +} // namespace at diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/bitwise_xor_ops.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/bitwise_xor_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..c4d99b4af816a7cf2c8c607bad2177b8e28558ac --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/bitwise_xor_ops.h @@ -0,0 +1,105 @@ +#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 bitwise_xor_Tensor_out { + using schema = at::Tensor & (const at::Tensor &, const 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::bitwise_xor") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Tensor_out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "bitwise_xor.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, const at::Tensor & other, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & other, at::Tensor & out); +}; + +struct TORCH_API bitwise_xor_Scalar_out { + using schema = 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::bitwise_xor") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Scalar_out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "bitwise_xor.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, const at::Scalar & other, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Scalar & other, at::Tensor & out); +}; + +struct TORCH_API bitwise_xor_Scalar { + using schema = 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::bitwise_xor") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Scalar") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "bitwise_xor.Scalar(Tensor self, Scalar other) -> Tensor") + static at::Tensor call(const at::Tensor & self, const at::Scalar & other); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Scalar & other); +}; + +struct TORCH_API bitwise_xor_Scalar_Tensor { + using schema = at::Tensor (const at::Scalar &, 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::bitwise_xor") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Scalar_Tensor") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "bitwise_xor.Scalar_Tensor(Scalar self, Tensor other) -> Tensor") + static at::Tensor call(const at::Scalar & self, const at::Tensor & other); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Scalar & self, const at::Tensor & other); +}; + +struct TORCH_API bitwise_xor_Tensor { + using schema = at::Tensor (const at::Tensor &, 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::bitwise_xor") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Tensor") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "bitwise_xor.Tensor(Tensor self, Tensor other) -> Tensor") + static at::Tensor call(const at::Tensor & self, const at::Tensor & other); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & other); +}; + +struct TORCH_API bitwise_xor__Scalar { + using schema = at::Tensor & (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::bitwise_xor_") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Scalar") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "bitwise_xor_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)") + static at::Tensor & call(at::Tensor & self, const at::Scalar & other); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self, const at::Scalar & other); +}; + +struct TORCH_API bitwise_xor__Tensor { + using schema = at::Tensor & (at::Tensor &, 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::bitwise_xor_") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Tensor") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "bitwise_xor_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!)") + static at::Tensor & call(at::Tensor & self, const at::Tensor & other); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self, const at::Tensor & other); +}; + +struct TORCH_API bitwise_xor_Scalar_Tensor_out { + using schema = at::Tensor & (const at::Scalar &, const 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::bitwise_xor") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Scalar_Tensor_out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "bitwise_xor.Scalar_Tensor_out(Scalar self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Scalar & self, const at::Tensor & other, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Scalar & self, const at::Tensor & other, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/div_ops.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/div_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..7d17a4be1d2af72360d110a36905eb38c023a3b2 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/div_ops.h @@ -0,0 +1,149 @@ +#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 div_Tensor { + using schema = at::Tensor (const at::Tensor &, 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::div") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Tensor") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "div.Tensor(Tensor self, Tensor other) -> Tensor") + static at::Tensor call(const at::Tensor & self, const at::Tensor & other); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & other); +}; + +struct TORCH_API div__Tensor { + using schema = at::Tensor & (at::Tensor &, 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::div_") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Tensor") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "div_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!)") + static at::Tensor & call(at::Tensor & self, const at::Tensor & other); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self, const at::Tensor & other); +}; + +struct TORCH_API div_out { + using schema = at::Tensor & (const at::Tensor &, const 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::div") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "div.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, const at::Tensor & other, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & other, at::Tensor & out); +}; + +struct TORCH_API div_Tensor_mode { + using schema = at::Tensor (const at::Tensor &, const at::Tensor &, c10::optional); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::div") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Tensor_mode") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "div.Tensor_mode(Tensor self, Tensor other, *, str? rounding_mode) -> Tensor") + static at::Tensor call(const at::Tensor & self, const at::Tensor & other, c10::optional rounding_mode); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & other, c10::optional rounding_mode); +}; + +struct TORCH_API div__Tensor_mode { + using schema = at::Tensor & (at::Tensor &, const at::Tensor &, c10::optional); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::div_") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Tensor_mode") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "div_.Tensor_mode(Tensor(a!) self, Tensor other, *, str? rounding_mode) -> Tensor(a!)") + static at::Tensor & call(at::Tensor & self, const at::Tensor & other, c10::optional rounding_mode); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self, const at::Tensor & other, c10::optional rounding_mode); +}; + +struct TORCH_API div_out_mode { + using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, 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::div") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out_mode") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "div.out_mode(Tensor self, Tensor other, *, str? rounding_mode, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, const at::Tensor & other, c10::optional rounding_mode, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & other, c10::optional rounding_mode, at::Tensor & out); +}; + +struct TORCH_API div_Scalar { + using schema = 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::div") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Scalar") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "div.Scalar(Tensor self, Scalar other) -> Tensor") + static at::Tensor call(const at::Tensor & self, const at::Scalar & other); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Scalar & other); +}; + +struct TORCH_API div__Scalar { + using schema = at::Tensor & (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::div_") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Scalar") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "div_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)") + static at::Tensor & call(at::Tensor & self, const at::Scalar & other); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self, const at::Scalar & other); +}; + +struct TORCH_API div_Scalar_mode { + using schema = at::Tensor (const at::Tensor &, const at::Scalar &, c10::optional); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::div") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Scalar_mode") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "div.Scalar_mode(Tensor self, Scalar other, *, str? rounding_mode) -> Tensor") + static at::Tensor call(const at::Tensor & self, const at::Scalar & other, c10::optional rounding_mode); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Scalar & other, c10::optional rounding_mode); +}; + +struct TORCH_API div__Scalar_mode { + using schema = at::Tensor & (at::Tensor &, const at::Scalar &, c10::optional); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::div_") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Scalar_mode") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "div_.Scalar_mode(Tensor(a!) self, Scalar other, *, str? rounding_mode) -> Tensor(a!)") + static at::Tensor & call(at::Tensor & self, const at::Scalar & other, c10::optional rounding_mode); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self, const at::Scalar & other, c10::optional rounding_mode); +}; + +struct TORCH_API div_Scalar_out { + using schema = 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::div") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Scalar_out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "div.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, const at::Scalar & other, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Scalar & other, at::Tensor & out); +}; + +struct TORCH_API div_Scalar_mode_out { + using schema = at::Tensor & (const at::Tensor &, const at::Scalar &, 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::div") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Scalar_mode_out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "div.Scalar_mode_out(Tensor self, Scalar other, *, str? rounding_mode, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, const at::Scalar & other, c10::optional rounding_mode, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Scalar & other, c10::optional rounding_mode, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/dropout_ops.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/dropout_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..48a507437261cc748955bcd01cf015fc8b0d7e3e --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/dropout_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 dropout { + using schema = at::Tensor (const at::Tensor &, double, bool); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::dropout") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "dropout(Tensor input, float p, bool train) -> Tensor") + static at::Tensor call(const at::Tensor & input, double p, bool train); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & input, double p, bool train); +}; + +struct TORCH_API dropout_ { + using schema = at::Tensor & (at::Tensor &, double, bool); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::dropout_") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "dropout_(Tensor(a!) self, float p, bool train) -> Tensor(a!)") + static at::Tensor & call(at::Tensor & self, double p, bool train); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self, double p, bool train); +}; + +}} // namespace at::_ops diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/embedding_sparse_backward_ops.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/embedding_sparse_backward_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..cdb010bf7fa381025a6b3a49c3bfabfff92e8960 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/embedding_sparse_backward_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 embedding_sparse_backward { + using schema = at::Tensor (const at::Tensor &, const at::Tensor &, int64_t, int64_t, bool); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::embedding_sparse_backward") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "embedding_sparse_backward(Tensor grad, Tensor indices, int num_weights, int padding_idx, bool scale_grad_by_freq) -> Tensor") + static at::Tensor call(const at::Tensor & grad, const at::Tensor & indices, int64_t num_weights, int64_t padding_idx, bool scale_grad_by_freq); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & grad, const at::Tensor & indices, int64_t num_weights, int64_t padding_idx, bool scale_grad_by_freq); +}; + +}} // namespace at::_ops diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/i0_meta.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/i0_meta.h new file mode 100644 index 0000000000000000000000000000000000000000..036ec5cf8388536fa56c0f19ef6517cb5fdcc8d6 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/i0_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_i0 : public TensorIteratorBase { + + + void meta(const at::Tensor & self); +}; + +} // namespace native +} // namespace at diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/log2_ops.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/log2_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..902a17815d49cba9aca582a067a35e8d6e6ab38e --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/log2_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 log2 { + using schema = at::Tensor (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::log2") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "log2(Tensor self) -> Tensor") + static at::Tensor call(const at::Tensor & self); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self); +}; + +struct TORCH_API log2_ { + using schema = 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::log2_") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "log2_(Tensor(a!) self) -> Tensor(a!)") + static at::Tensor & call(at::Tensor & self); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self); +}; + +struct TORCH_API log2_out { + using schema = at::Tensor & (const 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::log2") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "log2.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/log_native.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/log_native.h new file mode 100644 index 0000000000000000000000000000000000000000..ea94823534933d2dca7960dbe943b644ea5fb2a3 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/log_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 +#include + +namespace at { +namespace native { +struct TORCH_API structured_log_out : public at::meta::structured_log { +void impl(const at::Tensor & self, const at::Tensor & out); +}; +} // namespace native +} // namespace at diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/min_meta_dispatch.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/min_meta_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..b1b65a44d257a0d6e80cdde77d67d5e122683d3e --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/min_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 ::std::tuple min(const at::Tensor & self, int64_t dim, bool keepdim=false); +TORCH_API ::std::tuple min_out(at::Tensor & min, at::Tensor & min_indices, const at::Tensor & self, int64_t dim, bool keepdim=false); +TORCH_API ::std::tuple min_outf(const at::Tensor & self, int64_t dim, bool keepdim, at::Tensor & min, at::Tensor & min_indices); + +} // namespace meta +} // namespace at diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/min_ops.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/min_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..2639418d2d34e3b92d58fb5893d1e56bcd93d4d4 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/min_ops.h @@ -0,0 +1,105 @@ +#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 min_dim { + using schema = ::std::tuple (const at::Tensor &, int64_t, bool); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::min") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "dim") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "min.dim(Tensor self, int dim, bool keepdim=False) -> (Tensor values, Tensor indices)") + static ::std::tuple call(const at::Tensor & self, int64_t dim, bool keepdim); + static ::std::tuple redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, int64_t dim, bool keepdim); +}; + +struct TORCH_API min_dim_min { + using schema = ::std::tuple (const at::Tensor &, int64_t, bool, 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::min") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "dim_min") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "min.dim_min(Tensor self, int dim, bool keepdim=False, *, Tensor(a!) min, Tensor(b!) min_indices) -> (Tensor(a!) values, Tensor(b!) indices)") + static ::std::tuple call(const at::Tensor & self, int64_t dim, bool keepdim, at::Tensor & min, at::Tensor & min_indices); + static ::std::tuple redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, int64_t dim, bool keepdim, at::Tensor & min, at::Tensor & min_indices); +}; + +struct TORCH_API min_names_dim { + using schema = ::std::tuple (const at::Tensor &, at::Dimname, bool); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::min") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "names_dim") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "min.names_dim(Tensor self, Dimname dim, bool keepdim=False) -> (Tensor values, Tensor indices)") + static ::std::tuple call(const at::Tensor & self, at::Dimname dim, bool keepdim); + static ::std::tuple redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::Dimname dim, bool keepdim); +}; + +struct TORCH_API min_names_dim_min { + using schema = ::std::tuple (const at::Tensor &, at::Dimname, bool, 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::min") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "names_dim_min") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "min.names_dim_min(Tensor self, Dimname dim, bool keepdim=False, *, Tensor(a!) min, Tensor(b!) min_indices) -> (Tensor(a!) values, Tensor(b!) indices)") + static ::std::tuple call(const at::Tensor & self, at::Dimname dim, bool keepdim, at::Tensor & min, at::Tensor & min_indices); + static ::std::tuple redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::Dimname dim, bool keepdim, at::Tensor & min, at::Tensor & min_indices); +}; + +struct TORCH_API min { + using schema = at::Tensor (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::min") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "min(Tensor self) -> Tensor") + static at::Tensor call(const at::Tensor & self); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self); +}; + +struct TORCH_API min_unary_out { + using schema = at::Tensor & (const 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::min") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "unary_out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "min.unary_out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::Tensor & out); +}; + +struct TORCH_API min_out { + using schema = at::Tensor & (const at::Tensor &, const 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::min") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "min.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, const at::Tensor & other, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & other, at::Tensor & out); +}; + +struct TORCH_API min_other { + using schema = at::Tensor (const at::Tensor &, 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::min") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "other") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "min.other(Tensor self, Tensor other) -> Tensor") + static at::Tensor call(const at::Tensor & self, const at::Tensor & other); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & other); +}; + +}} // namespace at::_ops diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/repeat_native.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/repeat_native.h new file mode 100644 index 0000000000000000000000000000000000000000..728d566b09073fb161e23ddf3c58e80d4ca685fe --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/repeat_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 repeat(const at::Tensor & self, at::IntArrayRef repeats); +TORCH_API at::Tensor & repeat_out_symint(const at::Tensor & self, c10::SymIntArrayRef repeats, at::Tensor & out); +} // namespace native +} // namespace at diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/special_erf_compositeimplicitautograd_dispatch.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/special_erf_compositeimplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..863a10eb0deaa82d8bf8274f9de2e149ed74693f --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/special_erf_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 special_erf(const at::Tensor & self); +TORCH_API at::Tensor & special_erf_out(at::Tensor & out, const at::Tensor & self); +TORCH_API at::Tensor & special_erf_outf(const at::Tensor & self, at::Tensor & out); + +} // namespace compositeimplicitautograd +} // namespace at diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/tril_meta.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/tril_meta.h new file mode 100644 index 0000000000000000000000000000000000000000..5d5dda9a1838505068fb8abd306c71688afb4d38 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/tril_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_tril : public at::impl::MetaBase { + + + void meta(const at::Tensor & self, int64_t diagonal); +}; + +} // namespace native +} // namespace at diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/triplet_margin_loss_ops.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/triplet_margin_loss_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..599359b395b6b8ca6a5a34ed3fdce643d947d812 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/triplet_margin_loss_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 triplet_margin_loss { + using schema = at::Tensor (const at::Tensor &, const at::Tensor &, const at::Tensor &, double, double, double, bool, int64_t); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::triplet_margin_loss") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "triplet_margin_loss(Tensor anchor, Tensor positive, Tensor negative, float margin=1.0, float p=2, float eps=1e-06, bool swap=False, int reduction=Mean) -> Tensor") + static at::Tensor call(const at::Tensor & anchor, const at::Tensor & positive, const at::Tensor & negative, double margin, double p, double eps, bool swap, int64_t reduction); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & anchor, const at::Tensor & positive, const at::Tensor & negative, double margin, double p, double eps, bool swap, int64_t reduction); +}; + +}} // namespace at::_ops diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/triu_indices.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/triu_indices.h new file mode 100644 index 0000000000000000000000000000000000000000..a31af3c930033a6cdee9a0b4cb21523beb26c11b --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/triu_indices.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::triu_indices(int row, int col, int offset=0, *, ScalarType? dtype=long, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor +inline at::Tensor triu_indices(int64_t row, int64_t col, int64_t offset=0, at::TensorOptions options=at::kLong) { + return at::_ops::triu_indices::call(row, col, offset, optTypeMetaToScalarType(options.dtype_opt()), options.layout_opt(), options.device_opt(), options.pinned_memory_opt()); +} +// aten::triu_indices(int row, int col, int offset=0, *, ScalarType? dtype=long, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor +inline at::Tensor triu_indices(int64_t row, int64_t col, int64_t offset, c10::optional dtype, c10::optional layout, c10::optional device, c10::optional pin_memory) { + return at::_ops::triu_indices::call(row, col, offset, dtype, layout, device, pin_memory); +} + +// aten::triu_indices.out(int row, int col, int offset=0, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & triu_indices_out(at::Tensor & out, int64_t row, int64_t col, int64_t offset=0) { + return at::_ops::triu_indices_out::call(row, col, offset, out); +} +// aten::triu_indices.out(int row, int col, int offset=0, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & triu_indices_outf(int64_t row, int64_t col, int64_t offset, at::Tensor & out) { + return at::_ops::triu_indices_out::call(row, col, offset, out); +} + +} diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/upsample_nearest1d_backward_cuda_dispatch.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/upsample_nearest1d_backward_cuda_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..1fff6e678303841234c14ae539d3c64ecc89ff0a --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/upsample_nearest1d_backward_cuda_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 cuda { + +TORCH_API at::Tensor upsample_nearest1d_backward(const at::Tensor & grad_output, at::IntArrayRef output_size, at::IntArrayRef input_size, c10::optional scales=c10::nullopt); +TORCH_API at::Tensor upsample_nearest1d_backward_symint(const at::Tensor & grad_output, c10::SymIntArrayRef output_size, c10::SymIntArrayRef input_size, c10::optional scales=c10::nullopt); +TORCH_API at::Tensor & upsample_nearest1d_backward_out(at::Tensor & grad_input, const at::Tensor & grad_output, at::IntArrayRef output_size, at::IntArrayRef input_size, c10::optional scales=c10::nullopt); +TORCH_API at::Tensor & upsample_nearest1d_backward_outf(const at::Tensor & grad_output, at::IntArrayRef output_size, at::IntArrayRef input_size, c10::optional scales, at::Tensor & grad_input); +TORCH_API at::Tensor & upsample_nearest1d_backward_symint_out(at::Tensor & grad_input, const at::Tensor & grad_output, c10::SymIntArrayRef output_size, c10::SymIntArrayRef input_size, c10::optional scales=c10::nullopt); +TORCH_API at::Tensor & upsample_nearest1d_backward_symint_outf(const at::Tensor & grad_output, c10::SymIntArrayRef output_size, c10::SymIntArrayRef input_size, c10::optional scales, at::Tensor & grad_input); + +} // namespace cuda +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/cupyx/distributed/__pycache__/__init__.cpython-310.pyc b/vllm/lib/python3.10/site-packages/cupyx/distributed/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cfcb6c214ba3896e231b7749a9e412a5badf9b6a Binary files /dev/null and b/vllm/lib/python3.10/site-packages/cupyx/distributed/__pycache__/__init__.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/cupyx/distributed/__pycache__/_comm.cpython-310.pyc b/vllm/lib/python3.10/site-packages/cupyx/distributed/__pycache__/_comm.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bee622ff45cc7f3194a1cc5d33dc6ab68617b414 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/cupyx/distributed/__pycache__/_comm.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/cupyx/distributed/__pycache__/_init.cpython-310.pyc b/vllm/lib/python3.10/site-packages/cupyx/distributed/__pycache__/_init.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3b0458036fc5a6ebb7dedc115b649f25cecaea9a Binary files /dev/null and b/vllm/lib/python3.10/site-packages/cupyx/distributed/__pycache__/_init.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/cupyx/distributed/__pycache__/_klv_utils.cpython-310.pyc b/vllm/lib/python3.10/site-packages/cupyx/distributed/__pycache__/_klv_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c48cb363e86f7f31234eb5c0452b34ba4f72ccc7 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/cupyx/distributed/__pycache__/_klv_utils.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/cupyx/distributed/__pycache__/_nccl_comm.cpython-310.pyc b/vllm/lib/python3.10/site-packages/cupyx/distributed/__pycache__/_nccl_comm.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..84a23dda1f2fdc3190f4132800c02d5b0e26e54f Binary files /dev/null and b/vllm/lib/python3.10/site-packages/cupyx/distributed/__pycache__/_nccl_comm.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/cupyx/distributed/__pycache__/_store.cpython-310.pyc b/vllm/lib/python3.10/site-packages/cupyx/distributed/__pycache__/_store.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c9929d1a3e5b5208708e8b0dae654c476c414276 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/cupyx/distributed/__pycache__/_store.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/cupyx/distributed/__pycache__/_store_actions.cpython-310.pyc b/vllm/lib/python3.10/site-packages/cupyx/distributed/__pycache__/_store_actions.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..70ea451c20ff202306b19756b99de92a9fa35a5d Binary files /dev/null and b/vllm/lib/python3.10/site-packages/cupyx/distributed/__pycache__/_store_actions.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/cupyx/distributed/array/__pycache__/__init__.cpython-310.pyc b/vllm/lib/python3.10/site-packages/cupyx/distributed/array/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..131c5a312c2fde0496f735a9184edb6e060911a1 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/cupyx/distributed/array/__pycache__/__init__.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/cupyx/distributed/array/__pycache__/_array.cpython-310.pyc b/vllm/lib/python3.10/site-packages/cupyx/distributed/array/__pycache__/_array.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..083ee0f4ead66b23ee234f1d328ee5ee4d2dd644 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/cupyx/distributed/array/__pycache__/_array.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/cupyx/distributed/array/__pycache__/_chunk.cpython-310.pyc b/vllm/lib/python3.10/site-packages/cupyx/distributed/array/__pycache__/_chunk.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a02720bf0d22bfebdc7620318274efbe9ddefa26 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/cupyx/distributed/array/__pycache__/_chunk.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/cupyx/distributed/array/__pycache__/_data_transfer.cpython-310.pyc b/vllm/lib/python3.10/site-packages/cupyx/distributed/array/__pycache__/_data_transfer.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d99dc26bf0e7799fc18d0895639855336f399298 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/cupyx/distributed/array/__pycache__/_data_transfer.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/cupyx/distributed/array/__pycache__/_elementwise.cpython-310.pyc b/vllm/lib/python3.10/site-packages/cupyx/distributed/array/__pycache__/_elementwise.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a6671c6a717b771b01b24f28ff6ed6228a4051ed Binary files /dev/null and b/vllm/lib/python3.10/site-packages/cupyx/distributed/array/__pycache__/_elementwise.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/cupyx/distributed/array/__pycache__/_index_arith.cpython-310.pyc b/vllm/lib/python3.10/site-packages/cupyx/distributed/array/__pycache__/_index_arith.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8c6c01e44caf5ce3cf781f3664b445d01c80242c Binary files /dev/null and b/vllm/lib/python3.10/site-packages/cupyx/distributed/array/__pycache__/_index_arith.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/cupyx/distributed/array/__pycache__/_linalg.cpython-310.pyc b/vllm/lib/python3.10/site-packages/cupyx/distributed/array/__pycache__/_linalg.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a63e5185d669b2832c812b7cea8b3f37d3476b7c Binary files /dev/null and b/vllm/lib/python3.10/site-packages/cupyx/distributed/array/__pycache__/_linalg.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/cupyx/distributed/array/__pycache__/_modes.cpython-310.pyc b/vllm/lib/python3.10/site-packages/cupyx/distributed/array/__pycache__/_modes.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e7db35c53395a9dc1015951ef4c2da4f5405d15f Binary files /dev/null and b/vllm/lib/python3.10/site-packages/cupyx/distributed/array/__pycache__/_modes.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/cupyx/distributed/array/__pycache__/_reduction.cpython-310.pyc b/vllm/lib/python3.10/site-packages/cupyx/distributed/array/__pycache__/_reduction.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..659c4cc38fda7b1c44fdfa28592447d04a7cb0c6 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/cupyx/distributed/array/__pycache__/_reduction.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/cupyx/distributed/array/_array.py b/vllm/lib/python3.10/site-packages/cupyx/distributed/array/_array.py new file mode 100644 index 0000000000000000000000000000000000000000..9b185bbc85788a0c3b2631d2af74341a52ed16ff --- /dev/null +++ b/vllm/lib/python3.10/site-packages/cupyx/distributed/array/_array.py @@ -0,0 +1,899 @@ +from itertools import chain +from typing import Any, Callable, Iterable, Optional + +import numpy +from numpy.typing import ArrayLike +from numpy.typing import DTypeLike + +import cupy +from cupy._core.core import ndarray +import cupy._creation.from_data as _creation_from_data +import cupy._core._routines_math as _math +import cupy._core._routines_statistics as _statistics +from cupy.cuda.device import Device +from cupy.cuda.stream import Stream +from cupy.cuda.stream import get_current_stream + +from cupyx.distributed.array import _chunk +from cupyx.distributed.array._chunk import _Chunk +from cupyx.distributed.array import _data_transfer +from cupyx.distributed.array._data_transfer import _Communicator +from cupyx.distributed.array import _elementwise +from cupyx.distributed.array import _index_arith +from cupyx.distributed.array import _modes +from cupyx.distributed.array import _reduction +from cupyx.distributed.array import _linalg + + +class _MultiDeviceDummyMemory(cupy.cuda.memory.Memory): + pass + + +class _MultiDeviceDummyPointer(cupy.cuda.memory.MemoryPointer): + @property + def device(self) -> Device: + # This override is needed to assign an invalid device id + # Since the array is not residing in a single device now + return Device(-1) + + +def _make_chunk_async(src_dev, dst_dev, idx, src_array, comms): + src_stream = get_current_stream(src_dev) + with src_array.device: + src_array = _creation_from_data.ascontiguousarray(src_array) + src_data = _data_transfer._AsyncData( + src_array, src_stream.record(), prevent_gc=src_array) + with Device(dst_dev): + dst_stream = get_current_stream() + copied = _data_transfer._transfer( + comms[src_dev], src_stream, src_data, + comms[dst_dev], dst_stream, dst_dev) + return _Chunk(copied.array, copied.ready, idx, + prevent_gc=src_data) + + +def _make_chunk_sync(src_dev, dst_dev, idx, src_array, comms): + with Device(dst_dev): + stream = get_current_stream() + copied = _creation_from_data.array(src_array) + return _Chunk(copied, stream.record(), idx, prevent_gc=src_array) + + +class DistributedArray(ndarray): + """ + __init__(self, shape, dtype, chunks_map, mode=REPLICA, comms=None) + + Multi-dimensional array distributed across multiple CUDA devices. + + This class implements some elementary operations that :class:`cupy.ndarray` + provides. The array content is split into chunks, contiguous arrays + corresponding to slices of the original array. Note that one device can + hold multiple chunks. + + This direct constructor is designed for internal calls. Users should create + distributed arrays using :func:`distributed_array`. + + Args: + shape (tuple of ints): Shape of created array. + dtype (dtype_like): Any object that can be interpreted as a numpy data + type. + chunks_map (dict from int to list of chunks): Lists of chunk objects + associated with each device. + mode (mode object, optional): Mode that determines how overlaps + of the chunks are interpreted. Defaults to + ``cupyx.distributed.array.REPLICA``. + comms (optional): Communicator objects which a distributed array + hold internally. Sharing them with other distributed arrays can + save time because their initialization is a costly operation. + + .. seealso:: + :attr:`DistributedArray.mode` for details about modes. + """ + + _chunks_map: dict[int, list[_Chunk]] + _mode: _modes.Mode + _streams: dict[int, Stream] + _comms: dict[int, _Communicator] + + def __new__( + cls, shape: tuple[int, ...], dtype: DTypeLike, + chunks_map: dict[int, list[_Chunk]], + mode: _modes.Mode = _modes.REPLICA, + comms: Optional[dict[int, _Communicator]] = None, + ) -> 'DistributedArray': + mem = _MultiDeviceDummyMemory(0) + memptr = _MultiDeviceDummyPointer(mem, 0) + obj = super().__new__(cls, shape, dtype, memptr=memptr) + obj._chunks_map = chunks_map + + obj._mode = mode + + obj._streams = {} + obj._comms = comms if comms is not None else {} + + return obj + + def __init__(self, *args, **kwargs) -> None: + super().__init__(*args, **kwargs) + + def __array_finalize__(self, obj): + if obj is not None: + raise RuntimeError( + 'Distributed array can only be instantiated by an explicit' + 'constructor call') + + @property + def mode(self) -> _modes.Mode: + """Describe how overlaps of the chunks are interpreted. + + In the replica mode, chunks are guaranteed to have identical values on + their overlapping segments. In other modes, they are not necessarily + identical and represent the original data as their max, sum, etc. + + :class:`DistributedArray` currently supports + ``cupyx.distributed.array.REPLICA``, ``cupyx.distributed.array.MIN``, + ``cupyx.distributed.array.MAX``, ``cupyx.distributed.array.SUM``, + ``cupyx.distributed.array.PROD`` modes. + + Many operations on distributed arrays including :class:`cupy.ufunc` + and :func:`~cupyx.distributed.array.matmul` involve changing their mode + beforehand. These mode conversions are done automatically, so in most + cases users do not have to manage modes manually. + + Example: + >>> A = distributed_array( + ... cupy.arange(6).reshape(2, 3), + ... make_2d_index_map([0, 2], [0, 1, 3], + ... [[{0}, {1, 2}]])) + >>> B = distributed_array( + ... cupy.arange(12).reshape(3, 4), + ... make_2d_index_map([0, 1, 3], [0, 2, 4], + ... [[{0}, {0}], + ... [{1}, {2}]])) + >>> C = A @ B + >>> C + array([[20, 23, 26, 29], + [56, 68, 80, 92]]) + >>> C.mode + 'sum' + >>> C.all_chunks() + {0: [array([[0, 0], + [0, 3]]), # left half + array([[0, 0], + [6, 9]])], # right half + 1: [array([[20, 23], + [56, 65]])], # left half + 2: [array([[26, 29], + [74, 83]])]} # right half + >>> C_replica = C.change_mode('replica') + >>> C_replica.mode + 'replica' + >>> C_replica.all_chunks() + {0: [array([[20, 23], + [56, 68]]), # left half + array([[26, 29], + [80, 92]])], # right half + 1: [array([[20, 23], + [56, 68]])], # left half + 2: [array([[26, 29], + [80, 92]])]} # right half + """ + return self._mode + + @property + def devices(self) -> Iterable[int]: + """A collection of device IDs holding part of the data.""" + return self._chunks_map.keys() + + @property + def index_map(self) -> dict[int, list[tuple[slice, ...]]]: + """Indices for the chunks that devices with designated IDs own.""" + return {dev: [chunk.index for chunk in chunks] + for dev, chunks in self._chunks_map.items()} + + def all_chunks(self) -> dict[int, list[ndarray]]: + """Return the chunks with all buffered data flushed. + + Buffered data are created in situations such as resharding and mode + changing. + """ + chunks_map: dict[int, list[ndarray]] = {} + for dev, chunks in self._chunks_map.items(): + chunks_map[dev] = [] + for chunk in chunks: + chunk.flush(self._mode) + chunks_map[dev].append(chunk.array) + return chunks_map + + def _prepare_comms_and_streams(self, devices: Iterable[int]) -> None: + # Ensure communicators and streams are prepared for communication + # between `devices` and the devices currently owning chunks + devices = self._chunks_map.keys() | devices + + if not devices.issubset(self._comms.keys()): + self._comms = _data_transfer._create_communicators(devices) + + for dev in devices - self._streams.keys(): + with Device(dev): + self._streams[dev] = Stream() + + def __cupy_override_elementwise_kernel__(self, kernel, *args, **kwargs): + # This method is called from cupy.ufunc and cupy.ElementwiseKernel + # to dispatch elementwise operations + return _elementwise._execute(kernel, args, kwargs) + + def __cupy_override_reduction_kernel__( + self, kernel, axis, dtype, out, keepdims) -> Any: + # This method is called from _SimpleReductionKernel and elementary + # reduction methods of ndarray to dispatch reduction operations + # TODO: Support user-defined ReductionKernel + if axis is None: + raise RuntimeError('axis must be specified') + if out is not None: + raise RuntimeError('Argument `out` is not supported') + if keepdims: + raise RuntimeError('Argument `keepdims` is not supported') + + return _reduction._execute(self, kernel, axis, dtype) + + def __array_ufunc__(self, ufunc, method, *inputs, **kwargs): + if ufunc.__name__ == 'matmul' and method == '__call__': + return _linalg.matmul(*inputs, **kwargs) + return NotImplemented + + def __matmul__(x, y): + if isinstance(y, DistributedArray): + return _linalg.matmul(x, y) + else: + return NotImplemented + + def _copy_chunks_map_in_replica_mode(self) -> dict[int, list[_Chunk]]: + # Return a copy of self.chunks_map in the replica mode + chunks_map = {} + for dev, chunks in self._chunks_map.items(): + chunks_map[dev] = [chunk.copy() for chunk in chunks] + + if self._mode is not _modes.REPLICA: + self._prepare_comms_and_streams(self._chunks_map.keys()) + _chunk._all_reduce_intersections( + self._mode, self.shape, chunks_map, self._comms, self._streams) + + return chunks_map + + def _copy_chunks_map_in_op_mode( + self, op_mode: _modes._OpMode) -> dict[int, list[_Chunk]]: + # Return a copy of self.chunks_map in the given op mode + chunks_map = self._copy_chunks_map_in_replica_mode() + + for chunk in chain.from_iterable(chunks_map.values()): + chunk.flush(_modes.REPLICA) + + chunks_list = list(chain.from_iterable(chunks_map.values())) + identity = op_mode.identity_of(self.dtype) + + # TODO: Fair distribution of work + # In the current implementation, devices that appear earlier have to + # execute set_identity_on_intersection repeatedly, whereas the last + # device has no work to do + for i in range(len(chunks_list)): + a_chunk = chunks_list[i] + for j in range(i + 1, len(chunks_list)): + b_chunk = chunks_list[j] + a_chunk.set_identity_on_intersection( + b_chunk.index, self.shape, identity) + + return chunks_map + + def _to_op_mode(self, op_mode: _modes.Mode) -> 'DistributedArray': + # Return a view or a copy of the chunks_map in the given mode + if self._mode is op_mode: + return self + + if len(self._chunks_map) == 1: + chunks, = self._chunks_map.values() + if len(chunks) == 1: + chunks[0].flush(self._mode) + return DistributedArray( + self.shape, self.dtype, self._chunks_map, + op_mode, self._comms) + if op_mode is _modes.REPLICA: + chunks_map = self._copy_chunks_map_in_replica_mode() + else: + assert op_mode is not None + chunks_map = self._copy_chunks_map_in_op_mode(op_mode) + return DistributedArray( + self.shape, self.dtype, chunks_map, op_mode, self._comms) + + def change_mode(self, mode: _modes.Mode) -> 'DistributedArray': + """Return a view or a copy in the given mode. + + Args: + mode (mode Object): How overlaps of + the chunks are interpreted. + + .. seealso:: + :attr:`DistributedArray.mode` for details about modes. + """ + return self._to_op_mode(mode) + + def reshard(self, index_map: dict[int, Any]) -> 'DistributedArray': + """Return a view or a copy having the given index_map. + + Data transfers across devices are done on separate streams created + internally. To make them asynchronous, transferred data is buffered and + reflected to the chunks when necessary. + + Args: + index_map (dict from int to array indices): Indices for the chunks + that devices with designated IDs own. The current index_map of + a distributed array can be obtained from + :attr:`DistributedArray.index_map`. + """ + new_index_map = _index_arith._normalize_index_map( + self.shape, index_map) + if new_index_map == self.index_map: + return self + + old_chunks_map = self._chunks_map + new_chunks_map: dict[int, list[_Chunk]] = {} + + # Set up new_chunks_map compatible with new_index_map + # as placeholders of chunks + for dev, idxs in new_index_map.items(): + new_chunks_map[dev] = [] + + for idx in idxs: + with Device(dev): + dst_shape = _index_arith._shape_after_indexing( + self.shape, idx) + new_chunk = _Chunk.create_placeholder(dst_shape, dev, idx) + new_chunks_map[dev].append(new_chunk) + + self._prepare_comms_and_streams(index_map.keys()) + + # Data transfer from old chunks to new chunks + # TODO: Reorder transfers to minimize latency + + # The current implementation transfers the same data multiple times + # where chunks overlap. This is particularly problematic when matrix + # multiplication is involved, where one block tends to be shared + # between multiple devices + # TODO: Avoid duplicate data transfers + for src_chunk in chain.from_iterable(old_chunks_map.values()): + src_chunk.flush(self._mode) + + if self._mode is not _modes.REPLICA: + src_chunk = src_chunk.copy() + + for dst_chunk in chain.from_iterable(new_chunks_map.values()): + src_chunk.apply_to( + dst_chunk, self._mode, self.shape, + self._comms, self._streams) + + return DistributedArray( + self.shape, self.dtype, new_chunks_map, self._mode, self._comms) + + def get( + self, stream=None, order='C', out=None, blocking=True + ) -> numpy.ndarray: + """Return a copy of the array on the host memory.""" + if stream is not None: + raise RuntimeError('Argument `stream` not supported') + if order != 'C': + raise RuntimeError('Argument `order` not supported') + if out is not None: + raise RuntimeError('Argument `out` not supported') + + for chunk in chain.from_iterable(self._chunks_map.values()): + chunk.flush(self._mode) + + if self._mode is _modes.REPLICA: + np_array = numpy.empty(self.shape, dtype=self.dtype) + else: + identity = self._mode.identity_of(self.dtype) + np_array = numpy.full(self.shape, identity, self.dtype) + + # We avoid 0D array because we expect data[idx] to return a view + np_array = numpy.atleast_1d(np_array) + + for chunk in chain.from_iterable(self._chunks_map.values()): + chunk.ready.synchronize() + idx = chunk.index + if self._mode is _modes.REPLICA: + np_array[idx] = cupy.asnumpy(chunk.array) + else: + self._mode.numpy_func( + np_array[idx], cupy.asnumpy(chunk.array), np_array[idx]) + + # Undo numpy.atleast_1d + return np_array.reshape(self.shape) + + # ----------------------------------------------------- + # Overriding unsupported methods inherited from ndarray + # ----------------------------------------------------- + + def __getitem__(self, *args, **kwargs): + """Not supported.""" + raise NotImplementedError( + 'DistributedArray currently does not support __getitem__.') + + def __setitem__(self, *args, **kwargs): + """Not supported.""" + raise NotImplementedError( + 'DistributedArray currently does not support __setitem__.') + + def __len__(self, *args, **kwargs): + """Not supported.""" + raise NotImplementedError( + 'DistributedArray currently does not support __len__.') + + def __iter__(self, *args, **kwargs): + """Not supported.""" + raise NotImplementedError( + 'DistributedArray currently does not support __iter__.') + + def __copy__(self, *args, **kwargs): + """Not supported.""" + raise NotImplementedError( + 'DistributedArray currently does not support __copy__.') + + def all(self, *args, **kwargs): + """Not supported.""" + raise NotImplementedError( + 'DistributedArray currently does not support all.') + + def any(self, *args, **kwargs): + """Not supported.""" + raise NotImplementedError( + 'DistributedArray currently does not support any.') + + def argmax(self, *args, **kwargs): + """Not supported.""" + raise NotImplementedError( + 'DistributedArray currently does not support argmax.') + + def argmin(self, *args, **kwargs): + """Not supported.""" + raise NotImplementedError( + 'DistributedArray currently does not support argmin.') + + def argpartition(self, *args, **kwargs): + """Not supported.""" + raise NotImplementedError( + 'DistributedArray currently does not support argpartition.') + + def argsort(self, *args, **kwargs): + """Not supported.""" + raise NotImplementedError( + 'DistributedArray currently does not support argsort.') + + def astype(self, *args, **kwargs): + """Not supported.""" + raise NotImplementedError( + 'DistributedArray currently does not support astype.') + + def choose(self, *args, **kwargs): + """Not supported.""" + raise NotImplementedError( + 'DistributedArray currently does not support choose.') + + def clip(self, *args, **kwargs): + """Not supported.""" + raise NotImplementedError( + 'DistributedArray currently does not support clip.') + + def compress(self, *args, **kwargs): + """Not supported.""" + raise NotImplementedError( + 'DistributedArray currently does not support compress.') + + def copy(self, *args, **kwargs): + """Not supported.""" + raise NotImplementedError( + 'DistributedArray currently does not support copy.') + + def cumprod(self, *args, **kwargs): + """Not supported.""" + raise NotImplementedError( + 'DistributedArray currently does not support cumprod.') + + def cumsum(self, *args, **kwargs): + """Not supported.""" + raise NotImplementedError( + 'DistributedArray currently does not support cumsum.') + + def diagonal(self, *args, **kwargs): + """Not supported.""" + raise NotImplementedError( + 'DistributedArray currently does not support diagonal.') + + def dot(self, *args, **kwargs): + """Not supported.""" + raise NotImplementedError( + 'DistributedArray currently does not support dot.') + + def dump(self, *args, **kwargs): + """Not supported.""" + raise NotImplementedError( + 'DistributedArray currently does not support dump.') + + def dumps(self, *args, **kwargs): + """Not supported.""" + raise NotImplementedError( + 'DistributedArray currently does not support dumps.') + + def fill(self, *args, **kwargs): + """Not supported.""" + raise NotImplementedError( + 'DistributedArray currently does not support fill.') + + def flatten(self, *args, **kwargs): + """Not supported.""" + raise NotImplementedError( + 'DistributedArray currently does not support flatten.') + + def item(self, *args, **kwargs): + """Not supported.""" + raise NotImplementedError( + 'DistributedArray currently does not support item.') + + def max(self, axis=None, out=None, keepdims=False): + """Return the maximum along a given axis. + + .. note:: + + Currently, it only supports non-``None`` values for ``axis`` and + the default values for ``out`` and ``keepdims``. + + .. seealso:: + :meth:`cupy.ndarray.max`, :meth:`numpy.ndarray.max` + """ + return self.__cupy_override_reduction_kernel__( + _statistics.amax, axis, None, out, keepdims) + + def mean(self, *args, **kwargs): + """Not supported.""" + raise NotImplementedError( + 'DistributedArray currently does not support mean.') + + def min(self, axis=None, out=None, keepdims=False): + """Return the minimum along a given axis. + + .. note:: + + Currently, it only supports non-``None`` values for ``axis`` and + the default values for ``out`` and ``keepdims``. + + .. seealso:: + :meth:`cupy.ndarray.min`, :meth:`numpy.ndarray.min` + """ + return self.__cupy_override_reduction_kernel__( + _statistics.amin, axis, None, out, keepdims) + + def nonzero(self, *args, **kwargs): + """Not supported.""" + raise NotImplementedError( + 'DistributedArray currently does not support nonzero.') + + def partition(self, *args, **kwargs): + """Not supported.""" + raise NotImplementedError( + 'DistributedArray currently does not support partition.') + + def prod(self, axis=None, dtype=None, out=None, keepdims=None): + """Return the minimum along a given axis. + + .. note:: + + Currently, it only supports non-``None`` values for ``axis`` and + the default values for ``out`` and ``keepdims``. + + .. seealso:: + :meth:`cupy.ndarray.prod`, :meth:`numpy.ndarray.prod` + """ + if dtype is None: + return self.__cupy_override_reduction_kernel__( + _math.prod_auto_dtype, axis, dtype, out, keepdims) + else: + return self.__cupy_override_reduction_kernel__( + _math.prod_keep_dtype, axis, dtype, out, keepdims) + + def ptp(self, *args, **kwargs): + """Not supported.""" + raise NotImplementedError( + 'DistributedArray currently does not support ptp.') + + def put(self, *args, **kwargs): + """Not supported.""" + raise NotImplementedError( + 'DistributedArray currently does not support put.') + + def ravel(self, *args, **kwargs): + """Not supported.""" + raise NotImplementedError( + 'DistributedArray currently does not support ravel.') + + def reduced_view(self, *args, **kwargs): + """Not supported.""" + raise NotImplementedError( + 'DistributedArray currently does not support reduced_view.') + + def repeat(self, *args, **kwargs): + """Not supported.""" + raise NotImplementedError( + 'DistributedArray currently does not support repeat.') + + def reshape(self, *args, **kwargs): + """Not supported.""" + raise NotImplementedError( + 'DistributedArray currently does not support reshape.') + + def round(self, *args, **kwargs): + """Not supported.""" + raise NotImplementedError( + 'DistributedArray currently does not support round.') + + def scatter_add(self, *args, **kwargs): + """Not supported.""" + raise NotImplementedError( + 'DistributedArray currently does not support scatter_add.') + + def scatter_max(self, *args, **kwargs): + """Not supported.""" + raise NotImplementedError( + 'DistributedArray currently does not support scatter_max.') + + def scatter_min(self, *args, **kwargs): + """Not supported.""" + raise NotImplementedError( + 'DistributedArray currently does not support scatter_min.') + + def searchsorted(self, *args, **kwargs): + """Not supported.""" + raise NotImplementedError( + 'DistributedArray currently does not support searchsorted.') + + def set(self, *args, **kwargs): + """Not supported.""" + raise NotImplementedError( + 'DistributedArray currently does not support set.') + + def sort(self, *args, **kwargs): + """Not supported.""" + raise NotImplementedError( + 'DistributedArray currently does not support sort.') + + def squeeze(self, *args, **kwargs): + """Not supported.""" + raise NotImplementedError( + 'DistributedArray currently does not support squeeze.') + + def std(self, *args, **kwargs): + """Not supported.""" + raise NotImplementedError( + 'DistributedArray currently does not support std.') + + def sum(self, axis=None, dtype=None, out=None, keepdims=False): + """Return the minimum along a given axis. + + .. note:: + + Currently, it only supports non-``None`` values for ``axis`` and + the default values for ``out`` and ``keepdims``. + + .. seealso:: + :meth:`cupy.ndarray.sum`, :meth:`numpy.ndarray.sum` + """ + if dtype is None: + return self.__cupy_override_reduction_kernel__( + _math.sum_auto_dtype, axis, dtype, out, keepdims) + else: + return self.__cupy_override_reduction_kernel__( + _math.sum_keep_dtype, axis, dtype, out, keepdims) + + def swapaxes(self, *args, **kwargs): + """Not supported.""" + raise NotImplementedError( + 'DistributedArray currently does not support swapaxes.') + + def take(self, *args, **kwargs): + """Not supported.""" + raise NotImplementedError( + 'DistributedArray currently does not support take.') + + def toDlpack(self, *args, **kwargs): + """Not supported.""" + raise NotImplementedError( + 'DistributedArray currently does not support toDlpack.') + + def tobytes(self, *args, **kwargs): + """Not supported.""" + raise NotImplementedError( + 'DistributedArray currently does not support tobytes.') + + def tofile(self, *args, **kwargs): + """Not supported.""" + raise NotImplementedError( + 'DistributedArray currently does not support tofile.') + + def tolist(self, *args, **kwargs): + """Not supported.""" + raise NotImplementedError( + 'DistributedArray currently does not support tolist.') + + def trace(self, *args, **kwargs): + """Not supported.""" + raise NotImplementedError( + 'DistributedArray currently does not support trace.') + + def transpose(self, *args, **kwargs): + """Not supported.""" + raise NotImplementedError( + 'DistributedArray currently does not support transpose.') + + def var(self, *args, **kwargs): + """Not supported.""" + raise NotImplementedError( + 'DistributedArray currently does not support var.') + + def view(self, *args, **kwargs): + """Not supported.""" + raise NotImplementedError( + 'DistributedArray currently does not support view.') + + @property + def T(self): + """Not supported.""" + raise NotImplementedError( + 'DistributedArray currently does not support T.') + + @property + def base(self): + """Not supported.""" + raise NotImplementedError( + 'DistributedArray currently does not support base.') + + @property + def cstruct(self): + """Not supported.""" + raise NotImplementedError( + 'DistributedArray currently does not support cstruct.') + + @property + def data(self): + """Not supported.""" + raise NotImplementedError( + 'DistributedArray currently does not support data.') + + @property + def device(self): + """Not supported.""" + raise NotImplementedError( + 'DistributedArray currently does not support device.') + + @property + def flags(self): + """Not supported.""" + raise NotImplementedError( + 'DistributedArray currently does not support flags.') + + @property + def flat(self): + """Not supported.""" + raise NotImplementedError( + 'DistributedArray currently does not support flat.') + + @property + def imag(self): + """Not supported.""" + raise NotImplementedError( + 'DistributedArray currently does not support imag.') + + @property + def real(self): + """Not supported.""" + raise NotImplementedError( + 'DistributedArray currently does not support real.') + + @property + def shape(self): + """Tuple of array dimensions. + + Assignment to this property is currently not supported. + + .. seealso: :attr:`cupy.ndarray.shape`, :attr:`numpy.ndarray.shape` + + """ + return super().shape + + @shape.setter + def shape(self, newshape): + raise NotImplementedError( + 'DistributedArray currently does not support assignment to shape.') + + @property + def strides(self): + """Not supported.""" + raise NotImplementedError( + 'DistributedArray currently does not support strides.') + + +def distributed_array( + array: ArrayLike, + index_map: dict[int, Any], + mode: _modes.Mode = _modes.REPLICA, +) -> DistributedArray: + """Creates a distributed array from the given data. + + This function does not check if all elements of the given array are stored + in some of the chunks. + + Args: + array (array_like): :class:`DistributedArray` object, + :class:`cupy.ndarray` object or any other object that can be passed + to :func:`numpy.array`. + index_map (dict from int to array indices): Indices for the chunks + that devices with designated IDs own. One device can have multiple + chunks, which can be specified as a list of array indices. + mode (mode object, optional): Mode that determines how overlaps + of the chunks are interpreted. Defaults to + ``cupyx.distributed.array.REPLICA``. + + .. seealso:: + :attr:`DistributedArray.mode` for details about modes. + + Example: + >>> array = cupy.arange(9).reshape(3, 3) + >>> A = distributed_array( + ... array, + ... {0: [(slice(2), slice(2)), # array[:2, :2] + ... slice(None, None, 2)], # array[::2] + ... 1: (slice(1, None), 2)}) # array[1:, 2] + """ + if isinstance(array, DistributedArray): + if array.mode != mode: + array = array.change_mode(mode) + if array.index_map != index_map: + array = array.reshard(index_map) + return DistributedArray( + array.shape, array.dtype, array._chunks_map, array._mode, + array._comms) + + if isinstance(array, (numpy.ndarray, ndarray)): + if mode != _modes.REPLICA: + array = array.copy() + else: + array = numpy.array(array) + + index_map = _index_arith._normalize_index_map(array.shape, index_map) + comms = None + + # Define how to form a chunk from (dev, idx, src_array) + make_chunk: Callable[ + [int, int, tuple[slice, ...], ndarray, Optional[list[Any]]], + _Chunk + ] + + if isinstance(array, ndarray): + src_dev = array.device.id + devices = index_map.keys() | {array.device.id} + comms = _data_transfer._create_communicators(devices) + make_chunk = _make_chunk_async + else: + src_dev = -1 + make_chunk = _make_chunk_sync + + chunks_map: dict[int, list[_Chunk]] = {} + for dev, idxs in index_map.items(): + chunks_map[dev] = [] + + for idx in idxs: + chunk_array = array[idx] + chunk = make_chunk(src_dev, dev, idx, chunk_array, comms) + chunks_map[dev].append(chunk) + if (mode is not _modes.REPLICA + and not mode.idempotent): + array[idx] = mode.identity_of(array.dtype) + + return DistributedArray( + array.shape, array.dtype, chunks_map, mode, comms) diff --git a/vllm/lib/python3.10/site-packages/cupyx/distributed/array/_chunk.py b/vllm/lib/python3.10/site-packages/cupyx/distributed/array/_chunk.py new file mode 100644 index 0000000000000000000000000000000000000000..702572529ca8517cdaaf40c89ba34d9694cd8f22 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/cupyx/distributed/array/_chunk.py @@ -0,0 +1,228 @@ +import contextlib +from itertools import chain +from typing import Any, Iterator, Optional, Union + +import numpy + +from cupy._core.core import ndarray +import cupy._creation.basic as _creation_basic +import cupy._manipulation.dims as _manipulation_dims +from cupy.cuda.device import Device +from cupy.cuda.stream import Event +from cupy.cuda.stream import Stream +from cupy.cuda.stream import get_current_stream + +from cupyx.distributed.array import _modes +from cupyx.distributed.array import _index_arith +from cupyx.distributed.array import _data_transfer +from cupyx.distributed.array._data_transfer import _Communicator + + +class _ArrayPlaceholder: + # Mocks ndarray + # Eventually overwritten by PartialUpdates entirely, so + # any operation on _DataPlaceholder can be skipped + shape: tuple[int, ...] + device: Device + + def __init__(self, shape: tuple[int, ...], device: Device) -> None: + self.shape = shape + self.device = device + + def reshape(self, new_shape: tuple[int, ...]) -> '_ArrayPlaceholder': + return _ArrayPlaceholder(new_shape, self.device) + + def to_ndarray( + self, mode: '_modes.Mode', dtype: numpy.dtype) -> ndarray: + with self.device: + if mode is _modes.REPLICA: + data = _creation_basic.empty(self.shape, dtype) + else: + value = mode.identity_of(dtype) + data = _creation_basic.full(self.shape, value, dtype) + + # We avoid 0D array because we expect data[idx] to return a view + return _manipulation_dims.atleast_1d(data) + + +class _Chunk: + array: Union[ndarray, _ArrayPlaceholder] + ready: Event + index: tuple[slice, ...] + updates: list[_data_transfer._PartialUpdate] + prevent_gc: Any = None # TODO: Release it to avoid OOM + + # Rule: whenever data is DataPlaceholder, ready is empty + + def __init__( + self, data: Union[ndarray, _ArrayPlaceholder], ready: Event, + index: tuple[slice, ...], + updates: Optional[list[_data_transfer._PartialUpdate]] = None, + prevent_gc: Any = None + ) -> None: + self.array = data + self.ready = ready + self.index = index + self.updates = updates if updates is not None else [] + self.prevent_gc = prevent_gc + + @classmethod + def create_placeholder( + cls, shape: tuple[int, ...], device: Union[int, Device], + index: tuple[slice, ...], + updates: Optional[list[_data_transfer._PartialUpdate]] = None, + ) -> '_Chunk': + if isinstance(device, int): + device = Device(device) + + data = _ArrayPlaceholder(shape, device) + with device: + ready = Event() + if updates is None: + updates = [] + + return _Chunk(data, ready, index, updates) + + @contextlib.contextmanager + def on_ready(self) -> Iterator[Stream]: + with self.array.device: + stream = get_current_stream() + stream.wait_event(self.ready) + yield stream + + def add_update( + self, update: _data_transfer._AsyncData, idx: tuple[slice, ...], + ) -> None: + self.updates.append((update, idx)) + + def copy(self) -> '_Chunk': + # TODO: Calling flush here would reduce the amount of future copying + if isinstance(self.array, _ArrayPlaceholder): + data = self.array + ready = self.ready + else: + with self.on_ready() as stream: + data = self.array.copy() + ready = stream.record() + + return _Chunk(data, ready, self.index, list(self.updates), + prevent_gc=self.prevent_gc) + + def flush(self, mode: '_modes.Mode') -> None: + """Apply all updates in-place.""" + if len(self.updates) == 0: + return + + if isinstance(self.array, _ArrayPlaceholder): + dtype = self.updates[0][0].array.dtype + self.array = self.array.to_ndarray(mode, dtype) + + with self.on_ready() as stream: + for update_data, idx in self.updates: + stream.wait_event(update_data.ready) + if mode is _modes.REPLICA: + self.array[idx] = update_data.array + else: + self.array[idx] = mode.func( + self.array[idx], update_data.array) + + stream.record(self.ready) + self.prevent_gc = (self.prevent_gc, self.updates) + self.updates = [] + + def apply_to( + self, target: '_Chunk', mode: '_modes.Mode', + shape: tuple[int, ...], + comms: dict[int, _data_transfer._Communicator], + streams: dict[int, Stream], + ) -> None: + # Overwrite target with mode.func(self, target) on their overlaps + # This is just appending part of self to target.updates in the mode + src_chunk = self + dst_chunk = target + + assert len(src_chunk.updates) == 0 + assert isinstance(src_chunk.array, ndarray) + + src_dev = src_chunk.array.device.id + dst_dev = dst_chunk.array.device.id + src_idx = src_chunk.index + dst_idx = dst_chunk.index + + intersection = _index_arith._index_intersection( + src_idx, dst_idx, shape) + if intersection is None: + return + + src_new_idx = _index_arith._index_for_subindex( + src_idx, intersection, shape) + dst_new_idx = _index_arith._index_for_subindex( + dst_idx, intersection, shape) + + data_to_transfer = _data_transfer._AsyncData( + src_chunk.array[src_new_idx], src_chunk.ready, + src_chunk.prevent_gc) + + if mode is not _modes.REPLICA and not mode.idempotent: + data_to_transfer = data_to_transfer.copy() + + update = _data_transfer._transfer( + comms[src_dev], streams[src_dev], data_to_transfer, + comms[dst_dev], streams[dst_dev], dst_dev) + dst_chunk.add_update(update, dst_new_idx) + + if mode is not _modes.REPLICA and not mode.idempotent: + dtype = src_chunk.array.dtype + with data_to_transfer.on_ready() as stream: + # Now src data has been copied, so we can write on src_chunk + src_chunk.array[src_new_idx] = mode.identity_of(dtype) + stream.record(src_chunk.ready) + + def set_identity_on_intersection( + self, idx: tuple[slice, ...], shape: tuple[int, ...], identity, + ) -> None: + assert isinstance(self.array, ndarray) + + intersection = _index_arith._index_intersection(self.index, idx, shape) + if intersection is None: + return + self_new_idx = _index_arith._index_for_subindex( + self.index, intersection, shape) + with self.on_ready() as stream: + self.array[self_new_idx] = identity + stream.record(self.ready) + + def set_identity_on_overwritten_entries(self, identity) -> None: + if isinstance(self.array, _ArrayPlaceholder): + return + + with self.on_ready() as stream: + for _, idx in self.updates: + self.array[idx] = identity + stream.record(self.ready) + + +def _all_reduce_intersections( + op_mode: '_modes._OpMode', shape: tuple[int, ...], + chunk_map: dict[int, list[_Chunk]], + comms: dict[int, _Communicator], streams: dict[int, Stream], +) -> None: + chunks_list = list(chain.from_iterable(chunk_map.values())) + + for i in range(len(chunks_list)): + src_chunk = chunks_list[i] + src_chunk.flush(op_mode) + + for j in range(i + 1, len(chunks_list)): + dst_chunk = chunks_list[j] + + src_chunk.apply_to(dst_chunk, op_mode, shape, comms, streams) + + for j in range(len(chunks_list) - 1, -1, -1): + src_chunk = chunks_list[j] + src_chunk.flush(_modes.REPLICA) + + for i in range(j): + dst_chunk = chunks_list[i] + src_chunk.apply_to( + dst_chunk, _modes.REPLICA, shape, comms, streams) diff --git a/vllm/lib/python3.10/site-packages/cupyx/distributed/array/_data_transfer.py b/vllm/lib/python3.10/site-packages/cupyx/distributed/array/_data_transfer.py new file mode 100644 index 0000000000000000000000000000000000000000..a960f7d73f62499dd4989de674b3c1ceeb95e4be --- /dev/null +++ b/vllm/lib/python3.10/site-packages/cupyx/distributed/array/_data_transfer.py @@ -0,0 +1,122 @@ +import contextlib +import dataclasses +from typing import Any, Iterable, Iterator + +from cupy._core.core import ndarray +import cupy._creation.from_data as _creation_from_data +import cupy._creation.basic as _creation_basic +from cupy.cuda.device import Device +from cupy.cuda.stream import Event +from cupy.cuda.stream import Stream +from cupy.cuda.stream import get_current_stream + +from cupy.cuda import nccl +from cupyx.distributed._nccl_comm import _get_nccl_dtype_and_count + +if nccl.available: + from cupy.cuda.nccl import NcclCommunicator as _Communicator +else: + class _MockCommunicator: + pass + + _Communicator = _MockCommunicator + + +@dataclasses.dataclass +class _AsyncData: + array: ndarray + ready: Event + prevent_gc: Any = None # TODO: Release it to avoid OOM + + def copy(self) -> '_AsyncData': + with self.on_ready() as stream: + array = self.array.copy() + stream.record(self.ready) + + return _AsyncData(array, stream.record(), self.prevent_gc) + + @contextlib.contextmanager + def on_ready(self) -> Iterator[Stream]: + with self.array.device: + stream = get_current_stream() + stream.wait_event(self.ready) + yield stream + + +# Overwrite in replica mode, apply in op mode +_PartialUpdate = tuple[_AsyncData, tuple[slice, ...]] + + +if nccl.available: + def _create_communicators( + devices: Iterable[int], + ) -> dict[int, _Communicator]: + comms_list = _Communicator.initAll(list(devices)) + return {comm.device_id(): comm for comm in comms_list} + + def _transfer( + src_comm: _Communicator, src_stream: Stream, src_data: _AsyncData, + dst_comm: _Communicator, dst_stream: Stream, dst_dev: int, + ) -> _AsyncData: + src_dev = src_data.array.device.id + if src_dev == dst_dev: + return _AsyncData(src_data.array, src_data.ready) + + prev_src_stream = get_current_stream(src_dev) + prev_dst_stream = get_current_stream(dst_dev) + try: + with Device(src_dev): + src_stream.use() + src_stream.wait_event(src_data.ready) + src_array = _creation_from_data.ascontiguousarray( + src_data.array) + + with Device(dst_dev): + dst_stream.use() + dst_buf = _creation_basic.empty( + src_array.shape, src_array.dtype) + + dtype, count = _get_nccl_dtype_and_count(src_array) + nccl.groupStart() + + with Device(src_dev): + src_comm.send(src_array.data.ptr, count, dtype, + dst_comm.rank_id(), src_stream.ptr) + + with Device(dst_dev): + dst_comm.recv(dst_buf.data.ptr, count, dtype, + src_comm.rank_id(), dst_stream.ptr) + + nccl.groupEnd() + return _AsyncData(dst_buf, dst_stream.record(), + prevent_gc=src_data) + finally: + with Device(src_dev): + prev_src_stream.use() + with Device(dst_dev): + prev_dst_stream.use() +else: + def _create_communicators( + devices: Iterable[int], + ) -> dict[int, _Communicator]: + return {dev: _Communicator() for dev in devices} + + def _transfer( + src_comm: _Communicator, src_stream: Stream, src_data: _AsyncData, + dst_comm: _Communicator, dst_stream: Stream, dst_dev: int, + ) -> _AsyncData: + src_dev = src_data.array.device.id + if src_dev == dst_dev: + return _AsyncData(src_data.array, src_data.ready) + + with Device(dst_dev): + prev_stream = get_current_stream() + try: + dst_stream.use() + dst_stream.wait_event(src_data.ready) + + dst_array = src_data.array.copy() + return _AsyncData( + dst_array, dst_stream.record(), prevent_gc=src_data.array) + finally: + prev_stream.use() diff --git a/vllm/lib/python3.10/site-packages/cupyx/distributed/array/_reduction.py b/vllm/lib/python3.10/site-packages/cupyx/distributed/array/_reduction.py new file mode 100644 index 0000000000000000000000000000000000000000..8ceb99c33e198d7ec4e357f5418d1b2690c76499 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/cupyx/distributed/array/_reduction.py @@ -0,0 +1,90 @@ +import typing +from typing import Any + +from numpy.typing import DTypeLike + +import cupy._manipulation.dims as _manipulation_dims +from cupyx.distributed.array import _array +from cupyx.distributed.array import _chunk +from cupyx.distributed.array import _data_transfer +from cupyx.distributed.array import _modes + + +def _execute( + arr: '_array.DistributedArray', kernel, axis: int, dtype: DTypeLike, +) -> Any: + overwrites = False + mode_overrides = { + 'cupy_max': _modes.MAX, + 'cupy_min': _modes.MIN, + 'cupy_sum': _modes.SUM, + 'cupy_prod': _modes.PROD, + } + if kernel.name not in mode_overrides: + + raise RuntimeError(f'Unsupported kernel: {kernel.name}') + mode = mode_overrides[kernel.name] + if mode in (_modes.MAX, _modes.MIN): + if arr._mode is not mode: + arr = arr._to_op_mode(_modes.REPLICA) + overwrites = True + else: + arr = arr._to_op_mode(mode) + + chunks_map = arr._chunks_map + + if overwrites: + mode = typing.cast(_modes._OpMode, mode) + identity = mode.identity_of(arr.dtype) + for chunks in chunks_map.values(): + for i in range(len(chunks)): + if len(chunks[i].updates) == 0: + continue + chunks[i] = chunks[i].copy() + chunks[i].set_identity_on_overwritten_entries(identity) + + shape = arr.shape[:axis] + arr.shape[axis+1:] + out_dtype = None + out_chunks_map: dict[int, list[_chunk._Chunk]] = {} + + for dev, chunks in chunks_map.items(): + out_chunks_map[dev] = [] + for chunk in chunks: + with chunk.on_ready() as stream: + out_index = chunk.index[:axis] + chunk.index[axis+1:] + + if isinstance(chunk.array, _chunk._ArrayPlaceholder): + old_shape = chunk.array.shape + out_shape = old_shape[:axis] + old_shape[axis+1:] + out_chunk = _chunk._Chunk.create_placeholder( + out_shape, chunk.array.device, out_index) + else: + # We avoid 0D array because + # we expect data[idx] to return a view + out_array = _manipulation_dims.atleast_1d( + kernel(chunk.array, axis=axis, dtype=dtype)) + + out_dtype = out_array.dtype + out_chunk = _chunk._Chunk( + out_array, stream.record(), out_index, + prevent_gc=chunk.prevent_gc) + + out_chunks_map[dev].append(out_chunk) + + if len(chunk.updates) == 0: + continue + + for update, update_index in chunk.updates: + stream.wait_event(update.ready) + out_update_array = _manipulation_dims.atleast_1d( + kernel(update.array, axis=axis, dtype=dtype)) + out_dtype = out_update_array.dtype + + out_update = _data_transfer._AsyncData( + out_update_array, stream.record(), + prevent_gc=update.prevent_gc) + out_index = update_index[:axis] + update_index[axis+1:] + out_chunk.add_update(out_update, out_index) + + return _array.DistributedArray( + shape, out_dtype, out_chunks_map, mode, arr._comms) diff --git a/vllm/lib/python3.10/site-packages/cupyx/jit/__init__.py b/vllm/lib/python3.10/site-packages/cupyx/jit/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6561cd6ed5ff31029c82ecc5b3be5797c6b105ce --- /dev/null +++ b/vllm/lib/python3.10/site-packages/cupyx/jit/__init__.py @@ -0,0 +1,36 @@ +from cupyx.jit._interface import rawkernel # NOQA + +from cupyx.jit._interface import threadIdx # NOQA +from cupyx.jit._interface import blockDim # NOQA +from cupyx.jit._interface import blockIdx # NOQA +from cupyx.jit._interface import gridDim # NOQA +from cupyx.jit._interface import warpsize # NOQA + +from cupyx.jit._builtin_funcs import range_ as range # NOQA +from cupyx.jit._builtin_funcs import syncthreads # NOQA +from cupyx.jit._builtin_funcs import syncwarp # NOQA +from cupyx.jit._builtin_funcs import shared_memory # NOQA +from cupyx.jit._builtin_funcs import atomic_add # NOQA +from cupyx.jit._builtin_funcs import atomic_sub # NOQA +from cupyx.jit._builtin_funcs import atomic_exch # NOQA +from cupyx.jit._builtin_funcs import atomic_min # NOQA +from cupyx.jit._builtin_funcs import atomic_max # NOQA +from cupyx.jit._builtin_funcs import atomic_inc # NOQA +from cupyx.jit._builtin_funcs import atomic_dec # NOQA +from cupyx.jit._builtin_funcs import atomic_cas # NOQA +from cupyx.jit._builtin_funcs import atomic_and # NOQA +from cupyx.jit._builtin_funcs import atomic_or # NOQA +from cupyx.jit._builtin_funcs import atomic_xor # NOQA +from cupyx.jit._builtin_funcs import grid # NOQA +from cupyx.jit._builtin_funcs import gridsize # NOQA +from cupyx.jit._builtin_funcs import laneid # NOQA +from cupyx.jit._builtin_funcs import shfl_sync # NOQA +from cupyx.jit._builtin_funcs import shfl_up_sync # NOQA +from cupyx.jit._builtin_funcs import shfl_down_sync # NOQA +from cupyx.jit._builtin_funcs import shfl_xor_sync # NOQA + +from cupyx.jit import cg # NOQA +from cupyx.jit import cub # NOQA +from cupyx.jit import thrust # NOQA + +_n_functions_upperlimit = 100 diff --git a/vllm/lib/python3.10/site-packages/cupyx/jit/__pycache__/_builtin_funcs.cpython-310.pyc b/vllm/lib/python3.10/site-packages/cupyx/jit/__pycache__/_builtin_funcs.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1fdad5cb72c3965b3d4e51e4ef0e00df5fbbda8f Binary files /dev/null and b/vllm/lib/python3.10/site-packages/cupyx/jit/__pycache__/_builtin_funcs.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/cupyx/jit/__pycache__/_compile.cpython-310.pyc b/vllm/lib/python3.10/site-packages/cupyx/jit/__pycache__/_compile.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3226c9007633569c4a687d5e6e739fcaef32b52b Binary files /dev/null and b/vllm/lib/python3.10/site-packages/cupyx/jit/__pycache__/_compile.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/cupyx/jit/__pycache__/_cuda_typerules.cpython-310.pyc b/vllm/lib/python3.10/site-packages/cupyx/jit/__pycache__/_cuda_typerules.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..22cfcdf115f479f03dbcd2f4dc2416fb30bea44f Binary files /dev/null and b/vllm/lib/python3.10/site-packages/cupyx/jit/__pycache__/_cuda_typerules.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/cupyx/jit/__pycache__/_cuda_types.cpython-310.pyc b/vllm/lib/python3.10/site-packages/cupyx/jit/__pycache__/_cuda_types.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..51c3403e7517ac119989c718a57c0086637d7b78 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/cupyx/jit/__pycache__/_cuda_types.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/cupyx/jit/__pycache__/_interface.cpython-310.pyc b/vllm/lib/python3.10/site-packages/cupyx/jit/__pycache__/_interface.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e2d89decfafd10ddcf3f42d9f4e62854d79ab20e Binary files /dev/null and b/vllm/lib/python3.10/site-packages/cupyx/jit/__pycache__/_interface.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/cupyx/jit/__pycache__/_internal_types.cpython-310.pyc b/vllm/lib/python3.10/site-packages/cupyx/jit/__pycache__/_internal_types.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d6eed222ec84329c821f2363745b8220b372c53e Binary files /dev/null and b/vllm/lib/python3.10/site-packages/cupyx/jit/__pycache__/_internal_types.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/cupyx/jit/__pycache__/cg.cpython-310.pyc b/vllm/lib/python3.10/site-packages/cupyx/jit/__pycache__/cg.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..91bd42ec401fa6eb38a8abc7308e6143b070202b Binary files /dev/null and b/vllm/lib/python3.10/site-packages/cupyx/jit/__pycache__/cg.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/cupyx/jit/__pycache__/thrust.cpython-310.pyc b/vllm/lib/python3.10/site-packages/cupyx/jit/__pycache__/thrust.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..110ac5e235e2127435e0d8d95de31128b541c2f2 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/cupyx/jit/__pycache__/thrust.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/cupyx/jit/_builtin_funcs.py b/vllm/lib/python3.10/site-packages/cupyx/jit/_builtin_funcs.py new file mode 100644 index 0000000000000000000000000000000000000000..264ae15b504bab17e9b456fce60045f2bb1b3b93 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/cupyx/jit/_builtin_funcs.py @@ -0,0 +1,490 @@ +from typing import Any, Mapping +import warnings + +import cupy + +from cupy_backends.cuda.api import runtime +from cupy.cuda import device +from cupyx.jit import _cuda_types +from cupyx.jit import _cuda_typerules +from cupyx.jit._internal_types import BuiltinFunc +from cupyx.jit._internal_types import Data +from cupyx.jit._internal_types import Constant +from cupyx.jit._internal_types import Range +from cupyx.jit import _compile + +from functools import reduce + + +class RangeFunc(BuiltinFunc): + + def __call__(self, *args, unroll=None): + """Range with loop unrolling support. + + Args: + start (int): + Same as that of built-in :obj:`range`. + stop (int): + Same as that of built-in :obj:`range`. + step (int): + Same as that of built-in :obj:`range`. + unroll (int or bool or None): + + - If `True`, add ``#pragma unroll`` directive before the + loop. + - If `False`, add ``#pragma unroll(1)`` directive before + the loop to disable unrolling. + - If an `int`, add ``#pragma unroll(n)`` directive before + the loop, where the integer ``n`` means the number of + iterations to unroll. + - If `None` (default), leave the control of loop unrolling + to the compiler (no ``#pragma``). + + .. seealso:: `#pragma unroll`_ + + .. _#pragma unroll: + https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#pragma-unroll + """ + super().__call__() + + def call(self, env, *args, unroll=None): + if len(args) == 0: + raise TypeError('range expected at least 1 argument, got 0') + elif len(args) == 1: + start, stop, step = Constant(0), args[0], Constant(1) + elif len(args) == 2: + start, stop, step = args[0], args[1], Constant(1) + elif len(args) == 3: + start, stop, step = args + else: + raise TypeError( + f'range expected at most 3 argument, got {len(args)}') + + if unroll is not None: + if not all(isinstance(x, Constant) + for x in (start, stop, step, unroll)): + raise TypeError( + 'loop unrolling requires constant start, stop, step and ' + 'unroll value') + unroll = unroll.obj + if not (isinstance(unroll, int) or isinstance(unroll, bool)): + raise TypeError( + 'unroll value expected to be of type int, ' + f'got {type(unroll).__name__}') + if unroll is False: + unroll = 1 + if not (unroll is True or 0 < unroll < 1 << 31): + warnings.warn( + 'loop unrolling is ignored as the unroll value is ' + 'non-positive or greater than INT_MAX') + + if isinstance(step, Constant): + step_is_positive = step.obj >= 0 + elif step.ctype.dtype.kind == 'u': + step_is_positive = True + else: + step_is_positive = None + + stop = Data.init(stop, env) + start = Data.init(start, env) + step = Data.init(step, env) + + if start.ctype.dtype.kind not in 'iu': + raise TypeError('range supports only for integer type.') + if stop.ctype.dtype.kind not in 'iu': + raise TypeError('range supports only for integer type.') + if step.ctype.dtype.kind not in 'iu': + raise TypeError('range supports only for integer type.') + + if env.mode == 'numpy': + ctype = _cuda_types.Scalar(int) + elif env.mode == 'cuda': + ctype = stop.ctype + else: + assert False + + return Range(start, stop, step, ctype, step_is_positive, unroll=unroll) + + +class LenFunc(BuiltinFunc): + + def call(self, env, *args, **kwds): + if len(args) != 1: + raise TypeError(f'len() expects only 1 argument, got {len(args)}') + if kwds: + raise TypeError('keyword arguments are not supported') + arg = args[0] + if not isinstance(arg.ctype, _cuda_types.CArray): + raise TypeError('len() supports only array type') + if not arg.ctype.ndim: + raise TypeError('len() of unsized array') + return Data(f'static_cast({arg.code}.shape()[0])', + _cuda_types.Scalar('q')) + + +class MinFunc(BuiltinFunc): + + def call(self, env, *args, **kwds): + if len(args) < 2: + raise TypeError( + f'min() expects at least 2 arguments, got {len(args)}') + if kwds: + raise TypeError('keyword arguments are not supported') + return reduce(lambda a, b: _compile._call_ufunc( + cupy.minimum, (a, b), None, env), args) + + +class MaxFunc(BuiltinFunc): + + def call(self, env, *args, **kwds): + if len(args) < 2: + raise TypeError( + f'max() expects at least 2 arguments, got {len(args)}') + if kwds: + raise TypeError('keyword arguments are not supported') + return reduce(lambda a, b: _compile._call_ufunc( + cupy.maximum, (a, b), None, env), args) + + +class SyncThreads(BuiltinFunc): + + def __call__(self): + """Calls ``__syncthreads()``. + + .. seealso:: `Synchronization functions`_ + + .. _Synchronization functions: + https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#synchronization-functions + """ + super().__call__() + + def call_const(self, env): + return Data('__syncthreads()', _cuda_types.void) + + +class SyncWarp(BuiltinFunc): + + def __call__(self, *, mask=0xffffffff): + """Calls ``__syncwarp()``. + + Args: + mask (int): Active threads in a warp. Default is 0xffffffff. + + .. seealso:: `Synchronization functions`_ + + .. _Synchronization functions: + https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#synchronization-functions + """ + super().__call__() + + def call(self, env, *, mask=None): + if runtime.is_hip: + if mask is not None: + warnings.warn(f'mask {mask} is ignored on HIP', RuntimeWarning) + mask = None + + if mask: + if isinstance(mask, Constant): + if not (0x0 <= mask.obj <= 0xffffffff): + raise ValueError('mask is out of range') + mask = _compile._astype_scalar( + mask, _cuda_types.int32, 'same_kind', env) + mask = Data.init(mask, env) + code = f'__syncwarp({mask.code})' + else: + code = '__syncwarp()' + return Data(code, _cuda_types.void) + + +class SharedMemory(BuiltinFunc): + + def __call__(self, dtype, size, alignment=None): + """Allocates shared memory and returns it as a 1-D array. + + Args: + dtype (dtype): + The dtype of the returned array. + size (int or None): + If ``int`` type, the size of static shared memory. + If ``None``, declares the shared memory with extern specifier. + alignment (int or None): Enforce the alignment via __align__(N). + """ + super().__call__() + + def call_const(self, env, dtype, size, alignment=None): + name = env.get_fresh_variable_name(prefix='_smem') + ctype = _cuda_typerules.to_ctype(dtype) + var = Data(name, _cuda_types.SharedMem(ctype, size, alignment)) + env.decls[name] = var + env.locals[name] = var + return Data(name, _cuda_types.Ptr(ctype)) + + +class AtomicOp(BuiltinFunc): + + def __init__(self, op, dtypes): + self._op = op + self._name = 'atomic' + op + self._dtypes = dtypes + doc = f"""Calls the ``{self._name}`` function to operate atomically on + ``array[index]``. Please refer to `Atomic Functions`_ for detailed + explanation. + + Args: + array: A :class:`cupy.ndarray` to index over. + index: A valid index such that the address to the corresponding + array element ``array[index]`` can be computed. + value: Represent the value to use for the specified operation. For + the case of :obj:`atomic_cas`, this is the value for + ``array[index]`` to compare with. + alt_value: Only used in :obj:`atomic_cas` to represent the value + to swap to. + + .. seealso:: `Numba's corresponding atomic functions`_ + + .. _Atomic Functions: + https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#atomic-functions + + .. _Numba's corresponding atomic functions: + https://numba.readthedocs.io/en/stable/cuda-reference/kernel.html#synchronization-and-atomic-operations + """ + self.__doc__ = doc + + def __call__(self, array, index, value, alt_value=None): + super().__call__() + + def call(self, env, array, index, value, value2=None): + name = self._name + op = self._op + array = Data.init(array, env) + if not isinstance(array.ctype, (_cuda_types.CArray, _cuda_types.Ptr)): + raise TypeError('The first argument must be of array type.') + target = _compile._indexing(array, index, env) + ctype = target.ctype + if ctype.dtype.name not in self._dtypes: + raise TypeError(f'`{name}` does not support {ctype.dtype} input.') + # On HIP, 'e' is not supported and we will never reach here + value = _compile._astype_scalar(value, ctype, 'same_kind', env) + value = Data.init(value, env) + if op == 'CAS': + assert value2 is not None + # On HIP, 'H' is not supported and we will never reach here + if ctype.dtype.char == 'H': + if int(device.get_compute_capability()) < 70: + raise RuntimeError( + 'uint16 atomic operation is not supported before ' + 'sm_70') + value2 = _compile._astype_scalar(value2, ctype, 'same_kind', env) + value2 = Data.init(value2, env) + code = f'{name}(&{target.code}, {value.code}, {value2.code})' + else: + assert value2 is None + code = f'{name}(&{target.code}, {value.code})' + return Data(code, ctype) + + +class GridFunc(BuiltinFunc): + + def __init__(self, mode): + if mode == 'grid': + self._desc = 'Compute the thread index in the grid.' + self._eq = 'jit.threadIdx.x + jit.blockIdx.x * jit.blockDim.x' + self._link = 'numba.cuda.grid' + self._code = 'threadIdx.{n} + blockIdx.{n} * blockDim.{n}' + elif mode == 'gridsize': + self._desc = 'Compute the grid size.' + self._eq = 'jit.blockDim.x * jit.gridDim.x' + self._link = 'numba.cuda.gridsize' + self._code = 'blockDim.{n} * gridDim.{n}' + else: + raise ValueError('unsupported function') + + doc = f""" {self._desc} + + Computation of the first integer is as follows:: + + {self._eq} + + and for the other two integers the ``y`` and ``z`` attributes are used. + + Args: + ndim (int): The dimension of the grid. Only 1, 2, or 3 is allowed. + + Returns: + int or tuple: + If ``ndim`` is 1, an integer is returned, otherwise a tuple. + + .. note:: + This function follows the convention of Numba's + :func:`{self._link}`. + """ + self.__doc__ = doc + + def __call__(self, ndim): + super().__call__() + + def call_const(self, env, ndim): + if not isinstance(ndim, int): + raise TypeError('ndim must be an integer') + + # Numba convention: for 1D we return a single variable, + # otherwise a tuple + if ndim == 1: + return Data(self._code.format(n='x'), _cuda_types.uint32) + elif ndim == 2: + dims = ('x', 'y') + elif ndim == 3: + dims = ('x', 'y', 'z') + else: + raise ValueError('Only ndim=1,2,3 are supported') + + elts_code = ', '.join(self._code.format(n=n) for n in dims) + ctype = _cuda_types.Tuple([_cuda_types.uint32]*ndim) + # STD is defined in carray.cuh + if ndim == 2: + return Data(f'STD::make_pair({elts_code})', ctype) + else: + return Data(f'STD::make_tuple({elts_code})', ctype) + + +class WarpShuffleOp(BuiltinFunc): + + def __init__(self, op, dtypes): + self._op = op + self._name = '__shfl_' + (op + '_' if op else '') + 'sync' + self._dtypes = dtypes + doc = f"""Calls the ``{self._name}`` function. Please refer to + `Warp Shuffle Functions`_ for detailed explanation. + + .. _Warp Shuffle Functions: + https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#warp-shuffle-functions + """ + self.__doc__ = doc + + def __call__(self, mask, var, val_id, *, width=32): + super().__call__() + + def call(self, env, mask, var, val_id, *, width=None): + name = self._name + + var = Data.init(var, env) + ctype = var.ctype + if ctype.dtype.name not in self._dtypes: + raise TypeError(f'`{name}` does not support {ctype.dtype} input.') + + try: + mask = mask.obj + except Exception: + raise TypeError('mask must be an integer') + if runtime.is_hip: + warnings.warn(f'mask {mask} is ignored on HIP', RuntimeWarning) + elif not (0x0 <= mask <= 0xffffffff): + raise ValueError('mask is out of range') + + # val_id refers to "delta" for shfl_{up, down}, "srcLane" for shfl, and + # "laneMask" for shfl_xor + if self._op in ('up', 'down'): + val_id_t = _cuda_types.uint32 + else: + val_id_t = _cuda_types.int32 + val_id = _compile._astype_scalar(val_id, val_id_t, 'same_kind', env) + val_id = Data.init(val_id, env) + + if width: + if isinstance(width, Constant): + if width.obj not in (2, 4, 8, 16, 32): + raise ValueError('width needs to be power of 2') + else: + width = Constant(64) if runtime.is_hip else Constant(32) + width = _compile._astype_scalar( + width, _cuda_types.int32, 'same_kind', env) + width = Data.init(width, env) + + code = f'{name}({hex(mask)}, {var.code}, {val_id.code}' + code += f', {width.code})' + return Data(code, ctype) + + +class LaneID(BuiltinFunc): + def __call__(self): + """Returns the lane ID of the calling thread, ranging in + ``[0, jit.warpsize)``. + + .. note:: + Unlike :obj:`numba.cuda.laneid`, this is a callable function + instead of a property. + """ + super().__call__() + + def _get_preamble(self): + preamble = '__device__ __forceinline__ unsigned int LaneId() {' + if not runtime.is_hip: + # see https://github.com/NVIDIA/cub/blob/main/cub/util_ptx.cuh#L419 + preamble += """ + unsigned int ret; + asm ("mov.u32 %0, %%laneid;" : "=r"(ret) ); + return ret; } + """ + else: + # defined in hip/hcc_detail/device_functions.h + preamble += """ + return __lane_id(); } + """ + return preamble + + def call_const(self, env): + env.generated.add_code(self._get_preamble()) + return Data('LaneId()', _cuda_types.uint32) + + +builtin_functions_dict: Mapping[Any, BuiltinFunc] = { + range: RangeFunc(), + len: LenFunc(), + min: MinFunc(), + max: MaxFunc(), +} + +range_ = RangeFunc() +syncthreads = SyncThreads() +syncwarp = SyncWarp() +shared_memory = SharedMemory() +grid = GridFunc('grid') +gridsize = GridFunc('gridsize') +laneid = LaneID() + +# atomic functions +atomic_add = AtomicOp( + 'Add', + ('int32', 'uint32', 'uint64', 'float32', 'float64') + + (() if runtime.is_hip else ('float16',))) +atomic_sub = AtomicOp( + 'Sub', ('int32', 'uint32')) +atomic_exch = AtomicOp( + 'Exch', ('int32', 'uint32', 'uint64', 'float32')) +atomic_min = AtomicOp( + 'Min', ('int32', 'uint32', 'uint64')) +atomic_max = AtomicOp( + 'Max', ('int32', 'uint32', 'uint64')) +atomic_inc = AtomicOp( + 'Inc', ('uint32',)) +atomic_dec = AtomicOp( + 'Dec', ('uint32',)) +atomic_cas = AtomicOp( + 'CAS', + ('int32', 'uint32', 'uint64') + + (() if runtime.is_hip else ('uint16',))) +atomic_and = AtomicOp( + 'And', ('int32', 'uint32', 'uint64')) +atomic_or = AtomicOp( + 'Or', ('int32', 'uint32', 'uint64')) +atomic_xor = AtomicOp( + 'Xor', ('int32', 'uint32', 'uint64')) + +# warp-shuffle functions +_shfl_dtypes = ( + ('int32', 'uint32', 'int64', 'float32', 'float64') + + (() if runtime.is_hip else ('uint64', 'float16'))) +shfl_sync = WarpShuffleOp('', _shfl_dtypes) +shfl_up_sync = WarpShuffleOp('up', _shfl_dtypes) +shfl_down_sync = WarpShuffleOp('down', _shfl_dtypes) +shfl_xor_sync = WarpShuffleOp('xor', _shfl_dtypes) diff --git a/vllm/lib/python3.10/site-packages/cupyx/jit/_compile.py b/vllm/lib/python3.10/site-packages/cupyx/jit/_compile.py new file mode 100644 index 0000000000000000000000000000000000000000..ad4732f4a65d434c63d811bd4ee21750ec7b9f89 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/cupyx/jit/_compile.py @@ -0,0 +1,1025 @@ +import ast +import collections +import inspect +import linecache +import numbers +import re +import sys +from typing import Any, Dict, List, Optional, Sequence, Tuple, TypeVar, Union +import warnings +import types + +import numpy + +from cupy.exceptions import ComplexWarning +from cupy_backends.cuda.api import runtime +from cupy._core._codeblock import CodeBlock, _CodeType +from cupy._core import _kernel +from cupy._core._dtype import _raise_if_invalid_cast +from cupyx import jit +from cupyx.jit import _cuda_types +from cupyx.jit import _cuda_typerules +from cupyx.jit import _internal_types +from cupyx.jit._internal_types import Data +from cupyx.jit._internal_types import Constant +from cupyx.jit import _builtin_funcs +from cupyx.jit import _interface + + +_is_debug_mode = False + +_typeclasses = (bool, numpy.bool_, numbers.Number) + +if (3, 8) <= sys.version_info: + from typing import Literal + _CastingType = Optional[ + Literal['no', 'equiv', 'safe', 'same_kind', 'unsafe']] +else: + _CastingType = str + +Result = collections.namedtuple( + 'Result', + [ + 'func_name', + 'code', + 'return_type', + 'enable_cooperative_groups', + 'backend', + 'options', + 'jitify', + ]) + + +class _JitCompileError(Exception): + + def __init__(self, e, node): + self.error_type = type(e) + self.mes = str(e) + self.node = node + + def reraise(self, pycode): + start = self.node.lineno + end = getattr(self.node, 'end_lineno', start) + pycode = '\n'.join([ + (f'> {line}' if start <= i + 1 <= end else f' {line}').rstrip() + for i, line in enumerate(pycode.split('\n'))]) + raise self.error_type(self.mes + '\n\n' + pycode) + + +def transpile_function_wrapper(func): + def new_func(node, *args, **kwargs): + try: + return func(node, *args, **kwargs) + except _JitCompileError: + raise + except Exception as e: + raise _JitCompileError(e, node) + + return new_func + + +def _parse_function_object(func): + """Returns the tuple of ``ast.FunctionDef`` object and the source string + for the given callable ``func``. + + ``func`` can be a ``def`` function or a ``lambda`` expression. + + The source is returned only for informational purposes (i.e., rendering + an exception message in case of an error). + """ + if not callable(func): + raise ValueError('`func` must be a callable object.') + + try: + # ``filename`` can be any of: + # - A "real" file path on the filesystem + # - "" (within Python interpreter) + # - "" (within IPython interpreter) + filename = inspect.getsourcefile(func) + except TypeError: + # Built-in function or method, or inside Doctest + filename = None + + if filename == '': + raise RuntimeError( + f'JIT needs access to the Python source code for {func}' + ' but it cannot be retrieved within the Python interactive' + ' interpreter. Consider using IPython instead.') + + if func.__name__ != '': + lines, _ = inspect.getsourcelines(func) + num_indent = len(lines[0]) - len(lines[0].lstrip()) + source = ''.join([ + line.replace(' ' * num_indent, '', 1) for line in lines]) + tree = ast.parse(source) + assert isinstance(tree, ast.Module) + assert len(tree.body) == 1 + return tree.body[0], source + + if filename is None: + # filename is needed for lambdas. + raise ValueError( + f'JIT needs access to Python source code for {func}' + ' but could not be located.\n' + '(hint: it is likely you passed a built-in function or method)') + + # Extract the AST of the lambda from the AST of the whole source file + # that defines that lambda. + # This is needed because ``inspect.getsourcelines(lambda_expr)`` may + # return unparsable code snippet. + + # Use ``linecache.getlines`` instead of directly opening a file to + # support notebook environments. + full_source = ''.join(linecache.getlines(filename)) + source, start_line = inspect.getsourcelines(func) + end_line = start_line + len(source) + source = ''.join(source) + + tree = ast.parse(full_source) + + nodes = [node for node in ast.walk(tree) + if isinstance(node, ast.Lambda) + and start_line <= node.lineno < end_line] + if len(nodes) > 1: + # TODO(kmaehashi): can be improved by heuristics (e.g. number of args) + raise ValueError('Multiple callables are found near the' + f' definition of {func}, and JIT could not' + ' identify the source code for it.') + node = nodes[0] + return ast.FunctionDef( + name='_lambda_kernel', args=node.args, + body=[ast.Return(node.body)], + decorator_list=[], returns=None, type_comment=None, + ), source + + +class Generated: + + def __init__(self) -> None: + # list of str + self.codes: List[str] = [] + # (function, in_types) => Optional(function_name, return_type) + self.device_function: \ + Dict[Tuple[Any, Tuple[_cuda_types.TypeBase, ...]], + Tuple[str, _cuda_types.TypeBase]] = {} + # whether to use cooperative launch + self.enable_cg = False + # whether to include cooperative_groups.h + self.include_cg = False + # whether to include cooperative_groups/memcpy_async.h + self.include_cg_memcpy_async = False + # whether to include cuda/barrier + self.include_cuda_barrier = False + # compiler options + self.options = ('-DCUPY_JIT_MODE', '--std=c++17', + # WAR: for compiling any CCCL header + '-DCUB_DISABLE_BF16_SUPPORT',) + # workaround for hipRTC: as of ROCm 4.1.0 hipRTC still does not + # recognize "-D", so we have to compile using hipcc... + self.backend = 'nvcc' if runtime.is_hip else 'nvrtc' + # workaround for CUB/libcudacxx headers: they can be compiled by NVRTC + # but they need Jitify; Thrust headers can only be compiled by NVCC + # for now. We keep Jitify off by default to reduce overhead. + self.jitify = False + + def add_code(self, code: str) -> None: + if code not in self.codes: + self.codes.append(code) + if len(self.codes) > jit._n_functions_upperlimit: + raise ValueError("Number of functions exceeds upper limit.") + + +def transpile(func, attributes, mode, in_types, ret_type): + """Transpiles the target function. + + Args: + func (function): Target function. + attributes (list of str): Attributes of the generated CUDA function. + mode ('numpy' or 'cuda'): The rule for typecast. + in_types (list of _cuda_types.TypeBase): Types of the arguments. + ret_type (_cuda_types.TypeBase or None): Type of the return value. + """ + generated = Generated() + in_types = tuple(in_types) + name, return_type = _transpile_func_obj( + func, attributes, mode, in_types, ret_type, generated) + func_name, _ = generated.device_function[(func, in_types)] + code = '\n'.join(generated.codes) + backend = generated.backend + options = generated.options + jitify = generated.jitify + enable_cg = generated.enable_cg + + if _is_debug_mode: + print(code) + + return Result( + func_name=func_name, code=code, return_type=return_type, jitify=jitify, + enable_cooperative_groups=enable_cg, backend=backend, options=options) + + +def _transpile_func_obj(func, attributes, mode, in_types, ret_type, generated): + if (func, in_types) in generated.device_function: + result = generated.device_function[(func, in_types)] + if result is None: + raise ValueError("Recursive function is not supported.") + return result + + # Do sanity check first. + tree, source = _parse_function_object(func) + + cvars = inspect.getclosurevars(func) + consts = dict(**cvars.globals, **cvars.nonlocals, **cvars.builtins) + attributes = ' '.join(attributes) + name = tree.name + if len(generated.device_function) > 0: + name += '_' + str(len(generated.device_function)) + generated.device_function[(func, in_types)] = None + + cuda_code, env = _transpile_function( + tree, name, attributes, mode, consts, + in_types, ret_type, generated, source=source) + + generated.device_function[(func, in_types)] = (name, env.ret_type) + generated.add_code(cuda_code) + return name, env.ret_type + + +def _indent(lines: List[str], spaces: str = ' ') -> List[str]: + return [spaces + line for line in lines] + + +def is_constants(*values: _internal_types.Expr) -> bool: + assert all(isinstance(x, _internal_types.Expr) for x in values) + return all(isinstance(x, Constant) for x in values) + + +class Environment: + """Environment of the scope + + Attributes: + mode ('numpy' or 'cuda'): The rule for typecast. + consts (dict): The dictionary with keys as the variable names and + the values as the data that is determined at compile-time. + params (dict): The dictionary of function arguments with keys as + the variable names and the values as the Data. + locals (dict): The dictionary with keys as the variable names and the + values as the Data stored at the local scope of the function. + ret_type (_cuda_types.TypeBase): + The type of return value of the function. + If it is initialized to be ``None``, the return type must be + inferred until the end of transpilation of the function. + generated (Generated): Generated CUDA functions. + """ + + def __init__( + self, + mode: str, + consts: Dict[str, Constant], + params: Dict[str, Data], + ret_type: _cuda_types.TypeBase, + generated: Generated, + ): + self.mode = mode + self.consts = consts + self.params = params + self.locals: Dict[str, Data] = {} + self.decls: Dict[str, Data] = {} + self.ret_type = ret_type + self.generated = generated + self.count = 0 + + def __getitem__(self, key: str) -> Optional[Union[Constant, Data]]: + if key in self.locals: + return self.locals[key] + if key in self.params: + return self.params[key] + if key in self.consts: + return self.consts[key] + return None + + def get_fresh_variable_name( + self, prefix: str = '', suffix: str = '') -> str: + self.count += 1 + name = f'{prefix}{self.count}{suffix}' + if self[name] is None: + return name + else: + return self.get_fresh_variable_name(prefix, suffix) + + +def _transpile_function( + func, name, attributes, mode, consts, + in_types, ret_type, generated, *, source): + """Transpile the function + Args: + func (ast.FunctionDef): Target function. + name (str): Function name. + attributes (str): The attributes of target function. + mode ('numpy' or 'cuda'): The rule for typecast. + consts (dict): The dictionary with keys as variable names and + values as concrete data object. + in_types (list of _cuda_types.TypeBase): The types of arguments. + ret_type (_cuda_types.TypeBase): The type of return value. + + Returns: + code (str): The generated CUDA code. + env (Environment): More details of analysis result of the function, + which includes preambles, estimated return type and more. + """ + try: + return _transpile_function_internal( + func, name, attributes, mode, consts, + in_types, ret_type, generated) + except _JitCompileError as e: + exc = e + if _is_debug_mode: + exc.reraise(source) + + # Raises the error out of `except` block to clean stack trace. + exc.reraise(source) + assert False + + +def _transpile_function_internal( + func, name, attributes, mode, consts, in_types, ret_type, generated): + consts = dict([(k, Constant(v)) for k, v, in consts.items()]) + + if not isinstance(func, ast.FunctionDef): + # TODO(asi1024): Support for `ast.ClassDef`. + raise NotImplementedError('Not supported: {}'.format(type(func))) + if len(func.decorator_list) > 0: + if sys.version_info >= (3, 9): + # Code path for Python versions that support `ast.unparse`. + for deco in func.decorator_list: + deco_code = ast.unparse(deco) + if not any(word in deco_code + for word in ['rawkernel', 'vectorize']): + warnings.warn( + f'Decorator {deco_code} may not supported in JIT.', + RuntimeWarning) + arguments = func.args + if arguments.vararg is not None: + raise NotImplementedError('`*args` is not supported currently.') + if len(arguments.kwonlyargs) > 0: # same length with `kw_defaults`. + raise NotImplementedError( + 'keyword only arguments are not supported currently .') + if arguments.kwarg is not None: + raise NotImplementedError('`**kwargs` is not supported currently.') + if len(arguments.defaults) > 0: + raise NotImplementedError( + 'Default values are not supported currently.') + + args = [arg.arg for arg in arguments.args] + if len(args) != len(in_types): + raise TypeError( + f'{name}() takes {len(args)} positional arguments ' + f'but {len(in_types)} were given.') + params = dict([(x, Data(x, t)) for x, t in zip(args, in_types)]) + env = Environment(mode, consts, params, ret_type, generated) + body = _transpile_stmts(func.body, True, env) + params_s = ', '.join([t.declvar(x, None) for x, t in zip(args, in_types)]) + local_vars = [v.ctype.declvar(n, None) + ';' for n, v in env.decls.items()] + + if env.ret_type is None: + env.ret_type = _cuda_types.void + + head = f'{attributes} {env.ret_type} {name}({params_s})' + code = CodeBlock(head, local_vars + body) + return str(code), env + + +def _eval_operand( + op: ast.AST, + args: Sequence[Union[Constant, Data]], + env: Environment, +) -> Union[Constant, Data]: + if is_constants(*args): + pyfunc = _cuda_typerules.get_pyfunc(type(op)) + return Constant(pyfunc(*[x.obj for x in args])) + + if isinstance(op, ast.Add): + x, y = args + x = Data.init(x, env) + y = Data.init(y, env) + if hasattr(x.ctype, '_add'): + out = x.ctype._add(env, x, y) + if out is not NotImplemented: + return out + if hasattr(y.ctype, '_radd'): + out = y.ctype._radd(env, x, y) + if out is not NotImplemented: + return out + + if isinstance(op, ast.Sub): + x, y = args + x = Data.init(x, env) + y = Data.init(y, env) + if hasattr(x.ctype, '_sub'): + out = x.ctype._sub(env, x, y) + if out is not NotImplemented: + return out + if hasattr(y.ctype, '_rsub'): + out = y.ctype._rsub(env, x, y) + if out is not NotImplemented: + return out + + ufunc = _cuda_typerules.get_ufunc(env.mode, type(op)) + return _call_ufunc(ufunc, args, None, env) + + +def _call_ufunc( + ufunc: _kernel.ufunc, + args: Sequence[Union[Constant, Data]], + dtype: Optional[numpy.dtype], + env: Environment, +) -> Data: + if len(args) != ufunc.nin: + raise ValueError('invalid number of arguments') + + in_types = [] + for x in args: + if isinstance(x, Constant): + t = _cuda_typerules.get_ctype_from_scalar(env.mode, x.obj).dtype + elif isinstance(x.ctype, _cuda_types.Scalar): + t = x.ctype.dtype + else: + raise TypeError(f'cupy.ufunc: {x.ctype} is unsupported') + in_types.append(t) + + op = _cuda_typerules.guess_routine(ufunc, tuple(in_types), dtype, env.mode) + + if op is None: + raise TypeError( + f'"{ufunc.name}" does not support for the input types: {in_types}') + + if op.error_func is not None: + op.error_func() + + if ufunc.nout == 1 and op.routine.startswith('out0 = '): + out_type = _cuda_types.Scalar(op.out_types[0]) + expr = op.routine.replace('out0 = ', '') + + in_params = [] + for x, t in zip(args, op.in_types): + x = _astype_scalar(x, _cuda_types.Scalar(t), 'same_kind', env) + x = Data.init(x, env) + in_params.append(x) + + can_use_inline_expansion = True + for i in range(ufunc.nin): + if len(list(re.finditer(r'in{}'.format(i), op.routine))) > 1: + can_use_inline_expansion = False + if f'in{i}_type' in op.routine: + can_use_inline_expansion = False + + env.generated.add_code(ufunc._preamble) + + if can_use_inline_expansion: + # Code pass for readable generated code + for i, x in enumerate(in_params): + expr = expr.replace(f'in{i}', x.code) + expr = '(' + expr.replace('out0_type', str(out_type)) + ')' + else: + template_typenames = ', '.join([ + f'typename in{i}_type' for i in range(ufunc.nin)]) + ufunc_name = f'{ufunc.name}_{str(numpy.dtype(op.out_types[0]))}' + params = ', '.join([f'in{i}_type in{i}' for i in range(ufunc.nin)]) + ufunc_code = f"""template <{template_typenames}> +__device__ {out_type} {ufunc_name}({params}) {{ + typedef {out_type} out0_type; + return {expr}; +}} +""" + env.generated.add_code(ufunc_code) + in_params_code = ', '.join([a.code for a in in_params]) + expr = f'{ufunc_name}({in_params_code})' + return Data(expr, out_type) + + raise NotImplementedError(f'ufunc `{ufunc.name}` is not supported.') + + +def _transpile_stmts( + stmts: List[ast.stmt], + is_toplevel: bool, + env: Environment, +) -> _CodeType: + codeblocks = [] + for stmt in stmts: + codeblocks.extend(_transpile_stmt(stmt, is_toplevel, env)) + return codeblocks + + +@transpile_function_wrapper +def _transpile_stmt( + stmt: ast.stmt, + is_toplevel: bool, + env: Environment, +) -> _CodeType: + """Transpile the statement. + + Returns (list of [CodeBlock or str]): The generated CUDA code. + """ + + if isinstance(stmt, ast.ClassDef): + raise NotImplementedError('class is not supported currently.') + if isinstance(stmt, (ast.FunctionDef, ast.AsyncFunctionDef)): + raise NotImplementedError( + 'Nested functions are not supported currently.') + if isinstance(stmt, ast.Return): + value = _transpile_expr(stmt.value, env) + value = Data.init(value, env) + t = value.ctype + if env.ret_type is None: + env.ret_type = t + elif env.ret_type != t: + raise ValueError( + f'Failed to infer the return type: {env.ret_type} or {t}') + return [f'return {value.code};'] + if isinstance(stmt, ast.Delete): + raise NotImplementedError('`del` is not supported currently.') + + if isinstance(stmt, ast.Assign): + if len(stmt.targets) != 1: + raise NotImplementedError('Not implemented.') + + value = _transpile_expr(stmt.value, env) + var = stmt.targets[0] + + if is_constants(value) and isinstance(var, ast.Name): + name = var.id + if not isinstance(value.obj, _typeclasses): + if is_toplevel: + if isinstance(env[name], Data): + raise TypeError(f'Type mismatch of variable: `{name}`') + env.consts[name] = value + return [] + else: + raise TypeError( + 'Cannot assign constant value not at top-level.') + + value = Data.init(value, env) + return _transpile_assign_stmt(var, env, value, is_toplevel) + + if isinstance(stmt, ast.AugAssign): + value = _transpile_expr(stmt.value, env) + target = _transpile_expr(stmt.target, env) + if not isinstance(target, Data): + raise TypeError(f'Cannot augassign to {target.code}') + value = Data.init(value, env) + tmp = Data(env.get_fresh_variable_name('_tmp_'), target.ctype) + result = _eval_operand(stmt.op, (tmp, value), env) + assert isinstance(target, Data) + assert isinstance(result, Data) + assert isinstance(target.ctype, _cuda_types.Scalar) + assert isinstance(result.ctype, _cuda_types.Scalar) + _raise_if_invalid_cast( + result.ctype.dtype, target.ctype.dtype, 'same_kind') + + return ['{ ' + target.ctype.declvar('&' + tmp.code, target) + '; ' + + target.ctype.assign(tmp, result) + '; }'] + + if isinstance(stmt, ast.For): + if len(stmt.orelse) > 0: + raise NotImplementedError('while-else is not supported.') + assert isinstance(stmt.target, ast.Name) + name = stmt.target.id + iters = _transpile_expr(stmt.iter, env) + loop_var = env[name] + + if loop_var is None: + target = Data(stmt.target.id, iters.ctype) + env.locals[name] = target + env.decls[name] = target + elif isinstance(loop_var, Constant): + raise TypeError('loop counter must not be constant value') + elif loop_var.ctype != iters.ctype: + raise TypeError( + f'Data type mismatch of variable: `{name}`: ' + f'{loop_var.ctype} != {iters.ctype}') + + if not isinstance(iters, _internal_types.Range): + raise NotImplementedError( + 'for-loop is supported only for range iterator.') + + body = _transpile_stmts(stmt.body, False, env) + + init_code = (f'{iters.ctype} ' + f'__it = {iters.start.code}, ' + f'__stop = {iters.stop.code}, ' + f'__step = {iters.step.code}') + cond = '__step >= 0 ? __it < __stop : __it > __stop' + if iters.step_is_positive is True: + cond = '__it < __stop' + elif iters.step_is_positive is False: + cond = '__it > __stop' + + head = f'for ({init_code}; {cond}; __it += __step)' + code: _CodeType = [CodeBlock(head, [f'{name} = __it;'] + body)] + + unroll = iters.unroll + if unroll is True: + code = ['#pragma unroll'] + code + elif unroll is not None: + code = [f'#pragma unroll({unroll})'] + code + return code + + if isinstance(stmt, ast.AsyncFor): + raise ValueError('`async for` is not allowed.') + if isinstance(stmt, ast.While): + if len(stmt.orelse) > 0: + raise NotImplementedError('while-else is not supported.') + condition = _transpile_expr(stmt.test, env) + condition = _astype_scalar(condition, _cuda_types.bool_, 'unsafe', env) + condition = Data.init(condition, env) + body = _transpile_stmts(stmt.body, False, env) + head = f'while ({condition.code})' + return [CodeBlock(head, body)] + if isinstance(stmt, ast.If): + condition = _transpile_expr(stmt.test, env) + if is_constants(condition): + stmts = stmt.body if condition.obj else stmt.orelse + return _transpile_stmts(stmts, is_toplevel, env) + head = f'if ({condition.code})' + then_body = _transpile_stmts(stmt.body, False, env) + else_body = _transpile_stmts(stmt.orelse, False, env) + return [CodeBlock(head, then_body), CodeBlock('else', else_body)] + if isinstance(stmt, (ast.With, ast.AsyncWith)): + raise ValueError('Switching contexts are not allowed.') + if isinstance(stmt, (ast.Raise, ast.Try)): + raise ValueError('throw/catch are not allowed.') + if isinstance(stmt, ast.Assert): + value = _transpile_expr(stmt.test, env) + if is_constants(value): + assert value.obj + return [';'] + else: + return ['assert(' + value + ');'] + if isinstance(stmt, (ast.Import, ast.ImportFrom)): + raise ValueError('Cannot import modules from the target functions.') + if isinstance(stmt, (ast.Global, ast.Nonlocal)): + raise ValueError('Cannot use global/nonlocal in the target functions.') + if isinstance(stmt, ast.Expr): + value = _transpile_expr(stmt.value, env) + return [';'] if is_constants(value) else [value.code + ';'] + if isinstance(stmt, ast.Pass): + return [';'] + if isinstance(stmt, ast.Break): + raise NotImplementedError('Not implemented.') + if isinstance(stmt, ast.Continue): + raise NotImplementedError('Not implemented.') + assert False + + +@transpile_function_wrapper +def _transpile_expr(expr: ast.expr, env: Environment) -> _internal_types.Expr: + """Transpile the statement. + + Returns (Data): The CUDA code and its type of the expression. + """ + res = _transpile_expr_internal(expr, env) + + if isinstance(res, Constant) and isinstance(res.obj, _internal_types.Expr): + return res.obj + else: + return res + + +def _transpile_expr_internal( + expr: ast.expr, + env: Environment, +) -> _internal_types.Expr: + if isinstance(expr, ast.BoolOp): + values = [_transpile_expr(e, env) for e in expr.values] + value = values[0] + for rhs in values[1:]: + value = _eval_operand(expr.op, (value, rhs), env) + return value + if isinstance(expr, ast.BinOp): + left = _transpile_expr(expr.left, env) + right = _transpile_expr(expr.right, env) + return _eval_operand(expr.op, (left, right), env) + if isinstance(expr, ast.UnaryOp): + value = _transpile_expr(expr.operand, env) + return _eval_operand(expr.op, (value,), env) + if isinstance(expr, ast.Lambda): + raise NotImplementedError('Not implemented.') + if isinstance(expr, ast.Compare): + values = [expr.left] + expr.comparators + if len(values) != 2: + raise NotImplementedError( + 'Comparison of 3 or more values is not implemented.') + values = [_transpile_expr(e, env) for e in values] + return _eval_operand(expr.ops[0], values, env) + if isinstance(expr, ast.IfExp): + cond = _transpile_expr(expr.test, env) + x = _transpile_expr(expr.body, env) + y = _transpile_expr(expr.orelse, env) + + if isinstance(expr, Constant): + return x if expr.obj else y + if cond.ctype.dtype.kind == 'c': + raise TypeError("Complex type value cannot be boolean condition.") + x, y = _infer_type(x, y, env), _infer_type(y, x, env) + if x.ctype.dtype != y.ctype.dtype: + raise TypeError( + 'Type mismatch in conditional expression.: ' + f'{x.ctype.dtype} != {y.ctype.dtype}') + cond = _astype_scalar(cond, _cuda_types.bool_, 'unsafe', env) + return Data(f'({cond.code} ? {x.code} : {y.code})', x.ctype) + + if isinstance(expr, ast.Call): + func = _transpile_expr(expr.func, env) + args = [_transpile_expr(x, env) for x in expr.args] + kwargs: Dict[str, Union[Constant, Data]] = {} + for kw in expr.keywords: + assert kw.arg is not None + kwargs[kw.arg] = _transpile_expr(kw.value, env) + + builtin_funcs = _builtin_funcs.builtin_functions_dict + if is_constants(func) and (func.obj in builtin_funcs): + func = builtin_funcs[func.obj] + + if isinstance(func, _internal_types.BuiltinFunc): + return func.call(env, *args, **kwargs) + + if not isinstance(func, Constant): + raise TypeError(f"'{func}' is not callable.") + + func = func.obj + + if isinstance(func, _interface._cuda_types.TypeBase): + return func._instantiate(env, *args, **kwargs) + + if isinstance(func, _interface._JitRawKernel): + if not func._device: + raise TypeError( + f'Calling __global__ function {func._func.__name__} ' + 'from __global__ function is not allowed.') + args = [Data.init(x, env) for x in args] + in_types = tuple([x.ctype for x in args]) + fname, return_type = _transpile_func_obj( + func._func, ['__device__'], env.mode, + in_types, None, env.generated) + in_params = ', '.join([x.code for x in args]) + return Data(f'{fname}({in_params})', return_type) + + if isinstance(func, _kernel.ufunc): + # ufunc call + dtype = kwargs.pop('dtype', Constant(None)).obj + if len(kwargs) > 0: + name = next(iter(kwargs)) + raise TypeError( + f"'{name}' is an invalid keyword to ufunc {func.name}") + return _call_ufunc(func, args, dtype, env) + + if is_constants(*args, *kwargs.values()): + # compile-time function call + args = [x.obj for x in args] + kwargs = dict([(k, v.obj) for k, v in kwargs.items()]) + return Constant(func(*args, **kwargs)) + + if inspect.isclass(func) and issubclass(func, _typeclasses): + # explicit typecast + if len(args) != 1: + raise TypeError( + f'function takes {func} invalid number of argument') + ctype = _cuda_types.Scalar(func) + return _astype_scalar(args[0], ctype, 'unsafe', env) + + raise TypeError(f"Invalid function call '{func.__name__}'.") + + if isinstance(expr, ast.Constant): + return Constant(expr.value) + if isinstance(expr, ast.Subscript): + array = _transpile_expr(expr.value, env) + index = _transpile_expr(expr.slice, env) + return _indexing(array, index, env) + if isinstance(expr, ast.Name): + value = env[expr.id] + if value is None: + raise NameError(f'Unbound name: {expr.id}') + return value + if isinstance(expr, ast.Attribute): + value = _transpile_expr(expr.value, env) + if isinstance(value, Constant): + return Constant(getattr(value.obj, expr.attr)) + if isinstance(value, Data) and hasattr(value.ctype, expr.attr): + attr = getattr(value.ctype, expr.attr, None) + if isinstance(attr, types.MethodType): + return attr(value) + if isinstance(attr, Data): + return attr + raise AttributeError(f'Unknown attribute: {expr.attr}') + + if isinstance(expr, ast.Tuple): + elts = [_transpile_expr(x, env) for x in expr.elts] + + if all([isinstance(x, Constant) for x in elts]): + return Constant(tuple([x.obj for x in elts])) + + elts = [Data.init(x, env) for x in elts] + elts_code = ', '.join([x.code for x in elts]) + # STD is defined in carray.cuh + if len(elts) == 2: + return Data( + f'STD::make_pair({elts_code})', + _cuda_types.Tuple([x.ctype for x in elts])) + else: + return Data( + f'STD::make_tuple({elts_code})', + _cuda_types.Tuple([x.ctype for x in elts])) + + if isinstance(expr, ast.Index): + # Deprecated in Python 3.9 + return _transpile_expr(expr.value, env) # type: ignore + + raise ValueError('Not supported: type {}'.format(type(expr))) + + +def _emit_assign_stmt( + lvalue: Union[Constant, Data], + rvalue: Data, + env: Environment, +) -> _CodeType: + if isinstance(lvalue, Constant): + raise TypeError('lvalue of assignment must not be constant value') + + if (isinstance(lvalue.ctype, _cuda_types.Scalar) + and isinstance(rvalue.ctype, _cuda_types.Scalar)): + rvalue = _astype_scalar(rvalue, lvalue.ctype, 'same_kind', env) + elif lvalue.ctype != rvalue.ctype: + raise TypeError( + f'Data type mismatch of variable: `{lvalue.code}`: ' + f'{lvalue.ctype} != {rvalue.ctype}') + + return [lvalue.ctype.assign(lvalue, rvalue) + ';'] + + +def _transpile_assign_stmt( + target: ast.expr, + env: Environment, + value: Data, + is_toplevel: bool, + depth: int = 0, +) -> _CodeType: + if isinstance(target, ast.Name): + name = target.id + lvalue = env[name] + if lvalue is None: + lvalue = Data(name, value.ctype) + env.locals[name] = lvalue + if is_toplevel and depth == 0: + return [value.ctype.declvar(name, value) + ';'] + env.decls[name] = lvalue + return _emit_assign_stmt(lvalue, value, env) + + if isinstance(target, ast.Subscript): + lvalue = Data.init(_transpile_expr(target, env), env) + return _emit_assign_stmt(lvalue, value, env) + + if isinstance(target, ast.Tuple): + if not isinstance(value.ctype, _cuda_types.Tuple): + raise ValueError(f'{value.ctype} cannot be unpack') + size = len(target.elts) + if len(value.ctype.types) > size: + raise ValueError(f'too many values to unpack (expected {size})') + if len(value.ctype.types) < size: + raise ValueError(f'not enough values to unpack (expected {size})') + codes = [value.ctype.declvar(f'_temp{depth}', value) + ';'] + for i in range(size): + # STD is defined in carray.cuh + code = f'STD::get<{i}>(_temp{depth})' + ctype = value.ctype.types[i] + stmt = _transpile_assign_stmt( + target.elts[i], env, Data(code, ctype), is_toplevel, depth + 1) + codes.extend(stmt) + return [CodeBlock('', codes)] + + assert False + + +def _indexing( + array: _internal_types.Expr, + index: _internal_types.Expr, + env: Environment, +) -> Union[Data, Constant]: + if isinstance(array, Constant): + if isinstance(index, Constant): + return Constant(array.obj[index.obj]) + raise TypeError( + f'{type(array.obj)} is not subscriptable with non-constants.') + + array = Data.init(array, env) + + if isinstance(array.ctype, _cuda_types.Tuple): + if isinstance(index, Constant): + i = index.obj + t = array.ctype.types[i] + # STD is defined in carray.cuh + return Data(f'STD::get<{i}>({array.code})', t) + raise TypeError('Tuple is not subscriptable with non-constants.') + + if isinstance(array.ctype, _cuda_types.ArrayBase): + index = Data.init(index, env) + ndim = array.ctype._ndim + if isinstance(index.ctype, _cuda_types.Scalar): + index_dtype = index.ctype.dtype + if ndim == 0: + raise TypeError( + 'Scalar indexing is not supported for 0-dim array.') + if ndim > 1: + new_carray = _cuda_types.CArray( + array.ctype.dtype, + array.ctype._ndim - 1, + array.ctype._c_contiguous, + array.ctype._index_32_bits) + return Data( + f'{array.code}._slicing({index.code})', new_carray) + if index_dtype.kind not in 'ui': + raise TypeError('Array indices must be integers.') + return Data( + f'{array.code}[{index.code}]', array.ctype.child_type) + if isinstance(index.ctype, _cuda_types.Tuple): + if ndim < len(index.ctype.types): + raise IndexError( + f'The number of indices is beyond array dim: {ndim}') + for t in index.ctype.types: + if not isinstance(t, _cuda_types.Scalar): + raise TypeError('Array indices must be scalar.') + if t.dtype.kind not in 'iu': + raise TypeError('Array indices must be integer.') + if ndim > len(index.ctype.types): + new_carray = _cuda_types.CArray( + array.ctype.dtype, + array.ctype._ndim - len(index.ctype.types), + array.ctype._c_contiguous, + array.ctype._index_32_bits) + params = f'{index.code}, Dim<{len(index.ctype.types)}>()' + return Data(f'{array.code}._slicing({params})', new_carray) + if ndim == 0: + return Data( + f'{array.code}[0]', array.ctype.child_type) + if ndim == 1: + # STD is defined in carray.cuh + return Data( + f'{array.code}[STD::get<0>({index.code})]', + array.ctype.child_type) + return Data( + f'{array.code}._indexing({index.code})', + array.ctype.child_type) + if isinstance(index.ctype, _cuda_types.CArray): + raise TypeError('Advanced indexing is not supported.') + assert False # Never reach. + + raise TypeError(f'{array.code} is not subscriptable.') + + +_T = TypeVar('_T', Constant, Data, Union[Constant, Data]) + + +def _astype_scalar( + x: _T, + ctype: _cuda_types.Scalar, + casting: _CastingType, + env: Environment, +) -> _T: + if isinstance(x, Constant): + assert not isinstance(x, Data) + return Constant(ctype.dtype.type(x.obj)) + # # TODO + # if not isinstance(x, Data): + # raise TypeError(f'{x} is not scalar type.') + if not isinstance(x.ctype, _cuda_types.Scalar): + raise TypeError(f'{x.code} is not scalar type.') + from_t = x.ctype.dtype + to_t = ctype.dtype + if from_t == to_t: + return x + # Uses casting rules for scalar values. + # TODO(seberg): NEP 50/NumPy 2.0 hopefully makes `from_t.type(0)` + # unnecessary allowing to use `_raise_if_invalid_cast()`. + if not numpy.can_cast(from_t.type(0), to_t, casting): + raise TypeError( + f"Cannot cast from '{from_t}' to {to_t} " + f"with casting rule {casting}.") + if from_t.kind == 'c' and to_t.kind != 'c': + if to_t.kind != 'b': + warnings.warn( + 'Casting complex values to real discards the imaginary part', + ComplexWarning) + return Data(f'({ctype})({x.code}.real())', ctype) + return Data(f'({ctype})({x.code})', ctype) + + +def _infer_type( + x: Union[Constant, Data], + hint: Union[Constant, Data], + env: Environment, +) -> Data: + if not isinstance(x, Constant) or isinstance(x.obj, numpy.generic): + return Data.init(x, env) + hint = Data.init(hint, env) + assert isinstance(hint.ctype, _cuda_types.Scalar) + cast_x = _astype_scalar(x, hint.ctype, 'same_kind', env) + return Data.init(cast_x, env) diff --git a/vllm/lib/python3.10/site-packages/cupyx/jit/_cuda_typerules.py b/vllm/lib/python3.10/site-packages/cupyx/jit/_cuda_typerules.py new file mode 100644 index 0000000000000000000000000000000000000000..d750b6a1989a61a81ab0ef8c53e4b1c25cbd1648 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/cupyx/jit/_cuda_typerules.py @@ -0,0 +1,162 @@ +import ast +from typing import Any, Callable, Mapping, Optional, Tuple, Type + +import numpy +import numpy.typing as npt +import operator + +import cupy +from cupy._logic import ops +from cupy._math import arithmetic +from cupy._logic import comparison +from cupy._binary import elementwise +from cupy import _core + +from cupyx.jit import _cuda_types + + +_numpy_scalar_invert = _core.create_ufunc( + 'numpy_scalar_invert', + ('?->?', 'b->b', 'B->B', 'h->h', 'H->H', 'i->i', 'I->I', + 'l->l', 'L->L', 'q->q', 'Q->Q'), + 'out0 = ~in0', +) + + +_numpy_scalar_logical_not = _core.create_ufunc( + 'numpy_scalar_logical_not', + ('?->?', 'b->?', 'B->?', 'h->?', 'H->?', 'i->?', 'I->?', 'l->?', 'L->?', + 'q->?', 'Q->?', 'e->?', 'f->?', 'd->?', + ('F->?', 'out0 = !in0.real() && !in0.imag()'), + ('D->?', 'out0 = !in0.real() && !in0.imag()')), + 'out0 = !in0', +) + + +_scalar_lt = _core.create_comparison('scalar_less', '<') +_scalar_lte = _core.create_comparison('scalar_less', '<=') +_scalar_gt = _core.create_comparison('scalar_less', '>') +_scalar_gte = _core.create_comparison('scalar_less', '>=') + + +_py_ops: Mapping[Type[ast.AST], Callable[..., Any]] = { + ast.And: lambda x, y: x and y, + ast.Or: lambda x, y: x or y, + ast.Add: operator.add, + ast.Sub: operator.sub, + ast.Mult: operator.mul, + ast.Pow: operator.pow, + ast.Div: operator.truediv, + ast.FloorDiv: operator.floordiv, + ast.Mod: operator.mod, + ast.LShift: operator.lshift, + ast.RShift: operator.rshift, + ast.BitOr: operator.or_, + ast.BitAnd: operator.and_, + ast.BitXor: operator.xor, + ast.Invert: operator.invert, + ast.Not: operator.not_, + ast.Eq: operator.eq, + ast.NotEq: operator.ne, + ast.Lt: operator.lt, + ast.LtE: operator.le, + ast.Gt: operator.gt, + ast.GtE: operator.ge, + ast.USub: operator.neg, +} + + +_numpy_ops: Mapping[Type[ast.AST], cupy.ufunc] = { + ast.And: ops.logical_and, + ast.Or: ops.logical_or, + ast.Add: arithmetic.add, + ast.Sub: arithmetic.subtract, + ast.Mult: arithmetic.multiply, + ast.Pow: arithmetic.power, + ast.Div: arithmetic.true_divide, + ast.FloorDiv: arithmetic.floor_divide, + ast.Mod: arithmetic.remainder, + ast.LShift: elementwise.left_shift, + ast.RShift: elementwise.right_shift, + ast.BitOr: elementwise.bitwise_or, + ast.BitAnd: elementwise.bitwise_and, + ast.BitXor: elementwise.bitwise_xor, + ast.Invert: _numpy_scalar_invert, + ast.Not: _numpy_scalar_logical_not, + ast.Eq: comparison.equal, + ast.NotEq: comparison.not_equal, + ast.Lt: _scalar_lt, + ast.LtE: _scalar_lte, + ast.Gt: _scalar_gt, + ast.GtE: _scalar_gte, + ast.USub: arithmetic.negative, +} + + +def get_pyfunc(op_type: Type[ast.AST]) -> Callable[..., Any]: + return _py_ops[op_type] + + +def get_ufunc(mode: str, op_type: Type[ast.AST]) -> cupy.ufunc: + if mode == 'numpy': + return _numpy_ops[op_type] + if mode == 'cuda': + return _numpy_ops[op_type] + assert False + + +def get_ctype_from_scalar(mode: str, x: Any) -> _cuda_types.Scalar: + if isinstance(x, numpy.generic): + return _cuda_types.Scalar(x.dtype) + + if mode == 'numpy': + if isinstance(x, bool): + return _cuda_types.Scalar(numpy.bool_) + if isinstance(x, int): + # use plain int here for cross-platform portability + return _cuda_types.Scalar(int) + if isinstance(x, float): + return _cuda_types.Scalar(numpy.float64) + if isinstance(x, complex): + return _cuda_types.Scalar(numpy.complex128) + + if mode == 'cuda': + if isinstance(x, bool): + return _cuda_types.Scalar(numpy.bool_) + if isinstance(x, int): + if -(1 << 31) <= x < (1 << 31): + return _cuda_types.Scalar(numpy.int32) + return _cuda_types.Scalar(numpy.int64) + if isinstance(x, float): + return _cuda_types.Scalar(numpy.float32) + if isinstance(x, complex): + return _cuda_types.Scalar(numpy.complex64) + + raise NotImplementedError(f'{x} is not scalar object.') + + +_typechars = '?bBhHiIlLqQefdFD' + + +def _cuda_can_cast(from_dtype: npt.DTypeLike, to_dtype: npt.DTypeLike) -> bool: + from_dtype = numpy.dtype(from_dtype) + to_dtype = numpy.dtype(to_dtype) + return _typechars.find(from_dtype.char) <= _typechars.find(to_dtype.char) + + +def guess_routine( + ufunc: cupy.ufunc, + in_types: Tuple[numpy.dtype, ...], + dtype: Optional[numpy.dtype], + mode: str, +) -> cupy._core._kernel._Op: + if dtype is not None: + return ufunc._ops._guess_routine_from_dtype(dtype) + can_cast = numpy.can_cast if mode == 'numpy' else _cuda_can_cast + return ufunc._ops._guess_routine_from_in_types(tuple(in_types), can_cast) + + +def to_ctype(t) -> _cuda_types.TypeBase: + if isinstance(t, _cuda_types.TypeBase): + return t + return _cuda_types.Scalar(numpy.dtype(t)) diff --git a/vllm/lib/python3.10/site-packages/cupyx/jit/_cuda_types.py b/vllm/lib/python3.10/site-packages/cupyx/jit/_cuda_types.py new file mode 100644 index 0000000000000000000000000000000000000000..e12bc3b71f467d2a0e06bec9e2da35ab507e8ddd --- /dev/null +++ b/vllm/lib/python3.10/site-packages/cupyx/jit/_cuda_types.py @@ -0,0 +1,345 @@ +from typing import Mapping, Optional, Sequence, Union, TYPE_CHECKING + +import numpy +import numpy.typing as npt + +import cupy +from cupy._core._scalar import get_typename + +if TYPE_CHECKING: + from cupyx.jit._internal_types import Data + + +# Base class for cuda types. +class TypeBase: + + def __str__(self) -> str: + raise NotImplementedError + + def declvar(self, x: str, init: Optional['Data']) -> str: + if init is None: + return f'{self} {x}' + return f'{self} {x} = {init.code}' + + def assign(self, var: 'Data', value: 'Data') -> str: + return f'{var.code} = {value.code}' + + +class Void(TypeBase): + + def __init__(self) -> None: + pass + + def __str__(self) -> str: + return 'void' + + +class Unknown(TypeBase): + + def __init__(self, *, label: Optional[str] = None) -> None: + self.label = label + + def __str__(self) -> str: + raise TypeError('unknown type can be used only in ary of a function.') + + +class Scalar(TypeBase): + + def __init__(self, dtype: npt.DTypeLike) -> None: + self.dtype = numpy.dtype(dtype) + + def __str__(self) -> str: + dtype = self.dtype + if dtype == numpy.float16: + # For the performance + dtype = numpy.dtype('float32') + return get_typename(dtype) + + def __eq__(self, other: object) -> bool: + assert isinstance(other, TypeBase) + return isinstance(other, Scalar) and self.dtype == other.dtype + + def __hash__(self) -> int: + return hash(self.dtype) + + +class PtrDiff(Scalar): + + def __init__(self) -> None: + super().__init__('q') + + def __str__(self) -> str: + return 'ptrdiff_t' + + +class ArrayBase(TypeBase): + + def ndim(self, instance: 'Data'): + from cupyx.jit import _internal_types # avoid circular import + return _internal_types.Constant(self._ndim) + + def __init__(self, child_type: TypeBase, ndim: int) -> None: + assert isinstance(child_type, TypeBase) + self.child_type = child_type + self._ndim = ndim + + +class PointerBase(ArrayBase): + + def __init__(self, child_type: TypeBase) -> None: + super().__init__(child_type, 1) + + @staticmethod + def _add(env, x: 'Data', y: 'Data') -> 'Data': + from cupyx.jit import _internal_types # avoid circular import + if isinstance(y.ctype, Scalar) and y.ctype.dtype.kind in 'iu': + return _internal_types.Data(f'({x.code} + {y.code})', x.ctype) + return NotImplemented + + @staticmethod + def _radd(env, x: 'Data', y: 'Data') -> 'Data': + from cupyx.jit import _internal_types # avoid circular import + if isinstance(x.ctype, Scalar) and x.ctype.dtype.kind in 'iu': + return _internal_types.Data(f'({x.code} + {y.code})', y.ctype) + return NotImplemented + + @staticmethod + def _sub(env, x: 'Data', y: 'Data') -> 'Data': + from cupyx.jit import _internal_types # avoid circular import + if isinstance(y.ctype, Scalar) and y.ctype.dtype.kind in 'iu': + return _internal_types.Data(f'({x.code} - {y.code})', x.ctype) + if x.ctype == y.ctype: + return _internal_types.Data(f'({x.code} - {y.code})', PtrDiff()) + return NotImplemented + + +class CArray(ArrayBase): + from cupyx.jit import _internal_types # avoid circular import + + def __init__( + self, + dtype: npt.DTypeLike, + ndim: int, + is_c_contiguous: bool, + index_32_bits: bool, + ) -> None: + self.dtype = numpy.dtype(dtype) + self._ndim = ndim + self._c_contiguous = is_c_contiguous + self._index_32_bits = index_32_bits + super().__init__(Scalar(dtype), ndim) + + @classmethod + def from_ndarray(cls, x: cupy.ndarray) -> 'CArray': + return CArray(x.dtype, x.ndim, x._c_contiguous, x._index_32_bits) + + def size(self, instance: 'Data') -> 'Data': + from cupyx.jit import _internal_types # avoid circular import + return _internal_types.Data( + f'static_cast({instance.code}.size())', Scalar('q')) + + def shape(self, instance: 'Data') -> 'Data': + from cupyx.jit import _internal_types # avoid circular import + if self._ndim > 10: + raise NotImplementedError( + 'getting shape/strides for an array with ndim > 10 ' + 'is not supported yet') + return _internal_types.Data( + f'{instance.code}.get_shape()', Tuple([PtrDiff()] * self._ndim)) + + def strides(self, instance: 'Data') -> 'Data': + from cupyx.jit import _internal_types # avoid circular import + if self._ndim > 10: + raise NotImplementedError( + 'getting shape/strides for an array with ndim > 10 ' + 'is not supported yet') + return _internal_types.Data( + f'{instance.code}.get_strides()', Tuple([PtrDiff()] * self._ndim)) + + @_internal_types.wraps_class_method + def begin(self, env, instance: 'Data', *args) -> 'Data': + from cupyx.jit import _internal_types # avoid circular import + if self._ndim != 1: + raise NotImplementedError( + 'getting begin iterator for an array with ndim != 1 ' + 'is not supported yet') + method_name = 'begin_ptr' if self._c_contiguous else 'begin' + return _internal_types.Data( + f'{instance.code}.{method_name}()', + CArrayIterator(instance.ctype)) # type: ignore + + @_internal_types.wraps_class_method + def end(self, env, instance: 'Data', *args) -> 'Data': + from cupyx.jit import _internal_types # avoid circular import + if self._ndim != 1: + raise NotImplementedError( + 'getting end iterator for an array with ndim != 1 ' + 'is not supported yet') + method_name = 'end_ptr' if self._c_contiguous else 'end' + return _internal_types.Data( + f'{instance.code}.{method_name}()', + CArrayIterator(instance.ctype)) # type: ignore + + def __str__(self) -> str: + ctype = get_typename(self.dtype) + ndim = self._ndim + c_contiguous = get_cuda_code_from_constant(self._c_contiguous, bool_) + index_32_bits = get_cuda_code_from_constant(self._index_32_bits, bool_) + return f'CArray<{ctype}, {ndim}, {c_contiguous}, {index_32_bits}>' + + def __eq__(self, other: object) -> bool: + return str(self) == str(other) + + def __hash__(self) -> int: + return hash(str(self)) + + +class CArrayIterator(PointerBase): + + def __init__(self, carray_type: CArray) -> None: + self._carray_type = carray_type + super().__init__(Scalar(carray_type.dtype)) + + def __str__(self) -> str: + return f'{str(self._carray_type)}::iterator' + + def __eq__(self, other: object) -> bool: + assert isinstance(other, TypeBase) + return ( + isinstance(other, CArrayIterator) and + self._carray_type == other._carray_type + ) + + def __hash__(self) -> int: + return hash( + (self.dtype, self.ndim, self._c_contiguous, self._index_32_bits)) + + +class SharedMem(ArrayBase): + + def __init__( + self, + child_type: TypeBase, + size: Optional[int], + alignment: Optional[int] = None, + ) -> None: + if not (isinstance(size, int) or size is None): + raise 'size of shared_memory must be integer or `None`' + if not (isinstance(alignment, int) or alignment is None): + raise 'alignment must be integer or `None`' + self._size = size + self._alignment = alignment + super().__init__(child_type, 1) + + def declvar(self, x: str, init: Optional['Data']) -> str: + assert init is None + if self._alignment is not None: + code = f'__align__({self._alignment})' + else: + code = '' + if self._size is None: + code = f'extern {code} __shared__ {self.child_type} {x}[]' + else: + code = f'{code} __shared__ {self.child_type} {x}[{self._size}]' + return code + + +class Ptr(PointerBase): + + def __init__(self, child_type: TypeBase) -> None: + super().__init__(child_type) + + def __str__(self) -> str: + return f'{self.child_type}*' + + +class Tuple(TypeBase): + + def __init__(self, types: Sequence[TypeBase]) -> None: + self.types = types + + def __str__(self) -> str: + types = ', '.join([str(t) for t in self.types]) + # STD is defined in carray.cuh + if len(self.types) == 2: + return f'STD::pair<{types}>' + else: + return f'STD::tuple<{types}>' + + def __eq__(self, other: object) -> bool: + assert isinstance(other, TypeBase) + return isinstance(other, Tuple) and self.types == other.types + + +void: Void = Void() +bool_: Scalar = Scalar(numpy.bool_) +int32: Scalar = Scalar(numpy.int32) +uint32: Scalar = Scalar(numpy.uint32) +uint64: Scalar = Scalar(numpy.uint64) + + +class Dim3(TypeBase): + """ + An integer vector type based on uint3 that is used to specify dimensions. + + Attributes: + x (uint32) + y (uint32) + z (uint32) + """ + + def x(self, instance: 'Data') -> 'Data': + from cupyx.jit import _internal_types # avoid circular import + return _internal_types.Data(f'{instance.code}.x', uint32) + + def y(self, instance: 'Data') -> 'Data': + from cupyx.jit import _internal_types # avoid circular import + return _internal_types.Data(f'{instance.code}.y', uint32) + + def z(self, instance: 'Data') -> 'Data': + from cupyx.jit import _internal_types # avoid circular import + return _internal_types.Data(f'{instance.code}.z', uint32) + + def __str__(self) -> str: + return 'dim3' + + +dim3: Dim3 = Dim3() + + +_suffix_literals_dict: Mapping[str, str] = { + 'float64': '', + 'float32': 'f', + 'int64': 'll', + 'int32': '', + 'uint64': 'ull', + 'uint32': 'u', + 'bool': '', +} + + +def get_cuda_code_from_constant( + x: Union[bool, int, float, complex], + ctype: Scalar, +) -> str: + dtype = ctype.dtype + ctype_str = str(ctype) + if dtype.kind == 'c': + child_ctype = Scalar(dtype.char.lower()) + real = get_cuda_code_from_constant(x.real, child_ctype) + imag = get_cuda_code_from_constant(x.imag, child_ctype) + return f'{ctype_str}({real}, {imag})' + + suffix_literal = _suffix_literals_dict.get(dtype.name) + if not numpy.isfinite(x): + s = str(x) + if dtype == numpy.float64: + return s.replace('nan', 'nan("")').replace('inf', 'CUDART_INF') + else: + return s.replace('nan', 'nanf("")').replace('inf', 'CUDART_INF_F') + if suffix_literal is not None: + s = str(x).lower() + return f'{s}{suffix_literal}' + if ' ' in ctype_str: + return f'({ctype_str}){x}' + return f'{ctype_str}({x})' diff --git a/vllm/lib/python3.10/site-packages/cupyx/jit/_interface.py b/vllm/lib/python3.10/site-packages/cupyx/jit/_interface.py new file mode 100644 index 0000000000000000000000000000000000000000..6a4d63444fe6bb2a6a8f8713a0ba0c5ede343bfd --- /dev/null +++ b/vllm/lib/python3.10/site-packages/cupyx/jit/_interface.py @@ -0,0 +1,190 @@ +import functools +import warnings + +import numpy + +import cupy +from cupy._core import core +from cupyx.jit import _compile +from cupyx.jit import _cuda_typerules +from cupyx.jit import _cuda_types +from cupyx.jit import _internal_types +from cupyx.jit._cuda_types import Scalar + + +class _CudaFunction: + """JIT cupy function object + """ + + def __init__(self, func, mode, device=False, inline=False): + self.attributes = [] + + if device: + self.attributes.append('__device__') + else: + self.attributes.append('__global__') + + if inline: + self.attributes.append('inline') + + self.name = getattr(func, 'name', func.__name__) + self.func = func + self.mode = mode + + def __call__(self, *args, **kwargs): + raise NotImplementedError + + def _emit_code_from_types(self, in_types, ret_type=None): + return _compile.transpile( + self.func, self.attributes, self.mode, in_types, ret_type) + + +class _JitRawKernel: + """JIT CUDA kernel object. + + The decorator :func:``cupyx.jit.rawkernel`` converts the target function + to an object of this class. This class is not intended to be instantiated + by users. + """ + + def __init__(self, func, mode, device): + self._func = func + self._mode = mode + self._device = device + self._cache = {} + self._cached_codes = {} + + def __call__( + self, grid, block, args, shared_mem=0, stream=None): + """Calls the CUDA kernel. + + The compilation will be deferred until the first function call. + CuPy's JIT compiler infers the types of arguments at the call + time, and will cache the compiled kernels for speeding up any + subsequent calls. + + Args: + grid (tuple of int): Size of grid in blocks. + block (tuple of int): Dimensions of each thread block. + args (tuple): + Arguments of the kernel. The type of all elements must be + ``bool``, ``int``, ``float``, ``complex``, NumPy scalar or + ``cupy.ndarray``. + shared_mem (int): + Dynamic shared-memory size per thread block in bytes. + stream (cupy.cuda.Stream): CUDA stream. + + .. seealso:: :ref:`jit_kernel_definition` + """ + in_types = [] + for x in args: + if isinstance(x, cupy.ndarray): + t = _cuda_types.CArray.from_ndarray(x) + elif numpy.isscalar(x): + t = _cuda_typerules.get_ctype_from_scalar(self._mode, x) + else: + raise TypeError(f'{type(x)} is not supported for RawKernel') + in_types.append(t) + in_types = tuple(in_types) + device_id = cupy.cuda.get_device_id() + + kern, enable_cg = self._cache.get((in_types, device_id), (None, None)) + if kern is None: + result = self._cached_codes.get(in_types) + if result is None: + result = _compile.transpile( + self._func, + ['extern "C"', '__global__'], + self._mode, + in_types, + _cuda_types.void, + ) + self._cached_codes[in_types] = result + + fname = result.func_name + enable_cg = result.enable_cooperative_groups + options = result.options + backend = result.backend + if backend == 'nvcc': + options += ('-DCUPY_JIT_NVCC',) + jitify = result.jitify + module = core.compile_with_cache( + source=result.code, + options=options, + backend=backend, + jitify=jitify) + kern = module.get_function(fname) + self._cache[(in_types, device_id)] = (kern, enable_cg) + + new_args = [] + for a, t in zip(args, in_types): + if isinstance(t, Scalar): + if t.dtype.char == 'e': + a = numpy.float32(a) + else: + a = t.dtype.type(a) + new_args.append(a) + + kern(grid, block, tuple(new_args), shared_mem, stream, enable_cg) + + def __getitem__(self, grid_and_block): + """Numba-style kernel call. + + .. seealso:: :ref:`jit_kernel_definition` + """ + grid, block = grid_and_block + if not isinstance(grid, tuple): + grid = (grid, 1, 1) + if not isinstance(block, tuple): + block = (block, 1, 1) + return lambda *args, **kwargs: self(grid, block, args, **kwargs) + + @property + def cached_codes(self): + """Returns a dict that has input types as keys and codes values. + + This property method is for debugging purpose. + The return value is not guaranteed to keep backward compatibility. + """ + if len(self._cached_codes) == 0: + warnings.warn( + 'No codes are cached because compilation is deferred until ' + 'the first function call.') + return dict([(k, v.code) for k, v in self._cached_codes.items()]) + + @property + def cached_code(self): + """Returns `next(iter(self.cached_codes.values()))`. + + This property method is for debugging purpose. + The return value is not guaranteed to keep backward compatibility. + """ + codes = self.cached_codes + if len(codes) > 1: + warnings.warn( + 'The input types of the kernel could not be inferred. ' + 'Please use `.cached_codes` instead.') + return next(iter(codes.values())) + + +def rawkernel(*, mode='cuda', device=False): + """A decorator compiles a Python function into CUDA kernel. + """ + cupy._util.experimental('cupyx.jit.rawkernel') + + def wrapper(func): + return functools.update_wrapper( + _JitRawKernel(func, mode, device), func) + return wrapper + + +threadIdx = _internal_types.Data('threadIdx', _cuda_types.dim3) +blockDim = _internal_types.Data('blockDim', _cuda_types.dim3) +blockIdx = _internal_types.Data('blockIdx', _cuda_types.dim3) +gridDim = _internal_types.Data('gridDim', _cuda_types.dim3) + +warpsize = _internal_types.Data('warpSize', _cuda_types.int32) +warpsize.__doc__ = r"""Returns the number of threads in a warp. + +.. seealso:: :obj:`numba.cuda.warpsize` +""" diff --git a/vllm/lib/python3.10/site-packages/cupyx/jit/_internal_types.py b/vllm/lib/python3.10/site-packages/cupyx/jit/_internal_types.py new file mode 100644 index 0000000000000000000000000000000000000000..881569bc686f913af52ac0b6fcf993ec601f7f5a --- /dev/null +++ b/vllm/lib/python3.10/site-packages/cupyx/jit/_internal_types.py @@ -0,0 +1,131 @@ +import functools +import itertools +from typing import Any, NoReturn, Optional, Union, TYPE_CHECKING + +from cupyx.jit import _cuda_types +from cupyx.jit import _cuda_typerules + +if TYPE_CHECKING: + from cupyx.jit._compile import Environment + + +class Expr: + + def __repr__(self) -> str: + raise NotImplementedError + + +class Data(Expr): + + def __init__(self, code: str, ctype: _cuda_types.TypeBase) -> None: + assert isinstance(code, str) + assert isinstance(ctype, _cuda_types.TypeBase) + self.code = code + self.ctype = ctype + if not isinstance(ctype, _cuda_types.Unknown): + try: + self.__doc__ = f'{str(ctype)} {code}\n{ctype.__doc__}' + except NotImplementedError: + self.__doc__ = f'{code}' + + @property + def obj(self): + raise ValueError(f'Constant value is required: {self.code}') + + def __repr__(self) -> str: + return f'' + + @classmethod + def init(cls, x: Expr, env) -> 'Data': + if isinstance(x, Data): + return x + if isinstance(x, Constant): + if isinstance(x.obj, tuple): + elts = [Data.init(Constant(e), env) for e in x.obj] + elts_code = ', '.join([e.code for e in elts]) + # STD is defined in carray.cuh + if len(elts) == 2: + return Data( + f'STD::make_pair({elts_code})', + _cuda_types.Tuple([x.ctype for x in elts])) + return Data( + f'STD::make_tuple({elts_code})', + _cuda_types.Tuple([x.ctype for x in elts])) + ctype = _cuda_typerules.get_ctype_from_scalar(env.mode, x.obj) + code = _cuda_types.get_cuda_code_from_constant(x.obj, ctype) + return Data(code, ctype) + raise TypeError(f"'{x}' cannot be interpreted as a cuda object.") + + +class Constant(Expr): + + def __init__(self, obj: Any) -> None: + self._obj = obj + + @property + def obj(self) -> Any: + return self._obj + + def __repr__(self) -> str: + return f'' + + +class Range(Expr): + + def __init__( + self, start: Data, stop: Data, step: Data, + ctype: _cuda_types.Scalar, + step_is_positive: Optional[bool], + *, + unroll: Union[None, int, bool] = None, + ) -> None: + self.start = start + self.stop = stop + self.step = step + self.ctype = ctype + self.step_is_positive = step_is_positive # True, False or None + self.unroll = unroll + + +class BuiltinFunc(Expr): + # subclasses must implement: + # - either call or call_const + # - `__call__` with a correct signature, which calls the parent's __call__ + + def call(self, env: 'Environment', *args, **kwargs) -> Expr: + for x in itertools.chain(args, kwargs.values()): + if not isinstance(x, Constant): + raise TypeError('Arguments must be constants.') + args = tuple([x.obj for x in args]) + kwargs = dict([(k, v.obj) for k, v in kwargs.items()]) + return self.call_const(env, *args, **kwargs) + + def call_const(self, env: 'Environment', *args: Any, **kwarg: Any) -> Expr: + raise NotImplementedError + + def __init__(self) -> None: + self.__doc__ = type(self).__call__.__doc__ + + def __call__(self) -> NoReturn: + raise RuntimeError('Cannot call this function from Python layer.') + + def __repr__(self) -> str: + return '' + + @classmethod + def from_class_method(cls, method, ctype_self, instance): + class _Wrapper(BuiltinFunc): + + def call(self, env, *args, **kwargs): + return method(ctype_self, env, instance, *args) + + return _Wrapper() + + +def wraps_class_method(method): + + @functools.wraps(method) + def f(ctype_self: _cuda_types.TypeBase, instance: Data) -> BuiltinFunc: + return BuiltinFunc.from_class_method(method, ctype_self, instance) + + return f diff --git a/vllm/lib/python3.10/site-packages/cupyx/jit/cg.py b/vllm/lib/python3.10/site-packages/cupyx/jit/cg.py new file mode 100644 index 0000000000000000000000000000000000000000..ce5286f9422745dd7a493201e3115adc1e952cbf --- /dev/null +++ b/vllm/lib/python3.10/site-packages/cupyx/jit/cg.py @@ -0,0 +1,438 @@ +from cupy.cuda import runtime as _runtime +from cupyx.jit import _compile +from cupyx.jit import _cuda_types +from cupyx.jit._internal_types import BuiltinFunc as _BuiltinFunc +from cupyx.jit._internal_types import Constant as _Constant +from cupyx.jit._internal_types import Data as _Data +from cupyx.jit._internal_types import wraps_class_method as _wraps_class_method + + +# public interface of this module +__all__ = ['this_grid', 'this_thread_block', + 'sync', 'wait', 'wait_prior', 'memcpy_async'] + + +# To avoid ABI issues (which libcudacxx manages to raise a compile-time error), +# we always include a header from libcudacxx before any cg include. +_header_to_code = { + 'cg': ("#include \n" + "#include \n" + "namespace cg = cooperative_groups;\n"), + 'cg_memcpy_async': "#include ", +} + + +def _check_include(env, header): + flag = getattr(env.generated, f"include_{header}") + if flag is False: + # prepend the header + env.generated.codes.append(_header_to_code[header]) + setattr(env.generated, f"include_{header}", True) + + +class _ThreadGroup(_cuda_types.TypeBase): + """ Base class for all cooperative groups. """ + + child_type = None + + def __init__(self): + raise NotImplementedError + + def __str__(self): + return f'{self.child_type}' + + def _sync(self, env, instance): + _check_include(env, 'cg') + return _Data(f'{instance.code}.sync()', _cuda_types.void) + + +class _GridGroup(_ThreadGroup): + """A handle to the current grid group. Must be created via :func:`this_grid`. + + .. seealso:: `CUDA Grid Group API`_, :class:`numba.cuda.cg.GridGroup` + + .. _CUDA Grid Group API: + https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#grid-group-cg + """ # NOQA + + def __init__(self): + self.child_type = 'cg::grid_group' + + @_wraps_class_method + def is_valid(self, env, instance): + """ + is_valid() + + Returns whether the grid_group can synchronize. + """ + _check_include(env, 'cg') + return _Data(f'{instance.code}.is_valid()', _cuda_types.bool_) + + @_wraps_class_method + def sync(self, env, instance): + """ + sync() + + Synchronize the threads named in the group. + + .. seealso:: :meth:`numba.cuda.cg.GridGroup.sync` + """ + # when this methond is called, we need to use the cooperative + # launch API + env.generated.enable_cg = True + return super()._sync(env, instance) + + @_wraps_class_method + def thread_rank(self, env, instance): + """ + thread_rank() + + Rank of the calling thread within ``[0, num_threads)``. + """ + _check_include(env, 'cg') + return _Data(f'{instance.code}.thread_rank()', _cuda_types.uint64) + + @_wraps_class_method + def block_rank(self, env, instance): + """ + block_rank() + + Rank of the calling block within ``[0, num_blocks)``. + """ + if _runtime._getLocalRuntimeVersion() < 11060: + raise RuntimeError("block_rank() is supported on CUDA 11.6+") + _check_include(env, 'cg') + return _Data(f'{instance.code}.block_rank()', _cuda_types.uint64) + + @_wraps_class_method + def num_threads(self, env, instance): + """ + num_threads() + + Total number of threads in the group. + """ + if _runtime._getLocalRuntimeVersion() < 11060: + raise RuntimeError("num_threads() is supported on CUDA 11.6+") + _check_include(env, 'cg') + return _Data(f'{instance.code}.num_threads()', _cuda_types.uint64) + + @_wraps_class_method + def num_blocks(self, env, instance): + """ + num_blocks() + + Total number of blocks in the group. + """ + if _runtime._getLocalRuntimeVersion() < 11060: + raise RuntimeError("num_blocks() is supported on CUDA 11.6+") + _check_include(env, 'cg') + return _Data(f'{instance.code}.num_blocks()', _cuda_types.uint64) + + @_wraps_class_method + def dim_blocks(self, env, instance): + """ + dim_blocks() + + Dimensions of the launched grid in units of blocks. + """ + if _runtime._getLocalRuntimeVersion() < 11060: + raise RuntimeError("dim_blocks() is supported on CUDA 11.6+") + _check_include(env, 'cg') + return _Data(f'{instance.code}.dim_blocks()', _cuda_types.dim3) + + @_wraps_class_method + def block_index(self, env, instance): + """ + block_index() + + 3-Dimensional index of the block within the launched grid. + """ + if _runtime._getLocalRuntimeVersion() < 11060: + raise RuntimeError("block_index() is supported on CUDA 11.6+") + _check_include(env, 'cg') + return _Data(f'{instance.code}.block_index()', _cuda_types.dim3) + + @_wraps_class_method + def size(self, env, instance): + """ + size() + + Total number of threads in the group. + """ + # despite it is an alias of num_threads, we need it for earlier 11.x + _check_include(env, 'cg') + return _Data(f'{instance.code}.size()', _cuda_types.uint64) + + @_wraps_class_method + def group_dim(self, env, instance): + """ + group_dim() + + Dimensions of the launched grid in units of blocks. + """ + # despite it is an alias of dim_blocks, we need it for earlier 11.x + _check_include(env, 'cg') + return _Data(f'{instance.code}.group_dim()', _cuda_types.dim3) + + +class _ThreadBlockGroup(_ThreadGroup): + """A handle to the current thread block group. Must be + created via :func:`this_thread_block`. + + .. seealso:: `CUDA Thread Block Group API`_ + + .. _CUDA Thread Block Group API: + https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#thread-block-group-cg + """ + + def __init__(self): + self.child_type = 'cg::thread_block' + + @_wraps_class_method + def sync(self, env, instance): + """ + sync() + + Synchronize the threads named in the group. + """ + return super()._sync(env, instance) + + @_wraps_class_method + def thread_rank(self, env, instance): + """ + thread_rank() + + Rank of the calling thread within ``[0, num_threads)``. + """ + _check_include(env, 'cg') + return _Data(f'{instance.code}.thread_rank()', _cuda_types.uint32) + + @_wraps_class_method + def group_index(self, env, instance): + """ + group_index() + + 3-Dimensional index of the block within the launched grid. + """ + _check_include(env, 'cg') + return _Data(f'{instance.code}.group_index()', _cuda_types.dim3) + + @_wraps_class_method + def thread_index(self, env, instance): + """ + thread_index() + + 3-Dimensional index of the thread within the launched block. + """ + _check_include(env, 'cg') + return _Data(f'{instance.code}.thread_index()', _cuda_types.dim3) + + @_wraps_class_method + def dim_threads(self, env, instance): + """ + dim_threads() + + Dimensions of the launched block in units of threads. + """ + if _runtime._getLocalRuntimeVersion() < 11060: + raise RuntimeError("dim_threads() is supported on CUDA 11.6+") + _check_include(env, 'cg') + return _Data(f'{instance.code}.dim_threads()', _cuda_types.dim3) + + @_wraps_class_method + def num_threads(self, env, instance): + """ + num_threads() + + Total number of threads in the group. + """ + if _runtime._getLocalRuntimeVersion() < 11060: + raise RuntimeError("num_threads() is supported on CUDA 11.6+") + _check_include(env, 'cg') + return _Data(f'{instance.code}.num_threads()', _cuda_types.uint32) + + @_wraps_class_method + def size(self, env, instance): + """ + size() + + Total number of threads in the group. + """ + # despite it is an alias of num_threads, we need it for earlier 11.x + _check_include(env, 'cg') + return _Data(f'{instance.code}.size()', _cuda_types.uint32) + + @_wraps_class_method + def group_dim(self, env, instance): + """ + group_dim() + + Dimensions of the launched block in units of threads. + """ + # despite it is an alias of dim_threads, we need it for earlier 11.x + _check_include(env, 'cg') + return _Data(f'{instance.code}.group_dim()', _cuda_types.dim3) + + +class _ThisCgGroup(_BuiltinFunc): + + def __init__(self, group_type): + if group_type == "grid": + name = "grid group" + typename = "_GridGroup" + elif group_type == 'thread_block': + name = "thread block group" + typename = "_ThreadBlockGroup" + else: + raise NotImplementedError + self.group_type = group_type + self.__doc__ = f""" + Returns the current {name} (:class:`~cupyx.jit.cg.{typename}`). + + .. seealso:: :class:`cupyx.jit.cg.{typename}`""" + if group_type == "grid": + self.__doc__ += ", :func:`numba.cuda.cg.this_grid`" + + def __call__(self): + super().__call__() + + def call_const(self, env): + if _runtime.is_hip: + raise RuntimeError('cooperative group is not supported on HIP') + if self.group_type == 'grid': + cg_type = _GridGroup() + elif self.group_type == 'thread_block': + cg_type = _ThreadBlockGroup() + return _Data(f'cg::this_{self.group_type}()', cg_type) + + +class _Sync(_BuiltinFunc): + + def __call__(self, group): + """Calls ``cg::sync()``. + + Args: + group: a valid cooperative group + + .. seealso:: `cg::sync`_ + + .. _cg::sync: + https://docs.nvidia.com/cuda/archive/11.6.0/cuda-c-programming-guide/index.html#collectives-cg-sync + """ + super().__call__() + + def call(self, env, group): + if not isinstance(group.ctype, _ThreadGroup): + raise ValueError("group must be a valid cooperative group") + _check_include(env, 'cg') + return _Data(f'cg::sync({group.code})', _cuda_types.void) + + +class _MemcpySync(_BuiltinFunc): + + def __call__(self, group, dst, dst_idx, src, src_idx, size, *, + aligned_size=None): + """Calls ``cg::memcpy_sync()``. + + Args: + group: a valid cooperative group + dst: the destination array that can be viewed as a 1D + C-contiguous array + dst_idx: the start index of the destination array element + src: the source array that can be viewed as a 1D C-contiguous + array + src_idx: the start index of the source array element + size (int): the number of bytes to be copied from + ``src[src_index]`` to ``dst[dst_idx]`` + aligned_size (int): Use ``cuda::aligned_size_t`` to guarantee + the compiler that ``src``/``dst`` are at least N-bytes aligned. + The behavior is undefined if the guarantee is not held. + + .. seealso:: `cg::memcpy_sync`_ + + .. _cg::memcpy_sync: + https://docs.nvidia.com/cuda/archive/11.6.0/cuda-c-programming-guide/index.html#collectives-cg-memcpy-async + """ + super().__call__() + + def call(self, env, group, dst, dst_idx, src, src_idx, size, *, + aligned_size=None): + _check_include(env, 'cg') + _check_include(env, 'cg_memcpy_async') + + dst = _Data.init(dst, env) + src = _Data.init(src, env) + for arr in (dst, src): + if not isinstance( + arr.ctype, (_cuda_types.CArray, _cuda_types.Ptr)): + raise TypeError('dst/src must be of array type.') + dst = _compile._indexing(dst, dst_idx, env) + src = _compile._indexing(src, src_idx, env) + + size = _compile._astype_scalar( + # it's very unlikely that the size would exceed 2^32, so we just + # pick uint32 for simplicity + size, _cuda_types.uint32, 'same_kind', env) + size = _Data.init(size, env) + size_code = f'{size.code}' + + if aligned_size: + if not isinstance(aligned_size, _Constant): + raise ValueError( + 'aligned_size must be a compile-time constant') + size_code = (f'cuda::aligned_size_t<{aligned_size.obj}>' + f'({size_code})') + return _Data(f'cg::memcpy_async({group.code}, &({dst.code}), ' + f'&({src.code}), {size_code})', _cuda_types.void) + + +class _Wait(_BuiltinFunc): + + def __call__(self, group): + """Calls ``cg::wait()``. + + Args: + group: a valid cooperative group + + .. seealso: `cg::wait`_ + + .. _cg::wait: + https://docs.nvidia.com/cuda/archive/11.6.0/cuda-c-programming-guide/index.html#collectives-cg-wait + """ + super().__call__() + + def call(self, env, group): + _check_include(env, 'cg') + return _Data(f'cg::wait({group.code})', _cuda_types.void) + + +class _WaitPrior(_BuiltinFunc): + + def __call__(self, group): + """Calls ``cg::wait_prior()``. + + Args: + group: a valid cooperative group + step (int): wait for the first ``N`` steps to finish + + .. seealso: `cg::wait_prior`_ + + .. _cg::wait_prior: + https://docs.nvidia.com/cuda/archive/11.6.0/cuda-c-programming-guide/index.html#collectives-cg-wait + """ + super().__call__() + + def call(self, env, group, step): + _check_include(env, 'cg') + if not isinstance(step, _Constant): + raise ValueError('step must be a compile-time constant') + return _Data(f'cg::wait_prior<{step.obj}>({group.code})', + _cuda_types.void) + + +this_grid = _ThisCgGroup('grid') +this_thread_block = _ThisCgGroup('thread_block') +sync = _Sync() +wait = _Wait() +wait_prior = _WaitPrior() +memcpy_async = _MemcpySync() diff --git a/vllm/lib/python3.10/site-packages/cupyx/jit/cub.py b/vllm/lib/python3.10/site-packages/cupyx/jit/cub.py new file mode 100644 index 0000000000000000000000000000000000000000..d1ce57dd94c42d48b214ad4fd06bf10ba233a2ec --- /dev/null +++ b/vllm/lib/python3.10/site-packages/cupyx/jit/cub.py @@ -0,0 +1,120 @@ +from cupyx.jit import _cuda_types +from cupyx.jit import _cuda_typerules +from cupyx.jit import _internal_types +from cupy_backends.cuda.api import runtime as _runtime + + +class _ClassTemplate: + + def __init__(self, class_type): + self._class_type = class_type + self.__doc__ = self._class_type.__doc__ + + def __getitem__(self, args): + if isinstance(args, tuple): + return self._class_type(*args) + else: + return self._class_type(args) + + +def _include_cub(env): + if _runtime.is_hip: + env.generated.add_code('#include ') + env.generated.backend = 'nvcc' + else: + # Including the master header (cub/cub.cuh) would break NVRTC, because + # it implicitly includes many Thrust headers that would give Jitify a + # hard time. We only include what we need (for block-/warp- level + # algorithms). + # WAR: warp_reduce.cuh is implicitly included. + env.generated.add_code('#include ') + env.generated.backend = 'nvrtc' + env.generated.jitify = False + + +def _get_cub_namespace(): + return 'hipcub' if _runtime.is_hip else 'cub' + + +class _TempStorageType(_cuda_types.TypeBase): + + def __init__(self, parent_type): + assert isinstance(parent_type, _CubReduceBaseType) + self.parent_type = parent_type + super().__init__() + + def __str__(self) -> str: + return f'typename {self.parent_type}::TempStorage' + + +class _CubReduceBaseType(_cuda_types.TypeBase): + + def _instantiate(self, env, temp_storage) -> _internal_types.Data: + _include_cub(env) + if temp_storage.ctype != self.TempStorage: + raise TypeError( + f'Invalid temp_storage type {temp_storage.ctype}. ' + f'({self.TempStorage} is expected.)') + return _internal_types.Data(f'{self}({temp_storage.code})', self) + + @_internal_types.wraps_class_method + def Sum(self, env, instance, input) -> _internal_types.Data: + if input.ctype != self.T: + raise TypeError( + f'Invalid input type {input.ctype}. ({self.T} is expected.)') + return _internal_types.Data( + f'{instance.code}.Sum({input.code})', input.ctype) + + @_internal_types.wraps_class_method + def Reduce(self, env, instance, input, reduction_op): + if input.ctype != self.T: + raise TypeError( + f'Invalid input type {input.ctype}. ({self.T} is expected.)') + return _internal_types.Data( + f'{instance.code}.Reduce({input.code}, {reduction_op.code})', + input.ctype) + + +class _WarpReduceType(_CubReduceBaseType): + + def __init__(self, T) -> None: + self.T = _cuda_typerules.to_ctype(T) + self.TempStorage = _TempStorageType(self) + super().__init__() + + def __str__(self) -> str: + namespace = _get_cub_namespace() + return f'{namespace}::WarpReduce<{self.T}>' + + +class _BlockReduceType(_CubReduceBaseType): + + def __init__(self, T, BLOCK_DIM_X: int) -> None: + self.T = _cuda_typerules.to_ctype(T) + self.BLOCK_DIM_X = BLOCK_DIM_X + self.TempStorage = _TempStorageType(self) + super().__init__() + + def __str__(self) -> str: + namespace = _get_cub_namespace() + return f'{namespace}::BlockReduce<{self.T}, {self.BLOCK_DIM_X}>' + + +WarpReduce = _ClassTemplate(_WarpReduceType) +BlockReduce = _ClassTemplate(_BlockReduceType) + + +class _CubFunctor(_internal_types.BuiltinFunc): + + def __init__(self, name): + namespace = _get_cub_namespace() + self.fname = f'{namespace}::{name}()' + + def call_const(self, env): + return _internal_types.Data( + self.fname, _cuda_types.Unknown(label='cub_functor')) + + +Sum = _CubFunctor('Sum') +Max = _CubFunctor('Max') +Min = _CubFunctor('Min') diff --git a/vllm/lib/python3.10/site-packages/cupyx/jit/thrust.py b/vllm/lib/python3.10/site-packages/cupyx/jit/thrust.py new file mode 100644 index 0000000000000000000000000000000000000000..be919e560c4d44df45901ff35206ebac616b719d --- /dev/null +++ b/vllm/lib/python3.10/site-packages/cupyx/jit/thrust.py @@ -0,0 +1,952 @@ +from cupyx.jit import _internal_types +from cupyx.jit import _cuda_types +from cupyx.jit._internal_types import Data as _Data + + +def _wrap_thrust_func(headers): + def wrapper(func): + class FuncWrapper(_internal_types.BuiltinFunc): + def call(self, env, *args, **kwargs): + for header in headers: + env.generated.add_code(f'#include <{header}>') + env.generated.add_code('#include ') + env.generated.add_code('#include ') + env.generated.backend = 'nvcc' + data_args = [_Data.init(a, env) for a in args] + data_kwargs = {k: _Data.init(kwargs[k], env) for k in kwargs} + return func(env, *data_args, **data_kwargs) + return FuncWrapper() + return wrapper + + +class _ExecPolicyType(_cuda_types.TypeBase): + pass + + +def _assert_exec_policy_type(exec_policy: _Data): + if not isinstance(exec_policy.ctype, _ExecPolicyType): + raise TypeError(f'{exec_policy.code} must be execution policy type') + + +def _assert_pointer_type(a: _Data) -> None: + # TODO(asi1024): Typecheck for EqualityComparable. + if not isinstance(a.ctype, _cuda_types.PointerBase): + raise TypeError(f'`{a.code}` must be of pointer type: `{a.ctype}`') + + +def _assert_same_type(a: _Data, b: _Data) -> None: + if a.ctype != b.ctype: + raise TypeError( + f'`{a.code}` and `{b.code}` must be of the same type: ' + f'`{a.ctype}` != `{b.ctype}`') + + +def _assert_same_pointer_type(a: _Data, b: _Data) -> None: + # TODO(asi1024): Typecheck for EqualityComparable. + _assert_pointer_type(a) + _assert_pointer_type(b) + if a.ctype.child_type != b.ctype.child_type: + raise TypeError( + f'`{a.code}` and `{b.code}` must be of the same pointer type: ' + f'`{a.ctype.child_type}` != `{b.type.child_type}`') + + +def _assert_pointer_of(a: _Data, b: _Data) -> None: + _assert_pointer_type(a) + if a.ctype.child_type != b.ctype: + raise TypeError( + f'`*{a.code}` and `{b.code}` must be of the same type: ' + f'`{a.ctype.child_type}` != `{b.ctype}`') + + +host = _Data('thrust::host', _ExecPolicyType()) +device = _Data('thrust::device', _ExecPolicyType()) +seq = _Data('thrust::seq', _ExecPolicyType()) + + +@_wrap_thrust_func(['thrust/adjacent_difference.h']) +def adjacent_difference(env, exec_policy, first, last, result, binary_op=None): + """Computes the differences of adjacent elements. + """ + _assert_exec_policy_type(exec_policy) + _assert_same_type(first, last) + _assert_same_pointer_type(first, result) + if binary_op is not None: + raise NotImplementedError('binary_op option is not supported') + args = [exec_policy, first, last, result] + params = ', '.join([a.code for a in args]) + return _Data(f'thrust::adjacent_difference({params})', result.ctype) + + +# TODO(asi1024): Support all_of +# TODO(asi1024): Support any_of + + +@_wrap_thrust_func(['thrust/binary_search.h']) +def binary_search(env, exec_policy, first, last, *args): + """Attempts to find the element value with binary search. + """ + _assert_exec_policy_type(exec_policy) + _assert_pointer_type(first) + _assert_same_type(first, last) + + if 1 <= len(args) <= 2: + value = args[0] + comp = args[1] if len(args) == 2 else None + _assert_pointer_of(first, value) + result_ctype = _cuda_types.bool_ + elif 3 <= len(args) <= 4: + value_first = args[0] + value_last = args[1] + result = args[2] + comp = args[3] if len(args) == 4 else None + _assert_same_pointer_type(first, value_first) + _assert_same_type(value_first, value_last) + result_ctype = result.ctype + else: + raise TypeError('Invalid number of inputs of thrust.binary_search') + + if comp is not None: + raise NotImplementedError('comp option is not supported') + args = [exec_policy, first, last, *args] + params = ', '.join([a.code for a in args]) + return _Data(f'thrust::binary_search({params})', result_ctype) + + +@_wrap_thrust_func(['thrust/copy.h']) +def copy(env, exec_policy, first, last, result): + """Copies the elements. + """ + _assert_exec_policy_type(exec_policy) + _assert_same_type(first, last) + _assert_same_pointer_type(first, result) + # TODO(asi1024): Typecheck for EqualityComparable. + args = [exec_policy, first, last, result] + params = ', '.join([a.code for a in args]) + return _Data(f'thrust::copy({params})', result.ctype) + + +# TODO(asi1024): Add copy_if +# TODO(asi1024): Add copy_n + + +@_wrap_thrust_func(['thrust/count.h']) +def count(env, exec_policy, first, last, value): + """Counts the number of elements in [first, last) that equals to ``value``. + """ + _assert_exec_policy_type(exec_policy) + if not isinstance(first.ctype, _cuda_types.PointerBase): + raise TypeError('`first` must be of pointer type') + if first.ctype != last.ctype: + raise TypeError('`first` and `last` must be of the same type') + # TODO(asi1024): Typecheck for EqualityComparable. + args = [exec_policy, first, last, value] + params = ', '.join([a.code for a in args]) + return _Data(f'thrust::count({params})', _cuda_types.int32) + + +# TODO(asi1024): Add count_if + + +@_wrap_thrust_func(['thrust/equal.h']) +def equal(env, exec_policy, first1, last1, first2, binary_pred=None): + """Returns true if the two ranges are identical. + """ + _assert_exec_policy_type(exec_policy) + _assert_same_type(first1, last1) + _assert_same_pointer_type(first1, first2) + if binary_pred is not None: + raise NotImplementedError('binary_pred option is not supported') + args = [exec_policy, first1, last1, first2] + params = ', '.join([a.code for a in args]) + return _Data(f'thrust::equal({params})', _cuda_types.bool_) + + +@_wrap_thrust_func(['thrust/binary_search.h']) +def equal_range(env, exec_policy, first, last, value, comp=None): + """Attempts to find the element value in an ordered range. + """ + _assert_exec_policy_type(exec_policy) + _assert_pointer_type(first) + _assert_same_type(first, last) + if comp is not None: + raise NotImplementedError('comp option is not supported') + args = [exec_policy, first, last, value] + params = ', '.join([a.code for a in args]) + return _Data( + f'thrust::equal_range({params})', + _cuda_types.Tuple([first.ctype, first.ctype])) + + +@_wrap_thrust_func(['thrust/scan.h']) +def exclusive_scan( + env, exec_policy, first, last, result, init=None, binary_op=None): + """Computes an exclusive prefix sum operation. + """ + _assert_exec_policy_type(exec_policy) + _assert_same_type(first, last) + _assert_same_pointer_type(first, result) + if binary_op is not None: + raise NotImplementedError('binary_op option is not supported') + args = [exec_policy, first, last, result] + if init is not None: + args.append(init) + params = ', '.join([a.code for a in args]) + return _Data(f'thrust::exclusive_scan({params})', result.ctype) + + +@_wrap_thrust_func(['thrust/scan.h']) +def exclusive_scan_by_key( + env, exec_policy, first1, last1, first2, result, + init=None, binary_pred=None, binary_op=None): + """Computes an exclusive prefix sum operation by key. + _assert_exec_policy_type(exec_policy) + """ + _assert_pointer_type(first1) + _assert_same_type(first1, last1) + _assert_same_pointer_type(first2, result) + if binary_pred is not None: + raise NotImplementedError('binary_pred option is not supported') + if binary_op is not None: + raise NotImplementedError('binary_op option is not supported') + args = [exec_policy, first1, last1, first2, result] + if init is not None: + args.append(init) + params = ', '.join([a.code for a in args]) + return _Data(f'thrust::exclusive_scan_by_key({params})', result.ctype) + + +@_wrap_thrust_func(['thrust/fill.h']) +def fill(env, exec_policy, first, last, value): + """Assigns the value to every element in the range. + """ + _assert_exec_policy_type(exec_policy) + _assert_same_type(first, last) + # TODO(asi1024): Typecheck for EqualityComparable. + args = [exec_policy, first, last, value] + params = ', '.join([a.code for a in args]) + return _Data(f'thrust::fill({params})', _cuda_types.void) + + +# TODO(asi1024): Add fill_n + + +@_wrap_thrust_func(['thrust/find.h']) +def find(env, exec_policy, first, last, value): + """Finds the first iterator whose value equals to ``value``. + """ + _assert_exec_policy_type(exec_policy) + _assert_pointer_type(first) + _assert_same_type(first, last) + # TODO(asi1024): Typecheck for EqualityComparable. + args = [exec_policy, first, last, value] + params = ', '.join([a.code for a in args]) + return _Data(f'thrust::find({params})', first.ctype) + + +# TODO(asi1024): Add find_if +# TODO(asi1024): Add find_if_not +# TODO(asi1024): Add for_each +# TODO(asi1024): Add for_each_n + + +@_wrap_thrust_func(['thrust/gather.h']) +def gather(env, exec_policy, map_first, map_last, input_first, result): + """Copies elements from source into destination according to a map. + """ + _assert_exec_policy_type(exec_policy) + _assert_pointer_type(map_first) + _assert_same_type(map_first, map_last) + _assert_same_pointer_type(input_first, result) + args = [exec_policy, map_first, map_last, input_first, result] + params = ', '.join([a.code for a in args]) + return _Data(f'thrust::gather({params})', result.ctype) + + +# TODO(asi1024): Add gather_if +# TODO(asi1024): Add generate_n + + +@_wrap_thrust_func(['thrust/scan.h']) +def inclusive_scan( + env, exec_policy, first, last, result, binary_op=None): + """Computes an inclusive prefix sum operation. + """ + _assert_exec_policy_type(exec_policy) + _assert_same_type(first, last) + _assert_same_pointer_type(first, result) + if binary_op is not None: + raise NotImplementedError('binary_op option is not supported') + args = [exec_policy, first, last, result] + params = ', '.join([a.code for a in args]) + return _Data(f'thrust::inclusive_scan({params})', result.ctype) + + +@_wrap_thrust_func(['thrust/scan.h']) +def inclusive_scan_by_key( + env, exec_policy, first1, last1, first2, result, + binary_pred=None, binary_op=None): + """Computes an inclusive prefix sum operation by key. + """ + _assert_exec_policy_type(exec_policy) + _assert_pointer_type(first1) + _assert_same_type(first1, last1) + _assert_same_pointer_type(first2, result) + if binary_pred is not None: + raise NotImplementedError('binary_pred option is not supported') + if binary_op is not None: + raise NotImplementedError('binary_op option is not supported') + args = [exec_policy, first1, last1, first2, result] + params = ', '.join([a.code for a in args]) + return _Data(f'thrust::inclusive_scan_by_key({params})', result.ctype) + + +@_wrap_thrust_func(['thrust/inner_product.h']) +def inner_product( + env, exec_policy, first1, last1, first2, init, + binary_op1=None, binary_op2=None): + """Calculates an inner product of the ranges. + """ + _assert_exec_policy_type(exec_policy) + _assert_same_type(first1, last1) + _assert_same_pointer_type(first1, first2) + if binary_op1 is not None: + raise NotImplementedError('binary_op1 option is not supported') + if binary_op2 is not None: + raise NotImplementedError('binary_op2 option is not supported') + args = [exec_policy, first1, last1, first2, init] + params = ', '.join([a.code for a in args]) + return _Data(f'thrust::inner_product({params})', init.ctype) + + +# TODO(asi1024): Add is_partitioned + + +@_wrap_thrust_func(['thrust/sort.h']) +def is_sorted(env, exec_policy, first, last, comp=None): + """Returns true if the range is sorted in ascending order. + """ + _assert_exec_policy_type(exec_policy) + _assert_pointer_type(first) + _assert_same_type(first, last) + if comp is not None: + raise NotImplementedError('comp option is not supported') + args = [exec_policy, first, last] + params = ', '.join([a.code for a in args]) + return _Data(f'thrust::is_sorted({params})', _cuda_types.bool_) + + +@_wrap_thrust_func(['thrust/sort.h']) +def is_sorted_until(env, exec_policy, first, last, comp=None): + """Returns the last iterator for which the range is sorted. + """ + _assert_exec_policy_type(exec_policy) + _assert_pointer_type(first) + _assert_same_type(first, last) + if comp is not None: + raise NotImplementedError('comp option is not supported') + args = [exec_policy, first, last] + params = ', '.join([a.code for a in args]) + return _Data(f'thrust::is_sorted_until({params})', first.ctype) + + +@_wrap_thrust_func(['thrust/binary_search.h']) +def lower_bound(env, exec_policy, first, last, *args): + """Attempts to find the element value with binary search. + """ + _assert_exec_policy_type(exec_policy) + _assert_pointer_type(first) + _assert_same_type(first, last) + + if 1 <= len(args) <= 2: + value = args[0] + comp = args[1] if len(args) == 2 else None + _assert_pointer_of(first, value) + result_ctype = first.ctype + elif 3 <= len(args) <= 4: + value_first = args[0] + value_last = args[1] + result = args[2] + comp = args[3] if len(args) == 4 else None + _assert_same_pointer_type(first, value_first) + _assert_same_type(value_first, value_last) + result_ctype = result.ctype + else: + raise TypeError('Invalid number of inputs of thrust.lower_bound') + + if comp is not None: + raise NotImplementedError('comp option is not supported') + args = [exec_policy, first, last, *args] + params = ', '.join([a.code for a in args]) + return _Data(f'thrust::lower_bound({params})', result_ctype) + + +class _ConstantIterator(_cuda_types.PointerBase): + + def __str__(self) -> str: + value_type = self.child_type + return f'thrust::constant_iterator<{value_type}>' + + +@_wrap_thrust_func(['thrust/iterator/constant_iterator.h']) +def make_constant_iterator(env, x, i=None): + """Finds the first positions whose values differ. + """ + if i is not None: + raise NotImplementedError('index_type is not supported') + args = [x] + params = ', '.join([a.code for a in args]) + return _Data( + f'thrust::make_constant_iterator({params})', + _ConstantIterator(x.ctype) + ) + + +class _CountingIterator(_cuda_types.PointerBase): + + def __str__(self) -> str: + value_type = self.child_type + return f'thrust::counting_iterator<{value_type}>' + + +@_wrap_thrust_func(['thrust/iterator/counting_iterator.h']) +def make_counting_iterator(env, x, i=None): + """Finds the first positions whose values differ. + """ + if i is not None: + raise NotImplementedError('index_type is not supported') + args = [x] + params = ', '.join([a.code for a in args]) + return _Data( + f'thrust::make_counting_iterator({params})', + _CountingIterator(x.ctype) + ) + + +# TODO(asi1024): Add make_discard_iterator +# TODO(asi1024): Add make_index_sequence + + +@_wrap_thrust_func(['thrust/mismatch.h']) +def mismatch(env, exec_policy, first1, last1, first2, pred=None): + """Finds the first positions whose values differ. + """ + _assert_exec_policy_type(exec_policy) + _assert_same_type(first1, last1) + _assert_same_pointer_type(first1, first2) + # TODO(asi1024): Typecheck for EqualityComparable. + if pred is not None: + raise NotImplementedError('pred option is not supported') + args = [exec_policy, first1, last1, first2] + params = ', '.join([a.code for a in args]) + return _Data( + f'thrust::mismatch({params})', + _cuda_types.Tuple([first1.ctype, first2.ctype]) + ) + + +# TODO(asi1024): Add none_of +# TODO(asi1024): Add partition +# TODO(asi1024): Add partition_copy +# TODO(asi1024): Add partition_point + + +@_wrap_thrust_func(['thrust/reduce.h']) +def reduce(env, exec_policy, first, last, init=None, binary_op=None): + """Generalization of summation. + """ + _assert_exec_policy_type(exec_policy) + _assert_pointer_type(first) + _assert_same_type(first, last) + args = [exec_policy, first, last] + if init is not None: + # TODO(asi1024): Typecheck for init. + args.append(init) + return_type = init.ctype + else: + return_type = first.ctype.child_type + if binary_op is not None: + raise NotImplementedError('binary_op option is not supported') + params = ', '.join([a.code for a in args]) + return _Data(f'thrust::reduce({params})', return_type) + + +@_wrap_thrust_func(['thrust/reduce.h']) +def reduce_by_key( + env, exec_policy, keys_first, keys_last, values_first, + keys_output, values_output, binary_pred=None, binary_op=None): + """Generalization of reduce to key-value pairs. + """ + _assert_exec_policy_type(exec_policy) + _assert_pointer_type(keys_first) + _assert_same_type(keys_first, keys_last) + _assert_pointer_type(values_first) + _assert_pointer_type(keys_output) + _assert_pointer_type(values_output) + args = [ + exec_policy, keys_first, keys_last, values_first, + keys_output, values_output + ] + if binary_pred is not None: + raise NotImplementedError('binary_pred option is not supported') + if binary_op is not None: + raise NotImplementedError('binary_op option is not supported') + params = ', '.join([a.code for a in args]) + return _Data( + f'thrust::reduce_by_key({params})', + _cuda_types.Tuple([keys_output.ctype, values_output.ctype]) + ) + + +@_wrap_thrust_func(['thrust/remove.h']) +def remove(env, exec_policy, first, last, value): + """Removes from the range all elements that are equal to value. + """ + _assert_exec_policy_type(exec_policy) + _assert_pointer_type(first) + _assert_same_type(first, last) + args = [exec_policy, first, last, value] + params = ', '.join([a.code for a in args]) + return _Data(f'thrust::remove({params})', first.ctype) + + +@_wrap_thrust_func(['thrust/remove.h']) +def remove_copy(env, exec_policy, first, last, result, value): + """Removes from the range all elements that are equal to value. + """ + _assert_exec_policy_type(exec_policy) + _assert_pointer_type(first) + _assert_same_type(first, last) + _assert_pointer_type(result) + args = [exec_policy, first, last, result, value] + params = ', '.join([a.code for a in args]) + return _Data(f'thrust::remove_copy({params})', result.ctype) + + +# TODO(asi1024): Add remove_copy_if +# TODO(asi1024): Add remove_if + + +@_wrap_thrust_func(['thrust/replace.h']) +def replace(env, exec_policy, first, last, old_value, new_value): + """Replaces every element in the range equal to old_value with new_value. + """ + _assert_exec_policy_type(exec_policy) + _assert_pointer_type(first) + _assert_same_type(first, last) + _assert_same_type(old_value, new_value) + args = [exec_policy, first, last, old_value, new_value] + params = ', '.join([a.code for a in args]) + return _Data(f'thrust::replace({params})', _cuda_types.void) + + +@_wrap_thrust_func(['thrust/replace.h']) +def replace_copy(env, exec_policy, first, last, result, old_value, new_value): + """Replaces every element in the range equal to old_value with new_value. + """ + _assert_exec_policy_type(exec_policy) + _assert_pointer_type(first) + _assert_same_type(first, last) + _assert_pointer_type(result) + _assert_same_type(old_value, new_value) + args = [exec_policy, first, last, result, old_value, new_value] + params = ', '.join([a.code for a in args]) + return _Data(f'thrust::replace_copy({params})', result.ctype) + + +# TODO(asi1024): Add replace_copy_if +# TODO(asi1024): Add replace_if + + +@_wrap_thrust_func(['thrust/reverse.h']) +def reverse(env, exec_policy, first, last): + """Reverses a range. + """ + _assert_exec_policy_type(exec_policy) + _assert_pointer_type(first) + _assert_same_type(first, last) + args = [exec_policy, first, last] + params = ', '.join([a.code for a in args]) + return _Data(f'thrust::reverse({params})', _cuda_types.void) + + +@_wrap_thrust_func(['thrust/reverse.h']) +def reverse_copy(env, exec_policy, first, last, result): + """Reverses a range. + """ + _assert_exec_policy_type(exec_policy) + _assert_pointer_type(first) + _assert_same_type(first, last) + _assert_pointer_type(result) + args = [exec_policy, first, last, result] + params = ', '.join([a.code for a in args]) + return _Data(f'thrust::reverse_copy({params})', result.ctype) + + +@_wrap_thrust_func(['thrust/scatter.h']) +def scatter(env, exec_policy, first, last, map, result): + """Copies elements from source range into an output range according to map. + """ + _assert_exec_policy_type(exec_policy) + _assert_pointer_type(first) + _assert_same_type(first, last) + _assert_pointer_type(map) + _assert_pointer_type(result) + args = [exec_policy, first, last, map, result] + params = ', '.join([a.code for a in args]) + return _Data(f'thrust::scatter({params})', _cuda_types.void) + + +# TODO(asi1024): Add scatter_if + + +@_wrap_thrust_func(['thrust/sequence.h']) +def sequence(env, exec_policy, first, last, init=None, step=None): + """Fills the range with a sequence of numbers. + """ + _assert_exec_policy_type(exec_policy) + _assert_pointer_type(first) + _assert_same_type(first, last) + args = [exec_policy, first, last] + if init is not None: + args.append(init) + if step is not None: + _assert_same_type(init, step) + args.append(step) + params = ', '.join([a.code for a in args]) + return _Data(f'thrust::sequence({params})', _cuda_types.void) + + +@_wrap_thrust_func(['thrust/set_operations.h']) +def set_difference( + env, exec_policy, first1, last1, first2, last2, result, comp=None): + """Constructs a sorted range that is the set difference of sorted inputs. + """ + # TODO(asi1024): Typecheck for Comparable. + _assert_exec_policy_type(exec_policy) + _assert_same_type(first1, last1) + _assert_same_type(first2, last2) + _assert_pointer_type(result) + args = [exec_policy, first1, last1, first2, last2, result] + if comp is not None: + raise NotImplementedError('comp option is not supported') + params = ', '.join([a.code for a in args]) + return _Data(f'thrust::set_difference({params})', result.ctype) + + +@_wrap_thrust_func(['thrust/set_operations.h']) +def set_difference_by_key( + env, exec_policy, keys_first1, keys_last1, keys_first2, keys_last2, + values_first1, values_first2, keys_result, values_result, comp=None): + """Constructs the key-value set difference of sorted inputs. + """ + # TODO(asi1024): Typecheck for Comparable. + _assert_exec_policy_type(exec_policy) + _assert_same_type(keys_first1, keys_last1) + _assert_same_type(keys_first2, keys_last2) + _assert_pointer_type(values_first1) + _assert_pointer_type(values_first2) + _assert_pointer_type(keys_result) + _assert_pointer_type(values_result) + args = [exec_policy, keys_first1, keys_last1, keys_first2, keys_last2, + values_first1, values_first2, keys_result, values_result] + if comp is not None: + raise NotImplementedError('comp option is not supported') + params = ', '.join([a.code for a in args]) + return _Data( + f'thrust::set_difference_by_key({params})', + _cuda_types.Tuple([keys_result.ctype, values_result.ctype]) + ) + + +@_wrap_thrust_func(['thrust/set_operations.h']) +def set_intersection( + env, exec_policy, first1, last1, first2, last2, result, comp=None): + """Constructs a sorted range that is the set intersection of sorted inputs. + """ + # TODO(asi1024): Typecheck for Comparable. + _assert_exec_policy_type(exec_policy) + _assert_same_type(first1, last1) + _assert_same_type(first2, last2) + _assert_pointer_type(result) + args = [exec_policy, first1, last1, first2, last2, result] + if comp is not None: + raise NotImplementedError('comp option is not supported') + params = ', '.join([a.code for a in args]) + return _Data(f'thrust::set_intersection({params})', result.ctype) + + +@_wrap_thrust_func(['thrust/set_operations.h']) +def set_intersection_by_key( + env, exec_policy, keys_first1, keys_last1, keys_first2, keys_last2, + values_first1, keys_result, values_result, comp=None): + """Constructs the key-value set intersection of sorted inputs. + """ + # TODO(asi1024): Typecheck for Comparable. + _assert_exec_policy_type(exec_policy) + _assert_same_type(keys_first1, keys_last1) + _assert_same_type(keys_first2, keys_last2) + _assert_pointer_type(values_first1) + _assert_pointer_type(keys_result) + _assert_pointer_type(values_result) + args = [exec_policy, keys_first1, keys_last1, keys_first2, keys_last2, + values_first1, keys_result, values_result] + if comp is not None: + raise NotImplementedError('comp option is not supported') + params = ', '.join([a.code for a in args]) + return _Data( + f'thrust::set_intersection_by_key({params})', + _cuda_types.Tuple([keys_result.ctype, values_result.ctype]) + ) + + +@_wrap_thrust_func(['thrust/set_operations.h']) +def set_symmetric_difference( + env, exec_policy, first1, last1, first2, last2, result, comp=None): + """Constructs a sorted range that is the symmetric difference. + """ + # TODO(asi1024): Typecheck for Comparable. + _assert_exec_policy_type(exec_policy) + _assert_same_type(first1, last1) + _assert_same_type(first2, last2) + _assert_pointer_type(result) + args = [exec_policy, first1, last1, first2, last2, result] + if comp is not None: + raise NotImplementedError('comp option is not supported') + params = ', '.join([a.code for a in args]) + return _Data(f'thrust::set_symmetric_difference({params})', result.ctype) + + +@_wrap_thrust_func(['thrust/set_operations.h']) +def set_symmetric_difference_by_key( + env, exec_policy, keys_first1, keys_last1, keys_first2, keys_last2, + values_first1, values_first2, keys_result, values_result, comp=None): + """Constructs the key-value symmetric difference of sorted inputs. + """ + # TODO(asi1024): Typecheck for Comparable. + _assert_exec_policy_type(exec_policy) + _assert_same_type(keys_first1, keys_last1) + _assert_same_type(keys_first2, keys_last2) + _assert_pointer_type(values_first1) + _assert_pointer_type(values_first2) + _assert_pointer_type(keys_result) + _assert_pointer_type(values_result) + args = [exec_policy, keys_first1, keys_last1, keys_first2, keys_last2, + values_first1, values_first2, keys_result, values_result] + if comp is not None: + raise NotImplementedError('comp option is not supported') + params = ', '.join([a.code for a in args]) + return _Data( + f'thrust::set_symmetric_difference_by_key({params})', + _cuda_types.Tuple([keys_result.ctype, values_result.ctype]) + ) + + +@_wrap_thrust_func(['thrust/set_operations.h']) +def set_union( + env, exec_policy, first1, last1, first2, last2, result, comp=None): + """Constructs a sorted range that is the set union of sorted inputs. + """ + # TODO(asi1024): Typecheck for Comparable. + _assert_exec_policy_type(exec_policy) + _assert_same_type(first1, last1) + _assert_same_type(first2, last2) + _assert_pointer_type(result) + args = [exec_policy, first1, last1, first2, last2, result] + if comp is not None: + raise NotImplementedError('comp option is not supported') + params = ', '.join([a.code for a in args]) + return _Data(f'thrust::set_union({params})', result.ctype) + + +@_wrap_thrust_func(['thrust/set_operations.h']) +def set_union_by_key( + env, exec_policy, keys_first1, keys_last1, keys_first2, keys_last2, + values_first1, values_first2, keys_result, values_result, comp=None): + """Constructs the key-value union of sorted inputs. + """ + # TODO(asi1024): Typecheck for Comparable. + _assert_exec_policy_type(exec_policy) + _assert_same_type(keys_first1, keys_last1) + _assert_same_type(keys_first2, keys_last2) + _assert_pointer_type(values_first1) + _assert_pointer_type(values_first2) + _assert_pointer_type(keys_result) + _assert_pointer_type(values_result) + args = [exec_policy, keys_first1, keys_last1, keys_first2, keys_last2, + values_first1, values_first2, keys_result, values_result] + if comp is not None: + raise NotImplementedError('comp option is not supported') + params = ', '.join([a.code for a in args]) + return _Data( + f'thrust::set_union_by_key({params})', + _cuda_types.Tuple([keys_result.ctype, values_result.ctype]) + ) + + +# TODO(asi1024): Add shuffle +# TODO(asi1024): Add shuffle_copy + + +@_wrap_thrust_func(['thrust/sort.h']) +def sort(env, exec_policy, first, last, comp=None): + """Sorts the elements in [first, last) into ascending order. + """ + _assert_exec_policy_type(exec_policy) + _assert_pointer_type(first) + _assert_same_type(first, last) + if comp is not None: + raise NotImplementedError('comp option is not supported') + # TODO(asi1024): Typecheck for Comparable. + args = [exec_policy, first, last] + params = ', '.join([a.code for a in args]) + return _Data(f'thrust::sort({params})', _cuda_types.void) + + +@_wrap_thrust_func(['thrust/sort.h']) +def sort_by_key( + env, exec_policy, keys_first, keys_last, values_first, comp=None): + """Performs key-value sort. + """ + _assert_exec_policy_type(exec_policy) + _assert_pointer_type(keys_first) + _assert_same_type(keys_first, keys_last) + _assert_pointer_type(values_first) + if comp is not None: + raise NotImplementedError('comp option is not supported') + # TODO(asi1024): Typecheck for Comparable. + args = [exec_policy, keys_first, keys_last, values_first] + params = ', '.join([a.code for a in args]) + return _Data(f'thrust::sort_by_key({params})', _cuda_types.void) + + +# TODO(asi1024): Add stable_partition +# TODO(asi1024): Add stable_partition_copy + + +@_wrap_thrust_func(['thrust/sort.h']) +def stable_sort(env, exec_policy, first, last, comp=None): + """Sorts the elements in [first, last) into ascending order. + """ + _assert_exec_policy_type(exec_policy) + _assert_pointer_type(first) + _assert_same_type(first, last) + if comp is not None: + raise NotImplementedError('comp option is not supported') + # TODO(asi1024): Typecheck for Comparable. + args = [exec_policy, first, last] + params = ', '.join([a.code for a in args]) + return _Data(f'thrust::stable_sort({params})', _cuda_types.void) + + +@_wrap_thrust_func(['thrust/sort.h']) +def stable_sort_by_key( + env, exec_policy, keys_first, keys_last, values_first, comp=None): + """Performs key-value sort. + """ + _assert_exec_policy_type(exec_policy) + _assert_pointer_type(keys_first) + _assert_same_type(keys_first, keys_last) + _assert_pointer_type(values_first) + if comp is not None: + raise NotImplementedError('comp option is not supported') + # TODO(asi1024): Typecheck for Comparable. + args = [exec_policy, keys_first, keys_last, values_first] + params = ', '.join([a.code for a in args]) + return _Data(f'thrust::stable_sort_by_key({params})', _cuda_types.void) + + +@_wrap_thrust_func(['thrust/swap.h']) +def swap_ranges(env, exec_policy, first1, last1, first2): + """Swaps each of the elements in the range. + """ + _assert_exec_policy_type(exec_policy) + _assert_pointer_type(first1) + _assert_same_type(first1, last1) + _assert_pointer_type(first2) + # TODO(asi1024): Typecheck for Comparable. + args = [exec_policy, first1, last1, first2] + params = ', '.join([a.code for a in args]) + return _Data(f'thrust::swap_ranges({params})', first2.ctype) + + +# TODO(asi1024): Add tabulate +# TODO(asi1024): Add transform +# TODO(asi1024): Add transform_exclusive_scan +# TODO(asi1024): Add transform_if +# TODO(asi1024): Add transform_inclusive_scan +# TODO(asi1024): Add transform_reduce +# TODO(asi1024): Add uninitialized_copy +# TODO(asi1024): Add uninitialized_copy_n +# TODO(asi1024): Add uninitialized_fill +# TODO(asi1024): Add uninitialized_fill_n + + +@_wrap_thrust_func(['thrust/unique.h']) +def unique(env, exec_policy, first, last, binary_pred=None): + """Removes all but the first element of the group. + """ + _assert_exec_policy_type(exec_policy) + _assert_pointer_type(first) + _assert_same_type(first, last) + if binary_pred is not None: + raise NotImplementedError('binary_pred option is not supported') + args = [exec_policy, first, last] + params = ', '.join([a.code for a in args]) + return _Data(f'thrust::unique({params})', first.ctype) + + +@_wrap_thrust_func(['thrust/unique.h']) +def unique_by_key( + env, exec_policy, keys_first, keys_last, values_first, + binary_pred=None): + """Uniques key-value pairs. + """ + _assert_exec_policy_type(exec_policy) + _assert_pointer_type(keys_first) + _assert_same_type(keys_first, keys_last) + _assert_pointer_type(values_first) + args = [exec_policy, keys_first, keys_last, values_first] + if binary_pred is not None: + raise NotImplementedError('binary_pred option is not supported') + params = ', '.join([a.code for a in args]) + return _Data( + f'thrust::unique_by_key({params})', + _cuda_types.Tuple([keys_first.ctype, values_first.ctype]), + ) + + +# TODO(asi1024): Add unique_by_key_copy +# TODO(asi1024): Add unique_by_key +# TODO(asi1024): Add unique_count + + +@_wrap_thrust_func(['thrust/binary_search.h']) +def upper_bound(env, exec_policy, first, last, *args): + """Attempts to find the element value with binary search. + """ + _assert_exec_policy_type(exec_policy) + _assert_pointer_type(first) + _assert_same_type(first, last) + + if 1 <= len(args) <= 2: + value = args[0] + comp = args[1] if len(args) == 2 else None + _assert_pointer_of(first, value) + result_ctype = first.ctype + elif 3 <= len(args) <= 4: + value_first = args[0] + value_last = args[1] + result = args[2] + comp = args[3] if len(args) == 4 else None + _assert_same_pointer_type(first, value_first) + _assert_same_type(value_first, value_last) + result_ctype = result.ctype + else: + raise TypeError('Invalid number of inputs of thrust.upper_bound') + + if comp is not None: + raise NotImplementedError('comp option is not supported') + args = [exec_policy, first, last, *args] + params = ', '.join([a.code for a in args]) + return _Data(f'thrust::upper_bound({params})', result_ctype) diff --git a/vllm/lib/python3.10/site-packages/cupyx/linalg/__init__.py b/vllm/lib/python3.10/site-packages/cupyx/linalg/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1c588059f4e98d0f62ac9e34612046af89416e19 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/cupyx/linalg/__init__.py @@ -0,0 +1,3 @@ +# "NOQA" to suppress flake8 warning +from cupyx.linalg import sparse # NOQA +from cupyx.linalg._solve import invh # NOQA diff --git a/vllm/lib/python3.10/site-packages/cupyx/linalg/__pycache__/__init__.cpython-310.pyc b/vllm/lib/python3.10/site-packages/cupyx/linalg/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cabd73e88b667955ee8ca54293a4f24553545a32 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/cupyx/linalg/__pycache__/__init__.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/cupyx/linalg/__pycache__/_solve.cpython-310.pyc b/vllm/lib/python3.10/site-packages/cupyx/linalg/__pycache__/_solve.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0e5e548ba8de1bfe1dc6f0d9b8ce1e597c42303a Binary files /dev/null and b/vllm/lib/python3.10/site-packages/cupyx/linalg/__pycache__/_solve.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/cupyx/linalg/_solve.py b/vllm/lib/python3.10/site-packages/cupyx/linalg/_solve.py new file mode 100644 index 0000000000000000000000000000000000000000..2af0fb7f33d84115190060dd40d4a16ca62bd154 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/cupyx/linalg/_solve.py @@ -0,0 +1,26 @@ +from cupy.linalg import _util + + +def invh(a): + """Compute the inverse of a Hermitian matrix. + + This function computes a inverse of a real symmetric or complex hermitian + positive-definite matrix using Cholesky factorization. If matrix ``a`` is + not positive definite, Cholesky factorization fails and it raises an error. + + Args: + a (cupy.ndarray): Real symmetric or complex hermitian maxtix. + + Returns: + cupy.ndarray: The inverse of matrix ``a``. + """ + from cupyx import lapack + + _util._assert_cupy_array(a) + # TODO: Use `_assert_stacked_2d` instead, once cusolver supports nrhs > 1 + # for potrsBatched + _util._assert_2d(a) + _util._assert_stacked_square(a) + + b = _util.stacked_identity_like(a) + return lapack.posv(a, b) diff --git a/vllm/lib/python3.10/site-packages/cupyx/linalg/sparse/__init__.py b/vllm/lib/python3.10/site-packages/cupyx/linalg/sparse/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..52c8b745631938e1ef932b642b5fcf72876b6a8a --- /dev/null +++ b/vllm/lib/python3.10/site-packages/cupyx/linalg/sparse/__init__.py @@ -0,0 +1,3 @@ + +# "NOQA" to suppress flake8 warning +from cupyx.linalg.sparse._solve import lschol # NOQA diff --git a/vllm/lib/python3.10/site-packages/cupyx/linalg/sparse/__pycache__/__init__.cpython-310.pyc b/vllm/lib/python3.10/site-packages/cupyx/linalg/sparse/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ed919dee1a7f5d008fa020e184329a4c8324b2df Binary files /dev/null and b/vllm/lib/python3.10/site-packages/cupyx/linalg/sparse/__pycache__/__init__.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/cupyx/linalg/sparse/__pycache__/_solve.cpython-310.pyc b/vllm/lib/python3.10/site-packages/cupyx/linalg/sparse/__pycache__/_solve.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eaae8553f30e29f5554794968029769322b2799e Binary files /dev/null and b/vllm/lib/python3.10/site-packages/cupyx/linalg/sparse/__pycache__/_solve.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/cupyx/linalg/sparse/_solve.py b/vllm/lib/python3.10/site-packages/cupyx/linalg/sparse/_solve.py new file mode 100644 index 0000000000000000000000000000000000000000..0cfc876a4592388ac840afb19c42e531cdb525f6 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/cupyx/linalg/sparse/_solve.py @@ -0,0 +1,62 @@ +import numpy + +import cupy +from cupy.cuda import device +from cupy.linalg import _util +from cupyx.scipy import sparse + + +def lschol(A, b): + """Solves linear system with cholesky decomposition. + + Find the solution to a large, sparse, linear system of equations. + The function solves ``Ax = b``. Given two-dimensional matrix ``A`` is + decomposed into ``L * L^*``. + + Args: + A (cupy.ndarray or cupyx.scipy.sparse.csr_matrix): The input matrix + with dimension ``(N, N)``. Must be positive-definite input matrix. + Only symmetric real matrix is supported currently. + b (cupy.ndarray): Right-hand side vector. + + Returns: + ret (cupy.ndarray): The solution vector ``x``. + + """ + from cupy_backends.cuda.libs import cusolver + + if not sparse.isspmatrix_csr(A): + A = sparse.csr_matrix(A) + # csr_matrix is 2d + _util._assert_stacked_square(A) + _util._assert_cupy_array(b) + m = A.shape[0] + if b.ndim != 1 or len(b) != m: + raise ValueError('b must be 1-d array whose size is same as A') + + # Cast to float32 or float64 + if A.dtype == 'f' or A.dtype == 'd': + dtype = A.dtype + else: + dtype = numpy.promote_types(A.dtype, 'f') + + handle = device.get_cusolver_sp_handle() + nnz = A.nnz + tol = 1.0 + reorder = 1 + x = cupy.empty(m, dtype=dtype) + singularity = numpy.empty(1, numpy.int32) + + if dtype == 'f': + csrlsvchol = cusolver.scsrlsvchol + else: + csrlsvchol = cusolver.dcsrlsvchol + csrlsvchol( + handle, m, nnz, A._descr.descriptor, A.data.data.ptr, + A.indptr.data.ptr, A.indices.data.ptr, b.data.ptr, tol, reorder, + x.data.ptr, singularity.ctypes.data) + + # The return type of SciPy is always float64. + x = x.astype(numpy.float64) + + return x diff --git a/vllm/lib/python3.10/site-packages/cupyx/tools/__init__.py b/vllm/lib/python3.10/site-packages/cupyx/tools/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/vllm/lib/python3.10/site-packages/cupyx/tools/__pycache__/__init__.cpython-310.pyc b/vllm/lib/python3.10/site-packages/cupyx/tools/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f07d9455fa3c0d260cf9ad814516b64439f70896 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/cupyx/tools/__pycache__/__init__.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/cupyx/tools/__pycache__/_hipsparse_stub_mapper.cpython-310.pyc b/vllm/lib/python3.10/site-packages/cupyx/tools/__pycache__/_hipsparse_stub_mapper.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..46dbb80611f0d58987bda71e9957a3e9f1a0a06e Binary files /dev/null and b/vllm/lib/python3.10/site-packages/cupyx/tools/__pycache__/_hipsparse_stub_mapper.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/cupyx/tools/__pycache__/install_library.cpython-310.pyc b/vllm/lib/python3.10/site-packages/cupyx/tools/__pycache__/install_library.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b9c739ab57d9b2520c930807de95924ac6cde09d Binary files /dev/null and b/vllm/lib/python3.10/site-packages/cupyx/tools/__pycache__/install_library.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/cupyx/tools/_hipsparse_stub_mapper.py b/vllm/lib/python3.10/site-packages/cupyx/tools/_hipsparse_stub_mapper.py new file mode 100644 index 0000000000000000000000000000000000000000..da556b87e162868c47a2f30e5f574f8d3ab803df --- /dev/null +++ b/vllm/lib/python3.10/site-packages/cupyx/tools/_hipsparse_stub_mapper.py @@ -0,0 +1,402 @@ +import urllib.request +import sys +from typing import Tuple + + +# Take cupy_backends/stub/cupy_cusparse.h and generate +# cupy_backends/hip/cupy_hipsparse.h, with all return values replaced by an +# error if not supported. This script mainly focuses on getting the CUDA -> +# HIP API mapping done correctly; structs, enums, etc, are handled +# automatically to the maximal extent. +# +# The stub functions, such as this, +# +# cusparseStatus_t cusparseDestroyMatDescr(...) { +# return HIPSPARSE_STATUS_NOT_SUPPORTED; +# } +# +# are mapped to their HIP counterparts, like this +# +# cusparseStatus_t cusparseDestroyMatDescr(cusparseMatDescr_t descrA) { +# return hipsparseDestroyMatDescr(descrA); +# } + + +# some cuSPARSE APIs are removed in recent CUDA 11.x, so we also need to +# look up older CUDA to fetch the API signatures +cusparse_h = '/usr/local/cuda-{0}/include/cusparse.h' +cu_versions = ('11.3', '11.0', '10.2') + + +hipsparse_url = ('https://raw.githubusercontent.com/ROCmSoftwarePlatform/' + 'hipSPARSE/rocm-{0}/library/include/hipsparse.h') +hip_versions = ("3.5.0", "3.7.0", "3.8.0", "3.9.0", "4.0.0", "4.2.0") + + +# typedefs +typedefs: Tuple[str, ...] +typedefs = ('cusparseIndexBase_t', 'cusparseStatus_t', 'cusparseHandle_t', + 'cusparseMatDescr_t', 'csrsv2Info_t', 'csrsm2Info_t', + 'csric02Info_t', 'bsric02Info_t', 'csrilu02Info_t', + 'bsrilu02Info_t', 'csrgemm2Info_t', + 'cusparseMatrixType_t', 'cusparseFillMode_t', 'cusparseDiagType_t', + 'cusparsePointerMode_t', 'cusparseAction_t', 'cusparseDirection_t', + 'cusparseSolvePolicy_t', 'cusparseOperation_t') + + +# typedefs for generic API +typedefs += ('cusparseSpVecDescr_t', 'cusparseDnVecDescr_t', + 'cusparseSpMatDescr_t', 'cusparseDnMatDescr_t', + 'cusparseIndexType_t', 'cusparseFormat_t', 'cusparseOrder_t', + 'cusparseSpMVAlg_t', 'cusparseSpMMAlg_t', + 'cusparseSparseToDenseAlg_t', 'cusparseDenseToSparseAlg_t', + 'cusparseCsr2CscAlg_t',) + + +# helpers +cudaDataType_converter = r""" +#if HIP_VERSION >= 402 +static hipDataType convert_hipDatatype(cudaDataType type) { + switch(static_cast(type)) { + case 2 /* CUDA_R_16F */: return HIP_R_16F; + case 0 /* CUDA_R_32F */: return HIP_R_32F; + case 1 /* CUDA_R_64F */: return HIP_R_64F; + case 6 /* CUDA_C_16F */: return HIP_C_16F; + case 4 /* CUDA_C_32F */: return HIP_C_32F; + case 5 /* CUDA_C_64F */: return HIP_C_64F; + default: throw std::runtime_error("unrecognized type"); + } +} +#endif +""" + +cusparseOrder_converter = r""" +#if HIP_VERSION >= 402 +typedef enum {} cusparseOrder_t; +static hipsparseOrder_t convert_hipsparseOrder_t(cusparseOrder_t type) { + switch(static_cast(type)) { + case 1 /* CUSPARSE_ORDER_COL */: return HIPSPARSE_ORDER_COLUMN; + case 2 /* CUSPARSE_ORDER_ROW */: return HIPSPARSE_ORDER_ROW; + default: throw std::runtime_error("unrecognized type"); + } +} +""" + +default_return_code = r""" +#if HIP_VERSION < 401 +#define HIPSPARSE_STATUS_NOT_SUPPORTED (hipsparseStatus_t)10 +#endif +""" + + +# keep track of typedefs that are already handled (as we move from older +# to newer HIP version) +processed_typedefs = set() + + +def get_idx_to_func(cu_h, cu_func): + cu_sig = cu_h.find(cu_func) + # 1. function names are always followed immediately by a "(" + # 2. we need a loop here to find the exact match + while True: + if cu_sig == -1: + break + elif cu_h[cu_sig+len(cu_func)] != "(": + cu_sig = cu_h.find(cu_func, cu_sig+1) + else: + break # match + return cu_sig + + +def get_hip_ver_num(hip_version): + # "3.5.0" -> 305 + hip_version = hip_version.split('.') + return int(hip_version[0]) * 100 + int(hip_version[1]) + + +def merge_bad_broken_lines(cu_sig): + # each line ends with an argument, which is followed by a "," or ")" + # except for cusparseCbsric02, cusparseCooGet, ... + cu_sig_processed = [] + skip_line = None + for line, s in enumerate(cu_sig): + if line != skip_line: + if s.endswith(',') or s.endswith(')'): + cu_sig_processed.append(s) + else: + break_idx = s.find(',') + if break_idx == -1: + break_idx = s.find(')') + if break_idx == -1: + cu_sig_processed.append(s + cu_sig[line+1]) + skip_line = line+1 + else: + # argument could be followed by an inline comment + cu_sig_processed.append(s[:break_idx+1]) + return cu_sig_processed + + +def process_func_args(s, hip_sig, decl, hip_func): + # TODO(leofang): prettier print? note that we currently rely on "hip_sig" + # being a one-liner... + # TODO(leofang): I am being silly here; these can probably be handled more + # elegantly using regex... + if 'const cuComplex*' in s: + s = s.split() + arg = '(' + s[-1][:-1] + ')' + s[-1][-1] + cast = 'reinterpret_cast' + elif 'const cuDoubleComplex*' in s: + s = s.split() + arg = '(' + s[-1][:-1] + ')' + s[-1][-1] + cast = 'reinterpret_cast' + elif 'cuComplex*' in s: + s = s.split() + arg = '(' + s[-1][:-1] + ')' + s[-1][-1] + cast = 'reinterpret_cast' + elif 'cuDoubleComplex*' in s: + s = s.split() + arg = '(' + s[-1][:-1] + ')' + s[-1][-1] + cast = 'reinterpret_cast' + elif 'cuComplex' in s: + s = s.split() + decl += ' hipComplex blah;\n' + decl += f' blah.x={s[-1][:-1]}.x;\n blah.y={s[-1][:-1]}.y;\n' + arg = 'blah' + s[-1][-1] + cast = '' + elif 'cuDoubleComplex' in s: + s = s.split() + decl += ' hipDoubleComplex blah;\n' + decl += f' blah.x={s[-1][:-1]}.x;\n blah.y={s[-1][:-1]}.y;\n' + arg = 'blah' + s[-1][-1] + cast = '' + elif 'cudaDataType*' in s: + s = s.split() + arg = '(' + s[-1][:-1] + ')' + s[-1][-1] + cast = 'reinterpret_cast' + elif 'cudaDataType' in s: + s = s.split() + decl += ' hipDataType blah = convert_hipDatatype(' + decl += s[-1][:-1] + ');\n' + arg = 'blah' + s[-1][-1] + cast = '' + elif 'cusparseOrder_t*' in s: + s = s.split() + decl += ' hipsparseOrder_t blah2 = ' + decl += 'convert_hipsparseOrder_t(*' + s[-1][:-1] + ');\n' + arg = '&blah2' + s[-1][-1] + cast = '' + elif 'cusparseOrder_t' in s: + s = s.split() + decl += ' hipsparseOrder_t blah2 = ' + decl += 'convert_hipsparseOrder_t(' + s[-1][:-1] + ');\n' + arg = 'blah2' + s[-1][-1] + cast = '' + elif ('const void*' in s + and hip_func == 'hipsparseSpVV_bufferSize'): + # work around HIP's bad typing... + s = s.split() + arg = '(' + s[-1][:-1] + ')' + s[-1][-1] + cast = 'const_cast' + else: + s = s.split() + arg = s[-1] + cast = '' + hip_sig += (cast + arg + ' ') + return hip_sig, decl + + +def main(hip_h, cu_h, stubs, hip_version, init): + hip_version = get_hip_ver_num(hip_version) + + # output HIP stub + hip_stub_h = [] + + for i, line in enumerate(stubs): + if i == 3 and not init: + hip_stub_h.append(line) + if hip_version == 305: + # insert the include after the include guard + hip_stub_h.append('#include ') + hip_stub_h.append( + '#include // for HIP_VERSION') + hip_stub_h.append( + '#include // for hipDataType') + hip_stub_h.append(cudaDataType_converter) + hip_stub_h.append(default_return_code) + + elif line.startswith('typedef'): + old_line = '' + typedef_found = False + typedef_needed = True + for t in typedefs: + if t in line and t not in processed_typedefs: + hip_t = 'hip' + t[2:] if t.startswith('cu') else t + if hip_t in hip_h: + old_line = line + if t != hip_t: + old_line = line + line = 'typedef ' + hip_t + ' ' + t + ';' + else: + if hip_version == 305: + line = None + typedef_needed = False + typedef_found = True + else: + # new API not supported yet, use typedef from stub + pass + break + else: + t = None + + if line is not None: + # hack... + if t == 'cusparseOrder_t' and hip_version == 402: + hip_stub_h.append(cusparseOrder_converter) + + elif typedef_found and hip_version > 305: + if typedef_needed: + hip_stub_h.append(f'#if HIP_VERSION >= {hip_version}') + else: + hip_stub_h.append(f'#if HIP_VERSION < {hip_version}') + + # hack... + if not (t == 'cusparseOrder_t' and hip_version == 402): + hip_stub_h.append(line) + + if typedef_found and hip_version > 305: + + if typedef_needed: + hip_stub_h.append('#else') + hip_stub_h.append(old_line) + hip_stub_h.append('#endif\n') + + if t is not None and typedef_found: + processed_typedefs.add(t) + + elif '...' in line: + # ex: line = "cusparseStatus_t cusparseDestroyMatDescr(...) {" + sig = line.split() + try: + assert len(sig) == 3 + except AssertionError: + print(f"sig is {sig}") + raise + + # strip the prefix "cu" and the args "(...)", and assume HIP has + # the same function + cu_func = sig[1] + cu_func = cu_func[:cu_func.find('(')] + hip_func = 'hip' + cu_func[2:] + + # find the full signature from cuSPARSE header + cu_sig = get_idx_to_func(cu_h, cu_func) + # check if HIP has the corresponding function + hip_sig = get_idx_to_func(hip_h, hip_func) + if cu_sig == -1 and hip_sig == -1: + assert False + elif cu_sig == -1 and hip_sig != -1: + print(cu_func, "not found in cuSPARSE, maybe removed?", + file=sys.stderr) + can_map = False + elif cu_sig != -1 and hip_sig == -1: + print(hip_func, "not found in hipSPARSE, maybe not supported?", + file=sys.stderr) + can_map = False + else: + end_idx = cu_h[cu_sig:].find(')') + assert end_idx != -1 + cu_sig = cu_h[cu_sig:cu_sig+end_idx+1] + + # pretty print + cu_sig = cu_sig.split('\n') + new_cu_sig = cu_sig[0] + '\n' + for s in cu_sig[1:]: + new_cu_sig += (' ' * (len(sig[0]) + 1)) + s + '\n' + cu_sig = new_cu_sig[:-1] + + sig[1] = cu_sig + can_map = True + hip_stub_h.append(' '.join(sig)) + + # now we have the full signature, map the return to HIP's function; + # note that the "return" line is in the next two lines + line = stubs[i+1] + if 'return' not in line: + line = stubs[i+2] + assert 'return' in line + if can_map: + cu_sig = cu_sig.split('\n') + cu_sig = merge_bad_broken_lines(cu_sig) + + if hip_version != 305: + hip_stub_h.append(f"#if HIP_VERSION >= {hip_version}") + hip_sig = ' return ' + hip_func + '(' + decl = '' + for s in cu_sig: + hip_sig, decl = process_func_args( + s, hip_sig, decl, hip_func) + hip_sig = hip_sig[:-1] + ';' + hip_stub_h.append(decl+hip_sig) + if hip_version != 305: + hip_stub_h.append("#else") + hip_stub_h.append( + ' return HIPSPARSE_STATUS_NOT_SUPPORTED;') + hip_stub_h.append("#endif") + else: + hip_stub_h.append( + (line[:line.find('return')+6] + + ' HIPSPARSE_STATUS_NOT_SUPPORTED;')) + + elif 'return' in line: + if 'CUSPARSE_STATUS' in line: + # don't do anything, as we handle the return when + # parsing "(...)" + pass + elif 'HIPSPARSE_STATUS_NOT_SUPPORTED' in line: + if '#else' in stubs[i-1]: + # just copy from the stub + hip_stub_h.append(line) + else: + # just copy from the stub + hip_stub_h.append(line) + + else: + # just copy from the stub + hip_stub_h.append(line) + + return ('\n'.join(hip_stub_h)) + '\n' + + +if __name__ == '__main__': + with open('cupy_backends/stub/cupy_cusparse.h', 'r') as f: + stubs = f.read() + + init = False + for cu_ver in cu_versions: + with open(cusparse_h.format(cu_ver), 'r') as f: + cu_h = f.read() + + x = 0 + for hip_ver in hip_versions: + stubs_splitted = stubs.splitlines() + + req = urllib.request.urlopen(hipsparse_url.format(hip_ver)) + with req as f: + hip_h = f.read().decode() + + stubs = main(hip_h, cu_h, stubs_splitted, hip_ver, init) + init = True + + # more hacks... + stubs = stubs.replace( + '#define CUSPARSE_VERSION -1', + ('#define CUSPARSE_VERSION ' + '(hipsparseVersionMajor*100000+hipsparseVersionMinor*100' + '+hipsparseVersionPatch)')) + stubs = stubs.replace( + 'INCLUDE_GUARD_STUB_CUPY_CUSPARSE_H', + 'INCLUDE_GUARD_HIP_CUPY_HIPSPARSE_H') + stubs = stubs[stubs.find('\n'):] + + with open('cupy_backends/hip/cupy_hipsparse.h', 'w') as f: + f.write(stubs) diff --git a/vllm/lib/python3.10/site-packages/cupyx/tools/install_library.py b/vllm/lib/python3.10/site-packages/cupyx/tools/install_library.py new file mode 100644 index 0000000000000000000000000000000000000000..964c764829da8bd0cadbb291d3b1f6cd225009bf --- /dev/null +++ b/vllm/lib/python3.10/site-packages/cupyx/tools/install_library.py @@ -0,0 +1,285 @@ +#!/usr/bin/env python + +""" +CUDA Library Installer + +Installs the latest CUDA library supported by CuPy. +""" + +# This script will also be used as a standalone script when building wheels. +# Keep the script runnable without CuPy dependency. + +import argparse +import json +import os +import platform +import shutil +import subprocess +import sys +import tempfile +import urllib.request + + +_cudnn_records = [] +_cutensor_records = [] +_nccl_records = [] +library_records = {} + + +def _make_cudnn_url(platform, filename): + # https://developer.download.nvidia.com/compute/cudnn/redist/cudnn/linux-x86_64/cudnn-linux-x86_64-8.8.1.3_cuda12-archive.tar.xz + return ( + 'https://developer.download.nvidia.com/compute/cudnn/redist/cudnn/' + + f'{platform}/{filename}') + + +def __make_cudnn_record( + cuda_version, public_version, filename_linux, filename_windows): + major_version = public_version.split('.')[0] + # Dependency order is documented at: + # https://docs.nvidia.com/deeplearning/cudnn/api/index.html + suffix_list = ['', '_ops_infer', '_ops_train', + '_cnn_infer', '_cnn_train', + '_adv_infer', '_adv_train'] + return { + 'cuda': cuda_version, + 'cudnn': public_version, + 'assets': { + 'Linux': { + 'url': _make_cudnn_url('linux-x86_64', filename_linux), + 'filenames': [f'libcudnn{suffix}.so.{public_version}' + for suffix in suffix_list] + }, + 'Windows': { + 'url': _make_cudnn_url('windows-x86_64', filename_windows), + 'filenames': [f'cudnn{suffix}64_{major_version}.dll' + for suffix in suffix_list] + }, + } + } + + +def _make_cudnn_record(cuda_version): + cuda_major = int(cuda_version.split('.')[0]) + assert cuda_major in (11, 12) + return __make_cudnn_record( + cuda_version, '8.8.1', + f'cudnn-linux-x86_64-8.8.1.3_cuda{cuda_major}-archive.tar.xz', + f'cudnn-windows-x86_64-8.8.1.3_cuda{cuda_major}-archive.zip') + + +# Latest cuDNN versions: https://developer.nvidia.com/rdp/cudnn-download +_cudnn_records.append(_make_cudnn_record('12.x')) +_cudnn_records.append(_make_cudnn_record('11.x')) # CUDA 11.2+ +library_records['cudnn'] = _cudnn_records + + +def _make_cutensor_url(platform, filename): + # https://developer.download.nvidia.com/compute/cutensor/redist/libcutensor/linux-x86_64/libcutensor-linux-x86_64-1.5.0.3-archive.tar.xz + return ( + 'https://developer.download.nvidia.com/compute/cutensor/' + + f'redist/libcutensor/{platform}-x86_64/{filename}') + + +def __make_cutensor_record( + cuda_version, public_version, filename_linux, filename_windows): + return { + 'cuda': cuda_version, + 'cutensor': public_version, + 'assets': { + 'Linux': { + 'url': _make_cutensor_url('linux', filename_linux), + 'filenames': ['libcutensor.so.{}'.format(public_version)], + }, + 'Windows': { + 'url': _make_cutensor_url('windows', filename_windows), + 'filenames': ['cutensor.dll'], + }, + } + } + + +def _make_cutensor_record(cuda_version): + return __make_cutensor_record( + cuda_version, '2.1.0', + 'libcutensor-linux-x86_64-2.1.0.9-archive.tar.xz', + 'libcutensor-windows-x86_64-2.1.0.9-archive.zip') + + +_cutensor_records.append(_make_cutensor_record('12.x')) +_cutensor_records.append(_make_cutensor_record('11.x')) # CUDA 11.2+ +library_records['cutensor'] = _cutensor_records + + +def _make_nccl_url(public_version, filename): + # https://developer.download.nvidia.com/compute/redist/nccl/v2.8/nccl_2.8.4-1+cuda11.2_x86_64.txz + return ( + 'https://developer.download.nvidia.com/compute/redist/nccl/' + + 'v{}/{}'.format(public_version, filename)) + + +def _make_nccl_record( + cuda_version, full_version, public_version, filename_linux): + return { + 'cuda': cuda_version, + 'nccl': full_version, + 'assets': { + 'Linux': { + 'url': _make_nccl_url(public_version, filename_linux), + 'filenames': ['libnccl.so.{}'.format(full_version)], + }, + }, + } + + +# https://docs.nvidia.com/deeplearning/nccl/release-notes/overview.html +_nccl_records.append(_make_nccl_record( + '12.x', '2.25.1', '2.25.1', + 'nccl_2.25.1-1+cuda12.8_x86_64.txz')) +_nccl_records.append(_make_nccl_record( + '11.x', '2.16.5', '2.16.5', # CUDA 11.2+ + 'nccl_2.16.5-1+cuda11.8_x86_64.txz')) +library_records['nccl'] = _nccl_records + + +def _unpack_archive(filename, extract_dir): + try: + shutil.unpack_archive(filename, extract_dir) + except shutil.ReadError: + print('The archive format is not supported in your Python ' + 'environment. Falling back to "tar" command...') + try: + os.makedirs(extract_dir, exist_ok=True) + subprocess.run( + ['tar', 'xf', filename, '-C', extract_dir], check=True) + except subprocess.CalledProcessError: + msg = 'Failed to extract the archive using "tar" command.' + raise RuntimeError(msg) + + +def install_lib(cuda, prefix, library): + if platform.uname().machine.lower() not in ('x86_64', 'amd64'): + raise RuntimeError(''' +Currently this tool only supports x86_64 architecture.''') + record = None + lib_records = library_records + for record in lib_records[library]: + if record['cuda'] == cuda: + break + else: + raise RuntimeError(''' +The CUDA version specified is not supported. +Should be one of {}.'''.format(str([x['cuda'] for x in lib_records[library]]))) + if prefix is None: + prefix = os.path.expanduser('~/.cupy/cuda_lib') + destination = calculate_destination(prefix, cuda, library, record[library]) + + if os.path.exists(destination): + raise RuntimeError(''' +The destination directory {} already exists. +Remove the directory first if you want to reinstall.'''.format(destination)) + + target_platform = platform.system() + asset = record['assets'].get(target_platform, None) + if asset is None: + raise RuntimeError(''' +The current platform ({}) is not supported.'''.format(target_platform)) + + if library == 'cudnn': + print('By downloading and using cuDNN, you accept the terms and' + ' conditions of the NVIDIA cuDNN Software License Agreement:') + print(' https://docs.nvidia.com/deeplearning/cudnn/sla/index.html') + print() + elif library == 'cutensor': + print('By downloading and using cuTENSOR, you accept the terms and' + ' conditions of the NVIDIA cuTENSOR Software License Agreement:') + print(' https://docs.nvidia.com/cuda/cutensor/license.html') + print() + elif library == 'nccl': + pass # BSD + else: + assert False + + print('Installing {} {} for CUDA {} to: {}'.format( + library, record[library], record['cuda'], destination)) + + url = asset['url'] + print('Downloading {}...'.format(url)) + with tempfile.TemporaryDirectory() as tmpdir: + with open(os.path.join(tmpdir, os.path.basename(url)), 'wb') as f: + with urllib.request.urlopen(url) as response: + f.write(response.read()) + print('Extracting...') + outdir = os.path.join(tmpdir, 'extract') + _unpack_archive(f.name, outdir) + + subdir = os.listdir(outdir) + assert len(subdir) == 1 + dir_name = subdir[0] + + print('Installing...') + if library == 'cudnn': + libdirs = ['bin', 'lib'] if sys.platform == 'win32' else ['lib'] + for item in libdirs + ['include', 'LICENSE']: + shutil.move( + os.path.join(outdir, dir_name, item), + os.path.join(destination, item)) + elif library == 'cutensor': + if cuda.startswith('11.') and cuda != '11.0': + cuda = '11' + elif cuda.startswith('12.'): + cuda = '12' + license = 'LICENSE' + shutil.move( + os.path.join(outdir, dir_name, 'include'), + os.path.join(destination, 'include')) + shutil.move( + os.path.join(outdir, dir_name, 'lib', cuda), + os.path.join(destination, 'lib')) + shutil.move( + os.path.join(outdir, dir_name, license), destination) + elif library == 'nccl': + shutil.move(os.path.join(outdir, dir_name), destination) + else: + assert False + print('Cleaning up...') + print('Done!') + + +def calculate_destination(prefix, cuda, lib, lib_ver): + """Calculates the installation directory. + + ~/.cupy/cuda_lib/{cuda_version}/{library_name}/{library_version} + """ + return os.path.join(prefix, cuda, lib, lib_ver) + + +def main(args): + parser = argparse.ArgumentParser() + + parser.add_argument('--library', + choices=['cudnn', 'cutensor', 'nccl'], + required=True, + help='Library to install') + parser.add_argument('--cuda', type=str, required=True, + help='CUDA version') + parser.add_argument('--prefix', type=str, default=None, + help='Install destination') + parser.add_argument('--action', choices=['install', 'dump'], + default='install', + help='Action to perform') + params = parser.parse_args(args) + + if params.prefix is not None: + params.prefix = os.path.abspath(params.prefix) + + if params.action == 'install': + install_lib(params.cuda, params.prefix, params.library) + elif params.action == 'dump': + print(json.dumps(library_records[params.library], indent=4)) + else: + assert False + + +if __name__ == '__main__': + main(sys.argv[1:]) diff --git a/vllm/lib/python3.10/site-packages/huggingface_hub/inference/__pycache__/_client.cpython-310.pyc b/vllm/lib/python3.10/site-packages/huggingface_hub/inference/__pycache__/_client.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7a050d0b9f601b096490d97adfdd107451119f0e --- /dev/null +++ b/vllm/lib/python3.10/site-packages/huggingface_hub/inference/__pycache__/_client.cpython-310.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3049a4a00f7cb0cf574db2b40142fceef02059c1e0af7c29de916206d7cc39f8 +size 135484 diff --git a/vllm/lib/python3.10/site-packages/huggingface_hub/inference/_generated/__pycache__/_async_client.cpython-310.pyc b/vllm/lib/python3.10/site-packages/huggingface_hub/inference/_generated/__pycache__/_async_client.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..845db44b710f19497f730210599f66390b2a30cd --- /dev/null +++ b/vllm/lib/python3.10/site-packages/huggingface_hub/inference/_generated/__pycache__/_async_client.cpython-310.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a221ce216365f9f9ab02034032727c863d12786b1c5ab0fbe1f24d113e33b5a8 +size 142105