diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/backend.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/backend.h new file mode 100644 index 0000000000000000000000000000000000000000..5aae642fa5517b8dd518117682734f24404c4ee7 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/backend.h @@ -0,0 +1,119 @@ +#pragma once + +#include +#include +#include +#include + +namespace torch { +namespace jit { +namespace { +// NOLINTNEXTLINE(clang-diagnostic-unneeded-internal-declaration) +inline c10::FunctionSchema getIsAvailableSchema() { + c10::Argument self("self", c10::AnyType::get()); + c10::Argument available("available", c10::BoolType::get()); + c10::FunctionSchema preprocessor_schema( + "is_available", + /*overload_name=*/"", + /*arguments=*/{self}, + /*returns=*/{available}); + return preprocessor_schema; +} + +constexpr static auto kBackendsNamespace = "__backends__"; + +// NOLINTNEXTLINE(clang-diagnostic-unneeded-internal-declaration) +inline c10::FunctionSchema getCompileSchema() { + c10::Argument self("self", c10::AnyType::get()); + c10::Argument mod("processed", c10::AnyType::get()); + auto any_dict_ty = + c10::DictType::create(c10::StringType::get(), c10::AnyType::get()); + c10::Argument method_compile_spec("method_compile_spec", any_dict_ty); + c10::Argument handles("handles", any_dict_ty); + + c10::FunctionSchema compile_schema( + "compile", + /*overload_name=*/"", + /*arguments=*/{self, mod, method_compile_spec}, + /*returns=*/{handles}); + return compile_schema; +} + +// NOLINTNEXTLINE(clang-diagnostic-unneeded-internal-declaration) +inline c10::FunctionSchema getExecuteSchema() { + auto any_list_ty = c10::ListType::create(c10::AnyType::get()); + c10::Argument self("self", c10::AnyType::get()); + c10::Argument handle("handle", c10::AnyType::get()); + c10::Argument input("input", any_list_ty); + c10::Argument output("output", any_list_ty); + return c10::FunctionSchema( + "execute", + /*overload_name=*/"", + /*arguments=*/{self, handle, input}, + /*returns=*/{output}); +} + +template +std::function getIsAvailableFunc() { + return [](Stack& stack) { + auto self = pop(stack).toCustomClass(); + auto ret = self->is_available(); + push(stack, ret); + }; +} + +template +std::function getCompileFunc() { + return [](Stack& stack) { + auto method_compile_spec = pop(stack).toGenericDict(); + auto processed = pop(stack); + auto self = pop(stack).toCustomClass(); + auto ret = self->compile(processed, method_compile_spec); + push(stack, ret); + }; +} + +template +std::function getExecuteFunc() { + return [](Stack& stack) { + auto args = pop(stack); + auto handle = pop(stack); + auto self = pop(stack); + auto backend = self.toCustomClass(); + auto res = backend->execute(handle, args.toList()); + push(stack, res); + }; +} +} // namespace + +// Static registration API for backends. +template +class backend { + static_assert( + std::is_base_of::value, + "torch::jit::backend requires T to inherit from PyTorchBackendInterface"); + std::string backend_name_; + + public: + // Registers a new backend with /p name, and the given /p preprocess + // function. + backend(const std::string& name) : backend_name_(name) { + static auto cls = torch::class_(kBackendsNamespace, name) + .def(torch::init<>()) + ._def_unboxed( + "is_available", + getIsAvailableFunc(), + getIsAvailableSchema()) + ._def_unboxed( + "compile", + getCompileFunc(), + getCompileSchema()) + ._def_unboxed( + "execute", + getExecuteFunc(), + getExecuteSchema()); + } +}; + +} // namespace jit +} // namespace torch diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/backend_preprocess.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/backend_preprocess.h new file mode 100644 index 0000000000000000000000000000000000000000..0a256134aa96ece80442b43b238b80af556e1062 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/backend_preprocess.h @@ -0,0 +1,18 @@ +#pragma once + +#include +namespace torch { +namespace jit { +class backend_preprocess_register { + std::string backend_name_; + + public: + backend_preprocess_register( + const std::string& name, + const detail::BackendPreprocessFunction& preprocess) + : backend_name_(name) { + detail::registerBackendPreprocessFunction(name, preprocess); + } +}; +} // namespace jit +} // namespace torch diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/cuda/interface.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/cuda/interface.h new file mode 100644 index 0000000000000000000000000000000000000000..0ccdfe2c9ebd992fa7c0c50c01159ce06b7f53d2 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/cuda/interface.h @@ -0,0 +1,58 @@ +#pragma once + +#include +#include +#include +#include + +/* + * This file contains APIs for cuda fuser; + * + * We use an empty static struct to hold the function pointers, which are + * registered separately. This is to support cpu-only compilation. + * Registration is done in torch/csrc/jit/codegen/cuda/register_interface.cpp + */ + +namespace torch { +namespace jit { +namespace fuser { +namespace cuda { + +TORCH_API std::atomic& getCudaFusionGuardMode(); + +TORCH_API bool getSingletonFusion(); +TORCH_API bool setSingletonFusion(bool value); +TORCH_API bool getHorizontalFusion(); +TORCH_API bool setHorizontalFusion(bool value); + +// dummy struct to allow API registration +struct CudaFuserInterface { + void (*fn_compile_n)(Node*) = nullptr; + void (*fn_run_n_s)(const Node*, Stack&) = nullptr; + void (*fn_fuse_graph)(std::shared_ptr&) = nullptr; + bool (*fn_can_fuse_n)(const Node*) = nullptr; + void (*fn_insert_profile_inodes)(ProfilingRecord* pr) = nullptr; + bool (*fn_profile_n)(const Node*) = nullptr; + bool (*fn_skip_n)(const std::string&, bool flip) = nullptr; +}; + +// Get interface, this is used by registration and user facing API internally +TORCH_API CudaFuserInterface* getFuserInterface(); + +TORCH_API void compileFusionGroup(Node* fusion_node); +TORCH_API void runFusionGroup(const Node* fusion_node, Stack& stack); +TORCH_API void fuseGraph(std::shared_ptr&); +TORCH_API bool canFuseNode(const Node* node); +TORCH_API void InsertProfileNodesForCUDAFuser(ProfilingRecord* pr); +TORCH_API bool profileNode(const Node* node); + +TORCH_API bool skipNode(const std::string& symbol_str, bool flip = true); + +TORCH_API bool isEnabled(); +TORCH_API bool setEnabled(bool is_enabled); +TORCH_API bool canBeEnabled(); + +} // namespace cuda +} // namespace fuser +} // namespace jit +} // namespace torch diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/canonicalize_modified_loop.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/canonicalize_modified_loop.h new file mode 100644 index 0000000000000000000000000000000000000000..ce78a21689d7be1b7efb44deacddfd17fcb65f6f --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/canonicalize_modified_loop.h @@ -0,0 +1,14 @@ +#pragma once +#include + +#include + +namespace torch::jit { + +struct Graph; + +// Transforms loops so that they can be represented as python +// for or while loops +TORCH_API void CanonicalizeModifiedLoops(std::shared_ptr& graph); + +} // namespace torch::jit diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/concrete_module_type.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/concrete_module_type.h new file mode 100644 index 0000000000000000000000000000000000000000..f756eda9b4077463730b8b44f6595e4538f86b28 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/concrete_module_type.h @@ -0,0 +1,239 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +namespace torch::jit { + +enum class IterableModuleKind { NONE, LIST, DICT, PARAMLIST, PARAMDICT }; +class ConcreteModuleType; + +// You can think of an nn.Module as a template that corresponds to a family of +// JIT types. The template "arguments" are things like the constant values. +// e.g. +// class M(nn.Module): +// __constants__ = ["const"] +// ... +// +// Is similar to writing the following in C++: +// +// template +// class M { +// ... +// } +// +// We need to consider each different member of the type family a different JIT +// type because, e.g. different constant values lead to different versions of +// the same method. +// +// ConcreteModuleType corresponds to a single member of the type family, with +// all template arguments fully specified. Two Modules that share a +// ConcreteModuleType can share a JIT type, and vice versa. +// +// Why not just use a JIT type to represent concrete types? Because constants, +// function attributes, etc. are currently not representable in the type system, +// so this acts a non-first-class way of tracking concrete types. +// +// ConcreteModuleType is also the source of truth for servicing all +// ModuleValue::attr calls. This is so we can guarantee that if two Module's +// share a JIT type (and thus a ConcreteModuleType), then they behave the same +// way when you access attributes on them. + +// ConcreteModuleType has two phases. +// 1. Creation: First we build it up, during the ScriptModule conversion +// process. This is represented by ConcreteModuleTypeBuilder. +// ...then the converter calls ConcreteModuleTypeBuilder::build(), producing +// a +// ConcreteModuleType ready for querying. +// 2. Querying: We use ConcreteModuleType as a source of truth for +// ModuleValue::attr calls during method compilation. + +// Represents a concrete type during in the process for construction. We use +// this to decide whether we can share types between modules. +class VISIBILITY_HIDDEN ConcreteModuleTypeBuilder { + public: + explicit ConcreteModuleTypeBuilder(py::object pyClass) { + TORCH_INTERNAL_ASSERT(pyClass); + pyClass_ = std::move(pyClass); + } + + void addConstant(std::string name, py::object value); + void addConstant(std::string name, IValue value); + void addAttribute( + std::string name, + const TypePtr& type, + bool isParameter, + bool isBuffer); + void addFunctionAttribute( + std::string name, + const TypePtr& type, + py::object pyFunction); + + void addModule(std::string name, std::shared_ptr meta); + + void addForwardHook(py::object hook); + void addForwardPreHook(py::object pre_hook); + + void addOverload( + std::string methodName, + std::vector overloadedMethodNames); + void addBuiltinFunction(std::string name, const std::string& symbol_name); + void addFailedAttribute(std::string name, std::string failureReason); + void addIgnoredAttribute(std::string name); + void setIterableModuleKind(IterableModuleKind kind); + + // If a ConcreteModuleType is poisoned, it will never compare equal to any + // other concrete type + void setPoisoned(); + + std::shared_ptr build() const { + return std::make_shared(*this); + } + + // This determines whether two modules can share a type. The container structs + // used by ConcreteModuleType have been defined such that operator== + // implements a meaningful comparison in that context. + bool equals(const ConcreteModuleTypeBuilder& other) const; + + struct FunctionAttribute { + FunctionTypePtr function_; + py::object pyFunction_; + + friend bool operator==( + const FunctionAttribute& lhs, + const FunctionAttribute& rhs) { + // Functions are not first class, so we can't do type comparison like a + // regular attribute. So we do a pointer equality check on the actual + // Python function object. + return lhs.pyFunction_.is(rhs.pyFunction_); + } + }; + + struct Attribute { + Attribute(TypePtr type, bool isParam, bool isBuffer) + : type_(std::move(type)), isParam_(isParam), isBuffer_(isBuffer) {} + + friend bool operator==(const Attribute& lhs, const Attribute& rhs) { + return *(lhs.type_) == *(rhs.type_) && lhs.isParam_ == rhs.isParam_; + } + TypePtr type_; + bool isParam_; + bool isBuffer_; + }; + + struct ModuleInfo { + ModuleInfo(std::string name, std::shared_ptr meta) + : name_(std::move(name)), meta_(std::move(meta)) {} + + friend bool operator==(const ModuleInfo& lhs, const ModuleInfo& rhs); + + std::string name_; + std::shared_ptr meta_; + }; + + private: + ConcreteModuleTypeBuilder() = default; + ClassTypePtr createTypeFromThis() const; + + // If true, this type will never compare equally to anything else. This is + // used if we want to ensure that this type is not shared (for example, if it + // came from a traced module) + bool isPoisoned_ = false; + + // The value of any constants defined by the module. + std::unordered_map constants_; + // The types of any attributes + OrderedDict attributes_; + // Overloads, in the same format as `__overloads__` in Python + std::unordered_map> overloads_; + // Any attributes we failed to convert to TorchScript, along with a hint as to + // why + std::unordered_map failedAttributes_; + // Any attributes that were marked as ignored. They cannot be used in + // TorchScript but can still be used in ignored function in Python. + std::unordered_set ignoredAttributes_; + // Any function attributes. These are special right now because functions are + // not first-class in the type system. + std::unordered_map functionAttributes_; + // Function attributes that are calls to builtin functions. These get + // de-sugared directly into the corresponding aten:: call. The map is + // attribute name -> aten symbol name + std::unordered_map builtinFunctions_; + // The concrete types of any submodules + std::vector modules_; + // Hooks to be called before/after forward when the module + // is called directly. Used to ensure modules have different types + // when they have different python hooks + // Actual hooks are added to ClassType directly during compilation + std::vector forwardHooks_; + std::vector forwardPreHooks_; + + // If something is a ModuleDict/ModuleList, it means: + // 1. The order of the submodules matters for comparing the type + // 2. The compiler is allowed to treat it like a dict/tuple + IterableModuleKind iterableModuleKind_ = IterableModuleKind::NONE; + + // The original `nn.Module` class that we derived this ScriptModule from. + py::object pyClass_; + + // NOTE: If you ever add any more state to this struct, you need to make sure + // operator== still makes sense! + friend ConcreteModuleType; +}; + +// Represents a finalized concrete type, used to service ModuleValue::attr calls +// during method compilation. +class VISIBILITY_HIDDEN ConcreteModuleType { + public: + explicit ConcreteModuleType(ConcreteModuleTypeBuilder data); + + static std::shared_ptr fromJitType(TypePtr type); + + TypePtr getJitType() const; + std::optional getPyClass() const; + IterableModuleKind getIterableModuleKind() const; + std::optional> findOverloads( + const std::string& name) const; + std::optional findFunctionAttribute(const std::string& name) const; + std::optional findBuiltinFunction(const std::string& name) const; + std::shared_ptr findSubmoduleConcreteType( + const std::string& name) const; + std::optional findFailedAttribute(const std::string& name) const; + bool isIgnoredAttribute(const std::string& name) const; + + // These getters are only here to return things as types that can be + // automatically converted by pybind. + std::unordered_map getConstantsPy() const; + std::unordered_map> getAttributesPy() + const; + std::vector>> + getModulesPy() const; + + bool equals(const ConcreteModuleType& other) const { + if (jitType_ == other.jitType_) { + // If the computed types are the same, these modules can (obviously) share + // a type. + return true; + } + + return data_.equals(other.data_); + } + bool equals(const ConcreteModuleTypeBuilder& other) const { + return data_.equals(other); + } + + void dump() const; + + private: + ConcreteModuleType() = default; + + // The JIT type derived from this ConcreteModuleType. + ConcreteModuleTypeBuilder data_; + TypePtr jitType_; +}; + +} // namespace torch::jit diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/edit_distance.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/edit_distance.h new file mode 100644 index 0000000000000000000000000000000000000000..761e7ff50f022210f43ce9c32b1121c99352a797 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/edit_distance.h @@ -0,0 +1,13 @@ +#pragma once + +#include +#include + +namespace torch::jit { + +TORCH_API size_t ComputeEditDistance( + const char* word1, + const char* word2, + size_t maxEditDistance); + +} // namespace torch::jit diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/error_report.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/error_report.h new file mode 100644 index 0000000000000000000000000000000000000000..635dd35468e3b3c83d2fe993868973fb8297c6d9 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/error_report.h @@ -0,0 +1,51 @@ +#pragma once + +#include + +namespace torch::jit { + +struct Call { + std::string fn_name; + SourceRange caller_range; +}; + +struct TORCH_API ErrorReport : public std::exception { + ErrorReport(const ErrorReport& e); + + explicit ErrorReport(const SourceRange& r); + explicit ErrorReport(const TreeRef& tree) : ErrorReport(tree->range()) {} + explicit ErrorReport(const Token& tok) : ErrorReport(tok.range) {} + + const char* what() const noexcept override; + + struct TORCH_API CallStack { + // These functions are used to report why a function was being compiled + // (i.e. what was the call stack of user functions at compilation time that + // led to this error) + CallStack(const std::string& name, const SourceRange& range); + ~CallStack(); + + // Change the range that is relevant for the current function (i.e. after + // each successful expression compilation, change it to the next expression) + static void update_pending_range(const SourceRange& range); + }; + + static std::string current_call_stack(); + + private: + template + friend const ErrorReport& operator<<(const ErrorReport& e, const T& t); + + mutable std::stringstream ss; + OwnedSourceRange context; + mutable std::string the_message; + std::vector error_stack; +}; + +template +const ErrorReport& operator<<(const ErrorReport& e, const T& t) { + e.ss << t; + return e; +} + +} // namespace torch::jit diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/exit_transforms.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/exit_transforms.h new file mode 100644 index 0000000000000000000000000000000000000000..94a983ce388b726433c7474028aa079edfa29fee --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/exit_transforms.h @@ -0,0 +1,10 @@ +#pragma once + +#include +#include + +namespace torch::jit { + +TORCH_API void TransformExits(std::shared_ptr& graph); + +} // namespace torch::jit diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/function_schema_parser.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/function_schema_parser.h new file mode 100644 index 0000000000000000000000000000000000000000..c1a560181f888c83802f81af14e40dbdff55e0ce --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/function_schema_parser.h @@ -0,0 +1,23 @@ +#pragma once + +#include +#include +#include +#include + +namespace torch::jit { + +// allow_typevars: If true, we assume that lowercase types that we don't +// understand are type variables. This is only needed for TorchScript (and not +// not needed for custom ops). +// If false, we disallow typevars, except in certain cases for BC reason (i.e. +// your op is in the aten or prim namespace). +TORCH_API std::variant parseSchemaOrName( + const std::string& schemaOrName, + bool allow_typevars = true); +TORCH_API c10::FunctionSchema parseSchema( + const std::string& schema, + bool allow_typevars = true); +TORCH_API c10::OperatorName parseName(const std::string& name); + +} // namespace torch::jit diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/inline_loop_condition.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/inline_loop_condition.h new file mode 100644 index 0000000000000000000000000000000000000000..74ba37411a9ae6c7405cf74c9fe449080cca3a2b --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/inline_loop_condition.h @@ -0,0 +1,14 @@ +#pragma once +#include +#include +#include + +#include +#include + +namespace torch::jit { + +TORCH_API void InlineLoopCondition(std::shared_ptr& graph); +TORCH_API void InlineBlockBeforeNode(Node* before_node, Block* block); + +} // namespace torch::jit diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/name_mangler.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/name_mangler.h new file mode 100644 index 0000000000000000000000000000000000000000..2f436f91a1f3e64b6304a5bd47f703390863b789 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/name_mangler.h @@ -0,0 +1,25 @@ +#pragma once + +#include +#include + +namespace torch::jit { + +/** + * class NameMangler + * + * Utility to mangle qualified names in order to make them unique. We use this + * in various places where we to de-duplicate qualified names. + */ +class TORCH_API NameMangler { + public: + // Given a qualified name, return a mangled version that is guaranteed to be + // unique with respect to previous/future calls of `mangled()` on this name + // mangler instance. + c10::QualifiedName mangle(const c10::QualifiedName& name); + + private: + size_t mangleIndex_ = 0; +}; + +} // namespace torch::jit diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/parser.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/parser.h new file mode 100644 index 0000000000000000000000000000000000000000..7f4d17b0ce8dc0ddfdfca4720e7aa66e6fee8798 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/parser.h @@ -0,0 +1,31 @@ +#pragma once +#include +#include +#include +#include + +namespace torch::jit { + +struct Decl; +struct ParserImpl; +struct Lexer; + +TORCH_API Decl mergeTypesFromTypeComment( + const Decl& decl, + const Decl& type_annotation_decl, + bool is_method); + +struct TORCH_API Parser { + explicit Parser(const std::shared_ptr& src); + TreeRef parseFunction(bool is_method); + TreeRef parseClass(); + Decl parseTypeComment(); + Expr parseExp(); + Lexer& lexer(); + ~Parser(); + + private: + std::unique_ptr pImpl; +}; + +} // namespace torch::jit diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/parser_constants.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/parser_constants.h new file mode 100644 index 0000000000000000000000000000000000000000..cf51d10b098711e7b8d9507266966b80cee891cc --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/parser_constants.h @@ -0,0 +1,5 @@ +#pragma once + +namespace torch::jit { +static const char* valid_single_char_tokens = "+-*/%@()[]:,={}><.?!&^|~"; +} // namespace torch::jit diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/resolver.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/resolver.h new file mode 100644 index 0000000000000000000000000000000000000000..d5b0f1954c833d10cf778667e01cfed72c9f4fa5 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/resolver.h @@ -0,0 +1,66 @@ +#pragma once + +#include +#include +#include + +namespace torch::jit { + +struct Resolver; +using ResolverPtr = std::shared_ptr; + +/** + * class Resolver + * + * Represents an "outer environment" in which we an look up names and return + * a corresponding SugaredValue. This is used during compilation to resolve + * references to names which are not defined internal to the graph. + * + * Example: PythonResolver looks at the enclosing Python scope for `name`. + * + * NOTE: When adding methods, keep this an abstract class (i.e. all new methods + * should be purely virtual). Resist the urge to provide a default + * implementation; you should explicitly think about how each resolver would + * handle the method. + */ +struct Resolver { + virtual ~Resolver() = default; + + // Resolve a given name to a SugaredValue. This takes the method `m` that the + // caller is currently constructing, since we may need to insert nodes into + // the graph to create a value. + virtual std::shared_ptr resolveValue( + const std::string& name, + GraphFunction& m, + const SourceRange& loc) { + return nullptr; + } + + // Resolve `name` to a TypePtr. + virtual TypePtr resolveType(const std::string& name, const SourceRange& loc) { + return nullptr; + } +}; + +// A resolver that only understands "torch.foo()" lookups. +struct NativeResolver : public Resolver { + std::shared_ptr resolveValue( + const std::string& name, + GraphFunction& m, + const SourceRange& loc) override { + if (name == "torch") { + return std::make_shared("aten"); + } + return nullptr; + } + + TypePtr resolveType(const std::string& name, const SourceRange& loc) + override { + return nullptr; + } +}; + +inline std::shared_ptr nativeResolver() { + return std::make_shared(); +} +} // namespace torch::jit diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/schema_matching.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/schema_matching.h new file mode 100644 index 0000000000000000000000000000000000000000..ddc6f1f22dd118e02f5676b6f5eba6af5664da6a --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/schema_matching.h @@ -0,0 +1,68 @@ +#pragma once +#include +#include +#include + +#include + +namespace torch::jit { + +// Try to match a list of inputs and keyword 'attributes' to this +// schema. Return the flat list of positional inputs to the call or +// `std::nullopt` on failure (`failure_messages` contains a good error +// report in this case) + +struct MatchedSchema { + std::vector inputs; + std::vector return_types; + c10::OptNameList return_field_names; + std::string schema_name; +}; + +TORCH_API bool isBlockListedSchema(const FunctionSchema& schema); + +TORCH_API MatchedSchema matchSchema( + const ::c10::FunctionSchema& schema, + const SourceRange& loc, + Graph& graph, + at::ArrayRef args, + at::ArrayRef kwargs, + const std::optional& self = std::nullopt); + +TORCH_API std::pair matchSchemas( + const std::vector& schemas, + const SourceRange& loc, + Graph& graph, + at::ArrayRef args, + at::ArrayRef kwargs, + const std::optional& self = std::nullopt, + bool render_errors = false); + +TORCH_API bool convertibleToList( + const TypePtr& type, + const TypePtr& list_type_); + +TORCH_API std::string getFullSchemaName(const ::c10::FunctionSchema& schema); + +TORCH_API Value* emitBuiltinCall( + const SourceRange& loc, + Graph& graph, + Symbol name, + at::ArrayRef args, + at::ArrayRef kwargs, + const std::optional& self = std::nullopt); + +TORCH_API std::optional findInputWithName( + const std::string& name, + at::ArrayRef kwargs, + bool is_aten = false); + +// applies implicit conversion from value trying to turn it into type +// concrete_type it succeeds if the return_value->isSubtypeOf(concrete_type) +TORCH_API Value* tryConvertToType( + const SourceRange& loc, + Graph& graph, + const TypePtr& concrete_type, + Value* value, + bool allow_conversions); +} // namespace torch::jit diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/schema_type_parser.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/schema_type_parser.h new file mode 100644 index 0000000000000000000000000000000000000000..ca5a00ecaa3fbd72d9d23d95bd509fc4b2aa70f4 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/schema_type_parser.h @@ -0,0 +1,44 @@ +#pragma once + +#include +#include +#include +#include +#include + +namespace torch::jit { + +using TypePtr = c10::TypePtr; + +struct TORCH_API SchemaTypeParser { + TypePtr parseBaseType(); + std::optional parseAliasAnnotation(); + std::pair> parseType(); + std::tuple> + parseFakeAndRealType(); + std::optional parseTensorDType(const std::string& dtype); + TypePtr parseRefinedTensor(); + + SchemaTypeParser( + Lexer& L, + bool parse_complete_tensor_types, + bool allow_typevars) + : complete_tensor_types(parse_complete_tensor_types), + L(L), + allow_typevars_(allow_typevars) {} + + private: + std::optional tryToParseRequiresGrad(); + std::optional tryToParseDeviceType(); + void parseList( + int begin, + int sep, + int end, + c10::function_ref callback); + + bool complete_tensor_types; + Lexer& L; + size_t next_id = 0; + bool allow_typevars_; +}; +} // namespace torch::jit diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/source_range.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/source_range.h new file mode 100644 index 0000000000000000000000000000000000000000..0f6aa71034eb6ba08e63756326288c7049b0471e --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/source_range.h @@ -0,0 +1,455 @@ +#pragma once +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace torch::jit { + +class SourceRangeUnpickler; +struct SourceRange; + +// A stringlike class backed by a vector of string_view +// the string represented are logically the concatenation of the string_views +// This has advantage of not needing continues memory. +struct TORCH_API StringCordView { + StringCordView(); + StringCordView(const StringCordView&) = default; + StringCordView(StringCordView&&) noexcept = default; + StringCordView( + std::vector inputs, + std::vector> ownerships); + + StringCordView& operator=(const StringCordView&) = default; + StringCordView& operator=(StringCordView&&) noexcept = default; + + size_t size() const { + return accumulated_sizes_.back(); + } + + size_t find(const std::string& tok, size_t start) const; + size_t find_regex(const std::string& tok, size_t start) const; + StringCordView substr(size_t start, size_t size) const; + + char at(size_t index) const { + return *iter_for_pos(index); + } + char operator[](size_t index) const { + return at(index); + } + + std::string str() const { + std::stringstream ss; + for (auto s : pieces_) { + ss << std::string(s); + } + return ss.str(); + } + + bool operator==(const std::string& rhs) const; + + bool operator==(const StringCordView& rhs) const; + + c10::string_view piece(size_t index) const { + return pieces_[index]; + } + + struct Iterator { + Iterator( + const StringCordView* str, + size_t start_line, + size_t start_pos, + size_t size) + : line_(start_line), pos_(start_pos), str_(str), size_(size) {} + explicit Iterator(const StringCordView* str) + : Iterator(str, 0, 0, str->size()) {} + + Iterator() : Iterator(nullptr, 0, 0, 0) {} + + Iterator(const Iterator&) = default; + Iterator(Iterator&&) = default; + Iterator& operator=(const Iterator&) = default; + Iterator& operator=(Iterator&&) = default; + + Iterator operator++() { + if (size_ == 0) { + return *this; + } + if ((pos_ + 1) < str_->pieces_[line_].size()) { + pos_++; + } else { + line_++; + pos_ = 0; + } + return *this; + } + + Iterator operator++(int) { + Iterator prev(*this); + ++(*this); + return prev; + } + + Iterator next_iter() const { + Iterator next(*this); + ++next; + return next; + } + + Iterator& operator+=(size_t num) { + if (!has_next()) { + return *this; + } + size_t target_pos = pos_ + num; + if (target_pos >= str_->accumulated_sizes_[line_] && + (line_ + 1) < str_->accumulated_sizes_.size() && + target_pos < str_->accumulated_sizes_[line_ + 1]) { + pos_ = target_pos; + return *this; + } + + size_t target_abs_pos = pos() + num; + *this = str_->iter_for_pos(target_abs_pos); + return *this; + } + + bool operator==(const Iterator& rhs) const { + if (!has_next() && !rhs.has_next()) { + return true; + } + return (str_ == rhs.str_) && (line_ == rhs.line_) && (pos_ == rhs.pos_); + } + bool operator!=(const Iterator& rhs) { + return !((*this) == rhs); + } + bool has_next() const { + return size_ > 0 && (line_ < str_->pieces_.size()); + } + + char operator*() const { + TORCH_INTERNAL_ASSERT(line_ < str_->pieces_.size()); + TORCH_INTERNAL_ASSERT(pos_ < str_->pieces_[line_].size()); + return str_->pieces_[line_].at(pos_); + } + + // returns rest of the line of the current iterator + c10::string_view rest_line() const { + if (line_ >= str_->pieces_.size()) { + return ""; + } + + c10::string_view cur_line = str_->pieces_[line_]; + return cur_line.substr(pos_, std::string::npos); + } + + size_t pos() const { + if (size_ == 0) { + return 0; + } + return str_->accumulated_sizes_[line_] + pos_; + } + + private: + size_t line_; + size_t pos_; + const StringCordView* str_; + size_t size_; + friend struct StringCordView; + }; + + Iterator begin() const { + return Iterator(this, 0, 0, size()); + } + Iterator end() const { + return Iterator(this, pieces_.size(), 0, 0); + } + Iterator iter_for_pos(size_t pos) const; + + private: + std::vector pieces_; + std::vector accumulated_sizes_; + std::vector> owned_strings_; +}; + +// Source represents a code segment. It keeps track of: +// - text_view : the view into text of the code segment +// - filename (optional) : if present, represents the name of the file from +// which the code segment originated. +// - starting_line_no : represents the line in the original file where the +// code segment started. +struct TORCH_API Source { + // Whether or not Source should copy the string passed in the constructor. + enum CopiesString { COPIES_STRING, DONT_COPY }; + + explicit Source( + c10::string_view text_view, + std::optional filename = std::nullopt, + size_t starting_line_no = 0, + std::shared_ptr gen_ranges = nullptr, + CopiesString copies_str = COPIES_STRING) + : filename_(std::move(filename)), + starting_line_no_(starting_line_no), + gen_ranges_(std::move(gen_ranges)) { + if (copies_str == COPIES_STRING) { + std::shared_ptr allocated_str = + std::make_shared(text_view.data(), text_view.size()); + text_view_ = StringCordView({*allocated_str}, {allocated_str}); + } else { + text_view_ = StringCordView({text_view}, {}); + } + + calc_line_start_offsets(); + } + + explicit Source( + StringCordView str, + std::optional filename = std::nullopt, + size_t starting_line_no = 0, + std::shared_ptr gen_ranges = nullptr) + : text_view_(std::move(str)), + filename_(std::move(filename)), + starting_line_no_(starting_line_no), + gen_ranges_(std::move(gen_ranges)) { + calc_line_start_offsets(); + } + // Given a line number (within source_), return the byte offset of the + // beginning of that line. + size_t offset_for_line(size_t line) const { + return line_starting_offsets_.at(line); + } + + // Returns number of lines present. + size_t num_lines() const { + return line_starting_offsets_.size(); + } + + // Calculate the line (within the code segment) on which `offset` resides. + size_t lineno_for_offset(size_t offset) const { + auto iter = std::upper_bound( + line_starting_offsets_.begin(), line_starting_offsets_.end(), offset); + return iter - line_starting_offsets_.begin() - 1; + } + + // Calculate the line (within the original source file, if present) on which + // `lineno` resides. + size_t lineno_to_source_lineno(size_t lineno) const { + if (filename_) { + return lineno + starting_line_no_; + } else { + return lineno; + } + } + + StringCordView get_line(size_t lineno) const { + auto start = offset_for_line(lineno); + auto size = (lineno + 1) < num_lines() ? offset_for_line(lineno + 1) - start + : text_view_.size() - start; + return text_view_.substr(start, size); + } + + const StringCordView& text_str() const { + return text_view_; + } + + char char_at(size_t index) const { + return text_view_.at(index); + } + + size_t size() const { + return text_view_.size(); + } + + std::optional& filename() { + return filename_; + } + + size_t starting_line_no() const { + return starting_line_no_; + } + + std::optional findSourceRangeThatGenerated( + const SourceRange& range); + + ~Source() = default; + + private: + void calc_line_start_offsets() { + line_starting_offsets_.clear(); + line_starting_offsets_.push_back(0); + size_t pos = 0; + while ((pos = text_view_.find("\n", pos)) != std::string::npos) { + line_starting_offsets_.push_back(++pos); + } + } + + StringCordView text_view_; + + std::optional filename_; + // If filename_ is not present, starting_line_no_ is don't care + size_t starting_line_no_; + // Starting offsets for lines into the source. e.g. line 0 starts at + // line_starting_offsets_[0], etc. + std::vector line_starting_offsets_; + + std::shared_ptr gen_ranges_; +}; + +// A SourceRange is a reference to subset of a Source, specified by `start` and +// `end` byte offsets into the source text. +struct TORCH_API SourceRange { + SourceRange(std::shared_ptr source_view, size_t start_, size_t end_) + : source_view_(std::move(source_view)), start_(start_), end_(end_) { + if (source_view_) { + start_iter_ = source_view_->text_str().iter_for_pos(start_); + } + } + + SourceRange() : source_view_(nullptr), start_(0), end_(0) {} + + SourceRange( + std::shared_ptr source_view_, + StringCordView::Iterator start_iter, + size_t end_) + : source_view_(std::move(source_view_)), + start_(start_iter.pos()), + end_(end_), + start_iter_(start_iter) {} + + const c10::string_view token_text() const { + size_t size = end() - start(); + return start_iter_.rest_line().substr(0, size); + } + + const StringCordView text() const { + return source_view_->text_str().substr(start(), end() - start()); + } + size_t size() const { + return end() - start(); + } + static const size_t CONTEXT = 3; + void highlight(std::ostream& out) const; + + // Customizable version of 'highlight' method. + void print_with_context( + std::ostream& out, + size_t context, + bool highlight, + const std::string& funcname) const; + + const std::shared_ptr& source() const { + return source_view_; + } + size_t start() const { + return start_; + } + size_t end() const { + return end_; + } + std::string str() const { + std::stringstream ss; + highlight(ss); + return ss.str(); + } + + std::optional> file_line_col() const { + if (!source_view_ || !source()->filename()) { + return std::nullopt; + } + + auto lineno = source_view_->lineno_for_offset(start_); + auto col_offset = (int)start_ - (int)source_view_->offset_for_line(lineno); + // TODO: std::optional<>::value returns an rvalue ref so can't use it here?? + return std::make_tuple( + source_view_->filename().value_or(""), + source_view_->lineno_to_source_lineno(lineno), + (size_t)col_offset); + } + + bool operator==(const SourceRange& rhs) const { + return start() == rhs.start() && end() == rhs.end() && + source() == rhs.source(); + } + + bool operator!=(const SourceRange& rhs) const { + return !(*this == rhs); + } + + std::optional findSourceRangeThatGenerated() const { + if (!source_view_) { + return std::nullopt; + } + return source_view_->findSourceRangeThatGenerated(*this); + } + + protected: + std::shared_ptr source_view_; + + private: + size_t start_; + size_t end_; + StringCordView::Iterator start_iter_; +}; + +// OwnedSourceRange is just like a SourceRange except that it owns a `Source` +// instead of `Source`. Thus OwnedSourceRange owns a copy of source text. +struct OwnedSourceRange : public SourceRange { + explicit OwnedSourceRange(const SourceRange& source_range) + : SourceRange(source_range) { + const auto& source = source_range.source(); + if (source) { + source_view_ = std::make_shared( + source->text_str().str(), + source->filename(), + source->starting_line_no()); + } + } +}; + +struct TORCH_API SourceRangeHasher { + public: + size_t operator()(const torch::jit::SourceRange& key) const; +}; + +struct StackEntry { + std::string filename; + SourceRange range; +}; + +TORCH_API void format_stack_trace( + std::ostream& out, + const std::vector& entries); + +inline std::ostream& operator<<(std::ostream& out, const SourceRange& range) { + range.highlight(out); + return out; +} + +// A pair of (byte offset, SourceRange) describing a specific segment +// of the output stream +struct TaggedRange { + TaggedRange(size_t bytes, SourceRange range) + : bytes(bytes), range(std::move(range)) {} + size_t bytes; + SourceRange range; +}; +using SourceRangeRecords = std::vector; +using SourceRangeTagMap = + std::unordered_map; + +} // namespace torch::jit + +namespace std { +template <> +struct iterator_traits { + using value_type = char; + using difference_type = ptrdiff_t; + using pointer = char*; + using reference = char&; + using iterator_category = std::forward_iterator_tag; +}; +} // namespace std diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/source_ref.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/source_ref.h new file mode 100644 index 0000000000000000000000000000000000000000..c9ea38fa777503fe5a5b4bd8af382e799c651659 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/source_ref.h @@ -0,0 +1,45 @@ +#pragma once + +#include +#include + +#include +#include +#include + +namespace torch::jit { + +/** + * SourceRef does two things: + * 1. Owns a Source object. + * 2. Serves as lookup key to the owned Source in associative containers, for + * runtime data aggregation. + * We don't want to use std::shared_ptr directly because we want to + * support heteogeneous lookup, and also shared_ptr is an implementation detail + * which should be encapsulated. + */ +class TORCH_API SourceRef : public CustomClassHolder { + public: + explicit SourceRef(std::shared_ptr source_view) + : source_view_(std::move(source_view)) {} + bool operator==(const SourceRef& other) const { + return source_view_ == other.source_view_; + } + bool operator<(const Source& other) const { + return source_view_.get() < &other; + } + friend bool operator<(const Source& other, const SourceRef& self) { + return &other < self.source_view_.get(); + } + bool operator<(const SourceRef& other) const { + return *this < *other.source_view_; + } + const Source* operator->() const { + return source_view_.get(); + } + + private: + std::shared_ptr source_view_; +}; + +} // namespace torch::jit diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/strtod.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/strtod.h new file mode 100644 index 0000000000000000000000000000000000000000..eb704a3e689ef79cb5977f59fe28a4b68b6eec72 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/strtod.h @@ -0,0 +1,10 @@ +#pragma once + +#include + +namespace torch::jit { + +TORCH_API double strtod_c(const char* nptr, char** endptr); +TORCH_API float strtof_c(const char* nptr, char** endptr); + +} // namespace torch::jit diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/tracer.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/tracer.h new file mode 100644 index 0000000000000000000000000000000000000000..106a82e3a9ec3212fd3cf6796818be412ef4ff1e --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/tracer.h @@ -0,0 +1,410 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include +#include +#include +#include + +namespace torch::jit { +struct Node; +struct Value; +struct Graph; +struct Module; + +namespace tracer { + +using ::c10::ivalue::Shared; + +using ::c10::IValue; +using ::c10::ivalue::Future; + +using ::c10::ArrayRef; +using ::c10::TupleType; +using ::c10::TupleTypePtr; +using ::c10::ivalue::ConstantString; + +using torch::autograd::Variable; +using variable_list = std::vector; + +TORCH_API std::atomic& getTracerStateWarnMode(); + +struct TORCH_API TracingState + : public std::enable_shared_from_this { + TracingState(); + ~TracingState(); + + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + std::shared_ptr graph; + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + bool warn = getTracerStateWarnMode(); + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + bool strict = true; + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + bool force_outplace = false; + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + std::function lookup_var_name_fn = + [](const Variable& var) { return ""; }; + + void enterFrame() { + env_stack.emplace_back(); + } + + void leaveFrame() { + env_stack.pop_back(); + } + + void setValue(const IValue& v, Value* value); + void delValue(const IValue& var); + Value* getValue(const IValue& var); + Value* getOutput(const IValue& var, size_t i); + bool hasValue(const IValue& var) const; + + Node* createNode(c10::Symbol op_name, size_t num_outputs); + void insertNode(Node* node); + + private: + using WeakIValue = at::WeakIValue; + + struct WeakIValueHasher { + size_t operator()(const WeakIValue& t) const { + return t.hash(); + } + }; + + struct WeakIValueEq { + bool operator()(const WeakIValue& t1, const WeakIValue& t2) const { + return t1.isSameIdentity(t2); + } + }; + + using Frame = + std::unordered_map; + std::vector env_stack; +}; + +// This is meant to be used as a thread local place, where we can store extra +// info that gets lost when we call into ATen from Python bindings. One example +// for when this happens is when we get an IntArrayRef argument with e.g. sizes +// for view. When tracing, those might be tensors, which let us encode extra +// data dependencies, but once they get to the ATen call where we actually have +// the tracing logic, they get converted into a raw IntArrayRef, and we loose +// all information. To prevent this, we temporarily stash it in here. +struct ArgumentStash { + struct IntArrayRefTrace : std::vector { + IntArrayRefTrace(size_t size) : std::vector(size, nullptr) {} + }; + + static bool empty() { + return stash.intlists.empty(); + } + + TORCH_API static void stashIntArrayRefElem( + const std::string& arg_name, + size_t size, + size_t idx, + const Variable& var); + + static bool hasIntArrayRef(const std::string& arg_name) { + return stash.intlists.count(arg_name) > 0; + } + + static IntArrayRefTrace popIntArrayRef(const std::string& arg_name) { + auto info = std::move(stash.intlists.at(arg_name)); + stash.intlists.erase(arg_name); + return info; + } + + // Value stashing: Use these methods to stash arguments which correspond + // to regular Value*'s in the graph. i.e. they don't require special + // handling like in the case of IntArrayRefs + TORCH_API static void stashValue( + const std::string& arg_name, + size_t idx, + const Variable& var, + const c10::TypePtr& type = nullptr); + + static bool hasValue(const std::string& arg_name) { + return stash.values.count(arg_name) > 0; + } + + static Value* popValue(const std::string& arg_name) { + auto info = stash.values.at(arg_name); + stash.values.erase(arg_name); + return info; + } + + private: + static thread_local ArgumentStash stash; + std::unordered_map intlists; + std::unordered_map values; +}; + +// Retrieve or set the current tracing state. Returns a nullptr if tracing is +// disabled. +TORCH_API const std::shared_ptr& getTracingState(); +TORCH_API void setTracingState(std::shared_ptr state); + +inline bool isTracing() { + return static_cast(getTracingState()); +} + +using warn_fn_type = void (*)(const std::string& msg); +TORCH_API extern const char* WARN_PYTHON_DATAFLOW; +TORCH_API extern const char* WARN_CONSTRUCTOR; +TORCH_API extern const char* WARN_RESIZE; +TORCH_API extern const char* STRICT_TRACER_MSG; +TORCH_API void _do_warn(const char* _reason, const char* _kind); +inline void warn(const char* _reason, const char* _kind = nullptr) { + if (const auto& state = getTracingState()) { + if (!state->warn) + return; + _do_warn(_reason, _kind); + } +} +TORCH_API void setWarn(warn_fn_type fn); + +struct TORCH_API NoWarn { + NoWarn() : state(getTracingState()) { + if (state) { + prev = state->warn; + state->warn = false; + } + } + ~NoWarn() { + if (state) { + state->warn = prev; + } + } + std::shared_ptr state; + bool prev{false}; +}; + +struct WithNestedTracingFrame { + WithNestedTracingFrame() { + getTracingState()->enterFrame(); + } + + ~WithNestedTracingFrame() { + getTracingState()->leaveFrame(); + } +}; +TORCH_API void recordSourceLocation(Node* n); +TORCH_API void setRecordSourceLocation(void (*v)(Node*)); + +TORCH_API std::vector pythonCallstack(); +TORCH_API void setPythonCallstack(std::vector (*v)()); + +// Having finished adding a new 'node' to the graph IR 'setValueTrace' +// associates this node with an output variable, so that further operations +// involving this variable know which node in the IR to reference. +TORCH_API void setValueTrace(const IValue& v, Value* value); + +TORCH_API void delValueTrace(const IValue& var); + +TORCH_API std::function pauseTracing(); + +TORCH_API Value* getValueTrace(const IValue& var); + +TORCH_API std::pair, Stack> trace( + Stack inputs, + const std::function& traced_fn, + std::function var_name_lookup_fn, + bool strict = true, + bool force_outplace = false, + Module* self = nullptr, + const std::vector& argument_names = {}); + +TORCH_API void abandon(); + +// NB: those serve both as an intermediate steps in addInputs below, +// as well as the overloads that terminate template recursion +TORCH_API void addInputs(Node* n, const char* name, int64_t value); +TORCH_API void addInputs(Node* n, const char* name, const c10::SymInt& value); +TORCH_API void addInputs( + Node* n, + const char* name, + std::optional value); +TORCH_API void addInputs(Node* n, const char* name, bool value); +TORCH_API void addInputs( + Node* n, + const char* name, + const std::optional& value); +TORCH_API void addInputs(Node* n, const char* name, double value); +TORCH_API void addInputs( + Node* n, + const char* name, + const std::optional& value); +TORCH_API void addInputs(Node* n, const char* name, const at::Scalar& value); +TORCH_API void addInputs( + Node* n, + const char* name, + const std::optional& value); +TORCH_API void addInputs(Node* n, const char* name, const at::Tensor& value); +TORCH_API void addInputs( + Node* n, + const char* name, + const std::optional& value); +TORCH_API void addInputs(Node* n, const char* name, ArrayRef value); +TORCH_API void addInputs(Node* n, const char* name, c10::SymIntArrayRef value); +TORCH_API void addInputs( + Node* n, + const char* name, + std::optional value); +TORCH_API void addInputs( + Node* n, + const char* name, + const std::optional>& value); +TORCH_API void addInputs( + Node* n, + const char* name, + const at::OptionalIntArrayRef& opt_value); +TORCH_API void addInputs( + Node* n, + const char* name, + const at::OptionalSymIntArrayRef& opt_value); +TORCH_API void addInputs( + Node* n, + const char* name, + ArrayRef value, + bool allow_undefined = false); +TORCH_API void addInputs( + Node* n, + const char* name, + const std::vector& value, + bool allow_undefined = false); +TORCH_API void addInputs( + Node* n, + const char* name, + at::ITensorListRef value, + bool allow_undefined = false); +TORCH_API void addInputs( + Node* n, + const char* name, + const List>& value); +TORCH_API void addInputs( + Node* n, + const char* name, + ArrayRef> value, + const c10::ClassTypePtr& class_type); +TORCH_API void addInputs(Node* n, const char* name, ArrayRef value); +TORCH_API void addInputs( + Node* n, + const char* name, + const std::optional>& value); +TORCH_API void addInputs( + Node* n, + const char* name, + const c10::string_view value); +TORCH_API void addInputs( + Node* n, + const char* name, + const std::optional& value); +TORCH_API void addInputs(Node* n, const char* name, at::Device value); +TORCH_API void addInputs(Node* n, const char* name, c10::Stream stream); +TORCH_API void addInputs(Node* n, const char* name, at::Layout value); +TORCH_API void addInputs(Node* n, const char* name, at::ScalarType value); +TORCH_API void addInputs( + Node* n, + const char* name, + const std::optional& value); +TORCH_API void addInputs( + Node* n, + const char* name, + const std::optional& value); +TORCH_API void addInputs( + Node* n, + const char* name, + const std::optional& value); +TORCH_API void addInputs(Node* n, const char* name, at::MemoryFormat value); +TORCH_API void addInputs( + Node* n, + const char* name, + std::optional value); +TORCH_API void addInputs( + Node* n, + const char* name, + const std::optional& value); +TORCH_API void addInputs( + Node* n, + const char* name, + const std::optional& value); + +inline void addInputs( + Node* n, + const char* name, + const std::vector& value) { + AT_ERROR("Tracing a list of bool type is currently not supported!"); +} + +template +void addInputs(Node* n, const char* name, ArrayRef value) { + AT_ERROR("Tracing a list of arbitrary type is currently not supported!"); +} +template +void addInputs( + Node* n, + const char* name, + const std::unordered_map& value) { + AT_ERROR("Tracing a dict of arbitrary types is currently not supported!"); +} + +template +void addInputs(Node* n, const char* name, std::array value) { + throw std::runtime_error( + "Found an unsupported argument type in the JIT tracer. File a bug report."); +} + +TORCH_API void addInputs( + Node* n, + const char* name, + const c10::intrusive_ptr& obj); + +TORCH_API void ensureUniqueIfOutOfPlaced( + const char* name, + const at::Tensor& tensor); +TORCH_API void ensureUniqueIfOutOfPlaced( + const char* name, + const std::optional& tensor); + +template < + typename T, + typename = std::enable_if_t< + (!std::is_convertible_v, at::TensorList> && + !std::is_convertible_v, c10::List> && + !std::is_convertible_v, at::Tensor> && + !std::is_convertible_v< + std::decay_t, + c10::intrusive_ptr>)>> +void addOutput(Node* node, T&&) { + AT_ERROR( + "Found an unsupported argument type ", + c10::demangle_type(), + " in the JIT tracer. File a bug report."); +} +TORCH_API void addOutput(Node* node, const at::Tensor& tensor); +TORCH_API void setOutput(Value* value, const at::Tensor& output); +TORCH_API void addOutput(Node* node, const std::vector& list); +TORCH_API void addOutput(Node* node, const c10::List& list); +TORCH_API void addOutput( + Node* node, + const c10::intrusive_ptr& output); + +TORCH_API autograd::Variable getSizeOf( + const autograd::Variable& var, + int64_t dim); + +TORCH_API autograd::Variable getNumelOf(const autograd::Variable& var); + +} // namespace tracer +} // namespace torch::jit diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/versioned_symbols.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/versioned_symbols.h new file mode 100644 index 0000000000000000000000000000000000000000..fc6b0ff7a960c4a8fed6d9335f93015f4fb55342 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/versioned_symbols.h @@ -0,0 +1,19 @@ +#pragma once + +#include +#include +#include + +#include + +namespace torch::jit { +// Maps the given symbol into an implementation of its behavior at the +// given version. +// See note [Versioned Symbols] +TORCH_API Symbol +get_symbol_for_version(const Symbol name, const uint64_t version); + +// Maps the given kind to the minimum version that supports it. +// See note [Dynamic Versions and torch.jit.save vs. torch.save] +TORCH_API uint64_t get_min_version_for_kind(const NodeKind& kind); +} // namespace torch::jit diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/mobile/import_data.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/mobile/import_data.h new file mode 100644 index 0000000000000000000000000000000000000000..a75753c9efac9663f00ddf85377687015563575f --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/mobile/import_data.h @@ -0,0 +1,36 @@ +#pragma once + +#include +#include +#include +#include + +#include +#include +#include + +namespace torch::jit { + +/** + * Loads named parameters from the serialized data in @p in. + * + * Calls #TORCH_CHECK() if the data format is not recognized. + */ +TORCH_API std::map _load_parameters( + std::istream& in, + std::optional device = std::nullopt); + +/** + * Loads named parameters from the serialized data in @p filename. + * + * Calls #TORCH_CHECK() if the data format is not recognized. + */ +TORCH_API std::map _load_parameters( + const std::string& filename, + std::optional device = std::nullopt); + +// NOTE: Please prefer using _load_parameters over using the function below. +TORCH_API std::map mobile_module_to_parameter_map( + const mobile::Module& module); + +} // namespace torch::jit diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/mobile/interpreter.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/mobile/interpreter.h new file mode 100644 index 0000000000000000000000000000000000000000..e67595c06b5782dcf5ef13752a4483296069d490 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/mobile/interpreter.h @@ -0,0 +1,26 @@ +#pragma once + +#include + +#include +#include + +namespace torch::jit::mobile { + +struct InterpreterState { + TORCH_API explicit InterpreterState(const Code& code); + TORCH_API bool run(Stack& stack); + + private: + void enterFrame(const Code&); + void leaveFrame(); + void saveExceptionDebugHandles(); + void callFunction(torch::jit::Function& f, Stack& stack); + + c10::IValue& reg(size_t reg); + std::vector registers_; + std::vector frames_; +}; + +const std::vector& getInterpretersExceptionDebugHandles(); +} // namespace torch::jit::mobile diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/mobile/parse_bytecode.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/mobile/parse_bytecode.h new file mode 100644 index 0000000000000000000000000000000000000000..cfc473682054747e81732950706b0aae83f9a812 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/mobile/parse_bytecode.h @@ -0,0 +1,21 @@ +#pragma once +#include + +namespace torch::jit::mobile { +using c10::IValue; +TORCH_API void parseInstructions( + const std::string& function_name, + c10::ivalue::TupleElements&& ins_list, + c10::ivalue::TupleElements& debug_handles_m_tuple, + mobile::Function* function); +TORCH_API void parseConstants( + const c10::ivalue::TupleElements& consts_list, + mobile::Function* function); +TORCH_API void parseTypes( + const c10::ivalue::TupleElements& types_list, + mobile::Function* function); +TORCH_API void parseRegisterSize(size_t rsize, mobile::Function* function); +TORCH_API void applyUpgrader( + mobile::Function* function, + uint64_t operator_version); +} // namespace torch::jit::mobile diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/mobile/parse_operators.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/mobile/parse_operators.h new file mode 100644 index 0000000000000000000000000000000000000000..9cd529d4f3c7b308b3b44de4d4ce1f021f330db5 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/mobile/parse_operators.h @@ -0,0 +1,25 @@ +#pragma once +#include + +namespace torch::jit { +using c10::IValue; + +enum MobileModuleLoadOptions { + OPERATOR_CHECK = 1, + // PARSE_ALL_EXTRA_FILE_MAPS is used to gate for ExtraFileMaps to pull all + // files automatically without explicit entries mapping. Refer to PR for a + // detail: https://github.com/pytorch/pytorch/pull/99747 + PARSE_ALL_EXTRA_FILE_MAPS = 2, +}; + +const uint64_t kDefaultMobileLoadOptions = + MobileModuleLoadOptions::OPERATOR_CHECK; + +namespace mobile { + +TORCH_API void parseOperators( + c10::ivalue::TupleElements&& ops_list, + const uint64_t& module_load_options, + mobile::Function* function); +} // namespace mobile +} // namespace torch::jit diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/mobile/promoted_prim_ops.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/mobile/promoted_prim_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..71baa74f95ae5a0b1c03e6f3d09fad8355a36a9c --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/mobile/promoted_prim_ops.h @@ -0,0 +1,61 @@ +#pragma once +#include +#include + +namespace torch::jit { + +void tupleIndex(Stack& stack); + +void raiseException(Stack& stack); + +void is(Stack& stack); + +void unInitialized(Stack& stack); + +void isNot(Stack& stack); + +void aten_format(Stack& stack); + +void size(Stack& stack); + +void sym_size(Stack& stack); + +void sym_size_int(Stack& stack); + +void sym_stride_int(Stack& stack); + +void sym_numel(Stack& stack); + +void sym_storage_offset(Stack& stack); + +void sym_stride(Stack& stack); + +void device(Stack& stack); + +void device_with_index(Stack& stack); + +void dtype(Stack& stack); + +void layout(Stack& stack); + +void toPrimDType(Stack& stack); + +void dim(Stack& stack); + +void _not(Stack& stack); + +void boolTensor(Stack& stack); + +void toList(Stack& stack); + +void numToTensorScalar(Stack& stack); + +void isCuda(Stack& stack); + +void numToTensorBool(Stack& stack); + +void dictIndex(Stack& stack); + +void raiseExceptionWithMessage(Stack& stack); + +} // namespace torch::jit diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/mobile/quantization.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/mobile/quantization.h new file mode 100644 index 0000000000000000000000000000000000000000..fbe870ee1518d2e7d91443c121b4d883385c7d3c --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/mobile/quantization.h @@ -0,0 +1,34 @@ +#pragma once + +#include +#include + +namespace torch::jit::mobile { +class Module; +namespace quantization { +/* + * Device side PTQ API. + * Once the model has been prepared for quantization on server side, such model + * is sent to device. On device side the model is further trained. At the end of + * the training, before the model is readied for inference, we need to quantize + * the model. + * Usage of this API is as follows. + * PTQQuanizationHelper ptq_helper; + * ptq_helper.quantize_dynamic(m, "forward"); + * Args: + * m: Captured by reference, an instance of mobile::Module. This module will be + * mutated in place to replace its method with quantized + * equivalent. method:name: Name of the method to be quantized. AOT preparation + * for quantization must also have been done for this method. Returns: In place + * mutated `m` whose size should be smaller due to weight quantization and whose + * method should use quantized ops + */ +class TORCH_API PTQQuanizationHelper { + public: + PTQQuanizationHelper() = default; + void quantize_dynamic( + torch::jit::mobile::Module& m, + const std::string& method_name); +}; +} // namespace quantization +} // namespace torch::jit::mobile diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/python/pybind_utils.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/python/pybind_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..96a6f23d6dad5421f9f14f48b7d597d72b672f0d --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/python/pybind_utils.h @@ -0,0 +1,1279 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef USE_DISTRIBUTED +#include +#include +#endif + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +// The visibility attribute is to avoid a warning about storing a field in the +// struct that has a different visibility (from pybind) than the struct. +#ifdef _WIN32 +#define VISIBILITY_HIDDEN +#else +#define VISIBILITY_HIDDEN __attribute__((visibility("hidden"))) +#endif + +namespace torch::jit { + +using ResolutionCallback = std::function; + +void clear_registered_instances(void* ptr); + +TORCH_PYTHON_API IValue toIValue( + py::handle obj, + const TypePtr& type, + std::optional N = std::nullopt); + +TORCH_PYTHON_API py::object toPyObject(IValue ivalue); + +// Hack to overload the behavior of toIValue to accept Python +// numbers in places where a Tensor is expected +// See also torch::should_allow_numbers_as_tensors +class ToIValueAllowNumbersAsTensors { + bool old_; + + public: + ToIValueAllowNumbersAsTensors(bool enable); + ~ToIValueAllowNumbersAsTensors(); +}; + +// Wrap Python function to guard deref +// NB: Need VISIBILITY_HIDDEN for silencing compiler error, +// 'torch::jit::PythonFunctionGuard' declared with greater visibility than the +// type of its field 'torch::jit::PythonFunctionGuard::func_' +struct VISIBILITY_HIDDEN PythonFunctionGuard { + explicit PythonFunctionGuard(py::function func) : func_(std::move(func)) {} + + ~PythonFunctionGuard() { + pybind11::gil_scoped_acquire ag; + func_.dec_ref(); + // explicitly setting PyObject* to nullptr to prevent py::object's dtor to + // decref on the PyObject again. + // See Note [Destructing py::object] in python_ivalue.h + func_.ptr() = nullptr; + } + + py::function func_; +}; + +// The PythonFutureWrapper for ivalue::Future +// +// NB: VISIBILITY_HIDDEN is for silencing compiling error, +// "error: 'torch::jit::PythonFutureWrapper' declared with greater visibility +// than the type of its field 'torch::jit::PythonFutureWrapper::unwrap_func' +// [-Werror=attributes]" +// +// NB: inherit from enable_shared_from_this because then(py::function) needs to +// get a shared_ptr from this pointer. +struct VISIBILITY_HIDDEN PythonFutureWrapper + : std::enable_shared_from_this { + using UnwrapFunc = std::function; + + explicit PythonFutureWrapper( + c10::intrusive_ptr fut, + std::optional unwrap_func = std::nullopt) + : fut(std::move(fut)), unwrap_func(std::move(unwrap_func)) {} + + explicit PythonFutureWrapper(const PythonFutureWrapper&) = delete; + PythonFutureWrapper& operator=(const PythonFutureWrapper&) = delete; + + bool done() { + return fut->completed(); + } + + py::object value() { + // acquiring GIL as toPyObject creates new py::object + // without grabbing the GIL. + py::gil_scoped_acquire acquire; + py::object py_obj = toPyObject(fut->value()); + // unwrap_func is a general compositional function that takes in a + // py::object and executes some python function. It is currently mostly used + // to throw python exceptions. + if (unwrap_func) { + (*unwrap_func)(py_obj); + } + return py_obj; + } + + py::object wait() { + fut->wait(); + if (jit::tracer::isTracing()) { + auto graph = jit::tracer::getTracingState()->graph; + + Value* fut_val = jit::tracer::getValueTrace(fut); + auto output = graph->insert(aten::wait, {fut_val}); + jit::tracer::setValueTrace(fut->value(), output); + } + return value(); + } + + // The py::function cb arg must take a std::shared_ptr + // (i.e., torch._C.Future) as the only argument. If the type mismatches, an + // error will be thrown when waiting for the value of this returned Future. + std::shared_ptr then(py::function cb) { + // We need this an additional layer of wrapper here to guard the + // destruction of the py::function object. Because, the + // Future owns a reference to the py::function in its callback + // vector, but Future does not acquire GIL on destruction. + auto pf = std::make_shared(std::move(cb)); + + return std::make_shared(fut->then( + // Capture a copy of the ivalue::Future instead of the `this` pointer + // because the PythonFutureWrapper object could have been deleted + // when the callbacks are fired. For example, RPC only captures the + // ivalue::Future instead of PythonFutureWrapper in JitFuture's + // callback functions. Hence, if user code does not hold a reference to + // this PythonFutureWrapper object, there is no guarantee that the + // PythonFutureWrapper is still valid when running the callback. + [pyFut(this->getPtr()), + pf(std::move(pf))](c10::ivalue::Future& /* unused */) -> IValue { + try { + pybind11::gil_scoped_acquire ag; + return toIValue(pf->func_(pyFut), PyObjectType::get()); + } catch (py::error_already_set& e) { + auto err = std::runtime_error(c10::str( + "Got the following error when running the callback: ", + e.what())); + { + pybind11::gil_scoped_acquire ag; + // Release ownership on py::objects and also restore Python + // Error Indicator. + e.restore(); + // Clear the Python Error Indicator as we has recorded the + // exception in the response message. + PyErr_Clear(); + } + + throw std::runtime_error(err); + } + }, + PyObjectType::get())); + } + + void add_done_callback(py::function cb) { + auto pf = std::make_shared(std::move(cb)); + // NOLINTNEXTLINE(modernize-avoid-bind) + fut->addCallback(std::bind( + [pyFut(this->getPtr())]( + const std::shared_ptr& pf) { + try { + pybind11::gil_scoped_acquire ag; + pf->func_(pyFut); + } catch (py::error_already_set& e) { + { + pybind11::gil_scoped_acquire ag; + // Release ownership on py::objects and also restore Python + // Error Indicator. + e.restore(); + // Clear the Python Error Indicator as we has recorded the + // exception in the response message. + PyErr_Clear(); + } + // Log and ignore exceptions raised through the callback + LOG(ERROR) << "Got the following error when running the callback: " + << e.what(); + + } catch (const std::exception& e) { + // Log and ignore exceptions raised through the callback + LOG(ERROR) << "Got the following error when running the callback: " + << e.what(); + } + }, + std::move(pf))); + } + + void markCompleted(const py::object& pyValue) { + DCHECK(PyGILState_Check()); + IValue value = toIValue(pyValue, PyObjectType::get()); + + py::gil_scoped_release release; + fut->markCompleted(std::move(value)); + } + + c10::intrusive_ptr fut; + // unwrap_func works like a callback for the value returned by + // PythonFutureWrapper::wait(). + std::optional unwrap_func; + + private: + std::shared_ptr getPtr() { + return shared_from_this(); + } +}; + +// The PythonAwaitWrapper for ivalue::Await +// +// Expresses delayed function execution with Lazy semantic. +// i.e. Await[W] in eager mode can be used as W. +// When the attribute of W type is requested, Await[W] will return the +// attribute of W, transparently calling wait() beforehand. +// No Lazy semantic for script, explicit wait(Await[W]) -> W must be called to +// convert to type W. +// +// The Await object takes shared ownership of specified function and the +// arguments. After first call for wait() it owns the result. Deliberately no +// type inference for eager mode. +struct VISIBILITY_HIDDEN PythonAwaitWrapper + : std::enable_shared_from_this { + explicit PythonAwaitWrapper(c10::intrusive_ptr aw) + : aw_(std::move(aw)) {} + explicit PythonAwaitWrapper(py::handle input) { + args_ = py::tuple(1u); + args_[0] = input; + auto type = PyObjectType::get(); + aw_ = c10::make_intrusive(type); + aw_->markCompleted(toIValue(input, type)); + } + + explicit PythonAwaitWrapper(py::function pf, py::tuple args) + : args_(std::move(args)) { + pyfg_ = std::make_shared(std::move(pf)); + + std::function f = [fg(pyfg_), &args(args_)]() { + pybind11::gil_scoped_acquire ag; + return toIValue(fg->func_(*args), PyObjectType::get()); + }; + aw_ = c10::make_intrusive( + PyObjectType::get(), std::move(f)); + } + + explicit PythonAwaitWrapper(const PythonAwaitWrapper&) = delete; + PythonAwaitWrapper& operator=(const PythonAwaitWrapper&) = delete; + + py::object wait() { + py::gil_scoped_acquire acquire; + return toPyObject(aw_->wait()); + } + + // Nowait semantic means trivial case when Await is constructed from the + // result + bool is_nowait() { + return pyfg_ == nullptr; + } + + const py::function fn() { + TORCH_CHECK( + pyfg_, "Await constructed as awaitable_nowait does not have fn"); + return pyfg_->func_; + } + + const py::tuple args() { + return args_; + } + + TypePtr type() { + return aw_->type(); + } + + c10::intrusive_ptr aw_; + std::shared_ptr pyfg_; + py::tuple args_; + + private: + std::shared_ptr getPtr() { + return shared_from_this(); + } +}; + +// error reporting: when reporting user-caused errors, these functions should +// not use AT_ERROR macros, since these macros add stack trace information +// that is confusing to display to the end user since it always reports +// locations in libtorch code rather than user code. + +inline std::shared_ptr get_python_cu() { + return py::module::import("torch.jit._state") + .attr("_python_cu") + .cast>(); +} + +struct TypedIValue : public std::pair { + using pair::pair; + + IValue& ivalue() { + return this->first; + } + TypePtr& type() { + return this->second; + } +}; + +inline TypedIValue toDictKeyIValue(py::handle key) { + if (py::isinstance(key)) { + return TypedIValue( + ConstantString::create(py::cast(key)), StringType::get()); + } else if (py::isinstance(key)) { + return TypedIValue(py::cast(key), IntType::get()); + } else if (py::isinstance(key)) { + return TypedIValue(py::cast(key), FloatType::get()); + } else { + AT_ERROR("Dictionary inputs may only have string, int, or float keys"); + } +} + +inline std::optional unifyOrInitializeType( + const TypePtr& accum, + const TypePtr& unify) { + if (!accum) { + return unify; + } + return unifyTypes(accum, unify); +} + +using InferredType = c10::InferredType; + +InferredType tryToInferContainerType(py::handle input, bool primitiveTypeOnly); + +// Try to infer the type of a Python object +// The type cannot be inferred if: +// input is an empty container (list, dict) +// input is an list with element types that cannot be unified +// input is an dict with key or value types that cannot be unified +inline InferredType tryToInferType(py::handle input) { + // Try tensor types + if (THPVariable_Check(input.ptr())) { + return InferredType(TensorType::get()); + } + + if (input.is_none()) { + return InferredType(NoneType::get()); + } + + if (py::isinstance(input)) { + auto fn = py::cast(input).function_; + return InferredType(FunctionType::create(fn)); + } + + // Try basic types first + if (py::isinstance(input)) { + return InferredType(BoolType::get()); + // NOLINTNEXTLINE(bugprone-branch-clone) + } else if (py::isinstance(input)) { + return InferredType(IntType::get()); + } else if (py::isinstance(input)) { + return InferredType(FloatType::get()); + } else if (PyComplex_CheckExact(input.ptr())) { + return InferredType(ComplexType::get()); + } else if (py::isinstance(input)) { + return InferredType(StringType::get()); + } else if (THPLayout_Check(input.ptr())) { + return InferredType(IntType::get()); + } else if (THPDevice_Check(input.ptr())) { + return InferredType(DeviceObjType::get()); + } else if (THPGenerator_Check(input.ptr())) { + return InferredType(GeneratorType::get()); + } else if (THPStream_Check(input.ptr())) { + return InferredType(StreamObjType::get()); + } else if (THPDtype_Check(input.ptr())) { + return InferredType(IntType::get()); + } else if (THPQScheme_Check(input.ptr())) { + return InferredType(IntType::get()); + } else if (THPLayout_Check(input.ptr())) { + return InferredType(IntType::get()); + } + + auto enum_type = py::module::import("enum").attr("Enum"); + py::bool_ isEnumValue = py::isinstance(input, enum_type); + if (py::cast(isEnumValue)) { + auto enum_class = input.attr("__class__"); + auto enum_type = py::cast( + py::module::import("torch.jit.annotations") + .attr("try_ann_to_type")(enum_class, SourceRange())); + return InferredType(std::move(enum_type)); + } + + py::bool_ isClass = + py::module::import("inspect").attr("isclass")(input.get_type()); + if (py::cast(isClass)) { + // Assume that the class is compiled already or will compile. Invalidate + // this later if needed. + bool class_compiled = true; + + // Check if the type is already compiled. + py::object existing_ty = py::module::import("torch.jit._state") + .attr("_get_script_class")(input.get_type()); + + if (existing_ty.is_none()) { + // If not, try to compile it. + py::bool_ can_compile = py::module::import("torch._jit_internal") + .attr("can_compile_class")(input.get_type()); + + if (py::cast(can_compile)) { + // Try to compile the class. This is wrapped in a try-catch because + // compilation of class types can raise an Exception and in that case, + // we want to defer to other attempts at type inference below rather + // than fail compilation altogether. + try { + py::module::import("torch.jit._script") + .attr("_recursive_compile_class")( + input.get_type(), SourceRange()); + } catch (...) { + // Invalidate the assumption that the class compiled so that we don't + // look up and return its JIT type as the type for the input. + class_compiled = false; + } + } + } + + // If the class compiled successfully, look up the existing JIT type by + // qualified name and return it. + if (class_compiled) { + auto script_class = py::module::import("torch.jit._state") + .attr("_get_script_class")(input.get_type()); + + if (!script_class.is_none()) { + auto class_type = py::cast(script_class); + + if (class_type && !class_type->is_module()) { + return InferredType(std::move(class_type)); + } + } + } + } + + if (py::isinstance(input)) { + auto object = py::cast(input); + return InferredType(object.type()); +#ifdef USE_RPC + } else if (py::isinstance(input)) { + auto rref_ivalue = input.cast().toIValue(); + return InferredType(rref_ivalue.type()); +#endif + } + + auto await_type = py::module::import("torch._awaits").attr("_Await"); + py::bool_ is_await = py::isinstance(input, await_type); + if (py::cast(is_await)) { + auto awptr = input.cast>(); + return InferredType(AwaitType::create(awptr->aw_->elementType())); + } + + if (as_module(py::cast(input))) { + return InferredType("Cannot infer type of ScriptModule"); + } + + auto module_type = py::module::import("torch.nn").attr("Module"); + py::bool_ is_module = py::isinstance(input, module_type); + if (py::cast(is_module)) { + return InferredType("Cannot infer concrete type of torch.nn.Module"); + } + + // Try container types + return tryToInferContainerType(input, false); +} + +// This function is similar to tryToInferType, but it only tries to infer +// primitive types (int, float, bool, complex) or nested container of primitive +// types. +inline InferredType tryToInferPrimitiveType(py::handle input) { + if (input.is_none()) { + return InferredType(NoneType::get()); + } + + // Only primitive data type + if (py::isinstance(input)) { + return InferredType(BoolType::get()); + // NOLINTNEXTLINE(bugprone-branch-clone) + } else if (py::isinstance(input)) { + return InferredType(IntType::get()); + } else if (py::isinstance(input)) { + return InferredType(FloatType::get()); + } else if (PyComplex_CheckExact(input.ptr())) { + return InferredType(ComplexType::get()); + } + + // Try container types + return tryToInferContainerType(input, true); +} + +inline InferredType tryToInferContainerType( + py::handle input, + bool primitiveTypeOnly = false) { + if (six::isTuple(input)) { + py::tuple tuple = py::cast(input); + std::vector element_types; + element_types.reserve(tuple.size()); + + for (py::handle elem : tuple) { + auto type_match = primitiveTypeOnly ? tryToInferPrimitiveType(elem) + : tryToInferType(elem); + if (type_match.success()) { + element_types.push_back(type_match.type()); + } else { + // Forward error message along + return type_match.reason(); + } + } + return InferredType(TupleType::create(std::move(element_types))); + } else if (PyDict_Check(input.ptr())) { + // Check to make sure we can generate useful input/output types + auto dict = py::cast(input); + size_t len = py::len(dict); + if (!len) { + return InferredType("Dictionary inputs must have entries"); + } + + TypePtr key_type = nullptr; + TypePtr value_type = nullptr; + + for (auto entry : dict) { + // Try to infer the key type and unify it with the existing one + auto entry_key_type_match = primitiveTypeOnly + ? tryToInferPrimitiveType(entry.first) + : tryToInferType(entry.first); + if (!entry_key_type_match.success()) { + return entry_key_type_match.reason(); + } + auto unified_key = + unifyOrInitializeType(key_type, entry_key_type_match.type()); + if (!unified_key) { + return InferredType(c10::str( + "Dictionary inputs to traced functions must have consistent type. Found ", + key_type->repr_str(), + " and ", + (entry_key_type_match.type())->repr_str())); + } + + // Try to infer the value type and unify it with the existing one + auto entry_value_type_match = primitiveTypeOnly + ? tryToInferPrimitiveType(entry.second) + : tryToInferType(entry.second); + if (!entry_value_type_match.success()) { + return entry_value_type_match.reason(); + } + auto unified_value = + unifyOrInitializeType(value_type, entry_value_type_match.type()); + if (!unified_value) { + return InferredType(c10::str( + "Dictionary inputs to traced functions must have consistent type. Found ", + value_type->repr_str(), + " and ", + (entry_value_type_match.type())->repr_str())); + } + + key_type = *unified_key; + value_type = *unified_value; + } + return InferredType( + DictType::create(std::move(key_type), std::move(value_type))); + } else if (PyList_Check(input.ptr())) { + auto list = py::cast(input); + size_t len = py::len(list); + if (!len) { + return InferredType("List trace inputs must have elements"); + } + + TypePtr element_type = nullptr; + for (auto elem : list) { + auto element_type_match = primitiveTypeOnly + ? tryToInferPrimitiveType(elem) + : tryToInferType(elem); + if (!element_type_match.success()) { + return InferredType(c10::str( + "Could not infer type of list element: ", + element_type_match.reason())); + } + auto unified_type = + unifyOrInitializeType(element_type, element_type_match.type()); + if (!unified_type) { + return InferredType(c10::str( + "List inputs to traced functions must have consistent element type. Found ", + element_type->repr_str(), + " and ", + (element_type_match.type())->repr_str())); + } + element_type = *unified_type; + } + return InferredType(ListType::create(element_type)); + } else { + if (primitiveTypeOnly) { + return InferredType(c10::str( + "Only tuple, list, or dict (possibly nested) of primitive types (bool, float, int, complex)", + "are supported ", + "as inputs or outputs of traced functions", + ", but instead got value of type ", + py::str(input.get_type().attr("__name__")), + ".")); + } else { + // TODO: this message is not correct anymore, since this InferredType is + // used from a bunch of circumstances unrelated to tracing. We can re-use + // this instead of the attribute_failure stuff in concreteType + return InferredType(c10::str( + "Only tensors and (possibly nested) tuples of tensors, lists, or dicts", + "are supported ", + "as inputs or outputs of traced functions", + ", but instead got value of type ", + py::str(input.get_type().attr("__name__")), + ".")); + } + } +} + +inline bool isTraceableType(const TypePtr& type) { + if (type->isSubtypeOf(*TensorType::get())) { + return true; + } + + if (auto list_type = type->cast()) { + return isTraceableType(list_type->getElementType()); + } + + if (auto tuple_type = type->cast()) { + return std::all_of( + tuple_type->elements().begin(), + tuple_type->elements().end(), + [](const TypePtr& element_type) { + return isTraceableType(element_type); + }); + } + + if (auto dict_type = type->cast()) { + return isTraceableType(dict_type->getValueType()); + } + + return false; +} + +inline IValue toTypeInferredIValue(py::handle input) { + auto match = tryToInferType(input); + if (!match.success()) { + auto object = py::cast(input); + if (auto mod = as_module(object)) { + // if obj is already a ScriptModule, just return its ivalue + auto ptr = mod.value()._ivalue(); + // explict copy semantics for strong ownership of the resource. + return c10::intrusive_ptr::reclaim_copy( + ptr.release()); + } + + // Check if the obj is a ScriptObject. + if (auto script_obj = as_object(object)) { + auto ptr = script_obj.value()._ivalue(); + return c10::intrusive_ptr::reclaim_copy( + ptr.release()); + } + AT_ERROR( + "Tracer cannot infer type of ", py::str(input), "\n:", match.reason()); + } + return toIValue(input, match.type()); +} + +inline Stack toTraceableStack(const py::tuple& inputs) { + auto info = toTypeInferredIValue(inputs); + TORCH_CHECK( + isTraceableType(info.type()), + "Type '", + info.type()->repr_str(), + "' cannot be traced. Only Tensors and (possibly nested) Lists, Dicts, and" + " Tuples of Tensors can be traced"); + return info.toTupleRef().elements().vec(); +} + +// Serialize the python dictionary into a traceable stack. +inline Stack toTraceableStack(const py::dict& inputs) { + Stack res; + for (auto it = inputs.begin(); it != inputs.end(); it++) { + if (THPVariable_Check(it->second.ptr())) { + res.push_back(toIValue(it->second, tryToInferType(it->second).type())); + } + } + return res; +} + +inline IValue createGenericList(py::handle obj, const TypePtr& elem_type) { + auto elems = c10::impl::GenericList(elem_type); + for (auto elem : obj) { + elems.push_back(toIValue(elem, elem_type)); + } + return IValue(elems); +} + +inline IValue createGenericDict( + const py::dict& obj, + const TypePtr& key_type, + const TypePtr& value_type) { + c10::impl::GenericDict elems(key_type, value_type); + elems.reserve(py::len(obj)); + for (auto& entry : obj) { + elems.insert( + toIValue(entry.first, key_type), toIValue(entry.second, value_type)); + } + return IValue(elems); +} + +template +inline void guardAgainstNamedTensor(const T& var) { + TORCH_CHECK( + !var.has_names(), + "NYI: Named tensors are currently unsupported in TorchScript. As a " + "workaround please drop names via `tensor = tensor.rename(None)`."); +} + +// Extract custom class registered with torchbind +template +c10::intrusive_ptr toCustomClass(py::handle obj) { + static_assert( + std::is_base_of_v, "T is not a CustomClass"); + const auto& type = c10::getCustomClassType>(); + c10::IValue ivalue = toIValue(obj, type); + return std::move(ivalue).toCustomClass(); +} + +// Small wrapper around getting the type name string from Python to make +// types easier to interpret, e.g. give the structural type for a NamedTuple +inline std::string friendlyTypeName(py::handle obj) { + if (py::isinstance(obj) && py::hasattr(obj, "_fields")) { + auto field_names = + py::cast>(py::getattr(obj, "_fields")); + std::stringstream ss; + ss << py::str(obj.get_type().attr("__name__")); + ss << " (aka NamedTuple("; + bool first = true; + for (auto& field_name : field_names) { + if (!first) { + ss << ", "; + } + ss << field_name; + first = false; + } + ss << "))"; + return ss.str(); + } else { + return py::str(obj.get_type().attr("__name__")); + } +} + +// Thrown when trying to create a schema for a list of python +// arguments that cannot be converted. +// Can be caught by the caller to attempt to use other schema +// when there is an overloaded operator. +struct schema_match_error : public std::runtime_error { + using std::runtime_error::runtime_error; +}; + +inline IValue argumentToIValue( + const FunctionSchema& schema, + size_t argumentPosition, + py::handle object) { + const auto& argument = schema.arguments().at(argumentPosition); + try { + return toIValue(object, argument.real_type(), argument.N()); + } catch (const py::cast_error& error) { + throw schema_match_error(c10::str( + schema.formatTypeMismatchMsg( + argument, + friendlyTypeName(object), + argumentPosition, + py::repr(object)), + "\nCast error details: ", + error.what())); + } catch (const py::error_already_set& error) { + throw schema_match_error(c10::str( + schema.formatTypeMismatchMsg( + argument, + friendlyTypeName(object), + argumentPosition, + py::repr(object)), + "\n Python error details: ", + error.what())); + } +} + +inline IValue returnToIValue(const TypePtr& type, py::handle object) { + try { + return toIValue(object, type); + } catch (const py::cast_error& error) { + throw std::runtime_error(c10::str( + " expected value of type ", + type->str(), + " for return value but instead got value of type ", + py::str(object.get_type().attr("__name__")), + ".", + "\nValue: ", + py::repr(object), + "\nCast error details: ", + error.what())); + } +} + +inline py::object getScriptedClassOrError(const c10::NamedTypePtr& classType) { + auto py_class = + py::module::import("torch.jit._state") + .attr("_get_python_class")(classType->name()->qualifiedName()); + if (py_class.is_none()) { + std::stringstream err; + err << "Unknown reference to ScriptClass "; + err << classType->name()->qualifiedName(); + err << ". (Did you forget to import it?)"; + throw std::runtime_error(err.str()); + } + return py_class; +} + +struct VISIBILITY_HIDDEN tuple_slice { + /*implicit*/ tuple_slice(py::tuple tup_) + : tup(std::move(tup_)), b(0), e(tup.size()) {} + tuple_slice(py::tuple tup_, int64_t b_) + : tup(std::move(tup_)), b(b_), e(tup.size()) {} + tuple_slice(py::tuple tup_, int64_t b_, int64_t e_) + : tup(std::move(tup_)), b(b_), e(e_) {} + py::detail::tuple_iterator begin() const { + return {tup, static_cast(b)}; + } + py::detail::tuple_iterator end() const { + return {tup, static_cast(e)}; + } + size_t size() const { + return e - b; + } + py::detail::tuple_accessor operator[](size_t index) const { + return {tup, static_cast(b + index)}; + } + + private: + py::tuple tup; + int64_t b; + int64_t e; +}; + +inline bool validateFakeScriptObjectSchema( + const c10::FunctionSchema& schema, + size_t argumentPosition, + py::handle object) { + auto argument = schema.arguments().at(argumentPosition); + auto class_type = argument.real_type()->expect(); + auto fake_class_registry = + py::module::import("torch._library.fake_class_registry"); + auto fake_class = fake_class_registry.attr("find_fake_class")( + class_type->name().value().qualifiedName()); + if (!py::isinstance(object.attr("wrapped_obj"), fake_class)) { + throw schema_match_error(c10::str( + schema.formatTypeMismatchMsg( + argument, + friendlyTypeName(object), + argumentPosition, + py::repr(object.attr("wrapped_obj"))), + "\nCast error details: ", + argument.name(), + " is expected to be a FakeScriptObject of ", + class_type->name().value().qualifiedName())); + } + return true; +} + +inline bool matchSchemaAllowFakeScriptObject( + const FunctionSchema& schema, + const tuple_slice& args, + const py::kwargs& kwargs) { + size_t all_arguments = args.size() + kwargs.size(); + if (all_arguments > schema.arguments().size()) { + throw schema_match_error(c10::str( + schema.name(), + "() expected at most ", + schema.arguments().size(), + " argument(s) but received ", + all_arguments, + " argument(s). Declaration: ", + schema)); + } + + int64_t arg_idx = 0; + auto fake_class_registry = + py::module::import("torch._library.fake_class_registry"); + + // First push all positional args. + for (const auto& arg : args) { + // ...but refuse to do it if the schema says that this was supposed + // to be keyword only + if (schema.arguments()[arg_idx].kwarg_only()) { + throw schema_match_error(c10::str( + schema.name(), + "() takes ", + arg_idx, + " positional argument(s) but ", + args.size(), + " was/were given. Declaration: ", + schema)); + } + // Use the type information from the schema to convert the PyObject. + const auto& argument = schema.arguments().at(arg_idx); + if (argument.real_type()->kind() == TypeKind::ClassType && + py::isinstance(arg, fake_class_registry.attr("FakeScriptObject"))) { + validateFakeScriptObjectSchema(schema, arg_idx, arg); + } else { + argumentToIValue(schema, arg_idx, arg); + } + + arg_idx++; + } + + // Now for every remaining non-positional argument in the schema, look for it + // in the kwargs dict and push it if found, or use its default value if it + // has one. + size_t consumed_kwargs = 0; + for (size_t i = arg_idx; i < schema.arguments().size(); ++i) { + const auto& arg = schema.arguments()[i]; + if (kwargs.contains(arg.name().c_str())) { + auto cur_kwarg = kwargs[arg.name().c_str()]; + if (arg.real_type()->kind() == TypeKind::ClassType && + py::isinstance( + cur_kwarg, fake_class_registry.attr("FakeScriptObject"))) { + validateFakeScriptObjectSchema(schema, i, cur_kwarg); + } else { + argumentToIValue(schema, i, cur_kwarg); + } + consumed_kwargs += 1; + } else if (arg.default_value()) { + continue; + } else { + throw schema_match_error(c10::str( + schema.name(), + "() is missing value for argument '", + arg.name(), + "'. Declaration: ", + schema)); + } + } + + if (consumed_kwargs != kwargs.size()) { + std::vector names; + for (const auto& kwarg : kwargs) { + names.emplace_back(py::cast(kwarg.first)); + } + throw schema_match_error(schema.findErrorInKwargs(names)); + } + + return true; +} + +inline Stack createStackForSchema( + const FunctionSchema& schema, + const tuple_slice& args, + const py::kwargs& kwargs, + std::optional self) { + size_t all_arguments = (self ? 1 : 0) + args.size() + kwargs.size(); + if (all_arguments > schema.arguments().size()) { + throw schema_match_error(c10::str( + schema.name(), + "() expected at most ", + schema.arguments().size(), + " argument(s) but received ", + all_arguments, + " argument(s). Declaration: ", + schema)); + } + Stack stack; + stack.reserve(schema.arguments().size()); + + int64_t arg_idx = 0; + if (self) { + push(stack, std::move(*self)); + arg_idx++; + } + // First push all positional args. + for (const auto& arg : args) { + // ...but refuse to do it if the schema says that this was supposed + // to be keyword only + if (schema.arguments()[arg_idx].kwarg_only()) { + throw schema_match_error(c10::str( + schema.name(), + "() takes ", + arg_idx, + " positional argument(s) but ", + self ? 1 + args.size() : args.size(), + " was/were given. Declaration: ", + schema)); + } + // Use the type information from the schema to convert the PyObject. + push(stack, argumentToIValue(schema, stack.size(), arg)); + arg_idx++; + } + + // Now for every remaining non-positional argument in the schema, look for it + // in the kwargs dict and push it if found, or use its default value if it + // has one. + size_t consumed_kwargs = 0; + for (size_t i = stack.size(); i < schema.arguments().size(); ++i) { + const auto& arg = schema.arguments()[i]; + if (kwargs.contains(arg.name().c_str())) { + push(stack, argumentToIValue(schema, i, kwargs[arg.name().c_str()])); + consumed_kwargs += 1; + } else if (arg.default_value()) { + push(stack, *arg.default_value()); + } else { + throw schema_match_error(c10::str( + schema.name(), + "() is missing value for argument '", + arg.name(), + "'. Declaration: ", + schema)); + } + } + + if (consumed_kwargs != kwargs.size()) { + std::vector names; + for (const auto& kwarg : kwargs) { + names.emplace_back(py::cast(kwarg.first)); + } + throw schema_match_error(schema.findErrorInKwargs(names)); + } + + return stack; +} + +inline py::object createPyObjectForStack(Stack&& stack) { + if (stack.empty()) { + return py::none(); + } + + // Return a simple value and not a single-element tuple if there is only one + // return value. + if (stack.size() == 1) { + return toPyObject(std::move(stack[0])); + } + + // If there is more than one return value, pop them into a py::tuple. + py::tuple return_values(stack.size()); + for (const auto ret : c10::irange(return_values.size())) { + return_values[ret] = toPyObject(std::move(stack[ret])); + } + + return std::move(return_values); +} + +// TODO: Remove once we clean up the GraphExecutor usage. +inline Stack evilDeprecatedBadCreateStackDoNotUse( + const py::tuple& tuple, + at::ArrayRef inputs, + size_t reserve_extra_space = 0) { + if (tuple.size() != inputs.size()) { + AT_ERROR( + "expected " + std::to_string(inputs.size()) + " inputs, but got " + + std::to_string(tuple.size())); + } + Stack result; + result.reserve(tuple.size() + reserve_extra_space); + for (const auto i : c10::irange(inputs.size())) { + result.push_back(toIValue(std::move(tuple[i]), inputs[i]->type())); + } + return result; +} + +// Run `callee`, potentially inserting a CallFunction/CallMethod node into the +// tracing graph. +inline py::object runAndInsertCall( + Function& callee, + const tuple_slice& args, + const py::kwargs& kwargs, + std::optional self, + // Lambda that tells this function how to insert `callee` into the graph if + // we're tracing. + const std::function& + callInserter) { + auto stack = + createStackForSchema(callee.getSchema(), args, kwargs, std::move(self)); + const auto& tracing_state = tracer::getTracingState(); + if (!tracing_state) { + pybind11::gil_scoped_release no_gil_guard; + // If we're not tracing, just run the callee as normal. + callee.run(stack); + } else { + // If we are tracing, insert the appropriate CallFunction or CallMethod node + // and then run the callee with tracing disabled. + + // Get the graph `Value`s that represent the input IValues + auto inputs = last(stack, callee.num_inputs()); + auto input_values = + fmap(inputs, [](const IValue& v) { return tracer::getValueTrace(v); }); + TORCH_INTERNAL_ASSERT(callee.getSchema().returns().size() == 1) + auto return_type = callee.getSchema().returns().at(0).type(); + auto graph = tracing_state->graph; + std::vector named_values; + named_values.reserve(input_values.size()); + for (Value* v : input_values) { + named_values.emplace_back(v); + } + + // Add a call node. + MatchedSchema match = matchSchema( + callee.getSchema(), + tracer::getPythonInterpreterSourceRange(), + *graph, + named_values, + {}); + auto output_value = callInserter(*graph, match); + + // Actually run the callee. Pause the tracer so that we don't double-add the + // callee nodes. + { + pybind11::gil_scoped_release no_gil_guard; + ResourceGuard guard(tracer::pauseTracing()); + callee.run(stack); + } + + // Associate the output IValues with the output `Value`s in the graph + tracer::setValueTrace(stack.back(), output_value); + } + + TORCH_CHECK( + !stack.empty(), + "Expected values in the stack after execution but found none"); + return toPyObject(std::move(stack.back())); +} + +inline std::optional maybeTorchFunctionDispatch( + const py::object& callee, + const tuple_slice& args_no_self, + const py::kwargs& kwargs, + const c10::QualifiedName& qualname) { + std::vector args_vec; + for (const auto& arg : args_no_self) { + args_vec.push_back(arg); + } + py::tuple args = py::cast(args_vec); + + // Handle __torch_function__ dispatch + std::vector overloaded_args; + size_t total_arg_num = args.size() + kwargs.size(); + for (const auto& arg : args) { + is_tensor_and_append_overloaded(arg.ptr(), &overloaded_args); + is_tensor_list_and_append_overloaded( + arg.ptr(), + &overloaded_args, + static_cast(total_arg_num), + false /* throw_error */); + } + // NB: for kwargs, we cannot guarantee the order of appending + // is the same as the argument order in operator's schema. + // This is suboptimal, but should be fine. Later when we have + // better schema matching and argument parsing, we could + // match the operator in `operations` first, then the order will + // be guaranteed. + for (auto item : kwargs) { + is_tensor_and_append_overloaded(item.second.ptr(), &overloaded_args); + is_tensor_list_and_append_overloaded( + item.second.ptr(), + &overloaded_args, + total_arg_num, + false /* throw_error */); + } + if (!overloaded_args.empty()) { + return pybind11::reinterpret_steal( + handle_torch_function_no_python_arg_parser( + /*overloaded_args=*/overloaded_args, + /*args=*/args.ptr(), + /*kwargs=*/kwargs.ptr(), + /*func_name=*/qualname.name().c_str(), + /*torch_api_function=*/callee.ptr(), + /*module_name=*/qualname.prefix().c_str())); + } + + return std::nullopt; +} + +inline py::object invokeScriptFunctionFromPython( + Function& callee, + const tuple_slice& args, + const py::kwargs& kwargs) { + // TODO: we could add __torch_function__ dispatch here but I don't know + // the implications of doing so + + return runAndInsertCall( + callee, + args, + kwargs, + /*self=*/std::nullopt, + [&](Graph& graph, const MatchedSchema& match) { + return graph.insertFunctionCall(&callee, match); + }); +} + +inline py::object invokeScriptMethodFromPython( + Method& callee, + const tuple_slice& args, + const py::kwargs& kwargs) { + auto self = callee.owner()._ivalue(); + + if (auto torch_fn_result = maybeTorchFunctionDispatch( + py::cast(callee), args, kwargs, callee.name())) { + return *torch_fn_result; + } + + return runAndInsertCall( + callee.function(), + args, + kwargs, + self, + [&](Graph& graph, const MatchedSchema& match) { + return graph.insertMethodCall(callee.name(), match); + }); +} + +TORCH_PYTHON_API std::pair, Stack> getOpWithStack( + const std::vector>& operations, + const py::args& args, + const py::kwargs& kwargs); + +TORCH_PYTHON_API py::object invokeOperatorFromPython( + const std::vector>& operations, + const py::args& args, + const py::kwargs& kwargs, + std::optional dk = std::nullopt); + +TORCH_PYTHON_API std::optional _maybe_handle_torch_function( + const std::string& ns, + const std::string& method_name, + const std::string& overload_name, + bool is_overload, + const py::args& args, + const py::kwargs& kwargs); + +TORCH_PYTHON_API bool checkSchemaAllowFakeScriptObject( + const FunctionSchema& schema, + const py::args& args, + const py::kwargs& kwargs); + +TORCH_PYTHON_API py::object _get_operation_for_overload_or_packet( + const std::vector>& operations, + Symbol symbol, + const py::args& args, + const py::kwargs& kwargs, + bool is_overload, + std::optional dk = std::nullopt); + +} // namespace torch::jit diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/python/python_tracer.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/python/python_tracer.h new file mode 100644 index 0000000000000000000000000000000000000000..55c36f7a88ab05d58ccedaf26f8cd2958647f765 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/python/python_tracer.h @@ -0,0 +1,45 @@ +#pragma once + +#include +#include +#include +#include + +#include +#include + +namespace torch::jit { + +struct Module; + +namespace tracer { +void initPythonTracerBindings(PyObject* module); + +SourceRange getPythonInterpreterSourceRange(); + +Node* preRecordPythonTrace( + THPObjectPtr pyobj, + const std::string& arg_types, + at::ArrayRef inputs, + std::vector scalar_args); + +std::pair, Stack> createGraphByTracingWithDict( + const py::function& func, + const py::dict& inputs_dict, + const Stack& inputs, + const py::function& var_name_lookup_fn, + bool strict, + bool force_outplace, + Module* self = nullptr, + const std::vector& argument_names = {}); + +std::pair, Stack> createGraphByTracing( + const py::function& func, + Stack inputs, + const py::function& var_name_lookup_fn, + bool strict, + bool force_outplace, + Module* self = nullptr, + const std::vector& argument_names = {}); +} // namespace tracer +} // namespace torch::jit diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/python/python_tree_views.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/python/python_tree_views.h new file mode 100644 index 0000000000000000000000000000000000000000..796bf125defd824520dda38496aa09d71480252a --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/python/python_tree_views.h @@ -0,0 +1,9 @@ +#pragma once + +#include + +namespace torch::jit { + +void initTreeViewBindings(PyObject* module); + +} // namespace torch::jit diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/python/update_graph_executor_opt.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/python/update_graph_executor_opt.h new file mode 100644 index 0000000000000000000000000000000000000000..81cfd658f6ede87517a2edad395984293885ab76 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/python/update_graph_executor_opt.h @@ -0,0 +1,6 @@ +#pragma once +#include +namespace torch::jit { +TORCH_API void setGraphExecutorOptimize(bool o); +TORCH_API bool getGraphExecutorOptimize(); +} // namespace torch::jit diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/analysis.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/analysis.h new file mode 100644 index 0000000000000000000000000000000000000000..e6a2791023f8baca6bbc78cdb78272861bbc0321 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/analysis.h @@ -0,0 +1,398 @@ +#pragma once + +#include +#include +#include +#include + +#include + +namespace torch::jit::tensorexpr { +class HasRand : public IRVisitor { + public: + HasRand(StmtPtr stmt) : stmt_(std::move(stmt)) { + stmt_->accept(this); + } + + bool has_rand() const { + return has_rand_; + } + + private: + void visit(const IntrinsicsPtr& v) override { + if (v->op_type() == IntrinsicsOp::kRand) { + has_rand_ = true; + } else { + IRVisitor::visit(v); + } + } + StmtPtr stmt_; + bool has_rand_ = false; +}; + +template +class NodeFinder : public IRVisitor { + public: + void visit(const NodePtr& v) override { + nodes.push_back((NodePtr)v); + IRVisitor::visit(v); + } + + static std::vector> find(const StmtPtr& s) { + NodeFinder nf; + s->accept(&nf); + return nf.nodes; + } + + static std::vector> find(const ExprPtr& e) { + NodeFinder nf; + e->accept(&nf); + return nf.nodes; + } + + std::vector> nodes; +}; + +class VarFinder : public IRVisitor { + public: + void visit(const VarPtr& v) override { + vars_.insert(v); + IRVisitor::visit(v); + } + + static std::unordered_set find(const StmtPtr& s) { + VarFinder nf; + s->accept(&nf); + return nf.vars(); + } + + static std::unordered_set find(const ExprPtr& e) { + VarFinder nf; + e->accept(&nf); + return nf.vars(); + } + + const std::unordered_set& vars() { + return vars_; + } + + private: + std::unordered_set vars_; +}; + +class BufFinder : public IRVisitor { + public: + void visit(const BufPtr& v) override { + bufs_.insert(v); + IRVisitor::visit(v); + } + + static std::unordered_set find(const StmtPtr& s) { + BufFinder nf; + s->accept(&nf); + return nf.bufs(); + } + + static std::unordered_set find(const ExprPtr& e) { + BufFinder nf; + e->accept(&nf); + return nf.bufs(); + } + + const std::unordered_set& bufs() { + return bufs_; + } + + private: + std::unordered_set bufs_; +}; + +// Finds all kinds of write operations to the provided Buf. +class WritesToBuf : public IRVisitor { + public: + WritesToBuf(BufPtr target) : target_(std::move(target)) {} + + std::vector writes() { + return writes_; + } + + static std::vector find(const StmtPtr& s, BufPtr b) { + WritesToBuf finder(std::move(b)); + s->accept(&finder); + return finder.writes(); + } + + private: + void visit(const StorePtr& v) override { + if (v->buf() == target_) { + writes_.push_back(v); + } + } + + void visit(const AtomicAddPtr& v) override { + if (v->buf() == target_) { + writes_.push_back(v); + } + } + + BufPtr target_; + std::vector writes_; +}; + +class StmtsReadingBuf : public IRVisitor { + public: + StmtsReadingBuf(BufPtr target) : target_(std::move(target)) {} + + std::vector reads() { + return reads_; + } + + static std::vector find(const StmtPtr& s, BufPtr b) { + StmtsReadingBuf finder(std::move(b)); + s->accept(&finder); + return finder.reads(); + } + + private: + bool readsBuffer(const StmtPtr& s) { + auto loads = NodeFinder::find(s); + for (const auto& l : loads) { + if (l->buf() == target_) { + return true; + } + } + return false; + } + + void visit(const StorePtr& v) override { + if (readsBuffer(v)) { + reads_.push_back(v); + } + } + + void visit(const LetPtr& v) override { + if (readsBuffer(v)) { + reads_.push_back(v); + } + } + + void visit(const CondPtr& v) override { + if (readsBuffer(v)) { + reads_.push_back(v); + } + } + + void visit(const AtomicAddPtr& v) override { + if (readsBuffer(v)) { + reads_.push_back(v); + } + } + + BufPtr target_; + std::vector reads_; +}; + +class ExternalAllocBufFinder : public IRVisitor { + public: + void visit(const ExternalCallWithAllocPtr& v) override { + const auto& bufs_out = v->buf_out_args(); + bufs_.insert(bufs_out.begin(), bufs_out.end()); + IRVisitor::visit(v); + } + + static std::unordered_set find(const StmtPtr& s) { + ExternalAllocBufFinder f; + s->accept(&f); + return f.bufs(); + } + + static std::unordered_set find(const ExprPtr& e) { + ExternalAllocBufFinder f; + e->accept(&f); + return f.bufs(); + } + + const std::unordered_set& bufs() { + return bufs_; + } + + private: + std::unordered_set bufs_; +}; + +// Traverses the IR to determine if a particular Var is modified within it. +class ModifiesVarChecker : public IRVisitor { + public: + ModifiesVarChecker(VarPtr v) : var_(std::move(v)) {} + + static bool check(const StmtPtr& s, VarPtr v) { + ModifiesVarChecker checker(std::move(v)); + s->accept(&checker); + return checker.found(); + } + + bool found() { + return found_; + } + + private: + void visit(const StorePtr& v) override { + if (v->buf()->base_handle() == var_) { + found_ = true; + return; + } + IRVisitor::visit(v); + } + + void visit(const AtomicAddPtr& v) override { + if (v->buf()->base_handle() == var_) { + found_ = true; + return; + } + IRVisitor::visit(v); + } + + void visit(const LetPtr& v) override { + if (v->var() == var_) { + found_ = true; + return; + } + IRVisitor::visit(v); + } + + void visit(const ForPtr& v) override { + if (v->var() == var_) { + found_ = true; + return; + } + IRVisitor::visit(v); + } + + VarPtr var_; + bool found_{false}; +}; + +// Traverse the Block stmt to identify the live range of the specified buf. The +// live range, indicated by a pair of integers, specifies the first and last +// stmt in block stmts that access to the buf. +class BufLiveRange : public IRVisitor { + public: + BufLiveRange(BufPtr b) : buf_(std::move(b)) {} + + static std::tuple liveRange(const StmtPtr& s, BufPtr b) { + BlockPtr block = to(s); + // We Only analyze buffer live ranges for block stmts. + if (!block) { + return std::make_tuple(0, 0); + } + + BufLiveRange analyzer(std::move(b)); + block->accept(&analyzer); + return analyzer.getLiveRange(); + } + + private: + std::tuple getLiveRange() { + return std::make_tuple(begin_, end_); + } + + bool hasBufReads(const StmtPtr& s) { + auto loads1 = NodeFinder::find(s); + for (const auto& l : loads1) { + if (l->buf() == buf_) { + return true; + } + } + auto loads2 = NodeFinder::find(s); + for (const auto& l : loads2) { + for (const auto& lb : l->buf_args()) { + if (lb == buf_) { + return true; + } + } + } + auto loads3 = NodeFinder::find(s); + for (const auto& l : loads3) { + for (const auto& lb : l->buf_args()) { + if (lb == buf_) { + return true; + } + } + } + return false; + } + + bool hasBufWrites(const StmtPtr& s) { + auto writes1 = NodeFinder::find(s); + for (const auto& w : writes1) { + if (w->buf() == buf_) { + return true; + } + } + auto writes2 = NodeFinder::find(s); + for (const auto& w : writes2) { + if (w->buf() == buf_) { + return true; + } + } + auto writes3 = NodeFinder::find(s); + for (const auto& w : writes3) { + for (const auto& wb : w->buf_out_args()) { + if (wb == buf_) { + return true; + } + } + } + return false; + } + + void findAccAndUpdateLiveRange(const StmtPtr& s) { + bool has_reads = hasBufReads(s), has_writes = hasBufWrites(s); + if (has_reads || has_writes) { + if (begin_ == -1) { + begin_ = curr_index_; + }; + end_ = curr_index_; + } + } + + void visit(const BlockPtr& v) override { + for (const StmtPtr& s : *v) { + curr_index_ += 1; + findAccAndUpdateLiveRange(s); + } + } + + BufPtr buf_; + int32_t begin_ = -1; + int32_t end_ = -1; + int32_t curr_index_ = -1; +}; + +// A class that analyzes the given program relevant for Block backend +// It creates a map of multi dim buffers and their flat versions +class CreateBufferMap : public IRVisitor { + public: + const std::unordered_map& getBufferMap() const { + return map_input_to_tensor_bufs_; + } + + private: + void visit(const StorePtr& v) override { + auto load_node = to(v->value()); + if (load_node) { + auto t_buf = load_node->buf(); + map_input_to_tensor_bufs_.emplace(t_buf->name_hint(), v->buf()); + } else { + auto add_node = to(v->value()); + auto mul_node = to(v->value()); + // This means for now, v->value() can be Add or Mul + TORCH_INTERNAL_ASSERT(add_node || mul_node, buildErrorMessage()); + map_input_to_tensor_bufs_.emplace(v->buf()->name_hint(), v->buf()); + } + v->value()->accept(this); + } + std::unordered_map map_input_to_tensor_bufs_; +}; + +} // namespace torch::jit::tensorexpr diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/block_codegen.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/block_codegen.h new file mode 100644 index 0000000000000000000000000000000000000000..45311409ed6605e3a0ea03939e9be61dbac9c6a2 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/block_codegen.h @@ -0,0 +1,146 @@ +#pragma once + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace torch::jit::tensorexpr { + +// A class that analyzes the given program relevant for Block backend. +class BlockAnalysis : public IRVisitor { + public: + bool is_buf_store_target(const BufPtr& buf) const { + return store_targets_.count(buf) > 0; + } + + const std::unordered_set& loads() const { + return loads_; + } + + const std::unordered_set& stores() const { + return store_targets_; + } + + int64_t block_size() const { + return block_size_; + } + + bool areBufsInMap(const std::unordered_set& bufs) const; + + BufPtr getMultiDimBuf(const BufPtr& buf) const; + + std::string getInputName(const BufPtr& buf) const; + + std::string getFlatInputName(const BufPtr& buf) const { + return getInputName(buf) + "_flat"; + } + + std::unordered_map getBufferMap() const { + return map_input_to_tensor_bufs_; + } + + private: + void visit(const StorePtr& v) override; + void visit(const LoadPtr& v) override; + void visit(const ForPtr& v) override; + + std::unordered_map map_input_to_tensor_bufs_; + std::unordered_set store_targets_; + std::unordered_set loads_; + int64_t block_size_ = 32; +}; + +// A class that overrides the underlying IRPrinter to produce Block. +class BlockPrinter : public IRPrinter { + public: + BlockPrinter(std::ostream* os, BlockAnalysis* block_analysis) + : IRPrinter(*os), block_analysis_(block_analysis) {} + + using IRPrinter::name_manager; + using IRPrinter::visit; + + private: + BlockAnalysis* block_analysis_; + std::unordered_map dim_values_map; + std::vector dim_names = {"N", "H", "W", "C"}; + std::vector flat_dim_names = {"N", "NH", "NHW", "NHWC"}; + void PrintTensorInfo(const std::unordered_set& bufs); + void PrintArguments(const std::unordered_set& bufs); + void PrintBufferInfo(const std::unordered_set& bufs); + void PrintDistribution(const std::unordered_set& bufs); + void PrintLoop(const std::unordered_set& bufs, bool block_idx = true); + void PrintReshapeInfo( + const std::unordered_set& bufs, + bool reverse = false); + void PrintDMAs(const std::unordered_set& bufs); + void PrintAdjustBuffers(const std::unordered_set& bufs); + + void visit(const ForPtr& v) override; + void visit(const LoadPtr& v) override; + void visit(const StorePtr& v) override; + void visit(const BlockPtr& v) override; + void visit(const AddPtr& v) override; + void visit(const MulPtr& v) override; +}; + +class TORCH_API BlockCodeGen : public CodeGen { + public: + template + /* implicit */ + BlockCodeGen(StmtPtr stmt, Ts... ts) + : CodeGen( + stmt, + std::vector({BufferArg(ts)...}), + at::Device(at::kCPU)) { + Initialize(); + } + + BlockCodeGen( + StmtPtr stmt, + const std::vector& buffer_args, + at::Device device = at::Device(at::kCPU), + const std::string& kernel_func_name = "func") + : CodeGen(std::move(stmt), buffer_args, device, kernel_func_name) { + Initialize(); + } + + ~BlockCodeGen() override; + + void call(const std::vector& args) override; + void call_raw(const std::vector& args) override; + + void Initialize(); + + std::string getCodeText(const std::string& attr = "") override { + return oss_.str(); + } + + private: + UniqueNameManager* name_manager() { + if (!printer_) { + throw std::runtime_error("Null IRPrinter is not expected"); + } + return printer_->name_manager(); + } + + std::ostream& os() { + return printer_->os(); + } + + std::ostringstream oss_; + std::unique_ptr printer_; + std::unique_ptr block_analysis_; + + std::string GetUniqueFuncName(const std::string& func_prefix); +}; +} // namespace torch::jit::tensorexpr diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/bounds_inference.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/bounds_inference.h new file mode 100644 index 0000000000000000000000000000000000000000..300cb89a788f5d742d284810920fd01c0c49bfab --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/bounds_inference.h @@ -0,0 +1,79 @@ +#pragma once + +#include +#include + +#include +#include + +namespace torch { +namespace jit { +namespace tensorexpr { + +class Expr; +class Buf; +class Stmt; + +enum C10_API_ENUM TensorAccessKind { kLoad, kStore, kMutate }; + +struct TORCH_API TensorAccessBoundsInfo { + TensorAccessKind kind; + std::vector start; + std::vector stop; +}; + +using BoundsInfo = + std::unordered_map>; + +TORCH_API BoundsInfo +inferBounds(const StmtPtr& s, bool distinctAccessKinds = true); + +// Bounds inference caching the analysis. The MemDependencyChecker must already +// have been run. +TORCH_API BoundsInfo getInferredBounds( + analysis::MemDependencyChecker& analyzer, + const StmtPtr& s, + bool distinctAccessKinds = true); +TORCH_API BoundsInfo getInferredBounds( + analysis::MemDependencyChecker& analyzer, + const ExprPtr& e, + bool distinctAccessKinds = true); + +TORCH_API void printBoundsInfo(const BoundsInfo& v); + +TORCH_API std::vector getBoundExtents( + const std::vector& infos); + +// The kind of dependency found, in increasing order of exclusivity. +enum class HazardKind { + ReadAfterWrite, + WriteAfterRead, + WriteAfterWrite, + NoDependency, +}; +TORCH_API HazardKind getPotentialHazards( + analysis::MemDependencyChecker& analyzer, + const StmtPtr& A, + const StmtPtr& B); + +// Returns true if there is a conflicting overlap between accesses in +// statements A and B. A conflicting overlap is an overlap in buffer accesses +// where at least one of the accesses is a Store. +TORCH_API bool hasConflictingOverlap( + analysis::MemDependencyChecker& analyzer, + const StmtPtr& A, + const StmtPtr& B); +// Same as above, between accesses in stores S1 and S2. +TORCH_API bool isOverlapping( + analysis::MemDependencyChecker& analyzer, + const StorePtr& S1, + const StorePtr& S2); +// Same as above, between accesses in store S and load L. +TORCH_API bool isOverlapping( + analysis::MemDependencyChecker& analyzer, + const StorePtr& S, + const LoadPtr& L); + +} // namespace tensorexpr +} // namespace jit +} // namespace torch diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/cpp_codegen.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/cpp_codegen.h new file mode 100644 index 0000000000000000000000000000000000000000..d8a46fa7893aaf9c2da29b65e7c64241b6470b75 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/cpp_codegen.h @@ -0,0 +1,98 @@ +#pragma once + +#include +#include + +namespace torch::jit::tensorexpr { + +class CppVarNameRewriter; + +// Generates C++ code from the IR. +// +// Vector operations are unrolled. +// For example: +// C[Ramp(0, 1, 3)] = A[Ramp(0, 2, 3)] + B[Ramp(0, 3, 3)]; +// is unrolled into: +// C[0] = A[0] + B[0]; +// C[1] = A[2] + B[3]; +// C[2] = A[4] + B[6]; +class TORCH_API CppPrinter : public IRPrinter { + public: + explicit CppPrinter(std::ostream* os); + ~CppPrinter() override; + + void printPrologue(); + + using IRPrinter::visit; + + // Binary expressions. + void visit(const ModPtr&) override; + void visit(const MaxPtr&) override; + void visit(const MinPtr&) override; + + // Conditional expressions. + void visit(const CompareSelectPtr&) override; + void visit(const IfThenElsePtr&) override; + + // Tensor operations. + void visit(const AllocatePtr&) override; + void visit(const FreePtr&) override; + void visit(const LoadPtr&) override; + void visit(const StorePtr&) override; + + // Casts. + void visit(const CastPtr&) override; + void visit(const BitCastPtr&) override; + + // Calls. + void visit(const IntrinsicsPtr&) override; + void visit(const ExternalCallPtr&) override; + + // Vars. + void visit(const LetPtr&) override; + void visit(const VarPtr&) override; + + // Vector data types. + void visit(const RampPtr&) override; + void visit(const BroadcastPtr&) override; + + private: + int lane_; + std::unordered_map vector_vars_; +}; + +class TORCH_API CppCodeGen : public CodeGen { + public: + CppCodeGen( + StmtPtr stmt, + const std::vector& buffer_args, + at::Device device = at::kCPU, + const std::string& kernel_func_name = "func"); + + ~CppCodeGen() override; + + void call(const std::vector& args) override; + void call_raw(const std::vector& args) override; + + template + void operator()(const Ts&... ts) { + call(std::vector({CallArg(ts)...})); + } + + std::string getCodeText(const std::string& attr = "") override { + return oss_.str(); + } + + private: + void init(); + + std::ostream& os() { + return printer_->os(); + } + + std::ostringstream oss_; + std::unique_ptr printer_; + std::unique_ptr var_name_rewriter_; +}; + +} // namespace torch::jit::tensorexpr diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/cpp_intrinsics.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/cpp_intrinsics.h new file mode 100644 index 0000000000000000000000000000000000000000..caeeed693ff38f2129d8916204a5e843c88e062f --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/cpp_intrinsics.h @@ -0,0 +1,36 @@ +#pragma once + +namespace torch { +namespace jit { +namespace tensorexpr { + +constexpr auto cpp_intrinsics_definition = R"( +namespace std { + +template ::value, int>::type = 0> +T rsqrt(T v) { + return 1.0f / std::sqrt(v); +} + +template ::value, int>::type = 0> +T frac(T v) { + T intpart; + return std::modf(v, &intpart); +} + +template +To bitcast(const From& v) { + assert(sizeof(To) == sizeof(From)); + To res; + std::memcpy(&res, &v, sizeof(From)); + return res; +} + +} // namespace std +)"; + +} // namespace tensorexpr +} // namespace jit +} // namespace torch diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/cuda_codegen.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/cuda_codegen.h new file mode 100644 index 0000000000000000000000000000000000000000..394b6ad242d4c90de9a6983b604171cf72208ac4 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/cuda_codegen.h @@ -0,0 +1,286 @@ +#pragma once + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace torch::jit::tensorexpr { + +// A class that analyzes the given program relevant for Cuda backends. +class CudaAnalysis : public IRVisitor { + public: + CudaAnalysis() { + gpu_block_extents_ = {alloc(1), alloc(1), alloc(1)}; + gpu_thread_extents_ = { + alloc(1), alloc(1), alloc(1)}; + } + bool is_buf_store_target(const BufPtr& buf) const { + return store_targets_.count(buf) > 0; + } + + const std::unordered_set& thread_local_bufs() const { + return thread_local_bufs_; + } + + const std::unordered_set& cross_block_bufs() const { + return cross_block_bufs_; + } + + const std::vector& gpu_block_extents() const { + return gpu_block_extents_; + } + + const std::vector& gpu_thread_extents() const { + return gpu_thread_extents_; + } + + private: + void visit(const StorePtr& v) override { + store_targets_.insert(v->buf()); + } + + void visit(const AllocatePtr& v) override; + void visit(const FreePtr& v) override; + void visit(const PlacementAllocatePtr& v) override; + void visit(const ForPtr& v) override; + + std::unordered_set store_targets_; + std::unordered_set thread_local_bufs_; + std::unordered_set cross_block_bufs_; + + std::vector gpu_block_extents_; + std::vector gpu_thread_extents_; +}; + +// An IRMutator that replaces binding loop options with Cuda metavars, and masks +// statements blocks which should execute with less reach than the launch +// parameter extent. +// +// We do this by segmenting each block into chunks which should have the same +// execution parameters, then if those params differ from the max mask each dim. +class GPUMetaVarRewriter : public IRMutator { + public: + explicit GPUMetaVarRewriter(const CudaAnalysis* cuda_analysis) + : cuda_analysis_(cuda_analysis) { + gpu_block_vars_ = { + alloc("blockIdx.x", kInt), + alloc("blockIdx.y", kInt), + alloc("blockIdx.z", kInt)}; + gpu_thread_vars_ = { + alloc("threadIdx.x", kInt), + alloc("threadIdx.y", kInt), + alloc("threadIdx.z", kInt)}; + + current_block_reach_ = { + alloc(1), alloc(1), alloc(1)}; + current_thread_reach_ = { + alloc(1), alloc(1), alloc(1)}; + } + + StmtPtr mutate(const ForPtr& v) override; + StmtPtr mutate(const BlockPtr& v) override; + + const std::vector& gpu_block_vars() const { + return gpu_block_vars_; + } + + const std::vector& gpu_thread_vars() const { + return gpu_thread_vars_; + } + + const std::vector& gpu_block_extents() const { + return cuda_analysis_->gpu_block_extents(); + } + + const std::vector& gpu_thread_extents() const { + return cuda_analysis_->gpu_thread_extents(); + } + + private: + // When processing a block, stores the contents of each sub-segment. + class Segment { + public: + void reset(bool mask) { + stmts_.clear(); + mask_ = mask; + } + + bool empty() const { + return stmts_.empty(); + } + + std::vector& stmts() { + return stmts_; + } + bool mask() { + return mask_; + } + + private: + std::vector stmts_; + bool mask_{true}; + }; + + // Returns true if the current execution scope is equivalent to the launch + // parameters. + bool isFullExtent(); + + std::vector gpu_block_vars_; + std::vector gpu_thread_vars_; + + std::vector current_block_reach_; + std::vector current_thread_reach_; + + const CudaAnalysis* cuda_analysis_; +}; + +// A class that overrides the underlying IRPrinter to produce Cuda C. +class CudaPrinter : public IRPrinter { + public: + explicit CudaPrinter( + std::ostream* os, + const CudaAnalysis* cuda_analysis, + bool has_random) + : IRPrinter(*os), cuda_analysis_(cuda_analysis) { + if (has_random) { + rand_func_ = alloc("rand", kHandle); + } + } + + void visit(const CastPtr& v) override; + void visit(const IntrinsicsPtr& v) override; + void visit(const ForPtr& v) override; + + void visit(const LoadPtr& v) override; + void visit(const StorePtr& v) override; + void visit(const AtomicAddPtr& v) override; + void visit(const MaxPtr& v) override; + void visit(const MinPtr& v) override; + void visit(const IfThenElsePtr& v) override; + void visit(const BlockPtr& v) override; + void visit(const AllocatePtr& v) override; + void visit(const FreePtr& v) override; + void visit(const LetPtr& v) override; + + void visit(const ExternalCallPtr& v) override; + + VarPtr rand_func() const { + return rand_func_; + } + + std::string dtypeToCppString(const Dtype& dtype) override; + + using IRPrinter::name_manager; + using IRPrinter::visit; + + private: + VarPtr rand_func_; + const CudaAnalysis* cuda_analysis_; + + void print_flat_alloc(const AllocatePtr& alloc); +}; + +// Construct Cuda C from the buffer and tensor input, and invoke the +// kernel when real arguments are provided. +class TORCH_CUDA_CU_API CudaCodeGen : public CodeGen { + public: + template + CudaCodeGen(StmtPtr stmt, Ts... ts) + : CodeGen( + stmt, + std::vector({BufferArg(ts)...}), + at::Device(at::kCUDA, at::cuda::current_device())) { + Initialize(); + } + + CudaCodeGen( + StmtPtr stmt, + const std::vector& buffer_args, + at::Device device = at::Device(at::kCUDA, at::cuda::current_device()), + const std::string& kernel_func_name = "func") + : CodeGen(std::move(stmt), buffer_args, device, kernel_func_name) { + Initialize(); + } + + ~CudaCodeGen() override; + + void call(const std::vector& args) override; + void call_raw(const std::vector& args) override; + void call_with_numel(void** args, int64_t numel) override; + + template + void operator()(const Ts&... ts) { + call(std::vector({CallArg(ts)...})); + } + + at::Tensor empty_strided( + c10::IntArrayRef size, + c10::IntArrayRef stride, + std::optional dtype_opt, + std::optional layout_opt, + std::optional device_opt, + std::optional pin_memory_opt) override; + + const std::vector& gpu_block_extents() const { + return cuda_analysis_->gpu_block_extents(); + } + + const std::vector& gpu_thread_extents() const { + return cuda_analysis_->gpu_thread_extents(); + } + + std::string getCodeText(const std::string& attr = "") override { + return oss_.str(); + } + + private: + void Initialize(); + + void CompileToNVRTC(const std::string& code, const std::string& func_name); + + UniqueNameManager* name_manager() { + if (!printer_) { + throw std::runtime_error("Null IRPrinter is not expected"); + } + return printer_->name_manager(); + } + + std::ostream& os() { + return printer_->os(); + } + + std::ostringstream oss_; + std::unique_ptr printer_; + std::unique_ptr cuda_analysis_; + std::unique_ptr metavar_rewriter_; + std::unordered_set taken_func_names; + std::mutex eval_lock_; + CUfunction function_{nullptr}; + bool has_random_ = false; + int thread_block_size_ = -1; + + std::vector arg_pos_in_extents_; +#ifdef TORCH_ENABLE_LLVM + std::vector> block_extents_eval_; + std::vector> thread_extents_eval_; +#else + std::vector> block_extents_eval_; + std::vector> thread_extents_eval_; +#endif + + std::string GetUniqueFuncName(const std::string& func_prefix); +}; + +} // namespace torch::jit::tensorexpr diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/cuda_random.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/cuda_random.h new file mode 100644 index 0000000000000000000000000000000000000000..987ac5211d92960e335bfe2c8688a2c06fc6677d --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/cuda_random.h @@ -0,0 +1,104 @@ +#pragma once + +namespace torch { +namespace jit { +namespace tensorexpr { + +constexpr auto philox_random_string = R"( + +class Philox { +public: + __device__ inline Philox(unsigned long long seed, + unsigned long long subsequence, + unsigned long long offset) { + key.x = (unsigned int)seed; + key.y = (unsigned int)(seed >> 32); + counter = make_uint4(0, 0, 0, 0); + counter.z = (unsigned int)(subsequence); + counter.w = (unsigned int)(subsequence >> 32); + STATE = 0; + incr_n(offset / 4); + } + + __device__ inline unsigned long operator()() { + if(STATE == 0) { + uint4 counter_ = counter; + uint2 key_ = key; + for(int i = 0; i < 9; i++) { + counter_ = single_round(counter_, key_); + key_.x += (kPhilox10A); key_.y += (kPhilox10B); + } + output = single_round(counter_, key_); + incr(); + } + unsigned long ret; + switch(STATE) { + case 0: ret = output.x; break; + case 1: ret = output.y; break; + case 2: ret = output.z; break; + case 3: ret = output.w; break; + } + STATE = (STATE + 1) % 4; + return ret; + } + +private: + uint4 counter; + uint4 output; + uint2 key; + unsigned int STATE; + __device__ inline void incr_n(unsigned long long n) { + unsigned int nlo = (unsigned int)(n); + unsigned int nhi = (unsigned int)(n >> 32); + counter.x += nlo; + if (counter.x < nlo) + nhi++; + counter.y += nhi; + if (nhi <= counter.y) + return; + if (++counter.z) + return; + ++counter.w; + } + __device__ inline void incr() { + if (++counter.x) + return; + if (++counter.y) + return; + if (++counter.z) + return; + ++counter.w; + } + __device__ unsigned int mulhilo32(unsigned int a, unsigned int b, + unsigned int *result_high) { + *result_high = __umulhi(a, b); + return a*b; + } + + __device__ inline uint4 single_round(uint4 ctr, uint2 key) { + unsigned int hi0; + unsigned int hi1; + unsigned int lo0 = mulhilo32(kPhiloxSA, ctr.x, &hi0); + unsigned int lo1 = mulhilo32(kPhiloxSB, ctr.z, &hi1); + + uint4 ret = {hi1 ^ ctr.y ^ key.x, lo1, hi0 ^ ctr.w ^ key.y, lo0}; + return ret; + } + + static const unsigned long kPhilox10A = 0x9E3779B9; + static const unsigned long kPhilox10B = 0xBB67AE85; + static const unsigned long kPhiloxSA = 0xD2511F53; + static const unsigned long kPhiloxSB = 0xCD9E8D57; +}; + +// Inverse of 2^32. +#define M_RAN_INVM32 2.3283064e-10f +__device__ __inline__ float Uint32ToFloat(unsigned int x) { + return x * M_RAN_INVM32; +} + +)"; + +} // namespace tensorexpr +} // namespace jit +} // namespace torch diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/eval.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/eval.h new file mode 100644 index 0000000000000000000000000000000000000000..5d57318ab17df2704652fe1da30841ce90433cfc --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/eval.h @@ -0,0 +1,324 @@ +#pragma once + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace torch::jit::tensorexpr { + +class InterpValue { + public: + InterpValue() : dtype_(kInt) { + Intvalues.push_back(0); + } + + template + InterpValue(Dtype dtype, T v) : dtype_(dtype) { +#define TYPE_CASE(Type, Name) \ + if (dtype == k##Name) { \ + Name##values.push_back(v); \ + return; \ + } + AT_FORALL_SCALAR_TYPES_AND3(Bool, Half, BFloat16, TYPE_CASE); +#undef TYPE_CASE + throw unsupported_dtype(); + } + +#define VALUE_CTOR(Type, Name) \ + InterpValue(Type v) : dtype_(k##Name) { \ + Name##values.push_back(v); \ + } + AT_FORALL_SCALAR_TYPES_AND3(Bool, Half, BFloat16, VALUE_CTOR); +#undef VALUE_CTOR + + explicit InterpValue(c10::quint8 v) : dtype_(kQUInt8) { + QUInt8values.emplace_back(v.val_); + } + + explicit InterpValue(c10::qint8 v) : dtype_(kQInt8) { + QInt8values.emplace_back(v.val_); + } + +#define VALUE_VEC_CTOR(Type, Name) \ + InterpValue(const std::vector& v) \ + : dtype_(Dtype(k##Name, v.size())), Name##values(v) {} + AT_FORALL_SCALAR_TYPES_AND3(Bool, Half, BFloat16, VALUE_VEC_CTOR); + VALUE_VEC_CTOR(c10::quint8, QUInt8) + VALUE_VEC_CTOR(c10::qint8, QInt8) +#undef VALUE_VEC_CTOR + + template + T as() const; + + template + const std::vector& as_vec() const; + + int64_t intValue() const; + + Dtype dtype() const { + return dtype_; + } + + private: + Dtype dtype_; + +#define VALUE_STORAGE(Type, Name) std::vector Name##values; + AT_FORALL_SCALAR_TYPES_AND3(Bool, Half, BFloat16, VALUE_STORAGE); + VALUE_STORAGE(c10::qint8, QInt8); + VALUE_STORAGE(c10::quint8, QUInt8); +#undef VALUE_STORAGE + void* ptr{nullptr}; +}; + +#define VALUE_AS_DISPATCH(Type, Name) \ + template <> \ + inline Type InterpValue::as() const { \ + if (dtype_ != k##Name) { \ + throw unsupported_dtype(); \ + } \ + return Name##values[0]; \ + } +AT_FORALL_SCALAR_TYPES_AND3(Bool, Half, BFloat16, VALUE_AS_DISPATCH); +VALUE_AS_DISPATCH(c10::quint8, QUInt8); +VALUE_AS_DISPATCH(c10::qint8, QInt8); +#undef VALUE_AS_DISPATCH + +#define VALUE_AS_VEC_DISPATCH(Type, Name) \ + template <> \ + inline const std::vector& InterpValue::as_vec() const { \ + if (dtype_.scalar_type() != ScalarType::Name) { \ + throw unsupported_dtype(); \ + } \ + return Name##values; \ + } +AT_FORALL_SCALAR_TYPES_AND3(Bool, Half, BFloat16, VALUE_AS_VEC_DISPATCH); +VALUE_AS_VEC_DISPATCH(c10::quint8, QUInt8); +VALUE_AS_VEC_DISPATCH(c10::qint8, QInt8); +#undef VALUE_AS_VEC_DISPATCH + +template +auto underlyingValue(Type x) { + return x; +} + +template <> +inline auto underlyingValue(c10::quint8 x) { + return x.val_; +} + +template <> +inline auto underlyingValue(c10::qint8 x) { + return x.val_; +} + +template +To raw_bitcast(const From& src) { + TORCH_CHECK(sizeof(To) == sizeof(From), "Invalid bitcast invocation"); + To storage; + std::memcpy(&storage, &src, sizeof(To)); + return reinterpret_cast(storage); +} + +class SimpleIREvaluatorImpl; +class TORCH_API SimpleIREvaluator : public CodeGen { + public: + SimpleIREvaluator( + StmtPtr stmt, + const std::vector& buffer_args, + at::Device device = at::kCPU, + const std::string& kernel_func_name = "func"); + + ~SimpleIREvaluator() override; + + void call(const std::vector& args) override; + void call_raw(const std::vector& args) override; + + template + void operator()(const Ts&... ts) { + std::vector args({CallArg(ts)...}); + call(args); + } + + void bindVar(const VarPtr& v, const ExprPtr& e); + InterpValue value() const; + + private: + void bindArg(const BufferArg& buf, void* data); + void expand_intrinsics() { + GenericIntrinsicsExpander intrinsics_expander; + apply_mutator(&intrinsics_expander); + } + + std::unique_ptr impl_; +}; + +template +class ExprEval { + public: + using BufferArg = CodeGen::BufferArg; + using CallArg = CodeGen::CallArg; + + template + ExprEval(const ExprHandle& expr, Ts... ts) + : ExprEval(expr, {BufferArg(ts)...}) {} + + ExprEval(const ExprHandle& expr, const std::vector& buffer_args) + : dtype_(expr.dtype()) { + std::vector buffer_args_extended = buffer_args; + BufHandle ret_buf("ret_val", {1}, dtype_); + std::vector indices; + ExprHandle zero = IntImm::make(0); + for (size_t i = 0; i < ret_buf.ndim(); i++) { + indices.push_back(zero); + } + StmtPtr store_stmt = Store::make(ret_buf, indices, expr); + buffer_args_extended.emplace_back(ret_buf); + codegen_.reset(new CodeGenType(store_stmt, buffer_args_extended)); + } + + template + void operator()(Ts... ts) { + call(ts...); + } + + void operator()(const std::vector& call_args) { + call(call_args); + } + + void bindVar(VarPtr v, ExprPtr e) { + codegen_->bindVar(v, e); + } + + void bindVar(const VarHandle& v, const ExprHandle& e) { + codegen_->bindVar(v.node(), e.node()); + } + + template + void call(Ts... ts) { + call({CallArg(ts)...}); + } + + void call(const std::vector& call_args) { + std::vector call_args_extended = call_args; + switch (dtype_.scalar_type()) { +#define TYPE_CASE(Type, Name) \ + case ScalarType::Name: { \ + std::vector ret_val_arg(1); \ + call_args_extended.emplace_back(ret_val_arg); \ + codegen_->call(call_args_extended); \ + ret_value_ = InterpValue(ret_val_arg[0]); \ + } break; + AT_FORALL_SCALAR_TYPES_AND2(Half, BFloat16, TYPE_CASE); + TYPE_CASE(c10::quint8, QUInt8); + TYPE_CASE(c10::qint8, QInt8); +#undef TYPE_CASE + case ScalarType::Bool: { + std::vector ret_val_arg(1); + call_args_extended.emplace_back(ret_val_arg.data()); + codegen_->call(call_args_extended); + ret_value_ = InterpValue((bool)ret_val_arg[0]); + } break; + default: + throw unsupported_dtype(); + } + } + + void call_raw(const std::vector& args) { + std::vector args_extended = args; + switch (dtype_.scalar_type()) { +#define TYPE_CASE(Type, Name) \ + case ScalarType::Name: { \ + std::vector ret_val_arg(1); \ + args_extended.push_back(ret_val_arg.data()); \ + codegen_->call_raw(args_extended); \ + ret_value_ = InterpValue(ret_val_arg[0]); \ + } break; + AT_FORALL_SCALAR_TYPES_AND2(Half, BFloat16, TYPE_CASE); + TYPE_CASE(c10::quint8, QUInt8); + TYPE_CASE(c10::qint8, QInt8); +#undef TYPE_CASE + case ScalarType::Bool: { + std::vector ret_val_arg(1); + args_extended.push_back(ret_val_arg.data()); + codegen_->call_raw(args_extended); + ret_value_ = InterpValue((bool)ret_val_arg[0]); + } break; + default: + throw unsupported_dtype(); + } + } + + template + T value(const std::vector& args) { + call_raw(args); + return ret_value_.as(); + } + + template + T value(Ts... ts) { + call(std::forward(ts)...); + return ret_value_.as(); + } + + Dtype dtype() { + return dtype_; + } + + private: + Dtype dtype_; + std::unique_ptr codegen_; + InterpValue ret_value_; +}; + +// Evaluates the given expression and returns an int64_t value if the result of +// the given expression is int64_t. +std::optional evalInt(ExprPtr e); + +// Substitutes the given vars with their corresponding expressions in the input +// expression. +inline ExprPtr Substitute(const ExprPtr& expr, const VarMapping& var_mapping) { + VarSubMutator var_sub(var_mapping); + return expr->accept_mutator(&var_sub); +} + +// Substitutes the given vars with their corresponding expressions in the input +// statement. +inline StmtPtr Substitute(const StmtPtr& stmt, const VarMapping& var_mapping) { + VarSubMutator var_sub(var_mapping); + return stmt->accept_mutator(&var_sub); +} + +// Creates a clone of the input expression and substitutes the given vars with +// their corresponding expressions in the clone. +// NOTE: This works because cloning reuses variables and does not create new +// ones, and `VarMapping` input has variables as the key. +inline ExprPtr SubstituteInClone( + const ExprPtr& expr, + const VarMapping& var_mapping) { + VarSubMutator var_sub(var_mapping); + return Expr::clone(expr)->accept_mutator(&var_sub); +} + +// Creates a clone of the input statement and substitutes the given vars with +// their corresponding expressions in the clone. +// NOTE: This works because cloning reuses variables and does not create new +// ones, and `VarMapping` input has variables as the key. +inline StmtPtr SubstituteInClone( + const StmtPtr& stmt, + const VarMapping& var_mapping) { + VarSubMutator var_sub(var_mapping); + return Stmt::clone(stmt)->accept_mutator(&var_sub); +} + +} // namespace torch::jit::tensorexpr diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/exceptions.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/exceptions.h new file mode 100644 index 0000000000000000000000000000000000000000..1241400474a402c665451b333acc252a05d9ece3 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/exceptions.h @@ -0,0 +1,83 @@ +#pragma once + +#include +#include + +#include + +// Forward declarations of types + +namespace torch::jit::tensorexpr { +class Expr; +class Stmt; +} // namespace torch::jit::tensorexpr + +// Forward declarations of functions +namespace std { +TORCH_API std::string to_string(const torch::jit::tensorexpr::ExprPtr&); +TORCH_API std::string to_string(const torch::jit::tensorexpr::StmtPtr&); +} // namespace std + +namespace torch::jit::tensorexpr { + +class unsupported_dtype : public std::runtime_error { + public: + explicit unsupported_dtype() : std::runtime_error("UNSUPPORTED DTYPE") {} + explicit unsupported_dtype(const std::string& err) + : std::runtime_error("UNSUPPORTED DTYPE: " + err) {} +}; + +class out_of_range_index : public std::runtime_error { + public: + explicit out_of_range_index() : std::runtime_error("OUT OF RANGE INDEX") {} + explicit out_of_range_index(const std::string& err) + : std::runtime_error("OUT OF RANGE INDEX: " + err) {} +}; + +class unimplemented_lowering : public std::runtime_error { + public: + explicit unimplemented_lowering() + : std::runtime_error("UNIMPLEMENTED LOWERING") {} + explicit unimplemented_lowering(const ExprPtr& expr) + : std::runtime_error("UNIMPLEMENTED LOWERING: " + std::to_string(expr)) {} + explicit unimplemented_lowering(const StmtPtr& stmt) + : std::runtime_error("UNIMPLEMENTED LOWERING: " + std::to_string(stmt)) {} +}; + +class malformed_input : public std::runtime_error { + public: + explicit malformed_input() : std::runtime_error("MALFORMED INPUT") {} + explicit malformed_input(const std::string& err) + : std::runtime_error("MALFORMED INPUT: " + err) {} + explicit malformed_input(const ExprPtr& expr) + : std::runtime_error("MALFORMED INPUT: " + std::to_string(expr)) {} + explicit malformed_input(const std::string& err, const ExprPtr& expr) + : std::runtime_error( + "MALFORMED INPUT: " + err + " - " + std::to_string(expr)) {} + explicit malformed_input(const StmtPtr& stmt) + : std::runtime_error("MALFORMED INPUT: " + std::to_string(stmt)) {} + explicit malformed_input(const std::string& err, const StmtPtr& stmt) + : std::runtime_error( + "MALFORMED INPUT: " + err + " - " + std::to_string(stmt)) {} +}; + +class malformed_ir : public std::runtime_error { + public: + explicit malformed_ir() : std::runtime_error("MALFORMED IR") {} + explicit malformed_ir(const std::string& err) + : std::runtime_error("MALFORMED IR: " + err) {} + explicit malformed_ir(const ExprPtr& expr) + : std::runtime_error("MALFORMED IR: " + std::to_string(expr)) {} + explicit malformed_ir(const std::string& err, const ExprPtr& expr) + : std::runtime_error( + "MALFORMED IR: " + err + " - " + std::to_string(expr)) {} + explicit malformed_ir(const StmtPtr& stmt) + : std::runtime_error("MALFORMED IR: " + std::to_string(stmt)) {} + explicit malformed_ir(const std::string& err, const StmtPtr& stmt) + : std::runtime_error( + "MALFORMED IR: " + err + " - " + std::to_string(stmt)) {} +}; + +TORCH_API std::string buildErrorMessage(const std::string& s = ""); + +} // namespace torch::jit::tensorexpr diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/expr.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/expr.h new file mode 100644 index 0000000000000000000000000000000000000000..fbef2b134057e353c94db8b2715528d86f306006 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/expr.h @@ -0,0 +1,493 @@ +/** + * This file implements the core classes for Tensor Expressions. + * + * The structure of the expressions is inspired by Halide/TVM IR. + */ +#pragma once + +#include +#include +#include +#include +#include +#include + +#include + +namespace torch::jit::tensorexpr { + +enum IRNodeType { + kPrimitive, + kAdd, + kSub, + kMul, + kDiv, + kMod, + kMax, + kMin, + kAnd, + kOr, + kLshift, + kRshift, + kXor, + kCompareSelect, + kCast, + kBitCast, + kOther, +}; + +// The common base between all expression node. +class TORCH_API Expr : public std::enable_shared_from_this { + public: + explicit Expr(Dtype dtype, IRNodeType expr_type = kOther) + : dtype_(dtype), expr_type_(expr_type) {} + virtual ~Expr() = default; + Dtype dtype() const { + return dtype_; + } + virtual void accept(IRVisitor* visitor) = 0; + virtual ExprPtr accept_mutator(IRMutator* mutator) = 0; + + IRNodeType expr_type() const { + return expr_type_; + } + // Is this a fixed (constant) immediate value. + virtual bool isConstant() const { + return false; + } + + void set_dtype(Dtype dtype) { + dtype_ = dtype; + } + + /* + * Make a deep copy of the given expression. + * + * All sub-expressions inside the given expressions are also cloned. Note + * that the variables are not deep-copied since they are immutable. + */ + static ExprPtr clone(const ExprPtr& s); + + protected: + std::shared_ptr getptr() { + return shared_from_this(); + } + + private: + Dtype dtype_; + IRNodeType expr_type_; +}; + +// A CRTP pattern to accept visitors for children class, +// and dispatch back to the children. +template +class ExprNode : public Base { + public: + using ExprNodeBase = ExprNode; + void accept(IRVisitor* visitor) override { + visitor->visit(static_to(Base::getptr())); + } + ExprPtr accept_mutator(IRMutator* mutator) override; + // pass the constructor to the base class + using Base::Base; +}; + +// A wrapper object to the underlying ExprNode. +// Also serves the primary way to build and operate on other expressions. +class TORCH_API ExprHandle { + public: + ExprHandle() = default; + explicit ExprHandle(ExprPtr node) : base_expr_node_(std::move(node)) {} + + ExprPtr node() { + return base_expr_node_; + } + + ExprPtr node() const { + return base_expr_node_; + } + + bool empty() const { + return base_expr_node_ == nullptr; + } + +#define IMM_EXPR_DECLARE(Type, Name) ExprHandle(Type v); + AT_FORALL_SCALAR_TYPES_AND3(Bool, Half, BFloat16, IMM_EXPR_DECLARE); +#undef IMM_EXPR_DECLARE + + template + NodePtr AsNode() { + return to(this->node()); + } + + template + NodePtr AsNode() const { + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast) + return const_cast(this)->AsNode(); + } + + Dtype dtype() const { + return node()->dtype(); + } + + // Handling the math operators. + ExprHandle operator+(const ExprHandle& other) const; + ExprHandle operator-(const ExprHandle& other) const; + ExprHandle operator*(const ExprHandle& other) const; + ExprHandle operator/(const ExprHandle& other) const; + ExprHandle operator%(const ExprHandle& other) const; + ExprHandle operator==(const ExprHandle& other) const; + ExprHandle operator!=(const ExprHandle& other) const; + ExprHandle operator>(const ExprHandle& other) const; + ExprHandle operator>=(const ExprHandle& other) const; + ExprHandle operator<(const ExprHandle& other) const; + ExprHandle operator<=(const ExprHandle& other) const; + ExprHandle operator&(const ExprHandle& other) const; + ExprHandle operator|(const ExprHandle& other) const; + ExprHandle operator&&(const ExprHandle& other) const; + ExprHandle operator||(const ExprHandle& other) const; + ExprHandle operator^(const ExprHandle& other) const; + ExprHandle operator<<(const ExprHandle& other) const; + ExprHandle operator>>(const ExprHandle& other) const; + + private: + ExprPtr base_expr_node_ = nullptr; +}; + +// The underlying representation node to a Var. +// Currently, each Var object represents a unique variable, even though the +// names might be the same. We should consider add a unique_name as well. +class TORCH_API Var : public ExprNode { + public: + static ExprHandle make(const std::string& name_hint, Dtype dtype) { + return ExprHandle(alloc(name_hint, dtype)); + } + static ExprHandle make(Dtype dtype) { + return ExprHandle(alloc("", dtype)); + } + + // TODO: unique_name + const std::string& name_hint() const { + return name_hint_; + } + + void set_name_hint(const std::string& name) { + name_hint_ = name; + } + + void set_name_hint(std::string&& name) { + name_hint_ = std::move(name); + } + + Var(std::string name_hint, Dtype dtype) + : ExprNodeBase(dtype, kPrimitive), name_hint_(std::move(name_hint)) {} + + private: + std::string name_hint_; +}; + +TORCH_API std::vector make_contiguous_strides( + const std::vector& dims); +TORCH_API std::vector make_channels_last_strides( + const std::vector& dims); + +class TORCH_API Buf : public ExprNode { + public: + static BufHandle make(const std::vector& dims, Dtype dtype); + + static BufHandle make( + const std::string& name_hint, + const std::vector& dims, + const std::vector& strides, + Dtype dtype); + + static BufHandle make( + const std::string& name_hint, + const std::vector& dims, + Dtype dtype, + std::optional initializer = std::nullopt, + const std::optional>& strides = std::nullopt, + std::optional qscale = std::nullopt, + std::optional qzero = std::nullopt); + + // TODO: unique_name + VarPtr base_handle() const { + return base_handle_; + } + void set_base_handle(VarPtr base_handle) { + base_handle_ = std::move(base_handle); + } + + const std::string& name_hint() const { + return base_handle_->name_hint(); + } + void set_name_hint(const std::string& name_hint) { + base_handle_->set_name_hint(name_hint); + } + + Buf(const std::string& name_hint, + const std::vector& dims, + Dtype dtype, + ExprPtr initializer = nullptr, + std::optional> strides = std::nullopt, + ExprPtr qscale = nullptr, + ExprPtr qzero = nullptr) + : Buf(alloc(name_hint, kHandle), + dims, + dtype, + std::move(initializer), + std::move(strides), + std::move(qscale), + std::move(qzero)) {} + + Buf(const VarPtr& var, + std::vector dims, + Dtype dtype, + ExprPtr initializer = nullptr, + std::optional> strides = std::nullopt, + ExprPtr qscale = nullptr, + ExprPtr qzero = nullptr); + + size_t ndim() const { + return dims_.size(); + } + ExprPtr dim(size_t index) const { + if (index >= ndim()) { + throw out_of_range_index(); + } + return dims_[index]; + } + std::vector dims() const { + return dims_; + } + void set_dims(std::vector dims) { + dims_ = std::move(dims); + } + + std::vector strides() const { + return strides_; + } + + void set_strides(std::vector strides) { + strides_ = std::move(strides); + } + + ExprPtr initializer() const { + return initializer_; + }; + + ExprPtr qzero() const { + return qzero_; + } + + ExprPtr qscale() const { + return qscale_; + } + + void set_qzero(ExprPtr qzero) { + qzero_ = std::move(qzero); + } + + void set_qscale(ExprPtr qscale) { + qscale_ = std::move(qscale); + } + + bool hasConstantDims() const { + for (const auto& d : dims_) { + if (!d->isConstant()) { + return false; + } + } + return true; + } + + bool is_contiguous( + at::MemoryFormat memory_format = at::MemoryFormat::Contiguous) const; + + // The channels-last 1d can benefit the performance of some operators like + // conv1d. But the MemoryFormat enum has not covered this layout yet. Hence, + // we abstract a dedicated function to check channels-last 1d contiguous. + // + // Channels-last 1d: + // dims: n c l + // strides(nlc): c*l 1 c + bool is_channels_last_1d_contiguous() const { + if (dims_.size() != 3) { + return false; + } + return is_stride_one(1) && is_cont_with(2, 1) && is_cont_with(0, 2); + } + + private: + bool is_cont_with(int cur_dim, int adjacent_dim) const; + bool is_stride_one(int cur_dim) const; + + VarPtr base_handle_; + std::vector dims_; + std::vector strides_; + ExprPtr initializer_; + // qscale_ and qzero_ are used only for quantized dtypes Bufs: kQUInt8, kQInt8 + ExprPtr qscale_; + ExprPtr qzero_; +}; + +class TORCH_API BufHandle : public ExprHandle { + public: + BufHandle( + const std::string& name_hint, + const std::vector& dims, + Dtype dtype) + : ExprHandle(Buf::make(name_hint, dims, dtype)) {} + + BufHandle( + const std::string& name_hint, + const std::vector& dims, + const std::vector& strides, + Dtype dtype) + : ExprHandle(Buf::make(name_hint, dims, strides, dtype)) {} + + BufHandle(const std::vector& dims, Dtype dtype) + : ExprHandle(Buf::make("_", dims, dtype)) {} + + explicit BufHandle(Dtype dtype) : ExprHandle(Buf::make("_", {}, dtype)) {} + + explicit BufHandle(BufPtr node) : ExprHandle(std::move(node)) {} + BufPtr node() const { + return static_to(ExprHandle::node()); + } + BufPtr node() { + return static_to(ExprHandle::node()); + } + + template + inline ExprHandle load(const Ts&... ts) const; + + template + inline ExprHandle load(const std::vector& args) const; + + inline ExprHandle load(const std::vector& args) const; + + StorePtr store(const std::vector& args, const ExprHandle& val) + const; + + bool operator==(const BufHandle& other) const { + return this->node() == other.node(); + } + bool operator!=(const BufHandle& other) const { + return !(*this == other); + } + + const std::string& name_hint() const { + return this->node()->name_hint(); + } + + bool empty() const { + return (this->node() == nullptr); + } + + size_t ndim() const { + return node()->ndim(); + } + + std::vector dims() const; + + ExprHandle dim(size_t index) const { + return ExprHandle(node()->dim(index)); + } + + bool is_contiguous( + at::MemoryFormat memory_format = at::MemoryFormat::Contiguous) const { + return node()->is_contiguous(memory_format); + } + + bool is_channels_last_1d_contiguous() const { + return node()->is_channels_last_1d_contiguous(); + } +}; + +// An expression to construct the underlying variable node. +// Note: do not store any info here, since it is often possible to slice this +// object. For example: VarHandle x('x'); ExprHandle x2 = x; +class TORCH_API VarHandle : public ExprHandle { + public: + // Creates an empty VarHandle whose base Var is set to nullptr. + VarHandle() : ExprHandle() {} + + explicit VarHandle(Dtype dtype) : ExprHandle(Var::make(dtype)) {} + + VarHandle(const std::string& name_hint, Dtype dtype) + : ExprHandle(Var::make(name_hint, dtype)) {} + + explicit VarHandle(VarPtr node) : ExprHandle(std::move(node)) {} + + VarPtr node() const { + return static_to(ExprHandle::node()); + } + bool operator==(const VarHandle& other) const { + return this->node() == other.node(); + } + bool operator!=(const VarHandle& other) const { + return !(*this == other); + } + + const std::string& name_hint() const { + return this->node()->name_hint(); + } + bool empty() const { + return (this->node() == nullptr); + } +}; + +template +ExprPtr ExprNode::accept_mutator(IRMutator* mutator) { + return mutator->mutate(static_to(Base::getptr())); +} + +inline bool same_node(const ExprHandle& expr1, const ExprHandle& expr2) { + return expr1.AsNode() == expr2.AsNode(); +} + +TORCH_API ExprHandle sin(const ExprHandle& v); +TORCH_API ExprHandle cos(const ExprHandle& v); +TORCH_API ExprHandle tan(const ExprHandle& v); +TORCH_API ExprHandle asin(const ExprHandle& v); +TORCH_API ExprHandle acos(const ExprHandle& v); +TORCH_API ExprHandle atan(const ExprHandle& v); +TORCH_API ExprHandle sinh(const ExprHandle& v); +TORCH_API ExprHandle cosh(const ExprHandle& v); +TORCH_API ExprHandle tanh(const ExprHandle& v); +TORCH_API ExprHandle sigmoid(const ExprHandle& v); +TORCH_API ExprHandle exp(const ExprHandle& v); +TORCH_API ExprHandle expm1(const ExprHandle& v); +TORCH_API ExprHandle abs(const ExprHandle& v); +TORCH_API ExprHandle log(const ExprHandle& v); +TORCH_API ExprHandle fast_tanh(const ExprHandle& v); +TORCH_API ExprHandle fast_sigmoid(const ExprHandle& v); +TORCH_API ExprHandle fast_log(const ExprHandle& v); +TORCH_API ExprHandle log_vml(const ExprHandle& v); +TORCH_API ExprHandle log2(const ExprHandle& v); +TORCH_API ExprHandle log10(const ExprHandle& v); +TORCH_API ExprHandle log1p(const ExprHandle& v); +TORCH_API ExprHandle erf(const ExprHandle& v); +TORCH_API ExprHandle erfc(const ExprHandle& v); +TORCH_API ExprHandle sqrt(const ExprHandle& v); +TORCH_API ExprHandle rsqrt(const ExprHandle& v); +TORCH_API ExprHandle ceil(const ExprHandle& v); +TORCH_API ExprHandle floor(const ExprHandle& v); +TORCH_API ExprHandle round(const ExprHandle& v); +TORCH_API ExprHandle trunc(const ExprHandle& v); +TORCH_API ExprHandle frac(const ExprHandle& v); +TORCH_API ExprHandle lgamma(const ExprHandle& v); +TORCH_API ExprHandle atan2(const ExprHandle& v1, const ExprHandle& v2); +TORCH_API ExprHandle pow(const ExprHandle& v1, const ExprHandle& v2); +TORCH_API ExprHandle fmod(const ExprHandle& v1, const ExprHandle& v2); +TORCH_API ExprHandle remainder(const ExprHandle& v1, const ExprHandle& v2); +TORCH_API ExprHandle isnan(const ExprHandle& v1); +TORCH_API ExprHandle Relu(const ExprHandle& v1); + +TORCH_API ExprHandle +ifThenElse(const ExprHandle& c, const ExprHandle& t, const ExprHandle& f); + +TORCH_API ExprHandle expr_to_vec(ExprHandle v, int lanes); + +} // namespace torch::jit::tensorexpr diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/external_functions.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/external_functions.h new file mode 100644 index 0000000000000000000000000000000000000000..9710793583af40346506728a73e5ee16cdb752f9 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/external_functions.h @@ -0,0 +1,111 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +#define FOR_ALL_EXTERNAL_FUNCTIONS(_) \ + _(nnc_aten_adaptive_avg_pool2d) \ + _(nnc_aten_addmm) \ + _(nnc_aten_conv2d) \ + _(nnc_aten_conv1d) \ + _(nnc_aten_conv1d_out) \ + _(nnc_aten_dequantize) \ + _(nnc_aten_dequantize_out) \ + _(nnc_aten_embedding) \ + _(nnc_aten_matmul) \ + _(nnc_aten_mv) \ + _(nnc_aten_mm) \ + _(nnc_aten_mean) \ + _(nnc_aten_max_red) \ + _(nnc_aten_max_red_out) \ + _(nnc_aten_quantized_conv1d) \ + _(nnc_aten_quantized_conv1d_out) \ + _(nnc_aten_quantized_conv2d) \ + _(nnc_aten_quantized_conv2d_out) \ + _(nnc_aten_quantized_conv2d_relu) \ + _(nnc_aten_quantized_conv2d_relu_out) \ + _(nnc_aten_quantized_linear) \ + _(nnc_aten_quantized_linear_out) \ + _(nnc_aten_quantized_linear_relu) \ + _(nnc_aten_quantized_add) \ + _(nnc_aten_quantized_cat) \ + _(nnc_aten_quantized_mul) \ + _(nnc_aten_quantized_mul_out) \ + _(nnc_aten_quantized_mul_scalar) \ + _(nnc_aten_quantized_mul_scalar_out) \ + _(nnc_aten_quantized_relu) \ + _(nnc_aten_quantized_sigmoid) \ + _(nnc_aten_quantized_sigmoid_out) \ + _(nnc_aten_quantize_per_tensor) \ + _(nnc_aten_quantize_per_tensor_out) \ + _(nnc_aten_triangular_solve) \ + _(nnc_aten_upsample_nearest2d) \ + _(nnc_aten_upsample_nearest2d_out) \ + _(nnc_prepacked_conv2d_clamp_run) \ + _(nnc_prepacked_linear_clamp_run) + +#define DECLARE_EXTERNAL_FUNCTION(NAME) \ + TORCH_API void NAME( \ + int64_t bufs_num, \ + void** buf_data, \ + int64_t* buf_ranks, \ + int64_t* buf_dims, \ + int64_t* buf_strides, \ + int8_t* buf_dtypes, \ + int64_t args_num, \ + int64_t* extra_args); + +namespace torch::jit::tensorexpr { +struct QIData final { + double scale; + int64_t zero; + c10::ScalarType scalarType; +}; +std::vector constructTensors( + int64_t bufs_num, + void** buf_data, + int64_t* buf_ranks, + int64_t* buf_dims, + int64_t* buf_strides, + int8_t* buf_dtypes, + std::optional>> qdataArg = + std::nullopt); + +std::vector constructTensors2( + int64_t bufs_in_num, + void** buf_data, + int64_t* buf_ranks, + int64_t* buf_dims, + int64_t* buf_strides, + int8_t* buf_dtypes, + std::optional>> qdataArg = + std::nullopt, + size_t bufs_out_num = 0); + +#ifdef C10_MOBILE +extern "C" { +#endif +void DispatchParallel( + int8_t* func, + int64_t start, + int64_t stop, + int8_t* packed_data) noexcept; + +FOR_ALL_EXTERNAL_FUNCTIONS(DECLARE_EXTERNAL_FUNCTION) +#if AT_MKLDNN_ENABLED() +DECLARE_EXTERNAL_FUNCTION(nnc_mkldnn_prepacked_conv_run); +#endif + +TORCH_API void nnc_aten_free(size_t bufs_num, void** ptrs) noexcept; + +#ifdef C10_MOBILE +} // extern "C" +#endif + +} // namespace torch::jit::tensorexpr + +#undef DECLARE_EXTERNAL_FUNCTION diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/external_functions_core.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/external_functions_core.h new file mode 100644 index 0000000000000000000000000000000000000000..95a2569c234487b02e1d8d6dfba2f8026772c70c --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/external_functions_core.h @@ -0,0 +1,25 @@ +#pragma once + +#include +#include +#include +#include + +namespace torch::jit::tensorexpr { + +#ifdef C10_MOBILE +extern "C" { +#endif +void DispatchParallel( + int8_t* func, + int64_t start, + int64_t stop, + int8_t* packed_data) noexcept; + +TORCH_API void nnc_aten_free(size_t bufs_num, void** ptrs) noexcept; + +#ifdef C10_MOBILE +} // extern "C" +#endif + +} // namespace torch::jit::tensorexpr diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/external_functions_registry.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/external_functions_registry.h new file mode 100644 index 0000000000000000000000000000000000000000..e2466a3deab30ccf2a96a4de69c84544714c3c77 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/external_functions_registry.h @@ -0,0 +1,57 @@ +#pragma once + +#include +#include +#include +#include + +namespace torch::jit::tensorexpr { + +// The external functions that could be called from NNC must have the same +// signature defined by `NNCExternalFunction`. +// +// Why this signature? +// It was picked for two reasons: 1) it should be generic enough to represent +// most of the ops we might want to call, 2) it should be possible to generate a +// code for this call in LLVM codegen. +// The first 5 parameters allow to pass any number of contiguous CPU tensors in +// case we need to run aten ops (TODO: support different devices). The first +// buffer in the array is assumed to be the output buffer. We couldn't use +// `at::Tensor` (or `c10::IValue`) type there directly as it would mean that +// we'd need to declare it in LLVM codegen in LLVM IR form, which would be very +// cumbersome and hard to maintain. Note that the dimensions of all tensors are +// concatenated into a single array buf_dims. We do not need to pass its length, +// since it can be deduced from total number of buffers and their ranks. +// +// The last 2 arguments allow to pass any non-tensor arguments encoded as an +// array of int64_t values. The way they are encoded is not specified and could +// be arbitrary - whatever the most convenient for the specific bridge function +// is. +// +// The bridge functions must not throw exceptions - properly propagating them +// from the generated code is too cumbersome, and thus all calls to functions +// that could throw must be wrapped with try-catch blocks. +using NNCExternalFunction = void (*)( + int64_t bufs_num, + void** buf_data, + int64_t* buf_ranks, + int64_t* buf_dims, + int64_t* buf_strides, + int8_t* buf_dtypes, + int64_t args_num, + int64_t* extra_args); + +// Return a global map "function-name" -> "function-pointer" for all registered +// in NNC external functions +TORCH_API std::unordered_map& +getNNCFunctionRegistry(); + +// To register a new external function in NNC one needs to create an instance of +// this struct +struct RegisterNNCExternalFunction { + RegisterNNCExternalFunction(const std::string& name, NNCExternalFunction fn) { + getNNCFunctionRegistry()[name] = fn; + } +}; + +} // namespace torch::jit::tensorexpr diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/fwd_decls.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/fwd_decls.h new file mode 100644 index 0000000000000000000000000000000000000000..84c34a278a09991e2d5e05dfa879e2b0a13cb1c2 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/fwd_decls.h @@ -0,0 +1,129 @@ +#pragma once +#include +#include + +namespace torch { +namespace jit { +namespace tensorexpr { + +template +using NodePtr = std::shared_ptr; + +template +NodePtr to(const NodePtr& x) { + return std::dynamic_pointer_cast(x); +} + +template +NodePtr static_to(NodePtr x) { + return std::static_pointer_cast(x); +} + +template +NodePtr alloc(Args&&... args) { + return std::make_shared(std::forward(args)...); +} + +class Buf; +class Expr; +class Stmt; +class Var; + +using BufPtr = NodePtr; +using ExprPtr = NodePtr; +using StmtPtr = NodePtr; +using VarPtr = NodePtr; + +class ExprHandle; +class VarHandle; +class BufHandle; + +class Add; +class And; +class BitCast; +class Broadcast; +class Cast; +class CompareSelect; +class Div; +class IfThenElse; +class Intrinsics; +class Let; +class Load; +class Lshift; +class Max; +class MaxTerm; +class Min; +class MinTerm; +class Mod; +class Mul; +class Or; +class Polynomial; +class Ramp; +class ReduceOp; +class RoundOff; +class Rshift; +class Store; +class Sub; +class Term; +class Xor; +using AddPtr = NodePtr; +using AndPtr = NodePtr; +using BitCastPtr = NodePtr; +using BroadcastPtr = NodePtr; +using CastPtr = NodePtr; +using CompareSelectPtr = NodePtr; +using DivPtr = NodePtr
; +using IfThenElsePtr = NodePtr; +using IntrinsicsPtr = NodePtr; +using LetPtr = NodePtr; +using LoadPtr = NodePtr; +using LshiftPtr = NodePtr; +using MaxPtr = NodePtr; +using MaxTermPtr = NodePtr; +using MinPtr = NodePtr; +using MinTermPtr = NodePtr; +using ModPtr = NodePtr; +using MulPtr = NodePtr; +using OrPtr = NodePtr; +using PolynomialPtr = NodePtr; +using RampPtr = NodePtr; +using ReduceOpPtr = NodePtr; +using RoundOffPtr = NodePtr; +using RshiftPtr = NodePtr; +using StorePtr = NodePtr; +using SubPtr = NodePtr; +using TermPtr = NodePtr; +using XorPtr = NodePtr; + +class Allocate; +class AtomicAdd; +class Block; +class Cond; +class ExternalCall; +class ExternalCallWithAlloc; +class For; +class Free; +class FreeExt; +class PlacementAllocate; +class SyncThreads; +using AllocatePtr = NodePtr; +using AtomicAddPtr = NodePtr; +using BlockPtr = NodePtr; +using CondPtr = NodePtr; +using ExternalCallPtr = NodePtr; +using ExternalCallWithAllocPtr = NodePtr; +using ForPtr = NodePtr; +using FreePtr = NodePtr; +using FreeExtPtr = NodePtr; +using PlacementAllocatePtr = NodePtr; +using SyncThreadsPtr = NodePtr; + +#define IMM_DECLARE(Type, Name) \ + class Name##Imm; \ + using Name##ImmPtr = NodePtr; +AT_FORALL_SCALAR_TYPES_AND3(Bool, Half, BFloat16, IMM_DECLARE); +#undef IMM_DECLARE + +} // namespace tensorexpr +} // namespace jit +} // namespace torch diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/graph_opt.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/graph_opt.h new file mode 100644 index 0000000000000000000000000000000000000000..95bab317d0a0d0790ce3c23d78c44b0a67ba2fc8 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/graph_opt.h @@ -0,0 +1,111 @@ +#pragma once + +#include + +namespace torch::jit::tensorexpr { + +// Optimize aten::cat ops in the given subgraph. +// +// Moving users of cat to its inputs. +// Cat ops get lowered into multiple loops, one per input. When the result +// of cat is used by some other op, it results in a situation where inlining +// of cat does not happen. This in turn results in intermediate buffers +// being created for the result of cat, since it is not inlined. +// +// For example, consider the following graph: +// graph(%x : Float(10, strides=[1], device=cpu), +// %y : Float(20, strides=[1], device=cpu)): +// %dim : int = prim::Constant[value=0]() +// %xy_list : Tensor[] = prim::ListConstruct(%x, %y) +// %cat : Float(60, strides=[1], device=cpu) = aten::cat(%xy_list, %dim) +// %5 : Float(60, strides=[1], device=cpu) = aten::log(%cat) +// return (%5))IR"; +// +// This will get lowered into: +// Allocate(aten_cat); +// for (...) +// aten_cat[...] = x[...] +// for (...) +// aten_cat[...] = y[...] +// for (...) +// aten_log[...] = log(aten_cat[...]) +// Free(aten_cat); +// Note that aten_cat is not inlined into aten_log and it results in +// an intermediate buffer allocation as well. +// +// Optimization: +// We move the ops that use the result of `cat` into its inputs whenever +// possible. +// +// The graph above will be transformed to: +// graph(%x : Float(10, strides=[1], device=cpu), +// %y : Float(20, strides=[1], device=cpu)): +// %3 : int = prim::Constant[value=0]() +// %7 : Float(10, strides=[1], device=cpu) = aten::log(%x) +// %8 : Float(20, strides=[1], device=cpu) = aten::log(%y) +// %9 : Tensor[] = prim::ListConstruct(%7, %8) +// %10 : Float(60, strides=[1], device=cpu) = aten::cat(%9, %3) +// return (%10) +// +// This will get lowered into: +// for (...) +// aten_cat[...] = log(x[...]) +// for (...) +// aten_cat[...] = log(y[...]) +// aten_cat is the output buffer here. + +bool OptimizeCat(const std::shared_ptr& graph); + +TORCH_API void annotateInputShapes( + const std::shared_ptr& graph, + const std::vector>& example_inputs); +TORCH_API std::shared_ptr removeUnusedSelfArgument( + const std::shared_ptr& graph); +TORCH_API std::shared_ptr removeGraphOutput( + const std::shared_ptr& graph, + size_t idx); +TORCH_API std::shared_ptr replaceListOutputWithTuple( + const std::shared_ptr& graph); + +// Perform \p ITERS rounds of "trimming" for the given \p GRAPH. +// +// Trimming means that we try to remove a small portion of the graph while +// keeping it valid. This is useful for debugging when we try to find a minimal +// example reproducing the issue at hand. When ITERS is 0, the graph remains +// unchanged, when ITERS is a big number, the graph usually becomes empty. +TORCH_API std::shared_ptr trimGraph( + const std::shared_ptr& graph, + int64_t iters); + +// Scan all values in the given graph and replace each dimension with a size Xi +// present in \p SIZES with a symbolic shape Yi. Return a vector of symbol +// values [Y0, Y1, .., Yn]. +// +// For example: +// Input: +// graph(%x : Float(10, 20, 30, 40)): +// %y : Float(10, 20, 30, 40) = aten::relu(%x) +// return %y +// +// If we run makeShapesSymbolic(graph, {20, 40}), then we'll get: +// +// graph(%x : Float(10, SS(-3), 30, SS(-5))): +// %y : Float(10, SS(-3), 30, SS(-5)) = aten::relu(%x) +// return %y +// +// and get {-3, -5} as the return value. +TORCH_API std::vector makeShapesSymbolic( + std::shared_ptr& graph, + const std::vector& sizes); + +// Inspect the graph and report whether it can be converted to TE IR. +// TODO: add error reporting for graphs that can't be converted. +TORCH_API bool isGraphCompilable(const std::shared_ptr& graph); + +// Examine the graph and (hackily) fill in missing tensor type info, such as +// scalar type, device, and strides. Ideally, this should be done by a proper +// dtype/device/shape propagation passes, but until they are ready we can use +// this, not always correct, workaround pass. +TORCH_API void fixupMissingShapeInfo(const std::shared_ptr& graph); + +} // namespace torch::jit::tensorexpr diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/half_support.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/half_support.h new file mode 100644 index 0000000000000000000000000000000000000000..82f7e0ff7c9a224c86100ede78e38abc7975aa8b --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/half_support.h @@ -0,0 +1,212 @@ +#pragma once + +#include +#include +#include +#include + +namespace torch::jit::tensorexpr { + +// Walk the Statement looking for Half size loads/stores. +class HalfChecker : public IRVisitor { + public: + HalfChecker(const std::vector& args) { + for (const auto& BA : args) { + hasHalf_ |= BA.dtype().scalar_type() == ScalarType::Half; + } + } + + bool hasHalf() const { + return hasHalf_; + } + + bool hasBFloat16() const { + return hasBFloat16_; + } + + void visit(const LoadPtr& v) override { + hasHalf_ |= v->dtype().scalar_type() == ScalarType::Half; + hasBFloat16_ |= v->dtype().scalar_type() == ScalarType::BFloat16; + IRVisitor::visit(v); + } + + void visit(const StorePtr& v) override { + hasHalf_ |= v->buf()->dtype().scalar_type() == ScalarType::Half; + hasBFloat16_ |= v->buf()->dtype().scalar_type() == ScalarType::BFloat16; + IRVisitor::visit(v); + } + + void visit(const HalfImmPtr& v) override { + hasHalf_ = true; + } + + void visit(const BFloat16ImmPtr& v) override { + hasBFloat16_ = true; + } + + void visit(const CastPtr& v) override { + hasHalf_ |= v->dtype().scalar_type() == ScalarType::Half; + hasBFloat16_ |= v->dtype().scalar_type() == ScalarType::BFloat16; + IRVisitor::visit(v); + } + + private: + bool hasHalf_{false}; + bool hasBFloat16_{false}; +}; + +class HalfRewriter : public IRMutator { + ExprPtr mutate(const LoadPtr& v) override { + ExprPtr child = IRMutator::mutate(v); + if (!isHalf(child)) { + return child; + } + + ExprPtr ret = alloc( + child->dtype().cloneWithScalarType(ScalarType::Float), child); + + inserted_half_casts_.insert(ret); + return ret; + } + + StmtPtr mutate(const StorePtr& v) override { + // Since mutation changes the `value()` expression in-place, we need to + // get the dtype of the `value()` before that is mutated. + auto newType = v->value()->dtype(); + ExprPtr new_val = v->value()->accept_mutator(this); + auto bufType = v->buf()->dtype(); + + if (isHalf(newType.scalar_type())) { + new_val = alloc(newType, new_val); + inserted_half_casts_.insert(new_val); + } + + // The scalar_type of value is not Half while the buf is Half + if (!isHalf(newType.scalar_type()) && isHalf(bufType.scalar_type())) { + new_val = alloc( + newType.cloneWithScalarType(bufType.scalar_type()), new_val); + inserted_half_casts_.insert(new_val); + } + + v->set_value(new_val); + return v; + } + + ExprPtr mutate(const HalfImmPtr& v) override { + return alloc(kFloat, v); + } + + ExprPtr mutate(const BFloat16ImmPtr& v) override { + return alloc(kFloat, v); + } + + ExprPtr mutate(const CastPtr& v) override { + ExprPtr child = v->src_value()->accept_mutator(this); + + // just don't allow half casts we didn't insert. + if (isHalf(v)) { + if (inserted_half_casts_.count(v) < 1) { + v->set_src_value(child); + v->set_dtype(v->dtype().cloneWithScalarType(c10::kFloat)); + return v; + } + } + + // Remove Half(Float()) and friends. + CastPtr cast_child = to(child); + if (cast_child) { + auto cast_to_double = v->dtype().scalar_type() == ScalarType::Double; + auto from_half = isHalf(cast_child->src_value()); + // Cannot simplify the double(float(half)) to double(half) as NNC does + // not support cast BF16 to double directly. + auto not_cast_half_to_doulbe = !(cast_to_double && from_half); + if (v->dtype().is_floating_point() && + cast_child->dtype().is_floating_point() && not_cast_half_to_doulbe) { + return alloc(v->dtype(), cast_child->src_value()); + } + } + + if (child == v->src_value()) { + return v; + } + + return alloc(v->dtype(), child); + } + + StmtPtr mutate(const LetPtr& v) override { + if (isHalf(v->var()->dtype().scalar_type())) { + VarPtr load_new_var = alloc(v->var()->name_hint(), kFloat); + ExprPtr new_value = alloc( + v->var()->dtype().cloneWithScalarType(ScalarType::Float), + v->value()->accept_mutator(this)); + var_map[v->var()] = load_new_var; + + return alloc(load_new_var, new_value); + } + + return IRMutator::mutate(v); + } + + ExprPtr mutate(const VarPtr& v) override { + auto it = var_map.find(v); + if (it != var_map.end()) { + return it->second; + } + + return v; + } + + template + ExprPtr mutateArithmetic(T v) { + IRMutator::mutate(v); + if (isHalf(v)) { + v->set_dtype(v->dtype().cloneWithScalarType(c10::kFloat)); + } + return v; + } + + ExprPtr mutate(const AddPtr& v) override { + return mutateArithmetic(v); + } + ExprPtr mutate(const SubPtr& v) override { + return mutateArithmetic(v); + } + ExprPtr mutate(const MulPtr& v) override { + return mutateArithmetic(v); + } + ExprPtr mutate(const DivPtr& v) override { + return mutateArithmetic(v); + } + ExprPtr mutate(const MaxPtr& v) override { + return mutateArithmetic(v); + } + ExprPtr mutate(const MinPtr& v) override { + return mutateArithmetic(v); + } + ExprPtr mutate(const CompareSelectPtr& v) override { + return mutateArithmetic(v); + } + ExprPtr mutate(const BroadcastPtr& v) override { + return mutateArithmetic(v); + } + ExprPtr mutate(const IfThenElsePtr& v) override { + return mutateArithmetic(v); + } + ExprPtr mutate(const IntrinsicsPtr& v) override { + return mutateArithmetic(v); + } + + private: + static bool isHalf(ScalarType st) { + return st == ScalarType::Half || st == ScalarType::BFloat16; + } + + static bool isHalf(const ExprPtr& v) { + return isHalf(v->dtype().scalar_type()); + } + + std::unordered_set inserted_half_casts_; + std::unordered_map var_map; +}; + +} // namespace torch::jit::tensorexpr diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/hash_provider.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/hash_provider.h new file mode 100644 index 0000000000000000000000000000000000000000..b50b4bfeabfbdb97fde305053ecfbc2f833cbec0 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/hash_provider.h @@ -0,0 +1,281 @@ +#pragma once + +#include +#include +#include +#include + +#include + +namespace torch::jit::tensorexpr { + +struct TORCH_API SimplifierHashType { + SimplifierHashType() = default; + explicit SimplifierHashType(size_t s) : _h(s) {} + + bool operator==(const SimplifierHashType& other) const; + bool operator!=(const SimplifierHashType& other) const; + bool operator<(const SimplifierHashType& other) const; + bool operator==(const size_t other) const; + bool operator!=(const size_t other) const; + + size_t _h{0}; +}; + +} // namespace torch::jit::tensorexpr + +namespace std { +template <> +struct hash { + size_t operator()(const torch::jit::tensorexpr::SimplifierHashType& k) const { + return k._h; + } +}; + +} // namespace std + +namespace torch::jit::tensorexpr { + +#define CACHE_GUARD() \ + if (cachedHash(v)) { \ + return; \ + } + +class Term; +class Polynomial; + +/* Expression hasher providing comparable values representing sub-exprs. + * Uses memoization to avoid excessive recursion. */ +class TORCH_API HashProvider : public IRVisitor { + public: + template + SimplifierHashType hash(T e) { + e->accept(this); + return hashOf(e); + } + + bool cachedHash(const ExprPtr& e) { + return exprToHash_.find(e) != exprToHash_.end(); + } + bool cachedHash(const StmtPtr& s) { + return stmtToHash_.find(s) != stmtToHash_.end(); + } + + void clearCache() { + exprToHash_.clear(); + stmtToHash_.clear(); + } + + void visit(const AddPtr& v) override; + void visit(const SubPtr& v) override; + void visit(const MulPtr& v) override; + void visit(const DivPtr& v) override; + void visit(const ModPtr& v) override; + void visit(const RoundOffPtr& v) override; + void visit(const MaxPtr& v) override; + void visit(const MinPtr& v) override; + void visit(const AndPtr& v) override; + void visit(const OrPtr& v) override; + void visit(const XorPtr& v) override; + void visit(const LshiftPtr& v) override; + void visit(const RshiftPtr& v) override; + void visit(const CompareSelectPtr& v) override; + +#define IMM_VISIT(Type, Name) \ + void visit(const Name##ImmPtr& v) override { \ + CACHE_GUARD(); \ + putHash(v, hash_combine(#Name, v->value())); \ + } + AT_FORALL_SCALAR_TYPES_AND3(Bool, Half, BFloat16, IMM_VISIT); +#undef IMM_VISIT + + void visit(const CastPtr& v) override; + void visit(const VarPtr& v) override; + void visit(const RampPtr& v) override; + void visit(const LoadPtr& v) override; + void visit(const StorePtr& v) override; + void visit(const BlockPtr& v) override; + void visit(const ForPtr& v) override; + void visit(const BroadcastPtr& v) override; + void visit(const IfThenElsePtr& v) override; + void visit(const IntrinsicsPtr& v) override; + void visit(const AllocatePtr& v) override; + void visit(const FreePtr& v) override; + void visit(const CondPtr& v) override; + void visit(const TermPtr& v) override; + void visit(const PolynomialPtr& v) override; + void visit(const MaxTermPtr& v) override; + void visit(const MinTermPtr& v) override; + + template + SimplifierHashType hash_combine(const Types&... args) { + SimplifierHashType seed; + _hash_combine(seed, args...); + return seed; + } + + private: + SimplifierHashType hashOf(const ExprPtr& e) { + auto it = exprToHash_.find(e); + if (it != exprToHash_.end()) { + return it->second; + } + + // As a failsafe fall back to IRPrinter. + std::stringstream ss; + IRPrinter printer(ss); + e->accept(&printer); + SimplifierHashType hash = SimplifierHashType(te_hash(ss.str())); + putHash(e, hash); + + return hash; + } + + SimplifierHashType hashOf(const StmtPtr& s) { + auto it = stmtToHash_.find(s); + if (it != stmtToHash_.end()) { + return it->second; + } + + // As a failsafe fall back to IRPrinter. + std::stringstream ss; + IRPrinter printer(ss); + s->accept(&printer); + SimplifierHashType hash = SimplifierHashType(te_hash(ss.str())); + putHash(s, hash); + + return hash; + } + + // Hash funcs for various types, numbers are random. + template + void _hash_combine(SimplifierHashType& seed, const T& val) { + seed._h ^= te_hash(val) + 0x1f752c19 + (seed._h << 7) + (seed._h >> 4); + } + + void _hash_combine(SimplifierHashType& seed, const char* val) { + seed._h ^= te_hash(val) + 0x1f752c19 + (seed._h << 7) + (seed._h >> 4); + } + + // at:::Half doesn't have a prime_number_hash, so cast to short. + void _hash_combine(SimplifierHashType& seed, const at::Half& val) { + seed._h ^= + te_hash((uint16_t)val) + 0x1f752c19 + (seed._h << 7) + (seed._h >> 4); + } + + void _hash_combine(SimplifierHashType& seed, const Dtype& val) { + seed._h ^= te_hash(val.ToCppString()) + 0x1f752c19 + (seed._h << 7) + + (seed._h >> 4); + } + + void _hash_combine(SimplifierHashType& seed, ExprPtr e) { + _hash_combine(seed, hash(std::move(e))); + } + + template + void _hash_combine( + SimplifierHashType& seed, + const T& val, + const Types&... args) { + _hash_combine(seed, val); + _hash_combine(seed, args...); + } + + void putHash(const ExprPtr& e, SimplifierHashType h) { + auto res = exprToHash_.emplace(e, h); + if (res.second == false) { + // This is always a logic bug since we should check the cache first. + throw std::runtime_error("hash collision"); + } + } + void putHash(const StmtPtr& s, SimplifierHashType h) { + auto res = stmtToHash_.emplace(s, h); + if (res.second == false) { + // This is always a logic bug since we should check the cache first. + throw std::runtime_error("hash collision"); + } + } + + std::unordered_map exprToHash_; + std::unordered_map stmtToHash_; + UniqueNameManager name_manager_; + + size_t te_hash(SimplifierHashType val) { + return val._h; + } + + size_t te_hash(int64_t val) { + // put the thing down. + size_t h = val ^ 0x647AA4D20C0B; + // bit flip it. + size_t h2 = ~h; + // and reverse byte order. + size_t h3 = 0; + for (unsigned int i = 0; i < 64; i += 8) { + h3 |= ((h2 >> i) & 0xFF) << (64 - i - 8); + } + return h3; + } + + size_t te_hash(int32_t val) { + int64_t v2 = val; + return te_hash(v2); + } + + size_t te_hash(uint32_t val) { + int64_t v2 = val; + return te_hash(v2); + } + + size_t te_hash(uint64_t val) { + int64_t v2 = val; + return te_hash(v2); + } + + size_t te_hash(int16_t val) { + int64_t v2 = val; + return te_hash(v2); + } + + size_t te_hash(std::string val) { + size_t hash{0}; + int64_t intval{0}; + int64_t s = val.size() - 1; + while (s >= 0) { + for (unsigned int i = 0; i < 8; ++i) { + if (s < 0) + break; + int64_t c = val[s]; + intval |= (c << (i * 8)); + + s--; + } + hash ^= te_hash(intval); + intval = 0; + } + + return hash; + } + + size_t te_hash(double d) { + int64_t* n = reinterpret_cast(&d); + return te_hash(*n); + } + + size_t te_hash(float d) { + int32_t* n = reinterpret_cast(&d); + return te_hash(*n); + } + + size_t te_hash(at::Half d) { + int16_t* n = reinterpret_cast(&d); + return te_hash(*n); + } + + size_t te_hash(at::BFloat16 d) { + int16_t* n = reinterpret_cast(&d); + return te_hash(*n); + } +}; + +} // namespace torch::jit::tensorexpr diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/intrinsic_symbols.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/intrinsic_symbols.h new file mode 100644 index 0000000000000000000000000000000000000000..7508090f93060865cbd9cb5b48c0cfa34bc1b72a --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/intrinsic_symbols.h @@ -0,0 +1,22 @@ +#pragma once + +#ifdef TORCH_ENABLE_LLVM +#include + +namespace torch { +namespace jit { +namespace tensorexpr { + +struct SymbolAddress { + const char* symbol; + void* address; + + SymbolAddress(const char* sym, void* addr) : symbol(sym), address(addr) {} +}; + +c10::ArrayRef getIntrinsicSymbols(); + +} // namespace tensorexpr +} // namespace jit +} // namespace torch +#endif // TORCH_ENABLE_LLVM diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/ir_mutator.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/ir_mutator.h new file mode 100644 index 0000000000000000000000000000000000000000..7eea01522d6f2d43428c9ab33ca7c701fba2470a --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/ir_mutator.h @@ -0,0 +1,62 @@ +#pragma once +#include +#include +#include + +namespace torch::jit::tensorexpr { + +class TORCH_API IRMutator { + public: + virtual ~IRMutator() = default; + virtual ExprPtr mutate(const AddPtr& v); + virtual ExprPtr mutate(const SubPtr& v); + virtual ExprPtr mutate(const MulPtr& v); + virtual ExprPtr mutate(const DivPtr& v); + virtual ExprPtr mutate(const ModPtr& v); + virtual ExprPtr mutate(const MaxPtr& v); + virtual ExprPtr mutate(const MinPtr& v); + virtual ExprPtr mutate(const AndPtr& v); + virtual ExprPtr mutate(const OrPtr& v); + virtual ExprPtr mutate(const XorPtr& v); + virtual ExprPtr mutate(const LshiftPtr& v); + virtual ExprPtr mutate(const RshiftPtr& v); + virtual ExprPtr mutate(const CompareSelectPtr& v); +#define IMM_MUTATE_DECLARE(Type, Name) \ + virtual ExprPtr mutate(const Name##ImmPtr& v); + AT_FORALL_SCALAR_TYPES_AND3(Bool, Half, BFloat16, IMM_MUTATE_DECLARE); +#undef IMM_MUTATE_DECLARE + virtual ExprPtr mutate(const CastPtr& v); + virtual ExprPtr mutate(const BitCastPtr& v); + virtual ExprPtr mutate(const VarPtr& v); + virtual ExprPtr mutate(const BufPtr& v); + virtual ExprPtr mutate(const RampPtr& v); + virtual ExprPtr mutate(const LoadPtr& v); + virtual ExprPtr mutate(const BroadcastPtr& v); + virtual ExprPtr mutate(const IfThenElsePtr& v); + virtual ExprPtr mutate(const IntrinsicsPtr& v); + + virtual ExprPtr mutate(const TermPtr& v); + virtual ExprPtr mutate(const PolynomialPtr& v); + virtual ExprPtr mutate(const RoundOffPtr& v); + virtual ExprPtr mutate(const MaxTermPtr& v); + virtual ExprPtr mutate(const MinTermPtr& v); + + virtual ExprPtr mutate(const ReduceOpPtr& v); + + virtual StmtPtr mutate(const ForPtr& v); + virtual StmtPtr mutate(const BlockPtr& v); + virtual StmtPtr mutate(const StorePtr& v); + virtual StmtPtr mutate(const AtomicAddPtr& v); + virtual StmtPtr mutate(const SyncThreadsPtr& v); + virtual StmtPtr mutate(const ExternalCallPtr& v); + virtual StmtPtr mutate(const ExternalCallWithAllocPtr& v); + + virtual StmtPtr mutate(const AllocatePtr& v); + virtual StmtPtr mutate(const FreePtr& v); + virtual StmtPtr mutate(const FreeExtPtr& v); + virtual StmtPtr mutate(const PlacementAllocatePtr& v); + virtual StmtPtr mutate(const LetPtr& v); + virtual StmtPtr mutate(const CondPtr& v); +}; + +} // namespace torch::jit::tensorexpr diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/ir_simplifier.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/ir_simplifier.h new file mode 100644 index 0000000000000000000000000000000000000000..d1e57a1a5a1b92c4ecbdc24b487520aca3dd2471 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/ir_simplifier.h @@ -0,0 +1,546 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +#include + +/* IR Simplification + * + * Simplifies expressions in two stages: + * 1. Recursively traverse the map combining similar operations into Terms + * (interacted via Multiplication) and Polynomials (interacted via Addition). We + * reorder the components of each Term or Polynomial into a consistent order to + * allow combination or cancelling of like terms. + * 2. Once the format of the tree is minimal, expand each Term into a sequence + * of Muls, and each Polynomial into a sequence of Ads. + */ + +namespace torch::jit::tensorexpr { + +// A bunch of helpers for determine the Dtype of the output of a multi argument +// Term or Polynomial. +template +Dtype promoteTypesVec(const ExprPtr& s, const std::vector& v) { + Dtype t = s->dtype(); + bool first = true; + + for (const auto& e : v) { + if (first) { + t = Dtype(t.scalar_type(), e->dtype().lanes()); + first = false; + } + t = promoteTypes(t, e->dtype()); + } + return t; +} + +template +Dtype promoteTypesVec(const std::vector& v) { + if (v.empty()) { + throw malformed_input("empty list of types"); + } + + Dtype t = v[0]->dtype(); + for (const auto& e : v) { + t = promoteTypes(t, e->dtype()); + } + return t; +} + +template +Dtype promoteTypesMap( + const ExprPtr& s, + std::unordered_map& m) { + Dtype t = s->dtype(); + bool first = true; + for (auto& e : m) { + if (first) { + t = Dtype(t.scalar_type(), e.second->dtype().lanes()); + first = false; + } + t = promoteTypes(t, e.second->dtype()); + } + return t; +} + +template +Dtype promoteTypesVar(ExprType e) { + return e->dtype(); +} + +template +Dtype promoteTypesVar(ExprType e, Args... es) { + Dtype lhs = e->dtype(); + Dtype rhs = promoteTypesVar(es...); + if (e->isConstant()) { + lhs = Dtype(lhs.scalar_type(), rhs.lanes()); + } + + return promoteTypes(lhs, rhs); +} + +// Uses the evaluator to fold an Expression with constant terms. +// E.g. evaluateOp(Add(3, 4)) => 7. +// Expr v must not have any unbound Vars. +inline ExprPtr evaluateOp(const ExprPtr& v) { + ExprHandle handle(v); + ExprEval eval(handle); + + switch (v->dtype().scalar_type()) { +#define TYPE_CASE(Type, Name) \ + case ScalarType::Name: { \ + Type val = eval.value(); \ + return getImmediateByType(v->dtype().scalar_type(), val); \ + } + AT_FORALL_SCALAR_TYPES_AND3(Bool, Half, BFloat16, TYPE_CASE); +#undef TYPE_CASE + default: + LOG(FATAL) << "Unsupported datatype: " << v->dtype(); + return nullptr; + } + return nullptr; +} + +// A Term represents a grouping of Exprs through multiplication. +// E.g. product(scalar, *variables). +class Term : public ExprNode { + public: + template + Term(HashProvider& hasher, ExprPtr s, Args... ts) + : ExprNodeBase(promoteTypesVar(s, ts...)), scalar_(s), hasher_(hasher) { + CHECK(s->isConstant()); + addComponent(ts...); + sort(); + } + + Term(HashProvider& hasher, ExprPtr s, std::vector v) + : ExprNodeBase(promoteTypesVec(s, v)), + variables_(std::move(v)), + scalar_(std::move(s)), + hasher_(hasher) { + sort(); + } + + // Convenience constructor from a map of hash -> var, used when merging Terms. + Term( + HashProvider& hasher, + const ExprPtr& s, + std::unordered_map varmap) + : ExprNodeBase(promoteTypesMap(s, varmap)), scalar_(s), hasher_(hasher) { + for (auto& p : varmap) { + addComponent(p.second); + } + sort(); + } + + ExprPtr scalar() const { + return scalar_; + } + const std::vector& variables() const { + return variables_; + } + HashProvider& hasher() const { + return hasher_; + } + + // Produce a hash of just the variable components of this term, to determine + // if it can be combined with another term. + SimplifierHashType hashVars() const; + + private: + std::vector variables_; + ExprPtr scalar_; + HashProvider& hasher_; + + void addComponent() {} + void addComponent(ExprPtr e) { + variables_.push_back(std::move(e)); + } + template + void addComponent(ExprPtr e, Es&&... es) { + addComponent(std::move(e)); + addComponent(std::forward(es)...); + } + + // Sort by hash to normalize order of components. + void sort(); +}; + +// Polynomial represents a grouping of Exprs by addition. +// E.g. sum(*variables, scalar). +// This would better be called Expression, but, naming conflict... +class Polynomial : public ExprNode { + public: + template + Polynomial(HashProvider& hasher, ExprPtr s, Args... ts) + : ExprNodeBase(promoteTypesVar(s, ts...)), scalar_(s), hasher_(hasher) { + CHECK(s->isConstant()); + addTerm(ts...); + sort(); + } + + Polynomial(HashProvider& hasher, const ExprPtr& s, std::vector v) + : ExprNodeBase(promoteTypesVec(s, v)), + variables_(std::move(v)), + scalar_(s), + hasher_(hasher) { + sort(); + } + + // Helper constructor for list of terms with no scalar component. + Polynomial(HashProvider& hasher, std::vector terms) + : ExprNodeBase(promoteTypesVec(terms)), + variables_(std::move(terms)), + scalar_(getImmediateByType(dtype(), 0)), + hasher_(hasher) { + sort(); + } + + // Convenience constructor for map of hash -> var, used when merging + // Polynomials. + Polynomial( + HashProvider& hasher, + const ExprPtr& s, + std::unordered_map varmap) + : ExprNodeBase(promoteTypesMap(s, varmap)), scalar_(s), hasher_(hasher) { + for (auto& p : varmap) { + addTerm(p.second); + } + sort(); + } + + ExprPtr scalar() const { + return scalar_; + } + const std::vector& variables() const { + return variables_; + } + HashProvider& hasher() const { + return hasher_; + } + + SimplifierHashType hashVars() const; + + private: + std::vector variables_; + ExprPtr scalar_; + HashProvider& hasher_; + + void addTerm(TermPtr t) { + variables_.push_back(std::move(t)); + } + template + void addTerm(TermPtr t, Ts&&... ts) { + addTerm(std::move(t)); + addTerm(std::forward(ts)...); + } + + // Sort by hash to normalize order of terms. + void sort(); +}; + +class RoundOff : public BinaryOpNode { + public: + RoundOff(ExprPtr lhs, ExprPtr rhs) + : BinaryOpNode(std::move(lhs), std::move(rhs), IRNodeType::kOther) {} +}; + +class MaxTerm : public ExprNode { + public: + template + MaxTerm(HashProvider& hasher, ExprPtr s, bool p, Args... ts) + : ExprNodeBase(s ? promoteTypesVar(s, ts...) : promoteTypesVar(ts...)), + scalar_(s), + hasher_(hasher), + propagate_nans_(p) { + addComponent(ts...); + uniquefy(); + } + + MaxTerm( + HashProvider& hasher, + const ExprPtr& s, + bool p, + std::vector v) + : ExprNodeBase(s ? promoteTypesVec(s, v) : promoteTypesVec(v)), + variables_(std::move(v)), + scalar_(s), + hasher_(hasher), + propagate_nans_(p) { + uniquefy(); + } + + bool propagate_nans() const { + return propagate_nans_; + } + + ExprPtr scalar() const { + return scalar_; + } + const std::vector& variables() const { + return variables_; + } + HashProvider& hasher() const { + return hasher_; + } + + private: + std::vector variables_; + ExprPtr scalar_; + HashProvider& hasher_; + bool propagate_nans_; + + void addComponent() {} + void addComponent(ExprPtr e) { + variables_.push_back(std::move(e)); + } + template + void addComponent(ExprPtr e, Es&&... es) { + addComponent(std::move(e)); + addComponent(std::forward(es)...); + } + + // Uniquefy the terms using their hash. + void uniquefy(); +}; + +class MinTerm : public ExprNode { + public: + template + MinTerm(HashProvider& hasher, ExprPtr s, bool p, Args... ts) + : ExprNodeBase(s ? promoteTypesVar(s, ts...) : promoteTypesVar(ts...)), + scalar_(s), + hasher_(hasher), + propagate_nans_(p) { + addComponent(ts...); + uniquefy(); + } + + MinTerm( + HashProvider& hasher, + const ExprPtr& s, + bool p, + std::vector v) + : ExprNodeBase(s ? promoteTypesVec(s, v) : promoteTypesVec(v)), + variables_(std::move(v)), + scalar_(s), + hasher_(hasher), + propagate_nans_(p) { + uniquefy(); + } + + bool propagate_nans() const { + return propagate_nans_; + } + + ExprPtr scalar() const { + return scalar_; + } + const std::vector& variables() const { + return variables_; + } + HashProvider& hasher() const { + return hasher_; + } + + private: + std::vector variables_; + ExprPtr scalar_; + HashProvider& hasher_; + bool propagate_nans_; + + void addComponent() {} + void addComponent(ExprPtr e) { + variables_.push_back(std::move(e)); + } + template + void addComponent(ExprPtr e, Es&&... es) { + addComponent(std::move(e)); + addComponent(std::forward(es)...); + } + + // Uniquefy the terms using their hash. + void uniquefy(); +}; + +// Context-sensitive IR simplification +using VarBoundInfo = std::unordered_map; + +class TORCH_API SimplifierUnderContext : public IRMutator { + public: + ~SimplifierUnderContext() override = default; + // Add boundary info for index variables in for-loops + StmtPtr mutate(const ForPtr& v) override; + + ExprPtr mutate(const DivPtr& v) override; + ExprPtr mutate(const ModPtr& v) override; + ExprPtr mutate(const CompareSelectPtr& v) override; + ExprPtr mutate(const IfThenElsePtr& v) override; + + protected: + bool getLoopBoundInfo(const ExprPtr& expr, analysis::Bound* loop_bound_info); + + protected: + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + HashProvider hasher_; + VarBoundInfo var_bound_info_; +}; + +// Stmt simplification should occur in both modes. +class TORCH_API PolynomialBase : public IRMutator { + public: + ~PolynomialBase() override = default; + + StmtPtr mutate(const BlockPtr& v) override; + + StmtPtr mutate(const CondPtr& v) override; + + StmtPtr mutate(const ForPtr& v) override; + + // Trivially factorize terms by GCD of scalar components. + TermPtr factorizePolynomial(const PolynomialPtr& poly); + + HashProvider& hasher() { + return hasher_; + } + + protected: + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + HashProvider hasher_; +}; + +// Simplify the IR by combining arithmetic expressions over common terms. +class TORCH_API PolynomialTransformer : public PolynomialBase { + public: + using PolynomialBase::mutate; + // Inserts term into the provided map, in the case of a hash collision + // combines the term with the existing and updates the map. + void addOrUpdateTerm( + std::unordered_map& varmap, + const TermPtr& term); + + // Add Polynomial expressions, combining Terms representing the same + // variables. + ExprPtr addPolynomials(const PolynomialPtr& lhs, const PolynomialPtr& rhs); + + // Insert a new Term into the provided polynomial. If the new term has + // common variables to an existing term it is combined. + ExprPtr insertTerm(const PolynomialPtr& poly, const TermPtr& term); + + // Merge and simplify addition. + ExprPtr mutate(const AddPtr& v) override; + + // Subtract one term from another, cancelling if necessary. + ExprPtr subTerms(const TermPtr& lhs, TermPtr rhs, bool negated); + + // Subtract the RHS Polynomial from the LHS Polynomial, cancelling out where + // possible. + ExprPtr subPolynomials(const PolynomialPtr& lhs, const PolynomialPtr& rhs); + + // Merge and simplify subtraction. + ExprPtr mutate(const SubPtr& v) override; + + // Multiply two terms together, usually creating a new term with the variable + // lists concatenated. + TermPtr mulTerms(const TermPtr& lhs, const TermPtr& rhs); + + // Multiply a Polynomial by a Term. + ExprPtr polyByTerm(const PolynomialPtr& poly, const TermPtr& term); + + // Match a rounding pattern and create a RoundOff if found. + ExprPtr isRoundOff(const ExprPtr& lhs, const ExprPtr& rhs); + + // Inserts a new component into a term, simplifying if possible. + ExprPtr insertIntoTerm(const TermPtr& term, const ExprPtr& expr); + + // Merge and simplify multiplication. + ExprPtr mutate(const MulPtr& v) override; + + ExprPtr mutate(const DivPtr& v) override; + + ExprPtr mutate(const ModPtr& v) override; + + ExprPtr mutate(const AndPtr& v) override; + + ExprPtr mutate(const XorPtr& v) override; + + ExprPtr mutate(const LshiftPtr& v) override; + + ExprPtr mutate(const RshiftPtr& v) override; + + ExprPtr mutate(const MaxPtr& v) override; + + ExprPtr mutate(const MinPtr& v) override; + + ExprPtr mutate(const CompareSelectPtr& v) override; + + ExprPtr mutate(const IntrinsicsPtr& v) override; + + ExprPtr mutate(const CastPtr& v) override; + + ExprPtr mutate(const IfThenElsePtr& v) override; + + static ExprPtr simplify(ExprPtr e); + static ExprHandle simplify(const ExprHandle& e); + static StmtPtr simplify(StmtPtr e); +}; + +// Expands Terms and Polynomial expressions into primitive operations. +// Does some simple factorization and reordering. +class TORCH_API TermExpander : public PolynomialBase { + PolynomialTransformer* simplifier_; + std::set eliminated_allocations_; + + public: + using PolynomialBase::mutate; + TermExpander(PolynomialTransformer* simplifier) : simplifier_(simplifier) {} + bool check_safe() { + return eliminated_allocations_.empty(); + } + + // Expand Terms out to a series of Muls. + ExprPtr mutate(const TermPtr& v) override; + + // Expand Polynomials out to a series of Adds. + ExprPtr mutate(const PolynomialPtr& v) override; + + // Expand MaxTerms to a series of Max ops. + ExprPtr mutate(const MaxTermPtr& v) override; + + // Expand MinTerms to a series of Min ops. + ExprPtr mutate(const MinTermPtr& v) override; + + // Expand RoundOff to it's component: Mul(Div(lhs, rhs), rhs). + ExprPtr mutate(const RoundOffPtr& v) override; + + // Eliminate zero length allocations. + StmtPtr mutate(const AllocatePtr& v) override; + StmtPtr mutate(const FreePtr& v) override; + + // Override to enable condition fusing. + BlockPtr fuseConditions(BlockPtr v); + StmtPtr fuseSyncThreads(BlockPtr block); + StmtPtr mutate(const BlockPtr& v) override; +}; + +class TORCH_API IRSimplifier { + public: + static StmtPtr simplify(StmtPtr s); + static ExprPtr simplify(ExprPtr e); + static ExprHandle simplify(const ExprHandle& e) { + return ExprHandle(simplify(e.node())); + } +}; + +// Flattens the buf and performs the simplifier on the flattened dims. +ExprPtr buf_flat_size(const BufPtr& v); +// Returns true if expressions A and B can be simplified to an equal expression. +TORCH_API bool exprEquals(const ExprPtr& A, const ExprPtr& B); + +} // namespace torch::jit::tensorexpr diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/ir_verifier.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/ir_verifier.h new file mode 100644 index 0000000000000000000000000000000000000000..020c01a23340e94872c6b45a66dff60628d5f8b9 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/ir_verifier.h @@ -0,0 +1,58 @@ +#pragma once + +#include +#include + +namespace torch { +namespace jit { +namespace tensorexpr { + +class Expr; +class ExprHandle; +class Mod; +class And; +class Or; +class Xor; +class Lshift; +class Rshift; +class CompareSelect; +class Ramp; +class Load; +class IfThenElse; +class Intrinsics; + +class Stmt; +class ExternalCall; +class Store; +class For; +class Block; + +class TORCH_API IRVerifier : public IRVisitor { + public: + IRVerifier() = default; + + void visit(const ModPtr& v) override; + void visit(const AndPtr& v) override; + void visit(const OrPtr& v) override; + void visit(const XorPtr& v) override; + void visit(const LshiftPtr& v) override; + void visit(const RshiftPtr& v) override; + void visit(const CompareSelectPtr& v) override; + void visit(const RampPtr& v) override; + void visit(const LoadPtr& v) override; + void visit(const IfThenElsePtr& v) override; + void visit(const IntrinsicsPtr& v) override; + + void visit(const ExternalCallPtr& v) override; + void visit(const StorePtr& v) override; + void visit(const ForPtr& v) override; + void visit(const BlockPtr& v) override; +}; + +TORCH_API void verify(const StmtPtr&); +TORCH_API void verify(const ExprPtr&); +TORCH_API void verify(const ExprHandle&); + +} // namespace tensorexpr +} // namespace jit +} // namespace torch diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/llvm_codegen.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/llvm_codegen.h new file mode 100644 index 0000000000000000000000000000000000000000..1d96b4dd0467e3e807aa6a4282c745f2daa7f637 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/llvm_codegen.h @@ -0,0 +1,143 @@ +#pragma once + +#ifdef TORCH_ENABLE_LLVM +#include + +#include +#include +#include + +#include + +#include +#include + +namespace torch { +namespace jit { +namespace tensorexpr { + +class LLVMCodeGenImpl; +class LLVMCodeGenCallee; + +class TORCH_API LLVMCodeGen : public CodeGen { + public: + explicit LLVMCodeGen( + StmtPtr stmt, + const std::vector& args, + at::Device device = at::kCPU, + const std::string& kernel_func_name = "func", + Dtype dtype = kInt, + std::optional triple = std::nullopt, + std::optional cpu = std::nullopt, + std::optional attrs = std::nullopt); + explicit LLVMCodeGen(StmtPtr stmt); + + LLVMCodeGen() = delete; + ~LLVMCodeGen() override; + + // Cleans up all the memory used during LLVM code generation pass except + // the generated kernel. After calling this method, users should not call + // methods like `getCodeText` that require the LLVMCodeGenImpl data. However, + // users can continue to call this kernel using `call` and `call_raw`. + void cleanup_memory(); + + TORCH_API void call(const std::vector& args) override; + TORCH_API void call_raw(const std::vector& args) override; + TORCH_API void call_with_numel(void** args, int64_t numel) override; + + at::Tensor empty_strided( + c10::IntArrayRef size, + c10::IntArrayRef stride, + std::optional dtype_opt, + std::optional layout_opt, + std::optional device_opt, + std::optional pin_memory_opt) override; + + template + T value() { + return value(nullptr); + } + + template + T value(std::vector& args) { + return value(args.data()); + } + + template + T value(void** args) { + T (*fp)(void**) = (T(*)(void**))getKernelAddress(callee_.get()); + T rv = fp(args); + return rv; + } + + std::string getCodeText(const std::string& attr = "") override; + + private: + void* getKernelAddress(LLVMCodeGenCallee* callee); + + std::unique_ptr callee_; + std::unique_ptr impl_; +}; + +struct TORCH_API LLVMCodeGenBuilder { + using BufferArg = CodeGen::BufferArg; + + LLVMCodeGenBuilder(StmtPtr stmt, std::vector args) + : stmt_(stmt), args_(std::move(args)) {} + + LLVMCodeGenBuilder& device(at::Device device) { + device_ = device; + return *this; + } + + LLVMCodeGenBuilder& kernelFuncName(std::string name) { + kernelFuncName_ = std::move(name); + return *this; + } + + LLVMCodeGenBuilder& dtype(Dtype d) { + dtype_ = d; + return *this; + } + + LLVMCodeGenBuilder& triple(std::string triple) { + triple_ = std::move(triple); + return *this; + } + + LLVMCodeGenBuilder& cpu(std::string cpu) { + cpu_ = std::move(cpu); + return *this; + } + + LLVMCodeGenBuilder& attrs(std::string attrs) { + attrs_ = std::move(attrs); + return *this; + } + + std::unique_ptr build() { + return std::make_unique( + stmt_, args_, device_, kernelFuncName_, dtype_, triple_, cpu_, attrs_); + } + + private: + StmtPtr stmt_; + std::vector args_; + at::Device device_ = at::kCPU; + std::string kernelFuncName_ = "func"; + Dtype dtype_ = kInt; + std::optional triple_ = std::nullopt; + std::optional cpu_ = std::nullopt; + std::optional attrs_ = std::nullopt; +}; + +TORCH_API std::optional& LLVMTargetTriple(); +TORCH_API std::optional& LLVMTargetCPU(); +TORCH_API std::optional& LLVMTargetAttrs(); +TORCH_API bool& LLVMAOTWorkflow(); + +} // namespace tensorexpr +} // namespace jit +} // namespace torch + +#endif // TORCH_ENABLE_LLVM diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/llvm_jit.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/llvm_jit.h new file mode 100644 index 0000000000000000000000000000000000000000..beadbdd5e537e7f054a70200af16a2f7a67c21fa --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/llvm_jit.h @@ -0,0 +1,77 @@ +#pragma once + +#ifdef TORCH_ENABLE_LLVM +#include +#include +#include +#include + +C10_DIAGNOSTIC_PUSH_AND_IGNORED_IF_DEFINED("-Wsuggest-override") +#include +C10_DIAGNOSTIC_POP() +#include +#include +#include + +#include +#include + +namespace torch { +namespace jit { +namespace tensorexpr { + +inline std::string formatError(llvm::Error&& err, const char* msg) { + static constexpr const char* defaultErrorMsg = + "Unexpected failure in LLVM JIT"; + std::string errorMsg(msg ? msg : defaultErrorMsg); + llvm::raw_string_ostream ss(errorMsg); + ss << ": " << err; + return ss.str(); +} + +template +T assertSuccess(llvm::Expected valOrErr, const char* msg = nullptr) { + TORCH_INTERNAL_ASSERT(valOrErr, formatError(valOrErr.takeError(), msg)); + return std::move(*valOrErr); +} + +inline void assertSuccess(llvm::Error err, const char* msg = nullptr) { + TORCH_INTERNAL_ASSERT(!err, formatError(std::move(err), msg)); +} + +} // namespace tensorexpr +} // namespace jit +} // namespace torch + +namespace llvm { +namespace orc { + +class PytorchLLVMJITImpl; + +class TORCH_API PytorchLLVMJIT { + public: + PytorchLLVMJIT( + std::optional triple, + std::optional cpu, + std::optional attrs); + ~PytorchLLVMJIT(); + + void addModule(std::unique_ptr M, std::unique_ptr C); + + JITSymbol findSymbol(const std::string Name); + + bool hasSymbol(const std::string& Name); + + TargetMachine& getTargetMachine(); + + const DataLayout& getDataLayout(); + + private: + // Use the PImpl idiom here to hide the no-rtti parts of the JIT structure. + std::unique_ptr impl_; +}; + +} // end namespace orc +} // end namespace llvm + +#endif // ENABLE LLVM diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/loopnest.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/loopnest.h new file mode 100644 index 0000000000000000000000000000000000000000..20614fea0bad9dafaf9190b1a931a8e24ed2b030 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/loopnest.h @@ -0,0 +1,616 @@ +#pragma once + +#include +#include +#include +#include + +#include +#include + +namespace torch::jit::tensorexpr { + +class Expr; +class Var; +class Buf; +class Tensor; +class Function; +class Stmt; +class For; +class Block; +class Store; +class Dtype; + +class TORCH_API LoopNest { + public: + // A constructor for building a LoopNest from a list of Tensors + LoopNest( + const std::vector& output_tensors, + const std::vector& tensors_to_compute); + + // A convenience constructor for the case when all tensors are output tensors + LoopNest(const std::vector& output_tensors); + + // A constructor for building a LoopNest from an Stmt and a list of output + // buffers. + LoopNest(StmtPtr stmt, std::unordered_set output_bufs); + + // A constructor for building a LoopNest from another loopnest. It clones the + // other loopnest's stmt. + LoopNest(const LoopNest& other); + + StmtPtr root_stmt() const { + return root_stmt_; + } + + std::vector getLoopStmtsFor(const Tensor&) const; + std::vector getLoopStmtsFor(const BufPtr&) const; + std::vector getLoopStmtsFor(StmtPtr) const; + StmtPtr getLoopBodyFor(const Tensor&) const; + StmtPtr getLoopBodyFor(BufPtr) const; + + // Returns the For stmt indexed by 'indices' in the 'root' For stmt. + //'indices' indicates the path to the returned loop from 'root' in AST, e.g., + // + // root: for(int i...){ + // j_loop: for (int j...){ + // k1_loop: for (int k1...){ + // A[i, j, k1] = .... + // } + // B[i, j] = ... + // k2_loop: for (int k2...){ + // A[i, j, k2] = ... + // } + // } + // } + // + // the path from 'root' to 'j_loop' is [0] + // the path from 'root' to 'k1_loop' is [0, 0] + // the path from 'root' to 'k2_loop' is [0, 2] + ForPtr getLoopAt(ForPtr root, const std::vector& indices) const; + + // Returns the For stmt that is immediately enclosing the given stmt. + static ForPtr getParentLoop(const StmtPtr& st); + + // Returns the list of For stmts corresponding to the loopnest that is + // enclosing the given stmt. + static std::vector getEnclosingLoopNest(const StmtPtr& st); + + // Returns a list of all Stmts that write to the given buf. + std::vector getAllWritesToBuf(BufPtr) const; + + // The following methods return the For loops that contain writes to + // the given buf. + // + // For example, consider the following code: + // for i1 + // for j1 + // a[i1,j1] = + // for i2 + // for j2 + // for k2 + // a[i2,j2] = + // for j3 + // a[i2,j3] = + + // Returns a list of For loops which directly contain a Stmt that writes + // to buf. + // For the above example: + // getAllInnermostLoopsWritingToBuf(a) => {j1, k2, j3} + std::vector getAllInnermostLoopsWritingToBuf(BufPtr) const; + + // Returns a list of For loopnests which contain a Stmt that writes to + // the given buf. Each loopnest here is a vector For loops. + // For the above example: + // getAllLoopNestsWritingToBuf(a) => {{i1,j1}, {i2,j2,k2}, {i2,j3}} + std::vector> getAllLoopNestsWritingToBuf(BufPtr) const; + + StmtPtr simplify(); + + // Sanitize variables and buffer names. + // The pass assigns predefined names for loop index variables + // (i,j,k,l,m,n,o,p,i1,j1,k1,...) and ensures these names are not conflicting + // anywhere. It also removes duplicates from other Buf nad Var names as well + // as replaces illegal characters in them with underscores. + // + // Note: since it's currently technically possible to use the same variable + // as index in two different loops, this transformation finds such cases and + // introduces new variables to avoid duplication. + static StmtPtr sanitizeNames(StmtPtr s); + + bool computeInline(const StmtPtr& s); + bool computeInline(const BufPtr& b); + void inlineIntermediateBufs(bool allow_duplicated_work); + + // Optimizes conditionals. + // + // Currently, only the following pattern of conditionals is optimized. + // This corresponds to the conditional format that is generated to handle + // `aten::cat` op. + // + // for (int i = 0; i < 20; i++) { + // A[i] = IfThenElse(i<5 ? 1 : 0, B[i], C[i-5]) + // } + // + // Constraints that must be satisfied for this optimization: + // * All conditions should be of the form "var < expr". + // * All conditions should have the same variable, say v. + // * The condition variable found should be the same as the inner-most + // loop variable. TODO: Remove this constraint. + // * If there are multiple stores that contain conditionals using the same + // loop variable, only the first conditional will be optimized. + // TODO: Remove this constraint. + bool optimizeConditionals(); + + // Splits the given loop into 2 nested loops with the given factor as the + // inner loop bound. If the factor does not evenly divide the loop bound, + // then the remaining iterations are extracted into a tail loop that is + // added after the given loop. + // + // For example, consider the following code: + // for (int i = 0; i < 100; ++i) { + // A[i] = + // } + // + // splitWithTail(i, 8, ...) will result in: + // for (int i_outer = 0; i_outer < 12; ++i_outer) { + // for (int i_inner = 0; i_inner < 8; ++i_inner) { + // A[i_outer * 8 + i_inner] = + // } + // } + // for (int i_tail = 0; i_tail < 4; ++i_tail) { + // A[i_tail + 96] = + // } + // + // The given loop will be transformed to the outer loop after splitting. + // So, the pointer to the input loop should be valid after splitting and + // will point to the outer loop. The `inner` and `tail` parameters will be + // set to point to the inner and tail loops that are generated. + static void splitWithTail( + const ForPtr& f, + int factor, + ForPtr* inner, + ForPtr* tail); + // A convenience wrapper when the caller does not need to access the + // split loops. + static void splitWithTail(const ForPtr& f, int factor); + + // Splits the given loop into 2 nested loops with the given factor as the + // inner loop bound. If the factor does not evenly divide the loop bound, + // then a conditional is inserted into the body to handle the remaining + // iterations appropriately. + // + // For example, consider the following code: + // for (int i = 0; i < 100; ++i) { + // A[i] = + // } + // + // splitWithMask(i, 8, ...) will result in: + // for (int i_outer = 0; i_outer < 13; ++i_outer) { + // for (int i_inner = 0; i_inner < 8; ++i_inner) { + // if (i_outer * 8 + i_inner < 100) { + // A[i_outer * 8 + i_inner] = + // } + // } + // } + // + // The given loop will be transformed to the outer loop after splitting. + // So, the pointer to the input loop should be valid after splitting and + // will point to the outer loop. The `inner` parameter will be set to point + // to the inner loop that is generated. + static void splitWithMask(const ForPtr& f, int factor, ForPtr* inner); + // A convenience wrapper when the caller does not need to access the + // split loops. + static void splitWithMask(const ForPtr& f, int factor); + + // The following methods support loop distribution. + // For example, consider the following code. This will be used to + // demonstrate the methods below. + // + // S0: for m + // S1: for i + // S2: A[i] = 0 + // S3: for j + // S4: A[i] = A[i] + + // S5: B[i] = A[i] + // S6: for k + // S7: B[i] = B[i] + + + // This method distributes the given loop over its body by splitting + // after every given pivot stmt. + // + // NOTE: Pivot stmts that are not in the given loop's body will be ignored. + // + // For the above example: + // distributeLoop(S1, {S3, S5}) + // will result in: + // S0: for m + // S1: for i + // S2: A[i] = 0 + // S3: for j + // S4: A[i] = A[i] + + // : for i + // S5: B[i] = A[i] + // : for i + // S6: for k + // S7: B[i] = B[i] + + static std::vector distributeLoop( + const ForPtr& loop, + const std::unordered_set& pivots); + + // This method distributes the given loop over every stmt in its body. + // + // For the above example: + // distributeLoop(S1) + // will result in: + // S0: for m + // S1: for i + // S2: A[i] = 0 + // : for i + // S3: for j + // S4: A[i] = A[i] + + // : for i + // S5: B[i] = A[i] + // : for i + // S6: for k + // S7: B[i] = B[i] + + static std::vector distributeLoop(const ForPtr& loop); + // Same as above, but also distribute parent loops. + // Returns the result of distributing the outermost loop. + // + // For the above example: + // distributeLoopAndParents(S1) will result in: + // S0: for m + // S1: for i + // S2: A[i] = 0 + // : for m + // : for i + // S3: for j + // S4: A[i] = A[i] + + // : for m + // : for i + // S5: B[i] = A[i] + // : for m + // : for i + // S6: for k + // S7: B[i] = B[i] + + static std::vector distributeLoopAndParents(const ForPtr& loop); + + // This method distributes the given loop over its body by splitting + // after every For stmt in its body. + // + // For the above example: + // distributeLoopOverInnerLoops(S1) + // will result in: + // S0: for m + // S1: for i + // S2: A[i] = 0 + // S3: for j + // S4: A[i] = A[i] + + // : for i + // S5: B[i] = A[i] + // S6: for k + // S7: B[i] = B[i] + + static std::vector distributeLoopOverInnerLoops(const ForPtr& loop); + // Same as above, but also distribute parent loops. + // Returns the result of distributing the outermost loop. + // + // For the above example: + // distributeLoopAndParentsOverInnerLoops(S1) + // will result in: + // S0: for m + // S1: for i + // S2: A[i] = 0 + // S3: for j + // S4: A[i] = A[i] + + // : for m + // : for i + // S5: B[i] = A[i] + // S6: for k + // S7: B[i] = B[i] + + static std::vector distributeLoopAndParentsOverInnerLoops( + const ForPtr& loop); + + // This method performs loop fusion. + // For example, consider the following code. + // + // S1: for m + // S2: A[m] = 0 + // S3: for j + // S4: A[m] = A[m] + + // S5: for n + // S5: B[n] = A[n] + // S6: for k + // S7: B[n] = B[n] + + // + // fuseLoops({S1, S5}), will return the following loop: + // S1: for m + // S2: A[m] = 0 + // S3: for j + // S4: A[m] = A[m] + + // S5: B[m] = A[m] + // S6: for k + // S7: B[m] = B[m] + + // + // This transformation is unsafe as it simply add all loops into the body of + // the first loop for fusion without correctness checks. + // + // Below are the two requirements to apply unsafeFuseLoops: + // * All the loops have the same parent. + // * There are no statements between these loops in their parent body. + static bool unsafeFuseLoops(const std::vector& loops, ForPtr* fused); + + // Loop fusion is done only when all the conditions below are satisfied. + // * All the loops have the same parent. + // * There are no statements between these loops in their parent body. + // * The start bounds are the same for all loops. + // * The stop bounds are the same for all loops. + // * Fusing the loops does not violate or add any dependencies. + static bool fuseLoops(const std::vector& loops, ForPtr* fused); + + static void reorderAxis(const ForPtr& a, const ForPtr& b); + + // Reorder the given list of loops according to the permutation specified. + // Here `permutation[i]` represents the position of the loop in the input + // which will end up at position `i` after the reorder. + // + // For example, consider the following code: + // for p + // for q + // for r + // for s + // A[p,q,r,s] = + // + // reorder({p, q, r, s}, {2, 3, 0, 1}) will return the list of loops in the + // following form: + // for r + // for s + // for p + // for q + // A[p,q,r,s] = + static std::vector reorder( + const std::vector& loops, + const std::vector& permutation); + + // Tile takes a 2d domain (x, y) and splits it into small rectangular blocks + // each with shape (x_factor, y_factor). The traversal over the domain turns + // into an outer iteration over the blocks and an inner traversal over all + // points in the block. + // Note that if x dim % x_factor or y dim % y_factor does not equal to 0, the + // loop body will generate corresponding tailing loops. + // The transformation is in-place and returns 'xtail'. + // + // For example, consider the following code: + // for i: [0, 64) + // for j: [0, 64) + // for k: [0, 32) + // A[i, j] = B[i, k] + C[j, k] + // + // tile(i, j, 4, 8) will transform "i" for-stmt into the following nested + // loop: + // for i_outer: [0, 16) + // for j_outer: [0, 8) + // for i_inner: [0, 4) + // for j_inner: [0, 8) + // for k: [0, 32) + // A[i_outer * 4 + i_inner, j_outer * 8 + j_inner] = + // B[i_outer * 4 + i_inner, k] + C[j_outer * 8 + j_inner, k] + // + // tile(i, j, 4, 9) will transform "i" for-stmt into the following nested + // loop: + // for i_outer: [0, 16) + // for j_outer: [0, 7) + // for i_inner: [0, 4) + // for j_inner: [0, 9) + // for k: (0, 32) + // A[i_outer * 4 + i_inner, j_outer * 9 + j_inner] = + // B[i_outer * 4 + i_inner, k] + C[j_outer * 9 + j_inner, k] + // for j_tail: [0, 1) + // for i_inner: [0, 4) + // for k: (0, 32) + // A[i_outer * 4 + i_inner, 7 * 9 + j_tail] = + // B[i_outer * 4 + i_inner, k] + C[7 * 9 + j_tail, k] + ForPtr tile(const ForPtr& x, const ForPtr& y, int x_factor, int y_factor); + + // Returns true if the given loops are perfectly nested, i.e., every loop + // (except the innermost) should have exactly one statement in its body + // and that statement must be the next inner loop. + static bool areLoopsPerfectlyNested(const std::vector& loops); + + // Returns true if the given loop has a loop-carried dependence. + static bool hasLoopCarriedDependence(const ForPtr& loop); + + // Unrolls all the iterations of the given loop. + // Requires that the loop bounds are constant. + static void fullUnroll(const ForPtr& f, StmtPtr* unrolled); + static void fullUnroll(const ForPtr& f); + + // Unrolls the given loop for the specified factor. + // This does not require constant bounds for the loop being unrolled. + static void unroll(const ForPtr& f, int factor, ForPtr* tail); + static void unroll(const ForPtr& f, int factor); + + static bool normalize(const ForPtr& f); + static bool isNormalized(const ForPtr& f); + + static bool flatten(const std::vector& f, ForPtr* flattened); + static bool flatten(const std::vector& f); + + // Compresses the given buffer based on its use in the given Stmts. + // + // NOTE: This API assumes that there are no accesses to the given buffer + // outside the given statement. So, this should be called with the entire + // kernel statement to avoid incorrect buffer compressions. + // + // For example, given the input: + // + // for (int i = 0; i < 100; ++i) { + // for (int j = 0; j < 200; ++j) { + // A[i,j] = sin(i*j) + // } + // for (int j = 0; j < 199; ++j) { + // B[i,j] = A[i,j] + A[i, j+1] + // } + // } + // + // compressBuffer(A, ...) will compress buffer A from + // [100, 200] to [1, 200] and modify the code as follows: + // + // for (int i = 0; i < 100; ++i) { + // for (int j = 0; j < 200; ++j) { + // A[0,j] = sin(i*j) + // } + // for (int j = 0; j < 199; ++j) { + // B[i,j] = A[0,j] + A[0, j+1] + // } + // } + static void compressBuffer(const BufPtr& buf, const StmtPtr& stmt); + + // Compresses all buffers in the given statement. + // + // NOTE: This API assumes that there are no accesses to buffers outside + // the given statement. So, this should be called with the entire + // kernel statement to avoid incorrect buffer compressions. + // + // TODO: Add an IR verifier check to detect invalidly compressed buffers. + static void compressAllBuffers(const StmtPtr& stmt); + + // Get 'num' loops from the loopnest starting at 'f'. + static std::vector getLoopStmtsInLoopNest( + const ForPtr& f, + size_t num); + + // LoopOptions are propagated to tail. + static void sliceHead( + const ForPtr& f, + int factor, + ForPtr* head, + ForPtr* tail); + static void sliceHead(const ForPtr& f, int factor); + // LoopOptions are propagated to head. + static void sliceTail( + const ForPtr& f, + int factor, + ForPtr* head, + ForPtr* tail); + static void sliceTail(const ForPtr& f, int factor); + + using AccessResult = std::pair; + // Insert a cache for the consumer's usages of the buffer produced in + // consumer, and redirect reads and writes in the consumer to that cache. + // Returns a pair of the new cache buffer, and the new rewritten consumer. + static AccessResult cacheAccesses( + const BufPtr& producer, + const std::string& name, + const StmtPtr& consumer); + + // Insert a temporary computation of statement S in the scope of loop AT. + // S is assumed to be a Store or a Block containing a Store. Along with the + // computation itself, this transformation inserts Alloc/Free statements for + // the temporary buffer used in the computation. + static void computeAt(const StmtPtr& s, const ForPtr& at); + + // Rfactor a reduction axis into a normal axis. + // + // Requirements: + // * S is the reduction store + // * S is the only statement in the innermost loop + // * There is at least two reduction arguments in S + // * OUTER_REDUCTION_FOR loop corresponds to the outermost reduction variable + // used in the store and all other reduction variables are index variables of + // children loops of OUTER_REDUCTION_FOR + // * OUTER_REDUCTION_FOR is a perfect loop nest, i.e. it has only loops + // corresponding to the other reduction variables and the store, nested into + // each other + // + // What it does: + // * Introduce a new buffer with an extra dimension of a size equal to the + // span of the loop OUTER_REDUCTION_FOR (the new buffer is returned via + // RFAC_BUF_PTR) + // * Insert an initialization store for the new buffer in + // OUTER_REDUCTION_FOR before its nested loop + // * Replace the reduction store to the original buffer with the reduction + // store to the temp buffer, removing the index var of OUTER_REDUCTION_FOR + // from reduction arguments + // * Insert a final reduction store over the extra dimension of the new + // buffer to the original buffer + // * Returns TRUE if the transformation succeeded and FALSE otherwise + // + // Example: + // Original IR: + // S1: for i # normal axis + // S2: X[i] = 0 + // S3: for j # reduction axis + // S4: for k # reduction axis + // S5: X[i] = ReduceOp(X[i] + Y[i,j,k], reduce_axis={j,k}) + // + // After RFACTOR(S5, S3) + // S1: for i # normal axis + // S2: X[i] = 0 + // S3: for j # reduction axis for X, normal axis for X_rfac + // X_rfac[i,j] = 0 + // S4: for k # reduction axis + // X_rfac[i,j] = ReduceOp(X_rfac[i,j] + Y[i,j,k], reduce_axis={k}) + // X[i] = ReduceOp(X[i] + X_rfac[i,j], reduce_axis={j}) + static bool rfactor(const StmtPtr& s, const ForPtr& outer_reduction_for); + static bool rfactor( + const StmtPtr& s, + const ForPtr& outer_reduction_for, + BufPtr* rfac_buf_ptr); + + // Vectorize the given loop. This method requires that the given loop + // does not perform a reduction. + // It returns true if vectorization is successful and false otherwise. + static bool vectorize(const ForPtr&); + + // Find the inner-most loops and vectorize them. Currently, this only works + // for the LLVM backend, when no reductions are involved. + void vectorizeInnerLoops(); + + void eliminateDeadStores(); + + void prepareForCodegen(); + + const std::unordered_set getInputBufs() const; + const std::unordered_set getOutputBufs() const { + return output_bufs_; + } + std::vector getIntermediateBufs() const; + + // Finds which is the outer For between a and b for loops. If neither of the 2 + // Fors is an ancestor of the other, it returns nullptr. + static ForPtr findOuterFor(ForPtr a, ForPtr b); + + private: + void initialize( + const std::vector& output_tensors, + const std::vector& tensors_to_compute); + + StmtPtr root_stmt_; + + std::unordered_set output_bufs_; +}; + +TORCH_API StmtPtr FlattenIndexes(const StmtPtr& s); + +// TODO: Revisit this once we decide on how dependencies analysis should look +// like. Maybe we would choose to use a different API and BufUse would be +// removed, or if we decide to keep it we need to properly document its API. +struct BufLoadOrStoreUse { + StmtPtr s; + bool isStore; +}; + +/* + * Returns a map ( Buf -> uses of this Buf), uses are represented as vectors of + * BufUse elements, which are StmtPtr and a bool isStore flag. The order of uses + * in the vectors reflects the order in which the uses appear in the given + * statement. + */ +std::unordered_map> findLoadOrStoreUses( + const StmtPtr& s); + +// replaces all invalid characters with underscore +TORCH_API std::string sanitizeName(const std::string& input_name); + +} // namespace torch::jit::tensorexpr diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/loopnest_randomization.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/loopnest_randomization.h new file mode 100644 index 0000000000000000000000000000000000000000..3f5f687416cb752aa32319680d49c928e1549fe4 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/loopnest_randomization.h @@ -0,0 +1,9 @@ +#pragma once + +namespace torch::jit::tensorexpr { + +// Applies a series of loop optimizations chosen randomly. This is only for +// testing purposes. This allows automatic stress testing of NNC loop +// transformations. +void loopnestRandomization(int64_t seed, LoopNest& l); +} // namespace torch::jit::tensorexpr diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/lowerings.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/lowerings.h new file mode 100644 index 0000000000000000000000000000000000000000..2f53a2c791d4d78247eb3bf03a7a11a6f68ab97e --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/lowerings.h @@ -0,0 +1,45 @@ +// This file defines classes for registering standard lowerings from JIT to TE +// IR. +#pragma once + +#include +#include +#include +#include +#include + +namespace torch::jit::tensorexpr { + +using ArgNone = std::monostate; +using BufList = std::vector; +using DoubleList = std::vector; +using IntList = std::vector; +using ArgValue = std::variant< + tensorexpr::BufHandle, + tensorexpr::VarHandle, + double, + int64_t, + bool, + BufList, + DoubleList, + IntList, + std::string, + ArgNone>; + +using NNCLoweringFunction = std::function&, + const std::vector&, + const std::vector&, + const std::optional&, + at::Device)>; + +TORCH_API FunctionSchemaMap& getNNCLoweringRegistry(); +TORCH_API NNCLoweringFunction getStandardLoweringFor(const std::string& op); + +struct RegisterNNCLoweringsFunction { + RegisterNNCLoweringsFunction( + const std::vector& schemas, + const NNCLoweringFunction& fn); +}; + +} // namespace torch::jit::tensorexpr diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/mem_dependency_checker.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/mem_dependency_checker.h new file mode 100644 index 0000000000000000000000000000000000000000..39202f487ad2de57b5e566bcd1e5cb9ac0fdd50e --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/mem_dependency_checker.h @@ -0,0 +1,409 @@ +#pragma once +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace torch::jit::tensorexpr::analysis { + +enum class AccessType { + Input, + Output, + Load, + Store, + Call, + AtomicAdd, + Alloc, + Free +}; +const char* AccessToString(AccessType a); + +class AccessInfo; +using DependencySet = std::unordered_set>; + +/* AccessInfo + * + * Represents a single bounded memory access to a buffer, for instance a Load or + * a Store. Holds information relating to the specific access and links to + * connected accesses in the dependency graph. + */ +class TORCH_API AccessInfo { + public: + AccessInfo( + size_t id, + AccessType type, + StmtPtr stmt, + VarPtr var, + IndexBounds bounds) + : id_(id), + type_(type), + stmt_(std::move(stmt)), + expr_(nullptr), + var_(std::move(var)), + bounds_(std::move(bounds)) {} + + AccessInfo( + size_t id, + AccessType type, + ExprPtr expr, + StmtPtr stmt, + VarPtr var, + IndexBounds bounds) + : id_(id), + type_(type), + stmt_(std::move(stmt)), + expr_(std::move(expr)), + var_(std::move(var)), + bounds_(std::move(bounds)) {} + + // Id is a unique int representing the order this access occurred in the + // graph. + size_t id() const { + return id_; + } + + // The type of the access (Load, Store, etc). + AccessType type() const { + return type_; + } + + // The enclosing Stmt this access represents. E.g. if this is a Store then + // Stmt is the Store itself, while if the access is caused by an Expr, this is + // the most immediate parent Stmt. + StmtPtr stmt() const { + return stmt_; + } + + // If the access is represented by an Expr (such as Load or Call) then this is + // it, otherwise it's nullptr. + ExprPtr expr() const { + return expr_; + } + + // The Var representing the underlying Buffer. + VarPtr var() const { + return var_; + } + + // A vector of Bounds representing the start and end expression for each + // dimension. + IndexBounds& bounds() { + return bounds_; + } + + // Each access that this depends upon, + // eg. if this is a Load, then it contains every Store that immediately + // contributes to a load of the bounds. + // or: if this is a Store, it contains all reads on the RHS of the Store. + const std::map>& dependencies() const { + return dependencies_; + } + + // Each access that depends on this one. + // ie. this access is present in the dependencies map of all accesses that are + // dependent. + std::map> dependents() const { + std::map> res; + for (const auto& kv : dependents_) { + res.emplace(kv.first, kv.second.lock()); + } + return res; + } + + // Returns the symbolic expression of the indices of this access. + std::vector getIndices() const; + + // Establishes a dependency or dependent relationship with another access. + void addDependency(const std::shared_ptr& write); + void addDependent(const std::shared_ptr& read); + + // helper for checking dependencies. + bool hasDependency(const std::shared_ptr& info) const; + + // Returns the set of all nodes that are direct (immediate) dependencies of + // this access. + DependencySet getDirectDependencies(); + // likewise, returns all nodes that directly depend on this one. + DependencySet getDirectDependents(); + + // Returns the full list of all nodes in the graph that this access depends + // on, and all nodes they depend on, and so forth, back to the inputs. + DependencySet getIndirectDependencies(); + // likewise, returns the full list of all nodes that depend on this node, and + // all nodes that depend on those nodes and so on down to the outputs. + DependencySet getIndirectDependents(); + + // Does this access represent a read of memory (Load, ReduceOp, Call, etc). + bool isRead() const; + // Does this access represent a write of memory (Store, etc). + bool isWrite() const; + + // Helpers for dumping accesses in various formats. + void print() const; + void dumpDOT(std::ostream& os) const; + const char* AccessTypeColour() const; + + private: + size_t id_; + AccessType type_; + StmtPtr stmt_; + ExprPtr expr_; + VarPtr var_; + IndexBounds bounds_; + + // Yes these should be sorted. + std::map> dependencies_; + std::map> dependents_; +}; + +using VarBoundMap = std::unordered_map; + +/* MemDependencyChecker analyses a IR fragment and builds a dependency graph of + * accesses contained within. + * + * It's possible to retrieve the entire graph in node-object form, or can be + * used as an oracle for answering dependency questions. e.g: + * + * analyzer.hasIndirectDependency(BufA, BufB); or, + * analyzer.hasDirectDependency(LoadA, StoreB); + */ +class TORCH_API MemDependencyChecker : public IRVisitor { + struct Scope; + + public: + MemDependencyChecker(); + MemDependencyChecker( + const std::unordered_set& inputs, + const std::unordered_set& outputs); + MemDependencyChecker( + const std::vector& inputs, + const std::vector& outputs); + + ~MemDependencyChecker() override = default; + + // Whether or not to allow loop execution order to influence dependency + // calculation. If the loop may later be parallelized you don't want this. + bool allowLoopExecutionOrderAnalysis(bool allow = true); + + // Dependency Checking API. + // The goal is to have enough overloads here so you don't really have to think + // about it. + + // Returns true if any read in A has a direct dependence on a write in B. + bool dependsDirectly(const StmtPtr& A, const StmtPtr& B); + bool dependsDirectly(const ExprPtr& A, const StmtPtr& B); + + // Returns true of the output depends directly on a write contained in B. + bool dependsDirectly(const BufPtr& output, const StmtPtr& B); + + // Returns true if a read in A depends directly on the provided input. + bool dependsDirectly(const StmtPtr& A, const BufPtr& input); + bool dependsDirectly(const ExprPtr& A, const BufPtr& input); + + // Outputs/inputs cannot depend directly. + + // Returns true if the access A has B as an immediate dependency. + bool dependsDirectly( + const std::shared_ptr& A, + const std::shared_ptr& B); + + // Returns true if any read in A has an ancestor write contained in B. + bool dependsIndirectly(const StmtPtr& A, const StmtPtr& B); + bool dependsIndirectly(const ExprPtr& A, const StmtPtr& B); + + // Returns true of the output depends indirectly on a write contained in B. + bool dependsIndirectly(const BufPtr& output, const StmtPtr& B); + + // Returns true if a read in A depends indirectly on the provided input. + bool dependsIndirectly(const StmtPtr& A, const BufPtr& input); + bool dependsIndirectly(const ExprPtr& A, const BufPtr& input); + + // returns true if the output uses any load of the input. + bool dependsIndirectly(const BufPtr& output, const BufPtr& input); + + // Returns true if the access A has a dependency chain to access B. + bool dependsIndirectly( + const std::shared_ptr& A, + const std::shared_ptr& B); + + // Returns the AccessInfo + std::shared_ptr accessFor(const StmtPtr& A) const; + std::shared_ptr accessFor(const ExprPtr& A) const; + + // Returns all AccessInfos. + std::unordered_set> accessesWithin( + const StmtPtr& A) const; + // TODO: this will return only the AccessInfo for A. It's included for + // completeness but be aware it wont return accesses used in the computation + // of A. + std::unordered_set> accessesWithin( + const ExprPtr& A) const; + + // Accesses relating to input and output buffers. + std::shared_ptr input(const BufPtr& B) const; + std::shared_ptr output(const BufPtr& B) const; + + // Returns the full history of reads and writes. + const std::vector>& getHistory() const; + + // Dumps the dependency graph in DOT format. + void dumpDAG(const std::string& filename) const; + + private: + // Node visitors. + void visit(const StorePtr& v) override; + void visit(const LoadPtr& v) override; + void visit(const ForPtr& v) override; + void visit(const CondPtr& v) override; + void visit(const IfThenElsePtr& v) override; + void visit(const CompareSelectPtr& v) override; + void visit(const BlockPtr& v) override; + void visit(const LetPtr& v) override; + void visit(const AtomicAddPtr& v) override; + void visit(const AllocatePtr& v) override; + void visit(const FreePtr& v) override; + + using BoundRelationship = std::pair>; + + // An internal struct holding the accesses found within a scope Block. + struct Scope { + Scope(BlockPtr b, std::shared_ptr p) + : block(std::move(b)), parent(std::move(p)) {} + + BlockPtr block; + std::shared_ptr parent; + + std::unordered_map shadowedVarBounds; + std::unordered_set localVars; + + std::vector> accesses_; + + std::unordered_map> openWrites_; + }; + std::shared_ptr currentScope_; + + bool allowExecutionOrderAnalysis_{false}; + + std::unordered_multimap> stmtToAccess_; + std::unordered_multimap> exprToAccess_; + std::unordered_map>> + scopeToAccesses_; + + VarBoundMap knownVarBounds_; + + // Finds all accesses that are reads within the scope of v. + template + DependencySet getAllReadsWithin(const StmtOrExprPtr& v) { + DependencySet reads; + auto insertAllReads = [&](const auto& nodes) { + for (const auto& l : nodes) { + auto bound = exprToAccess_.equal_range(l); + for (auto it = bound.first; it != bound.second; ++it) { + if (it->second->isRead()) { + reads.insert(it->second); + } + } + } + }; + + // Look for and insert accesses belonging to all nodes that act like + // reads. + insertAllReads(NodeFinder::find(v)); + insertAllReads(NodeFinder::find(v)); + + return reads; + } + + // Finds all accesses that are writes within the scope of v. + // Writes cannot occur in Exprs, so this is a little simpler. + DependencySet getAllWritesWithin(const StmtPtr& v) { + DependencySet writes; + + // writes just Store currently. + auto stores = NodeFinder::find(v); + for (const auto& s : stores) { + auto bound = stmtToAccess_.equal_range(s); + for (auto it = bound.first; it != bound.second; ++it) { + if (it->second->isWrite()) { + writes.insert(it->second); + } + } + } + return writes; + } + + // Templated helpers to work on either Exprs or Stmts. + template + bool dependsDirectlyHelper(const StmtOrExprPtr& A, const StmtPtr& B) { + auto aReads = getAllReadsWithin(A); + auto bWrites = getAllWritesWithin(B); + + for (auto& read : aReads) { + for (auto& depPair : read->dependencies()) { + if (bWrites.count(depPair.second) != 0) { + return true; + } + } + } + + return false; + } + + template + bool dependsIndirectlyHelper(StmtOrExprPtr A, const StmtPtr& B) { + auto aReads = getAllReadsWithin(A); + auto bWrites = getAllWritesWithin(B); + + auto aDeps = getAllWriteDependencies(aReads); + + for (auto& dependency : aDeps) { + if (bWrites.count(dependency) != 0) { + return true; + } + } + + return false; + } + + DependencySet getAllWriteDependencies(const DependencySet& products); + + // Maps for inputs and outputs, since they aren't present directly in the IR. + std::unordered_map> inputs_; + std::unordered_map> outputs_; + std::unordered_map> intermediates_; + + // Inserts accesses for Buf's: specifically for inputs and outputs. + void insertBuffers( + std::unordered_map>& bufs, + AccessType type); + + // Update the write history with a new write, adding dependencies and closing + // any overlapped writes (if possible). + void updateWriteHistory( + std::list& writeHistory, + const std::shared_ptr& info, + size_t latestAccessToClose, + bool closeOverlapped = true, + bool insert = true); + + // Merge a child scope into a parent scope, adding dependencies for open + // writes in the parent to accesses in the child. + void mergeScope( + const std::shared_ptr& child, + const std::shared_ptr& parent, + bool closeOverlapped = true); + + // Binds symbolic vars in indices with the low and high bound for those vars. + std::vector getIndicesBounds(const std::vector& indices); + + size_t nextAccess_{0}; + StmtPtr lastStmt_{nullptr}; +}; + +} // namespace torch::jit::tensorexpr::analysis diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/operators/conv2d.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/operators/conv2d.h new file mode 100644 index 0000000000000000000000000000000000000000..f842a1350a55111c0d24c2f0a688e1648149a552 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/operators/conv2d.h @@ -0,0 +1,105 @@ +#pragma once + +#include +#include + +namespace torch { +namespace jit { +namespace tensorexpr { + +// An API to compute 2D depthwise convolutions with bias. +TORCH_API Tensor conv2d_depthwise( + BufHandle input, + BufHandle weight, + BufHandle bias, + int stride, + int pad, + int groups); + +// An API to compute 2D depthwise convolutions without bias. +TORCH_API Tensor conv2d_depthwise( + BufHandle input, + BufHandle weight, + int stride, + int pad, + int groups); + +TORCH_API Tensor conv2d_depthwise( + BufHandle input, + BufHandle weight, + BufHandle bias, + ExprHandle N, + ExprHandle C, + ExprHandle H, + ExprHandle W, + ExprHandle K, + ExprHandle CperG, + ExprHandle R, + ExprHandle S, + ExprHandle stride, + ExprHandle pad, + ExprHandle groups); + +TORCH_API Tensor conv2d_depthwise( + BufHandle input, + BufHandle weight, + ExprHandle N, + ExprHandle C, + ExprHandle H, + ExprHandle W, + ExprHandle K, + ExprHandle CperG, + ExprHandle R, + ExprHandle S, + ExprHandle stride, + ExprHandle pad, + ExprHandle groups); + +bool conv2dIsSupported( + const TensorInfo& input, + const TensorInfo& weight, + const TensorInfo& bias, + const std::vector& stride, + const std::vector& pad, + const std::vector& dilation, + int64_t groups); +bool mkldnnPrepackedConvIsSupported( + const TensorInfo& input, + const TensorInfo& weight, + const std::vector& stride, + const std::vector& pad, + const std::vector& dilation, + int64_t groups); +Tensor computeConv2d( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + at::Device device); +Tensor computeConv1d( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + at::Device device); +Tensor computePrepackedConv2dClampRun( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + at::Device device); +Tensor computePrepackedLinearClampRun( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + at::Device device); +Tensor computeMkldnnPrepackedConvRun( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + at::Device device); +} // namespace tensorexpr +} // namespace jit +} // namespace torch diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/operators/matmul.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/operators/matmul.h new file mode 100644 index 0000000000000000000000000000000000000000..40ef3cfd9b619929afef7192dbaa6bf22e800ab5 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/operators/matmul.h @@ -0,0 +1,24 @@ +#pragma once + +#include + +namespace torch { +namespace jit { +namespace tensorexpr { + +Tensor computeMatmul( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + at::Device device); +Tensor computeAddMM( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + at::Device device); + +} // namespace tensorexpr +} // namespace jit +} // namespace torch diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/operators/misc.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/operators/misc.h new file mode 100644 index 0000000000000000000000000000000000000000..cb257eb3b7e03e25ddc96d4ea749c848ac4666e7 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/operators/misc.h @@ -0,0 +1,94 @@ +#pragma once + +#include +#include +#include + +namespace torch::jit::tensorexpr { + +struct TensorInfo { + std::vector dims; + c10::ScalarType dtype; +}; +std::optional getTensorInfo(const BufHandle& b); + +int64_t normalizeAndCheckIndex(int64_t idx, int64_t list_size); + +// Convert boolean to integer, if needed. +ExprHandle boolToInteger(const ExprHandle& x); +ExprHandle promoteToDtype(ExprHandle e, ScalarType dt); +void promoteInputs( + std::vector& inputs, + const int typeConstraints = kAllTypes); +ExprHandle promoteIntegerToDefaultType(const ExprHandle& e); +ExprHandle promoteHalfToFloat(const ExprHandle& e); +ExprHandle demoteOutput( + const ExprHandle& e, + const std::optional type); + +std::vector broadcastShapes( + std::vector> shapes); +std::vector broadcastShapes( + const std::vector& a, + const std::vector& b); + +std::vector valueShape(const ArgValue& v); +ExprHandle tensorOrConstant( + const ArgValue& v, + const std::vector& axes); +ExprHandle scalarOrConstant(const ArgValue& v); +ExprHandle broadcast(const BufHandle& b, const std::vector& axes); +ExprHandle constant(const ArgValue& v); + +ExprHandle clamp( + const ExprHandle& cmin, + const ExprHandle& cmax, + const ExprHandle& input); + +Tensor computeChunk( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + at::Device device); +Tensor computeTranspose( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + at::Device device); +Tensor computeExpand( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + at::Device device); +Tensor computeReshape( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + at::Device device); +Tensor computeFlatten( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + at::Device device); +Tensor computeCatWoConditionals( + const std::vector& inputs, + const std::vector& outputShape); +Tensor computeCat( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + at::Device device); +Tensor computeEmbedding( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + at::Device device); + +} // namespace torch::jit::tensorexpr diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/operators/norm.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/operators/norm.h new file mode 100644 index 0000000000000000000000000000000000000000..dbe6140cca8b43179bc960c7744b90a246f8b377 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/operators/norm.h @@ -0,0 +1,18 @@ +#pragma once + +#include + +namespace torch { +namespace jit { +namespace tensorexpr { + +Tensor computeBatchNorm( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + at::Device device); + +} // namespace tensorexpr +} // namespace jit +} // namespace torch diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/operators/operators.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/operators/operators.h new file mode 100644 index 0000000000000000000000000000000000000000..6298a6480149b9db1536ea408094e1d259c2605f --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/operators/operators.h @@ -0,0 +1,10 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/operators/pointwise.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/operators/pointwise.h new file mode 100644 index 0000000000000000000000000000000000000000..1e3366a2858762afd94919124fed281df0e2b9d6 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/operators/pointwise.h @@ -0,0 +1,86 @@ +#pragma once + +#include + +namespace torch { +namespace jit { +namespace tensorexpr { + +TORCH_API Tensor computeSign( + const std::vector& inputs, + const std::vector& outputShape, + const std::optional>& outputStrides = std::nullopt); + +Tensor computeOneOperand( + const std::string& name, + const std::vector& inputValues, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + const std::function& innerExpr, + const int checkParamTypes = kAllTypes); +Tensor computeTwoOperand( + const std::string& name, + const std::vector& inputValues, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + const std::function& + innerExpr); +Tensor computeTwoOperandWithAlpha( + const std::string& name, + const std::vector& inputValues, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + const std::function& + innerExpr); +Tensor computeConditionWithTwoOperand( + const std::string& name, + const std::vector& inputValues, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + const std::function< + ExprHandle(const ExprHandle&, const ExprHandle&, const ExprHandle&)>& + innerExpr); +Tensor computeThreeOperand( + const std::string& name, + const std::vector& inputValues, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + const std::function< + ExprHandle(const ExprHandle&, const ExprHandle&, const ExprHandle&)>& + innerExpr, + bool promote_inputs = true); +Tensor computeFourOperand( + const std::string& name, + const std::vector& inputValues, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + const std::function& innerExpr); +Tensor computeNoop( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + at::Device device); + +Tensor computeScalar( + const std::string& name, + const std::vector& inputValues, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + const std::function& + innerExpr); + +} // namespace tensorexpr +} // namespace jit +} // namespace torch diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/operators/quantization.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/operators/quantization.h new file mode 100644 index 0000000000000000000000000000000000000000..d48c9e3273ba0df95b518fc267a7f17a98239148 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/operators/quantization.h @@ -0,0 +1,160 @@ +#pragma once + +#include + +namespace torch { +namespace jit { +namespace tensorexpr { + +TORCH_API ExprHandle quantizePerTensorQParamFromArg(ArgValue arg); + +TORCH_API double immQScale(const BufHandle& qx); + +TORCH_API int64_t immQZero(const BufHandle& qx); + +TORCH_API ScalarType immQDType(const BufHandle& qx); + +TORCH_API bool isQuantized(const BufHandle& qx); + +TORCH_API Tensor computeQuantizePerTensor( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + at::Device device); + +TORCH_API Tensor computeQuantizePerTensorExternalCall( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + at::Device device); + +TORCH_API Tensor computeQuantizedConv1d( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + at::Device device); + +TORCH_API Tensor computeQuantizedConv2dPrepack( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + at::Device device); + +TORCH_API Tensor computeQuantizedConv1d( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + at::Device device); + +TORCH_API Tensor computeQuantizedConv2d( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + at::Device device); + +TORCH_API Tensor computeQuantizedConv2dRelu( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + at::Device device); + +TORCH_API Tensor computeQuantizedLinear( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + at::Device device); + +TORCH_API Tensor computeQuantizedLinearRelu( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + at::Device device); + +TORCH_API Tensor computeQuantizedAdd( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + at::Device device); + +Tensor computeQuantizedAddExternalCall( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + at::Device device); + +TORCH_API Tensor computeQuantizedMul( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + at::Device device); + +TORCH_API Tensor computeQuantizedMulScalar( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + at::Device device); + +TORCH_API Tensor computeQuantizedCat( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + at::Device device); + +TORCH_API Tensor computeQuantizedRelu( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + at::Device device); + +TORCH_API Tensor computeDequantize( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + at::Device device); + +TORCH_API Tensor computeDequantizeExternalCall( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + at::Device device); + +TORCH_API Tensor computeUpsampleNearest2d( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + at::Device device); + +TORCH_API Tensor computeUpsampleNearest2dExternalCall( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + at::Device device); + +TORCH_API Tensor computeQuantizedSigmoidExternalCall( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + at::Device); +} // namespace tensorexpr +} // namespace jit +} // namespace torch diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/operators/reduction.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/operators/reduction.h new file mode 100644 index 0000000000000000000000000000000000000000..7d25e14a171ce36280b9dcc1b134ed3cbdd559dc --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/operators/reduction.h @@ -0,0 +1,36 @@ +#pragma once + +#include + +namespace torch { +namespace jit { +namespace tensorexpr { + +TORCH_API Tensor computeSum( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + at::Device device); +TORCH_API Tensor computeMean( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + at::Device device); +TORCH_API Tensor computeAdaptiveAvgPool2d( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + at::Device device); +Tensor computeMax( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + const std::optional& outputType, + at::Device device); + +} // namespace tensorexpr +} // namespace jit +} // namespace torch diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/operators/softmax.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/operators/softmax.h new file mode 100644 index 0000000000000000000000000000000000000000..d5dd7fd429bed004a6e49e9a88090503aba30948 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/operators/softmax.h @@ -0,0 +1,17 @@ +#pragma once + +#include + +namespace torch { +namespace jit { +namespace tensorexpr { + +Tensor computeSoftmax( + const std::vector& inputs, + const std::vector& outputShape, + const std::vector& outputStrides, + bool log_softmax); + +} // namespace tensorexpr +} // namespace jit +} // namespace torch diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/reduction.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/reduction.h new file mode 100644 index 0000000000000000000000000000000000000000..c65cf43be7fba00ff9cc974c7316d468deb3ad12 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/reduction.h @@ -0,0 +1,306 @@ +#pragma once + +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace torch::jit::tensorexpr { + +using ParameterList = const std::vector; +using ReduceInteraction = std::function; + +// A Reducer is a user interface describing a particular reduction +// operation. It has three components: An initialization value, a way of +// interacting each value with the accumulation, and a method for obtaining the +// current value to be reduced. It is materialized into a ReduceOp when loop +// variables are known. +class TORCH_API Reducer { + public: + Reducer(ExprHandle init, ReduceInteraction& interaction) + : init_(init.node()), interaction_(interaction) {} + + template + Reducer(ExprHandle init, RI interaction) + : init_(init.node()), interaction_(std::move(interaction)) {} + + ExprPtr initializer() const { + return init_; + } + + ExprHandle operator()( + const BufHandle& result_buf, + ExprHandle body, + const std::vector& output, + const std::vector& inner) const; + + ReduceOpPtr operator()( + const BufPtr& result_buf, + ExprPtr body, + const std::vector& output, + const std::vector& inner) const; + + ExprHandle operator()( + const BufHandle& result_buf, + BufHandle acc_buf, + const ExprHandle& body, + const std::vector& output, + const std::vector& inner) const; + + // Polymorphic handling of Body functions with a variety of parameters. + static ExprHandle getReduceBody( + const std::function& func, + const std::vector& vars) { + return func(vars); + } + + static ExprHandle getReduceBody( + const std::function& func, + const std::vector& vars) { + if (vars.size() != 1) { + throw malformed_input("mismatch between reduce body and arg size (1)"); + } + + return func(vars[0]); + } + + static ExprHandle getReduceBody( + const std::function& func, + const std::vector& vars) { + if (vars.size() != 2) { + throw malformed_input("mismatch between reduce body and arg size (2)"); + } + return func(vars[0], vars[1]); + } + + static ExprHandle getReduceBody( + const std::function< + ExprHandle(const VarHandle&, const VarHandle&, const VarHandle&)>& + func, + const std::vector& vars) { + if (vars.size() != 3) { + throw malformed_input("mismatch between reduce body and arg size (3)"); + } + return func(vars[0], vars[1], vars[2]); + } + + static ExprHandle getReduceBody( + const std::function& func, + const std::vector& vars) { + if (vars.size() != 4) { + throw malformed_input("mismatch between reduce body and arg size (4)"); + } + return func(vars[0], vars[1], vars[2], vars[3]); + } + + // Completes the reduction operator by applying the interaction function to + // the accumulation and the body expression. + static ExprPtr complete( + const BufPtr& accumulator, + const ReduceInteraction& interaction, + ExprHandle body, + const std::vector& output_args, + const std::vector& reduce_args) { + ExprHandle accum = + ExprHandle(alloc(body.dtype(), accumulator, output_args)); + auto e = interaction(std::move(accum), std::move(body)); + return e.node(); + } + static ExprHandle complete( + const BufHandle& accumulator, + const ReduceInteraction& interaction, + ExprHandle body, + const std::vector& output_args, + const std::vector& reduce_args) { + ExprHandle accum = Load::make(body.dtype(), accumulator, output_args); + auto e = interaction(std::move(accum), std::move(body)); + return e; + } + + private: + ExprPtr init_; + ReduceInteraction interaction_; +}; + +// An expression representing a Reduction operation (e.g. Sum, Max) broken into +// it's component parts: initialization, accumulation var, acquisition of value +// to be reduced and interaction. +// +// This is intended to be expanded in the loopnest and not make it to codegen. +class TORCH_API ReduceOp : public ExprNode { + public: + ReduceOp( + const ExprPtr& body, + std::vector reduce_args, + Reducer reducer) + : ExprNodeBase(body->dtype()), + body_(body), + reduce_args_(std::move(reduce_args)), + reducer_(std::move(reducer)) { + result_buf_ = nullptr; + acc_buf_ = nullptr; + ri_operand_ = nullptr; + } + + ReduceOp( + const ExprPtr& body, + std::vector reduce_args, + BufPtr result_buf, + BufPtr acc_buf, + ExprPtr ri_operand, + Reducer reducer) + : ExprNodeBase(body->dtype()), + body_(body), + reduce_args_(std::move(reduce_args)), + result_buf_(std::move(result_buf)), + acc_buf_(std::move(acc_buf)), + ri_operand_(std::move(ri_operand)), + reducer_(std::move(reducer)) {} + + static ExprHandle make( + ExprHandle body, + const std::vector& reduce_args, + const Reducer& reducer); + + static ExprHandle make( + ExprHandle body, + const std::vector& reduce_args, + BufHandle result_buf, + BufHandle acc_buf, + ExprHandle ri_operand, + const Reducer& reducer); + + // return the body expression which obtains the value to be reduced. + ExprPtr body() const { + return body_; + } + + // Returns the original Reducer factory that can create ReduceOps. + const Reducer& reducer() const { + return reducer_; + } + + // returns variables associated with the axes of reduction. + const std::vector& reduce_args() const { + return reduce_args_; + } + + void setAccBuf(BufHandle acc_buf) { + acc_buf_ = acc_buf.node(); + } + BufPtr getAccBuf() { + return acc_buf_; + } + + void setResultBuf(BufHandle buf) { + result_buf_ = buf.node(); + } + BufPtr getResultBuf() { + return result_buf_; + } + + void setRiOperand(ExprHandle ri_operand) { + ri_operand_ = ri_operand.node(); + } + ExprPtr getRiOperand() { + return ri_operand_; + } + + private: + // body_ = reducer_->interaction_(result_buf_, ri_operand_) + ExprPtr body_; + std::vector reduce_args_; + + BufPtr result_buf_; + BufPtr acc_buf_; + ExprPtr ri_operand_; + + const Reducer reducer_; +}; + +class Sum : public Reducer { + public: + Sum() + : Reducer(ExprHandle(0), [](const ExprHandle& a, const ExprHandle& b) { + return a + b; + }) {} +}; + +inline ExprHandle maximumVal(ScalarType type) { + switch (type) { +#define MAX_BY_TYPE_CASE(Type, Name) \ + case ScalarType::Name: \ + return ExprHandle(std::numeric_limits::max()); + AT_FORALL_SCALAR_TYPES_AND3(Bool, Half, BFloat16, MAX_BY_TYPE_CASE) +#undef MAX_BY_TYPE_CASE + default: + throw unsupported_dtype(); + } + return ExprHandle(); +} + +inline ExprHandle minimumVal(ScalarType type) { + switch (type) { +#define MAX_BY_TYPE_CASE(Type, Name) \ + case ScalarType::Name: \ + return ExprHandle(std::numeric_limits::min()); + AT_FORALL_SCALAR_TYPES_AND3(Bool, Half, BFloat16, MAX_BY_TYPE_CASE) +#undef MAX_BY_TYPE_CASE + default: + throw unsupported_dtype(); + } +} + +class Maximum : public Reducer { + public: + // TODO possible to remove this arg by deferring the init value until we + // know the dtype of the body. + Maximum(Dtype dtype) + : Reducer( + minimumVal(dtype.scalar_type()), + [](const ExprHandle& a, const ExprHandle& b) { + return Max::make(a, b, true); + }) {} + Maximum(ExprHandle initializer) + : Reducer( + std::move(initializer), + [](const ExprHandle& a, const ExprHandle& b) { + return Max::make(a, b, true); + }) {} +}; + +class Minimum : public Reducer { + public: + Minimum(Dtype dtype) + : Reducer( + maximumVal(dtype.scalar_type()), + [](const ExprHandle& a, const ExprHandle& b) { + return Min::make(a, b, true); + }) {} + Minimum(const ExprHandle& initializer) + : Reducer(initializer, [](const ExprHandle& a, const ExprHandle& b) { + return Min::make(a, b, true); + }) {} +}; + +class ReductionExpander : public IRMutator { + public: + StmtPtr expand(const StmtPtr& s) { + return s->accept_mutator(this); + } + + ExprPtr mutate(const ReduceOpPtr& v) override { + return v->body(); + } +}; + +} // namespace torch::jit::tensorexpr diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/registerizer.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/registerizer.h new file mode 100644 index 0000000000000000000000000000000000000000..15d4bce415cb4e17f112d3480e0460bb18c4775d --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/registerizer.h @@ -0,0 +1,426 @@ +#pragma once +#include +#include +#include + +#include +#include +#include +#include + +#include +#include + +namespace torch::jit::tensorexpr { +namespace registerizer { + +/* The Registerizer performs scalar replacement by looking for common Stores and +Loads to a single item in a buffer and replacing them with a local temporary +scalar which is cheaper to write. + +For example it can replace: + +{ + A[0] = 0; + for(const auto x : c10::irange(10)) { + A[0] = (A[0]) + x; + } +} + +with: + +{ + int A_ = 0; + for(const auto x : c10::irange(10)) { + A_ = x + A_; + } + A[0] = A_; +} + +This is particularly useful on GPUs when parallelizing, since after replacing +loops with metavars we have a lot of accesses like this. */ + +class Scope; + +/* Holds analysis information about accesses to a specific range of a + buffer, including the number of loads and stores and the lowest common parent + Block. + */ +class AccessInfo { + public: + AccessInfo() = default; + AccessInfo( + SimplifierHashType h, + BufPtr b, + std::vector i, + size_t accessOrder) + : hash_(h), + buf_(std::move(b)), + indices_(std::move(i)), + store_cost_(alloc(0)), + load_cost_(alloc(0)), + accessOrder_(accessOrder) {} + + // Adds a Store to this access, which is in the provided scope. + void addStore(const StorePtr& store, const std::shared_ptr& scope); + + // Adds a Load to this access, which occurs in the usage Stmt in the provided + // scope. + void addLoad( + const LoadPtr& load, + const std::shared_ptr& scope, + const StmtPtr& usage); + + // Merge another AccessInfo into this one. + void merge(const std::shared_ptr& other); + + // Returns true if the other AccessInfo's bounds may overlap this one. + bool overlaps(const std::shared_ptr& other); + + // Returns true if the indices of this access depend on the provided Var. + bool dependsOnVar(const VarPtr& v); + + // Clone this AccessInfo, and set this as the new accesses' hiddenAccess. + static std::shared_ptr cloneWithHiddenInfo( + const std::shared_ptr& orig); + + // print for debugging. + void print() const; + + SimplifierHashType hash() const { + return hash_; + } + + BufPtr buf() const { + return buf_; + } + + const std::vector& indices() const { + return indices_; + } + + BlockPtr block() const { + return block_; + } + + void setEnclosingBlock(BlockPtr b) { + block_ = std::move(b); + } + + StmtPtr first_usage() const { + return first_usage_; + } + StmtPtr last_usage() const { + return last_usage_; + } + + void setUsageMarks(StmtPtr first, StmtPtr last) { + first_usage_ = std::move(first); + last_usage_ = std::move(last); + } + + bool firstUsageOverlapped() const { + return firstUsageOverlapped_; + } + + ExprPtr store_cost() const { + return store_cost_; + } + + ExprPtr load_cost() const { + return load_cost_; + } + + const std::vector& stores() const { + return stores_; + } + + const std::vector& loads() const { + return loads_; + } + + void hoistCosts(const ExprPtr& extent) { + store_cost_ = IRSimplifier::simplify(alloc(store_cost_, extent)); + load_cost_ = IRSimplifier::simplify(alloc(load_cost_, extent)); + } + + size_t conditionId() const { + return conditionId_; + } + + void setConditionId(size_t c) { + conditionId_ = c; + } + + size_t accessOrder() const { + return accessOrder_; + } + + std::shared_ptr hiddenAccess() const { + return hiddenAccess_; + } + + // Holds state relating to the scalar variable we will insert to replace some + // number of loads and stores. + struct ScalarReplacement { + VarPtr var{nullptr}; + BufPtr var_wrapper{nullptr}; + LetPtr initializer{nullptr}; + }; + + ScalarReplacement& replacement() { + return replacement_; + } + + private: + SimplifierHashType hash_; + BufPtr buf_; + std::vector indices_; + BlockPtr block_{nullptr}; + + StmtPtr first_usage_{nullptr}; + StmtPtr last_usage_{nullptr}; + + // Whether or not this access is overlapped in the first Stmt it appears. This + // means we cannot use it's first Store as the initializer. + bool firstUsageOverlapped_{false}; + + // The cost in real ops that this access represents, to enable + // filtering accesses that wont save any loads or stores. + ExprPtr store_cost_; + ExprPtr load_cost_; + + // The actual Stores and Loads which represent this access. + // Be careful with these, any mutator will invalidate these pointers. + std::vector stores_; + std::vector loads_; + + // An identifier representing the conditional block, if any, this access + // depends on. + size_t conditionId_{0}; + + // An identifier representing the order this access was first encountered, for + // sorting returned results. + size_t accessOrder_{0}; + + // Sometimes when traversing the tree we need to record what would happen if + // we hoisted an access, but sometimes it doesn't work out. This lets us + // "undo" some mutation and return to the internal hidden AccessInfo. + // It will be removed after any further additions to this AccessInfo. + std::shared_ptr hiddenAccess_; + + ScalarReplacement replacement_; +}; + +using AccessHashMap = + std::unordered_map>; + +// Represents a scope block and holds all accesses contained within it. +class Scope { + public: + Scope(BlockPtr b, std::shared_ptr parent, size_t conditionId = 0) + : block_(std::move(b)), + parent_(std::move(parent)), + conditionId_(conditionId) {} + + AccessHashMap& getAccessMapByBuf(const BufPtr& b); + + std::unordered_map& openAccesses() { + return openAccesses_; + } + + std::vector>& closedAccesses() { + return closedAccesses_; + } + + BlockPtr block() const { + return block_; + } + + std::shared_ptr parent() const { + return parent_; + } + + size_t conditionId() const { + return conditionId_; + } + + const std::unordered_set& localVars() const { + return localVars_; + } + void addLocalVar(VarPtr v) { + localVars_.insert(std::move(v)); + } + + void closeAccess(const std::shared_ptr& info); + + void filterClosed(); + + private: + // Map of map to access, narrowing by Buf then by hash(Buf+Indices). + // This allows us to find a candidate access easily, and also check for + // overlap with other accesses to the same buf. Buf -> + // Hash -> + // Access + std::unordered_map openAccesses_; + std::vector> closedAccesses_; + + // The Block object this scope represents. + BlockPtr block_; + + // The enclosing scope object. + std::shared_ptr parent_; + + // An identifier representing the condition block this scope depends on. + size_t conditionId_; + + // A set of variables local to this scope (e.g. loop vars). + std::unordered_set localVars_; +}; + +/* Analyzes the graph and collects accesses to the same symbolic tensor element + * which can be replaced by a single local scalar. + * + * This works by recursively walking the tree in postfix order, building sets of + * accesses to the same symbolic element by scope and then merging lower scopes + * into their enclosing scope. + * + * It is safe to move two accesses of the same Tensor element to a local scalar + * Var if between all usages of the element there are no other Loads or Stores + * that may refer to it. In the comments I refer to this as overlapping the + * access, or "cutting" the existing AccessInfo. In the case where a candidate + * for registerization is cut, it may be possible to finalize the access early + * by writing it back to the Tensor and then create a new scalar variable after + * the overlapping access is complete. We will attempt to do this when it saves + * memory accesses. + * + * There are a few cases that make this more challenging: + * + * - For: Loops change the number of real usages of a buffer by the loop + * extent, but only if we can pull the definition and finalization of the scalar + * variable out of the loop block. + * + * - Cond: Conditions complicate lifting scalars out of internal scopes. + * Generally we cannot lift an access outside of a conditional scope unless + * there is already a reference to that same access at the higher scope, since + * we don't know if the condition was guarding an array access not safe at the + * higher scope. In the comments I refer to this as the condition "hiding" the + * access, and the outer access "unhiding" it. + * + * - IfThenElse: Same situation as Cond, except since IfThenElse is an Expr + * rather than a Stmt we cannot insert the scalar definition or finalizer + * within the conditional scope. Accesses inside an IfThenElse can be safely + * combined with external accesses but cannot exist completely within. + * + * - Let: Accesses dependent on local variables via Let Stmts, or loop vars, + * cannot be raised outside of the scope of the dependent var. + */ +class TORCH_API RegisterizerAnalysis : public IRVisitor { + public: + RegisterizerAnalysis() + : currentScope_(std::make_shared(nullptr, nullptr, 0)) {} + ~RegisterizerAnalysis() override = default; + + void visit(const ForPtr& v) override; + + void visit(const CondPtr& v) override; + + void visit(const BlockPtr& v) override; + + void visit(const StorePtr& v) override; + + void visit(const LoadPtr& v) override; + + void visit(const IfThenElsePtr& v) override; + + void visit(const LetPtr& v) override; + +#define STMT_ON_STACK(Op) \ + void visit(const Op##Ptr& v) override { \ + stmtStack_.push_front(v); \ + IRVisitor::visit(v); \ + stmtStack_.pop_front(); \ + } + + STMT_ON_STACK(AtomicAdd); + STMT_ON_STACK(Allocate); + STMT_ON_STACK(Free); + +#undef STMT_ON_STACK + + std::vector> getCandidates(); + + private: + void mergeCurrentScopeIntoParent(); + void mergeHiddenScope(bool allowClosed); + void closeAccessIntoScope( + const std::shared_ptr& info, + const std::shared_ptr& scope); + + std::unordered_set exprConditionals_; + + // A stack of enclosing Stmts for tracking the usage Stmt of Loads. + std::deque stmtStack_; + + // The current scope being analyzed. + std::shared_ptr currentScope_; + + HashProvider hasher_; + + size_t conditionId_{0}; + size_t accessOrder_{0}; +}; + +/* Replaces each registerizable access with a Scalar variable, including + * definition, initializer and finalizer. + */ +class TORCH_API RegisterizerReplacer : public IRMutator { + public: + RegisterizerReplacer(std::vector>& vec) + : infoSet_(vec) { + buildReplacements(); + } + + ExprPtr mutate(const LoadPtr& v) override; + + StmtPtr mutate(const StorePtr& v) override; + + StmtPtr mutate(const BlockPtr& v) override; + + private: + struct ReplacerScope { + std::unordered_map>> + initializerPoints_; + std::unordered_map>> + finalizePoints_; + }; + + // Creates the various ReplacerScope objects and builds internal maps. + void buildReplacements(); + + // State relating to the accesses yet to be replaced. + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + std::vector>& infoSet_; + std::unordered_map> storeToAccess_; + std::unordered_map> loadToAccess_; + std::unordered_map parentToAccesses_; + + // Holds the set of Stores that should be pulled into an initializer, so they + // can be eliminated. + std::set eliminatedIntializers_; + + // Tracks the number of times we've seen each buffer, so we can name the + // scalar Vars appropriately. + std::unordered_map bufferAccessCounts_; + unsigned int getBufferAccessCount(const BufPtr& b) { + return ++bufferAccessCounts_[b]; + } +}; +} // namespace registerizer + +// Apply scalar replacement to all accesses in s. +// To produce safe code, this must occur after handling parallelized axes and +// atomics. +TORCH_API StmtPtr registerize(StmtPtr s); + +} // namespace torch::jit::tensorexpr diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/tensor.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/tensor.h new file mode 100644 index 0000000000000000000000000000000000000000..c7b2e65b44771b5ac15d01910b9d20757d61d0e8 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/tensor.h @@ -0,0 +1,321 @@ +#pragma once + +#include +#include +#include +#include + +#include +#include + +namespace torch::jit::tensorexpr { + +class TORCH_API Tensor { + public: + Tensor(BufPtr buf, const std::vector& args, const ExprPtr& body) + : buf_(std::move(buf)) { + stmt_ = constructStmt(args, body, {}, {}); + } + Tensor(BufHandle buf, const std::vector& args, ExprHandle body) + : Tensor(buf.node(), VarHandleVectorToVarVector(args), body.node()) {} + + Tensor( + BufPtr buf, + const std::vector& args, + const std::vector& reduce_dims, + const std::vector& reduce_args, + const ExprPtr& body) + : buf_(std::move(buf)) { + stmt_ = constructStmt(args, body, reduce_dims, reduce_args); + } + Tensor( + BufHandle buf, + const std::vector& args, + const std::vector& reduce_dims, + const std::vector& reduce_args, + ExprHandle body) + : Tensor( + buf.node(), + VarHandleVectorToVarVector(args), + ExprHandleVectorToExprVector(reduce_dims), + VarHandleVectorToVarVector(reduce_args), + body.node()) {} + + Tensor(BufPtr buf, StmtPtr stmt) + : buf_(std::move(buf)), stmt_(std::move(stmt)) {} + + BufPtr buf() const { + return buf_; + } + + StmtPtr stmt() const { + return stmt_; + } + + template + inline ExprHandle load(const std::vector& args) const; + template + inline ExprHandle load(const Ts&... ts) const; + + private: + StmtPtr constructStmt( + const std::vector& args, + const ExprPtr& body, + const std::vector& reduce_dims, + const std::vector& reduce_args) const; + + BufPtr buf_; + StmtPtr stmt_; +}; + +TORCH_API Tensor Compute( + const std::string& func_name, + const std::vector& dims, + const std::optional>& strides, + const std::function& body_func); +TORCH_API Tensor Compute( + const std::string& func_name, + const std::vector& dims, + const std::function& body_func); +TORCH_API Tensor Compute( + const std::string& func_name, + const std::vector& dims, + const std::optional>& strides, + const std::function& + body_func); +TORCH_API Tensor Compute( + const std::string& func_name, + const std::vector& dims, + const std::function& + body_func); +TORCH_API Tensor Compute( + const std::string& func_name, + const std::vector& dims, + const std::optional>& strides, + const std::function< + ExprHandle(const VarHandle&, const VarHandle&, const VarHandle&)>& + body_func); +TORCH_API Tensor Compute( + const std::string& func_name, + const std::vector& dims, + const std::function< + ExprHandle(const VarHandle&, const VarHandle&, const VarHandle&)>& + body_func); +TORCH_API Tensor Compute( + const std::string& func_name, + const std::vector& dims, + const std::optional>& strides, + const std::function& body_func); +TORCH_API Tensor Compute( + const std::string& func_name, + const std::vector& dims, + const std::function& body_func); +TORCH_API Tensor Compute( + const std::string& func_name, + const std::vector& dims, + const std::optional>& strides, + const std::function&)>& body_func); +TORCH_API Tensor Compute( + const std::string& func_name, + const std::vector& dims, + const std::function&)>& body_func); + +inline std::vector create_index_vars( + const std::vector& dims) { + std::vector vars; + vars.reserve(dims.size()); + for (const ExprHandle& dim : dims) { + vars.emplace_back(alloc( + "i", dim.dtype().scalar_type() == ScalarType::Long ? kLong : kInt)); + } + return vars; +} + +// Handle reductions over a Reducer and a body_func which produces values. +template +Tensor Reduce( + const std::string& func_name, + const std::vector& dims, + const std::optional>& strides, + const Reducer& reducer, + const InitFunc& init_func, + const BodyFunc& body_func, + const std::vector& reduce_dims) { + std::vector vars = create_index_vars(dims); + std::vector reduce_vars = create_index_vars(reduce_dims); + + // If reduce_vars is empty, then it's not a reduction, but rather a simple + // copy + if (reduce_vars.empty()) { + ExprHandle body = Reducer::getReduceBody(body_func, vars); + BufHandle func_result = + Buf::make(func_name, dims, body.dtype(), std::nullopt, strides); + return Tensor(std::move(func_result), vars, std::move(body)); + } + + std::vector all_vars; + all_vars.insert(all_vars.end(), vars.begin(), vars.end()); + all_vars.insert(all_vars.end(), reduce_vars.begin(), reduce_vars.end()); + + ExprHandle body = Reducer::getReduceBody(body_func, all_vars); + std::vector output_args(vars.begin(), vars.end()); + ExprHandle init_expr = Cast::make(body.dtype(), init_func(vars)); + BufHandle func_result = Buf::make(func_name, dims, body.dtype(), init_expr); + + ExprHandle reduce_op = reducer(func_result, body, output_args, reduce_vars); + if (body.dtype() == kBFloat16) { + ExprHandle init_expr_acc = Cast::make(kFloat, init_func(vars)); + BufHandle func_result_acc = + Buf::make(func_name + "_acc", dims, kFloat, init_expr_acc); + reduce_op = reducer( + func_result, + std::move(func_result_acc), + body, + output_args, + reduce_vars); + } + + Tensor t = Tensor( + std::move(func_result), + vars, + reduce_dims, + reduce_vars, + std::move(reduce_op)); + return t; +} +template +Tensor Reduce( + const std::string& func_name, + const std::vector& dims, + const Reducer& reducer, + const InitFunc& init_func, + const BodyFunc& body_func, + const std::vector& reduce_dims) { + return Reduce( + func_name, + dims, + std::nullopt, + reducer, + init_func, + body_func, + reduce_dims); +} + +template +Tensor Reduce( + const std::string& func_name, + const std::vector& dims, + const std::optional>& strides, + const Reducer& reducer, + const BodyFunc& body_func, + const std::vector& reduce_dims) { + return Reduce( + func_name, + dims, + strides, + reducer, + [&](ParameterList& p [[maybe_unused]]) { + return ExprHandle(reducer.initializer()); + }, + body_func, + reduce_dims); +} +template +Tensor Reduce( + const std::string& func_name, + const std::vector& dims, + const Reducer& reducer, + const BodyFunc& body_func, + const std::vector& reduce_dims) { + return Reduce( + func_name, dims, std::nullopt, reducer, body_func, reduce_dims); +} + +// Overload which allows inline lambda functions for the body_func. +template +Tensor Reduce( + const std::string& func_name, + const std::vector& dims, + const std::optional>& strides, + const Reducer& reducer, + const BodyFunc&& body_func, + const std::vector& reduce_dims) { + return Reduce(func_name, dims, strides, reducer, body_func, reduce_dims); +} +template +Tensor Reduce( + const std::string& func_name, + const std::vector& dims, + const Reducer& reducer, + const BodyFunc&& body_func, + const std::vector& reduce_dims) { + return Reduce(func_name, dims, std::nullopt, reducer, body_func, reduce_dims); +} + +TORCH_API Tensor Reduce( + const std::string& name, + const std::vector& dims, + const std::optional>& strides, + const Reducer& reducer, + const BufHandle& buffer, + const std::vector& reduce_dims); +TORCH_API Tensor Reduce( + const std::string& name, + const std::vector& dims, + const Reducer& reducer, + const BufHandle& buffer, + const std::vector& reduce_dims); + +// Overload for the common case of all dimensions of a previously Computed +// Tensor. +TORCH_API Tensor Reduce( + const std::string& func_name, + const std::vector& dims, + const std::optional>& strides, + const Reducer& reducer, + const Tensor& tensor, + const std::vector& reduce_dims); +TORCH_API Tensor Reduce( + const std::string& func_name, + const std::vector& dims, + const Reducer& reducer, + const Tensor& tensor, + const std::vector& reduce_dims); + +template +inline ExprHandle Tensor::load(const Ts&... ts) const { + std::vector params({ExprHandle(ts)...}); + return Load::make(BufHandle(this->buf()), params); +} + +template +inline ExprHandle Tensor::load(const std::vector& args) const { + std::vector params(args.begin(), args.end()); + return Load::make(BufHandle(this->buf()), params); +} + +template +inline ExprHandle BufHandle::load(const Ts&... ts) const { + std::vector params({ExprHandle(ts)...}); + return ExprHandle(alloc(node(), ExprHandleVectorToExprVector(params))); +} + +template +inline ExprHandle BufHandle::load(const std::vector& args) const { + std::vector params(args.begin(), args.end()); + return ExprHandle(alloc(node(), ExprHandleVectorToExprVector(params))); +} + +inline ExprHandle BufHandle::load(const std::vector& args) const { + return this->template load(args); +} + +} // namespace torch::jit::tensorexpr diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/tensorexpr_init.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/tensorexpr_init.h new file mode 100644 index 0000000000000000000000000000000000000000..1dc38660615824654df2b5f5b0d6a426eefc263a --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/tensorexpr_init.h @@ -0,0 +1,9 @@ +#pragma once + +#include +#include + +namespace torch::jit { +// Initialize Python bindings for Tensor Expressions +void initTensorExprBindings(PyObject* module); +} // namespace torch::jit diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/unique_name_manager.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/unique_name_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..f5ceac667d158730af57c4ddc6192e59040e3d4b --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/unique_name_manager.h @@ -0,0 +1,33 @@ +#pragma once + +#include +#include +#include + +#include +#include + +namespace torch::jit::tensorexpr { + +class VarHandle; +class Var; + +using VarNameMap = std::unordered_map; + +// A manager to get unique names from vars. +// It starts with the name hints of the var and append "_" + $counter until it +// hits a unique name. +class TORCH_API UniqueNameManager { + public: + const std::string& get_unique_name(const VarHandle& v); + + const std::string& get_unique_name(const VarPtr& v); + + private: + friend class ScopedVarName; + VarNameMap unique_name_mapping_; + std::unordered_map unique_name_count_; + std::unordered_set all_unique_names_; +}; + +} // namespace torch::jit::tensorexpr diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/var_substitutor.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/var_substitutor.h new file mode 100644 index 0000000000000000000000000000000000000000..e3009902bc33497303942c86a8958dccde2eba1d --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/var_substitutor.h @@ -0,0 +1,61 @@ +#pragma once + +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace torch::jit::tensorexpr { + +using VarMapping = std::vector>; + +class VarSubMutator : public IRMutator { + public: + VarSubMutator(const VarMapping& var_mapping) { + for (auto& entry : var_mapping) { + VarPtr key_var = entry.first; + ExprPtr value = entry.second; + if (!key_var) { + throw malformed_input("missing key in VarSubMutator"); + } + var_mapping_[std::move(key_var)] = std::move(value); + } + } + + ExprPtr mutate(const VarPtr& var) override { + auto iter = var_mapping_.find(var); + if (iter == var_mapping_.end()) { + return var; + } + return iter->second; + } + + ExprPtr mutate(const ReduceOpPtr& var) override { + auto body = var->body()->accept_mutator(this); + std::vector new_inner; + + for (const auto& v : var->reduce_args()) { + ExprPtr e = v->accept_mutator(this); + if (VarPtr new_var = to(e)) { + new_inner.push_back(std::move(new_var)); + } else { + VarFinder varFinder; + e->accept(&varFinder); + auto varlist = varFinder.vars(); + new_inner.insert(new_inner.end(), varlist.begin(), varlist.end()); + } + } + + return alloc(body, new_inner, var->reducer()); + } + + private: + std::unordered_map var_mapping_; +}; + +} // namespace torch::jit::tensorexpr diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/testing/file_check.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/testing/file_check.h new file mode 100644 index 0000000000000000000000000000000000000000..6e9290f5130baffe4c1fbbadb61e80b6c88d46d4 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/testing/file_check.h @@ -0,0 +1,81 @@ +#pragma once + +#include +#include +#include + +namespace torch { +namespace jit { + +struct Graph; + +namespace testing { + +struct FileCheckImpl; + +struct FileCheck { + public: + TORCH_API explicit FileCheck(); + TORCH_API ~FileCheck(); + + // Run FileCheck against test string + TORCH_API void run(const std::string& test_string); + + // Run FileCheck against dump of graph IR + TORCH_API void run(const Graph& graph); + + // Parsing input checks string and run against test string / dump of graph IR + TORCH_API void run( + const std::string& input_checks_string, + const std::string& test_string); + TORCH_API void run( + const std::string& input_checks_string, + const Graph& graph); + + // Checks that the string occurs, starting at the end of the most recent match + TORCH_API FileCheck* check(const std::string& str); + + // Checks that the string does not occur between the previous match and next + // match. Consecutive check_nots test against the same previous match and next + // match + TORCH_API FileCheck* check_not(const std::string& str); + + // Checks that the string occurs on the same line as the previous match + TORCH_API FileCheck* check_same(const std::string& str); + + // Checks that the string occurs on the line immediately following the + // previous match + TORCH_API FileCheck* check_next(const std::string& str); + + // Checks that the string occurs count number of times, starting at the end + // of the previous match. If exactly is true, checks that there are exactly + // count many matches + TORCH_API FileCheck* check_count( + const std::string& str, + size_t count, + bool exactly = false); + + // A series of consecutive check_dags get turned into a group of checks + // which can appear in any order relative to each other. The checks begin + // at the end of the previous match, and the match for the check_dag group + // is the minimum match of all individual checks to the maximum match of all + // individual checks. + TORCH_API FileCheck* check_dag(const std::string& str); + + // Checks that source token is highlighted in str (usually an error message). + TORCH_API FileCheck* check_source_highlighted(const std::string& str); + + // Checks that the regex matched string occurs, starting at the end of the + // most recent match + TORCH_API FileCheck* check_regex(const std::string& str); + + // reset checks + TORCH_API void reset(); + + private: + bool has_run = false; + std::unique_ptr fcImpl; +}; +} // namespace testing +} // namespace jit +} // namespace torch diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/testing/hooks_for_testing.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/testing/hooks_for_testing.h new file mode 100644 index 0000000000000000000000000000000000000000..108dea3f1f72d79433faf1b9ddb56f54727ac6e3 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/testing/hooks_for_testing.h @@ -0,0 +1,21 @@ +#pragma once +#include +#include +#include +#include + +namespace torch { +namespace jit { +struct Module; + +using ModuleHook = std::function; +using FunctionHook = std::function; + +TORCH_API void didFinishEmitModule(Module module); +TORCH_API void didFinishEmitFunction(StrongFunctionPtr defined); +TORCH_API void setEmitHooks(ModuleHook for_module, FunctionHook for_fn); + +TORCH_API std::pair getEmitHooks(); + +} // namespace jit +} // namespace torch