diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/metrics/RpcMetricsHandler.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/metrics/RpcMetricsHandler.h new file mode 100644 index 0000000000000000000000000000000000000000..d46a0e9be89a5957fd498fe2fbd17c7e02767e4b --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/metrics/RpcMetricsHandler.h @@ -0,0 +1,45 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include +#include + +namespace torch::distributed::rpc { +// All metrics are prefixed with the following key. +// NOLINTNEXTLINE(cppcoreguidelines-avoid-c-arrays,modernize-avoid-c-arrays) +constexpr char kRpcMetricsKeyPrefix[] = "torch.distributed.rpc."; +// APIs for logging time-series metrics for RPC-based distributed +// training. Implementations of this class should provide thread safety so that +// metrics can be logged from multiple threads without the user needing to +// coordinate serialization. +class RpcMetricsHandler { + public: + // Accumulates the metric value specified by the name for purposes of + // computing aggregate statistics over time. + virtual void accumulateMetric(const std::string& name, double value) = 0; + // Increment a count for the metric given by the name. + virtual void incrementMetric(const std::string& name) = 0; + virtual ~RpcMetricsHandler() = default; +}; + +// Configuration struct for metrics handling. +struct RpcMetricsConfig { + explicit RpcMetricsConfig(std::string handlerName, bool enabled) + : handlerName_(std::move(handlerName)), enabled_(enabled) {} + + // Handler name + std::string handlerName_; + // Whether metrics exporting should be enabled or not. + bool enabled_; +}; + +// A registry for different implementations of RpcMetricsHandler. Classes +// implementing the above interface should use this to register implementations. +TORCH_DECLARE_REGISTRY( + RpcMetricsHandlerRegistry, + torch::distributed::rpc::RpcMetricsHandler); + +} // namespace torch::distributed::rpc + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/profiler/remote_profiler_manager.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/profiler/remote_profiler_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..ba39ea8a02305f64f642b6927ee43b35459d10b8 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/profiler/remote_profiler_manager.h @@ -0,0 +1,60 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include +#include +#include +#include +#include + +namespace torch::distributed::rpc { +extern const std::string REMOTE_PROFILING_KEY_PREFIX; + +class TORCH_API RemoteProfilerManager { + public: + // Retrieves the lazily-initialized RemoteProfilerManager singleton instance. + static RemoteProfilerManager& getInstance(); + // Sets the current, thread-local profiling key. + void setCurrentKey(std::string key); + // Returns whether the current profiling key is set. + bool isCurrentKeySet() const; + // Unsets the current, thread-local profiling key to allow other RPCs to reset + // it. + void unsetCurrentKey(); + // inserts a pair (globallyUniqueId, key) to an in-memory map. The + // corresponding ID is used in RPC deserialization to prefix remotely profiled + // events with the right key. + void saveRPCKey( + ProfilingId globallyUniqueId, + const std::string& rpcProfilingKey); + // Retrieves the profiling key corresponding to the given globallyUniqueId. + // Throws if it is not found. + std::string retrieveRPCProfilingKey(const ProfilingId& globallyUniqueId); + // Generates the next globally unique ID for profiling. + ProfilingId getNextProfilerId(); + // Retrieves the currently set thread-local profiling key. Throws if it is not + // set. + std::string& getCurrentProfilingKey(); + // erases the globallyUniqueId from the map. This can help save memory in the + // case that many RPCs are being profiled. + void eraseKey(const ProfilingId& globallyUniqueId); + + RemoteProfilerManager(const RemoteProfilerManager& other) = delete; + RemoteProfilerManager operator=(const RemoteProfilerManager& other) = delete; + RemoteProfilerManager(RemoteProfilerManager&&) = delete; + RemoteProfilerManager& operator=(RemoteProfilerManager&&) = delete; + + private: + RemoteProfilerManager(); + ~RemoteProfilerManager() = default; + local_id_t getNextLocalId(); + std::unordered_map + profiledRpcKeys_; + static thread_local std::optional currentThreadLocalKey_; + std::mutex mutex_; + local_id_t currentLocalId_; +}; +} // namespace torch::distributed::rpc + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/profiler/server_process_global_profiler.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/profiler/server_process_global_profiler.h new file mode 100644 index 0000000000000000000000000000000000000000..f86461f6f895bee8a46b54b9f57dd88b66362ad6 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/profiler/server_process_global_profiler.h @@ -0,0 +1,134 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +#include + +namespace torch::distributed::rpc::profiler::processglobal { + +using namespace torch::autograd::profiler; + +// Process global profiler state. +// +// This class holds information about a profiling range, from "enable" to +// "disable". +// An instance of this ``State`` will be +// pushed into a global stack, so nested profiling range is supported. +// +// It has 2 members. +// One is ``autograd::profiler::ProfilerConfig``. It's set by user and +// will be copied to thread-local profiler state of RPC threads. +// The other is a container that aggregates recorded +// ``autograd::profiler::Event``s from all thread-local profilers on RPC +// threads. +class State { + public: + explicit State(ProfilerConfig config) : config_(std::move(config)) {} + ~State() = default; + + const ProfilerConfig& config() const { + return config_; + } + + void pushResult(thread_event_lists result) { + std::unique_lock lock(resultsMutex_); + + // NB: When a thread wants to push an entry into the this container, + // main control logic might have exited the process-global profile range. + results_.emplace_back(std::move(result)); + } + + std::vector results(); + + private: + // Each result comes from a profile range. In each profile range, there is a + // "__profiler_start" marker event that all following events calculate time + // relative to it, so it's required to call + // parse_cpu_trace(result) for results of all profile range. + std::mutex resultsMutex_; + std::vector results_; + const ProfilerConfig config_ = ProfilerConfig(ProfilerState::Disabled); +}; + +class StateStackEntry; + +#if defined(__MACH__) +// Compiler error: 'shared_timed_mutex' is unavailable: introduced in +// macOS 10.12 +using mutexType = std::mutex; +// Compiler error: 'shared_lock' is unavailable: introduced in +// macOS 10.12 +using rLockType = std::unique_lock; +using wLockType = std::unique_lock; +#else +using mutexType = std::shared_timed_mutex; +using rLockType = std::shared_lock; +using wLockType = std::unique_lock; +#endif + +// This is the global stack of ``State``s. +TORCH_API extern std::shared_ptr currentStateStackEntryPtr; +TORCH_API extern mutexType currentStateStackEntryMutex; + +// This class is used to implement a stack of ``State``s. +// It has 2 members. +// One is `prevPtr`, a shared_ptr pointing to previous element in the +// stack. +// The other is ``statePtr``, a shared_ptr pointing to ``State``. +class StateStackEntry { + public: + StateStackEntry( + std::shared_ptr prevPtr, + std::shared_ptr statePtr) + : prevPtr_(std::move(prevPtr)), statePtr_(std::move(statePtr)) {} + + static void pushRange(std::shared_ptr profilerProcessGlobalStatePtr); + static std::shared_ptr popRange(); + + static std::shared_ptr current() { + rLockType rlock(currentStateStackEntryMutex); + + return currentStateStackEntryPtr; + } + + std::shared_ptr prevPtr() const { + return prevPtr_; + } + + std::shared_ptr statePtr() const { + return statePtr_; + } + + private: + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + const std::shared_ptr prevPtr_{nullptr}; + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + const std::shared_ptr statePtr_{nullptr}; +}; + +// Push the result to ``State``s of current profile range and recursively outer +// profile ranges. +TORCH_API void pushResultRecursive( + std::shared_ptr stateStackEntryPtr, + const thread_event_lists& result); + +// User-facing API. +// +// Enter a server-side process-global profiling range. +// Profiling range can be neste, so it's ok to call this API for multiple +// times. This enables all RPC threads running server-side request callbacks. +TORCH_API void enableServer(const ProfilerConfig& new_config); +// +// Exit a server-side process-global profiling range. +// Profiling range can be neste, so it's possible that profiler is still on +// after calling this API. +// This enables all RPC threads running server-side request callbacks. +TORCH_API std::vector disableServer(); + +} // namespace torch::distributed::rpc::profiler::processglobal + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/script_call.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/script_call.h new file mode 100644 index 0000000000000000000000000000000000000000..b4073693ec762921a3816b558a8c76913b940357 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/script_call.h @@ -0,0 +1,72 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include + +namespace torch::distributed::rpc { + +using torch::jit::Operator; + +// A ScriptCall instance represents an invocation of a builtin operator for a +// TorchScript function. If it is a builtin operator, it +// contains a shared ptr to the `Operator` and a list of arguments. +// If it is a TorchScript function, it contains a non empty qualifiedName string +// to the TorchScript function schema name and a list of arguments. +class TORCH_API ScriptCall : public RpcCommandBase { + public: + // Constructor for builtin operator call. + ScriptCall(std::shared_ptr op, std::vector&& stack); + // Constructor for TorchScript function call. + ScriptCall( + const c10::QualifiedName& qualifiedName, + std::vector&& stack, + const bool isAsyncExecution = false); + + bool hasOp() const; + std::shared_ptr op() const; + bool hasQualifiedName() const; + const c10::QualifiedName& qualifiedName() const; + // return the argument stack of this builtin operator + const std::vector& stack() const; + std::vector& stackRef(); + inline bool isAsyncExecution() const { + return isAsyncExecution_; + } + + c10::intrusive_ptr toMessageImpl() && override; + static std::unique_ptr fromMessage(const Message& message); + + ~ScriptCall() override = default; + + protected: + virtual void toIValues(std::vector& ivalues) const; + static std::unique_ptr fromIValues( + std::vector& ivalues); + + private: + // Given an operator symbol and a string schema, return the matched operator. + static std::shared_ptr matchOperator(const std::string& str_schema); + + static const std::string BUILTIN_OP_NAMESPACE_; + static const std::string ATEN_PREFIX_; + + // This field has value if this ScriptCall represents invocation of a builtin + // operator. + std::optional> op_; + // This field has non empty string if this ScriptCall represents invocation of + // an annotated torchscript function defined by users. + std::optional qualifiedName_; + std::vector stack_; + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + const bool isAsyncExecution_; +}; + +} // namespace torch::distributed::rpc + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/script_remote_call.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/script_remote_call.h new file mode 100644 index 0000000000000000000000000000000000000000..6ae72a328d457a150ae78f30c8c4c1d18c4b2664 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/script_remote_call.h @@ -0,0 +1,59 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include + +namespace torch::distributed::rpc { + +using torch::jit::Operator; + +// A ScriptRemoteCall instance represents an invocation of `dist.remote` on a +// builtin operator. Currently, it does not support using RRef as arguments yet. +// Besides the operator and a vector of arguments, ScriptRemoteCall also +// contains the RRefId and the ForkId of the return value RRef. +class TORCH_API ScriptRemoteCall final : public ScriptCall { + public: + // Constructor for builtin operator call. + ScriptRemoteCall( + std::shared_ptr op, + std::vector&& stack, + const RRefId& retRRefId, + const ForkId& retForkId); + + // Constructor for TorchScript function call. + ScriptRemoteCall( + const c10::QualifiedName& qualifiedName, + std::vector&& stack, + const RRefId& retRRefId, + const ForkId& retForkId, + const bool isAsyncExecution); + + inline const RRefId& retRRefId() const { + return retRRefId_; + } + + inline const ForkId& retForkId() const { + return retForkId_; + } + + static std::unique_ptr fromIValues( + std::vector& ivalues); + + c10::intrusive_ptr toMessageImpl() && override; + static std::unique_ptr fromMessage(const Message& message); + + private: + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + const RRefId retRRefId_; + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + const ForkId retForkId_; +}; + +} // namespace torch::distributed::rpc + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/script_resp.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/script_resp.h new file mode 100644 index 0000000000000000000000000000000000000000..e4fb8e7ca92d1389f1501908ad7062b0a223a204 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/script_resp.h @@ -0,0 +1,27 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +namespace torch::distributed::rpc { + +// Return value of a builtin operator or a TorchScript function. +class TORCH_API ScriptResp final : public RpcCommandBase { + public: + explicit ScriptResp(at::IValue&& values); + + const at::IValue& value(); + c10::intrusive_ptr toMessageImpl() && override; + static std::unique_ptr fromMessage(const Message& message); + + private: + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + const at::IValue value_; +}; + +} // namespace torch::distributed::rpc + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/tensorpipe_agent.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/tensorpipe_agent.h new file mode 100644 index 0000000000000000000000000000000000000000..b5f3a788d0cb86657effd94171062c84f0efc0e9 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/tensorpipe_agent.h @@ -0,0 +1,498 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#ifdef USE_TENSORPIPE + +#include +#include + +#include +#include +#include +#include +#include + +// Forward-declare the TensorPipe classes we need, to avoid including its +// headers in PyTorch's ones and thus have it become a public dependency. + +namespace tensorpipe { + +class Context; +class Error; +class Listener; +class Message; +class Pipe; + +namespace transport { +class Context; +} // namespace transport + +namespace channel { +class Context; +} // namespace channel + +} // namespace tensorpipe + +namespace torch::distributed::rpc { + +// These priorities instruct TensorPipe on which transport/channel to pick +// during handshake. Higher priorities will take precedence over lower ones. +// The transport with lowest priority will be the one used to bootstrap pipes. + +constexpr int64_t kShmTransportPriority = 200; +constexpr int64_t kIbvTransportPriority = 100; +// The UV transport just uses TCP and should work everywhere, thus keep it last. +constexpr int64_t kUvTransportPriority = 0; + +constexpr int64_t kCmaChannelPriority = 1200; +constexpr int64_t kMultiplexedUvChannelPriority = 1100; +// The basic channel reuses a transport as a channel, and is thus our fallback. +constexpr int64_t kBasicChannelPriority = 1000; + +// CPU channel have higher priority than CUDA channels, since the latter might +// handle CPU-to-CPU transfers, but will always be less efficient than their +// CPU-only counterparts. +constexpr int64_t kCudaIpcChannelPriority = 300; +constexpr int64_t kCudaGdrChannelPriority = 200; +constexpr int64_t kCudaXthChannelPriority = 400; +constexpr int64_t kCudaBasicChannelPriority = 0; + +using steady_clock_time_point = + std::chrono::time_point; + +struct TORCH_API TransportRegistration { + std::shared_ptr transport; + int64_t priority; + std::string address; +}; + +TORCH_DECLARE_REGISTRY(TensorPipeTransportRegistry, TransportRegistration); + +struct TORCH_API ChannelRegistration { + std::shared_ptr channel; + int64_t priority; +}; + +TORCH_DECLARE_REGISTRY(TensorPipeChannelRegistry, ChannelRegistration); + +struct TORCH_API TensorPipeRpcBackendOptions : public RpcBackendOptions { + TensorPipeRpcBackendOptions( + int numWorkerThreads, + std::optional> transports, + std::optional> channels, + float rpc_timeout, + std::string init_method, + std::unordered_map device_maps = {}, + std::vector devices = {}) + : RpcBackendOptions(rpc_timeout, std::move(init_method)), + numWorkerThreads(numWorkerThreads), + transports(std::move(transports)), + channels(std::move(channels)), + deviceMaps(std::move(device_maps)), + devices(std::move(devices)) { + TORCH_CHECK( + numWorkerThreads > 0, + "num_worker_threads must be positive, got ", + numWorkerThreads); + + if (this->transports.has_value()) { + for (const std::string& transportName : this->transports.value()) { + TORCH_CHECK( + TensorPipeTransportRegistry()->Has(transportName), + "Unknown transport: ", + transportName); + } + } + + if (this->channels.has_value()) { + for (const std::string& channelName : this->channels.value()) { + TORCH_CHECK( + TensorPipeChannelRegistry()->Has(channelName), + "Unknown channel: ", + channelName); + } + } + } + + void setDeviceMap(const std::string& workerName, const DeviceMap& deviceMap) { + auto iter = deviceMaps.find(workerName); + if (iter == deviceMaps.end()) { + deviceMaps[workerName] = deviceMap; + } else { + for (auto& entry : deviceMap) { + // c10::Device has no default constructor, hence map[device] doesn't + // work In C++-17 we can use insert_or_assign. + auto entryIter = iter->second.find(entry.first); + if (entryIter == iter->second.end()) { + iter->second.emplace(entry.first, entry.second); + } else { + entryIter->second = entry.second; + } + } + } + } + + int numWorkerThreads; + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + const std::optional> transports; + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + const std::optional> channels; + std::unordered_map deviceMaps; + std::vector devices; +}; + +// Struct to track the network source metrics +struct TORCH_API NetworkSourceInfo { + worker_id_t srcRank; + std::vector srcMachineAddr; +}; + +// Struct to track aggregated network metrics +struct TORCH_API AggregatedNetworkData { + uint64_t numCalls{0}; + uint64_t totalSentBytes{0}; + uint64_t totalRecvBytes{0}; + uint64_t totalErrors{0}; +}; + +// TensorPipeAgent leverages TensorPipe (https://github.com/pytorch/tensorpipe) +// to transparently move tensors and payloads through the fastest available +// transport or channel. It acts like a hybrid RPC transport, providing shared +// memory (linux) and TCP (linux & mac) support. CUDA support is in progress. +class TORCH_API TensorPipeAgent : public RpcAgent { + public: + TensorPipeAgent( + const c10::intrusive_ptr<::c10d::Store>& store, + std::string selfName, + worker_id_t selfId, + std::optional worldSize, + TensorPipeRpcBackendOptions opts, + std::unordered_map reverseDeviceMaps, + std::vector devices, + std::unique_ptr cb); + + TensorPipeAgent(const TensorPipeAgent&) = delete; + TensorPipeAgent& operator=(const TensorPipeAgent&) = delete; + + c10::intrusive_ptr send( + const WorkerInfo& to, + c10::intrusive_ptr message, + const float rpcTimeoutSeconds = kUnsetRpcTimeout, + const DeviceMap& deviceMap = {}) override; + + // join() and sync() would be deprecated - + // https://github.com/pytorch/pytorch/issues/27647 + void join(bool shutdown = false, float timeout = 0) override; + void sync() override {} + void startImpl() override; + void shutdownImpl() override; + + ~TensorPipeAgent() override; + + const WorkerInfo& getWorkerInfo(const std::string& workerName) const override; + const WorkerInfo& getWorkerInfo(worker_id_t workerId) const override; + std::vector getWorkerInfos() const override; + void updateGroupMembership( + const WorkerInfo& workerInfo, + const std::vector& devices, + const std::unordered_map& reverseDeviceMaps, + bool isJoin); + + std::unordered_map getMetrics() override; + + void addGilWaitTime(const std::chrono::microseconds gilWaitTime) override; + + TensorPipeRpcBackendOptions getBackendOptions() const; + + const c10::intrusive_ptr<::c10d::Store> getStore() const; + + DeviceMap getDeviceMap(const WorkerInfo& dest) const override; + + const std::vector& getDevices() const override; + + using NetworkDataDict = + std::unordered_map; + + // Returns metrics tracked by the NetworkDataDict + NetworkDataDict getNetworkData(); + // Returns NetworkSourceInfo struct + NetworkSourceInfo getNetworkSourceInfo(); + + static const std::string& guessAddress(); + + // For testing purposes. + size_t timeoutMapSize(); + size_t numPendingResponses(); + size_t messageIdToTimeoutMapSize(); + + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + const bool isStaticGroup_; + + protected: + // TensorPipe write function that could be used to write response + // messages by server, and write request messages by client. This + // is a protected method since it is overwritten by FaultyTensorPipeAgent + virtual void pipeWrite( + const std::shared_ptr& /*pipe*/, + const c10::intrusive_ptr& message, + std::vector&& devices, + std::vector streams, + std::function /*fn*/) noexcept; + + private: + // Removes the given messageId with the given expirationTime from the + // timeoutMap_. + void removeFromTimeoutMap(uint64_t messageId); + + // Populates workerIdToInfo_ and workerNameToInfo_ using addressStore_ + void prepareNames(bool isStaticGroup); + + // Check the static group attribute with the value set in store + void checkAndSetStaticGroup(const c10::intrusive_ptr<::c10d::Store>& store); + + const std::string& findWorkerURL(const WorkerInfo& worker) const; + + // Only use for Dynamic RPC groups, method to have worker leave group + void leaveGroup(); + + // TensorPipe read function that could be used to read response messages + // by client, and read request messages by server. + void pipeRead( + const std::shared_ptr& /*pipe*/, + std::function, + std::vector)> /*fn*/) noexcept; + + // Callback of listener accept() + void onListenerAccepted( + const tensorpipe::Error& error, + std::shared_ptr& pipe); + + // Respond to a call from a peer + void respond(std::shared_ptr& pipe); + + void sendCompletedResponseMessage( + std::shared_ptr& pipe, + JitFuture& futureResponseMessage, + uint64_t messageId, + std::vector stream); + + // Collects metrics from successful RPC calls + void trackNetworkData( + uint64_t requestSize, + uint64_t responseSize, + const std::string& destWorkerName); + + // Collects metrics from failed RPC calls + void trackNetworkError( + uint64_t requestSize, + const std::string& destWorkerName); + + inline std::vector getDevicesForRemote( + const std::string& remoteName, + const Message& message) const; + + // When a request+response completes, we need to mark the future message as + // complete. However, if its timeout has already expired, it already has an + // error set. There is no atomic "test-and-set" way to mark a future complete + // only if it isn't yet. It does exist for errors (setErrorIfNeeded) but, even + // then, it ends up printing a log message, which may worry the user. To solve + // both issues we use a separate atomic flag to know the status of the future. + struct AtomicJitFuture { + explicit AtomicJitFuture(const std::vector& devices) { + jitFuture = c10::make_intrusive( + at::AnyClassType::get(), devices); + } + + std::atomic_flag isComplete = ATOMIC_FLAG_INIT; + c10::intrusive_ptr jitFuture; + }; + + // Maintains state per client pipe to track pending response messages and + // error states. pendingResponseMessage_ should be protected by a mutex since + // it can be raced with user send() call. + // TODO: To achieve better performance we can have a pipe pool per + // client that can be configured using RpcBackendOptions. + struct ClientPipe { + explicit ClientPipe(std::shared_ptr pipe) + : pipe_(std::move(pipe)) {} + std::shared_ptr pipe_; + mutable std::mutex mutex_; + bool inError_{false}; + // Map from Message Request ID's to corresponding futures. + std::unordered_map> + pendingResponseMessage_; + }; + + const c10::intrusive_ptr<::c10d::Store> store_; + + const TensorPipeRpcBackendOptions opts_; + // For dynamic RPC, the reverse device maps are updated whenever a new rank + // joins or leaves the group + std::unordered_map reverseDeviceMaps_; + // Local devices used by this agent. If application didn't specify this + // field, it will be initialized using corresponding local devices in + // opts_.deviceMaps and reverseDeviceMaps_; + std::vector devices_; + + ThreadPool threadPool_; + std::shared_ptr context_; + std::shared_ptr listener_; + + mutable std::mutex connectedPipesMutex_; + std::unordered_map connectedPipes_; + + // Maps keyed on name and id for easy WorkerInfo lookup. + std::unordered_map workerIdToInfo_; + std::unordered_map workerNameToInfo_; + std::unordered_map workerNameToURL_; + + ::c10d::PrefixStore rankToNameStore_; + ::c10d::PrefixStore nameToAddressStore_; + // Store keys that will used to count joined processes and active calls during + // the shutdown process + ::c10d::PrefixStore shutdownStore_; + int worldSize_ = 0; + std::atomic nextMessageID_{0}; + + // Metadata used for tracking of whether certain RPCs have timed out or not. + struct TimeoutMessageMetadata { + TimeoutMessageMetadata( + uint64_t messageId_, + std::shared_ptr responseFuture_, + std::chrono::milliseconds timeout_) + : messageId(messageId_), + responseFuture(std::move(responseFuture_)), + timeout(timeout_) {} + uint64_t messageId; + std::shared_ptr responseFuture; + std::chrono::milliseconds timeout; + }; + + // Map to store the expiration times for each message. + std::map> + timeoutMap_; + + // Map to store the messageId to expiry time. + std::unordered_map messageIdToTimeout_; + + // Thread that will poll the timeoutMap_ for timed out messages and mark them + // with an error accordingly + std::thread timeoutThread_; + + // Function run by the timeoutThread_ to check for timed out RPCs + void pollTimeoutRpcs(); + + // Mutex to guard the timeoutMap_ + std::mutex timeoutMapMutex_; + + // Condition Variable to signal population of the timeoutMap_ + std::condition_variable timeoutThreadCV_; + + // Returns the expiration time for an RPC by adding the current time to the + // passed in timeout. + inline steady_clock_time_point computeRpcMessageExpiryTime( + std::chrono::milliseconds timeout) const { + return std::chrono::time_point_cast( + std::chrono::steady_clock::now() + timeout); + } + + // Handle error on an outgoing pipe + void handleClientError( + ClientPipe& clientPipe, + const tensorpipe::Error& error); + + // This is a generic struct for capturing Time-Series Metrics. It keeps a + // running sum and count of data points (observations), and can return an + // average of the data points seen so far. This is currently only used for + // tracking the GIL Wait Time in RPC Agents, but can be used for other metrics + // as well. + struct TimeSeriesMetricsTracker { + // Running sum of the data points seen so far + uint64_t currentSum_; + // Running count of the data points seen so far + uint64_t currentCount_; + + explicit TimeSeriesMetricsTracker( + uint64_t currentSum = 0, + uint64_t currentCount = 0); + + // Adds a data point (which is basically one observation for the metric + // being tracked) to the running sum and count. + void addData(uint64_t dataPoint); + // Returns the average of all the data points seen so far. + float computeAverage() const; + }; + + // Map of Time-Series metrics tracked by the RPC Agent + std::unordered_map timeSeriesMetrics_; + // Mutex to guard timeSeriesMetrics_ + std::mutex metricsMutex_; + + // Custom lock guard used to check if the RPC group is dynamic and lock the + // mutex if so + struct GroupMembershipLockGuard { + GroupMembershipLockGuard(std::mutex& mutex, bool isStaticGroup) + : ref_(mutex), isStaticGroup_(isStaticGroup) { + if (isStaticGroup_) { + ref_.lock(); + } + } + + ~GroupMembershipLockGuard() { + if (isStaticGroup_) { + ref_.unlock(); + } + } + + GroupMembershipLockGuard(const GroupMembershipLockGuard&) = delete; + + private: + std::mutex& ref_; + bool isStaticGroup_; + }; + // Mutex to guard access to group membership data + // e.g. updates to (workerIdToInfo_, workerNameToInfo_, workerNameToURL_) + mutable std::mutex groupMembershipMutex_; + + // Map to Track Network Data + NetworkDataDict networkData_; + // Mutex to guard networkData_ + std::mutex networkDataMutex_; + + // A mutex and a cv to guard access to the call counts and watch for changes. + std::mutex callCountMutex_; + std::condition_variable callCountCV_; + // Running total of un-processed, un-errored RPC calls sent + int32_t clientActiveCalls_{0}; + // Running total of un-processed RPC requests received + int32_t serverActiveCalls_{0}; + // Running total of RPC requests that will be completed asynchronously + int32_t serverActiveAsyncCalls_{0}; + + // Whether a global graceful shutdown has begun, in which case we'll silence + // error messages due to remote workers closing their pipes. + std::atomic shuttingDown_{false}; + + // Helpers to modify the counts while correctly dealing with the mutex and cv. + void increaseCallCount(int32_t& count); + void decreaseCallCount(int32_t& count); + + // Helpers to set the state of the requests. + void markFutureAsComplete( + std::shared_ptr atomicFuture, + c10::intrusive_ptr message, + std::vector streams); + void markFutureWithError( + std::shared_ptr atomicFuture, + std::string errorMsg); +}; + +} // namespace torch::distributed::rpc + +#endif // USE_TENSORPIPE + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/tensorpipe_utils.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/tensorpipe_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..025e143190c2df7c2898f03187e70064619bbf3c --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/tensorpipe_utils.h @@ -0,0 +1,124 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#ifdef USE_TENSORPIPE + +#include + +namespace tensorpipe { +class Message; +class Allocation; +class Descriptor; +} // namespace tensorpipe + +namespace torch::distributed::rpc { + +TORCH_API const c10::Stream& getStreamForDevice( + const std::vector& streams, + const c10::Device& device); + +// Inspired by c10/core/impl/DeviceGuardImplInterface.h. + +class TensorpipeDeviceTypeConverter { + public: + // Ideally we'd want this to also return a tensorpipe::Message::Tensor object + // but we cannot forward-declare that class (because it's nested), and we + // cannot include the TensorPipe headers because it's a private dependency. + // Thus we bend over backwards and entrust this method with appending that + // object to the `tensors` field of the tensorpipe::Message object we pass. + virtual std::optional> prepareTensorForSending( + const c10::Storage& storage, + const std::vector& streams, + tensorpipe::Message& message) const = 0; + + // Same as above: this method cannot return a tensorpipe::Allocation::Tensor, + // thus it appends it to the `tensors` field of the tensorpipe::Allocation. + virtual at::DataPtr allocateTensorForReceiving( + c10::DeviceIndex deviceIndex, + size_t length, + const std::vector& streams, + tensorpipe::Allocation& allocation) const = 0; + + virtual ~TensorpipeDeviceTypeConverter() = default; +}; + +extern TORCH_API std::array< + std::atomic, + static_cast(DeviceType::COMPILE_TIME_MAX_DEVICE_TYPES)> + device_type_converter_registry; + +class TORCH_API TensorpipeDeviceTypeConverterRegistrar { + public: + TensorpipeDeviceTypeConverterRegistrar( + DeviceType /*type*/, + const TensorpipeDeviceTypeConverter* /*impl*/); +}; + +#define C10_REGISTER_TENSORPIPE_DEVICE_TYPE_CONVERTER( \ + DevType, TensorpipeDeviceTypeConverter) \ + static ::torch::distributed::rpc::TensorpipeDeviceTypeConverterRegistrar \ + C10_ANONYMOUS_VARIABLE(g_##DeviceType)( \ + ::c10::DeviceType::DevType, new TensorpipeDeviceTypeConverter()); + +inline const TensorpipeDeviceTypeConverter* getDeviceTypeConverter( + DeviceType type) { + return device_type_converter_registry[static_cast(type)].load(); +} + +// A struct that holds pointers that keep alive all the memory that will be +// accessed by TensorPipe during a write operation. +struct TensorpipeWriteBuffers { + // Allocate on heap so pointers stay valid as we move the holder. + std::unique_ptr type; + std::unique_ptr id; + std::vector payload; + std::vector pickle; + // This contains the original tensors and the clones of the sparse tensors. + std::vector tensors; + // This contains the copies of the data of the tensors that didn't own their + // memory, e.g., the ones created from torch::from_blob() with no deleter. + std::vector> copiedTensors; +}; + +// A struct that holds pointers that keep alive all the memory that will be +// accessed by TensorPipe during a read operation. +struct TensorpipeReadBuffers { + // Allocate on heap so pointers stay valid as we move the holder. + std::unique_ptr type; + std::unique_ptr id; + std::vector payload; + std::vector pickle; + std::vector tensors; +}; + +// Convert an RPC message into a TensorPipe message, plus a holder to all the +// data that must be kept alive while the write is performed asynchronously. +TORCH_API std::tuple +tensorpipeSerialize( + const c10::intrusive_ptr& rpcMessage, + std::vector devices, + const std::vector& streams); + +// Allocate the buffers that will hold the incoming data. They will be managed +// by the returned holder, which must be kept alive until the asynchronous read +// has finished. Pointers to these buffers will be stored in the returned +// tensorpipe::Allocation struct. +TORCH_API std::pair +tensorpipeAllocate( + const tensorpipe::Descriptor& tpDescriptor, + const std::vector& streams); + +// Convert a TensorPipe message back into an RPC message. This requires the data +// to be available and can thus only be performed once the asynchronous read has +// completed. The holder can be destroyed once this function returns. +TORCH_API c10::intrusive_ptr tensorpipeDeserialize( + const tensorpipe::Descriptor& tpDescriptor, + TensorpipeReadBuffers&& holder); + +} // namespace torch::distributed::rpc + +#endif // USE_TENSORPIPE + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/testing/faulty_tensorpipe_agent.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/testing/faulty_tensorpipe_agent.h new file mode 100644 index 0000000000000000000000000000000000000000..c0adb349f2095a721970b5bfdd9acd7141abe827 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/testing/faulty_tensorpipe_agent.h @@ -0,0 +1,109 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#ifdef USE_TENSORPIPE + +#include +#include + +namespace torch::distributed::rpc { + +struct TORCH_API FaultyTensorPipeRpcBackendOptions + : public TensorPipeRpcBackendOptions { + FaultyTensorPipeRpcBackendOptions( + int num_worker_threads, + float rpc_timeout, + std::string init_method, + std::vector messages_to_fail, + std::unordered_map messages_to_delay, + int num_fail_sends = 0) + : TensorPipeRpcBackendOptions( + num_worker_threads, + std::optional>(), + std::optional>(), + rpc_timeout, + std::move(init_method)), + messagesToFail(std::move(messages_to_fail)), + messagesToDelay(std::move(messages_to_delay)), + numFailSends(num_fail_sends) { + TORCH_CHECK(numFailSends >= 0, "numFailSends should be non-negative"); + } + + std::vector messagesToFail; + std::unordered_map messagesToDelay; + int numFailSends; +}; + +class TORCH_API FaultyTensorPipeAgent : public TensorPipeAgent { + public: + FaultyTensorPipeAgent( + const c10::intrusive_ptr<::c10d::Store>& store, + std::string selfName, + worker_id_t selfId, + int worldSize, + FaultyTensorPipeRpcBackendOptions opts, + std::unordered_map reverseDeviceMaps, + std::vector devices, + std::unique_ptr callback); + + // Faulty send function for this class. + c10::intrusive_ptr send( + const WorkerInfo& to, + c10::intrusive_ptr message, + const float rpcTimeoutSeconds = torch::distributed::rpc::kUnsetRpcTimeout, + const DeviceMap& deviceMap = {}) override; + + // Add delay to writes + void pipeWrite( + const std::shared_ptr& pipe, + const c10::intrusive_ptr& rpcMessage, + std::vector&& devices, + std::vector streams, + std::function fn) noexcept override; + + protected: + // This function checks the messageTypesToFail_ to determine whether to use + // the faulty send or not. + bool shouldFailMessage(MessageType type) const; + + private: + // This function parses the list of strings passed in by the python tests and + // resolves the Message Types that must use the faulty send. + std::vector parseMessagesToFailInput( + const std::vector& messagesToFail) const; + + // Returns amount of time in seconds to delay sending of the given message + // type. + float getDelayForMessage(MessageType type) const; + + // Parse message types that we should inject arbitrary delays for. + std::unordered_map> parseMessagesToDelay( + const std::unordered_map& messageTypesToDelay) const; + + // Number of sends to intentionally fail before allowing one to succeed. + const int numFailSends_; + + // Vector of the MessageTypes that we must use the faulty send for. This is + // parsed based on a list of strings passed in by the python tests. + const std::vector messageTypesToFail_; + + // Mapping of message types to amount we should delay send for in the ::send() + // function. + std::unordered_map> messageTypesToDelay_; + + // Map to track the number of sends we've failed for each RPC. + std::unordered_map failMessageCountMap_; + + // Mutex to guard failMessageCountMap_ + std::mutex failMapMutex_; + + MessageType messageStringToType(const std::string& messageString) const; +}; + +} // namespace torch::distributed::rpc + +#endif // USE_TENSORPIPE + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/testing/testing.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/testing/testing.h new file mode 100644 index 0000000000000000000000000000000000000000..baf94a5397fe21394cf9ab024800a29cbc4fe9d6 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/testing/testing.h @@ -0,0 +1,14 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::distributed::rpc::testing { + +PyMethodDef* python_functions(); + +} // namespace torch::distributed::rpc::testing + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/torchscript_functions.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/torchscript_functions.h new file mode 100644 index 0000000000000000000000000000000000000000..37c6975d05559d13de07463d279ea11cab121f79 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/torchscript_functions.h @@ -0,0 +1,42 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include + +namespace torch::distributed::rpc { + +// This function sends an rpc call to run torchscript function, currently the +// torchscript function could only be a user defined python function with +// "@torch.jit.script" annotation. The torchscript function could not be +// a class constructor, class method, instance method or a script module. +// dst: destination worker name +// qualifiedName: torchscript function qualified name string like +// "moduleName::torchscriptFunctionName", e.g, +// "dist_autograd_test::my_py_add" +// stack: a bag of IValue args passed to torchscriptFunctionName +// It returns c10::intrusive_ptr +c10::intrusive_ptr TORCH_API rpcTorchscript( + const std::string& dstWorkerName, + const c10::QualifiedName& qualifiedName, + const c10::FunctionSchema& functionSchema, + std::vector stack, + const float rpcTimeoutSeconds = torch::distributed::rpc::kUnsetRpcTimeout, + const bool isAsyncExecution = false); + +c10::intrusive_ptr TORCH_API remoteTorchscript( + const std::string& dstWorkerName, + const c10::QualifiedName& qualifiedName, + const c10::FunctionSchema& functionSchema, + std::vector& stack, + const float rpcTimeoutSeconds = torch::distributed::rpc::kUnsetRpcTimeout, + const bool isAsyncExecution = false); + +} // namespace torch::distributed::rpc + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/types.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/types.h new file mode 100644 index 0000000000000000000000000000000000000000..f8ec54b86e986a64fd2f55d2c35e1d5c594f30f4 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/types.h @@ -0,0 +1,75 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::distributed::rpc { + +using worker_id_t = int16_t; +using local_id_t = int64_t; + +bool getAllowJitRRefPickle(); +TORCH_API void enableJitRRefPickle(); +TORCH_API void disableJitRRefPickle(); + +struct TORCH_API JitRRefPickleGuard { + JitRRefPickleGuard(); + JitRRefPickleGuard(JitRRefPickleGuard&& other) = delete; + JitRRefPickleGuard(const JitRRefPickleGuard&) = delete; + JitRRefPickleGuard& operator=(const JitRRefPickleGuard&) = delete; + JitRRefPickleGuard& operator=(JitRRefPickleGuard&&) = delete; + ~JitRRefPickleGuard(); +}; + +struct TORCH_API GloballyUniqueId final { + GloballyUniqueId(worker_id_t createdOn, local_id_t localId); + GloballyUniqueId(const GloballyUniqueId& other) = default; + GloballyUniqueId& operator=(const GloballyUniqueId& other) = delete; + GloballyUniqueId(GloballyUniqueId&& other) = default; + GloballyUniqueId& operator=(GloballyUniqueId&& other) = delete; + ~GloballyUniqueId() = default; + + bool operator==(const GloballyUniqueId& other) const; + bool operator!=(const GloballyUniqueId& other) const; + + at::IValue toIValue() const; + static GloballyUniqueId fromIValue(const at::IValue& /*ivalue*/); + + struct Hash { + size_t operator()(const GloballyUniqueId& key) const { + return (uint64_t(key.createdOn_) << kLocalIdBits) | key.localId_; + } + }; + + static constexpr int kLocalIdBits = 48; + + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + const worker_id_t createdOn_; + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + const local_id_t localId_; +}; + +TORCH_API std::ostream& operator<<( + std::ostream& os, + const GloballyUniqueId& globalId); + +using RRefId = GloballyUniqueId; +using ForkId = GloballyUniqueId; +using ProfilingId = GloballyUniqueId; + +struct TORCH_API SerializedPyObj final { + SerializedPyObj(std::string&& payload, std::vector&& tensors) + : payload_(std::move(payload)), tensors_(std::move(tensors)) {} + + std::vector toIValues() &&; + static SerializedPyObj fromIValues(std::vector value); + + std::string payload_; + std::vector tensors_; +}; + +} // namespace torch::distributed::rpc + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/unpickled_python_call.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/unpickled_python_call.h new file mode 100644 index 0000000000000000000000000000000000000000..da76292342019059afd7d1c868c7cac1e375fd88 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/unpickled_python_call.h @@ -0,0 +1,43 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +namespace torch::distributed::rpc { + +// This class converts the content in a PythonCall into py::object. This is a +// helper class to make sure that all arguments deserialization is done before +// entering RequestCallbackImpl::processRpc(...), so that the deserialization +// related logic can be carried out in one spot instead of scattered in multiple +// places for different message types. +// NB: The reason for not consolidating class into PythonCall is because +// PythonCall is a libtorch type which should not depend on Python types. +class TORCH_API UnpickledPythonCall : public RpcCommandBase { + public: + UnpickledPythonCall( + const SerializedPyObj& serializedPyObj, + bool isAsyncExecution); + ~UnpickledPythonCall() override; + + // toMessage() method is not implemented, as objects of this class should + // never be directly converted into a Message object. + c10::intrusive_ptr toMessageImpl() && override; + const py::object& pythonUdf() const; + + inline bool isAsyncExecution() const { + return isAsyncExecution_; + } + + private: + py::object pythonUdf_; + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + const bool isAsyncExecution_; +}; + +} // namespace torch::distributed::rpc + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/unpickled_python_remote_call.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/unpickled_python_remote_call.h new file mode 100644 index 0000000000000000000000000000000000000000..afe8a977a615e59b2f77e180275e9fc0e6adc92b --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/unpickled_python_remote_call.h @@ -0,0 +1,38 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include + +namespace torch::distributed::rpc { + +// This class converts the content in a PythonRemoteCall into py::object. This +// is a helper class to make sure that all arguments deserialization is done +// before entering RequestCallbackImpl::processRpc(...), so that the +// deserialization related logic can be carried out in one spot instead of +// scattered in multiple places for different message types. +// NB: The reason for not consolidating class into PythonRemoteCall is because +// PythonRemoteCall is a libtorch type which should not depend on Python types. +class TORCH_API UnpickledPythonRemoteCall final : public UnpickledPythonCall { + public: + explicit UnpickledPythonRemoteCall( + const SerializedPyObj& serializedPyObj, + const at::IValue& retRRefId, + const at::IValue& retForkId, + const bool isAsyncExecution); + + const RRefId& rrefId() const; + const ForkId& forkId() const; + + private: + RRefId rrefId_; + ForkId forkId_; +}; + +} // namespace torch::distributed::rpc + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/utils.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/utils.h new file mode 100644 index 0000000000000000000000000000000000000000..324d76b2e4dc48b6b12b593fa58c198daa723ad9 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/utils.h @@ -0,0 +1,91 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +namespace torch::distributed::rpc { + +// Parse error message and return RPCErrorType based on the message. +TORCH_API RPCErrorType getRPCErrorType(const JitFuture& jitFuture); +// Create an error string given the error description and error type +TORCH_API std::string makeRPCError( + const std::string& rpcErrorStr, + RPCErrorType errorType); + +// Given an RPC message received as a request over the wire, deserialize it into +// the appropriate 'RpcCommandBase' type. +TORCH_API std::unique_ptr deserializeRequest( + const Message& request); + +// Given an RPC message received as a response over the wire, deserialize it +// into the appropriate 'RpcCommandBase' type, if the response is +// FORWARD_AUTOGRAD_RESP type, unwrap it, attach recvBackward() functions +// to received tensors and set the wrappedMsgType to its wrapped message type. +TORCH_API std::unique_ptr deserializeResponse( + const Message& response, + MessageType& wrappedMsgType); + +// Given an RPC message received as a response over the wire, deserialize it +// into the valid IValue if the message is for a script rpc result, +// otherwise deserialize it into dummy none ivalue that will never be used. +// In this deserialization, we also attach recv rpc backward functions if +// needed. +IValue deserializeResptoIValueInternal( + RpcCommandBase& rpc, + MessageType messageType); +TORCH_API IValue deserializeRespToIValue(const Message& message); + +// Note: format is subject to change and intended for RPCs. +// For saving persistently to disk, use torch::save(). +TORCH_API std::string wireSerialize( + const std::vector& payload, + const std::vector& tensors); + +TORCH_API std::pair, std::vector> wireDeserialize( + const void* data, + size_t data_size); + +// We use vector as the type of blobs because it's what rpc::Message uses +// for its payload, even though it has the disadvantage that it cannot be +// allocated with uninitialized memory: it is always zeroed out. + +// Some Tensors are effectively views of larger Tensors, where only a small +// subset of the Storage data is referenced. This normally is good and avoids +// copies when kept locally, but if we naively push the whole Storage over the +// wire, we'll end up with excess network traffic. This change clones tensors if +// we'd save at least half the data, and over a minimum hurdle. +TORCH_API c10::List cloneSparseTensors( + const std::vector& tensors); + +// Combines an original payload and wrapped payload into the original payload. +// Used to generate the overall payload for the wrapped RPC. +TORCH_API void writeWrappedPayload( + std::vector& originalPayload, + std::vector& additionalPayload); + +// Reads the additional, wrapped payload from a wrapped RPC off of the input +// payload. After this, payload will contain the payload of the original, +// un-wrapped RPC. +TORCH_API std::vector readWrappedPayload( + std::vector& payload, + const rpc::Message& message); + +// Takes a list of events from autograd profiler and populates them into +// profiledEvents to be carried over RPC. +TORCH_API void populateRemoteProfiledEvents( + std::vector& profiledEvents, + const torch::autograd::profiler::ProfilerConfig& profilerConfig, + const std::vector>& + eventLists); + +} // namespace torch::distributed::rpc + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/cache_entry.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/cache_entry.h new file mode 100644 index 0000000000000000000000000000000000000000..c178ce57cf456cbd3e7bc3913364e37d80b5c592 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/cache_entry.h @@ -0,0 +1,100 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +#ifdef __cplusplus + +#include +#include +#include + +extern "C" { + +#endif + +/* +Our cache resides on the extra scratch space of the code object. The structure +of the cache is as follows: + +-> ExtraState + -> CacheEntry (list) + -> guard_manager (a wrapper that contains the actual guard manager at its +attr named root) + -> code + -> FrameState + +CacheEntry is a linked list node containing the guard_manager for guards +and the optimized code. + +The FrameState is a PyDict that enables sharing between different frames. This +is used to detect dynamism in automatic dynamic shapes. + +These two are encapsulated into a ExtraState. +*/ + +typedef struct CacheEntry CacheEntry; +typedef struct ExtraState ExtraState; + +#ifdef __cplusplus + +C10_DIAGNOSTIC_PUSH_AND_IGNORED_IF_DEFINED( + "-Wdeprecated-copy-with-user-provided-dtor") +C10_DIAGNOSTIC_PUSH_AND_IGNORED_IF_DEFINED("-Wdeprecated-copy-dtor") +// NOLINTNEXTLINE(cppcoreguidelines-special-member-functions) +typedef struct VISIBILITY_HIDDEN CacheEntry { + // check the guards: lambda: : bool + py::object guard_manager; + // modified user bytecode (protected by guard_manager's guards) + py::object code; + // CompileId corresponding to this compilation + py::object compile_id; + // root guard manager if exists + void* root_mgr{nullptr}; + // diff guard root guard manager if exists + void* diff_guard_root_mgr{nullptr}; + // backend used to create this cache entry + py::object backend; + // Reference to owning ExtraState + ExtraState* _owner{nullptr}; + // Reference to this CacheEntry's location in owner's linked list + std::list::iterator _owner_loc; + // Reference to string representation of the CompileContext + std::string trace_annotation; + + CacheEntry(const py::handle& guarded_code, PyObject* backend); + CacheEntry(const CacheEntry&) = default; + CacheEntry(CacheEntry&&) = default; + CacheEntry& operator=(const CacheEntry&) = default; + CacheEntry& operator=(CacheEntry&&) = default; + ~CacheEntry(); + + // Warning: returns a reference whose lifetime is controlled by C++ + py::object next(); + + void invalidate(py::object deleted_guard_manager); + // Called from the python side to update the diff guard root manager + void update_diff_guard_root_manager(); +} CacheEntry; +C10_DIAGNOSTIC_POP() +C10_DIAGNOSTIC_POP() + +#endif + +// Returns borrowed reference +PyCodeObject* CacheEntry_get_code(CacheEntry* e); + +// Returns borrowed string representation of CompileContext +const char* CacheEntry_get_trace_annotation(CacheEntry* e); + +// Returns a borrowed reference to CacheEntry as a PyObject +// Warning: lifetime is controlled by C++ +PyObject* CacheEntry_to_obj(CacheEntry* e); + +#ifdef __cplusplus +} // extern "C" +#endif + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/compiled_autograd.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/compiled_autograd.h new file mode 100644 index 0000000000000000000000000000000000000000..294641783728f9968e9e10beb5b872e11f6cf879 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/compiled_autograd.h @@ -0,0 +1,1566 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// see [Note: Compiled Autograd] + +namespace torch::dynamo::autograd { +using namespace torch::autograd; + +// This is a layer of indirection for calling methods on the Python +// AutogradCompilerInstance (referred to as the "py_compiler") from +// libtorch_cpu (where Python is not available). +// A PyCompilerInterfaceImpl in libtorch_python subclasses it and +// overrides the methods to do the actual calls back to Python. +struct TORCH_API PyCompilerInterface { + PyCompilerInterface() = default; + PyCompilerInterface(const PyCompilerInterface&) = delete; + PyCompilerInterface& operator=(const PyCompilerInterface&) = delete; + PyCompilerInterface(PyCompilerInterface&&) = delete; + PyCompilerInterface& operator=(PyCompilerInterface&&) = delete; + virtual ~PyCompilerInterface() = default; + + // Invokes py_compiler.bind_function + virtual std::string bind_function( + PyObject* py_compiler, + const std::string& fn_name, + // NOLINTNEXTLINE(performance-unnecessary-value-param) + functional_apply_t fn, + // NOLINTNEXTLINE(performance-unnecessary-value-param) + std::vector packed_args_schema, + bool is_custom_function = false, + bool is_traceable = true) const { + TORCH_INTERNAL_ASSERT(false, "Needs to be overridden"); + } + + // Invokes py_compiler.method_name(fn_name, inputs, packed_args, + // output_metadata) + virtual variable_list call_function( + PyObject* py_compiler, + const char* method_name, + const std::string& fn_name, + const variable_list& inputs, + const ivalue_list& packed_args, + const c10::IValue& output_metadata) const { + TORCH_INTERNAL_ASSERT(false, "Needs to be overridden"); + } + virtual variable_list call_copy_slices_prologue( + PyObject* py_compiler, + const variable_list& inputs, + const at::TensorGeometry& base, + const at::TensorGeometry& view) const { + TORCH_INTERNAL_ASSERT(false, "Needs to be overridden"); + } + virtual variable_list call_copy_slices_epilogue( + PyObject* py_compiler, + const std::vector& needs_input_grad, + const at::Tensor& result, + const variable_list& res, + const at::Tensor& grad_slice) const { + TORCH_INTERNAL_ASSERT(false, "Needs to be overridden"); + } + virtual at::Tensor call_unpack( + PyObject* py_compiler, + std::optional hook_id, + size_t hook_input_id) const { + TORCH_INTERNAL_ASSERT(false, "Needs to be overridden"); + } + virtual void call_accumulate_grad( + PyObject* py_compiler, + const at::Tensor& variable, + const at::Tensor& grad, + bool has_post_hooks) const { + TORCH_INTERNAL_ASSERT(false, "Needs to be overridden"); + } +}; + +TORCH_API const std::unique_ptr& getPyCompilerInterface(); +struct TORCH_API PyCompilerGuard { + explicit PyCompilerGuard(std::unique_ptr&& impl); + PyCompilerGuard(const PyCompilerGuard&) = delete; + PyCompilerGuard& operator=(const PyCompilerGuard&) = delete; + PyCompilerGuard(PyCompilerGuard&&) = delete; + PyCompilerGuard& operator=(PyCompilerGuard&&) = delete; + + ~PyCompilerGuard(); +}; + +// including torch/csrc/autograd/engine.h breaks BC by somehow introducing +// symbol resolution issues. Instead requiring downstream users to include +// engine.h to access collect_input_metadata, we provide it here (with a +// different name to avoid ambiguous symbols...) +TORCH_API std::vector> get_input_metadata( + const edge_list& edges); + +struct SizeInput { + // Note: int value is still needed when dynamic to pass as an arg + enum DynType : uint8_t { STATIC = 0, DYNAMIC = 1 }; + SizeInput(DynType dt, int64_t v) : dyn_type(dt), value(v) {} + DynType dyn_type; + int64_t value; +}; + +struct CacheKeyBuffer { + CacheKeyBuffer(const uint8_t* key, uint16_t len) : data(new uint8_t[len]) { + std::memcpy(data.get(), key, len); + } + const uint8_t* get() const { + return data.get(); + } + + private: + // NOLINTNEXTLINE(*c-array*) + std::unique_ptr data; +}; + +struct CacheKey { + // Key to find the next node in the shadow graph. We use C++ RTTI for the + // type of the node (ntype), then a key generated with a visitor pattern. + CacheKey(const std::type_index& ntype, const uint8_t* key, uint16_t len) + : node_type(ntype), key_size(len), key(key) {} + + bool operator<(const CacheKey& other) const { + if (node_type != other.node_type) { + return node_type < other.node_type; + } + if (key_size != other.key_size) { + return key_size < other.key_size; + } + return std::memcmp(key, other.key, key_size) < 0; + } + + bool operator==(const CacheKey& other) const { + return node_type == other.node_type && key_size == other.key_size && + std::memcmp(key, other.key, key_size) == 0; + } + + size_t hash() const { + // don't bother hashing the key data, common case 1 cache entry per node + return std::hash()(node_type) ^ key_size; + } + + std::type_index node_type; + uint16_t key_size; + const uint8_t* key; +}; + +struct NodeCall { + NodeCall(uint32_t id_, std::shared_ptr node_) + : id(id_), node(std::move(node_)) {} + + void mark_output(int input_nr, int output_idx) { + graph_output.emplace_back(input_nr, output_idx); + } + + uint32_t id; + std::shared_ptr node; + std::vector> tensor_pre_hooks; + std::vector> cpp_tensor_pre_hooks; + std::vector pre_hooks; + std::vector post_hooks; + std::vector post_acc_grad_hooks; + std::vector> graph_output; + bool needed = true; +}; + +struct NodeCalls : public std::unordered_map { + NodeCall& lookup(const std::shared_ptr& function) { + auto it = find(function.get()); + if (it == end()) { + it = emplace(function.get(), NodeCall(_next_id++, function)).first; + nodes.emplace_back(function.get()); + } + return it->second; + } + + const NodeCall& lookup(uint32_t id) const { + TORCH_INTERNAL_ASSERT(id < nodes.size()); + auto it = find(nodes[id]); + TORCH_INTERNAL_ASSERT(it != end()); + return it->second; + } + + void clear() { + _next_id = 0; + std::unordered_map::clear(); + nodes.clear(); + } + + private: + uint32_t _next_id = 0; + std::vector nodes; +}; + +struct TensorArg { + // Represents a de-duplicated tensor that will be passed into the graph + TensorArg(uint32_t i = 0) : id(i) {} + uint32_t index() const { + TORCH_INTERNAL_ASSERT(defined()); + return id - 1; + } + bool defined() const { + return id != 0; + } + uint32_t id; + at::Tensor proxy_tensor; +}; + +struct TensorArgs { + // Manages a collection of TensorArgs and mappings from Tensors/SavedVariables + // to them. This also allows us to unpack SavedVariable exactly once and + // store the unpacked Tensor. + TensorArgs(const std::optional& active_node_call_idx) + : active_node_call_idx(active_node_call_idx) {} + + TensorArg& lookup(const at::Tensor& tensor, bool create = false) { + if (!tensor.defined()) { + return _undefined; + } + auto impl = tensor.unsafeGetTensorImpl(); + auto it = _args.find(impl); + if (it == _args.end()) { + TORCH_INTERNAL_ASSERT(create && inputs.size() == _next_id - 1); + it = _args.emplace(impl, TensorArg(_next_id++)).first; + inputs.emplace_back(tensor); + if (active_node_call_idx.has_value()) { + input_origins.emplace_back(active_node_call_idx.value()); + } + } + return it->second; + } + + TensorArg& lookup(const SavedVariable& sv) { + if (auto it = _saved_variables.find(&sv); it != _saved_variables.end()) { + // unpacked before graph + return *it->second; + } + // unpacked in graph + auto it2 = _saved_variables_proxies.find(&sv); + TORCH_INTERNAL_ASSERT(it2 != _saved_variables_proxies.end()); + return *it2->second; + } + + TensorArg& add(const at::Tensor& tensor) { + return lookup(tensor, true); + } + + TensorArg& add(const SavedVariable& sv, const std::shared_ptr& node) { + // no unpack hooks in this codepath + at::Tensor tensor = sv.unpack(node); + TensorArg& arg = add(tensor); + _saved_variables.emplace(&sv, &arg); + return arg; + } + + // the concrete tensors that will get passed into the graph as inputs + std::vector inputs; + // NodeCall id of each input, only when verbose logging is enabled + std::vector input_origins; + + private: + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + const std::optional& active_node_call_idx; + std::unordered_map _args; + // Every TensorArg from this is actually owned by _args (or _undefined) and + // that's why we have an un-owned pointer here. + std::unordered_map _saved_variables; + std::unordered_map _saved_variables_proxies; + TensorArg _undefined; + uint32_t _next_id = 1; // id=0 used by _undefined +}; + +struct LiftedIValueArg { + LiftedIValueArg() = delete; + LiftedIValueArg(const at::IValue* ptr) + : actual_ptr(ptr), proxy(at::IValue::uninitialized()) {} + + const at::IValue* actual_ptr; // lifetime handled by autograd node + at::IValue proxy; +}; + +struct LiftedIValueArgs { + LiftedIValueArgs(const std::optional& active_node_call_idx) + : active_node_call_idx(active_node_call_idx) {} + + at::IValue& next_proxy(const at::IValue* actual_ptr) { + TORCH_INTERNAL_ASSERT(next < args.size()); + auto& iv_arg = args.at(next++); + TORCH_INTERNAL_ASSERT(iv_arg.actual_ptr == actual_ptr); + return iv_arg.proxy; + } + + void add(const at::IValue* iv) { + args.emplace_back(iv); + if (active_node_call_idx.has_value()) { + args_origins.emplace_back(active_node_call_idx.value()); + } + } + + std::vector args; + size_t next = 0; + // NodeCall id of each arg, only when verbose logging is enabled + std::vector args_origins; + + private: + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + const std::optional& active_node_call_idx; +}; + +struct AutogradCompilerCall { + AutogradCompilerCall(SizeInput::DynType default_dyn_type) + : active_node_call_idx(std::nullopt), + tensor_args(active_node_call_idx), + lifted_ivalue_args(active_node_call_idx), + default_dyn_type(default_dyn_type) {} + void add_size_input(const c10::SymInt& s) { + all_size_inputs.emplace_back( + default_dyn_type, s.guard_int(__FILE__, __LINE__)); + if (active_node_call_idx.has_value()) { + size_input_origins.emplace_back(active_node_call_idx.value()); + } + } + + size_t emplace_hook(c10::SafePyObject&& fn) { + hooks.emplace_back(std::move(fn)); + return hooks.size() - 1; + } + + size_t emplace_cpp_tensor_pre_hook( + std::function&& fn) { + cpp_tensor_pre_hooks.emplace_back(std::move(fn)); + return cpp_tensor_pre_hooks.size() - 1; + } + + size_t emplace_packed_input(c10::SafePyObject&& input) { + packed_inputs.emplace_back(std::move(input)); + return packed_inputs.size() - 1; + } + + void set_active_node_call_idx(size_t node_call_idx) { + active_node_call_idx = node_call_idx; + } + + std::optional active_node_call_idx; + TensorArgs tensor_args; + std::vector all_size_inputs; + LiftedIValueArgs lifted_ivalue_args; + std::vector dyn_size_inputs; + std::vector hooks; + std::vector> + cpp_tensor_pre_hooks; + std::vector packed_inputs; + NodeCalls node_calls; + SizeInput::DynType default_dyn_type; + // NodeCall id of each size, only when verbose logging is enabled + std::vector size_input_origins; + std::unordered_map> + sv_to_hooks; + // pynode -> backward and backward state idx + std::unordered_map>> + pynode_objs; +}; + +class CompiledNodeArgs { + // CompiledNodeArgs builds a representation of the constant values found + // across all the nodes in the compiled graph, via 'collect' overloads. The + // collected constants are specialized on by concatenation into a cache key. + // Tensor, symint arguments (which are lifted to become graph inputs rather + // than specialized on) are forwarded to the compiler and not included in the + // key. + public: + void collect(const TensorArg& t) { + collect_size(t.id); + if (t.defined()) { + const at::Tensor& tensor = _compiler.tensor_args.inputs[t.index()]; + // including these in the cache key means dynamo-level tensor guards can + // be skipped + collect(tensor.device()); + collect(tensor.dtype()); + collect(tensor.requires_grad()); + } + } + + void collect(const at::Tensor& t) { + collect(_compiler.tensor_args.add(t)); + } + void collect(const SavedVariable& sv, bool is_output) { + if (auto hook_data = sv.retrieve_unpack_hook_data(); + hook_data.has_value()) { + // hooks, unpack in graph + auto& [hook, packed_input] = hook_data.value(); + size_t hook_id = _compiler.emplace_hook(std::move(hook)); + // rely on dynamo to dedup packed tensors from unpacked tensors + size_t input_id = _compiler.emplace_packed_input(std::move(packed_input)); + _compiler.sv_to_hooks.emplace(&sv, std::make_pair(hook_id, input_id)); + } else { + // no hooks, unpack now + collect( + _compiler.tensor_args.add(sv, is_output ? _node_call.node : nullptr)); + } + } + void collect(const c10::SymInt& t) { + _compiler.add_size_input(t); + } + void collect(const std::vector& t, bool is_output) { + collect_size(t.size()); + for (const SavedVariable& i : t) { + collect(i, is_output); + } + } + template + void collect(const std::vector& t) { + collect_size(t.size()); + for (const T& i : t) { + collect(i); + } + } + void collect(const c10::ArrayRef& t, bool is_output) { + collect_size(t.size()); + for (const SavedVariable& i : t) { + collect(i, is_output); + } + } + template + void collect(const c10::ArrayRef& t) { + collect_size(t.size()); + for (const T& i : t) { + collect(i); + } + } + template + void collect(const c10::OptionalArray& t) { + collect(t.list); + } + template + void collect(const std::optional& t) { + if (cond(t.has_value())) { + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + collect(*t); + } + } + template + void collect(const std::pair& t) { + collect(t.first); + collect(t.second); + } + template + void collect(const ska::flat_hash_map& m) { + collect_size(m.size()); + + std::vector keys; + keys.reserve(m.size()); + std::transform( + m.begin(), m.end(), std::back_inserter(keys), [](const auto& entry) { + return entry.first; + }); + std::sort(keys.begin(), keys.end()); + for (const auto& k : keys) { + collect(k); + collect(m.at(k)); + } + } + void collect(const at::IValue& iv, bool nested = false) { + // used by AutogradContext::saved_data from CppNode + if (iv.isList()) { + c10::List list = iv.toList(); + collect_size(list.size()); + for (auto&& value : list) { + collect(value, true); + } + } else if (iv.isGenericDict()) { + c10::Dict ordered_dict = iv.toGenericDict(); + collect_size(ordered_dict.size()); + // NOLINTNEXTLINE(modernize-loop-convert) + for (auto it = ordered_dict.begin(); it != ordered_dict.end(); it++) { + collect(it->key()); + collect(it->value(), true); + } + } else if (iv.isTensor()) { + collect(iv.toTensor()); + } else if ( + !nested && + (iv.isInt() || iv.isSymInt() || iv.isDouble() || iv.isSymFloat())) { + // can't lift ivalues nested in collections + _compiler.lifted_ivalue_args.add(&iv); + } else { + try { + collect(static_cast(at::IValue::hash(iv))); + } catch (const std::runtime_error& e) { + std::string msg = + "Compiled autograd can not trace unhashable IValues, error: " + + std::string(e.what()); + TORCH_CHECK_NOT_IMPLEMENTED(false, msg); + } + } + } + void collect(const c10::Scalar& t) { + auto type = t.type(); + specialize_on_bytes(type); + if (type == c10::ScalarType::Double) { + collect(t.toDouble()); + } else if (type == c10::ScalarType::Long) { + collect(t.toLong()); + } else if (type == c10::ScalarType::Bool) { + collect(t.toBool()); + } else if (type == c10::ScalarType::ComplexDouble) { + auto c = t.toComplexDouble(); + collect(c.real()); + collect(c.imag()); + } else { + TORCH_INTERNAL_ASSERT(false); + } + } + void collect(const c10::TensorOptions& t) { + collect(t.device()); + collect(t.dtype()); + collect(t.layout()); + collect(t.requires_grad()); + collect(t.pinned_memory()); + collect(t.memory_format_opt()); + } + void collect(const at::TensorGeometry& t) { + collect(t.sym_sizes()); + collect(t.sym_strides()); + collect(t.sym_storage_offset()); + } + void collect(const torch::autograd::TypeAndSize& t) { + collect(t.sym_sizes); + collect(t.options); + } + void collect(const c10::Device& t) { + collect(t.type()); + collect(t.index()); + } + void collect(const std::string& t) { + collect_size(t.size()); + for (char c : t) { + collect(c); + } + } + void collect(const caffe2::TypeMeta& t) { + specialize_on_bytes(t.id()); + } + void collect(const std::shared_ptr& t) { + // Note: this is only capturing the ID of the node not everything + // contained inside it. This is used for tracking connections between + // nodes and the actual details of the node itself must be handled by + // a separate call to `node->compiled_args()`. + if (cond((bool)t)) { + collect(_compiler.node_calls.lookup(t)); + } + } + void collect(const NodeCall& t) { + collect_size(t.id); + collect(t.graph_output); + collect_hooks_from(t.node.get()); + } + void collect(const Edge& t) { + if (cond(t.is_valid())) { + collect_size(_compiler.node_calls.lookup(t.function).id); + collect_size(t.input_nr); + collect(t.function->input_metadata(t.input_nr)); // for validate_outputs + } + } + void collect(const InputMetadata& t) { + TORCH_CHECK_NOT_IMPLEMENTED( + !t.is_nested_tensor(), "NestedTensor support not implemented. "); + collect(t.options()); + collect(t.is_tensor_subclass()); + collect(t.shape_as_dim_vector()); + } + void collect(const VariableInfo& t) { + collect(t.layout); + collect(t.device); + collect(t.scalar_type); + collect(t.size); + collect(t.requires_grad); + collect(t.is_empty); + } + bool cond(bool cond) { + collect(cond); + return cond; + } + +#define COLLECT_AS_BYTES(T) \ + void collect(T t) { \ + specialize_on_bytes(t); \ + } + COLLECT_AS_BYTES(c10::ScalarType) + COLLECT_AS_BYTES(c10::DeviceType) + COLLECT_AS_BYTES(c10::Layout) + COLLECT_AS_BYTES(c10::MemoryFormat) + COLLECT_AS_BYTES(int8_t) + COLLECT_AS_BYTES(int16_t) + COLLECT_AS_BYTES(int32_t) + COLLECT_AS_BYTES(int64_t) + COLLECT_AS_BYTES(uint8_t) + COLLECT_AS_BYTES(uint16_t) + COLLECT_AS_BYTES(uint32_t) + COLLECT_AS_BYTES(uint64_t) + COLLECT_AS_BYTES(bool) + COLLECT_AS_BYTES(float) + COLLECT_AS_BYTES(double) +#undef COLLECT_AS_BYTES + + void collect_hooks_from(Node* fn) { + for (auto& i : fn->tensor_pre_hooks()) { + i->compiled_args(*this); + } + for (auto& [_, i] : fn->retains_grad_hooks()) { + i->compiled_args(*this); + } + for (auto& i : fn->pre_hooks()) { + i->compiled_args(*this); + } + for (auto& i : fn->post_hooks()) { + i->compiled_args(*this); + } + collect_size(_node_call.tensor_pre_hooks.size()); + collect_size(_node_call.pre_hooks.size()); + collect_size(_node_call.post_hooks.size()); + for (const auto& h : _node_call.tensor_pre_hooks) { + collect_size(static_cast(h.second)); + } + } + + CacheKey key() const { + Node* node = _node_call.node.get(); + return CacheKey( + typeid(*node), _specialization_key, _specialization_key_size); + } + + void collect_pynode_objs( + const Node* pynode, + c10::SafePyObject&& bwd, + std::optional&& bwd_state) { + size_t bwd_idx = _compiler.emplace_hook(std::move(bwd)); + std::optional bwd_state_idx; + if (auto state = std::move(bwd_state); state.has_value()) { + bwd_state_idx = _compiler.emplace_hook(std::move(state.value())); + } + _compiler.pynode_objs.emplace( + pynode, std::make_pair(bwd_idx, bwd_state_idx)); + } + + void add_tensor_pre_hook(c10::SafePyObject&& obj, int index) { + auto fn_id = _compiler.emplace_hook(std::move(obj)); + collect_size(fn_id); + _node_call.tensor_pre_hooks.emplace_back(fn_id, index); + } + + void add_cpp_single_tensor_pre_hook( + const std::function& hook, + size_t idx) { + auto wrapper = [hook](const at::TensorBase& grad) { + // handle when hook returns nothing + auto out = hook(grad); + if (!out.defined()) { + return grad; + } + return out; + }; + + auto hook_id = _compiler.emplace_cpp_tensor_pre_hook(std::move(wrapper)); + collect_size(hook_id); + _node_call.cpp_tensor_pre_hooks.emplace_back(hook_id, idx); + } + + void add_pre_hook(c10::SafePyObject&& obj) { + auto fn_id = _compiler.emplace_hook(std::move(obj)); + collect_size(fn_id); + _node_call.pre_hooks.emplace_back(fn_id); + } + + void add_post_hook(c10::SafePyObject&& obj) { + auto fn_id = _compiler.emplace_hook(std::move(obj)); + collect_size(fn_id); + _node_call.post_hooks.emplace_back(fn_id); + } + + void add_post_acc_grad_hook(c10::SafePyObject&& obj) { + auto fn_id = _compiler.emplace_hook(std::move(obj)); + collect_size(fn_id); + _node_call.post_acc_grad_hooks.emplace_back(fn_id); + } + + // Need to template the size_t to silence internal 32-bit build errors due to + // a mix of -Werror, -Wtautological-type-limit-compare and + // -Wunknown-pragmas + template + std::enable_if_t, void> collect_size(T s) { + // we expect sizes to be small, so try to cram them into a single byte + constexpr uint8_t encode_as_u64 = std::numeric_limits::max(); + constexpr uint8_t encode_as_u32 = encode_as_u64 - 1; + constexpr uint8_t encode_as_u16 = encode_as_u64 - 2; + if (C10_UNLIKELY(s >= encode_as_u16)) { + // first write a byte indicating the path we followed, then the data + if (s <= std::numeric_limits::max()) { + // 3 bytes + specialize_on_bytes(encode_as_u16); + specialize_on_bytes(static_cast(s)); + } else if (s <= std::numeric_limits::max()) { + // 5 bytes + specialize_on_bytes(encode_as_u32); + specialize_on_bytes(static_cast(s)); + } else { + // 9 bytes + specialize_on_bytes(encode_as_u64); + specialize_on_bytes(s); + } + } else { + // happy case, 1 byte + specialize_on_bytes(static_cast(s)); + } + } + + SizeInput::DynType set_default_dyn_type(SizeInput::DynType default_dyn_type) { + return std::exchange(_compiler.default_dyn_type, default_dyn_type); + } + + CompiledNodeArgs(AutogradCompilerCall& compiler, NodeCall& node_call) + : _compiler(compiler), + _node_call(node_call), + _specialization_key( + // NOLINTNEXTLINE(cppcoreguidelines-no-malloc) + (uint8_t*)std::malloc(_specialization_key_storage)) {} + CompiledNodeArgs(const CompiledNodeArgs&) = delete; + CompiledNodeArgs(CompiledNodeArgs&&) = delete; + CompiledNodeArgs& operator=(const CompiledNodeArgs&) = delete; + CompiledNodeArgs& operator=(CompiledNodeArgs&&) = delete; + ~CompiledNodeArgs() { + // NOLINTNEXTLINE(cppcoreguidelines-no-malloc) + std::free(_specialization_key); + } + + private: + template + void specialize_on_bytes(const T& t) { + while (C10_UNLIKELY( + _specialization_key_size + sizeof(T) > _specialization_key_storage)) { + _specialization_key_storage *= 2; + // NOLINTNEXTLINE(cppcoreguidelines-no-malloc) + _specialization_key = (uint8_t*)std::realloc( + _specialization_key, _specialization_key_storage); + } + std::memcpy(_specialization_key + _specialization_key_size, &t, sizeof(T)); + _specialization_key_size += sizeof(T); + } + + AutogradCompilerCall& _compiler; + NodeCall& _node_call; + size_t _specialization_key_size{0}; + size_t _specialization_key_storage{1024}; + uint8_t* _specialization_key; +}; + +struct TraceState { + TraceState(std::vector>&& ss, size_t num_outputs) + : sym_sizes(std::move(ss)), outputs(num_outputs) {} + + void debug_asserts() { + TORCH_INTERNAL_ASSERT(sym_sizes_index == sym_sizes.size()); + } + std::optional next_sym_size() { + TORCH_INTERNAL_ASSERT(sym_sizes_index < sym_sizes.size()); + return sym_sizes[sym_sizes_index++]; + } + + size_t sym_sizes_index{0}; + std::vector> sym_sizes; + variable_list outputs; +}; + +class SwapSavedVariables { + // SwapSavedVariables is used during the tracing/compilation phase after a + // cache-miss. It swaps any 'lifted' inputs (tensors, symints) to proxy nodes, + // allows tracing to happen, then swaps them back afterwards. + public: + std::pair> retrieve_pynode_objs( + Node* pynode) const { + auto it = compiler.pynode_objs.find(pynode); + TORCH_INTERNAL_ASSERT(it != compiler.pynode_objs.end()); + return it->second; + } + + void before(at::Tensor& t) { + TensorArg& arg = compiler.tensor_args.lookup(t); + stashed_tensors.save(&t, std::move(t)); + if (arg.defined()) { + TORCH_INTERNAL_ASSERT(arg.proxy_tensor.defined()); + t = arg.proxy_tensor; + } + } + void after(at::Tensor& t) { + stashed_tensors.restore(&t); + } + + void before(SavedVariable& t) { + if (auto it = compiler.sv_to_hooks.find(&t); + it != compiler.sv_to_hooks.end()) { + const auto& pyinterface = + torch::dynamo::autograd::getPyCompilerInterface(); + auto proxy_tensor = pyinterface->call_unpack( + get_py_compiler(), it->second.first, it->second.second); + stashed_variables.save(&t, std::move(t)); + bool prior = at::SavedTensorDefaultHooks::set_tracing(true); + t = SavedVariable(proxy_tensor, false); + at::SavedTensorDefaultHooks::set_tracing(prior); + } else { + // no hooks, was already unpacked + TensorArg& arg = compiler.tensor_args.lookup(t); + stashed_variables.save(&t, std::move(t)); + if (arg.defined()) { + bool prior = at::SavedTensorDefaultHooks::set_tracing(true); + TORCH_INTERNAL_ASSERT(arg.proxy_tensor.defined()); + t = SavedVariable(arg.proxy_tensor, false); + at::SavedTensorDefaultHooks::set_tracing(prior); + } + } + } + void after(SavedVariable& t) { + stashed_variables.restore(&t); + } + + void before(c10::SymInt& t) { + stashed_symints.save(&t, c10::SymInt(t)); + auto opt_value = state.next_sym_size(); + if (opt_value.has_value()) { + t = *opt_value; // dynamic shape + } + } + void after(c10::SymInt& t) { + stashed_symints.restore(&t); + } + + void before(at::IValue& iv) { + if (iv.isTensor()) { + before(iv.toTensor()); + } else { + stashed_ivalues.save(&iv, at::IValue(iv)); + if (iv.isInt() || iv.isSymInt() || iv.isDouble() || iv.isSymFloat()) { + iv = compiler.lifted_ivalue_args.next_proxy(&iv); + } + } + } + + void after(at::IValue& t) { + if (t.isTensor()) { + after(t.toTensor()); + } else { + stashed_ivalues.restore(&t); + } + } + + void before(Edge& t) { + if (t.is_valid()) { + // need for symints used by validate_outputs + before(t.function->mutable_input_metadata(t.input_nr)); + } + } + void after(Edge& t) { + if (t.is_valid()) { + after(t.function->mutable_input_metadata(t.input_nr)); + } + } + void before(InputMetadata& t) { + before(t.mutable_shape_as_dim_vector()); + } + void after(InputMetadata& t) { + after(t.mutable_shape_as_dim_vector()); + } + void before(at::TensorGeometry& t) { + before(t.mutable_sizes()); + before(t.mutable_strides()); + before(t.mutable_storage_offset()); + t.recompute(); + } + void after(at::TensorGeometry& t) { + after(t.mutable_sizes()); + after(t.mutable_strides()); + after(t.mutable_storage_offset()); + t.recompute(); + } + void before(torch::autograd::TypeAndSize& t) { + before(t.sym_sizes); + before(t.options); + } + void after(torch::autograd::TypeAndSize& t) { + after(t.sym_sizes); + after(t.options); + } + void before(VariableInfo& t) { + before(t.size); + } + void after(VariableInfo& t) { + after(t.size); + } + + template + void before(std::vector& t) { + for (T& i : t) { + before(i); + } + } + template + void after(std::vector& t) { + for (T& i : t) { + after(i); + } + } + template + void before(c10::SmallVector& t) { + for (T& i : t) { + before(i); + } + } + template + void after(c10::SmallVector& t) { + for (T& i : t) { + after(i); + } + } + + template + void before(c10::OptionalArray& t) { + before(t.list); + } + template + void after(c10::OptionalArray& t) { + after(t.list); + } + + template + void before(std::optional& t) { + if (t.has_value()) { + before(*t); + } + } + template + void after(std::optional& t) { + if (t.has_value()) { + after(*t); + } + } + + template + void before(ska::flat_hash_map& m) { + std::vector keys; + keys.reserve(m.size()); + std::transform( + m.begin(), m.end(), std::back_inserter(keys), [](const auto& entry) { + return entry.first; + }); + std::sort(keys.begin(), keys.end()); + for (auto& k : keys) { + before(m.at(k)); + } + } + + template + void after(ska::flat_hash_map& m) { + for (auto& [_, v] : m) { + after(v); + } + } + +#define NO_OP_VISIT(T) \ + void before(const T&) {} \ + void after(const T&) {} + NO_OP_VISIT(caffe2::TypeMeta) + NO_OP_VISIT(c10::Device) + NO_OP_VISIT(c10::DeviceType) + NO_OP_VISIT(c10::Layout) + NO_OP_VISIT(c10::MemoryFormat) + NO_OP_VISIT(c10::ScalarType) + NO_OP_VISIT(c10::Scalar) + NO_OP_VISIT(c10::TensorOptions) + NO_OP_VISIT(std::string) + NO_OP_VISIT(int64_t) + NO_OP_VISIT(bool) + NO_OP_VISIT(double) +#undef NO_OP_VISIT + + SwapSavedVariables( + AutogradCompilerCall& c, + TraceState& s, + PyObject* p, + const NodeCall& n) + : compiler(c), state(s), py_compiler(p), curr_node_call(n) {} + + PyObject* get_py_compiler() const { + return py_compiler; + } + + const NodeCall& get_curr_node_call() { + return curr_node_call; + } + + void debug_asserts() { + stashed_variables.debug_assert(); + stashed_tensors.debug_assert(); + stashed_symints.debug_assert(); + } + + private: + template + struct Stashed { + Stashed(T&& v) : prior_value(std::move(v)) {} + T prior_value; + // Note: we need count here to support duplicate calls to before() + // which happen when we have multiple autograd::Edge objects pointing + // to the same autograd::Node + int count = 1; + }; + + template + struct StashedVars : public std::unordered_map> { + void save(const T* key, T&& value) { + auto [it, inserted] = this->try_emplace(key, std::move(value)); + if (!inserted) { + // keep the value from the prior save() + it->second.count++; + } + } + void restore(T* var) { + auto it = this->find(var); + TORCH_INTERNAL_ASSERT(it != this->end(), "missing before())"); + if (--it->second.count == 0) { + // restore the value on the last restore() + *var = std::move(it->second.prior_value); + this->erase(it); + } + } + void debug_assert() { + TORCH_INTERNAL_ASSERT(this->empty(), "missing call to after()"); + } + }; + + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + AutogradCompilerCall& compiler; + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + TraceState& state; + // This is a borrowed reference, we do not increment ownership, or lower it, + // it's lifecycle is entirely longer than this objects. + PyObject* py_compiler; + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + const NodeCall& curr_node_call; + + // These mappings are used to save the prior values when we overwrite things + // in before(). In after(), we use these to cleanup after ourselves. + StashedVars stashed_variables; + StashedVars stashed_tensors; + StashedVars stashed_symints; + StashedVars stashed_ivalues; +}; + +// NOTE: [Compiled Autograd and backward functions] +// Built-in autograd nodes have functional apply variants +// (e.g. MulBackward0_apply_functional). Compiled Autograd's initial graph +// capture wants to take a variant of this function and proxy it into the graph. +// Every autograd node defines an apply_with_saved function, that when invoked, +// proxies a call to a function into the Compiled Autograd graph. +// +// Some requirements that we have are: +// - The proxy'ed function must have inputs that are FX-graphable types. +// - Windows has a DLL symbol limit of 65536. +// - Node::apply_with_saved is in libtorch_cpu which does not have direct access +// to Python +// +// There were multiple ways to skin the cat, but what we end up doing is: +// - for e.g. MulBackward0_apply_functional, we create a new C++ function +// MulBackward0_apply_functional_ivalue that accepts vector. +// - We define how to pack and unpack arbitrary C++ types into IValues. +// - apply_with_saved passes MulBackward0_apply_functional_ivalue and +// the IValue arguments to Python via an indirection. +// In Python, these get proxy'ed into a graph. + +// Helper struct for packing/unpacking an arbitrary C++ type into a single +// IValue. There are various full and partial specializations for IValuePacker +// to handle packing specific types (like TensorOptions) into an IValue. +template +struct IValuePacker { + // Defines how to pack T into an IValue. + static at::IValue pack(const T& t) { + return t; + } + // Defines how to unpack an IValue into T. + static T unpack(const at::IValue& t) { + return t.to(); + } + // Returns the TypePtr for the IValue (this is like the "type" of the IValue). + // We use this when passing the packed IValue from Python to C++. + // In Python, the IValue is just a PyObject* with the native type. + // For example, it may be a Python int, a Python List[int], etc. + // When passing this PyObject* into C++, we need to know how to parse it + // into a C++ type that then gets put into an IValue. + // That's what the TypePtr is for: it contains the information to do the + // parsing. See torch::jit::toIValue for more information. + static at::TypePtr packed_type() { + // On windows CPU is support compiled autograd. +#if defined(_WIN32) && (defined(USE_CUDA) || defined(USE_ROCM)) + // NB: the if-constexpr usage triggers compilation errors on Windows + // with certain compiler settings + // (see https://github.com/pytorch/pytorch/pull/144707 for examples). + // It's not clear what the problem is, so we're going to ignore it for now. + TORCH_CHECK_NOT_IMPLEMENTED( + false, "torch.compile not supported on Windows"); +#else + if constexpr (::std::is_same_v) { + return at::TensorType::get(); + } else if constexpr (::std::is_same_v) { + return at::IntType::get(); + } else if constexpr (::std::is_same_v) { + return at::SymIntType::get(); + } else if constexpr (::std::is_same_v) { + return at::BoolType::get(); + } else if constexpr (::std::is_same_v) { + return at::FloatType::get(); + } else if constexpr (::std::is_same_v) { + return at::SymFloatType::get(); + } else if constexpr (::std::is_same_v) { + return at::SymBoolType::get(); + } else if constexpr (::std::is_same_v) { + return at::LayoutType::get(); + } else if constexpr (::std::is_same_v) { + return at::StringType::get(); + } else if constexpr (::std::is_same_v) { + return at::DeviceObjType::get(); + } else if constexpr (::std::is_same_v) { + return at::NumberType::get(); + } else if constexpr (::std::is_same_v) { + return at::MemoryFormatType::get(); + } else if constexpr (::std::is_same_v) { + return at::ScalarTypeType::get(); + } else { + // If you got here, you have probably added a member of a new type + // to a built-in C++ autograd node. + // Unfortunately, we don't know how to handle this type yet. + // To get this new type to work with Compiled Autograd, please + // either change it to be an IValue-constructible type, or + // define how to pack and unpack an object of this time into an IValue + // by creating a specialization of IValuePacker for this type. + // See NOTE: [Compiled Autograd and backward functions] for context. + TORCH_CHECK_NOT_IMPLEMENTED( + false, "IValuePacker not implemented for type"); + return at::NoneType::get(); + } +#endif + } +}; + +template <> +struct IValuePacker { + static at::IValue pack(const size_t& t) { + // We generally use size_t as the size of a list of Tensors or number of + // dimensions. The number of dimensions generally do not exceed 64 + // (TensorIterator has that limitation), and lists of Tensors generally do + // not exceed the int64_t max (you'd probably run out of RAM or run into + // significant Tensor overhead). If you run into this limitation the fix is + // to figure out how to pack size_t into int64_t. Note that size_t has some + // weird behavior on Mac OS. + uint64_t maximum_value = std::numeric_limits::max(); + TORCH_INTERNAL_ASSERT( + static_cast(t) <= maximum_value, + "size_t too large to pack into IValue"); + return static_cast(t); // pack as int64_t + } + static size_t unpack(const at::IValue& t) { + return static_cast(t.toInt()); + } + static at::TypePtr packed_type() { + return IValuePacker::packed_type(); + } +}; + +template <> +struct IValuePacker> { + static at::IValue pack(const std::vector& t) { + return t; + } + static std::vector unpack(const at::IValue& t) { + // We need this because there's no t.to>() override? + return t.toSymIntVector(); + } + static at::TypePtr packed_type() { + return at::ListType::create(at::SymIntType::get()); + } +}; + +template <> +struct IValuePacker { + static at::IValue pack(const VariableInfo& t) { + auto tuple = std::make_tuple( + t.layout, t.device, t.scalar_type, t.size, t.requires_grad, t.is_empty); + return tuple; + } + static VariableInfo unpack(const at::IValue& t) { + auto tuple = t.toTuple(); + const auto& tuple_elements = tuple->elements(); + const auto elements = tuple_elements.asArrayRef(); + TORCH_INTERNAL_ASSERT(elements.size() == 6); + VariableInfo v; + v.layout = elements[0].toLayout(); + v.device = elements[1].toDevice(); + v.scalar_type = elements[2].toScalarType(); + v.size = elements[3].toSymIntVector(); + v.requires_grad = elements[4].toBool(); + v.is_empty = elements[5].toBool(); + return v; + } + static at::TypePtr packed_type() { + return at::TupleType::create({ + at::LayoutType::get(), + at::DeviceObjType::get(), + at::ScalarTypeType::get(), + at::ListType::create(at::SymIntType::get()), + at::BoolType::get(), + at::BoolType::get(), + }); + } +}; + +template <> +struct IValuePacker { + static at::IValue pack(const caffe2::TypeMeta& t) { + return at::typeMetaToScalarType(t); // pack as at::ScalarType + } + static caffe2::TypeMeta unpack(const at::IValue& t) { + return caffe2::TypeMeta::fromScalarType(t.to()); + } + static at::TypePtr packed_type() { + return IValuePacker::packed_type(); + } +}; + +inline std::optional optTypeMetaToScalarType( + const std::optional& t) { + if (t.has_value()) { + return at::typeMetaToScalarType(t.value()); + } else { + return std::nullopt; + } +} + +using packed_tensoroptions_t = std::tuple< + std::optional, + std::optional, + std::optional, + std::optional, + std::optional, + std::optional>; + +inline packed_tensoroptions_t pack_TensorOptions(const at::TensorOptions& t) { + auto tuple = std::make_tuple( + t.requires_grad_opt(), + t.memory_format_opt(), + t.device_opt(), + optTypeMetaToScalarType(t.dtype_opt()), + t.layout_opt(), + t.pinned_memory_opt()); + return tuple; +} +inline at::TensorOptions unpack_TensorOptions( + const packed_tensoroptions_t& tuple) { + at::TensorOptions result; + auto maybe_requires_grad = std::get<0>(tuple); + if (maybe_requires_grad.has_value()) { + result = result.requires_grad(maybe_requires_grad); + } + auto maybe_memory_format = std::get<1>(tuple); + if (maybe_memory_format.has_value()) { + result = result.memory_format(maybe_memory_format); + } + auto maybe_device = std::get<2>(tuple); + if (maybe_device.has_value()) { + result = result.device(maybe_device.value()); + } + auto maybe_dtype = std::get<3>(tuple); + if (maybe_dtype.has_value()) { + result = + result.dtype(caffe2::TypeMeta::fromScalarType(maybe_dtype.value())); + } + auto maybe_layout = std::get<4>(tuple); + if (maybe_layout.has_value()) { + result = result.layout(maybe_layout); + } + auto maybe_pinned_memory = std::get<5>(tuple); + if (maybe_pinned_memory.has_value()) { + result = result.pinned_memory(maybe_pinned_memory); + } + return result; +} + +template <> +struct IValuePacker { + static at::IValue pack(const at::TensorOptions& t) { + return pack_TensorOptions(t); + } + static at::TensorOptions unpack(const at::IValue& t) { + auto tuple = t.to(); + return unpack_TensorOptions(tuple); + } + static at::TypePtr packed_type() { + return at::TupleType::create( + {at::OptionalType::create(at::BoolType::get()), + at::OptionalType::create(at::MemoryFormatType::get()), + at::OptionalType::create(at::DeviceObjType::get()), + at::OptionalType::create(at::ScalarTypeType::get()), + at::OptionalType::create(at::LayoutType::get()), + at::OptionalType::create(at::BoolType::get())}); + } +}; + +template <> +struct IValuePacker { + static at::IValue pack(const TypeAndSize& t) { + auto tuple = std::make_tuple(t.sym_sizes, pack_TensorOptions(t.options)); + return tuple; + } + static TypeAndSize unpack(const at::IValue& t) { + auto tuple = + t.to, packed_tensoroptions_t>>(); + TypeAndSize result; + result.sym_sizes = std::get<0>(tuple); + result.options = unpack_TensorOptions(std::get<1>(tuple)); + return result; + } + static at::TypePtr packed_type() { + return at::TupleType::create( + {IValuePacker>::packed_type(), + IValuePacker::packed_type()}); + } +}; + +template +struct IValuePacker> { + static at::IValue pack(const std::optional& t) { + if (t.has_value()) { + return IValuePacker::pack(t.value()); + } else { + return std::nullopt; + } + } + static std::optional unpack(const at::IValue& t) { + if (t.isNone()) { + return std::nullopt; + } else { + return IValuePacker::unpack(t); + } + } + static at::TypePtr packed_type() { + return at::OptionalType::create(IValuePacker::packed_type()); + } +}; + +template +struct IValuePacker> { + static at::IValue pack(const std::vector& t) { + if constexpr (::std::is_constructible_v) { + return t; + } + if (t.empty()) { + auto lst = c10::impl::GenericList(at::AnyType::get()); + return lst; + } + auto type_ptr = IValuePacker::pack(t[0]).type(); + auto lst = c10::impl::GenericList(type_ptr); + for (const auto& elt : t) { + lst.emplace_back(IValuePacker::pack(elt)); + } + return lst; + } + static std::vector unpack(const at::IValue& t) { + if constexpr (::std::is_constructible_v) { + return t.to<::std::vector>(); + } + std::vector result; + auto lst = t.toList(); + for (size_t i = 0; i < lst.size(); ++i) { + const at::IValue& elt = lst.get(i); + result.emplace_back(IValuePacker::unpack(elt)); + } + return result; + } + static at::TypePtr packed_type() { + return at::ListType::create(IValuePacker::packed_type()); + } +}; + +template +struct IValuePacker> { + static at::IValue pack(const c10::List& t) { + return IValuePacker>::pack(t.vec()); + } + static c10::List unpack(const at::IValue& t) { + return c10::List(IValuePacker>::unpack(t)); + } + static at::TypePtr packed_type() { + return IValuePacker>::packed_type(); + } +}; + +template +struct IValuePacker> { + static at::IValue pack(const std::array& t) { + std::vector result(t.begin(), t.end()); + return IValuePacker>::pack(result); + } + static std::array unpack(const at::IValue& t) { + std::array result; + auto packed = IValuePacker>::unpack(t); + for (size_t i = 0; i < packed.size(); i++) { + result[i] = packed[i]; + } + return result; + } + static at::TypePtr packed_type() { + return IValuePacker>::packed_type(); + } +}; + +template <> +struct IValuePacker { + static at::IValue pack(const at::TensorGeometry& t) { + auto tuple = std::make_tuple( + t.sym_sizes().vec(), t.sym_strides().vec(), t.sym_storage_offset()); + return tuple; + } + static at::TensorGeometry unpack(const at::IValue& t) { + auto tuple = t.to, + std::vector, + at::SymInt>>(); + return at::TensorGeometry( + std::get<0>(tuple), std::get<1>(tuple), std::get<2>(tuple)); + } + static at::TypePtr packed_type() { + return at::TupleType::create( + {IValuePacker>::packed_type(), + IValuePacker>::packed_type(), + at::SymIntType::get()}); + } +}; + +template <> +struct IValuePacker { + static at::IValue pack(const InputMetadata& t) { + TORCH_INTERNAL_ASSERT(!t.is_nested_tensor()); + auto tuple = std::make_tuple( + pack_TensorOptions(t.options()), + t.shape_as_dim_vector().vec(), + t.is_tensor_subclass(), + t.grad_dtype()); + return tuple; + } + static InputMetadata unpack(const at::IValue& t) { + auto tuple = t.to, + bool, + std::optional>>(); + + return InputMetadata( + unpack_TensorOptions(std::get<0>(tuple)), + SymIntSmallVec(std::get<1>(tuple)), + std::get<2>(tuple), + false, + std::get<3>(tuple)); + } + static at::TypePtr packed_type() { + return at::TupleType::create( + {IValuePacker::packed_type(), + IValuePacker>::packed_type(), + at::BoolType::get(), + IValuePacker>::packed_type()}); + } +}; + +template +struct IValuePacker> { + static at::IValue pack(const at::OptionalArray& t) { + return IValuePacker>>::pack(t.list); + } + static at::OptionalArray unpack(const at::IValue& t) { + auto result = IValuePacker>>::unpack(t); + if (result.has_value()) { + return {result.value()}; + } else { + return {}; + } + } + static at::TypePtr packed_type() { + return IValuePacker>>::packed_type(); + } +}; + +// This is a helper struct for packing and unpacking multiple arguments into +// an ivalue_list. It leverages IValuePacker. +struct PackedArgs { + PackedArgs() = default; + + explicit PackedArgs(std::vector stack_) + : stack(std::move(stack_)) {} + + const std::vector& vec() const { + return stack; + } + + template + void pack(const T& t) { + stack.emplace_back(IValuePacker::pack(t)); + } + template + T unpack() { + return IValuePacker::unpack(std::move(stack[idx++])); + } + + void pack_saved_data(const ska::flat_hash_map& dct) { + std::vector keys; + std::vector values; + for (const auto& [key, value] : dct) { + keys.emplace_back(key); + values.emplace_back(value); + } + pack(keys); + for (const auto& value : values) { + pack(value); + } + } + + ska::flat_hash_map unpack_saved_data() { + ska::flat_hash_map dct; + auto keys = unpack>(); + for (const auto& key : keys) { + dct.insert({key, std::move(stack[idx++])}); + } + return dct; + } + + private: + std::vector stack; + int64_t idx = 0; +}; + +} // namespace torch::dynamo::autograd + +template <> +struct std::hash { + size_t operator()(const torch::dynamo::autograd::CacheKey& k) const { + return k.hash(); + } +}; + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/cpp_shim.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/cpp_shim.h new file mode 100644 index 0000000000000000000000000000000000000000..d764297efb4acb23aaadfea5a2658f8b5a3512f1 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/cpp_shim.h @@ -0,0 +1,20 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +struct _PytorchRecordFunctionState; +typedef struct _PytorchRecordFunctionState _PytorchRecordFunctionState; + +_PytorchRecordFunctionState* _pytorch_record_function_enter(const char* name); +void _pytorch_record_function_exit(_PytorchRecordFunctionState* state); + +#ifdef __cplusplus +} // extern "C" +#endif + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/cpython_defs.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/cpython_defs.h new file mode 100644 index 0000000000000000000000000000000000000000..d2d361c2b8ec4fd4b6331738ee01f9bc3d54356a --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/cpython_defs.h @@ -0,0 +1,45 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +// Functions that need to be copied from the CPython source +// should go in cpython_defs.c. Copying is required when, e.g., +// we need to call internal CPython functions that are not exposed. + +#if IS_PYTHON_3_11_PLUS + +typedef struct _PyInterpreterFrame _PyInterpreterFrame; + +PyFunctionObject* _PyFunction_CopyWithNewCode( + PyFunctionObject* o, + PyCodeObject* code); + +void THP_PyFrame_Clear(_PyInterpreterFrame* frame); + +_PyInterpreterFrame* THP_PyThreadState_BumpFramePointerSlow( + PyThreadState* tstate, + size_t size); + +void THP_PyThreadState_PopFrame( + PyThreadState* tstate, + _PyInterpreterFrame* frame); + +#endif + +// pointers to _PyOpcode_Caches for C++ +#ifdef __cplusplus +extern "C" { +#endif + +extern const uint8_t* THP_PyOpcode_Caches; +extern int THP_PyOpcode_Caches_size; +void init_THPCaches(); + +#ifdef __cplusplus +} // extern "C" +#endif + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/cpython_includes.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/cpython_includes.h new file mode 100644 index 0000000000000000000000000000000000000000..ea994e6fce119bcb14ed14239d80fe4faa4de1b9 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/cpython_includes.h @@ -0,0 +1,76 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +// Problem in CPython includes when mixing core and non-core build +// The fix was not backported to 3.12 so this is needed here +// https://github.com/python/cpython/issues/105268 +#if IS_PYTHON_3_12_PLUS +#undef _PyGC_FINALIZED +#endif + +// see https://bugs.python.org/issue35886 +#define Py_BUILD_CORE + +#ifndef __cplusplus +// C-only headers +#include + +#endif // __cplusplus + +#if IS_PYTHON_3_11_PLUS +#include + +#include +#if IS_PYTHON_3_14_PLUS && !defined(_WIN32) +#include +#include +#include +#include +#elif IS_PYTHON_3_14_PLUS && defined(_WIN32) +#include // _PyInterpreterFrame +#endif + +#endif + +#undef Py_BUILD_CORE + +#ifdef __cplusplus +extern "C" { +#endif + +#if IS_PYTHON_3_14_PLUS + +#define F_CODE(x) \ + ((PyCodeObject*)THP_PyStackRef_AsPyObjectBorrow(&(x)->f_executable)) +#define PREV_INSTR(x) (x)->instr_ptr + +#else + +#if IS_PYTHON_3_13_PLUS +#define F_CODE(x) ((PyCodeObject*)(x)->f_executable) +#define PREV_INSTR(x) (x)->instr_ptr +#else +#define F_CODE(x) ((PyCodeObject*)(x)->f_code) +#define PREV_INSTR(x) (x)->prev_instr +#endif // IS_PYTHON_3_13_PLUS + +#endif // IS_PYTHON_3_14_PLUS + +#if IS_PYTHON_3_14_PLUS +#define FUNC(x) \ + ((PyFunctionObject*)THP_PyStackRef_AsPyObjectBorrow(&(x)->f_funcobj)) +#elif IS_PYTHON_3_12_PLUS +#define FUNC(x) ((PyFunctionObject*)(x)->f_funcobj) +#else +#define FUNC(x) ((PyFunctionObject*)(x)->f_func) +#endif + +#ifdef __cplusplus +} // extern "C" +#endif + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/debug_macros.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/debug_macros.h new file mode 100644 index 0000000000000000000000000000000000000000..49ef7b69fe4ab8a5a6948644c98008c11518489d --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/debug_macros.h @@ -0,0 +1,107 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +#ifdef __cplusplus +#include +#else +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef _WIN32 +#define unlikely(x) (x) +#else +#define unlikely(x) __builtin_expect((x), 0) +#endif + +#define NULL_CHECK(val) \ + if (unlikely((val) == NULL)) { \ + fprintf(stderr, "NULL ERROR: %s:%d\n", __FILE__, __LINE__); \ + PyErr_Print(); \ + abort(); \ + } else { \ + } + +// CHECK might be previously declared +#undef CHECK +#define CHECK(cond) \ + if (unlikely(!(cond))) { \ + fprintf(stderr, "DEBUG CHECK FAILED: %s:%d\n", __FILE__, __LINE__); \ + abort(); \ + } else { \ + } + +// Uncomment next line to print debug message +// #define TORCHDYNAMO_DEBUG 1 +#ifdef TORCHDYNAMO_DEBUG + +#define DEBUG_CHECK(cond) CHECK(cond) +#define DEBUG_NULL_CHECK(val) NULL_CHECK(val) +#define DEBUG_TRACE(msg, ...) \ + fprintf(stderr, "TRACE[%s:%d] " msg "\n", __func__, __LINE__, __VA_ARGS__) +#define DEBUG_TRACE0(msg) \ + fprintf(stderr, "TRACE[%s:%d] " msg "\n", __func__, __LINE__) + +#else + +#define DEBUG_CHECK(cond) +#define DEBUG_NULL_CHECK(val) +#define DEBUG_TRACE(msg, ...) +#define DEBUG_TRACE0(msg) + +#endif + +inline _PyFrameEvalFunction _debug_set_eval_frame( + PyThreadState* tstate, + _PyFrameEvalFunction eval_frame) { + _PyFrameEvalFunction prev = + _PyInterpreterState_GetEvalFrameFunc(tstate->interp); + _PyInterpreterState_SetEvalFrameFunc(tstate->interp, eval_frame); + return prev; +} + +// Inspect PyObject*'s from C/C++ at the Python level, in pdb. +// e.g. +// +// PyObject* obj1 = PyList_New(...); +// PyObject* obj2 = PyObject_CallFunction(...); +// INSPECT(obj1, obj2); +// (pdb) p args[0] +// # list +// (pdb) p args[1] +// # some object +// (pdb) p args[1].some_attr +// # etc. +// +// Implementation: set eval frame callback to default, call +// torch._dynamo.utils._breakpoint_for_c_dynamo, reset eval frame callback. +#define INSPECT(...) \ + { \ + PyThreadState* cur_tstate = PyThreadState_Get(); \ + _PyFrameEvalFunction prev_eval_frame = \ + _debug_set_eval_frame(cur_tstate, &_PyEval_EvalFrameDefault); \ + PyObject* torch__dynamo_utils_module = \ + PyImport_ImportModule("torch._dynamo.utils"); \ + NULL_CHECK(torch__dynamo_utils_module); \ + PyObject* breakpoint_for_c_dynamo_fn = PyObject_GetAttrString( \ + torch__dynamo_utils_module, "_breakpoint_for_c_dynamo"); \ + NULL_CHECK(breakpoint_for_c_dynamo_fn); \ + PyObject_CallFunctionObjArgs( \ + breakpoint_for_c_dynamo_fn, __VA_ARGS__, NULL); \ + _debug_set_eval_frame(cur_tstate, prev_eval_frame); \ + Py_DECREF(breakpoint_for_c_dynamo_fn); \ + Py_DECREF(torch__dynamo_utils_module); \ + } + +#ifdef __cplusplus +} // extern "C" +#endif + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/eval_frame.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/eval_frame.h new file mode 100644 index 0000000000000000000000000000000000000000..8bac42f0fc1fa59aa2b5cf8d9cd4c556cbd53553 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/eval_frame.h @@ -0,0 +1,65 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include + +#include +#include +#ifdef __cplusplus + +extern "C" { + +PyObject* torch_c_dynamo_eval_frame_init(void); + +#endif + +// All the eval APIs change in 3.11 so we need to decide which one to use on the +// fly https://docs.python.org/3/c-api/init.html#c._PyFrameEvalFunction +#if IS_PYTHON_3_11_PLUS +#define THP_EVAL_API_FRAME_OBJECT _PyInterpreterFrame +#else +#define THP_EVAL_API_FRAME_OBJECT PyFrameObject +#endif // IS_PYTHON_3_11_PLUS + +// We need to be able to return the _PyInterpreterFrame to python so create +// a python binding for it + +typedef struct THPPyInterpreterFrame { + PyObject_HEAD + THP_EVAL_API_FRAME_OBJECT* frame; // Borrowed reference + PyObject* locals; +} THPPyInterpreterFrame; + +THPPyInterpreterFrame* THPPyInterpreterFrame_New( + THP_EVAL_API_FRAME_OBJECT* frame); + +extern bool is_skip_guard_eval_unsafe; + +void clear_old_frame_if_python_312_plus( + PyThreadState* tstate, + THP_EVAL_API_FRAME_OBJECT* frame); + +void eval_frame_callback_set(PyObject* obj); + +const char* get_frame_name(THP_EVAL_API_FRAME_OBJECT* frame); + +PyObject* dynamo_eval_frame_default( + PyThreadState* tstate, + THP_EVAL_API_FRAME_OBJECT* frame, + int throw_flag); + +PyObject* dynamo_eval_custom_code( + PyThreadState* tstate, + THP_EVAL_API_FRAME_OBJECT* frame, + PyCodeObject* code, + const char* trace_annotation, + int throw_flag); + +#ifdef __cplusplus + +} // extern "C" + +#endif + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/eval_frame_cpp.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/eval_frame_cpp.h new file mode 100644 index 0000000000000000000000000000000000000000..1a817972d2ffc8d092773a1a5b6cf880b1f6c389 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/eval_frame_cpp.h @@ -0,0 +1,34 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include + +#include +#include +#include +#ifdef __cplusplus + +extern "C" { + +#endif + +PyObject* dynamo__custom_eval_frame( + PyThreadState* tstate, + THP_EVAL_API_FRAME_OBJECT* frame, + int throw_flag, + PyObject* callback); + +PyObject* dynamo_set_code_exec_strategy(PyObject* dummy, PyObject* obj); +void dynamo_skip_code_recursive(PyCodeObject* code); + +void dynamo_set_c_recursion_limit(int32_t limit); +int32_t dynamo_get_c_recursion_limit(); + +#ifdef __cplusplus + +} // extern "C" + +#endif + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/extra_state.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/extra_state.h new file mode 100644 index 0000000000000000000000000000000000000000..04d8789fd3aaba74bda9291f7042b75152c89e2d --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/extra_state.h @@ -0,0 +1,213 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +#include + +#ifdef __cplusplus + +#include +#include +#include + +namespace py = pybind11; + +extern "C" { + +#else + +#include + +#endif + +enum FrameAction { + DEFAULT, // look through the cache, compile if not found + SKIP, // eager + RUN_ONLY, // look through the cache, run eager if not found +}; + +typedef struct FrameExecStrategy { + enum FrameAction cur_action; // action to take for current frame + enum FrameAction recursive_action; // action to take for recursive frames +} FrameExecStrategy; + +// Points to the extra scratch space on the code object +extern Py_ssize_t extra_index; + +// function to call when cache lookup errors +extern PyObject* guard_error_hook; + +typedef PyObject FrameState; +typedef struct CacheEntry CacheEntry; + +// ExtraState encasulates CacheEntry and FrameState. ExtraState is the highest +// level of abstraction of what is stored on the extra code object. Previously, +// we saved different parts on different extra indexes. We prefer this way +// because of cleaner abstraction and faster SetExtra access. + +#ifdef __cplusplus + +typedef struct VISIBILITY_HIDDEN PrecompileEntry { + py::object guard_manager; + py::object code; + void* root_mgr; + + PrecompileEntry(py::object gm, py::object c); +} PrecompileEntry; + +typedef struct VISIBILITY_HIDDEN ExtraState { + // A pointer to the orig_code object to prevent race conditions in invalidate + // function. + PyCodeObject* orig_code; + std::list precompile_entries; + // List of cache entries for compiled code objects + std::list cache_entry_list; + // Frame state to detect dynamic shape dims + py::dict frame_state; + // Actions to apply to all frames with this code object + FrameExecStrategy strategy{DEFAULT, DEFAULT}; + + ExtraState(PyCodeObject* orig_code_arg); + CacheEntry* get_first_entry(); + void move_to_front(CacheEntry* cache_entry); + void move_to_back(CacheEntry* cache_entry); + void invalidate(CacheEntry* cache_entry, py::object deleted_guard_manager); +} ExtraState; + +#else + +typedef struct ExtraState ExtraState; +typedef struct PrecompileEntry PrecompileEntry; + +#endif + +// Helper to extra the cache_entry from the extra state. +// Ownership contract +// args +// - extra_state: Borrowed +// return +// - CacheEntry: Borrowed. +CacheEntry* extract_cache_entry(ExtraState* extra_state); + +// Returns either the previously stored frame state or an empty dict. +// Ownership contract +// args +// - extra_state: Borrowed +// return +// - extra_state->frame_state: Borrowed. +FrameState* extract_frame_state(ExtraState* extra_state); + +// Returns the FrameExecStrategy stored in extra_state. +// Ownership contract +// args +// - extra_state: Borrowed +FrameExecStrategy extra_state_get_exec_strategy(ExtraState* extra_state); + +// Set the FrameExecStrategy to be done to all frames with code object +// corresponding to this extra_state. Ownership contract +// - extra_state: Borrowed +void extra_state_set_exec_strategy( + ExtraState* extra_state, + FrameExecStrategy strategy); + +// Ownership contract +// args +// - code: Borrowed +// return +// - extra_state: Borrowed. +ExtraState* get_extra_state(PyCodeObject* code); + +// This is passed as freefunc to _PyEval_RequestCodeExtraIndex. This acts as a +// deleter for the object on extra scratch space. This function is called +// internally in _PyCode_SetExtra and also during the code deallocation. + +// Destroys the extra state by deleting cache_entry, frame state and finally +// freeing the constructed extra state. + +// Developer note - You should not call this function directly. This is called +// directly inside set_extra_state. If you are in a situation trying to call +// this function, consider if set_extra_state should be called. +void destroy_extra_state(void* obj); + +// Clears the existing object sitting on the extra scratch spance and sets it +// up with the new state. Note that _PyCode_SetExtra calls the +// destroy_extra_state deleter internally, and therefore we don't call it +// explicitly here. + +// Ownership contract +// args +// - extra_state: Stolen +// return +// - there is no return, but the extra_state is stolen, so it becomes +// set_extra_state responsibility to clean it up. It will be deleted during +// the reset_code, when the set_extra_state is called with NULL. + +// Invariant - Dont set the extra state for the extra state that is already on +// the code object. Otherwise, we will first free up the old extra state +// (which is also the new extra state) and write something invalid on the +// scratch space. +void set_extra_state(PyCodeObject* code, ExtraState* extra_state); + +// Creates a new extra state and put it on the extra scratch space of the code +// object. + +// Ownership contract +// args +// - code: Borrowed +// return: +// - extra_state: New reference. +// These references are then further passed to set_extra_state which becomes +// the final owner of these references. +ExtraState* init_and_set_extra_state(PyCodeObject* code); + +// Lookup the cache held by extra_state. +// Ownership contract +// args +// - extra_state: Borrowed +// return: +// - Py_None or PyCodeObject: Borrowed reference. +// - Py_None or PyObject: Trace id of the compiled code. +void lookup( + ExtraState* extra_state, + FrameLocalsMapping* f_locals, + PyObject* backend, + PyObject** maybe_cached_code, + const char** trace_annotation, + bool is_skip_guard_eval_unsafe); + +// Create a new cache entry at extra_state holding on to guarded_code. +// Ownership contract +// args +// - extra_state: Borrowed +// - guarded_code: Borrowed +// return: +// - cache_entry: Borrowed reference +CacheEntry* create_cache_entry( + ExtraState* extra_state, + PyObject* guraded_code, + PyObject* callback); + +// Extracts the backend fn from the callback. +PyObject* get_backend(PyObject* callback); + +#ifdef __cplusplus + +} // extern "C" + +// Returns the list of CacheEntry corresponding to code_obj. +// Warning: returns references whose lifetimes are controlled by C++ +py::list _debug_get_cache_entry_list(const py::handle& code_obj); +void _reset_precompile_entries(const py::handle& code_obj); +void _load_precompile_entry( + const py::handle& code_obj, + py::object guard_manager, + py::object dynamo_code); +py::list _debug_get_precompile_entries(const py::handle& code_obj); +void _set_lru_cache(py::object boolean); + +#endif + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/framelocals_mapping.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/framelocals_mapping.h new file mode 100644 index 0000000000000000000000000000000000000000..a604a35ff5a988ddfd6fc65c61b6200ee1d1814f --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/framelocals_mapping.h @@ -0,0 +1,97 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +#ifdef __cplusplus + +#include +#include + +#include +#include + +extern "C" { + +#if IS_PYTHON_3_11_PLUS +using FrameLocalsFrameType = _PyInterpreterFrame; +#else +using FrameLocalsFrameType = PyFrameObject; +#endif // IS_PYTHON_3_11_PLUS + +/** + * Utility to view a frame's localsplus (locals + cells + freevars) + * in C/C++ and Python, without changing the state of the frame. + * + * Notes on usage: + * - C/C++ can directly read the frame's localsplus using an index. + * - Cell/free variables are unboxed. + * - Can be converted into a dict for use in Python. + * The dict is constructed once per FrameLocalsMapping, lazily. + * - Lifetime should not exceed the lifetime of the frame + * + * How do guards use FrameLocalsMapping? + * - When a guard accesses a frame's localsplus, we find the index of the + * variable name in the frame's code object and create a + * FrameLocalsGuardAccessor. + * - We create a FrameLocalsMapping for the frame that we pass on to guard eval. + * - LeafGuards/GuardManagers/GuardAccessors now need to define how they + * handle FrameLocalsMapping. By default, the FrameLocalsMapping is converted + * to a Python dict and the guard check is performed on the resulting dict. + * - Some guard checks don't actually depend on the input arguments, e.g. they + * only check global state. In this case, no dict conversion of + * FrameLocalsMapping is done. + * - FrameLocalsGuardAccessor is like DictGetItemGuardAccessor, except it knows + * how to handle FrameLocalsMapping - by using the framelocals variable name + * index that it was given when it was built. + */ +typedef struct VISIBILITY_HIDDEN FrameLocalsMapping { + private: + py::object _code_obj; + // can't use localsplus directly due to closure variables: + // - in 3.11+, the closure vars in the frame's closure object and + // the corresponding localsplus entry is nullptr + // - regardless of Python version, we need to unbox the cell variable + std::vector _framelocals; + + py::object _dict{py::none()}; + + void _realize_dict(); + + public: + explicit FrameLocalsMapping(FrameLocalsFrameType* frame); + + PyObject* get(int idx); + + bool dict_realized() const { + return _dict.is_none(); + } + + // Borrowed reference + PyDictObject* to_dict() { + if (this->dict_realized()) { + _realize_dict(); + } + return (PyDictObject*)_dict.ptr(); + } +} FrameLocalsMapping; + +#else + +// opaque type for C +typedef struct FrameLocalsMapping FrameLocalsMapping; + +#endif + +// Borrowed reference +PyDictObject* framelocals_mapping_to_dict(FrameLocalsMapping* map); + +#ifdef __cplusplus +} // extern "C" + +py::tuple code_framelocals_names(py::handle code); +#endif + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/guards.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/guards.h new file mode 100644 index 0000000000000000000000000000000000000000..1541a95dccfbf2e4a39427e7721a1d5ecc259d29 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/guards.h @@ -0,0 +1,119 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include +#include +#include +#include + +namespace torch::dynamo { + +PyObject* torch_c_dynamo_guards_init(); + +// interfaces for extra_state and eval_frame.c because RootGuardManager class is +// not visible there. +void* convert_to_root_guard_manager(py::object root); +bool run_root_guard_manager(void* root, FrameLocalsMapping* f_locals); + +extern thread_local bool tls_is_in_mode_without_ignore_compile_internals; + +void set_is_in_mode_without_ignore_compile_internals(bool value); + +// If we're in a mode with ignore_compile_internals=False, we WON'T mask +// Python keys from guard checking (they should be visible, so eager fallback is +// possible). Otherwise (invisible mode or no mode), we WILL mask Python keys to +// avoid guard failures on the dispatch keyset at runtime. +bool get_is_in_mode_without_ignore_compile_internals(); + +struct LocalState { + // TLS state that changes operators + c10::impl::LocalDispatchKeySet dispatch_modifier; + c10::DispatchKeySet override_dispatch_key_set; + bool grad_mode_enabled; + bool should_mask_python_keys; + + at::DispatchKeySet apply(at::DispatchKeySet ks) const { + if (override_dispatch_key_set.empty()) { + auto result = + (ks | dispatch_modifier.included_) - dispatch_modifier.excluded_; + + if (should_mask_python_keys) { + result = result - + c10::DispatchKeySet( + {c10::DispatchKey::Python, + c10::DispatchKey::PythonTLSSnapshot}); + } + + return result; + } else { + return override_dispatch_key_set; + } + } + + LocalState() + : dispatch_modifier(c10::impl::tls_local_dispatch_key_set()), + override_dispatch_key_set(c10::BackendComponent::InvalidBit), + grad_mode_enabled(at::GradMode::is_enabled()), + should_mask_python_keys( + !get_is_in_mode_without_ignore_compile_internals()) {} + + void overrideDispatchKeySet(c10::DispatchKeySet ks) { + override_dispatch_key_set = ks; + } +}; + +class TensorCheck { + public: + TensorCheck( + const LocalState& state, + PyTypeObject* pt, + const at::Tensor& v, + c10::DispatchKeySet dispatch_key_set, + std::vector> dynamic_dims_sizes, + std::vector> dynamic_dims_strides); + + TensorCheck( + const LocalState& state, + PyTypeObject* pt, + c10::DispatchKeySet dispatch_key_set, + at::ScalarType dtype, + at::DeviceIndex device_index, + bool requires_grad, + std::vector> dynamic_dims_sizes, + std::vector> dynamic_dims_strides); + + bool check(const LocalState& state, const at::Tensor& v); + bool check( + const LocalState& state, + const c10::DispatchKeySet& dispatch_key_set, + const at::ScalarType& dtype, + const c10::Device& device, + const c10::SymIntArrayRef& dynamic_dims_sizes, + const c10::SymIntArrayRef& dynamic_dims_strides, + const bool& requires_grad); + std::string check_verbose( + const LocalState& state, + const at::Tensor& v, + const std::string& tensor_name); + + PyTypeObject* pytype; + + private: + uint64_t dispatch_key_; // DispatchKeySet includes device/layout + at::ScalarType dtype_; + // Note(voz): While dispatch_key_ is sufficiently representative of a device + // In that keys are more granular AND device specific - they do not + // necessarily capture device indices correctly. + at::DeviceIndex device_index_; + bool requires_grad_; + // NB: These are unset if dynamic shapes is enabled. + std::vector> sizes_; + std::vector> strides_; + // Not strictly required for dense tensors, but nested tensors need it. + int64_t dim_; +}; + +} // namespace torch::dynamo + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/init.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/init.h new file mode 100644 index 0000000000000000000000000000000000000000..74f5673ff3a012da01afa6b8386db56c48c9516a --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/init.h @@ -0,0 +1,16 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +// C2039 MSVC +#include +#include + +#include + +namespace torch::dynamo { +void initDynamoBindings(PyObject* torch); +} + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/python_compiled_autograd.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/python_compiled_autograd.h new file mode 100644 index 0000000000000000000000000000000000000000..dd48feff5884dacc2b37cb32264a6579f81f8daf --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/python_compiled_autograd.h @@ -0,0 +1,12 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include + +// see [Note: Compiled Autograd] +namespace torch::dynamo::autograd { +PyObject* torch_c_dynamo_compiled_autograd_init(); +} // namespace torch::dynamo::autograd + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/stackref_bridge.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/stackref_bridge.h new file mode 100644 index 0000000000000000000000000000000000000000..6ad3a6390e68e35fdbbce7ce71b86169113094da --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/stackref_bridge.h @@ -0,0 +1,23 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +#if IS_PYTHON_3_14_PLUS + +#ifdef __cplusplus +extern "C" { +#endif // __cplusplus + +// Use a void* to avoid exposing the internal _PyStackRef union on this +// translation unit +PyObject* THP_PyStackRef_AsPyObjectBorrow(void* stackref); + +#ifdef __cplusplus +} +#endif // __cplusplus +#endif // IS_PYTHON_3_14_PLUS + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/utils.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/utils.h new file mode 100644 index 0000000000000000000000000000000000000000..3a6063bf47bf724386c321c87fe1baad658fada4 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/utils.h @@ -0,0 +1,23 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include +// C2039 MSVC +#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::dynamo { +PyObject* torch_c_dynamo_utils_init(); +} // namespace torch::dynamo + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/export/example_upgraders.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/export/example_upgraders.h new file mode 100644 index 0000000000000000000000000000000000000000..1fb15f1f81f0c047e26443519d168d853dea5751 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/export/example_upgraders.h @@ -0,0 +1,20 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +namespace torch::_export { + +/// Register example upgraders for the upgrader system for testing. +/// This function demonstrates common upgrade patterns and is primarily +/// used for testing and demonstration purposes. +void registerExampleUpgraders(); + +/// Deregister example upgraders for the upgrader system for testing. +/// This function cleans up the example upgraders that were registered +/// by registerExampleUpgraders(). +void deregisterExampleUpgraders(); + +} // namespace torch::_export + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/export/pt2_archive_constants.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/export/pt2_archive_constants.h new file mode 100644 index 0000000000000000000000000000000000000000..1bcca4aabc64c5a27500098ca89090e0f1e3a857 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/export/pt2_archive_constants.h @@ -0,0 +1,76 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +namespace torch::_export::archive_spec { + +#define FORALL_CONSTANTS(DO) \ + DO(ARCHIVE_ROOT_NAME, "package") \ + /* Archive format */ \ + DO(ARCHIVE_FORMAT_PATH, "archive_format") \ + DO(ARCHIVE_FORMAT_VALUE, "pt2") \ + /* Archive version */ \ + DO(ARCHIVE_VERSION_PATH, "archive_version") \ + DO(ARCHIVE_VERSION_VALUE, "0") /* Sep.4.2024: This is the initial version of \ + the PT2 Archive Spec */ \ + /* \ + * ######## Note on updating ARCHIVE_VERSION_VALUE ######## \ + * When there is a BC breaking change to the PT2 Archive Spec, \ + * e.g. deleting a folder, or changing the naming convention of the \ + * following fields it would require bumping the ARCHIVE_VERSION_VALUE \ + * Archive reader would need corresponding changes to support loading both \ + * the current and older versions of the PT2 Archive. \ + */ \ + /* Model definitions */ \ + DO(MODELS_DIR, "models/") \ + DO(MODELS_FILENAME_FORMAT, "models/{}.json") /* {model_name} */ \ + /* AOTInductor artifacts */ \ + DO(AOTINDUCTOR_DIR, "data/aotinductor/") \ + /* MTIA artifacts */ \ + DO(MTIA_DIR, "data/mtia") \ + /* weights, including parameters and buffers */ \ + DO(WEIGHTS_DIR, "data/weights/") \ + DO(WEIGHT_FILENAME_PREFIX, "weight_") \ + DO(WEIGHTS_PARAM_CONFIG_FORMAT, "data/weights/{}_model_param_config.json") \ + DO(WEIGHTS_CONFIG_FILENAME_FORMAT, "data/weights/{}_weights_config.json") \ + /* constants, including tensor_constants, non-persistent buffers and script \ + * objects */ \ + DO(CONSTANTS_DIR, "data/constants/") \ + DO(CONSTANTS_PARAM_CONFIG_FORMAT, \ + "data/constants/{}_model_constants_config.json") \ + DO(CONSTANTS_CONFIG_FILENAME_FORMAT, \ + "data/constants/{}_constants_config.json") \ + DO(TENSOR_CONSTANT_FILENAME_PREFIX, "tensor_") \ + DO(CUSTOM_OBJ_FILENAME_PREFIX, "custom_obj_") \ + /* example inputs */ \ + DO(SAMPLE_INPUTS_DIR, "data/sample_inputs/") \ + DO(SAMPLE_INPUTS_FILENAME_FORMAT, \ + "data/sample_inputs/{}.pt") /* {model_name} */ \ + /* ExecuTorch artifacts, including PTE files */ \ + DO(EXECUTORCH_DIR, "data/executorch/") \ + /* extra folder */ \ + DO(EXTRA_DIR, "extra/") \ + DO(MODULE_INFO_PATH, "extra/module_info.json") \ + /* xl_model_weights, this folder is used for storing per-feature-weights for \ + * remote net data in this folder is consume by Predictor, and is not \ + * intended to be used by Sigmoid */ \ + DO(XL_MODEL_WEIGHTS_DIR, "xl_model_weights/") \ + DO(XL_MODEL_WEIGHTS_PARAM_CONFIG_PATH, "xl_model_weights/model_param_config") + +#define DEFINE_GLOBAL(NAME, VALUE) \ + inline constexpr std::string_view NAME = VALUE; +FORALL_CONSTANTS(DEFINE_GLOBAL) +#undef DEFINE_GLOBAL + +#define DEFINE_ENTRY(NAME, VALUE) std::pair(#NAME, VALUE), +inline constexpr std::array kAllConstants{FORALL_CONSTANTS(DEFINE_ENTRY)}; +#undef DEFINE_ENTRY + +#undef FORALL_CONSTANTS +} // namespace torch::_export::archive_spec + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/export/pybind.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/export/pybind.h new file mode 100644 index 0000000000000000000000000000000000000000..a621d3cc80658866a78f6f44a0aecef59c6dabf2 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/export/pybind.h @@ -0,0 +1,12 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#include + +namespace torch::_export { + +void initExportBindings(PyObject* module); + +} // namespace torch::_export + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/export/upgrader.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/export/upgrader.h new file mode 100644 index 0000000000000000000000000000000000000000..d0c9d1f72fdb1c2a56014351d011f60fe6af2cec --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/export/upgrader.h @@ -0,0 +1,124 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include + +namespace torch::_export { + +/// Function type for upgrading JSON fields during schema version migration. +/// Takes a JSON field and returns the upgraded version of that field. +using UpgraderFunction = std::function; + +/// Structure containing upgrader information for a specific keypath. +/// The version is stored as the map key in the registry, so it's not +/// duplicated here. +struct Upgrader { + /// Path to the field that should be upgraded (e.g., {"graph_module", "graph", + /// "nodes"}) Assuming top-level is a JSON object that represents + /// ExportedProgram + std::vector keypath; + + /// Function that performs the actual upgrade transformation + UpgraderFunction upgrade_func; + + /// Constructor for creating an upgrader with keypath and function + Upgrader(std::vector kp, UpgraderFunction func); + + /// Comparator for maintaining bottom-up ordering in the registry. + /// Deeper keypaths are processed first to ensure safe upgrade application + /// without conflicts between parent and child field modifications. + bool operator<(const Upgrader& other) const; +}; + +/// Register an upgrader function for a specific schema version and keypath. +/// +/// This function allows registration of custom upgrade logic that will be +/// applied when upgrading artifacts from the specified version. Upgraders +/// are applied in bottom-up order (deeper keypaths first) to prevent +/// conflicts between parent and child field modifications. +/// +/// @param version The schema version this upgrader applies to +/// @param keypath The key path to the field that should be upgraded +/// @param upgrade_func Function that performs the upgrade transformation +void registerUpgrader( + int version, + const std::vector& keypath, + const UpgraderFunction& upgrade_func); + +/// Register an upgrader function using dot-separated keypath notation. +/// +/// Convenience overload that accepts dot-separated keypath strings for +/// simpler syntax. For example: "graph_module.graph.nodes" instead of +/// {"graph_module", "graph", "nodes"}. +/// +/// @param version The schema version this upgrader applies to +/// @param dot_keypath Dot-separated keypath string (e.g., "graph.nodes") +/// @param upgrade_func Function that performs the upgrade transformation +void registerUpgrader( + int version, + const std::string& dot_keypath, + const UpgraderFunction& upgrade_func); + +/// Deregister an upgrader function for a specific schema version and keypath. +/// +/// This function allows removal of previously registered upgrade logic for +/// the specified version and keypath. This is useful for testing scenarios +/// where you need to clean up registered upgraders or modify upgrader +/// behavior dynamically. +/// +/// @param version The schema version to deregister the upgrader from +/// @param keypath The key path to the field that should be deregistered +/// @return true if an upgrader was found and removed, false otherwise +bool deregisterUpgrader(int version, const std::vector& keypath); + +/// Deregister an upgrader function using dot-separated keypath notation. +/// +/// Convenience overload that accepts dot-separated keypath strings for +/// simpler syntax. For example: "graph_module.graph.nodes" instead of +/// {"graph_module", "graph", "nodes"}. +/// +/// @param version The schema version to deregister the upgrader from +/// @param dot_keypath Dot-separated keypath string (e.g., "graph.nodes") +/// @return true if an upgrader was found and removed, false otherwise +bool deregisterUpgrader(int version, const std::string& dot_keypath); + +/// Utility function for throwing consistent upgrader errors. +/// +/// This function formats error messages in a standardized way for upgrader +/// failures, including version information and optional problematic object +/// details for debugging. +/// +/// @param upgrader_name Name of the upgrader that failed +/// @param from_version Source schema version being upgraded from +/// @param error_message Descriptive error message +/// @param problematic_object Optional JSON object that caused the error +/// @throws std::runtime_error Always throws with formatted error message +void throwUpgraderError( + const std::string& upgrader_name, + int from_version, + const std::string& error_message, + const nlohmann::json& problematic_object = nlohmann::json::object()); + +/// Upgrade a JSON artifact to a specific target version with available +/// upgraders until a target version is reached. +/// +/// This handles major version upgrade only. For minor version upgrade, +/// e.g. adding a new field with default value, it's automatically handled by +/// the default constructor in generated_serialization_types.h. +/// +/// @param artifact The JSON artifact to upgrade(passed by value: function +/// operates on a local copy, original remains unmodified) +/// @param target_version The target schema version to upgrade to +/// @return The upgraded JSON artifact with updated schema version +/// @throws std::runtime_error if artifact is missing schema_version field +/// @throws std::runtime_error if final version doesn't match target version +nlohmann::json upgrade(nlohmann::json artifact, int target_version); + +} // namespace torch::_export + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/functionalization/Module.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/functionalization/Module.h new file mode 100644 index 0000000000000000000000000000000000000000..8d9ef7eee21ea132de0b5ce75a25345bdfc2539f --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/functionalization/Module.h @@ -0,0 +1,41 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +#include +#include + +namespace torch::functionalization { + +// Creates the default bindings for `ViewMeta` specializations. +// +// Defines a constructor using the types in `SerializableTuple`, as well +// as pickle methods. +template +void create_binding_with_pickle(py::module m) { + py::class_, at::functionalization::ViewMeta>( + m, T::name()) + .def(py::init()) + .def( + "as_tuple", + [](const std::shared_ptr& meta) { + return meta->to_serializable_tuple(); + }) + .def(py::pickle( + [](const std::shared_ptr& meta) { + return meta->to_serializable_tuple(); + }, + [](const typename T::SerializableTuple& tpl) { + return std::make_shared(tpl); + })); +} + +void initModule(PyObject* module); +void initGenerated(PyObject* module); + +} // namespace torch::functionalization + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/functorch/init.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/functorch/init.h new file mode 100644 index 0000000000000000000000000000000000000000..e92e68fc321237beb24195636ff4f689105e5733 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/functorch/init.h @@ -0,0 +1,12 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#include + +namespace torch::functorch::impl { + +void initFuncTorchBindings(PyObject* module); + +} + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/fx/node.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/fx/node.h new file mode 100644 index 0000000000000000000000000000000000000000..a4d3f2d4fdcb780ca683a63b5a384c1f6aafc93c --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/fx/node.h @@ -0,0 +1,11 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +bool NodeBase_init(PyObject* module); +bool NodeIter_init(PyObject* module); + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_eager/kernel_holder.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_eager/kernel_holder.h new file mode 100644 index 0000000000000000000000000000000000000000..b742973eeee6e6d1a9264fdc9d428cf2650c7c0a --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_eager/kernel_holder.h @@ -0,0 +1,117 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#if !defined(C10_MOBILE) && !defined(ANDROID) +#pragma once + +#include +#include +#include + +#include +#include +#include +#include + +#include + +namespace torch::inductor { + +// Represent AOTI kernel. It contains all the parameter metadata of the kernel +// and the AOTI model runner. +struct AOTIKernelMetadata { + // Represent all the parameters of AOTI kernel + std::vector parameter_metadata_list_; + // AOTI model runner to run the AOTI kernel + std::shared_ptr kernel_runner_; + AOTIKernelMetadata() : kernel_runner_(nullptr) {} + + // Check whether the given parameter metadata list is the same as the + // parameter metadata list of the AOTI kernel. + bool check( + const std::vector& parameter_metadata_list) const { + if (parameter_metadata_list_.size() != parameter_metadata_list.size()) { + return false; + } + + for (size_t i = 0; i < parameter_metadata_list_.size(); ++i) { + if (parameter_metadata_list_[i] == parameter_metadata_list[i]) { + continue; + } else { + return false; + } + } + + return true; + } +}; + +// The AOTIPythonKernelHolder class uses the AOT Inductor to generate a kernel +// for a specified operation. To speed up this process, the generated kernel +// library is cached on disk. Detailed information from the input tensors is +// used as the key for caching the kernel library. On subsequent runs, these +// input tensors are used to search the cache. If a cache hit occurs, the cached +// kernel library is loaded and executed. If a cache miss occurs, the AOT +// Inductor is called again to generate the kernel library. +class AOTIPythonKernelHolder : public c10::OperatorKernel { + // A DispatchKey object that represents the dispatch key for the kernel. + c10::DispatchKey dispatch_key_; + // Namespace of the kernel. + std::string ns_; + // Name of the operation the kernel performs. + std::string op_name_with_overload_; + // The device on which the kernel is to be executed. + c10::Device device_; + // The Python interpreter to get OpOverload object with the given op_name and + // op_overload_name. + c10::impl::PyInterpreter* pyinterpreter_; + // Cache the produced kernels by AOTI and its metadata + std::vector aoti_kernel_cache_; + + public: + AOTIPythonKernelHolder( + c10::DispatchKey dispatch_key, + std::string_view ns, + std::string_view op_name_with_overload); + + void operator()( + const c10::OperatorHandle& op, + c10::DispatchKeySet keyset, + torch::jit::Stack* stack); + + private: + bool cache_lookup( + const c10::OperatorHandle& op, + const c10::DispatchKeySet& keyset, + const torch::jit::Stack* stack, + AOTIKernelMetadata& aoti_kernel_metadata); + void cache_miss( + const c10::OperatorHandle& op, + const c10::DispatchKeySet& keyset, + torch::jit::Stack* stack); + void cache_hit( + const AOTIKernelMetadata& aoti_kernel_metadata, + const c10::OperatorHandle& op, + const c10::DispatchKeySet& keyset, + torch::jit::Stack* stack); + // Invoke python utility function on the Inductor side to produce AOTI kernel + // for the given operation. + // Inductor utility function - + // torch._inductor.utils.aoti_compile_with_persistent_cache + std::string produce_aoti_kernel_lib( + const c10::OperatorHandle& op, + const c10::DispatchKeySet& keyset, + const torch::jit::Stack* stack); + // Invoke python utility function on the Inductor side to load AOTI kernel for + // the given operation. + // Inductor utility function - torch._inductor.utils.load_aoti_eager_cache + void init_aoti_kernel_cache(); + // Load the AOTIModelContainerRunner object from the given file path. + std::shared_ptr load_aoti_model_runner( + const std::string& /*so_path*/); +}; + +} // namespace torch::inductor +#endif + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_eager/kernel_meta_info.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_eager/kernel_meta_info.h new file mode 100644 index 0000000000000000000000000000000000000000..c2f7db1289d19a202cc30661f94edd2a47387ff3 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_eager/kernel_meta_info.h @@ -0,0 +1,147 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#if !defined(C10_MOBILE) && !defined(ANDROID) +#pragma once + +#include +#include +#include + +#include + +namespace torch::inductor { + +// Regarding a aten operation implemented by AOTI, the metadata of the input +// tensors will be cached on the disk to accelerate next run. TensorMetada +// structure is to represent the metadata of each input tensor. It includes +// whether the tensor is symbolic, the dtype, the device, the sizes and the +// strides of the tensor. When the metadata of the input tensors is the same as +// the cached metadata, the cached kernel library will be loaded and executed. +// Otherwise, the AOT Inductor will be called again to generate the kernel +// library. +// Beyond the TensorMetadata, we build guard/TensorCheck for each input tensor +// as well to support symbolic shape. We intend to utilize TensorCheck to find +// out the proper kernel rather than TensorMetada comparison. Suppose an +// operation with a single input tensor and two kernels: +// kernel1: TensorMetadata(is_symbolic=false, dtype=Float, device=CPU, +// sizes=[s0, s1, s2], strides=[s1 * s2, s2, 1]) kernel2: +// TensorMetadata(is_symbolic=false, dtype=Float, device=CPU, sizes=[3, s1, +// s2], strides=[s1 * s2, s2, 1]) +// If a tensor with sizes=[3, 4, 5] is passed to the operation, both kernel1 and +// kernel2 support the tensor shape. In this case, we need to use TensorCheck +// plus some heruistic rules to find out the proper kernel. +struct TensorMetadata { + // Indicate whether the tensor is symbolic and it may be concluded by sizes_ + // and strides_ in the future. + bool is_symbolic_; + // Dtype of a tensor(For scalar, we will wrap it as a scalar tensor) + c10::ScalarType dtype_ = c10::ScalarType::Undefined; + // Device of a tensor. + c10::Device device_; + // Dispatch key set of a tensor + c10::DispatchKeySet dispatch_key_set_; + // Sizes of a tensor. Currently, we only support static shape and use int64_t + // to represent the sizes. In the future, we will create symbolic size and use + // SymInt to represent it to support symbolic shape. + std::vector sizes_; + // Strides of a tensor. For symbolic shape support, it is the same as sizes_ + std::vector strides_; + // requires grad + bool requires_grad_ = false; + // TensorCheck for the tensor + std::optional tensor_check_; + + TensorMetadata() + : is_symbolic_(false), + device_(c10::DeviceType::COMPILE_TIME_MAX_DEVICE_TYPES), + sizes_({}), + strides_({}) {} + TensorMetadata(const at::Tensor& src_tensor); + TensorMetadata( + bool is_symbolic, + c10::ScalarType dtype, + c10::Device device, + c10::DispatchKeySet dispatch_key_set, + std::vector sizes, + std::vector strides, + bool requires_grad = false); + + // Build TensorCheck for the tensor by using the data fields in TensorMetadata + void build_guard(const dynamo::LocalState& local_state); + + // Compare two TensorMetadata objects + bool operator==(const TensorMetadata& other) const; +}; + +// ParameterTag is to represent the type of the input parameters of a aten +// operation. Currently, we support the following types: +// 1. TENSOR: a single tensor +// 2. TENSOR_OPTIONAL: a single optional tensor +// 3. TENSOR_LIST: a list of tensors +// 4. TENSOR_LIST_OPTIONAL: a list of optional tensors +// 5. SCALAR: a scalar value +// If we need to support more types in the future, we will add more types in the +// ParameterTag enum. For example, we will extend the enum to support string, +// Dimname and so on to support more types of input parameters of aten +// operations. +enum ParameterTag { + TENSOR, + TENSOR_OPTIONAL, + TENSOR_LIST, + TENSOR_LIST_OPTIONAL, + SCALAR, + STRING, + DEVICE, + INVALID, +}; + +// ParameterMetadataValue is to represent the value of the input parameters of a +// aten operation. +using ParameterMetadataValue = std::variant< + TensorMetadata, + std::vector, + c10::Scalar, + std::string, + c10::Device>; + +// ParameterMetadata is to represent the metadata of the input parameters of a +// aten operation. It includes the tag of the parameter, the value of the +// parameter and the order of the parameter. +struct ParameterMetadata { + // The tag of the parameter. It indicates the type of the parameter. + ParameterTag tag_; + // The value of the parameter. It can be a tensor, a list of tensors or a + // scalar. + ParameterMetadataValue value_; + // The order of the parameter is used to distinguish the parameters with the + // same tag. For example, an operation with two input tensors, the first + // tensor is a optional tensor and the second tensor is a tensor. The first + // tensor will have the order 0 and the second tensor will have the order 1. + uint64_t order_{}; + + ParameterMetadata() : tag_(INVALID) {} + ParameterMetadata(TensorMetadata tensor_metadata, uint64_t input_order); + ParameterMetadata(const at::Tensor& tensor, uint64_t input_order); + ParameterMetadata( + const std::vector& tensor_list, + uint64_t input_order); + ParameterMetadata( + const std::vector& tensor_metadata_list, + uint64_t input_order); + ParameterMetadata(const c10::Scalar& scalar, uint64_t input_order); + ParameterMetadata(const std::string& string_value, uint64_t input_order); + ParameterMetadata(const c10::Device& device, uint64_t input_order); + + bool operator==(const ParameterMetadata& other) const; + + private: + // Helper function to compare two ParameterMetadata objects with the same + // SCALAR tag. + bool equal_to(const c10::Scalar& scalar) const; +}; + +} // namespace torch::inductor +#endif + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_include/array_ref.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_include/array_ref.h new file mode 100644 index 0000000000000000000000000000000000000000..27cd706592b540eab7f1dab3c76afec0d2789440 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_include/array_ref.h @@ -0,0 +1,12 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_include/common.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_include/common.h new file mode 100644 index 0000000000000000000000000000000000000000..a676e55c9d3b9844b801adbcba8ca3c7473fea95 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_include/common.h @@ -0,0 +1,21 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +#include +#include + +#include +#include + +// Round up to the nearest multiple of 64 +[[maybe_unused]] inline int64_t align(int64_t nbytes) { + return (nbytes + 64 - 1) & -64; +} + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_include/cpu.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_include/cpu.h new file mode 100644 index 0000000000000000000000000000000000000000..08fe09380478cca15008bdbf611eb30606c4b908 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_include/cpu.h @@ -0,0 +1,9 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_include/cuda.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_include/cuda.h new file mode 100644 index 0000000000000000000000000000000000000000..b7e910bf59b308eb889ea81c56a60dbbad8359e3 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_include/cuda.h @@ -0,0 +1,9 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_include/mps.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_include/mps.h new file mode 100644 index 0000000000000000000000000000000000000000..6ed9ce406262d8402fe0ebbdb16822256051896e --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_include/mps.h @@ -0,0 +1,9 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_include/xpu.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_include/xpu.h new file mode 100644 index 0000000000000000000000000000000000000000..59c681ea6a49947bb2b079d31a2669aec7b95ff6 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_include/xpu.h @@ -0,0 +1,9 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_package/model_package_loader.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_package/model_package_loader.h new file mode 100644 index 0000000000000000000000000000000000000000..07ea91b062aac3878b110440f58cd343b0d75b7d --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_package/model_package_loader.h @@ -0,0 +1,64 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#if !defined(C10_MOBILE) && !defined(ANDROID) +#pragma once + +#include +#include +#include + +namespace torch::inductor { +class TORCH_API AOTIModelPackageLoader { + public: + AOTIModelPackageLoader( + const std::string& model_package_path, + const std::string& model_name = "model", + const bool run_single_threaded = false, + const size_t num_runners = 1, + const c10::DeviceIndex device_index = -1); + ~AOTIModelPackageLoader(); + + AOTIModelContainerRunner* get_runner(); + std::unordered_map get_metadata(); + + std::vector run( + const std::vector& inputs, + void* stream_handle = nullptr); + + // boxed_run will steal the ownership of the input tensors + std::vector boxed_run( + std::vector&& inputs, + void* stream_handle = nullptr); + + std::vector get_call_spec(); + void load_constants( + std::unordered_map& constants_map, + bool use_inactive, + bool check_full_update, + bool user_managed = false); + std::vector get_constant_fqns(); + + void update_constant_buffer( + std::unordered_map& tensor_map, + bool use_inactive, + bool validate_full_updates, + bool user_managed = false); + + // Static function to load metadata directly from a model package + static std::unordered_map load_metadata_from_package( + const std::string& model_package_path, + const std::string& model_name); + + private: + std::string temp_dir_; + std::unique_ptr runner_; + std::unordered_map metadata_; + + void load_metadata(const std::string& cpp_filename); +}; + +} // namespace torch::inductor +#endif + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_package/pybind.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_package/pybind.h new file mode 100644 index 0000000000000000000000000000000000000000..7c27556e79df2539098ffd878ea9a6aa44658fec --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_package/pybind.h @@ -0,0 +1,12 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#include + +namespace torch::inductor { + +void initAOTIPackageBindings(PyObject* module); + +} // namespace torch::inductor + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runner/model_container_runner.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runner/model_container_runner.h new file mode 100644 index 0000000000000000000000000000000000000000..90048f79cec66edcf79dfa493e39dea131662f85 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runner/model_container_runner.h @@ -0,0 +1,145 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#if !defined(C10_MOBILE) && !defined(ANDROID) +#pragma once + +#include +#include +#include + +// Forward declare DynamicLibrary +namespace at { +struct DynamicLibrary; +} + +namespace torch::inductor { +using TensorConstantMap = std::unordered_map; + +class TORCH_API AOTIModelContainerRunner { + public: + AOTIModelContainerRunner() = delete; + AOTIModelContainerRunner(const AOTIModelContainerRunner& other) = delete; + AOTIModelContainerRunner(AOTIModelContainerRunner&& other) = delete; + AOTIModelContainerRunner& operator=(const AOTIModelContainerRunner& other) = + delete; + AOTIModelContainerRunner& operator=(AOTIModelContainerRunner&& other) = + delete; + virtual ~AOTIModelContainerRunner(); + + std::vector run( + const std::vector& inputs, + void* stream_handle = nullptr); + + // boxed_run will steal the ownership of the input tensors + std::vector boxed_run( + std::vector&& inputs, + void* stream_handle = nullptr); + + std::unordered_map getConstantNamesToOriginalFQNs() + const; + std::unordered_map getConstantNamesToDtypes() const; + + const std::unordered_map extract_constants_map( + bool use_inactive) const; + void update_inactive_constant_buffer(const TensorConstantMap& const_map); + void update_constant_buffer( + std::unordered_map& tensor_map, + bool use_inactive, + bool validate_full_updates, + bool user_managed = false); + void update_constant_buffer( + const TensorConstantMap& const_map, + bool use_inactive, + bool validate_full_updates, + bool user_managed = false); + void run_const_fold( + bool use_inactive, + AOTInductorStreamHandle cuda_stream_handle = nullptr); + void swap_constant_buffer(); + void free_inactive_constant_buffer(); + void update_constant_buffer_from_blob(const std::string& weights_path); + + std::vector get_call_spec(); + + protected: + AOTIModelContainerRunner( + const std::string& model_so_path, + size_t num_models, + const std::string& device_str, + const std::string& cubin_dir, + const bool run_single_threaded); + + virtual std::vector run_impl( + std::vector& input_handles, + void* stream_handle); + + std::unique_ptr model_so_; + decltype(&AOTInductorModelContainerCreateWithDevice) create_func_{nullptr}; + decltype(&AOTInductorModelContainerDelete) delete_func_{nullptr}; + decltype(&AOTInductorModelContainerGetNumOutputs) get_num_outputs_func_{ + nullptr}; + decltype(&AOTInductorModelContainerRun) run_func_{nullptr}; + decltype(&AOTInductorModelContainerGetNumConstants) get_num_constants_func_{ + nullptr}; + decltype(&AOTInductorModelContainerGetConstantName) get_constant_name_func_{ + nullptr}; + decltype(&AOTInductorModelContainerGetConstantOriginalFQN) + get_constant_original_fqn_func_{nullptr}; + decltype(&AOTInductorModelContainerGetConstantDtype) get_constant_dtype_func_{ + nullptr}; + decltype(&AOTInductorModelContainerExtractConstantsMap) + extract_constants_map_func_{nullptr}; + decltype(&AOTInductorModelContainerUpdateUserManagedConstantBuffer) + update_user_managed_constant_buffer_func_{nullptr}; + decltype(&AOTInductorModelContainerUpdateConstantBuffer) + update_constant_buffer_func_{nullptr}; + decltype(&AOTInductorModelContainerUpdateInactiveConstantBuffer) + update_inactive_constant_buffer_func_{nullptr}; + decltype(&AOTInductorModelContainerRunConstantFolding) run_const_fold_func_{ + nullptr}; + decltype(&AOTInductorModelContainerSwapConstantBuffer) + swap_constant_buffer_func_{nullptr}; + decltype(&AOTInductorModelContainerFreeInactiveConstantBuffer) + free_inactive_constant_buffer_func_{nullptr}; + decltype(&AOTInductorModelContainerGetCallSpec) get_call_spec_func_{nullptr}; + decltype(&AOTInductorModelContainerGetConstantsBlobSize) + get_constants_blob_size_func_{nullptr}; + decltype(&AOTInductorModelUpdateConstantsFromBlob) + update_constants_from_blob_func_{nullptr}; + + AOTInductorModelContainerHandle container_handle_ = nullptr; + + AOTIProxyExecutorHandle proxy_executor_handle_; + + private: + std::unique_ptr proxy_executor_; +}; + +using CreateAOTIModelRunnerFunc = std::unique_ptr (*)( + const std::string& model_so_path, + size_t num_models, + const std::string& device_str, + const std::string& bin_dir, + const bool run_single_threaded); + +// Return a global map "device name" -> "aoti model runner create function" for +// all registered in AOTI external backends +TORCH_API std::unordered_map& +getAOTIModelRunnerRegistry(); + +// To register a new external backend in AOTI one needs to create an instance of +// this struct. It is not thread-safe. Because it is expected to be called +// during the initialization of the program. +struct TORCH_API RegisterAOTIModelRunner{RegisterAOTIModelRunner( + const std::string& name, + CreateAOTIModelRunnerFunc create_aoti_model_runner_fn){ + getAOTIModelRunnerRegistry()[name] = create_aoti_model_runner_fn; +} // namespace torch::inductor +} +; + +} // namespace torch::inductor +#endif + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runner/model_container_runner_cpu.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runner/model_container_runner_cpu.h new file mode 100644 index 0000000000000000000000000000000000000000..83eecc1c684973fc4c30e5409ee9b4d48f61cf9a --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runner/model_container_runner_cpu.h @@ -0,0 +1,23 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#if !defined(C10_MOBILE) && !defined(ANDROID) +#pragma once + +#include + +namespace torch::inductor { +class TORCH_API AOTIModelContainerRunnerCpu : public AOTIModelContainerRunner { + public: + AOTIModelContainerRunnerCpu( + const std::string& model_so_path, + size_t num_models = 1, + const bool run_single_threaded = false); + + ~AOTIModelContainerRunnerCpu() override; +}; + +} // namespace torch::inductor +#endif + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runner/model_container_runner_cuda.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runner/model_container_runner_cuda.h new file mode 100644 index 0000000000000000000000000000000000000000..dfdfdaf735409d2f5901b95b13678cd89ef4881c --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runner/model_container_runner_cuda.h @@ -0,0 +1,40 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#if !defined(C10_MOBILE) && !defined(ANDROID) +#pragma once + +#include +#include + +namespace torch::inductor { + +// NOTICE: Following APIs are subject to change due to active development +// We provide NO BC guarantee for these APIs +// NOLINTNEXTLINE(cppcoreguidelines-special-member-functions) +class TORCH_CUDA_CPP_API AOTIModelContainerRunnerCuda + : public AOTIModelContainerRunner { + public: + // @param device_str: cuda device string, e.g. "cuda", "cuda:0" + AOTIModelContainerRunnerCuda( + const std::string& model_so_path, + size_t num_models = 1, + const std::string& device_str = "cuda", + const std::string& cubin_dir = "", + const bool run_single_threaded = false); + + ~AOTIModelContainerRunnerCuda() override; + + std::vector run_impl( + std::vector& input_handles, + void* stream_handle) override; + + std::vector run_with_cuda_stream( + const std::vector& inputs, + const at::cuda::CUDAStream& cuda_stream); +}; + +} // namespace torch::inductor +#endif + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runner/model_container_runner_mps.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runner/model_container_runner_mps.h new file mode 100644 index 0000000000000000000000000000000000000000..2e36e600a6f575e2d8b05cbfdde89fd6837a87d2 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runner/model_container_runner_mps.h @@ -0,0 +1,23 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#if defined(__APPLE__) +#pragma once + +#include + +namespace torch::inductor { +class TORCH_API AOTIModelContainerRunnerMps : public AOTIModelContainerRunner { + public: + AOTIModelContainerRunnerMps( + const std::string& model_so_path, + size_t num_models = 1, + const bool run_single_threaded = false); + + ~AOTIModelContainerRunnerMps() override; +}; + +} // namespace torch::inductor +#endif + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runner/model_container_runner_xpu.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runner/model_container_runner_xpu.h new file mode 100644 index 0000000000000000000000000000000000000000..2a55999f70b8be633b9d90237b18ad8c6502b349 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runner/model_container_runner_xpu.h @@ -0,0 +1,42 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#if !defined(C10_MOBILE) && !defined(ANDROID) +#pragma once + +#include +#include + +namespace torch::inductor { + +// NOTICE: Following APIs are subject to change due to active development +// We provide NO BC guarantee for these APIs + +// HERE we use C10_EXPORT because libtorch_python needs this Symbol be exported. +// And `TORCH_API and `TORCH_XPU_API`` do not export the symbol in Windows +// build. +class C10_EXPORT AOTIModelContainerRunnerXpu : public AOTIModelContainerRunner { + public: + // @param device_str: xpu device string, e.g. "xpu", "xpu:0" + AOTIModelContainerRunnerXpu( + const std::string& model_so_path, + size_t num_models = 1, + const std::string& device_str = "xpu", + const std::string& kernel_bin_dir = "", + const bool run_single_threaded = false); + + ~AOTIModelContainerRunnerXpu() override; + + std::vector run_impl( + std::vector& input_handles, + void* stream_handle) override; + + std::vector run_with_xpu_stream( + const std::vector& inputs, + const at::xpu::XPUStream& xpu_stream); +}; + +} // namespace torch::inductor +#endif + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runner/pybind.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runner/pybind.h new file mode 100644 index 0000000000000000000000000000000000000000..5a0eef2af2edaccf962ce0fc92de97761c2becf1 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runner/pybind.h @@ -0,0 +1,12 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#include + +namespace torch::inductor { + +void initAOTIRunnerBindings(PyObject* module); + +} // namespace torch::inductor + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/arrayref_tensor.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/arrayref_tensor.h new file mode 100644 index 0000000000000000000000000000000000000000..eb556ed29b1d42777a6c38837ed62d80d908ce7c --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/arrayref_tensor.h @@ -0,0 +1,247 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +#include +#include +#include + +namespace torch::aot_inductor { + +using MiniIntArrayRef = MiniArrayRef; + +static_assert( + sizeof(MiniIntArrayRef) == sizeof(void*) + sizeof(size_t), + "changing the size of MiniArrayRef breaks ABI compatibility!"); + +inline bool is_contiguous_strides_for_shape( + int64_t ndim, + const int64_t* strides_ptr, + const int64_t* sizes_ptr) { + int64_t z = 1; + for (int64_t d = ndim - 1; d >= 0; d--) { + const auto& size_d = sizes_ptr[d]; + if (size_d != 1) { + if (strides_ptr[d] == z) { + z *= size_d; + } else { + return false; + } + } + } + return true; +} + +// Shim for AOTI generated code to pretend a raw array works like an +// AtenTensorHandle. +template +class ArrayRefTensor { + public: + ArrayRefTensor() = default; + + explicit ArrayRefTensor( + MiniArrayRef arr, + MiniArrayRef sizes, + MiniArrayRef strides, + int32_t device_type, + int32_t device_idx) + : arrayRef_(arr), + sizes_(sizes), + strides_(strides), + device_type_(device_type), + device_idx_(device_idx) { + assert(sizes.size() == strides.size()); + assert(is_contiguous_strides_for_shape( + sizes.size(), strides.data(), sizes.data())); + } + + AtenTensorHandle expensiveCopyToTensor() const { + AtenTensorHandle result = nullptr; + AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_empty_strided( + sizes_.size(), + sizes_.data(), + strides_.data(), + aoti_torch_dtype>(), + device_type_, + device_idx_, + &result)); + void* dataPtr = nullptr; + AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_get_data_ptr(result, &dataPtr)); + std::memcpy(dataPtr, data(), numel() * sizeof(T)); + return result; + } + + // We need to look the same as RAIIAtenTensorHandle, which returns + // an owning AtenTensorHandle from release(). So, we allocate one! + AtenTensorHandle release() { + return expensiveCopyToTensor(); + } + + AtenTensorHandle borrowAsTensor() const { + AtenTensorHandle result = nullptr; + AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_create_tensor_from_blob_v2( + data(), + sizes_.size(), + sizes_.data(), + strides_.data(), + 0, + aoti_torch_dtype>(), + device_type_, + device_idx_, + &result, + aoti_torch_layout_strided(), + nullptr, + 0)); + return result; + } + + // We don't need to free any memory. + void reset() {} + + auto sizes() const { + return sizes_; + } + + auto strides() const { + return strides_; + } + + auto device_type() const { + return device_type_; + } + + auto device_idx() const { + return device_idx_; + } + + T* data() const { + return arrayRef_.data(); + } + + auto numel() const { + return arrayRef_.size(); + } + + void set_arrayref(MiniArrayRef new_arrayref) { + arrayRef_ = new_arrayref; + } + + private: + MiniArrayRef arrayRef_; + // We expect generated code to have statically available sizes & + // strides for us. + MiniArrayRef sizes_; + MiniArrayRef strides_; + int32_t device_type_ = 0; + int32_t device_idx_ = 0; + // We continue to zero-initialize this field in case we repurpose + // the space later; having predictable contents can only help. + int32_t unusedDoNotRemoveForABICompatibility_ = 0; +}; + +static_assert( + sizeof(ArrayRefTensor) == + 3 * sizeof(MiniIntArrayRef) + 3 * sizeof(int32_t) + + (alignof(ArrayRefTensor) > 4 ? sizeof(int32_t) : 0), + "changing the size of ArrayRefTensor breaks ABI compatibility!"); + +template +inline ArrayRefTensor reinterpret_tensor_wrapper( + const ArrayRefTensor& self, + int64_t ndim, + const int64_t* sizes_ptr, + const int64_t* strides_ptr, + int64_t storage_offset) { + // REVIEW: we should add a way to build the DSO in debug mode during + // tests so we can have checks like this! + assert(is_contiguous_strides_for_shape(ndim, strides_ptr, sizes_ptr)); + return ArrayRefTensor( + MiniArrayRef( + self.data() + storage_offset, self.numel() - storage_offset), + MiniArrayRef(sizes_ptr, ndim), + MiniArrayRef(strides_ptr, ndim), + self.device_type(), + self.device_idx()); +} + +template +inline T* get_data_ptr_wrapper(ArrayRefTensor& tensor) { + return tensor.data(); +} + +template +inline T* get_data_ptr_wrapper(const MiniArrayRef& arr) { + return arr.data(); +} + +template +inline const ArrayRefTensor& unwrap_raii_handle_if_needed( + const ArrayRefTensor& tensor) { + return tensor; +} + +template +inline ArrayRefTensor& unwrap_raii_handle_if_needed( + ArrayRefTensor& tensor) { + return tensor; +} + +template +inline const ArrayRefTensor& wrap_with_raii_handle_if_needed( + const ArrayRefTensor& tensor) { + return tensor; +} + +template +inline ArrayRefTensor& wrap_with_raii_handle_if_needed( + ArrayRefTensor& tensor) { + return tensor; +} + +template +inline ArrayRefTensor wrap_with_raii_handle_if_needed( + ArrayRefTensor&& tensor) { + return std::move(tensor); +} + +template +inline RAIIAtenTensorHandle expensive_copy_to_tensor_if_needed( + const ArrayRefTensor& tensor) { + return tensor.expensiveCopyToTensor(); +} + +inline AtenTensorHandle expensive_copy_to_tensor_if_needed( + AtenTensorHandle handle) { + return handle; +} + +template +const T& copy_arrayref_tensor_to_tensor(const T& t) { + return t; +} + +template +RAIIAtenTensorHandle copy_arrayref_tensor_to_tensor( + const ArrayRefTensor& art) { + return art.expensiveCopyToTensor(); +} + +template +const T& borrow_arrayref_tensor_as_tensor(const T& t) { + return t; +} + +template +RAIIAtenTensorHandle borrow_arrayref_tensor_as_tensor( + const ArrayRefTensor& art) { + return art.borrowAsTensor(); +} + +} // namespace torch::aot_inductor + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/constant_type.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/constant_type.h new file mode 100644 index 0000000000000000000000000000000000000000..8666e0556acbebc2e798e02d05b725be57a167ea --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/constant_type.h @@ -0,0 +1,25 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +// WARNING: Be careful when adding new includes here. This header will be used +// in model.so, and should not refer to any aten/c10 headers except the stable +// C ABI defined in torch/csrc/inductor/aoti_torch/c/shim.h. The same rule +// applies to other files under torch/csrc/inductor/aoti_runtime/. + +namespace torch::aot_inductor { + +enum ConstantType : uint8_t { + Unknown = 0, + Parameter = 1, + Buffer = 2, + TensorConstant = 3, + FoldedConstant = 4, +}; + +} // namespace torch::aot_inductor + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/device_utils.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/device_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..1c57f319b594df4f4ad0135aab86eff3424244a9 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/device_utils.h @@ -0,0 +1,72 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +// WARNING: Be careful when adding new includes here. This header will be used +// in model.so, and should not refer to any aten/c10 headers except the stable +// C ABI defined in torch/csrc/inductor/aoti_torch/c/shim.h. The same rule +// applies to other files under torch/csrc/inductor/aoti_runtime/. + +#ifdef USE_CUDA + +// FIXME: Currently, CPU and CUDA backend are mutually exclusive. +// This is a temporary workaround. We need a better way to support +// multi devices. + +#include +#include + +#define AOTI_RUNTIME_CUDA_CHECK(EXPR) \ + do { \ + const cudaError_t code = EXPR; \ + const char* msg = cudaGetErrorString(code); \ + if (code != cudaSuccess) { \ + throw std::runtime_error( \ + std::string("CUDA error: ") + std::string(msg)); \ + } \ + } while (0) + +namespace torch::aot_inductor { + +using DeviceStreamType = cudaStream_t; + +} // namespace torch::aot_inductor + +#elif defined(USE_XPU) +#include +#include +#include +#define AOTI_RUNTIME_XPU_CHECK(EXPR) \ + do { \ + const ze_result_t status = EXPR; \ + if (status != ZE_RESULT_SUCCESS) { \ + std::stringstream ss; \ + ss << "L0 runtime error: " << std::hex << std::uppercase << status; \ + throw std::runtime_error(ss.str()); \ + } \ + } while (0) + +namespace torch::aot_inductor { + +using DeviceStreamType = sycl::queue*; + +} // namespace torch::aot_inductor + +#else + +#define AOTI_RUNTIME_CPU_CHECK(EXPR) \ + bool ok = EXPR; \ + if (!ok) { \ + throw std::runtime_error("CPU runtime error"); \ + } + +namespace torch::aot_inductor { + +using DeviceStreamType = void*; + +} // namespace torch::aot_inductor + +#endif // USE_CUDA + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/interface.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/interface.h new file mode 100644 index 0000000000000000000000000000000000000000..e452c68c0be1114b4ec23e05cb77da5a73deb938 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/interface.h @@ -0,0 +1,273 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +// WARNING: Be careful when adding new includes here. This header will be used +// in model.so, and should not refer to any aten/c10 headers except the stable +// C ABI defined in torch/csrc/inductor/aoti_torch/c/shim.h. The same rule +// applies to other files under torch/csrc/inductor/aoti_runtime/. +#include + +#ifdef _WIN32 +/* +On Windows, we need to explicit declaration for export APIs. And because the +package loader call these API via GetProcAddress(ldsym on Linux), we can ignore +the import case. +*/ +#define AOTI_API __declspec(dllexport) +#else +#define AOTI_API __attribute__((__visibility__("default"))) +#endif + +extern "C" { +struct AOTInductorModelOpaque; +using AOTInductorModelHandle = AOTInductorModelOpaque*; + +struct AOTInductorModelContainerOpaque; +using AOTInductorModelContainerHandle = AOTInductorModelContainerOpaque*; + +struct AOTInductorStreamOpaque; +using AOTInductorStreamHandle = AOTInductorStreamOpaque*; + +struct AOTInductorConstantMap; +using AOTInductorConstantMapHandle = AOTInductorConstantMap*; + +struct AOTInductorConstantMapEntry { + const char* name; + AtenTensorHandle handle; +}; + +// TODO: Deprecate this API. This was kept for BC compatibility. +// Please use AOTInductorModelContainerCreateWithDevice instead. +AOTI_API AOTIRuntimeError AOTInductorModelContainerCreate( + AOTInductorModelContainerHandle* container_handle, + size_t num_models, + bool is_cpu, + const char* cubin_dir); + +// Creates an AOTInductor model container. The parameter num_models +// specifies the number of model instances that may be run concurrently for +// the same input model. +// `device_str` MUST NOT be nullptr. It must be a valid device string, e.g. +// "cpu", "cuda", "cuda:0", etc. If the device index is not specified for CUDA +// device, runtime will use the device index returned by +// "cudaGetDevice(&device_idx)" +AOTI_API AOTIRuntimeError AOTInductorModelContainerCreateWithDevice( + AOTInductorModelContainerHandle* container_handle, + size_t num_models, + const char* device_str, + const char* cubin_dir); + +// Deletes the AOTInductor model container. +AOTI_API AOTIRuntimeError AOTInductorModelContainerDelete( + AOTInductorModelContainerHandle container_handle); + +// Runs the inference. +AOTI_API AOTIRuntimeError AOTInductorModelContainerRun( + AOTInductorModelContainerHandle container_handle, + AtenTensorHandle* input_handles, // array of input AtenTensorHandle; handles + // are stolen; the array itself is borrowed + size_t num_inputs, + AtenTensorHandle* + output_handles, // array for writing output AtenTensorHandle; handles + // will be stolen by the caller; the array itself is + // borrowed + size_t num_outputs, + AOTInductorStreamHandle stream_handle, + AOTIProxyExecutorHandle proxy_executor_handle); + +// Single-threaded variant of previous. +AOTI_API AOTIRuntimeError AOTInductorModelContainerRunSingleThreaded( + AOTInductorModelContainerHandle container_handle, + AtenTensorHandle* input_handles, // array of input AtenTensorHandle; handles + // are stolen; the array itself is borrowed + size_t num_inputs, + AtenTensorHandle* + output_handles, // array for writing output AtenTensorHandle; handles + // will be stolen by the caller; the array itself is + // borrowed + size_t num_outputs, + AOTInductorStreamHandle stream_handle, + AOTIProxyExecutorHandle proxy_executor_handle); + +// Retrieves the number of constants for the model. +AOTI_API AOTIRuntimeError AOTInductorModelContainerGetNumConstants( + AOTInductorModelContainerHandle container_handle, + size_t* num_constants); + +// Retrieves a constant's name. +// idx is the index of the internal's constants. +// Need idx < num_constants from AOTInductorModelContainerGetNumConstants +AOTI_API AOTIRuntimeError AOTInductorModelContainerGetConstantName( + AOTInductorModelContainerHandle container_handle, + size_t idx, + const char** name); + +// Retrieves a constant's original FQN. +// idx is the index of the internal's constants. +// Need idx < num_constants from AOTInductorModelContainerGetNumConstants +AOTI_API AOTIRuntimeError AOTInductorModelContainerGetConstantOriginalFQN( + AOTInductorModelContainerHandle container_handle, + size_t idx, + const char** original_fqn); + +// Retrieves whether a constant is from folded. +// idx is the index of the internal's constants. +// Need idx < num_constants from AOTInductorModelContainerGetNumConstants +AOTI_API AOTIRuntimeError AOTInductorModelContainerGetConstantFromFolded( + AOTInductorModelContainerHandle container_handle, + size_t idx, + bool* from_folded); + +// Retrieves the inductor constant type. +// idx is the index of the internal's constants. +// Need idx < num_constants from AOTInductorModelContainerGetNumConstants +AOTI_API AOTIRuntimeError AOTInductorModelContainerGetConstantType( + AOTInductorModelContainerHandle container_handle, + size_t idx, + int32_t* type); + +// Retrieves a constant's dtype. +// idx is the index of the internal's constants. +// Need idx < num_constants from AOTInductorModelContainerGetNumConstants +AOTI_API AOTIRuntimeError AOTInductorModelContainerGetConstantDtype( + AOTInductorModelContainerHandle container_handle, + size_t idx, + int32_t* dtype); + +// Retrieves a constant's data size. +// idx is the index of the internal's constants. +// Need idx < num_constants from AOTInductorModelContainerGetNumConstants +AOTI_API AOTIRuntimeError AOTInductorModelContainerGetConstantDataSize( + AOTInductorModelContainerHandle container_handle, + size_t idx, + size_t* data_size); + +// Extract the constants that is being used in the container. +AOTI_API AOTIRuntimeError AOTInductorModelContainerExtractConstantsMap( + AOTInductorModelContainerHandle container_handle, + AOTInductorConstantMapHandle constant_map_handle, + bool use_inactive); + +// Setup the constant buffer in model container with provided ConstantMap. +// The ConstantMap is user managed, and the user would retain ownership. +AOTI_API AOTIRuntimeError +AOTInductorModelContainerUpdateUserManagedConstantBuffer( + AOTInductorModelContainerHandle container_handle, + AOTInductorConstantMapHandle constant_map_handle, + bool use_inactive, + bool validate_full_update); + +// Same as AOTInductorModelContainerUpdateUserManagedConstantBuffer, +// but no std::unordered_map crosses DLL boundaries for cross-compilation. +AOTI_API AOTIRuntimeError +AOTInductorModelContainerUpdateUserManagedConstantBufferPairs( + AOTInductorModelContainerHandle container_handle, + const AOTInductorConstantMapEntry* pairs, + size_t num_pairs, + bool use_inactive, + bool validate_full_update); + +// Setup the constant buffer in model container with provided ConstantMap +// use_inactive should be set as true if the inactive buffer is to be updated. +// validate_full_update checks if all constants are included in the ConstantMap +AOTI_API AOTIRuntimeError AOTInductorModelContainerUpdateConstantBuffer( + AOTInductorModelContainerHandle container_handle, + AOTInductorConstantMapHandle constant_map_handle, + bool use_inactive, + bool validate_full_update); + +// Setup the inactive constant buffer in model container with provided +// ConstantMap +AOTI_API AOTIRuntimeError AOTInductorModelContainerUpdateInactiveConstantBuffer( + AOTInductorModelContainerHandle container_handle, + AOTInductorConstantMapHandle constant_map_handle); + +// Free the inactive constant buffer in model container. +AOTI_API AOTIRuntimeError AOTInductorModelContainerFreeInactiveConstantBuffer( + AOTInductorModelContainerHandle container_handle); + +// Run constant folding on constant buffer. +AOTI_API AOTIRuntimeError AOTInductorModelContainerRunConstantFolding( + AOTInductorModelContainerHandle container_handle, + bool use_inactive, + AOTInductorStreamHandle stream_handle, + AOTIProxyExecutorHandle proxy_executor_handle); + +// Swap the constant buffer being used to the inactive one. +AOTI_API AOTIRuntimeError AOTInductorModelContainerSwapConstantBuffer( + AOTInductorModelContainerHandle container_handle); + +// Retrieves the number of inputs for the model. +AOTI_API AOTIRuntimeError AOTInductorModelContainerGetNumInputs( + AOTInductorModelContainerHandle container_handle, + size_t* ret_num_inputs); + +// Retrieves the input name at the given index. +AOTI_API AOTIRuntimeError AOTInductorModelContainerGetInputName( + AOTInductorModelContainerHandle container_handle, + size_t input_idx, + const char** ret_input_names); + +// Retrieves the number of outputs for the model. +AOTI_API AOTIRuntimeError AOTInductorModelContainerGetNumOutputs( + AOTInductorModelContainerHandle container_handle, + size_t* ret_num_outputs); + +// Retrieves the output name at the given index. +AOTI_API AOTIRuntimeError AOTInductorModelContainerGetOutputName( + AOTInductorModelContainerHandle container_handle, + size_t output_idx, + const char** ret_output_names); + +// Creates an AOTInductorModel instance. This is a thin and light wrapper +// around the compiled model; it doesn't handle concurrency, queueing, device +// management, etc. Use this if bare-metal performance is needed and you are +// willing to handle other "management" aspects yourself. +// +// constant_map_handle is an opaque type to satisfy the C ABI. It should be a +// std::unordered_map*. +AOTI_API AOTIRuntimeError AOTInductorModelCreate( + AOTInductorModelHandle* model_handle, + AOTInductorConstantMapHandle constant_map_handle); + +// Run an AOTInductorModel (see AOTInductorModelCreate for when one should use +// this function versus AOTInductorModelContainerRun). +AOTI_API AOTIRuntimeError AOTInductorModelRun( + AOTInductorModelHandle model_handle, + AtenTensorHandle* input_handles, + AtenTensorHandle* output_handles); + +// Replace AOTInductorModel's constant map. Note it doesn't handle concurrency +// so be sure to handle ordering if AOTInductorModelRun is ran concurrently. +AOTI_API AOTIRuntimeError AOTInductorModelUpdateConstantsMap( + AOTInductorModelHandle model_handle, + AOTInductorConstantMapHandle constant_map_handle); + +// Get the size of the constant blob +AOTI_API AOTIRuntimeError AOTInductorModelContainerGetConstantsBlobSize( + AOTInductorModelContainerHandle container_handle, + uint64_t* ret_size); + +// Load weights from a single blob in weight_blob_ptr +AOTI_API AOTIRuntimeError AOTInductorModelUpdateConstantsFromBlob( + AOTInductorModelContainerHandle container_handle, + const uint8_t* weight_blob_ptr); + +// Delete an AOTInductorModel created by AOTInductorModelCreate. +AOTI_API AOTIRuntimeError +AOTInductorModelDelete(AOTInductorModelHandle model_handle); + +AOTI_API AOTIRuntimeError AOTInductorModelGetNumOutputs( + AOTInductorModelHandle model_handle, + size_t* ret_num_outputs); + +AOTI_API AOTIRuntimeError AOTInductorModelContainerGetCallSpec( + AOTInductorModelContainerHandle container_handle, + const char** in_spec, + const char** out_spec); + +} // extern "C" + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/kernel_context_tls.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/kernel_context_tls.h new file mode 100644 index 0000000000000000000000000000000000000000..5aca1631d18490dc28b4ed631701d62968e7dfda --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/kernel_context_tls.h @@ -0,0 +1,92 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include + +namespace torch::aot_inductor { + +struct KernelContext { + std::string kernel_name; + std::string python_stack; + std::string compressed_python_stack; + + KernelContext(std::string name, std::string stack) + : kernel_name(std::move(name)), python_stack(std::move(stack)) { + compressed_python_stack = compress_python_stack(python_stack); + } + + KernelContext(const KernelContext&) = default; + KernelContext& operator=(const KernelContext&) = default; + KernelContext(KernelContext&&) = default; + KernelContext& operator=(KernelContext&&) = default; + + private: + static std::string compress_python_stack(const std::string& stack) { + namespace fs = std::filesystem; + char func[129]; + char path[1025]; + uint32_t line; + int ret; + std::string compressed_stack; + std::stringstream stream{stack}; + std::string str; + std::string fmt = "File \"%1024[^\"]\", line %u, in %128[^\n]\n"; + while (std::getline(stream, str)) { + ret = sscanf(str.c_str(), fmt.c_str(), path, &line, func); + if (ret == 3) { + compressed_stack += func; + compressed_stack += ' '; + compressed_stack += fs::path{path}.filename(); + compressed_stack += ':'; + compressed_stack += std::to_string(line); + compressed_stack += '\n'; + } + } + return compressed_stack; + } +}; + +// Thread-local pointer +extern thread_local KernelContext* tls_kernel_context; + +inline KernelContext* current_kernel_context() { + return tls_kernel_context; +} + +inline void set_kernel_context(KernelContext* ctx) { + tls_kernel_context = ctx; +} + +inline void clear_kernel_context() { + tls_kernel_context = nullptr; +} + +struct KernelContextGuard { + KernelContextGuard(const std::string& name, const std::string& stack) + : owned_context_(name, stack) { + set_kernel_context(&owned_context_); + } + ~KernelContextGuard() { + clear_kernel_context(); + } + + // Delete copy constructor and copy assignment operator + KernelContextGuard(const KernelContextGuard&) = delete; + KernelContextGuard& operator=(const KernelContextGuard&) = delete; + + KernelContextGuard(KernelContextGuard&&) = default; + KernelContextGuard& operator=(KernelContextGuard&&) = delete; + + private: + KernelContext owned_context_; +}; + +} // namespace torch::aot_inductor + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/mini_array_ref.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/mini_array_ref.h new file mode 100644 index 0000000000000000000000000000000000000000..31cdf3063f928702619631d25997c1bd703e54db --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/mini_array_ref.h @@ -0,0 +1,165 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include + +namespace torch::aot_inductor { + +// Can't use c10::ArrayRef because it's not truly header-only and +// pulls in other c10 headers. This is (sadly) copy-pasted and +// adapted. +template +class MiniArrayRef final { + public: + using iterator = T*; + using const_iterator = const T*; + using size_type = size_t; + using value_type = T; + + using reverse_iterator = std::reverse_iterator; + + private: + /// The start of the array, in an external buffer. + T* Data; + + /// The number of elements. + size_type Length; + + public: + /// @name Constructors + /// @{ + + /// Construct an empty MiniArrayRef. + /* implicit */ constexpr MiniArrayRef() : Data(nullptr), Length(0) {} + + /// Construct an MiniArrayRef from a single element. + // TODO Make this explicit + constexpr MiniArrayRef(const T& OneElt) : Data(&OneElt), Length(1) {} + + /// Construct an MiniArrayRef from a pointer and length. + constexpr MiniArrayRef(T* data, size_t length) : Data(data), Length(length) {} + + /// Construct an MiniArrayRef from a range. + constexpr MiniArrayRef(T* begin, T* end) : Data(begin), Length(end - begin) {} + + template < + typename Container, + typename = std::enable_if_t().data())>, + T*>>> + /* implicit */ MiniArrayRef(Container& container) + : Data(container.data()), Length(container.size()) {} + + /// Construct an MiniArrayRef from a std::vector. + // The enable_if stuff here makes sure that this isn't used for + // std::vector, because MiniArrayRef can't work on a std::vector + // bitfield. + template + /* implicit */ MiniArrayRef(const std::vector& Vec) + : Data(Vec.data()), Length(Vec.size()) { + static_assert( + !std::is_same_v, + "MiniArrayRef cannot be constructed from a std::vector bitfield."); + } + + /// Construct an MiniArrayRef from a std::array + template + /* implicit */ constexpr MiniArrayRef(std::array& Arr) + : Data(Arr.data()), Length(N) {} + + /// Construct an MiniArrayRef from a C array. + template + // NOLINTNEXTLINE(*c-array*) + /* implicit */ constexpr MiniArrayRef(T (&Arr)[N]) : Data(Arr), Length(N) {} + + // /// Construct an MiniArrayRef from an empty C array. + /* implicit */ constexpr MiniArrayRef(const volatile void* Arr) + : Data(nullptr), Length(0) {} + + /// Construct an MiniArrayRef from a std::initializer_list. + /* implicit */ constexpr MiniArrayRef(const std::initializer_list& Vec) + : Data( + std::begin(Vec) == std::end(Vec) ? static_cast(nullptr) + : std::begin(Vec)), + Length(Vec.size()) {} + + /// @} + /// @name Simple Operations + /// @{ + + constexpr iterator begin() const { + return Data; + } + constexpr iterator end() const { + return Data + Length; + } + + // These are actually the same as iterator, since MiniArrayRef only + // gives you const iterators. + constexpr const_iterator cbegin() const { + return Data; + } + constexpr const_iterator cend() const { + return Data + Length; + } + + constexpr reverse_iterator rbegin() const { + return reverse_iterator(end()); + } + constexpr reverse_iterator rend() const { + return reverse_iterator(begin()); + } + + /// empty - Check if the array is empty. + constexpr bool empty() const { + return Length == 0; + } + + constexpr T* data() const { + return Data; + } + + /// size - Get the array size. + constexpr size_t size() const { + return Length; + } + + /// equals - Check for element-wise equality. + constexpr bool equals(MiniArrayRef RHS) const { + return Length == RHS.Length && std::equal(begin(), end(), RHS.begin()); + } + + /// @} + /// @name Operator Overloads + /// @{ + constexpr const T& operator[](size_t Index) const { + return Data[Index]; + } + + /// Disallow accidental assignment from a temporary. + /// + /// The declaration here is extra complicated so that "arrayRef = {}" + /// continues to select the move assignment operator. + template + std::enable_if_t, MiniArrayRef>& operator=( + // NOLINTNEXTLINE(cppcoreguidelines-missing-std-forward) + U&& Temporary) = delete; + + /// Disallow accidental assignment from a temporary. + /// + /// The declaration here is extra complicated so that "arrayRef = {}" + /// continues to select the move assignment operator. + template + std::enable_if_t, MiniArrayRef>& operator=( + std::initializer_list) = delete; +}; + +} // namespace torch::aot_inductor + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/model.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/model.h new file mode 100644 index 0000000000000000000000000000000000000000..eca53e62494e348a7c5f75684f650b71c45caa7f --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/model.h @@ -0,0 +1,67 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +// WARNING: Be careful when adding new includes here. This header will be used +// in model.so, and should not refer to any aten/c10 headers except the stable +// C ABI defined in torch/csrc/inductor/aoti_torch/c/shim.h. The same rule +// applies to other files under torch/csrc/inductor/aoti_runtime/. +#include + +namespace torch::aot_inductor { + +class AOTInductorModel : public AOTInductorModelBase { + public: + AOTInductorModel( + std::shared_ptr constants_map, + std::shared_ptr> constants_array, + const std::string& device_str, + std::optional cubin_dir); + + std::unordered_map const_run_impl( + DeviceStreamType stream, + AOTIProxyExecutorHandle proxy_executor, + bool initialization = false); + + void _const_run_impl( + std::vector& output_handles, + DeviceStreamType stream, + AOTIProxyExecutorHandle proxy_executor); + + void run_impl( + AtenTensorHandle* + input_handles, // array of input AtenTensorHandle; handles + // are stolen; the array itself is borrowed + AtenTensorHandle* + output_handles, // array for writing output AtenTensorHandle; handles + // will be stolen by the caller; the array itself is + // borrowed + DeviceStreamType stream, + AOTIProxyExecutorHandle proxy_executor); + + template + Outputs run_impl_minimal_arrayref_interface( + const Inputs& inputs, + DeviceStreamType stream, + AOTIProxyExecutorHandle proxy_executor); + + static std::unique_ptr Create( + std::shared_ptr constants_map, + std::shared_ptr> constants_array, + const std::string& device_str, + std::optional cubin_dir) { + return std::make_unique( + std::move(constants_map), + std::move(constants_array), + device_str, + std::move(cubin_dir)); + } + + private: + std::unique_ptr kernels_; +}; + +} // namespace torch::aot_inductor + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/model_base.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/model_base.h new file mode 100644 index 0000000000000000000000000000000000000000..86870dc944096a3752359c8b80f691af62a16eca --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/model_base.h @@ -0,0 +1,1048 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#ifdef _WIN32 +#include +#include // std::function +#ifdef USE_MMAP_SELF +#include +#include +#include +#include + +#define PROT_READ 0x1 +#define PROT_WRITE 0x2 +#define PROT_EXEC 0x4 + +#define MAP_SHARED 0x01 +#define MAP_PRIVATE 0x02 +#define MAP_FAILED ((void*)-1) + +#define SEEK_SET 0 +#define SEEK_CUR 1 +#define SEEK_END 2 + +struct Dl_info { + char dli_fname[MAX_PATH]; /**< Filename of defining object */ + void* dli_fbase; /**< Load address of that object */ + const char* dli_sname; /**< Name of nearest lower symbol */ + void* dli_saddr; /**< Exact value of nearest symbol */ +}; +typedef struct Dl_info Dl_info; + +int dladdr(const void* addr, Dl_info* info) { + // only returns filename, FWIW. + CHAR tpath[MAX_PATH]; + MEMORY_BASIC_INFORMATION mbi; + char* path; + char* tmp; + size_t length; + int ret = 0; + + if (!info) + return 0; + + HMODULE hModule; + if (!GetModuleHandleExA( + GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | + GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, + (LPCSTR)addr, + &hModule) || + hModule == NULL) + return 0; + + ret = GetModuleFileNameA(hModule, (LPSTR)&tpath, MAX_PATH); + if (!ret) + return 0; + + path = tpath; + + length = strlen(path); + if (length >= MAX_PATH) { + length = MAX_PATH - 1; + path[MAX_PATH - 1] = '\0'; + } + + tmp = path; + while (*tmp) { + if (*tmp == '\\') + *tmp = '/'; + tmp++; + } + + memcpy(info->dli_fname, path, length + 1); + info->dli_fbase = hModule; + info->dli_sname = NULL; + info->dli_saddr = NULL; + return 1; +} + +static DWORD get_creation_disposition(int flags) { + if (flags & O_CREAT) { + if (flags & O_EXCL) + return CREATE_NEW; + if (flags & O_TRUNC) + return CREATE_ALWAYS; + return OPEN_ALWAYS; + } + if (flags & O_TRUNC) + return TRUNCATE_EXISTING; + return OPEN_EXISTING; +} + +#define O_ACCMODE 03 +#define O_RDONLY 00 +#define O_WRONLY 01 +#define O_RDWR 02 + +static DWORD get_access_mode(int flags) { + switch (flags & O_ACCMODE) { + case O_RDONLY: + return GENERIC_READ; + case O_WRONLY: + return GENERIC_WRITE; + case O_RDWR: + return GENERIC_READ | GENERIC_WRITE; + default: + return GENERIC_READ; + } +} +#ifndef O_DSYNC +#define O_DSYNC 00010000 /* used to be O_SYNC, see below */ +#endif + +#ifndef O_SYNC +#define __O_SYNC 04000000 +#define O_SYNC (__O_SYNC | O_DSYNC) +#endif + +int open(char* pathname, int flags) { + DWORD dwDesiredAccess = get_access_mode(flags); + DWORD dwCreationDisposition = get_creation_disposition(flags); + DWORD dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE; + DWORD dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL; + + if (flags & O_SYNC) { + dwFlagsAndAttributes |= FILE_FLAG_WRITE_THROUGH; + } + + if (flags & O_SEQUENTIAL) { + dwFlagsAndAttributes |= FILE_FLAG_SEQUENTIAL_SCAN; + } + + if (flags & O_RANDOM) { + dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS; + } + + HANDLE hFile = CreateFileA( + pathname, + dwDesiredAccess, + dwShareMode, + NULL, + dwCreationDisposition, + dwFlagsAndAttributes, + NULL); + + if (hFile == INVALID_HANDLE_VALUE) { + switch (GetLastError()) { + case ERROR_FILE_NOT_FOUND: + errno = ENOENT; + break; + case ERROR_PATH_NOT_FOUND: + errno = ENOTDIR; + break; + case ERROR_ACCESS_DENIED: + errno = EACCES; + break; + case ERROR_FILE_EXISTS: + errno = EEXIST; + break; + case ERROR_TOO_MANY_OPEN_FILES: + errno = EMFILE; + break; + default: + errno = EIO; + } + return -1; + } + + int fd = _open_osfhandle((intptr_t)hFile, flags); + if (fd == -1) { + CloseHandle(hFile); + errno = EMFILE; + return -1; + } + + if (flags & O_APPEND) { + lseek(fd, 0, SEEK_END); + } + + return fd; +} + +int close(int fd) { + return _close(fd); +} + +void* mmap( + void* addr, + size_t length, + int prot, + int flags, + int fd, + off_t offset) { + HANDLE hFile = (HANDLE)_get_osfhandle(fd); + if (hFile == INVALID_HANDLE_VALUE) { + errno = EBADF; + return MAP_FAILED; + } + + DWORD flProtect; + if (prot & PROT_WRITE) { + flProtect = PAGE_READWRITE; + } else if (prot & PROT_READ) { + flProtect = PAGE_READONLY; + } else { + flProtect = PAGE_NOACCESS; + } + + flProtect = PAGE_READONLY; + + DWORD dwDesiredAccess = 0; + if (prot & PROT_READ) + dwDesiredAccess |= FILE_MAP_READ; + if (prot & PROT_WRITE) + dwDesiredAccess |= FILE_MAP_WRITE; + if (prot & PROT_EXEC) + dwDesiredAccess |= FILE_MAP_EXECUTE; + + dwDesiredAccess = FILE_MAP_READ; + + SYSTEM_INFO SysInfo; + GetSystemInfo(&SysInfo); + DWORD dwSysGran = SysInfo.dwAllocationGranularity; + + DWORD dwFileMapStart = (offset / dwSysGran) * dwSysGran; + DWORD dwMapViewSize = (offset % dwSysGran) + length; + DWORD dwFileMapSize = offset + length; + int iViewDelta = offset - dwFileMapStart; + + HANDLE hMapping = + CreateFileMapping(hFile, NULL, flProtect, 0, dwFileMapSize, NULL); + + if (!hMapping) { + DWORD dwErrCode = GetLastError(); + errno = EACCES; + return MAP_FAILED; + } + + void* lpMapAddress = MapViewOfFileEx( + hMapping, dwDesiredAccess, 0, dwFileMapStart, dwMapViewSize, addr); + if (!lpMapAddress) { + DWORD dwErrCode = GetLastError(); + errno = EINVAL; + } + + void* pData = (char*)lpMapAddress + iViewDelta; + + CloseHandle(hMapping); + + if (!lpMapAddress) { + return MAP_FAILED; + } + + return pData; +} + +int munmap(void* addr, size_t length) { + if (!UnmapViewOfFile(addr)) { + errno = EINVAL; + return -1; + } + return 0; +} +#endif // USE_MMAP_SELF +#else // !_WIN32 +#include +#include +#include +#endif // _WIN32 + +#include +#include +#include +#include +#include +#include + +// WARNING: Be careful when adding new includes here. This header will be used +// in model.so, and should not refer to any aten/c10 headers except the stable +// C ABI defined in torch/csrc/inductor/aoti_torch/c/shim.h. The same rule +// applies to other files under torch/csrc/inductor/aoti_runtime/. +#include +#ifdef USE_MPS +#include +#endif // USE_MPS +#ifdef USE_XPU +#include +#else +#include +#endif // USE_XPU +#include + +#define AOTI_RUNTIME_CHECK(EXPR, MSG) \ + do { \ + bool ok = EXPR; \ + if (!ok) { \ + throw std::runtime_error(MSG); \ + } \ + } while (0) + +// At codegen time, we write out a binary file called constants.bin. +// We then turn the raw binary to an object file that exposes this +// symbol and link it into the final .so. +// For information on the binary format, see `man objcopy`, under +// the "binary-architecture" flag: +// https://man7.org/linux/man-pages/man1/objcopy.1.html +// todo: use #embed in C++ 23 once available +// The constants are NOT readonly because they may be mutated. +// NOLINTNEXTLINE(*array*) +extern uint8_t _binary_constants_bin_start[]; +// NOLINTNEXTLINE(*array*) +extern uint8_t _binary_constants_bin_end[]; + +#if defined(USE_CUDA) || defined(USE_XPU) +// Compute required blob size with 64-alignment if on GPU. +#define AOTI_CONST_ALIGNMENT 64 +#else +// Use 64-alignment (use something >=64)for better performance on CPU. +#define AOTI_CONST_ALIGNMENT 64 +#endif + +namespace { + +using RAIIDataPtr = std::unique_ptr>; + +#ifdef USE_CUDA + +// NOLINTNEXTLINE(clang-diagnostic-unneeded-internal-declaration) +RAIIDataPtr RAII_gpuMalloc(size_t num_bytes) { +#ifdef AOT_INDUCTOR_USE_CACHING_ALLOCATOR + // Use caching allocator for allocating GPU memory + void* data_ptr = nullptr; + AOTI_TORCH_ERROR_CODE_CHECK( + aoti_torch_cuda_caching_allocator_raw_alloc(num_bytes, &data_ptr)); + auto deleter = [](void* ptr) { + AOTI_TORCH_ERROR_CODE_CHECK( + aoti_torch_cuda_caching_allocator_raw_delete(ptr)); + }; + return RAIIDataPtr(data_ptr, deleter); +#else + // Use cudaMalloc directly for allocating GPU memory + void* data_ptr = nullptr; + AOTI_RUNTIME_CUDA_CHECK(cudaMalloc((void**)&data_ptr, num_bytes)); + auto deleter = [](void* ptr) { AOTI_RUNTIME_CUDA_CHECK(cudaFree(ptr)); }; + return RAIIDataPtr(data_ptr, deleter); +#endif +} + +#elif defined(USE_XPU) + +RAIIDataPtr RAII_gpuMalloc(size_t num_bytes) { + sycl::queue* queue_ptr = nullptr; + aoti_torch_get_current_sycl_queue((void**)&queue_ptr); + void* data_ptr = sycl::malloc_device(num_bytes, *queue_ptr); + auto deleter = [queue_ptr](void* ptr) { sycl::free(ptr, *queue_ptr); }; + return RAIIDataPtr(data_ptr, deleter); +} + +#elif defined(USE_MPS) + +RAIIDataPtr RAII_gpuMalloc(size_t num_bytes) { + void* data_ptr = nullptr; + aoti_torch_mps_malloc(&data_ptr, num_bytes); + auto deleter = [](void* ptr) { aoti_torch_mps_free(ptr); }; + return RAIIDataPtr(data_ptr, deleter); +} + +#else + +RAIIDataPtr RAII_cpuMalloc(size_t num_bytes) { + void* data_ptr = std::malloc(num_bytes); + if (!data_ptr) { + throw std::bad_alloc(); + } + auto deleter = [](void* ptr) { std::free(ptr); }; + return RAIIDataPtr(data_ptr, deleter); +} + +#endif // USE_CUDA + +} // anonymous namespace + +namespace torch::aot_inductor { + +using ConstantMap = + std::unordered_map; + +// valid device strs are: cpu, cuda, cuda:0, cuda:1, ... +// Update the list here if more devices are supported in the future +inline void parse_device_str( + const std::string& device_str, + int32_t& device_type, + int32_t& device_idx) { + std::regex re("(cpu|cuda|xpu|mps)(:([0-9]+))?"); + std::smatch sm; + bool matched = std::regex_match(device_str, sm, re); + AOTI_RUNTIME_CHECK(matched, "Invalid device: " + device_str); + + if (sm[1].str() == "cpu") { + device_type = aoti_torch_device_type_cpu(); + } else if (sm[1].str() == "cuda") { + device_type = aoti_torch_device_type_cuda(); +#ifdef USE_XPU + } else if (sm[1].str() == "xpu") { + device_type = aoti_torch_device_type_xpu(); +#endif +#ifdef USE_MPS + } else if (sm[1].str() == "mps") { + device_type = aoti_torch_device_type_mps(); +#endif + } else { + AOTI_RUNTIME_CHECK(false, "Invalid device: " + device_str); + } + + if (sm[3].matched) { + device_idx = stoi(sm[3].str()); + } else { + device_idx = -1; + } +} + +// Defines the base class for AOTInductorModel, which is generated by the +// AOTInductor cpp codegen. Since we do not need dynamic dispatch, we rely +// on curiously recurring template pattern (CRTP) to save some runtime +// v-table overhead. The generated AOTInductorModel is specialized with +// methods such as run_impl. +template +class AOTInductorModelBase { + public: + AOTInductorModelBase( + size_t num_inputs, + size_t num_outputs, + size_t num_constants, + const std::string& device_str, + std::optional cubin_dir, + bool include_weights = true) + : inputs_info_(num_inputs), + outputs_info_(num_outputs), + constants_info_(num_constants), + cubin_dir_(std::move(cubin_dir)), + include_weights(include_weights) { + parse_device_str(device_str, device_type_, device_idx_); + +#ifdef USE_CUDA + if (device_idx_ == -1) { + AOTI_RUNTIME_CUDA_CHECK(cudaGetDevice(&device_idx_)); + } else { + // If device_idx_ is passed in, we need to set the current device to it + AOTI_RUNTIME_CUDA_CHECK(cudaSetDevice(device_idx_)); + } +#endif // USE_CUDA +#ifdef USE_XPU + if (device_idx_ == -1) { + aoti_torch_get_current_xpu_device(&device_idx_); + } else { + aoti_torch_set_current_xpu_device(device_idx_); + } +#endif // USE_XPU +#ifdef USE_MPS + if (device_idx_ == -1) { + device_idx_ = 0; + } +#endif // USE_MPS + } + + // NOLINTNEXTLINE(modernize-use-equals-default) + ~AOTInductorModelBase() { +#ifdef USE_CUDA + if (run_finished_) { + auto code = cudaEventDestroy(*run_finished_); + if (code != cudaSuccess) { + std::cerr << "Failed to destroy CUDA event in AOTInductor model: " + << cudaGetErrorString(code) << '\n'; + } + } +#endif // USE_CUDA +#ifdef USE_XPU + if (run_finished_) { + (*run_finished_)->wait_and_throw(); + delete *run_finished_; + } +#endif // USE_XPU + } + + AOTInductorModelBase(AOTInductorModelBase&&) = delete; + AOTInductorModelBase& operator=(AOTInductorModelBase&&) = delete; + AOTInductorModelBase(const AOTInductorModelBase&) = delete; + AOTInductorModelBase& operator=(const AOTInductorModelBase&) = delete; + + void run( + AtenTensorHandle* + input_handles, // array of input AtenTensorHandle; handles + // are stolen; the array itself is borrowed + AtenTensorHandle* + output_handles, // array for writing output AtenTensorHandle; handles + // will be stolen by the caller; the array itself is + // borrowed + DeviceStreamType stream, + AOTIProxyExecutorHandle proxy_executor) { +#ifdef USE_CUDA + if (!run_finished_) { + cudaEvent_t run_finished = nullptr; + AOTI_RUNTIME_CUDA_CHECK(cudaEventCreate(&run_finished)); + run_finished_.emplace(run_finished); + } +#elif defined(USE_XPU) + if (run_finished_) { + (*run_finished_)->wait_and_throw(); + delete *run_finished_; + run_finished_.reset(); + } +#else // !USE_CUDA && !USE_XPU + run_finished_ = false; +#endif + + auto* model = static_cast(this); + model->run_impl(input_handles, output_handles, stream, proxy_executor); + +#ifdef USE_CUDA + AOTI_RUNTIME_CUDA_CHECK(cudaEventRecord(*run_finished_, stream)); +#elif defined(USE_XPU) + run_finished_ = std::make_optional(new sycl::event( + static_cast(stream)->ext_oneapi_submit_barrier())); +#else // !USE_CUDA && !USE_XPU + run_finished_ = true; +#endif // USE_CUDA + } + + // Non-thread-aware variant of run(). Obviously unsafe to use in a threaded + // environment :) + void run_single_threaded( + AtenTensorHandle* + input_handles, // array of input AtenTensorHandle; handles + // are stolen; the array itself is borrowed + AtenTensorHandle* + output_handles, // array for writing output AtenTensorHandle; handles + // will be stolen by the caller; the array itself is + // borrowed + DeviceStreamType stream, + AOTIProxyExecutorHandle proxy_executor) { + // don't bother with any of the run_finished stuff; this is unsafe to call + // in a threaded context + auto* model = static_cast(this); + model->run_impl(input_handles, output_handles, stream, proxy_executor); + } + + std::unordered_map run_const_fold( + DeviceStreamType stream, + AOTIProxyExecutorHandle proxy_executor, + bool initialization = false) { +#ifdef USE_CUDA + if (!run_finished_) { + cudaEvent_t run_finished = nullptr; + AOTI_RUNTIME_CUDA_CHECK(cudaEventCreate(&run_finished)); + run_finished_.emplace(run_finished); + } +#elif defined(USE_XPU) + if (run_finished_) { + (*run_finished_)->wait_and_throw(); + delete *run_finished_; + run_finished_.reset(); + } +#else // !USE_CUDA && !USE_XPU + run_finished_ = false; +#endif + + auto* model = static_cast(this); + auto folded_constants = + model->const_run_impl(stream, proxy_executor, initialization); + +#ifdef USE_CUDA + AOTI_RUNTIME_CUDA_CHECK(cudaEventRecord(*run_finished_, stream)); +#elif defined(USE_XPU) + // sycl::queue* queue_ptr = nullptr; + // aoti_torch_get_current_sycl_queue((void**)&queue_ptr); + run_finished_ = std::make_optional(new sycl::event( + static_cast(stream)->ext_oneapi_submit_barrier())); + +#else // !USE_CUDA && !USE_XPU + run_finished_ = true; +#endif // USE_CUDA + + return folded_constants; + } + + void update_constants_from_blob(const uint8_t* weight_blob_ptr) { +#if defined(USE_MMAP_EXTERNAL) + user_managed_mmap = const_cast(weight_blob_ptr); + load_constants(true); +#endif + } + + void load_constants(bool force = false) { + size_t num_constants = this->num_constants(); + size_t num_folded_constants = this->num_folded_constants(); + constants_map_->reserve(num_constants); + + std::vector constants_internal_offset( + num_constants - num_folded_constants); + size_t blob_size = 0; + compute_constant_blob(blob_size, constants_internal_offset); + if (!force && !include_weights) { + return; + } +#if defined(USE_CUDA) || defined(USE_XPU) || defined(USE_MPS) + constant_blob_ = RAII_gpuMalloc(blob_size); +#else + constant_blob_ = RAII_cpuMalloc(blob_size); +#endif + + size_t bytes_read = 0; + size_t non_folded_idx = 0; // Separate index for non-folded constants + for (size_t i = 0; i < num_constants; i++) { + bool from_folded = this->constant_from_folded(i); + if (from_folded) { + continue; + } + std::string name = this->constant_name(i); + size_t data_size = this->constant_data_size(i); + uint8_t* internal_ptr = (data_size != 0) + ? constant_ptr( + constants_internal_offset[non_folded_idx], + bytes_read, + data_size, + /* skip_copy = */ false) + : nullptr; + bytes_read += data_size; + non_folded_idx++; // Increment the non-folded index + + // Create at::Tensor from copied memory. + auto dtype = this->constant_dtype(i); + auto ndim = this->constant_ndim(i); + auto size = this->constant_shape(i); + auto stride = this->constant_stride(i); +#ifdef USE_MPS + auto offset = this->constant_offset(i) + + (constants_internal_offset[i] / aoti_torch_dtype_element_size(dtype)); +#else + auto offset = this->constant_offset(i); +#endif + auto layout = this->constant_layout(i); + auto opaque_metadata_ptr = this->opaque_metadata(i); + auto opaque_metadata_size = this->opaque_metadata_size(i); + + AtenTensorHandle tensor_handle = nullptr; + AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_create_tensor_from_blob_v2( + internal_ptr, + ndim, + size, + stride, + offset, + dtype, + device_type_, + device_idx_, + &tensor_handle, + layout, + opaque_metadata_ptr, + opaque_metadata_size)); + constants_map_->emplace(std::move(name), tensor_handle); + } + if (constants_map_) { + this->update_constants_array_from_map(); + } + } + + RAIIDataPtr&& release_constant_blob() { + return std::move(constant_blob_); + } + + std::shared_ptr> get_constants_array() { + return constants_; + } + + int32_t get_device_type() const { + return device_type_; + } + + int32_t get_device_idx() const { + return device_idx_; + } + + uint8_t* constant_ptr( + size_t constant_offset, + size_t bytes_read, + size_t data_size, + bool skip_copy) { + auto* constants_ptr = static_cast(constant_blob_.get()); + uint8_t* internal_ptr = constants_ptr + constant_offset; + // TODO: Handle shared storage case. + if (!skip_copy) { +#ifdef USE_XPU + sycl::queue* queue_ptr = nullptr; + aoti_torch_get_current_sycl_queue((void**)&queue_ptr); + queue_ptr + ->memcpy(internal_ptr, _get_constants_start() + bytes_read, data_size) + .wait(); +#elif USE_CUDA + AOTI_RUNTIME_CUDA_CHECK(cudaMemcpy( + internal_ptr, + _get_constants_start() + bytes_read, + data_size, + cudaMemcpyHostToDevice)); +#elif USE_MPS + aoti_torch_mps_memcpy( + constants_ptr, + constant_offset, + bytes_read, + data_size, + _get_constants_start()); + return constants_ptr; +#else + memcpy(internal_ptr, _get_constants_start() + bytes_read, data_size); +#endif + } + return internal_ptr; + } + + void compute_constant_blob( + size_t& blob_size, + std::vector& constants_internal_offset) { + size_t num_constants = this->num_constants(); + blob_size = 0; + size_t curr_idx = 0; + for (size_t i = 0; i < num_constants; i++) { + if (this->constant_from_folded(i)) { + continue; + } + size_t data_size = this->constant_data_size(i); + if (data_size % AOTI_CONST_ALIGNMENT) { + data_size = AOTI_CONST_ALIGNMENT + + (data_size / AOTI_CONST_ALIGNMENT) * AOTI_CONST_ALIGNMENT; + } + constants_internal_offset[curr_idx++] = blob_size; + blob_size += data_size; + } + } + + size_t num_inputs() const { + return inputs_info_.size(); + } + + size_t num_outputs() const { + return outputs_info_.size(); + } + + size_t num_constants() const { + return constants_info_.size(); + } + + size_t num_folded_constants() const { + size_t total_consts = this->num_constants(); + size_t folded_consts = 0; + for (size_t i = 0; i < total_consts; i++) { + if (this->constant_from_folded(i)) { + folded_consts++; + } + } + return folded_consts; + } + + const char* input_name(int64_t idx) const { + return inputs_info_.at(idx).name; + } + + const char* output_name(int64_t idx) const { + return outputs_info_.at(idx).name; + } + + const char* constant_name(int64_t idx) const { + return constants_info_.at(idx).name; + } + + size_t constant_ndim(int64_t idx) { + return constants_info_.at(idx).shape.size(); + } + + const int64_t* constant_shape(int64_t idx) const { + return constants_info_.at(idx).shape.data(); + } + + const int64_t* constant_stride(int64_t idx) const { + return constants_info_.at(idx).stride.data(); + } + + int32_t constant_dtype(int64_t idx) const { + return constants_info_.at(idx).dtype; + } + + int32_t constant_layout(int64_t idx) const { + return constants_info_.at(idx).layout; + } + + size_t constant_offset(int64_t idx) const { + return constants_info_.at(idx).offset; + } + + size_t constant_data_size(int64_t idx) const { + return constants_info_.at(idx).data_size; + } + + const char* constant_original_fqn(int64_t idx) const { + return constants_info_.at(idx).original_fqn; + } + + const uint8_t* opaque_metadata(int64_t idx) const { + return constants_info_.at(idx).opaque_metadata.data(); + } + + size_t opaque_metadata_size(int64_t idx) { + return constants_info_.at(idx).opaque_metadata.size(); + } + + bool constant_from_folded(int64_t idx) const { + return constants_info_.at(idx).from_folded; + } + + int32_t constant_type(int64_t idx) const { + return constants_info_.at(idx).type; + } + + const char* get_in_spec() const { + return in_spec_.c_str(); + } + + const char* get_out_spec() const { + return out_spec_.c_str(); + } + + uint64_t constant_blob_size() const { +#if defined(USE_MMAP_SELF) || defined(USE_MMAP_EXTERNAL) + const uint64_t weights_size = + reinterpret_cast(_binary_constants_bin_start)[0]; + return weights_size; +#else + throw std::runtime_error{ + "constant blob size is only available for mmap'd weights"}; +#endif + } + + void update_constants_array_from_map() { + if (!constants_map_) { + throw std::runtime_error{ + "constants_map_ was not ready when constants_ is trying to be constructed from it!"}; + } + if (!constants_) { + constants_ = + std::make_shared>(constants_info_.size()); + } else { + constants_->resize(constants_info_.size()); + } + int idx = 0; + for (const auto& info : constants_info_) { + const auto it = constants_map_->find(info.name); + if (it != constants_map_->end()) { + constants_->at(idx) = ConstantHandle(it->second); + } + idx++; + } + } + + void update_constants_map( + std::shared_ptr constants_map, + bool remap_constants_array = true) { + constants_map_ = std::move(constants_map); + if (remap_constants_array) { + update_constants_array_from_map(); + } + } + + // This function allows us to update the constants_ that is used to look up + // the corresponding constant tensor during runtime. + void update_constants_array( + std::shared_ptr> constants_array) { + constants_ = std::move(constants_array); + } + + /// Returns true if the model is complete. + bool is_finished() { +#ifdef USE_CUDA + if (!run_finished_) { + throw std::runtime_error{"Model CUDA event was not initialized"}; + } + + auto event_status = cudaEventQuery(*run_finished_); + if (event_status == cudaSuccess) { + return true; + } else if (event_status == cudaErrorNotReady) { + return false; + } + + throw std::runtime_error( + std::string("The model did not finish successfully. Error: ") + + cudaGetErrorString(cudaGetLastError())); +#elif defined(USE_XPU) + if (!run_finished_) { + throw std::runtime_error{"Model XPU event was not initialized"}; + } + using namespace sycl::info; + return (*run_finished_)->get_info() == + event_command_status::complete; + +#else // !USE_CUDA && !USE_XPU + return run_finished_; +#endif // USE_CUDA + } + + /// Synchronizes completion event. + void wait_for_completion() { +#ifdef USE_CUDA + if (!run_finished_) { + throw std::runtime_error{"Model event was not initialized"}; + } + + AOTI_RUNTIME_CUDA_CHECK(cudaEventSynchronize(*run_finished_)); +#endif // USE_CUDA +#ifdef USE_XPU + if (!run_finished_) { + throw std::runtime_error{"Model event was not initialized"}; + } + (*run_finished_)->wait_and_throw(); +#endif + } + + protected: + uint8_t* _get_constants_start() { +#if defined(USE_MMAP_EXTERNAL) + if (!user_managed_mmap) { + throw std::runtime_error{ + "Constants are not mmap'd. Use AOTInductorModelUpdateConstantsBlob to initialize the constants first."}; + } + // Mapped memory for weights + return user_managed_mmap; +#endif + +#ifndef USE_MMAP_SELF + // NOLINTNEXTLINE(*const-cast*) + return const_cast(_binary_constants_bin_start); +#else + if (self_mmap) { + return self_mmap; + } + Dl_info dl_info; + // get pointer to constant which are appended to the binary + AOTI_RUNTIME_CHECK( + dladdr(__func__, &dl_info), "Can't find shared library name"); + int fd = open(dl_info.dli_fname, O_RDONLY); + AOTI_RUNTIME_CHECK(fd >= 0, "Shared library file cannot be opened"); + auto fsize = lseek(fd, 0, SEEK_END); + auto weights_size = + reinterpret_cast(_binary_constants_bin_start)[0]; + auto magic_number = + reinterpret_cast(_binary_constants_bin_start)[1]; + auto weights_offset = fsize - weights_size; + AOTI_RUNTIME_CHECK( + (weights_offset & 0x3fff) == 0, + "weights_offset must be aligned to 16K boundary"); + auto ptr = mmap( + NULL, + weights_size, + PROT_READ | PROT_WRITE, + MAP_PRIVATE, + fd, + weights_offset); + close(fd); + AOTI_RUNTIME_CHECK(ptr != MAP_FAILED, "mmap() failed"); + self_mmap = static_cast(ptr); + AOTI_RUNTIME_CHECK( + reinterpret_cast( + self_mmap + weights_size - sizeof(uint64_t))[0] == magic_number, + "Weights data seems corrupt"); + return self_mmap; +#endif + } + + struct ParamInfo { + const char* name = nullptr; + }; + + struct ConstInfo { + const char* name = nullptr; + std::vector shape; + std::vector stride; + int32_t dtype{}; + int64_t offset{}; + size_t data_size{}; + int32_t layout{}; + std::vector opaque_metadata; + int64_t opaque_metadata_size{}; + const char* original_fqn = nullptr; + bool from_folded{}; + int32_t type{}; + }; + + std::vector inputs_info_; + std::vector outputs_info_; + std::vector constants_info_; + std::string in_spec_; + std::string out_spec_; + + std::shared_ptr constants_map_; + std::shared_ptr> constants_; + + // Holds the blob storage for constants' at::Tensor. + RAIIDataPtr constant_blob_; + +#if defined(USE_MMAP_SELF) + // Mapped memory for weights + uint8_t* self_mmap = NULL; +#endif + +#if defined(USE_MMAP_EXTERNAL) + // Mapped memory for weights + uint8_t* user_managed_mmap = NULL; +#endif + + // A directory with CUDA binary files, e.g. compiled kernels, etc. + const std::optional cubin_dir_; + + // This is the flag that implies whether the weight is included in the model. + // If True, we would prepare the weight when loading the model, otherwise the + // model will be loaded without weights, and need to be provided by the user. + bool include_weights; + + // Record if the model finishes an inference run so that its owning + // AOTModelContainer can reuse this instance. +#ifdef USE_CUDA + std::optional run_finished_; +#elif defined(USE_XPU) + std::optional run_finished_; +#else // !USE_CUDA + bool run_finished_{}; +#endif + + // Generated model uses this device index to create CUDA guards. + int32_t device_type_{}; + int32_t device_idx_{}; +}; + +// Codegen-ed classes can derive from this to keep pointers to loaded kernels. +class AOTInductorModelKernelsBase { + public: + virtual ~AOTInductorModelKernelsBase() = default; +}; + +} // namespace torch::aot_inductor + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/model_container.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/model_container.h new file mode 100644 index 0000000000000000000000000000000000000000..7eed530d84d1391f7d4e9f5b47304d15d7e0ed7f --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/model_container.h @@ -0,0 +1,808 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include + +// WARNING: Be careful when adding new includes here. This header will be used +// in model.so, and should not refer to any aten/c10 headers except the stable +// C ABI defined in torch/csrc/inductor/aoti_torch/c/shim.h. The same rule +// applies to other files under torch/csrc/inductor/aoti_runtime/. +#include + +namespace torch::aot_inductor { +// The state transition is done by: +// (1) NONE state: The default state when created. This state should only exist +// when model_container is created and no constants are being loaded or updated. +// (2) INITIALIZED state: This state get set whenever we load the constants into +// the buffer. This could be done by load_constants or update_constants_buffer. +// (3) FOLDED state: This state should transition from INITIALIZED after +// const_fold is being invoked. +enum class ConstantState : uint8_t { NONE, INITIALIZED, FOLDED, UNKNOWN }; + +inline std::string toStringConstantState(ConstantState state) { + switch (state) { + case ConstantState::NONE: + return "ConstantState::NONE"; + case ConstantState::INITIALIZED: + return "ConstantState::INITIALIZED"; + case ConstantState::FOLDED: + return "ConstantState::FOLDED"; + case ConstantState::UNKNOWN: + return "ConstantState::UNKNOWN"; + default: + return "Unknown enum class state for ConstantState"; + } +} + +class AOTInductorModelContainer { + public: + AOTInductorModelContainer( + size_t num_models, + const std::string& device_str, + const std::optional& cubin_dir = std::nullopt) { + constants_map_ = std::make_shared(); + constants_array_ = std::make_shared>(); + + models_.reserve(num_models); + available_models_.reserve(num_models); + for (size_t i = 0; i < num_models; ++i) { + models_.push_back(AOTInductorModel::Create( + constants_map_, constants_array_, device_str, cubin_dir)); + available_models_.push_back(models_.back().get()); + } + + // Note that the all following fields (input_names_, output_names, + // etc) can be filled in by the AOT + // codegen. However, we choose to query such information from + // the owned AOTInductorModel for a couple of reasons: + // * simplify the codegen templates + // * reduce information fragmentation and duplication + // * the initialization process below is done only once when the container + // is constructed, so it would have little performance impact + auto* model = available_models_[0]; + size_t num_inputs = model->num_inputs(); + input_names_.reserve(num_inputs); + for (size_t i = 0; i < num_inputs; i++) { + input_names_.emplace_back(model->input_name(static_cast(i))); + } + + size_t num_outputs = model->num_outputs(); + output_names_.reserve(num_outputs); + for (size_t i = 0; i < num_outputs; i++) { + output_names_.emplace_back(model->output_name(static_cast(i))); + } + model->load_constants(); + constant_blob_ = model->release_constant_blob(); + constants_internal_offset_.resize( + model->num_constants() - model->num_folded_constants()); + model->compute_constant_blob(blob_size_, constants_internal_offset_); + constant_folded_ = ConstantState::INITIALIZED; + + for (auto& model : models_) { + model->update_constants_map(constants_map_); + } + + in_spec_ = model->get_in_spec(); + out_spec_ = model->get_out_spec(); + } + + void run( + AtenTensorHandle* + input_handles, // array of input AtenTensorHandle; handles + // are stolen; the array itself is borrowed + AtenTensorHandle* + output_handles, // array for writing output AtenTensorHandle; handles + // will be stolen by the caller; the array itself is + // borrowed + DeviceStreamType stream, + AOTIProxyExecutorHandle proxy_executor) { + std::shared_lock model_lk(model_exec_mutex_); + auto* model = get_available_model(); + + ConstantState& const_folded = + use_secondary_ ? constant_folded_secondary_ : constant_folded_; + if (const_folded == ConstantState::INITIALIZED) { + // At this point, constant is not ready yet. We need to call constant + // folding before we execute the model. We obtain a unique lock at this + // point to make sure constant is ready for all. + model_lk.unlock(); + std::unique_lock constants_folding_lk(model_exec_mutex_); + // Double locking to make sure constant folding is only ran once. + if (const_folded == ConstantState::INITIALIZED) { + auto folded_const_map = model->run_const_fold( + stream, proxy_executor, /* initialization = */ true); + update_constant_buffer( + std::move(folded_const_map), + /* use_inactive = */ false, + /* validate_full_update = */ false); + const_folded = ConstantState::FOLDED; + } + constants_folding_lk.unlock(); + model_lk.lock(); + } else if (const_folded != ConstantState::FOLDED) { + throw std::runtime_error( + "Unknown constant state: " + toStringConstantState(constant_folded_)); + } + + try { + model->run(input_handles, output_handles, stream, proxy_executor); + } catch (...) { + std::lock_guard lk(models_mutex_); + available_models_.push_back(model); + throw; + } + + { + std::lock_guard lk(models_mutex_); + pending_models_.push_back(model); + } + pending_models_available_.notify_one(); + } + + // Non-thread-aware variant of run(). Obviously unsafe to use in a threaded + // environment :) + void run_single_threaded( + AtenTensorHandle* + input_handles, // array of input AtenTensorHandle; handles + // are stolen; the array itself is borrowed + AtenTensorHandle* + output_handles, // array for writing output AtenTensorHandle; handles + // will be stolen by the caller; the array itself is + // borrowed + DeviceStreamType stream, + AOTIProxyExecutorHandle proxy_executor) { + auto* model = available_models_[0]; + + ConstantState& const_folded = + use_secondary_ ? constant_folded_secondary_ : constant_folded_; + if (const_folded == ConstantState::INITIALIZED) { + auto folded_const_map = model->run_const_fold( + stream, proxy_executor, /* initialization = */ true); + update_constant_buffer( + std::move(folded_const_map), + /* use_inactive = */ false, + /* validate_full_update = */ false); + const_folded = ConstantState::FOLDED; + } else if (constant_folded_ != ConstantState::FOLDED) { + throw std::runtime_error( + "Unknown constant state: " + toStringConstantState(constant_folded_)); + } + + model->run_single_threaded( + input_handles, output_handles, stream, proxy_executor); + } + + const std::unordered_map extract_constants_map( + bool use_inactive) const { + size_t n_consts = this->num_constants(); + std::unordered_map ret; + ret.reserve(n_consts); + + std::shared_ptr extract_map = constants_map_; + // Essentially a XOR + if (use_inactive != use_secondary_) { + extract_map = constants_map_secondary_; + } + for (size_t idx = 0; idx < n_consts; idx++) { + if (this->constant_from_folded(idx)) { + continue; + } + + auto it = extract_map->find(this->constant_name(idx)); + if (it != extract_map->end()) { + ret.emplace(this->constant_original_fqn(idx), it->second); + continue; + } + } + + return ret; + } + + size_t num_constants() const { + if (this->num_models() == 0) { + throw std::runtime_error("No available models in container!"); + } + return models_[0]->num_constants(); + } + + // retrieve the constant name of constants_info_[idx] + const char* constant_name(size_t idx) const { + if (this->num_models() == 0) { + throw std::runtime_error("No available models in container!"); + } + return models_[0]->constant_name(static_cast(idx)); + } + + // retrieve original FQN of constants_info_[idx] + const char* constant_original_fqn(size_t idx) const { + if (this->num_models() == 0) { + throw std::runtime_error("No available models in container!"); + } + return models_[0]->constant_original_fqn(static_cast(idx)); + } + + // retrieve whether constant is from folded of constants_info_[idx] + bool constant_from_folded(size_t idx) const { + if (this->num_models() == 0) { + throw std::runtime_error("No available models in container!"); + } + return models_[0]->constant_from_folded(static_cast(idx)); + } + + size_t constant_data_size(size_t idx) const { + if (this->num_models() == 0) { + throw std::runtime_error("No available models in container!"); + } + return models_[0]->constant_data_size(static_cast(idx)); + } + + // retrieve type of constants_info_[idx] + int32_t constant_type(size_t idx) const { + if (this->num_models() == 0) { + throw std::runtime_error("No available models in container!"); + } + return models_[0]->constant_type(static_cast(idx)); + } + + // retrieve dtype of constants_info_[idx] + int32_t constant_dtype(size_t idx) const { + if (this->num_models() == 0) { + throw std::runtime_error("No available models in container!"); + } + return models_[0]->constant_dtype(static_cast(idx)); + } + + uint64_t constant_blob_size() const { + if (this->num_models() == 0) { + throw std::runtime_error("No available models in container!"); + } + return models_[0]->constant_blob_size(); + } + + void update_constants_from_blob(const uint8_t* weight_blob_ptr) { + if (this->num_models() == 0) { + throw std::runtime_error("No available models in container!"); + } + return models_[0]->update_constants_from_blob(weight_blob_ptr); + } + + void run_const_fold( + bool inactive_buffer, + DeviceStreamType stream, + AOTIProxyExecutorHandle proxy_executor) { + AOTInductorModel* model; + ConstantState& const_folded = inactive_buffer == use_secondary_ + ? constant_folded_ + : constant_folded_secondary_; + if (!inactive_buffer) { + // We would need to acquire a unique lock if we want to run constant + // folding on the active buffer. + std::unique_lock constants_folding_lk(model_exec_mutex_); + model = get_available_model(); + try { + auto folded_const_map = model->run_const_fold(stream, proxy_executor); + update_constant_buffer( + std::move(folded_const_map), + /* use_inactive = */ false, + /* validate_full_update = */ false); + const_folded = ConstantState::FOLDED; + } catch (...) { + std::lock_guard lk(models_mutex_); + available_models_.push_back(model); + throw; + } + } else { + std::shared_lock model_lk(model_exec_mutex_); + model = get_available_model(); + + // We swap the constant mapping to the inactive buffer in the model to run + // const run. + auto constants_map = get_constants_map(/* get_inactive= */ true); + auto constants_array = get_constants_array(/* get_inactive= */ true); + + try { + model->update_constants_map( + constants_map, /* remap_constants_array= */ false); + model->update_constants_array(constants_array); + + auto folded_const_map = model->run_const_fold(stream, proxy_executor); + update_constant_buffer( + std::move(folded_const_map), + /* use_inactive = */ true, + /* validate_full_update = */ false); + + // Swap back the model's constants mapping + constants_map = get_constants_map(/* get_inactive= */ false); + constants_array = get_constants_array(/* get_inactive= */ false); + model->update_constants_map( + constants_map, /* remap_constants_array= */ false); + model->update_constants_array(constants_array); + const_folded = ConstantState::FOLDED; + } catch (...) { + std::lock_guard lk(models_mutex_); + available_models_.push_back(model); + throw; + } + } + + { + std::lock_guard lk(models_mutex_); + pending_models_.push_back(model); + } + pending_models_available_.notify_one(); + } + + bool _is_tensor_constant_type(const size_t idx) const { + auto constant_type = models_[0]->constant_type(static_cast(idx)); + // We should skip constants + return constant_type == ConstantType::TensorConstant; + } + + bool _is_buffer_type(const size_t idx) const { + auto constant_type = models_[0]->constant_type(static_cast(idx)); + // Buffer can be optionally skipped, so if it not provided by upstream + // services, it is OK to relax the check. + return constant_type == ConstantType::Buffer; + } + + bool _is_empty_parameter_type(const size_t idx) const { + auto constant_type = models_[0]->constant_type(static_cast(idx)); + auto constant_data_size = + models_[0]->constant_data_size(static_cast(idx)); + // Empty parameters are skipped and not provided by the upstream services, + // it is OK to skip. + return constant_type == ConstantType::Parameter && constant_data_size == 0; + } + + bool _is_tensor_constant_or_buffer_type_or_empty_parameter( + const size_t idx) const { + return _is_tensor_constant_type(idx) || _is_buffer_type(idx) || + _is_empty_parameter_type(idx); + } + + void assert_all_constants( + const std::unordered_map& constants_map) { + auto num_constants = models_[0]->num_constants(); + for (size_t idx = 0; idx < num_constants; idx++) { + if (models_[0]->constant_from_folded(static_cast(idx))) { + continue; + } + + auto constant_name = + std::string(models_[0]->constant_name(static_cast(idx))); + auto it = constants_map.find(constant_name); + if (it == constants_map.end()) { + if (_is_tensor_constant_or_buffer_type_or_empty_parameter(idx)) { + // tracing sometimes creates tensors that are non-existent in + // original graph. We could skip those and do a direct copy. + std::cerr << "[WARNING] Found constant or module state buffer or " + << "empty module state parameter " << constant_name + << " in model, but not provided by user!\n"; + continue; + } + throw std::runtime_error( + std::string("Cannot find constants ") + constant_name + + std::string(" in constants_map!")); + } + } + } + + // We directly take ownership from AtenTensorHandle if constants are moved. + void update_constant_buffer( + std::unordered_map&& constants_map, + bool use_inactive, + bool validate_full_update) { + if (this->num_models() == 0) { + throw std::runtime_error("No model available in container!"); + } + if (validate_full_update) { + assert_all_constants(constants_map); + } + + ConstantState& const_folded = use_inactive == use_secondary_ + ? constant_folded_ + : constant_folded_secondary_; + const_folded = ConstantState::INITIALIZED; + + auto original_constants_map = get_constants_map(!use_inactive); + auto constants_map_to_update = get_constants_map(use_inactive); + + auto num_constants = models_[0]->num_constants(); + for (size_t idx = 0; idx < num_constants; idx++) { + auto constant_name = + std::string(models_[0]->constant_name(static_cast(idx))); + auto it = constants_map.find(constant_name); + if (it == constants_map.end() && + !(use_inactive && _is_tensor_constant_type(idx))) { + continue; + } + + AtenTensorHandle tensor; + if (it == constants_map.end()) { + aoti_torch_clone( + original_constants_map->find(constant_name)->second.get(), &tensor); + } else { + tensor = it->second; + } + + constants_map_to_update->insert_or_assign( + constant_name, RAIIAtenTensorHandle(tensor)); + } + // Update the inactive constant array. + update_array_from_map( + get_constants_array(use_inactive), constants_map_to_update); + } + + // This function updates the buffer for storing constants. + // It will update the buffer, the mapping and the array mapping. + void update_constant_buffer( + const std::unordered_map& constants_map, + bool use_inactive, + bool validate_full_update, + bool user_managed = false) { + if (this->num_models() == 0) { + throw std::runtime_error("No model available in container!"); + } + if (validate_full_update) { + assert_all_constants(constants_map); + } + + ConstantState& const_folded = use_inactive == use_secondary_ + ? constant_folded_ + : constant_folded_secondary_; + const_folded = ConstantState::INITIALIZED; + + auto original_constants_map = get_constants_map(!use_inactive); + auto constants_map_to_update = get_constants_map(use_inactive); + + auto num_constants = models_[0]->num_constants(); + for (size_t idx = 0; idx < num_constants; idx++) { + auto constant_name = + std::string(models_[0]->constant_name(static_cast(idx))); + auto it = constants_map.find(constant_name); + if (it == constants_map.end() && + !(use_inactive && + _is_tensor_constant_or_buffer_type_or_empty_parameter(idx))) { + continue; + } + + AtenTensorHandle tensor; + if (it == constants_map.end()) { + tensor = original_constants_map->find(constant_name)->second.get(); + } else { + tensor = it->second; + } + + if (user_managed) { + // If user managed, we pass in the pointer directly, and skip the + // copy. + constants_map_to_update->insert_or_assign( + constant_name, + MaybeOwningAtenTensorHandle(tensor, /* user_managed = */ true)); + continue; + } + + auto* constants_blob_ptr = + static_cast(get_constant_blob_ptr(use_inactive)); + + // Move the data to container handled blob. + uint8_t* internal_constants_ptr = + constants_blob_ptr + constants_internal_offset_[idx]; + void* user_constant_ptr; + int64_t constant_size; + int64_t* stride; + int64_t offset; + aoti_torch_get_data_ptr(tensor, &user_constant_ptr); + aoti_torch_get_storage_size(tensor, &constant_size); + AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_get_strides(tensor, &stride)); + AOTI_TORCH_ERROR_CODE_CHECK( + aoti_torch_get_storage_offset(tensor, &offset)); + auto dtype = models_[0]->constant_dtype(idx); + +#ifdef USE_XPU + sycl::queue* queue_ptr = nullptr; + aoti_torch_get_current_sycl_queue((void**)&queue_ptr); + queue_ptr + ->memcpy(internal_constants_ptr, user_constant_ptr, constant_size) + .wait(); +#elif USE_MPS + internal_constants_ptr = constants_blob_ptr; + aoti_torch_mps_copy_buffer( + user_constant_ptr, + constants_blob_ptr, + constant_size, + offset, + constants_internal_offset_[idx]); + // For mps tensors, all constants are stored in one buffer, with the + // offset being where the constant starts. So we want to change the + // constant tensor's offset to point to constants_internal_offset_[idx] + offset = constants_internal_offset_[idx] / + aoti_torch_dtype_element_size(dtype); +#elif USE_CUDA + AOTI_RUNTIME_CUDA_CHECK(cudaMemcpy( + internal_constants_ptr, + user_constant_ptr, + constant_size, + cudaMemcpyDefault)); +#else + memcpy(internal_constants_ptr, user_constant_ptr, constant_size); +#endif + // Generate Tensor from container handled blob. + // We extract stride and offset from provided Tensor since we do not + // guarantee that the tensor is contiguous. + AtenTensorHandle tensor_handle; + int device_type = models_[0]->get_device_type(); + int device_idx = models_[0]->get_device_idx(); + AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_create_tensor_from_blob( + internal_constants_ptr, + models_[0]->constant_ndim(idx), + models_[0]->constant_shape(idx), + stride, + offset, + dtype, + device_type, + device_idx, + &tensor_handle)); + + // Now place the tensor to constants_map. Note at this point the + // ownership of the tensor_handle will be taken over. + constants_map_to_update->insert_or_assign( + constant_name, RAIIAtenTensorHandle(tensor_handle)); + } + // Update the inactive constant array. + update_array_from_map( + get_constants_array(use_inactive), constants_map_to_update); + } + + void update_array_from_map( + const std::shared_ptr>& constants_array, + const std::shared_ptr& constants_map) { + auto num_constants = models_[0]->num_constants(); + for (size_t idx = 0; idx < num_constants; idx++) { + if (constants_map->find(models_[0]->constant_name( + static_cast(idx))) != constants_map->end()) { + constants_array->at(idx) = ConstantHandle( + constants_map + ->find(models_[0]->constant_name(static_cast(idx))) + ->second); + } + } + } + + void swap_constant_buffer() { + std::lock_guard unique_lk(model_exec_mutex_); + + auto constants_map = get_constants_map(/* get_inactive= */ true); + auto constants_array = get_constants_array(/* get_inactive= */ true); + + for (auto& model : models_) { + model->update_constants_map( + constants_map, /* remap_constants_array = */ false); + model->update_constants_array(constants_array); + } + + use_secondary_ = !use_secondary_; + } + + void free_inactive_constant_buffer() { + if (use_secondary_) { + constant_folded_ = ConstantState::NONE; + constant_blob_.reset(); + } else { + constant_folded_secondary_ = ConstantState::NONE; + constant_blob_secondary_.reset(); + } + // Free the internally held constants + int num_constants = static_cast(models_[0]->num_constants()); + std::shared_ptr to_free_map = + use_secondary_ ? constants_map_ : constants_map_secondary_; + + for (int i = 0; i < num_constants; i++) { + if (models_[0]->constant_from_folded(i)) { + auto it = to_free_map->find(models_[0]->constant_name(i)); + if (it != to_free_map->end()) { + it->second.reset(); + } + } + } + } + + size_t num_inputs() const { + return input_names_.size(); + } + + size_t num_outputs() const { + return output_names_.size(); + } + + const char* input_name(size_t idx) const { + return input_names_.at(idx).c_str(); + } + + const char* output_name(size_t idx) const { + return output_names_.at(idx).c_str(); + } + + size_t num_models() const { + return models_.size(); + } + + const char* get_in_spec() const { + return in_spec_; + } + + const char* get_out_spec() const { + return out_spec_; + } + + private: + std::vector input_names_; + std::vector output_names_; + const char* in_spec_; + const char* out_spec_; + + // Holds the blob storage for constants' at::Tensor within the container. + // This blob of memory will be managed by the container. + RAIIDataPtr constant_blob_; + RAIIDataPtr constant_blob_secondary_; + + size_t blob_size_; + std::vector constants_internal_offset_; + + // Determine which constants is being used for the model. + // If true, + // constants_map_secondary/constant_blob_secondary/constants_array_secondary + // is being used. + bool use_secondary_{false}; + + // Determine whether we have ran constant folding + ConstantState constant_folded_{ConstantState::NONE}; + ConstantState constant_folded_secondary_{ConstantState::NONE}; + + // Holds the mapping of constants to at::Tensor. + // The underlying data of at::Tensor is in either constant_blob_ (for CUDA). + // or _binary_constants_bin_start (for CPU). + std::shared_ptr constants_map_; + std::shared_ptr constants_map_secondary_; + + // Holds the indexed array of constant for faster lookup during runtime. + std::shared_ptr> constants_array_; + std::shared_ptr> constants_array_secondary_; + + // Holds all the AOTInductorModel instances owned by this container. + std::vector> models_; + + // Holds the AOTInductorModel instances available for inference. + std::vector available_models_; + + // Holds the AOTInductorModel instances that have started running + // inference and can be placed onto available_models_ upon their + // completion. + std::deque pending_models_; + + // Protects available_models_ and pending_models_. + std::mutex models_mutex_; + + // Notified whenever a model is placed onto pending_models_. + std::condition_variable pending_models_available_; + + AOTInductorModel* get_available_model() { + std::unique_lock lk(models_mutex_); + if (available_models_.empty()) { + reclaim_finished_models(lk); + } + auto* result = available_models_.back(); + available_models_.pop_back(); + return result; + } + + // This mutex is used to protect execution of model. + // We acquire the mutex in shared mode if we allow concurrent execution. + // We acquire the mutex in unique mode when we want exclusive access of the + // model. One such case is when we want to do a weight swapping. We want to + // make sure no one is executing the model. + std::shared_mutex model_exec_mutex_; + + RAIIDataPtr allocate_constant_blob() { +#if defined(USE_CUDA) || defined(USE_XPU) || defined(USE_MPS) + return RAII_gpuMalloc(blob_size_); +#else + return RAII_cpuMalloc(blob_size_); +#endif // USE_CUDA + } + + void* get_constant_blob_ptr(bool get_inactive) { + if ((get_inactive && use_secondary_) || + (!get_inactive && !use_secondary_)) { + if (!constant_blob_) { + constant_blob_ = allocate_constant_blob(); + } + return constant_blob_.get(); + } else { + if (!constant_blob_secondary_) { + constant_blob_secondary_ = allocate_constant_blob(); + } + return constant_blob_secondary_.get(); + } + } + + std::shared_ptr get_constants_map(bool get_inactive) { + if ((get_inactive && use_secondary_) || + (!get_inactive && !use_secondary_)) { + return constants_map_; + } else { + if (!constants_map_secondary_) { + constants_map_secondary_ = std::make_shared(); + } + return constants_map_secondary_; + } + } + + std::shared_ptr> get_constants_array( + bool get_inactive) { + if ((get_inactive && use_secondary_) || + (!get_inactive && !use_secondary_)) { + return constants_array_; + } else { + if (!constants_array_secondary_) { + constants_array_secondary_ = + std::make_shared>( + models_[0]->num_constants()); + } + return constants_array_secondary_; + } + } + + void reclaim_finished_models(std::unique_lock& lk) { +#ifdef __aarch64__ + // push finished model instances to the end of pending_models_ + auto it = std::partition( + pending_models_.begin(), + pending_models_.end(), + [](AOTInductorModel* m) { return !m->is_finished(); }); +#else + // push finished model instances to the end of pending_models_ + auto it = std::stable_partition( + pending_models_.begin(), + pending_models_.end(), + [](AOTInductorModel* m) { return !m->is_finished(); }); +#endif + + if (it != pending_models_.end()) { + // We have finished model instances that can be pushed into + // available_models_ so that we don't have to be blocked on waiting + // the pending_models_available_ condition. + available_models_.insert( + available_models_.end(), it, pending_models_.end()); + pending_models_.erase(it, pending_models_.end()); + return; + } + + pending_models_available_.wait( + lk, [this]() { return !pending_models_.empty(); }); + // Let's make the schedule simple first. We always wait on the first + // pending_models_ to be complete. + auto* model = pending_models_.front(); + pending_models_.pop_front(); + lk.unlock(); + try { + model->wait_for_completion(); + } catch (...) { + lk.lock(); + available_models_.push_back(model); + throw; + } + lk.lock(); + available_models_.push_back(model); + } +}; + +} // namespace torch::aot_inductor + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/scalar_to_tensor.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/scalar_to_tensor.h new file mode 100644 index 0000000000000000000000000000000000000000..3ba22f3a286f0cb7725f2d013ed0bc4c447a7ffb --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/scalar_to_tensor.h @@ -0,0 +1,43 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +namespace torch::aot_inductor { + +template +inline RAIIAtenTensorHandle scalar_to_tensor_handle(T value) { + throw std::runtime_error("Unsupported scalar_to_tensor_handle"); +} + +// Specialize for supported C++ primitive types +#define AOTI_RUNTIME_SCALAR_TO_TENSOR(dtype, ctype) \ + template <> \ + inline RAIIAtenTensorHandle scalar_to_tensor_handle(ctype value) { \ + AtenTensorHandle tensor_handle; \ + AOTI_TORCH_ERROR_CODE_CHECK( \ + aoti_torch_scalar_to_tensor_##dtype(value, &tensor_handle)); \ + return RAIIAtenTensorHandle(tensor_handle); \ + } + +AOTI_RUNTIME_SCALAR_TO_TENSOR(float32, float) +AOTI_RUNTIME_SCALAR_TO_TENSOR(float64, double) +AOTI_RUNTIME_SCALAR_TO_TENSOR(uint8, uint8_t) +AOTI_RUNTIME_SCALAR_TO_TENSOR(uint16, uint16_t) +AOTI_RUNTIME_SCALAR_TO_TENSOR(uint32, uint32_t) +AOTI_RUNTIME_SCALAR_TO_TENSOR(uint64, uint64_t) +AOTI_RUNTIME_SCALAR_TO_TENSOR(int8, int8_t) +AOTI_RUNTIME_SCALAR_TO_TENSOR(int16, int16_t) +AOTI_RUNTIME_SCALAR_TO_TENSOR(int32, int32_t) +AOTI_RUNTIME_SCALAR_TO_TENSOR(int64, int64_t) +AOTI_RUNTIME_SCALAR_TO_TENSOR(bool, bool) +AOTI_RUNTIME_SCALAR_TO_TENSOR(complex64, c10::complex) +AOTI_RUNTIME_SCALAR_TO_TENSOR(complex128, c10::complex) +#undef AOTI_RUNTIME_SCALAR_TO_TENSOR + +} // namespace torch::aot_inductor + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/sycl_runtime_wrappers.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/sycl_runtime_wrappers.h new file mode 100644 index 0000000000000000000000000000000000000000..5e013ef81634689ea01268d365e9c3b016568559 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/sycl_runtime_wrappers.h @@ -0,0 +1,172 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +// NOLINT +#pragma once +#ifdef USE_XPU +#include +#include +#include +#include +#include +#include + +#define ZE_CHECK(status) \ + { \ + if (status != ZE_RESULT_SUCCESS) { \ + std::stringstream ss; \ + ss << "L0 runtime error: " << std::hex << std::uppercase << status; \ + throw std::runtime_error(ss.str()); \ + } \ + } + +static ze_module_handle_t _createModule( + const uint8_t* binaryPtr, + size_t binarySize) { + sycl::device& syclDevice = + c10::xpu::get_raw_device(c10::xpu::current_device()); + auto& syclContext = c10::xpu::get_device_context(); + auto device = + sycl::get_native(syclDevice); + auto context = + sycl::get_native(syclContext); + + const char* buildFlags = ""; + const ze_module_format_t format = ZE_MODULE_FORMAT_IL_SPIRV; + ze_module_desc_t moduleDescription = {}; + moduleDescription.stype = ZE_STRUCTURE_TYPE_MODULE_DESC; + moduleDescription.format = format; + moduleDescription.inputSize = binarySize; + moduleDescription.pInputModule = (uint8_t*)binaryPtr; + moduleDescription.pBuildFlags = buildFlags; + ze_module_build_log_handle_t buildLog = nullptr; + ze_module_handle_t module = nullptr; + auto error_no = ZE_RESULT_SUCCESS; + error_no = + zeModuleCreate(context, device, &moduleDescription, &module, &buildLog); + + if (error_no != ZE_RESULT_SUCCESS) { + size_t szLog = 0; + ZE_CHECK(zeModuleBuildLogGetString(buildLog, &szLog, nullptr)); + char* strLog = (char*)malloc(szLog); + ZE_CHECK(zeModuleBuildLogGetString(buildLog, &szLog, strLog)); + std::cerr << "L0 build module failed. Log: " << strLog << std::endl; + free(strLog); + } + if (buildLog) { + ZE_CHECK(zeModuleBuildLogDestroy(buildLog)); + } + ZE_CHECK(error_no); + return module; +} + +static std::unique_ptr _createKernel( + ze_module_handle_t module, + const char* kernelName) { + assert(module); + assert(kernelName); + ze_kernel_handle_t kernel = nullptr; + ze_kernel_desc_t kernelDescription = {}; + kernelDescription.stype = ZE_STRUCTURE_TYPE_KERNEL_DESC; + kernelDescription.pNext = nullptr; + kernelDescription.flags = ZE_KERNEL_FLAG_FORCE_RESIDENCY; + kernelDescription.pKernelName = kernelName; + ZE_CHECK(zeKernelCreate(module, &kernelDescription, &kernel)); + + auto& syclContext = c10::xpu::get_device_context(); + auto mod = sycl::make_kernel_bundle< + sycl::backend::ext_oneapi_level_zero, + sycl::bundle_state::executable>( + {module, sycl::ext::oneapi::level_zero::ownership::transfer}, + syclContext); + auto fun = sycl::make_kernel( + {mod, kernel, sycl::ext::oneapi::level_zero::ownership::transfer}, + syclContext); + return std::make_unique(fun); +} + +// GPU Cpp Wrapper API +[[maybe_unused]] static std::unique_ptr loadKernel( + std::string filePath, + const std::string& funcName, + uint32_t sharedMemBytes, + const std::optional& binDir = std::nullopt) { + if (binDir) { + std::filesystem::path p1{*binDir}; + std::filesystem::path p2{filePath}; + filePath = (p1 / p2.filename()).string(); + } + + std::ifstream IFS(filePath.c_str(), std::ios::binary); + std::ostringstream OSS; + OSS << IFS.rdbuf(); + std::string data(OSS.str()); + + auto mod = _createModule( + reinterpret_cast(data.c_str()), data.size()); + + return _createKernel(mod, funcName.c_str()); +} + +// GPU Cpp Wrapper API +[[maybe_unused]] static std::unique_ptr loadKernel( + const void* start, + const void* end, + const std::string& funcName, + uint32_t sharedMemBytes) { + size_t size = reinterpret_cast(end) - + reinterpret_cast(start); + + auto mod = _createModule(reinterpret_cast(start), size); + + return _createKernel(mod, funcName.c_str()); +} + +// GPU Cpp Wrapper API +[[maybe_unused]] static void launchKernel( + std::unique_ptr& kernelPtr, + uint32_t gridX, + uint32_t gridY, + uint32_t gridZ, + uint32_t numWarps, + uint32_t sharedMemory, + void** params, + sycl::queue* queuePtr, + uint32_t threadsPerWarp) { + std::string kernelName = + kernelPtr->get_info(); + uint32_t numParams = kernelPtr->get_info(); + size_t globalRangeX = gridX * threadsPerWarp * numWarps; + size_t globalRangeY = gridY; + size_t globalRangeZ = gridZ; + size_t localRangeX = numWarps * threadsPerWarp; + size_t localRangeY = 1; + size_t localRangeZ = 1; + sycl::range<3> globalRange(globalRangeZ, globalRangeY, globalRangeX); + sycl::range<3> localRange(localRangeZ, localRangeY, localRangeX); + sycl::nd_range<3> parallelWorkSize(globalRange, localRange); + if (sharedMemory) { + // numParams from sycl info = user provided args + sharedMemoryBuffer + numParams -= 1; + } + // Submit the imported kernel. + auto cgf = [&](sycl::handler& cgh) { + for (uint32_t i = 0; i < numParams; ++i) { + cgh.set_arg(i, *(static_cast(params[i]))); + } + + if (sharedMemory > 0) { + constexpr int dimensions = 1; + using share_mem_t = sycl::local_accessor; + share_mem_t localBuffer = share_mem_t(sharedMemory, cgh); + cgh.set_arg(numParams, localBuffer); + cgh.parallel_for(parallelWorkSize, *kernelPtr); + } else { + cgh.parallel_for(parallelWorkSize, *kernelPtr); + } + }; + auto event = queuePtr->submit(cgf); +} +#endif + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/thread_local.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/thread_local.h new file mode 100644 index 0000000000000000000000000000000000000000..7aea78361dc5765eae78d748e3022cfbfa1ec63d --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/thread_local.h @@ -0,0 +1,165 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::aot_inductor { + +template +struct ThreadLocalCachedOutputTensor; + +template <> +struct ThreadLocalCachedOutputTensor { + explicit ThreadLocalCachedOutputTensor(const RAIIAtenTensorHandle&) {} + void copy_data_from(const RAIIAtenTensorHandle& handle) { + throw std::runtime_error("can't happen"); + } + + AtenTensorHandle tensor() const { + throw std::runtime_error("can't happen"); + } +}; + +template <> +struct ThreadLocalCachedOutputTensor { + explicit ThreadLocalCachedOutputTensor(const AtenTensorHandle&) {} + void copy_data_from(const AtenTensorHandle& handle) { + throw std::runtime_error("can't happen"); + } + + AtenTensorHandle tensor() const { + throw std::runtime_error("can't happen"); + } +}; + +template <> +struct ThreadLocalCachedOutputTensor { + explicit ThreadLocalCachedOutputTensor(const ConstantHandle&) {} + void copy_data_from(const ConstantHandle& handle) { + throw std::runtime_error("can't happen"); + } + + AtenTensorHandle tensor() const { + throw std::runtime_error("can't happen"); + } +}; + +template +struct ThreadLocalCachedOutputTensor> { + explicit ThreadLocalCachedOutputTensor(const ArrayRefTensor& t) { + realloc(t); + } + + void copy_data_from(const ArrayRefTensor& t) { + if (t.numel() > capacity_) { + realloc(t); + } + std::copy(t.data(), t.data() + t.numel(), storage_.get()); + } + + AtenTensorHandle tensor() const { + return tensor_.get(); + } + + private: + void realloc(const ArrayRefTensor& t) { + capacity_ = t.numel(); + // NOLINTNEXTLINE(*arrays*) + storage_ = std::make_unique(t.numel()); + AtenTensorHandle handle = nullptr; + AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_create_tensor_from_blob( + storage_.get(), + t.sizes().size(), + t.sizes().data(), + t.strides().data(), + 0, + aoti_torch_dtype>(), + t.device_type(), + t.device_idx(), + &handle)); + tensor_ = handle; + } + + // NOLINTNEXTLINE(*arrays*) + std::unique_ptr storage_; + int64_t capacity_ = 0; + RAIIAtenTensorHandle tensor_; +}; + +template +struct ThreadLocalCachedOutputArray; + +// Just needs to compile, doesn't need to do anything. +template <> +struct ThreadLocalCachedOutputArray { + explicit ThreadLocalCachedOutputArray(const RAIIAtenTensorHandle&) { + throw std::runtime_error("can't happen"); + } + + // Not supported yet! We would need to put contiguous() or + // expect_contiguous() into the ABI. + void copy_data_from(const RAIIAtenTensorHandle&) { + throw std::runtime_error("can't happen"); + } + + template + ArrayRefTensor arrayref_tensor() const { + throw std::runtime_error("can't happen"); + } +}; + +// Just needs to compile, doesn't need to do anything. +template <> +struct ThreadLocalCachedOutputArray { + explicit ThreadLocalCachedOutputArray(const ConstantHandle&) { + throw std::runtime_error("can't happen"); + } + + // Not supported yet! We would need to put contiguous() or + // expect_contiguous() into the ABI. + void copy_data_from(const ConstantHandle&) { + throw std::runtime_error("can't happen"); + } + + template + ArrayRefTensor arrayref_tensor() const { + throw std::runtime_error("can't happen"); + } +}; + +template +struct ThreadLocalCachedOutputArray> { + explicit ThreadLocalCachedOutputArray(const ArrayRefTensor& t) {} + + template < + typename U, + std::enable_if_t< + std::is_same_v, std::remove_const_t>, + bool> = true> + ArrayRefTensor arrayref_tensor() const { + return tensor_; + } + + void copy_data_from(const ArrayRefTensor& t) { + if (t.numel() > capacity_) { + capacity_ = t.numel(); + // NOLINTNEXTLINE(*arrays*) + storage_ = std::make_unique(capacity_); + } + std::copy(t.data(), t.data() + t.numel(), storage_.get()); + tensor_ = t; + tensor_.set_arrayref(MiniArrayRef(storage_.get(), t.numel())); + } + + private: + // NOLINTNEXTLINE(*arrays*) + std::unique_ptr storage_; + uint32_t capacity_ = 0; + ArrayRefTensor tensor_; +}; + +} // namespace torch::aot_inductor + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/utils.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/utils.h new file mode 100644 index 0000000000000000000000000000000000000000..1eb79da9f82d5bbb45f9e9452da1842cfacf7347 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/utils.h @@ -0,0 +1,484 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include +#include + +// WARNING: Be careful when adding new includes here. This header will be used +// in model.so, and should not refer to any aten/c10 headers except the stable +// C ABI defined in torch/csrc/inductor/aoti_torch/c/shim.h. The same rule +// applies to other files under torch/csrc/inductor/aoti_runtime/. +#include +#include + +#if defined(__GNUC__) || defined(__clang__) +#define AOTI_NOINLINE __attribute__((noinline)) +#elif _MSC_VER +#define AOTI_NOINLINE __declspec(noinline) +#else +#define AOTI_NOINLINE +#endif + +#define AOTI_TORCH_ERROR_CODE_CHECK(call) \ + if ((call) != AOTI_TORCH_SUCCESS) { \ + torch::headeronly::detail::throw_exception(#call, __FILE__, __LINE__); \ + } + +using AOTIRuntimeError = int32_t; +#define AOTI_RUNTIME_SUCCESS 0 +#define AOTI_RUNTIME_FAILURE 1 + +#define AOTI_RUNTIME_ERROR_CODE_CHECK(call) \ + if ((call) != AOTI_RUNTIME_SUCCESS) { \ + torch::headeronly::detail::throw_exception(#call, __FILE__, __LINE__); \ + } + +namespace torch::aot_inductor { + +using DeleterFnPtr = void (*)(void*); + +inline void noop_deleter(void* /*unused*/) {} + +inline void delete_record_function_object(void* ptr) { + AOTI_TORCH_ERROR_CODE_CHECK(aoti_record_function_end( + reinterpret_cast(ptr))); +} + +inline void delete_tensor_object(void* ptr) { + AOTI_TORCH_ERROR_CODE_CHECK( + aoti_torch_delete_tensor_object(reinterpret_cast(ptr))); +} + +inline void delete_c10_value_object(void* ptr) { + AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_delete_c10_value_object( + reinterpret_cast(ptr))); +} + +class RAIIAtenRecordFunctionHandle { + public: + RAIIAtenRecordFunctionHandle() : handle_(nullptr, noop_deleter) {} + RAIIAtenRecordFunctionHandle(const RAIIAtenRecordFunctionHandle& other) = + delete; + RAIIAtenRecordFunctionHandle& operator=( + const RAIIAtenRecordFunctionHandle& other) = delete; + + // Initiate an RAII RecordFunction without Inputs + RAIIAtenRecordFunctionHandle(const char* name, IValueMapHandle kwargs) + : handle_(nullptr, delete_record_function_object) { + AtenRecordFunctionHandle tmp_handle = nullptr; + aoti_record_function_start(name, kwargs, nullptr, 0, &tmp_handle); + handle_.reset(tmp_handle); + } + + // Initiate an RAII RecordFunction with Inputs + RAIIAtenRecordFunctionHandle( + const char* name, + IValueMapHandle kwargs, + std::vector inputs) + : handle_(nullptr, delete_record_function_object) { + AtenRecordFunctionHandle tmp_handle = nullptr; + aoti_record_function_start( + name, kwargs, inputs.data(), inputs.size(), &tmp_handle); + handle_.reset(tmp_handle); + } + + // Steal the ownership from another RAIIAtenRecordFunctionHandle using + // std::move + RAIIAtenRecordFunctionHandle(RAIIAtenRecordFunctionHandle&& other) = default; + RAIIAtenRecordFunctionHandle& operator=( + RAIIAtenRecordFunctionHandle&& other) = default; + + // Steal the ownership from raw AtenRecordFunctionHandle + RAIIAtenRecordFunctionHandle(AtenRecordFunctionHandle handle) + : handle_(handle, delete_record_function_object) {} + + ~RAIIAtenRecordFunctionHandle() { + handle_.reset(); + } + + // Return a raw AtenRecordFunctionHandle to be used by aoti_torch functions + // Note: this function does NOT transfer the ownership of the handle + operator AtenRecordFunctionHandle() const { + return handle_.get(); + } + + AtenRecordFunctionHandle release() { + return handle_.release(); + } + + AtenRecordFunctionHandle get() const { + return handle_.get(); + } + + void reset() { + handle_.reset(); + } + + private: + std::unique_ptr handle_; +}; + +// RAIIAtenTensorHandle steals the tensor objects created by the libtorch C ABI +class RAIIAtenTensorHandle { + public: + RAIIAtenTensorHandle() : handle_(nullptr, noop_deleter) {} + RAIIAtenTensorHandle(const RAIIAtenTensorHandle& other) = delete; + RAIIAtenTensorHandle& operator=(const RAIIAtenTensorHandle& other) = delete; + + // Steal the ownership from another RAIIAtenTensorHandle using std::move + RAIIAtenTensorHandle(RAIIAtenTensorHandle&& other) = default; + RAIIAtenTensorHandle& operator=(RAIIAtenTensorHandle&& other) = default; + + // Steal the ownership from raw AtenTensorHandle + RAIIAtenTensorHandle(AtenTensorHandle handle) + : handle_(handle, delete_tensor_object) {} + + ~RAIIAtenTensorHandle() { + handle_.reset(); + } + + // Return a raw AtenTensorHandle to be used by aoti_torch functions + // Note: this function does NOT transfer the ownership of the handle + operator AtenTensorHandle() const { + return handle_.get(); + } + + AtenTensorHandle release() { + return handle_.release(); + } + + AtenTensorHandle get() const { + return handle_.get(); + } + + void reset() { + handle_.reset(); + } + + int64_t size(int64_t d) { + int64_t size = 0; + AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_get_size(handle_.get(), d, &size)); + return size; + } + + int64_t stride(int64_t d) { + int64_t stride = 0; + AOTI_TORCH_ERROR_CODE_CHECK( + aoti_torch_get_stride(handle_.get(), d, &stride)); + return stride; + } + + int64_t storage_offset() { + int64_t storage_offset = 0; + AOTI_TORCH_ERROR_CODE_CHECK( + aoti_torch_get_storage_offset(handle_.get(), &storage_offset)); + return storage_offset; + } + + void* data_ptr() const { + void* result = nullptr; + AOTI_TORCH_ERROR_CODE_CHECK( + aoti_torch_get_data_ptr(handle_.get(), &result)); + return result; + } + + int64_t* sizes() const { + int64_t* result = nullptr; + AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_get_sizes(handle_.get(), &result)); + return result; + } + + int64_t* strides() const { + int64_t* result = nullptr; + AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_get_strides(handle_.get(), &result)); + return result; + } + + private: + std::unique_ptr handle_; +}; + +// RAIIC10IValueHandle steals the IValue objects created by the libtorch C ABI +class RAIIC10IValueHandle { + public: + RAIIC10IValueHandle() : handle_(nullptr, noop_deleter) {} + RAIIC10IValueHandle(const RAIIC10IValueHandle& other) = delete; + RAIIC10IValueHandle& operator=(const RAIIC10IValueHandle& other) = delete; + + // Steal the ownership from another RAIIC10IValueHandle using std::move + RAIIC10IValueHandle(RAIIC10IValueHandle&& other) = default; + RAIIC10IValueHandle& operator=(RAIIC10IValueHandle&& other) = default; + + // Steal the ownership from raw C10IValueHandle + RAIIC10IValueHandle(C10IValueHandle handle) + : handle_(handle, delete_c10_value_object) {} + + ~RAIIC10IValueHandle() { + handle_.reset(); + } + + // Return a raw C10IValueHandle to be used by aoti_torch functions + // Note: this function does NOT transfer the ownership of the handle + operator C10IValueHandle() const { + return handle_.get(); + } + + C10IValueHandle release() { + return handle_.release(); + } + + C10IValueHandle get() const { + return handle_.get(); + } + + void reset() { + handle_.reset(); + } + + private: + std::unique_ptr handle_; +}; + +class MaybeOwningAtenTensorHandle { + public: + MaybeOwningAtenTensorHandle() : handle_(nullptr) {} + // We skip copy constructor as MaybeOwningAtenTensorHandle might be RAII which + // makes it undefined. + MaybeOwningAtenTensorHandle(const MaybeOwningAtenTensorHandle& other) = + delete; + MaybeOwningAtenTensorHandle& operator=( + const MaybeOwningAtenTensorHandle& other) = delete; + + // Move constructor and move assignment operator + MaybeOwningAtenTensorHandle(MaybeOwningAtenTensorHandle&& other) = default; + MaybeOwningAtenTensorHandle& operator=(MaybeOwningAtenTensorHandle&& other) = + default; + + // Steal the ownership from another RAIIAtenTensorHandle using std::move + MaybeOwningAtenTensorHandle(RAIIAtenTensorHandle&& other) + : raii_handle_(std::move(other)) { + handle_ = raii_handle_.get(); + } + MaybeOwningAtenTensorHandle& operator=(RAIIAtenTensorHandle&& other) { + raii_handle_ = std::move(other); + handle_ = raii_handle_.get(); + return *this; + } + + // By default, steal the ownership from raw AtenTensorHandle + MaybeOwningAtenTensorHandle(AtenTensorHandle handle) : raii_handle_(handle) { + handle_ = raii_handle_.get(); + } + + // If user_managed is true, we do not steal the ownership. + MaybeOwningAtenTensorHandle(AtenTensorHandle handle, bool user_managed) { + if (user_managed) { + aoti_torch_new_tensor_handle(handle, &handle_); + } else { + raii_handle_ = RAIIAtenTensorHandle(handle); + handle_ = raii_handle_.get(); + } + } + + ~MaybeOwningAtenTensorHandle() { + // This is no-op if we don't hold raii_handle with the + // MaybeOwningAtenTensorHandle. + raii_handle_.reset(); + } + + // Return a raw AtenTensorHandle to be used by aoti_torch functions + // Note: this function does NOT transfer the ownership of the handle + operator AtenTensorHandle() const { + return handle_; + } + + AtenTensorHandle release() { + if (raii_handle_) { + return raii_handle_.release(); + } else { + AtenTensorHandle handle = handle_; + handle_ = nullptr; + return handle; + } + } + + AtenTensorHandle get() const { + return handle_; + } + + void reset() { + handle_ = nullptr; + raii_handle_.reset(); + } + + int64_t size(int64_t d) { + int64_t size = 0; + AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_get_size(handle_, d, &size)); + return size; + } + + int64_t stride(int64_t d) { + int64_t stride = 0; + AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_get_stride(handle_, d, &stride)); + return stride; + } + + int64_t storage_offset() { + int64_t storage_offset = 0; + AOTI_TORCH_ERROR_CODE_CHECK( + aoti_torch_get_storage_offset(handle_, &storage_offset)); + return storage_offset; + } + + void* data_ptr() const { + void* result = nullptr; + AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_get_data_ptr(handle_, &result)); + return result; + } + + int64_t* sizes() const { + int64_t* result = nullptr; + AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_get_sizes(handle_, &result)); + return result; + } + + int64_t* strides() const { + int64_t* result = nullptr; + AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_get_strides(handle_, &result)); + return result; + } + + private: + // handle_ is the underlying AtenTensorHandle of raii_handle_ if raii_handle_ + // exists. Otherwise it would just be the AtenTensorHandle passed in by users. + AtenTensorHandle handle_; + RAIIAtenTensorHandle raii_handle_; +}; + +// Steal the ownership from raw AtenTensorHandle to RAIIAtenTensorHandle +inline std::vector steal_from_raw_handles_to_raii_handles( + AtenTensorHandle* handles, + size_t size) { + std::vector result; + result.reserve(size); + for (size_t i = 0; i < size; i++) { + result.emplace_back(handles[i]); + handles[i] = nullptr; + } + return result; +} + +inline AtenTensorHandle reinterpret_tensor_wrapper( + AtenTensorHandle self, + int64_t ndim, + const int64_t* sizes_ptr, + const int64_t* strides_ptr, + int64_t storage_offset) { + AtenTensorHandle result = nullptr; + AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch__reinterpret_tensor( + self, ndim, sizes_ptr, strides_ptr, storage_offset, &result)); + return result; +} + +inline void* get_data_ptr_wrapper(AtenTensorHandle tensor) { + void* result = nullptr; + AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_get_data_ptr(tensor, &result)); + return result; +} + +inline AtenTensorHandle unwrap_raii_handle_if_needed( + const RAIIAtenTensorHandle& handle) { + return handle.get(); +} + +inline RAIIAtenTensorHandle wrap_with_raii_handle_if_needed( + AtenTensorHandle handle) { + return RAIIAtenTensorHandle(handle); +} + +class ConstantHandle { + public: + ConstantHandle() = default; + + explicit ConstantHandle(AtenTensorHandle handle) : handle_(handle) { + AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_get_data_ptr(handle_, &data_)); + } + + operator AtenTensorHandle() const { + return handle_; + } + + AtenTensorHandle tensor() const { + return handle_; + } + + AtenTensorHandle get() const { + return handle_; + } + + void* data_ptr() const { + return data_; + } + + int64_t* sizes() const { + int64_t* result = nullptr; + AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_get_sizes(handle_, &result)); + return result; + } + + int64_t* strides() const { + int64_t* result = nullptr; + AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_get_strides(handle_, &result)); + return result; + } + + private: + AtenTensorHandle handle_{}; + void* data_ = nullptr; +}; + +inline void* get_data_ptr_wrapper(const ConstantHandle& constant) { + return constant.data_ptr(); +} + +inline const ConstantHandle& unwrap_raii_handle_if_needed( + const ConstantHandle& handle) { + return handle; +} + +// Shouldn't be called. +inline AtenTensorHandle wrap_with_raii_handle_if_needed( + const ConstantHandle& handle) = delete; + +// DANGEROUS. Do not call unless you explicitly intend to get a reference to a +// temporary value, which will expire at the end of the current expression. +// This should only be called in cases where the C-shim API expects an optional +// input argument (passed by pointer), and a temporary needs to be passed to it. +template +T& temporary_reference(T&& t) { + return t; +} + +#define CACHE_TORCH_DTYPE(typename) \ + static auto cached_torch_dtype_##typename = aoti_torch_dtype_##typename() + +#define CACHE_TORCH_DEVICE(device) \ + static auto cached_torch_device_type_##device = \ + aoti_torch_device_type_##device() + +#define CACHE_TORCH_LAYOUT(layout) \ + static auto cached_torch_layout_##layout = aoti_torch_layout_##layout() + +#define CACHE_TORCH_MEMORY_FORMAT(format) \ + static auto cached_torch_memory_format_##format = \ + aoti_torch_memory_format_##format() + +} // namespace torch::aot_inductor + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/utils_cuda.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/utils_cuda.h new file mode 100644 index 0000000000000000000000000000000000000000..3dce90bd4059e185b68ead3729c2bb729cf7cbf7 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/utils_cuda.h @@ -0,0 +1,68 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#ifdef USE_CUDA +// WARNING: Be careful when adding new includes here. This header will be used +// in model.so, and should not refer to any aten/c10 headers except the stable +// C ABI defined in torch/csrc/inductor/aoti_torch/c/shim.h. The same rule +// applies to other files under torch/csrc/inductor/aoti_runtime/. +#include + +#include +#include +#ifndef USE_ROCM +#include +#include +#include +#endif + +namespace torch::aot_inductor { + +inline void delete_cuda_guard(void* ptr) { + AOTI_TORCH_ERROR_CODE_CHECK( + aoti_torch_delete_cuda_guard(reinterpret_cast(ptr))); +} + +inline void delete_cuda_stream_guard(void* ptr) { + AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_delete_cuda_stream_guard( + reinterpret_cast(ptr))); +} + +class AOTICudaGuard { + public: + AOTICudaGuard(int32_t device_index) : guard_(nullptr, delete_cuda_guard) { + CUDAGuardHandle ptr = nullptr; + AOTI_TORCH_ERROR_CODE_CHECK( + aoti_torch_create_cuda_guard(device_index, &ptr)); + guard_.reset(ptr); + } + + void set_index(int32_t device_index) { + AOTI_TORCH_ERROR_CODE_CHECK( + aoti_torch_cuda_guard_set_index(guard_.get(), device_index)); + } + + private: + std::unique_ptr guard_; +}; + +class AOTICudaStreamGuard { + public: + AOTICudaStreamGuard(cudaStream_t stream, int32_t device_index) + : guard_(nullptr, delete_cuda_stream_guard) { + CUDAStreamGuardHandle ptr = nullptr; + AOTI_TORCH_ERROR_CODE_CHECK( + aoti_torch_create_cuda_stream_guard(stream, device_index, &ptr)); + guard_.reset(ptr); + } + + private: + std::unique_ptr guard_; +}; + +} // namespace torch::aot_inductor +#endif // USE_CUDA + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/utils_xpu.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/utils_xpu.h new file mode 100644 index 0000000000000000000000000000000000000000..50149503b3117d912df41cabfe395af47bd7cbc5 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runtime/utils_xpu.h @@ -0,0 +1,61 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#ifdef USE_XPU +// WARNING: Be careful when adding new includes here. This header will be used +// in model.so, and should not refer to any aten/c10 headers except the stable +// C ABI defined in torch/csrc/inductor/aoti_torch/c/shim.h. The same rule +// applies to other files under torch/csrc/inductor/aoti_runtime/. +#include +#include + +namespace torch::aot_inductor { + +inline void delete_xpu_guard(void* ptr) { + AOTI_TORCH_ERROR_CODE_CHECK( + aoti_torch_delete_xpu_guard(reinterpret_cast(ptr))); +} + +inline void delete_xpu_stream_guard(void* ptr) { + AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_delete_xpu_stream_guard( + reinterpret_cast(ptr))); +} + +class AOTIXpuGuard { + public: + AOTIXpuGuard(int32_t device_index) : guard_(nullptr, delete_xpu_guard) { + XPUGuardHandle ptr = nullptr; + AOTI_TORCH_ERROR_CODE_CHECK( + aoti_torch_create_xpu_guard(device_index, &ptr)); + guard_.reset(ptr); + } + + void set_index(int32_t device_index) { + AOTI_TORCH_ERROR_CODE_CHECK( + aoti_torch_xpu_guard_set_index(guard_.get(), device_index)); + } + + private: + std::unique_ptr guard_; +}; + +class AOTIXpuStreamGuard { + public: + AOTIXpuStreamGuard(void* stream, int32_t device_index) + : guard_(nullptr, delete_xpu_stream_guard) { + XPUStreamGuardHandle ptr = nullptr; + AOTI_TORCH_ERROR_CODE_CHECK( + aoti_torch_create_xpu_stream_guard(stream, device_index, &ptr)); + guard_.reset(ptr); + } + + private: + std::unique_ptr guard_; +}; + +} // namespace torch::aot_inductor +#endif // USE_XPU + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/c/macros.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/c/macros.h new file mode 100644 index 0000000000000000000000000000000000000000..e49cd39deac0c8f2f0a5939c1503f515abed0d04 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/c/macros.h @@ -0,0 +1,66 @@ +#ifndef AOTI_TORCH_MACRO_H +#define AOTI_TORCH_MACRO_H + +#include +#include +#ifdef __GNUC__ +#define AOTI_TORCH_EXPORT __attribute__((__visibility__("default"))) +#else // !__GNUC__ +#ifdef _WIN32 +// PyTorch2 doesn't currently work on Windows. Exporting these APIs can lead +// to symbol clashes at link time if libtorch is included in a DLL and binary +// that depends on the DLL. As a short term fix, we don't export the symbols. +// In the long term, this will need to be addressed when Windows is supported. +#ifdef OVRSOURCE +// Do not export AOTI on Windows for internal builds +#define AOTI_TORCH_EXPORT +#else /* OVRSOURCE */ +#ifdef EXPORT_AOTI_FUNCTIONS +#define AOTI_TORCH_EXPORT __declspec(dllexport) +#else +#define AOTI_TORCH_EXPORT __declspec(dllimport) +#endif +#endif /* OVRSOURCE */ +#else // !_WIN32 +#define AOTI_TORCH_EXPORT +#endif // _WIN32 +#endif // __GNUC__ + +#ifdef __cplusplus +extern "C" { +#endif +// AtenTensorHandle represents an abstract notion of Tensor that can be passed +// between model.so and libtorch.so. The contents of the structure itself +// are private; model.so is not allowed to access any fields directly, it must +// go through functions defined in this ABI. Under the hood, this is +// represented as at::Tensor*, but we reserve the right to change this (and in +// fact, we probably should change it to at::TensorImpl* at least). +// +// An AtenTensorHandle can be owning (please check the API reference for exact +// ownership/borrow semantics). If you have an owning AtenTensorHandle +// in model.so, you are obligated to aoti_torch_delete_tensor_object when you +// are done. You can use the helper C++ class RAIIAtenTensorHandle +// (see aot_runtime/model.h) to ensure the deallocator is called in RAII style +// (note that RAIIAtenTensorHandle is private to model.so, and never crosses +// the ABI boundary.) +struct AtenTensorOpaque; +using AtenTensorHandle = AtenTensorOpaque*; + +struct AtenGeneratorOpaque; +using AtenGeneratorHandle = AtenGeneratorOpaque*; + +struct AOTIProxyExecutorOpaque; +using AOTIProxyExecutorHandle = AOTIProxyExecutorOpaque*; + +struct C10IValueOpaque; +using C10IValueHandle = C10IValueOpaque*; + +using AOTITorchError = int32_t; +#define AOTI_TORCH_SUCCESS 0 +#define AOTI_TORCH_FAILURE 1 + +#ifdef __cplusplus +} // extern "C" +#endif + +#endif // AOTI_TORCH_MACRO_H diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/c/shim.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/c/shim.h new file mode 100644 index 0000000000000000000000000000000000000000..2eda2b218e705e85c2566ef9dc26f0227ec18ce2 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/c/shim.h @@ -0,0 +1,692 @@ +#ifndef AOTI_TORCH_SHIM +#define AOTI_TORCH_SHIM + +#include +#include + +// This header defines a stable C API for certain ATen functionality in +// libtorch. The AOTInductor compiled model.so will only refer to this header +// instead of other headers from aten/c10, which means it will NOT be able to +// directly use any data structures or call functions from libtorch. +// +// What problems are we trying to solve here? Direct use of aten/c10 APIs +// means use of C++ APIs on a library that doesn't have any ABI compatibility +// guarantees. However, we want model.so to remain usable across updates +// to the PyTorch C++ libraries, which requires a stable ABI. By introducing +// a C shim layer, we can minimize the surface that will cause breakage. The +// corresponding software stack can be illustrated as follows: +// +// |--------------------------------| +// | inference service code | +// |--------------------------------| +// | model.so | +// |--------------|-----------------| +// | | +// | libtorch.so | +// |--------------------------------| +// +// The general guidelines for the C API: +// +// - No exceptions, return an explicit error code to be checked at call site +// - Only pointers (AtenTensorHandle counts), integers and floats in headers +// +// If you want to make changes to this header, you MUST MAINTAIN ABI +// compatibility. Typically, this means you will have to add a _v2 version +// of a function that you, e.g., want to add a new function parameter to, and +// maintain the old and new versions of the APIs until all old model.so +// go out of use. + +// The following files are implemented in a header-only way and are guarded by +// test/cpp/aoti_abi_check +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +// Getter functions for retrieving various constants from the runtime, that +// can subsequently be passed to other aoti_* functions. By hiding these +// behind functions, the precise value of device/dtype is NOT part of the +// ABI contract. (In practice, aten/c10 is pretty good about not renumbering +// these, so we probably could later switch to having these in the ABI, if +// desired for perf reasons.) +AOTI_TORCH_EXPORT int32_t aoti_torch_device_type_cpu(); +AOTI_TORCH_EXPORT int32_t aoti_torch_device_type_cuda(); +AOTI_TORCH_EXPORT int32_t aoti_torch_device_type_meta(); +AOTI_TORCH_EXPORT int32_t aoti_torch_device_type_xpu(); +AOTI_TORCH_EXPORT int32_t aoti_torch_device_type_mps(); +AOTI_TORCH_EXPORT int32_t aoti_torch_device_type_privateuse1(); + +AOTI_TORCH_EXPORT int32_t aoti_torch_dtype_float8_e5m2(); +AOTI_TORCH_EXPORT int32_t aoti_torch_dtype_float8_e4m3fn(); +AOTI_TORCH_EXPORT int32_t aoti_torch_dtype_float8_e5m2fnuz(); +AOTI_TORCH_EXPORT int32_t aoti_torch_dtype_float8_e4m3fnuz(); +AOTI_TORCH_EXPORT int32_t aoti_torch_dtype_bfloat16(); +AOTI_TORCH_EXPORT int32_t aoti_torch_dtype_float16(); +AOTI_TORCH_EXPORT int32_t aoti_torch_dtype_float32(); +AOTI_TORCH_EXPORT int32_t aoti_torch_dtype_float64(); +AOTI_TORCH_EXPORT int32_t aoti_torch_dtype_uint8(); +AOTI_TORCH_EXPORT int32_t aoti_torch_dtype_uint16(); +AOTI_TORCH_EXPORT int32_t aoti_torch_dtype_uint32(); +AOTI_TORCH_EXPORT int32_t aoti_torch_dtype_uint64(); +AOTI_TORCH_EXPORT int32_t aoti_torch_dtype_int8(); +AOTI_TORCH_EXPORT int32_t aoti_torch_dtype_int16(); +AOTI_TORCH_EXPORT int32_t aoti_torch_dtype_int32(); +AOTI_TORCH_EXPORT int32_t aoti_torch_dtype_int64(); +AOTI_TORCH_EXPORT int32_t aoti_torch_dtype_bool(); +AOTI_TORCH_EXPORT int32_t aoti_torch_dtype_complex32(); +AOTI_TORCH_EXPORT int32_t aoti_torch_dtype_complex64(); +AOTI_TORCH_EXPORT int32_t aoti_torch_dtype_complex128(); +AOTI_TORCH_EXPORT size_t aoti_torch_dtype_element_size(int32_t dtype); + +AOTI_TORCH_EXPORT int32_t aoti_torch_layout_strided(); +AOTI_TORCH_EXPORT int32_t aoti_torch_layout_sparse_coo(); +AOTI_TORCH_EXPORT int32_t aoti_torch_layout_sparse_csr(); +AOTI_TORCH_EXPORT int32_t aoti_torch_layout_sparse_csc(); +AOTI_TORCH_EXPORT int32_t aoti_torch_layout_sparse_bsr(); +AOTI_TORCH_EXPORT int32_t aoti_torch_layout_sparse_bsc(); +AOTI_TORCH_EXPORT int32_t aoti_torch_layout__mkldnn(); +AOTI_TORCH_EXPORT int32_t aoti_torch_layout_jagged(); + +AOTI_TORCH_EXPORT int32_t aoti_torch_memory_format_contiguous_format(); +AOTI_TORCH_EXPORT int32_t aoti_torch_memory_format_channels_last(); +AOTI_TORCH_EXPORT int32_t aoti_torch_memory_format_channels_last_3d(); +AOTI_TORCH_EXPORT int32_t aoti_torch_memory_format_preserve_format(); + +// Get TORCH_ABI_VERSION of the built libtorch.so +AOTI_TORCH_EXPORT uint64_t aoti_torch_abi_version(); + +// Functions for converting a single-element tensor to a scalar value +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_item_float16(AtenTensorHandle tensor, c10::Half* ret_value); +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_item_float32(AtenTensorHandle tensor, float* ret_value); +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_item_float64(AtenTensorHandle tensor, double* ret_value); +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_item_uint8(AtenTensorHandle tensor, uint8_t* ret_value); +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_item_uint16(AtenTensorHandle tensor, uint16_t* ret_value); +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_item_uint32(AtenTensorHandle tensor, uint32_t* ret_value); +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_item_uint64(AtenTensorHandle tensor, uint64_t* ret_value); +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_item_int8(AtenTensorHandle tensor, int8_t* ret_value); +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_item_int16(AtenTensorHandle tensor, int16_t* ret_value); +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_item_int32(AtenTensorHandle tensor, int32_t* ret_value); +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_item_int64(AtenTensorHandle tensor, int64_t* ret_value); +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_item_bool(AtenTensorHandle tensor, bool* ret_value); +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_item_bfloat16(AtenTensorHandle tensor, c10::BFloat16* ret_value); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_item_complex64( + AtenTensorHandle tensor, + c10::complex* ret_value); + +// Functions for wrapping a scalar value to a single-element tensor +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_scalar_to_tensor_float32( + float value, + AtenTensorHandle* ret_new_tensor); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_scalar_to_tensor_float64( + double value, + AtenTensorHandle* ret_new_tensor); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_scalar_to_tensor_uint8( + uint8_t value, + AtenTensorHandle* ret_new_tensor); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_scalar_to_tensor_uint16( + uint16_t value, + AtenTensorHandle* ret_new_tensor); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_scalar_to_tensor_uint32( + uint32_t value, + AtenTensorHandle* ret_new_tensor); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_scalar_to_tensor_uint64( + uint64_t value, + AtenTensorHandle* ret_new_tensor); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_scalar_to_tensor_int8( + int8_t value, + AtenTensorHandle* ret_new_tensor); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_scalar_to_tensor_int16( + int16_t value, + AtenTensorHandle* ret_new_tensor); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_scalar_to_tensor_int32( + int32_t value, + AtenTensorHandle* ret_new_tensor); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_scalar_to_tensor_int64( + int64_t value, + AtenTensorHandle* ret_new_tensor); +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_scalar_to_tensor_bool(bool value, AtenTensorHandle* ret_new_tensor); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_scalar_to_tensor_complex64( + c10::complex value, + AtenTensorHandle* ret_new_tensor); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_scalar_to_tensor_complex128( + c10::complex value, + AtenTensorHandle* ret_new_tensor); + +AOTI_TORCH_EXPORT bool aoti_torch_grad_mode_is_enabled(); +AOTI_TORCH_EXPORT void aoti_torch_grad_mode_set_enabled(bool enabled); + +// Free the tensor object +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_delete_tensor_object(AtenTensorHandle tensor); + +// c10::IValue object conversion +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_int64_to_ivalue(int64_t val, C10IValueHandle* ivalue); + +// c10::IValue object conversions +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_strlist_to_ivalue( + const char** val, + int64_t len, + C10IValueHandle* ivalue); + +// c10::IValue object conversions +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_str_to_ivalue(const char* val, C10IValueHandle* ivalue); + +// c10::IValue object conversions +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_tensor_to_ivalue(AtenTensorHandle val, C10IValueHandle* ivalue); + +// Free the c10::IValue object +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_delete_c10_value_object(C10IValueHandle handle); + +// Get a pointer to the underlying storage data +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_get_data_ptr( + AtenTensorHandle tensor, + void** ret_data_ptr // returns borrowed reference +); + +// Get the nbytes of the underlying storage +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_get_storage_size(AtenTensorHandle tensor, int64_t* ret_size); + +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_get_dim(AtenTensorHandle tensor, int64_t* ret_dim); + +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_get_numel(AtenTensorHandle tensor, int64_t* ret_numel); + +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_get_storage_numel(AtenTensorHandle tensor, int64_t* ret_numel); + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_get_sizes( + AtenTensorHandle tensor, + int64_t** ret_sizes // returns borrowed reference +); + +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_get_size(AtenTensorHandle tensor, int64_t d, int64_t* ret_size); + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_get_strides( + AtenTensorHandle tensor, + int64_t** ret_strides // returns borrowed reference +); + +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_get_stride(AtenTensorHandle tensor, int64_t d, int64_t* ret_stride); + +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_get_dtype(AtenTensorHandle tensor, int32_t* ret_dtype); + +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_get_device_type(AtenTensorHandle tensor, int32_t* ret_device_type); + +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_get_device_index(AtenTensorHandle tensor, int32_t* ret_device_index); + +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_get_layout(AtenTensorHandle tensor, int32_t* ret_layout); + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_get_storage_offset( + AtenTensorHandle tensor, + int64_t* ret_storage_offset); + +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_is_contiguous(AtenTensorHandle tensor, bool* ret_is_contiguous); + +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_is_defined(AtenTensorHandle tensor, bool* ret_is_defined); + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_new_tensor_handle( + AtenTensorHandle orig_handle, + AtenTensorHandle* new_handle); + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch__alloc_from_pool( + AtenTensorHandle self, + int64_t offset_bytes, + int32_t dtype, + int64_t ndim, + const int64_t* sizes_ptr, + const int64_t* strides_ptr, + AtenTensorHandle* ret_new_tensor); + +// This function will create a new tensor object and its pointer is returned +// through *out. The caller is responsible for wrapping the tensor pointer +// with RAIIAtenTensorHandle which will call aoti_torch_delete_tensor_object +// when going out of scope. +AOTI_TORCH_EXPORT AOTITorchError aoti_torch__reinterpret_tensor( + AtenTensorHandle self, + int64_t ndim, + const int64_t* sizes_ptr, + const int64_t* strides_ptr, + int64_t storage_offset, + AtenTensorHandle* ret_new_tensor // returns new reference +); + +// This function will create a new tensor object and its pointer is returned +// through *out. The caller is responsible for wrapping the tensor pointer +// with RAIIAtenTensorHandle which will call aoti_torch_delete_tensor_object +// when going out of scope. +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_empty_strided( + int64_t ndim, + const int64_t* sizes_ptr, + const int64_t* strides_ptr, + int32_t dtype, + int32_t device_type, + int32_t device_index, + AtenTensorHandle* ret_new_tensor // returns new reference +); + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_empty_strided_pinned( + int64_t ndim, + const int64_t* sizes_ptr, + const int64_t* strides_ptr, + int32_t dtype, + int32_t device_type, + int32_t device_index, + AtenTensorHandle* ret_new_tensor // returns new reference +); + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_as_strided( + AtenTensorHandle self, + const int64_t* sizes_ptr, + const int64_t* strides_ptr, + AtenTensorHandle* ret); + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_create_tensor_from_blob( + void* data, + int64_t ndim, + const int64_t* sizes_ptr, + const int64_t* strides_ptr, + int64_t storage_offset, + int32_t dtype, + int32_t device_type, + int32_t device_index, + AtenTensorHandle* ret // returns new reference +); + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_create_tensor_from_blob_v2( + void* data, + int64_t ndim, + const int64_t* sizes_ptr, + const int64_t* strides_ptr, + int64_t storage_offset, + int32_t dtype, + int32_t device_type, + int32_t device_index, + AtenTensorHandle* ret, // returns new reference + int32_t layout, + const uint8_t* opaque_metadata, + int64_t opaque_metadata_size); + +// This function will create a new uninitialized tensor object +// and its pointer is returned through *ret. +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_new_uninitialized_tensor(AtenTensorHandle* ret); + +// WARNING: This will be deprecated. Use aoti_torch_copy_ instead. +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_tensor_copy_(AtenTensorHandle src, AtenTensorHandle dst); + +// Make the tensor referred to by dst an alias for the tensor referred +// to by src. The two tensors must still be deleted with +// aoti_torch_delete_tensor separately (or not) as before the call. +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_assign_tensors(AtenTensorHandle src, AtenTensorHandle dst); + +// Make a shallow copy of the tensor referred to by src and assign +// it to the handle in the ret_dst. This is similar to the above +// aoti_torch_assign_tensors function, but creates and sets the +// ret_dst from within. +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_assign_tensors_out(AtenTensorHandle src, AtenTensorHandle* ret_dst); + +// This function will create a new tensor object and its pointer is returned +// through *ret. The caller is responsible for wrapping the tensor pointer +// with RAIIAtenTensorHandle which will call aoti_torch_delete_tensor_object +// when going out of scope. +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_clone(AtenTensorHandle self, AtenTensorHandle* ret); + +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_clone_preserve_strides(AtenTensorHandle self, AtenTensorHandle* ret); + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_copy_( + AtenTensorHandle self, + AtenTensorHandle src, + int32_t non_blocking); + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch__mm_plus_mm_out( + AtenTensorHandle out, + AtenTensorHandle a, + AtenTensorHandle b, + AtenTensorHandle c, + AtenTensorHandle d); + +// This will soon be deprecated after ao_quantization is complete. +// Please refrain from using this or increasing callsites. +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_cpu_wrapped_fbgemm_pack_gemm_matrix_fp16( + AtenTensorHandle weight, + AtenTensorHandle* out); + +// This will soon be deprecated after ao_quantization is complete. +// Please refrain from using this or increasing callsites. +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__wrapped_linear_prepack( + AtenTensorHandle weight, + AtenTensorHandle weight_scale, + AtenTensorHandle weight_zero_point, + AtenTensorHandle bias, + AtenTensorHandle* out); + +// This will soon be deprecated after ao_quantization is complete. +// Please refrain from using this or increasing callsites. +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_cpu_wrapped_fbgemm_linear_fp16_weight( + AtenTensorHandle input, + AtenTensorHandle weight, + AtenTensorHandle bias, // optional argument + int64_t out_channel, + AtenTensorHandle* out); + +// This will soon be deprecated after ao_quantization is complete. +// Please refrain from using this or increasing callsites. +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_cpu__wrapped_quantized_linear_prepacked( + AtenTensorHandle input, + AtenTensorHandle input_scale, + AtenTensorHandle input_zero_point, + AtenTensorHandle weight, + AtenTensorHandle out_scale, + AtenTensorHandle out_zeropoint, + int64_t out_channel, + AtenTensorHandle* out); + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_zero_(AtenTensorHandle self); + +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_check_inf_and_nan(const char* tensor_name, AtenTensorHandle tensor); + +struct AtenRecordFunctionOpaque; +using AtenRecordFunctionHandle = AtenRecordFunctionOpaque*; + +struct IValueMapOpaque; +using IValueMapHandle = IValueMapOpaque*; + +AOTI_TORCH_EXPORT AOTITorchError aoti_record_function_start( + const char* name, + IValueMapHandle kwargs, + const C10IValueHandle* inputs, + const uint64_t n_inputs, + AtenRecordFunctionHandle* guard); + +AOTI_TORCH_EXPORT AOTITorchError +aoti_record_function_end(AtenRecordFunctionHandle guard); + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_scatter_out( + AtenTensorHandle out, + AtenTensorHandle self, + int64_t dim, + AtenTensorHandle index, + AtenTensorHandle src); + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_scatter_reduce_out( + AtenTensorHandle out, + AtenTensorHandle self, + int64_t dim, + AtenTensorHandle index, + AtenTensorHandle src, + const char* reduce, + int32_t include_self); + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_index_put_out( + AtenTensorHandle out, + AtenTensorHandle self, + const AtenTensorHandle* indices, + const uint32_t num_indices, + const AtenTensorHandle values, + bool accumulate); + +AOTI_TORCH_EXPORT void aoti_torch_print_tensor_handle( + AtenTensorHandle self, + const char* msg); + +// When AOTI debug printer option is enabled, this function will be invoked to +// torch pickle save the intermediate tensor for debugging purpose. +AOTI_TORCH_EXPORT void aoti_torch_save_tensor_handle( + AtenTensorHandle self, + const char* tensor_name, + const char* launch_prefix, + const char* kernel_name); + +// helpers for converting between StableIValue and actual IValues +using StableIValue = uint64_t; + +class TorchLibraryOpaque; +using TorchLibraryHandle = TorchLibraryOpaque*; + +// stable corollary to torch::Library constructor with Kind::IMPL +// will create a new torch::Library object on the heap +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_library_init_impl( + const char* ns, + const char* k, + const char* file, + uint32_t line, + TorchLibraryHandle* ret_new_torch_lib); + +// stable corollary to torch::Library constructor with Kind::DEF +// will create a new torch::Library object on the heap +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_library_init_def( + const char* ns, + const char* file, + uint32_t line, + TorchLibraryHandle* ret_new_torch_lib); + +// stable corollary to torch::Library constructor with Kind::FRAGMENT +// will create a new torch::Library object on the heap +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_library_init_fragment( + const char* ns, + const char* file, + uint32_t line, + TorchLibraryHandle* ret_new_torch_lib); + +// stable corollary to torch::Library method m.impl(), should be +// called from StableLibrary +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_library_impl( + TorchLibraryHandle self, + const char* name, + void (*fn)(StableIValue*, uint64_t, uint64_t)); + +// stable corollary to torch::Library method m.def(), should be +// called from StableLibrary +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_library_def(TorchLibraryHandle self, const char* schema); + +// the above stable constructors for torch::Library add Library objects +// to the heap. if you are calling those functions directly, please use +// this function to free the Library's memory. The more user friendly +// alternative is to use StableLibrary, which will free its handle upon +// destruction +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_delete_library_object(TorchLibraryHandle tlh); + +// calls the op overload defined by a given opName, overloadName, and a +// stack of StableIValues. This call will populate any return values of the +// op into the stack in their StableIValue form, with ret0 at index 0, ret1 +// at index 1, and so on. +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_call_dispatcher( + const char* opName, + const char* overloadName, + StableIValue* stack); + +// Device-generic guard for managing device context +struct DeviceGuardOpaque; +using DeviceGuardHandle = DeviceGuardOpaque*; + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_create_device_guard( + int32_t device_index, + DeviceGuardHandle* ret_guard // returns new reference +); + +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_delete_device_guard(DeviceGuardHandle guard); + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_device_guard_set_index( + DeviceGuardHandle guard, + int32_t device_index); + +// Device-generic stream for managing stream objects +struct StreamOpaque; +using StreamHandle = StreamOpaque*; + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_delete_stream(StreamHandle stream); + +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_stream_id(StreamHandle stream, int64_t* ret_stream_id); + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_get_current_stream( + int32_t device_index, + StreamHandle* ret_stream // returns new reference +); + +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_get_current_device_index(int32_t* ret_device_index); + +#ifdef USE_CUDA + +struct CUDAGuardOpaque; +using CUDAGuardHandle = CUDAGuardOpaque*; + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_create_cuda_guard( + int32_t device_index, + CUDAGuardHandle* ret_guard // returns new reference +); + +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_delete_cuda_guard(CUDAGuardHandle guard); + +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_cuda_guard_set_index(CUDAGuardHandle guard, int32_t device_index); + +struct CUDAStreamGuardOpaque; +using CUDAStreamGuardHandle = CUDAStreamGuardOpaque*; + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_create_cuda_stream_guard( + void* stream, + int32_t device_index, + CUDAStreamGuardHandle* ret_guard // returns new reference +); + +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_delete_cuda_stream_guard(CUDAStreamGuardHandle guard); + +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_get_current_cuda_stream(int32_t device_index, void** ret_stream); + +// CUDA memory allocation using CUDACachingAllocator +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_caching_allocator_raw_alloc( + uint64_t nbytes, + void** ret_ptr // returns raw GPU memory pointer +); + +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_cuda_caching_allocator_raw_delete(void* ptr); + +#endif // USE_CUDA + +// See `ProxyExecutor Design Note` in ir.py for more details +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_proxy_executor_call_function( + AOTIProxyExecutorHandle proxy_executor, + int extern_node_index, + int num_ints, + int64_t* flatten_int_args, + int num_tensors, + AtenTensorHandle* flatten_tensor_args); + +AOTI_TORCH_EXPORT void aoti_torch_check( + bool cond, + const char* func, + const char* file, + uint32_t line, + const char* msg); + +#ifdef STRIP_ERROR_MESSAGES +#define AOTI_TORCH_CHECK(cond, ...) \ + if (!(cond)) { \ + aoti_torch_check( \ + false, \ + __func__, \ + __FILE__, \ + static_cast(__LINE__), \ + TORCH_CHECK_MSG(cond, "", __VA_ARGS__)); \ + } +#else +#define AOTI_TORCH_CHECK(cond, ...) \ + if (!(cond)) { \ + aoti_torch_check( \ + false, \ + __func__, \ + __FILE__, \ + static_cast(__LINE__), \ + TORCH_CHECK_MSG(cond, "", ##__VA_ARGS__)); \ + } +#endif + +AOTI_TORCH_EXPORT void aoti_torch_warn( + const char* func, + const char* file, + uint32_t line, + const char* msg); + +#ifdef DISABLE_WARN +#define AOTI_TORCH_WARN(...) ((void)0); +#else +#define AOTI_TORCH_WARN(...) \ + aoti_torch_warn( \ + __func__, __FILE__, static_cast(__LINE__), #__VA_ARGS__); +#endif + +#ifdef __cplusplus +} // extern "C" + +template +int32_t aoti_torch_dtype() = delete; + +#define DEFINE_DTYPE_SPECIALIZATION(ctype, typename) \ + template <> \ + inline int32_t aoti_torch_dtype() { \ + return aoti_torch_dtype_##typename(); \ + } + +DEFINE_DTYPE_SPECIALIZATION(c10::BFloat16, bfloat16) +DEFINE_DTYPE_SPECIALIZATION(c10::Half, float16) +DEFINE_DTYPE_SPECIALIZATION(c10::complex, complex64) +DEFINE_DTYPE_SPECIALIZATION(float, float32) +DEFINE_DTYPE_SPECIALIZATION(double, float64) +DEFINE_DTYPE_SPECIALIZATION(uint8_t, uint8) +DEFINE_DTYPE_SPECIALIZATION(int8_t, int8) +DEFINE_DTYPE_SPECIALIZATION(int16_t, int16) +DEFINE_DTYPE_SPECIALIZATION(int32_t, int32) +DEFINE_DTYPE_SPECIALIZATION(int64_t, int64) +DEFINE_DTYPE_SPECIALIZATION(bool, bool) + +#endif +#endif // AOTI_TORCH_SHIM diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/c/shim_cpu.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/c/shim_cpu.h new file mode 100644 index 0000000000000000000000000000000000000000..5a10290decd1db529a924a89596e17c8e6829dcc --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/c/shim_cpu.h @@ -0,0 +1,267 @@ +#ifndef AOTI_TORCH_SHIM_CPU +#define AOTI_TORCH_SHIM_CPU + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#if AT_MKLDNN_ENABLED() + +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_cpu_mkldnn__convolution_pointwise_binary( + AtenTensorHandle X, + AtenTensorHandle other, + AtenTensorHandle W, + AtenTensorHandle* B, + const int64_t* padding, + int64_t padding_len_, + const int64_t* stride, + int64_t stride_len_, + const int64_t* dilation, + int64_t dilation_len_, + int64_t groups, + const char* binary_attr, + double* alpha, + const char** unary_attr, + const double** unary_scalars, + int64_t unary_scalars_len_, + const char** unary_algorithm, + AtenTensorHandle* ret0); + +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_cpu_mkldnn__convolution_pointwise_binary_( + AtenTensorHandle other, + AtenTensorHandle X, + AtenTensorHandle W, + AtenTensorHandle* B, + const int64_t* padding, + int64_t padding_len_, + const int64_t* stride, + int64_t stride_len_, + const int64_t* dilation, + int64_t dilation_len_, + int64_t groups, + const char* binary_attr, + double* alpha, + const char** unary_attr, + const double** unary_scalars, + int64_t unary_scalars_len_, + const char** unary_algorithm, + AtenTensorHandle* ret0); + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_mkldnn__convolution_pointwise( + AtenTensorHandle X, + AtenTensorHandle W, + AtenTensorHandle* B, + const int64_t* padding, + int64_t padding_len_, + const int64_t* stride, + int64_t stride_len_, + const int64_t* dilation, + int64_t dilation_len_, + int64_t groups, + const char* attr, + const double** scalars, + int64_t scalars_len_, + const char** algorithm, + AtenTensorHandle* ret0); + +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_cpu_mkldnn__convolution_transpose_pointwise( + AtenTensorHandle X, + AtenTensorHandle W, + AtenTensorHandle* B, + const int64_t* padding, + int64_t padding_len_, + const int64_t* output_padding, + int64_t output_padding_len_, + const int64_t* stride, + int64_t stride_len_, + const int64_t* dilation, + int64_t dilation_len_, + int64_t groups, + const char* attr, + const double** scalars, + int64_t scalars_len_, + const char** algorithm, + AtenTensorHandle* ret0); + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_mkldnn_rnn_layer( + AtenTensorHandle input, + AtenTensorHandle weight0, + AtenTensorHandle weight1, + AtenTensorHandle weight2, + AtenTensorHandle weight3, + AtenTensorHandle hx_, + AtenTensorHandle cx_, + int32_t reverse, + const int64_t* batch_sizes, + int64_t batch_sizes_len_, + int64_t mode, + int64_t hidden_size, + int64_t num_layers, + int32_t has_biases, + int32_t bidirectional, + int32_t batch_first, + int32_t train, + AtenTensorHandle* ret0, + AtenTensorHandle* ret1, + AtenTensorHandle* ret2, + AtenTensorHandle* ret3); + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__linear_pointwise( + AtenTensorHandle X, + AtenTensorHandle W, + AtenTensorHandle* B, + const char* attr, + const double** scalars, + int64_t scalars_len_, + const char** algorithm, + AtenTensorHandle* ret0); + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__linear_pointwise_binary( + AtenTensorHandle X, + AtenTensorHandle other, + AtenTensorHandle W, + AtenTensorHandle* B, + const char* attr, + AtenTensorHandle* ret0); + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__qlinear_pointwise_tensor( + AtenTensorHandle X, + AtenTensorHandle act_scale, + AtenTensorHandle act_zero_point, + AtenTensorHandle onednn_weight, + AtenTensorHandle weight_scales, + AtenTensorHandle weight_zero_points, + AtenTensorHandle* B, + double output_scale, + int64_t output_zero_point, + const int32_t* output_dtype, + const char* post_op_name, + const double** post_op_args, + int64_t post_op_args_len_, + const char* post_op_algorithm, + AtenTensorHandle* ret0); + +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_cpu__qlinear_pointwise_binary_tensor( + AtenTensorHandle X, + AtenTensorHandle act_scale, + AtenTensorHandle act_zero_point, + AtenTensorHandle onednn_weight, + AtenTensorHandle weight_scales, + AtenTensorHandle weight_zero_points, + AtenTensorHandle* other, + AtenTensorHandle* B, + double output_scale, + int64_t output_zero_point, + const int32_t* output_dtype, + double other_scale, + int64_t other_zero_point, + const char* binary_post_op, + double binary_alpha, + const char* unary_post_op, + const double** unary_post_op_args, + int64_t unary_post_op_args_len_, + const char* unary_post_op_algorithm, + AtenTensorHandle* ret0); + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__qconv_pointwise_tensor( + AtenTensorHandle X, + AtenTensorHandle act_scale, + AtenTensorHandle act_zero_point, + AtenTensorHandle onednn_weight, + AtenTensorHandle weight_scales, + AtenTensorHandle weight_zero_points, + AtenTensorHandle* B, + const int64_t* stride, + int64_t stride_len_, + const int64_t* padding, + int64_t padding_len_, + const int64_t* dilation, + int64_t dilation_len_, + int64_t groups, + double output_scale, + int64_t output_zero_point, + const int32_t* output_dtype, + const char* attr, + const double** post_op_args, + int64_t post_op_args_len_, + const char** algorithm, + AtenTensorHandle* ret0); + +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_cpu__qconv2d_pointwise_binary_tensor( + AtenTensorHandle X, + AtenTensorHandle act_scale, + AtenTensorHandle act_zero_point, + AtenTensorHandle onednn_weight, + AtenTensorHandle weight_scales, + AtenTensorHandle weight_zero_points, + AtenTensorHandle accum, + AtenTensorHandle* B, + const int64_t* stride_args, + int64_t stride_len_, + const int64_t* padding_args, + int64_t padding_len_, + const int64_t* dilation_args, + int64_t dilation_len_, + int64_t groups, + double output_scale, + int64_t output_zero_point, + const int32_t* output_dtype, + double accum_scale, + int64_t accum_zero_point, + const char* binary_attr, + double* alpha, + const char** unary_attr, + const double** unary_scalars, + int64_t unary_scalars_len_, + const char** unary_algorithm, + AtenTensorHandle* ret0); + +#if AT_MKL_ENABLED() + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__mkl_linear( + AtenTensorHandle X, + AtenTensorHandle W, + AtenTensorHandle origin_W, + AtenTensorHandle* B, + int64_t prepack_batch_size, + AtenTensorHandle* ret0); + +#endif // AT_MKL_ENABLED + +#endif // AT_MKLDNN_ENABLED() + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__weight_int4pack_mm_cpu_tensor( + AtenTensorHandle X, + AtenTensorHandle w, + AtenTensorHandle qGroupSize, + AtenTensorHandle qScaleAndZeros, + AtenTensorHandle* ret0); + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__c10d_functional_all_reduce_( + AtenTensorHandle inp, + const char* reduce_op, + const char* group_name, + AtenTensorHandle* ret0); + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__c10d_functional_all_reduce( + AtenTensorHandle inp, + const char* reduce_op, + const char* group_name, + AtenTensorHandle* ret0); + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__c10d_functional_wait_tensor( + AtenTensorHandle inp, + AtenTensorHandle* ret0); + +#ifdef __cplusplus +} // extern "C" +#endif +#endif // AOTI_TORCH_SHIM_CPU diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/c/shim_deprecated.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/c/shim_deprecated.h new file mode 100644 index 0000000000000000000000000000000000000000..964db6b0076c97bcbaac3bf5a831b6b87cec54c3 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/c/shim_deprecated.h @@ -0,0 +1,199 @@ +#ifndef AOTI_TORCH_SHIM_DEPRECATED +#define AOTI_TORCH_SHIM_DEPRECATED + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +[[deprecated( + "aoti_torch__embedding_bag is deprecated and will be removed in future versions.")]] +AOTI_TORCH_EXPORT AOTITorchError aoti_torch__embedding_bag( + AtenTensorHandle weight, + AtenTensorHandle indices, + AtenTensorHandle offsets, + int32_t scale_grad_by_freq, + int32_t mode, + int32_t sparse, + AtenTensorHandle per_sample_weights, // optional argument + int32_t include_last_offset, + int32_t padding_idx, + AtenTensorHandle* ret0, // returns new reference + AtenTensorHandle* ret1, // returns new reference + AtenTensorHandle* ret2, // returns new reference + AtenTensorHandle* ret3 // returns new reference +); + +[[deprecated( + "aoti_torch__fft_c2c is deprecated and will be removed in future versions.")]] +AOTI_TORCH_EXPORT AOTITorchError aoti_torch__fft_c2c( + AtenTensorHandle self, + const int64_t* dim_ptr, + int64_t dim_size, + int64_t normalization, + int32_t forward, + AtenTensorHandle* ret // returns new reference +); + +[[deprecated( + "aoti_torch__scaled_mm is deprecated and will be removed in future versions.")]] +AOTI_TORCH_EXPORT AOTITorchError aoti_torch__scaled_mm( + AtenTensorHandle self, + AtenTensorHandle mat2, + AtenTensorHandle bias, + int32_t* out_dtype, + AtenTensorHandle scale_a, + AtenTensorHandle scale_b, + AtenTensorHandle scale_result, + int8_t use_fast_accum, + AtenTensorHandle* ret0, + AtenTensorHandle* ret1); + +[[deprecated( + "aoti_torch__scaled_mm_v2 is deprecated and will be removed in future versions.")]] +AOTI_TORCH_EXPORT AOTITorchError aoti_torch__scaled_mm_v2( + AtenTensorHandle self, + AtenTensorHandle mat2, + AtenTensorHandle scale_a, + AtenTensorHandle scale_b, + AtenTensorHandle bias, + AtenTensorHandle scale_result, + int32_t* out_dtype, + int8_t use_fast_accum, + AtenTensorHandle* ret0); + +[[deprecated( + "aoti_torch_addmm_out is deprecated and will be removed in future versions.")]] +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_addmm_out( + AtenTensorHandle out, + AtenTensorHandle self, + AtenTensorHandle mat1, + AtenTensorHandle mat2, + float beta, + float alpha); + +[[deprecated( + "aoti_torch_bmm is deprecated and will be removed in future versions.")]] +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_bmm_out( + AtenTensorHandle out, + AtenTensorHandle self, + AtenTensorHandle mat2); + +[[deprecated( + "aoti_torch_convolution is deprecated and will be removed in future versions.")]] +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_convolution( + AtenTensorHandle input, + AtenTensorHandle weight, + AtenTensorHandle bias, // optional argument + const int64_t* stride_ptr, + int64_t stride_size, + const int64_t* padding_ptr, + int64_t padding_size, + const int64_t* dilation_ptr, + int64_t dilation_size, + int transposed, + const int64_t* output_padding_ptr, + int64_t output_padding_size, + int64_t groups, + AtenTensorHandle* ret // returns new reference +); + +[[deprecated( + "aoti_torch_mm_out is deprecated and will be removed in future versions.")]] +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mm_out( + AtenTensorHandle out, + AtenTensorHandle self, + AtenTensorHandle mat2); + +[[deprecated( + "aoti_torch_nonzero is deprecated and will be removed in future versions.")]] +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_nonzero(AtenTensorHandle self, AtenTensorHandle* out); + +[[deprecated( + "aoti_torch_repeat_interleave_Tensor is deprecated and will be removed in future versions.")]] +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_repeat_interleave_Tensor( + AtenTensorHandle repeats, + int64_t* output_size, + AtenTensorHandle* out); + +[[deprecated( + "aoti_torch_view_as_real is deprecated and will be removed in future versions.")]] +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_view_as_real( + AtenTensorHandle self, + AtenTensorHandle* ret // returns new reference +); + +[[deprecated( + "aoti_torch_view_dtype is deprecated and will be removed in future versions.")]] +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_view_dtype( + AtenTensorHandle self, + int32_t dtype, + AtenTensorHandle* ret // returns new reference +); + +[[deprecated( + "aoti_torch__scaled_dot_product_flash_attention is deprecated and will be removed in future versions.")]] +AOTI_TORCH_EXPORT AOTITorchError aoti_torch__scaled_dot_product_flash_attention( + AtenTensorHandle query, + AtenTensorHandle key, + AtenTensorHandle value, + double dropout_p, + bool is_causal, + bool return_debug_mask, + double scale, + AtenTensorHandle* ret0, // returns new reference + AtenTensorHandle* ret1, // returns new reference + AtenTensorHandle* ret2, // returns new reference + AtenTensorHandle* ret3, // returns new reference + int64_t* ret4, + int64_t* ret5, + AtenTensorHandle* ret6, // returns new reference + AtenTensorHandle* ret7, // returns new reference + AtenTensorHandle* ret8 // returns new reference +); + +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch__scaled_dot_product_flash_attention_v2( + AtenTensorHandle query, + AtenTensorHandle key, + AtenTensorHandle value, + double dropout_p, + int is_causal, + int return_debug_mask, + double* scale, // optional argument + AtenTensorHandle* ret0, // returns new reference + AtenTensorHandle* ret1, // returns new reference + AtenTensorHandle* ret2, // returns new reference + AtenTensorHandle* ret3, // returns new reference + int64_t* ret4, + int64_t* ret5, + AtenTensorHandle* ret6, // returns new reference + AtenTensorHandle* ret7, // returns new reference + AtenTensorHandle* ret8 // returns new reference +); + +[[deprecated( + "aoti_torch__scaled_dot_product_efficient_attention is deprecated and will be removed in future versions.")]] +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch__scaled_dot_product_efficient_attention( + AtenTensorHandle query, + AtenTensorHandle key, + AtenTensorHandle value, + AtenTensorHandle attn_bias, // optional argument + int compute_log_sumexp, + double dropout_p, + int is_causal, + double* scale, // optional argument + AtenTensorHandle* ret0, // returns new reference + AtenTensorHandle* ret1, // returns new reference + AtenTensorHandle* ret2, // returns new reference + AtenTensorHandle* ret3 // returns new reference +); + +#ifdef __cplusplus +} // extern "C" + +#endif +#endif // AOTI_TORCH_SHIM_DEPRECATED diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/c/shim_mps.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/c/shim_mps.h new file mode 100644 index 0000000000000000000000000000000000000000..2ab0057805121c902c23e18386cb6121073ebe92 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/c/shim_mps.h @@ -0,0 +1,103 @@ +#ifndef AOTI_TORCH_SHIM_MPS +#define AOTI_TORCH_SHIM_MPS + +#include + +struct AOTIMetalKernelFunctionOpaque; +using AOTIMetalKernelFunctionHandle = AOTIMetalKernelFunctionOpaque*; + +struct AOTIMetalShaderLibraryOpaque; +using AOTIMetalShaderLibraryHandle = AOTIMetalShaderLibraryOpaque*; + +#ifdef __cplusplus +extern "C" { +#endif + +// MetalShaderLibrary functions +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_create_shader_library( + const char* metal_shader_source, + AOTIMetalShaderLibraryHandle* library_handle); + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_delete_shader_library( + AOTIMetalShaderLibraryHandle library_handle); + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_get_kernel_function( + AOTIMetalShaderLibraryHandle library_handle, + const char* kernel_name, + AOTIMetalKernelFunctionHandle* function_handle); + +// MetalKernelFunction functions +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_mps_start_encoding(AOTIMetalKernelFunctionHandle func); + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_set_arg_tensor( + AOTIMetalKernelFunctionHandle func, + unsigned idx, + AtenTensorHandle tensor); + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_set_arg_int( + AOTIMetalKernelFunctionHandle func, + unsigned idx, + int64_t val); + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_dispatch_single( + AOTIMetalKernelFunctionHandle func, + uint64_t length); + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_dispatch_single_with_group_size( + AOTIMetalKernelFunctionHandle func, + uint64_t length, + uint64_t group_size); + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_dispatch_array( + AOTIMetalKernelFunctionHandle func, + const uint64_t* length, + size_t length_size); + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_dispatch_array_with_group_size( + AOTIMetalKernelFunctionHandle func, + const uint64_t* length, + size_t length_size, + const uint64_t* group_size, + size_t group_size_size); + +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_mps_malloc(void** buffer, size_t num_bytes); + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_free(void* ptr); + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_memcpy( + void* buffer, + size_t constant_offset, + size_t bytes_read, + size_t data_size, + uint8_t* constants_start); + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_copy_buffer( + void* src_buffer, + void* dst_buffer, + size_t data_size, + size_t src_offset, + size_t dst_offset); + +// C callback function type for command block execution +typedef void (*aoti_torch_mps_command_block_callback_t)( + AOTIMetalKernelFunctionHandle func, + void* user_data); + +// Shared callback function for std::function trampoline +AOTI_TORCH_EXPORT void aoti_torch_mps_shared_callback( + AOTIMetalKernelFunctionHandle func, + void* user_data); + +// Pure C version using function pointer and user data for trampoline pattern +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_run_command_block( + AOTIMetalKernelFunctionHandle func, + aoti_torch_mps_command_block_callback_t callback, + void* user_data); + +#ifdef __cplusplus +} // extern "C" +#endif + +#endif // AOTI_TORCH_SHIM_MPS diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/c/shim_xpu.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/c/shim_xpu.h new file mode 100644 index 0000000000000000000000000000000000000000..c25fe6443c9485c1c4b82760b3ccd4012fa03802 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/c/shim_xpu.h @@ -0,0 +1,210 @@ +#ifndef AOTI_TORCH_SHIM_XPU +#define AOTI_TORCH_SHIM_XPU + +#include +#include + +#ifdef USE_XPU +#ifdef __cplusplus +extern "C" { +#endif + +struct XPUGuardOpaque; +using XPUGuardHandle = XPUGuardOpaque*; + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_create_xpu_guard( + int32_t device_index, + XPUGuardHandle* ret_guard // returns new reference +); + +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_delete_xpu_guard(XPUGuardHandle guard); + +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_xpu_guard_set_index(XPUGuardHandle guard, int32_t device_index); + +struct XPUStreamGuardOpaque; +using XPUStreamGuardHandle = XPUStreamGuardOpaque*; + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_create_xpu_stream_guard( + void* stream, + int32_t device_index, + XPUStreamGuardHandle* ret_guard // returns new reference +); + +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_delete_xpu_stream_guard(XPUStreamGuardHandle guard); + +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_get_current_xpu_stream(int32_t device_index, void** ret_stream); + +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_get_current_xpu_device(int32_t* device_index); + +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_set_current_xpu_device(const int32_t& device_index); + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_get_current_sycl_queue(void** ret); + +#if AT_MKLDNN_ENABLED() + +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_xpu_mkldnn__convolution_pointwise_binary( + AtenTensorHandle X, + AtenTensorHandle other, + AtenTensorHandle W, + AtenTensorHandle* B, + const int64_t* padding, + int64_t padding_len_, + const int64_t* stride, + int64_t stride_len_, + const int64_t* dilation, + int64_t dilation_len_, + int64_t groups, + const char* binary_attr, + double* alpha, + const char** unary_attr, + const double** unary_scalars, + int64_t unary_scalars_len_, + const char** unary_algorithm, + AtenTensorHandle* ret0); + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_mkldnn__convolution_pointwise( + AtenTensorHandle X, + AtenTensorHandle W, + AtenTensorHandle* B, + const int64_t* padding, + int64_t padding_len_, + const int64_t* stride, + int64_t stride_len_, + const int64_t* dilation, + int64_t dilation_len_, + int64_t groups, + const char* attr, + const double** scalars, + int64_t scalars_len_, + const char** algorithm, + AtenTensorHandle* ret0); + +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_xpu_mkldnn__convolution_pointwise_binary_( + AtenTensorHandle other, + AtenTensorHandle X, + AtenTensorHandle W, + AtenTensorHandle* B, + const int64_t* padding, + int64_t padding_len_, + const int64_t* stride, + int64_t stride_len_, + const int64_t* dilation, + int64_t dilation_len_, + int64_t groups, + const char* binary_attr, + double* alpha, + const char** unary_attr, + const double** unary_scalars, + int64_t unary_scalars_len_, + const char** unary_algorithm, + AtenTensorHandle* ret0); + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu__qlinear_pointwise_tensor( + AtenTensorHandle X, + AtenTensorHandle act_scale, + AtenTensorHandle act_zero_point, + AtenTensorHandle onednn_weight, + AtenTensorHandle weight_scales, + AtenTensorHandle weight_zero_points, + AtenTensorHandle* B, + double output_scale, + int64_t output_zero_point, + const int32_t* output_dtype, + const char* post_op_name, + const double** post_op_args, + int64_t post_op_args_len_, + const char* post_op_algorithm, + AtenTensorHandle* ret0); + +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_xpu__qlinear_pointwise_binary_tensor( + AtenTensorHandle X, + AtenTensorHandle act_scale, + AtenTensorHandle act_zero_point, + AtenTensorHandle onednn_weight, + AtenTensorHandle weight_scales, + AtenTensorHandle weight_zero_points, + AtenTensorHandle* other, + AtenTensorHandle* B, + double output_scale, + int64_t output_zero_point, + const int32_t* output_dtype, + double other_scale, + int64_t other_zero_point, + const char* binary_post_op, + double binary_alpha, + const char* unary_post_op, + const double** unary_post_op_args, + int64_t unary_post_op_args_len_, + const char* unary_post_op_algorithm, + AtenTensorHandle* ret0); + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu__qconv_pointwise_tensor( + AtenTensorHandle X, + AtenTensorHandle act_scale, + AtenTensorHandle act_zero_point, + AtenTensorHandle onednn_weight, + AtenTensorHandle weight_scales, + AtenTensorHandle weight_zero_points, + AtenTensorHandle* B, + const int64_t* stride, + int64_t stride_len_, + const int64_t* padding, + int64_t padding_len_, + const int64_t* dilation, + int64_t dilation_len_, + int64_t groups, + double output_scale, + int64_t output_zero_point, + const int32_t* output_dtype, + const char* attr, + const double** post_op_args, + int64_t post_op_args_len_, + const char** algorithm, + AtenTensorHandle* ret0); + +AOTI_TORCH_EXPORT AOTITorchError +aoti_torch_xpu__qconv2d_pointwise_binary_tensor( + AtenTensorHandle X, + AtenTensorHandle act_scale, + AtenTensorHandle act_zero_point, + AtenTensorHandle onednn_weight, + AtenTensorHandle weight_scales, + AtenTensorHandle weight_zero_points, + AtenTensorHandle accum, + AtenTensorHandle* B, + const int64_t* stride_args, + int64_t stride_len_, + const int64_t* padding_args, + int64_t padding_len_, + const int64_t* dilation_args, + int64_t dilation_len_, + int64_t groups, + double output_scale, + int64_t output_zero_point, + const int32_t* output_dtype, + double accum_scale, + int64_t accum_zero_point, + const char* binary_attr, + double* alpha, + const char** unary_attr, + const double** unary_scalars, + int64_t unary_scalars_len_, + const char** unary_algorithm, + AtenTensorHandle* ret0); + +#endif // AT_MKLDNN_ENABLED() +#ifdef __cplusplus +} // extern "C" +#endif + +#endif // USE_XPU +#endif // AOTI_TORCH_SHIM_XPU diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/generated/c_shim_aten.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/generated/c_shim_aten.h new file mode 100644 index 0000000000000000000000000000000000000000..96348d6a129be1c1be09b3e716edd6133315d840 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/generated/c_shim_aten.h @@ -0,0 +1,28 @@ + + +// WARNING: THIS FILE IS AUTOGENERATED BY torchgen. DO NOT MODIFY BY HAND. +// See https://github.com/pytorch/pytorch/blob/7e86a7c0155295539996e0cf422883571126073e/torchgen/gen.py#L2424-L2436 for details + +// This file corresponds to the aten_shimified_ops list in torchgen/aoti/fallback_ops.py + + +#pragma once + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_aten_amax(AtenTensorHandle self, const int64_t* dim, int64_t dim_len_, int32_t keepdim, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_aten_fill__Scalar(AtenTensorHandle self, double value); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_aten_full(const int64_t* size, int64_t size_len_, double fill_value, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_aten_narrow(AtenTensorHandle self, int64_t dim, int64_t start, int64_t length, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_aten_new_empty(AtenTensorHandle self, const int64_t* size, int64_t size_len_, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_aten_new_zeros(AtenTensorHandle self, const int64_t* size, int64_t size_len_, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_aten_pad(AtenTensorHandle self, const int64_t* pad, int64_t pad_len_, const char* mode, double* value, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_aten_subtract_Tensor(AtenTensorHandle self, AtenTensorHandle other, double alpha, AtenTensorHandle* ret0); + +#ifdef __cplusplus +} // extern "C" +#endif diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/generated/c_shim_cpu.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/generated/c_shim_cpu.h new file mode 100644 index 0000000000000000000000000000000000000000..aced2b2f539de1559cc86d76b9706d02e70d1e70 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/generated/c_shim_cpu.h @@ -0,0 +1,160 @@ + + +// WARNING: THIS FILE IS AUTOGENERATED BY torchgen. DO NOT MODIFY BY HAND. +// See https://github.com/pytorch/pytorch/blob/7e86a7c0155295539996e0cf422883571126073e/torchgen/gen.py#L2424-L2436 for details + +#pragma once + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__adaptive_avg_pool2d(AtenTensorHandle self, const int64_t* output_size, int64_t output_size_len_, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__adaptive_avg_pool2d_backward(AtenTensorHandle grad_output, AtenTensorHandle self, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__adaptive_avg_pool3d(AtenTensorHandle self, const int64_t* output_size, int64_t output_size_len_, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__adaptive_avg_pool3d_backward(AtenTensorHandle grad_output, AtenTensorHandle self, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__addmm_activation(AtenTensorHandle self, AtenTensorHandle mat1, AtenTensorHandle mat2, double beta, double alpha, int32_t use_gelu, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__cdist_backward(AtenTensorHandle grad, AtenTensorHandle x1, AtenTensorHandle x2, double p, AtenTensorHandle cdist, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__cdist_forward(AtenTensorHandle x1, AtenTensorHandle x2, double p, int64_t* compute_mode, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__dyn_quant_matmul_4bit(AtenTensorHandle inp, AtenTensorHandle packed_weights, int64_t block_size, int64_t in_features, int64_t out_features, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__dyn_quant_pack_4bit_weight(AtenTensorHandle weights, AtenTensorHandle scales_zeros, AtenTensorHandle* bias, int64_t block_size, int64_t in_features, int64_t out_features, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__efficientzerotensor(const int64_t* size, int64_t size_len_, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__embedding_bag(AtenTensorHandle weight, AtenTensorHandle indices, AtenTensorHandle offsets, int32_t scale_grad_by_freq, int64_t mode, int32_t sparse, AtenTensorHandle* per_sample_weights, int32_t include_last_offset, int64_t padding_idx, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2, AtenTensorHandle* ret3); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__embedding_bag_dense_backward(AtenTensorHandle grad, AtenTensorHandle indices, AtenTensorHandle offset2bag, AtenTensorHandle bag_size, AtenTensorHandle maximum_indices, int64_t num_weights, int32_t scale_grad_by_freq, int64_t mode, AtenTensorHandle* per_sample_weights, int64_t padding_idx, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__embedding_bag_forward_only(AtenTensorHandle weight, AtenTensorHandle indices, AtenTensorHandle offsets, int32_t scale_grad_by_freq, int64_t mode, int32_t sparse, AtenTensorHandle* per_sample_weights, int32_t include_last_offset, int64_t padding_idx, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2, AtenTensorHandle* ret3); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__embedding_bag_per_sample_weights_backward(AtenTensorHandle grad, AtenTensorHandle weight, AtenTensorHandle indices, AtenTensorHandle offsets, AtenTensorHandle offset2bag, int64_t mode, int64_t padding_idx, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__fft_c2c(AtenTensorHandle self, const int64_t* dim, int64_t dim_len_, int64_t normalization, int32_t forward, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__fft_r2c(AtenTensorHandle self, const int64_t* dim, int64_t dim_len_, int64_t normalization, int32_t onesided, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__fused_moving_avg_obs_fq_helper(AtenTensorHandle self, AtenTensorHandle observer_on, AtenTensorHandle fake_quant_on, AtenTensorHandle running_min, AtenTensorHandle running_max, AtenTensorHandle scale, AtenTensorHandle zero_point, double averaging_const, int64_t quant_min, int64_t quant_max, int64_t ch_axis, int32_t per_row_fake_quant, int32_t symmetric_quant, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__fused_moving_avg_obs_fq_helper_functional(AtenTensorHandle self, AtenTensorHandle observer_on, AtenTensorHandle fake_quant_on, AtenTensorHandle running_min, AtenTensorHandle running_max, AtenTensorHandle scale, AtenTensorHandle zero_point, double averaging_const, int64_t quant_min, int64_t quant_max, int64_t ch_axis, int32_t per_row_fake_quant, int32_t symmetric_quant, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2, AtenTensorHandle* ret3, AtenTensorHandle* ret4, AtenTensorHandle* ret5); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__fused_rms_norm(AtenTensorHandle input, const int64_t* normalized_shape, int64_t normalized_shape_len_, AtenTensorHandle* weight, double* eps, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__histogramdd_from_bin_cts(AtenTensorHandle self, const int64_t* bins, int64_t bins_len_, const double** range, int64_t range_len_, AtenTensorHandle* weight, int32_t density, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__int_mm_out(AtenTensorHandle out, AtenTensorHandle self, AtenTensorHandle mat2); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__pdist_backward(AtenTensorHandle grad, AtenTensorHandle self, double p, AtenTensorHandle pdist, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__pdist_forward(AtenTensorHandle self, double p, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__scaled_dot_product_flash_attention_for_cpu(AtenTensorHandle query, AtenTensorHandle key, AtenTensorHandle value, double dropout_p, int32_t is_causal, AtenTensorHandle* attn_mask, double* scale, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__scaled_dot_product_flash_attention_for_cpu_backward(AtenTensorHandle grad_out, AtenTensorHandle query, AtenTensorHandle key, AtenTensorHandle value, AtenTensorHandle out, AtenTensorHandle logsumexp, double dropout_p, int32_t is_causal, AtenTensorHandle* attn_mask, double* scale, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__scaled_dot_product_fused_attention_overrideable(AtenTensorHandle query, AtenTensorHandle key, AtenTensorHandle value, AtenTensorHandle* attn_bias, double dropout_p, int32_t is_causal, int32_t return_debug_mask, double* scale, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2, AtenTensorHandle* ret3, int64_t* ret4, int64_t* ret5, AtenTensorHandle* ret6, AtenTensorHandle* ret7, AtenTensorHandle* ret8); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__scaled_dot_product_fused_attention_overrideable_backward(AtenTensorHandle grad_out, AtenTensorHandle query, AtenTensorHandle key, AtenTensorHandle value, AtenTensorHandle attn_bias, const int32_t* grad_input_mask, int64_t grad_input_mask_len_, AtenTensorHandle out, AtenTensorHandle logsumexp, AtenTensorHandle cum_seq_q, AtenTensorHandle cum_seq_k, int64_t max_q, int64_t max_k, double dropout_p, int32_t is_causal, AtenTensorHandle philox_seed, AtenTensorHandle philox_offset, double* scale, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2, AtenTensorHandle* ret3); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__scaled_mm(AtenTensorHandle self, AtenTensorHandle mat2, AtenTensorHandle scale_a, AtenTensorHandle scale_b, AtenTensorHandle* bias, AtenTensorHandle* scale_result, int32_t* out_dtype, int32_t use_fast_accum, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__scaled_mm_out(AtenTensorHandle out, AtenTensorHandle self, AtenTensorHandle mat2, AtenTensorHandle scale_a, AtenTensorHandle scale_b, AtenTensorHandle* bias, AtenTensorHandle* scale_result, int32_t* out_dtype, int32_t use_fast_accum); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__segment_reduce_backward(AtenTensorHandle grad, AtenTensorHandle output, AtenTensorHandle data, const char* reduce, AtenTensorHandle* lengths, AtenTensorHandle* offsets, int64_t axis, double* initial, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__to_sparse(AtenTensorHandle self, int32_t* layout, const int64_t** blocksize, int64_t blocksize_len_, int64_t* dense_dim, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__trilinear(AtenTensorHandle i1, AtenTensorHandle i2, AtenTensorHandle i3, const int64_t* expand1, int64_t expand1_len_, const int64_t* expand2, int64_t expand2_len_, const int64_t* expand3, int64_t expand3_len_, const int64_t* sumdim, int64_t sumdim_len_, int64_t unroll_dim, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu__weight_int8pack_mm(AtenTensorHandle self, AtenTensorHandle mat2, AtenTensorHandle scales, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_abs(AtenTensorHandle self, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_adaptive_max_pool2d(AtenTensorHandle self, const int64_t* output_size, int64_t output_size_len_, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_adaptive_max_pool2d_backward(AtenTensorHandle grad_output, AtenTensorHandle self, AtenTensorHandle indices, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_adaptive_max_pool3d(AtenTensorHandle self, const int64_t* output_size, int64_t output_size_len_, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_adaptive_max_pool3d_backward(AtenTensorHandle grad_output, AtenTensorHandle self, AtenTensorHandle indices, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_add_Scalar(AtenTensorHandle self, double other, double alpha, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_add_Tensor(AtenTensorHandle self, AtenTensorHandle other, double alpha, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_addbmm(AtenTensorHandle self, AtenTensorHandle batch1, AtenTensorHandle batch2, double beta, double alpha, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_addmm_out(AtenTensorHandle out, AtenTensorHandle self, AtenTensorHandle mat1, AtenTensorHandle mat2, double beta, double alpha); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_addmv(AtenTensorHandle self, AtenTensorHandle mat, AtenTensorHandle vec, double beta, double alpha, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_angle(AtenTensorHandle self, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_avg_pool2d(AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, int32_t ceil_mode, int32_t count_include_pad, int64_t* divisor_override, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_avg_pool2d_backward(AtenTensorHandle grad_output, AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, int32_t ceil_mode, int32_t count_include_pad, int64_t* divisor_override, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_avg_pool3d(AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, int32_t ceil_mode, int32_t count_include_pad, int64_t* divisor_override, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_avg_pool3d_backward(AtenTensorHandle grad_output, AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, int32_t ceil_mode, int32_t count_include_pad, int64_t* divisor_override, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_baddbmm_out(AtenTensorHandle out, AtenTensorHandle self, AtenTensorHandle batch1, AtenTensorHandle batch2, double beta, double alpha); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_bernoulli__Tensor(AtenTensorHandle self, AtenTensorHandle p, AtenGeneratorHandle* generator); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_bernoulli__float(AtenTensorHandle self, double p, AtenGeneratorHandle* generator); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_bmm_out(AtenTensorHandle out, AtenTensorHandle self, AtenTensorHandle mat2); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_bucketize_Tensor(AtenTensorHandle self, AtenTensorHandle boundaries, int32_t out_int32, int32_t right, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_cat(const AtenTensorHandle* tensors, int64_t tensors_len_, int64_t dim, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_cholesky_inverse(AtenTensorHandle self, int32_t upper, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_cholesky_solve(AtenTensorHandle self, AtenTensorHandle input2, int32_t upper, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_convolution(AtenTensorHandle input, AtenTensorHandle weight, AtenTensorHandle* bias, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, const int64_t* dilation, int64_t dilation_len_, int32_t transposed, const int64_t* output_padding, int64_t output_padding_len_, int64_t groups, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_convolution_backward(AtenTensorHandle grad_output, AtenTensorHandle input, AtenTensorHandle weight, const int64_t** bias_sizes, int64_t bias_sizes_len_, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, const int64_t* dilation, int64_t dilation_len_, int32_t transposed, const int64_t* output_padding, int64_t output_padding_len_, int64_t groups, const int32_t* output_mask, int64_t output_mask_len_, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_cummax(AtenTensorHandle self, int64_t dim, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_cummin(AtenTensorHandle self, int64_t dim, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_cumprod(AtenTensorHandle self, int64_t dim, int32_t* dtype, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_cumsum(AtenTensorHandle self, int64_t dim, int32_t* dtype, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_exponential(AtenTensorHandle self, double lambd, AtenGeneratorHandle* generator, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_fill__Scalar(AtenTensorHandle self, double value); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_fractional_max_pool2d(AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* output_size, int64_t output_size_len_, AtenTensorHandle random_samples, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_fractional_max_pool2d_backward(AtenTensorHandle grad_output, AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* output_size, int64_t output_size_len_, AtenTensorHandle indices, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_fractional_max_pool3d(AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* output_size, int64_t output_size_len_, AtenTensorHandle random_samples, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_fractional_max_pool3d_backward(AtenTensorHandle grad_output, AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* output_size, int64_t output_size_len_, AtenTensorHandle indices, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_gcd(AtenTensorHandle self, AtenTensorHandle other, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_geqrf(AtenTensorHandle self, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_grid_sampler_2d_backward(AtenTensorHandle grad_output, AtenTensorHandle input, AtenTensorHandle grid, int64_t interpolation_mode, int64_t padding_mode, int32_t align_corners, const int32_t* output_mask, int64_t output_mask_len_, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_hann_window(int64_t window_length, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_histc(AtenTensorHandle self, int64_t bins, double min, double max, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_histogram_bin_ct(AtenTensorHandle self, int64_t bins, const double** range, int64_t range_len_, AtenTensorHandle* weight, int32_t density, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_index_Tensor(AtenTensorHandle self, const AtenTensorHandle** indices, int64_t indices_len_, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_index_put(AtenTensorHandle self, const AtenTensorHandle** indices, int64_t indices_len_, AtenTensorHandle values, int32_t accumulate, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_index_reduce(AtenTensorHandle self, int64_t dim, AtenTensorHandle index, AtenTensorHandle source, const char* reduce, int32_t include_self, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_kthvalue(AtenTensorHandle self, int64_t k, int64_t dim, int32_t keepdim, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_logcumsumexp(AtenTensorHandle self, int64_t dim, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_lu_unpack(AtenTensorHandle LU_data, AtenTensorHandle LU_pivots, int32_t unpack_data, int32_t unpack_pivots, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_masked_scatter(AtenTensorHandle self, AtenTensorHandle mask, AtenTensorHandle source, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_masked_scatter_backward(AtenTensorHandle grad_output, AtenTensorHandle mask, const int64_t* sizes, int64_t sizes_len_, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_masked_select(AtenTensorHandle self, AtenTensorHandle mask, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_max_pool2d_with_indices(AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, const int64_t* dilation, int64_t dilation_len_, int32_t ceil_mode, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_max_pool2d_with_indices_backward(AtenTensorHandle grad_output, AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, const int64_t* dilation, int64_t dilation_len_, int32_t ceil_mode, AtenTensorHandle indices, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_max_pool3d_with_indices(AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, const int64_t* dilation, int64_t dilation_len_, int32_t ceil_mode, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_max_pool3d_with_indices_backward(AtenTensorHandle grad_output, AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, const int64_t* dilation, int64_t dilation_len_, int32_t ceil_mode, AtenTensorHandle indices, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_max_unpool2d(AtenTensorHandle self, AtenTensorHandle indices, const int64_t* output_size, int64_t output_size_len_, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_max_unpool3d(AtenTensorHandle self, AtenTensorHandle indices, const int64_t* output_size, int64_t output_size_len_, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_median(AtenTensorHandle self, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_mm_out(AtenTensorHandle out, AtenTensorHandle self, AtenTensorHandle mat2); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_mode(AtenTensorHandle self, int64_t dim, int32_t keepdim, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_mul_Scalar(AtenTensorHandle self, double other, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_mul_Tensor(AtenTensorHandle self, AtenTensorHandle other, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_nanmedian(AtenTensorHandle self, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_narrow(AtenTensorHandle self, int64_t dim, int64_t start, int64_t length, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_native_dropout(AtenTensorHandle input, double p, int32_t* train, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_nonzero(AtenTensorHandle self, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_normal_functional(AtenTensorHandle self, double mean, double std, AtenGeneratorHandle* generator, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_ormqr(AtenTensorHandle self, AtenTensorHandle input2, AtenTensorHandle input3, int32_t left, int32_t transpose, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_pad(AtenTensorHandle self, const int64_t* pad, int64_t pad_len_, const char* mode, double* value, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_permute(AtenTensorHandle self, const int64_t* dims, int64_t dims_len_, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_polar(AtenTensorHandle abs, AtenTensorHandle angle, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_pow_Scalar(double self, AtenTensorHandle exponent, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_pow_Tensor_Scalar(AtenTensorHandle self, double exponent, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_pow_Tensor_Tensor(AtenTensorHandle self, AtenTensorHandle exponent, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_rand(const int64_t* size, int64_t size_len_, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_rand_generator(const int64_t* size, int64_t size_len_, AtenGeneratorHandle* generator, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_randint(int64_t high, const int64_t* size, int64_t size_len_, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_randint_generator(int64_t high, const int64_t* size, int64_t size_len_, AtenGeneratorHandle* generator, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_randint_low(int64_t low, int64_t high, const int64_t* size, int64_t size_len_, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_randint_low_out(AtenTensorHandle out, int64_t low, int64_t high, const int64_t* size, int64_t size_len_); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_randn(const int64_t* size, int64_t size_len_, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_randn_generator(const int64_t* size, int64_t size_len_, AtenGeneratorHandle* generator, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_randperm(int64_t n, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_repeat_interleave_Tensor(AtenTensorHandle repeats, int64_t* output_size, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_replication_pad1d_backward(AtenTensorHandle grad_output, AtenTensorHandle self, const int64_t* padding, int64_t padding_len_, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_replication_pad2d_backward(AtenTensorHandle grad_output, AtenTensorHandle self, const int64_t* padding, int64_t padding_len_, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_reshape(AtenTensorHandle self, const int64_t* shape, int64_t shape_len_, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_resize_(AtenTensorHandle self, const int64_t* size, int64_t size_len_, int32_t* memory_format); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_resize_as_(AtenTensorHandle self, AtenTensorHandle the_template, int32_t* memory_format); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_scatter_src_out(AtenTensorHandle out, AtenTensorHandle self, int64_t dim, AtenTensorHandle index, AtenTensorHandle src); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_scatter_value_out(AtenTensorHandle out, AtenTensorHandle self, int64_t dim, AtenTensorHandle index, double value); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_scatter_reduce_two_out(AtenTensorHandle out, AtenTensorHandle self, int64_t dim, AtenTensorHandle index, AtenTensorHandle src, const char* reduce, int32_t include_self); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_searchsorted_Scalar(AtenTensorHandle sorted_sequence, double self, int32_t out_int32, int32_t right, const char** side, AtenTensorHandle* sorter, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_searchsorted_Tensor(AtenTensorHandle sorted_sequence, AtenTensorHandle self, int32_t out_int32, int32_t right, const char** side, AtenTensorHandle* sorter, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_segment_reduce(AtenTensorHandle data, const char* reduce, AtenTensorHandle* lengths, AtenTensorHandle* indices, AtenTensorHandle* offsets, int64_t axis, int32_t unsafe, double* initial, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_set__source_Tensor(AtenTensorHandle self, AtenTensorHandle source); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_slice_Tensor(AtenTensorHandle self, int64_t dim, int64_t* start, int64_t* end, int64_t step, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_soft_margin_loss_backward(AtenTensorHandle grad_output, AtenTensorHandle self, AtenTensorHandle target, int64_t reduction, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_sort(AtenTensorHandle self, int64_t dim, int32_t descending, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_sort_stable(AtenTensorHandle self, int32_t* stable, int64_t dim, int32_t descending, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_squeeze_dim(AtenTensorHandle self, int64_t dim, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_to_sparse(AtenTensorHandle self, int32_t* layout, const int64_t** blocksize, int64_t blocksize_len_, int64_t* dense_dim, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_topk(AtenTensorHandle self, int64_t k, int64_t dim, int32_t largest, int32_t sorted, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_triangular_solve(AtenTensorHandle self, AtenTensorHandle A, int32_t upper, int32_t transpose, int32_t unitriangular, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_uniform(AtenTensorHandle self, double from, double to, AtenGeneratorHandle* generator, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_upsample_bicubic2d_backward(AtenTensorHandle grad_output, const int64_t* output_size, int64_t output_size_len_, const int64_t* input_size, int64_t input_size_len_, int32_t align_corners, double* scales_h, double* scales_w, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_upsample_linear1d_backward(AtenTensorHandle grad_output, const int64_t* output_size, int64_t output_size_len_, const int64_t* input_size, int64_t input_size_len_, int32_t align_corners, double* scales, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_upsample_trilinear3d_backward(AtenTensorHandle grad_output, const int64_t* output_size, int64_t output_size_len_, const int64_t* input_size, int64_t input_size_len_, int32_t align_corners, double* scales_d, double* scales_h, double* scales_w, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_view_dtype(AtenTensorHandle self, int32_t dtype, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_view_as_complex(AtenTensorHandle self, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cpu_view_as_real(AtenTensorHandle self, AtenTensorHandle* ret0); + +#ifdef __cplusplus +} // extern "C" +#endif diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/generated/c_shim_cuda.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/generated/c_shim_cuda.h new file mode 100644 index 0000000000000000000000000000000000000000..c41487ae6dd8950ea240426196472c9a3a2c76f5 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/generated/c_shim_cuda.h @@ -0,0 +1,168 @@ + + +// WARNING: THIS FILE IS AUTOGENERATED BY torchgen. DO NOT MODIFY BY HAND. +// See https://github.com/pytorch/pytorch/blob/7e86a7c0155295539996e0cf422883571126073e/torchgen/gen.py#L2424-L2436 for details + +#pragma once + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__adaptive_avg_pool2d(AtenTensorHandle self, const int64_t* output_size, int64_t output_size_len_, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__adaptive_avg_pool2d_backward(AtenTensorHandle grad_output, AtenTensorHandle self, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__adaptive_avg_pool3d(AtenTensorHandle self, const int64_t* output_size, int64_t output_size_len_, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__adaptive_avg_pool3d_backward(AtenTensorHandle grad_output, AtenTensorHandle self, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__addmm_activation(AtenTensorHandle self, AtenTensorHandle mat1, AtenTensorHandle mat2, double beta, double alpha, int32_t use_gelu, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__cdist_backward(AtenTensorHandle grad, AtenTensorHandle x1, AtenTensorHandle x2, double p, AtenTensorHandle cdist, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__cdist_forward(AtenTensorHandle x1, AtenTensorHandle x2, double p, int64_t* compute_mode, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__cudnn_rnn(AtenTensorHandle input, const AtenTensorHandle* weight, int64_t weight_len_, int64_t weight_stride0, AtenTensorHandle* weight_buf, AtenTensorHandle hx, AtenTensorHandle* cx, int64_t mode, int64_t hidden_size, int64_t proj_size, int64_t num_layers, int32_t batch_first, double dropout, int32_t train, int32_t bidirectional, const int64_t* batch_sizes, int64_t batch_sizes_len_, AtenTensorHandle* dropout_state, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2, AtenTensorHandle* ret3, AtenTensorHandle* ret4); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__efficient_attention_backward(AtenTensorHandle grad_out_, AtenTensorHandle query, AtenTensorHandle key, AtenTensorHandle value, AtenTensorHandle* bias, AtenTensorHandle out, AtenTensorHandle* cu_seqlens_q, AtenTensorHandle* cu_seqlens_k, int64_t max_seqlen_q, int64_t max_seqlen_k, AtenTensorHandle logsumexp, double dropout_p, AtenTensorHandle philox_seed, AtenTensorHandle philox_offset, int64_t custom_mask_type, int32_t bias_requires_grad, double* scale, int64_t* num_splits_key, int64_t* window_size, int32_t shared_storage_dqdkdv, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2, AtenTensorHandle* ret3); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__efficient_attention_forward(AtenTensorHandle query, AtenTensorHandle key, AtenTensorHandle value, AtenTensorHandle* bias, AtenTensorHandle* cu_seqlens_q, AtenTensorHandle* cu_seqlens_k, int64_t* max_seqlen_q, int64_t* max_seqlen_k, double dropout_p, int64_t custom_mask_type, int32_t compute_log_sumexp, double* scale, AtenTensorHandle* seqlen_k, int64_t* window_size, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2, AtenTensorHandle* ret3, int64_t* ret4, int64_t* ret5); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__efficientzerotensor(const int64_t* size, int64_t size_len_, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__embedding_bag(AtenTensorHandle weight, AtenTensorHandle indices, AtenTensorHandle offsets, int32_t scale_grad_by_freq, int64_t mode, int32_t sparse, AtenTensorHandle* per_sample_weights, int32_t include_last_offset, int64_t padding_idx, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2, AtenTensorHandle* ret3); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__embedding_bag_dense_backward(AtenTensorHandle grad, AtenTensorHandle indices, AtenTensorHandle offset2bag, AtenTensorHandle bag_size, AtenTensorHandle maximum_indices, int64_t num_weights, int32_t scale_grad_by_freq, int64_t mode, AtenTensorHandle* per_sample_weights, int64_t padding_idx, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__embedding_bag_forward_only(AtenTensorHandle weight, AtenTensorHandle indices, AtenTensorHandle offsets, int32_t scale_grad_by_freq, int64_t mode, int32_t sparse, AtenTensorHandle* per_sample_weights, int32_t include_last_offset, int64_t padding_idx, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2, AtenTensorHandle* ret3); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__embedding_bag_per_sample_weights_backward(AtenTensorHandle grad, AtenTensorHandle weight, AtenTensorHandle indices, AtenTensorHandle offsets, AtenTensorHandle offset2bag, int64_t mode, int64_t padding_idx, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__fft_c2c(AtenTensorHandle self, const int64_t* dim, int64_t dim_len_, int64_t normalization, int32_t forward, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__fft_r2c(AtenTensorHandle self, const int64_t* dim, int64_t dim_len_, int64_t normalization, int32_t onesided, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__flash_attention_backward(AtenTensorHandle grad_out, AtenTensorHandle query, AtenTensorHandle key, AtenTensorHandle value, AtenTensorHandle out, AtenTensorHandle logsumexp, AtenTensorHandle cum_seq_q, AtenTensorHandle cum_seq_k, int64_t max_q, int64_t max_k, double dropout_p, int32_t is_causal, AtenTensorHandle rng_state, AtenTensorHandle unused, double* scale, int64_t* window_size_left, int64_t* window_size_right, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__flash_attention_forward(AtenTensorHandle query, AtenTensorHandle key, AtenTensorHandle value, AtenTensorHandle* cum_seq_q, AtenTensorHandle* cum_seq_k, int64_t max_q, int64_t max_k, double dropout_p, int32_t is_causal, int32_t return_debug_mask, double* scale, int64_t* window_size_left, int64_t* window_size_right, AtenTensorHandle* seqused_k, AtenTensorHandle* alibi_slopes, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2, AtenTensorHandle* ret3, AtenTensorHandle* ret4); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__fused_moving_avg_obs_fq_helper(AtenTensorHandle self, AtenTensorHandle observer_on, AtenTensorHandle fake_quant_on, AtenTensorHandle running_min, AtenTensorHandle running_max, AtenTensorHandle scale, AtenTensorHandle zero_point, double averaging_const, int64_t quant_min, int64_t quant_max, int64_t ch_axis, int32_t per_row_fake_quant, int32_t symmetric_quant, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__fused_moving_avg_obs_fq_helper_functional(AtenTensorHandle self, AtenTensorHandle observer_on, AtenTensorHandle fake_quant_on, AtenTensorHandle running_min, AtenTensorHandle running_max, AtenTensorHandle scale, AtenTensorHandle zero_point, double averaging_const, int64_t quant_min, int64_t quant_max, int64_t ch_axis, int32_t per_row_fake_quant, int32_t symmetric_quant, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2, AtenTensorHandle* ret3, AtenTensorHandle* ret4, AtenTensorHandle* ret5); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__fused_rms_norm(AtenTensorHandle input, const int64_t* normalized_shape, int64_t normalized_shape_len_, AtenTensorHandle* weight, double* eps, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__int_mm_out(AtenTensorHandle out, AtenTensorHandle self, AtenTensorHandle mat2); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__pdist_backward(AtenTensorHandle grad, AtenTensorHandle self, double p, AtenTensorHandle pdist, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__pdist_forward(AtenTensorHandle self, double p, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__scaled_dot_product_cudnn_attention(AtenTensorHandle query, AtenTensorHandle key, AtenTensorHandle value, AtenTensorHandle* attn_bias, int32_t compute_log_sumexp, double dropout_p, int32_t is_causal, int32_t return_debug_mask, double* scale, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2, AtenTensorHandle* ret3, int64_t* ret4, int64_t* ret5, AtenTensorHandle* ret6, AtenTensorHandle* ret7, AtenTensorHandle* ret8); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__scaled_dot_product_cudnn_attention_backward(AtenTensorHandle grad_out, AtenTensorHandle query, AtenTensorHandle key, AtenTensorHandle value, AtenTensorHandle out, AtenTensorHandle logsumexp, AtenTensorHandle philox_seed, AtenTensorHandle philox_offset, AtenTensorHandle attn_bias, AtenTensorHandle cum_seq_q, AtenTensorHandle cum_seq_k, int64_t max_q, int64_t max_k, double dropout_p, int32_t is_causal, double* scale, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__scaled_dot_product_efficient_attention(AtenTensorHandle query, AtenTensorHandle key, AtenTensorHandle value, AtenTensorHandle* attn_bias, int32_t compute_log_sumexp, double dropout_p, int32_t is_causal, double* scale, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2, AtenTensorHandle* ret3); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__scaled_dot_product_efficient_attention_backward(AtenTensorHandle grad_out_, AtenTensorHandle query, AtenTensorHandle key, AtenTensorHandle value, AtenTensorHandle attn_bias, AtenTensorHandle out, AtenTensorHandle logsumexp, AtenTensorHandle philox_seed, AtenTensorHandle philox_offset, double dropout_p, const int32_t* grad_input_mask, int64_t grad_input_mask_len_, int32_t is_causal, double* scale, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2, AtenTensorHandle* ret3); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__scaled_dot_product_flash_attention(AtenTensorHandle query, AtenTensorHandle key, AtenTensorHandle value, double dropout_p, int32_t is_causal, int32_t return_debug_mask, double* scale, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2, AtenTensorHandle* ret3, int64_t* ret4, int64_t* ret5, AtenTensorHandle* ret6, AtenTensorHandle* ret7, AtenTensorHandle* ret8); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__scaled_dot_product_flash_attention_backward(AtenTensorHandle grad_out, AtenTensorHandle query, AtenTensorHandle key, AtenTensorHandle value, AtenTensorHandle out, AtenTensorHandle logsumexp, AtenTensorHandle cum_seq_q, AtenTensorHandle cum_seq_k, int64_t max_q, int64_t max_k, double dropout_p, int32_t is_causal, AtenTensorHandle philox_seed, AtenTensorHandle philox_offset, double* scale, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__scaled_dot_product_fused_attention_overrideable(AtenTensorHandle query, AtenTensorHandle key, AtenTensorHandle value, AtenTensorHandle* attn_bias, double dropout_p, int32_t is_causal, int32_t return_debug_mask, double* scale, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2, AtenTensorHandle* ret3, int64_t* ret4, int64_t* ret5, AtenTensorHandle* ret6, AtenTensorHandle* ret7, AtenTensorHandle* ret8); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__scaled_dot_product_fused_attention_overrideable_backward(AtenTensorHandle grad_out, AtenTensorHandle query, AtenTensorHandle key, AtenTensorHandle value, AtenTensorHandle attn_bias, const int32_t* grad_input_mask, int64_t grad_input_mask_len_, AtenTensorHandle out, AtenTensorHandle logsumexp, AtenTensorHandle cum_seq_q, AtenTensorHandle cum_seq_k, int64_t max_q, int64_t max_k, double dropout_p, int32_t is_causal, AtenTensorHandle philox_seed, AtenTensorHandle philox_offset, double* scale, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2, AtenTensorHandle* ret3); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__scaled_grouped_mm(AtenTensorHandle self, AtenTensorHandle mat2, AtenTensorHandle scale_a, AtenTensorHandle scale_b, AtenTensorHandle* offs, AtenTensorHandle* bias, AtenTensorHandle* scale_result, int32_t* out_dtype, int32_t use_fast_accum, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__scaled_mm(AtenTensorHandle self, AtenTensorHandle mat2, AtenTensorHandle scale_a, AtenTensorHandle scale_b, AtenTensorHandle* bias, AtenTensorHandle* scale_result, int32_t* out_dtype, int32_t use_fast_accum, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__scaled_mm_out(AtenTensorHandle out, AtenTensorHandle self, AtenTensorHandle mat2, AtenTensorHandle scale_a, AtenTensorHandle scale_b, AtenTensorHandle* bias, AtenTensorHandle* scale_result, int32_t* out_dtype, int32_t use_fast_accum); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__segment_reduce_backward(AtenTensorHandle grad, AtenTensorHandle output, AtenTensorHandle data, const char* reduce, AtenTensorHandle* lengths, AtenTensorHandle* offsets, int64_t axis, double* initial, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__thnn_fused_lstm_cell(AtenTensorHandle input_gates, AtenTensorHandle hidden_gates, AtenTensorHandle cx, AtenTensorHandle* input_bias, AtenTensorHandle* hidden_bias, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__to_sparse(AtenTensorHandle self, int32_t* layout, const int64_t** blocksize, int64_t blocksize_len_, int64_t* dense_dim, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__trilinear(AtenTensorHandle i1, AtenTensorHandle i2, AtenTensorHandle i3, const int64_t* expand1, int64_t expand1_len_, const int64_t* expand2, int64_t expand2_len_, const int64_t* expand3, int64_t expand3_len_, const int64_t* sumdim, int64_t sumdim_len_, int64_t unroll_dim, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__weight_int4pack_mm(AtenTensorHandle self, AtenTensorHandle mat2, int64_t qGroupSize, AtenTensorHandle qScaleAndZeros, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda__weight_int8pack_mm(AtenTensorHandle self, AtenTensorHandle mat2, AtenTensorHandle scales, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_abs(AtenTensorHandle self, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_adaptive_max_pool2d(AtenTensorHandle self, const int64_t* output_size, int64_t output_size_len_, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_adaptive_max_pool2d_backward(AtenTensorHandle grad_output, AtenTensorHandle self, AtenTensorHandle indices, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_adaptive_max_pool3d(AtenTensorHandle self, const int64_t* output_size, int64_t output_size_len_, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_adaptive_max_pool3d_backward(AtenTensorHandle grad_output, AtenTensorHandle self, AtenTensorHandle indices, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_add_Scalar(AtenTensorHandle self, double other, double alpha, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_add_Tensor(AtenTensorHandle self, AtenTensorHandle other, double alpha, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_addbmm(AtenTensorHandle self, AtenTensorHandle batch1, AtenTensorHandle batch2, double beta, double alpha, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_addmm_out(AtenTensorHandle out, AtenTensorHandle self, AtenTensorHandle mat1, AtenTensorHandle mat2, double beta, double alpha); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_addmv(AtenTensorHandle self, AtenTensorHandle mat, AtenTensorHandle vec, double beta, double alpha, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_angle(AtenTensorHandle self, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_avg_pool2d(AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, int32_t ceil_mode, int32_t count_include_pad, int64_t* divisor_override, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_avg_pool2d_backward(AtenTensorHandle grad_output, AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, int32_t ceil_mode, int32_t count_include_pad, int64_t* divisor_override, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_avg_pool3d(AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, int32_t ceil_mode, int32_t count_include_pad, int64_t* divisor_override, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_avg_pool3d_backward(AtenTensorHandle grad_output, AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, int32_t ceil_mode, int32_t count_include_pad, int64_t* divisor_override, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_baddbmm_out(AtenTensorHandle out, AtenTensorHandle self, AtenTensorHandle batch1, AtenTensorHandle batch2, double beta, double alpha); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_bernoulli__Tensor(AtenTensorHandle self, AtenTensorHandle p, AtenGeneratorHandle* generator); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_bernoulli__float(AtenTensorHandle self, double p, AtenGeneratorHandle* generator); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_bmm_out(AtenTensorHandle out, AtenTensorHandle self, AtenTensorHandle mat2); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_bucketize_Tensor(AtenTensorHandle self, AtenTensorHandle boundaries, int32_t out_int32, int32_t right, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_cat(const AtenTensorHandle* tensors, int64_t tensors_len_, int64_t dim, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_cholesky_inverse(AtenTensorHandle self, int32_t upper, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_cholesky_solve(AtenTensorHandle self, AtenTensorHandle input2, int32_t upper, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_convolution(AtenTensorHandle input, AtenTensorHandle weight, AtenTensorHandle* bias, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, const int64_t* dilation, int64_t dilation_len_, int32_t transposed, const int64_t* output_padding, int64_t output_padding_len_, int64_t groups, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_convolution_backward(AtenTensorHandle grad_output, AtenTensorHandle input, AtenTensorHandle weight, const int64_t** bias_sizes, int64_t bias_sizes_len_, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, const int64_t* dilation, int64_t dilation_len_, int32_t transposed, const int64_t* output_padding, int64_t output_padding_len_, int64_t groups, const int32_t* output_mask, int64_t output_mask_len_, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_cummax(AtenTensorHandle self, int64_t dim, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_cummin(AtenTensorHandle self, int64_t dim, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_cumprod(AtenTensorHandle self, int64_t dim, int32_t* dtype, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_cumsum(AtenTensorHandle self, int64_t dim, int32_t* dtype, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_exponential(AtenTensorHandle self, double lambd, AtenGeneratorHandle* generator, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_fill__Scalar(AtenTensorHandle self, double value); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_fractional_max_pool2d(AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* output_size, int64_t output_size_len_, AtenTensorHandle random_samples, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_fractional_max_pool2d_backward(AtenTensorHandle grad_output, AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* output_size, int64_t output_size_len_, AtenTensorHandle indices, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_fractional_max_pool3d(AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* output_size, int64_t output_size_len_, AtenTensorHandle random_samples, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_fractional_max_pool3d_backward(AtenTensorHandle grad_output, AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* output_size, int64_t output_size_len_, AtenTensorHandle indices, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_gcd(AtenTensorHandle self, AtenTensorHandle other, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_geqrf(AtenTensorHandle self, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_grid_sampler_2d_backward(AtenTensorHandle grad_output, AtenTensorHandle input, AtenTensorHandle grid, int64_t interpolation_mode, int64_t padding_mode, int32_t align_corners, const int32_t* output_mask, int64_t output_mask_len_, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_hann_window(int64_t window_length, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_histc(AtenTensorHandle self, int64_t bins, double min, double max, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_index_Tensor(AtenTensorHandle self, const AtenTensorHandle** indices, int64_t indices_len_, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_index_put(AtenTensorHandle self, const AtenTensorHandle** indices, int64_t indices_len_, AtenTensorHandle values, int32_t accumulate, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_index_reduce(AtenTensorHandle self, int64_t dim, AtenTensorHandle index, AtenTensorHandle source, const char* reduce, int32_t include_self, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_kthvalue(AtenTensorHandle self, int64_t k, int64_t dim, int32_t keepdim, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_logcumsumexp(AtenTensorHandle self, int64_t dim, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_lu_unpack(AtenTensorHandle LU_data, AtenTensorHandle LU_pivots, int32_t unpack_data, int32_t unpack_pivots, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_masked_scatter(AtenTensorHandle self, AtenTensorHandle mask, AtenTensorHandle source, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_masked_scatter_backward(AtenTensorHandle grad_output, AtenTensorHandle mask, const int64_t* sizes, int64_t sizes_len_, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_masked_select(AtenTensorHandle self, AtenTensorHandle mask, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_max_pool2d_with_indices(AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, const int64_t* dilation, int64_t dilation_len_, int32_t ceil_mode, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_max_pool2d_with_indices_backward(AtenTensorHandle grad_output, AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, const int64_t* dilation, int64_t dilation_len_, int32_t ceil_mode, AtenTensorHandle indices, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_max_pool3d_with_indices(AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, const int64_t* dilation, int64_t dilation_len_, int32_t ceil_mode, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_max_pool3d_with_indices_backward(AtenTensorHandle grad_output, AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, const int64_t* dilation, int64_t dilation_len_, int32_t ceil_mode, AtenTensorHandle indices, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_max_unpool2d(AtenTensorHandle self, AtenTensorHandle indices, const int64_t* output_size, int64_t output_size_len_, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_max_unpool3d(AtenTensorHandle self, AtenTensorHandle indices, const int64_t* output_size, int64_t output_size_len_, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_median(AtenTensorHandle self, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_mm_out(AtenTensorHandle out, AtenTensorHandle self, AtenTensorHandle mat2); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_mode(AtenTensorHandle self, int64_t dim, int32_t keepdim, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_mul_Scalar(AtenTensorHandle self, double other, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_mul_Tensor(AtenTensorHandle self, AtenTensorHandle other, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_nanmedian(AtenTensorHandle self, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_narrow(AtenTensorHandle self, int64_t dim, int64_t start, int64_t length, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_native_dropout(AtenTensorHandle input, double p, int32_t* train, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_nonzero(AtenTensorHandle self, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_normal_functional(AtenTensorHandle self, double mean, double std, AtenGeneratorHandle* generator, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_ormqr(AtenTensorHandle self, AtenTensorHandle input2, AtenTensorHandle input3, int32_t left, int32_t transpose, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_pad(AtenTensorHandle self, const int64_t* pad, int64_t pad_len_, const char* mode, double* value, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_permute(AtenTensorHandle self, const int64_t* dims, int64_t dims_len_, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_polar(AtenTensorHandle abs, AtenTensorHandle angle, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_pow_Scalar(double self, AtenTensorHandle exponent, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_pow_Tensor_Scalar(AtenTensorHandle self, double exponent, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_pow_Tensor_Tensor(AtenTensorHandle self, AtenTensorHandle exponent, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_rand(const int64_t* size, int64_t size_len_, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_rand_generator(const int64_t* size, int64_t size_len_, AtenGeneratorHandle* generator, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_randint(int64_t high, const int64_t* size, int64_t size_len_, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_randint_generator(int64_t high, const int64_t* size, int64_t size_len_, AtenGeneratorHandle* generator, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_randint_low(int64_t low, int64_t high, const int64_t* size, int64_t size_len_, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_randint_low_out(AtenTensorHandle out, int64_t low, int64_t high, const int64_t* size, int64_t size_len_); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_randn(const int64_t* size, int64_t size_len_, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_randn_generator(const int64_t* size, int64_t size_len_, AtenGeneratorHandle* generator, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_randperm(int64_t n, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_repeat_interleave_Tensor(AtenTensorHandle repeats, int64_t* output_size, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_replication_pad1d_backward(AtenTensorHandle grad_output, AtenTensorHandle self, const int64_t* padding, int64_t padding_len_, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_replication_pad2d_backward(AtenTensorHandle grad_output, AtenTensorHandle self, const int64_t* padding, int64_t padding_len_, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_reshape(AtenTensorHandle self, const int64_t* shape, int64_t shape_len_, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_resize_(AtenTensorHandle self, const int64_t* size, int64_t size_len_, int32_t* memory_format); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_resize_as_(AtenTensorHandle self, AtenTensorHandle the_template, int32_t* memory_format); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_scatter_src_out(AtenTensorHandle out, AtenTensorHandle self, int64_t dim, AtenTensorHandle index, AtenTensorHandle src); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_scatter_value_out(AtenTensorHandle out, AtenTensorHandle self, int64_t dim, AtenTensorHandle index, double value); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_scatter_reduce_two_out(AtenTensorHandle out, AtenTensorHandle self, int64_t dim, AtenTensorHandle index, AtenTensorHandle src, const char* reduce, int32_t include_self); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_searchsorted_Scalar(AtenTensorHandle sorted_sequence, double self, int32_t out_int32, int32_t right, const char** side, AtenTensorHandle* sorter, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_searchsorted_Tensor(AtenTensorHandle sorted_sequence, AtenTensorHandle self, int32_t out_int32, int32_t right, const char** side, AtenTensorHandle* sorter, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_segment_reduce(AtenTensorHandle data, const char* reduce, AtenTensorHandle* lengths, AtenTensorHandle* indices, AtenTensorHandle* offsets, int64_t axis, int32_t unsafe, double* initial, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_set__source_Tensor(AtenTensorHandle self, AtenTensorHandle source); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_slice_Tensor(AtenTensorHandle self, int64_t dim, int64_t* start, int64_t* end, int64_t step, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_soft_margin_loss_backward(AtenTensorHandle grad_output, AtenTensorHandle self, AtenTensorHandle target, int64_t reduction, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_sort(AtenTensorHandle self, int64_t dim, int32_t descending, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_sort_stable(AtenTensorHandle self, int32_t* stable, int64_t dim, int32_t descending, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_squeeze_dim(AtenTensorHandle self, int64_t dim, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_to_sparse(AtenTensorHandle self, int32_t* layout, const int64_t** blocksize, int64_t blocksize_len_, int64_t* dense_dim, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_topk(AtenTensorHandle self, int64_t k, int64_t dim, int32_t largest, int32_t sorted, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_triangular_solve(AtenTensorHandle self, AtenTensorHandle A, int32_t upper, int32_t transpose, int32_t unitriangular, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_uniform(AtenTensorHandle self, double from, double to, AtenGeneratorHandle* generator, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_upsample_bicubic2d_backward(AtenTensorHandle grad_output, const int64_t* output_size, int64_t output_size_len_, const int64_t* input_size, int64_t input_size_len_, int32_t align_corners, double* scales_h, double* scales_w, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_upsample_linear1d_backward(AtenTensorHandle grad_output, const int64_t* output_size, int64_t output_size_len_, const int64_t* input_size, int64_t input_size_len_, int32_t align_corners, double* scales, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_upsample_trilinear3d_backward(AtenTensorHandle grad_output, const int64_t* output_size, int64_t output_size_len_, const int64_t* input_size, int64_t input_size_len_, int32_t align_corners, double* scales_d, double* scales_h, double* scales_w, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_view_dtype(AtenTensorHandle self, int32_t dtype, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_view_as_complex(AtenTensorHandle self, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_cuda_view_as_real(AtenTensorHandle self, AtenTensorHandle* ret0); + +#ifdef __cplusplus +} // extern "C" +#endif diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/generated/c_shim_mps.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/generated/c_shim_mps.h new file mode 100644 index 0000000000000000000000000000000000000000..e075956e14d73112b4e1f46bdc1b769d94903693 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/generated/c_shim_mps.h @@ -0,0 +1,133 @@ + + +// WARNING: THIS FILE IS AUTOGENERATED BY torchgen. DO NOT MODIFY BY HAND. +// See https://github.com/pytorch/pytorch/blob/7e86a7c0155295539996e0cf422883571126073e/torchgen/gen.py#L2424-L2436 for details + +#pragma once + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps__adaptive_avg_pool2d(AtenTensorHandle self, const int64_t* output_size, int64_t output_size_len_, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps__adaptive_avg_pool2d_backward(AtenTensorHandle grad_output, AtenTensorHandle self, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps__cdist_forward(AtenTensorHandle x1, AtenTensorHandle x2, double p, int64_t* compute_mode, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps__efficientzerotensor(const int64_t* size, int64_t size_len_, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps__embedding_bag(AtenTensorHandle weight, AtenTensorHandle indices, AtenTensorHandle offsets, int32_t scale_grad_by_freq, int64_t mode, int32_t sparse, AtenTensorHandle* per_sample_weights, int32_t include_last_offset, int64_t padding_idx, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2, AtenTensorHandle* ret3); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps__embedding_bag_dense_backward(AtenTensorHandle grad, AtenTensorHandle indices, AtenTensorHandle offset2bag, AtenTensorHandle bag_size, AtenTensorHandle maximum_indices, int64_t num_weights, int32_t scale_grad_by_freq, int64_t mode, AtenTensorHandle* per_sample_weights, int64_t padding_idx, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps__embedding_bag_forward_only(AtenTensorHandle weight, AtenTensorHandle indices, AtenTensorHandle offsets, int32_t scale_grad_by_freq, int64_t mode, int32_t sparse, AtenTensorHandle* per_sample_weights, int32_t include_last_offset, int64_t padding_idx, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2, AtenTensorHandle* ret3); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps__embedding_bag_per_sample_weights_backward(AtenTensorHandle grad, AtenTensorHandle weight, AtenTensorHandle indices, AtenTensorHandle offsets, AtenTensorHandle offset2bag, int64_t mode, int64_t padding_idx, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps__fft_c2c(AtenTensorHandle self, const int64_t* dim, int64_t dim_len_, int64_t normalization, int32_t forward, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps__fft_r2c(AtenTensorHandle self, const int64_t* dim, int64_t dim_len_, int64_t normalization, int32_t onesided, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps__fused_moving_avg_obs_fq_helper_functional(AtenTensorHandle self, AtenTensorHandle observer_on, AtenTensorHandle fake_quant_on, AtenTensorHandle running_min, AtenTensorHandle running_max, AtenTensorHandle scale, AtenTensorHandle zero_point, double averaging_const, int64_t quant_min, int64_t quant_max, int64_t ch_axis, int32_t per_row_fake_quant, int32_t symmetric_quant, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2, AtenTensorHandle* ret3, AtenTensorHandle* ret4, AtenTensorHandle* ret5); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps__fused_rms_norm(AtenTensorHandle input, const int64_t* normalized_shape, int64_t normalized_shape_len_, AtenTensorHandle* weight, double* eps, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps__histogramdd_from_bin_cts(AtenTensorHandle self, const int64_t* bins, int64_t bins_len_, const double** range, int64_t range_len_, AtenTensorHandle* weight, int32_t density, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps__scaled_dot_product_attention_math_for_mps(AtenTensorHandle query, AtenTensorHandle key, AtenTensorHandle value, AtenTensorHandle* attn_mask, double dropout_p, int32_t is_causal, AtenTensorHandle* dropout_mask, double* scale, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps__scaled_dot_product_fused_attention_overrideable(AtenTensorHandle query, AtenTensorHandle key, AtenTensorHandle value, AtenTensorHandle* attn_bias, double dropout_p, int32_t is_causal, int32_t return_debug_mask, double* scale, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2, AtenTensorHandle* ret3, int64_t* ret4, int64_t* ret5, AtenTensorHandle* ret6, AtenTensorHandle* ret7, AtenTensorHandle* ret8); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps__scaled_dot_product_fused_attention_overrideable_backward(AtenTensorHandle grad_out, AtenTensorHandle query, AtenTensorHandle key, AtenTensorHandle value, AtenTensorHandle attn_bias, const int32_t* grad_input_mask, int64_t grad_input_mask_len_, AtenTensorHandle out, AtenTensorHandle logsumexp, AtenTensorHandle cum_seq_q, AtenTensorHandle cum_seq_k, int64_t max_q, int64_t max_k, double dropout_p, int32_t is_causal, AtenTensorHandle philox_seed, AtenTensorHandle philox_offset, double* scale, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2, AtenTensorHandle* ret3); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps__to_sparse(AtenTensorHandle self, int32_t* layout, const int64_t** blocksize, int64_t blocksize_len_, int64_t* dense_dim, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps__trilinear(AtenTensorHandle i1, AtenTensorHandle i2, AtenTensorHandle i3, const int64_t* expand1, int64_t expand1_len_, const int64_t* expand2, int64_t expand2_len_, const int64_t* expand3, int64_t expand3_len_, const int64_t* sumdim, int64_t sumdim_len_, int64_t unroll_dim, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps__weight_int4pack_mm(AtenTensorHandle self, AtenTensorHandle mat2, int64_t qGroupSize, AtenTensorHandle qScaleAndZeros, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps__weight_int8pack_mm(AtenTensorHandle self, AtenTensorHandle mat2, AtenTensorHandle scales, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_abs(AtenTensorHandle self, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_adaptive_max_pool2d(AtenTensorHandle self, const int64_t* output_size, int64_t output_size_len_, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_adaptive_max_pool2d_backward(AtenTensorHandle grad_output, AtenTensorHandle self, AtenTensorHandle indices, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_add_Scalar(AtenTensorHandle self, double other, double alpha, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_add_Tensor(AtenTensorHandle self, AtenTensorHandle other, double alpha, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_addbmm(AtenTensorHandle self, AtenTensorHandle batch1, AtenTensorHandle batch2, double beta, double alpha, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_addmm_out(AtenTensorHandle out, AtenTensorHandle self, AtenTensorHandle mat1, AtenTensorHandle mat2, double beta, double alpha); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_addmv(AtenTensorHandle self, AtenTensorHandle mat, AtenTensorHandle vec, double beta, double alpha, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_angle(AtenTensorHandle self, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_avg_pool2d(AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, int32_t ceil_mode, int32_t count_include_pad, int64_t* divisor_override, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_avg_pool2d_backward(AtenTensorHandle grad_output, AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, int32_t ceil_mode, int32_t count_include_pad, int64_t* divisor_override, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_avg_pool3d(AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, int32_t ceil_mode, int32_t count_include_pad, int64_t* divisor_override, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_avg_pool3d_backward(AtenTensorHandle grad_output, AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, int32_t ceil_mode, int32_t count_include_pad, int64_t* divisor_override, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_baddbmm_out(AtenTensorHandle out, AtenTensorHandle self, AtenTensorHandle batch1, AtenTensorHandle batch2, double beta, double alpha); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_bernoulli__Tensor(AtenTensorHandle self, AtenTensorHandle p, AtenGeneratorHandle* generator); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_bernoulli__float(AtenTensorHandle self, double p, AtenGeneratorHandle* generator); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_bmm_out(AtenTensorHandle out, AtenTensorHandle self, AtenTensorHandle mat2); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_bucketize_Tensor(AtenTensorHandle self, AtenTensorHandle boundaries, int32_t out_int32, int32_t right, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_cat(const AtenTensorHandle* tensors, int64_t tensors_len_, int64_t dim, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_cholesky_solve(AtenTensorHandle self, AtenTensorHandle input2, int32_t upper, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_convolution(AtenTensorHandle input, AtenTensorHandle weight, AtenTensorHandle* bias, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, const int64_t* dilation, int64_t dilation_len_, int32_t transposed, const int64_t* output_padding, int64_t output_padding_len_, int64_t groups, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_convolution_backward(AtenTensorHandle grad_output, AtenTensorHandle input, AtenTensorHandle weight, const int64_t** bias_sizes, int64_t bias_sizes_len_, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, const int64_t* dilation, int64_t dilation_len_, int32_t transposed, const int64_t* output_padding, int64_t output_padding_len_, int64_t groups, const int32_t* output_mask, int64_t output_mask_len_, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_cummax(AtenTensorHandle self, int64_t dim, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_cummin(AtenTensorHandle self, int64_t dim, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_cumprod(AtenTensorHandle self, int64_t dim, int32_t* dtype, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_cumsum(AtenTensorHandle self, int64_t dim, int32_t* dtype, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_exponential(AtenTensorHandle self, double lambd, AtenGeneratorHandle* generator, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_fill__Scalar(AtenTensorHandle self, double value); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_hann_window(int64_t window_length, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_histc(AtenTensorHandle self, int64_t bins, double min, double max, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_histogram_bin_ct(AtenTensorHandle self, int64_t bins, const double** range, int64_t range_len_, AtenTensorHandle* weight, int32_t density, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_index_Tensor(AtenTensorHandle self, const AtenTensorHandle** indices, int64_t indices_len_, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_index_put(AtenTensorHandle self, const AtenTensorHandle** indices, int64_t indices_len_, AtenTensorHandle values, int32_t accumulate, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_kthvalue(AtenTensorHandle self, int64_t k, int64_t dim, int32_t keepdim, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_logcumsumexp(AtenTensorHandle self, int64_t dim, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_lu_unpack(AtenTensorHandle LU_data, AtenTensorHandle LU_pivots, int32_t unpack_data, int32_t unpack_pivots, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_masked_scatter(AtenTensorHandle self, AtenTensorHandle mask, AtenTensorHandle source, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_masked_scatter_backward(AtenTensorHandle grad_output, AtenTensorHandle mask, const int64_t* sizes, int64_t sizes_len_, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_masked_select(AtenTensorHandle self, AtenTensorHandle mask, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_max_pool2d_with_indices(AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, const int64_t* dilation, int64_t dilation_len_, int32_t ceil_mode, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_max_pool2d_with_indices_backward(AtenTensorHandle grad_output, AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, const int64_t* dilation, int64_t dilation_len_, int32_t ceil_mode, AtenTensorHandle indices, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_max_pool3d_with_indices(AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, const int64_t* dilation, int64_t dilation_len_, int32_t ceil_mode, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_max_pool3d_with_indices_backward(AtenTensorHandle grad_output, AtenTensorHandle self, const int64_t* kernel_size, int64_t kernel_size_len_, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, const int64_t* dilation, int64_t dilation_len_, int32_t ceil_mode, AtenTensorHandle indices, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_max_unpool2d(AtenTensorHandle self, AtenTensorHandle indices, const int64_t* output_size, int64_t output_size_len_, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_max_unpool3d(AtenTensorHandle self, AtenTensorHandle indices, const int64_t* output_size, int64_t output_size_len_, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_median(AtenTensorHandle self, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_mm_out(AtenTensorHandle out, AtenTensorHandle self, AtenTensorHandle mat2); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_mul_Scalar(AtenTensorHandle self, double other, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_mul_Tensor(AtenTensorHandle self, AtenTensorHandle other, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_nanmedian(AtenTensorHandle self, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_narrow(AtenTensorHandle self, int64_t dim, int64_t start, int64_t length, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_native_dropout(AtenTensorHandle input, double p, int32_t* train, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_nonzero(AtenTensorHandle self, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_normal_functional(AtenTensorHandle self, double mean, double std, AtenGeneratorHandle* generator, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_pad(AtenTensorHandle self, const int64_t* pad, int64_t pad_len_, const char* mode, double* value, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_permute(AtenTensorHandle self, const int64_t* dims, int64_t dims_len_, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_polar(AtenTensorHandle abs, AtenTensorHandle angle, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_pow_Scalar(double self, AtenTensorHandle exponent, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_pow_Tensor_Scalar(AtenTensorHandle self, double exponent, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_pow_Tensor_Tensor(AtenTensorHandle self, AtenTensorHandle exponent, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_rand(const int64_t* size, int64_t size_len_, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_rand_generator(const int64_t* size, int64_t size_len_, AtenGeneratorHandle* generator, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_randint(int64_t high, const int64_t* size, int64_t size_len_, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_randint_generator(int64_t high, const int64_t* size, int64_t size_len_, AtenGeneratorHandle* generator, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_randint_low(int64_t low, int64_t high, const int64_t* size, int64_t size_len_, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_randint_low_out(AtenTensorHandle out, int64_t low, int64_t high, const int64_t* size, int64_t size_len_); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_randn(const int64_t* size, int64_t size_len_, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_randn_generator(const int64_t* size, int64_t size_len_, AtenGeneratorHandle* generator, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_randperm(int64_t n, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_repeat_interleave_Tensor(AtenTensorHandle repeats, int64_t* output_size, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_replication_pad1d_backward(AtenTensorHandle grad_output, AtenTensorHandle self, const int64_t* padding, int64_t padding_len_, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_replication_pad2d_backward(AtenTensorHandle grad_output, AtenTensorHandle self, const int64_t* padding, int64_t padding_len_, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_reshape(AtenTensorHandle self, const int64_t* shape, int64_t shape_len_, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_resize_(AtenTensorHandle self, const int64_t* size, int64_t size_len_, int32_t* memory_format); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_resize_as_(AtenTensorHandle self, AtenTensorHandle the_template, int32_t* memory_format); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_scatter_src_out(AtenTensorHandle out, AtenTensorHandle self, int64_t dim, AtenTensorHandle index, AtenTensorHandle src); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_scatter_value_out(AtenTensorHandle out, AtenTensorHandle self, int64_t dim, AtenTensorHandle index, double value); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_scatter_reduce_two_out(AtenTensorHandle out, AtenTensorHandle self, int64_t dim, AtenTensorHandle index, AtenTensorHandle src, const char* reduce, int32_t include_self); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_searchsorted_Scalar(AtenTensorHandle sorted_sequence, double self, int32_t out_int32, int32_t right, const char** side, AtenTensorHandle* sorter, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_searchsorted_Tensor(AtenTensorHandle sorted_sequence, AtenTensorHandle self, int32_t out_int32, int32_t right, const char** side, AtenTensorHandle* sorter, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_set__source_Tensor(AtenTensorHandle self, AtenTensorHandle source); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_slice_Tensor(AtenTensorHandle self, int64_t dim, int64_t* start, int64_t* end, int64_t step, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_soft_margin_loss_backward(AtenTensorHandle grad_output, AtenTensorHandle self, AtenTensorHandle target, int64_t reduction, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_sort(AtenTensorHandle self, int64_t dim, int32_t descending, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_sort_stable(AtenTensorHandle self, int32_t* stable, int64_t dim, int32_t descending, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_squeeze_dim(AtenTensorHandle self, int64_t dim, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_to_sparse(AtenTensorHandle self, int32_t* layout, const int64_t** blocksize, int64_t blocksize_len_, int64_t* dense_dim, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_topk(AtenTensorHandle self, int64_t k, int64_t dim, int32_t largest, int32_t sorted, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_triangular_solve(AtenTensorHandle self, AtenTensorHandle A, int32_t upper, int32_t transpose, int32_t unitriangular, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_uniform(AtenTensorHandle self, double from, double to, AtenGeneratorHandle* generator, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_upsample_bicubic2d_backward(AtenTensorHandle grad_output, const int64_t* output_size, int64_t output_size_len_, const int64_t* input_size, int64_t input_size_len_, int32_t align_corners, double* scales_h, double* scales_w, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_upsample_linear1d_backward(AtenTensorHandle grad_output, const int64_t* output_size, int64_t output_size_len_, const int64_t* input_size, int64_t input_size_len_, int32_t align_corners, double* scales, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_upsample_trilinear3d_backward(AtenTensorHandle grad_output, const int64_t* output_size, int64_t output_size_len_, const int64_t* input_size, int64_t input_size_len_, int32_t align_corners, double* scales_d, double* scales_h, double* scales_w, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_view_dtype(AtenTensorHandle self, int32_t dtype, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_view_as_complex(AtenTensorHandle self, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_mps_view_as_real(AtenTensorHandle self, AtenTensorHandle* ret0); + +#ifdef __cplusplus +} // extern "C" +#endif diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/generated/c_shim_xpu.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/generated/c_shim_xpu.h new file mode 100644 index 0000000000000000000000000000000000000000..49adef8de403168dc8e2a3cf30380c3115527089 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/generated/c_shim_xpu.h @@ -0,0 +1,74 @@ + + +// WARNING: THIS FILE IS AUTOGENERATED BY torchgen. DO NOT MODIFY BY HAND. +// See https://github.com/pytorch/pytorch/blob/7e86a7c0155295539996e0cf422883571126073e/torchgen/gen.py#L2424-L2436 for details + +#pragma once + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu__addmm_activation(AtenTensorHandle self, AtenTensorHandle mat1, AtenTensorHandle mat2, double beta, double alpha, int32_t use_gelu, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu__fused_moving_avg_obs_fq_helper_functional(AtenTensorHandle self, AtenTensorHandle observer_on, AtenTensorHandle fake_quant_on, AtenTensorHandle running_min, AtenTensorHandle running_max, AtenTensorHandle scale, AtenTensorHandle zero_point, double averaging_const, int64_t quant_min, int64_t quant_max, int64_t ch_axis, int32_t per_row_fake_quant, int32_t symmetric_quant, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2, AtenTensorHandle* ret3, AtenTensorHandle* ret4, AtenTensorHandle* ret5); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu__fused_rms_norm(AtenTensorHandle input, const int64_t* normalized_shape, int64_t normalized_shape_len_, AtenTensorHandle* weight, double* eps, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu__int_mm_out(AtenTensorHandle out, AtenTensorHandle self, AtenTensorHandle mat2); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu__scaled_dot_product_flash_attention(AtenTensorHandle query, AtenTensorHandle key, AtenTensorHandle value, double dropout_p, int32_t is_causal, int32_t return_debug_mask, double* scale, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2, AtenTensorHandle* ret3, int64_t* ret4, int64_t* ret5, AtenTensorHandle* ret6, AtenTensorHandle* ret7, AtenTensorHandle* ret8); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu__scaled_dot_product_flash_attention_backward(AtenTensorHandle grad_out, AtenTensorHandle query, AtenTensorHandle key, AtenTensorHandle value, AtenTensorHandle out, AtenTensorHandle logsumexp, AtenTensorHandle cum_seq_q, AtenTensorHandle cum_seq_k, int64_t max_q, int64_t max_k, double dropout_p, int32_t is_causal, AtenTensorHandle philox_seed, AtenTensorHandle philox_offset, double* scale, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu__scaled_dot_product_fused_attention_overrideable(AtenTensorHandle query, AtenTensorHandle key, AtenTensorHandle value, AtenTensorHandle* attn_bias, double dropout_p, int32_t is_causal, int32_t return_debug_mask, double* scale, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2, AtenTensorHandle* ret3, int64_t* ret4, int64_t* ret5, AtenTensorHandle* ret6, AtenTensorHandle* ret7, AtenTensorHandle* ret8); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu__scaled_dot_product_fused_attention_overrideable_backward(AtenTensorHandle grad_out, AtenTensorHandle query, AtenTensorHandle key, AtenTensorHandle value, AtenTensorHandle attn_bias, const int32_t* grad_input_mask, int64_t grad_input_mask_len_, AtenTensorHandle out, AtenTensorHandle logsumexp, AtenTensorHandle cum_seq_q, AtenTensorHandle cum_seq_k, int64_t max_q, int64_t max_k, double dropout_p, int32_t is_causal, AtenTensorHandle philox_seed, AtenTensorHandle philox_offset, double* scale, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2, AtenTensorHandle* ret3); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu__scaled_mm(AtenTensorHandle self, AtenTensorHandle mat2, AtenTensorHandle scale_a, AtenTensorHandle scale_b, AtenTensorHandle* bias, AtenTensorHandle* scale_result, int32_t* out_dtype, int32_t use_fast_accum, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu__scaled_mm_out(AtenTensorHandle out, AtenTensorHandle self, AtenTensorHandle mat2, AtenTensorHandle scale_a, AtenTensorHandle scale_b, AtenTensorHandle* bias, AtenTensorHandle* scale_result, int32_t* out_dtype, int32_t use_fast_accum); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu__trilinear(AtenTensorHandle i1, AtenTensorHandle i2, AtenTensorHandle i3, const int64_t* expand1, int64_t expand1_len_, const int64_t* expand2, int64_t expand2_len_, const int64_t* expand3, int64_t expand3_len_, const int64_t* sumdim, int64_t sumdim_len_, int64_t unroll_dim, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu__weight_int4pack_mm_with_scales_and_zeros(AtenTensorHandle self, AtenTensorHandle mat2, int64_t qGroupSize, AtenTensorHandle qScale, AtenTensorHandle qZeros, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu__weight_int8pack_mm(AtenTensorHandle self, AtenTensorHandle mat2, AtenTensorHandle scales, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_abs(AtenTensorHandle self, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_add_Scalar(AtenTensorHandle self, double other, double alpha, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_addbmm(AtenTensorHandle self, AtenTensorHandle batch1, AtenTensorHandle batch2, double beta, double alpha, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_addmm_out(AtenTensorHandle out, AtenTensorHandle self, AtenTensorHandle mat1, AtenTensorHandle mat2, double beta, double alpha); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_addmv(AtenTensorHandle self, AtenTensorHandle mat, AtenTensorHandle vec, double beta, double alpha, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_baddbmm_out(AtenTensorHandle out, AtenTensorHandle self, AtenTensorHandle batch1, AtenTensorHandle batch2, double beta, double alpha); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_bmm_out(AtenTensorHandle out, AtenTensorHandle self, AtenTensorHandle mat2); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_cholesky_solve(AtenTensorHandle self, AtenTensorHandle input2, int32_t upper, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_convolution(AtenTensorHandle input, AtenTensorHandle weight, AtenTensorHandle* bias, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, const int64_t* dilation, int64_t dilation_len_, int32_t transposed, const int64_t* output_padding, int64_t output_padding_len_, int64_t groups, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_convolution_backward(AtenTensorHandle grad_output, AtenTensorHandle input, AtenTensorHandle weight, const int64_t** bias_sizes, int64_t bias_sizes_len_, const int64_t* stride, int64_t stride_len_, const int64_t* padding, int64_t padding_len_, const int64_t* dilation, int64_t dilation_len_, int32_t transposed, const int64_t* output_padding, int64_t output_padding_len_, int64_t groups, const int32_t* output_mask, int64_t output_mask_len_, AtenTensorHandle* ret0, AtenTensorHandle* ret1, AtenTensorHandle* ret2); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_cummax(AtenTensorHandle self, int64_t dim, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_cummin(AtenTensorHandle self, int64_t dim, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_exponential(AtenTensorHandle self, double lambd, AtenGeneratorHandle* generator, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_hann_window(int64_t window_length, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_index_put(AtenTensorHandle self, const AtenTensorHandle** indices, int64_t indices_len_, AtenTensorHandle values, int32_t accumulate, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_kthvalue(AtenTensorHandle self, int64_t k, int64_t dim, int32_t keepdim, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_logcumsumexp(AtenTensorHandle self, int64_t dim, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_masked_scatter(AtenTensorHandle self, AtenTensorHandle mask, AtenTensorHandle source, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_masked_scatter_backward(AtenTensorHandle grad_output, AtenTensorHandle mask, const int64_t* sizes, int64_t sizes_len_, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_mm_out(AtenTensorHandle out, AtenTensorHandle self, AtenTensorHandle mat2); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_mul_Scalar(AtenTensorHandle self, double other, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_narrow(AtenTensorHandle self, int64_t dim, int64_t start, int64_t length, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_normal_functional(AtenTensorHandle self, double mean, double std, AtenGeneratorHandle* generator, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_pad(AtenTensorHandle self, const int64_t* pad, int64_t pad_len_, const char* mode, double* value, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_permute(AtenTensorHandle self, const int64_t* dims, int64_t dims_len_, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_polar(AtenTensorHandle abs, AtenTensorHandle angle, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_rand(const int64_t* size, int64_t size_len_, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_rand_generator(const int64_t* size, int64_t size_len_, AtenGeneratorHandle* generator, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_randint(int64_t high, const int64_t* size, int64_t size_len_, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_randint_generator(int64_t high, const int64_t* size, int64_t size_len_, AtenGeneratorHandle* generator, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_randint_low(int64_t low, int64_t high, const int64_t* size, int64_t size_len_, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_randint_low_out(AtenTensorHandle out, int64_t low, int64_t high, const int64_t* size, int64_t size_len_); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_randn(const int64_t* size, int64_t size_len_, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_randn_generator(const int64_t* size, int64_t size_len_, AtenGeneratorHandle* generator, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_randperm(int64_t n, int32_t* dtype, int32_t* layout, int32_t* device, int32_t device_index_, int32_t* pin_memory, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_reshape(AtenTensorHandle self, const int64_t* shape, int64_t shape_len_, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_resize_as_(AtenTensorHandle self, AtenTensorHandle the_template, int32_t* memory_format); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_slice_Tensor(AtenTensorHandle self, int64_t dim, int64_t* start, int64_t* end, int64_t step, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_soft_margin_loss_backward(AtenTensorHandle grad_output, AtenTensorHandle self, AtenTensorHandle target, int64_t reduction, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_sort(AtenTensorHandle self, int64_t dim, int32_t descending, AtenTensorHandle* ret0, AtenTensorHandle* ret1); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_squeeze_dim(AtenTensorHandle self, int64_t dim, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_to_sparse(AtenTensorHandle self, int32_t* layout, const int64_t** blocksize, int64_t blocksize_len_, int64_t* dense_dim, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_uniform(AtenTensorHandle self, double from, double to, AtenGeneratorHandle* generator, AtenTensorHandle* ret0); +AOTI_TORCH_EXPORT AOTITorchError aoti_torch_xpu_view_dtype(AtenTensorHandle self, int32_t dtype, AtenTensorHandle* ret0); + +#ifdef __cplusplus +} // extern "C" +#endif diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/mkldnn_tensor.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/mkldnn_tensor.h new file mode 100644 index 0000000000000000000000000000000000000000..57aa0645fb79e83c94f30a120fc6898062e89bce --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/mkldnn_tensor.h @@ -0,0 +1,22 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::aot_inductor { + +void* data_ptr_from_mkldnn(at::Tensor* mkldnn_tensor); + +at::Tensor mkldnn_tensor_from_data_ptr( + void* data_ptr, + at::IntArrayRef dims, + at::ScalarType dtype, + at::Device device, + const uint8_t* opaque_metadata, + int64_t opaque_metadata_size); + +} // namespace torch::aot_inductor + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/oss_proxy_executor.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/oss_proxy_executor.h new file mode 100644 index 0000000000000000000000000000000000000000..61428e2cef64ceb3c600d8a8dd03ac63e018c4b1 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/oss_proxy_executor.h @@ -0,0 +1,158 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include +#include +#include // @manual +#include +#include + +namespace torch::aot_inductor { + +inline std::ostream& operator<<(std::ostream& os, DynamicArgType arg_type) { + os << static_cast(arg_type); + return os; +} + +struct OSSDynamicArg { + OSSDynamicArg( + int arg_index, + DynamicArgType arg_type, + int length, + std::optional> list_item_types = std::nullopt) + : arg_index(arg_index), + arg_type(arg_type), + length(length), + list_item_types(std::move(list_item_types)) {} + int arg_index; + DynamicArgType arg_type; + int length; + std::optional> + list_item_types; // only used for parsing list of optional tensors +}; + +struct OSSTorchBindArg { + OSSTorchBindArg(int arg_index, std::string arg_name) + : arg_index(arg_index), arg_name(std::move(arg_name)) {} + int arg_index; + // arg_name is used to find the corresponding IValue in customObjs_ + std::string arg_name; +}; + +struct OSSOpKernel { + explicit OSSOpKernel(std::string target) : target_(std::move(target)) {} + // Explicitly declare copy and move constructors + OSSOpKernel(const OSSOpKernel&) = default; + OSSOpKernel(OSSOpKernel&&) = default; + // Explicitly declare copy and move assignment operators + OSSOpKernel& operator=(const OSSOpKernel&) = default; + OSSOpKernel& operator=(OSSOpKernel&&) = default; + + std::string target_; + std::vector dynamic_args_; + std::vector torchbind_args_; + std::vector outputs_; + std::vector stack_; + + int num_output_tensors() const { + int num_output_tensors = 0; + for (const auto& output : outputs_) { + if (isTensorType(output.arg_type)) { + num_output_tensors += output.length; + } + } + return num_output_tensors; + } + + int num_output_ints() const { + int num_output_ints = 0; + for (const auto& output : outputs_) { + if (output.arg_type == DynamicArgType::IntType) { + num_output_ints += output.length; + } + } + return num_output_ints; + } + + virtual void run(std::vector& stack) = 0; + virtual c10::FunctionSchema schema() const = 0; + virtual ~OSSOpKernel() = default; +}; + +struct OSSOpKernelOperator : public OSSOpKernel { + OSSOpKernelOperator(std::string target, c10::OperatorHandle op_handle) + : OSSOpKernel(std::move(target)), op_handle_(std::move(op_handle)) {} + + c10::OperatorHandle op_handle_; + void run(std::vector& stack) override { + op_handle_.callBoxed(stack); + } + + c10::FunctionSchema schema() const override { + return op_handle_.schema(); + } +}; + +struct OSSCallTorchBindKernel : public OSSOpKernel { + OSSCallTorchBindKernel(std::string target, torch::jit::Function* method) + : OSSOpKernel(std::move(target)), method_(method) {} + torch::jit::Function* method_; + void run(std::vector& stack) override { + method_->run(stack); + } + + c10::FunctionSchema schema() const override { + return method_->getSchema(); + } +}; + +class OSSProxyExecutor : public ProxyExecutor { + public: + explicit OSSProxyExecutor( + const std::string& json_path, + bool is_cpu, + std::optional> custom_objs = + std::nullopt); + + void call_function( + int extern_node_index, + int num_ints, + int64_t* flatten_int_args, + int num_tensors, + AtenTensorHandle* flatten_tensor_args) override; + + private: + void prefill_stack_with_static_arguments( + size_t index, + const at::TypePtr& schema_arg_type, + const nlohmann::json& serialized_arg, + OSSOpKernel* op_kernel, + const std::string& torchbind_arg_name); + + void get_input_info_from_serialized( + const std::vector& schema_args, + const nlohmann::json& serialized_node, + OSSOpKernel& op_kernel); + + void get_output_info_from_serialized( + const std::vector& schema_returns, + const nlohmann::json& serialized_node, + OSSOpKernel& op_kernel); + + std::unique_ptr get_call_torch_bind_kernel( + const nlohmann::json& serialized_node); + + std::vector> op_kernels_; + std::unique_ptr device_; + std::unordered_map custom_objs_; +}; + +} // namespace torch::aot_inductor + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/proxy_executor.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/proxy_executor.h new file mode 100644 index 0000000000000000000000000000000000000000..b25a7e396c8c349810c56d59a20e800fa68d0882 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/proxy_executor.h @@ -0,0 +1,42 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +namespace torch::aot_inductor { + +enum class DynamicArgType : int { + TensorType = 0, + ListTensorType = 1, + ListOptionalTensorType = 2, + IntType = 3, + ListIntType = 4, + NoneType = 5, +}; + +inline bool isTensorType(DynamicArgType arg_type) { + return arg_type == DynamicArgType::TensorType || + arg_type == DynamicArgType::ListTensorType || + arg_type == DynamicArgType::ListOptionalTensorType; +} + +class ProxyExecutor { + public: + ProxyExecutor() = default; + virtual ~ProxyExecutor() = default; + + virtual void call_function( + int extern_node_index, + int num_ints, + int64_t* flatten_int_args, + int num_tensors, + AtenTensorHandle* flatten_tensor_args) = 0; +}; + +} // namespace torch::aot_inductor + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/tensor_converter.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/tensor_converter.h new file mode 100644 index 0000000000000000000000000000000000000000..4461d682ad3a5f70ae83161c6590cab63bf6a675 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/tensor_converter.h @@ -0,0 +1,31 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +namespace torch::aot_inductor { + +// Functions declared here are not meant to be called from the AOTInductor +// generated model.so + +// unsafe_alloc_new_handles_from_tensors is used for allocating new aten +// tensor objects and return them as a vector of AtenTensorHandle (raw +// pointers), and those pointers will be stolen by model.so. +TORCH_API std::vector unsafe_alloc_new_handles_from_tensors( + const std::vector& tensors); + +// alloc_tensors_by_stealing_from_handles is used for creating a vector of aten +// tensors by stealing from an array of handles. Only the handles are stolen, +// and the array itself is borrowed. +// +// WARNING: Can NOT be called in model.so +TORCH_API std::vector alloc_tensors_by_stealing_from_handles( + AtenTensorHandle* handles, + size_t length); + +} // namespace torch::aot_inductor + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/utils.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/utils.h new file mode 100644 index 0000000000000000000000000000000000000000..0e71766b3f0a24a6129eac1e08fec84fefbbabbf --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_torch/utils.h @@ -0,0 +1,240 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define AOTI_TORCH_CONVERT_EXCEPTION_TO_ERROR_CODE(...) \ + try { \ + __VA_ARGS__ \ + } catch (const std::exception& e) { \ + LOG(ERROR) << "Exception in aoti_torch: " << e.what(); \ + return AOTI_TORCH_FAILURE; \ + } catch (...) { \ + LOG(ERROR) << "Exception in aoti_torch: UNKNOWN"; \ + return AOTI_TORCH_FAILURE; \ + } \ + return AOTI_TORCH_SUCCESS; + +namespace torch::aot_inductor { + +inline at::Tensor* tensor_handle_to_tensor_pointer(AtenTensorHandle handle) { + return reinterpret_cast(handle); +} + +inline AtenTensorHandle tensor_pointer_to_tensor_handle(at::Tensor* tensor) { + return reinterpret_cast(tensor); +} + +inline at::Tensor resolve_tensor_dispatch_flags(AtenTensorHandle handle) { + at::Tensor* tensor{tensor_handle_to_tensor_pointer(handle)}; + if (tensor->is_conj() || tensor->is_neg()) { + // If the conjugation or negation dispatch flags are set, runtime dispatch + // handles them by cloning the tensor before passing them to the native ATen + // function. Since the C-shim calls the native function directly, we have + // to handle the flags ourselves, or results will be silently incorrect. + return tensor->clone(); + } + return *tensor; +} + +inline std::optional resolve_tensor_dispatch_flags( + const AtenTensorHandle* handle) { + return handle ? std::make_optional(resolve_tensor_dispatch_flags(*handle)) + : std::nullopt; +} + +inline std::vector resolve_tensor_list_dispatch_flags( + const AtenTensorHandle* handle, + int64_t len) { + std::vector ret{}; + ret.reserve(len); + for (int64_t i{0}; i < len; ++i) { + ret.emplace_back(resolve_tensor_dispatch_flags(handle[i])); + } + return ret; +} + +inline std::vector> resolve_tensor_list_dispatch_flags( + const AtenTensorHandle** handle, + int64_t len) { + std::vector> ret{}; + ret.reserve(len); + for (int64_t i{0}; i < len; ++i) { + ret.emplace_back(resolve_tensor_dispatch_flags(handle[i])); + } + return ret; +} + +inline at::Generator* generator_handle_to_generator_pointer( + AtenGeneratorHandle handle) { + return reinterpret_cast(handle); +} + +inline AtenGeneratorHandle generator_pointer_to_generator_handle( + at::Generator* generator) { + return reinterpret_cast(generator); +} + +inline AtenTensorHandle new_tensor_handle(at::Tensor&& tensor) { + at::Tensor* new_tensor = new at::Tensor(std::move(tensor)); + return tensor_pointer_to_tensor_handle(new_tensor); +} + +inline void assert_inf_and_nan( + const std::string& tensor_name, + at::Tensor& check_tensor) { + auto isnan_tensor = check_tensor.isnan(); + if (isnan_tensor.any().item()) { + throw std::runtime_error("At least one NaN in " + tensor_name); + } + auto isinf_tensor = check_tensor.isinf(); + if (isinf_tensor.any().item()) { + throw std::runtime_error("At least one INF in " + tensor_name); + } +} + +// utility functions to convert a pointer to an optional value +template +inline std::optional pointer_to_optional(T* ptr) { + return ptr ? std::make_optional(*ptr) : std::nullopt; +} + +template >> +inline std::optional pointer_to_optional(U* ptr) { + return ptr ? std::make_optional(T(*ptr)) : std::nullopt; +} + +template <> +inline std::optional pointer_to_optional(AtenTensorHandle* ptr) { + return ptr ? std::make_optional(*tensor_handle_to_tensor_pointer(*ptr)) + : std::nullopt; +} + +template <> +inline std::optional pointer_to_optional( + const AtenTensorHandle* ptr) { + return ptr ? std::make_optional(*tensor_handle_to_tensor_pointer(*ptr)) + : std::nullopt; +} + +template <> +inline std::optional pointer_to_optional( + AtenGeneratorHandle* ptr) { + return ptr ? std::make_optional(*generator_handle_to_generator_pointer(*ptr)) + : std::nullopt; +} + +inline std::optional pointer_to_optional_device( + int32_t* device_type, + int32_t device_index) { + return device_type ? std::make_optional(c10::Device( + static_cast(*device_type), + static_cast(device_index))) + : std::nullopt; +} + +// utility functions to convert a pointer to a list +template +struct is_optional : std::false_type {}; +template +struct is_optional> : std::true_type {}; + +template +inline c10::ArrayRef pointer_to_list(T* ptr, int64_t len) { + return c10::ArrayRef(ptr, len); +} + +template < + class T, + class U, + typename = std::enable_if_t>, + typename = std::enable_if_t::value>> +inline std::vector pointer_to_list(U* ptr, int64_t len) { + // std::vector will be implicitly converted to c10::ArrayRef at the call + // site + std::vector result; + result.reserve(len); + for (int64_t i = 0; i < len; i++) { + result.emplace_back(T(ptr[i])); + } + return result; +} + +template ::value>> +inline std::vector pointer_to_list(U** ptr, int64_t len) { + // Here U** denotes a list of optional arguments + // std::vector will be implicitly converted to c10::ArrayRef at the call + // site + std::vector result; + result.reserve(len); + for (int64_t i = 0; i < len; i++) { + result.emplace_back(pointer_to_optional(ptr[i])); + } + return result; +} + +template <> +inline std::vector pointer_to_list( + const AtenTensorHandle* ptr, + int64_t len) { + std::vector result; + result.reserve(len); + for (int64_t i = 0; i < len; i++) { + result.emplace_back(*tensor_handle_to_tensor_pointer(ptr[i])); + } + return result; +} + +template <> +inline std::vector> pointer_to_list( + const AtenTensorHandle** ptr, + int64_t len) { + std::vector> result; + result.reserve(len); + for (int64_t i = 0; i < len; i++) { + result.emplace_back(pointer_to_optional(ptr[i])); + } + return result; +} + +template +inline std::array pointer_to_list(const int32_t* ptr) { + std::array result; + std::copy(ptr, ptr + N, result.begin()); + return result; +} + +// Utility function to convert a pointer to an optional list of values +template +inline std::optional> pointer_to_optional_list( + U** ptr, + int64_t len) { + return ptr + ? std::make_optional>(pointer_to_list(*ptr, len)) + : std::nullopt; +} + +template +static c10::List convert_to_c10_List(const T* scalars, const int64_t len) { + c10::List scalars_list; + scalars_list.reserve(len); + for (int64_t i = 0; i < len; i++) { + scalars_list.emplace_back(scalars[i]); + } + return scalars_list; +} + +} // namespace torch::aot_inductor + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/array_ref_impl.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/array_ref_impl.h new file mode 100644 index 0000000000000000000000000000000000000000..f61765114014dc45abc3a1d6002bd6c0fe182fc3 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/array_ref_impl.h @@ -0,0 +1,92 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include + +namespace torch::aot_inductor { +template +void convert_output_to_handle( + const ArrayRefTensor& output, + AtenTensorHandle& handle) { + handle = output.expensiveCopyToTensor(); +} + +template +void convert_outputs_to_handles_helper( + const std::tuple...>& outputs, + AtenTensorHandle* output_handles, + std::index_sequence) { + (convert_output_to_handle(std::get(outputs), output_handles[Is]), ...); +} +template +void convert_outputs_to_handles( + const std::tuple...>& outputs, + AtenTensorHandle* output_handles) { + convert_outputs_to_handles_helper( + outputs, output_handles, std::make_index_sequence()); +} + +template +void convert_handle_to_arrayref_tensor( + AtenTensorHandle handle, + ArrayRefTensor& input) { + void* data_ptr; + AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_get_data_ptr(handle, &data_ptr)); + int64_t dim; + AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_get_dim(handle, &dim)); + int64_t numel; + AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_get_numel(handle, &numel)); + int64_t* sizes; + AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_get_sizes(handle, &sizes)); + int64_t* strides; + AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_get_strides(handle, &strides)); + int32_t dtype; + AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_get_dtype(handle, &dtype)); + int32_t device_type; + AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_get_device_type(handle, &device_type)); + int32_t device_index; + AOTI_TORCH_ERROR_CODE_CHECK( + aoti_torch_get_device_index(handle, &device_index)); + + input = ArrayRefTensor( + MiniArrayRef(reinterpret_cast(data_ptr), numel), + MiniArrayRef(sizes, dim), + MiniArrayRef(strides, dim), + device_type, + device_index); +} + +template +void convert_handles_to_inputs_helper( + AtenTensorHandle* input_handles, + std::tuple...>& inputs, + std::index_sequence) { + (convert_handle_to_arrayref_tensor(input_handles[Is], std::get(inputs)), + ...); +} + +template +void convert_handles_to_inputs( + AtenTensorHandle* input_handles, + std::tuple...>& inputs) { + convert_handles_to_inputs_helper( + input_handles, inputs, std::make_index_sequence()); +} + +template +void assert_numel(const ArrayRefTensor& tensor, uint64_t numel) { + TORCH_CHECK( + tensor.numel() == numel, + "incorrect numel for input tensor. expected ", + numel, + ", got ", + tensor.numel()); +} +} // namespace torch::aot_inductor + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/cpp_prefix.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/cpp_prefix.h new file mode 100644 index 0000000000000000000000000000000000000000..5d867caf8b49364f006675c01cc03ee89c21a851 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/cpp_prefix.h @@ -0,0 +1,1328 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// WARNING: be extra careful when including more ATen/c10 header files here! +// Because AOTInductor generated code will copy-paste this cpp_prefix.h for +// the CPU backend, we have to make sure the used headers are implemented +// in a header-only way, i.e. all the function and class definitions are +// in .h files instead of .cpp files, to avoid ABI backward-compatibility +// breakage. + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if defined(CPU_CAPABILITY_AVX512) || defined(CPU_CAPABILITY_AVX2) || \ + defined(CPU_CAPABILITY_ZVECTOR) || defined(CPU_CAPABILITY_NEON) || \ + defined(CPU_CAPABILITY_VSX) || defined(CPU_CAPABILITY_SVE256) +#define INDUCTOR_USE_VECTOR_TYPES() 1 +#else +#define INDUCTOR_USE_VECTOR_TYPES() 0 +#endif + +#if INDUCTOR_USE_VECTOR_TYPES() +#include +#include +#else +// For calc_erfinv +#include +#endif + +template +struct Welford { + T mean = T(0); + T m2 = T(0); + // Use weight for tail cases since the index of each element in the vec may be + // different. A single index can not express masked welford reduction. + T weight = T(0); + uint64_t index = 0; +}; + +template +struct IsVecType : std::false_type {}; + +template +struct IsVecMaskType : std::false_type {}; + +#if INDUCTOR_USE_VECTOR_TYPES() +template +struct IsVecType> : std::true_type {}; +template +struct IsVecType> : std::true_type {}; + +template +struct IsVecMaskType> : std::true_type {}; +#endif + +template +struct GetScalarType { + using type = T; +}; + +#if INDUCTOR_USE_VECTOR_TYPES() +template +struct GetScalarType> { + using type = T; +}; +template +struct GetScalarType> { + using type = T; +}; +#endif + +template +struct CascadeSumHelper { + // A data struct to help cascade summation: + std::vector sum_stk{}; + uint64_t depth{0}; // depth of sum_stk. + uint64_t num_chunks{0}; // number of chunks stored in sum_stk. + uint64_t index{0}; // index of the current data. + CascadeSumHelper() = default; + CascadeSumHelper(uint64_t N) { + uint64_t m = (N + kChunkSize - 1) / kChunkSize; // div up + depth = m > 0 + ? static_cast(ceil(log2(static_cast(m)))) + : 0; + if constexpr (IsVecType::value) { + sum_stk.assign( + std::max(depth, static_cast(1)), + T(typename T::value_type(0))); + } else { + sum_stk.assign(std::max(depth, static_cast(1)), T(0)); + } + } +}; + +template +inline T cascade_sum_combine(T& data, CascadeSumHelper* c) { + // Note: In order to be consistent with other reductions in inductor, + // the returned value may be wrong and cascade_sum_final must be executed to + // get the final correct result. Inductor uses the reduction suffix to ensure + // that cascade_sum_final is called in the end. + c->sum_stk[0] = c->sum_stk[0] + data; + // Use cascade summation to improve numerical stability. + // https://en.wikipedia.org/wiki/Pairwise_summation + if (c->depth > 0) { + c->index++; + if (c->index == kChunkSize) { + c->num_chunks += 1; + c->index = 0; + uint64_t mask = c->num_chunks; + uint64_t j = 1; + for (; j < c->depth && (mask & 1) == 0; ++j) { + c->sum_stk[j] = c->sum_stk[j] + c->sum_stk[j - 1]; + c->sum_stk[j - 1] = T(0); + mask >>= 1; + } + return c->sum_stk[j - 1]; + } + } + return c->sum_stk[0]; +} + +template +inline T cascade_sum_final(CascadeSumHelper* c) { + T result = c->sum_stk[0]; + for (const auto i : c10::irange(1, c->depth)) { + result = result + c->sum_stk[i]; + } + return result; +} + +template +struct WelfordHelper { + // A data struct to help welford reduction: + // 1. Save the reciprocal of weights to avoid redundant divisions. + // 2. Save the welford stack, which is used to combine welford reduction + // with cascade summation to improve numerical stability. + static std::vector::type> weight_recps; + std::vector> welford_stk{}; + uint64_t depth{0}; // depth of welford_stk. + uint64_t num_chunks{0}; // number of chunks stored in welford_stk. + WelfordHelper() = default; + WelfordHelper(uint64_t N) { + uint64_t m = (N + kChunkSize - 1) / kChunkSize; // div up + depth = m > 0 + ? static_cast(ceil(log2(static_cast(m)))) + : 0; + welford_stk.assign(depth, Welford()); + } +}; + +template +std::vector::type> + WelfordHelper::weight_recps = []() { + using scalar_t = typename GetScalarType::type; + std::vector temp(kChunkSize); + for (const auto i : c10::irange(kChunkSize)) { + temp[i] = scalar_t(static_cast(1) / static_cast(i + 1)); + } + return temp; + }(); + +template +Welford welford_combine( + const Welford& a, + const Welford& b, + bool use_index = false) { + if (a.index == 0) { + return b; + } + if (b.index == 0) { + return a; + } + auto delta = b.mean - a.mean; + auto a_weight = use_index ? T(a.index) : a.weight; + auto b_weight = use_index ? T(b.index) : b.weight; + auto new_weight = a_weight + b_weight; + auto new_index = a.index + b.index; + auto wb_over_w = b_weight / new_weight; + if constexpr (IsVecType::value) { + // Guard against division by zero + wb_over_w = T::blendv(wb_over_w, T(0), new_weight == T(0)); + } + auto result = Welford{ + a.mean + delta * wb_over_w, + a.m2 + b.m2 + delta * delta * a_weight * wb_over_w, + new_weight, + new_index}; + return result; +} + +template +Welford welford_combine( + Welford& acc, + T& data, + WelfordHelper* w = nullptr) { + // Combine welford reduction with cascade summation to improve numerical + // stability. + // https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance + // https://en.wikipedia.org/wiki/Pairwise_summation + if (w != nullptr && w->depth > 0 && acc.index == kChunkSize) { + w->welford_stk[0] = welford_combine(w->welford_stk[0], acc); + w->num_chunks += 1; + acc.mean = T(0); + acc.m2 = T(0); + acc.weight = T(0); + acc.index = 0; + uint64_t mask = w->num_chunks; + for (uint64_t j = 1; j < w->depth && (mask & 1) == 0; ++j) { + w->welford_stk[j] = + welford_combine(w->welford_stk[j], w->welford_stk[j - 1]); + w->welford_stk[j - 1] = Welford(); + mask >>= 1; + } + } + // Add a single data point + uint64_t new_index = acc.index + 1; + auto new_weight = acc.weight + T(1); + auto delta = data - acc.mean; + T new_mean; + // use new_index to fecth 1 / new_weight to avoid divisions + new_mean = acc.mean + + ((w == nullptr || acc.index >= w->weight_recps.size()) + ? delta / new_weight + : delta * T(w->weight_recps[acc.index])); + auto new_delta = data - new_mean; + auto result = + Welford{new_mean, acc.m2 + delta * new_delta, new_weight, new_index}; + return result; +} + +template +Welford welford_combine(Welford& acc, WelfordHelper* w) { + for (const auto i : c10::irange(w->depth)) { + acc = welford_combine(acc, w->welford_stk[i]); + } + return acc; +} + +template +struct IndexValue { + int64_t index{}; + T value; + IndexValue(int64_t idx, T val) : index(idx), value(val) {} + IndexValue() = default; +}; + +#if INDUCTOR_USE_VECTOR_TYPES() +template +Welford welford_combine( + Welford& acc, + T& data, + int64_t tail_size, + WelfordHelper* w = nullptr) { + auto out = welford_combine(acc, data, w); + return Welford{ + T::set(acc.mean, out.mean, tail_size), + T::set(acc.m2, out.m2, tail_size), + T::set(acc.weight, out.weight, tail_size), + out.index}; +} + +template +inline T cascade_sum_combine( + T& data, + int64_t tail_size, + CascadeSumHelper* c) { + auto out = c->sum_stk[0] + data; + c->sum_stk[0] = T::set(c->sum_stk[0], out, tail_size); + if (c->depth > 0) { + c->index++; + if (c->index == kChunkSize) { + c->num_chunks += 1; + c->index = 0; + uint64_t mask = c->num_chunks; + uint64_t j = 1; + for (; j < c->depth && (mask & 1) == 0; ++j) { + c->sum_stk[j] = c->sum_stk[j] + c->sum_stk[j - 1]; + c->sum_stk[j - 1] = T(0); + mask >>= 1; + } + return c->sum_stk[j - 1]; + } + } + return c->sum_stk[0]; +} + +template +inline T max_masked_reduce(const T& a, const T& b, const int64_t tail_size) { + auto out = at::vec::maximum(a, b); + return T::set(a, out, tail_size); +} + +template <> +inline at::vec::VecMask max_masked_reduce( + const at::vec::VecMask& a, + const at::vec::VecMask& b, + const int64_t tail_size) { + auto out = a | b; + return at::vec::VecMask::set(a, out, tail_size); +} + +template +inline T min_masked_reduce(const T& a, const T& b, const int64_t tail_size) { + auto out = at::vec::minimum(a, b); + return T::set(a, out, tail_size); +} + +template <> +inline at::vec::VecMask min_masked_reduce( + const at::vec::VecMask& a, + const at::vec::VecMask& b, + const int64_t tail_size) { + auto out = a & b; + return at::vec::VecMask::set(a, out, tail_size); +} + +template +inline T sum_masked_reduce(const T& a, const T& b, const int64_t tail_size) { + auto out = a + b; + return T::set(a, out, tail_size); +} + +template <> +inline at::vec::VecMask sum_masked_reduce( + const at::vec::VecMask& a, + const at::vec::VecMask& b, + const int64_t tail_size) { + auto out = a | b; + return at::vec::VecMask::set(a, out, tail_size); +} + +template +T prod_masked_reduce(const T& a, const T& b, const int64_t tail_size) { + auto out = a * b; + return T::set(a, out, tail_size); +} + +template +T xor_sum_masked_reduce(const T& a, const T& b, const int64_t tail_size) { + auto out = a ^ b; + return T::set(a, out, tail_size); +} + +template +T any_masked_reduce(const T& a, const T& b, const int64_t tail_size) { + auto out = a | b; + return T::set(a, out, tail_size); +} +#endif + +// Refer to +// https://github.com/pytorch/pytorch/blob/b5b36cf0c4e1958f1ff25120f5d4beeef3288187/ +// aten/src/ATen/native/SharedReduceOps.h#L419-L445 +template +inline bool greater_or_nan( + scalar_t a, + scalar_t b, + int64_t idx_a, + int64_t idx_b) { + // If (a == b), then choose the one with lower idx, else max(a, b) + if (at::_isnan(a)) { + if (at::_isnan(b)) { + return idx_a < idx_b; + } + return true; + } + return (a == b) ? idx_a < idx_b : (a > b); +} + +template +inline bool less_or_nan(scalar_t a, scalar_t b, int64_t idx_a, int64_t idx_b) { + // If (a == b), then choose the one with lower idx, else min(a, b) + if (at::_isnan(a)) { + if (at::_isnan(b)) { + return idx_a < idx_b; + } + return true; + } + return (a == b) ? idx_a < idx_b : (a < b); +} + +template +inline IndexValue& argmin_combine( + IndexValue& a, + T next_value, + int64_t next_index) { + if (!(less_or_nan(a.value, next_value, a.index, next_index))) { + a.value = next_value; + a.index = next_index; + } + return a; +} +template +inline IndexValue& argmax_combine( + IndexValue& a, + T next_value, + int64_t next_index) { + if (!(greater_or_nan(a.value, next_value, a.index, next_index))) { + a.value = next_value; + a.index = next_index; + } + return a; +} +template +inline IndexValue& argmin_combine( + IndexValue& a, + const IndexValue& next) { + return argmin_combine(a, next.value, next.index); +} +template +inline IndexValue& argmax_combine( + IndexValue& a, + const IndexValue& next) { + return argmax_combine(a, next.value, next.index); +} + +#if INDUCTOR_USE_VECTOR_TYPES() + +template +inline at::vec::Vectorized div_floor_floating_vec( + const at::vec::Vectorized& a, + const at::vec::Vectorized& b) { + using vec_t = at::vec::Vectorized; + const auto basic_div = a / b; + vec_t inf(std::numeric_limits::infinity()); + auto mod = a.fmod(b); + // Fixup for a case that isn't properly handled by Sleef_fmod + auto floor = + vec_t::blendv(a - mod, a, (basic_div.abs() == inf) & (a.abs() != inf)); + auto div = floor / b; + const auto zero = vec_t(0); + auto mask = (mod != zero) & ((b < zero) ^ (mod < zero)); + const auto one = vec_t(1); + div = vec_t::blendv(div, div - one, mask); + auto floordiv = div.floor(); + mask = (div - floordiv) > vec_t(0.5); + floordiv = vec_t::blendv(floordiv, floordiv + one, mask); + floordiv = vec_t::blendv(floordiv, zero.copysign(basic_div), div == zero); + floordiv = vec_t::blendv(floordiv, basic_div, b == zero); + return floordiv; +}; + +template +inline at::vec::VectorizedN div_floor_floating_vec( + const at::vec::VectorizedN& a, + const at::vec::VectorizedN& b) { + at::vec::VectorizedN result; +#ifndef _MSC_VER +#pragma unroll +#endif + for (int i = 0; i < N; ++i) { + result[i] = div_floor_floating_vec(a[i], b[i]); + } + return result; +} + +template +struct IndexValueVec { + at::vec::VectorizedN value; + at::vec::VectorizedN index; + + IndexValueVec(const T _value) { + value = at::vec::VectorizedN(_value); + index = at::vec::VectorizedN(0); + }; + + IndexValueVec() {}; +}; + +template < + typename T, + int NV, + int NI, + typename std::enable_if_t, int> = 0> +at::vec::VecMask inline get_mask_for_argmin_argmax( + const at::vec::VecMask& vmask, + const IndexValueVec& a, + const at::vec::VectorizedN& value, + const at::vec::VectorizedN& index) { + /* + vec impl for less_or_nan and greater_or_nan + example for argmin: + a.value = [NaN, NaN, 0, 2, 1, 0] + value = [NaN, 0, 0, 1, 2, NaN] + vmask = [false, false, false, false, true, false] + all_nan_or_equal = [true, false, true, false, false, false] + imask = [a.index[0] < index[0], ..., a.index[-1] < index[-1]] + iv_mask = blendv (vmask, imask, all_nan_or_equal) + [a.index[0] < index[0], false, a.index[2] < index[2], false, true, + false] a_nan_b_not: [false, false, false, false, false, true] mask = iv_mask | + a_nan_b_not [a.index[0] < index[0], false, a.index[2] < index[2], false, true, + true] + */ + using v_t = at::vec::VecMask; + using i_t = at::vec::VecMask; + i_t vmask_itype = vmask.template cast(); + // use itype here since there is vec impl for operator~ for itype + // while there may not vec impl for vtype + v_t isnan_a = a.value.isnan(); + i_t isnan_a_itype = isnan_a.template cast(); + v_t isnan_b = value.isnan(); + i_t isnan_b_type = isnan_b.template cast(); + i_t all_nan_mask = isnan_a_itype & isnan_b_type; + v_t equal_mask = (a.value == value); + i_t equal_mask_itype = equal_mask.template cast(); + i_t all_nan_or_equal = all_nan_mask | equal_mask_itype; + i_t imask(a.index < index); + i_t iv_mask = i_t::blendv(vmask_itype, imask, all_nan_or_equal); + i_t isnan_a_notnan_b = isnan_a_itype & (~isnan_b_type); + return iv_mask | isnan_a_notnan_b; +} + +template < + typename T, + int NV, + int NI, + typename std::enable_if_t, int> = 0> +at::vec::VecMask inline get_mask_for_argmin_argmax( + const at::vec::VecMask& vmask, + const IndexValueVec& a, + const at::vec::VectorizedN& value, + const at::vec::VectorizedN& index) { + using v_t = at::vec::VecMask; + using i_t = at::vec::VecMask; + i_t vmask_itype = vmask.template cast(); + v_t equal_mask = (a.value == value); + i_t equal_mask_itype = equal_mask.template cast(); + i_t imask(a.index < index); + return i_t::blendv(vmask_itype, imask, equal_mask_itype); +} + +template +inline IndexValueVec& argmin_vec_impl( + IndexValueVec& a, + at::vec::VectorizedN value, + at::vec::VectorizedN index, + std::optional tail_size) { + at::vec::VecMask vmask(a.value < value); + at::vec::VecMask final_mask = + get_mask_for_argmin_argmax(vmask, a, value, index); + if (tail_size.has_value()) { + a.value = at::vec::VectorizedN::set( + a.value, at::vec::minimum(a.value, value), tail_size.value()); + a.index = at::vec::VectorizedN::set( + a.index, + at::vec::VecMask::blendv(index, a.index, final_mask), + tail_size.value()); + } else { + a.value = at::vec::minimum(a.value, value); + a.index = at::vec::VecMask::blendv(index, a.index, final_mask); + } + return a; +} + +template +inline IndexValueVec& argmax_vec_impl( + IndexValueVec& a, + at::vec::VectorizedN value, + at::vec::VectorizedN index, + std::optional tail_size) { + at::vec::VecMask vmask(a.value > value); + at::vec::VecMask final_mask = + get_mask_for_argmin_argmax(vmask, a, value, index); + if (tail_size.has_value()) { + a.value = at::vec::VectorizedN::set( + a.value, at::vec::maximum(a.value, value), tail_size.value()); + a.index = at::vec::VectorizedN::set( + a.index, + at::vec::VecMask::blendv(index, a.index, final_mask), + tail_size.value()); + } else { + a.value = at::vec::maximum(a.value, value); + a.index = at::vec::VecMask::blendv(index, a.index, final_mask); + } + return a; +} + +template +inline at::vec::VectorizedN create_index(int64_t next_index) { + at::vec::VectorizedN next_idx; + if constexpr (horizontal) { + next_idx = at::vec::VectorizedN::arange(next_index, 1); + } else { + next_idx = at::vec::VectorizedN(next_index); + } + return next_idx; +} + +template +inline IndexValueVec& argmin_combine_vec( + IndexValueVec& a, + at::vec::VectorizedN next_value, + int64_t next_index, + std::optional tail_size = std::nullopt) { + auto next_idx = create_index(next_index); + return argmin_vec_impl(a, next_value, next_idx, tail_size); +} + +template +inline IndexValueVec& argmax_combine_vec( + IndexValueVec& a, + at::vec::VectorizedN next_value, + int64_t next_index, + std::optional tail_size = std::nullopt) { + auto next_idx = create_index(next_index); + return argmax_vec_impl(a, next_value, next_idx, tail_size); +} + +template +inline IndexValue argmin_vec_reduce_all( + const IndexValueVec& vec) { + constexpr int len = at::vec::VectorizedN::size(); + __at_align__ T tmpval[len]; + __at_align__ int64_t tmpidx[len]; + vec.value.store(tmpval); + vec.index.store(tmpidx); + IndexValue res = IndexValue(tmpidx[0], tmpval[0]); + for (int i = 1; i < len; i++) { + res = argmin_combine(res, tmpval[i], tmpidx[i]); + } + return res; +} + +template +inline IndexValue argmax_vec_reduce_all( + const IndexValueVec& vec) { + constexpr int len = at::vec::VectorizedN::size(); + __at_align__ T tmpval[len]; + __at_align__ int64_t tmpidx[len]; + vec.value.store(tmpval); + vec.index.store(tmpidx); + IndexValue res = IndexValue(tmpidx[0], tmpval[0]); + for (int i = 1; i < len; i++) { + res = argmax_combine(res, tmpval[i], tmpidx[i]); + } + return res; +} + +template +inline IndexValueVec& argmin_combine_vec( + IndexValueVec& vec_a, + const IndexValueVec& vec_b, + std::optional tail_size = std::nullopt) { + return argmin_vec_impl(vec_a, vec_b.value, vec_b.index, tail_size); +} + +template +inline IndexValueVec& argmax_combine_vec( + IndexValueVec& vec_a, + const IndexValueVec& vec_b, + std::optional tail_size = std::nullopt) { + return argmax_vec_impl(vec_a, vec_b.value, vec_b.index, tail_size); +} + +template +inline at::vec::Vectorized vec_shuffle_down( + at::vec::Vectorized x, + size_t n) { + using Vec = at::vec::Vectorized; + alignas(alignof(Vec)) scalar_t array[Vec::size()]; + x.store(array); + for (size_t i = 0; i + n < Vec::size(); i += 2 * n) { + array[i] = array[i + n]; + } + return Vec::loadu(array); +} + +#ifdef CPU_CAPABILITY_AVX2 +inline at::vec::Vectorized vec_shuffle_down( + at::vec::Vectorized x, + size_t n) { + using vec_t = at::vec::Vectorized; +#define SHUFFLE_MASK(z, y, x, w) ((z << 6) | (y << 4) | (x << 2) | w) + switch (n) { + case 1: + return vec_t(_mm256_permute_ps(x, SHUFFLE_MASK(1, 1, 3, 3))); + case 2: + return vec_t(_mm256_permute_ps(x, SHUFFLE_MASK(2, 2, 2, 2))); + case 4: + return vec_t(_mm256_permute2f128_ps(x, x, SHUFFLE_MASK(1, 1, 1, 1))); + } + + TORCH_CHECK(false, "Unhandled vec_shuffle_down value ", n); +} +#endif + +#ifdef CPU_CAPABILITY_AVX512 +inline at::vec::Vectorized vec_shuffle_down( + at::vec::Vectorized x, + size_t n) { + using vec_t = at::vec::Vectorized; +#define SHUFFLE_MASK(z, y, x, w) ((z << 6) | (y << 4) | (x << 2) | w) + switch (n) { + case 1: + return vec_t(_mm512_permute_ps(x, SHUFFLE_MASK(1, 1, 3, 3))); + case 2: + return vec_t(_mm512_permute_ps(x, SHUFFLE_MASK(2, 2, 2, 2))); + case 4: + return vec_t(_mm512_permutexvar_ps( + _mm512_set_epi32( + 12, 12, 12, 12, 12, 12, 12, 12, 4, 4, 4, 4, 4, 4, 4, 4), + x)); + case 8: + return vec_t(_mm512_permutexvar_ps( + _mm512_set_epi32(8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8), x)); + } + + TORCH_CHECK(false, "Unhandled vec_shuffle_down value ", n); +} +#endif + +template +Welford welford_vec_reduce_all( + Welford> acc) { + using Vec = at::vec::Vectorized; + Welford result; + if (acc.index == 0) { + return result; + } + // if all values of acc.weight are same as index, + // use index to reduce to save the overhead of vec_shuffle_down for acc.weight + bool use_index = (acc.weight - Vec(acc.index)).zero_mask() == + static_cast((1 << Vec::size()) - 1); + for (size_t n = 1; n < Vec::size(); n *= 2) { + auto shuffled = Welford{ + vec_shuffle_down(acc.mean, n), + vec_shuffle_down(acc.m2, n), + use_index ? Vec(0) : vec_shuffle_down(acc.weight, n), + acc.index}; + acc = welford_combine(acc, shuffled, use_index); + } + + alignas(alignof(Vec)) scalar_t array[Vec::size()]; + acc.mean.store(array); + result.mean = array[0]; + + acc.m2.store(array); + result.m2 = array[0]; + + acc.weight.store(array); + result.weight = array[0]; + result.index = result.weight; + + return result; +} + +template +Welford welford_vec_reduce_all( + Welford> acc) { + auto Welford0 = Welford>{ + acc.mean[0], acc.m2[0], acc.weight[0], acc.index}; + auto Welford1 = Welford>{ + acc.mean[1], acc.m2[1], acc.weight[1], acc.index}; + return welford_vec_reduce_all(welford_combine(Welford0, Welford1)); +} +#endif + +template +inline typename std::common_type_t mod(T a, U b) { + return a % b; +} +template <> +inline float mod(float a, float b) { + return std::fmod(a, b); +} +template <> +inline double mod(double a, double b) { + return std::fmod(a, b); +} + +template +inline scalar_t max_propagate_nan(scalar_t a, scalar_t b) { + if (at::_isnan(a)) { + return a; + } + return a > b ? a : b; +} + +template +inline scalar_t min_propagate_nan(scalar_t a, scalar_t b) { + if (at::_isnan(a)) { + return a; + } + return a < b ? a : b; +} + +constexpr float uint32_to_uniform_float(uint32_t value) { + // maximum value such that `MAX_INT * scale < 1.0` (with float rounding) + constexpr float scale = 4.6566127342e-10; + return static_cast(value & 0x7FFFFFFF) * scale; +} + +inline float normalized_rand_cpu(uint32_t seed, uint32_t offset) { + return uint32_to_uniform_float(at::Philox4_32(seed, 0, offset)()); +} + +inline float randn_cpu(uint32_t seed, uint32_t offset) { + at::Philox4_32 engine(seed, 0, offset); + return engine.randn(10); +} + +inline int64_t randint64_cpu( + uint32_t seed, + uint32_t offset, + int64_t low, + int64_t high) { + auto gen = at::Philox4_32(seed, 0, offset); + uint64_t r0 = gen(); + uint64_t r1 = gen(); + uint64_t result = r0 | (r1 << 32); + return static_cast(result % (high - low)) + low; +} + +template +struct AsIntegerType { + typedef T type; +}; +template <> +struct AsIntegerType { + typedef uint32_t type; +}; +template <> +struct AsIntegerType { + typedef uint64_t type; +}; +template <> +struct AsIntegerType { + typedef uint16_t type; +}; + +template +typename std::enable_if_t< + !c10::is_reduced_floating_point_v, + T> inline fetch_value(volatile T* addr) { + return *addr; +} + +template +typename std::enable_if_t< + c10::is_reduced_floating_point_v, + T> inline fetch_value(volatile T* addr) { + return T(addr->x, T::from_bits()); +} + +template +typename std::enable_if_t> atomic_add( + volatile T* addr, + T offset) { + typedef typename AsIntegerType::type alt_type; + + static_assert( + sizeof(std::atomic) == sizeof(T), "std::atomic issue"); + + alt_type expected; + + alt_type desired; + + std::atomic* atomic_addr = (std::atomic*)addr; + do { + T val = fetch_value(addr); + reinterpret_cast(&expected)[0] = val; + reinterpret_cast(&desired)[0] = val + offset; + } while (!atomic_addr->compare_exchange_weak( + expected, desired, std::memory_order_relaxed)); +} + +// Since C++20 float is supported by fetch_add, but the performance may not +// better than compare_exchange_weak, which can be checked by microbenchmark +// inductor_cpu_atomic.py +template +typename std::enable_if_t> atomic_add( + volatile T* addr, + T offset) { + static_assert(sizeof(std::atomic) == sizeof(T), "std::atomic issue"); + std::atomic* atomic_addr = (std::atomic*)addr; + atomic_addr->fetch_add(offset, std::memory_order_relaxed); +} + +#if INDUCTOR_USE_VECTOR_TYPES() +template +void atomic_add_vec( + T* addr, + at::vec::VectorizedN index, + at::vec::VectorizedN offset, + std::optional tail_size = std::nullopt) { + constexpr int len = at::vec::VectorizedN::size(); + static_assert(len <= at::vec::VectorizedN::size()); + __at_align__ std::array tmpbuf; + __at_align__ std::array tmpidx; + offset.store(tmpbuf.data(), len); + index.store(tmpidx.data(), len); + int size = tail_size.has_value() ? tail_size.value() : len; + for (int i = 0; i < size; i++) { + atomic_add(addr + tmpidx[i], tmpbuf[i]); + } +} + +template +struct transpose_mxn_helper; + +template +struct transpose_mxn_helper { + static void call( + const T* src, + int64_t ld_src, + T* dst, + int64_t ld_dst, + int M, + int N) { + for (int i = 0; i < M; i++) { + for (int j = 0; j < N; j++) { + atomic_add(&dst[j * ld_dst + i], src[i * ld_src + j]); + } + } + } +}; + +template +struct transpose_mxn_helper { + static void call( + const T* src, + int64_t ld_src, + T* dst, + int64_t ld_dst, + int M, + int N) { + at::vec::transpose_mxn(src, ld_src, dst, ld_dst, M, N); + } +}; + +template +inline void transpose_mxn( + const T* src, + int64_t ld_src, + T* dst, + int64_t ld_dst, + int M, + int N) { + transpose_mxn_helper::call(src, ld_src, dst, ld_dst, M, N); +} + +template +inline void transpose_mxn( + const T* src, + int64_t ld_src, + T* dst, + int64_t ld_dst) { + transpose_mxn(src, ld_src, dst, ld_dst, M, N); +} +#endif + +// NOLINTBEGIN(*-avoid-c-arrays) +inline std::tuple, int> _get_factors( + int64_t number) { + int count = 0; + for (auto i = static_cast(std::sqrt(number)); i > 0; --i) { + if (number % i == 0) { + count += 2; + } + } + auto factors = std::shared_ptr(new int64_t[count]); + int index = 0; + for (auto i = static_cast(std::sqrt(number)); i > 0; --i) { + if (number % i == 0) { + factors[index++] = number / i; + factors[index++] = i; + } + } + return std::make_tuple(factors, count); +} + +inline std::tuple, int> get_factors(int64_t number) { + thread_local std::map, int>> + cache; + auto it = cache.find(number); + if (it != cache.end()) { + return it->second; + } else { + auto factors = _get_factors(number); + cache[number] = factors; + return factors; + } +} +// NOLINTEND(*-avoid-c-arrays) + +inline void _mm_get_thread_blocking( + int num_threads, + int max_k_slices, + int64_t M, + int64_t N, + int64_t K, + int64_t Mr, + int64_t Nr, + int64_t Kr, + int64_t& Mt, + int64_t& Nt, + int64_t& Kt) { + // see NOTE [Thread blocking in Cpp GEMM] for heuristics + Mt = Nt = Kt = 0; + + auto get_blocking = [](int64_t m_factor, + int64_t n_factor, + int64_t k_factor, + int64_t m_blocks, + int64_t n_blocks, + int64_t k_blocks) { + int64_t thread_block_k = (k_blocks + k_factor - 1) / k_factor; + int64_t thread_block_n = (n_blocks + n_factor - 1) / n_factor; + int64_t thread_block_m = (m_blocks + m_factor - 1) / m_factor; + return std::make_tuple(thread_block_m, thread_block_n, thread_block_k); + }; + + auto is_better_blocking = [=](int64_t Mt_, + int64_t Nt_, + int64_t Kt_, + int64_t Mt, + int64_t Nt, + int64_t Kt) { + return Mt == 0 || Kt_ < Kt || Mt_ * Mr + Nt_ * Nr < Mt * Mr + Nt * Nr; + }; + + int64_t m_blocks = (M + Mr - 1) / Mr; + int64_t n_blocks = (N + Nr - 1) / Nr; + int64_t k_blocks = (K + Kr - 1) / Kr; + + auto [factors, count] = get_factors(num_threads); + assert(count > 0); + + for (int i = 0; i < count; ++i) { + int64_t n_factor = factors[i]; + int64_t m_factor = num_threads / n_factor; + if (n_blocks >= n_factor && m_blocks >= m_factor) { + auto [Mt_, Nt_, Kt_] = + get_blocking(m_factor, n_factor, 1, m_blocks, n_blocks, k_blocks); + if (is_better_blocking(Mt_, Nt_, Kt_, Mt, Nt, Kt)) { + std::tie(Mt, Nt, Kt) = std::make_tuple(Mt_, Nt_, Kt_); + } + } + } + + if (Mt != 0) { + return; + } + + for (int i = 0; i < count; ++i) { + int64_t k_factor = factors[i]; + if (k_blocks >= k_factor && + (max_k_slices == 0 || k_factor <= max_k_slices)) { + auto [mxn_factors, mxn_count] = get_factors(num_threads / k_factor); + for (int j = 0; j < mxn_count; ++j) { + int64_t n_factor = mxn_factors[j]; + int64_t m_factor = num_threads / (k_factor * n_factor); + if (n_blocks >= n_factor && m_blocks >= m_factor) { + auto [Mt_, Nt_, Kt_] = get_blocking( + m_factor, n_factor, k_factor, m_blocks, n_blocks, k_blocks); + if (is_better_blocking(Mt_, Nt_, Kt_, Mt, Nt, Kt)) { + std::tie(Mt, Nt, Kt) = std::make_tuple(Mt_, Nt_, Kt_); + } + } + } + } + } + + if (Mt != 0) { + return; + } + + for (int i = 0; i < count; ++i) { + int64_t n_factor = factors[i]; + int64_t m_factor = num_threads / n_factor; + if (n_blocks >= n_factor || m_blocks >= m_factor) { + auto [Mt_, Nt_, Kt_] = + get_blocking(m_factor, n_factor, 1, m_blocks, n_blocks, k_blocks); + if (is_better_blocking(Mt_, Nt_, Kt_, Mt, Nt, Kt)) { + std::tie(Mt, Nt, Kt) = std::make_tuple(Mt_, Nt_, Kt_); + } + } + } + + assert(Mt != 0); +} + +inline void mm_get_thread_blocking( + int num_threads, + int max_k_slices, + int64_t M, + int64_t N, + int64_t K, + int64_t Mr, + int64_t Nr, + int64_t Kr, + int64_t& Mt, + int64_t& Nt, + int64_t& Kt) { + thread_local std::map< + std:: + tuple, + std::tuple> + cache; + auto key = std::make_tuple(num_threads, max_k_slices, M, N, K, Mr, Nr, Kr); + auto it = cache.find(key); + if (it != cache.end()) { + std::tie(Mt, Nt, Kt) = it->second; + return; + } else { + _mm_get_thread_blocking( + num_threads, max_k_slices, M, N, K, Mr, Nr, Kr, Mt, Nt, Kt); + cache[key] = std::make_tuple(Mt, Nt, Kt); + } +} + +// NOLINTBEGIN(*-narrowing-conversions) +template +void _mm_get_cache_blocking( + int num_threads, + int64_t M, + int64_t N, + int64_t K, + int64_t Mr, + int64_t Nr, + int64_t Kr, + int64_t Mt_blocks, + int64_t Nt_blocks, + int64_t Kt_blocks, + int64_t& Mc_blocks, + int64_t& Nc_blocks, + int64_t& Kc_blocks, + uint32_t L1_cache_size, + uint32_t L2_cache_size) { + // See NOTE [CPP GEMM Cache Blocking Algorithm] for the cache blocking + // algorithm. + // TODO(jgong5): cache cache blocking results + // TODO: tune the factor here + float L1_limit_factor = 0.8; + float L2_limit_factor = 0.5; + + auto L1 = L1_cache_size * L1_limit_factor; + auto L2 = L2_cache_size * L2_limit_factor; + + constexpr size_t num_byte_A = sizeof(X_t); + constexpr size_t num_byte_B = sizeof(W_t); + + int64_t size_cache_B = Kr * Kt_blocks * Nr * num_byte_B; + Kc_blocks = Kt_blocks; + if (size_cache_B > L1) { + Kc_blocks = (int64_t)std::floor(L1 / (Kr * Nr * num_byte_B)); + } + + float min_Mc_ratio = 2; + int64_t min_Mc_blocks = std::ceil(min_Mc_ratio * Mr / Nr); + auto Kt_bytes = Kt_blocks * Kr * num_byte_A; + if (min_Mc_blocks * Mr * Kt_bytes < L2) { + Mc_blocks = std::min(Mt_blocks, (int64_t)std::floor(L2 / (Mr * Kt_bytes))); + Nc_blocks = 1; + } else { + Mc_blocks = Mt_blocks; + Nc_blocks = + std::min((int64_t)std::ceil((float)Mc_blocks * Mr / Nr), Nt_blocks); + auto Nc_bytes = Nc_blocks * Nr * 4; + auto Kc_bytes = Kc_blocks * Kr * num_byte_A; + if (Mc_blocks * Mr * (Kc_bytes + Nc_bytes) > L2) { + auto M_max = (std::sqrt(Kc_bytes * Kc_bytes + 16 * L2) - Kc_bytes) / 8; + if (M_max < Mc_blocks * Mr) { + Mc_blocks = (int64_t)std::floor(M_max / Mr); + Nc_blocks = + std::min((int64_t)std::ceil((float)Mc_blocks * Mr / Nr), Nt_blocks); + } + } + } +} +// NOLINTEND(*-narrowing-conversions) + +template +void mm_get_cache_blocking( + int num_threads, + int64_t M, + int64_t N, + int64_t K, + int64_t Mr, + int64_t Nr, + int64_t Kr, + int64_t Mt_blocks, + int64_t Nt_blocks, + int64_t Kt_blocks, + int64_t& Mc_blocks, + int64_t& Nc_blocks, + int64_t& Kc_blocks, + uint32_t L1_cache_size, + uint32_t L2_cache_size) { + thread_local std::map< + std::tuple< + int, + int64_t, + int64_t, + int64_t, + int64_t, + int64_t, + int64_t, + int64_t, + int64_t, + int64_t, + int64_t, + int64_t>, + std::tuple> + cache; + auto key = std::make_tuple( + num_threads, + M, + N, + K, + Mr, + Nr, + Kr, + Mt_blocks, + Nt_blocks, + Kt_blocks, + L1_cache_size, + L2_cache_size); + auto it = cache.find(key); + if (it != cache.end()) { + std::tie(Mc_blocks, Nc_blocks, Kc_blocks) = it->second; + return; + } else { + _mm_get_cache_blocking( + num_threads, + M, + N, + K, + Mr, + Nr, + Kr, + Mt_blocks, + Nt_blocks, + Kt_blocks, + Mc_blocks, + Nc_blocks, + Kc_blocks, + L1_cache_size, + L2_cache_size); + cache[key] = std::make_tuple(Mc_blocks, Nc_blocks, Kc_blocks); + } +} + +struct amx_tilecfg { + uint8_t palette_id{0}; + uint8_t start_row{0}; + std::array reserved_0{}; + std::array colsb{}; + std::array rows{}; +}; + +class AMXState { + private: + amx_tilecfg tilecfg_{}; + uint8_t rows_{0}; + uint16_t colsb_{0}; + uint8_t num_tile_rows_{0}; + uint8_t num_tile_columns_{0}; + + public: + AMXState() = default; + + inline void configure( + uint8_t rows, + uint16_t colsb, + uint8_t num_tile_rows, + uint8_t num_tile_columns, + void (*loadconfig)(const amx_tilecfg&)) { + if (tilecfg_.palette_id == 1 && rows_ == rows && colsb_ == colsb && + num_tile_rows_ == num_tile_rows && + num_tile_columns_ == num_tile_columns) { + return; + } + tilecfg_.palette_id = 1; + rows_ = rows; + colsb_ = colsb; + num_tile_rows_ = num_tile_rows; + num_tile_columns_ = num_tile_columns; + const auto num_c_tiles = num_tile_rows * num_tile_columns; + // For C + for (int i = 0; i < num_c_tiles; i++) { + tilecfg_.rows[i] = rows; + tilecfg_.colsb[i] = 64; + } + // For A + for (int i = 0; i < num_tile_rows; i++) { + tilecfg_.rows[i + num_c_tiles] = rows; + tilecfg_.colsb[i + num_c_tiles] = colsb; + } + // For B + for (int i = 0; i < num_tile_columns; i++) { + tilecfg_.rows[i + num_c_tiles + num_tile_rows] = colsb / 4; + tilecfg_.colsb[i + num_c_tiles + num_tile_rows] = 64; + } + loadconfig(tilecfg_); + } + + inline void release(void (*tile_release)()) { + tilecfg_.palette_id = 0; + tile_release(); + } +}; + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/cpp_wrapper/array_ref.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/cpp_wrapper/array_ref.h new file mode 100644 index 0000000000000000000000000000000000000000..3ff757120d49fa01155e8e20626bff05d9a0c9fe --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/cpp_wrapper/array_ref.h @@ -0,0 +1,12 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/cpp_wrapper/common.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/cpp_wrapper/common.h new file mode 100644 index 0000000000000000000000000000000000000000..a335699653e1a4cce726683b08e0e7f8b3891f94 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/cpp_wrapper/common.h @@ -0,0 +1,80 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include + +#include +#include + +// Include some often-used cpp_wrapper headers, for precompiling. +#include +#include +#include +#include +#include +#include + +namespace py = pybind11; // NOLINT(misc-unused-alias-decls) + +class RAIIPyObject { + public: + RAIIPyObject() = default; + // steals a reference to a PyObject + RAIIPyObject(PyObject* obj) : obj_{obj} {} + RAIIPyObject(const RAIIPyObject& other) : obj_{other.obj_} { + Py_XINCREF(obj_); + } + RAIIPyObject(RAIIPyObject&& other) noexcept { + // refcount doesn't change, and obj_ is currently nullptr + std::swap(obj_, other.obj_); + } + ~RAIIPyObject() { + Py_XDECREF(obj_); + } + RAIIPyObject& operator=(const RAIIPyObject& other) { + if (this != &other) { + Py_XDECREF(obj_); + obj_ = other.obj_; + Py_XINCREF(obj_); + } + return *this; + } + RAIIPyObject& operator=(RAIIPyObject&& other) noexcept { + // refcount to the current object decreases, but refcount to other.obj_ is + // the same + Py_XDECREF(obj_); + obj_ = std::exchange(other.obj_, nullptr); + return *this; + } + operator bool() const noexcept { + return obj_; + } + operator PyObject*() { + return obj_; + } + PyObject* get() { + return obj_; + } + + private: + PyObject* obj_{nullptr}; +}; + +#include +#include +using namespace torch::aot_inductor; + +#include +#include + +// Round up to the nearest multiple of 64 +[[maybe_unused]] inline int64_t align(int64_t nbytes) { + return (nbytes + 64 - 1) & -64; +} + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/cpp_wrapper/cpu.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/cpp_wrapper/cpu.h new file mode 100644 index 0000000000000000000000000000000000000000..e98e987de358efd0ad1c810d837cae8205bbb33c --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/cpp_wrapper/cpu.h @@ -0,0 +1,9 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/cpp_wrapper/cuda.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/cpp_wrapper/cuda.h new file mode 100644 index 0000000000000000000000000000000000000000..04e34e99ff997f6701ba699c3a50542274228429 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/cpp_wrapper/cuda.h @@ -0,0 +1,9 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/cpp_wrapper/device_internal/cpu.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/cpp_wrapper/device_internal/cpu.h new file mode 100644 index 0000000000000000000000000000000000000000..98fd14fb45fc6138446fcc80b9148b3471d4ebde --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/cpp_wrapper/device_internal/cpu.h @@ -0,0 +1,8 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/cpp_wrapper/device_internal/cuda.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/cpp_wrapper/device_internal/cuda.h new file mode 100644 index 0000000000000000000000000000000000000000..2f9e7104c1b2a16f8d4a0dbd920e6a2816f059a2 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/cpp_wrapper/device_internal/cuda.h @@ -0,0 +1,9 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/cpp_wrapper/device_internal/mps.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/cpp_wrapper/device_internal/mps.h new file mode 100644 index 0000000000000000000000000000000000000000..7711a5e019966c970818c5e7082a5b99f22856e1 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/cpp_wrapper/device_internal/mps.h @@ -0,0 +1,9 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/cpp_wrapper/device_internal/xpu.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/cpp_wrapper/device_internal/xpu.h new file mode 100644 index 0000000000000000000000000000000000000000..eda98fd2052767ac360e31245fa94a9e350cbdaf --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/cpp_wrapper/device_internal/xpu.h @@ -0,0 +1,10 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/cpp_wrapper/mps.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/cpp_wrapper/mps.h new file mode 100644 index 0000000000000000000000000000000000000000..00d4464071f64f8c46df042813e6bd56222a304e --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/cpp_wrapper/mps.h @@ -0,0 +1,9 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/cpp_wrapper/xpu.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/cpp_wrapper/xpu.h new file mode 100644 index 0000000000000000000000000000000000000000..787def8bd78bb93e2afc4dd16f025f90dec14ab7 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/cpp_wrapper/xpu.h @@ -0,0 +1,9 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/inductor_ops.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/inductor_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..77eef6c69f5eb4725fcf08489bf57e27dd97ae30 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/inductor_ops.h @@ -0,0 +1,44 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::inductor { + +TORCH_API at::Tensor _mm_plus_mm_out( + at::Tensor& out, + const at::Tensor& a, + const at::Tensor& b, + const at::Tensor& c, + const at::Tensor& d); + +// After adding _mm_plus_mm_out, this should not be exposed and called by model +// code. Keeping it around for backward compatibility. Will be deprecated later. +TORCH_API at::Tensor _mm_plus_mm( + const at::Tensor& a, + const at::Tensor& b, + const at::Tensor& c, + const at::Tensor& d, + at::Tensor& out); + +TORCH_API at::Tensor _alloc_from_pool( + const at::Tensor& self, + int64_t offset_bytes, + at::ScalarType dtype, + at::IntArrayRef size, + at::IntArrayRef stride); + +// Similar to as_strided with the following differences +// - offset is added to the existing offset (rather than replacing it) +// - view tracking is disabled similar to unsafe_view +TORCH_API at::Tensor _reinterpret_tensor( + const at::Tensor& self, + at::IntArrayRef size, + at::IntArrayRef stride, + int64_t offset_increment = 0); + +} // namespace torch::inductor + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/static_cuda_launcher.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/static_cuda_launcher.h new file mode 100644 index 0000000000000000000000000000000000000000..b28a38e70236d66e2ba2c927bf20e855c7612130 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/static_cuda_launcher.h @@ -0,0 +1,12 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#if defined(USE_CUDA) && !defined(USE_ROCM) +#include +#include + +bool StaticCudaLauncher_init(PyObject* module); +#endif + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/instruction_counter/Module.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/instruction_counter/Module.h new file mode 100644 index 0000000000000000000000000000000000000000..b7fbac85c979734a709aef89819ae609e54b6686 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/instruction_counter/Module.h @@ -0,0 +1,13 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include + +namespace torch::instruction_counter { + +void initModule(PyObject* module); + +} // namespace torch::instruction_counter + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/api/compilation_unit.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/api/compilation_unit.h new file mode 100644 index 0000000000000000000000000000000000000000..e6264f6f992a61123df6647a90176397261bc47f --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/api/compilation_unit.h @@ -0,0 +1,356 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace torch::jit { + +struct Def; +struct Property; +struct ClassDef; +struct SugaredValue; +struct Resolver; + +using ResolverPtr = std::shared_ptr; +struct Self { + virtual ~Self() = default; + virtual std::shared_ptr makeSugared(Value* v) const = 0; + virtual ClassTypePtr getClassType() const = 0; +}; + +// A CompilationUnit is a list of named Functions +// with helper methods to iterate the list or invoke the function. +// Classes have a CompilationUnit holding the class methods, +// and Modules have a CompilationUnit holding the Functions that +// are used to implement their Methods + +struct TORCH_API CompilationUnit { + enum class FunctionType { Method, Hook, PreHook }; + // constructor that takes a set of functions to compile using the native + // resolver + explicit CompilationUnit(const std::string& source); + CompilationUnit() = default; + + CompilationUnit& operator=(CompilationUnit&&) = default; + CompilationUnit(CompilationUnit&&) = default; + CompilationUnit& operator=(const CompilationUnit&) = delete; + CompilationUnit(const CompilationUnit&) = delete; + + Function* find_function(const c10::QualifiedName& name) const { + auto it = dict_.find(name); + if (it == dict_.end()) { + return nullptr; + } + return functions_[it->second].get(); + } + + Function& get_function(const c10::QualifiedName& name) const { + if (auto r = find_function(name)) { + return *r; + } + TORCH_CHECK(false, "attempted to get undefined function ", name.name()); + } + + void set_optimized(bool o) { + TORCH_WARN( + "CompilationUnit::set_optimized() is deprecated and has no effect. " + "Please use setGraphExecutorOptimize()"); + } + + bool is_optimized() const { + TORCH_WARN( + "CompilationUnit::is_optimized() is deprecated and always returns true. " + "Please use getGraphExecutorOptimize()"); + return true; + } + + // for historic reasons, these are defined in ir_emitter.cpp + // Returns the list of Functions just defined. + std::vector define( + const std::optional& prefix, + const std::vector& properties, + const std::vector& propResolvers, + const std::vector& definitions, + const std::vector& + defResolvers, /* determines how we handle free + variables in each definition*/ + // if non-null, the first argument to each def, is bound to this value + const Self* self, + // see [name mangling] + bool shouldMangle = false, + std::optional operator_set_version = std::nullopt); + + void define_hooks( + const std::optional& prefix, + const std::vector& hookDefs, + const std::vector& hookResolvers, + const std::vector& preHookDefs, + const std::vector& preHookResolvers, + const Self* self, + bool shouldMangle = false); + + // same as above but parse the definitions from source + // Returns the list of Functions just defined. + std::vector define( + // prefix namespace to put all the defined functions into + const std::optional& prefix, + const std::string& source, + const ResolverPtr& resolver, + const Self* self); + + void define_interface( + const c10::QualifiedName& qualifiedName, + const ClassDef& classDef, + ResolverPtr rcb, + bool is_module = false); + + Function* create_function( + c10::QualifiedName name, + std::shared_ptr graph, + bool shouldMangle = false) { + if (shouldMangle) { + name = mangle(name); + } + auto fn = std::make_unique( + std::move(name), std::move(graph), nullptr); + auto ret = fn.get(); + register_function(std::move(fn)); + return ret; + } + + std::vector get_functions() const { + return fmap(functions_, [](const std::unique_ptr& fn) { + return fn.get(); + }); + } + + /// Run a method from this compilation. + /// + /// For example: + /// @code + /// IValue output = module->run("relu_script", a, b); + /// @endcode + /// + /// To get a compile a module from a source string, see torch::jit::compile + /// + /// @param method_name The name of the method to run + /// @param args Arguments to be passed to the method + /// @return An IValue containing the return value (or values if it is a tuple) + /// from the method + template + IValue run_method(const c10::QualifiedName& method_name, Types&&... args) { + return get_function(method_name)({IValue(std::forward(args))...}); + } + + void drop_all_functions() { + dict_.clear(); + functions_.clear(); + } + + /** + * Register a class as being owned by this compilation unit. + */ + void register_type(c10::NamedTypePtr namedType) { + // TODO: class types cannot be redefined because we have no way right now + // of invalidating their methods. NamedTuples are fine though, since they + // don't have methods. + TORCH_CHECK( + 0 == classDict_.count(*namedType->name()), + "class '", + namedType->name()->qualifiedName(), + "' already defined."); + classes_.push_back(std::move(namedType)); + classDict_[*classes_.back()->name()] = classes_.size() - 1; + } + + c10::ClassTypePtr get_class(const c10::QualifiedName& name) const { + auto type = get_type(name); + if (!type) { + return nullptr; + } + return type->cast(); + } + + c10::InterfaceTypePtr get_interface(const c10::QualifiedName& name) const { + auto type = get_type(name); + if (!type) { + return nullptr; + } + return type->cast(); + } + + c10::TupleTypePtr get_named_tuple(const c10::QualifiedName& name) const { + for (const auto& cls : classes_) { + if (cls->name()->qualifiedName() == name.qualifiedName()) { + return cls->expect(); + } + } + return nullptr; + } + + c10::NamedTypePtr get_type(const c10::QualifiedName& name) const { + auto it = classDict_.find(name); + if (it == classDict_.end()) { + return nullptr; + } + return classes_[it->second]; + } + + // For testing: clear all Python-defined classes to ensure that unit tests + // have isolation. + void _clear_python_cu() { + // Delete all the associated class methods + for (const auto& type : classes_) { + if (auto cls = type->cast()) { + for (auto method : cls->methods()) { + // Tombstone the method in the compilation unit. + // Don't erase because the dict_ + auto it = dict_.find(method->qualname()); + if (it != dict_.end()) { + functions_[it->second] = nullptr; + // Erase in our big lookup table + dict_.erase(it); + } + } + // Classes can have multiple pointers to the same hook, + // need to make sure to not delete it twice + std::unordered_set hooks_to_delete; + for (const auto& hook : cls->getForwardHooks()) { + hooks_to_delete.insert(hook); + } + for (const auto& pre_hook : cls->getForwardPreHooks()) { + hooks_to_delete.insert(pre_hook); + } + for (const auto& hook : hooks_to_delete) { + // Tombstone the hook in the compilation unit. + auto it = dict_.find(hook->qualname()); + if (it != dict_.end()) { + functions_[it->second] = nullptr; + // Erase in our big lookup table + dict_.erase(it); + } + } + } + } + classes_.clear(); + classDict_.clear(); + } + + // [Internal Only] Remove method. + // Note Used for freezing. + void unsafeRemoveMethod(const c10::QualifiedName& method_name) { + auto it = dict_.find(method_name); + TORCH_CHECK( + it != dict_.end(), + "method '", + method_name.qualifiedName(), + "' does not exist."); + functions_[it->second] = nullptr; + dict_.erase(it); + } + + // [name mangling] All code objects must have a unique qualified name in a + // CompilationUnit. In Python, sometimes functions won't have unique qualified + // name (for example, nested functions). So we mangle Python functions to + // ensure that they are uniquely named. + // + // We also use mangling to distinguish different Module instances. Since each + // Module is a singleton class instance, different instances of the same + // Python Module will have different types but the same qualified name. + c10::QualifiedName mangle(const c10::QualifiedName& name) const { + auto mangled = name; + while (get_type(mangled) || find_function(mangled)) { + mangled = mangler_.mangle(mangled); + } + return mangled; + } + + private: + std::unique_ptr define( + const std::optional& prefix, + const Def& def, + const ResolverPtr& resolver, + const Self* self, + const std::unordered_map& function_table, + bool shouldMangle = false, + FunctionType type = FunctionType::Method, + std::optional version = std::nullopt) const; + + // Define a property on \p self. + struct PropertyPair; + PropertyPair define_property( + const std::optional& prefix, + const Property& prop, + const ResolverPtr& resolver, + const Self* self, + const std::unordered_map& function_table, + bool shouldMangle = false) const; + + Function& register_function(std::unique_ptr fn) { + TORCH_CHECK( + 0 == dict_.count(fn->qualname().qualifiedName()), + "method '", + fn->qualname().qualifiedName(), + "' already defined."); + functions_.emplace_back(std::move(fn)); + dict_[functions_.back()->qualname()] = functions_.size() - 1; + return *functions_.back(); + } + std::vector> functions_; + // for fast lookup + std::unordered_map dict_; + std::unordered_map classDict_; + + // [class ownership] Right now there are two relationships between classes + // and compilation units: + // 1. Classes have compilation units internally that hold their methods. + // 2. On load, the TypePtrs of any imported classes are owned by the main + // module's compilation unit. + std::vector classes_; + + mutable NameMangler mangler_; +}; + +// An owning pointer to a Function. Just a pair of a raw Function ptr and it's +// owning CU. We need this because pybind requires a ref-counted way to refer to +// Functions. +struct StrongFunctionPtr { + StrongFunctionPtr(std::shared_ptr cu, Function* function) + : cu_(std::move(cu)), function_(function) { + TORCH_INTERNAL_ASSERT(cu_); + TORCH_INTERNAL_ASSERT(function_); + } + std::shared_ptr cu_; + Function* function_; +}; + +namespace script { +// We once had a `script::` namespace that was deleted. This is for backcompat +// of the public API; new code should not use this type alias. +using CompilationUnit = ::torch::jit::CompilationUnit; +} // namespace script +} // namespace torch::jit + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/api/function_impl.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/api/function_impl.h new file mode 100644 index 0000000000000000000000000000000000000000..e311563890e13e39c5382b582953433131ab62cd --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/api/function_impl.h @@ -0,0 +1,185 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +namespace torch::jit { + +struct TORCH_API GraphFunction : public Function { + GraphFunction( + c10::QualifiedName name, + std::shared_ptr graph, + std::function function_creator, + std::optional executor_execution_mode = + std::nullopt) + : name_(std::move(name)), + graph_(std::move(graph)), + executor_execution_mode_(executor_execution_mode), + function_creator_(std::move(function_creator)) {} + + bool isGraphFunction() const override { + return true; + } + + void run(Stack& stack) override; + + std::function function_creator() const { + return function_creator_; + } + + c10::intrusive_ptr runAsync( + Stack& stack, + TaskLauncher taskLauncher = at::launch) override; + + std::shared_ptr graph() const { + return graph_; + } + + std::shared_ptr optimized_graph() const; + + const c10::QualifiedName& qualname() const override { + return name_; + } + + // private/unstable api. sets the initial execution mode + // will not affect executor if there is an existing executor + // created for this function + void _set_initial_executor_execution_mode(ExecutorExecutionMode mode) { + executor_execution_mode_ = mode; + } + // private/unstable api. sets flag of whether or not to ignore amp. + // will not affect executor if there is an existing executor + // created for this function + void _set_ignore_amp(bool ignore_amp) { + force_no_amp_ = ignore_amp; + } + + // if this isn't yet defined, run its method_creator function + void ensure_defined() override; + + size_t num_inputs() const override { + return graph()->inputs().size(); + } + + Function& setSchema(FunctionSchema schema) override { + schema_ = std::make_unique(std::move(schema)); + return *this; + } + + const FunctionSchema& getSchema() const override; + + GraphExecutorState getDebugState() { + return get_executor().getDebugState(); + } + + bool is_optimized() const { + TORCH_WARN( + "GraphFunction::is_optimized() is deprecated and always returns true. " + "Please use getGraphExecutorOptimize()"); + return true; + } + + void check_single_output() { + TORCH_CHECK( + graph()->outputs().size() == 1, + "Method (but not graphs in general) require a single output. Use None/Tuple for 0 or 2+ outputs"); + } + + GraphExecutor& get_executor() { + ensure_defined(); + std::lock_guard lock(compile_mutex); + auto& executor = executors_[currentSpecialization()]; + if (executor) { + return *executor; + } + check_single_output(); + const std::string& name = name_.name(); + std::shared_ptr opt_graph = optimized_graph(); + if (!executor_execution_mode_) { + executor = GraphExecutor(opt_graph, name); + } else { + executor = GraphExecutor(opt_graph, name, *executor_execution_mode_); + } + return *executor; + } + + using Function::call; + bool call( + Stack& stack, + std::optional bailOut, + c10::function_ref f) override { + f(get_executor().getPlanFor(stack, bailOut).code); + return true; + } + + void clear_optimized_graphs() { + optimized_graphs_.fill(nullptr); + } + + private: + enum SpecializationKey { + AutocastOff, + CpuAutocastOn, + GpuAutocastOn, + CpuGpuAutocastOn, + + // This provides the number of specializations + // (Must be last entry) + TotalCount + }; + + SpecializationKey currentSpecialization() const; + + private: + c10::QualifiedName name_; + // The original, non-optimized graph + std::shared_ptr graph_; // for debugging and for inlining + + // allows users to specify Simple/Profiling Executor for function + // TODO: add more executors + mutable std::optional executor_execution_mode_; + + // if invoked on a graph that has already traced through amp + // don't invoke amp pass + mutable bool force_no_amp_ = false; + // Optimized graph, computed lazily. Used for inlining. + mutable std::array, SpecializationKey::TotalCount> + optimized_graphs_; + + // GraphFunctions are invocable from multiple threads, so this lock needs to + // be held when we're initializing graph executor for the first time or + // computing the optimized graph. We're using reentrant mutex so that we don't + // need to worry about causing a deadlock by calling one method from another + // (e.g. optimized_graph() from get_executor()). + mutable std::recursive_mutex compile_mutex; + + // executor_[0] - autocast off + // executor_[1] - autocast cpu on + // executor_[2] - autocast gpu on + // executor_[3] - autocast cpu & gpu on + std::array, SpecializationKey::TotalCount> + executors_; + + // an optional function that actually creates the method when + // ensure_defined() is called. This is used by the compiler so + // that it can construct methods out of order + std::function function_creator_; + + // if absent, then we generate a default schema based on the graph + // mutable because getSchema caches the default schema if one is requested + // before a call to setSchema + mutable std::unique_ptr schema_; +}; + +// Short hands for dynamic_cast. +TORCH_API GraphFunction* tryToGraphFunction(Function& /*function*/) noexcept; +TORCH_API GraphFunction& toGraphFunction(Function& /*function*/); +TORCH_API const GraphFunction& toGraphFunction(const Function& /*function*/); +} // namespace torch::jit +C10_DECLARE_bool(torch_jit_do_not_store_optimized_graph); + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/api/method.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/api/method.h new file mode 100644 index 0000000000000000000000000000000000000000..d138f8f847d2d0074f0b1669022fa0f4b3e811f6 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/api/method.h @@ -0,0 +1,91 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include + +namespace torch::jit { + +using ObjectPtr = c10::intrusive_ptr; + +// A method in a module, e.g. f in: +// +// class M(ScriptModule): +// @script_method +// def f(self, x): +// ... +// Note: because Method/Module are exposed to python these +// classes use python method naming conventions +struct TORCH_API Method : public torch::IMethod { + Method(ObjectPtr owner, Function* function); + + // the module that contains this method. + Module owner() const; + // the raw objectptr that owns this method, for when the method is owned by a + // torchbind object. + ObjectPtr raw_owner() const; + void run(Stack& stack); + void run(Stack&& stack) { + run(stack); + } + + c10::IValue operator()( + std::vector stack, + const Kwargs& kwargs = Kwargs()) const override; + + // Run method async. Invocation on this function would invokes a JIT + // interpreter that executes ops inline, one by one, on caller's thread. A + // model can utilize async op, i.e. `fork`, to launch an asynchronous task + // which will be launched on provided `taskLauncher`. + c10::intrusive_ptr run_async( + std::vector stack, + const Kwargs& kwargs = Kwargs(), + TaskLauncher taskLauncher = at::launch); + + std::shared_ptr graph() const { + return toGraphFunction(*function_).graph(); + } + + const std::string& name() const override { + return function_->name(); + } + + size_t num_inputs() const { + return function_->num_inputs(); + } + + GraphExecutor& get_executor() { + return toGraphFunction(*function_).get_executor(); + } + + Function& function() const { + return *function_; + } + + private: + void setArgumentNames( + std::vector& /*argumentNames*/ /*argumentNamesOut*/) + const override; + + // Methods are uniqued owned by a single module. This raw pointer allows + // looking up the module. + ObjectPtr owner_; + + // Underlying unbound function + Function* function_; +}; + +namespace script { +// We once had a `script::` namespace that was deleted. This is for backcompat +// of the public API; new code should not use this type alias. +using Method = ::torch::jit::Method; +} // namespace script + +} // namespace torch::jit + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/api/module.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/api/module.h new file mode 100644 index 0000000000000000000000000000000000000000..385c1ec489fc9d43caee073b604b4d5c777c286e --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/api/module.h @@ -0,0 +1,690 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#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 +#include + +// This file contains classes which assist in desugaring Python style +// modules and their methods into flattened graphs which don't have any +// function calls. + +namespace torch::jit { + +using ::c10::Argument; +using ::c10::FunctionSchema; +using ::c10::QualifiedName; +// Map which stores filename to content. +using ExtraFilesMap = std::unordered_map; + +using ModulePtr = c10::intrusive_ptr; + +struct Module; + +template +struct slot_list_impl; + +template +struct Named { + std::string name; + T value; +}; + +using NameModule = Named; +using NameValue = Named; +using NameTensor = Named; + +namespace detail { +struct TORCH_API ModulePolicy; +struct TORCH_API ParameterPolicy; +struct TORCH_API AttributePolicy; +struct TORCH_API BufferPolicy; +template +struct NamedPolicy; +} // namespace detail + +using module_list = slot_list_impl; +using named_module_list = + slot_list_impl>; + +using parameter_list = slot_list_impl; +using named_parameter_list = + slot_list_impl>; + +using attribute_list = slot_list_impl; +using named_attribute_list = + slot_list_impl>; + +using buffer_list = slot_list_impl; +using named_buffer_list = + slot_list_impl>; + +using ModuleLookup = std::function&)>; + +struct TORCH_API Module : public Object { + explicit Module(c10::QualifiedName class_name); + Module(std::shared_ptr cu, const c10::ClassTypePtr& type); + Module() = default; + Module(const Module&) = default; + Module& operator=(const Module&) = default; + Module(Module&&) noexcept = default; + Module& operator=(Module&&) noexcept = default; + Module( + c10::QualifiedName /*class_name*/, + std::shared_ptr cu, + bool shouldMangle = false); + Module(ModulePtr module_value) : Object(std::move(module_value)) {} + ~Module() = default; + + void set_optimized(bool o) { + TORCH_WARN( + "Module::set_optimized() is deprecated and has no effect. " + "Please use setGraphExecutorOptimize()"); + } + + bool is_optimized() const { + TORCH_WARN( + "Module::is_optimized() is deprecated and always returns true. " + "Please use getGraphExecutorOptimize()"); + return true; + } + + IValue forward(std::vector inputs, const Kwargs& kwargs = Kwargs()) { + return get_method("forward")(std::move(inputs), kwargs); + } + + // In script modules, buffers are Tensors attribute that are _not_ registered + // as parameters. This is different than in nn.Module where there is a special + // register_buffer method. With this simplification, we only need to track + // whether a slot is a parameter to be able to classify it. + void register_buffer(const std::string& name, at::Tensor v) { + bool is_param = false; + bool is_buffer = true; + std::lock_guard lock(*register_mutex_); + type()->addOrCheckAttribute(name, TensorType::get(), is_param, is_buffer); + _ivalue()->setAttr(name, std::move(v)); + } + + void register_parameter( + const std::string& name, + at::Tensor v, + bool is_buffer) { + std::lock_guard lock(*register_mutex_); + type()->addOrCheckAttribute(name, TensorType::get(), !is_buffer, is_buffer); + _ivalue()->setAttr(name, std::move(v)); + } + + void register_attribute( + const std::string& name, + const TypePtr& t, + IValue v, + bool is_param = false, + bool is_buffer = false) { + type()->addOrCheckAttribute(name, t, is_param, is_buffer); + _ivalue()->setAttr(name, std::move(v)); + } + + void register_module(const std::string& name, const Module& module) { + type()->addOrCheckAttribute(name, module.type()); + _ivalue()->setAttr(name, module._ivalue()); + } + + void apply(const std::function& fn); + + buffer_list buffers(bool recurse = true) const; + named_buffer_list named_buffers(bool recurse = true) const; + + module_list children() const; // direct modules + named_module_list named_children() const; + module_list modules() const; // all modules, including this one, recursively + named_module_list named_modules() const; + + // all tensors involved in gradient optimization + parameter_list parameters(bool recurse = true) const; + named_parameter_list named_parameters(bool recurse = true) const; + + // all members of the object, similar to iterating over dir(obj) in python + attribute_list attributes(bool recurse = true) const; + named_attribute_list named_attributes(bool recurse = true) const; + + void dump( + bool print_method_bodies, + bool print_attr_values, + bool print_param_values) const; + + std::string dump_to_str( + bool print_method_bodies, + bool print_attr_values, + bool print_param_values) const; + + /// Enables "training" mode. + void train(bool on = true); + /// Calls train(false) to enable "eval" mode. + /// Do not override this method, override `train()` instead. + void eval() { + train(/*on=*/false); + } + /// True if the module is in training mode. + bool is_training() const { + return attr("training", true).toBool(); + } + + /// Recursively casts all parameters to the given `dtype` and `device`. + /// + /// If `non_blocking` is true and the source is in pinned memory and + /// destination is on the GPU or vice versa, the copy is performed + /// asynchronously with respect to the host. Otherwise, the argument has no + /// effect. + void to(at::Device device, at::ScalarType dtype, bool non_blocking = false); + + /// Recursively casts all parameters to the given dtype. + /// + /// If `non_blocking` is true and the source is in pinned memory and + /// destination is on the GPU or vice versa, the copy is performed + /// asynchronously with respect to the host. Otherwise, the argument has no + /// effect. + void to(at::ScalarType dtype, bool non_blocking = false); + + /// Recursively moves all parameters to the given device. + /// + /// If `non_blocking` is true and the source is in pinned memory and + /// destination is on the GPU or vice versa, the copy is performed + /// asynchronously with respect to the host. Otherwise, the argument has no + /// effect. + void to(at::Device device, bool non_blocking = false); + + void save( + std::ostream& out, + const ExtraFilesMap& extra_files = ExtraFilesMap()) const; + + void save( + const std::string& filename, + const ExtraFilesMap& extra_files = ExtraFilesMap()) const; + + void _save_for_mobile( + std::ostream& out, + const ExtraFilesMap& extra_files = ExtraFilesMap(), + bool save_mobile_debug_info = false, + bool use_flatbuffer = false) const; + + void _save_for_mobile( + const std::string& filename, + const ExtraFilesMap& extra_files = ExtraFilesMap(), + bool save_mobile_debug_info = false, + bool use_flatbuffer = false) const; + + Module copy() const; + + Module deepcopy(std::optional device = std::nullopt) const; + + // Clones both the underlying `ClassType` and the module instance(data), this + // function creates a new `ClassType` and returns a new instance that has the + // same data as the current instance but with the new type, shared ClassType + // will be preserved as well + Module clone(bool inplace = false) const; + + // Clones both the underlying `ClassType` and the module instance(data), this + // function creates a new `ClassType` and returns a new instance that has the + // same data as the current instance but with the new type, shared ClassType + // will be preserved as well. Also allows the caller to specify a set of + // method and attribute names to not clone. + Module clone( + bool inplace, + const std::unordered_set& ignored_method, + const std::unordered_set& ignored_attributes) const; + + void clone_method(const Module& orig, const std::string& name); + + IValue operator()(std::vector inputs); + + template + IValue create_class(const c10::QualifiedName& name, Types&&... args) const { + return create_class(name, {IValue(std::forward(args))...}); + } + + IValue create_class(const c10::QualifiedName& name, Stack stack) const; + + inline bool operator==(const Module& y) const noexcept { + return _ivalue() == y._ivalue(); + } + + void set_delete_memory(std::shared_ptr delete_mem) { + mem_to_delete_ = std::move(delete_mem); + } + + // A set of functions to maintain input shapes through torch.jit.save and + // torch.jit.load. It only works on tensors and lists/dicts of tensors + // because tracing is only supported by these types. + void store_traced_inputs( + const std::string& func_name, + std::vector inputs) { + if (inputs.empty()) { + return; + } + auto c10_inputs = c10::impl::GenericList(AnyType::get()); + for (IValue& value : inputs) { + // Not checking whether this is traceable type as that is already checked + // higher up in the stack and changing that would require a larger + // restructuring. + c10_inputs.emplace_back(std::move(value)); + } + traced_inputs_.insert_or_assign(func_name, c10_inputs); + } + + c10::Dict retrieve_traced_inputs() + const { + return traced_inputs_; + } + + private: + Module clone_impl( + std::unordered_map& type_remap, + bool inplace, + IValue::HashIdentityIValueMap memo, + const std::unordered_set& ignored_methods, + const std::unordered_set& ignored_attributes) const; + + void clone_method( + const Module& orig, + const Function& method, + const std::unordered_map& type_remap); + + c10::QualifiedName getNameForMethod(std::string basename) const { + return QualifiedName(*type()->name(), std::move(basename)); + } + + void to_impl( + const std::optional& device, + const std::optional& dtype, + bool non_blocking); + + // Extra handle for the module to delete when itself is deleted + std::shared_ptr mem_to_delete_; + + // Map of function names to the traced inputs that they have been traced with + c10::Dict traced_inputs_; + + // Mutex to keep registering buffer or parameter thread safe. + std::shared_ptr register_mutex_ = std::make_shared(); +}; + +// C++ equivalent api of `torch.jit.freeze`. See documentation there for +// details. +TORCH_API Module freeze( + const Module& module, + const std::optional>& preserved_attrs = + std::nullopt, + bool optimize_numerics = true); + +// C++ equivalent api of `torch.jit.optimize_for_inference`. See documentation +// there for details. +TORCH_API Module optimize_for_inference( + Module& module, + const std::vector& other_methods = {}); + +enum class FusionBehavior { STATIC, DYNAMIC }; + +using FusionStrategy = std::vector>; +// clang-format off +/* +Sets the type and number of specializations that can occur during fusion. + +Usage: provide a list of pairs (type, depth) where type is one of STATIC or DYNAMIC +and depth is an integer. + +Behavior - static vs dynamic: + In STATIC fusion, fused ops are compiled to have fixed input shapes. The shape is determined + based on some initial profiling runs. + In DYNAMIC fusion, fused ops are compiled to have variable input shapes, so that multiple + shapes are possible. + +In both cases, we also recompile on new striding behavior, device, or dtype. + +Behavior - fallback functions & depth: + When an input doesn't match the format required by the specialized compiled op, it will run + a fallback function. Fallback functions are recursively be compiled and specialized based + on the observed tensor shapes. Since compilation can be slow, the "depth" parameter is provided to + limit the number of specializations that can be compiled, before giving up on recompiling and + falling back to a completely un-fused, un-specialized implementation. + +The list of (type, depth) pairs controls the type of specializations and the number of +specializations. For example: [(STATIC, 2), (DYNAMIC, 2)] indicates that the first +two specializations will use static fusions, the following two specializations will use +dynamic fusion, and any inputs that satisfy none of the 4 options will run an +unfused implementation. + +NB: in the future, if more as more fusion backends are added there may be more granular +apis for specific fusers. +*/ +// clang-format on +TORCH_API FusionStrategy getFusionStrategy(); +// returns previous strategy +TORCH_API FusionStrategy setFusionStrategy(FusionStrategy& fusion_strategy); + +namespace detail { + +struct TORCH_API SlotCursor { + Module module_; + int64_t i_; // slot offset, -1 indicates the module itself +}; + +} // namespace detail + +// This iterator allows the (optionally recursive) enumeration of +// the members of a Module. It performs a depth-first pre-order +// traversal of the module. The Policy template parameter determines +// which slots of the object should be included. For instance, +// when iterating parameters, we return the parameter tensors, +// but skip modules, buffers, and other attributes. +// See ModulePolicy for comments about Policy object's API. +template +struct slot_iterator_impl { + using SlotCursor = detail::SlotCursor; + using value_type = typename Policy::value_type; + slot_iterator_impl( + Module root, + bool recurse, // if true, do a depth-first search, otherwise, just look at + // slots of root + bool return_module) // if true include root itself as the first thing + // visited (used in modules()) + : cursors_({SlotCursor{std::move(root), return_module ? -1 : 0}}), + recurse_(recurse) { + // advance iterator to first valid element (or the end, if empty) + while_not_valid_next(); + } + // empty cursors_, represents end of iteration + slot_iterator_impl() : recurse_(false) {} + value_type operator*() const { + return Policy::create(cursors_, cur()); + } + value_type operator->() const { + return **this; + } + slot_iterator_impl& operator++() { + next_valid(); + return *this; + } + slot_iterator_impl operator++(int) { + // this is really expensive, should we delete it so people don't use it + // instead of prefix? + slot_iterator_impl old = *this; + ++(*this); + return old; + } + + private: + // return_module() is a corner case where instead of returning a submodule + // of root, we are returning root itself, because we are iterating modules(), + // which contains the root module itself. + // It is represented with a single SlotCursor whose index is -1. + bool return_module() const { + return top().i_ == -1; + } + const SlotCursor& top() const { + return cursors_.back(); + } + SlotCursor& top() { + return cursors_.back(); + } + IValue cur() const { + return return_module() ? top().module_._ivalue() + : top().module_._ivalue()->getSlot(top().i_); + } + + // advance to the next slot in a depth first pre-order traversal of the + // modules slots. This function does not guarantee the next slot is a + // valid element of the iteration. That is done by valid(). + // invariant: !cursors_.empty() + void next() { + // we just returned the module itself, advance i_ to 0 so we are now + // at the first slot of the module. + if (return_module()) { + ++top().i_; + return; + } + // the last traversal action advanced beyond the number of slots in the + // module so continue the iteration in the parent. + if (top().i_ >= int64_t(top().module_._ivalue()->type()->numAttributes())) { + cursors_.pop_back(); + if (!cursors_.empty()) { + ++top().i_; + } + return; + } + // if the current thing is a module, we have to scan it for recursive + // traversals. We do this by adding a new SlotCursor to track the traversal. + if (recurse_ && + top().module_._ivalue()->type()->getAttribute(top().i_)->is_module()) { + cursors_.emplace_back(SlotCursor{cur().toModule(), 0}); + return; + } + // common case: advance to the next slot. + ++top().i_; + } + // is the current position of the iterator a valid one? + // otherwise, we have to continue advancing. + bool valid() const { + return top().i_ < + int64_t(top().module_._ivalue()->type()->numAttributes()) && + Policy::valid( + top().module_._ivalue()->type(), + top().i_, + top().module_._ivalue()->getSlot(top().i_)); + } + void while_not_valid_next() { + // advance iteration until we are either at the end (cursors_.empty()) + // or in a valid state. return_module() is a special case, + // and is always considered valid, regardless of Policy, because it is + // it is only true when we are iterating modules. + while (!cursors_.empty() && !return_module() && !valid()) { + next(); + } + } + void next_valid() { + // avoid crashing if this is empty + if (cursors_.empty()) { + return; + } + // advance to next element, which is maybe not valid + next(); + while_not_valid_next(); + } + + std::vector cursors_; + bool recurse_; + + friend inline bool operator!=( + const slot_iterator_impl& a, + const slot_iterator_impl& b) { + // we are finished iteration when we have no more iteration SlotCursors. + // end is always an empty iterator with no cursors. + return (a.cursors_.empty() != b.cursors_.empty()); + } +}; + +// This type represents lists of parameters, attributes, and +// submodules contained in the module. It is abstract because +// they are not stored directly in std::vectors but inside the +// module's IValue object itself. +template +struct slot_list_impl { + using iterator = slot_iterator_impl; + using const_iterator = slot_iterator_impl; + using value_type = typename iterator::value_type; + slot_iterator_impl begin() const { + return slot_iterator_impl(module_, recurse_, return_module_); + } + slot_iterator_impl end() const { + return slot_iterator_impl(); + } + size_t size() const { + if (!size_) { + size_ = size_t(0); + for ([[maybe_unused]] const value_type& _ : *(this)) { + ++*size_; + } + } + return *size_; + } + + slot_list_impl(Module module, bool recurse, bool return_module) + : module_(std::move(module)), + recurse_(recurse), + return_module_(return_module), + size_(std::nullopt) { + if (!recurse && !return_module && Policy::all_slots) { + size_ = module_.num_slots(); + } + } + + private: + Module module_; + bool recurse_; + bool return_module_; + // size of this list, cached on first request + // when we need to filter the slot list + mutable std::optional size_; + friend struct Module; +}; + +namespace detail { + +// slot_iterator_impl always iterate over all the slots in a module, +// the Policy template argument determines slots should be returned and their +// types +struct TORCH_API ModulePolicy { + // the type of the value being returned + using value_type = Module; + + // the logic for creating the type being returned, given the raw IValue + // of that object. + static value_type create( + const std::vector& cursors, + IValue v) { + return Module(std::move(v).toObject()); + } + // is slot i in typ something that this iterator should return, otherwise, + // we skip it. + static bool valid(const ClassTypePtr& typ, size_t i, const IValue& v) { + return typ->getAttribute(i)->is_module(); + } + // are we going to return everything? If so, we can optimize the calculate + // of the size of the list. + static constexpr bool all_slots = false; +}; + +struct TORCH_API ParameterPolicy { + using value_type = at::Tensor; + static value_type create( + const std::vector& cursors, + IValue v) { + return std::move(v).toTensor(); + } + static bool valid(const ClassTypePtr& typ, size_t i, const IValue& v) { + return typ->is_parameter(i) && v.isTensor(); + } + static constexpr bool all_slots = false; +}; + +struct TORCH_API BufferPolicy { + using value_type = at::Tensor; + static value_type create( + const std::vector& cursors, + IValue v) { + return std::move(v).toTensor(); + } + static bool valid(const ClassTypePtr& typ, size_t i, const IValue& v) { + return typ->getAttribute(i)->isSubtypeOf(*TensorType::get()) && + typ->is_buffer(i); + } + static constexpr bool all_slots = false; +}; + +struct TORCH_API AttributePolicy { + using value_type = IValue; + static value_type create( + const std::vector& cursors, + IValue v) { + return v; + } + static bool valid(const ClassTypePtr& typ, size_t i, const IValue& v) { + return true; + } + static constexpr bool all_slots = true; +}; + +// take a Policy object, and make a version of it that returns the slot. +// along with the fully qualified name of that slot. This is used for the named_ +// variants like named_parameters(). +template +struct NamedPolicy { + using value_type = Named; + static value_type create( + const std::vector& cursors, + IValue v) { + std::string name; + if (cursors.size() == 1) { + name = (cursors.back().i_ == -1) ? "" : nameFragment(cursors.back()); + } else { + std::ostringstream ss; + for (const auto i : c10::irange(cursors.size())) { + if (i > 0) { + ss << '.'; + } + ss << nameFragment(cursors[i]); + } + name = ss.str(); + } + return value_type{std::move(name), Policy::create(cursors, std::move(v))}; + } + static bool valid(const ClassTypePtr& t, size_t i, const IValue& v) { + return Policy::valid(t, i, v); + } + static constexpr bool all_slots = Policy::all_slots; + + private: + static std::string nameFragment(const detail::SlotCursor& f) { + return f.module_.type()->getAttributeName(f.i_); + } +}; + +} // namespace detail + +TORCH_API bool& getInlineEverythingMode(); + +namespace script { +// We once had a `script::` namespace that was deleted. This is for backcompat +// of the public API; new code should not use this type alias. +using Module = ::torch::jit::Module; +using ExtraFilesMap = ::torch::jit::ExtraFilesMap; +} // namespace script + +} // namespace torch::jit + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/api/object.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/api/object.h new file mode 100644 index 0000000000000000000000000000000000000000..f25e599974b138172c593fe2c3f9f9fac2e26397 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/api/object.h @@ -0,0 +1,205 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include + +#include + +namespace torch::jit { + +struct Resolver; +using ResolverPtr = std::shared_ptr; + +using ObjectPtr = c10::intrusive_ptr; + +// Throw this in C++ land if `attr` fails. This will be converted to a Python +// AttributeError by the Python binding code +class ObjectAttributeError : public std::runtime_error { + public: + ObjectAttributeError(const std::string& what) : std::runtime_error(what) {} +}; + +struct TORCH_API Object { + Object() = default; + Object(const Object&) = default; + Object& operator=(const Object&) = default; + Object(Object&&) noexcept = default; + Object& operator=(Object&&) noexcept = default; + Object(ObjectPtr _ivalue) : _ivalue_(std::move(_ivalue)) {} + Object(std::shared_ptr cu, const c10::ClassTypePtr& type); + Object( + c10::QualifiedName, + std::shared_ptr cu, + bool shouldMangle = false); + + ObjectPtr _ivalue() const { + TORCH_INTERNAL_ASSERT(_ivalue_); + return _ivalue_; + } + + c10::ClassTypePtr type() const { + return _ivalue()->type(); + } + + struct Property { + std::string name; + Method getter_func; + std::optional setter_func; + }; + + void setattr(const std::string& name, c10::IValue v) { + if (_ivalue()->type()->hasConstant(name)) { + TORCH_CHECK( + false, + "Can't set constant '", + name, + "' which has value:", + _ivalue()->type()->getConstant(name)); + } else if (auto slot = _ivalue()->type()->findAttributeSlot(name)) { + const c10::TypePtr& expected = _ivalue()->type()->getAttribute(*slot); + TORCH_CHECK( + v.type()->isSubtypeOf(*expected), + "Expected a value of type '", + expected->repr_str(), + "' for field '", + name, + "', but found '", + v.type()->repr_str(), + "'"); + _ivalue()->setSlot(*slot, std::move(v)); + } else { + TORCH_CHECK(false, "Module has no attribute '", name, "'"); + } + } + + c10::IValue attr(const std::string& name) const { + if (auto r = _ivalue()->type()->findAttributeSlot(name)) { + return _ivalue()->getSlot(*r); + } + if (auto r = _ivalue()->type()->findConstantSlot(name)) { + return _ivalue()->type()->getConstant(*r); + } + std::stringstream err; + err << _ivalue()->type()->repr_str() << " does not have a field with name '" + << name.c_str() << "'"; + throw ObjectAttributeError(err.str()); + } + + c10::IValue attr(const std::string& name, c10::IValue or_else) const { + if (auto r = _ivalue()->type()->findAttributeSlot(name)) { + return _ivalue()->getSlot(*r); + } + if (auto r = _ivalue()->type()->findConstantSlot(name)) { + return _ivalue()->type()->getConstant(*r); + } + return or_else; + } + + bool hasattr(const std::string& name) const { + return _ivalue()->type()->hasAttribute(name) || + _ivalue()->type()->hasConstant(name); + } + + // each object owns its methods. The reference returned here + // is guaranteed to stay valid until this module has been destroyed + Method get_method(const std::string& name) const { + if (auto method = find_method(name)) { + return *method; + } + TORCH_CHECK(false, "Method '", name, "' is not defined."); + } + + const std::vector get_methods() const { + return c10::fmap(type()->methods(), [&](Function* func) { + return Method(_ivalue(), func); + }); + } + + bool has_property(const std::string& name) const { + for (const auto& prop : type()->properties()) { + if (prop.name == name) { + return true; + } + } + return false; + } + + const Property get_property(const std::string& name) const { + for (const auto& prop : type()->properties()) { + if (prop.name == name) { + std::optional setter = std::nullopt; + if (prop.setter) { + setter = Method(_ivalue(), prop.setter); + } + return Property{ + prop.name, Method(_ivalue(), prop.getter), std::move(setter)}; + } + } + TORCH_CHECK(false, "Property '", name, "' is not defined."); + } + + const std::vector get_properties() const { + return c10::fmap(type()->properties(), [&](ClassType::Property prop) { + std::optional setter = std::nullopt; + if (prop.setter) { + setter = Method(_ivalue(), prop.setter); + } + return Property{ + std::move(prop.name), + Method(_ivalue(), prop.getter), + std::move(setter)}; + }); + } + + std::optional find_method(const std::string& basename) const; + + /// Run a method from this module. + /// + /// For example: + /// @code + /// IValue output = module->run("relu_script", a, b); + /// @endcode + /// + /// To get a compile a module from a source string, see torch::jit::compile + /// + /// @param method_name The name of the method to run + /// @param args Arguments to be passed to the method + /// @return An IValue containing the return value (or values if it is a tuple) + /// from the method + template + IValue run_method(const std::string& method_name, Types&&... args) { + return get_method(method_name)({IValue(std::forward(args))...}); + } + + // so that C++ users can easily add methods + void define(const std::string& src, const ResolverPtr& resolver = nullptr); + + size_t num_slots() const { + return _ivalue()->slots().size(); + } + + // shallow copy the object + Object copy() const; + + // Copies all the attributes of the object recursively without creating new + // `ClassType`, including deepcopy of Tensors + Object deepcopy() const; + + private: + // mutable be we lazily initialize in module_object. + mutable ObjectPtr _ivalue_; +}; + +namespace script { +// We once had a `script::` namespace that was deleted. This is for backcompat +// of the public API; new code should not use this type alias. +using Object = ::torch::jit::Object; +} // namespace script +} // namespace torch::jit + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/backend.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/backend.h new file mode 100644 index 0000000000000000000000000000000000000000..cea04920023b6876ac4c8123c4b887b88d457fbd --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/backend.h @@ -0,0 +1,119 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include + +namespace torch::jit { +namespace { +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__"; + +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; +} + +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_v, + "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 torch::jit + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/backend_debug_handler.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/backend_debug_handler.h new file mode 100644 index 0000000000000000000000000000000000000000..ec124d0cf8ae0cbee9a38a575c49c22e2712164d --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/backend_debug_handler.h @@ -0,0 +1,143 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include + +#include +#include +#include + +#include + +namespace torch::jit { + +/* + * BackendDebugHandleManager is responsible for issuing debug handles to + * backends. Debug handles are associated with nodes of a graph. + * BackendDebugHandleManager also maintains a map + * [debug-handle, DebugInfoTuple = {source range, inlined callstack ptr]} that + * will help generate a callstack for exception raised using debug handles. + * Effectively debug handles are something that is given to backend and later + * when an exception occurs in the backend, backend can tell, using debug + * handle, that an exception occurred here. Then the runtime can generate + * callstack corresponding to the exception. + * There are two parts to BackendDebugHandleManager: + * 1. static std::atomic debug_handle + * 2. Map of [debug-handle, DebugInfoTuple] + * + * About 1: + * Why do they have to be unique. The reason is that by ensuring + * uniqueness of debug handles, we remove the burden of another layer of + * mapping where we need to say this set of debug handles were generated for + * this lowered module or this bytecode function. This simplifies the API for + * serialization since debug handles can uniquely identify DebugInfoTuple. + * Thus simplifies the runtime API for throwing exception. Exception throwing + * only needs to know debug_handle and not which module or method threw it. + * There are 2 issues to keep in mind, though,for static std::atomic + * debug_handle: A. Performance implications of using atomic variable. However + * this is only used for compilation so we assume to absorb some of that + * penalty. Plus if there is no contention then we should have less to worry + * about. B. If repeated compilation is part of a long running process then we + * may overflow int64_t. We may detect and fail on this. For now this is not + * done. + * + * Now about 2: + * There are two usecases for [debug-handle, DebugInfoTuple] + * A. During bytecode generation the DebugInfoTuple corresponding to the nodes + * of the inlined graph being serialized, are stored in this object and a + * unique debug handle is returned. This unique debug handle is stored in + * mobile_debug info for pytorch lite models. It will be used for raising + * exceptions as well as profiling. B. During backend lowering, each backend's + * preprocess/compile method can compile method's graph and serialize those + * methods. Once the method is lowered to backend, graph is essentially lost. + * Without access to graph it is hard to generate model level debug info. Thus + * the debug handles provide a way to map nodes of the graph to the model level + * debug info. + * + * During byte-code model serialization, [debug-handle, DebugInfoTuple] is + * serialized. Now we know a. debug handles and b. how to map debug handles to + * model source code. Thus we can either do eager symbolication by converting + * debug handles to corresponding source code at runtime, or do lazy + * symbolicattion offline. + * + * Note that it is not necessary to serialize [debug-handle, DebugInfoTuple] + * corresponding to lowered backend if the lowering process, that is + * preprocess/compile, and execution happens in the same session, then eager + * symbolication can be employed. + * + * Now how does BackendDebugHandleManager capture all of the above? + * By providing two API. + * 1. getNextDebugHandle which given a Node* returns a unique debug handle, + * that will uniquely identify DebugInfoTuple. + * and + * 2. getCallStackPtrMap which returns the map + * [debug-handle, DebugInfoTuple] + * + * 1 provides debug handles to backends and 2 provides runtime a way to map + * debug handles to source level debug info. + * + * So why does debug handle map to DebugInfoTuple = {source range and inlined + * cs}? {debug_handle, source_range_tag, serialized_callstack} Take this + * example: class L(nn.Module): def __init__(self) -> None: + * ... + * def forward(self, x): + * return x * 5 + * class M(nn.Module): + * def __init__(self) -> None: + * ... + * def forward(self, x): + * return x - 2 + * class N(nn.Module): + * def __init__(self) -> None: + * self.m = M() + * def forward(self, x): + * return self.m(x) + 3 + * m = torch.jit.script(N()) + * Once you inline m's forward method, m.forward.graph will look something + * like this + * graph(%self...): + * %x = aten::mul(..) + * %x = aten::sub(x, ..) + * %y = aten::add(x, ..) + * .. + * Inlined callstack ptr for these two nodes will look like: + * aten::mul's inlined CS (callstack): [N.forward, source range] -> [M.forward, + * source range] aten::sub's inlined CS (callstack): [N.forward, source range] + * aten::add's inlined CS: null + * mul node's inlined CS contains only information about the callsites' source + * range The information about mul node's source range ('return x * 5') is not + * available in its inlined CS. It is rather part of node's source range + * instead of inlined CS. Thus to get full stack: [N.forward, source range] -> + * [M.forward, source range] -> [aten::mul's source range] We need to track + * mul's source range and inlined CS both. + */ + +using BackendDebugInfoMapType = + std::unordered_map; + +/* + * This class is used to generate debug info map. + * backend's preprocess will call generate_debug_handles (see + * backend_detail.cpp), which uses debug_handle_manager to generate debug + * handles. When lowering process finishes, calling stopRecording will + * return debug info map from debug_handle_manager + */ +class TORCH_API BackendDebugInfoRecorder { + public: + BackendDebugInfoRecorder() = default; + int64_t getNextDebugHandle(const Node* node); + // Reason this is not done as RAII is that work done in stopRecording + // can throw, and throwing with dtor will call terminate and thus voids any + // exception catching at a higher level. + BackendDebugInfoMapType stopRecording(); + NodeToDebugHandle generate_debug_handles(const std::shared_ptr& graph); + + private: + static std::atomic unique_debug_handle_; + BackendDebugInfoMapType handles_to_inlined_callstack_ptrs_; +}; + +} // namespace torch::jit + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/backend_debug_info.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/backend_debug_info.h new file mode 100644 index 0000000000000000000000000000000000000000..b2ff9a3fe801206fba4bf40538e5770a3ae493e4 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/backend_debug_info.h @@ -0,0 +1,68 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#ifndef BUILD_LITE_INTERPRETER +#include +#endif +#include + +namespace torch::jit { + +constexpr static auto kBackendUtilsNamespace = "backendutils"; +constexpr static auto kBackendDebugInfoClass = "BackendDebugInfo"; + +#ifndef BUILD_LITE_INTERPRETER +/* + * Custom class for holding debug information in lowered modules, intended + * purely for keeping this information to be later serialized outside of the + * lowered module itself. + * Its usage pattern is: + * 1. LoweredModule declares an instance of this class in __backend_debug_info + * 2. During serialization, __backend_debug_info is used to obtain the debug + * information. + * 3. The contents of LoweredModule.__backend_debug_info are not serialized + * within the LoweredModule itself. + */ +class TORCH_API PyTorchBackendDebugInfo : public torch::CustomClassHolder { + public: + PyTorchBackendDebugInfo() = default; + + std::optional& getDebugInfoMap() { + return debug_info_map_; + } + + void setDebugInfoMap(BackendDebugInfoMapType&& debug_info_map) { + debug_info_map_ = std::move(debug_info_map); + } + + private: + std::optional debug_info_map_; +}; + +#else + +/* + * Dummy instance exists for the following reason: + * __backend_debug_info is of type BackendDebugInfo which is a torchbind' + * class backed by cpp class PyTorchBackendDebugInfo. + * PyTorchBackendDebugInfo, depends on ir.h., scope.h, source_range etc. + * We dont include this on lite interpreter side. Thus on lite interpreter side + * we cannot have valid definition of PyTorchBackendDebugInfo. However we do not + * need valid instance of __backend_debug_info in lite interpreter anyway as we + * dont serialize this info as part of LowerdModule as mentioned ealrier. + * However since LoweredModule has registered attribute of __backend_debug_info + * we still need to make sure that BackendDebugInfo is registered with + * TorchScript. However in this instance it does not have to be backed by + * PyTorchBackendDebugInfo, so we create a dummy PyTorchBackendDebugInfoDummy + * just for this purpose. + */ +class PyTorchBackendDebugInfoDummy : public torch::CustomClassHolder { + public: + PyTorchBackendDebugInfoDummy() = default; +}; +#endif +} // namespace torch::jit + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/backend_detail.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/backend_detail.h new file mode 100644 index 0000000000000000000000000000000000000000..cca52f2866881927fa9db1b8f35cb20be87a5183 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/backend_detail.h @@ -0,0 +1,44 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +#include + +#include + +namespace torch::jit { + +using DebugHandleType = int64_t; + +using NodeToDebugHandle = std::unordered_map; + +using BackendDebugHandleGenerator = + std::function&)>; + +namespace detail { + +using BackendPreprocessFunction = std::function&, + const BackendDebugHandleGenerator& generate_debug_handles)>; + +TORCH_API void registerBackendPreprocessFunction( + const std::string& name, + const BackendPreprocessFunction& preprocess); + +bool hasBackendPreprocessFunction(const std::string& name); + +BackendPreprocessFunction getBackendPreprocessFunction(const std::string& name); + +TORCH_API Module codegen_backend_module( + const std::string& backend_name, + const Module& orig_module, + const c10::Dict& method_compile_spec, + const c10::DictTypePtr& any_dict_ty); +} // namespace detail +} // namespace torch::jit + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/backend_exception.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/backend_exception.h new file mode 100644 index 0000000000000000000000000000000000000000..14a22a5704d99e3bdb2a347cecb906c7f8c681e2 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/backend_exception.h @@ -0,0 +1,61 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include + +#include + +namespace c10 { +class TORCH_API BackendRuntimeException : public c10::Error { + public: + // Use debug_handle to throw exception + BackendRuntimeException( + SourceLocation loc, + std::string msg, + int64_t debug_handle) + : c10::Error(loc, std::move(msg)) { + debug_handles.push_back(debug_handle); + } + // If rethrowing, can push another debug_handle + // This is useful in couple of scenarios. + // 1. A submodule is lowered and lite interpreter has CallMethod + // to lowered module's method. In this case lowered module will throw with + // a handle, plus there will be another debug handle corresponding + // to the CallMethod node in lite interpreter. Both together give complete + // trace. This function allows lite interpreter to rethrow with debug + // handle it has for CallMethod. + // 2. Another scenarios is when lite interpreter can make function calls or + // the lowered backend also has function call ability. Thus we have + // multiple function frames. Now we need a stack of handles to symbolicate + // entire stack trace. + void pushDebugHandle(int64_t debug_handle) { + debug_handles.push_back(debug_handle); + } + const std::vector& getDebugHandles() { + return debug_handles; + } + + private: + // Stores stack of debug handles. + std::vector debug_handles; +}; + +} // namespace c10 +#define TORCH_DELEGATED_BACKEND_THROW(cond, msg, debug_handle) \ + if (C10_UNLIKELY_OR_CONST(!(cond))) { \ + throw ::c10::BackendRuntimeException( \ + {__func__, __FILE__, static_cast(__LINE__)}, \ + msg, \ + debug_handle); \ + } + +#define TORCH_DELEGATED_BACKEND_RETHROW(e, debug_handle) \ + do { \ + e.pushDebugHandle(debug_handle); \ + throw; \ + } while (false) + +#define DEBUG_HANDLE_UNKNOWN -1 + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/backend_init.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/backend_init.h new file mode 100644 index 0000000000000000000000000000000000000000..bc490802ff882f7c10b304af7803b80d1c511b9e --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/backend_init.h @@ -0,0 +1,14 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +namespace torch::jit { +// Initialize Python bindings for JIT to_ functions. +void initJitBackendBindings(PyObject* module); +} // namespace torch::jit + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/backend_interface.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/backend_interface.h new file mode 100644 index 0000000000000000000000000000000000000000..5f7056a86d0628c1a861465c1cc30d46fc2d1db7 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/backend_interface.h @@ -0,0 +1,37 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit { + +// Interface for a JIT backend. +class TORCH_API PyTorchBackendInterface : public torch::CustomClassHolder { + public: + PyTorchBackendInterface() noexcept; + ~PyTorchBackendInterface() override; + + // Returns true if the backend is available to process delegation calls. + virtual bool is_available() = 0; + + // Compile the module contained in \p processed using the details provided in + // \p method_compile_spec for each module method that should be compiled for + // the backend. \p method_compile_spec should be of type Dict. + // \returns a dictionary of type Dict that contains a backend + // handle each method that can run on the backend (i.e. each key in \p + // method_compile_spec). + virtual c10::impl::GenericDict compile( + c10::IValue processed, + c10::impl::GenericDict method_compile_spec) = 0; + + // Execute the method specified by \p handle using \p inputs. \returns the + // outputs as a tuple. + virtual c10::impl::GenericList execute( + c10::IValue handle, + c10::impl::GenericList inputs) = 0; +}; +} // namespace torch::jit + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/backend_preprocess.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/backend_preprocess.h new file mode 100644 index 0000000000000000000000000000000000000000..f0241ec96ef63b32e94b6116f8fcc31df5da9f51 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/backend_preprocess.h @@ -0,0 +1,21 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +namespace torch::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 torch::jit + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/backend_resolver.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/backend_resolver.h new file mode 100644 index 0000000000000000000000000000000000000000..aee7fac6ddfb3fe942a82ad33074e672a3422821 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/backend_resolver.h @@ -0,0 +1,13 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit { +// Create a Resolver for use in generating LoweredModules for specific backends. +TORCH_API std::shared_ptr loweredModuleResolver(); +} // namespace torch::jit + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/coreml/cpp/context.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/coreml/cpp/context.h new file mode 100644 index 0000000000000000000000000000000000000000..6ac2655639b3b0dc4a087056e90a7f75a593f226 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/coreml/cpp/context.h @@ -0,0 +1,27 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#ifndef PTM_COREML_Context_h +#define PTM_COREML_Context_h + +#include + +namespace torch::jit::mobile::coreml { + +struct ContextInterface { + virtual ~ContextInterface() = default; + virtual void setModelCacheDirectory(std::string path) = 0; +}; + +class BackendRegistrar { + public: + explicit BackendRegistrar(ContextInterface* ctx); +}; + +void setModelCacheDirectory(std::string path); + +} // namespace torch::jit::mobile::coreml + +#endif + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/coreml/objc/PTMCoreMLCompiler.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/coreml/objc/PTMCoreMLCompiler.h new file mode 100644 index 0000000000000000000000000000000000000000..1b040c52c64f22364741a4c926686ec3579edd3b --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/coreml/objc/PTMCoreMLCompiler.h @@ -0,0 +1,27 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#import + +#include + +NS_ASSUME_NONNULL_BEGIN + +@interface PTMCoreMLCompiler : NSObject + ++ (void)setCacheDirectory:(const std::string&)dir; + ++ (NSString*)cacheDirectory; + ++ (BOOL)compileModel:(const std::string&)modelSpecs modelID:(const std::string&)modelID; + ++ (nullable MLModel*)loadModel:(const std::string)modelID + backend:(const std::string)backend + allowLowPrecision:(BOOL)allowLowPrecision + error:(NSError**)error; + +@end + +NS_ASSUME_NONNULL_END + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/coreml/objc/PTMCoreMLExecutor.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/coreml/objc/PTMCoreMLExecutor.h new file mode 100644 index 0000000000000000000000000000000000000000..5a79337260dcc3099d395a1639f39420796ab6b0 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/coreml/objc/PTMCoreMLExecutor.h @@ -0,0 +1,24 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#import + +#import + +NS_ASSUME_NONNULL_BEGIN + +@interface PTMCoreMLExecutor : NSObject + +@property(atomic, strong) MLModel* model; + +- (instancetype)initWithFeatureNames:(NSArray*)featureNames; + +- (void)setInputs:(c10::impl::GenericList)inputs; + +- (id)forward:(NSError**)error; + +@end + +NS_ASSUME_NONNULL_END + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/coreml/objc/PTMCoreMLFeatureProvider.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/coreml/objc/PTMCoreMLFeatureProvider.h new file mode 100644 index 0000000000000000000000000000000000000000..c0e536370b6ee5209dc88ae869539bad7a423260 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/coreml/objc/PTMCoreMLFeatureProvider.h @@ -0,0 +1,21 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#import +#import + +NS_ASSUME_NONNULL_BEGIN + +@interface PTMCoreMLFeatureProvider : NSObject + +- (instancetype)initWithFeatureNames:(NSSet*)featureNames; + +- (void)clearInputTensors; + +- (void)setInputTensor:(const at::Tensor&)tensor forFeatureName:(NSString*)name; + +@end + +NS_ASSUME_NONNULL_END + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/coreml/objc/PTMCoreMLModelWrapper.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/coreml/objc/PTMCoreMLModelWrapper.h new file mode 100644 index 0000000000000000000000000000000000000000..5ee77404da4e52f35be363da00dbf4779b75af89 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/coreml/objc/PTMCoreMLModelWrapper.h @@ -0,0 +1,46 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#include +#include +#include + +namespace torch { +namespace jit { +namespace mobile { +namespace coreml { + +class MLModelWrapper : public CustomClassHolder { + public: + PTMCoreMLExecutor* executor; + std::vector outputs; + + MLModelWrapper() = delete; + + MLModelWrapper(PTMCoreMLExecutor* executor) : executor(executor) { + [executor retain]; + } + + MLModelWrapper(const MLModelWrapper& oldObject) { + executor = oldObject.executor; + outputs = oldObject.outputs; + [executor retain]; + } + + MLModelWrapper(MLModelWrapper&& oldObject) { + executor = oldObject.executor; + outputs = oldObject.outputs; + [executor retain]; + } + + ~MLModelWrapper() { + [executor release]; + } +}; + +} // namespace coreml +} // namespace mobile +} // namespace jit +} // namespace torch + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/coreml/objc/PTMCoreMLTensorSpec.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/coreml/objc/PTMCoreMLTensorSpec.h new file mode 100644 index 0000000000000000000000000000000000000000..7537f743d938199c4d13c8f8aca01c6e5b0c231b --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/coreml/objc/PTMCoreMLTensorSpec.h @@ -0,0 +1,31 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#include +#import + +#include + +namespace torch::jit::mobile::coreml { + +struct TensorSpec { + std::string name; + c10::ScalarType dtype = c10::ScalarType::Float; +}; + +static inline c10::ScalarType scalar_type(const std::string& type_string) { + if (type_string == "0") { + return c10::ScalarType::Float; + } else if (type_string == "1") { + return c10::ScalarType::Double; + } else if (type_string == "2") { + return c10::ScalarType::Int; + } else if (type_string == "3") { + return c10::ScalarType::Long; + } + return c10::ScalarType::Undefined; +} + +} // namespace torch::jit::mobile::coreml + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/xnnpack/compiler/xnn_compiler.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/xnnpack/compiler/xnn_compiler.h new file mode 100644 index 0000000000000000000000000000000000000000..61bd88c05345fc626ef96149efa97d5235afa52b --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/xnnpack/compiler/xnn_compiler.h @@ -0,0 +1,29 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +// Copyright (c) Meta Platforms, Inc. and affiliates. +// +// This source code is licensed under the BSD-style license found in the +// LICENSE file in the root directory of this source tree. + +#include +#include +#include +#include + +namespace torch::jit::xnnpack::delegate { + +class XNNCompiler { + public: + // Takes Flatbuffer Serialized XNNPack Model and rebuilds the xnn-subgraph + // returns an executor object that holds the xnn runtime object which we + // can then use to set inputs and run inference using the xnn graph. + static void compileModel( + const void* buffer_pointer, + size_t num_bytes, + XNNExecutor* executor); +}; + +} // namespace torch::jit::xnnpack::delegate + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/xnnpack/executor/xnn_executor.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/xnnpack/executor/xnn_executor.h new file mode 100644 index 0000000000000000000000000000000000000000..376de821a60acabd138d32b375e1c833bd077886 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/xnnpack/executor/xnn_executor.h @@ -0,0 +1,73 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +// Copyright (c) Meta Platforms, Inc. and affiliates. +// +// This source code is licensed under the BSD-style license found in the +// LICENSE file in the root directory of this source tree. + +#pragma once +#include +#include +#include + +namespace torch::jit::xnnpack::delegate { + +class XNNExecutor { + private: + std::unique_ptr runtime_{ + nullptr, + &xnn_delete_runtime}; + std::vector input_ids_; + std::vector output_ids_; + std::vector externals_; + + public: + XNNExecutor() = default; + + template + bool set_inputs(std::vector& inputs, std::vector& outputs) { + externals_.clear(); + + if (inputs.size() != input_ids_.size()) { + return false; + } + + for (int i = 0; i < inputs.size(); i++) { + externals_.emplace_back(xnn_external_value{input_ids_[i], inputs[i]}); + } + + if (outputs.size() != output_ids_.size()) { + return false; + } + + for (int i = 0; i < outputs.size(); i++) { + externals_.emplace_back(xnn_external_value{output_ids_[i], outputs[i]}); + } + + return true; + } + + bool forward() { + xnn_status status = + xnn_setup_runtime(runtime_.get(), externals_.size(), externals_.data()); + + if (status != xnn_status_success) { + return false; + } + + status = xnn_invoke_runtime(runtime_.get()); + + if (status != xnn_status_success) { + return false; + } + + return true; + } + + friend class XNNCompiler; +}; + +} // namespace torch::jit::xnnpack::delegate + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/xnnpack/serialization/serializer.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/xnnpack/serialization/serializer.h new file mode 100644 index 0000000000000000000000000000000000000000..1ca44842bad03c04d60d83a20a67ae8f845a1213 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/xnnpack/serialization/serializer.h @@ -0,0 +1,94 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +// Copyright (c) Meta Platforms, Inc. and affiliates. +// +// This source code is licensed under the BSD-style license found in the +// LICENSE file in the root directory of this source tree. + +#include +#include +#include +#include +#include + +namespace torch { +namespace jit { +namespace xnnpack { +namespace delegate { + +using namespace fb_xnnpack; // Specified in the schema + +class XNNSerializer { + public: + // Constructors + // initial buffersize of 1024 which will grow + // automatically, constant buffer and buffer sizes initialized with dummy + // values as 0 index is reserved for non-constant tensors + XNNSerializer() : XNNSerializer(1024) {} + + explicit XNNSerializer(size_t bufferSize) + : _builder(bufferSize), + _nodes(), + _values(), + _constantBuffer({CreateBuffer( + _builder, + {})}), // index 0 is reserved for non-const data + _bufferSizes({0}) {} + + // Serializing Nodes + + // Serialize add node, we are serializing the argument needed to call + // xnn_define_add2. Serializing these values, and at run time we build + // the graph by re running xnn_define_add2 + void serializeAddNode( + uint32_t input1_id, + uint32_t input2_id, + uint32_t output_id, + uint32_t flags); + + // Serializing Values + void serializeTensorValue( + uint32_t xnn_datatype, + size_t num_dims, + std::vector dims, + size_t buffer_data_idx, + uint32_t external_id, + uint32_t flags, + uint32_t id_out); + + // finish and serialize xnngraph returning serialized data + std::string finishAndSerialize( + std::vector input_ids, + std::vector output_ids, + size_t num_extern_ids); + + // decoupled data serialization with tensor values. This way constant tensor + // data can be referenced by multiple intermediate tensors. This call + // serializes the num_bytes of the data_ptr and returns the index it was + // placed in. + size_t serializeData(const uint8_t* data_ptr, size_t num_bytes); + + private: + // xnnpack version we are serializing + const char* _version_sha1 = "ae108ef49aa5623b896fc93d4298c49d1750d9ba"; + + // flatbuffer objects we will create and serialize together to create xnngraph + flatbuffers_fbsource::FlatBufferBuilder _builder; + + // Vector of the serialized xnnpack nodes + std::vector> _nodes; + + // Vector of the serialized xnnpack values + std::vector> _values; + + std::vector> _constantBuffer; + std::vector _bufferSizes; +}; + +} // namespace delegate +} // namespace xnnpack +} // namespace jit +} // namespace torch + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/xnnpack/xnnpack_graph_builder.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/xnnpack/xnnpack_graph_builder.h new file mode 100644 index 0000000000000000000000000000000000000000..369d56f8d9a33971d3047c5c499fe014a4dea7c9 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/backends/xnnpack/xnnpack_graph_builder.h @@ -0,0 +1,102 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +// Copyright (c) Meta Platforms, Inc. and affiliates. +// +// This source code is licensed under the BSD-style license found in the +// LICENSE file in the root directory of this source tree. + +#include +#include +#include +#include +#include +#include + +#include + +namespace torch { +namespace jit { +namespace xnnpack { +namespace delegate { + +class XNNGraph { + private: + const float output_min = -std::numeric_limits::infinity(); + const float output_max = std::numeric_limits::infinity(); + + // serializer class + XNNSerializer _serializer; + // xnn subgraph + xnn_subgraph_t _subgraph_ptr; + // Set of all the tensor values throughout the jit graph + std::unordered_set _intermediate_tensors; + // Set of all the tensor values mapped to the xnnpack ids + std::unordered_map _val_to_ids; + // Vector containing the torch valued inputs/outputs, + // must be ordered to preserve the order of input/outputs + std::vector _inputs; + std::vector _outputs; + + // Graph passes for optimizing and tracing torchscript graph + // Essentially massaging the graph into a digestiable format for + // xnnpack graph lowering. + std::shared_ptr optimizeAndTraceGraph( + std::shared_ptr graph, + std::vector& example_inputs); + + // Gather all the intermediate tensor values within a graph. This + // skips through all prim constants. The purpose of this is for defining + // the tensor values beforehand for the xnnpack subgraph. + void gatherTensorValues(std::shared_ptr& graph); + + // Gathers the tensor values in a give node + void gatherNodeInputs(torch::jit::Node& node); + + // Helper function to determine if a jit value is a graph input + bool isGraphInput(torch::jit::Value* val); + + // Helper function to determine if a jit value is a graph output + bool isGraphOutput(torch::jit::Value* val); + + // Defines all xnnpack nodes for the nodes in the graph + void defineAllNodes(std::shared_ptr& graph); + + // Defines all xnn tensor values used throughout the graph + void defineAllTensorValues(); + + // Makes a pass through the graph and throws if any ops are unsupported + void checkOpsToDelegate(std::shared_ptr& graph); + + public: + XNNGraph() : _serializer(), _subgraph_ptr(nullptr) { + xnn_status status = xnn_initialize(/*allocator =*/nullptr); + TORCH_CHECK(xnn_status_success == status, "Failed to initialize xnnpack"); + } + + ~XNNGraph() { + xnn_deinitialize(); + if (_subgraph_ptr != nullptr) { + xnn_delete_subgraph(_subgraph_ptr); + } + } + + void buildXNNGraph( + std::shared_ptr& graph, + std::vector example_inputs); + + void runGraphOnInputs( + std::vector tensor_inputs, + std::vector tensor_outputs); + + std::string serializedXNNGraph(); + + std::vector> getGraphOutputShapes(); +}; + +} // namespace delegate +} // namespace xnnpack +} // namespace jit +} // namespace torch + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/cuda/interface.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/cuda/interface.h new file mode 100644 index 0000000000000000000000000000000000000000..211a2fe3a749f934e4c9347b46fb0c6eb111e7f6 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/cuda/interface.h @@ -0,0 +1,57 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#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::jit::fuser::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& /*graph*/); +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 torch::jit::fuser::cuda + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/arg_spec.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/arg_spec.h new file mode 100644 index 0000000000000000000000000000000000000000..3621030aed0ee08ccf973d0d64ebe2592118a851 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/arg_spec.h @@ -0,0 +1,60 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include +#include // fmap +#include +#include +#include + +#include +#include + +namespace torch::jit::fuser { + +// Describes the (runtime) arguments to a kernel. +// ArgSpecs are also used as keys to lookup instantiated kernels, so +// they are hashable. +// Note: the device to run on is included in the arg spec because kernels +// are compiled per-device. +struct TORCH_API ArgSpec { + ArgSpec(at::TensorList inputs, const int _device) + : descs_{c10::fmap(inputs)}, + hash_code_{c10::get_hash(_device, inputs.size(), descs_)}, + device_{_device} {} + + // (Common) hash function + static size_t hash(const ArgSpec& spec) { + return spec.hash_code_; + } + + // Comparators + bool operator==(const ArgSpec& other) const { + return (descs_ == other.descs_ && device_ == other.device_); + } + + bool operator!=(const ArgSpec& spec) const { + return !(*this == spec); + } + + // Getters + size_t hashCode() const { + return hash_code_; + } + const std::vector& descs() const { + return descs_; + } + int device() const { + return device_; + } + + private: + std::vector descs_; + size_t hash_code_; + int device_; +}; + +} // namespace torch::jit::fuser + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/codegen.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/codegen.h new file mode 100644 index 0000000000000000000000000000000000000000..1cc359481bf7cb9eb5b1bf72b1f7043bf0612309 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/codegen.h @@ -0,0 +1,29 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include + +#include +#include + +namespace torch::jit::fuser { + +// Creates a CPU or CUDA kernel for the given graph. +// Returns the C++ or CUDA string implementing the kernel. +TORCH_API std::string generateKernel( + const std::string& name, + const Graph& graph, + const std::vector>>& + inputs, + const std::vector>& outputs, + const bool use_cuda); + +} // namespace torch::jit::fuser + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/compiler.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/compiler.h new file mode 100644 index 0000000000000000000000000000000000000000..e76959805a5cdee9d94582b09f76d3750e0ecdc4 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/compiler.h @@ -0,0 +1,61 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +namespace torch::jit::fuser { + +// Performs device-independent "upfront" compilation of the given fusion_group, +// if it has not been registered already. +// Returns a key that can be used to run the fusion later +TORCH_API int64_t registerFusion(const Node* fusion_group); + +// Performs device-specific "runtime" compilation of the given kernel +// with the runtime arguments specified in ArgSpec. +// Outputs are allocated using map_size on the specified device. +TORCH_API std::shared_ptr compileKernel( + const KernelSpec& spec, + const ArgSpec& arg_spec, + const std::vector& map_size, + const at::Device& device); + +TORCH_API size_t nCompiledKernels(); + +TORCH_API int debugFuser(); + +using FusedKernelConstructor = std::function( + int16_t device, + std::string name, + std::string code, + std::vector input_desc, + std::vector output_desc, + std::vector chunk_desc, + std::vector concat_desc, + bool has_random)>; + +TORCH_API void registerFusionBackend( + at::Device::Type backend_type, + FusedKernelConstructor ctor); +TORCH_API bool hasFusionBackend(at::Device::Type backend_type); +struct TORCH_API RegisterFusionBackend{RegisterFusionBackend( + at::Device::Type backend_type, + FusedKernelConstructor ctor){ + registerFusionBackend(backend_type, std::move(ctor)); +} // namespace torch::jit::fuser +} +; + +} // namespace torch::jit::fuser + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/cpu/fused_kernel.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/cpu/fused_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..13e37fe47a442853f902b18967222dfd930cec2c --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/cpu/fused_kernel.h @@ -0,0 +1,44 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include + +#include +#include +#include + +namespace torch::jit::fuser::cpu { + +// Represents a compiled CPU kernel and the metadata necessary to run it +struct TORCH_API FusedKernelCPU : public FusedKernel { + FusedKernelCPU( + std::string name, + std::string code, + std::vector input_desc, + std::vector output_desc, + std::vector chunk_desc, + std::vector concat_desc, + bool has_random); + + at::Backend backend() const override { + return at::Backend::CPU; + } + + void launch_raw(const uint32_t numel, std::vector& arguments) + const override { + kernel(numel, arguments.data()); + } + + private: + std::unique_ptr so_lib; + void (*kernel)(uint32_t, void**) = nullptr; +}; + +} // namespace torch::jit::fuser::cpu + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/cpu/resource_strings.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/cpu/resource_strings.h new file mode 100644 index 0000000000000000000000000000000000000000..62c3008b31ff5ecacfca5541068ced287dcb84cc --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/cpu/resource_strings.h @@ -0,0 +1,106 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit::fuser::cpu { + +/*with type_as not checking type of its input, a fusion group can have non-fp32 +tensor as input. Correct code for this case is generated, however, nvrtc does +not know how to handle int*_t integer types, so typedefs help it handle those +cases*/ + +static auto type_declarations_template = at::jit::CodeTemplate(R"( + +#define POS_INFINITY INFINITY +#define NEG_INFINITY -INFINITY + +typedef ${IndexType} IndexType; +template +struct TensorInfo { + T* data; + IndexType sizes[N]; + IndexType strides[N]; +}; +template +struct TensorInfo { + T * data; +}; +)"); + +static auto cpu_compilation_unit_template = at::jit::CodeTemplate(R"( +#include +#include +#include + +double rsqrt(double x) { + return 1.0/sqrt(x); +} + +float rsqrtf(float x) { + return 1.0f/sqrtf(x); +} + +double frac(double x) { + return x - trunc(x); +} + +float fracf(float x) { + return x - truncf(x); +} + +${type_declarations} + +#ifdef _MSC_VER +template struct int_of_size; + +#define DEFINE_INT_OF_SIZE(int_t) \ +template<> struct int_of_size { using type = int_t; } + +DEFINE_INT_OF_SIZE(int64_t); +DEFINE_INT_OF_SIZE(int32_t); +DEFINE_INT_OF_SIZE(int16_t); +DEFINE_INT_OF_SIZE(int8_t); + +#undef DEFINE_INT_OF_SIZE + +template +using int_same_size_t = typename int_of_size::type; + +#define IndexTypeLoop int_same_size_t +#define ToIndexTypeLoop(x) static_cast(x) +#else +#define IndexTypeLoop IndexType +#define ToIndexTypeLoop(x) x +#endif + +#define OMP_THRESHOLD 100000 +static void ${kernelName}_kernel(IndexType totalElements, ${formals}) { + #pragma omp parallel for if(totalElements > OMP_THRESHOLD) + for (IndexTypeLoop linearIndex = 0; + linearIndex < ToIndexTypeLoop(totalElements); + linearIndex += 1) { + // Convert `linearIndex` into an offset of tensor: + ${tensorOffsets} + // calculate the results + ${kernelBody} + } +} + +#ifdef _WIN32 +#define JIT_API __declspec(dllexport) +#else +#define JIT_API +#endif + +extern "C" +JIT_API void ${kernelName}(IndexType totalElements, void ** args) { + ${kernelName}_kernel(totalElements ${,argument_loads}); +} +)"); + +} // namespace torch::jit::fuser::cpu + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/cpu/temp_file.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/cpu/temp_file.h new file mode 100644 index 0000000000000000000000000000000000000000..726ca1e7cc63e1fa32a04b9ca9995aad365ff778 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/cpu/temp_file.h @@ -0,0 +1,140 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include + +#ifdef _WIN32 +#include +#include +#include +#include +#include +#include +#include +#include +#include +#else +#include +#endif + +#include +#include + +namespace torch::jit::fuser::cpu { + +#ifdef _MSC_VER +inline int wmkstemps(wchar_t* tmpl, int suffix_len) { + int len; + wchar_t* name; + int fd = -1; + int save_errno = errno; + + len = wcslen(tmpl); + if (len < 6 + suffix_len || + wcsncmp(&tmpl[len - 6 - suffix_len], L"XXXXXX", 6)) { + return -1; + } + + name = &tmpl[len - 6 - suffix_len]; + + std::random_device rd; + do { + for (unsigned i = 0; i < 6; ++i) { + name[i] = "abcdefghijklmnopqrstuvwxyz0123456789"[rd() % 36]; + } + + fd = _wopen(tmpl, _O_RDWR | _O_CREAT | _O_EXCL, _S_IWRITE | _S_IREAD); + } while (errno == EEXIST); + + if (fd >= 0) { + errno = save_errno; + return fd; + } else { + return -1; + } +} +#endif + +struct TempFile { + AT_DISALLOW_COPY_AND_ASSIGN(TempFile); + + TempFile(const std::string& t, int suffix) { +#ifdef _MSC_VER + auto wt = c10::u8u16(t); + std::vector tt(wt.c_str(), wt.c_str() + wt.size() + 1); + int fd = wmkstemps(tt.data(), suffix); + AT_ASSERT(fd != -1); + file_ = _wfdopen(fd, L"r+"); + auto wname = std::wstring(tt.begin(), tt.end() - 1); + name_ = c10::u16u8(wname); +#else + // mkstemps edits its first argument in places + // so we make a copy of the string here, including null terminator + std::vector tt(t.c_str(), t.c_str() + t.size() + 1); + int fd = mkstemps(tt.data(), suffix); + AT_ASSERT(fd != -1); + file_ = fdopen(fd, "r+"); + // - 1 because tt.size() includes the null terminator, + // but std::string does not expect one + name_ = std::string(tt.begin(), tt.end() - 1); +#endif + } + + const std::string& name() const { + return name_; + } + + void sync() { + fflush(file_); + } + + void write(const std::string& str) { + size_t result = fwrite(str.c_str(), 1, str.size(), file_); + AT_ASSERT(str.size() == result); + } + +#ifdef _MSC_VER + void close() { + if (file_ != nullptr) { + fclose(file_); + } + file_ = nullptr; + } +#endif + + FILE* file() { + return file_; + } + + ~TempFile() { +#ifdef _MSC_VER + if (file_ != nullptr) { + fclose(file_); + } + auto wname = c10::u8u16(name_); + if (!wname.empty() && _waccess(wname.c_str(), 0) != -1) { + _wunlink(wname.c_str()); + } +#else + if (file_ != nullptr) { + // unlink first to ensure another mkstemps doesn't + // race between close and unlink + unlink(name_.c_str()); + fclose(file_); + } +#endif + } + + private: + FILE* file_ = nullptr; + std::string name_; +}; + +} // namespace torch::jit::fuser::cpu + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/cuda/fused_kernel.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/cuda/fused_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..85c23b394ab73e4cce98eb632a4979059f2429d3 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/cuda/fused_kernel.h @@ -0,0 +1,64 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +#include +#include +#include + +#include +#include +#include + +namespace torch::jit::fuser::cuda { + +// query codegen output arch and target +TORCH_CUDA_CU_API void codegenOutputQuery( + const cudaDeviceProp* const prop, + int& major, + int& minor, + bool& compile_to_sass); + +// A class holding metadata for an actual CUDA function. +// Note: CUDA functions are per device. +struct TORCH_CUDA_CU_API FusedKernelCUDA + : public ::torch::jit::fuser::FusedKernel { + FusedKernelCUDA( + at::DeviceIndex device, + std::string name, + std::string code, + std::vector input_desc, + std::vector output_desc, + std::vector chunk_desc, + std::vector concat_desc, + bool has_random); + + ~FusedKernelCUDA() override; + + void launch_raw(const uint32_t numel, std::vector& arguments) + const override; + + at::Backend backend() const override { + return at::Backend::CUDA; + } + + private: + static constexpr auto kBlockSize = 128; + + // Note: per device to store device properties and compute launch heuristics + // Acquiring these values at launch time would be too slow + at::DeviceIndex device_; + int maxBlocks_{}; + cudaDeviceProp* prop_{}; + std::vector ptx_; + CUmodule module_{}; + CUfunction function_{}; +}; + +} // namespace torch::jit::fuser::cuda + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/cuda/resource_strings.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/cuda/resource_strings.h new file mode 100644 index 0000000000000000000000000000000000000000..b495251ad391d9d9a86ab1c8867e84dfd1f07f07 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/cuda/resource_strings.h @@ -0,0 +1,417 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +namespace torch::jit::fuser::cuda { + +/*with type_as not checking type of its input, a fusion group can have non-fp32 +tensor as input. Correct code for this case is generated, however, nvrtc does +not know how to handle int*_t integer types, so typedefs help it handle those +cases*/ + +static constexpr auto bfloat16_type_string = "__nv_bfloat16"; + +#if defined(USE_ROCM) && ROCM_VERSION < 70000 +static auto type_declarations_template = at::jit::CodeTemplate(R"( +${HalfHeader} +${BFloat16Header} +${RandHeader} + +#define NAN __int_as_float(0x7fffffff) +#define POS_INFINITY __int_as_float(0x7f800000) +#define NEG_INFINITY __int_as_float(0xff800000) + +typedef ${IndexType} IndexType; +template +struct TensorInfo { + T* data; + IndexType sizes[N]; + IndexType strides[N]; +}; +template +struct TensorInfo { + T * data; +}; +)"); +#else +static auto type_declarations_template = at::jit::CodeTemplate(R"( +typedef unsigned char uint8_t; +typedef signed char int8_t; +typedef short int int16_t; +typedef long long int int64_t; +typedef unsigned long long int uint64_t; +${HalfHeader} +${BFloat16Header} +${RandHeader} + +#define NAN __int_as_float(0x7fffffff) +#define POS_INFINITY __int_as_float(0x7f800000) +#define NEG_INFINITY __int_as_float(0xff800000) + +typedef ${IndexType} IndexType; +template +struct TensorInfo { + T* data; + IndexType sizes[N]; + IndexType strides[N]; +}; +template +struct TensorInfo { + T * data; +}; +)"); +#endif + +// We rewrite the code for philox RNG from curand as nvrtc couldn't resolve the +// curand header correctly. +constexpr auto rand_support_literal = 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 uniform(unsigned int x) { + return x * M_RAN_INVM32; + } +)"; + +constexpr auto rand_param = + ",unsigned long long seed, unsigned long long offset"; + +constexpr auto rand_init = R"( + int idx = blockIdx.x*blockDim.x + threadIdx.x; + Philox rnd(seed, idx, offset); +)"; + +static auto cuda_compilation_unit_template = at::jit::CodeTemplate(R"( +${type_declarations} + +extern "C" __global__ +void ${kernelName}(IndexType totalElements, ${formals} ${RandParam}) { + ${RandInit} + // check whether do vectorized load/store and allocate buffer + bool flag_vec4 = true; + ${tensorChecks} + if (flag_vec4) { + for (IndexType linearIndex = 4 * (blockIdx.x * blockDim.x + threadIdx.x); + linearIndex < totalElements; + linearIndex += 4 * gridDim.x * blockDim.x) { + // Convert `linearIndex` into an offset of tensor as it is: + ${tensorOffsets} + // load 4 at a time + ${kernelLoad} + #pragma unroll 4 + for (int i=0; i<4; i++) { + // calculate the results + ${kernelBody_vec4} + } + // store 4 at a time + ${kernelStore} + } + } else { + for (IndexType linearIndex = blockIdx.x * blockDim.x + threadIdx.x; + linearIndex < totalElements; + linearIndex += gridDim.x * blockDim.x) { + // Convert `linearIndex` into an offset of tensor: + ${tensorOffsets} + // calculate the results + ${kernelBody} + } + } +} +)"); + +// This snippet enables half support in the jit. Following the pattern for +// reductions, fp16 input data is immediately upconverted to float +// with __half2float(). All mathematical operations are done on float +// values, and if needed the intermediate float representation is +// converted to half with __float2half() when writing to a half tensor. +#if defined(USE_ROCM) +constexpr auto half_support_literal = + R"( +typedef __half half; +)"; +#else +constexpr auto half_support_literal = + R"( +#define __HALF_TO_US(var) *(reinterpret_cast(&(var))) +#define __HALF_TO_CUS(var) *(reinterpret_cast(&(var))) +#if defined(__cplusplus) + struct __align__(2) __half { + __host__ __device__ __half() { } + + protected: + unsigned short __x; + }; + + /* All intrinsic functions are only available to nvcc compilers */ + #if defined(__CUDACC__) + /* Definitions of intrinsics */ + __device__ __half __float2half(const float f) { + __half val; + asm("{ cvt.rn.f16.f32 %0, %1;}\n" : "=h"(__HALF_TO_US(val)) : "f"(f)); + return val; + } + + __device__ float __half2float(const __half h) { + float val; + asm("{ cvt.f32.f16 %0, %1;}\n" : "=f"(val) : "h"(__HALF_TO_CUS(h))); + return val; + } +)" + // MSVC's preprocessor (but not the standard compiler) has a bug + // where it incorrectly tokenizes raw string literals, ending when it sees a + // " this causes the #endif in this string literal to be treated as a + // preprocessor token which, in turn, cause sccache on windows CI to fail. + // See https://godbolt.org/z/eVTIJq as an example. + // This workaround uses string-pasting to separate the " and the #endif into + // different strings + R"( + #endif /* defined(__CUDACC__) */ +#endif /* defined(__cplusplus) */ +#undef __HALF_TO_US +#undef __HALF_TO_CUS + +typedef __half half; +)"; +#endif + +#if defined(USE_ROCM) + +#if ROCM_VERSION >= 70000 +#define BF16_UINT32_DEF "typedef unsigned int uint32_t;\n" +#else +#define BF16_UINT32_DEF "" +#endif + +constexpr auto bfloat16_support_literal = + R"( +#ifndef __align__ +#define __align__(x) __attribute__((aligned(x))) +#endif +)" BF16_UINT32_DEF R"( +typedef struct __align__(2) { + unsigned short x; +} +__nv_bfloat16_raw; + +#if defined(__cplusplus) +struct __align__(2) __nv_bfloat16 { + __host__ __device__ __nv_bfloat16() {} + + __host__ __device__ __nv_bfloat16& operator=(const __nv_bfloat16_raw& hr) { + __x = hr.x; + return *this; + } + + unsigned short __x; +}; + +__device__ unsigned short __internal_float2bfloat16( + const float f, + unsigned int& sign, + unsigned int& remainder) { + unsigned int x; + + x = __float_as_uint(f); + + if ((x & 0x7fffffffU) > 0x7f800000U) { + sign = 0U; + remainder = 0U; + return static_cast(0x7fffU); + } + sign = x >> 31; + remainder = x << 16; + return static_cast(x >> 16); +} + +/* Definitions of intrinsics */ +__device__ __nv_bfloat16 __float2bfloat16(const float a) { + __nv_bfloat16 val; + __nv_bfloat16_raw r; + unsigned int sign; + unsigned int remainder; + r.x = __internal_float2bfloat16(a, sign, remainder); + if ((remainder > 0x80000000U) || + ((remainder == 0x80000000U) && ((r.x & 0x1U) != 0U))) { + r.x++; + } + val = r; + return val; +} + +__device__ float __bfloat162float(const __nv_bfloat16 a) { + union + { + uint32_t int32; + float fp32; + } u = {uint32_t(a.__x) << 16}; + return u.fp32; +} +#endif /* defined(__cplusplus) */ +)"; +#else +constexpr auto bfloat16_support_literal = + R"( +#define __BFLOAT16_TO_US(var) *(reinterpret_cast(&(var))) +#define __BFLOAT16_TO_CUS(var) \ + *(reinterpret_cast(&(var))) + +typedef struct __align__(2) { + unsigned short x; +} +__nv_bfloat16_raw; + +#if defined(__cplusplus) +struct __align__(2) __nv_bfloat16 { + __host__ __device__ __nv_bfloat16() {} + + __host__ __device__ __nv_bfloat16& operator=(const __nv_bfloat16_raw& hr) { + __x = hr.x; + return *this; + } + + protected: + unsigned short __x; +}; + +#if defined(__CUDACC__) +__device__ unsigned short __internal_float2bfloat16( + const float f, + unsigned int& sign, + unsigned int& remainder) { + unsigned int x; + + x = __float_as_uint(f); + + if ((x & 0x7fffffffU) > 0x7f800000U) { + sign = 0U; + remainder = 0U; + return static_cast(0x7fffU); + } + sign = x >> 31; + remainder = x << 16; + return static_cast(x >> 16); +} + +/* Definitions of intrinsics */ +__device__ __nv_bfloat16 __float2bfloat16(const float a) { + __nv_bfloat16 val; +#if __CUDA_ARCH__ >= 800 + asm("{ cvt.rn.bf16.f32 %0, %1;}\n" : "=h"(__BFLOAT16_TO_US(val)) : "f"(a)); +#else + __nv_bfloat16_raw r; + unsigned int sign; + unsigned int remainder; + r.x = __internal_float2bfloat16(a, sign, remainder); + if ((remainder > 0x80000000U) || + ((remainder == 0x80000000U) && ((r.x & 0x1U) != 0U))) { + r.x++; + } + val = r; +#endif + return val; +} + +__device__ float __bfloat162float(const __nv_bfloat16 a) { + float val; + asm("{ mov.b32 %0, {0,%1};}\n" : "=f"(val) : "h"(__BFLOAT16_TO_CUS(a))); + return val; +} +#endif /* defined(__CUDACC__) */ +#endif /* defined(__cplusplus) */ +#undef __BFLOAT16_TO_US +#undef __BFLOAT16_TO_CUS +)"; +#endif + +} // namespace torch::jit::fuser::cuda + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/executor.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/executor.h new file mode 100644 index 0000000000000000000000000000000000000000..aa6c691a0b807558cb4f5ce030dd156afb128a18 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/executor.h @@ -0,0 +1,24 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include + +#include + +namespace torch::jit::fuser { + +// Runs the fusion associated with the key (see registerFusion() in interface.h) +// on the inputs taken from the given Stack. +TORCH_API bool runFusion( + const int64_t key, + Stack& stack, + std::string* code_out = nullptr); + +} // namespace torch::jit::fuser + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/fallback.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/fallback.h new file mode 100644 index 0000000000000000000000000000000000000000..393127a6e99dc29fa41aecbb36d7e437e3a5bd51 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/fallback.h @@ -0,0 +1,16 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +#include + +namespace torch::jit::fuser { + +void runFallback(int64_t key, Stack& stack); + +} // namespace torch::jit::fuser + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/fused_kernel.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/fused_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..ca2adedd7b196d1db9dddca4b3319c51e7060226 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/fused_kernel.h @@ -0,0 +1,103 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include + +#include +#include +#include + +namespace torch::jit::fuser { + +struct FusedKernel { + AT_DISALLOW_COPY_AND_ASSIGN(FusedKernel); + + FusedKernel( + std::string name, + std::string code, + std::vector input_desc, + std::vector output_desc, + std::vector chunk_desc, + std::vector concat_desc, + bool has_random) + : name_(std::move(name)), + code_(std::move(code)), + input_desc_(std::move(input_desc)), + output_desc_(std::move(output_desc)), + chunk_desc_(std::move(chunk_desc)), + concat_desc_(std::move(concat_desc)), + has_random_(has_random) {} + + virtual ~FusedKernel() = default; + + // arguments is a list of pointers to the arguments for the compiled CUDA/CPU + // code. + // The format of arguments is suitable for directly passing to a call to + // cuLaunchKernel as the kernel arguments. + // Currently the first argument is a pointer to numel (for passing to + // CUDA code), and the remainder are pointers to the TensorInfo structs + // that compiled code uses to load Tensor data. + // launch_with_tensors handles packing at::Tensors into this arguments array. + // CPU code uses the same convention so that launch_with_tensors can be + // shared. + virtual void launch_raw(const uint32_t numel, std::vector& arguments) + const = 0; + virtual at::Backend backend() const = 0; + + // Getters + const std::string& name() const { + return name_; + } + const std::string& code() const { + return code_; + } + const std::vector& inputDesc() const { + return input_desc_; + } + const std::vector& outputDesc() const { + return output_desc_; + } + const std::vector& chunkDesc() const { + return chunk_desc_; + } + const std::vector& concatDesc() const { + return concat_desc_; + } + bool hasRandom() const { + return has_random_; + } + + protected: + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + const std::string name_; + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + const std::string code_; + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + const std::vector input_desc_; + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + const std::vector output_desc_; + + // same size as input_desc, describes whether an + // input should be broken into subtensors (chunks) + // to be consumed by the fusion group + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + const std::vector chunk_desc_; + + // same size as output_desc, describes whether + // an output is actually a concatenation of + // many subtensors that the fusion group produces + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + const std::vector concat_desc_; + + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + const bool has_random_; +}; + +} // namespace torch::jit::fuser + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/interface.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/interface.h new file mode 100644 index 0000000000000000000000000000000000000000..516e192a0fb38a1c4af1cd56a9bff94509335347 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/interface.h @@ -0,0 +1,59 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include + +#include +#include +#include + +namespace torch::jit { + +constexpr int kCPUDevice = -1; + +// Assigns a "key" to the given fusion_group that it can use to run its +// fusion later (via runFusion() below). +TORCH_API int64_t registerFusion(const Node* fusion_group); + +// Runs the fusion corresponding to the given key on the inputs +// found on the stack. Outputs are placed on the same stack. +// In some cases a fusion cannot be run and a fallback path where +// PyTorch's interpreter runs the graph instead is attempted. +TORCH_API void runFusion(const int64_t key, Stack& stack); + +// True if the respective devices can fuse, false otherwise +TORCH_API bool canFuseOnCPU(); +TORCH_API bool canFuseOnGPU(); + +// Sets whether fusion on the CPU is allowed (disabled by default due to +// flakiness) +TORCH_API void overrideCanFuseOnCPU(bool value); + +// Sets whether fusion on CPU must use LLVM Codegen and not SimplieIREval +TORCH_API void overrideMustUseLLVMOnCPU(bool value); + +// Sets whether fusion on the GPU is allowed (enabled by default) +TORCH_API void overrideCanFuseOnGPU(bool value); + +// Treats the given graph as a fusion group and launches it on the +// specified device with the given inputs. +// Returns the outputs. +TORCH_API std::vector debugLaunchGraph( + Graph& graph, + at::ArrayRef inputs); + +// Treats the given graph as a fusion group and returns the generated code. +TORCH_API std::string debugGetFusedKernelCode( + Graph& graph, + at::ArrayRef inputs); + +TORCH_API size_t nCompiledKernels(); + +} // namespace torch::jit + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/kernel_cache.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/kernel_cache.h new file mode 100644 index 0000000000000000000000000000000000000000..d2446f6aa8af57c66c8eeef1c5198cf5199e966f --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/kernel_cache.h @@ -0,0 +1,38 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +#include +#include +#include + +namespace torch::jit::fuser { + +// A thread-safe cache interface. + +// Normalizes the graph by canonicalizing and erasing shape information +TORCH_API std::shared_ptr normalizeGraphForCache( + const std::shared_ptr& graph); + +// Stores the given graph, returning the key used to access it +TORCH_API int64_t store(std::shared_ptr graph); + +// Given a graph, find a KernelSpec based on it +TORCH_API std::optional lookupGraph( + const std::shared_ptr& graph); + +// Returns the graph corresponding to the given key (if it exists) +TORCH_API std::optional retrieve(const int64_t key); + +// Returns the size of the fusion key -> KernelSpec cache. +// Only used for testing. +TORCH_API int64_t debugNumCachedKernelSpecs(); + +} // namespace torch::jit::fuser + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/kernel_spec.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/kernel_spec.h new file mode 100644 index 0000000000000000000000000000000000000000..a84bcc7b3b7c18de8bda1dfc1905a44f77cead26 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/kernel_spec.h @@ -0,0 +1,149 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace torch::jit::fuser { + +// Helper struct containing partition information: the number of tensors +// created and the dimension the partitioning is performed on. +// Note: created during upfront compilation, once the tensors are known +// at runtime the partition info is logically combined with the tensor +// descriptions to create PartitionDesc objects. +struct TORCH_API PartitionInfo { + PartitionInfo(const int64_t _nSubTensors, const int64_t _dim) + : nSubTensors_{_nSubTensors}, dim_{_dim} {} + + int64_t nSubTensors() const { + return nSubTensors_; + } + int64_t dim() const { + return dim_; + } + + private: + int64_t nSubTensors_; + int64_t dim_; +}; + +// "Kernel Specification." - Contains device-independent fusion information. +// Each kernel specification contains a map of instantiated generated functions +// that implement some or most of its functionality. Multiple generated +// functions are needed by each abstract specification because of different +// devices (cpu vs gpu, different gpus) and different inputs (int vs float, +// contiguous vs discontiguous). +// Note: uses a mutex to control access to its kernel store +// Note: unordered containers do not invalidate references/pointers on +// rehashing, which is critical for thread-safety. +// TODO: allow abstract kernels to use multiple generated kernels +// TODO: allow abstract kernels to reuse generated kernels from common pool +struct TORCH_API KernelSpec { + // Note: assumes the spec is a single block + // Note: This is the appropriate place to generalize if you want to add other + // passes to upfront compilation that walk the graph. + KernelSpec(const int64_t _key, const std::shared_ptr& _graph) + : key_{_key}, + graph_{_graph}, + code_{_graph, ""}, + nInputs_{_graph->inputs().size()} + + { + // No need to iterate over reference since n is pointer + for (const auto n : graph_->nodes()) { + static_assert(std::is_pointer_v, "n must be a pointer"); + if (n->kind() == aten::rand_like) { + has_random_ = true; + break; + } + } + nTensorInputs_ = std::count_if( + graph_->inputs().begin(), graph_->inputs().end(), [](const Value* v) { + return v->type()->isSubtypeOf(*TensorType::get()); + }); + } + + // Getters + int64_t key() const { + return key_; + } + std::shared_ptr graph() const { + return graph_; + } + const Code& code() const { + return code_; + } + int64_t nInputs() const { + return nInputs_; + } + int64_t nTensorInputs() const { + return nTensorInputs_; + } + + std::vector>& inputBroadcastGroups() { + return inputBroadcastGroups_; + } + const std::vector>& inputBroadcastGroups() const { + return inputBroadcastGroups_; + } + + std::vector& inputChunks() { + return inputChunks_; + } + const std::vector& inputChunks() const { + return inputChunks_; + } + + bool hasRandom() const { + return has_random_; + } + + // Cache functions + std::optional> findKernel( + const ArgSpec& arg_spec) const { + std::lock_guard guard{mutex_}; + const auto it = kernels_.find(arg_spec); + if (it == kernels_.end()) + return std::nullopt; + return it->second; + } + void cacheKernel( + const ArgSpec& arg_spec, + const std::shared_ptr& kernel) const { + std::lock_guard guard{mutex_}; + kernels_.emplace(arg_spec, kernel); + } + + private: + int64_t key_; + std::shared_ptr graph_; + Code code_; + uint64_t nInputs_; + uint64_t nTensorInputs_{}; + std::vector> inputBroadcastGroups_; + std::vector inputChunks_; + bool has_random_{false}; + mutable std::mutex mutex_; + mutable std:: + unordered_map, c10::hash> + kernels_; +}; + +} // namespace torch::jit::fuser + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/partition_desc.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/partition_desc.h new file mode 100644 index 0000000000000000000000000000000000000000..6eee194e80d162044d5065be72d9e2797df3db2f --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/partition_desc.h @@ -0,0 +1,63 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +#include +#include +#include + +namespace torch::jit::fuser { + +// Descriptor for chunk-ing an input tensor into subtensors +// OR concat-ing an output tensor from subtensors +// Note: default constructed used for tensors that do not participate in +// chunk or cat operations. +struct TORCH_API PartitionDesc { + PartitionDesc() : nSubTensors_{1}, dim_{0} {} + + PartitionDesc(const TensorDesc& _desc, size_t _nSubTensors, size_t _dim) + : nSubTensors_{_nSubTensors}, dim_{_dim} { + AT_ASSERT(nSubTensors_ > 1); + std::vector cont = _desc.contiguity; + if (dim_ > 0) { + // when we narrow the concatenated output/chunked input + // we make the size[dim] smaller while keeping the stride[dim] the same, + // meaning: stride[dim - 1] != stride[dim]*size[dim] + // so dim - 1 is no longer contiguous + cont[dim_ - 1] = false; + } + subTensorDesc_ = std::make_shared(_desc.scalar_type, cont); + } + + bool isNoop() const { + return (nSubTensors_ == 1); + } + size_t nSubTensors() const { + return nSubTensors_; + } + size_t dim() const { + return dim_; + } + std::shared_ptr subTensorDesc() { + return subTensorDesc_; + } + const std::shared_ptr subTensorDesc() const { + return subTensorDesc_; + } + + private: + size_t nSubTensors_; // == 1 for tensors that should not be operated on via + // chunk/cat + size_t dim_; // dimension along which the chunk/concat occurs + std::shared_ptr + subTensorDesc_; // descriptor for the subtensor, if it exists +}; + +} // namespace torch::jit::fuser + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/tensor_desc.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/tensor_desc.h new file mode 100644 index 0000000000000000000000000000000000000000..0376875925a04b26615051b34d72ff4bf481898f --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/tensor_desc.h @@ -0,0 +1,103 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace torch::jit::fuser { + +// type information needed by the compiler for input/outputs +// contiguity[i] is true if the dim i is contiguous with dim i + 1. +// contiguity.back() == true means strides.back() == 1. +struct TORCH_API TensorDesc { + at::ScalarType scalar_type; + std::vector contiguity; + + TensorDesc(const at::ScalarType& type, const std::vector& contiguity) + : scalar_type{type}, contiguity{contiguity} { + if (contiguity.empty()) { + nDim_ = 0; + } else { + nDim_ = std::count(contiguity.begin(), contiguity.end(), false) + + (lastIsContiguous() ? 1 : 0); + } + } + + // Delegating constructors + TensorDesc( + const at::ScalarType& type, + const at::IntArrayRef& sizes, + const at::IntArrayRef& strides) + : TensorDesc(type, TensorDesc::findContiguous(sizes, strides)) {} + + TensorDesc(const at::Tensor& t) + : TensorDesc(t.scalar_type(), t.sizes(), t.strides()) {} + + TensorDesc(const c10::TensorTypePtr& type) + : TensorDesc( + type->scalarType().value(), + type->sizes().concrete_sizes().value(), + type->strides().concrete_sizes().value()) {} + + // number of dimensions after contiguity compression + size_t nDim() const { + return nDim_; + } + + // True iff innermost stride is 1 + bool lastIsContiguous() const { + return (contiguity.empty() || contiguity.back()); + } + + static std::vector findContiguous( + const at::IntArrayRef& sizes, + const at::IntArrayRef& strides) { + AT_ASSERT(sizes.size() == strides.size()); + std::vector cont(sizes.size()); + for (size_t i = 0; i < sizes.size(); ++i) { + const auto expected_stride = + (i + 1 < sizes.size()) ? sizes[i + 1] * strides[i + 1] : 1; + cont[i] = (strides[i] == expected_stride); + } + return cont; + } + + bool operator==(const TensorDesc& desc) const { + return scalar_type == desc.scalar_type && contiguity == desc.contiguity; + } + + bool operator!=(const TensorDesc& desc) const { + return !(*this == desc); + } + + static size_t hash(const TensorDesc& spec) { + return c10::get_hash( + spec.scalar_type, + spec.nDim_, + std::hash>{}(spec.contiguity)); + } + + private: + size_t nDim_; +}; + +inline std::ostream& operator<<(std::ostream& out, const TensorDesc& d) { + out << d.scalar_type << '['; + for (const auto b : d.contiguity) + out << b << ';'; + out << ']'; + return out; +} + +} // namespace torch::jit::fuser + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/tensor_info.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/tensor_info.h new file mode 100644 index 0000000000000000000000000000000000000000..df2c1e12963bdaa58b56e688a3d6b950ee4e2f2d --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/fuser/tensor_info.h @@ -0,0 +1,29 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include + +#include +#include + +namespace torch::jit::fuser { + +// Host-side view of TensorInfo +// Note dims[0] - we need to dynamically allocate the dims. +struct TORCH_API TensorInfo { + uint32_t* sizes(size_t nDim) { + return &sizes_strides[0]; + } + uint32_t* strides(size_t nDim) { + return &sizes_strides[nDim]; + } + + void* data; + // NOLINTNEXTLINE(cppcoreguidelines-avoid-c-arrays,modernize-avoid-c-arrays) + uint32_t sizes_strides[0]; +}; + +} // namespace torch::jit::fuser + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/onednn/LlgaTensorImpl.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/onednn/LlgaTensorImpl.h new file mode 100644 index 0000000000000000000000000000000000000000..72f267a4cffaffb73f8d10d2b1b129efe5cb159f --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/onednn/LlgaTensorImpl.h @@ -0,0 +1,277 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +#include +#include +#include + +namespace torch::jit::fuser::onednn { + +// Engine represents a device and its context. From the device kind, the engine +// knows how to generate code for the target device and what kind of device +// object to be expected. The device id ensures that there is a unique engine +// being created for each device. The device handle passed from PyTorch allows +// oneDNN Graph implementation to work on the device specified by PyTorch, which +// is currently CPU, so we only have one engine. +// Ref: +// https://oneapi-spec.uxlfoundation.org/specifications/oneapi/latest/elements/onednn/source/graph/programming_model#engine +struct Engine { + // CPU engine singleton + static dnnl::engine& getEngine(); + Engine(const Engine&) = delete; + void operator=(const Engine&) = delete; +}; + +// Stream is the logical abstraction for execution units. It is created on top +// of oneDNN Graph engine. A compiled oneDNN Graph partition is submitted to a +// stream for execution. +struct Stream { + // CPU stream singleton + static dnnl::stream& getStream(); + Stream(const Stream&) = delete; + void operator=(const Stream&) = delete; +}; + +struct LlgaTensorDesc { + using desc = dnnl::graph::logical_tensor; + + LlgaTensorDesc( + size_t tid, + std::vector sizes, + std::vector strides, + desc::data_type dtype, + desc::property_type property_type) + : tid_(tid), + sizes_(std::move(sizes)), + strides_(std::move(strides)), + dtype_(dtype), + property_type_(property_type), + layout_type_(desc::layout_type::strided), + layout_id_(-1) {} + + LlgaTensorDesc(const desc& t) + : tid_(t.get_id()), + sizes_(t.get_dims()), + strides_({-1}), + dtype_(t.get_data_type()), + property_type_(t.get_property_type()), + layout_type_(t.get_layout_type()), + layout_id_(-1) { + if (is_opaque()) { + layout_id_ = t.get_layout_id(); + } + if (is_strided()) { + strides_ = t.get_strides(); + } + } + + LlgaTensorDesc(const torch::jit::Value* v) + : LlgaTensorDesc( + v->unique(), + {}, + {}, + desc::data_type::f32, + get_property_type(v)) { + if (v->type()->isSubtypeOf(TensorType::get())) { + auto tt = v->type()->cast(); + + if (tt->scalarType()) { + dtype_ = getLlgaDataType(tt->scalarType().value()); + } + + auto sizes = tt->sizes(); + if (sizes.sizes()) { + for (auto d : *sizes.sizes()) { + sizes_.push_back(d.value_or(DNNL_GRAPH_UNKNOWN_DIM)); + } + } + + auto strides = tt->strides(); + if (strides.sizes()) { + for (auto d : *strides.sizes()) { + strides_.push_back(d.value_or(DNNL_GRAPH_UNKNOWN_DIM)); + } + } + } + } + + LlgaTensorDesc supplementTensorInfo(const at::Tensor& t) const; + + desc::data_type getLlgaDataType(at::ScalarType dt) const; + + at::ScalarType aten_scalar_type() const; + + const std::vector& sizes() const { + return sizes_; + } + + const std::vector& strides() const { + TORCH_CHECK(!is_opaque(), "Cannot get strides on opaque layout"); + return strides_; + } + + size_t tid() const { + return tid_; + } + + LlgaTensorDesc tid(uint64_t new_id) const { + auto ret = *this; + ret.tid_ = new_id; + return ret; + } + + desc::data_type dtype() const { + return dtype_; + } + + LlgaTensorDesc dtype(desc::data_type new_dtype) const { + return LlgaTensorDesc(tid_, sizes_, strides_, new_dtype, property_type_); + } + + desc::layout_type layout_type() const { + return layout_type_; + } + + LlgaTensorDesc layout_type(desc::layout_type new_layout_type) { + auto ret = *this; + ret.layout_type_ = new_layout_type; + return ret; + } + + desc::property_type get_property_type(const torch::jit::Value* v) { + switch (v->node()->kind()) { + case prim::Constant: + return desc::property_type::constant; + default: + return desc::property_type::variable; + } + } + + LlgaTensorDesc any() { + return layout_type(desc::layout_type::any); + } + + size_t storage_size() const { + return logical_tensor().get_mem_size(); + } + + desc logical_tensor() const { + if (is_dimensionality_unknown()) { + return desc( + tid_, dtype_, DNNL_GRAPH_UNKNOWN_NDIMS, layout_type_, property_type_); + } else if (is_opaque()) { + return desc(tid_, dtype_, sizes_, layout_id_, property_type_); + } else if (is_any()) { + return desc(tid_, dtype_, sizes_, layout_type_, property_type_); + } else { + return desc(tid_, dtype_, sizes_, strides_, property_type_); + } + } + + bool is_strided() const { + return layout_type_ == desc::layout_type::strided; + } + + bool is_any() const { + return layout_type_ == desc::layout_type::any; + } + + bool is_opaque() const { + return layout_type_ == desc::layout_type::opaque; + } + + bool operator==(const LlgaTensorDesc& desc) const { + return tid_ == desc.tid_ && sizes_ == desc.sizes_ && + dtype_ == desc.dtype_ && layout_type_ == desc.layout_type_ && + ((is_opaque() && layout_id_ == desc.layout_id_) || + strides_ == desc.strides_); + } + + bool operator!=(const LlgaTensorDesc& desc) const { + return (tid_ != desc.tid_) || (sizes_ != desc.sizes_) || + (dtype_ != desc.dtype_) || (layout_type_ != desc.layout_type_) || + !((is_opaque() && (layout_id_ == desc.layout_id_)) || + (strides_ == desc.strides_)); + } + + static size_t hash(const LlgaTensorDesc& desc) { + return c10::get_hash( + desc.tid_, + desc.sizes_, + desc.dtype_, + desc.layout_type_, + desc.layout_id_); + } + + void set_compute_inplace() { + compute_inplace_ = true; + } + + void set_input_tensor_index(size_t index) { + input_tensor_index_ = index; + } + + bool reuses_input_tensor() { + return compute_inplace_; + } + + size_t get_input_tensor_index() { + return input_tensor_index_; + } + + private: + bool is_dimensionality_unknown() const { + return sizes_.empty(); + } + + size_t tid_; + std::vector sizes_; + std::vector strides_; + desc::data_type dtype_; + desc::property_type property_type_; + desc::layout_type layout_type_; + size_t layout_id_; + // If this is an output tensor, and querying the compiled partition would + // determine that this tensor would reuse its input tensor, then + // compute_inplace would be true, and input_tensor_index would be the index of + // the corresponding input tensor in inputSpecs_ of the LlgaKernel object. + bool compute_inplace_ = false; + size_t input_tensor_index_{}; +}; + +// Initially, oneDNN Graph also used to have blocked layout for tensors between +// partitions, and the LlgaTensorImpl wrapper helped us bypass guard checks. +// oneDNN Graph has switched over to using strided tensors between partitions, +// but this wrapper still helps us bypass guard checks because the strides of +// tensors between partitions would be different from the ones the guard is +// otherwise expecting. +struct TORCH_API LlgaTensorImpl : public c10::TensorImpl { + LlgaTensorImpl( + at::Storage&& storage, + const caffe2::TypeMeta& data_type, + const LlgaTensorDesc& desc); + + const LlgaTensorDesc& desc() const { + return desc_; + } + + static at::Tensor llga_to_aten_tensor(LlgaTensorImpl* llgaImpl); + + private: + LlgaTensorDesc desc_; +}; + +at::Tensor empty_llga( + const LlgaTensorDesc& desc, + const c10::TensorOptions& options); + +dnnl::graph::tensor llga_from_aten_tensor(const at::Tensor& tensor); + +} // namespace torch::jit::fuser::onednn + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/onednn/decompose_silu.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/onednn/decompose_silu.h new file mode 100644 index 0000000000000000000000000000000000000000..24d20864e42cd77fa0540f8eb6378962af11f52c --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/onednn/decompose_silu.h @@ -0,0 +1,14 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit::fuser::onednn { + +void DecomposeSiluForLLGA(std::shared_ptr& graph); + +} // namespace torch::jit::fuser::onednn + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/onednn/defer_size_check.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/onednn/defer_size_check.h new file mode 100644 index 0000000000000000000000000000000000000000..0bb55003e88bb6c9d7b484ed761540a12a48e99a --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/onednn/defer_size_check.h @@ -0,0 +1,14 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit::fuser::onednn { + +void DeferSizeCheck(std::shared_ptr& graph); + +} // namespace torch::jit::fuser::onednn + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/onednn/graph_fuser.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/onednn/graph_fuser.h new file mode 100644 index 0000000000000000000000000000000000000000..8f14c5e33a9b3ac58392caaddb6b620c3444fc33 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/onednn/graph_fuser.h @@ -0,0 +1,52 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +namespace torch::jit::fuser::onednn { + +struct WorkBlock : public std::pair { + using pair::pair; + + Node* begin() { + return this->first; + } + Node* end() { + return this->second; + } +}; + +class GraphRewriter { + public: + GraphRewriter(Block* block, std::shared_ptr graph, AliasDb& aliasDb) + : block_(block), + graph_(std::move(graph)), + aliasDb_(aliasDb), + llgaHelper_(graph_) {} + + void cleanupSubgraphs(); + void buildupSubgraphs(); + + private: + Block* block_; + std::shared_ptr graph_; + AliasDb& aliasDb_; + LlgaGraphHelper llgaHelper_; + std::vector buildWorkBlocks(); + std::pair scanNode( + Node* consumer, + graph_node_list::iterator workblock_begin); + std::optional tryMerge(Node* consumer, Node* producer); +}; + +// This pass creates the subgraphs for oneDNN Graph Fusion Nodes. +// Its code-structure has been vastly inspired from +// torch/csrc/jit/passes/create_autodiff_subgraphs.cpp +void CreateLlgaSubgraphs(std::shared_ptr& graph); + +} // namespace torch::jit::fuser::onednn + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/onednn/graph_helper.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/onednn/graph_helper.h new file mode 100644 index 0000000000000000000000000000000000000000..582db7e71cf4856f2710c8e5aefe19b4383f957f --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/onednn/graph_helper.h @@ -0,0 +1,103 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include + +namespace torch::jit::fuser::onednn { + +#define STRIDED_LAYOUT 0 +#define OPAQUE_LAYOUT 1 + +struct OpPartitionMap { + void add(uint64_t opId, uint64_t partitionId) { + opmap_[opId] = partitionId; + } + void add(Node* n, uint64_t partitionId) { + add(Operator::getId(n), partitionId); + } + bool has(uint64_t opId) { + return opmap_.count(opId) > 0; + } + bool has(Node* n) { + return has(Operator::getId(n)); + } + uint64_t get(uint64_t opId) { + return opmap_[opId]; + } + uint64_t get(Node* n) { + auto opId = Operator::getId(n); + TORCH_CHECK( + has(opId), + "Node ", + n->kind().toQualString(), + " does not belong to any LLGA partition"); + return get(opId); + } + + private: + std::unordered_map opmap_; +}; + +class LlgaGraphHelper { + public: + LlgaGraphHelper( + const std::shared_ptr& graph, + dnnl::graph::partition::policy policy = + dnnl::graph::partition::policy::fusion); + + bool shouldMerge(Node* toMerge, Node* subgraph); + + bool shouldConsiderForMerge(Node* node); + + bool checkForSingleOpPartition(Node* node); + + Node* createSingletonSubgraph(Node* n, AliasDb& db); + + void mergeNodeIntoSubgraph(Node* toMerge, Node* subgraphNode, AliasDb& db); + + void unmergeIfAnyNodeIsMissing(Node* subgraphNode); + + static bool isLlgaSubgraph(const Node* node); + + Operator makeEltwiseOp(Node* node, dnnl::graph::op::kind kind); + + Operator makeBinaryOp(Node* node, dnnl::graph::op::kind kind); + + std::vector getPartitions() const; + + std::map getTensorIdToValue() const; + + Operator createOperator(Node* node); + + private: + size_t countSupportedOps(const std::shared_ptr& graph) const; + std::unique_ptr dnnl_graph_ = nullptr; + std::unique_ptr aliasDb_ = nullptr; + OpPartitionMap opToOwningPartition_; + std::vector partitions_; + std::map + tensorIdToValue_; // map from tensorId to torch::jit::Value +}; + +class LlgaNodeWrapper { + public: + LlgaNodeWrapper(const Node* node); + + void setOpaqueLayout(size_t offset); + + bool useOpaqueLayout(size_t offset) const; + + friend class LlgaGraphHelper; + + private: + Node* n; +}; + +} // namespace torch::jit::fuser::onednn + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/onednn/guard_shape.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/onednn/guard_shape.h new file mode 100644 index 0000000000000000000000000000000000000000..73ca360ff573d42805ce3d65f350d9f5f8c9433f --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/onednn/guard_shape.h @@ -0,0 +1,14 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit::fuser::onednn { + +void prepareFusionGroupAndGuardOutputs(Block* block); + +} // namespace torch::jit::fuser::onednn + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/onednn/interface.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/onednn/interface.h new file mode 100644 index 0000000000000000000000000000000000000000..68cc22c7d582f3589ab429c621424d86d73ae30d --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/onednn/interface.h @@ -0,0 +1,63 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include +#include +#include + +namespace torch::jit { +namespace fuser::onednn { + +static std::atomic onednn_enabled{false}; + +static std::atomic& getLlgaEnabled() { + return onednn_enabled; +} + +C10_EXPORT void fuseGraph(std::shared_ptr& g); + +} // namespace fuser::onednn + +struct C10_EXPORT RegisterLlgaFuseGraph + : public PassManager { + static bool setEnabled(bool enabled) { + TORCH_CHECK( + AT_MKLDNN_ENABLED(), + "Running oneDNN Graph fuser is only supported with MKLDNN builds."); + bool oldState = fuser::onednn::getLlgaEnabled(); + fuser::onednn::getLlgaEnabled() = enabled; + if (enabled) { + registerPass(fuser::onednn::fuseGraph); + } else { + clearPass(); + } + return oldState; + } + + static bool isEnabled() { + return fuser::onednn::getLlgaEnabled(); + } + + // override PassManager::registerPass to register pre-pass + static bool registerPass(GraphPass p) { + if (!isRegistered()) { + passID(registerPrePass(std::move(p)), true); + isRegistered(true); + return false; + } + return true; + } + + // override PassManager::clearPass to clear pre-pass + static void clearPass() { + if (isRegistered()) { + clearPrePass(passID()); + isRegistered(true); + } + } +}; + +} // namespace torch::jit + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/onednn/kernel.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/onednn/kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..0ac5b00556d552b765a6cfa21c76cb4ef0f36525 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/onednn/kernel.h @@ -0,0 +1,94 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +#include +#include +#include +#include +#include + +#include + +namespace torch::jit::fuser::onednn { + +using ArgSpec = LlgaTensorDesc; +using ArgSpecs = std::vector; +using RunArg = dnnl::graph::tensor; +using RunArgs = std::vector; +using TensorArgs = std::vector; + +class LlgaKernel { + public: + explicit LlgaKernel(const Node* fusionNode); + + void run(Stack& stack); + + void initialize(const TensorArgs& inputs); + + const std::string& debugName() const { + return debugName_; + } + + private: + bool useOpaqueLayout(size_t offset) const; + + // PyTorch copy constants inside the subgraph instead of referencing them. + // Constants inputs to the partition are no longer in the graph->inputs(). + // Need use the tid retrieved from the partition to find the missing + // constant inputs. + void initializeConstantInputs(); + + ArgSpecs initializeInputSpecs(const TensorArgs& inputs); + + ArgSpecs initializeOutputSpecs() const; + + dnnl::graph::compiled_partition compile( + const dnnl::graph::partition& partition); + + std::map initializeTensorIdToOccurence() const; + + std::tuple prepareRunArgs( + const TensorArgs& inputs, + TensorArgs& outputs) const; + + static std::string genDebugName() { + static size_t debugId = 0; + return "LlgaPartition_" + std::to_string(debugId++); + } + + static dnnl::graph::logical_tensor toLogicalTensor(const ArgSpec& s) { + return s.logical_tensor(); + } + + at::Device device_ = at::kCPU; + const Node* fusionNode_; + std::shared_ptr graph_; + int64_t nGraphInputs_ = 0; // number of inputs to graph_ on the IR + int64_t nOutputs_ = 0; + std::map tensorIdToValue_; + std::vector runArgsIdx_; + dnnl::graph::partition partition_; + // nPartitionInputs_ is the actual number of inputs to partition_ of graph_ + // needed by the backend. + // nPartitionInputs_ = nGraphInputs_ + constantInputs_.size() since Constant + // inputs are copied to the inside of the subgraph + int64_t nPartitionInputs_; + dnnl::graph::compiled_partition compilation_; + std::set initializedInputIds_; + std::vector constantValues_; + TensorArgs constantInputs_; + ArgSpecs inputSpecs_; + ArgSpecs outputSpecs_; + std::vector constantLogicalTensors_; + std::string debugName_; + c10::once_flag initialized_flag; + bool is_initialized_ = false; +}; + +} // namespace torch::jit::fuser::onednn + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/onednn/layout_propagation.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/onednn/layout_propagation.h new file mode 100644 index 0000000000000000000000000000000000000000..a654d8e7d15afb46e8c142d1f918ade6a1d20770 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/onednn/layout_propagation.h @@ -0,0 +1,14 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit::fuser::onednn { + +void PropagateLayout(const std::shared_ptr& graph); + +} // namespace torch::jit::fuser::onednn + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/onednn/operator.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/onednn/operator.h new file mode 100644 index 0000000000000000000000000000000000000000..ab289941e48a7087b30ae65efb9e1da3be51baab --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/onednn/operator.h @@ -0,0 +1,151 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include + +namespace torch::jit::fuser::onednn { + +class Operator { + public: + Operator(const Node* node, dnnl::graph::op::kind kind) + : n(node), o(getId(node), kind, node->kind().toQualString()), k(kind) {} + + // Returns output index if the Value is a graph output. + // Otherwise returns -1 + int32_t graphOutputIdx(Value* v) { + int32_t i = 0; + for (const Value* output : v->owningGraph()->outputs()) { + if (v == output) { + return i; + } + i++; + } + return -1; + } + + Operator& setInputValue(Value* v) { + if (v->mustNotBeNone()) { + if (v->type()->kind() == c10::TensorType::Kind) { + o.add_input(createLogicalTensor(v)); + } + } + return *this; + } + + Operator& setInput(size_t offset) { + return setInputValue(n->input(offset)); + } + + template + Operator& setInput(size_t offset, Ts... other) { + setInput(offset); + return setInput(other...); + } + + Operator& setOutputValue(Value* v) { + if (v->mustNotBeNone()) { + o.add_output(createLogicalTensor(v)); + } + return *this; + } + + // setOutputValue & setOutput require a pointer to the LLGA graph, as output + // logical tensors that are graph outputs should be connected to an End LLGA + // op. A value of NULL can be provided for the graph pointer in order to + // maintain the legacy functionality of this function. + Operator& setOutputValue(Value* v, std::unique_ptr& g) { + if (v->mustNotBeNone()) { + auto output_tensor = createLogicalTensor(v); + o.add_output(output_tensor); + if (g) { + int32_t outputIndex = graphOutputIdx(v); + if (outputIndex != -1) { + dnnl::graph::op newEndNode( + LONG_MAX - outputIndex, + dnnl::graph::op::kind::End, + "EndNodeForGraphOutput"); + newEndNode.add_input(output_tensor); + g->add_op(newEndNode); + } + } + } + return *this; + } + + Operator& setOutput(std::unique_ptr& g, size_t offset) { + return setOutputValue(n->output(offset), g); + } + + Operator& setOutput(size_t offset) { + return setOutputValue(n->output(offset)); + } + + template + Operator& setOutput( + std::unique_ptr& g, + size_t offset, + Ts... other) { + setOutput(g, offset); + return setOutput(g, other...); + } + + template + Operator& setAttr(dnnl::graph::op::attr name, Attr&& attr) { + o.set_attr(name, std::forward(attr)); + return *this; + } + + template + Operator& setAttr(dnnl::graph::op::attr name, const F& fn, size_t offset) { + return setAttr(name, fn(n, offset)); + } + + static float ScalarToFloat(const Node* node, size_t offset) { + return toIValue(node->input(offset))->toScalar().to(); + } + + static std::vector Ints(const Node* node, size_t offset) { + return toIValue(node->input(offset))->toIntVector(); + } + + static int64_t Int(const Node* node, size_t offset) { + return toIValue(node->input(offset))->toInt(); + } + + static float Float(const Node* node, size_t offset) { + return static_cast(toIValue(node->input(offset))->toDouble()); + } + + static bool Bool(const Node* node, size_t offset) { + return toIValue(node->input(offset))->toBool(); + } + + static uint64_t getId(const Node* node) { + return reinterpret_cast(node); // cast node address as op id + } + + dnnl::graph::op::kind kind() const { + return k; + } + + dnnl::graph::op llgaOp() const { + return o; + } + + private: + dnnl::graph::logical_tensor createLogicalTensor(Value* value) const { + return LlgaTensorDesc(value).logical_tensor(); + } + + const Node* n; + dnnl::graph::op o; + dnnl::graph::op::kind k; +}; + +} // namespace torch::jit::fuser::onednn + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/onednn/prepare_binary.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/onednn/prepare_binary.h new file mode 100644 index 0000000000000000000000000000000000000000..7e46d4d447b4922e96b66dbbf32b8d011af7cbae --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/codegen/onednn/prepare_binary.h @@ -0,0 +1,25 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit::fuser::onednn { + +// Prepare binary ops for LLGA +// +// The pass does the following: +// +// - Convert scalar input of aten::add and aten::mul into Float tensor with +// dimension [1] +// +// - Decompose fused add into aten::mul + aten::add when alpha != 1.0 +// +// - Eliminate identity add/mul, i.e., tensor + 0, tensor * 1 +// +void PrepareBinaryForLLGA(const std::shared_ptr& graph); + +} // namespace torch::jit::fuser::onednn + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/cuda/cuda.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/cuda/cuda.h new file mode 100644 index 0000000000000000000000000000000000000000..ff30c27553f68809ee4008c5c94c87d80c139042 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/cuda/cuda.h @@ -0,0 +1,184 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#include +#include +#include +#include + +namespace torch::jit { + +class CUDAEvent; +// This class is a wrapper around c10::cuda::CUDAStream. +// It is needed because TorchBind does not support all of the argument types +// for c10::cuda::CUDAStream. For more details, please refer to +// c10/cuda/CUDAStream.h. +class CUDAStream final : public CustomClassHolder { + public: + CUDAStream( + std::optional device = std::nullopt, + int64_t priority = 0) { + c10::DeviceIndex device_index = + device.has_value() ? device->index() : c10::cuda::current_device(); + stream_ = std::make_unique( + c10::cuda::getStreamFromPool(static_cast(priority), device_index)); + } + + CUDAStream(c10::cuda::CUDAStream s) { + stream_ = std::make_unique(s); + } + + bool query() { + return stream_->query(); + } + + c10::intrusive_ptr recordEvent( + c10::intrusive_ptr event); + + void synchronize() { + stream_->synchronize(); + } + + void waitEvent(const c10::intrusive_ptr& event); + + void waitStream(const c10::intrusive_ptr& stream); + + /// Get the CUDA device index that this stream is associated with. + int64_t device_index() const { + return stream_->device_index(); + } + + /// Get the full Device that this stream is associated with. The Device + /// is guaranteed to be a CUDA device. + c10::Device device() const { + return stream_->device(); + } + + /// Return the stream ID corresponding to this particular stream. + int64_t id() const { + return stream_->id(); + } + + private: + std::unique_ptr stream_; + friend class CUDAEvent; +}; + +// This class is a wrapper around at::cuda::CUDAStream. +// It is needed because TorchBind does not support all of the argument types +// for at::cuda::CUDAEvent. For more details, please refer to +// aten/src/ATen/cuda/CUDAEvent.h. +class CUDAEvent final : public CustomClassHolder { + public: + CUDAEvent( + bool enable_timing = false, + bool blocking = false, + bool interprocess = false) { + int flags = cudaEventDisableTiming; + if (enable_timing) { + flags = cudaEventDefault; + } + if (blocking) { + flags |= cudaEventBlockingSync; + } + if (interprocess) { + TORCH_CHECK(!enable_timing); + flags |= cudaEventInterprocess; + } + + event_ = std::make_unique(flags); + } + + double elapsedTime(const c10::intrusive_ptr& end) { + return event_->elapsed_time(*end->event_); + } + + std::string ipcHandle() { + cudaIpcEventHandle_t handle{}; + event_->ipc_handle(&handle); + std::string str_handle((const char*)&handle, sizeof(handle)); + return str_handle; + } + + bool query() { + return event_->query(); + } + + void record(const c10::intrusive_ptr& stream); + + void synchronize() { + event_->synchronize(); + } + void wait(const c10::intrusive_ptr& stream); + + private: + void recordInternal(CUDAStream* stream); + std::unique_ptr event_; + + friend class CUDAStream; +}; + +inline c10::intrusive_ptr CUDAStream::recordEvent( + c10::intrusive_ptr event) { + if (!event) { + event = c10::make_intrusive(); + } + + event->recordInternal(this); + return event; +} + +inline void CUDAStream::waitEvent(const c10::intrusive_ptr& event) { + event->event_->block(*stream_); +} + +inline void CUDAStream::waitStream( + const c10::intrusive_ptr& stream) { + auto ev = c10::make_intrusive(); + stream->recordEvent(ev); + waitEvent(ev); +} + +inline void CUDAEvent::record(const c10::intrusive_ptr& stream) { + event_->record(*stream->stream_); +} + +inline void CUDAEvent::recordInternal(CUDAStream* stream) { + event_->record(*stream->stream_); +} + +inline void CUDAEvent::wait(const c10::intrusive_ptr& stream) { + event_->block(*stream->stream_); +} + +TORCH_LIBRARY(cuda, m) { + auto stream_class = m.class_("Stream").def( + torch::init, int64_t>(), + "", + {torch::arg("device") = std::nullopt, torch::arg("priority") = 0}); + auto event_class = m.class_("Event").def( + torch::init(), + "", + {torch::arg("enable_timing") = false, + torch::arg("blocking") = false, + torch::arg("interprocess") = false}); + + stream_class.def("query", &CUDAStream::query) + .def("record_event", &CUDAStream::recordEvent) + .def("synchronize", &CUDAStream::synchronize) + .def("wait_event", &CUDAStream::waitEvent) + .def("wait_stream", &CUDAStream::waitStream) + .def("device_index", &CUDAStream::device_index) + .def_property("device", &CUDAStream::device) + .def("id", &CUDAStream::id); + + event_class.def("elapsed_time", &CUDAEvent::elapsedTime) + .def("query", &CUDAEvent::query) + .def("record", &CUDAEvent::record) + .def("synchronize", &CUDAEvent::synchronize) + .def("wait", &CUDAEvent::wait); +} + +} // namespace torch::jit + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/builtin_functions.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/builtin_functions.h new file mode 100644 index 0000000000000000000000000000000000000000..ed412b4acd8d06928e751733ec40f109863fb149 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/builtin_functions.h @@ -0,0 +1,14 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +namespace torch::jit { + +TORCH_API const std::vector& getAllBuiltinFunctionsFor(Symbol name); +} // namespace torch::jit + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/canonicalize_modified_loop.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/canonicalize_modified_loop.h new file mode 100644 index 0000000000000000000000000000000000000000..3dc39e392a8954600332b8e79ddf0a0e6a7b6a2f --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/canonicalize_modified_loop.h @@ -0,0 +1,19 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#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 + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/concrete_module_type.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/concrete_module_type.h new file mode 100644 index 0000000000000000000000000000000000000000..65e0aff09acc68c5c93d6078d9ccc58bef79ad00 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/concrete_module_type.h @@ -0,0 +1,244 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#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 + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/convert_to_ssa.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/convert_to_ssa.h new file mode 100644 index 0000000000000000000000000000000000000000..d9a3677aa2ef21c2e8a2ee0f35778832f9eb49e8 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/convert_to_ssa.h @@ -0,0 +1,19 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include +#include +#include + +#include +#include + +namespace torch::jit { + +// Convert a graph with Loads & Stores into SSA form +TORCH_API void ConvertToSSA(std::shared_ptr& graph); + +} // namespace torch::jit + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/edit_distance.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/edit_distance.h new file mode 100644 index 0000000000000000000000000000000000000000..711ddee3edd41e1c3e6c0ccccf5ab08c9bb8568b --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/edit_distance.h @@ -0,0 +1,18 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +namespace torch::jit { + +TORCH_API size_t ComputeEditDistance( + const char* word1, + const char* word2, + size_t maxEditDistance); + +} // namespace torch::jit + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/error_report.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/error_report.h new file mode 100644 index 0000000000000000000000000000000000000000..041831252736664f16f0547d34e27e2fa6175942 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/error_report.h @@ -0,0 +1,92 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#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; + + class TORCH_API Calls { + private: + std::vector calls_; + mutable std::mutex mutex_; + + public: + void push_back(Call call) { + std::lock_guard lock(mutex_); + calls_.push_back(std::move(call)); + } + + void pop_back() { + std::lock_guard lock(mutex_); + calls_.pop_back(); + } + + bool empty() const { + std::lock_guard lock(mutex_); + return calls_.empty(); + } + + void update_pending_range(const SourceRange& range) { + std::lock_guard lock(mutex_); + calls_.back().caller_range = range; + } + + std::vector get_stack() const { + std::lock_guard lock(mutex_); + return calls_; + } + }; + + 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); + + private: + std::shared_ptr source_callstack_; + }; + + 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 + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/exit_transforms.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/exit_transforms.h new file mode 100644 index 0000000000000000000000000000000000000000..c33e7cb04d7c6cbc3e330f61b6af9ee90b72d8b2 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/exit_transforms.h @@ -0,0 +1,15 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +namespace torch::jit { + +TORCH_API void TransformExits(std::shared_ptr& graph); + +} // namespace torch::jit + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/function_schema_parser.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/function_schema_parser.h new file mode 100644 index 0000000000000000000000000000000000000000..2626cfb7f96042a67194589f4f5a47a214bd2113 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/function_schema_parser.h @@ -0,0 +1,28 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#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 + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/inline_loop_condition.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/inline_loop_condition.h new file mode 100644 index 0000000000000000000000000000000000000000..6dba54dc8a69cc489da51be53469538908f4b849 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/inline_loop_condition.h @@ -0,0 +1,19 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#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 + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/ir_emitter.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/ir_emitter.h new file mode 100644 index 0000000000000000000000000000000000000000..4e723618bab2d7f129dcd3a40f11d00237f66d2d --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/ir_emitter.h @@ -0,0 +1,24 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace torch::jit { + +TORCH_API void runCleanupPasses(std::shared_ptr& to_clean); + +TORCH_API bool meaningfulName(const std::string& name); + +} // namespace torch::jit + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/lexer.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/lexer.h new file mode 100644 index 0000000000000000000000000000000000000000..d99be3ca74a0c21f9b0b284c19f6a462b194c937 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/lexer.h @@ -0,0 +1,568 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace torch::jit { + +// single character tokens are just the character itself '+' +// multi-character tokens need an entry here +// if the third entry is not the empty string, it is used +// in the lexer to match this token. + +// These kinds are also used in Tree.h as the kind of the AST node. +// Some kinds TK_APPLY, TK_LIST are only used in the AST and are not seen in the +// lexer. + +#define TC_FORALL_TOKEN_KINDS(_) \ + _(TK_EOF, "eof", "") \ + _(TK_WHITESPACE, "whitespace", "") \ + _(TK_WHITESPACE_EOF, "whitespace_eof", "") \ + _(TK_NUMBER, "number", "") \ + _(TK_NEWLINE, "newline", "") \ + _(TK_INDENT, "indent", "") \ + _(TK_DEDENT, "dedent", "") \ + _(TK_DEF, "def", "def") \ + _(TK_EQUIVALENT, "equivalent", "<=>") \ + _(TK_IDENT, "ident", "") \ + _(TK_STRING, "string", "") \ + _(TK_STRINGLITERAL, "string_literal", "") \ + _(TK_CONST, "const", "") \ + _(TK_LIST, "list", "") \ + _(TK_DICT, "dict", "") \ + _(TK_OPTION, "option", "") \ + _(TK_APPLY, "apply", "") \ + _(TK_COMPREHENSION, "comprehension", "") \ + _(TK_RANGE_CONSTRAINT, "range_constraint", "") \ + _(TK_PARAM, "param", "") \ + _(TK_INFERRED, "inferred", "") \ + _(TK_ACCESS, "access", "") \ + _(TK_ASSIGN, "assign", "") \ + _(TK_AUG_ASSIGN, "aug_assign", "") \ + _(TK_ATTRIBUTE, "attribute", "") \ + _(TK_IF, "if", "if") \ + _(TK_ELSE, "else", "else") \ + _(TK_ELIF, "elif", "elif") \ + _(TK_WHILE, "while", "while") \ + _(TK_EXPR_STMT, "expression statement", "") \ + _(TK_RETURN, "return", "return") \ + _(TK_IS, "is", "is") \ + _(TK_ISNOT, "is not", "is not") \ + _(TK_NE, "ne", "!=") \ + _(TK_EQ, "eq", "==") \ + _(TK_LE, "le", "<=") \ + _(TK_GE, "ge", ">=") \ + _(TK_FLOOR_DIV, "floordiv", "//") \ + _(TK_IF_EXPR, "if", "") \ + _(TK_TRUE, "True", "True") \ + _(TK_FALSE, "False", "False") \ + _(TK_NONE, "None", "None") \ + _(TK_AND, "and", "and") \ + _(TK_OR, "or", "or") \ + _(TK_NOT, "not", "not") \ + _(TK_LSHIFT, "<<", "<<") \ + _(TK_RSHIFT, ">>", ">>") \ + _(TK_CAST, "cast", "") \ + _(TK_PLUS_EQ, "+=", "+=") \ + _(TK_MINUS_EQ, "-=", "-=") \ + _(TK_TIMES_EQ, "*=", "*=") \ + _(TK_DIV_EQ, "/=", "/=") \ + _(TK_MOD_EQ, "%=", "%=") \ + _(TK_BIT_OR_EQ, "|=", "|=") \ + _(TK_BIT_AND_EQ, "&=", "&=") \ + _(TK_BIT_XOR_EQ, "^=", "^=") \ + _(TK_LSHIFT_EQ, "<<=", "<<=") \ + _(TK_RSHIFT_EQ, ">>=", ">>=") \ + _(TK_POW_EQ, "**=", "**=") \ + _(TK_GLOBAL, "global", "global") \ + _(TK_BUILT_IN, "built-in", "") \ + _(TK_SUBSCRIPT, "subscript", "") \ + _(TK_VAR, "variable", "") \ + _(TK_NOTHING, "nothing", "") \ + _(TK_DICT_LITERAL, "dict-literal", "") \ + _(TK_LIST_LITERAL, "list-literal", "") \ + _(TK_TUPLE_LITERAL, "tuple-literal", "") \ + _(TK_FOR, "for", "for") \ + _(TK_IN, "in", "in") \ + _(TK_NOTIN, "not in", "not in") \ + _(TK_STARRED, "starred", "") \ + _(TK_UNARY_MINUS, "unary minus", "") \ + _(TK_POW, "pow operator", "**") \ + _(TK_ARROW, "arrow", "->") \ + _(TK_DECL, "decl", "") \ + _(TK_SLICE_EXPR, "slice expr", "") \ + _(TK_TYPE_COMMENT, "type comment", "# type:") \ + _(TK_RAISE, "raise", "raise") \ + _(TK_ASSERT, "assert", "assert") \ + _(TK_DOTS, "dots", "...") \ + _(TK_LIST_COMP, "list comprehension", "") \ + _(TK_DICT_COMP, "dict comprehension", "") \ + _(TK_BREAK, "break", "break") \ + _(TK_CONTINUE, "continue", "continue") \ + _(TK_DELETE, "del", "del") \ + _(TK_PASS, "pass", "pass") \ + _(TK_CLASS_DEF, "class", "class") \ + _(TK_IMPORT, "import", "import") \ + _(TK_WITH, "with", "with") \ + _(TK_WITH_ITEM, "withitem", "") \ + _(TK_AS, "as", "as") \ + _(TK_PROP, "property", "") \ + _(TK_ELLIPSIS, "Ellipsis", "Ellipsis") \ + _(TK_NONE_TYPE, "NoneType", "NoneType") + +enum TokenKind { + // we use characters to represent themselves so skip all valid characters + // before + // assigning enum values to multi-char tokens. + TK_DUMMY_START = 256, +#define DEFINE_TOKEN(tok, _, _2) tok, + TC_FORALL_TOKEN_KINDS(DEFINE_TOKEN) +#undef DEFINE_TOKEN +}; + +TORCH_API std::string kindToString(int kind); +TORCH_API int stringToKind(const std::string& str); + +// nested hash tables that indicate char-by-char what is a valid token. +struct TokenTrie; +using TokenTrieRef = std::unique_ptr; +struct TokenTrie { + TokenTrie() = default; + void insert(const char* str, int tok) { + if (*str == '\0') { + AT_ASSERT(kind == 0); + kind = tok; + return; + } + + for (size_t i = 0, e = child_chars.size(); i < e; ++i) { + if (child_chars[i] == *str) { + child_tries[i]->insert(str + 1, tok); + return; + } + } + + child_chars.emplace_back(*str); + child_tries.emplace_back(std::make_unique()); + child_tries.back()->insert(str + 1, tok); + } + int kind{0}; // 0 == invalid token + + std::vector child_chars; + std::vector child_tries; +}; + +// stuff that is shared against all TC lexers/parsers and is initialized only +// once. +struct TORCH_API SharedParserData { + SharedParserData() : head(new TokenTrie()) { + for (const char* c = valid_single_char_tokens; *c; c++) { + std::string str(1, *c); + head->insert(str.c_str(), *c); + } + +#define ADD_CASE(tok, _, tokstring) \ + if (*(tokstring) != '\0') { \ + head->insert((tokstring), (tok)); \ + } + TC_FORALL_TOKEN_KINDS(ADD_CASE) +#undef ADD_CASE + } + + bool match( + StringCordView::Iterator pos, + bool continuation, // are we inside a scope where newlines don't count + // (e.g. inside parens) + bool whitespace_token, // should we treat whitespace as a token + int* kind, + StringCordView::Iterator* start, + StringCordView::Iterator* end) { + *start = pos; + // skip whitespace + while (pos.has_next() && isblank(*pos)) { + ++pos; + } + + // special handling + if (pos.has_next()) { + if (*pos == '#' && !isTypeComment(pos)) { + // skip comments + while (pos.has_next() && *pos != '\n') + ++pos; + // tail call, handle whitespace and more comments + return match(pos, continuation, whitespace_token, kind, start, end); + } + if (*pos == '\\') { + auto newiter = pos; + ++newiter; + if (newiter.has_next() && *newiter == '\n' && !whitespace_token) { + ++newiter; + return match(newiter, continuation, false, kind, start, end); + } + } + if (*pos == '\n') { + return match(++pos, continuation, !continuation, kind, start, end); + } + } + // we handle white space before EOF because in the case we have something + // like the following where we need to generate the dedent token if foo: + // ... + // else: + // pass + if (whitespace_token) { + *kind = !pos.has_next() ? TK_WHITESPACE_EOF : TK_WHITESPACE; + *end = pos; + return true; + } + if (!pos.has_next()) { + *kind = TK_EOF; + *start = pos; + *end = *start; + return true; + } + // invariant: the next token is not whitespace or newline + *start = pos; + // check for a valid number + size_t len = 0; + if (isNumber(pos.rest_line(), 0, &len)) { + *end = *start; + *end += len; + *kind = TK_NUMBER; + return true; + } + // check for string + if (isString(pos.rest_line(), 0, &len)) { + *kind = TK_STRINGLITERAL; + *end = *start; + *end += len; + return true; + } + + // check for either an ident or a token + // ident tracks whether what we have scanned so far could be an identifier + // matched indicates if we have found any match. + bool matched = false; + bool ident = true; + TokenTrie* cur = head.get(); + // for (size_t i = 0; pos + i < str.size() && (ident || cur != nullptr); + // i++) + for (size_t i = 0; pos.has_next() && (ident || cur != nullptr); + ++pos, ++i) { + ident = ident && validIdent(i, *pos); + if (ident) { + matched = true; + *end = pos.next_iter(); + *kind = TK_IDENT; + } + // check for token second, so that e.g. 'max' matches the token TK_MAX + // rather the + // identifier 'max' + if (cur) { + const auto begin_it = cur->child_chars.begin(); + const auto end_it = cur->child_chars.end(); + const auto ch_it = std::find(begin_it, end_it, *pos); + + cur = (ch_it == end_it) ? nullptr + : cur->child_tries[ch_it - begin_it].get(); + + if (cur && cur->kind != 0) { + matched = true; + *end = pos.next_iter(); + *kind = cur->kind; + } + } + } + return matched; + } + + bool isUnary(int kind, int* prec); + bool isBinary(int kind, int* prec); + bool isRightAssociative(int kind) { + switch (kind) { + case '?': + case TK_POW: + case TK_IF: + return true; + default: + return false; + } + } + + private: + bool validIdent(size_t i, char n) { + return isalpha(n) || n == '_' || (i > 0 && isdigit(n)); + } + + // 1. skip whitespace + // 2. handle comment or newline + // + bool isNumber(std::string_view str, size_t start, size_t* len) { + char first = str[start]; + // strtod allows numbers to start with + or - or nan or inf + // http://en.cppreference.com/w/cpp/string/byte/strtof + // but we want only the number part, otherwise 1+3 will turn into two + // adjacent numbers in the lexer + if (first == '-' || first == '+' || isalpha(first)) + return false; + const char* startptr = str.data() + start; + char* endptr = nullptr; + torch::jit::strtod_c(startptr, &endptr); + *len = endptr - startptr; + // check if the number is complex valued + // access is safe because string is assumed to be null terminated + if (endptr != nullptr && *endptr == 'j') { + *len += 1; + } + return *len > 0; + } + + bool isCharCount(char c, std::string_view str, size_t start, int len) { + // count checks from [start, start + len) + return start + len <= str.size() && + std::count(str.begin() + start, str.begin() + start + len, c) == len; + } + + // python concatenates all adjacent strings "a" "b" == "ab" + // strings can be enclosed with 1 or 3 single or double quotes + // if enclosed with 3 quotes newlines are valid + // as elsewhere, backslash and new line should be ignored + bool isString(std::string_view str, size_t start, size_t* len) { + char quote = str[start]; + if (quote != '\"' && quote != '\'') + return false; + int quote_len = isCharCount(quote, str, start, 3) ? 3 : 1; + + // end is now set past the opening quotation marks + size_t end = start + quote_len; + while (end < str.size() && !isCharCount(quote, str, end, quote_len)) { + if (str[end] == '\n' && quote_len != 3) { + return false; + } + // handle escaped characters. advances past escaped quotation marks, + // escaped newlines and escaped backslashes + // multi-char escapes like \x1A are handled fine here because the + // remainder of the escape are valid string characters anyway + if (str[end] == '\\') { + end++; + } + end++; + } + // set length equal to the complete string including quotations + *len = end - start + quote_len; + // if end finished without going past the last character of the string than + // there is a match + return end < str.size(); + } + + bool isblank(int n) { + return isspace(n) && n != '\n'; + } + + bool isTypeComment(StringCordView::Iterator str_iter) { + std::string_view rest_line = str_iter.rest_line(); + const std::string type_string = "# type:"; + if (rest_line.size() < type_string.length()) { + return false; + } + auto match_string = rest_line.substr(0, type_string.size()); + return match_string == type_string; + } + + // Make an exception ignoring comments for type annotation comments + bool isTypeComment(const StringCordView& str, size_t pos) { + const std::string type_string = "# type:"; + if (str.size() < pos + type_string.length()) { + return false; + } + auto match_string = str.substr(pos, type_string.size()); + return match_string == type_string; + } + + TokenTrieRef head; +}; + +TORCH_API SharedParserData& sharedParserData(); + +struct Token { + int kind; + SourceRange range; + Token(int kind, SourceRange range) : kind(kind), range(std::move(range)) {} + std::string text() const { + return std::string(range.token_text()); + } + + std::string_view text_view() const { + return range.token_text(); + } + + std::string kindString() const { + return kindToString(kind); + } +}; + +struct Lexer { + explicit Lexer(std::shared_ptr source) + : source(std::move(source)), shared(sharedParserData()) { + auto first_indent = lexRaw(true); + indent_stack.push_back(first_indent.range.size()); + lex(); + } + // Return the current token, and then move to the next one + Token next() { + if (next_tokens.empty()) + reportError("Lexer invariant violated: empty token queue"); + Token r = std::move(next_tokens.front()); + next_tokens.erase(next_tokens.begin()); + if (next_tokens.empty()) { + lex(); + } + return r; + } + // Skip the current token if it matches the given kind + bool nextIf(int kind) { + if (cur().kind != kind) + return false; + next(); + return true; + } + + [[noreturn]] void reportError(const std::string& what) { + reportError(what, cur()); + } + [[noreturn]] void reportError(const std::string& what, const Token& t) { + std::stringstream ss; + ss << what << ":\n"; + t.range.highlight(ss); + throw std::runtime_error(ss.str()); + } + [[noreturn]] void expected(const std::string& what, const Token& t) { + std::stringstream ss; + ss << "expected " << what << " but found '" << t.kindString() + << "' here:\n"; + t.range.highlight(ss); + throw std::runtime_error(ss.str()); + } + [[noreturn]] void expected(const std::string& what) { + expected(what, cur()); + } + // Check that the current token has a given kind, return the current token, + // and advance to the next one. + Token expect(int kind) { + if (cur().kind != kind) { + expected(kindToString(kind)); + } + return next(); + } + Token& lookahead() { + if (next_tokens.size() < 2) { + lex(); + } + return next_tokens[1]; + } + Token& cur() { + return next_tokens.front(); + } + + private: + void lex() { + auto r = lexRaw(); + switch (r.kind) { + case '(': + case '[': + case '{': + nesting++; + break; + case ')': + case ']': + case '}': + nesting--; + break; + case TK_WHITESPACE: + case TK_WHITESPACE_EOF: { + const auto depth = + r.kind == TK_WHITESPACE_EOF ? indent_stack.front() : r.range.size(); + // note: TK_WHITESPACE_EOF is whitespace right before the EOF token + // just like we allow the code to be indented to a particular initial + // indent level, we allow the final indent to be anything and set + // it back to the initial indent level. This allows the code to be + // put into string literals inside code without worrying about final + // whitespace + if (depth > indent_stack.back()) { + indent_stack.push_back(depth); + r.kind = TK_INDENT; + } else if (depth == indent_stack.back()) { + r.kind = TK_NEWLINE; + } else { + next_tokens.emplace_back(TK_NEWLINE, r.range); + while (indent_stack.back() != depth) { + indent_stack.pop_back(); + next_tokens.emplace_back(TK_DEDENT, r.range); + if (indent_stack.empty()) { + reportError("invalid indent level " + std::to_string(depth), r); + } + } + return; // We've already queued the tokens + } + } break; + default: + break; + } + next_tokens.push_back(std::move(r)); + } + Token lexRaw(bool whitespace_token = false) { + AT_ASSERT(source); + if (current == nullptr) { + AT_ASSERT(pos == 0); + current = std::make_unique( + source->text_str().begin()); + } + + StringCordView::Iterator start_iter = *current; + StringCordView::Iterator end_iter = *current; + int kind = 0; + if (!shared.match( + *current, + nesting > 0, + whitespace_token, + &kind, + &start_iter, + &end_iter)) { + expected( + "a valid token", + Token( + **current, + SourceRange(source, start_iter, start_iter.pos() + 1))); + } + + auto t = Token(kind, SourceRange(source, start_iter, end_iter.pos())); + pos = end_iter.pos(); + *current = end_iter; + return t; + } + + std::shared_ptr source; + std::unique_ptr current; + size_t pos{0}; + size_t nesting{0}; // depth of ( [ { nesting... + std::vector indent_stack; // stack of indentation level of blocks + // Invariant: this should always contain at least a single element + std::vector next_tokens; + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + SharedParserData& shared; +}; +} // namespace torch::jit + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/mini_environment.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/mini_environment.h new file mode 100644 index 0000000000000000000000000000000000000000..dfb7e43fe4b371b620fe1c1fd99ae675e71936da --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/mini_environment.h @@ -0,0 +1,60 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include + +namespace torch::jit { + +// Simple data structure for containing a type T in nested control blocks +// Should only be used after initial compilation where type checking and +// loads and stores are emitted + +template +struct MiniEnvironment { + MiniEnvironment(Block* b, std::shared_ptr next = nullptr) + : next(std::move(next)) {} + + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + std::shared_ptr> next; + + T findInThisFrame(const std::string& name) { + auto it = table.find(name); + if (it != table.end()) { + return it->second; + } + return nullptr; + } + + T findInAnyFrame(const std::string& name) { + for (auto runner = this; runner; runner = runner->next.get()) { + if (auto r = runner->findInThisFrame(name)) { + return r; + } + } + return nullptr; + } + + void setVar(const std::string& name, T value) { + table[name] = value; + } + + std::vector definedVariables() { + std::vector result; + result.reserve(table.size()); + for (auto& kv : table) { + result.push_back(kv.first); + } + std::sort(result.begin(), result.end()); + return result; + } + + private: + std::unordered_map table; +}; + +} // namespace torch::jit + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/name_mangler.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/name_mangler.h new file mode 100644 index 0000000000000000000000000000000000000000..2cede9aaaffb8a0fe6c376845796614b8c7cf408 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/name_mangler.h @@ -0,0 +1,30 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#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 + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/parse_string_literal.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/parse_string_literal.h new file mode 100644 index 0000000000000000000000000000000000000000..16f32df8d9b12fb47d3f117019380aa3f4344b52 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/parse_string_literal.h @@ -0,0 +1,92 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include +#include +#include + +namespace torch::jit { + +inline bool isCharCount(char c, const std::string& str, size_t start, int len) { + // count checks from [start, start + len) + return start + len <= str.size() && + std::count( + str.begin() + static_cast(start), + str.begin() + static_cast(start + len), + c) == len; +} + +inline std::optional parseOctal(const std::string& str, size_t pos) { + //\xxx where x are 0-7 + if (pos + 3 >= str.size()) + return std::nullopt; + size_t c = 0; + for (size_t i = 1, b = 64; i < 4; ++i, b /= 8) { + auto d = str[pos + i]; + if (d < '0' || d > '7') + return std::nullopt; + c += b * (d - '0'); + } + if (c >= 256) + return std::nullopt; + return c; +} + +inline std::string parseStringLiteral( + const SourceRange& range, + const std::string& str) { + size_t quote_len = isCharCount(str[0], str, 0, 3) ? 3 : 1; + auto ret_str = str.substr(quote_len, str.size() - quote_len * 2); + size_t pos = ret_str.find('\\'); + while (pos != std::string::npos) { + // invariant: pos has to escape a character because it is a valid string + char c = ret_str[pos + 1]; + size_t to_erase = 2; + switch (ret_str[pos + 1]) { + case '\\': + case '\'': + case '\"': + case '\n': + break; + case 'a': + c = '\a'; + break; + case 'b': + c = '\b'; + break; + case 'f': + c = '\f'; + break; + case 'n': + c = '\n'; + break; + case 'v': + c = '\v'; + break; + case 't': + c = '\t'; + break; + case 'x': + throw(ErrorReport(range) << "unsupported hex specifier"); + case 'u': + case 'U': + throw(ErrorReport(range) << "unsupported unicode specifier"); + default: + // octal value in format \nnn, n is [0-7] + if (auto v = parseOctal(ret_str, pos)) { + to_erase = 4; + c = *v; + } else { + throw(ErrorReport(range) << " ill formed octal specifier"); + } + } + ret_str.replace(pos, to_erase, /* num copies */ 1, c); + pos = ret_str.find('\\', pos + 1); + } + return ret_str; +} + +} // namespace torch::jit + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/parser.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/parser.h new file mode 100644 index 0000000000000000000000000000000000000000..77653ee4c4ab4dc00da00851d41d59344768295b --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/parser.h @@ -0,0 +1,36 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#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 + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/parser_constants.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/parser_constants.h new file mode 100644 index 0000000000000000000000000000000000000000..b71bc27928ebf8667f1b6df5b9d4e4596aa70a23 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/parser_constants.h @@ -0,0 +1,11 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +namespace torch::jit { +static constexpr const char* valid_single_char_tokens = + "+-*/%@()[]:,={}><.?!&^|~"; +} // namespace torch::jit + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/resolver.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/resolver.h new file mode 100644 index 0000000000000000000000000000000000000000..6be0d3b08423d6260e015246e0a36cd521a0eeab --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/resolver.h @@ -0,0 +1,71 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#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 + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/schema_matching.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/schema_matching.h new file mode 100644 index 0000000000000000000000000000000000000000..c84708353f64269d594eb45c5819c2e293bdfe3f --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/schema_matching.h @@ -0,0 +1,73 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#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 + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/schema_type_parser.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/schema_type_parser.h new file mode 100644 index 0000000000000000000000000000000000000000..b031c47a4f17fcb47a0ec7c972c45b79edaa7273 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/schema_type_parser.h @@ -0,0 +1,52 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include + +namespace torch::jit { + +using TypePtr = c10::TypePtr; + +TORCH_API void registerOpaqueType(const std::string& type_name); +TORCH_API bool isRegisteredOpaqueType(const std::string& type_name); + +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 + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/script_type_parser.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/script_type_parser.h new file mode 100644 index 0000000000000000000000000000000000000000..aa4105637e51d13b451484ebac382c6f6e32037c --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/script_type_parser.h @@ -0,0 +1,58 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include +#include +#include +#include + +namespace torch::jit { + +/** + * class ScriptTypeParser + * + * Parses expressions in our typed AST format (TreeView) into types and + * typenames. + */ +class TORCH_API ScriptTypeParser { + public: + explicit ScriptTypeParser() = default; + explicit ScriptTypeParser(ResolverPtr resolver) + : resolver_(std::move(resolver)) {} + + c10::TypePtr parseTypeFromExpr(const Expr& expr) const; + + std::optional> parseBroadcastList( + const Expr& expr) const; + + c10::TypePtr parseType(const std::string& str); + + FunctionSchema parseSchemaFromDef(const Def& def, bool skip_self); + + c10::IValue parseClassConstant(const Assign& assign); + + private: + c10::TypePtr parseTypeFromExprImpl(const Expr& expr) const; + + std::optional parseBaseTypeName(const Expr& expr) const; + at::TypePtr subscriptToType( + const std::string& typeName, + const Subscript& subscript) const; + std::vector evaluateDefaults( + const SourceRange& r, + const std::vector& default_types, + const std::vector& default_exprs); + std::vector parseArgsFromDecl(const Decl& decl, bool skip_self); + + std::vector parseReturnFromDecl(const Decl& decl); + + ResolverPtr resolver_ = nullptr; + + // Need to use `evaluateDefaults` in serialization + friend struct ConstantTableValue; + friend struct SourceImporterImpl; +}; +} // namespace torch::jit + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/source_range.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/source_range.h new file mode 100644 index 0000000000000000000000000000000000000000..f58ab00fac5e62175b160977891f89e3f1d17351 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/source_range.h @@ -0,0 +1,608 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#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; + + std::string_view piece(size_t index) const { + return pieces_[index]; + } + + // General-case iterator implementation. + struct IteratorImpl { + IteratorImpl( + 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 IteratorImpl(const StringCordView* str) + : IteratorImpl(str, 0, 0, str->size()) {} + + IteratorImpl() : IteratorImpl(nullptr, 0, 0, 0) {} + + IteratorImpl(const IteratorImpl&) = default; + IteratorImpl(IteratorImpl&&) = default; + IteratorImpl& operator=(const IteratorImpl&) = default; + IteratorImpl& operator=(IteratorImpl&&) = default; + + IteratorImpl& operator++() { + if (size_ == 0) { + return *this; + } + if ((pos_ + 1) < str_->pieces_[line_].size()) { + pos_++; + } else { + line_++; + pos_ = 0; + } + return *this; + } + + IteratorImpl operator++(int) { + IteratorImpl prev(*this); + ++(*this); + return prev; + } + + IteratorImpl next_iter() const { + IteratorImpl next(*this); + ++next; + return next; + } + + IteratorImpl& operator+=(size_t num); + + IteratorImpl operator+(size_t num) const { + IteratorImpl it(*this); + it += num; + return it; + } + + bool operator==(const IteratorImpl& rhs) const { + if (!has_next() && !rhs.has_next()) { + return true; + } + return (str_ == rhs.str_) && (line_ == rhs.line_) && (pos_ == rhs.pos_); + } + + bool operator!=(const IteratorImpl& rhs) const { + 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 + std::string_view rest_line() const { + if (line_ >= str_->pieces_.size()) { + return ""; + } + + std::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; + }; + + // Either an IteratorImpl, or a simple std::string_view::iterator + // (which is faster) if possible. + struct Iterator { + Iterator() = default; + + Iterator( + const StringCordView* str, + size_t start_line, + size_t start_pos, + size_t size) + : repr_( + str->pieces_.size() == 1 + ? repr_type(FastRepr( + start_line ? str->pieces_[0].end() + : str->pieces_[0].begin() + start_pos, + str)) + : repr_type(IteratorImpl(str, start_line, start_pos, size))) { + } + + Iterator(const StringCordView* str) : Iterator(str, 0, 0, str->size()) {} + + Iterator& operator++() { + if (auto* pit = std::get_if(&repr_)) { + ++(*pit); + } else { + ++fast_repr().it; + } + 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 (auto* pit = std::get_if(&repr_)) { + *pit += num; + } else { + fast_repr().it += num; + } + return *this; + } + + Iterator operator+(size_t num) const { + Iterator it(*this); + it += num; + return it; + } + + bool operator==(const Iterator& rhs) const { + return repr_ == rhs.repr_; + } + + bool operator!=(const Iterator& rhs) const { + return repr_ != rhs.repr_; + } + + bool has_next() const { + if (const auto* pit = std::get_if(&repr_)) { + return pit->has_next(); + } else { + return fast_repr().it != fast_repr().str->pieces_[0].end(); + } + } + + char operator*() const { + if (const auto* pit = std::get_if(&repr_)) { + return **pit; + } else { + return *fast_repr().it; + } + } + + std::string_view rest_line() const { + if (const auto* pit = std::get_if(&repr_)) { + return pit->rest_line(); + } else { + // NOTE: std::string_view(it, end) ctor wasn't added until C++20. + const auto fast_repr_end = fast_repr().str->pieces_[0].end(); + if (fast_repr().it != fast_repr_end) { + return std::string_view( + &*fast_repr().it, fast_repr_end - fast_repr().it); + } + return std::string_view(); + } + } + + size_t pos() const { + if (const auto* pit = std::get_if(&repr_)) { + return pit->pos(); + } else { + return fast_repr().it - fast_repr().str->pieces_[0].begin(); + } + } + + private: + // When we have only one entry in pieces_ (importantly, such as + // when called from torch::Library::def during startup), we can + // skip extra complexity and just use string_view::iterator + // directly. + struct FastRepr { + std::string_view::iterator it; + const StringCordView* str; + + FastRepr() : str(nullptr) {} + + explicit FastRepr( + std::string_view::iterator it_, + const StringCordView* str_) + : it(it_), str(str_) {} + + bool operator==(const FastRepr& rhs) const { + return it == rhs.it && str == rhs.str; + } + + bool operator!=(const FastRepr& rhs) const { + return !operator==(rhs); + } + }; + using repr_type = std::variant; + repr_type repr_; + + FastRepr& fast_repr() { + // -Oz refuses to inline std::get. + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(std::holds_alternative(repr_)); + return *std::get_if(&repr_); + } + + const FastRepr& fast_repr() const { + // -Oz refuses to inline std::get. + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(std::holds_alternative(repr_)); + return *std::get_if(&repr_); + } + }; + + 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: + IteratorImpl begin_impl() const { + return IteratorImpl(this, 0, 0, size()); + } + IteratorImpl end_impl() const { + return IteratorImpl(this, pieces_.size(), 0, 0); + } + IteratorImpl iter_impl_for_pos(size_t pos) const; + 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( + std::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) + : text_view_(create_text_view(copies_str, text_view)), + filename_(std::move(filename)), + starting_line_no_(starting_line_no), + gen_ranges_(std::move(gen_ranges)) { + 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); + } + } + + static StringCordView create_text_view( + CopiesString copies_str, + std::string_view text_view) { + if (copies_str == COPIES_STRING) { + auto allocated_str = + std::make_shared(text_view.data(), text_view.size()); + return StringCordView({*allocated_str}, {allocated_str}); + } else { + return StringCordView({text_view}, {}); + } + } + + 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 std::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 + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/source_ref.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/source_ref.h new file mode 100644 index 0000000000000000000000000000000000000000..c786cc523c9aa42e6f15afd81290e1e6619d0074 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/source_ref.h @@ -0,0 +1,50 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#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 + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/strtod.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/strtod.h new file mode 100644 index 0000000000000000000000000000000000000000..fefb4c36e6fd2682401ab299aa8a4fa9fcb6122b --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/strtod.h @@ -0,0 +1,15 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#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 + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/sugared_value.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/sugared_value.h new file mode 100644 index 0000000000000000000000000000000000000000..24e3bcf8cb3130700b604ec8d4b7f31993215b74 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/sugared_value.h @@ -0,0 +1,880 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace torch::jit { + +using SugaredValuePtr = std::shared_ptr; + +// The AST can contain nodes like `self`, `self.b` or `python_fn` that +// are not first-class values in the graph representation, but instead +// will be desugared based on how they are used in the AST. + +// SugaredValue is used to temporarily represent these values in a way +// that separates their behavior from the AST -> IR converter itself. +// This allows us to keep dependencies on python minimal. + +struct TORCH_API SugaredValue + : public std::enable_shared_from_this { + // what is this node? for error reporting (e.g. Module, python function) + virtual std::string kind() const = 0; + + // what can we do with this thing? + // use it as a value e.g. `this + 4` + virtual Value* asValue(const SourceRange& loc, GraphFunction& m) { + throw(ErrorReport(loc) << kind() << " cannot be used as a value"); + } + + // select an attribute on it, e.g. `this.field` + virtual std::shared_ptr attr( + const SourceRange& loc, + GraphFunction& m, + const std::string& field) { + throw(ErrorReport(loc) << "attribute lookup is not defined on " << kind()); + } + + virtual bool hasAttr( + const SourceRange& loc, + GraphFunction& m, + const std::string& field) { + throw(ErrorReport(loc) << "attribute lookup is not defined on " << kind()); + } + + // assign an attribute on it, e.g. `this.field = newValue` + virtual void setAttr( + const SourceRange& loc, + GraphFunction& m, + const std::string& field, + Value* newValue) { + throw( + ErrorReport(loc) << "attribute assignment is not defined on " + << kind()); + } + + // use it as a vector of values, e.g. a tuple of values as return value from + // a method invocation + virtual std::vector> asTuple( + const SourceRange& loc, + GraphFunction& m, + const std::optional& size_hint = {}) { + throw(ErrorReport(loc) << kind() << " cannot be used as a tuple"); + } + + // TODO @wconstab refactor to use ModuleValue::asTuple instead of new API + virtual SugaredValuePtr asTupleValue( + const SourceRange& loc, + GraphFunction& m) { + throw(ErrorReport(loc) << kind() << " cannot be used as a tuplevalue"); + } + + virtual std::vector> asType( + const SourceRange& loc, + Method& m) { + throw(ErrorReport(loc) << kind() << " cannot be used as a type"); + } + + // call it like a function, e.g. `outputs = this(inputs)` + virtual std::shared_ptr call( + const SourceRange& loc, + GraphFunction& m, + // note: names for args will be 'argument 0', 'argument 1', etc.. + at::ArrayRef args, + at::ArrayRef kwargs, + size_t n_binders) { + // n_binders is always set to the number of variables an expression is + // syntactically bound to: + // a = foo() # 1 binder (note in this case the single binder might be a + // tuple) a, * b = foo() # 1 binder a, b = foo() # 2 binders foo() # 0 + // binders + // + // In subexpressions, like bar() in foo(bar()), n_binders is always set to + // 1. n_binders is used as a hint to subexpressions to determine how many + // values they should return when that number is ambiguous statically. In + // particular it is currently used to decide how many tensors a call to a + // python function will return. It is only a hint, functions do not have to + // check that n_binders match the number of things they are returning, the + // assignment logic will do that anyway. + + throw(ErrorReport(loc) << "cannot call a " << kind()); + } + + // This function is called when to convert a SugaredValue to its iterator. + // For example, when iterating through a Dict we iterate over its keys + virtual std::shared_ptr iter( + const SourceRange& loc, + GraphFunction& m) { + throw(ErrorReport(loc) << kind() << " cannot be used as an iterable"); + } + + // If we are iterating over a Sugared Value and it returns a value from this + // function, then we emit an unrolled loop over the variable. This allows us + // to support containers of Heterogeneous types, like Module Containers & + // Tuples + virtual std::optional staticLen() { + return std::nullopt; + } + + // When iterating over this SugaredValue, should we emit the for loop as an + // unrolled loop. + bool shouldEmitUnrolled() { + return staticLen() != std::nullopt; + } + + // return length of this thing, if not then it can't be iterated. + // If it does not have a statically-determinable length, then it cannot + // be iterated over with a modulelist. If it does it must return a constant + // Value * + virtual Value* len(const SourceRange& loc, GraphFunction& m) { + throw( + ErrorReport(loc) << "'" << kind() << "'" << " object is not iterable"); + } + + // expression for ith element for iterable value + virtual std::shared_ptr getitem( + const SourceRange& loc, + GraphFunction& m, + Value* idx, + TypePtr type_hint = nullptr) { + throw( + ErrorReport(loc) << "'" << kind() << "'" + << " object is not subscriptable"); + } + + virtual ~SugaredValue() = default; +}; + +// most things in the environment are just simple value types +// and not special python syntax sugar types +struct TORCH_API SimpleValue : public SugaredValue { + SimpleValue(Value* value) : value_(value) {} + std::string kind() const override { + std::stringstream ss; + // NOLINTNEXTLINE(clang-analyzer-core.CallAndMessage) + ss << "value of type '" << value_->type()->annotation_str() << "'"; + return ss.str(); + } + Value* asValue(const SourceRange& range, GraphFunction& m) override { + return value_; + } + std::vector> asTuple( + const SourceRange& loc, + GraphFunction& m, + const std::optional& size_hint = {}) override; + std::shared_ptr attr( + const SourceRange& loc, + GraphFunction& m, + const std::string& field) override; + + bool hasAttr( + const SourceRange& loc, + GraphFunction& m, + const std::string& field) override; + + void setAttr( + const SourceRange& loc, + GraphFunction& m, + const std::string& field, + Value* newValue) override; + + std::shared_ptr call( + const SourceRange& loc, + GraphFunction& m, + // note: names for args will be 'argument 0', 'argument 1', etc.. + at::ArrayRef args, + at::ArrayRef kwargs, + size_t n_binders) override; + + std::shared_ptr iter(const SourceRange& loc, GraphFunction& m) + override; + + Value* getValue() const { + return value_; + } + + Value* len(const SourceRange& loc, GraphFunction& m) override; + SugaredValuePtr getitem( + const SourceRange& loc, + GraphFunction& m, + Value* idx, + TypePtr type_hint = nullptr) override; + + private: + Value* value_; +}; + +struct TORCH_API BuiltinFunction : public SugaredValue { + BuiltinFunction(Symbol symbol, std::optional self) + : symbol(symbol), self(std::move(self)) {} + + // The symbol of the function (e.g. `aten::relu`). + Symbol symbol; + + // if this is method, then this is the self argument. + std::optional self; + std::string kind() const override { + return "builtin"; + } + std::shared_ptr call( + const SourceRange& loc, + GraphFunction& m, + at::ArrayRef args, + at::ArrayRef kwargs, + size_t n_binders) override; + + // try to create this builtin but if it doesn't exist or the self argument + // cannot possibly match, then return nullptr. Use in situations where it is + // not clear if it is a valid builtin + static std::shared_ptr tryCreate( + Symbol symbol, + std::optional self); +}; + +struct TORCH_API SugaredTupleValue : public SugaredValue { + explicit SugaredTupleValue(std::vector> tup) + : tup_(std::move(tup)) {} + + std::vector> asTuple( + const SourceRange& loc, + GraphFunction& m, + const std::optional& size_hint = {}) override { + return tup_; + } + + Value* asValue(const SourceRange& loc, GraphFunction& m) override { + std::vector vec; + vec.reserve(tup_.size()); + for (const auto& sv : tup_) { + vec.push_back(sv->asValue(loc, m)); + } + Graph& g = *m.graph(); + return g.insertNode(g.createTuple(vec))->output(); + } + + std::string kind() const override { + return "Tuple"; + } + + SugaredValuePtr getitem( + const SourceRange& loc, + GraphFunction& m, + Value* idx, + TypePtr type_hint = nullptr) override { + if (!(idx->type()->cast() && toIValue(idx))) { + throw( + ErrorReport(loc) + << "Expected integer literal for index but got a variable or non-integer. " + << "ModuleList/Sequential indexing is only supported with integer literals. " + << "For example, 'i = 4; self.layers[i](x)' will fail because i is not a literal. " + << "Enumeration is supported, e.g. 'for index, v in enumerate(self): out = v(inp)'"); + } + auto index = toIValue(idx)->toInt(); + int64_t adj_index = + (index < 0) ? index + static_cast(tup_.size()) : index; + if (!(adj_index >= 0 && adj_index < static_cast(tup_.size()))) { + throw( + ErrorReport(loc) << "Index " << index << " out of range of length " + << tup_.size()); + } + return tup_.at(adj_index); + } + + // This function is called when a SugaredValue is used to convert a + // SugaredValue to its iterator. For example, when iterating through a Dict we + // iterate over its keys + std::shared_ptr iter(const SourceRange& loc, GraphFunction& m) + override { + return shared_from_this(); + } + + // Because this is used to contain SugaredValues of Heterogeneous types, + // we define staticLen() so that when this is iterated over it is emitted + // as an unrolled loop. + std::optional staticLen() override { + return static_cast(tup_.size()); + } + + std::vector> tup_; +}; + +struct TORCH_API BuiltinModule : public SugaredValue { + BuiltinModule(std::string name, std::optional version = std::nullopt) + : name(std::move(name)), version(version) {} + + std::string kind() const override { + return "builtin module"; + } + std::shared_ptr attr( + const SourceRange& loc, + GraphFunction& m, + const std::string& field) override { + if (field == "autograd") { + // When referring torch.autograd, it is also considered to be a + // BuiltinModule and we will dispatch to the aten operators for the + // methods under its module. + return std::make_shared("aten", version); + } + + auto sym = Symbol::fromQualString(name + "::" + field); + return std::make_shared(sym, std::nullopt); + } + + private: + std::string name; + // when we add operator versioning, emit this op as it existing at 'version' + // if not set, use the latest version + std::optional version; +}; + +// Represents a class, analogous to `int` or `dict`. Instances of classes, +// like `1` or `{"foo": 5}`, are represented as SimpleValues +struct TORCH_API ClassValue : public SugaredValue { + explicit ClassValue(ClassTypePtr type) : type_(std::move(type)) {} + + // Call the type's constructor, as in: + // n = Foo(constructor_arg) + std::shared_ptr call( + const SourceRange& loc, + GraphFunction& m, + at::ArrayRef args, + at::ArrayRef kwargs, + size_t n_binders) override; + + std::shared_ptr attr( + const SourceRange& loc, + GraphFunction& m, + const std::string& field) override; + + std::string kind() const override { + return type_->str(); + } + + ClassTypePtr type_; +}; + +struct TORCH_API NamedTupleConstructor : public SugaredValue { + explicit NamedTupleConstructor(TupleTypePtr type) : type_(std::move(type)) {} + + std::shared_ptr call( + const SourceRange& loc, + GraphFunction& m, + at::ArrayRef args, + at::ArrayRef kwargs, + size_t n_binders) override; + + std::string kind() const override { + return type_->str(); + } + + TupleTypePtr type_; +}; + +struct FunctionValue : public SugaredValue { + FunctionValue(Function* callee) : callees_({callee}) {} + FunctionValue(const StrongFunctionPtr& p) + : callees_({p.function_}), cu_(p.cu_) {} + FunctionValue(const std::vector& callees) { + for (const StrongFunctionPtr& callee : callees) { + cu_ = cu_ ? cu_ : callee.cu_; + TORCH_INTERNAL_ASSERT(callee.cu_ == cu_); + callees_.push_back(callee.function_); + } + } + + std::string kind() const override { + return "function"; + } + + std::shared_ptr call( + const SourceRange& loc, + GraphFunction& f, + at::ArrayRef args, + at::ArrayRef kwargs, + size_t n_binders) override { + std::vector schemas; + for (Function* callee : callees_) { + try { + callee->ensure_defined(); + } catch (const RecursiveMethodCallError&) { + throw( + ErrorReport(loc) + << " function '" << callee->name() << "' is called recursively. " + << "Recursive calls are not supported"); + } + schemas.push_back(&callee->getSchema()); + } + auto match = matchSchemas(schemas, loc, *f.graph(), args, kwargs); + Value* output = + f.graph()->insertFunctionCall(callees_[match.first], match.second); + output->node()->setSourceRange(loc); + return std::make_shared(output); + } + + const std::vector& callees() { + return callees_; + } + + private: + std::vector callees_; + // TODO holding this thing is creepy + std::shared_ptr cu_; +}; + +struct TORCH_API ClosureValue : public SugaredValue { + ClosureValue(Value* value) : value_(value) { + TORCH_INTERNAL_ASSERT(value_->node()->kind() == prim::Closure); + } + std::string kind() const override { + return "closure"; + } + Value* asValue(const SourceRange& range, GraphFunction& m) override { + return value_; + } + Value* value_; +}; + +// defines how a method obtained from a module/class/interface behaves in script +struct MethodValue : public SugaredValue { + MethodValue(Value* self, std::vector method_names) + : self_(self), method_names_(std::move(method_names)) {} + MethodValue(Value* self, std::string method_name) + : MethodValue(self, std::vector({std::move(method_name)})) {} + + std::string kind() const override { + return "method"; + } + + std::shared_ptr call( + const SourceRange& loc, + GraphFunction& f, + at::ArrayRef args, + at::ArrayRef kwargs, + size_t n_binders) override { + std::vector argsWithSelf = {self_}; + argsWithSelf.insert(argsWithSelf.end(), args.begin(), args.end()); + std::vector schemas; + for (const std::string& method_name : method_names_) { + if (auto class_type = self_->type()->cast()) { + Function& method = class_type->getMethod(method_name); + try { + method.ensure_defined(); + } catch (const RecursiveMethodCallError&) { + throw( + ErrorReport(loc) + << " method '" << method.name() << "' is called recursively. " + << "Recursive calls are not supported"); + } + schemas.push_back(&method.getSchema()); + } else if (auto interface_type = self_->type()->cast()) { + schemas.push_back(interface_type->getMethod(method_name)); + } else { + TORCH_INTERNAL_ASSERT( + false, "method constructed that is not a class or interface"); + } + } + auto match = matchSchemas(schemas, loc, *f.graph(), argsWithSelf, kwargs); + Value* output = + f.graph()->insertMethodCall(method_names_[match.first], match.second); + output->node()->setSourceRange(loc); + return std::make_shared(output); + } + + private: + Value* self_; + std::vector method_names_; +}; + +struct TORCH_API PrintValue : public SugaredValue { + std::string kind() const override { + return "print"; + } + std::shared_ptr call( + const SourceRange& loc, + GraphFunction& m, + at::ArrayRef args, + at::ArrayRef kwargs, + size_t n_binders) override; +}; + +// expressions like int(x) +// these are the same as call prim::Int or equivalent except it +// is a noop when the input is a subtype of 'type' +struct TORCH_API CastValue : public BuiltinFunction { + CastValue(TypePtr type, c10::Symbol method) + : BuiltinFunction(method, std::nullopt), type_(std::move(type)) {} + std::shared_ptr call( + const SourceRange& loc, + GraphFunction& m, + at::ArrayRef args, + at::ArrayRef kwargs, + size_t n_binders) override { + if (args.size() == 1 && kwargs.empty()) { + auto len_op = std::make_shared(aten::len, std::nullopt); + auto gt_op = std::make_shared(aten::gt, std::nullopt); + auto zero = m.graph()->insertConstant(0); + + auto v = args[0].value(*m.graph()); + if (v->type()->isSubtypeOf(*type_)) { + return std::make_shared(v); + } else if ( + *type_ == *BoolType::get() && + (v->type()->isSubtypeOf(*AnyListType::get()) || + v->type()->isSubtypeOf(*StringType::get()) || + v->type()->cast())) { + auto len = len_op->call(loc, m, {v}, {}, 1); + return gt_op->call(loc, m, {len->asValue(loc, m), zero}, {}, 1); + } + } + return BuiltinFunction::call(loc, m, args, kwargs, n_binders); + } + + private: + TypePtr type_; +}; + +struct TORCH_API TensorCastValue : public SugaredValue { + TensorCastValue(at::ScalarType type, NamedValue self) + : dtype_(type), self_(std::move(self)) {} + + std::string kind() const override { + return "Cast"; + } + + std::shared_ptr call( + const SourceRange& loc, + GraphFunction& m, + at::ArrayRef args, + at::ArrayRef kwargs, + size_t n_binders) override { + TORCH_INTERNAL_ASSERT(args.empty() && kwargs.empty()); + Value* dtype_const = m.graph()->insertConstant(dtype_, loc); + std::vector kwargs_{ + self_, NamedValue(loc, "dtype", dtype_const)}; + Value* casted_val = m.graph()->insert( + /*opname=*/Symbol::fromQualString("aten::to"), + /*args=*/args, + /*kwargs=*/kwargs_, + /*range=*/loc); + return std::make_shared(casted_val); + } + + at::ScalarType dtype_; + NamedValue self_; +}; + +// builtins operators and functions that call a method if it exists +// on a class type, like 'len(x)' and 'x + y' +struct TORCH_API MagicMethod : public SugaredValue { + MagicMethod(std::string desugared_name, SugaredValuePtr base) + : base_value_(std::move(base)), + desugared_name_(std::move(desugared_name)) {} + + std::string kind() const override { + return desugared_name_; + } + + std::shared_ptr call( + const SourceRange& loc, + GraphFunction& m, + at::ArrayRef args, + at::ArrayRef kwargs, + size_t n_binders) override; + + private: + SugaredValuePtr base_value_; + std::string desugared_name_; +}; + +// things that look like function applications, but +// perform non-standard evaluation are represented +// with SpecialFormValues, e.g. +// isinstance(x, int) +// fork(fn) +// annotate(int, 3) +// The implementation of each value is handled by a case inside emitApplyExpr +struct TORCH_API SpecialFormValue : public SugaredValue { + SpecialFormValue(Symbol form) : form_(form) {} + std::string kind() const override { + return form_.toUnqualString(); + } + Symbol form() const { + return form_; + } + static std::shared_ptr create(Symbol form) { + return std::make_shared(form); + } + + private: + Symbol form_; +}; + +struct TORCH_API LegacyTensorConstructor : public SpecialFormValue { + LegacyTensorConstructor(Symbol form, at::ScalarType dtype, at::Device device) + : SpecialFormValue(form), device_(device), dtype_(dtype) {} + + static std::shared_ptr create( + Symbol form, + at::ScalarType dtype, + at::Device device) { + return std::make_shared(form, dtype, device); + } + at::ScalarType dtype() const { + return dtype_; + } + + private: + at::Device device_; + at::ScalarType dtype_; +}; + +// matched against for special handling of range expressions +struct TORCH_API RangeValue : SugaredValue { + RangeValue( + const SourceRange& loc, + GraphFunction& m, + std::vector input, + std::optional static_len = std::nullopt); + + std::string kind() const override { + return "range"; + } + Value* len(const SourceRange& loc, GraphFunction& m) override; + SugaredValuePtr getitem( + const SourceRange& loc, + GraphFunction& m, + Value* idx, + TypePtr type_hint = nullptr) override; + std::shared_ptr iter(const SourceRange& loc, GraphFunction& m) + override; + + // When Range is instantiated via enumerate(iterable_with_static_len), + // then it takes the static length of the iterable + std::optional staticLen() override { + return static_len_; + } + + private: + Value* start_{}; + Value* end_{}; + Value* step_{}; + // a flag to determine if it's a simple range() call with only end_ from + // arguments If true, we will not insert length calculation and index + // derivation nodes to simplify the graph and enable more possible + // optimizations + bool has_only_end_{}; + std::optional static_len_; +}; + +// Specialized Tree structure to matched against for special handling +// of builtin functions iterables expressions like zip(), enumerate(), etc. +// zip and enumerate can be modeled as a tree of SimpleValue/RangeValue: +// zip(x, y) -> (x, y) with tuple assignment to each loop target +// enumerate(x) -> (range(0, math.inf, 1), x) +// So a complicated expression like zip(a, enumerate(b), range(0, 100)) will be: +// (a, (range(0, math.inf, 1), b), range(0, 100)) +// We use those base iterables to fill in the loop information like +// max_trip_count and set the value table for loop targets +// Iterables can contain lists of SugaredValues like ModuleLists. If it +// does, then we emit it unrolled and require that all values it contains +// have a statically-determinable length. +struct TORCH_API IterableTree : SugaredValue { + IterableTree() = default; + IterableTree( + const SourceRange& range, + GraphFunction& m, + at::ArrayRef children) { + for (const auto& child : children) { + addChild(range, m, child); + } + } + std::string kind() const override { + return "iterabletree"; + } + + std::shared_ptr iter(const SourceRange& loc, GraphFunction& m) + override { + return shared_from_this(); + } + + void addChild( + const SourceRange& range, + GraphFunction& m, + const SugaredValuePtr& iter_value); + + std::vector get_children() { + return children_; + } + + // If this iterable contains a ModuleList or Tuple, then it will have a + // static length, and we will emit it as an unrolled for loop. + std::optional staticLen() override { + return unroll_length_; + } + + // given a IterableTree node, get all the base iterables/leaves under the + // IterableTree node. This enables + // us to get all the basic SugaredValues that contains valid loop information + // with len() and getitem() + std::vector get_base_iterables(); + + Value* len(const SourceRange& loc, GraphFunction& m) override; + SugaredValuePtr getitem( + const SourceRange& loc, + GraphFunction& m, + Value* idx, + TypePtr type_hint = nullptr) override; + + private: + std::optional unroll_length_ = std::nullopt; + std::vector children_; +}; + +static inline std::vector toValues( + Graph& g, + at::ArrayRef nvs) { + return fmap(nvs, [&](const NamedValue& v) { return v.value(g); }); +} + +struct SimpleSelf : public Self { + explicit SimpleSelf(ClassTypePtr classType) + : Self(), classType_(std::move(classType)) {} + std::shared_ptr makeSugared(Value* v) const override { + v->setType(classType_); + return std::make_shared(v); + } + ClassTypePtr getClassType() const override { + return classType_; + } + + private: + ClassTypePtr classType_; +}; + +// This is not a SimpleValue so it can not pass through the code paths that +// expect a SimpleValue as a sugared value. +struct TORCH_API ExceptionMessageValue : public SugaredValue { + explicit ExceptionMessageValue( + Value* value, + Value* qualified_class_name = nullptr) + : value_(value), qualified_class_name_(qualified_class_name) {} + + std::string kind() const override { + return "exception message"; + } + + Value* getValue() { + return value_; + } + + // qualified python class name + Value* getQualifiedClassName() { + return qualified_class_name_; + } + + private: + Value* value_; + Value* qualified_class_name_; +}; + +struct TORCH_API ExceptionValue : public SugaredValue { + explicit ExceptionValue(std::string message) : message_(std::move(message)) {} + + std::string kind() const override { + return "exception"; + } + + std::shared_ptr call( + const SourceRange& loc, + GraphFunction& m, + at::ArrayRef args, + at::ArrayRef /*attributes*/, + size_t /*n_binders*/) override { + auto exception_message = insertConstant(*m.graph(), message_ + ": ", loc); + for (auto& input : args) { + auto input_str = input.value(*m.graph()); + if (!input_str->type()->isSubtypeOf(*StringType::get())) { + input_str = + emitBuiltinCall(loc, *m.graph(), aten::str, {input_str}, {}); + } + exception_message = emitBuiltinCall( + loc, *m.graph(), aten::add, {exception_message, input_str}, {}); + } + return std::make_shared(exception_message); + } + + std::string message_; +}; + +struct TORCH_API SugaredEnumClass : public SugaredValue { + explicit SugaredEnumClass(EnumTypePtr enum_type) + : enum_type_(std::move(enum_type)) {} + + std::string kind() const override { + return "EnumClass"; + } + + SugaredValuePtr attr( + const SourceRange& loc, + GraphFunction& m, + const std::string& field) override; + + SugaredValuePtr iter(const SourceRange& loc, GraphFunction& m) override; + + private: + EnumTypePtr enum_type_; +}; + +struct TORCH_API SliceValue : public SugaredValue { + explicit SliceValue(Value* start, Value* stop, Value* step) + : start_(start), stop_(stop), step_(step) {} + + std::string kind() const override { + return "Python slice value"; + } + + Value* start() { + return start_; + } + Value* stop() { + return stop_; + } + Value* step() { + return step_; + } + + private: + Value* start_; + Value* stop_; + Value* step_; +}; + +struct TORCH_API TorchCheckValue : public SugaredValue { + explicit TorchCheckValue() = default; + + std::string kind() const override { + return "torch._check sugared value"; + } + + std::shared_ptr call( + const SourceRange& loc, + GraphFunction& m, + at::ArrayRef args, + at::ArrayRef kwargs, + size_t n_binders) override; +}; + +} // namespace torch::jit + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/tracer.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/tracer.h new file mode 100644 index 0000000000000000000000000000000000000000..a3383b06b939c78f776d408f991fa573548e699b --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/tracer.h @@ -0,0 +1,418 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#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 std::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) { + TORCH_CHECK(false, "Tracing a list of bool type is currently not supported!"); +} + +template +void addInputs(Node* n, const char* name, ArrayRef value) { + TORCH_CHECK( + false, "Tracing a list of arbitrary type is currently not supported!"); +} +template +void addInputs( + Node* n, + const char* name, + const std::unordered_map& value) { + TORCH_CHECK( + false, "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&& /*unused*/) { + TORCH_CHECK( + false, + "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 + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/tree.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/tree.h new file mode 100644 index 0000000000000000000000000000000000000000..99ae0ff06622e087a299ade7da2b39419aa840f6 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/tree.h @@ -0,0 +1,227 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace torch::jit { + +// Trees are used to represent all forms of TC IR, pre- and post-typechecking. +// Rather than have a full class hierarchy for all TC statements, trees are a +// slight variation of Lisp s-expressions. For instance, the expression a*b+1 +// is represented as: +// (+ (* (ident a) (ident b)) (const 1)) +// Atoms like 'a', 'b', and '1' are represented by subclasses of Tree which +// define stringValue(). Everything else is a Compound object, which has a +// 'kind' that is a token from lexer.h's TokenKind enum. Single-character +// operators like '+' are represented using the character itself (so, add.kind() +// would be '+'). Each Compound object also contains a list of subtrees and is +// associated with a SourceRange for error reporting. +// Memory management of trees is done using intrusive_ptr. + +struct Tree; +using TreeRef = c10::intrusive_ptr; +using TreeList = at::SmallVector; + +struct Tree : c10::intrusive_ptr_target { + Tree(int kind_) : kind_(kind_) {} + int kind() const { + return kind_; + } + virtual bool isAtom() const { + return true; + } + virtual const SourceRange& range() const { + TORCH_CHECK(false, "is an Atom"); + } + virtual const std::string& stringValue() const { + TORCH_CHECK(false, "stringValue can only be called on TK_STRING"); + } + virtual const TreeList& trees() const { + static const TreeList empty_trees = {}; + return empty_trees; + } + const TreeRef& tree(size_t i) const { + return trees().at(i); + } + virtual TreeRef map(const std::function& fn) { + (void)fn; + c10::raw::intrusive_ptr::incref(this); // we are creating a new pointer + // from a raw `this` pointer + // so we need to bump the refcount + // to account for this ownership + return TreeRef::reclaim(this); + } + template + void match(int k, Args&... args) const { + matchD(k, "unknown", 0, args...); + } + template + void matchD(int k, const char* filename, int lineno, Args&... args) const { + std::initializer_list vars = {args...}; + matchNumSubtreesD(k, filename, lineno, vars.size(), true); + size_t i = 0; + for (TreeRef* v : vars) { + *v = trees()[i++]; + } + } + void matchNumSubtrees(int k, size_t expected_subtrees) { + return matchNumSubtreesD(k, "unknown", 0, expected_subtrees, false); + } + void matchNumSubtreesD( + int k, + const char* filename, + int lineno, + size_t expected_subtrees, + bool allow_more) const { + TORCH_CHECK( + kind() == k, + filename, + ":", + lineno, + ": expecting kind '", + kindToString(k), + "' but found '", + kindToString(kind()), + "'\n"); + if (trees().size() < expected_subtrees || + (!allow_more && trees().size() != expected_subtrees)) { + std::stringstream ss; + ss << filename << ':' << lineno << ": expected at least " + << expected_subtrees << " subtrees, but found only " << trees().size() + << '\n'; + range().highlight(ss); + TORCH_CHECK(false, ss.str()); + } + } + ~Tree() override = default; + + private: + int kind_; +}; + +struct String : public Tree { + String(std::string value) : Tree(TK_STRING), value_(std::move(value)) {} + const std::string& stringValue() const override { + return value_; + } + template + static TreeRef create(Args&&... args) { + return c10::make_intrusive(std::forward(args)...); + } + + private: + std::string value_; +}; + +static SourceRange mergeRanges(SourceRange c, const TreeList& others) { + for (const auto& t : others) { + if (t->isAtom()) + continue; + size_t s = std::min(c.start(), t->range().start()); + size_t e = std::max(c.end(), t->range().end()); + c = SourceRange(c.source(), s, e); + } + return c; +} + +struct Compound : public Tree { + Compound(int kind, SourceRange range) + : Tree(kind), range_(std::move(range)) {} + Compound(int kind, const SourceRange& range_, TreeList&& trees_) + : Tree(kind), + range_(mergeRanges(range_, trees_)), + trees_(std::move(trees_)) {} + const TreeList& trees() const override { + return trees_; + } + static TreeRef create( + int kind, + const SourceRange& range_, + TreeList&& trees_) { + return c10::make_intrusive(kind, range_, std::move(trees_)); + } + bool isAtom() const override { + return false; + } + TreeRef map(const std::function& fn) override { + TreeList ret; + for (auto& t : trees()) { + ret.push_back(fn(t)); + } + return Compound::create(kind(), range(), std::move(ret)); + } + + const SourceRange& range() const override { + return range_; + } + + private: + SourceRange range_; + TreeList trees_; +}; + +// tree pretty printer +struct pretty_tree { + pretty_tree(const TreeRef& tree, size_t col = 40) : tree(tree), col(col) {} + const TreeRef& tree; + size_t col; + std::unordered_map flat_strings; + const std::string& get_flat(const TreeRef& t) { + auto it = flat_strings.find(t); + if (it != flat_strings.end()) + return it->second; + + std::stringstream out; + switch (t->kind()) { + case TK_STRING: + out << t->stringValue(); + break; + default: + out << '(' << kindToString(t->kind()); + for (const auto& e : t->trees()) { + out << ' ' << get_flat(e); + } + out << ')'; + break; + } + auto it_ = flat_strings.emplace(t, out.str()); + return it_.first->second; + } + void print(std::ostream& out, const TreeRef& t, int indent) { + const std::string& s = get_flat(t); + if (indent + s.size() < col || t->isAtom()) { + out << s; + return; + } + std::string k = kindToString(t->kind()); + out << '(' << k; + for (const auto& e : t->trees()) { + out << '\n' << std::string(indent + 2, ' '); + print(out, e, indent + 2); + } + out << ')'; + } +}; + +static inline std::ostream& operator<<(std::ostream& out, pretty_tree t_) { + t_.print(out, t_.tree, 0); + return out << '\n'; +} + +static inline std::ostream& operator<<(std::ostream& out, const TreeRef& t) { + return out << pretty_tree(t); +} + +} // namespace torch::jit + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/tree_views.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/tree_views.h new file mode 100644 index 0000000000000000000000000000000000000000..1dc386d938f69651b4f9dd3cf9d5a335531c63e1 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/tree_views.h @@ -0,0 +1,1285 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace torch::jit { + +// clang-format off +// TreeView provides a statically-typed way to traverse the tree, which should +// be formed according to the grammar below. +// +// A few notes on types and their aliases: +// - List is really a Tree with kind TK_LIST and elements as subtrees +// - Maybe is really a Tree with kind TK_OPTION that has 0 or 1 subtree of type T +// - Builtin types are: Ident (TK_IDENT), String (TK_STRING) +// +// Param = Param(Maybe type, Ident name) TK_PARAM +// +// Decl = Decl(List params, Maybe return_type) TK_DECL +// Def = Def(Ident name, Decl decl, List body) TK_DEF +// ClassDef = ClassDef(Ident name, TK_CLASS_DEF +// Maybe superclass, +// List body) +// +// Stmt = If(Expr cond, List true_body, List false_body) TK_IF +// | For(List targets, List iters, List body) TK_FOR +// | While(Expr cond, List body) TK_WHILE +// | Global(List idents) TK_GLOBAL +// -- NB: the only type of Expr's allowed on lhs are Var +// Or a tuple containing Var with an optional terminating Starred +// | Assign(Expr lhs, Maybe rhs, Maybe type) TK_ASSIGN +// | AugAssign(Expr lhs, AugAssignKind aug_op, Expr rhs) TK_AUG_ASSIGN +// | Return(List values) TK_RETURN +// | ExprStmt(List expr) TK_EXPR_STMT +// | Raise(Expr expr) TK_RAISE +// | Def TK_DEF +// | With(List targets, List body) TK_WITH +// +// Expr = TernaryIf(Expr cond, Expr true_expr, Expr false_expr) TK_IF_EXPR +// | BinOp(Expr lhs, Expr rhs) +// | And TK_AND +// | Or TK_OR +// | Lt '<' +// | Gt '>' +// | Eq TK_EQ +// | Le TK_LE +// | Ge TK_GE +// | Ne TK_NE +// | Is TK_IS +// | IsNot TK_ISNOT +// | Add '+' +// | Sub '-' +// | Mul '*' +// | Div '/' +// | Mod '%' +// | MatMult '@' +// | Pow TK_POW +// | UnaryOp(Expr expr) +// | Not TK_NOT +// | USub '-' +// | Const(String value) TK_CONST +// -- NB: x.name(y) is desugared into name(x, y) +// | Apply(Ident name, List args, List kwargs) TK_APPLY +// | Select(Expr value, Ident selector) '.' +// | Subscript(Expr value, List subscript_exprs) TK_SUBSCRIPT +// | SliceExpr(Maybe start, Maybe end) TK_SLICE_EXPR +// | Var(Ident name) TK_VAR +// | ListLiteral(List inputs) TK_LIST_LITERAL +// | TupleLiteral(List inputs) TK_TUPLE_LITERAL +// | Starred(Expr expr) TK_STARRED +// | WithItem(Expr target, Maybe var) TK_WITH_ITEM +// -- NB: only allowed expressions are Const or List(Const) +// (List as a value, not type constructor) +// Attribute = Attribute(Ident name, Expr value) TK_ATTRIBUTE +// +// AugAssignKind = +// | Add() TK_PLUS_EQ +// | Sub() TK_MINUS_EQ +// | Mul() TK_TIMES_EQ +// | Div() TK_DIV_EQ +// | Mod() TK_MOD_EQ +// + +// Each subclass of TreeView should provide: +// 1. Constructor that takes a TreeRef, and checks that it's of the right type. +// 2. Accessors that get underlying information out of the object. If they +// return subtrees, they should wrap them in appropriate views too. +// 3. Static method 'create' that creates the underlying TreeRef object +// for every TreeRef kind that has a TreeView, the parser always uses +// (e.g.) Ident::create rather than Compound::Create, this means that +// changes to the structure of Ident are always made right here rather +// than both in the parser and in this code. +// XXX: these structs should have no fields to prevent slicing when passing by value +// clang-format on +struct TreeView { + explicit TreeView(TreeRef tree) : tree_(std::move(tree)) {} + TreeRef tree() const { + return tree_; + } + const SourceRange& range() const { + return tree_->range(); + } + operator TreeRef() const { + return tree_; + } + const TreeRef& get() const { + return tree_; + } + int kind() const { + return tree_->kind(); + } + void dump() const { + std::cout << tree_; + } + + protected: + const TreeRef& subtree(size_t i) const { + return tree_->trees().at(i); + } + // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) + TreeRef tree_; +}; + +template +struct ListIterator { + ListIterator(TreeList::const_iterator it) : it(it) {} + bool operator!=(const ListIterator& rhs) const { + return it != rhs.it; + } + bool operator==(const ListIterator& rhs) const { + return it == rhs.it; + } + T operator*() const { + return T(*it); + } + ListIterator& operator+=(std::ptrdiff_t n) { + it += n; + return *this; + } + ListIterator& operator++() { + ++it; + return *this; + } + ListIterator& operator--() { + --it; + return *this; + } + + private: + TreeList::const_iterator it; +}; + +template +struct List : public TreeView { + using iterator = ListIterator; + using const_iterator = ListIterator; + + List(const TreeRef& tree) : TreeView(tree) { + tree->match(TK_LIST); + // Iterate over list to temporarily instantiate Ts that will check the type + for (const T& elem : *this) { + (void)elem; // silence unused warning + } + } + iterator begin() const { + return iterator(tree_->trees().begin()); + } + iterator end() const { + return iterator(tree_->trees().end()); + } + bool empty() const { + return tree_->trees().begin() == tree_->trees().end(); + } + T operator[](size_t i) const { + return T(subtree(i)); + } + TreeRef map(const std::function& fn) { + return tree_->map([&](TreeRef v) { return fn(T(v)); }); + } + static List create(const SourceRange& range, const std::vector& subtrees) { + TreeList type_erased_sub{subtrees.begin(), subtrees.end()}; + return List(Compound::create(TK_LIST, range, std::move(type_erased_sub))); + } + static List unsafeCreate(const SourceRange& range, TreeList&& subtrees) { + return List(Compound::create(TK_LIST, range, std::move(subtrees))); + } + size_t size() const { + return tree_->trees().size(); + } +}; + +template +struct Maybe : public TreeView { + explicit Maybe(const TreeRef& tree) : TreeView(tree) { + tree_->match(TK_OPTION); + if (tree_->trees().size() > 1) + throw(ErrorReport(tree) << "Maybe trees can have at most one subtree"); + } + /* implicit */ Maybe(const T& tree) : TreeView(tree) {} + bool present() const { + return tree_->trees().size() > 0; + } + T get() const { + return T(tree_->trees().at(0)); + } + TreeRef map(const std::function& fn) { + return tree_->map([&](TreeRef v) { return fn(T(v)); }); + } + static Maybe create(const SourceRange& range) { + return Maybe(Compound::create(TK_OPTION, range, {})); + } + static Maybe create(const SourceRange& range, const T& value) { + return Maybe(Compound::create(TK_OPTION, range, {value})); + } +}; + +struct Ident : public TreeView { + explicit Ident(const TreeRef& tree) : TreeView(tree) { + tree_->match(TK_IDENT); + } + const std::string& name() const { + return subtree(0)->stringValue(); + } + static Ident create(const SourceRange& range, std::string name) { + return Ident( + Compound::create(TK_IDENT, range, {String::create(std::move(name))})); + } +}; + +//////////////////////////////////////////////////////////////////////////////// +// Base types (production LHS) +//////////////////////////////////////////////////////////////////////////////// + +struct Stmt : public TreeView { + explicit Stmt(const TreeRef& tree) : TreeView(tree) { + switch (tree->kind()) { + case TK_IF: + case TK_FOR: + case TK_WHILE: + case TK_GLOBAL: + case TK_ASSIGN: + case TK_AUG_ASSIGN: + case TK_RETURN: + case TK_EXPR_STMT: + case TK_RAISE: + case TK_ASSERT: + case TK_PASS: + case TK_BREAK: + case TK_DELETE: + case TK_CONTINUE: + case TK_DEF: + case TK_WITH: + return; + default: + throw( + ErrorReport(tree) + << kindToString(tree->kind()) << " is not a valid Stmt"); + } + } +}; + +struct Expr : public TreeView { + explicit Expr(const TreeRef& tree) : TreeView(tree) { + switch (tree->kind()) { + case TK_IF_EXPR: + case TK_AND: + case TK_OR: + case '<': + case '>': + case TK_IS: + case TK_ISNOT: + case TK_EQ: + case TK_LE: + case TK_GE: + case TK_NE: + case '+': + case '-': + case TK_UNARY_MINUS: + case '~': + case '*': + case TK_STARRED: + case '/': + case '%': + case TK_NOT: + case TK_CONST: + case TK_STRINGLITERAL: + case TK_TRUE: + case TK_FALSE: + case TK_NONE: + case TK_NONE_TYPE: + case TK_CAST: + case TK_APPLY: + case '.': + case TK_SUBSCRIPT: + case TK_SLICE_EXPR: + case TK_VAR: + case TK_LIST_LITERAL: + case TK_TUPLE_LITERAL: + case TK_DICT_LITERAL: + case '@': + case TK_POW: + case TK_LSHIFT: + case TK_RSHIFT: + case TK_FLOOR_DIV: + case '&': + case '^': + case '|': + case TK_LIST_COMP: + case TK_DICT_COMP: + case TK_DOTS: + case TK_IN: + case TK_WITH_ITEM: + return; + default: + throw( + ErrorReport(tree) + << kindToString(tree->kind()) << " is not a valid Expr"); + } + } +}; + +//////////////////////////////////////////////////////////////////////////////// +// Helper nodes (mostly for function arguments) +//////////////////////////////////////////////////////////////////////////////// + +struct Attribute : public TreeView { + explicit Attribute(const TreeRef& tree) : TreeView(tree) { + tree_->match(TK_ATTRIBUTE); + } + Ident name() const { + return Ident(subtree(0)); + } + Expr value() const { + return Expr(subtree(1)); + } + static Attribute create( + const SourceRange& range, + const Ident& name, + const TreeRef& value) { + return Attribute(Compound::create(TK_ATTRIBUTE, range, {name, value})); + } +}; + +struct Param : public TreeView { + explicit Param(const TreeRef& tree) : TreeView(tree) { + tree_->match(TK_PARAM); + } + static Param create( + const SourceRange& range, + const Ident& ident, + const Maybe& type, + const Maybe& def, + bool kwarg_only) { + TreeRef kwarg_only_tree = + Compound::create(kwarg_only ? TK_TRUE : TK_FALSE, range, {}); + return Param(Compound::create( + TK_PARAM, range, {ident, type, def, std::move(kwarg_only_tree)})); + } + Ident ident() const { + return Ident(subtree(0)); + } + Maybe type() const { + return Maybe(subtree(1)); + } + Maybe defaultValue() const { + return Maybe(subtree(2)); + } + bool kwarg_only() const { + return TK_TRUE == subtree(3)->kind(); + } + Param withType(const Maybe& typ) const { + return Param::create(range(), ident(), typ, defaultValue(), kwarg_only()); + } +}; + +//////////////////////////////////////////////////////////////////////////////// +// Top level definitions +//////////////////////////////////////////////////////////////////////////////// + +struct Decl : public TreeView { + explicit Decl(const TreeRef& tree) : TreeView(tree) { + tree->match(TK_DECL); + } + List params() const { + return List(subtree(0)); + } + Maybe return_type() const { + return Maybe(subtree(1)); + } + static Decl create( + const SourceRange& range, + const List& params, + const Maybe& return_type) { + return Decl(Compound::create(TK_DECL, range, {params, return_type})); + } +}; + +struct Def : public TreeView { + explicit Def(const TreeRef& tree) : TreeView(tree) { + tree->match(TK_DEF); + } + Def withName(std::string new_name) const { + auto new_ident = Ident::create(name().range(), std::move(new_name)); + return create(range(), new_ident, decl(), statements()); + } + Def withDecl(const Decl& decl) const { + return create(range(), name(), decl, statements()); + } + Ident name() const { + return Ident(subtree(0)); + } + Decl decl() const { + return Decl(subtree(1)); + } + List statements() const { + return List(subtree(2)); + } + static Def create( + const SourceRange& range, + const Ident& name, + const Decl& decl, + const List& stmts) { + return Def(Compound::create(TK_DEF, range, {name, decl, stmts})); + } +}; + +// Property represents a named attribute combined with a getter and setter +// method to access and mutate that attribute. +struct Property : public TreeView { + explicit Property(const TreeRef& tree) : TreeView(tree) { + tree->match(TK_PROP); + } + Ident name() const { + return Ident(subtree(0)); + } + Def getter() const { + return Def(subtree(1)); + } + Maybe setter() const { + return Maybe(subtree(2)); + } + static Property create( + const SourceRange& range, + const Ident& name, + const Def& getter, + const Maybe& setter) { + return Property(Compound::create(TK_PROP, range, {name, getter, setter})); + } +}; + +struct Assign; + +struct ClassDef : public TreeView { + explicit ClassDef(const TreeRef& tree) : TreeView(tree) { + tree->match(TK_CLASS_DEF); + } + explicit ClassDef(TreeRef&& tree) : TreeView(std::move(tree)) { + tree_->match(TK_CLASS_DEF); + } + ClassDef withName(std::string new_name) const { + auto new_ident = Ident::create(name().range(), std::move(new_name)); + return create(range(), new_ident, superclass(), body()); + } + Ident name() const { + return Ident(subtree(0)); + } + Maybe superclass() const { + return Maybe(subtree(1)); + } + List body() const { + return List(subtree(2)); + } + Maybe> properties() const { + return Maybe>(subtree(3)); + } + Maybe> assigns() const { + return Maybe>(subtree(4)); + } + static ClassDef create( + const SourceRange& range, + const Ident& name, + const Maybe& superclass, + const List& body) { + return ClassDef(Compound::create( + TK_CLASS_DEF, + range, + {name, + superclass, + body, + Maybe>::create(range), + Maybe>::create(range)})); + } + static ClassDef create( + const SourceRange& range, + const Ident& name, + const Maybe& superclass, + const List& body, + const List& properties, + const List& assigns); +}; + +TORCH_API std::vector getUnresolvedClassAttributes( + const ClassDef& def); + +//////////////////////////////////////////////////////////////////////////////// +// Statements +//////////////////////////////////////////////////////////////////////////////// + +struct If : public Stmt { + explicit If(const TreeRef& tree) : Stmt(tree) { + tree_->match(TK_IF); + } + Expr cond() const { + return Expr(subtree(0)); + } + List trueBranch() const { + return List(subtree(1)); + } + List falseBranch() const { + return List(subtree(2)); + } + If withNewBranches( + const List& true_branch, + const List& false_branch) const { + return create(range(), cond(), true_branch, false_branch); + } + static If create( + const SourceRange& range, + const Expr& cond, + const List& true_branch, + const List& false_branch) { + return If( + Compound::create(TK_IF, range, {cond, true_branch, false_branch})); + } +}; + +struct While : public Stmt { + explicit While(const TreeRef& tree) : Stmt(tree) { + tree_->match(TK_WHILE); + } + Expr cond() const { + return Expr(subtree(0)); + } + List body() const { + return List(subtree(1)); + } + static While create( + const SourceRange& range, + const Expr& cond, + const List& body) { + return While(Compound::create(TK_WHILE, range, {cond, body})); + } +}; + +struct For : public Stmt { + explicit For(const TreeRef& tree) : Stmt(tree) { + tree->match(TK_FOR); + } + List targets() const { + return List(subtree(0)); + } + List itrs() const { + return List(subtree(1)); + } + List body() const { + return List(subtree(2)); + } + static For create( + const SourceRange& range, + const List& targets, + const List& itrs, + const List& body) { + return For(Compound::create(TK_FOR, range, {targets, itrs, body})); + } +}; + +// TODO: supports only single comprehension for now +struct ListComp : public Expr { + explicit ListComp(const TreeRef& tree) : Expr(tree) { + tree->match(TK_LIST_COMP); + } + Expr elt() const { + return Expr(subtree(0)); + } + Expr target() const { + return Expr(subtree(1)); + } + Expr iter() const { + return Expr(subtree(2)); + } + // TODO: no ifs for now + static ListComp create( + const SourceRange& range, + const Expr& elt, + const Expr& target, + const Expr& iter) { + return ListComp(Compound::create(TK_LIST_COMP, range, {elt, target, iter})); + } +}; + +// TODO: supports only single comprehension for now +struct DictComp : public Expr { + explicit DictComp(const TreeRef& tree) : Expr(tree) { + tree->match(TK_DICT_COMP); + } + Expr key() const { + return Expr(subtree(0)); + } + Expr value() const { + return Expr(subtree(1)); + } + Expr target() const { + return Expr(subtree(2)); + } + Expr iter() const { + return Expr(subtree(3)); + } + // TODO: no ifs for now + static DictComp create( + const SourceRange& range, + const Expr& key, + const Expr& value, + const Expr& target, + const Expr& iter) { + return DictComp( + Compound::create(TK_DICT_COMP, range, {key, value, target, iter})); + } +}; + +struct Global : public Stmt { + explicit Global(const TreeRef& tree) : Stmt(tree) { + tree_->match(TK_GLOBAL); + } + List names() { + return List(subtree(0)); + } + static Global create(const SourceRange& range, const List& names) { + return Global(Compound::create(TK_GLOBAL, range, {names})); + } +}; + +struct AugAssignKind : public TreeView { + explicit AugAssignKind(const TreeRef& tree) : TreeView(tree) { + switch (tree->kind()) { + case '+': + case '-': + case '*': + case '/': + case '%': + case '|': + case '&': + case '^': + case TK_POW: + case TK_LSHIFT: + case TK_RSHIFT: + return; + default: + throw(ErrorReport(tree) << "is not a valid AugAssignKind"); + } + } +}; + +// Augmented assignment, like "foo += bar" +struct AugAssign : public Stmt { + explicit AugAssign(const TreeRef& tree) : Stmt(tree) { + tree_->match(TK_AUG_ASSIGN); + } + static AugAssign create( + const SourceRange& range, + const Expr& lhs, + const AugAssignKind& aug_op, + const Expr& rhs) { + return AugAssign( + Compound::create(TK_AUG_ASSIGN, range, {lhs, aug_op, rhs})); + } + Expr lhs() const { + return Expr(subtree(0)); + } + int aug_op() const { + return subtree(1)->kind(); + } + Expr rhs() const { + return Expr(subtree(2)); + } +}; + +struct Assign : public Stmt { + explicit Assign(const TreeRef& tree) : Stmt(tree) { + tree_->match(TK_ASSIGN); + } + static Assign create( + const SourceRange& range, + const List& lhs, + const Maybe& rhs, + const Maybe& type) { + return Assign(Compound::create(TK_ASSIGN, range, {lhs, rhs, type})); + } + + List lhs_list() const { + return List(subtree(0)); + } + + Expr lhs() const { + const auto& li = lhs_list(); + TORCH_INTERNAL_ASSERT(li.size() == 1); + return *li.begin(); + } + + Maybe rhs() const { + return Maybe(subtree(1)); + } + + Maybe type() const { + return Maybe(subtree(2)); + } +}; + +struct Return : public Stmt { + explicit Return(const TreeRef& tree) : Stmt(tree) { + tree_->match(TK_RETURN); + } + Expr expr() const { + return Expr(subtree(0)); + } + static Return create(const SourceRange& range, const Expr& value) { + return Return(Compound::create(TK_RETURN, range, {value})); + } +}; + +struct Raise : public Stmt { + explicit Raise(const TreeRef& tree) : Stmt(tree) { + tree_->match(TK_RAISE); + } + Expr expr() const { + return Expr(subtree(0)); + } + static Raise create(const SourceRange& range, const Expr& expr) { + return Raise(Compound::create(TK_RAISE, range, {expr})); + } +}; + +struct Assert : public Stmt { + explicit Assert(const TreeRef& tree) : Stmt(tree) { + tree_->match(TK_ASSERT); + } + Expr test() const { + return Expr(subtree(0)); + } + Maybe msg() const { + return Maybe(subtree(1)); + } + static Assert create( + const SourceRange& range, + const Expr& test, + const Maybe& msg) { + return Assert(Compound::create(TK_ASSERT, range, {test, msg})); + } +}; + +struct Pass : public Stmt { + explicit Pass(const TreeRef& tree) : Stmt(tree) { + tree_->match(TK_PASS); + } + static Pass create(const SourceRange& range) { + return Pass(Compound::create(TK_PASS, range, {})); + } +}; + +struct Dots : public Expr { + explicit Dots(const TreeRef& tree) : Expr(tree) { + tree_->match(TK_DOTS); + } + static Dots create(const SourceRange& range) { + return Dots(Compound::create(TK_DOTS, range, {})); + } +}; + +struct Break : public Stmt { + explicit Break(const TreeRef& tree) : Stmt(tree) { + tree_->match(TK_BREAK); + } + static Break create(const SourceRange& range) { + return Break(Compound::create(TK_BREAK, range, {})); + } +}; + +struct Continue : public Stmt { + explicit Continue(const TreeRef& tree) : Stmt(tree) { + tree_->match(TK_CONTINUE); + } + static Continue create(const SourceRange& range) { + return Continue(Compound::create(TK_CONTINUE, range, {})); + } +}; + +struct ExprStmt : public Stmt { + explicit ExprStmt(const TreeRef& tree) : Stmt(tree) { + tree_->match(TK_EXPR_STMT); + } + Expr expr() { + return Expr(subtree(0)); + } + static ExprStmt create(const SourceRange& range, const Expr& list) { + return ExprStmt(Compound::create(TK_EXPR_STMT, range, {list})); + } +}; + +//////////////////////////////////////////////////////////////////////////////// +// Expressions +//////////////////////////////////////////////////////////////////////////////// + +struct BinOp : public Expr { + explicit BinOp(const TreeRef& tree) : Expr(tree) { + switch (tree->kind()) { + case TK_AND: + case TK_OR: + case '<': + case '>': + case TK_IS: + case TK_ISNOT: + case TK_EQ: + case TK_LE: + case TK_GE: + case TK_NE: + case '+': + case '*': + case '/': + case '-': + case '@': + case TK_POW: + case TK_LSHIFT: + case TK_RSHIFT: + case '%': + case '&': + case '^': + case '|': + case TK_FLOOR_DIV: + case TK_IN: + if (tree->trees().size() != 2) + throw( + ErrorReport(tree) + << "BinOp expected 2 subtrees, found " << tree->trees().size()); + return; + default: + throw( + ErrorReport(tree) + << kindToString(tree->kind()) << " is not a valid BinOp"); + } + } + Expr lhs() const { + return Expr(subtree(0)); + } + Expr rhs() const { + return Expr(subtree(1)); + } + static BinOp create( + const SourceRange& range, + int kind, + const Expr& lhs, + const Expr& rhs) { + return BinOp(Compound::create(kind, range, {lhs, rhs})); + } +}; + +struct UnaryOp : public Expr { + explicit UnaryOp(const TreeRef& tree) : Expr(tree) { + switch (tree->kind()) { + case TK_UNARY_MINUS: + case '~': + case TK_NOT: + if (tree->trees().size() != 1) + throw( + ErrorReport(tree) + << "UnaryOp expected 1 subtree, found " << tree->trees().size()); + return; + default: + throw( + ErrorReport(tree) + << kindToString(tree->kind()) << " is not a valid UnaryOp"); + } + } + static UnaryOp create(const SourceRange& range, int kind, const Expr& expr) { + return UnaryOp(Compound::create(kind, range, {expr})); + } +}; + +struct Const : public Expr { + explicit Const(const TreeRef& tree) : Expr(tree) { + tree_->matchNumSubtrees(TK_CONST, 1); + } + bool isFloatingPoint() const { + if (isComplex()) + return false; + + bool is_inf = subtree(0)->stringValue() == "inf"; + return is_inf || + subtree(0)->stringValue().find_first_of(".eE") != std::string::npos; + } + bool isIntegral() const { + return !isFloatingPoint() && !isComplex(); + } + bool isComplex() const { + return subtree(0)->stringValue().find_first_of('j') != std::string::npos; + } + int64_t asIntegral() const { + try { + return std::stoll(subtree(0)->stringValue(), nullptr, 0); + } catch (const std::out_of_range&) { + throw( + ErrorReport(range()) << "Integral constant out of range " + "(must fit in a signed 64 bit integer)"); + } + } + double asFloatingPoint() const { + // We can't pass in nullptr as the dummy pointer gets dereferenced for + // Android version of strtod_c(). + char* dummy = nullptr; + return torch::jit::strtod_c(subtree(0)->stringValue().c_str(), &dummy); + } + c10::complex asComplex() const { + char* dummy = nullptr; + auto str = subtree(0)->stringValue(); + // Complex numbers (a+bj, where a is non-zero) are parsed as an addition + // between float/int a and a complex number "bj". When a is 0, a complex + // number bj is created as above. So, while parsing the string, we don't + // have to worry about the real component of the complex number. + auto imag = + torch::jit::strtod_c(str.substr(0, str.size() - 1).c_str(), &dummy); + return c10::complex(0, imag); + } + const std::string& text() const { + return subtree(0)->stringValue(); + } + static Const create(const SourceRange& range, const std::string& value) { + return Const(Compound::create(TK_CONST, range, {String::create(value)})); + } +}; + +struct StringLiteral : public Expr { + explicit StringLiteral(const TreeRef& tree) : Expr(tree) { + tree_->matchNumSubtrees(TK_STRINGLITERAL, 1); + } + const std::string& text() const { + return subtree(0)->stringValue(); + } + static StringLiteral create( + const SourceRange& range, + const std::string& value) { + return StringLiteral( + Compound::create(TK_STRINGLITERAL, range, {String::create(value)})); + } +}; + +struct Apply : public Expr { + explicit Apply(const TreeRef& tree) : Expr(tree) { + tree_->match(TK_APPLY); + } + Expr callee() const { + return Expr(subtree(0)); + } + List inputs() const { + return List(subtree(1)); + } + List attributes() const { + return List(subtree(2)); + } + static Apply create( + const SourceRange& range, + const Expr& callee, + const List& inputs, + const List& attributes) { + return Apply( + Compound::create(TK_APPLY, range, {callee, inputs, attributes})); + } +}; + +struct Select : public Expr { + explicit Select(const TreeRef& tree) : Expr(tree) { + tree_->match('.'); + } + Expr value() const { + return Expr(subtree(0)); + } + Ident selector() const { + return Ident(subtree(1)); + } + static Select create( + const SourceRange& range, + const Expr& value, + const Ident& selector) { + return Select(Compound::create('.', range, {value, selector})); + } +}; + +struct SliceExpr : public Expr { + explicit SliceExpr(const TreeRef& tree) : Expr(tree) { + tree_->match(TK_SLICE_EXPR); + } + Maybe start() const { + return Maybe(subtree(0)); + } + Maybe end() const { + return Maybe(subtree(1)); + } + Maybe step() const { + return Maybe(subtree(2)); + } + Expr startOr(int64_t alternative) const { + const auto startOption = start(); + return startOption.present() ? startOption.get() : createInt(alternative); + } + Expr endOr(int64_t alternative) const { + const auto endOption = end(); + return endOption.present() ? endOption.get() : createInt(alternative); + } + Expr stepOr(int64_t alternative) const { + const auto stepOption = step(); + return stepOption.present() ? stepOption.get() : createInt(alternative); + } + static SliceExpr create( + const SourceRange& range, + const Maybe& start, + const Maybe& end, + const Maybe& step) { + return SliceExpr( + Compound::create(TK_SLICE_EXPR, range, {start, end, step})); + } + + private: + Expr createInt(int64_t value) const { + return Expr(Const::create(range(), std::to_string(value))); + } +}; + +struct Subscript : public Expr { + explicit Subscript(const TreeRef& tree) : Expr(tree) { + tree_->match(TK_SUBSCRIPT); + } + Expr value() const { + return Expr(subtree(0)); + } + List subscript_exprs() const { + return List(subtree(1)); + } + static Subscript create( + const SourceRange& range, + const Expr& value, + const List& subscript_exprs) { + auto whole_range = SourceRange( + range.source(), range.start(), subscript_exprs.range().end() + 1); + return Subscript( + Compound::create(TK_SUBSCRIPT, whole_range, {value, subscript_exprs})); + } +}; + +struct Var : public Expr { + explicit Var(const TreeRef& tree) : Expr(tree) { + tree_->match(TK_VAR); + } + Ident name() const { + return Ident(subtree(0)); + } + static Var create(const SourceRange& range, const Ident& name) { + return Var(Compound::create(TK_VAR, range, {name})); + } +}; + +// WithItem represents an item using with a WithStmt. +struct WithItem : public Expr { + explicit WithItem(const TreeRef& tree) : Expr(tree) { + tree_->match(TK_WITH_ITEM); + } + + Expr target() const { + return Expr(subtree(0)); + } + + Maybe var() const { + return Maybe(subtree(1)); + } + + static WithItem create( + const SourceRange& range, + const Expr& target, + const Maybe& var) { + return WithItem(Compound::create(TK_WITH_ITEM, range, {target, var})); + } +}; + +// With represents a with statement consisting of a list of with items and a +// body of statements. +struct With : public Stmt { + explicit With(const TreeRef& tree) : Stmt(tree) { + tree_->match(TK_WITH); + } + + List targets() const { + return List(subtree(0)); + } + + List body() const { + return List(subtree(1)); + } + + static With create( + const SourceRange& range, + const List& targets, + const List& body) { + return With(Compound::create(TK_WITH, range, {targets, body})); + } +}; + +struct TernaryIf : public Expr { + explicit TernaryIf(const TreeRef& tree) : Expr(tree) { + tree_->matchNumSubtrees(TK_IF_EXPR, 3); + } + Expr cond() const { + return Expr(subtree(0)); + } + Expr true_expr() const { + return Expr(subtree(1)); + } + Expr false_expr() const { + return Expr(subtree(2)); + } + static TernaryIf create( + const SourceRange& range, + const Expr& cond, + const Expr& true_expr, + const Expr& false_expr) { + return TernaryIf( + Compound::create(TK_IF_EXPR, range, {cond, true_expr, false_expr})); + } +}; + +struct ListLiteral : public Expr { + explicit ListLiteral(const TreeRef& tree) : Expr(tree) { + tree_->match(TK_LIST_LITERAL); + } + List inputs() const { + return subtree(0); + } + static ListLiteral create( + const SourceRange& range, + const List& inputs) { + return ListLiteral(Compound::create(TK_LIST_LITERAL, range, {inputs})); + } +}; + +struct TupleLiteral : public Expr { + explicit TupleLiteral(const TreeRef& tree) : Expr(tree) { + tree_->match(TK_TUPLE_LITERAL); + } + List inputs() const { + return subtree(0); + } + static TupleLiteral create( + const SourceRange& range, + const List& inputs) { + return TupleLiteral(Compound::create(TK_TUPLE_LITERAL, range, {inputs})); + } +}; + +struct DictLiteral : public Expr { + explicit DictLiteral(const TreeRef& tree) : Expr(tree) { + tree_->match(TK_DICT_LITERAL); + } + List key_inputs() const { + return subtree(0); + } + List value_inputs() const { + return subtree(1); + } + static DictLiteral create( + const SourceRange& range, + const List& keys, + const List& values) { + return DictLiteral( + Compound::create(TK_DICT_LITERAL, range, {keys, values})); + } +}; + +struct Starred : public Expr { + explicit Starred(const TreeRef& tree) : Expr(tree) { + tree_->match(TK_STARRED); + } + Expr expr() const { + return Expr(subtree(0)); + } + static Starred create(const SourceRange& range, const Expr& expr) { + return Starred(Compound::create(TK_STARRED, range, {expr})); + } +}; + +struct Delete : public Stmt { + explicit Delete(const TreeRef& tree) : Stmt(tree) { + tree_->match(TK_DELETE); + } + List targets() const { + return subtree(0); + } + static Delete create(const SourceRange& range, const List& targets) { + return Delete(Compound::create(TK_DELETE, range, {targets})); + } +}; + +/* + * NOTE: transforming PEP 604 union into equivalent union type + * + * NOTE: Union[int, float] parses into: + * expr:(subscript + * (variable (ident Union)) + * (list + * (variable (ident int)) + * (variable (ident float)))) + * subscript + * + * NOTE: (int | float) parses into: + * expr:(| + * (variable (ident int)) + * (variable (ident float))) + * | + */ + +inline void _flatten_pep604_union( + const torch::jit::Expr& node, + std::vector* result) { + // flatten possibly nested union expressions like (int | (float | str)) + // into a flat list of expressions like [int, float, str] + if (node.kind() == '|') { + auto as_binop = torch::jit::BinOp(node); + _flatten_pep604_union(as_binop.lhs(), result); + _flatten_pep604_union(as_binop.rhs(), result); + } else { + result->push_back(node); + } +} + +inline std::vector get_pep604_union_members(const Expr& node) { + std::vector result; + _flatten_pep604_union(node, &result); + return result; +} + +// Flattens a PEP 604 union into a classical union. +// For example, ((x | y) | z) is transformed into Union[x, y, z]. +inline Expr pep604union_to_union(const Expr& expr) { + // noop if not a pep604 union + if (expr.kind() != '|') + return expr; + + // In order to support unions with more than 2 operands ((x|y)|z), we need to + // recursively flatten the tree of | expressions. + auto members = get_pep604_union_members(expr); + auto synthesised_union = Subscript::create( + expr.range(), + Var::create(expr.range(), Ident::create(expr.range(), "Union")), + List::create(expr.range(), members)); +#if defined(__clang__) + return std::move(synthesised_union); +#else + return synthesised_union; +#endif +} + +} // namespace torch::jit + +namespace std { + +template +struct iterator_traits> + : std::iterator_traits {}; + +} // namespace std + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/versioned_symbols.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/versioned_symbols.h new file mode 100644 index 0000000000000000000000000000000000000000..b8cb099cc27a3237256f2fa139e1973efc4f6ea7 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/versioned_symbols.h @@ -0,0 +1,24 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#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 + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/ir/alias_analysis.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/ir/alias_analysis.h new file mode 100644 index 0000000000000000000000000000000000000000..598426bd6807d67c4e9c8e00441bb0680e0ca91a --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/ir/alias_analysis.h @@ -0,0 +1,368 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include +#include +#include +#include +#include +#include + +namespace torch::jit { + +class ValueAndMemoryLocationSet; + +/** + * Alias analysis pass. + * + * This pass produces an AliasDb that contains aliasing and mutation + * information about the graph. Users can use this information to determine + * whether mutations to the graph are safe, i.e. they don't reorder/change + * nodes in a way that affects output. + * + * Every value with a mutable type (Tensors, Lists, Tuples, etc.) will be + * associated with one or more "alias sets". If two values share an alias set, + * that means they may alias, implying that a mutation to one value cannot be + * reordered past a use of the other. Only reordering two reads of an alias set + * is considered safe. + * + * There is a special alias set called the "wildcard set", which indicates that + * we're not sure what this value may alias. To be conservative, we consider the + * wildcard alias set as potentially aliasing any other wildcard value within + * the same type class. Whenever a value becomes contained by another value, + * such as when a Tensor is appended to a List[Tensor], the contained element + * becomes part of the wildcard set. + * + * Values that contain other mutable types, such as List[Tensor], are + * initialized as containing the Wildcard set for all contained mutable types. + * + * The AliasDb API references the idea of "mutable" vs "immutable" + * types. "Mutable" means that the object's value can change, while + * "immutable" means that the value is fixed. (For example, `List` is + * mutable, so you can add and delete elements from it. On the other + * hand, you can't modify a Tuple once you create it, making `Tuple` an + * immutable container.) + * + * `isFrozen` - if the Module is frozen then consider attributes as freshly + * created objects. Freezing API invokes alias analysis to check if they are + * mutated internally. + * + * `descendFunctionCalls` - recursively analyze function and method calls + * instead of conservative analysis. Generally analysis should be done after + * inlining so the implementation for recursive analysis is unoptimized. + */ +class AliasDb { + public: + TORCH_API explicit AliasDb( + std::shared_ptr graphi, + bool isFrozen = false, + bool descendFunctionCalls = false); + TORCH_API ~AliasDb(); + + // There are limitations to what effects the alias analysis can track. Two + // kinds of nodes may have untracked effects: + // 1. Nodes that write to a value that may alias the graph inputs (since + // the inputs can be used outside the graph). + // 2. Nodes that write to something in the wildcard set. + // + // These nodes are considered not safe to eliminate or mutate under any + // circumstances. + bool writesToWildcard(Node* n) const; + + // Does `n` write to an alias of one of the values in `vs`? + // if `recurseBlocks` is true, consider writes on the nodes in `n`s sub-blocks + TORCH_API bool writesToAlias(Node* n, const ValueSet& vs) const; + + // Does `n` write to any of the values in `vls`? + TORCH_API bool writesToAlias(Node* n, const ValueAndMemoryLocationSet& vls) + const; + + TORCH_API ValueAndMemoryLocationSet getValueAndMemoryLocationSet() const; + + // Does `a` and `b` potentially share a memory location or do either + // hold in memory any element that exists in the other + TORCH_API bool mayContainAlias(Value* a, Value* b) const; + + TORCH_API bool mayContainAlias(Value* a, const at::ArrayRef b) const; + + // Do any values in group `a` share a memory location or hold in memory + // any element that exists in group `b` + TORCH_API bool mayContainAlias( + const at::ArrayRef a, + const at::ArrayRef b) const; + + // Do `a` and `b` potentially share a memory location? + TORCH_API bool mayAlias(const Value* a, const Value* b) const; + // Do any values in group `a` potentially share a memory location with any + // value in group `b`? i.e. may they overlap? + TORCH_API bool mayAlias(const ValueSet& a, const ValueSet& b) const; + + // Do any nodes write to an alias set input to `n`? + TORCH_API bool hasInputWriters(const Node* n) const; + + // Do any nodes write to an alias set output by `n`? + TORCH_API bool hasOutputWriters(const Node* n) const; + + // Do any nodes write to an alias set inputted/outputted by `n`? + TORCH_API bool hasWriters(const Node* n) const; + + // Do any nodes write to `v`s memory location? + TORCH_API bool hasWriters(const Value* v) const; + + // Is the operation in-place? i.e. doesn't write anywhere but locations it + // reads from. + TORCH_API bool isMutable(Node* n) const; + + TORCH_API bool escapesScope(const at::ArrayRef& vs) const; + + // Is it safe to change whether `a` and `b` alias each other ? + TORCH_API bool safeToChangeAliasingRelationship( + const at::ArrayRef& a, + const at::ArrayRef& b) const; + + // Move `n` (already in the graph) after `movePoint` in the topological order. + // + // Tries to preserve value dependencies, so other nodes might be moved. We + // make two guarantees about the postcondition of the node list: + // - `n` is directly after `movePoint`. + // - only nodes between `n` and `movePoint` have been moved. + // + // Returns `false` if it's impossible to move `n` after `MovePoint` without + // violating dependencies, otherwise executes the move and returns `true` + TORCH_API bool moveAfterTopologicallyValid(Node* n, Node* movePoint); + TORCH_API bool moveBeforeTopologicallyValid(Node* n, Node* movePoint); + + bool couldMoveAfterTopologically(Node* n, Node* movePoint); + bool couldMoveBeforeTopologically(Node* n, Node* movePoint); + + // For debugging: print alias db state to stdout + TORCH_API void dump() const; + TORCH_API std::string toString() const; + + // Generates a DOT (www.graphviz.org) graph representation + // + // Returns `true` if the output file was successfully generated + // + // WARNING: The output dot file path can't include shell specific notations, + // for example you can't use "~/temp/aliasdb.dot" + // (instead, use "/home/user/temp/aliasdb.dot") + // + TORCH_API bool dumpToGraphvizFile(const char* filename) const; + TORCH_API std::string toGraphviz() const; + + // Returns `true` if the given element is mutable or if it is a + // container type with an internal mutable element (e.g. + // `Tuple[int, Tensor]` has an internal mutable type `Tensor`, so + // it would be considered a "mutable type" in AliasDb) + static bool isMutableType(const Value* v); + static bool isMutableType(const TypePtr& type); + + /** + * Mutation API + * + * These methods allow you to update AliasDb in-place if you are performing + * graph mutation. + * + * WARNING: These methods should be considered INTERNAL. They do not perform + * very many correctness checks, the user is responsible for making sure they + * are updating AliasDb correctly. `Lint()`ing the AliasDb can help with + * this. + */ + // Copy `existing`s aliasing info to `new_value`, and remove `existing`. + TORCH_API void replaceWithNewValue(Value* existing, Value* new_value); + // Copy `from`s aliasing info to `to`. + TORCH_API void copyValue(Value* from, Value* to); + // Create a new `value` that does not alias anything else. + TORCH_API void createValue(const Value* value); + + // Enable more precise treatment of prim::TupleConstruct. + void enablePreciseTupleContainerAnalysis(); + + friend struct MutationRemover; + friend class ValueAndMemoryLocationSet; + + private: + // Helper for topologically-safe node moves. + class WorkingSet; + enum class MoveSide { BEFORE, AFTER }; + bool tryMove(Node* toMove, Node* movePoint, MoveSide moveSide, bool dryRun); + void move(Node* toMove, Node* movePoint, MoveSide moveSide); + bool isBeforeOrAfter(const Node* n, MoveSide moveSide) const; + + bool isMutableTypeInternal(const Value* v) const; + bool isMutableTypeInternal(const TypePtr& type) const; + + /** + * Write and read internal API + */ + // Get all the values that `n` writes to. + // NOTE: this only returns values directly written to, not aliases thereof + // + // if `recurseBlocks` is true, gather writes on the nodes in `n`s sub-blocks + MemoryLocations getWrites(Node* n) const; + void getWritesImpl(Node* n, MemoryLocations& ret) const; + // Register the fact that `n` writes to `v`. + void registerWrite(const Value* v, Node* n, bool writeToContained = false); + // Get all the values that `n` reads from. + // if `recurseBlocks` is true, gather reads on the nodes in `n`s sub-blocks + MemoryLocations getReads(Node* n) const; + void getReadsImpl(Node* n, MemoryLocations& ret) const; + MemoryLocations getMemoryLocations(Value* v) const; + + /** + * Wildcard methods + */ + // Register `v` as a wildcard value. + std::optional setWildcard(const Value* v); + + // Is this a value which will not alias? + bool nonAliasingValue(const Value* elem) const; + + /** + * Special analysis methods + */ + void analyze(const std::shared_ptr& graph); + void analyze(Block* block); + void analyze(Node* node); + void analyzeImpl(Node* node); + void analyzeIf(Node* node); + void analyzeLoop(Node* node); + void analyzeSubgraph(Node* node, const std::shared_ptr& subgraph); + void analyzeSubgraph(Node* node); + void analyzeCreator(Node* node); + void analyzeExtractor(Node* node); + void analyzeChunk(Node* node); + void analyzeBroadcastingChunk(Node* node); + void analyzeFork(Node* node); + void analyzeWait(Node* node); + void analyzeAwaitable(Node* node); + void analyzeAwaitableWait(Node* node); + void analyzeRpcAsync(Node* node); + void analyzeBatchNorm(Node* node); + void analyzeInstanceNorm(Node* node); + void analyzeGradOf(Node* node); + void analyzeSetAttr(Node* node); + void analyzeConservative(Node* node); + void analyzeContainerConstruct(Node* node); + bool tryRegisteredAnalysis(Node* node); + + /** + * Alias manipulation methods + */ + void makeAllAlias(const std::vector& values); + void makePointerTo(const Value* value, const Value* to); + TORCH_API void addToContainedElements( + const Value* element, + const Value* container); + void mapAliases(at::ArrayRef to, at::ArrayRef from); + void giveFreshAlias( + const Value* value, + bool add_wildcard_to_contained_elems = true); + Element* getOrCreateElement(const Value* value); + + const AliasTypeSet* mapTypeToAliasTypeSetPtr(const TypePtr& type) const; + bool functionalNonEscapingListUse(const Use& use) const; + bool functionalNonEscapingTupleUse(const Use& use) const; + + std::shared_ptr graph_; + + // If the Module is frozen then consider attributes as freshly created + // objects. Freezing API invokes alias analysis to check if they are mutated + // internally. + bool isFrozen_; + + bool descend_function_calls_; + std::unordered_map>> + function_call_copies_; + + // The points-to graph that stores aliasing relationships + std::unique_ptr memoryDAGBuilder_; + std::unique_ptr memoryDAG_; + + // Mapping of values to MemoryDAG elements + ska::flat_hash_map elementMap_; + // All wildcard Elements (one for each unique mutable type) + ska::flat_hash_map wildcardIndex_; + Element* getWildcard(const TypePtr& type) const; + std::optional tryGetOrCreateWildcard(const TypePtr& type); + void addContainedTypesToFreshElement( + Element* container_elem, + const AliasTypeSet& mut_types); + void pointUnionTypeElementToAllContainedTypes( + Element* container_elem, + const AliasTypeSet& mut_types); + + std::vector getElements(at::ArrayRef vs) const; + bool mayAliasWildcard(const Value* v) const; + bool mayAliasWildcard(const at::ArrayRef vs) const; + bool hasWriters(const at::ArrayRef& values) const; + + // Cached mapping of type ptrs to their mutable types + mutable ska::flat_hash_map mapped_mutable_types_; + + /** + * State for tracking write info. + */ + // Write registry where the analysis can record the writes as it sees them. + // This information is later denormalized into various caches to improve query + // efficiency. + struct WriteRegistry; + std::unique_ptr writeRegistry_; + + // Map of nodes to the memory locations that they write to + using TWriteIndex = ska::flat_hash_map; + std::optional writeIndex_; + // Collection of all memory locations that are written to. + std::optional writtenToLocationsIndex_; + void buildWrittenToLocationsIndex(); + + std::unordered_set wildcards_; + + std::string getElementName(const Element* e) const; + + friend void Lint(const AliasDb* db); +}; + +// Helper check that invariants over AliasDb are maintained. +// Useful if you are using the AliasDb mutation API and want to check you did +// the right thing. +TORCH_API void Lint(const AliasDb* db); + +/** + * ValueAndMemoryLocationSet + * + * A insert-only set of values which also maintains a MemoryLocations bitset + * of the memory locations that the values alias. It is insert-only. It + * should be constructed by calling aliasDb.getValueAndMemoryLocationSet(). + * + * WARNING: + * * The AliasDb must not be mutated after construction of a + * ValueAndMemoryLocationsSet, or else the MemoryLocations stored in the + * ValueAndMemoryLocationSet will no longer be accurate. + * * A ValueAndMemoryLocationsSet is tied to an instance of AliasDb but + * does not own the AliasDb. It is the user's responsibility to ensure + * that the AliasDb outlives the ValuesAndMemoryLocationsSet. + * + * The use case for this is to be able to implement writesToAlias + * more efficiently for a set of values. + */ +class ValueAndMemoryLocationSet { + public: + TORCH_API void insert(Value* v); + TORCH_API ValueSet& getValueSet(); + + friend class AliasDb; + + private: + ValueAndMemoryLocationSet(const AliasDb* db) : aliasDb_(db) {} + + const AliasDb* aliasDb_; + ValueSet valueSet_; + MemoryLocations memoryLocations_; +}; + +} // namespace torch::jit + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/ir/attributes.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/ir/attributes.h new file mode 100644 index 0000000000000000000000000000000000000000..35dfe7a87642f60500ce791979e3f9d610e84994 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/ir/attributes.h @@ -0,0 +1,185 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include +#include +#include + +#include +#include + +#include + +namespace torch::jit { + +using ::c10::Symbol; + +constexpr int max_tensor_display_size = 10; + +enum class AttributeKind { + f, + fs, + c, + cs, + i, + is, + s, + ss, + t, + ts, + g, + gs, + ty, + tys, + ival +}; +static inline const char* toString(AttributeKind kind) { + // NOLINTNEXTLINE(cppcoreguidelines-avoid-c-arrays,modernize-avoid-c-arrays) + static constexpr const char* names[] = { + "f", + "c", + "cs", + "fs", + "i", + "is", + "s", + "ss", + "t", + "ts", + "g", + "gs", + "ty", + "tys", + "ival"}; + AT_ASSERT(size_t(kind) < sizeof(names) / sizeof(*names)); + return names[int(kind)]; +} + +struct AttributeValue { + AttributeValue(Symbol name) : name(name) {} + using Ptr = std::unique_ptr; + Symbol name; + virtual AttributeKind kind() const = 0; + virtual Ptr clone() const = 0; + virtual ~AttributeValue() = default; +}; + +template +struct ScalarAttributeValue : public AttributeValue { + using ConstructorType = T; + using ValueType = T; + ScalarAttributeValue(Symbol name, ConstructorType value_) + : AttributeValue(name), value_(std::move(value_)) {} + ValueType& value() { + return value_; + } + Ptr clone() const override { + return Ptr(new ScalarAttributeValue(name, value_)); + } + AttributeKind kind() const override { + return Kind; + } + + private: + ValueType value_; +}; + +template +struct VectorAttributeValue : public AttributeValue { + using ConstructorType = std::vector; + using ValueType = std::vector; + VectorAttributeValue(Symbol name, ConstructorType value_) + : AttributeValue(name), value_(std::move(value_)) {} + ValueType& value() { + return value_; + } + AttributeKind kind() const override { + return Kind; + } + std::unique_ptr clone() const override { + auto copy = value_; + return Ptr(new VectorAttributeValue(name, std::move(copy))); + } + + private: + ValueType value_; +}; + +using ComplexAttr = + ScalarAttributeValue, AttributeKind::c>; +using ComplexValsAttr = + VectorAttributeValue, AttributeKind::cs>; +using FloatAttr = ScalarAttributeValue; +using FloatsAttr = VectorAttributeValue; +using IntAttr = ScalarAttributeValue; +using IntsAttr = VectorAttributeValue; +using StringAttr = ScalarAttributeValue; +using StringsAttr = VectorAttributeValue; +using TensorAttr = ScalarAttributeValue; +using TensorsAttr = VectorAttributeValue; +using TypeAttr = ScalarAttributeValue; +using TypesAttr = VectorAttributeValue; +using IValueAttr = ScalarAttributeValue; + +struct Graph; + +// We special case Graph attributes like this because we want to ensure that +// Graph::copy() is called when we clone() these attributes. +struct TORCH_API GraphAttr : public AttributeValue { + using ConstructorType = std::shared_ptr; + using ValueType = std::shared_ptr; + GraphAttr(Symbol name, ConstructorType value_) + : AttributeValue(name), value_(std::move(value_)) {} + ValueType& value() { + return value_; + } + Ptr clone() const override; + AttributeKind kind() const override { + return AttributeKind::g; + } + + private: + std::shared_ptr value_; +}; + +struct TORCH_API GraphsAttr : public AttributeValue { + using ConstructorType = std::vector>; + using ValueType = std::vector>; + GraphsAttr(Symbol name, ConstructorType value_) + : AttributeValue(name), value_(std::move(value_)) {} + ValueType& value() { + return value_; + } + AttributeKind kind() const override { + return AttributeKind::gs; + } + std::unique_ptr clone() const override; + + private: + ValueType value_; +}; + +struct IRAttributeError : public std::exception { + IRAttributeError(Symbol name, bool defined) { + std::stringstream ss; + // NOLINTNEXTLINE(bugprone-branch-clone) + if (!defined) { + ss << "required keyword attribute '" << name.toUnqualString() + << "' is undefined"; + } else { + ss << "required keyword attribute '" << name.toUnqualString() + << "' has the wrong type"; + } + msg = ss.str(); + } + const char* what() const noexcept override { + return msg.c_str(); + } + + private: + std::string msg; +}; +} // namespace torch::jit + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/ir/constants.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/ir/constants.h new file mode 100644 index 0000000000000000000000000000000000000000..f7fd7f01304ca0fff41a52a4f1de7fd7b1e9ca6d --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/ir/constants.h @@ -0,0 +1,65 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once +#include +#include +#include +#include +#include + +// helpers for handling constants in the IR +// - create constant nodes from ints, floats, complex, intlist, Tensors, and +// other types +// - implement primitive constant ops. + +namespace torch::jit { + +using ::c10::IValue; + +struct Graph; +struct Value; + +// thrown when insertConstant cannot encode the IValue into a graph +struct TORCH_API constant_not_supported_error : public std::runtime_error { + using runtime_error::runtime_error; +}; + +TORCH_API Value* insertConstant( + Graph& g, + const IValue& val, + std::optional loc = std::nullopt, + std::optional scope = std::nullopt); + +// note: prefer g.insertConsant(val, loc) which does exactly the same thing +// this function is only declared/defined here because its implementation is +// closely related to the implementation of prim::Constant that is also in +// constants.cpp. +// +// returns a std::nullopt if the IValue kind cannot be inserted as a constant +TORCH_API std::optional tryInsertConstant( + Graph& g, + const IValue& val, + std::optional loc = std::nullopt, + std::optional scope = std::nullopt); + +//////////////////////////////////////////////////////////////////////////////// +// Helper for retrieving constants +//////////////////////////////////////////////////////////////////////////////// + +// attempt to convert a (possibly constant) Value* into an interpreter value +// (IValue). returns std::nullopt if the Value* was not constant +TORCH_API std::optional toIValue(const Value* v); + +// if a value is a constant then try to turn into type T using the +// same rules as the interpreter +template +std::optional constant_as(const Value* v) { + if (auto ivalue = toIValue(v)) { + return ivalue->to(); + } + return std::nullopt; +} +} // namespace torch::jit + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/ir/graph_node_list.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/ir/graph_node_list.h new file mode 100644 index 0000000000000000000000000000000000000000..e1ffa81efea513b2046ea9f86acc495b1f48e45c --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/ir/graph_node_list.h @@ -0,0 +1,204 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +namespace torch::jit { + +// Intrusive doubly linked lists with sane reverse iterators. +// The header file is named generic_graph_node_list.h because it is ONLY +// used for Graph's Node lists, and if you want to use it for other +// things, you will have to do some refactoring. +// +// At the moment, the templated type T must support a few operations: +// +// - It must have a field: T* next_in_graph[2] = { nullptr, nullptr }; +// which are used for the intrusive linked list pointers. +// +// - It must have a method 'destroy()', which removes T from the +// list and frees a T. +// +// In practice, we are only using it with Node and const Node. 'destroy()' +// needs to be renegotiated if you want to use this somewhere else. +// +// Regardless of the iteration direction, iterators always physically point +// to the element they logically point to, rather than +// the off-by-one behavior for all standard library reverse iterators like +// std::list. + +// The list is includes two sentinel nodes, one at the beginning and one at the +// end with a circular link between them. It is an error to insert nodes after +// the end sentinel node but before the beginning node: + +// Visualization showing only the next() links: +// HEAD -> first -> second -> ... -> last -> TAIL +// ^------------------------------------------ + +// Visualization showing only the prev() links: +// HEAD <- first <- second <- ... <- last <- TAIL +// ------------------------------------------^ + +static constexpr int kNextDirection = 0; +static constexpr int kPrevDirection = 1; + +template +struct generic_graph_node_list; + +template +struct generic_graph_node_list_iterator; + +struct Node; +using graph_node_list = generic_graph_node_list; +using const_graph_node_list = generic_graph_node_list; +using graph_node_list_iterator = generic_graph_node_list_iterator; +using const_graph_node_list_iterator = + generic_graph_node_list_iterator; + +template +struct generic_graph_node_list_iterator { + generic_graph_node_list_iterator() : cur(nullptr), d(kNextDirection) {} + generic_graph_node_list_iterator(T* cur, int d) : cur(cur), d(d) {} + generic_graph_node_list_iterator( + const generic_graph_node_list_iterator& rhs) = default; + generic_graph_node_list_iterator( + generic_graph_node_list_iterator&& rhs) noexcept = default; + generic_graph_node_list_iterator& operator=( + const generic_graph_node_list_iterator& rhs) = default; + generic_graph_node_list_iterator& operator=( + generic_graph_node_list_iterator&& rhs) noexcept = default; + T* operator*() const { + return cur; + } + T* operator->() const { + return cur; + } + generic_graph_node_list_iterator& operator++() { + AT_ASSERT(cur); + cur = cur->next_in_graph[d]; + return *this; + } + generic_graph_node_list_iterator operator++(int) { + generic_graph_node_list_iterator old = *this; + ++(*this); + return old; + } + generic_graph_node_list_iterator& operator--() { + AT_ASSERT(cur); + cur = cur->next_in_graph[reverseDir()]; + return *this; + } + generic_graph_node_list_iterator operator--(int) { + generic_graph_node_list_iterator old = *this; + --(*this); + return old; + } + + // erase cur without invalidating this iterator + // named differently from destroy so that ->/. bugs do not + // silently cause the wrong one to be called. + // iterator will point to the previous entry after call + void destroyCurrent() { + T* n = cur; + cur = cur->next_in_graph[reverseDir()]; + n->destroy(); + } + generic_graph_node_list_iterator reverse() { + return generic_graph_node_list_iterator(cur, reverseDir()); + } + + private: + int reverseDir() { + return d == kNextDirection ? kPrevDirection : kNextDirection; + } + T* cur; + int d; // direction 0 is forward 1 is reverse, see next_in_graph +}; + +template +struct generic_graph_node_list { + using iterator = generic_graph_node_list_iterator; + using const_iterator = generic_graph_node_list_iterator; + generic_graph_node_list_iterator begin() { + return generic_graph_node_list_iterator(head->next_in_graph[d], d); + } + generic_graph_node_list_iterator begin() const { + return generic_graph_node_list_iterator(head->next_in_graph[d], d); + } + generic_graph_node_list_iterator end() { + return generic_graph_node_list_iterator(head->next_in_graph[!d], d); + } + generic_graph_node_list_iterator end() const { + return generic_graph_node_list_iterator( + head->next_in_graph[!d], d); + } + generic_graph_node_list_iterator rbegin() { + return reverse().begin(); + } + generic_graph_node_list_iterator rbegin() const { + return reverse().begin(); + } + generic_graph_node_list_iterator rend() { + return reverse().end(); + } + generic_graph_node_list_iterator rend() const { + return reverse().end(); + } + generic_graph_node_list reverse() { + return generic_graph_node_list(head->next_in_graph[!d], !d); + } + const generic_graph_node_list reverse() const { + return generic_graph_node_list(head->next_in_graph[!d], !d); + } + T* front() { + return head->next_in_graph[d]; + } + const T* front() const { + return head->next_in_graph[d]; + } + T* back() { + return head->next_in_graph[!d]; + } + const T* back() const { + return head->next_in_graph[!d]; + } + generic_graph_node_list(T* head, int d) : head(head), d(d) {} + + private: + T* head; // both head and tail are sentinel nodes + // the first real node is head->next_in_graph[d] + // the tail sentinel is head->next_in_graph[!d] + int d; +}; + +template +static inline bool operator==( + generic_graph_node_list_iterator a, + generic_graph_node_list_iterator b) { + return *a == *b; +} + +template +static inline bool operator!=( + generic_graph_node_list_iterator a, + generic_graph_node_list_iterator b) { + return *a != *b; +} + +} // namespace torch::jit + +namespace std { + +template +struct iterator_traits> { + using difference_type = int64_t; + using value_type = T*; + using pointer = T**; + using reference = T*&; + using iterator_category = bidirectional_iterator_tag; +}; + +} // namespace std + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/ir/graph_utils.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/ir/graph_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..fe3c83f45e44792baf30e582f6cdbada415afc23 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/ir/graph_utils.h @@ -0,0 +1,28 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#pragma once + +#include + +#include + +namespace torch::jit { + +TORCH_API TypePtr getTensorType(const at::Tensor& t, bool complete); + +TORCH_API TypePtr inferShapeAndTypeForInput( + TypePtr input_type, + Stack::const_iterator& s_iter, + const Stack::const_iterator& s_iter_end, + bool complete); + +TORCH_API void setInputTensorTypes( + Graph& g, + const Stack& stack, + bool complete, + const std::vector& param_count_list = {}); + +} // namespace torch::jit + +#else +#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined." +#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/ir/ir.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/ir/ir.h new file mode 100644 index 0000000000000000000000000000000000000000..00989ec278295179dd96543358322c3647825dd3 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/jit/ir/ir.h @@ -0,0 +1,1836 @@ +#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION) +#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 + +// Forward declare, the real meat is in python_ir.cpp +template +class THPPointer; +using THPObjectPtr = THPPointer; +using pyobj_list = std::vector; + +namespace torch::jit { +namespace utils { +TORCH_API std::string getNodesModuleHierarchy(const Node& n); +} // namespace utils +class AliasDb; + +using ::c10::Argument; +using ::c10::FunctionSchema; +using ::c10::Symbol; + +using ::c10::ivalue::Shared; + +using ::c10::IValue; +using ::c10::ivalue::Future; + +using ::c10::ivalue::ConstantString; + +#define C10_USING(T) using ::c10::T; +C10_FORALL_TYPES(C10_USING) +#undef C10_USING + +#define C10_USING(T) using ::c10::T##Ptr; +C10_FORALL_TYPES(C10_USING) +#undef C10_USING + +using ::c10::Type; +using ::c10::TypeEnv; +using ::c10::TypePtr; + +using ::c10::getTypePtr; +using ::c10::MatchTypeReturn; +using ::c10::TypeKind; + +using ::c10::fmap; + +namespace prim { +using namespace ::c10::prim; +} +namespace attr { +using namespace ::c10::attr; +} +namespace aten { +using namespace ::c10::aten; +} +namespace cuda { +using namespace ::c10::cuda; +} // namespace cuda + +struct Function; +struct GraphFunction; +struct MatchedSchema; + +// A Graph represents one "function" of computation. +// It uses a simple ownership model where the graph owns all the nodes inside +// it. All references inside the graph are raw pointers. Destroying the Graph +// will invalidate any pointers to nodes in the graph. +struct Graph; + +// Node is the base class of the IR graph. It represents one computation +// and dependencies on a list of Values. The "prim-ops", so to speak. +struct Node; + +// A Value represents an input or output to node that is either a +// Tensor or an opaque Handle object, as determined by type(). +struct Value; + +TORCH_API std::ostream& operator<<(std::ostream& out, const Graph& g); +TORCH_API std::ostream& operator<<(std::ostream& out, const Node& n); + +// A list of nodes, with inputs and outputs +struct Block; + +// Each use is represented by this type, see 'Node::uses()' +// 'user' is the consumer of the value, 'offset' is the index into +// 'user's input this where the producers will be found. +struct Use { + Use(Node* user, size_t offset) : user(user), offset(offset) {} + Node* user; + size_t offset; + + bool operator==(const Use& b) { + return user == b.user && offset == b.offset; + } +}; + +// Note [User node does not uniquely identify use] +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// A while back, we wrote some code manipulating uses that looked like this: +// +// for (auto& use : used_val->uses_) { +// if (use.user == this_node) { +// use.offset += 1; +// break; +// } +// } +// +// This code is trying to find a particular use (our node's use) to update it. +// However, it's wrong: there may be *multiple* uses of a value %x in a node, +// as might be the case in this IR: +// +// %y = Add %x %x +// +// In this case, there are two uses of %x whose user is the node 'Add %x %x'. +// So, "use induced by this node" is not a well-formed concept. +// +// If you are looking for "use induced by an input", it's best to use +// findUseForInput() to get it. + +// the list types are intentionally simple, but we type-def +// them here so if we need to change them, refactoring will be easier +using node_list = std::vector; +using value_list = std::vector; +using use_list = std::vector; +template +using ArrayRef = at::ArrayRef; +using NodeKind = Symbol; +using topo_position_t = int64_t; +using ValueSet = std::unordered_set; + +struct OperatorSet; +template +struct OperatorMap; + +// This is a wrapper to allow invalidating the Python object +// safely when the C++ object for a Node/Value/Block is deleted +// like much of graph, it isn't safe for different threads to +// access the same graph +template +struct Wrap { + explicit Wrap(T* p) : elem(p) {} + void clear() { + if (clear_cb) { + clear_cb(elem); + } + elem = nullptr; + } + T* elem; + void (*clear_cb)(void*){nullptr}; +}; + +struct Value { + AT_DISALLOW_COPY_AND_ASSIGN(Value); + Value(Node* node_, size_t offset_); + + private: + friend struct Node; + friend struct Graph; + Node* node_; + size_t offset_; + size_t unique_ = 0; // unique id + use_list uses_; + std::string unique_name_; + TypePtr type_; + // a managing wrapper for Python to allow invalidation + std::shared_ptr> wrap_; + + public: + Value* setType(TypePtr type); + TORCH_API void inferTypeFrom(const at::Tensor& output); + TORCH_API void inferTypeFrom( + const c10::intrusive_ptr& output); + const TypePtr& type() const { + AT_ASSERT(type_ != nullptr); + return type_; + } + bool requires_grad() const { + return type()->requires_grad(); + } + bool isCompleteTensor() const { + if (auto pt = type()->cast()) { + return pt->isComplete(); + } + return false; + } + TORCH_API bool mustBeNone() const; + TORCH_API bool mustNotBeNone() const; + size_t unique() const { + return unique_; + } + bool hasDebugName() const { + return !unique_name_.empty(); + } + static bool isValidName(const std::string& name); + TORCH_API Value* setDebugName(const std::string& name); + std::string debugName() const { + if (hasDebugName()) { + return unique_name_; + } + return std::to_string(unique()); + } + TORCH_API std::string debugNameBase() const; + Node* node() { + return node_; + } + size_t offset() const { + return offset_; + } + void setOffset(size_t offset) { + offset_ = offset; + } + const Node* node() const { + return node_; + } + + /** + * @warning NEVER pass raw pointer of smart pointer managed Graph to Python. + * Check #87343 for details. + */ + Graph* owningGraph(); + const Graph* owningGraph() const; + // TODO: make this more const correct + const use_list& uses() const { + return uses_; + } + + bool hasUses() const { + return !uses().empty(); + } + + TORCH_API void replaceFirstUseWith(Value* newValue); + + // Replaces all uses of this value with 'newValue'. + // + // Given: %3 = f(%1, %2) + // %4 = g(%3) + // %5 = h(%3, %3) + // Execute: %3.replaceAllUsesWith(%6) + // Result: %3 = f(%1, %2) + // %4 = g(%6) + // %5 = h(%6, %6) + TORCH_API void replaceAllUsesWith(Value* newValue); + + // Replaces all uses of this value with 'newValue' after 'node'. + // Given: %3 = f(%1, %2) + // %4 = g(%3) + // %5 = inplace_(%3) + // %6 = h(%3, %3) + // Execute: %3.replaceAllUsesAfterNodeWith(%5.node(), %5) + // Result: %3 = f(%1, %2) + // %4 = g(%3) + // %5 = inplace_(%3) + // %6 = h(%5, %5) + // XXX: does not check scoping legality, consider using + // replaceAllUsesDominatedByNodeWith + TORCH_API void replaceAllUsesAfterNodeWith(const Node* node, Value* newValue); + + // Replaces all uses of this value with 'newValue' that are dominated by + // 'node'. Given: + // x = op(...). + // if cond: + // z = foo(..) + // bar(x) + // else: + // print(x) + // x.replaceAllUsesDominatedByNodeWith(foo, z) would replace bar(x) + // but not print(x) because print is not dominated by foo. + // replaceAllUsesAfterNode does not check domination, so in this example + // it would produce invalid IR. + TORCH_API void replaceAllUsesDominatedByNodeWith( + const Node* node, + Value* newValue); + + TORCH_API Value* copyMetadata(Value* from); + + TORCH_API std::shared_ptr> wrap() { + if (!wrap_) { + wrap_ = std::make_shared>(this); + } + return wrap_; + } + + virtual ~Value() { + if (wrap_) { + wrap_->clear(); + } + } +}; + +struct TORCH_API Node { + AT_DISALLOW_COPY_AND_ASSIGN(Node); + friend struct Graph; + friend struct Block; + friend struct Value; + friend graph_node_list; + friend const_graph_node_list; + friend graph_node_list_iterator; + friend const_graph_node_list_iterator; + + private: + const NodeKind kind_; + std::vector inputs_; + std::vector outputs_; + // subblocks + std::vector blocks_; + Graph* graph_; + Block* owning_block_; + std::optional source_range_; + ScopePtr scope_; + std::optional callstack_; + // Assumes FunctionSchemas are persistent, so we don't manage their lifetime. + // This field is effective a cache that's populated on attribute lookups and + // invalidated every time we perform an operation that could potentially + // change the schema. note: mutable because schema_ is effectively a cache + mutable const Operator* op_; + topo_position_t topo_position_ = 0; + // a managing wrapper for Python to allow invalidation + std::shared_ptr> wrap_; + // Stores the full schema name, if the operator is historic + // When the operator is deprecated or the name of the operator + // is changed, we need to rely on this name + // to retrieve old schemas to successfully apply upgraders + // for this operator. + std::optional historic_schema_name_ = std::nullopt; + + protected: + Node(Graph* graph_, NodeKind kind_); // defined after graph + public: + // Each Node but Return/Param Nodes are associated with exactly one + // place in the Node list of the Graph. The Graph itself is a circular + // doubly-linked list. The Return Node is used as the sentinel for the + // "beginning"/"end" of the list. This means that you can tell when + // you've traversed the entire list without means worrying about null + // pointers. `next_in_graph[0]` is the pointer to the next Node, while + // `next_in_graph[1]` is the pointer to the previous Node. The + // linked list is implemented as an array to allow the same iterator + // class for forward and reversed Node lists. Taken together, this + // list also represents a topological sort of the Nodes in the Graph. + // NOLINTNEXTLINE(cppcoreguidelines-avoid-c-arrays,cppcoreguidelines-non-private-member-variables-in-classes,modernize-avoid-c-arrays) + Node* next_in_graph[2] = {nullptr, nullptr}; + + std::shared_ptr> wrap() { + if (!wrap_) { + wrap_ = std::make_shared>(this); + } + return wrap_; + } + + const std::optional getHistoricSchemaName() { + return historic_schema_name_; + } + + void setHistoricSchemaName(const std::string& name) { + historic_schema_name_ = name; + } + + Node*& next() { + return next_in_graph[kNextDirection]; + } + Node*& prev() { + return next_in_graph[kPrevDirection]; + } + Node* const& next() const { + return next_in_graph[kNextDirection]; + } + Node* const& prev() const { + return next_in_graph[kPrevDirection]; + } + + NodeKind kind() const { + return kind_; + } + Node* setSourceRange(SourceRange r) { + source_range_ = std::move(r); + return this; + } + SourceRange sourceRange() const; + + /** + * @warning NEVER pass raw pointer of smart pointer managed Graph to Python. + * Check #87343 for details. + */ + Graph* owningGraph() { + return graph_; + } + const Graph* owningGraph() const { + return graph_; + } + Block* owningBlock() { + return owning_block_; + } + const Block* owningBlock() const { + return owning_block_; + } + ScopePtr scope() { + return scope_; + } + void setScope(ScopePtr scope) { + scope_ = std::move(scope); + } + std::string scopeName() const { + if (!scope_) { + return ""; + } + return scope_->namesFromRoot(); + } + + // Copies the source range, scope and callstack from another node. + Node* copyMetadata(Node* from) { + this->setSourceRange(from->sourceRange()); + this->setScope(from->scope()); + if (auto cs = from->callstack()) { + this->setCallStack(*cs); + } + return this; + } + + std::optional callstack() const { + return callstack_; + } + void setCallStack(InlinedCallStackPtr cs) { + callstack_ = std::move(cs); + } + + // NB: This returns an ArrayRef; that means that it will + // get invalidated if you resize inputs (e.g., using addInput) + // We can't return a std::vector& because there's no + // way to soundly cast to std::vector (an insane + // implementation of std::vector could make this representationally + // different.) + at::ArrayRef inputs() { + return inputs_; + } + at::ArrayRef inputs() const { + // Vectors are not convertible in const-ness of elements, but + // raw pointers are. + return {inputs_.data(), inputs_.size()}; + } + // NB: This returns an ArrayRef; that means that it will + // get invalidated if you resize inputs (e.g., using addInput) + // We can't return a std::vector& because there's no + // way to soundly cast to std::vector (an insane + // implementation of std::vector could make this representationally + // different.) + at::ArrayRef outputs() { + return outputs_; + } + at::ArrayRef outputs() const { + // Vectors are not convertible in const-ness of elements, but + // raw pointers are. + return {outputs_.data(), outputs_.size()}; + } + Value* output(size_t i) const { + return outputs_.at(i); + } + bool hasUses() const { + for (auto o : outputs()) { + if (!o->uses().empty()) { + return true; + } + } + return false; + } + + void replaceAllUsesWith(Node* n); + + // replaces `this` with a new node with the same inputs and outputs + // but a new node symbol. does not destroy `this` + Node* replaceWithNewSymbol(Symbol new_symbol); + + // Checks if this node is dominated by `dominator` which means that + // `dominator` will always be executed before `this` and `dominator` + // is in scope of `this. + bool isDominatedBy(const Node* dominator) const; + + // lots of things like chunk have a single input or single output, so we have + // a helper to make accessing it easier + Value* input() { + AT_ASSERT(inputs_.size() == 1); + return inputs_.at(0); + } + Value* output() { + AT_ASSERT(outputs_.size() == 1); + return outputs_.at(0); + } + const Value* output() const { + AT_ASSERT(outputs_.size() == 1); + return outputs_.at(0); + } + const Value* input() const { + AT_ASSERT(inputs_.size() == 1); + return inputs_.at(0); + } + // Access a particular input. This is a checked index. + Value* input(size_t i) const { + return inputs_.at(i); + } + + bool hasNamedInput(const std::string& unqualName) const; + Value* namedInput(const std::string& unqualName) const; + Value* namedInput(Symbol name) const; + + std::optional get(Symbol name) const; + + template + std::optional get(Symbol name) const { + if (auto v = get(name)) { + return v->template to(); + } + return std::nullopt; + } + + // Returns true if the value of input name is statically known + bool is_constant(Symbol name) const { + return static_cast(get(name)); + } + bool mustBeNone() const; + + bool isNondeterministic() const; + bool hasSideEffects() const; + + // instructions lowered by the interpreter and not run in the optimized graph + bool notExecutedOp() const { + return kind_ == prim::Constant || kind_ == prim::profile || + kind_ == prim::profile_ivalue; + } + + // Graphs + + // Note [Topological invariant] + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + // We always maintain an up-to-date topological ordering of all nodes via + // the next()/prev() links. All transformations to graphs must preserve + // this topological ordering: for example, it is only valid to 'addInput' + // with an input which is topologically before the current node. + // + // Usually, it is obvious whether or not topological order is maintained; + // for example, if you are adding nodes to the end of the topsort, it's + // impossible for them to refer to inputs that are not in the topsort. + // If it is not obvious, please comment accordingly. + + // Add 'node' as an input to 'this' at the end of existing + // arguments. Returns the added node for ease of chaining. + // + // Given: %3 = f(%1, %2) + // Execute: %3.addInput(%4) + // Result: %3 = f(%1, %2, %4) + Value* addInput(Value* value); + + // Add 'value' as an input to 'this' at the specified position in the + // arguments. Returns the added value for ease of chaining. + Value* insertInput(size_t i, Value* value); + + // Replace the input of 'this' at position 'i' with + // 'newValue', returning the old node. + // + // Given: %3 = f(%1, %2) + // Execute: %3.replaceInput(1, %4) + // Result: %3 = f(%1, %4) + Value* replaceInput(size_t i, Value* newValue); + + // Replace all occurrences of 'from' in the inputs of this + // node with 'to'. Corresponds to llvm's replaceUsesOfWith. + // + // Given: %3 = f(%1, %2, %1) + // Execute: %3.replaceInputWith(%1, %4) + // Result: %3 = f(%4, %2, %4) + void replaceInputWith(Value* from, Value* to); + + Value* addOutput(); + + Value* insertOutput(size_t i); + + void eraseOutput(size_t i); + + Block* addBlock(); + void eraseBlock(size_t i); + + // Each Node can have a list of subblocks. These are used to define structured + // nested control flow operators such as If and Loop. + // The meaning of a block is specific to the kind of node it is in, but + // all blocks share these semantics: + // * Nested lexical scoping: If a node 'Parent' has a subblock which contains + // a node 'Child', Child can use any value that was in scope for the Parent + // node in addition to any values defined before 'Child' in the subblock. + // * The list of inputs to the block are in scope for the duration of the + // block + // * the outputs of the Parent node are not in scope for the subblocks + // Typically the inputs to a block that represents control flow act as + // as the equivalents phi-nodes in standard SSA form, + // defining a new Value to represent any term that has multiple + // definitions depending on how control flowed. Outputs of the node containing + // control flow serve a similar purpose defining new values for variables + // that would have different definitions depending on which way control + // flowed. + + at::ArrayRef blocks() { + return blocks_; + } + at::ArrayRef blocks() const { + // Vectors are not convertible in const-ness of elements, but + // raw pointers are. + return {blocks_.data(), blocks_.size()}; + } + + // Is 'this' before 'n' in the topological order? + bool isBefore(const Node* n) const; + + // Is 'this' after 'n' in the topological order? + bool isAfter(const Node* n) const; + + // Insert unattached 'this' node before 'n' in the topological order. + // Returns this (for chaining). + // + // Given: %3 = f(%1, %2) + // %4 = g(%3) + // and unattached: %5 = h(%1) + // Execute: %5.insertBefore(%4) + // Result: %3 = f(%1, %2) + // %5 = h(%1) + // %4 = g(%3) + Node* insertBefore(Node* n); + + // Insert unattached 'this' node after 'n' in the topological order. + // Returns this (for chaining). + // + // Given: %3 = f(%1, %2) + // %4 = g(%3) + // and unattached: %5 = h(%1) + // Execute: %5.insertAfter(%4) + // Result: %3 = f(%1, %2) + // %4 = g(%3) + // %5 = h(%1) + Node* insertAfter(Node* n); + + // Move 'this' (already in the graph) after 'n' in the topological order. + // + // NOTE: Does not check that value dependencies are preserved, see + // AliasDb::moveAfterTopologicallyValid + // + // Given: %2 = f(%1) + // %3 = g(%1) + // Execute: %2.moveAfter(%3) + // Result: %3 = g(%1) + // %2 = f(%1) + // + void moveAfter(Node* n); + + // Move a node 'n' (already in the graph) before 'this' in the topological + // order. + // + // NOTE: Does not check that value dependencies are preserved, see + // AliasDb::moveBeforeTopologicallyValid + // + // Given: %2 = f(%1) + // %3 = g(%1) + // Execute: %3.moveBefore(%2) + // Result: %3 = g(%1) + // %2 = f(%1) + void moveBefore(Node* n); + + // Remove the input at 'i' from this node. + // + // WARNING: This is O(n) in the number of inputs, so avoid repeatedly calling + // removeInput. + // + // Given: %3 = f(%1, %2) + // Execute: %3.removeInput(1) + // Result: %3 = f(%1) + void removeInput(size_t i); + + // Remove all inputs from a node. + // + // Given: %3 = f(%1, %2) + // Execute: %3.removeAllInputs() + // Result: %3 = f() + void removeAllInputs(); + + // Remove all outputs from a node. + // + // Given: %1, %2 = f() + // Execute:removeAllInputs() + // Result: = f() + void removeAllOutputs(); + + // Rearrange the ordering of inputs or outputs of a node + // Given: %3 = f(%1, %2) + // Execute: %3.permuteInputs({1, 0}) + // Result: %3 = f(%2, %1) + // Each index must appear exactly once + void permuteInputs(const std::vector& new_inputs); + void permuteOutputs(const std::vector& new_inputs); + + // iterators of the node list starting at this node + // useful for resuming a search starting at this node + inline graph_node_list_iterator iterator() { + return {this, 0}; + } + inline graph_node_list_iterator reverseIterator() { + return iterator().reverse(); + } + inline const_graph_node_list_iterator iterator() const { + return {this, 0}; + } + inline const_graph_node_list_iterator reverseIterator() const { + return iterator().reverse(); + } + + // Remove 'this' from the instruction list and deallocate it. + // + // Invariant: no outputs of 'this' may have any uses. + // + // Given: %2 = f(%1) + // %3 = g(%1) + // Execute: %2.destroy() + // Result: %3 = g(%1) + void destroy(); + + // Dynamically cast this node to the subclass indicated by the + // template variable, returning nullptr if the cast is invalid.. + // + // Example usage: if(auto s = n.cast