file_path
stringlengths 7
180
| content
stringlengths 0
811k
| repo
stringclasses 11
values |
---|---|---|
src/runtime/graph_executor/graph_executor_factory.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* \file tvm/runtime/graph_executor/graph_executor_factory.h
* \brief Graph executor factory creating graph executor.
*/
#ifndef TVM_RUNTIME_GRAPH_EXECUTOR_GRAPH_EXECUTOR_FACTORY_H_
#define TVM_RUNTIME_GRAPH_EXECUTOR_GRAPH_EXECUTOR_FACTORY_H_
#include <tvm/runtime/c_runtime_api.h>
#include <tvm/runtime/module.h>
#include <tvm/runtime/ndarray.h>
#include <tvm/runtime/packed_func.h>
#include <algorithm>
#include <functional>
#include <numeric>
#include <string>
#include <unordered_map>
#include <vector>
#include "./graph_executor.h"
namespace tvm {
namespace runtime {
class TVM_DLL GraphExecutorFactory : public runtime::ModuleNode {
public:
/*!
* \brief Construct the GraphExecutorFactory.
* \param graph_json The execution graph.
* \param params The params of graph.
* \param module_name The module name of graph.
*/
GraphExecutorFactory(const std::string& graph_json,
const std::unordered_map<std::string, tvm::runtime::NDArray>& params,
const std::string& module_name = "default");
/*!
* \brief Get member function to front-end
* \param name The name of the function.
* \param sptr_to_self The pointer to the module node.
* \return The corresponding member function.
*/
PackedFunc GetFunction(const std::string& name, const ObjectPtr<Object>& sptr_to_self) final;
/*!
* \return The type key of the executor.
*/
const char* type_key() const final { return "GraphExecutorFactory"; }
/*!
* \brief Save the module to binary stream.
* \param stream The binary stream to save to.
*/
void SaveToBinary(dmlc::Stream* stream) override;
/*!
* \brief Create a specific executor module
* \param devs The device of the host and devices where graph nodes will be
* executed on.
* \return created executor module
*/
Module ExecutorCreate(const std::vector<Device>& devs);
/*!
* \brief Create a specific debug executor module
* \param devs The device of the host and devices where graph nodes will be
* executed on.
* \return created debug executor module
*/
Module DebugExecutorCreate(const std::vector<Device>& devs);
/*!
* \brief Create a specific cuda graph executor module
* \param devs The device of the host and devices where graph nodes will be
* executed on.
* \return created cuda graph executor module
*/
Module CudaGraphExecutorCreate(const std::vector<Device>& devs);
/*!
* \brief Set params.
* \param graph_executor The graph executor we want to set the params into.
* \param params The graph params value we want to set.
*/
void SetParams(GraphExecutor* graph_executor,
const std::unordered_map<std::string, tvm::runtime::NDArray>& params) const {
std::unordered_map<std::string, tvm::runtime::NDArray> value = params;
// upload big arrays first to avoid memory issue in rpc mode
std::vector<std::string> keys;
for (const auto& p : value) {
keys.emplace_back(p.first);
}
std::sort(std::begin(keys), std::end(keys),
[&](const std::string& lhs, const std::string& rhs) -> bool {
auto lhs_size = GetDataSize(*value[lhs].operator->());
auto rhs_size = GetDataSize(*value[rhs].operator->());
return lhs_size > rhs_size;
});
for (const auto& key : keys) {
int in_idx = graph_executor->GetInputIndex(key);
if (in_idx >= 0) {
graph_executor->SetInput(in_idx, const_cast<DLTensor*>(value[key].operator->()));
}
}
}
protected:
/*! \brief The execution graph. */
std::string graph_json_;
/*! \brief The params. */
std::unordered_map<std::string, tvm::runtime::NDArray> params_;
/*! \brief module name */
std::string module_name_;
};
} // namespace runtime
} // namespace tvm
#endif // TVM_RUNTIME_GRAPH_EXECUTOR_GRAPH_EXECUTOR_FACTORY_H_
| https://github.com/zk-ml/tachikoma |
src/runtime/hexagon/hexagon_buffer.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#ifndef TVM_RUNTIME_HEXAGON_HEXAGON_BUFFER_H_
#define TVM_RUNTIME_HEXAGON_HEXAGON_BUFFER_H_
#include <tvm/runtime/c_runtime_api.h>
#include <tvm/runtime/device_api.h>
#include <tvm/runtime/logging.h>
#include <tvm/runtime/ndarray.h>
#include <tvm/runtime/packed_func.h>
#include <memory>
#include <vector>
namespace tvm {
namespace runtime {
namespace hexagon {
struct Allocation;
class HexagonBuffer {
public:
/* \brief Allocate 1d (contiguous) memory within Hexagon accessible
* memory scopes.
*
* \param nbytes The number of bytes of physical storage
* to allocate.
*
* \param alignment The byte alignment to be used when allocating.
*
* \param scope Optional storage scope indicating the memory
* space in which to allocate. Defaults to global system
* memory (DDR).
*/
HexagonBuffer(size_t nbytes, size_t alignment, Optional<String> scope);
/* \brief Allocate 2d (discontiguous) memory within Hexagon accessible
* memory scopes.
*
* \param nallocs The number of allocations.
*
* \param nbytes The number of bytes of physical storage
* to allocate per allocation.
*
* \param alignment The byte alignment to be used when allocating.
*
* \param scope Optional storage scope indicating the memory
* space in which to allocate. Defaults to global system
* memory (DDR).
*/
HexagonBuffer(size_t nallocs, size_t nbytes, size_t alignment, Optional<String> scope);
//! \brief Destruction deallocates the underlying allocations.
~HexagonBuffer();
//! \brief Prevent copy construction of HexagonBuffers.
HexagonBuffer(const HexagonBuffer&) = delete;
//! \brief Prevent copy assignment with HexagonBuffers.
HexagonBuffer& operator=(const HexagonBuffer&) = delete;
//! \brief Prevent move construction.
HexagonBuffer(HexagonBuffer&&) = delete;
//! \brief Prevent move assignment.
HexagonBuffer& operator=(HexagonBuffer&&) = delete;
/*! \brief Return data pointer into the buffer
*
* The returned pointer is intended for use as the runtime value
* corresponding to the `Var BufferNode::data` of a buffer. The
* return type depends on the dimensionality of the buffer being
* accessed, and must be compatible with the usage defined in
* `CodeGenHexagon::CreateBufferPtr`.
*
* For a 1-d buffer, this pointer can be cast to a `T*` and accessed
* as a 1-d array (e.g. `static_cast<int32_t*>(GetPointer())[i]`).
* For a 2-d buffer, this pointer can be cast to a `T**` and
* accessed as a 2-d array
* (e.g. `static_cast<int32_t**>(GetPointer())[i][j]`).
*/
void* GetPointer();
//! \brief Memory scopes managed by a Hexagon Buffer.
enum class StorageScope {
//! \brief System DDR corresponding to global storage.
kDDR,
/*! \brief Vector tightly coupled memory corresponding to
* global.vtcm storage.
*/
kVTCM,
};
//! \brief Return storage scope of underlying allocation.
StorageScope GetStorageScope() const;
/* \brief Copy data from a Hexagon Buffer an external buffer.
*
* \param data The pointer to the external buffer.
*
* \param nbytes The number of bytes to copy.
*/
void CopyTo(void* data, size_t nbytes) const;
/* \brief Copy data from an external buffer to a Hexagon Buffer.
*
* \param data The pointer to the external buffer.
*
* \param nbytes The number of bytes to copy.
*/
void CopyFrom(void* data, size_t nbytes);
/* \brief Copy data from one Hexagon Buffer to another.
*
* \param other The other Hexagon Buffer.
*
* \param nbytes The number of bytes to copy.
*/
void CopyFrom(const HexagonBuffer& other, size_t nbytes);
private:
//! \brief Return the total number of bytes in this buffer
size_t TotalBytes() const { return nbytes_per_allocation_ * allocations_.size(); }
//! \brief Assign a storage scope to the buffer.
void SetStorageScope(Optional<String> scope);
/*! \brief Array of raw pointer allocations required by the buffer.
*
* For 1d (contiguous) storage a single allocation will result.
* For 2d (discontiguous) storage `nallocs` allocations will result.
*/
std::vector<void*> allocations_;
/*! \brief Managed allocations which follow RAII and are released
* during destruction.
*/
std::vector<std::unique_ptr<Allocation>> managed_allocations_;
/*! \brief The underlying storage type in which the allocation
* resides.
*/
size_t ndim_;
size_t nbytes_per_allocation_;
StorageScope storage_scope_;
};
/*! \brief Structure used to track/coalesce memory copies */
struct MemoryCopy {
static std::vector<MemoryCopy> MergeAdjacent(std::vector<MemoryCopy> micro_copies);
MemoryCopy(void* dest, void* src, size_t num_bytes)
: dest(dest), src(src), num_bytes(num_bytes) {}
bool IsDirectlyBefore(const MemoryCopy& other) {
void* src_end = static_cast<unsigned char*>(src) + num_bytes;
void* dest_end = static_cast<unsigned char*>(dest) + num_bytes;
return (src_end == other.src) && (dest_end == other.dest);
}
void* dest;
void* src;
size_t num_bytes;
};
/*!
*/
struct BufferSet {
// Determine all copies that do not cross boundaries in either
// source or destination region.
static std::vector<MemoryCopy> MemoryCopies(const BufferSet& dest, const BufferSet& src,
size_t bytes_to_copy);
BufferSet(void* const* buffers, size_t num_regions, size_t region_size_bytes)
: buffers(buffers), num_regions(num_regions), region_size_bytes(region_size_bytes) {}
size_t TotalBytes() const { return num_regions * region_size_bytes; }
void* const* buffers;
size_t num_regions;
size_t region_size_bytes;
};
} // namespace hexagon
} // namespace runtime
} // namespace tvm
#endif // TVM_RUNTIME_HEXAGON_HEXAGON_BUFFER_H_
| https://github.com/zk-ml/tachikoma |
src/runtime/hexagon/hexagon_buffer_manager.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#ifndef TVM_RUNTIME_HEXAGON_HEXAGON_BUFFER_MANAGER_H_
#define TVM_RUNTIME_HEXAGON_HEXAGON_BUFFER_MANAGER_H_
#include <tvm/runtime/logging.h>
#include <memory>
#include <unordered_map>
#include <utility>
#include <vector>
#include "hexagon_buffer.h"
namespace tvm {
namespace runtime {
namespace hexagon {
class HexagonBufferManager {
public:
~HexagonBufferManager() {
if (!hexagon_buffer_map_.empty()) {
DLOG(INFO) << "HexagonBufferManager is not empty upon destruction";
}
}
/*!
* \brief Free a HexagonBuffer.
* \param ptr Address of the HexagonBuffer as returned by `AllocateHexagonBuffer`.
*/
void FreeHexagonBuffer(void* ptr) {
std::lock_guard<std::mutex> lock(map_mutex_);
auto it = hexagon_buffer_map_.find(ptr);
CHECK(it != hexagon_buffer_map_.end())
<< "Attempt made to free unknown or already freed allocation";
CHECK(it->second != nullptr);
hexagon_buffer_map_.erase(it);
}
/*!
* \brief Allocate a HexagonBuffer.
* \param args Templated arguments to pass through to HexagonBuffer constructor.
*/
template <typename... Args>
void* AllocateHexagonBuffer(Args&&... args) {
auto buf = std::make_unique<HexagonBuffer>(std::forward<Args>(args)...);
void* ptr = buf->GetPointer();
{
std::lock_guard<std::mutex> lock(map_mutex_);
hexagon_buffer_map_.insert({ptr, std::move(buf)});
}
return ptr;
}
//! \brief Returns an iterator to the HexagonBuffer within the map.
HexagonBuffer* FindHexagonBuffer(void* ptr) {
std::lock_guard<std::mutex> lock(map_mutex_);
auto it = hexagon_buffer_map_.find(ptr);
if (it != hexagon_buffer_map_.end()) {
return it->second.get();
}
return nullptr;
}
private:
//! \brief Contains the HexagonBuffer objects managed by this class.
std::unordered_map<void*, std::unique_ptr<HexagonBuffer>> hexagon_buffer_map_;
//! \brief Protects updates to the map.
std::mutex map_mutex_;
};
} // namespace hexagon
} // namespace runtime
} // namespace tvm
#endif // TVM_RUNTIME_HEXAGON_HEXAGON_BUFFER_MANAGER_H_
| https://github.com/zk-ml/tachikoma |
src/runtime/hexagon/hexagon_common.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* \file hexagon_utils.h
*/
#ifndef TVM_RUNTIME_HEXAGON_HEXAGON_COMMON_H_
#define TVM_RUNTIME_HEXAGON_HEXAGON_COMMON_H_
#include <dlpack/dlpack.h>
#include <tvm/runtime/c_backend_api.h>
#include <tvm/runtime/object.h>
#include <tvm/runtime/packed_func.h>
#if defined(__hexagon__)
#include <HAP_farf.h>
#define HEXAGON_PRINT(level, ...) FARF(level, __VA_ARGS__)
#else
#include <cstdio>
#define HEXAGON_PRINT(level, ...) printf(__VA_ARGS__)
#endif
#define HEXAGON_SAFE_CALL(api_call) \
do { \
int result = api_call; \
if (result != 0) { \
HEXAGON_PRINT(ERROR, "ERROR: " #api_call " failed with error %d.", result); \
abort(); \
} \
} while (0)
inline bool IsHexagonDevice(DLDevice dev) { return dev.device_type == kDLHexagon; }
constexpr int kHexagonAllocAlignment = 2048;
#endif // TVM_RUNTIME_HEXAGON_HEXAGON_COMMON_H_
| https://github.com/zk-ml/tachikoma |
src/runtime/hexagon/hexagon_device_api.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#ifndef TVM_RUNTIME_HEXAGON_HEXAGON_DEVICE_API_H_
#define TVM_RUNTIME_HEXAGON_HEXAGON_DEVICE_API_H_
#include <tvm/runtime/device_api.h>
#include <map>
#include <memory>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>
#include "hexagon_buffer.h"
#include "hexagon_buffer_manager.h"
#include "hexagon_power_manager.h"
#include "hexagon_thread_manager.h"
#include "hexagon_user_dma.h"
#include "hexagon_vtcm_pool.h"
namespace tvm {
namespace runtime {
namespace hexagon {
/*!
* \brief Hexagon Device API that is compiled and run on Hexagon.
*/
class HexagonDeviceAPI final : public DeviceAPI {
public:
//! \brief Retrieve the global singleton instance of the HexagonDeviceAPI.
static HexagonDeviceAPI* Global();
//! \brief Constructor
HexagonDeviceAPI() {}
//! \brief Destructor
~HexagonDeviceAPI() {}
//! \brief Ensures resource managers are in a good state for the runtime
void AcquireResources() {
CHECK_EQ(runtime_power_manager, nullptr);
runtime_power_manager = std::make_unique<HexagonPowerManager>();
CHECK_EQ(runtime_vtcm, nullptr);
runtime_vtcm = std::make_unique<HexagonVtcmPool>();
CHECK_EQ(runtime_hexbuffs, nullptr);
runtime_hexbuffs = std::make_unique<HexagonBufferManager>();
CHECK_EQ(runtime_threads, nullptr);
runtime_threads =
std::make_unique<HexagonThreadManager>(threads, stack_size, pipe_size, hw_resources);
CHECK_EQ(runtime_dma, nullptr);
runtime_dma = std::make_unique<HexagonUserDMA>();
}
//! \brief Ensures all runtime resources are freed
void ReleaseResources() {
CHECK(runtime_dma) << "runtime_dma was not created in AcquireResources";
runtime_dma.reset();
CHECK(runtime_threads) << "runtime_threads was not created in AcquireResources";
runtime_threads.reset();
CHECK(runtime_hexbuffs) << "runtime_hexbuffs was not created in AcquireResources";
runtime_hexbuffs.reset();
CHECK(runtime_vtcm) << "runtime_vtcm was not created in AcquireResources";
runtime_vtcm.reset();
CHECK(runtime_power_manager) << "runtime_power_manager was not created in AcquireResources";
runtime_power_manager.reset();
}
/*! \brief Currently unimplemented interface to specify the active
* Hexagon device.
*/
void SetDevice(Device dev) final{};
//! \brief Return the queried Hexagon device attribute.
void GetAttr(Device dev, DeviceAttrKind kind, TVMRetValue* rv) final;
//! \brief Currently unimplemented interface to synchronize a device stream.
void StreamSync(Device dev, TVMStreamHandle stream) final {}
//! \note Standard memory allocation methods of the DeviceAPI interface.
//! \brief Allocate a flat allocation of global memory wrapped in a HexagonBuffer.
void* AllocDataSpace(Device dev, size_t nbytes, size_t alignment, DLDataType type_hint) final;
//! \brief Free the allocated HexagonBuffer.
void FreeDataSpace(Device dev, void* ptr) final;
/*! \brief Request a dynamically allocated HexagonBuffer from a workspace pool.
* \returns The underlying allocation pointer.
*/
void* AllocWorkspace(Device dev, size_t size, DLDataType type_hint) final;
//! Erase from HexagonBufferManager and free
void FreeWorkspace(Device dev, void* data) final;
/*!
* \brief Allocate an Nd data space on device with memory scope support.
*
* If mem_scope is undefined or is "global", treat shape as the
* tensor shape, to be flattened into an allocation of 1-d physical
* memory. This is done to maintain the semantics expected by callers of
* DeviceAPI::AllocDataSpace, in cases where it has a valid return value.
*
* For other values of mem_scope, the shape is the N-d physical
* shape of the allocation.
*
* \param dev The device to perform the operation.
* \param ndim The number of dimensions of allocated tensor.
* \param shape The shape of allocated tensor.
* \param dtype The element type.
* \param mem_scope The memory scope of the allocated tensor.
* \return The allocated HexagonBuffer pointer.
*/
void* AllocDataSpace(Device dev, int ndim, const int64_t* shape, DLDataType dtype,
Optional<String> mem_scope) final;
/*!
* \brief Allocate an Nd VTCM workspace.
* \param dev The device to perform the operation.
* \param ndim The number of dimensions of allocated tensor.
* \param shape The shape of allocated tensor.
* \param dtype The element type.
* \return The allocated HexagonBuffer pointer.
*/
void* AllocVtcmWorkspace(Device dev, int ndim, const int64_t* shape, DLDataType dtype,
Optional<String> mem_scope);
//! \brief Free the allocated Nd VTCM workspace.
void FreeVtcmWorkspace(Device dev, void* ptr);
/*!
* \brief Copy data from one storage to another.
* \note This API is designed to support special memory with shape dependent layout.
* DLTensor's are passed with shape information to support these cases.
* \param from The source array.
* \param to The target array.
* \param stream Optional stream object.
*/
void CopyDataFromTo(DLTensor* from, DLTensor* to, TVMStreamHandle stream) final;
HexagonThreadManager* ThreadManager() {
CHECK(runtime_threads) << "runtime_threads has not been created";
return runtime_threads.get();
}
HexagonUserDMA* UserDMA() {
CHECK(runtime_dma) << "runtime_dma has not been created";
return runtime_dma.get();
}
HexagonVtcmPool* VtcmPool() {
CHECK(runtime_vtcm) << "runtime_vtcm has not been created";
return runtime_vtcm.get();
}
protected:
//! Standard Device API interface to copy data from one storage to another.
void CopyDataFromTo(const void* from, size_t from_offset, void* to, size_t to_offset, size_t size,
Device dev_from, Device dev_to, DLDataType type_hint,
TVMStreamHandle stream) final;
private:
/*! \brief Helper to check if the device type is valid for the Hexagon Device API
* \return Boolean indicating whether the device type is valid
*/
bool IsValidDevice(DLDevice dev) {
// Added kDLCPU since we use hexagon as a sub-target of LLVM which by default maps to kDLCPU
return (dev.device_type == kDLHexagon) || (dev.device_type == kDLCPU);
}
//! \brief Manages runtime HexagonBuffer allocations
// runtime_hexbuffs is used for runtime allocations. It is created with a call to
// AcquireResources, and destroyed on ReleaseResources. The buffers in this manager are scoped
// to the lifetime of a user application session.
std::unique_ptr<HexagonBufferManager> runtime_hexbuffs;
//! \brief Thread manager
std::unique_ptr<HexagonThreadManager> runtime_threads;
const unsigned threads{6};
const unsigned pipe_size{1000};
const unsigned stack_size{0x4000}; // 16KB
const std::vector<HardwareResourceType> hw_resources{DMA_0, HTP_0, HVX_0, HVX_1, HVX_2, HVX_3};
//! \brief User DMA manager
std::unique_ptr<HexagonUserDMA> runtime_dma;
//! \brief VTCM memory manager
std::unique_ptr<HexagonVtcmPool> runtime_vtcm;
//! \brief Hexagon power manager
std::unique_ptr<HexagonPowerManager> runtime_power_manager;
};
} // namespace hexagon
} // namespace runtime
} // namespace tvm
#endif // TVM_RUNTIME_HEXAGON_HEXAGON_DEVICE_API_H_
| https://github.com/zk-ml/tachikoma |
src/runtime/hexagon/hexagon_htp.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#ifndef TVM_RUNTIME_HEXAGON_HEXAGON_HTP_H_
#define TVM_RUNTIME_HEXAGON_HEXAGON_HTP_H_
namespace tvm {
namespace runtime {
namespace hexagon {
class HexagonHtp {
public:
//! \brief Constructor.
HexagonHtp();
//! \brief Destructor.
~HexagonHtp();
//! \brief Prevent copy construction of HexagonHtp.
HexagonHtp(const HexagonHtp&) = delete;
//! \brief Prevent copy assignment with HexagonHtp.
HexagonHtp& operator=(const HexagonHtp&) = delete;
//! \brief Prevent move construction.
HexagonHtp(HexagonHtp&&) = delete;
//! \brief Prevent move assignment.
HexagonHtp& operator=(HexagonHtp&&) = delete;
void Lock();
void Unlock();
private:
//! \brief Acquisition context ID
unsigned int context_id_;
void Acquire();
void Release();
};
} // namespace hexagon
} // namespace runtime
} // namespace tvm
#endif // TVM_RUNTIME_HEXAGON_HEXAGON_HTP_H_
| https://github.com/zk-ml/tachikoma |
src/runtime/hexagon/hexagon_hvx.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#ifndef TVM_RUNTIME_HEXAGON_HEXAGON_HVX_H_
#define TVM_RUNTIME_HEXAGON_HEXAGON_HVX_H_
namespace tvm {
namespace runtime {
namespace hexagon {
class HexagonHvx {
public:
//! \brief Constructor.
// TODO(HWE): Pass in a parameter for which HVX instance to bind
HexagonHvx();
//! \brief Destructor.
~HexagonHvx();
//! \brief Prevent copy construction of HexagonHvx.
HexagonHvx(const HexagonHvx&) = delete;
//! \brief Prevent copy assignment with HexagonHvx.
HexagonHvx& operator=(const HexagonHvx&) = delete;
//! \brief Prevent move construction.
HexagonHvx(HexagonHvx&&) = delete;
//! \brief Prevent move assignment.
HexagonHvx& operator=(HexagonHvx&&) = delete;
//! \brief Lock one HVX to the calling thread.
void Lock();
//! \brief Unlock the HVX for the calling thread.
void Unlock();
//! \brief Number of HVX units reserved.
int ReservedCount() { return reserved_count_; }
private:
int reserved_count_;
void Acquire();
void Release();
};
} // namespace hexagon
} // namespace runtime
} // namespace tvm
#endif // TVM_RUNTIME_HEXAGON_HEXAGON_HVX_H_
| https://github.com/zk-ml/tachikoma |
src/runtime/hexagon/hexagon_module.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#ifndef TVM_RUNTIME_HEXAGON_HEXAGON_MODULE_H_
#define TVM_RUNTIME_HEXAGON_HEXAGON_MODULE_H_
#include <tvm/runtime/logging.h>
#include <tvm/runtime/module.h>
#include <array>
#include <memory>
#include <set>
#include <string>
#include <unordered_map>
#include "../meta_data.h"
namespace tvm {
namespace runtime {
/*!
* \brief Create a Hexagon module from data.
* \param data The module data.
* \param fmt The format of the data, can be "obj".
* \param fmap The function information map of each function.
* \param asm_str String with the generated assembly source.
* \param obj_str String with the object file data.
* \param ir_str String with the disassembled LLVM IR source.
* \param bc_str String with the bitcode LLVM IR.
*/
Module HexagonModuleCreate(std::string data, std::string fmt,
std::unordered_map<std::string, FunctionInfo> fmap, std::string asm_str,
std::string obj_str, std::string ir_str, std::string bc_str);
/*!
\brief Module implementation for compiled Hexagon binaries. It is suitable
for managing cross-compiled Hexagon code on a host machine.
See docstring for HexagonModuleCreate for
construction parameter details.
*/
class HexagonModuleNode : public runtime::ModuleNode {
public:
HexagonModuleNode(std::string data, std::string fmt,
std::unordered_map<std::string, FunctionInfo> fmap, std::string asm_str,
std::string obj_str, std::string ir_str, std::string bc_str);
PackedFunc GetFunction(const std::string& name, const ObjectPtr<Object>& sptr_to_self) override;
std::string GetSource(const std::string& format) override;
const char* type_key() const final { return "hexagon"; }
void SaveToFile(const std::string& file_name, const std::string& format) override;
void SaveToBinary(dmlc::Stream* stream) override;
protected:
std::string data_;
std::string fmt_;
std::unordered_map<std::string, FunctionInfo> fmap_;
std::string asm_;
std::string obj_;
std::string ir_;
std::string bc_;
};
} // namespace runtime
} // namespace tvm
#endif // TVM_RUNTIME_HEXAGON_HEXAGON_MODULE_H_
| https://github.com/zk-ml/tachikoma |
src/runtime/hexagon/hexagon_power_manager.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#ifndef TVM_RUNTIME_HEXAGON_HEXAGON_POWER_MANAGER_H_
#define TVM_RUNTIME_HEXAGON_HEXAGON_POWER_MANAGER_H_
namespace tvm {
namespace runtime {
namespace hexagon {
class HexagonPowerManager {
public:
//! \brief Constructor.
HexagonPowerManager();
//! \brief Destructor.
~HexagonPowerManager();
//! \brief Prevent copy construction of HexagonPowerManager.
HexagonPowerManager(const HexagonPowerManager&) = delete;
//! \brief Prevent copy assignment with HexagonPowerManager.
HexagonPowerManager& operator=(const HexagonPowerManager&) = delete;
//! \brief Prevent move construction.
HexagonPowerManager(HexagonPowerManager&&) = delete;
//! \brief Prevent move assignment.
HexagonPowerManager& operator=(HexagonPowerManager&&) = delete;
private:
//! \brief Power context
void* hap_pwr_ctx_;
void PowerOnHVX();
void PowerOffHVX();
void PowerOnHTP();
void PowerOffHTP();
void SetAppType();
void SetDCVS();
};
} // namespace hexagon
} // namespace runtime
} // namespace tvm
#endif // TVM_RUNTIME_HEXAGON_HEXAGON_POWER_MANAGER_H_
| https://github.com/zk-ml/tachikoma |
src/runtime/hexagon/hexagon_thread_manager.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#ifndef TVM_RUNTIME_HEXAGON_HEXAGON_THREAD_MANAGER_H_
#define TVM_RUNTIME_HEXAGON_HEXAGON_THREAD_MANAGER_H_
#include <tvm/runtime/c_runtime_api.h>
#include <tvm/runtime/logging.h>
#include <tvm/runtime/packed_func.h>
#include <memory>
#include <unordered_map>
#include <utility>
#include <vector>
#include "hexagon_buffer.h"
#include "hexagon_buffer_manager.h"
#include "hexagon_common.h"
#include "hexagon_htp.h"
#include "hexagon_hvx.h"
#include "qurt.h"
namespace tvm {
namespace runtime {
namespace hexagon {
typedef enum {
NONE = -1,
DMA_0 = 0,
HTP_0,
HVX_0,
HVX_1,
HVX_2,
HVX_3,
MAX,
} HardwareResourceType;
class HexagonThreadManager {
//! \brief Void function.
using voidfunc = void (*)(void*);
//! \brief Semaphore ID.
using SyncPoint = unsigned;
//! \brief Alignment of underlying memory allocations.
const unsigned MEM_ALIGNMENT = 32;
//! \brief Minimum stack size in bytes per thread.
const unsigned MIN_STACK_SIZE_BYTES = 0x400; // 1KB
//! \brief Maximum stack size in bytes per thread.
const unsigned MAX_STACK_SIZE_BYTES = 0x10000; // 64KB
//! \brief Minimum pipe (or command buffer) size in words (or commands) per thread.
const unsigned MIN_PIPE_SIZE_WORDS = 10;
//! \brief Maximum pipe (or command buffer) size in words (or commands) per thread.
const unsigned MAX_PIPE_SIZE_WORDS = 0x10000; // 64K words
public:
/*!
* \brief Spawn a number of Hexagon threads with a given stack (in bytes) and pipe (a.k.a. command
* buffer; in words or commands) within the min and max values specified above.
* \param num_threads Number of threads to spawn.
* \param thread_stack_size_bytes Stack size in bytes per thread.
* \param thread_pipe_size_words Pipe (or command buffer) size in words (or commands).
*/
HexagonThreadManager(unsigned, unsigned thread_stack_size_bytes, unsigned thread_pipe_size_words,
const std::vector<HardwareResourceType> = {});
//! \brief Destructor
~HexagonThreadManager();
/*!
* \brief Get the spawned threads as stream handles.
* \returns Vector of stream handles.
*/
const std::vector<TVMStreamHandle> GetStreamHandles();
/*!
* \brief Get the spawned threads as stream handles for a resource type.
* \returns stream handle.
*/
TVMStreamHandle GetStreamHandleByResourceType(HardwareResourceType type);
/*!
* \brief Get the resource type for a stream handle
* \returns stream handle.
*/
HardwareResourceType GetResourceTypeForStreamHandle(TVMStreamHandle thread);
/*!
* \brief Non-blocking dispatch of a void function and args on a given thread.
* \param thread Stream handle of the thread on which to dispatch the void function.
* \param f Void function to be dispatched.
* \param args Arguments to pass to the void function.
* \returns Boolean value indicating success or failure of the dispatch; user must either 1)
* `Start` threads executing to clear space in the pipe before retrying dispatch or 2) create a
* `HexagonThreadManager` with a larger pipe.
*/
bool Dispatch(TVMStreamHandle thread, voidfunc f, void* args);
/*!
* \brief Non-blocking signal of a semaphore with a given ID.
* \param thread Stream handle of the thread which will signal the semaphore.
* \param syncID ID of the semaphore to be signaled.
* \returns Boolean value indicating success or failure of the dispatch of the signal; user must
* either 1) `Start` threads executing to clear space in the pipe before retrying dispatch or 2)
* create a `HexagonThreadManager` with a larger pipe.
*/
bool Signal(TVMStreamHandle thread, SyncPoint syncID);
/*!
* \brief Non-blocking wait on a semaphore with a given ID.
* \param thread Stream handle of the thread which will wait on the semaphore.
* \param syncID ID of the semaphore on which to wait.
* \returns Boolean value indicating success or failure of the dispatch of the wait; user must
* either 1) `Start` threads executing to clear space in the pipe before retrying dispatch or 2)
* create a `HexagonThreadManager` with a larger pipe.
*/
bool Wait(TVMStreamHandle thread, SyncPoint syncID);
/*!
* \brief Creates a synchronization point between two threads by creating a semaphore,
*dispatching the `signal_thread` to signal that semaphore and dispatching the `wait_thread to
*wait on that semaphore.
* \param signal_thread Stream handle for the thread which will signal the
*semaphore.
* \param wait_thread Stream handle for the thread which will wait on the semaphore.
* \returns Boolean value indicating success or failure of the combined dispatch of both the
*signal and the wait; user must either 1) `Start` threads executing to clear space in the pipe
*before retrying dispatch or 2) create a `HexagonThreadManager` with a larger pipe.
*/
bool SyncFromTo(TVMStreamHandle signal_thread, TVMStreamHandle wait_thread);
//! \brief Unblock threads to start execution.
void Start();
//! \brief Unblock threads to start execution if `Start` has not already been called; blocking
//! call to wait until all threads have empty pipes.
void WaitOnThreads();
private:
struct ThreadContext {
qurt_pipe_t* pipe;
unsigned index;
HardwareResourceType resource_type;
HexagonHvx* hvx;
HexagonHtp* htp;
uint64_t status;
ThreadContext(qurt_pipe_t* pipe, unsigned index, HardwareResourceType resource_type,
HexagonHvx* hvx, HexagonHtp* htp)
: pipe(pipe), index(index), resource_type(resource_type), hvx(hvx), htp(htp), status(0) {
CHECK(resource_type == NONE || (hvx && htp))
<< "Missing resource manager pointer, type: " << resource_type << " hvx: " << hvx
<< " htp: " << htp;
}
};
//! \brief Helper function to ensure the set of requested resources is valid.
void CheckResources();
//! \brief Helper function for the constructor to spawn threads.
void SpawnThreads(unsigned thread_stack_size_bytes, unsigned thread_pipe_size_words);
//! \brief Helper function for `Signal` and `Wait` to create, initialize and map semaphores by ID.
void CheckSemaphore(unsigned syncID);
//! \brief Void function executed by a thread to signal a semaphore.
static void thread_signal(void* semaphore);
//! \brief Void function executed by a thread to wait on a semaphore; used by `Wait`.
static void thread_wait(void* semaphore);
//! \brief Void function executed by a thread to wait on and free a semaphore; used by
//! `SyncFromTo`.
static void thread_wait_free(void* semaphore);
//! \brief Void function executed by a thread to exit at time of destruction.
static void thread_exit(void* context);
//! \brief Void function executed by each thread as `main`.
static void thread_main(void* context);
//! \brief Manages underlying HexagonBuffer allocations.
HexagonBufferManager hexbuffs_;
//! \brief Number of threads allocatted.
unsigned nthreads_{0};
//! \brief Pointer to the base of the stacks allocated for all threads; size = `nthreads` *
//! `thread_stack_size_bytes`.
void* stack_buffer_{nullptr};
//! \brief Pointer to the base of the pipes (or command buffers) allocated for all threads; size =
//! `nthreads` * `thread_pipe_size_words` * sizeof(word).
void* pipe_buffer_{nullptr};
//! \brief QURT thread structure for each spawned thread.
std::vector<qurt_thread_t> threads_;
//! \brief QURT pipe (or command buffer) structure for each spawned thread.
std::vector<qurt_pipe_t> pipes_;
//! \brief Thread context passed into each `thread_main` function.
std::vector<ThreadContext*> contexts_;
//! \brief Semaphores used by `Signal` and `Wait` mapped by ID.
std::unordered_map<unsigned, qurt_sem_t*> semaphores_;
//! \brief Start semaphore created at time of construction; signled by `Start`.
qurt_sem_t start_semaphore_;
/*!
*\brief Encapsulate a void function pointer + arg pointer; sent via pipe to threads to execute.
*/
struct Command {
voidfunc f;
void* args;
Command(voidfunc f, void* args) : f(f), args(args) {}
};
//! \brief List of hardware resources
std::vector<HardwareResourceType> hw_resources_;
//! \brief Whether or not resource managers should be created
bool create_resource_managers_{false};
//! \brief HTP hardware resource.
// TODO(HWE): Move binding of HTP to a specific thread
std::unique_ptr<HexagonHtp> htp_;
//! \brief HVX hardware resource.
// TODO(HWE): Move binding of individual HVX instances to a specific thread
std::unique_ptr<HexagonHvx> hvx_;
};
} // namespace hexagon
} // namespace runtime
} // namespace tvm
#endif // TVM_RUNTIME_HEXAGON_HEXAGON_THREAD_MANAGER_H_
| https://github.com/zk-ml/tachikoma |
src/runtime/hexagon/hexagon_user_dma.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#ifndef TVM_RUNTIME_HEXAGON_HEXAGON_USER_DMA_H_
#define TVM_RUNTIME_HEXAGON_HEXAGON_USER_DMA_H_
#include "hexagon_common.h"
#include "hexagon_user_dma_descriptors.h"
#include "hexagon_user_dma_instructions.h"
#include "hexagon_user_dma_registers.h"
#include "ring_buffer.h"
namespace tvm {
namespace runtime {
namespace hexagon {
#define DMA_SUCCESS 0
#define DMA_FAILURE -1
#define DMA_RETRY 1
#define MAX_DMA_DESCRIPTORS 100
#define SYNC_DMA_QUEUE -1
class HexagonUserDMA {
public:
HexagonUserDMA();
~HexagonUserDMA();
HexagonUserDMA(const HexagonUserDMA&) = delete;
HexagonUserDMA& operator=(const HexagonUserDMA&) = delete;
HexagonUserDMA(HexagonUserDMA&&) = delete;
HexagonUserDMA& operator=(HexagonUserDMA&&) = delete;
/*!
* \brief Initiate DMA to copy memory from source to destination address
* \param dst Destination address
* \param src Source address
* \param length Length in bytes to copy
* \returns Status: DMA_SUCCESS or DMA_FAILURE
*/
int Copy(int queue_id, void* dst, void* src, uint32_t length);
/*!
* \brief Wait until the number of DMAs in flight is less than or equal to some maximum
* \param max_dmas_in_flight Maximum number of DMAs allowed to be in flight
* to satisfy the `Wait` e.g. use `Wait(0)` to wait on "all" outstanding DMAs to complete
*/
void Wait(int queue_id, uint32_t max_dmas_in_flight);
/*!
* \brief Poll the number of DMAs in flight
* \returns Number of DMAs in flight
*/
uint32_t Poll(int queue_id);
private:
//! \brief Initializes the Hexagon User DMA engine
unsigned int Init();
//! \brief Calculates and returns the number of DMAs in flight
uint32_t DMAsInFlight(int queue_id);
//! \brief Tracks whether the very first DMA has been executed
bool first_dma_ = true;
//! \brief Tracks the tail DMA descriptor
void* tail_dma_desc_ = nullptr;
//! \brief Storage for all DMA descriptors
QueuedRingBuffer<dma_desc_2d_t>* descriptors_ = nullptr;
};
} // namespace hexagon
} // namespace runtime
} // namespace tvm
#endif // TVM_RUNTIME_HEXAGON_HEXAGON_USER_DMA_H_
| https://github.com/zk-ml/tachikoma |
src/runtime/hexagon/hexagon_user_dma_descriptors.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#ifndef TVM_RUNTIME_HEXAGON_HEXAGON_USER_DMA_DESCRIPTORS_H_
#define TVM_RUNTIME_HEXAGON_HEXAGON_USER_DMA_DESCRIPTORS_H_
namespace tvm {
namespace runtime {
namespace hexagon {
// NOTE: Using 2D descriptor size even for 1D descriptors
#define DMA_DESC_2D_SIZE 32
// DMA State
// desc[0][3:0]
#define DESC_STATE_MASK 0x0000000F
#define DESC_STATE_SHIFT 0
#define DESC_STATE_READY 0
// desc[0][31:4]
// Descriptors addresses must be (minimum) 16 byte aligned
// -> Lower 4 bits masked to clear DMA Status
// -> But, descriptor address is not shifted
#define DESC_NEXT_MASK 0xFFFFFFF0
#define DESC_NEXT_SHIFT 0
// desc[1][23:0]
#define DESC_LENGTH_MASK 0x00FFFFFF
#define DESC_LENGTH_SHIFT 0
// desc[1][25:24]
#define DESC_DESCTYPE_MASK 0x03000000
#define DESC_DESCTYPE_SHIFT 24
#define DESC_DESCTYPE_1D 0
#define DESC_DESCTYPE_2D 1
// TODO(Straw): Definition? Not in the spec.
// desc[1][26]
#define DESC_DSTCOMP_MASK 0x04000000
#define DESC_DSTCOMP_SHIFT 26
// desc[1][27]
#define DESC_SRCCOMP_MASK 0x08000000
#define DESC_SRCCOMP_SHIFT 27
#define DESC_COMP_NONE 0
#define DESC_COMP_DLBC 1
// desc[1][28]
#define DESC_BYPASSDST_MASK 0x10000000
#define DESC_BYPASSDST_SHIFT 28
// desc[1][29]
#define DESC_BYPASSSRC_MASK 0x20000000
#define DESC_BYPASSSRC_SHIFT 29
#define DESC_BYPASS_OFF 0
#define DESC_BYPASS_ON 1
// desc[1][30]
#define DESC_ORDER_MASK 0x40000000
#define DESC_ORDER_SHIFT 30
#define DESC_ORDER_NOORDER 0
#define DESC_ORDER_ORDER 1
// desc[1][31]
#define DESC_DONE_MASK 0x80000000
#define DESC_DONE_SHIFT 31
#define DESC_DONE_INCOMPLETE 0
#define DESC_DONE_COMPLETE 1
// desc[2]
#define DESC_SRC_MASK 0xFFFFFFFF
#define DESC_SRC_SHIFT 0
// desc[3]
#define DESC_DST_MASK 0xFFFFFFFF
#define DESC_DST_SHIFT 0
// desc[4][25:24]
#define DESC_CACHEALLOC_MASK 0x03000000
#define DESC_CACHEALLOC_SHIFT 24
#define DESC_CACHEALLOC_NONE 0
#define DESC_CACHEALLOC_WRITEONLY 1
#define DESC_CACHEALLOC_READONLY 2
#define DESC_CACHEALLOC_READWRITE 3
// TODO(Straw): Definition? Not in the spec.
// desc[4][31:28]
#define DESC_PADDING_MASK 0xF0000000
#define DESC_PADDING_SHIFT 28
// desc[5][15:0]
#define DESC_ROIWIDTH_MASK 0x0000FFFF
#define DESC_ROIWIDTH_SHIFT 0
// desc[5][31:16]
#define DESC_ROIHEIGHT_MASK 0xFFFF0000
#define DESC_ROIHEIGHT_SHIFT 16
// desc[6][15:0]
#define DESC_SRCSTRIDE_MASK 0x0000FFFF
#define DESC_SRCSTRIDE_SHIFT 0
// desc[6][31:16]
#define DESC_DSTSTRIDE_MASK 0xFFFF0000
#define DESC_DSTSTRIDE_SHIFT 16
// desc[7][15:0]
#define DESC_SRCWIDTHOFFSET_MASK 0x0000FFFF
#define DESC_SRCWIDTHOFFSET_SHIFT 0
// desc[7][31:16]
#define DESC_DSTWIDTHOFFSET_MASK 0xFFFF0000
#define DESC_DSTWIDTHOFFSET_SHIFT 16
#define DMA_NULL_PTR 0
/**************************/
/* 1D (linear) descriptor */
/**************************/
struct dma_desc_1d_t {
unsigned int next_state;
unsigned int done_order_bypass_comp_desctype_length;
unsigned int src;
unsigned int dst;
};
/***********************/
/* 2D (box) descriptor */
/***********************/
struct dma_desc_2d_t {
unsigned int next_state;
unsigned int done_order_bypass_comp_desctype_length;
unsigned int src;
unsigned int dst;
unsigned int allocation_padding;
unsigned int roiheight_roiwidth;
unsigned int dststride_srcstride;
unsigned int dstwidthoffset_srcwidthoffset;
};
// desc[0][3:0]
inline void dma_desc_set_state(void* dma_desc_ptr, unsigned int v) {
dma_desc_1d_t* dma_desc_1d_ptr = reinterpret_cast<dma_desc_1d_t*>(dma_desc_ptr);
(dma_desc_1d_ptr->next_state) &= ~DESC_STATE_MASK;
(dma_desc_1d_ptr->next_state) |= ((v << DESC_STATE_SHIFT) & DESC_STATE_MASK);
}
// desc[0][31:4]
inline void dma_desc_set_next(void* dma_desc_ptr, unsigned int v) {
dma_desc_1d_t* dma_desc_1d_ptr = reinterpret_cast<dma_desc_1d_t*>(dma_desc_ptr);
(dma_desc_1d_ptr->next_state) &= ~DESC_NEXT_MASK;
(dma_desc_1d_ptr->next_state) |= ((v << DESC_NEXT_SHIFT) & DESC_NEXT_MASK);
}
// desc[1][23:0]
inline void dma_desc_set_length(void* dma_desc_ptr, unsigned int v) {
dma_desc_1d_t* dma_desc_1d_ptr = reinterpret_cast<dma_desc_1d_t*>(dma_desc_ptr);
(dma_desc_1d_ptr->done_order_bypass_comp_desctype_length) &= ~DESC_LENGTH_MASK;
(dma_desc_1d_ptr->done_order_bypass_comp_desctype_length) |=
((v << DESC_LENGTH_SHIFT) & DESC_LENGTH_MASK);
}
// desc[1][25:24]
inline void dma_desc_set_desctype(void* dma_desc_ptr, unsigned int v) {
dma_desc_1d_t* dma_desc_1d_ptr = reinterpret_cast<dma_desc_1d_t*>(dma_desc_ptr);
(dma_desc_1d_ptr->done_order_bypass_comp_desctype_length) &= ~DESC_DESCTYPE_MASK;
(dma_desc_1d_ptr->done_order_bypass_comp_desctype_length) |=
((v << DESC_DESCTYPE_SHIFT) & DESC_DESCTYPE_MASK);
}
// TODO(Straw): Definition? Not in the spec.
// desc[1][26]
inline void dma_desc_set_dstcomp(void* dma_desc_ptr, unsigned int v) {
dma_desc_1d_t* dma_desc_1d_ptr = reinterpret_cast<dma_desc_1d_t*>(dma_desc_ptr);
(dma_desc_1d_ptr->done_order_bypass_comp_desctype_length) &= ~DESC_DSTCOMP_MASK;
(dma_desc_1d_ptr->done_order_bypass_comp_desctype_length) |=
((v << DESC_DSTCOMP_SHIFT) & DESC_DSTCOMP_MASK);
}
// TODO(Straw): Definition? Not in the spec.
// desc[1][27]
inline void dma_desc_set_srccomp(void* dma_desc_ptr, unsigned int v) {
dma_desc_1d_t* dma_desc_1d_ptr = reinterpret_cast<dma_desc_1d_t*>(dma_desc_ptr);
(dma_desc_1d_ptr->done_order_bypass_comp_desctype_length) &= ~DESC_SRCCOMP_MASK;
(dma_desc_1d_ptr->done_order_bypass_comp_desctype_length) |=
((v << DESC_SRCCOMP_SHIFT) & DESC_SRCCOMP_MASK);
}
// desc[1][28]
inline void dma_desc_set_bypassdst(void* dma_desc_ptr, unsigned int v) {
dma_desc_1d_t* dma_desc_1d_ptr = reinterpret_cast<dma_desc_1d_t*>(dma_desc_ptr);
(dma_desc_1d_ptr->done_order_bypass_comp_desctype_length) &= ~DESC_BYPASSDST_MASK;
(dma_desc_1d_ptr->done_order_bypass_comp_desctype_length) |=
((v << DESC_BYPASSDST_SHIFT) & DESC_BYPASSDST_MASK);
}
// desc[1][29]
inline void dma_desc_set_bypasssrc(void* dma_desc_ptr, unsigned int v) {
dma_desc_1d_t* dma_desc_1d_ptr = reinterpret_cast<dma_desc_1d_t*>(dma_desc_ptr);
(dma_desc_1d_ptr->done_order_bypass_comp_desctype_length) &= ~DESC_BYPASSSRC_MASK;
(dma_desc_1d_ptr->done_order_bypass_comp_desctype_length) |=
((v << DESC_BYPASSSRC_SHIFT) & DESC_BYPASSSRC_MASK);
}
// desc[1][30]
inline void dma_desc_set_order(void* dma_desc_ptr, unsigned int v) {
dma_desc_1d_t* dma_desc_1d_ptr = reinterpret_cast<dma_desc_1d_t*>(dma_desc_ptr);
(dma_desc_1d_ptr->done_order_bypass_comp_desctype_length) &= ~DESC_ORDER_MASK;
(dma_desc_1d_ptr->done_order_bypass_comp_desctype_length) |=
((v << DESC_ORDER_SHIFT) & DESC_ORDER_MASK);
}
// desc[1][31]
inline void dma_desc_set_done(void* dma_desc_ptr, unsigned int v) {
dma_desc_1d_t* dma_desc_1d_ptr = reinterpret_cast<dma_desc_1d_t*>(dma_desc_ptr);
(dma_desc_1d_ptr->done_order_bypass_comp_desctype_length) &= ~DESC_DONE_MASK;
(dma_desc_1d_ptr->done_order_bypass_comp_desctype_length) |=
((v << DESC_DONE_SHIFT) & DESC_DONE_MASK);
}
// desc[1][31]
inline unsigned int dma_desc_get_done(void* dma_desc_ptr) {
dma_desc_1d_t* dma_desc_1d_ptr = reinterpret_cast<dma_desc_1d_t*>(dma_desc_ptr);
return (((dma_desc_1d_ptr->done_order_bypass_comp_desctype_length) & DESC_DONE_MASK) >>
DESC_DONE_SHIFT);
}
// desc[2]
inline void dma_desc_set_src(void* dma_desc_ptr, unsigned int v) {
dma_desc_1d_t* dma_desc_1d_ptr = reinterpret_cast<dma_desc_1d_t*>(dma_desc_ptr);
(dma_desc_1d_ptr->src) &= ~DESC_SRC_MASK;
(dma_desc_1d_ptr->src) |= ((v << DESC_SRC_SHIFT) & DESC_SRC_MASK);
}
// desc[3]
inline void dma_desc_set_dst(void* dma_desc_ptr, unsigned int v) {
dma_desc_1d_t* dma_desc_1d_ptr = reinterpret_cast<dma_desc_1d_t*>(dma_desc_ptr);
(dma_desc_1d_ptr->dst) &= ~DESC_DST_MASK;
(dma_desc_1d_ptr->dst) |= ((v << DESC_DST_SHIFT) & DESC_DST_MASK);
}
// desc[4][25:24]
inline void dma_desc_set_cachealloc(void* dma_desc_ptr, unsigned int v) {
dma_desc_2d_t* dma_desc_2d_ptr = reinterpret_cast<dma_desc_2d_t*>(dma_desc_ptr);
(dma_desc_2d_ptr->allocation_padding) &= ~DESC_CACHEALLOC_MASK;
(dma_desc_2d_ptr->allocation_padding) |= ((v << DESC_CACHEALLOC_SHIFT) & DESC_CACHEALLOC_MASK);
}
// TODO(Straw): Definition? Not in the spec.
// desc[4][31:28]
inline void dma_desc_set_padding(void* dma_desc_ptr, unsigned int v) {
dma_desc_2d_t* dma_desc_2d_ptr = reinterpret_cast<dma_desc_2d_t*>(dma_desc_ptr);
(dma_desc_2d_ptr->allocation_padding) &= ~DESC_PADDING_MASK;
(dma_desc_2d_ptr->allocation_padding) |= ((v << DESC_PADDING_SHIFT) & DESC_PADDING_MASK);
}
// desc[5][15:0]
inline void dma_desc_set_roiwidth(void* dma_desc_ptr, unsigned int v) {
dma_desc_2d_t* dma_desc_2d_ptr = reinterpret_cast<dma_desc_2d_t*>(dma_desc_ptr);
(dma_desc_2d_ptr->roiheight_roiwidth) &= ~DESC_ROIWIDTH_MASK;
(dma_desc_2d_ptr->roiheight_roiwidth) |= ((v << DESC_ROIWIDTH_SHIFT) & DESC_ROIWIDTH_MASK);
}
// desc[5][31:16]
inline void dma_desc_set_roiheight(void* dma_desc_ptr, unsigned int v) {
dma_desc_2d_t* dma_desc_2d_ptr = reinterpret_cast<dma_desc_2d_t*>(dma_desc_ptr);
(dma_desc_2d_ptr->roiheight_roiwidth) &= ~DESC_ROIHEIGHT_MASK;
(dma_desc_2d_ptr->roiheight_roiwidth) |= ((v << DESC_ROIHEIGHT_SHIFT) & DESC_ROIHEIGHT_MASK);
}
// desc[6][15:0]
inline void dma_desc_set_srcstride(void* dma_desc_ptr, unsigned int v) {
dma_desc_2d_t* dma_desc_2d_ptr = reinterpret_cast<dma_desc_2d_t*>(dma_desc_ptr);
(dma_desc_2d_ptr->dststride_srcstride) &= ~DESC_SRCSTRIDE_MASK;
(dma_desc_2d_ptr->dststride_srcstride) |= ((v << DESC_SRCSTRIDE_SHIFT) & DESC_SRCSTRIDE_MASK);
}
// desc[6][31:16]
inline void dma_desc_set_dststride(void* dma_desc_ptr, unsigned int v) {
dma_desc_2d_t* dma_desc_2d_ptr = reinterpret_cast<dma_desc_2d_t*>(dma_desc_ptr);
(dma_desc_2d_ptr->dststride_srcstride) &= ~DESC_DSTSTRIDE_MASK;
(dma_desc_2d_ptr->dststride_srcstride) |= ((v << DESC_DSTSTRIDE_SHIFT) & DESC_DSTSTRIDE_MASK);
}
// desc[7][15:0]
inline void dma_desc_set_srcwidthoffset(void* dma_desc_ptr, unsigned int v) {
dma_desc_2d_t* dma_desc_2d_ptr = reinterpret_cast<dma_desc_2d_t*>(dma_desc_ptr);
(dma_desc_2d_ptr->dstwidthoffset_srcwidthoffset) &= ~DESC_SRCWIDTHOFFSET_MASK;
(dma_desc_2d_ptr->dstwidthoffset_srcwidthoffset) |=
((v << DESC_SRCWIDTHOFFSET_SHIFT) & DESC_SRCWIDTHOFFSET_MASK);
}
// desc[7][31:16]
inline void dma_desc_set_dstwidthoffset(void* dma_desc_ptr, unsigned int v) {
dma_desc_2d_t* dma_desc_2d_ptr = reinterpret_cast<dma_desc_2d_t*>(dma_desc_ptr);
(dma_desc_2d_ptr->dstwidthoffset_srcwidthoffset) &= ~DESC_DSTWIDTHOFFSET_MASK;
(dma_desc_2d_ptr->dstwidthoffset_srcwidthoffset) |=
((v << DESC_DSTWIDTHOFFSET_SHIFT) & DESC_DSTWIDTHOFFSET_MASK);
}
} // namespace hexagon
} // namespace runtime
} // namespace tvm
#endif // TVM_RUNTIME_HEXAGON_HEXAGON_USER_DMA_DESCRIPTORS_H_
| https://github.com/zk-ml/tachikoma |
src/runtime/hexagon/hexagon_user_dma_instructions.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#ifndef TVM_RUNTIME_HEXAGON_HEXAGON_USER_DMA_INSTRUCTIONS_H_
#define TVM_RUNTIME_HEXAGON_HEXAGON_USER_DMA_INSTRUCTIONS_H_
namespace tvm {
namespace runtime {
namespace hexagon {
inline unsigned int dmpause() {
unsigned int dm0 = 0;
asm volatile(" %0 = dmpause" : "=r"(dm0));
return dm0;
}
inline void dmstart(void* next) { asm volatile(" dmstart(%0)" : : "r"(next)); }
inline void dmlink(void* tail, void* next) {
asm volatile(" dmlink(%0, %1)" : : "r"(tail), "r"(next));
}
inline unsigned int dmpoll() {
unsigned int dm0 = 0;
asm volatile(" %0 = dmpoll" : "=r"(dm0));
return dm0;
}
inline unsigned int dmwait() {
unsigned int dm0 = 0;
asm volatile(" %0 = dmwait" : "=r"(dm0));
return dm0;
}
inline void dmresume(unsigned int dm0) { asm volatile(" dmresume(%0)" : : "r"(dm0)); }
inline unsigned int dmsyncht() {
unsigned int dm0 = 0;
asm volatile(" %0 = dmsyncht" : "=r"(dm0));
return dm0;
}
inline unsigned int dmtlbsynch() {
unsigned int dm0 = 0;
asm volatile(" %0 = dmtlbsynch" : "=r"(dm0));
return dm0;
}
inline unsigned int dmcfgrd(unsigned int dmindex) {
unsigned int data = 0;
asm volatile(" %0 = dmcfgrd(%1)" : "=r"(data) : "r"(dmindex));
return data;
}
inline void dmcfgwr(unsigned int dmindex, unsigned int data) {
asm volatile(" dmcfgwr(%0, %1)" : : "r"(dmindex), "r"(data));
}
} // namespace hexagon
} // namespace runtime
} // namespace tvm
#endif // TVM_RUNTIME_HEXAGON_HEXAGON_USER_DMA_INSTRUCTIONS_H_
| https://github.com/zk-ml/tachikoma |
src/runtime/hexagon/hexagon_user_dma_registers.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#ifndef TVM_RUNTIME_HEXAGON_HEXAGON_USER_DMA_REGISTERS_H_
#define TVM_RUNTIME_HEXAGON_HEXAGON_USER_DMA_REGISTERS_H_
namespace tvm {
namespace runtime {
namespace hexagon {
/* Register offset */
#define regDM0 0x0 // per engine configuration
#define regDM1 0x1 // reserved
#define regDM2 0x2 // global control shared by all DMA Engines
#define regDM3 0x3 // reserved
#define regDM4 0x4 // global error syndrome register shared by all DMA Engines
#define regDM5 0x5 // global error syndrome register shared by all DMA Engines
// DM0[1:0]
#define DM0_STATUS_MASK 0x00000003
#define DM0_STATUS_SHIFT 0
#define DM0_STATUS_IDLE 0
#define DM0_STATUS_RUN 1
#define DM0_STATUS_ERROR 2
// DM0[31:4]
// Descriptors addresses must be (minimum) 16 byte aligned
// -> Lower 4 bits masked to clear DMA Status
// -> But, descriptor address is not shifted
#define DM0_DESC_ADDR_MASK 0xFFFFFFF0
#define DM0_DESC_ADDR_SHIFT 0
// DM2[0]
#define DM2_GUEST_MODE_STALL_MASK 0x00000001
#define DM2_GUEST_MODE_STALL_SHIFT 0
#define DM2_GUEST_MODE_STALL_YES 0
#define DM2_GUEST_MODE_STALL_NO 1
// DM2[1]
#define DM2_MONITOR_MODE_STALL_MASK 0x00000002
#define DM2_MONITOR_MODE_STALL_SHIFT 1
#define DM2_MONITOR_MODE_STALL_YES 0
#define DM2_MONITOR_MODE_STALL_NO 1
// DM2[3]
#define DM2_EXCEPTION_MODE_CONTINUE_MASK 0x00000008
#define DM2_EXCEPTION_MODE_CONTINUE_SHIFT 3
#define DM2_EXCEPTION_MODE_CONTINUE_YES 0
#define DM2_EXCEPTION_MODE_CONTINUE_NO 1
// DM2[4]
#define DM2_DEBUG_MODE_CONTINUE_MASK 0x00000010
#define DM2_DEBUG_MODE_CONTINUE_SHIFT 4
#define DM2_DEBUG_MODE_CONTINUE_NO 0
#define DM2_DEBUG_MODE_CONTINUE_YES 1
// DM2[6:5]
#define DM2_TRAFFIC_PRIORITY_MASK 0x00000060
#define DM2_TRAFFIC_PRIORITY_SHIFT 5
#define DM2_TRAFFIC_PRIORITY_IDLE 0
#define DM2_TRAFFIC_PRIORITY_LOW 1
#define DM2_TRAFFIC_PRIORITY_INHERIT 2
#define DM2_TRAFFIC_PRIORITY_HIGH 3
// DM2[7]
#define DM2_DLBC_ENABLE_MASK 0x00000080
#define DM2_DLBC_ENABLE_SHIFT 7
#define DM2_DLBC_DISABLE 0
#define DM2_DLBC_ENABLE 1
// DM2[8]
#define DM2_OOO_WRITE_MASK 0x00000100
#define DM2_OOO_WRITE_SHIFT 8
#define DM2_OOO_WRITE_ENABLE 0
#define DM2_OOO_WRITE_DISABLE 1
// DM2[9]
#define DM2_ERROR_EXCEPTION_MASK 0x00000200
#define DM2_ERROR_EXCEPTION_SHIFT 9
#define DM2_ERROR_EXCEPTION_GENERATE_NO 0
#define DM2_ERROR_EXCEPTION_GENERATE_YES 1
// DM2[23:16]
#define DM2_OUTSTANDING_READ_MASK 0x00FF0000
#define DM2_OUTSTANDING_READ_SHIFT 16
// DM2[31:24]
#define DM2_OUTSTANDING_WRITE_MASK 0xFF000000
#define DM2_OUTSTANDING_WRITE_SHIFT 24
// DM4[0]
#define DM4_ERROR_MASK 0x00000001
#define DM4_ERROR_SHIFT 0
#define DM4_ERROR_NO 0
#define DM4_ERROR_YES 1
// DM4[7:4]
#define DM4_THREAD_ID_MASK 0x000000F0
#define DM4_THREAD_ID_SHIFT 4
// DM4[15:8]
#define DM4_SYNDRONE_CODE_MASK 0x0000FF00
#define DM4_SYNDRONE_CODE_SHIFT 8
#define DM4_SYNDRONE_CODE_DM_COMMAND_ERROR 0
#define DM4_SYNDRONE_CODE_DESCRIPTOR_INVALID_ALIGNMENT 1
#define DM4_SYNDRONE_CODE_DESCRIPTOR_INVALID_TYPE 2
#define DM4_SYNDRONE_CODE_UNSUPPORTED_ADDRESS 3
#define DM4_SYNDRONE_CODE_UNSUPPORTED_BYPASS_MODE 4
#define DM4_SYNDRONE_CODE_UNSUPPORTED_COMP_FORMAT 5
#define DM4_SYNDRONE_CODE_DESCRIPTOR_ROI_ERROR 6
#define DM4_SYNDRONE_CODE_BUS_ERROR_DESCRIPTOR_RW 7
#define DM4_SYNDRONE_CODE_BUS_ERROR_L2_READ 8
#define DM4_SYNDRONE_CODE_BUS_ERROR_L2_WRITE 9
// TODO(Straw): Bus Error (10) on Compression Metadata?
// TODO(Straw): Definition? Not in the spec.
#define DM4_SYNDRONE_CODE_INVALID_ACCESS_RIGHTS 102
#define DM4_SYNDRONE_CODE_DATA_TIMEOUT 103
#define DM4_SYNDRONE_CODE_DATA_ABORT 104
// DM5
#define DM5_SYNDRONE_ADDR_MASK 0xFFFFFFFF
#define DM5_SYNDRONE_ADDR_SHIFT 0
// DM2[0]
static inline unsigned int dm2_get_guest_mode(unsigned int cfg) {
return (cfg & DM2_GUEST_MODE_STALL_MASK) >> DM2_GUEST_MODE_STALL_SHIFT;
}
// DM2[0]
static inline void dm2_set_guest_mode(unsigned int* cfg, unsigned int v) {
*cfg &= ~DM2_GUEST_MODE_STALL_MASK;
*cfg |= ((v << DM2_GUEST_MODE_STALL_SHIFT) & DM2_GUEST_MODE_STALL_MASK);
}
// DM2[1]
static inline unsigned int dm2_get_monitor_mode(unsigned int cfg) {
return (cfg & DM2_MONITOR_MODE_STALL_MASK) >> DM2_MONITOR_MODE_STALL_SHIFT;
}
// DM2[1]
static inline void dm2_set_monitor_mode(unsigned int* cfg, unsigned int v) {
*cfg &= ~DM2_MONITOR_MODE_STALL_MASK;
*cfg |= ((v << DM2_MONITOR_MODE_STALL_SHIFT) & DM2_MONITOR_MODE_STALL_MASK);
}
// DM2[3]
static inline unsigned int dm2_get_exception_mode(unsigned int cfg) {
return (cfg & DM2_EXCEPTION_MODE_CONTINUE_MASK) >> DM2_EXCEPTION_MODE_CONTINUE_SHIFT;
}
// DM2[3]
static inline void dm2_set_exception_mode(unsigned int* cfg, unsigned int v) {
*cfg &= ~DM2_EXCEPTION_MODE_CONTINUE_MASK;
*cfg |= ((v << DM2_EXCEPTION_MODE_CONTINUE_SHIFT) & DM2_EXCEPTION_MODE_CONTINUE_MASK);
}
// DM2[4]
static inline unsigned int dm2_get_debug_mode(unsigned int cfg) {
return (cfg & DM2_DEBUG_MODE_CONTINUE_MASK) >> DM2_DEBUG_MODE_CONTINUE_SHIFT;
}
// DM2[4]
static inline void dm2_set_debug_mode(unsigned int* cfg, unsigned int v) {
*cfg &= ~DM2_DEBUG_MODE_CONTINUE_MASK;
*cfg |= ((v << DM2_DEBUG_MODE_CONTINUE_SHIFT) & DM2_DEBUG_MODE_CONTINUE_MASK);
}
// DM2[6:5]
static inline unsigned int dm2_get_priority(unsigned int cfg) {
return (cfg & DM2_TRAFFIC_PRIORITY_MASK) >> DM2_TRAFFIC_PRIORITY_SHIFT;
}
// DM2[6:5]
static inline void dm2_set_priority(unsigned int* cfg, unsigned int v) {
*cfg &= ~DM2_TRAFFIC_PRIORITY_MASK;
*cfg |= ((v << DM2_TRAFFIC_PRIORITY_SHIFT) & DM2_TRAFFIC_PRIORITY_MASK);
}
// DM2[7]
static inline unsigned int dm2_get_dlbc_enable(unsigned int cfg) {
return (cfg & DM2_DLBC_ENABLE_MASK) >> DM2_DLBC_ENABLE_SHIFT;
}
// DM2[7]
static inline void dm2_set_dlbc_enable(unsigned int* cfg, unsigned int v) {
*cfg &= ~DM2_DLBC_ENABLE_MASK;
*cfg |= ((v << DM2_DLBC_ENABLE_SHIFT) & DM2_DLBC_ENABLE_MASK);
}
// DM2[8]
static inline unsigned int dm2_get_ooo_write_ctrl(unsigned int cfg) {
return (cfg & DM2_OOO_WRITE_MASK) >> DM2_OOO_WRITE_SHIFT;
}
// DM2[8]
static inline void dm2_set_ooo_write_ctrl(unsigned int* cfg, unsigned int v) {
*cfg &= ~DM2_OOO_WRITE_MASK;
*cfg |= ((v << DM2_OOO_WRITE_SHIFT) & DM2_OOO_WRITE_MASK);
}
// DM2[9]
static inline unsigned int dm2_get_error_exception_ctrl(unsigned int cfg) {
return (cfg & DM2_ERROR_EXCEPTION_MASK) >> DM2_ERROR_EXCEPTION_SHIFT;
}
// DM2[9]
static inline void dm2_set_error_exception_ctrl(unsigned int* cfg, unsigned int v) {
*cfg &= ~DM2_ERROR_EXCEPTION_MASK;
*cfg |= ((v << DM2_ERROR_EXCEPTION_SHIFT) & DM2_ERROR_EXCEPTION_MASK);
}
// DM2[23:16]
static inline unsigned int dm2_get_outstanding_transactions_read(unsigned int cfg) {
return (cfg & DM2_OUTSTANDING_READ_MASK) >> DM2_OUTSTANDING_READ_SHIFT;
}
// DM2[23:16]
static inline void dm2_set_outstanding_transactions_read(unsigned int* cfg, unsigned int v) {
*cfg &= ~DM2_OUTSTANDING_READ_MASK;
*cfg |= ((v << DM2_OUTSTANDING_READ_SHIFT) & DM2_OUTSTANDING_READ_MASK);
}
// DM2[31:24]
static inline unsigned int dm2_get_outstanding_transactions_write(unsigned int cfg) {
return (cfg & DM2_OUTSTANDING_WRITE_MASK) >> DM2_OUTSTANDING_WRITE_SHIFT;
}
// DM2[31:24]
static inline void dm2_set_outstanding_transactions_write(unsigned int* cfg, unsigned int v) {
*cfg &= ~DM2_OUTSTANDING_WRITE_MASK;
*cfg |= ((v << DM2_OUTSTANDING_WRITE_SHIFT) & DM2_OUTSTANDING_WRITE_MASK);
}
/*--------------------------------------------------------------------------*/
// DM4[0]
static inline unsigned int dm4_get_error(unsigned int cfg) {
return (cfg & DM4_ERROR_MASK) >> DM4_ERROR_SHIFT;
}
// DM4[7:4]
static inline unsigned int dm4_get_engine_id(unsigned int cfg) {
return (cfg & DM4_THREAD_ID_MASK) >> DM4_THREAD_ID_SHIFT;
}
// DM4[15:8]
static inline unsigned int dm4_get_syndrone_code(unsigned int cfg) {
return (cfg & DM4_SYNDRONE_CODE_MASK) >> DM4_SYNDRONE_CODE_SHIFT;
}
/*--------------------------------------------------------------------------*/
// DM5
static inline unsigned int dm5_get_syndrone_addr(unsigned int cfg) {
return (cfg & DM5_SYNDRONE_ADDR_MASK) >> DM5_SYNDRONE_ADDR_SHIFT;
}
} // namespace hexagon
} // namespace runtime
} // namespace tvm
#endif // TVM_RUNTIME_HEXAGON_HEXAGON_USER_DMA_REGISTERS_H_
| https://github.com/zk-ml/tachikoma |
src/runtime/hexagon/hexagon_vtcm_pool.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#ifndef TVM_RUNTIME_HEXAGON_HEXAGON_VTCM_POOL_H_
#define TVM_RUNTIME_HEXAGON_HEXAGON_VTCM_POOL_H_
#include <tvm/runtime/c_runtime_api.h>
#include <tvm/runtime/device_api.h>
#include <tvm/runtime/logging.h>
#include <tvm/runtime/ndarray.h>
#include <tvm/runtime/packed_func.h>
#include <utility>
#include <vector>
namespace tvm {
namespace runtime {
namespace hexagon {
class HexagonVtcmPool {
public:
//! \brief Allocates all of VTCM memory, and manages allocations from the runtime
HexagonVtcmPool();
//! \brief Destruction deallocates the underlying VTCM allocation.
~HexagonVtcmPool();
//! \brief Prevent copy construction of HexagonVtcmPool.
HexagonVtcmPool(const HexagonVtcmPool&) = delete;
//! \brief Prevent copy assignment with HexagonVtcmPool.
HexagonVtcmPool& operator=(const HexagonVtcmPool&) = delete;
//! \brief Prevent move construction.
HexagonVtcmPool(HexagonVtcmPool&&) = delete;
//! \brief Prevent move assignment.
HexagonVtcmPool& operator=(HexagonVtcmPool&&) = delete;
/* \brief Allocate memory from the VTCM manager
*
* \param nbytes The number of bytes to allocate.
*/
void* Allocate(size_t nbytes);
/* \brief Copy data from a Hexagon Buffer an external buffer.
*
* \param ptr The pointer to the buffer to be freed.
*
* \param nbytes The number of bytes to be freed.
*/
void Free(void* ptr, size_t nbytes);
//! \brief Returns the total number of bytes in this pool
size_t TotalBytes() { return reinterpret_cast<size_t>(vtcm_size_); }
private:
//! \brief Total size of VTCM pool
unsigned int vtcm_size_;
//! \brief Pointer to the beginning of the pool
void* vtcm_data_;
//! \brief Context for HAP_compute_res_*
unsigned int context_id_{0};
//! \brief List of allocations
std::vector<std::pair<char*, size_t>> allocations_;
//! \brief List of free segments
std::vector<std::pair<char*, size_t>> free_;
//! \brief Mutext to protect access to the lists
std::mutex mutex_;
//! \brief Debug only dump of the state of the lists
void DebugDump();
};
} // namespace hexagon
} // namespace runtime
} // namespace tvm
#endif // TVM_RUNTIME_HEXAGON_HEXAGON_VTCM_POOL_H_
| https://github.com/zk-ml/tachikoma |
src/runtime/hexagon/profiler/prof_utils.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* \file prof_utils.h
*/
#ifndef TVM_RUNTIME_HEXAGON_PROFILER_PROF_UTILS_H_
#define TVM_RUNTIME_HEXAGON_PROFILER_PROF_UTILS_H_
#include <string>
bool WriteLWPOutput(const std::string&);
#endif // TVM_RUNTIME_HEXAGON_PROFILER_PROF_UTILS_H_
| https://github.com/zk-ml/tachikoma |
src/runtime/hexagon/ring_buffer.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#ifndef TVM_RUNTIME_HEXAGON_RING_BUFFER_H_
#define TVM_RUNTIME_HEXAGON_RING_BUFFER_H_
#include <functional>
#include <vector>
#include "hexagon_common.h"
namespace tvm {
namespace runtime {
namespace hexagon {
template <class T>
class RingBuffer {
public:
//! \brief Returns the number of Ts in flight
uint32_t InFlight() {
while (id_oldest_ < id_next_ && !in_flight_(GetAddr(id_oldest_))) {
id_oldest_++;
}
return id_next_ - id_oldest_;
}
//! \brief Returns pointer to next T; null if ring buffer is full
T* Next() {
if (InFlight() == ring_buff_size_) {
return nullptr;
}
T* next = GetAddr(id_next_);
id_next_++;
return next;
}
/*! \brief Creates a ring buffer for storage items of type T
* \param ring_buff_size Size of the ring buffer in number of Ts
* \param in_flight Function that determines whether a T is in flight
*/
RingBuffer(uint32_t ring_buff_size, std::function<bool(T*)> in_flight)
: ring_buff_size_(ring_buff_size), in_flight_(in_flight) {
CHECK_NE(ring_buff_size, 0);
int ret = posix_memalign(reinterpret_cast<void**>(&ring_buff_ptr_), sizeof(T),
sizeof(T) * ring_buff_size_);
CHECK_EQ(ret, 0);
CHECK_NE(ring_buff_ptr_, nullptr);
}
~RingBuffer() { free(ring_buff_ptr_); }
private:
//! \brief Returns the address of a T given its index
T* GetAddr(uint32_t id) const {
uint32_t ring_buff_index = id % ring_buff_size_;
return ring_buff_ptr_ + ring_buff_index;
}
//! \brief Pointer to the ring buffer
T* ring_buff_ptr_ = nullptr;
//! \brief Size of the ring buffer in number of Ts
const uint32_t ring_buff_size_ = 0;
//! \brief Function that determines whether a T is in flight
const std::function<bool(T*)> in_flight_;
//! \brief Tracks the ID of the next T to be added to the ring buffer
uint32_t id_next_ = 0;
//! \brief Tracks the ID of the oldest T in flight
uint32_t id_oldest_ = 0;
};
//! \brief Separates a single RingBuffer into multiple virtual queues with each queue having a
//! unique integer ID; queues allow for indepent users of the same RingBuffer while mainting overall
//! FIFO ordering among all queues
template <class T>
class QueuedRingBuffer : RingBuffer<T> {
public:
QueuedRingBuffer(uint32_t ring_buff_size, std::function<bool(T*)> in_flight)
: RingBuffer<T>(ring_buff_size, in_flight) {}
//! \brief Returns pointer to next T; add the queue ID for tracking
T* Next(int queue_id) {
queue_ids_.push_back(queue_id);
return RingBuffer<T>::Next();
}
//! \brief Returns the number of Ts in flight for a given queue ID
uint32_t InFlight(int queue_id) {
uint32_t in_flight = 0;
// look at the queue IDs for the RingBuffer entries in flight
for (size_t i = queue_ids_.size() - RingBuffer<T>::InFlight(); i < queue_ids_.size(); ++i) {
// increment return value if in flight queue ID matches
if (queue_ids_[i] == queue_id) {
in_flight++;
}
}
return in_flight;
}
private:
std::vector<int> queue_ids_;
};
} // namespace hexagon
} // namespace runtime
} // namespace tvm
#endif // TVM_RUNTIME_HEXAGON_RING_BUFFER_H_
| https://github.com/zk-ml/tachikoma |
src/runtime/hexagon/rpc/simulator/hexagon_sim_proto.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#ifndef TVM_RUNTIME_HEXAGON_RPC_SIMULATOR_HEXAGON_SIM_PROTO_H_
#define TVM_RUNTIME_HEXAGON_RPC_SIMULATOR_HEXAGON_SIM_PROTO_H_
struct Message {
enum : uint32_t {
kNone = 0,
kAck,
kTerminate,
kReceiveStart,
kReceiveEnd,
kSendStart,
kSendEnd,
};
enum : uint32_t {
null_va = 0,
};
uint32_t code;
uint32_t len;
uint32_t va;
} __attribute__((packed));
// Protocol:
//
// Copying data from host to remote:
//
// Host >-- [ kReceiveStart, len, null_va ] --> Remote
// * Remote client prepares a buffer with at least `len` bytes.
// Host <-- [ kAck, buf_size, buf_ptr ] <-- Remote
// * Host writes `nbytes` into buffer, `nbytes` <= `len`.
// Host >-- [ kReceiveEnd, nbytes, buf_ptr ] --> Remote
// * Remote client processes the data.
// Host <-- [ kAck, ___, ___ ] <-- Remote
//
// Copying data from remote to host:
//
// Host >-- [ kSendStart, len, null_va ] --> Remote
// * Remote client returns pointer to the buffer with the data to be read.
// * There should be at least `len` bytes ready in the buffer.
// Host <-- [ kAck, buf_size, buf_ptr ] <-- Remote
// * Host reads `nbytes` from buffer, `nbytes` <= `buf_size`.
// Host >-- [ kSendEnd , nbytes, buf_ptr ] --> Remote
// * Remote client processes the data.
// Host <-- [ kAck, ___, ___ ] <-- Remote
//
// Teminating server:
//
// Host >-- [ kTerminate, ___, ___ ] --> Remote
// Host <-- [ kAck, ___, ___ ] <-- Remote
// * Host continues execution of the client.
// * Client terminates.
#define DISPATCH_FUNCTION_NAME dispatch_875b2e3a28186123
#define MESSAGE_BUFFER_NAME message_buffer_71d6a7b93c318d7e
#endif // TVM_RUNTIME_HEXAGON_RPC_SIMULATOR_HEXAGON_SIM_PROTO_H_
| https://github.com/zk-ml/tachikoma |
src/runtime/library_module.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* \file library_module.h
* \brief Module that builds from a libary of symbols.
*/
#ifndef TVM_RUNTIME_LIBRARY_MODULE_H_
#define TVM_RUNTIME_LIBRARY_MODULE_H_
#include <tvm/runtime/c_backend_api.h>
#include <tvm/runtime/c_runtime_api.h>
#include <tvm/runtime/module.h>
#include <functional>
#include <string>
namespace tvm {
namespace runtime {
/*! \brief Load a module with the given type key directly from the stream.
* This function wraps the registry mechanism used to store type based deserializers
* for each runtime::Module sub-class.
*
* \param type_key The type key of the serialized module.
* \param stream A pointer to the stream containing the serialized module.
* \return module The deserialized module.
*/
Module LoadModuleFromBinary(const std::string& type_key, dmlc::Stream* stream);
/*!
* \brief Library is the common interface
* for storing data in the form of shared libaries.
*
* \sa dso_library.cc
* \sa system_library.cc
*/
class Library : public Object {
public:
// destructor.
virtual ~Library() {}
/*!
* \brief Get the symbol address for a given name.
* \param name The name of the symbol.
* \return The symbol.
*/
virtual void* GetSymbol(const char* name) = 0;
// NOTE: we do not explicitly create an type index and type_key here for libary.
// This is because we do not need dynamic type downcasting.
};
/*!
* \brief Wrap a TVMBackendPackedCFunc to packed function.
* \param faddr The function address
* \param mptr The module pointer node.
*/
PackedFunc WrapPackedFunc(TVMBackendPackedCFunc faddr, const ObjectPtr<Object>& mptr);
/*!
* \brief Utility to initialize conext function symbols during startup
* \param fgetsymbol A symbol lookup function.
*/
void InitContextFunctions(std::function<void*(const char*)> fgetsymbol);
/*!
* \brief Type alias for function to wrap a TVMBackendPackedCFunc.
* \param The function address imported from a module.
* \param mptr The module pointer node.
* \return Packed function that wraps the invocation of the function at faddr.
*/
using PackedFuncWrapper =
std::function<PackedFunc(TVMBackendPackedCFunc faddr, const ObjectPtr<Object>& mptr)>;
/*! \brief Return a library object interface over dynamic shared
* libraries in Windows and Linux providing support for
* loading/unloading and symbol lookup.
* \param Full path to shared library.
* \return Returns pointer to the Library providing symbol lookup.
*/
ObjectPtr<Library> CreateDSOLibraryObject(std::string library_path);
/*!
* \brief Create a module from a library.
*
* \param lib The library.
* \param wrapper Optional function used to wrap a TVMBackendPackedCFunc,
* by default WrapPackedFunc is used.
* \return The corresponding loaded module.
*
* \note This function can create multiple linked modules
* by parsing the binary blob section of the library.
*/
Module CreateModuleFromLibrary(ObjectPtr<Library> lib, PackedFuncWrapper wrapper = WrapPackedFunc);
} // namespace runtime
} // namespace tvm
#endif // TVM_RUNTIME_LIBRARY_MODULE_H_
| https://github.com/zk-ml/tachikoma |
src/runtime/meta_data.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* \file meta_data.h
* \brief Meta data related utilities
*/
#ifndef TVM_RUNTIME_META_DATA_H_
#define TVM_RUNTIME_META_DATA_H_
#include <dmlc/io.h>
#include <dmlc/json.h>
#include <tvm/runtime/executor_info.h>
#include <tvm/runtime/metadata.h>
#include <tvm/runtime/module.h>
#include <tvm/runtime/ndarray.h>
#include <tvm/runtime/packed_func.h>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>
#include "runtime_base.h"
namespace tvm {
namespace runtime {
inline String get_name_mangled(const String& module_name, const String& name) {
std::stringstream ss;
ICHECK(module_name.defined());
ICHECK(name.defined());
ss << module_name << "_" << name;
return ss.str();
}
/*!
* \brief Create a metadata module object.
*
* \param metadata Exported metadata structure.
*
* \return The created metadata module.
*/
Module MetadataModuleCreate(metadata::Metadata metadata);
namespace launch_param {
/*! \brief A tag to specify whether or not dynamic shared memory is used */
constexpr const char* kUseDynamicSharedMemoryTag = "tir.use_dyn_shared_memory";
} // namespace launch_param
/*! \brief function information needed by device */
struct FunctionInfo {
std::string name;
std::vector<DLDataType> arg_types;
std::vector<std::string> launch_param_tags;
void Save(dmlc::JSONWriter* writer) const;
void Load(dmlc::JSONReader* reader);
void Save(dmlc::Stream* writer) const;
bool Load(dmlc::Stream* reader);
};
} // namespace runtime
} // namespace tvm
namespace dmlc {
DMLC_DECLARE_TRAITS(has_saveload, ::tvm::runtime::FunctionInfo, true);
} // namespace dmlc
#endif // TVM_RUNTIME_META_DATA_H_
| https://github.com/zk-ml/tachikoma |
src/runtime/metal/metal_common.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* \file metal_common.h
* \brief Metal common header
*/
#ifndef TVM_RUNTIME_METAL_METAL_COMMON_H_
#define TVM_RUNTIME_METAL_METAL_COMMON_H_
#import <Metal/MTLBlitCommandEncoder.h>
#import <Metal/MTLBuffer.h>
#import <Metal/MTLCommandBuffer.h>
#import <Metal/MTLCommandQueue.h>
#import <Metal/MTLDevice.h>
#import <Metal/MTLLibrary.h>
#include <tvm/runtime/c_runtime_api.h>
#include <tvm/runtime/device_api.h>
#include <tvm/runtime/logging.h>
#include <tvm/runtime/packed_func.h>
#include <memory>
#include <mutex>
#include <string>
#include <vector>
#include "../workspace_pool.h"
/* Macro for convenience in using AutoReleasePoolWrapper.
* With this macro we can add AutoReleasePoolWrapper to our ObjC code in more
* native way.
*
* For example, this is ObjC code with autoreleasepool:
* @autoreleasepool {
* // Some code
* }
*
* To avoid possible memory leaks when an exception will be generated, we
* should update this code:
* AUTORELEASEPOOL { // Replace @autoreleasepool -> AUTORELEASEPOOL
* // Some code
* }; // Add semicolon after close bracket
*
* In macro AUTORELEASEPOOL we get the instance of AutoReleasePoolWrapper and
* put a lambda function with code from autoreleasepool to the insertion
* operator of AutoReleasePoolWrapper class.
*
* Note: If you want to return a value from the autoreleasepool, you should
* declare the variable with result before AUTORELEASEPOOL macro. This variable
* will be captured by reference and you can use it in the code in autorelease
* pool. But you should write return statement after AUTORELEASEPOOL macro.
*/
#define AUTORELEASEPOOL tvm::runtime::metal::AutoReleasePoolWrapper::GetInstance() << [&]()
namespace tvm {
namespace runtime {
namespace metal {
/*!
* \brief Wrapper on autoreleasepool with exception handling
*
* \note In case when the exception was thrown from the autoreleasepool, the
* allocated resources won't be released in proper way. So, we handle exception
* in autoreleasepool and after the autoreleasepool we rethrow this exception.
*/
class AutoReleasePoolWrapper {
public:
static AutoReleasePoolWrapper& GetInstance();
template <typename T>
void operator<<(const T& f) {
std::exception_ptr eptr;
@autoreleasepool {
try {
f();
} catch (...) {
eptr = std::current_exception();
}
}
if (eptr) std::rethrow_exception(eptr);
}
private:
AutoReleasePoolWrapper() = default;
~AutoReleasePoolWrapper() = default;
AutoReleasePoolWrapper(const AutoReleasePoolWrapper&) = delete;
AutoReleasePoolWrapper& operator=(const AutoReleasePoolWrapper&) = delete;
};
/*!
* \brief Structure for error handling in queues
*/
class Stream {
public:
explicit Stream(id<MTLDevice> device) : error_happened_(false) {
queue_ = [device newCommandQueue];
}
~Stream() { [queue_ release]; }
id<MTLCommandBuffer> GetCommandBuffer() {
id<MTLCommandBuffer> cb = [queue_ commandBuffer];
[cb addCompletedHandler:^(id<MTLCommandBuffer> buffer) {
if (buffer.status == MTLCommandBufferStatusError) SetErrorStatus();
}];
return cb;
}
bool HasErrorHappened() { return error_happened_; }
private:
void SetErrorStatus() { error_happened_ = true; }
// Queue
id<MTLCommandQueue> queue_;
// Check if error happened in one previous run
bool error_happened_;
};
/*!
* \brief Process global Metal workspace.
*/
class MetalWorkspace final : public DeviceAPI {
public:
// the devices
std::vector<id<MTLDevice>> devices;
// Warp size constant
std::vector<int> warp_size;
// Whether it is initialized.
bool initialized_{false};
// the mutex for initialization
std::mutex mutex;
// Destructor
~MetalWorkspace();
// Get device for given device
id<MTLDevice> GetDevice(Device dev) {
ICHECK_EQ(dev.device_type, kDLMetal);
ICHECK(dev.device_id >= 0 && static_cast<size_t>(dev.device_id) < devices.size())
<< "Invalid Metal device_id=" << dev.device_id;
return devices[dev.device_id];
}
// Initialize workspace
// Return false if already initialized, otherwise return true.
void Init();
// override device API
void SetDevice(Device dev) final;
void GetAttr(Device dev, DeviceAttrKind kind, TVMRetValue* rv) final;
void* AllocDataSpace(Device dev, size_t nbytes, size_t alignment, DLDataType type_hint) final;
void FreeDataSpace(Device dev, void* ptr) final;
TVMStreamHandle CreateStream(Device dev) final;
void FreeStream(Device dev, TVMStreamHandle stream) final;
void StreamSync(Device dev, TVMStreamHandle stream) final;
void SetStream(Device dev, TVMStreamHandle stream) final;
void* AllocWorkspace(Device dev, size_t size, DLDataType type_hint) final;
void FreeWorkspace(Device dev, void* data) final;
void ReinitializeStreams();
// get the global workspace
static MetalWorkspace* Global();
protected:
void CopyDataFromTo(const void* from, size_t from_size, void* to, size_t to_size, size_t size,
Device dev_from, Device dev_to, DLDataType type_hint,
TVMStreamHandle stream) final;
private:
// Pointers to default allocated streams
std::vector<Stream*> default_streams_;
};
/*! \brief Thread local workspace */
class MetalThreadEntry {
public:
/*! \brief The current device */
Device device;
/*! \brief The current stream */
std::vector<Stream*> stream;
/*! \brief The shared buffer used for copy. */
std::vector<id<MTLBuffer>> temp_buffer_;
/*! \brief workspace pool */
WorkspacePool pool;
// constructor
MetalThreadEntry() : pool(static_cast<DLDeviceType>(kDLMetal), MetalWorkspace::Global()) {
device.device_id = 0;
device.device_type = static_cast<DLDeviceType>(kDLMetal);
}
~MetalThreadEntry();
// Get temp buffer with at least size under dev.
id<MTLBuffer> GetTempBuffer(Device dev, size_t size);
// get the global workspace
static MetalThreadEntry* ThreadLocal();
};
} // namespace metal
} // namespace runtime
} // namespace tvm
#endif // TVM_RUNTIME_METAL_METAL_COMMON_H_
| https://github.com/zk-ml/tachikoma |
src/runtime/metal/metal_module.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* \file metal_module.h
* \brief Execution handling of Metal kernels
*/
#ifndef TVM_RUNTIME_METAL_METAL_MODULE_H_
#define TVM_RUNTIME_METAL_METAL_MODULE_H_
#include <tvm/runtime/packed_func.h>
#include <memory>
#include <string>
#include <unordered_map>
#include <vector>
#include "../meta_data.h"
namespace tvm {
namespace runtime {
/*! \brief Maximum number of GPU supported in MetalModule. */
static constexpr const int kMetalMaxNumDevice = 32;
/*!
* \brief create a metal module from data.
*
* \param data The data content.
* \param fmt The format of the data, can be "metal" or "metallib"
* \param fmap The map function information map of each function.
* \param source Optional, source file
*/
Module MetalModuleCreate(std::string data, std::string fmt,
std::unordered_map<std::string, FunctionInfo> fmap, std::string source);
} // namespace runtime
} // namespace tvm
#endif // TVM_RUNTIME_METAL_METAL_MODULE_H_
| https://github.com/zk-ml/tachikoma |
src/runtime/micro/crt_config.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* \file tvm/runtime/crt/host/crt_config.h
* \brief CRT configuration for the host-linked CRT.
*/
#ifndef TVM_RUNTIME_MICRO_CRT_CONFIG_H_
#define TVM_RUNTIME_MICRO_CRT_CONFIG_H_
/*! Log level of the CRT runtime */
#define TVM_CRT_LOG_LEVEL TVM_CRT_LOG_LEVEL_DEBUG
/*! Support low-level debugging in MISRA-C runtime */
#define TVM_CRT_DEBUG 0
/*! Maximum supported dimension in NDArray */
#define TVM_CRT_MAX_NDIM 6
/*! Maximum supported arguments in generated functions */
#define TVM_CRT_MAX_ARGS 10
/*! Maximum supported string length in dltype, e.g. "int8", "int16", "float32" */
#define TVM_CRT_MAX_STRLEN_DLTYPE 10
/*! Maximum supported string length in function names */
#define TVM_CRT_MAX_STRLEN_FUNCTION_NAME 120
/*! Maximum supported string length in parameter names */
#define TVM_CRT_MAX_STRLEN_PARAM_NAME 80
/*! Maximum number of registered modules. */
#define TVM_CRT_MAX_REGISTERED_MODULES 2
/*! Size of the global function registry, in bytes. */
#define TVM_CRT_GLOBAL_FUNC_REGISTRY_SIZE_BYTES 512
/*! Maximum packet size, in bytes, including the length header. */
#define TVM_CRT_MAX_PACKET_SIZE_BYTES 8 * 1024
/*! \brief Maximum length of a PackedFunc function name. */
#define TVM_CRT_MAX_FUNCTION_NAME_LENGTH_BYTES 30
// #define TVM_CRT_FRAMER_ENABLE_LOGS
#endif // TVM_RUNTIME_MICRO_CRT_CONFIG_H_
| https://github.com/zk-ml/tachikoma |
src/runtime/micro/micro_session.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* \file micro_session.h
* \brief session to manage multiple micro modules
*
* Each session consists of an interaction with a *single* logical device.
* Within that interaction, multiple TVM modules can be loaded on the logical
* device.
*
* Multiple sessions can exist simultaneously, but there is only ever one
* *active* session. The idea of an active session mainly has implications for
* the frontend, in that one must make a session active in order to allocate
* new TVM objects on it. Aside from that, previously allocated objects can be
* used even if the session which they belong to is not currently active.
*/
#ifndef TVM_RUNTIME_MICRO_MICRO_SESSION_H_
#define TVM_RUNTIME_MICRO_MICRO_SESSION_H_
#endif // TVM_RUNTIME_MICRO_MICRO_SESSION_H_
| https://github.com/zk-ml/tachikoma |
src/runtime/micro/standalone/microtvm_graph_executor.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#ifndef TVM_RUNTIME_MICRO_STANDALONE_MICROTVM_GRAPH_EXECUTOR_H_
#define TVM_RUNTIME_MICRO_STANDALONE_MICROTVM_GRAPH_EXECUTOR_H_
#include <dlpack/dlpack.h>
#include <algorithm>
#include <functional>
#include <memory>
#include <numeric>
#include <string>
#include <utility>
#include <vector>
#include "microtvm_runtime_api.h"
#include "minimal_vector.h"
namespace tvm {
namespace micro {
typedef int (*BackendPackedCFunc)(void* args, int* type_codes, int num_args);
// dlopen/dlsym/dlclose abstraction.
class DSOModule {
public:
explicit DSOModule(const std::string& name);
~DSOModule();
BackendPackedCFunc GetFunction(const std::string& name) const;
private:
void* GetSymbol(const char* name) const;
void* lib_handle_{nullptr};
};
// The graph attribute fields.
struct GraphAttr {
DynArray<int> storage_id;
DynArray<std::string> dltype;
DynArray<DynArray<int64_t>> shape;
};
// Memory pool entry.
struct PoolEntry {
size_t size;
int device_type;
};
// Node entry
struct NodeEntry {
uint32_t node_id;
uint32_t index;
uint32_t version;
};
// Operator attributes about TVMOp
struct TVMOpParam {
std::string func_name;
uint32_t num_inputs;
uint32_t num_outputs;
uint32_t flatten_data;
};
// Node
struct Node {
// operator type in string
std::string op_type;
// name of the op
std::string name;
// parameters
TVMOpParam param;
// inputs
DynArray<NodeEntry> inputs;
};
// Minimal NDArray abstraction
class NDArray {
public:
// initialize NDArray with shape/dtype/device
static NDArray Empty(const DynArray<int64_t>& shape, DLDataType dtype, DLDevice dev);
// create a view of the NDArray storage, with the given shape/dtype
NDArray CreateView(const DynArray<int64_t>& shape, DLDataType dtype);
// Copy into the internal storage.
void CopyFrom(DLTensor* src);
// Copy out of the internal storage
void CopyTo(DLTensor* dst) const;
// View `this` as a DLTensor
DLTensor ToDLTensor();
~NDArray();
private:
// reference-counted storage
std::shared_ptr<void> storage_;
// tensor shape
DynArray<int64_t> shape_;
// tensor dtype
DLDataType dtype_;
// tensor device
DLDevice device_;
};
// Minimal GraphExecutor implementation
class MicroGraphExecutor {
public:
// Construct a GraphExecutor with the given graph and DSOModule.
MicroGraphExecutor(const std::string& graph_json, DSOModule* module);
~MicroGraphExecutor();
// Run the graph
void Run();
// Set the input at `index` to a copy of the tensor `data_in`
void SetInput(int index, DLTensor* data_in);
// Copy the output at `index` into `data_out`
void CopyOutputTo(int index, DLTensor* data_out);
private:
void SetupStorage();
void SetupOpExecs();
uint32_t num_node_entries() const { return node_row_ptr_.back(); }
uint32_t entry_id(uint32_t nid, uint32_t index) const { return node_row_ptr_[nid] + index; }
uint32_t entry_id(const NodeEntry& e) const { return entry_id(e.node_id, e.index); }
DSOModule* module_;
// TODO(tulloch): these are essentially unused after construction.
// The graph nodes
DynArray<Node> nodes_;
// The argument noes
DynArray<uint32_t> input_nodes_;
// Used for quick entry indexing
DynArray<uint32_t> node_row_ptr_;
// Output entries
DynArray<NodeEntry> outputs_;
// Additional graph attributes
GraphAttr attrs_;
// Execution device
DLDevice device_{kDLCPU, 0};
// Common storage pool
DynArray<NDArray> storage_pool_;
// Data entry for each node
DynArray<NDArray> data_entry_;
// Operator for each node
DynArray<std::function<void()>> op_execs_;
};
} // namespace micro
} // namespace tvm
#endif // TVM_RUNTIME_MICRO_STANDALONE_MICROTVM_GRAPH_EXECUTOR_H_
| https://github.com/zk-ml/tachikoma |
src/runtime/micro/standalone/microtvm_runtime_api.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#ifndef TVM_RUNTIME_MICRO_STANDALONE_MICROTVM_RUNTIME_API_H_
#define TVM_RUNTIME_MICRO_STANDALONE_MICROTVM_RUNTIME_API_H_
#include <stdint.h>
#include <stdlib.h>
#include <cassert>
// The subset of the TVM runtime API that is implemented by the minimal runtime API.
#define TVM_MICRO_RUNTIME_API_BACKEND_API extern "C" __attribute__((weak, visibility("default")))
TVM_MICRO_RUNTIME_API_BACKEND_API int TVMBackendFreeWorkspace(int device_type, int device_id,
void* ptr);
TVM_MICRO_RUNTIME_API_BACKEND_API void* TVMBackendAllocWorkspace(int device_type, int device_id,
uint64_t nbytes,
int dtype_code_hint,
int dtype_bits_hint);
typedef struct {
void* sync_handle;
int32_t num_task;
} TVMParallelGroupEnv;
typedef int (*FTVMParallelLambda)(int task_id, TVMParallelGroupEnv* penv, void* cdata);
TVM_MICRO_RUNTIME_API_BACKEND_API int TVMBackendParallelLaunch(FTVMParallelLambda flambda,
void* cdata, int num_task);
TVM_MICRO_RUNTIME_API_BACKEND_API void TVMAPISetLastError(const char* msg);
TVM_MICRO_RUNTIME_API_BACKEND_API const char* TVMGetLastError(void);
#undef TVM_MICRO_RUNTIME_API_BACKEND_API
#endif // TVM_RUNTIME_MICRO_STANDALONE_MICROTVM_RUNTIME_API_H_
| https://github.com/zk-ml/tachikoma |
src/runtime/micro/standalone/minimal_vector.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#ifndef TVM_RUNTIME_MICRO_STANDALONE_MINIMAL_VECTOR_H_
#define TVM_RUNTIME_MICRO_STANDALONE_MINIMAL_VECTOR_H_
#include <algorithm>
#include <cassert>
#include <memory>
namespace tvm {
namespace micro {
// A minimal wrapper, derived from https://github.com/Robbepop/dynarray/, that
// supports a minimal subset of the std::vector API with a minimized code size.
template <typename T>
struct DynArray {
using value_type = T;
using size_type = size_t;
using difference_type = std::ptrdiff_t;
using reference = value_type&;
using const_reference = value_type const&;
using pointer = value_type*;
using const_pointer = value_type const*;
using iterator = pointer;
using const_iterator = const_pointer;
using reverse_iterator = std::reverse_iterator<iterator>;
using const_reverse_iterator = std::reverse_iterator<const_iterator>;
explicit DynArray(size_type size = 0) { resize(size); }
DynArray(const DynArray& other) {
resize(other.size());
std::copy(other.begin(), other.end(), begin());
}
DynArray& operator=(const DynArray& other) {
resize(other.size());
std::copy(other.begin(), other.end(), begin());
return *this;
}
void resize(size_type size) {
if (size > 0) {
data_.reset(new T[size]);
} else {
data_.reset();
}
size_ = size;
}
size_type size() const { return size_; }
reference operator[](size_type pos) { return data_[pos]; }
const_reference operator[](size_type pos) const { return data_[pos]; }
pointer data() { return data_.get(); }
const_pointer data() const { return data_.get(); }
iterator begin() { return data_.get(); }
const_iterator begin() const { return data_.get(); }
const_iterator cbegin() const { return data_.get(); }
iterator end() { return data_.get() + size_; }
const_iterator end() const { return data_.get() + size_; }
const_iterator cend() const { return data_.get() + size_; }
reference front() { return data_[0]; }
const_reference front() const { return data_[0]; }
reference back() { return data_[size_ - 1]; }
const_reference back() const { return data_[size_ - 1]; }
private:
std::unique_ptr<T[]> data_;
size_type size_;
};
} // namespace micro
} // namespace tvm
#endif // TVM_RUNTIME_MICRO_STANDALONE_MINIMAL_VECTOR_H_
| https://github.com/zk-ml/tachikoma |
src/runtime/minrpc/minrpc_interfaces.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#ifndef TVM_RUNTIME_MINRPC_MINRPC_INTERFACES_H_
#define TVM_RUNTIME_MINRPC_MINRPC_INTERFACES_H_
#include <tvm/runtime/c_runtime_api.h>
#include "rpc_reference.h"
namespace tvm {
namespace runtime {
/*!
* \brief Return interface used in ExecInterface to generate and send the responses.
*/
class MinRPCReturnInterface {
public:
virtual ~MinRPCReturnInterface() {}
/*! * \brief sends a response to the client with kTVMNullptr in payload. */
virtual void ReturnVoid() = 0;
/*! * \brief sends a response to the client with one kTVMOpaqueHandle in payload. */
virtual void ReturnHandle(void* handle) = 0;
/*! * \brief sends an exception response to the client with a kTVMStr in payload. */
virtual void ReturnException(const char* msg) = 0;
/*! * \brief sends a packed argument sequnce to the client. */
virtual void ReturnPackedSeq(const TVMValue* arg_values, const int* type_codes, int num_args) = 0;
/*! * \brief sends a copy of the requested remote data to the client. */
virtual void ReturnCopyFromRemote(uint8_t* data_ptr, uint64_t num_bytes) = 0;
/*! * \brief sends an exception response to the client with the last TVM erros as the message. */
virtual void ReturnLastTVMError() = 0;
/*! * \brief internal error. */
virtual void ThrowError(RPCServerStatus code, RPCCode info = RPCCode::kNone) = 0;
};
/*!
* \brief Execute interface used in MinRPCServer to process different received commands
*/
class MinRPCExecInterface {
public:
virtual ~MinRPCExecInterface() {}
/*! * \brief Execute an Initilize server command. */
virtual void InitServer(int num_args) = 0;
/*! * \brief calls a function specified by the call_handle. */
virtual void NormalCallFunc(uint64_t call_handle, TVMValue* values, int* tcodes,
int num_args) = 0;
/*! * \brief Execute a copy from remote command by sending the data described in arr to the client
*/
virtual void CopyFromRemote(DLTensor* arr, uint64_t num_bytes, uint8_t* data_ptr) = 0;
/*! * \brief Execute a copy to remote command by receiving the data described in arr from the
* client */
virtual int CopyToRemote(DLTensor* arr, uint64_t num_bytes, uint8_t* data_ptr) = 0;
/*! * \brief calls a system function specified by the code. */
virtual void SysCallFunc(RPCCode code, TVMValue* values, int* tcodes, int num_args) = 0;
/*! * \brief internal error. */
virtual void ThrowError(RPCServerStatus code, RPCCode info = RPCCode::kNone) = 0;
/*! * \brief return the ReturnInterface pointer that is used to generate and send the responses.
*/
virtual MinRPCReturnInterface* GetReturnInterface() = 0;
};
} // namespace runtime
} // namespace tvm
#endif // TVM_RUNTIME_MINRPC_MINRPC_INTERFACES_H_
| https://github.com/zk-ml/tachikoma |
src/runtime/minrpc/minrpc_logger.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#ifndef TVM_RUNTIME_MINRPC_MINRPC_LOGGER_H_
#define TVM_RUNTIME_MINRPC_MINRPC_LOGGER_H_
#include <tvm/runtime/c_runtime_api.h>
#include <functional>
#include <sstream>
#include <string>
#include <unordered_map>
#include "minrpc_interfaces.h"
#include "rpc_reference.h"
namespace tvm {
namespace runtime {
#define PRINT_BYTES false
/*!
* \brief Generates a user readeable log on the console
*/
class Logger {
public:
Logger() {}
/*!
* \brief this function logs a string
*
* \param s the string to be logged.
*/
void Log(const char* s) { os_ << s; }
void Log(std::string s) { os_ << s; }
/*!
* \brief this function logs a numerical value
*
* \param desc adds any necessary description before the value.
* \param val is the value to be logged.
*/
template <typename T>
void LogValue(const char* desc, T val) {
os_ << desc << val;
}
/*!
* \brief this function logs the properties of a DLDevice
*
* \param desc adds any necessary description before the DLDevice.
* \param dev is the pointer to the DLDevice to be logged.
*/
void LogDLDevice(const char* desc, DLDevice* dev) {
os_ << desc << "(" << dev->device_type << "," << dev->device_id << ")";
}
/*!
* \brief this function logs the properties of a DLDataType
*
* \param desc adds any necessary description before the DLDataType.
* \param data is the pointer to the DLDataType to be logged.
*/
void LogDLData(const char* desc, DLDataType* data) {
os_ << desc << "(" << (uint16_t)data->code << "," << (uint16_t)data->bits << "," << data->lanes
<< ")";
}
/*!
* \brief this function logs a handle name.
*
* \param name is the name to be logged.
*/
void LogHandleName(std::string name) {
if (name.length() > 0) {
os_ << " <" << name.c_str() << ">";
}
}
/*!
* \brief this function logs a TVMValue based on its type.
*
* \param tcode the type_code of the value stored in TVMValue.
* \param value is the TVMValue to be logged.
*/
void LogTVMValue(int tcode, TVMValue value);
/*!
* \brief this function output the log to the console.
*/
void OutputLog();
private:
std::stringstream os_;
};
/*!
* \brief A wrapper for a MinRPCReturns object, that also logs the responses.
*
* \param next underlying MinRPCReturns that generates the responses.
*/
class MinRPCReturnsWithLog : public MinRPCReturnInterface {
public:
/*!
* \brief Constructor.
* \param io The IO handler.
*/
MinRPCReturnsWithLog(MinRPCReturnInterface* next, Logger* logger)
: next_(next), logger_(logger) {}
~MinRPCReturnsWithLog() {}
void ReturnVoid();
void ReturnHandle(void* handle);
void ReturnException(const char* msg);
void ReturnPackedSeq(const TVMValue* arg_values, const int* type_codes, int num_args);
void ReturnCopyFromRemote(uint8_t* data_ptr, uint64_t num_bytes);
void ReturnLastTVMError();
void ThrowError(RPCServerStatus code, RPCCode info = RPCCode::kNone);
/*!
* \brief this function logs a list of TVMValues, and registers handle_name when needed.
*
* \param values is the list of TVMValues.
* \param tcodes is the list type_code of the TVMValues.
* \param num_args is the number of items in the list.
*/
void ProcessValues(const TVMValue* values, const int* tcodes, int num_args);
/*!
* \brief this function is called when a new command is executed.
* It clears the handle_name_ and records the command code.
*
* \param code the RPC command code.
*/
void ResetHandleName(RPCCode code);
/*!
* \brief appends name to the handle_name_.
*
* \param name handle name.
*/
void UpdateHandleName(const char* name);
/*!
* \brief get the stored handle description.
*
* \param handle the handle to get the description for.
*/
void GetHandleName(void* handle);
/*!
* \brief remove the handle description from handle_descriptions_.
*
* \param handle the handle to remove the description for.
*/
void ReleaseHandleName(void* handle);
private:
/*!
* \brief add the handle description to handle_descriptions_.
*
* \param handle the handle to add the description for.
*/
void RegisterHandleName(void* handle);
MinRPCReturnInterface* next_;
std::string handle_name_;
std::unordered_map<void*, std::string> handle_descriptions_;
RPCCode code_;
Logger* logger_;
};
/*!
* \brief A wrapper for a MinRPCExecute object, that also logs the responses.
*
* \param next: underlying MinRPCExecute that processes the packets.
*/
class MinRPCExecuteWithLog : public MinRPCExecInterface {
public:
MinRPCExecuteWithLog(MinRPCExecInterface* next, Logger* logger) : next_(next), logger_(logger) {
ret_handler_ = reinterpret_cast<MinRPCReturnsWithLog*>(next_->GetReturnInterface());
}
~MinRPCExecuteWithLog() {}
void InitServer(int num_args);
void NormalCallFunc(uint64_t call_handle, TVMValue* values, int* tcodes, int num_args);
void CopyFromRemote(DLTensor* arr, uint64_t num_bytes, uint8_t* temp_data);
int CopyToRemote(DLTensor* arr, uint64_t _num_bytes, uint8_t* _data_ptr);
void SysCallFunc(RPCCode code, TVMValue* values, int* tcodes, int num_args);
void ThrowError(RPCServerStatus code, RPCCode info = RPCCode::kNone);
MinRPCReturnInterface* GetReturnInterface() { return next_->GetReturnInterface(); }
private:
/*!
* \brief this function logs a list of TVMValues, and updates handle_name when needed.
*
* \param values is the list of TVMValues.
* \param tcodes is the list type_code of the TVMValues.
* \param num_args is the number of items in the list.
*/
void ProcessValues(TVMValue* values, int* tcodes, int num_args);
/*!
* \brief this function is called when a new command is executed.
*
* \param code the RPC command code.
*/
void SetRPCCode(RPCCode code);
MinRPCExecInterface* next_;
MinRPCReturnsWithLog* ret_handler_;
Logger* logger_;
};
/*!
* \brief A No-operation MinRPCReturns used within the MinRPCSniffer
*
* \tparam TIOHandler* IO provider to provide io handling.
*/
template <typename TIOHandler>
class MinRPCReturnsNoOp : public MinRPCReturnInterface {
public:
/*!
* \brief Constructor.
* \param io The IO handler.
*/
explicit MinRPCReturnsNoOp(TIOHandler* io) : io_(io) {}
~MinRPCReturnsNoOp() {}
void ReturnVoid() {}
void ReturnHandle(void* handle) {}
void ReturnException(const char* msg) {}
void ReturnPackedSeq(const TVMValue* arg_values, const int* type_codes, int num_args) {}
void ReturnCopyFromRemote(uint8_t* data_ptr, uint64_t num_bytes) {}
void ReturnLastTVMError() {}
void ThrowError(RPCServerStatus code, RPCCode info) {}
private:
TIOHandler* io_;
};
/*!
* \brief A No-operation MinRPCExecute used within the MinRPCSniffer
*
* \tparam ReturnInterface* ReturnInterface pointer to generate and send the responses.
*/
class MinRPCExecuteNoOp : public MinRPCExecInterface {
public:
explicit MinRPCExecuteNoOp(MinRPCReturnInterface* ret_handler) : ret_handler_(ret_handler) {}
~MinRPCExecuteNoOp() {}
void InitServer(int _num_args) {}
void NormalCallFunc(uint64_t call_handle, TVMValue* values, int* tcodes, int num_args) {}
void CopyFromRemote(DLTensor* arr, uint64_t num_bytes, uint8_t* temp_data) {}
int CopyToRemote(DLTensor* arr, uint64_t num_bytes, uint8_t* data_ptr) { return 1; }
void SysCallFunc(RPCCode code, TVMValue* values, int* tcodes, int num_args) {}
void ThrowError(RPCServerStatus code, RPCCode info) {}
MinRPCReturnInterface* GetReturnInterface() { return ret_handler_; }
private:
MinRPCReturnInterface* ret_handler_;
};
} // namespace runtime
} // namespace tvm
#endif // TVM_RUNTIME_MINRPC_MINRPC_LOGGER_H_"
| https://github.com/zk-ml/tachikoma |
src/runtime/minrpc/minrpc_server.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* \file minrpc_server.h
* \brief Minimum RPC server implementation,
* redirects all the calls to C runtime API.
*
* \note This file do not depend on c++ std or c std,
* and only depends on TVM's C runtime API.
*/
#ifndef TVM_RUNTIME_MINRPC_MINRPC_SERVER_H_
#define TVM_RUNTIME_MINRPC_MINRPC_SERVER_H_
#ifndef DMLC_LITTLE_ENDIAN
#define DMLC_LITTLE_ENDIAN 1
#endif
#include <string.h>
#include <tvm/runtime/c_runtime_api.h>
#include <memory>
#include <utility>
#include "../../support/generic_arena.h"
#include "minrpc_interfaces.h"
#include "rpc_reference.h"
#ifndef MINRPC_CHECK
#define MINRPC_CHECK(cond) \
if (!(cond)) this->ThrowError(RPCServerStatus::kCheckError);
#endif
namespace tvm {
namespace runtime {
namespace detail {
template <typename TIOHandler>
class PageAllocator;
}
/*!
* \brief Responses to a minimum RPC command.
*
* \tparam TIOHandler IO provider to provide io handling.
*/
template <typename TIOHandler>
class MinRPCReturns : public MinRPCReturnInterface {
public:
/*!
* \brief Constructor.
* \param io The IO handler.
*/
explicit MinRPCReturns(TIOHandler* io) : io_(io) {}
void ReturnVoid() {
int32_t num_args = 1;
int32_t tcode = kTVMNullptr;
RPCCode code = RPCCode::kReturn;
uint64_t packet_nbytes = sizeof(code) + sizeof(num_args) + sizeof(tcode);
io_->MessageStart(packet_nbytes);
Write(packet_nbytes);
Write(code);
Write(num_args);
Write(tcode);
io_->MessageDone();
}
void ReturnHandle(void* handle) {
int32_t num_args = 1;
int32_t tcode = kTVMOpaqueHandle;
RPCCode code = RPCCode::kReturn;
uint64_t encode_handle = reinterpret_cast<uint64_t>(handle);
uint64_t packet_nbytes =
sizeof(code) + sizeof(num_args) + sizeof(tcode) + sizeof(encode_handle);
io_->MessageStart(packet_nbytes);
Write(packet_nbytes);
Write(code);
Write(num_args);
Write(tcode);
Write(encode_handle);
io_->MessageDone();
}
void ReturnException(const char* msg) { RPCReference::ReturnException(msg, this); }
void ReturnPackedSeq(const TVMValue* arg_values, const int* type_codes, int num_args) {
RPCReference::ReturnPackedSeq(arg_values, type_codes, num_args, this);
}
void ReturnCopyFromRemote(uint8_t* data_ptr, uint64_t num_bytes) {
RPCCode code = RPCCode::kCopyAck;
uint64_t packet_nbytes = sizeof(code) + num_bytes;
io_->MessageStart(packet_nbytes);
Write(packet_nbytes);
Write(code);
WriteArray(data_ptr, num_bytes);
io_->MessageDone();
}
void ReturnLastTVMError() {
const char* err = TVMGetLastError();
ReturnException(err);
}
void MessageStart(uint64_t packet_nbytes) { io_->MessageStart(packet_nbytes); }
void MessageDone() { io_->MessageDone(); }
void ThrowError(RPCServerStatus code, RPCCode info = RPCCode::kNone) {
io_->Exit(static_cast<int>(code));
}
template <typename T>
void Write(const T& data) {
static_assert(std::is_trivial<T>::value && std::is_standard_layout<T>::value,
"need to be trival");
return WriteRawBytes(&data, sizeof(T));
}
template <typename T>
void WriteArray(T* data, size_t count) {
static_assert(std::is_trivial<T>::value && std::is_standard_layout<T>::value,
"need to be trival");
return WriteRawBytes(data, sizeof(T) * count);
}
private:
void WriteRawBytes(const void* data, size_t size) {
const uint8_t* buf = static_cast<const uint8_t*>(data);
size_t ndone = 0;
while (ndone < size) {
ssize_t ret = io_->PosixWrite(buf, size - ndone);
if (ret <= 0) {
this->ThrowError(RPCServerStatus::kWriteError);
}
buf += ret;
ndone += ret;
}
}
TIOHandler* io_;
};
/*!
* \brief Executing a minimum RPC command.
*
* \tparam TIOHandler IO provider to provide io handling.
* \tparam MinRPCReturnInterface* handles response generatation and transmission.
*/
template <typename TIOHandler>
class MinRPCExecute : public MinRPCExecInterface {
public:
MinRPCExecute(TIOHandler* io, MinRPCReturnInterface* ret_handler)
: io_(io), ret_handler_(ret_handler) {}
void InitServer(int num_args) {
MINRPC_CHECK(num_args == 0);
ret_handler_->ReturnVoid();
}
void NormalCallFunc(uint64_t call_handle, TVMValue* values, int* tcodes, int num_args) {
TVMValue ret_value[3];
int ret_tcode[3];
int call_ecode = TVMFuncCall(reinterpret_cast<void*>(call_handle), values, tcodes, num_args,
&(ret_value[1]), &(ret_tcode[1]));
if (call_ecode == 0) {
// Return value encoding as in LocalSession
int rv_tcode = ret_tcode[1];
ret_tcode[0] = kDLInt;
ret_value[0].v_int64 = rv_tcode;
if (rv_tcode == kTVMNDArrayHandle) {
ret_tcode[1] = kTVMDLTensorHandle;
ret_value[2].v_handle = ret_value[1].v_handle;
ret_tcode[2] = kTVMOpaqueHandle;
ret_handler_->ReturnPackedSeq(ret_value, ret_tcode, 3);
} else if (rv_tcode == kTVMBytes) {
ret_tcode[1] = kTVMBytes;
ret_handler_->ReturnPackedSeq(ret_value, ret_tcode, 2);
TVMByteArrayFree(reinterpret_cast<TVMByteArray*>(ret_value[1].v_handle)); // NOLINT(*)
} else if (rv_tcode == kTVMPackedFuncHandle || rv_tcode == kTVMModuleHandle) {
ret_tcode[1] = kTVMOpaqueHandle;
ret_handler_->ReturnPackedSeq(ret_value, ret_tcode, 2);
} else {
ret_handler_->ReturnPackedSeq(ret_value, ret_tcode, 2);
}
} else {
ret_handler_->ReturnLastTVMError();
}
}
void CopyFromRemote(DLTensor* arr, uint64_t num_bytes, uint8_t* data_ptr) {
int call_ecode = 0;
if (arr->device.device_type != kDLCPU) {
DLTensor temp;
temp.data = static_cast<void*>(data_ptr);
temp.device = DLDevice{kDLCPU, 0};
temp.ndim = arr->ndim;
temp.dtype = arr->dtype;
temp.shape = arr->shape;
temp.strides = nullptr;
temp.byte_offset = 0;
call_ecode = TVMDeviceCopyDataFromTo(arr, &temp, nullptr);
// need sync to make sure that the copy is completed.
if (call_ecode == 0) {
call_ecode = TVMSynchronize(arr->device.device_type, arr->device.device_id, nullptr);
}
}
if (call_ecode == 0) {
ret_handler_->ReturnCopyFromRemote(data_ptr, num_bytes);
} else {
ret_handler_->ReturnLastTVMError();
}
}
int CopyToRemote(DLTensor* arr, uint64_t num_bytes, uint8_t* data_ptr) {
int call_ecode = 0;
int ret = ReadArray(data_ptr, num_bytes);
if (ret <= 0) return ret;
if (arr->device.device_type != kDLCPU) {
DLTensor temp;
temp.data = data_ptr;
temp.device = DLDevice{kDLCPU, 0};
temp.ndim = arr->ndim;
temp.dtype = arr->dtype;
temp.shape = arr->shape;
temp.strides = nullptr;
temp.byte_offset = 0;
call_ecode = TVMDeviceCopyDataFromTo(&temp, arr, nullptr);
// need sync to make sure that the copy is completed.
if (call_ecode == 0) {
call_ecode = TVMSynchronize(arr->device.device_type, arr->device.device_id, nullptr);
}
}
if (call_ecode == 0) {
ret_handler_->ReturnVoid();
} else {
ret_handler_->ReturnLastTVMError();
}
return 1;
}
void SysCallFunc(RPCCode code, TVMValue* values, int* tcodes, int num_args) {
switch (code) {
case RPCCode::kFreeHandle: {
SyscallFreeHandle(values, tcodes, num_args);
break;
}
case RPCCode::kGetGlobalFunc: {
SyscallGetGlobalFunc(values, tcodes, num_args);
break;
}
case RPCCode::kDevSetDevice: {
ret_handler_->ReturnException("SetDevice not supported");
break;
}
case RPCCode::kDevGetAttr: {
ret_handler_->ReturnException("GetAttr not supported");
break;
}
case RPCCode::kDevAllocData: {
SyscallDevAllocData(values, tcodes, num_args);
break;
}
case RPCCode::kDevAllocDataWithScope: {
SyscallDevAllocDataWithScope(values, tcodes, num_args);
break;
}
case RPCCode::kDevFreeData: {
SyscallDevFreeData(values, tcodes, num_args);
break;
}
case RPCCode::kDevCreateStream: {
SyscallDevCreateStream(values, tcodes, num_args);
break;
}
case RPCCode::kDevFreeStream: {
SyscallDevFreeStream(values, tcodes, num_args);
break;
}
case RPCCode::kDevStreamSync: {
SyscallDevStreamSync(values, tcodes, num_args);
break;
}
case RPCCode::kDevSetStream: {
SyscallDevSetStream(values, tcodes, num_args);
break;
}
case RPCCode::kCopyAmongRemote: {
SyscallCopyAmongRemote(values, tcodes, num_args);
break;
}
default: {
ret_handler_->ReturnException("Syscall not recognized");
break;
}
}
}
void SyscallFreeHandle(TVMValue* values, int* tcodes, int num_args) {
MINRPC_CHECK(num_args == 2);
MINRPC_CHECK(tcodes[0] == kTVMOpaqueHandle);
MINRPC_CHECK(tcodes[1] == kDLInt);
void* handle = values[0].v_handle;
int64_t type_code = values[1].v_int64;
int call_ecode;
if (type_code == kTVMNDArrayHandle) {
call_ecode = TVMArrayFree(static_cast<TVMArrayHandle>(handle));
} else if (type_code == kTVMPackedFuncHandle) {
call_ecode = TVMFuncFree(handle);
} else {
MINRPC_CHECK(type_code == kTVMModuleHandle);
call_ecode = TVMModFree(handle);
}
if (call_ecode == 0) {
ret_handler_->ReturnVoid();
} else {
ret_handler_->ReturnLastTVMError();
}
}
void SyscallGetGlobalFunc(TVMValue* values, int* tcodes, int num_args) {
MINRPC_CHECK(num_args == 1);
MINRPC_CHECK(tcodes[0] == kTVMStr);
void* handle;
int call_ecode = TVMFuncGetGlobal(values[0].v_str, &handle);
if (call_ecode == 0) {
ret_handler_->ReturnHandle(handle);
} else {
ret_handler_->ReturnLastTVMError();
}
}
void SyscallCopyAmongRemote(TVMValue* values, int* tcodes, int num_args) {
MINRPC_CHECK(num_args == 3);
// from dltensor
MINRPC_CHECK(tcodes[0] == kTVMDLTensorHandle);
// to dltensor
MINRPC_CHECK(tcodes[1] == kTVMDLTensorHandle);
// stream
MINRPC_CHECK(tcodes[2] == kTVMOpaqueHandle);
void* from = values[0].v_handle;
void* to = values[1].v_handle;
TVMStreamHandle stream = values[2].v_handle;
int call_ecode = TVMDeviceCopyDataFromTo(reinterpret_cast<DLTensor*>(from),
reinterpret_cast<DLTensor*>(to), stream);
if (call_ecode == 0) {
ret_handler_->ReturnVoid();
} else {
ret_handler_->ReturnLastTVMError();
}
}
void SyscallDevAllocData(TVMValue* values, int* tcodes, int num_args) {
MINRPC_CHECK(num_args == 4);
MINRPC_CHECK(tcodes[0] == kDLDevice);
MINRPC_CHECK(tcodes[1] == kDLInt);
MINRPC_CHECK(tcodes[2] == kDLInt);
MINRPC_CHECK(tcodes[3] == kTVMDataType);
DLDevice dev = values[0].v_device;
int64_t nbytes = values[1].v_int64;
int64_t alignment = values[2].v_int64;
DLDataType type_hint = values[3].v_type;
void* handle;
int call_ecode = TVMDeviceAllocDataSpace(dev, nbytes, alignment, type_hint, &handle);
if (call_ecode == 0) {
ret_handler_->ReturnHandle(handle);
} else {
ret_handler_->ReturnLastTVMError();
}
}
void SyscallDevAllocDataWithScope(TVMValue* values, int* tcodes, int num_args) {
MINRPC_CHECK(num_args == 2);
MINRPC_CHECK(tcodes[0] == kTVMDLTensorHandle);
MINRPC_CHECK(tcodes[1] == kTVMNullptr || tcodes[1] == kTVMStr);
DLTensor* arr = static_cast<DLTensor*>(values[0].v_handle);
const char* mem_scope = (tcodes[1] == kTVMNullptr ? nullptr : values[1].v_str);
void* handle;
int call_ecode = TVMDeviceAllocDataSpaceWithScope(arr->device, arr->ndim, arr->shape,
arr->dtype, mem_scope, &handle);
if (call_ecode == 0) {
ret_handler_->ReturnHandle(handle);
} else {
ret_handler_->ReturnLastTVMError();
}
}
void SyscallDevFreeData(TVMValue* values, int* tcodes, int num_args) {
MINRPC_CHECK(num_args == 2);
MINRPC_CHECK(tcodes[0] == kDLDevice);
MINRPC_CHECK(tcodes[1] == kTVMOpaqueHandle);
DLDevice dev = values[0].v_device;
void* handle = values[1].v_handle;
int call_ecode = TVMDeviceFreeDataSpace(dev, handle);
if (call_ecode == 0) {
ret_handler_->ReturnVoid();
} else {
ret_handler_->ReturnLastTVMError();
}
}
void SyscallDevCreateStream(TVMValue* values, int* tcodes, int num_args) {
MINRPC_CHECK(num_args == 1);
MINRPC_CHECK(tcodes[0] == kDLDevice);
DLDevice dev = values[0].v_device;
void* handle;
int call_ecode = TVMStreamCreate(dev.device_type, dev.device_id, &handle);
if (call_ecode == 0) {
ret_handler_->ReturnHandle(handle);
} else {
ret_handler_->ReturnLastTVMError();
}
}
void SyscallDevFreeStream(TVMValue* values, int* tcodes, int num_args) {
MINRPC_CHECK(num_args == 2);
MINRPC_CHECK(tcodes[0] == kDLDevice);
MINRPC_CHECK(tcodes[1] == kTVMOpaqueHandle);
DLDevice dev = values[0].v_device;
void* handle = values[1].v_handle;
int call_ecode = TVMStreamFree(dev.device_type, dev.device_id, handle);
if (call_ecode == 0) {
ret_handler_->ReturnVoid();
} else {
ret_handler_->ReturnLastTVMError();
}
}
void SyscallDevStreamSync(TVMValue* values, int* tcodes, int num_args) {
MINRPC_CHECK(num_args == 2);
MINRPC_CHECK(tcodes[0] == kDLDevice);
MINRPC_CHECK(tcodes[1] == kTVMOpaqueHandle);
DLDevice dev = values[0].v_device;
void* handle = values[1].v_handle;
int call_ecode = TVMSynchronize(dev.device_type, dev.device_id, handle);
if (call_ecode == 0) {
ret_handler_->ReturnVoid();
} else {
ret_handler_->ReturnLastTVMError();
}
}
void SyscallDevSetStream(TVMValue* values, int* tcodes, int num_args) {
MINRPC_CHECK(num_args == 2);
MINRPC_CHECK(tcodes[0] == kDLDevice);
MINRPC_CHECK(tcodes[1] == kTVMOpaqueHandle);
DLDevice dev = values[0].v_device;
void* handle = values[1].v_handle;
int call_ecode = TVMSetStream(dev.device_type, dev.device_id, handle);
if (call_ecode == 0) {
ret_handler_->ReturnVoid();
} else {
ret_handler_->ReturnLastTVMError();
}
}
void ThrowError(RPCServerStatus code, RPCCode info = RPCCode::kNone) {
ret_handler_->ThrowError(code, info);
}
MinRPCReturnInterface* GetReturnInterface() { return ret_handler_; }
private:
template <typename T>
int ReadArray(T* data, size_t count) {
static_assert(std::is_trivial<T>::value && std::is_standard_layout<T>::value,
"need to be trival");
return ReadRawBytes(data, sizeof(T) * count);
}
int ReadRawBytes(void* data, size_t size) {
uint8_t* buf = static_cast<uint8_t*>(data);
size_t ndone = 0;
while (ndone < size) {
ssize_t ret = io_->PosixRead(buf, size - ndone);
if (ret <= 0) return ret;
ndone += ret;
buf += ret;
}
return 1;
}
TIOHandler* io_;
MinRPCReturnInterface* ret_handler_;
};
/*!
* \brief A minimum RPC server that only depends on the tvm C runtime..
*
* All the dependencies are provided by the io arguments.
*
* \tparam TIOHandler IO provider to provide io handling.
* An IOHandler needs to provide the following functions:
* - PosixWrite, PosixRead, Close: posix style, read, write, close API.
* - MessageStart(num_bytes), MessageDone(): framing APIs.
* - Exit: exit with status code.
*/
template <typename TIOHandler, template <typename> class Allocator = detail::PageAllocator>
class MinRPCServer {
public:
using PageAllocator = Allocator<TIOHandler>;
/*!
* \brief Constructor.
* \param io The IO handler.
*/
MinRPCServer(TIOHandler* io, std::unique_ptr<MinRPCExecInterface>&& exec_handler)
: io_(io), arena_(PageAllocator(io_)), exec_handler_(std::move(exec_handler)) {}
explicit MinRPCServer(TIOHandler* io)
: io_(io),
arena_(PageAllocator(io)),
ret_handler_(new MinRPCReturns<TIOHandler>(io_)),
exec_handler_(std::unique_ptr<MinRPCExecInterface>(
new MinRPCExecute<TIOHandler>(io_, ret_handler_))) {}
~MinRPCServer() {
if (ret_handler_ != nullptr) {
delete ret_handler_;
}
}
/*! \brief Process a single request.
*
* \return true when the server should continue processing requests. false when it should be
* shutdown.
*/
bool ProcessOnePacket() {
RPCCode code;
uint64_t packet_len;
arena_.RecycleAll();
allow_clean_shutdown_ = true;
Read(&packet_len);
if (packet_len == 0) return true;
Read(&code);
allow_clean_shutdown_ = false;
if (code >= RPCCode::kSyscallCodeStart) {
HandleSyscallFunc(code);
} else {
switch (code) {
case RPCCode::kCallFunc: {
HandleNormalCallFunc();
break;
}
case RPCCode::kInitServer: {
HandleInitServer();
break;
}
case RPCCode::kCopyFromRemote: {
HandleCopyFromRemote();
break;
}
case RPCCode::kCopyToRemote: {
HandleCopyToRemote();
break;
}
case RPCCode::kShutdown: {
Shutdown();
return false;
}
default: {
this->ThrowError(RPCServerStatus::kUnknownRPCCode);
break;
}
}
}
return true;
}
void HandleInitServer() {
uint64_t len;
Read(&len);
char* proto_ver = ArenaAlloc<char>(len + 1);
ReadArray(proto_ver, len);
TVMValue* values;
int* tcodes;
int num_args;
RecvPackedSeq(&values, &tcodes, &num_args);
exec_handler_->InitServer(num_args);
}
void Shutdown() {
arena_.FreeAll();
io_->Close();
}
void HandleNormalCallFunc() {
uint64_t call_handle;
TVMValue* values;
int* tcodes;
int num_args;
Read(&call_handle);
RecvPackedSeq(&values, &tcodes, &num_args);
exec_handler_->NormalCallFunc(call_handle, values, tcodes, num_args);
}
void HandleCopyFromRemote() {
DLTensor* arr = ArenaAlloc<DLTensor>(1);
uint64_t data_handle;
Read(&data_handle);
arr->data = reinterpret_cast<void*>(data_handle);
Read(&(arr->device));
Read(&(arr->ndim));
Read(&(arr->dtype));
arr->shape = ArenaAlloc<int64_t>(arr->ndim);
ReadArray(arr->shape, arr->ndim);
arr->strides = nullptr;
Read(&(arr->byte_offset));
uint64_t num_bytes;
Read(&num_bytes);
uint8_t* data_ptr;
if (arr->device.device_type == kDLCPU) {
data_ptr = reinterpret_cast<uint8_t*>(data_handle) + arr->byte_offset;
} else {
data_ptr = ArenaAlloc<uint8_t>(num_bytes);
}
exec_handler_->CopyFromRemote(arr, num_bytes, data_ptr);
}
void HandleCopyToRemote() {
DLTensor* arr = ArenaAlloc<DLTensor>(1);
uint64_t data_handle;
Read(&data_handle);
arr->data = reinterpret_cast<void*>(data_handle);
Read(&(arr->device));
Read(&(arr->ndim));
Read(&(arr->dtype));
arr->shape = ArenaAlloc<int64_t>(arr->ndim);
ReadArray(arr->shape, arr->ndim);
arr->strides = nullptr;
Read(&(arr->byte_offset));
uint64_t num_bytes;
Read(&num_bytes);
int ret;
if (arr->device.device_type == kDLCPU) {
uint8_t* dptr = reinterpret_cast<uint8_t*>(data_handle) + arr->byte_offset;
ret = exec_handler_->CopyToRemote(arr, num_bytes, dptr);
} else {
uint8_t* temp_data = ArenaAlloc<uint8_t>(num_bytes);
ret = exec_handler_->CopyToRemote(arr, num_bytes, temp_data);
}
if (ret == 0) {
if (allow_clean_shutdown_) {
Shutdown();
io_->Exit(0);
} else {
this->ThrowError(RPCServerStatus::kReadError);
}
}
if (ret == -1) {
this->ThrowError(RPCServerStatus::kReadError);
}
}
void HandleSyscallFunc(RPCCode code) {
TVMValue* values;
int* tcodes;
int num_args;
RecvPackedSeq(&values, &tcodes, &num_args);
exec_handler_->SysCallFunc(code, values, tcodes, num_args);
}
void ThrowError(RPCServerStatus code, RPCCode info = RPCCode::kNone) {
io_->Exit(static_cast<int>(code));
}
template <typename T>
T* ArenaAlloc(int count) {
static_assert(std::is_trivial<T>::value && std::is_standard_layout<T>::value,
"need to be trival");
return arena_.template allocate_<T>(count);
}
template <typename T>
void Read(T* data) {
static_assert(std::is_trivial<T>::value && std::is_standard_layout<T>::value,
"need to be trival");
ReadRawBytes(data, sizeof(T));
}
template <typename T>
void ReadArray(T* data, size_t count) {
static_assert(std::is_trivial<T>::value && std::is_standard_layout<T>::value,
"need to be trival");
return ReadRawBytes(data, sizeof(T) * count);
}
private:
void RecvPackedSeq(TVMValue** out_values, int** out_tcodes, int* out_num_args) {
RPCReference::RecvPackedSeq(out_values, out_tcodes, out_num_args, this);
}
void ReadRawBytes(void* data, size_t size) {
uint8_t* buf = static_cast<uint8_t*>(data);
size_t ndone = 0;
while (ndone < size) {
ssize_t ret = io_->PosixRead(buf, size - ndone);
if (ret == 0) {
if (allow_clean_shutdown_) {
Shutdown();
io_->Exit(0);
} else {
this->ThrowError(RPCServerStatus::kReadError);
}
}
if (ret == -1) {
this->ThrowError(RPCServerStatus::kReadError);
}
ndone += ret;
buf += ret;
}
}
/*! \brief IO handler. */
TIOHandler* io_;
/*! \brief internal arena. */
support::GenericArena<PageAllocator> arena_;
MinRPCReturns<TIOHandler>* ret_handler_ = nullptr;
std::unique_ptr<MinRPCExecInterface> exec_handler_;
/*! \brief Whether we are in a state that allows clean shutdown. */
bool allow_clean_shutdown_{true};
static_assert(DMLC_LITTLE_ENDIAN == 1, "MinRPC only works on little endian.");
};
namespace detail {
// Internal allocator that redirects alloc to TVM's C API.
template <typename TIOHandler>
class PageAllocator {
public:
using ArenaPageHeader = tvm::support::ArenaPageHeader;
explicit PageAllocator(TIOHandler* io) : io_(io) {}
ArenaPageHeader* allocate(size_t min_size) {
size_t npages = ((min_size + kPageSize - 1) / kPageSize);
void* data;
if (TVMDeviceAllocDataSpace(DLDevice{kDLCPU, 0}, npages * kPageSize, kPageAlign,
DLDataType{kDLInt, 1, 1}, &data) != 0) {
io_->Exit(static_cast<int>(RPCServerStatus::kAllocError));
}
ArenaPageHeader* header = static_cast<ArenaPageHeader*>(data);
header->size = npages * kPageSize;
header->offset = sizeof(ArenaPageHeader);
return header;
}
void deallocate(ArenaPageHeader* page) {
if (TVMDeviceFreeDataSpace(DLDevice{kDLCPU, 0}, page) != 0) {
io_->Exit(static_cast<int>(RPCServerStatus::kAllocError));
}
}
static const constexpr int kPageSize = 2 << 10;
static const constexpr int kPageAlign = 8;
private:
TIOHandler* io_;
};
} // namespace detail
} // namespace runtime
} // namespace tvm
#endif // TVM_RUNTIME_MINRPC_MINRPC_SERVER_H_
| https://github.com/zk-ml/tachikoma |
src/runtime/minrpc/minrpc_server_logging.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#ifndef TVM_RUNTIME_MINRPC_MINRPC_SERVER_LOGGING_H_
#define TVM_RUNTIME_MINRPC_MINRPC_SERVER_LOGGING_H_
#include <memory>
#include <utility>
#include "minrpc_logger.h"
#include "minrpc_server.h"
namespace tvm {
namespace runtime {
/*!
* \brief A minimum RPC server that logs the received commands.
*
* \tparam TIOHandler IO provider to provide io handling.
*/
template <typename TIOHandler>
class MinRPCServerWithLog {
public:
explicit MinRPCServerWithLog(TIOHandler* io)
: ret_handler_(io),
ret_handler_wlog_(&ret_handler_, &logger_),
exec_handler_(io, &ret_handler_wlog_),
exec_handler_ptr_(new MinRPCExecuteWithLog(&exec_handler_, &logger_)),
next_(io, std::move(exec_handler_ptr_)) {}
bool ProcessOnePacket() { return next_.ProcessOnePacket(); }
private:
Logger logger_;
MinRPCReturns<TIOHandler> ret_handler_;
MinRPCExecute<TIOHandler> exec_handler_;
MinRPCReturnsWithLog ret_handler_wlog_;
std::unique_ptr<MinRPCExecuteWithLog> exec_handler_ptr_;
MinRPCServer<TIOHandler> next_;
};
/*!
* \brief A minimum RPC server that only logs the outgoing commands and received responses.
* (Does not process the packets or respond to them.)
*
* \tparam TIOHandler IO provider to provide io handling.
*/
template <typename TIOHandler, template <typename> class Allocator = detail::PageAllocator>
class MinRPCSniffer {
public:
using PageAllocator = Allocator<TIOHandler>;
explicit MinRPCSniffer(TIOHandler* io)
: io_(io),
arena_(PageAllocator(io_)),
ret_handler_(io_),
ret_handler_wlog_(&ret_handler_, &logger_),
exec_handler_(&ret_handler_wlog_),
exec_handler_ptr_(new MinRPCExecuteWithLog(&exec_handler_, &logger_)),
next_(io_, std::move(exec_handler_ptr_)) {}
bool ProcessOnePacket() { return next_.ProcessOnePacket(); }
void ProcessOneResponse() {
RPCCode code;
uint64_t packet_len = 0;
if (!Read(&packet_len)) return;
if (packet_len == 0) {
OutputLog();
return;
}
if (!Read(&code)) return;
switch (code) {
case RPCCode::kReturn: {
int32_t num_args;
int* type_codes;
TVMValue* values;
RPCReference::RecvPackedSeq(&values, &type_codes, &num_args, this);
ret_handler_wlog_.ReturnPackedSeq(values, type_codes, num_args);
break;
}
case RPCCode::kException: {
ret_handler_wlog_.ReturnException("");
break;
}
default: {
OutputLog();
break;
}
}
}
void OutputLog() { logger_.OutputLog(); }
void ThrowError(RPCServerStatus code, RPCCode info = RPCCode::kNone) {
logger_.Log("-> ");
logger_.Log(RPCServerStatusToString(code));
OutputLog();
}
template <typename T>
T* ArenaAlloc(int count) {
static_assert(std::is_trivial<T>::value && std::is_standard_layout<T>::value,
"need to be trival");
return arena_.template allocate_<T>(count);
}
template <typename T>
bool Read(T* data) {
static_assert(std::is_trivial<T>::value && std::is_standard_layout<T>::value,
"need to be trival");
return ReadRawBytes(data, sizeof(T));
}
template <typename T>
bool ReadArray(T* data, size_t count) {
static_assert(std::is_trivial<T>::value && std::is_standard_layout<T>::value,
"need to be trival");
return ReadRawBytes(data, sizeof(T) * count);
}
private:
bool ReadRawBytes(void* data, size_t size) {
uint8_t* buf = reinterpret_cast<uint8_t*>(data);
size_t ndone = 0;
while (ndone < size) {
ssize_t ret = io_->PosixRead(buf, size - ndone);
if (ret <= 0) {
this->ThrowError(RPCServerStatus::kReadError);
return false;
}
ndone += ret;
buf += ret;
}
return true;
}
Logger logger_;
TIOHandler* io_;
support::GenericArena<PageAllocator> arena_;
MinRPCReturnsNoOp<TIOHandler> ret_handler_;
MinRPCReturnsWithLog ret_handler_wlog_;
MinRPCExecuteNoOp exec_handler_;
std::unique_ptr<MinRPCExecuteWithLog> exec_handler_ptr_;
MinRPCServer<TIOHandler> next_;
};
} // namespace runtime
} // namespace tvm
#endif // TVM_RUNTIME_MINRPC_MINRPC_SERVER_LOGGING_H_
| https://github.com/zk-ml/tachikoma |
src/runtime/minrpc/rpc_reference.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* \file rpc_reference.h
* \brief Common header defining the communication code used in the RPC protocol.
*/
#ifndef TVM_RUNTIME_MINRPC_RPC_REFERENCE_H_
#define TVM_RUNTIME_MINRPC_RPC_REFERENCE_H_
namespace tvm {
namespace runtime {
/*! \brief The current RPC procotol version. */
constexpr const char* kRPCProtocolVer = "0.8.0";
// When tvm.rpc.server.GetCRTMaxPacketSize global function is not registered.
const uint64_t kRPCMaxTransferSizeBytesDefault = UINT64_MAX;
/*! \brief The RPC code */
enum class RPCCode : int {
kNone,
kShutdown,
kInitServer,
kCallFunc,
kReturn,
kException,
kCopyFromRemote,
kCopyToRemote,
kCopyAck,
// The following are syscall code that can send over CallRemote
kSyscallCodeStart,
kGetGlobalFunc = kSyscallCodeStart,
kFreeHandle,
kDevSetDevice,
kDevGetAttr,
kDevAllocData,
kDevFreeData,
kDevStreamSync,
kCopyAmongRemote,
kDevAllocDataWithScope,
kDevCreateStream,
kDevFreeStream,
kDevSetStream,
};
/*!
* \brief List of potential error status during rpc communication.
*/
enum class RPCServerStatus : int {
kSuccess = 0,
kInvalidTypeCodeObject,
kInvalidTypeCodeNDArray,
kInvalidDLTensorFieldStride,
kInvalidDLTensorFieldByteOffset,
kUnknownTypeCode,
kUnknownRPCCode,
kRPCCodeNotSupported,
kUnknownRPCSyscall,
kCheckError,
kReadError,
kWriteError,
kAllocError
};
inline const char* RPCCodeToString(RPCCode code) {
switch (code) {
case RPCCode::kShutdown:
return "kShutdown";
case RPCCode::kInitServer:
return "kInitServer";
case RPCCode::kCallFunc:
return "kCallFunc";
case RPCCode::kReturn:
return "kReturn";
case RPCCode::kException:
return "kException";
case RPCCode::kCopyFromRemote:
return "kCopyFromRemote";
case RPCCode::kCopyToRemote:
return "kCopyToRemote";
case RPCCode::kCopyAck:
return "kCopyAck";
// The following are syscall code that can send over CallRemote
case RPCCode::kGetGlobalFunc:
return "kGetGlobalFunc";
case RPCCode::kFreeHandle:
return "kFreeHandle";
case RPCCode::kDevSetDevice:
return "kDevSetDevice";
case RPCCode::kDevGetAttr:
return "kDevGetAttr";
case RPCCode::kDevAllocData:
return "kDevAllocData";
case RPCCode::kDevFreeData:
return "kDevFreeData";
case RPCCode::kDevCreateStream:
return "kDevCreateStream";
case RPCCode::kDevFreeStream:
return "kDevFreeStream";
case RPCCode::kDevStreamSync:
return "kDevStreamSync";
case RPCCode::kDevSetStream:
return "kDevSetStream";
case RPCCode::kCopyAmongRemote:
return "kCopyAmongRemote";
case RPCCode::kDevAllocDataWithScope:
return "kDevAllocDataWithScope";
default:
return "";
}
}
/*!
* \brief Convert RPC server status to string.
* \param status The status.
* \return The corresponding string.
*/
inline const char* RPCServerStatusToString(RPCServerStatus status) {
switch (status) {
case RPCServerStatus::kSuccess:
return "kSuccess";
case RPCServerStatus::kInvalidTypeCodeObject:
return "kInvalidTypeCodeObject";
case RPCServerStatus::kInvalidTypeCodeNDArray:
return "kInvalidTypeCodeNDArray";
case RPCServerStatus::kInvalidDLTensorFieldStride:
return "kInvalidDLTensorFieldStride";
case RPCServerStatus::kInvalidDLTensorFieldByteOffset: {
return "kInvalidDLTensorFieldByteOffset";
}
case RPCServerStatus::kUnknownTypeCode:
return "kUnknownTypeCode";
case RPCServerStatus::kUnknownRPCCode:
return "kUnknownRPCCode";
case RPCServerStatus::kRPCCodeNotSupported:
return "RPCCodeNotSupported";
case RPCServerStatus::kUnknownRPCSyscall:
return "kUnknownRPCSyscall";
case RPCServerStatus::kCheckError:
return "kCheckError";
case RPCServerStatus::kReadError:
return "kReadError";
case RPCServerStatus::kWriteError:
return "kWriteError";
case RPCServerStatus::kAllocError:
return "kAllocError";
default:
return "";
}
}
/*!
* \brief Reference implementation of the communication protocol.
*
* \note The implementation is intentionally written via template
* so it can be used in a dependency free setting.
*
* \sa src/runtime/rpc/device/min_rpc_server.h
*/
struct RPCReference {
/*!
* \brief Auxiliary class to get the packed sequence.
* \tparam TChannel The channel to throw errror.
*/
template <typename TChannel>
struct PackedSeqNumBytesGetter {
public:
explicit PackedSeqNumBytesGetter(TChannel* channel) : channel_(channel) {}
template <typename T>
void Write(const T& value) {
num_bytes_ += sizeof(T);
}
template <typename T>
void WriteArray(const T* value, size_t num) {
num_bytes_ += sizeof(T) * num;
}
void ThrowError(RPCServerStatus status) { channel_->ThrowError(status); }
uint64_t num_bytes() const { return num_bytes_; }
private:
TChannel* channel_;
uint64_t num_bytes_{0};
};
/*!
* \return the length of the str.
* \param str the string.
* \return The length.
*/
static uint64_t StrLength(const char* str) {
uint64_t len = 0;
while (str[len] != '\0') ++len;
return len;
}
/*!
* \brief Get the total nbytes to be sent in the packed sequence.
*
* \param arg_values The values to be sent over.
* \param type_codes The type codes to be sent over.
* \param num_args Number of argument.
* \param client_mode Whether it is a client to server call.
* \param channel The communication channel handler.
* \tparam TChannel The type of the communication channel.
* \return The total number of bytes.
*/
template <typename TChannel>
static uint64_t PackedSeqGetNumBytes(const TVMValue* arg_values, const int* type_codes,
int num_args, bool client_mode, TChannel* channel) {
PackedSeqNumBytesGetter<TChannel> getter(channel);
SendPackedSeq(arg_values, type_codes, num_args, client_mode, &getter);
return getter.num_bytes();
}
template <typename TChannelPtr>
static void SendDLTensor(TChannelPtr channel, DLTensor* arr) {
DLDevice dev;
uint64_t data;
// When we return NDArray, we directly return
// the space and the context
// The client will be further wrapping
dev = arr->device;
data = reinterpret_cast<uint64_t>(arr->data);
channel->Write(data);
channel->Write(dev);
channel->Write(arr->ndim);
channel->Write(arr->dtype);
channel->WriteArray(arr->shape, arr->ndim);
if (arr->strides != nullptr) {
channel->ThrowError(RPCServerStatus::kInvalidDLTensorFieldStride);
}
channel->Write(arr->byte_offset);
return;
}
template <typename TChannelPtr>
static DLTensor* ReceiveDLTensor(TChannelPtr channel) {
uint64_t handle;
channel->Read(&handle);
DLTensor* arr = channel->template ArenaAlloc<DLTensor>(1);
DLTensor& tensor = *arr;
tensor.data = reinterpret_cast<void*>(handle);
channel->Read(&(tensor.device));
channel->Read(&(tensor.ndim));
channel->Read(&(tensor.dtype));
tensor.shape = channel->template ArenaAlloc<int64_t>(tensor.ndim);
channel->ReadArray(tensor.shape, tensor.ndim);
tensor.strides = nullptr;
channel->Read(&(tensor.byte_offset));
return arr;
}
/*!
* \brief Send packed argument sequnce to the other peer.
*
* This function serves as the foundational communication primitive between peers.
*
* TVMValue sequence encoding protocol(according to the type):
*
* - int/float/uint/bytes/str: Serialize all content.
* - DLTensor: send meta-data, send data handle as opaque handle(via uint64_t)
* - OpaqueHandle: send as uint64_t
* - ModuleHandle, PackedFuncHandle: send as uint64_t,
* The support to Module/PackedFuncHandle are reserved for arguments
* in the CallFunc from a client to server only.
* Note that we cannot simply take these argument out(as the handle)
* refers to a value on the remote(instead of local).
*
* \param arg_values The values to be sent over.
* \param type_codes The type codes to be sent over.
* \param num_args Number of argument.
* \param client_mode Whether it is a client to server call.
* \param channel The communication channel handler.
* \tparam TChannel The type of the communication channel.
*/
template <typename TChannel>
static void SendPackedSeq(const TVMValue* arg_values, const int* type_codes, int num_args,
bool client_mode, TChannel* channel) {
channel->Write(num_args);
channel->WriteArray(type_codes, num_args);
// Argument packing.
for (int i = 0; i < num_args; ++i) {
int tcode = type_codes[i];
TVMValue value = arg_values[i];
switch (tcode) {
case kDLInt:
case kDLUInt:
case kDLFloat: {
channel->template Write<int64_t>(value.v_int64);
break;
}
case kTVMDataType: {
channel->Write(value.v_type);
// padding
int32_t padding = 0;
channel->template Write<int32_t>(padding);
break;
}
case kDLDevice: {
channel->Write(value.v_device);
break;
}
case kTVMPackedFuncHandle:
case kTVMModuleHandle: {
if (!client_mode) {
channel->ThrowError(RPCServerStatus::kInvalidTypeCodeObject);
}
// always send handle in 64 bit.
uint64_t handle = reinterpret_cast<uint64_t>(value.v_handle);
channel->Write(handle);
break;
}
case kTVMOpaqueHandle: {
// always send handle in 64 bit.
uint64_t handle = reinterpret_cast<uint64_t>(value.v_handle);
channel->Write(handle);
break;
}
case kTVMNDArrayHandle: {
channel->ThrowError(RPCServerStatus::kInvalidTypeCodeNDArray);
break;
}
case kTVMDLTensorHandle: {
DLTensor* arr = static_cast<DLTensor*>(value.v_handle);
SendDLTensor(channel, arr);
break;
}
case kTVMNullptr:
break;
case kTVMStr: {
const char* s = value.v_str;
uint64_t len = StrLength(s);
channel->Write(len);
channel->WriteArray(s, len);
break;
}
case kTVMBytes: {
TVMByteArray* bytes = static_cast<TVMByteArray*>(arg_values[i].v_handle);
uint64_t len = bytes->size;
channel->Write(len);
channel->WriteArray(bytes->data, len);
break;
}
default: {
channel->ThrowError(RPCServerStatus::kUnknownTypeCode);
break;
}
}
}
}
/*!
* \brief Receive packed seq from the channel.
*
* \param out_arg_values The values to be received.
* \param out_tcodes The type codes to be received.
* \param out_num_args Number of argument.
* \param channel The communication channel handler.
* \tparam TChannel The type of the communication channel.
* \note The temporary space are populated via an arena inside channel.
*/
template <typename TChannel>
static void RecvPackedSeq(TVMValue** out_values, int** out_tcodes, int* out_num_args,
TChannel* channel) {
// receive number of args
int num_args;
channel->Read(&num_args);
*out_num_args = num_args;
if (num_args == 0) {
*out_values = nullptr;
*out_tcodes = nullptr;
return;
}
TVMValue* values = channel->template ArenaAlloc<TVMValue>(num_args);
int* tcodes = channel->template ArenaAlloc<int>(num_args);
*out_values = values;
*out_tcodes = tcodes;
// receive type code.
channel->ReadArray(tcodes, num_args);
// receive arguments
for (int i = 0; i < num_args; ++i) {
auto& value = values[i];
switch (tcodes[i]) {
case kDLInt:
case kDLUInt:
case kDLFloat: {
channel->template Read<int64_t>(&(value.v_int64));
break;
}
case kTVMDataType: {
channel->Read(&(value.v_type));
int32_t padding = 0;
channel->template Read<int32_t>(&padding);
break;
}
case kDLDevice: {
channel->Read(&(value.v_device));
break;
}
case kTVMPackedFuncHandle:
case kTVMModuleHandle:
case kTVMOpaqueHandle: {
// always send handle in 64 bit.
uint64_t handle;
channel->Read(&handle);
value.v_handle = reinterpret_cast<void*>(handle);
break;
}
case kTVMNullptr: {
value.v_handle = nullptr;
break;
}
case kTVMStr: {
uint64_t len;
channel->Read(&len);
char* str = channel->template ArenaAlloc<char>(len + 1);
str[len] = '\0';
channel->ReadArray(str, len);
value.v_str = str;
break;
}
case kTVMBytes: {
uint64_t len;
channel->Read(&len);
TVMByteArray* arr = channel->template ArenaAlloc<TVMByteArray>(1);
char* data = channel->template ArenaAlloc<char>(len);
arr->size = len;
arr->data = data;
channel->ReadArray(data, len);
value.v_handle = arr;
break;
}
case kTVMDLTensorHandle: {
value.v_handle = ReceiveDLTensor(channel);
break;
}
default: {
channel->ThrowError(RPCServerStatus::kUnknownTypeCode);
break;
}
}
}
}
/*!
* \brief Return an exception packet.
*
* \param msg The error message.
* \param channel The communication channel handler.
* \tparam TChannel The type of the communication channel.
*/
template <typename TChannel>
static void ReturnException(const char* msg, TChannel* channel) {
RPCCode code = RPCCode::kException;
int32_t num_args = 1;
int32_t tcode = kTVMStr;
uint64_t len = StrLength(msg);
uint64_t packet_nbytes = sizeof(code) + sizeof(num_args) + sizeof(tcode) + sizeof(len) + len;
channel->MessageStart(packet_nbytes);
channel->Write(packet_nbytes);
channel->Write(code);
channel->Write(num_args);
channel->Write(tcode);
channel->Write(len);
channel->WriteArray(msg, len);
channel->MessageDone();
}
/*!
* \brief Return a normal packed sequence packet.
*
* \param msg The error message.
* \param channel The communication channel handler.
* \tparam TChannel The type of the communication channel.
*/
template <typename TChannel>
static void ReturnPackedSeq(const TVMValue* arg_values, const int* type_codes, int num_args,
TChannel* channel) {
RPCCode code = RPCCode::kReturn;
uint64_t packet_nbytes =
sizeof(code) + PackedSeqGetNumBytes(arg_values, type_codes, num_args, false, channel);
channel->MessageStart(packet_nbytes);
channel->Write(packet_nbytes);
channel->Write(code);
SendPackedSeq(arg_values, type_codes, num_args, false, channel);
channel->MessageDone();
}
/*!
* \brief Return a null(void) packet.
*
* \param channel The communication channel handler.
* \tparam TChannel The type of the communication channel.
*/
template <typename TChannel>
static void ReturnVoid(TChannel* channel) {
int32_t num_args = 1;
int32_t tcode = kTVMNullptr;
RPCCode code = RPCCode::kReturn;
uint64_t packet_nbytes = sizeof(code) + sizeof(num_args) + sizeof(tcode);
channel->MessageStart(packet_nbytes);
channel->Write(packet_nbytes);
channel->Write(code);
channel->Write(num_args);
channel->Write(tcode);
channel->MessageDone();
}
};
} // namespace runtime
} // namespace tvm
#endif // TVM_RUNTIME_MINRPC_RPC_REFERENCE_H_
| https://github.com/zk-ml/tachikoma |
src/runtime/object_internal.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* \file src/runtime/object_internal.h
* \brief Expose a few functions for CFFI purposes.
* This file is not intended to be used
*/
#ifndef TVM_RUNTIME_OBJECT_INTERNAL_H_
#define TVM_RUNTIME_OBJECT_INTERNAL_H_
#include <tvm/runtime/module.h>
#include <tvm/runtime/object.h>
#include <string>
#include <utility>
namespace tvm {
namespace runtime {
/*!
* \brief Internal object namespace to expose
* certain util functions for FFI.
*/
class ObjectInternal {
public:
/*!
* \brief Retain an object handle.
*/
static void ObjectRetain(TVMObjectHandle obj) {
if (obj != nullptr) {
static_cast<Object*>(obj)->IncRef();
}
}
/*!
* \brief Free an object handle.
*/
static void ObjectFree(TVMObjectHandle obj) {
if (obj != nullptr) {
static_cast<Object*>(obj)->DecRef();
}
}
/*!
* \brief Check of obj derives from the type indicated by type index.
* \param obj The original object.
* \param type_index The type index of interest.
* \return The derivation checking result.
*/
static bool DerivedFrom(const Object* obj, uint32_t type_index) {
return obj->DerivedFrom(type_index);
}
/*!
* \brief Expose TypeKey2Index
* \param type_key The original type key.
* \return the corresponding index.
*/
static uint32_t ObjectTypeKey2Index(const std::string& type_key) {
return Object::TypeKey2Index(type_key);
}
/*!
* \brief Convert ModuleHandle to module node pointer.
* \param handle The module handle.
* \return the corresponding module node pointer.
*/
static ModuleNode* GetModuleNode(TVMModuleHandle handle) {
// NOTE: we will need to convert to Object
// then to ModuleNode in order to get the correct
// address translation
return static_cast<ModuleNode*>(static_cast<Object*>(handle));
}
/*!
* \brief Move the ObjectPtr inside ObjectRef out
* \param obj The ObjectRef
* \return The result ObjectPtr
*/
static ObjectPtr<Object> MoveObjectPtr(ObjectRef* obj) {
ObjectPtr<Object> data = std::move(obj->data_);
return data;
}
};
} // namespace runtime
} // namespace tvm
#endif // TVM_RUNTIME_OBJECT_INTERNAL_H_
| https://github.com/zk-ml/tachikoma |
src/runtime/opencl/aocl/aocl_common.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* \file aocl_common.h
* \brief AOCL common header
*/
#ifndef TVM_RUNTIME_OPENCL_AOCL_AOCL_COMMON_H_
#define TVM_RUNTIME_OPENCL_AOCL_AOCL_COMMON_H_
#include <memory>
#include "../opencl_common.h"
namespace tvm {
namespace runtime {
namespace cl {
/*!
* \brief Process global AOCL workspace.
*/
class AOCLWorkspace final : public OpenCLWorkspace {
public:
// override OpenCL device API
void Init() final;
bool IsOpenCLDevice(Device dev) final;
OpenCLThreadEntry* GetThreadEntry() final;
// get the global workspace
static OpenCLWorkspace* Global();
};
/*! \brief Thread local workspace for AOCL */
class AOCLThreadEntry : public OpenCLThreadEntry {
public:
// constructor
AOCLThreadEntry()
: OpenCLThreadEntry(static_cast<DLDeviceType>(kDLAOCL), AOCLWorkspace::Global()) {}
// get the global workspace
static AOCLThreadEntry* ThreadLocal();
};
} // namespace cl
} // namespace runtime
} // namespace tvm
#endif // TVM_RUNTIME_OPENCL_AOCL_AOCL_COMMON_H_
| https://github.com/zk-ml/tachikoma |
src/runtime/opencl/aocl/aocl_module.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* \file aocl_module.h
* \brief Execution handling of OpenCL kernels for AOCL
*/
#ifndef TVM_RUNTIME_OPENCL_AOCL_AOCL_MODULE_H_
#define TVM_RUNTIME_OPENCL_AOCL_AOCL_MODULE_H_
#include <tvm/runtime/packed_func.h>
#include <memory>
#include <string>
#include <unordered_map>
#include <vector>
#include "../../meta_data.h"
namespace tvm {
namespace runtime {
/*!
* \brief create a opencl module for AOCL from data.
*
* \param data The module data.
* \param fmt The format of the data, can be "aocx"
* \param fmap The map function information map of each function.
*/
Module AOCLModuleCreate(std::string data, std::string fmt,
std::unordered_map<std::string, FunctionInfo> fmap, std::string source);
} // namespace runtime
} // namespace tvm
#endif // TVM_RUNTIME_OPENCL_AOCL_AOCL_MODULE_H_
| https://github.com/zk-ml/tachikoma |
src/runtime/opencl/opencl_common.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* \file opencl_common.h
* \brief OpenCL common header
*/
#ifndef TVM_RUNTIME_OPENCL_OPENCL_COMMON_H_
#define TVM_RUNTIME_OPENCL_OPENCL_COMMON_H_
#include <tvm/runtime/c_runtime_api.h>
#include <tvm/runtime/device_api.h>
#include <tvm/runtime/logging.h>
#include <tvm/runtime/ndarray.h>
#include <tvm/runtime/packed_func.h>
#include <tvm/runtime/profiling.h>
/* There are many OpenCL platforms that do not yet support OpenCL 2.0,
* hence we use 1.2 APIs, some of which are now deprecated. In order
* to turn off the deprecation warnings (elevated to errors by
* -Werror) we explicitly disable the 1.2 deprecation warnings.
*
* At the point TVM supports minimum version 2.0, we can remove this
* define.
*/
#define CL_USE_DEPRECATED_OPENCL_1_2_APIS
/* Newer releases of OpenCL header files (after May 2018) work with
* any OpenCL version, with an application's target version
* specified. Setting the target version disables APIs from after that
* version, and sets appropriate USE_DEPRECATED macros. The above
* macro for CL_USE_DEPRECATED_OPENCL_1_2_APIS is still needed in case
* we are compiling against the earlier version-specific OpenCL header
* files. This also allows us to expose the OpenCL version through
* tvm.runtime.Device.
*/
#define CL_TARGET_OPENCL_VERSION 120
#ifdef __APPLE__
#include <OpenCL/opencl.h>
#else
#include <CL/opencl.h>
#endif
#include <memory>
#include <mutex>
#include <string>
#include <unordered_map>
#include <vector>
#include "../file_utils.h"
#include "../meta_data.h"
#include "../pack_args.h"
#include "../texture.h"
#include "../thread_storage_scope.h"
#include "../workspace_pool.h"
namespace tvm {
namespace runtime {
namespace cl {
static_assert(sizeof(cl_mem) == sizeof(void*), "Required to store cl_mem inside void*");
inline const char* CLGetErrorString(cl_int error) {
switch (error) {
case CL_SUCCESS:
return "CL_SUCCESS";
case CL_DEVICE_NOT_FOUND:
return "CL_DEVICE_NOT_FOUND";
case CL_DEVICE_NOT_AVAILABLE:
return "CL_DEVICE_NOT_AVAILABLE";
case CL_COMPILER_NOT_AVAILABLE:
return "CL_COMPILER_NOT_AVAILABLE";
case CL_MEM_OBJECT_ALLOCATION_FAILURE:
return "CL_MEM_OBJECT_ALLOCATION_FAILURE";
case CL_OUT_OF_RESOURCES:
return "CL_OUT_OF_RESOURCES";
case CL_OUT_OF_HOST_MEMORY:
return "CL_OUT_OF_HOST_MEMORY";
case CL_PROFILING_INFO_NOT_AVAILABLE:
return "CL_PROFILING_INFO_NOT_AVAILABLE";
case CL_MEM_COPY_OVERLAP:
return "CL_MEM_COPY_OVERLAP";
case CL_IMAGE_FORMAT_MISMATCH:
return "CL_IMAGE_FORMAT_MISMATCH";
case CL_IMAGE_FORMAT_NOT_SUPPORTED:
return "CL_IMAGE_FORMAT_NOT_SUPPORTED";
case CL_BUILD_PROGRAM_FAILURE:
return "CL_BUILD_PROGRAM_FAILURE";
case CL_MAP_FAILURE:
return "CL_MAP_FAILURE";
case CL_INVALID_VALUE:
return "CL_INVALID_VALUE";
case CL_INVALID_DEVICE_TYPE:
return "CL_INVALID_DEVICE_TYPE";
case CL_INVALID_PLATFORM:
return "CL_INVALID_PLATFORM";
case CL_INVALID_DEVICE:
return "CL_INVALID_DEVICE";
case CL_INVALID_CONTEXT:
return "CL_INVALID_CONTEXT";
case CL_INVALID_QUEUE_PROPERTIES:
return "CL_INVALID_QUEUE_PROPERTIES";
case CL_INVALID_COMMAND_QUEUE:
return "CL_INVALID_COMMAND_QUEUE";
case CL_INVALID_HOST_PTR:
return "CL_INVALID_HOST_PTR";
case CL_INVALID_MEM_OBJECT:
return "CL_INVALID_MEM_OBJECT";
case CL_INVALID_IMAGE_FORMAT_DESCRIPTOR:
return "CL_INVALID_IMAGE_FORMAT_DESCRIPTOR";
case CL_INVALID_IMAGE_SIZE:
return "CL_INVALID_IMAGE_SIZE";
case CL_INVALID_SAMPLER:
return "CL_INVALID_SAMPLER";
case CL_INVALID_BINARY:
return "CL_INVALID_BINARY";
case CL_INVALID_BUILD_OPTIONS:
return "CL_INVALID_BUILD_OPTIONS";
case CL_INVALID_PROGRAM:
return "CL_INVALID_PROGRAM";
case CL_INVALID_PROGRAM_EXECUTABLE:
return "CL_INVALID_PROGRAM_EXECUTABLE";
case CL_INVALID_KERNEL_NAME:
return "CL_INVALID_KERNEL_NAME";
case CL_INVALID_KERNEL_DEFINITION:
return "CL_INVALID_KERNEL_DEFINITION";
case CL_INVALID_KERNEL:
return "CL_INVALID_KERNEL";
case CL_INVALID_ARG_INDEX:
return "CL_INVALID_ARG_INDEX";
case CL_INVALID_ARG_VALUE:
return "CL_INVALID_ARG_VALUE";
case CL_INVALID_ARG_SIZE:
return "CL_INVALID_ARG_SIZE";
case CL_INVALID_KERNEL_ARGS:
return "CL_INVALID_KERNEL_ARGS";
case CL_INVALID_WORK_DIMENSION:
return "CL_INVALID_WORK_DIMENSION";
case CL_INVALID_WORK_GROUP_SIZE:
return "CL_INVALID_WORK_GROUP_SIZE";
case CL_INVALID_WORK_ITEM_SIZE:
return "CL_INVALID_WORK_ITEM_SIZE";
case CL_INVALID_GLOBAL_OFFSET:
return "CL_INVALID_GLOBAL_OFFSET";
case CL_INVALID_EVENT_WAIT_LIST:
return "CL_INVALID_EVENT_WAIT_LIST";
case CL_INVALID_EVENT:
return "CL_INVALID_EVENT";
case CL_INVALID_OPERATION:
return "CL_INVALID_OPERATION";
case CL_INVALID_GL_OBJECT:
return "CL_INVALID_GL_OBJECT";
case CL_INVALID_BUFFER_SIZE:
return "CL_INVALID_BUFFER_SIZE";
case CL_INVALID_MIP_LEVEL:
return "CL_INVALID_MIP_LEVEL";
default:
return "Unknown OpenCL error code";
}
}
inline cl_channel_type DTypeToOpenCLChannelType(DLDataType data_type) {
DataType dtype(data_type);
if (dtype == DataType::Float(32)) {
return CL_FLOAT;
} else if (dtype == DataType::Float(16)) {
return CL_HALF_FLOAT;
} else if (dtype == DataType::Int(8)) {
return CL_SIGNED_INT8;
} else if (dtype == DataType::Int(16)) {
return CL_SIGNED_INT16;
} else if (dtype == DataType::Int(32)) {
return CL_SIGNED_INT32;
} else if (dtype == DataType::UInt(8)) {
return CL_UNSIGNED_INT8;
} else if (dtype == DataType::UInt(16)) {
return CL_UNSIGNED_INT16;
} else if (dtype == DataType::UInt(32)) {
return CL_UNSIGNED_INT32;
}
LOG(FATAL) << "data type is not supported in OpenCL runtime yet: " << dtype;
return CL_FLOAT;
}
/*!
* \brief Protected OpenCL call
* \param func Expression to call.
*/
#define OPENCL_CHECK_ERROR(e) \
{ ICHECK(e == CL_SUCCESS) << "OpenCL Error, code=" << e << ": " << cl::CLGetErrorString(e); }
#define OPENCL_CALL(func) \
{ \
cl_int e = (func); \
OPENCL_CHECK_ERROR(e); \
}
class OpenCLThreadEntry;
/*!
* \brief Process global OpenCL workspace.
*/
class OpenCLWorkspace : public DeviceAPI {
public:
// type key
std::string type_key;
// global platform id
cl_platform_id platform_id;
// global platform name
std::string platform_name;
// global context of this process
cl_context context{nullptr};
// whether the workspace it initialized.
bool initialized_{false};
// the device type
std::string device_type;
// the devices
std::vector<cl_device_id> devices;
// the queues
std::vector<cl_command_queue> queues;
// the events
std::vector<std::vector<cl_event>> events;
// Number of registered kernels
// Used to register kernel into the workspace.
size_t num_registered_kernels{0};
// The version counter, used
size_t timestamp{0};
// Ids that are freed by kernels.
std::vector<size_t> free_kernel_ids;
// the mutex for initialization
std::mutex mu;
// destructor
~OpenCLWorkspace() {
if (context != nullptr) {
OPENCL_CALL(clReleaseContext(context));
}
}
// Initialzie the device.
void Init(const std::string& type_key, const std::string& device_type,
const std::string& platform_name = "");
virtual void Init() { Init("opencl", "gpu"); }
// Check whether the context is OpenCL or not.
virtual bool IsOpenCLDevice(Device dev) { return dev.device_type == kDLOpenCL; }
// get the queue of the device
cl_command_queue GetQueue(Device dev) {
ICHECK(IsOpenCLDevice(dev));
this->Init();
ICHECK(dev.device_id >= 0 && static_cast<size_t>(dev.device_id) < queues.size())
<< "Invalid OpenCL device_id=" << dev.device_id;
return queues[dev.device_id];
}
// get the event queue of the context
std::vector<cl_event>& GetEventQueue(Device dev) {
ICHECK(IsOpenCLDevice(dev));
this->Init();
ICHECK(dev.device_id >= 0 && static_cast<size_t>(dev.device_id) < queues.size())
<< "Invalid OpenCL device_id=" << dev.device_id;
return events[dev.device_id];
}
// is current clCommandQueue in profiling mode
bool IsProfiling(Device dev) {
cl_command_queue queue = GetQueue(dev);
cl_command_queue_properties prop;
OPENCL_CALL(clGetCommandQueueInfo(queue, CL_QUEUE_PROPERTIES,
sizeof(cl_command_queue_properties), &prop, nullptr));
return prop & CL_QUEUE_PROFILING_ENABLE;
}
// override device API
void SetDevice(Device dev) final;
void GetAttr(Device dev, DeviceAttrKind kind, TVMRetValue* rv) final;
void* AllocDataSpace(Device dev, size_t size, size_t alignment, DLDataType type_hint) final;
void* AllocDataSpace(Device dev, int ndim, const int64_t* shape, DLDataType dtype,
Optional<String> mem_scope = NullOpt) final;
void FreeDataSpace(Device dev, void* ptr) final;
void StreamSync(Device dev, TVMStreamHandle stream) final;
void* AllocWorkspace(Device dev, size_t size, DLDataType type_hint) final;
void FreeWorkspace(Device dev, void* data) final;
// Texture (image2d_t) alloca APIs
cl_mem AllocTexture(Device dev, size_t width, size_t height, DLDataType type_hint);
void* AllocTextureWorkspace(Device dev, size_t width, size_t height, DLDataType type_hint);
void FreeTextureWorkspace(Device dev, void* data);
/*!
* \brief Get the thread local ThreadEntry
*/
virtual OpenCLThreadEntry* GetThreadEntry();
// get the global workspace
static OpenCLWorkspace* Global();
void CopyDataFromTo(DLTensor* from, DLTensor* to, TVMStreamHandle stream) final;
};
/*! \brief Thread local workspace */
class OpenCLThreadEntry {
public:
// The kernel entry and version.
struct KTEntry {
// The kernel handle.
cl_kernel kernel{nullptr};
// timestamp used to recognize stale kernel
size_t version{0};
};
/*! \brief The current device */
Device device;
/*! \brief The thread-local kernel table */
std::vector<KTEntry> kernel_table;
/*! \brief workspace pool */
WorkspacePool pool;
/*! \brief texture pool */
TexturePool texture_pool;
// constructor
OpenCLThreadEntry(DLDeviceType device_type, DeviceAPI* device_api)
: pool(device_type, device_api), texture_pool(device_type, device_api) {
device.device_id = 0;
device.device_type = device_type;
}
OpenCLThreadEntry() : OpenCLThreadEntry(kDLOpenCL, OpenCLWorkspace::Global()) {}
// get the global workspace
static OpenCLThreadEntry* ThreadLocal();
};
/*! \brief OpenCL runtime buffer structure with tracked memory layout
TODO(tvm-team): Uncouple use of storage scope and data layout by using the transform_layout
schedule primitive to express the desired texture layout. This will require supporting Nd
indices in BufferLoad and BufferStore in CodegenOpenCL, and ensuring Nd allocations for
texture are correctly routed to the AllocateTexture packed function in the OpenCL DeviceAPI.
*/
struct BufferDescriptor {
enum class MemoryLayout {
/*! \brief One dimensional buffer in row-major layout*/
kBuffer1D,
/*! \brief Two dimensional texture w/ width = axis[-1]
* e.g. image2d[height=NCH, width=W]
*/
kImage2DActivation,
/*! \brief Two dimensional texture w/ height = axis[0]
* e.g. image2d[height=O, width=IHW]
*/
kImage2DWeight,
/*! \brief Two dimensional texture w/ height = axis[1]
* e.g. image2d[height=NH, width=WC]
*/
kImage2DNHWC,
};
BufferDescriptor() = default;
explicit BufferDescriptor(Optional<String> scope) : layout(MemoryLayoutFromScope(scope)) {}
static MemoryLayout MemoryLayoutFromScope(Optional<String> mem_scope);
static String ScopeFromMemoryLayout(MemoryLayout mem_scope);
cl_mem buffer{nullptr};
MemoryLayout layout{MemoryLayout::kBuffer1D};
};
} // namespace cl
// Module to support thread-safe multi-device execution.
// OpenCL runtime is a bit tricky because clSetKernelArg is not thread-safe
// To make the call thread-safe, we create a thread-local kernel table
// and lazily install new kernels into the kernel table when the kernel is called.
// The kernels are recycled when the module get destructed.
class OpenCLModuleNode : public ModuleNode {
public:
// Kernel table reference entry.
struct KTRefEntry {
size_t kernel_id;
size_t version;
};
explicit OpenCLModuleNode(std::string data, std::string fmt,
std::unordered_map<std::string, FunctionInfo> fmap, std::string source)
: data_(data), fmt_(fmt), fmap_(fmap), source_(source) {}
// destructor
~OpenCLModuleNode();
/*!
* \brief Get the global workspace
*/
virtual cl::OpenCLWorkspace* GetGlobalWorkspace();
const char* type_key() const final { return workspace_->type_key.c_str(); }
PackedFunc GetFunction(const std::string& name, const ObjectPtr<Object>& sptr_to_self) final;
void SaveToFile(const std::string& file_name, const std::string& format) final;
void SaveToBinary(dmlc::Stream* stream) final;
std::string GetSource(const std::string& format) final;
// Initialize the programs
void Init();
// install a new kernel to thread local entry
cl_kernel InstallKernel(cl::OpenCLWorkspace* w, cl::OpenCLThreadEntry* t,
const std::string& func_name, const KTRefEntry& e);
private:
// The workspace, need to keep reference to use it in destructor.
// In case of static destruction order problem.
cl::OpenCLWorkspace* workspace_;
// the binary data
std::string data_;
// The format
std::string fmt_;
// function information table.
std::unordered_map<std::string, FunctionInfo> fmap_;
// Module local mutex
std::mutex build_lock_;
// The OpenCL source.
std::string source_;
// Mapping from primitive name to cl program for each device.
std::unordered_map<std::string, std::vector<cl_program>> programs_;
// kernel id cache
std::unordered_map<std::string, KTRefEntry> kid_map_;
// kernels build so far.
std::vector<cl_kernel> kernels_;
// parsed kernel data
std::unordered_map<std::string, std::string> parsed_kernels_;
};
/*! \brief OpenCL timer node */
class OpenCLTimerNode : public TimerNode {
public:
// Timer start
virtual void Start() {
this->duration = 0;
if (count_timer_execs == 0) {
cl::OpenCLWorkspace::Global()->GetEventQueue(dev_).clear();
// Very first call of Start() leads to the recreation of
// OpenCL command queue in profiling mode. This allows to run profile after inference.
recreateCommandQueue();
}
++count_timer_execs;
// set new first idx in event queue
if (event_start_idxs.size() < count_timer_execs) {
event_start_idxs.push_back(0);
}
}
// Timer stop
virtual void Stop() {
std::vector<cl_event> evt_queue = cl::OpenCLWorkspace::Global()->GetEventQueue(dev_);
cl_ulong start, end;
size_t start_idx = event_start_idxs[count_timer_execs - 1];
if (cl::OpenCLWorkspace::Global()->GetEventQueue(dev_).size() > 0) {
OPENCL_CALL(clWaitForEvents(1, &(cl::OpenCLWorkspace::Global()->GetEventQueue(dev_).back())));
for (size_t i = start_idx; i < evt_queue.size(); ++i) {
auto& kevt = evt_queue[i];
OPENCL_CALL(clGetEventProfilingInfo(kevt, CL_PROFILING_COMMAND_START, sizeof(cl_ulong),
&start, nullptr));
OPENCL_CALL(clGetEventProfilingInfo(kevt, CL_PROFILING_COMMAND_END, sizeof(cl_ulong), &end,
nullptr));
this->duration += (end - start);
}
}
// update event index for current call nesting
event_start_idxs[count_timer_execs - 1] = evt_queue.size();
--count_timer_execs;
}
virtual int64_t SyncAndGetElapsedNanos() { return this->duration; }
// destructor
virtual ~OpenCLTimerNode() {
// Profiling session ends, recreate clCommandQueue in non-profiling mode
// This will disable collection of cl_events in case of executing inference after profile
if (count_timer_execs == 0) {
recreateCommandQueue();
event_start_idxs.clear();
}
}
// constructor
OpenCLTimerNode() {}
explicit OpenCLTimerNode(Device dev) : dev_(dev) {}
static constexpr const char* _type_key = "OpenCLTimerNode";
static size_t count_timer_execs;
static std::vector<size_t> event_start_idxs;
TVM_DECLARE_FINAL_OBJECT_INFO(OpenCLTimerNode, TimerNode);
private:
int64_t duration;
Device dev_;
void recreateCommandQueue() {
cl_command_queue_properties prop;
if (!cl::OpenCLWorkspace::Global()->IsProfiling(dev_)) {
prop = CL_QUEUE_PROFILING_ENABLE;
} else {
prop = 0;
}
auto queue = cl::OpenCLWorkspace::Global()->GetQueue(dev_);
OPENCL_CALL(clFlush(queue));
OPENCL_CALL(clFinish(queue));
OPENCL_CALL(clReleaseCommandQueue(queue));
cl_int err_code;
cl_device_id did = cl::OpenCLWorkspace::Global()->devices[dev_.device_id];
auto profiling_queue =
clCreateCommandQueue(cl::OpenCLWorkspace::Global()->context, did, prop, &err_code);
OPENCL_CHECK_ERROR(err_code);
cl::OpenCLWorkspace::Global()->queues[dev_.device_id] = profiling_queue;
}
};
} // namespace runtime
} // namespace tvm
#endif // TVM_RUNTIME_OPENCL_OPENCL_COMMON_H_
| https://github.com/zk-ml/tachikoma |
src/runtime/opencl/opencl_module.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* \file opencl_module.h
* \brief Execution handling of OPENCL kernels
*/
#ifndef TVM_RUNTIME_OPENCL_OPENCL_MODULE_H_
#define TVM_RUNTIME_OPENCL_OPENCL_MODULE_H_
#include <tvm/runtime/packed_func.h>
#include <memory>
#include <string>
#include <unordered_map>
#include <vector>
#include "../meta_data.h"
namespace tvm {
namespace runtime {
/*!
* \brief create a opencl module for GPU devices from data.
*
* \param data The module data.
* \param fmt The format of the data, can be "clbin", "cl"
* \param fmap The map function information map of each function.
*/
Module OpenCLModuleCreate(std::string data, std::string fmt,
std::unordered_map<std::string, FunctionInfo> fmap, std::string source);
} // namespace runtime
} // namespace tvm
#endif // TVM_RUNTIME_OPENCL_OPENCL_MODULE_H_
| https://github.com/zk-ml/tachikoma |
src/runtime/opencl/sdaccel/sdaccel_common.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* \file sdaccel_common.h
* \brief SDAccel common header
*/
#ifndef TVM_RUNTIME_OPENCL_SDACCEL_SDACCEL_COMMON_H_
#define TVM_RUNTIME_OPENCL_SDACCEL_SDACCEL_COMMON_H_
#include <memory>
#include "../opencl_common.h"
namespace tvm {
namespace runtime {
namespace cl {
/*!
* \brief Process global SDAccel workspace.
*/
class SDAccelWorkspace final : public OpenCLWorkspace {
public:
// override OpenCL device API
void Init() final;
bool IsOpenCLDevice(Device dev) final;
OpenCLThreadEntry* GetThreadEntry() final;
// get the global workspace
static OpenCLWorkspace* Global();
};
/*! \brief Thread local workspace for SDAccel*/
class SDAccelThreadEntry : public OpenCLThreadEntry {
public:
// constructor
SDAccelThreadEntry()
: OpenCLThreadEntry(static_cast<DLDeviceType>(kDLSDAccel), SDAccelWorkspace::Global()) {}
// get the global workspace
static SDAccelThreadEntry* ThreadLocal();
};
} // namespace cl
} // namespace runtime
} // namespace tvm
#endif // TVM_RUNTIME_OPENCL_SDACCEL_SDACCEL_COMMON_H_
| https://github.com/zk-ml/tachikoma |
src/runtime/opencl/sdaccel/sdaccel_module.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* \file sdaccel_module.h
* \brief Execution handling of OPENCL kernels for SDAccel FPGAs
*/
#ifndef TVM_RUNTIME_OPENCL_SDACCEL_SDACCEL_MODULE_H_
#define TVM_RUNTIME_OPENCL_SDACCEL_SDACCEL_MODULE_H_
#include <tvm/runtime/packed_func.h>
#include <memory>
#include <string>
#include <unordered_map>
#include <vector>
#include "../../meta_data.h"
namespace tvm {
namespace runtime {
/*!
* \brief create a opencl module for SDAccel from data.
*
* \param data The module data.
* \param fmt The format of the data, can be "xclbin", "awsxclbin"
* \param fmap The map function information map of each function.
*/
Module SDAccelModuleCreate(std::string data, std::string fmt,
std::unordered_map<std::string, FunctionInfo> fmap, std::string source);
} // namespace runtime
} // namespace tvm
#endif // TVM_RUNTIME_OPENCL_SDACCEL_SDACCEL_MODULE_H_
| https://github.com/zk-ml/tachikoma |
src/runtime/pack_args.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* \file pack_args.h
* \brief Utility to pack TVMArgs to other type-erased fution calling convention.
*
* Two type erased function signatures are supported.
* - cuda_style(void** args, int num_args);
* - Pack everything by address
* - metal_style(void** buffers, int num_buffers,
* union_32bit args[N], int num_args);
* - Pack buffer by address, pack rest parameter into 32bit union buffer.
*/
#ifndef TVM_RUNTIME_PACK_ARGS_H_
#define TVM_RUNTIME_PACK_ARGS_H_
#include <tvm/runtime/c_runtime_api.h>
#include <tvm/runtime/packed_func.h>
#include <cstring>
#include <vector>
namespace tvm {
namespace runtime {
/*!
* \brief argument union type of 32bit.
*/
union ArgUnion32 {
int32_t v_int32;
uint32_t v_uint32;
float v_float32;
};
/*!
* \brief argument union type of 64 bit, for use by Vulkan and Metal runtime.
*/
union ArgUnion64 {
int32_t v_int32[2];
uint32_t v_uint32[2];
float v_float32[2];
int64_t v_int64;
uint64_t v_uint64;
double v_float64;
};
/*!
* \brief Create a packed function from void addr types.
*
* \param f with signiture (TVMArgs args, TVMRetValue* rv, void* void_args)
* \param arg_types The arguments type information.
* \tparam F the function type
*
* \return The wrapped packed function.
*/
template <typename F>
inline PackedFunc PackFuncVoidAddr(F f, const std::vector<DLDataType>& arg_types);
/*!
* \brief Create a packed function that from function only packs buffer arguments.
*
* \param f with signiture (TVMArgs args, TVMRetValue* rv, ArgUnion* pack_args)
* \param arg_types The arguments type information.
* \tparam F the function type
*
* \return The wrapped packed function.
*/
template <typename F>
inline PackedFunc PackFuncNonBufferArg(F f, const std::vector<DLDataType>& arg_types);
/*!
* \brief Create a packed function that from function that takes a packed arguments.
*
* \param f with signature (TVMArgs args, TVMRetValue* rv, void* pack_args, size_t nbytes)
* \param arg_types The arguments that wish to get from
* \tparam F the function type
*
* \return The wrapped packed function.
*/
template <typename F>
inline PackedFunc PackFuncPackedArg(F f, const std::vector<DLDataType>& arg_types);
/*!
* \brief Extract number of buffer argument from the argument types.
* \param arg_types The argument types.
* \return number of buffer arguments
*/
inline size_t NumBufferArgs(const std::vector<DLDataType>& arg_types);
// implementations details
namespace detail {
template <typename T, int kSize>
class TempArray {
public:
explicit TempArray(int size) {}
T* data() { return data_; }
private:
T data_[kSize];
};
template <typename T>
class TempArray<T, 0> {
public:
explicit TempArray(int size) : data_(size) {}
T* data() { return data_.data(); }
private:
std::vector<T> data_;
};
/*! \brief conversion code used in void arg. */
enum ArgConvertCode {
INT64_TO_INT64,
INT64_TO_INT32,
INT64_TO_UINT32,
FLOAT64_TO_FLOAT32,
FLOAT64_TO_FLOAT64,
HANDLE_TO_HANDLE
};
inline ArgConvertCode GetArgConvertCode(DLDataType t) {
ICHECK_EQ(t.lanes, 1U) << "Cannot pass vector type argument to devic function for now";
if (t.code == kDLInt) {
if (t.bits == 64U) return INT64_TO_INT64;
if (t.bits == 32U) return INT64_TO_INT32;
} else if (t.code == kDLUInt) {
if (t.bits == 32U) return INT64_TO_UINT32;
} else if (t.code == kDLFloat) {
if (t.bits == 64U) return FLOAT64_TO_FLOAT64;
if (t.bits == 32U) return FLOAT64_TO_FLOAT32;
} else if (t.code == kTVMOpaqueHandle) {
return HANDLE_TO_HANDLE;
}
LOG(FATAL) << "Cannot handle " << t << " as device function argument";
return HANDLE_TO_HANDLE;
}
template <int N, typename F>
inline PackedFunc PackFuncVoidAddr_(F f, const std::vector<ArgConvertCode>& codes) {
int num_args = static_cast<int>(codes.size());
auto ret = [f, codes, num_args](TVMArgs args, TVMRetValue* ret) {
TempArray<void*, N> addr_(num_args);
TempArray<ArgUnion32, N> holder_(num_args);
void** addr = addr_.data();
ArgUnion32* holder = holder_.data();
for (int i = 0; i < num_args; ++i) {
switch (codes[i]) {
case INT64_TO_INT64:
case FLOAT64_TO_FLOAT64:
case HANDLE_TO_HANDLE: {
addr[i] = (void*)&(args.values[i]); // NOLINT(*)
break;
}
case INT64_TO_INT32: {
holder[i].v_int32 = static_cast<int32_t>(args.values[i].v_int64);
addr[i] = &(holder[i]);
break;
}
case INT64_TO_UINT32: {
holder[i].v_uint32 = static_cast<uint32_t>(args.values[i].v_int64);
addr[i] = &(holder[i]);
break;
}
case FLOAT64_TO_FLOAT32: {
holder[i].v_float32 = static_cast<float>(args.values[i].v_float64);
addr[i] = &(holder[i]);
break;
}
}
}
f(args, ret, addr);
};
return PackedFunc(ret);
}
template <int N, typename F>
inline PackedFunc PackFuncNonBufferArg_(F f, int base, const std::vector<ArgConvertCode>& codes) {
int num_args = static_cast<int>(codes.size());
auto ret = [f, codes, base, num_args](TVMArgs args, TVMRetValue* ret) {
TempArray<ArgUnion64, N> holder_(num_args);
ArgUnion64* holder = holder_.data();
for (int i = 0; i < num_args; ++i) {
switch (codes[i]) {
case INT64_TO_INT64: {
holder[i].v_int64 = args.values[base + i].v_int64;
break;
}
case FLOAT64_TO_FLOAT64: {
holder[i].v_float64 = args.values[base + i].v_float64;
break;
}
case INT64_TO_INT32: {
holder[i].v_int32[0] = static_cast<int32_t>(args.values[base + i].v_int64);
break;
}
case INT64_TO_UINT32: {
holder[i].v_uint32[0] = static_cast<uint32_t>(args.values[base + i].v_int64);
break;
}
case FLOAT64_TO_FLOAT32: {
holder[i].v_float32[0] = static_cast<float>(args.values[base + i].v_float64);
break;
}
case HANDLE_TO_HANDLE: {
LOG(FATAL) << "not reached";
break;
}
}
}
f(args, ret, holder);
};
return PackedFunc(ret);
}
template <int N, typename F>
inline PackedFunc PackFuncPackedArg_(F f, const std::vector<ArgConvertCode>& codes) {
int num_args = static_cast<int>(codes.size());
auto ret = [f, codes, num_args](TVMArgs args, TVMRetValue* ret) {
TempArray<uint64_t, N> pack_(num_args);
int32_t* pack = reinterpret_cast<int32_t*>(pack_.data());
int32_t* ptr = pack;
static_assert(sizeof(TVMValue) == 8, "invariant");
static_assert(sizeof(void*) % sizeof(int32_t) == 0, "invariant");
for (int i = 0; i < num_args; ++i) {
switch (codes[i]) {
case HANDLE_TO_HANDLE: {
std::memcpy(ptr, &(args.values[i].v_handle), sizeof(void*));
ptr += sizeof(void*) / sizeof(int32_t);
break;
}
case INT64_TO_INT64:
case FLOAT64_TO_FLOAT64: {
std::memcpy(ptr, &args.values[i], sizeof(TVMValue));
ptr += 2;
break;
}
case INT64_TO_INT32: {
*ptr = static_cast<int32_t>(args.values[i].v_int64);
++ptr;
break;
}
case INT64_TO_UINT32: {
*reinterpret_cast<uint32_t*>(ptr) = static_cast<uint32_t>(args.values[i].v_int64);
++ptr;
break;
}
case FLOAT64_TO_FLOAT32: {
*reinterpret_cast<float*>(ptr) = static_cast<float>(args.values[i].v_float64);
++ptr;
break;
}
default: {
LOG(FATAL) << "not reached";
break;
}
}
}
f(args, ret, pack, (ptr - pack) * sizeof(int32_t));
};
return PackedFunc(ret);
}
} // namespace detail
template <typename F>
inline PackedFunc PackFuncVoidAddr(F f, const std::vector<DLDataType>& arg_types) {
std::vector<detail::ArgConvertCode> codes(arg_types.size());
for (size_t i = 0; i < arg_types.size(); ++i) {
codes[i] = detail::GetArgConvertCode(arg_types[i]);
}
size_t num_void_args = arg_types.size();
// specialization
if (num_void_args <= 4) {
return detail::PackFuncVoidAddr_<4>(f, codes);
} else if (num_void_args <= 8) {
return detail::PackFuncVoidAddr_<8>(f, codes);
} else {
return detail::PackFuncVoidAddr_<0>(f, codes);
}
}
inline size_t NumBufferArgs(const std::vector<DLDataType>& arg_types) {
size_t base = arg_types.size();
for (size_t i = 0; i < arg_types.size(); ++i) {
if (arg_types[i].code != kTVMOpaqueHandle) {
base = i;
break;
}
}
for (size_t i = base; i < arg_types.size(); ++i) {
ICHECK(arg_types[i].code != kTVMOpaqueHandle) << "Device function need to be organized";
}
return base;
}
template <typename F>
inline PackedFunc PackFuncNonBufferArg(F f, const std::vector<DLDataType>& arg_types) {
size_t num_buffer = NumBufferArgs(arg_types);
std::vector<detail::ArgConvertCode> codes;
for (size_t i = num_buffer; i < arg_types.size(); ++i) {
codes.push_back(detail::GetArgConvertCode(arg_types[i]));
}
int base = static_cast<int>(num_buffer);
size_t nargs = codes.size();
// specialization
if (nargs <= 4) {
return detail::PackFuncNonBufferArg_<4>(f, base, codes);
} else {
return detail::PackFuncNonBufferArg_<0>(f, base, codes);
}
}
template <typename F>
inline PackedFunc PackFuncPackedArg(F f, const std::vector<DLDataType>& arg_types) {
std::vector<detail::ArgConvertCode> codes;
for (size_t i = 0; i < arg_types.size(); ++i) {
codes.push_back(detail::GetArgConvertCode(arg_types[i]));
}
size_t nargs = codes.size();
// specialization
if (nargs <= 4) {
return detail::PackFuncPackedArg_<4>(f, codes);
} else {
return detail::PackFuncPackedArg_<0>(f, codes);
}
}
} // namespace runtime
} // namespace tvm
#endif // TVM_RUNTIME_PACK_ARGS_H_
| https://github.com/zk-ml/tachikoma |
src/runtime/pipeline/pipeline_executor.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* \brief pipeline executor
* \file pipeline_executor.h
*/
#ifndef TVM_RUNTIME_PIPELINE_PIPELINE_EXECUTOR_H_
#define TVM_RUNTIME_PIPELINE_PIPELINE_EXECUTOR_H_
#include <tvm/relay/expr.h>
#include <tvm/runtime/registry.h>
#include <array>
#include <iostream>
#include <memory>
#include <sstream>
#include <string>
#include <utility>
#include <vector>
#include "pipeline_scheduler.h"
namespace tvm {
namespace runtime {
/*!
* \brief pipeline executor.
* This executor class use the module list and dependency configuration of modules as
* the parameters and executes these modules on heterogeneous targets in a pipeline
* parallel manner to improve throughput.
*
* This executor can be accessed by various language via TVM runtime PackedFunc API.
*/
class TVM_DLL PipelineExecutor : public ModuleNode {
public:
/*!
* \Return the type key of the executor.
*/
const char* type_key() const final { return "PipelineExecutor"; }
/*!
* \brief Initialize the pipeline executor with module array and JSON text.
* \param modules The module list used for building pipeline.
* \param pipeline_json The configuration of modules dependencies.
*/
void Init(const std::vector<Module>& modules, const std::string& pipeline_json);
/*!
* \brief Use the information of mod_config to create a list of graph executor.
* \param mod_config The configuration information generated by the library export function call.
*/
std::vector<Module> CreateGraphModules(const ModuleConfig& mod_config);
/*!
* \brief Give frontends an access to packed functions.
* \param name The name of the function.
* \param sptr_to_self The pointer to the module node.
* \return The corresponding packed function.
*/
virtual PackedFunc GetFunction(const std::string& name, const ObjectPtr<Object>& sptr_to_self);
/*!
* \brief Using the global input name to get the index, and also get the input interface name
of corresponding subgraph from the input connection configuration.
* \param The global input name.
* \return Returning the index and the input interface name of corresponding subgraph.
*/
Array<String> GetInputPipeplineMap(std::string input_name);
/*!
* \brief This function return a module index for the global parameters group name.
* \param name The parameters group name.
* \return Returning a runtime module index.
*/
int GetParamsGroupPipelineMap(const std::string& name);
/*!
* \brief Use the input name to set the input data of pipeline executor.
* \param input_name The input name.
* \param data_in The input data.
*/
void SetInput(std::string input_name, DLTensor* data_in);
/*!
* \brief Use the input name to get the input data.
* \param input name The input name.
* \return Return input data.
*/
NDArray GetInput(std::string input_name);
/*!
* \brief Getting the count of running pipeline.
*/
int GetExecutionCount();
/*!
* \brief Use the parameters group name to get the specific backend runtime then use
* the param_key_name to set param data for the said backend runtime.
* \param param_group_name The parameters group name.
* \param param_key_name The parameter key name.
* \param data_in The parameter value.
*/
void SetParam(std::string param_group_name, std::string param_key_name, DLTensor* data_in);
/*!
* \brief Get the number of outputs.
*
* \return The number of outputs.
*/
int NumOutputs() const { return num_outputs_; }
/*!\brief Run the pipeline executor.*/
void Run();
int NumInputs();
/*!
* \brief Get a list output data.
* \return A list of output data.
*/
Array<NDArray> GetOutput();
/*!
* \brief A pipeline params with a specific name correspond with the params of a specific
* backend module, this function return the module index for the params name.
* \param name The parameters group name.
* \return Return backend runtime module index.
*/
int GetParamModuleIndex(const std::string& name);
/*!
* \brief A pipeline input with a specific name correspond with a input of a specific
* backend module, this function return a module index and a input index in "pair"
* form for a input name.
* return Return a module index and a input index.
*/
std::pair<int, int> GetInputIndex(const std::string& name);
/*!\brief Load the module files information.*/
ModuleConfig& LoadModuleConfig(dmlc::JSONReader* reader) {
reader->BeginArray();
while (reader->NextArrayItem()) {
std::string key;
reader->BeginObject();
int mod_idx = -1;
std::string lib_name;
std::string json_name;
std::string params_name;
std::string dev;
while (reader->NextObjectItem(&key)) {
if (key == "mod_idx") {
reader->Read(&mod_idx);
} else if (key == "lib_name") {
reader->Read(&lib_name);
} else if (key == "json_name") {
reader->Read(&json_name);
} else if (key == "params_name") {
reader->Read(¶ms_name);
} else if (key == "dev") {
reader->Read(&dev);
} else {
LOG(FATAL) << "do not support key " << key;
}
}
ICHECK(mod_idx >= 0) << "Invalid mod_idx value " << mod_idx;
// Load the lib, json, and params information.
ICHECK(!lib_name.empty()) << "lib_name is empty.";
ICHECK(!json_name.empty()) << "json_name is empty.";
ICHECK(!params_name.empty()) << "params_name is empty.";
mod_config_[mod_idx] = GraphModuleLoadInfo(lib_name, json_name, params_name, dev);
}
return mod_config_;
}
private:
/*!\brief The class used to execute and schedule the pipeline logic.*/
PipelineScheduler pipeline_scheduler_;
/*!\brief The dependency information of each graph runtime module of the pipeline.*/
ConfigPipelineExecution pipeline_config_;
/*!\brief The map of global input and subgraph input.*/
InputConnectionConfig input_connection_config_;
/*!\brief The map includes global parameters groups and runtime modules.*/
ParamConnectionConfig param_connection_config_;
/*!\brief The module information used to create the graph runtimes.*/
ModuleConfig mod_config_;
/*!\brief How many outputs are in this pipeline executor.*/
size_t num_outputs_ = 0;
/*!The list of backend runtime module.*/
std::vector<std::shared_ptr<BackendRuntime>> runtimes_;
std::shared_ptr<GlobalRuntime> global_runtime_;
/*!\brief Json loader.*/
void LoadConfig(dmlc::JSONReader* reader) {
reader->BeginObject();
std::string key;
while (reader->NextObjectItem(&key)) {
if (key == "module_connection") {
reader->Read(&pipeline_config_);
} else if (key == "input_connection") {
reader->Read(&input_connection_config_);
} else if (key == "param_connection") {
reader->Read(¶m_connection_config_);
} else {
LOG(FATAL) << "do not support key " << key;
}
}
return;
}
};
} // namespace runtime
} // namespace tvm
#endif // TVM_RUNTIME_PIPELINE_PIPELINE_EXECUTOR_H_
| https://github.com/zk-ml/tachikoma |
src/runtime/pipeline/pipeline_scheduler.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#ifndef TVM_RUNTIME_PIPELINE_PIPELINE_SCHEDULER_H_
#define TVM_RUNTIME_PIPELINE_PIPELINE_SCHEDULER_H_
#include <tvm/runtime/module.h>
#include <tvm/runtime/packed_func.h>
#include <tvm/runtime/registry.h>
#include <fstream>
#include <memory>
#include <string>
#include <vector>
#include "pipeline_struct.h"
namespace tvm {
namespace runtime {
/*!
* \brief The class that executes the pipeline logic,it is used to initialize the thread pool,
execute and schedule pipeline tasks, allocate and manage memory, etc.
*/
class PipelineScheduler {
public:
/*!
* \brief Initialize the pipeline.
* \param modules The list of graph executor module.
* \param pipeline_config The dependency information of each graph executor module.
*/
std::shared_ptr<GlobalRuntime> PipelineInit(const std::vector<Module>& modules,
const ConfigPipelineExecution& pipeline_config,
const InputConnectionConfig& input_connection_config);
/*!
* \brief Running the pipeline logic.
* \param runtimes A list of backend runtime modules.
*/
void PipelineRun(const std::vector<std::shared_ptr<BackendRuntime>>& runtimes);
/*!
* \brief Get a list of outputs.
*/
Array<NDArray> PipelineGetOutput();
private:
/*!\brief The list of graph executors.*/
std::vector<Module> graph_modules_;
/*!\brief A list of NDArray used to storage outputs.*/
Array<NDArray> output_arrays_;
/*!\brief The global runtime to represent the pipeline executor.*/
std::shared_ptr<GlobalRuntime> global_runtime_;
};
} // namespace runtime
} // namespace tvm
#endif // TVM_RUNTIME_PIPELINE_PIPELINE_SCHEDULER_H_
| https://github.com/zk-ml/tachikoma |
src/runtime/pipeline/pipeline_struct.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#ifndef TVM_RUNTIME_PIPELINE_PIPELINE_STRUCT_H_
#define TVM_RUNTIME_PIPELINE_PIPELINE_STRUCT_H_
#include <assert.h>
#include <dlpack/dlpack.h>
#include <dmlc/json.h>
#include <tvm/runtime/ndarray.h>
#include <tvm/runtime/packed_func.h>
#include <tvm/runtime/threading_backend.h>
#include <atomic>
#include <condition_variable>
#include <functional>
#include <limits>
#include <memory>
#include <string>
#include <thread>
#include <unordered_map>
#include <utility>
#include <vector>
#include "spsc_queue.h"
namespace tvm {
namespace runtime {
#define GLOBAL_MODULE_INDEX -1
/*!
*\brief The function is used to build the binding configuration for a runtime. The first
* 'int' is the output index of the current runtime, the second 'int' is the index of child
* runtime, and the 'string' is the input name of child runtime.
*/
using BindingConfigParseFunc = std::function<void(int, int, std::string)>;
/*!
*\brief The 'pair' includes the module output index and the global output index.
* The first 'int' is the module output index, and the second 'int' is the global output index.
*/
using GlobalOutputPair = std::pair<int, int>;
/*!
*\brief The pair includes the module index and the module output index.
* The first 'int' is the module index, and the second 'int' is the module output index.
*/
using ModuleOutputPair = std::pair<int, int>;
/*!
*\brief The pair includes the runtime module index and the module input index.
* The first 'int' is the module index, and the second 'int' is the module input index.
*/
using ModuleInputPair = std::pair<int, int>;
/*!\brief The runtime module interface type.*/
enum InterfaceType {
INPUT = 0,
OUTPUT,
};
/*!\brief The state of the pipeline.*/
enum PipelineState {
STOPPED = 0,
RUNNING,
STOPPING,
};
/*!
*\brief The structure includes the module index and the module output index.
*/
struct ModuleInterfaceID {
ModuleInterfaceID() { SetID(0, 0, INPUT); }
ModuleInterfaceID(int runtime_index, int runtime_interface_index, InterfaceType type = INPUT) {
SetID(runtime_index, runtime_interface_index, type);
}
/*!
* \brief Set the value of ID.
* \param runtime_index The index of runtime.
* \param runtime_interface_index The index of interface.
* \param type The type of the interface.
*/
void SetID(int runtime_index, int runtime_interface_index, InterfaceType type) {
runtime_idx = runtime_index;
runtime_interface_idx = runtime_interface_index;
interface_type = type;
}
int runtime_idx;
union {
/*!\brief The output interface index.*/
int runtime_output_idx;
/*!\brief The input interface index.*/
int runtime_input_idx;
/*!\brief The interface index.*/
int runtime_interface_idx;
};
/*!\brief The interface type*/
InterfaceType interface_type;
ModuleInterfaceID& operator=(const struct ModuleInterfaceID& id) {
SetID(id.runtime_idx, id.runtime_interface_idx, id.interface_type);
return *this;
}
bool operator==(const struct ModuleInterfaceID& id) const {
return id.interface_type == interface_type &&
id.runtime_interface_idx == runtime_interface_idx && id.runtime_idx == runtime_idx;
}
};
/*!brief The hash function used to generate the hash value for the "ModuleInterfaceID" variable.*/
struct ModuleIDHash {
bool operator()(const ModuleInterfaceID& id) const {
int offset = sizeof(std::size_t) / 3;
return id.interface_type | id.runtime_interface_idx << offset | id.runtime_idx << offset * 2;
}
};
/*!\brief The data notification structure.*/
class DataNotify {
private:
/*!\brief The 'contitional variable' is used to wait for notification.*/
std::condition_variable notify_cv_;
/*!\brief The mutex is used to protect the 'conditional variable'.*/
std::mutex mutex_;
/*!\brief Whether a data is ready or not.*/
bool data_ready_ = false;
/*!\brief Whether the thread should exit or not.*/
std::atomic<bool> exit_state_{false};
/*!\brief The 'ModuleInterfaceID' of an interface which sent this notification.*/
ModuleInterfaceID notification_source_;
public:
/*!
* \brief Constructing the DataNotify class.
* \param source_interface_id The id of a runtime interface which is sending out the data
* notification.
*/
explicit DataNotify(ModuleInterfaceID source_interface_id) {
notification_source_ = source_interface_id;
}
/*!
* \brief Getting the notification target.
* \return The ID of the interface which is sending out the notification.
*/
ModuleInterfaceID GetNotifySource(void) { return notification_source_; }
/*!
*\brief Waiting for the notification.
*\return Returning the value 'false' when the notification is in a 'exit' state, else
* return true.
*/
bool Wait(void) {
std::unique_lock<std::mutex> lock(mutex_);
notify_cv_.wait(lock, [&] { return this->data_ready_; });
data_ready_ = false;
return !GetExitState();
}
/*!brief Sending the notification in which the related data is ready.*/
void Notify(void) {
{
std::lock_guard<std::mutex> lock(mutex_);
data_ready_ = true;
}
notify_cv_.notify_one();
}
/*!brief Sending the notification when the notification state changes into 'exit'.*/
void ExitNotify(void) {
exit_state_.store(true, std::memory_order_release);
Notify();
}
/*!
*\brief Getting the 'exit state'.
*\return Returning the value of 'exit_state_'
*/
bool GetExitState(void) { return exit_state_.load(std::memory_order_acquire); }
};
/*!\brief The container used to store the forwarding data of the pipeline.*/
class QueueData {
public:
explicit QueueData(DLTensor* data) {
if (data_ == data) {
LOG(FATAL) << "The value of 'data'(" << data << ") is the same as 'data_'(" << data_ << ")";
}
data_ = data;
SetAsDataOwner(false);
}
QueueData() { SetAsDataOwner(true); }
/*!\brief Doing a deep copy for the 'QueueData' structure.*/
QueueData& operator=(const QueueData& data) {
CreateCopyFrom(data.GetDLData());
return *this;
}
QueueData& operator=(const NDArray& from) {
CreateCopyFrom(const_cast<DLTensor*>(from.operator->()));
return *this;
}
QueueData& operator=(const DLTensor* from) {
CreateCopyFrom(from);
return *this;
}
/*!\brief Create a deep copy of the 'DLTensor' data.*/
DLTensor* CreateCopyFrom(const DLTensor* from) {
if (!from) {
LOG(FATAL) << "the 'from' pointer is a null pointer!";
return nullptr;
}
size_t fromLen = tvm::runtime::GetDataSize(*from);
size_t toLen = data_ ? tvm::runtime::GetDataSize(*data_) : 0;
if (fromLen != toLen) {
// If this container ownes the variable 'data_', then recreating the 'data_' variable.
if (IsDataOwner()) {
if (data_) {
TVMArrayFree(data_);
data_ = nullptr;
}
TVMArrayAlloc(from->shape, from->ndim, from->dtype.code, from->dtype.bits,
from->dtype.lanes, from->device.device_type, from->device.device_id, &data_);
} else {
LOG(FATAL) << "The 'from' data is not matched with the 'data_'.";
}
}
TVMArrayCopyFromTo(const_cast<DLTensor*>(from), data_, nullptr);
return data_;
}
/*!\brief Return a pointer to the 'DLTensor' data.*/
DLTensor* GetDLData() const { return data_; }
~QueueData() {
if (IsDataOwner() && data_) {
TVMArrayFree(data_);
data_ = nullptr;
}
}
private:
/*!\brief Pointer to the forwarding data.*/
DLTensor* data_ = nullptr;
/*!\brief Whether this container is the owner of the 'data_'.*/
bool is_data_owner_ = false;
/*!\brief Set the current container as the owner of the 'data_'.*/
void SetAsDataOwner(bool is_owner) { is_data_owner_ = is_owner; }
/*!Check whether the current container is the owner of the 'data_'.*/
bool IsDataOwner() const { return is_data_owner_; }
};
/*!
* \brief All binding information of an output interface.
*/
class ConfigBindings {
public:
/*!\brief Whether this binding is bound to the PipelineExecutor output interface.*/
bool IsGlobalOutput() const { return global_output_index_ > -1; }
/*!\brief Getting the global output index in the current binding.*/
int GetGlobalOutputIndex() const { return global_output_index_; }
/*!\brief Returning the binding configuration.*/
std::unordered_map<int, std::string>& Get() { return bindings_; }
/*!
* \brief Enumerating the binding configuration.
* \param parse_function The function is used to parse the binding configuration.
* \param output_idx The index of output interface is used for parsing.
*/
void VisitOutput(BindingConfigParseFunc parse_function, int output_idx) {
for (auto output : bindings_) {
parse_function(output_idx, output.first, output.second);
}
if (IsGlobalOutput()) {
parse_function(output_idx, GLOBAL_MODULE_INDEX, std::to_string(global_output_index_));
}
}
/*!
* \brief Create a module interface map from JSONReader.
* \param reader JSON reader.
*/
void Load(dmlc::JSONReader* reader) {
reader->BeginArray();
while (reader->NextArrayItem()) {
std::string key;
reader->BeginObject();
std::string input_name;
int mod_idx = std::numeric_limits<int>::min();
// Whether the output binding is global.
bool global_binding = false;
while (reader->NextObjectItem(&key)) {
if (key == "mod_idx") {
reader->Read(&mod_idx);
} else if (key == "input_name") {
reader->Read(&input_name);
} else if (key == "global_output_index") {
// There should be only one global binding.
ICHECK(global_output_index_ < 0);
reader->Read(&global_output_index_);
// When the key value is 'global_output_index', it means that this output is bound to
// a global interface.
global_binding = true;
} else {
LOG(FATAL) << "do not support key " << key;
}
}
// When this output is bound to a global interface, check if the global interface index
// start from 0.
if (global_binding) {
ICHECK(global_output_index_ >= 0);
} else {
// When this output is bound to a graph executor module interface, check if the module
// index start from 0.
ICHECK(mod_idx >= 0);
bindings_[mod_idx] = input_name;
}
}
}
private:
/*!\brief Output interface binding information, 'int' is the index of the module that
* uses this output data as the input interface data, 'string' is the input interface name
* of the module.
*/
std::unordered_map<int, std::string> bindings_;
/*! The index value of the global interface to which the current output are bound.*/
int global_output_index_ = std::numeric_limits<int>::min();
};
/*!
* \brief The binding information of all outputs of a module.
*/
class ConfigRuntime {
public:
ConfigRuntime& operator=(const ConfigRuntime& output) {
output_binding_map_ = output.GetOutBindings();
cpu_affinity_ = output.GetCPUAffinity();
return *this;
}
ConfigBindings& operator[](const int key) {
ICHECK(output_binding_map_.find(key) != output_binding_map_.end());
return output_binding_map_[key];
}
/*!
* \brief Store the CPU affinity settings.
* \param cpu_affinity The CPU affinity settings in the text form.
*/
void StoreCPUAffinity(std::string cpu_affinity) { cpu_affinity_ = cpu_affinity; }
/*!
* \brief Getting the setting of the cpu affinity.
* \param Returning the cpu affinity in text form.
*/
std::string GetCPUAffinity() const { return cpu_affinity_; }
/*!
* \brief Enumerating the output configuration.
* \param parse_function The callback function is used to parse the binding configeration.
*/
void VisitOutputConfig(BindingConfigParseFunc parse_function) {
for (auto output : output_binding_map_) {
output.second.VisitOutput(parse_function, output.first);
}
}
/*!brief Return the variable "output_binding_map_".*/
std::unordered_map<int, ConfigBindings> GetOutBindings() const { return output_binding_map_; }
/*!
*\brief This function is used to verify whether ConfigRuntime is successfully loaded.
*\return Return true to indicate that this class has not been successfully loaded.
*/
bool Empty() { return output_binding_map_.empty(); }
/*!
* \brief The pipeline outputs is the final outputs of pipeline, this function is used to
* get how many pipeline outputs are in this Outputmap
* \return Number of pipeline outputs.
*/
size_t GetGlobalOutputNum(void) const {
size_t num_output = 0;
for (auto bindings : output_binding_map_) {
num_output += bindings.second.IsGlobalOutput() ? 1 : 0;
}
return num_output;
}
/*!
*\brief Getting the map which includes the global outputs and the current module outputs.
*\return A list of "GlobalOutputPair".
*/
std::vector<GlobalOutputPair> GetGlobalConfigOutputBindings(void) const {
std::vector<GlobalOutputPair> ret;
for (auto bindings : output_binding_map_) {
if (bindings.second.IsGlobalOutput()) {
ret.push_back(GlobalOutputPair(bindings.first, bindings.second.GetGlobalOutputIndex()));
}
}
return ret;
}
/*!
* \brief Create an output binding map from JSONReader.
* \param reader Json reader.
*/
void Load(dmlc::JSONReader* reader) {
reader->BeginArray();
while (reader->NextArrayItem()) {
std::string key;
reader->BeginObject();
int output_idx = -1;
ConfigBindings binding;
while (reader->NextObjectItem(&key)) {
if (key == "output_idx") {
reader->Read(&output_idx);
} else if (key == "dependencies") {
reader->Read(&binding);
} else {
LOG(FATAL) << "do not support key " << key;
}
}
ICHECK(output_idx >= 0);
output_binding_map_[output_idx] = binding;
}
}
private:
/*!\brief The map of output binding, 'int' is the output interface index.*/
std::unordered_map<int, ConfigBindings> output_binding_map_;
/*!\brief The cpu affinity setting for the tvm thread pool.*/
std::string cpu_affinity_;
};
/*!
* \brief The binding or dependency information of each module output interface.
*/
class ConfigPipelineExecution {
public:
ConfigRuntime& operator[](int key) {
ICHECK(config_.find(key) != config_.end());
return config_[key];
}
/*Get the cpu affinity settings.*/
std::string GetCPUAffinity(int runtime_idx) {
auto config = config_.find(runtime_idx);
if (config == config_.end()) {
LOG(FATAL) << "Do not finding the runtime " << runtime_idx;
}
auto config_runtime = config->second;
return config_runtime.GetCPUAffinity();
}
/*!
* \brief Enumerating the binding configuration for a specified runtime.
* \param parse_function The callback function is used to parse the binding configuration.
* \param runtime_index The index of a runtime is used to parse the binding configuration.
*/
void VisitRuntimeOutputConfig(BindingConfigParseFunc parse_function, int runtime_index) {
auto config = config_.find(runtime_index);
if (config == config_.end()) {
LOG(FATAL) << "Do not finding the runtime " << runtime_index;
}
config->second.VisitOutputConfig(parse_function);
}
/*
*!\brief This function is used to verify whether config is loaded successfully.
* \return Return "true" to indicate that this class has not been successfully loaded.
*/
bool Empty() { return config_.empty(); }
/*!
*\brief Check if the module index existing in the "config".
*/
bool FindModuleInConfig(int mod_idx) { return config_.find(mod_idx) != config_.end(); }
/*!
* \brief Getting the number of global outputs.
* \return The number of outputs in the entire pipeline.
*/
size_t GetGlobalOutputNum() const {
size_t num_output = 0;
for (auto mod_output : config_) {
num_output += mod_output.second.GetGlobalOutputNum();
}
return num_output;
}
/*
*!\brief Get the map of global outputs and module outputs.
*/
std::unordered_map<int, ModuleOutputPair> GetGlobalConfigOutputBindings(void) const {
return global_output_map_;
}
/*
*!\brief Parsing the configuration.
*/
void ParseConfiguration(const std::unordered_map<int, ConfigRuntime>& config) {
if (config.empty()) {
LOG(FATAL) << "The Configuration loading not finish yet.";
}
for (auto mod_output : config) {
// Using the global output index as the key to create a map including global index and
// module output index.
const std::vector<GlobalOutputPair>& global_output =
mod_output.second.GetGlobalConfigOutputBindings();
for (auto output : global_output) {
global_output_map_[output.second] = ModuleOutputPair(mod_output.first, output.first);
}
}
return;
}
/*!
* \brief Create a pipeline config from JSONReader.
* \param reader Json reader.
*/
void Load(dmlc::JSONReader* reader) {
reader->BeginArray();
while (reader->NextArrayItem()) {
std::string key;
reader->BeginObject();
int mod_idx = -1;
ConfigRuntime output;
std::string dev;
std::string cpu_affinity;
while (reader->NextObjectItem(&key)) {
if (key == "mod_idx") {
reader->Read(&mod_idx);
} else if (key == "dev") {
reader->Read(&dev);
} else if (key == "output") {
reader->Read(&output);
} else if (key == "cpu_affinity") {
reader->Read(&cpu_affinity);
} else {
LOG(FATAL) << "do not support key " << key;
}
}
ICHECK(mod_idx >= 0) << "Invalid mod_idx value " << mod_idx;
// Check if the output is successfully read.
ICHECK(!output.Empty()) << "Invalid output binding result.";
// Store the cpu affinity into the 'ConfigRuntime' structure.
output.StoreCPUAffinity(cpu_affinity);
// Build the mapping of mod_idx and "ConfigRuntime".
config_[mod_idx] = output;
}
// Doing the configuration parsing after the loading finished.
ParseConfiguration(config_);
}
private:
/*
*!\brief The key is the module index, this variable records all module pipeline configuration
* information.
*/
std::unordered_map<int, ConfigRuntime> config_;
/*
*\brief The key is the global output index, and the map is including global outputs index and
* the module outputs pair.
*/
std::unordered_map<int, ModuleOutputPair> global_output_map_;
};
struct InputConnectionConfig {
/*!\brief The key("string") is the name of global module input interfaces. The value("pair")
* includes the index of graph module and the name of a graph module input interface.
*/
std::unordered_map<std::string, std::pair<int, std::string>> input_connection;
/*!\brief The map includes the global input name and global input index.*/
std::unordered_map<std::string, int> input_name_index_map;
/*!
* \brief The map not only includes the runtime index ,but also the pair of global interface
* and runtime interface.
*/
std::unordered_map<int, std::vector<std::pair<std::string, std::string>>> input_runtime_map;
std::pair<int, std::string> operator[](const std::string key) {
if (input_connection.find(key) == input_connection.end()) {
LOG(FATAL) << "Not find the key " << key;
}
return input_connection[key];
}
/*!\brief Returns the number of global inputs through the input_runtime_map list size.*/
int GetInputNum() { return input_runtime_map.size(); }
/*!
* \brief Getting the global input index through the input name.
* \param input_name The global input name.
*/
int GetInputIndex(std::string input_name) {
auto input_index_iter = input_name_index_map.find(input_name);
if (input_index_iter == input_name_index_map.end()) {
LOG(FATAL) << "Do not finding the input name! " << input_name;
}
return input_index_iter->second;
}
/*!\brief Enumerating the input binding configuration for a specified runtime.*/
void VisitConfig(BindingConfigParseFunc parse_function, int runtime_index) {
auto config = input_runtime_map.find(runtime_index);
// Only do the processing when there are input configuration in the runtime.
if (config != input_runtime_map.end()) {
for (auto x : config->second) {
int input_index = GetInputIndex(x.first);
parse_function(input_index, runtime_index, x.second);
}
}
}
/*!
* \brief Create an input connection config from JSONReader.
* \param reader Json reader.
*/
void Load(dmlc::JSONReader* reader) {
int global_interface_index = 0;
reader->BeginArray();
while (reader->NextArrayItem()) {
reader->BeginObject();
std::string key;
std::string global_interface_name;
std::string module_interface_name;
int mod_idx = -1;
while (reader->NextObjectItem(&key)) {
if (key == "global_interface_name") {
reader->Read(&global_interface_name);
input_name_index_map[global_interface_name] = global_interface_index++;
} else if (key == "mod_idx") {
reader->Read(&mod_idx);
} else if (key == "module_interface_name") {
reader->Read(&module_interface_name);
} else {
LOG(FATAL) << "do not support key " << key;
}
}
ICHECK(mod_idx >= 0) << "Invalid mod_idx value " << mod_idx;
ICHECK(!global_interface_name.empty()) << "Invalid global interface name value";
ICHECK(!module_interface_name.empty()) << "Invalid module interface name value";
input_connection[global_interface_name] = make_pair(mod_idx, module_interface_name);
// Creating a map which not only includes the runtime index, but also the pair of gloal
// interface, and runtime interface.
input_runtime_map[mod_idx].push_back(
std::make_pair(global_interface_name, module_interface_name));
}
}
};
/*!
* \brief A map includes global module parameters groups and graph modudles.
*/
struct ParamConnectionConfig {
/*!\brief Mapping from the name of a global module parameters group to the index of a runtime
* module.
*/
std::unordered_map<std::string, int> param_connection;
bool Empty() { return param_connection.empty(); }
int operator[](const std::string key) {
if (param_connection.find(key) == param_connection.end()) {
LOG(FATAL) << "do not support key " << key;
}
return param_connection[key];
}
/*!
* \brief Load from JSONReader.
* \param reader Json reader.
*/
void Load(dmlc::JSONReader* reader) {
reader->BeginArray();
while (reader->NextArrayItem()) {
reader->BeginObject();
std::string key;
std::string global_param_name;
int mod_idx = -1;
while (reader->NextObjectItem(&key)) {
if (key == "global_param_name") {
reader->Read(&global_param_name);
} else if (key == "mod_idx") {
reader->Read(&mod_idx);
} else {
LOG(FATAL) << "do not support key " << key;
}
}
ICHECK(mod_idx >= 0) << "Invalid module index value " << mod_idx;
ICHECK(!global_param_name.empty()) << "Invalid global parameter group name value";
param_connection[global_param_name] = mod_idx;
}
}
};
/*!
* \brief The single consumer single producer queue which is used to forward data between two
* interfaces of backend cores.
*/
using ForwardQueue = SPSCLockFreeQueue<QueueData, ModuleInterfaceID>;
using ForwardQueueMap =
std::unordered_map<ModuleInterfaceID, std::shared_ptr<ForwardQueue>, ModuleIDHash>;
/*!\brief The basic class for runtime.*/
class BasicRuntime {
using ModuleInputPairList = std::vector<std::pair<std::shared_ptr<BasicRuntime>, int>>;
public:
explicit BasicRuntime(int runtime_idx) : runtime_idx_(runtime_idx) {}
/*!\brief Return the index of the current module.*/
int GetModuleIndex() { return runtime_idx_; }
/*!\brief Setting the data into this runtime via the input index.*/
virtual void SetInput(const int index, DLTensor* data_in) {}
/*!
* \brief Sending a notification when data is ready.
* \param input_index The index of an input interface which have data ready.
*/
virtual void ParentNotify(int input_index) {}
/*!
*\brief Creating a parent notification.
*\param input_index The input index of the 'current runtime'.
*\param parent_idx The index of 'parent runtime' which will send the notification.
*\param parent_output_idx The output index of the 'parent runtime' which will send
* the notification.
*/
void CreateParentsNotify(int input_index, int parent_idx, int parent_output_idx) {
if (parents_notify_.find(input_index) != parents_notify_.end()) {
LOG(FATAL) << "The notification associated with the input interface " << input_index
<< " in runtime " << runtime_idx_ << " already been created!";
return;
}
parents_notify_[input_index] =
std::make_shared<DataNotify>(ModuleInterfaceID(parent_idx, parent_output_idx, OUTPUT));
}
protected:
/*!\brief The index of runtime indicates the runtime position in the pipeline.*/
int runtime_idx_;
/*!\brief A list of runtime which depends on the current runtime.*/
std::unordered_map<int, ModuleInputPairList> children_;
/*!\brief The map includes the runtime input index and the notification data structure.*/
std::unordered_map<int, std::shared_ptr<DataNotify>> parents_notify_;
/*!
* \brief There is a list of SPSC input queues in which the input interface would poll the
* data comed from other backend cores.
*/
std::unordered_map<int, std::shared_ptr<ForwardQueue>> input_queue_;
/*!
* \brief A list of SPSC forward queues in which the parent interface will push the data to
* other backend cores.
*/
std::unordered_map<int, ForwardQueueMap> forward_queue_;
/*!\brief The state of the pipeline.*/
std::atomic<PipelineState> pipeline_state_{STOPPED};
/*!
* \brief Generate the ID of an input queue.
* \param runtime_index The index of backend runtime.
* \param interface_index The index of the interface.
* \param type The type of the interface.
*/
ModuleInterfaceID GenerateQueueID(int runtime_index, int interface_index, InterfaceType type) {
return ModuleInterfaceID(runtime_index, interface_index, type);
}
/*!
* \brief Forwarding the data into the child runtimes.
* \param forward_queue_map The map includes the id and the queue.
* \param child_runtime The child runtime.
* \param child_input_index The child runtime index.
* \param data The data is used for forwarding.
*/
bool ForwardData(const ForwardQueueMap* forward_queue_map,
std::shared_ptr<BasicRuntime> child_runtime, int child_input_index,
const DLTensor* data) {
auto child_runtime_index = child_runtime->GetModuleIndex();
auto queue_id = GenerateQueueID(child_runtime_index, child_input_index, INPUT);
if (forward_queue_map->find(queue_id) == forward_queue_map->end()) {
LOG(FATAL) << "Not find the associated queue of the runtime(" << child_runtime_index
<< ").input(" << child_input_index << ") which is connected with runtime("
<< runtime_idx_;
}
auto forward_queue = forward_queue_map->at(queue_id);
// If the queue is full, keep try until the push get success or the pipeline run into
// a STOP state.
while (!forward_queue->Push<const DLTensor*>(data)) {
if (PipelineIsStop()) {
LOG(INFO) << "The forwarding process is stopped after the pipeline status is changed"
<< " into stop.";
return false;
}
}
child_runtime->ParentNotify(child_input_index);
return true;
}
/*!
* \brief Creating a forwarding queue for the pair of an output interface and an input interface.
* \param forward_inf_idx The index of an interface which will send the forwarding data.
* \param child_runtime The backend runtime which owns the input interface.
* \param input_index The index of an input interface. This interface will receive the
* forwarding data.
*/
void CreateForwardingQueue(int forward_inf_idx, std::shared_ptr<BasicRuntime> child_runtime,
int input_index) {
auto queue_id = GenerateQueueID(child_runtime->GetModuleIndex(), input_index, INPUT);
// The forwarding queue map of a specified output interface.
auto& queue_map = forward_queue_[forward_inf_idx];
if (queue_map.find(queue_id) != queue_map.end()) {
LOG(FATAL) << "The queue " << queue_id.runtime_idx << "." << queue_id.runtime_interface_idx
<< " is already created!";
return;
}
auto queue = std::make_shared<ForwardQueue>(queue_id);
queue_map[queue_id] = queue;
// Use the created queue as the consumer queue for the input interface of this forwarding
// pair.
child_runtime->AppendInputQueue(input_index, queue);
}
/*!
* \brief Setting the consumer queue for the input interface.
* \param input_index The index of the input interface.
* \param queue The consumer queue.
*/
void AppendInputQueue(int input_index, std::shared_ptr<ForwardQueue> queue) {
input_queue_[input_index] = queue;
}
/*!\brief Checking if the pipeline is stopped or stopping.*/
const bool PipelineIsStop() const {
auto state = pipeline_state_.load(std::memory_order_acquire);
return state == STOPPING || state == STOPPED;
}
};
/*
*!\brief Backend Runtime.
*/
class BackendRuntime : public BasicRuntime {
private:
/*!The cpu affinity settings for this runtime.*/
std::string cpu_affinity_ = "";
/*!\brief The Runtime module of a backend graph executor.*/
Module module_;
/*\brief The thread is associated with the current runtime*/
std::thread thread_;
/*!\brief The execution count of the 'RunPipeline' function. */
uint32_t pipeline_execution_count_ = 0;
/*!
*\brief In order to transfer data from one backend runtime to another, we need a local
* tensor variable as a medium. "input_tensor_local_copy_" is a map including
* input data and local tensor vairable.
*/
std::unordered_map<DLTensor*, DLTensor*> input_tensor_local_copy_;
/*!\brief The packed functions.*/
tvm::runtime::PackedFunc set_input_;
tvm::runtime::PackedFunc get_input_;
tvm::runtime::PackedFunc get_output_;
tvm::runtime::PackedFunc get_num_output_;
tvm::runtime::PackedFunc get_num_inputs_;
tvm::runtime::PackedFunc get_input_index_;
tvm::runtime::PackedFunc run_;
/*!\brief The worker thread is used to execute the runtimes in pipeline.*/
void StartWorkThread() {
SetPipelineState(RUNNING);
if (runtime_idx_ == 0) {
this->SetCPUAffinity();
} else {
// Only launching the worker thread for the runtimes after the first runtime.
thread_ = std::thread([&]() {
this->SetCPUAffinity();
while (!this->WaitAndLoadPipelineData()) {
if (!this->RunPipeline()) {
break;
}
}
VLOG(1) << "Runtime " << this->runtime_idx_ << " exit.";
});
}
return;
}
/*!\brief Setting the state of the pipeline.*/
void SetPipelineState(PipelineState state) {
pipeline_state_.store(state, std::memory_order_release);
}
/*!\brief Stopping the threads in pipeline.*/
void StopPipeline() {
SetPipelineState(STOPPING);
for (auto notify : parents_notify_) {
notify.second->ExitNotify();
}
if (thread_.joinable()) {
thread_.join();
}
SetPipelineState(STOPPED);
}
/*!
* \brief Waiting for the internal forwarding data.
* \return Returning 'true' when getting a 'exit' notification otherwise returning 'false'.
*/
bool WaitAndLoadPipelineData() {
std::unordered_map<int, std::shared_ptr<DataNotify>> notifys = parents_notify_;
bool exit_notify = false;
while (!notifys.empty() && !exit_notify) {
auto notify = notifys.begin();
// Breaking the loop when the notification is in the exit state.
if ((exit_notify = notify->second->GetExitState())) break;
// Getting the source which sends this notification.
auto target_input_interface_index = notify->first;
// Loading the binding data.
while (!this->LoadBindingData(target_input_interface_index)) {
// Waiting for the notification.
if (!notify->second->Wait()) {
exit_notify = true;
break;
}
}
notifys.erase(notify);
}
return exit_notify;
}
/*!
* \brief Loading the binding data.
* \param input_index The index of the interface which will receive the forwarding data.
* \return Returning 'true' when data is loaded successfully, otherwise returning 'false'.
*/
bool LoadBindingData(int input_index) {
if (input_queue_.find(input_index) == input_queue_.end()) {
LOG(FATAL) << "Not finding the associated input queue of the input " << input_index << " !";
return false;
}
auto queue = input_queue_[input_index];
QueueData data;
// TODO(huajsj): Doing the 'SetInput' inside the poll function to avoid one time data copy.
if (!queue->Poll<QueueData>(&data)) {
return false;
}
SetInput(input_index, data.GetDLData());
return true;
}
/*!
* \brief Forwarding the output data into the child runtimes.
* \return bool Return false when the "PipelineIsStop" function returns true or this function
* reaches some errors. Otherwise, return true.
*/
bool ForwardingOutputDataToChildren(void) {
for (auto child : children_) {
auto output_idx = child.first;
if (forward_queue_.find(output_idx) == forward_queue_.end()) {
LOG(FATAL) << "Not find the forwarding queue map for output(" << output_idx << ")!";
return false;
}
NDArray output = GetOutput(output_idx);
auto forward_queue_map = forward_queue_[output_idx];
// Notifying the 'children runtime' that the forwarding data are ready.
for (auto module_pair : child.second) {
auto child_runtime = module_pair.first;
auto child_input_index = module_pair.second;
auto output_data = const_cast<DLTensor*>(output.operator->());
if (!ForwardData(&forward_queue_map, child_runtime, child_input_index, output_data)) {
return false;
}
}
}
return true;
}
/*!
* \brief Copying from a given tensor and using 'CPU' as the device.
*/
inline DLTensor* CopyDLTensorToCPU(const DLTensor* from) {
DLTensor* ret = NULL;
TVMArrayAlloc(from->shape, from->ndim, from->dtype.code, from->dtype.bits, from->dtype.lanes,
kDLCPU, 0, &ret);
return ret;
}
/*!\brief Creating a new NDArray with same shape and data type as the given DLTensor.*/
NDArray CreateNDArrayFromDLTensor(const DLTensor* from) {
std::vector<int64_t> shape;
for (int i = 0; i < from->ndim; i++) {
shape.push_back(from->shape[i]);
}
auto ndarray = NDArray::Empty(shape, from->dtype, from->device);
ndarray.CreateView(shape, from->dtype);
return ndarray;
}
/*
*\brief Copying data from one DLTensor to another.
*/
void CopyFromTo(DLTensor* from, DLTensor* to) {
// When the 'from' device and the 'to' device are not the same, we use a temporary CPU
// DLTensor as the bridge.
if (from->device.device_type != to->device.device_type && from->device.device_type != kDLCPU &&
to->device.device_type != kDLCPU) {
DLTensor* dltensor_local = nullptr;
if (input_tensor_local_copy_.find(to) == input_tensor_local_copy_.end()) {
dltensor_local = CopyDLTensorToCPU(from);
input_tensor_local_copy_[to] = dltensor_local;
} else {
dltensor_local = input_tensor_local_copy_[to];
}
TVMArrayCopyFromTo(from, dltensor_local, nullptr);
from = dltensor_local;
}
TVMArrayCopyFromTo(from, to, nullptr);
}
/*!\brief Setting the cpu affinity for the tvm threads pool in the current BackendRuntime.*/
void SetCPUAffinity(void) {
if (cpu_affinity_.empty()) {
return;
}
auto affinity_mode = tvm::runtime::threading::ThreadGroup::kSpecifyThreadShareAllCore;
std::istringstream istr(cpu_affinity_);
std::string affinity;
std::vector<unsigned int> cpus;
while (getline(istr, affinity, ',')) {
cpus.push_back(std::stoi(affinity));
}
tvm::runtime::threading::Configure(affinity_mode, 0, cpus);
}
public:
BackendRuntime(Module mod, int mod_idx) : BasicRuntime(mod_idx), module_(mod) {
get_input_index_ = module_.GetFunction("get_input_index");
get_num_output_ = module_.GetFunction("get_num_outputs");
get_num_inputs_ = module_.GetFunction("get_num_inputs");
set_input_ = module_.GetFunction("set_input");
get_input_ = module_.GetFunction("get_input");
get_output_ = module_.GetFunction("get_output");
run_ = module_.GetFunction("run");
}
~BackendRuntime() {
for (auto data : input_tensor_local_copy_) {
TVMArrayFree(data.second);
}
StopPipeline();
}
/*!
* \brief Getting the times of using pipeline function.
* \return The times of using pipeline function.
*/
int GetExecutionCount() const { return pipeline_execution_count_; }
/*!
* \brief Initializing data structures for the pipeline execution.
* \param config The pipeline configueration.
* \param runtimes A list of BackendRuntime.
*/
void InitializePipeline(ConfigPipelineExecution config,
std::vector<std::shared_ptr<BackendRuntime>>* runtimes,
std::shared_ptr<BasicRuntime> global_runtime) {
// Getting the current BackendRuntime's cpu affinity setting.
cpu_affinity_ = config.GetCPUAffinity(runtime_idx_);
// Getting the 'binding configuration' for each child runtime.
config.VisitRuntimeOutputConfig(
[&](int output_idx, int child_idx, std::string child_input_name) {
std::shared_ptr<BasicRuntime> child_runtime = nullptr;
int input_index;
if (GLOBAL_MODULE_INDEX == child_idx) {
int global_output_index = std::stoi(child_input_name);
input_index = global_output_index;
child_runtime = global_runtime;
} else {
int runtime_idx_max = runtimes->size();
if (child_idx < 0 || child_idx >= runtime_idx_max) {
LOG(FATAL) << "The runtime index " << child_idx << " is out of the range.";
}
auto runtime = runtimes->at(child_idx);
ICHECK(runtime->GetModuleIndex() == child_idx);
input_index = runtime->GetInputIndex(child_input_name);
if (input_index < 0) {
LOG(FATAL) << "Can not find the input " << input_index << "in runtime " << child_idx;
}
child_runtime = runtime;
}
ICHECK(child_runtime != nullptr);
children_[output_idx].push_back(std::make_pair(child_runtime, input_index));
child_runtime->CreateParentsNotify(input_index, runtime_idx_, output_idx);
VLOG(1) << " parent_idx.output:" << runtime_idx_ << "." << output_idx
<< " child.input:" << child_idx << "." << input_index;
// Creating the pipeline forwarding queue.
this->CreateForwardingQueue(output_idx, child_runtime, input_index);
},
runtime_idx_);
StartWorkThread();
}
/*!
* \brief Notifying an input is ready.
* \param input_index The index of 'input interface' which is ready for data.
*/
void ParentNotify(int input_index) {
auto notify = parents_notify_.find(input_index);
if (notify == parents_notify_.end()) {
LOG(FATAL) << "Can not find the input for index " << input_index << " in runtime"
<< runtime_idx_;
return;
}
notify->second->Notify();
}
/*!\brief Creating a NDArray containing same shape and data type with a module output. */
NDArray CreateFromOutput(int idx) {
NDArray data = get_output_(idx);
return CreateNDArrayFromDLTensor(const_cast<DLTensor*>(data.operator->()));
}
/*!\brief Return the number of output*/
int NumOutputs() const { return get_num_output_(); }
/*!\brief Return the number of input*/
int NumInputs() const { return get_num_inputs_(); }
/*!\brief Setting the data to this runtime via input index.*/
void SetInput(const int index, DLTensor* data_in) {
NDArray input = get_input_(index);
DLTensor* dltensor_input = const_cast<DLTensor*>(input.operator->());
CopyFromTo(data_in, dltensor_input);
}
/*!\brief Setting the data to the current runtime moduel via the input name. */
void SetInput(const std::string name, DLTensor* data_in) {
int index = this->GetInputIndex(name);
SetInput(index, data_in);
}
/*!\brief Getting the input data via the input index.*/
NDArray GetInput(int index) const { return get_input_(index); }
/*!\bief Getting the input data via the input name.*/
int GetInputIndex(const std::string& name) { return get_input_index_(name); }
/*!\brief Using the output index to get the module output.*/
NDArray GetOutput(int index) { return get_output_(index); }
/*!\brief Running the runtime.*/
void Run() { run_(); }
/*!
* \brief Running the runtime in the pipeline mode.
* \return Returning false if the forwarding function failed. Otherwise, returning true.;
*/
bool RunPipeline() {
Run();
bool ret = ForwardingOutputDataToChildren();
pipeline_execution_count_++;
return ret;
}
};
/*!
* \brief This global runtime represents the pipeline executor and exposes the input and output
* interface.
*/
class GlobalRuntime : public BasicRuntime {
public:
explicit GlobalRuntime(int runtime_idx) : BasicRuntime(runtime_idx) {}
/**/
std::vector<std::shared_ptr<BackendRuntime>> GetRuntimeList() { return runtimes_; }
/*!\brief Push the data into the queue for the current runtime.*/
void SetPipelineInput(const std::string input_name, DLTensor* data_in) {
auto input_index = input_config_.GetInputIndex(input_name);
auto child_iter = children_.find(input_index);
if (child_iter == children_.end()) {
return;
}
auto forward_queue_map = forward_queue_[input_index];
// Notifying the 'children runtime' that the forwarding data are ready.
for (auto module_pair : child_iter->second) {
auto child_runtime = module_pair.first;
auto child_input_index = module_pair.second;
// No need to go through the forward queue when the runtime is the first one.
if (child_runtime->GetModuleIndex() == 0) {
child_runtime->SetInput(child_input_index, data_in);
} else {
if (!ForwardData(&forward_queue_map, child_runtime, child_input_index, data_in)) {
return;
}
}
}
return;
}
/*!\brief Whether the output data is ready.*/
bool DataIsReady(bool wait_data) {
bool data_ready = true;
for (auto queue_pair : input_queue_) {
auto queue = queue_pair.second;
if (queue->Empty()) {
data_ready = false;
break;
}
}
if (!data_ready && wait_data) {
// TODO(huajsj): Waitting the data ready message.
}
return data_ready;
}
/*!\brief Get the output data.*/
bool GetOutput(Array<NDArray>* outputs, bool wait_data = false) {
if (!DataIsReady(wait_data)) {
return false;
}
for (auto queue_pair : input_queue_) {
auto output_index = queue_pair.first;
auto queue = queue_pair.second;
QueueData data(const_cast<DLTensor*>(((*outputs)[output_index]).operator->()));
if (!queue->Poll<QueueData>(&data)) {
LOG(FATAL) << "There is no data in the data queue, it should not happen!";
}
}
return true;
}
/*!\brief Initialized the data structures for pipeline.*/
void InitializePipeline(InputConnectionConfig input_config,
const std::vector<std::shared_ptr<BackendRuntime>> runtimes) {
input_config_ = input_config;
runtimes_ = runtimes;
for (auto child_runtime : runtimes) {
int runtime_idx = child_runtime->GetModuleIndex();
input_config.VisitConfig(
[&](int input_index, int child_idx, std::string child_input_name) {
auto child_input_index = child_runtime->GetInputIndex(child_input_name);
if (child_input_index < 0) {
LOG(FATAL) << "Can not find the input " << child_input_name << "in runtime "
<< child_idx;
}
children_[input_index].push_back(std::make_pair(child_runtime, child_input_index));
// Only create notify and queue for the runtime after the first runtime.
if (runtime_idx != 0) {
child_runtime->CreateParentsNotify(input_index, GLOBAL_MODULE_INDEX,
child_input_index);
// Creating the pipeline forwarding queue.
this->CreateForwardingQueue(input_index, child_runtime, child_input_index);
}
},
runtime_idx);
}
}
private:
std::vector<std::shared_ptr<BackendRuntime>> runtimes_;
InputConnectionConfig input_config_;
};
/*!
* \brief The information used to initialize the graph executor module, the information
* come from the export library function call.
*/
struct GraphModuleLoadInfo {
GraphModuleLoadInfo(const std::string& lib, const std::string& json, const std::string& params,
const std::string& device)
: lib_name(lib), json_name(json), params_name(params), dev(device) {}
GraphModuleLoadInfo() { ; }
std::string lib_name;
std::string json_name;
std::string params_name;
std::string dev;
};
/*! The Module information of each module.The 'int' is module index. */
using ModuleConfig = std::unordered_map<int, GraphModuleLoadInfo>;
}; // namespace runtime
}; // namespace tvm
#endif // TVM_RUNTIME_PIPELINE_PIPELINE_STRUCT_H_
| https://github.com/zk-ml/tachikoma |
src/runtime/pipeline/spsc_queue.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#ifndef TVM_RUNTIME_PIPELINE_SPSC_QUEUE_H_
#define TVM_RUNTIME_PIPELINE_SPSC_QUEUE_H_
#include <cstddef>
#include <thread>
/*!\brief A single producer and single consumer lock free queue.
*/
template <typename SlotType, typename IDType = int, int QueueLength = 1024>
class SPSCLockFreeQueue {
public:
explicit SPSCLockFreeQueue(IDType id) : id_(id) {}
/*A read barrier enforcing the CPU to performe the reads before this barrier.*/
inline void read_barrier() { std::atomic_thread_fence(std::memory_order_acquire); }
/*A write barrier enforcing the CPU to performe the writes before this barrier.*/
inline void write_barrier() { std::atomic_thread_fence(std::memory_order_release); }
/*!\brief Checking whether the queue is full.*/
bool Full() {
read_barrier();
return ((tail_ + 1) % len_) == head_;
}
/*!brief Checking whether the queue is empty.*/
bool Empty() {
read_barrier();
return head_ == tail_;
}
/*!
* \brief Pushing the data into the queue. Only a single producer will call this function.
* \param data The data which is pushed into the queue.
* \return Return false when the queue is full. Otherwise, return true.
*/
template <typename data_type>
bool Push(const data_type& data) {
if (Full()) return false;
queue_[tail_] = data;
write_barrier();
tail_ = (tail_ + 1) % len_;
return true;
}
/*!
* \brief Poll the data from the front of the queue. Only the single consumer will call this
* function.
* \param data A pointer to the structure which stores the polled data..
* \return Returning false when the queue is empty. Otherwise, return true.
*/
template <typename data_type>
bool Poll(data_type* data) {
if (Empty()) return false;
*data = queue_[head_];
write_barrier();
head_ = (head_ + 1) % len_;
return true;
}
private:
/*!\brief The pointer points to the first slot with valid data in the queue.*/
size_t head_ = 0;
/*!\brief The end of the queue at which elements are added.*/
size_t tail_ = 0;
/*!\brief The length of the queue.*/
size_t len_ = QueueLength;
/*!\brief The queue used to store the data.*/
SlotType queue_[QueueLength];
/*!\brief The ID of the queue.*/
IDType id_;
};
#endif // TVM_RUNTIME_PIPELINE_SPSC_QUEUE_H_
| https://github.com/zk-ml/tachikoma |
src/runtime/rocm/rocm_common.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* \file rocm_common.h
* \brief Common utilities for ROCM
*/
#ifndef TVM_RUNTIME_ROCM_ROCM_COMMON_H_
#define TVM_RUNTIME_ROCM_ROCM_COMMON_H_
#include <hip/hip_runtime_api.h>
#include <hip/hip_version.h>
#include <tvm/runtime/packed_func.h>
#include <string>
#include "../workspace_pool.h"
namespace tvm {
namespace runtime {
#define ROCM_DRIVER_CALL(x) \
{ \
hipError_t result = x; \
if (result != hipSuccess && result != hipErrorDeinitialized) { \
LOG(FATAL) << "ROCM HIP Error: " #x " failed with error: " << hipGetErrorString(result); \
} \
}
#define ROCM_CALL(func) \
{ \
hipError_t e = (func); \
ICHECK(e == hipSuccess) << "ROCM HIP: " << hipGetErrorString(e); \
}
/*! \brief Thread local workspace */
class ROCMThreadEntry {
public:
/*! \brief The hip stream */
hipStream_t stream{nullptr};
/*! \brief thread local pool*/
WorkspacePool pool;
/*! \brief constructor */
ROCMThreadEntry();
// get the threadlocal workspace
static ROCMThreadEntry* ThreadLocal();
};
} // namespace runtime
} // namespace tvm
#endif // TVM_RUNTIME_ROCM_ROCM_COMMON_H_
| https://github.com/zk-ml/tachikoma |
src/runtime/rocm/rocm_module.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* \file rocm_module.h
* \brief Execution handling of ROCM kernels
*/
#ifndef TVM_RUNTIME_ROCM_ROCM_MODULE_H_
#define TVM_RUNTIME_ROCM_ROCM_MODULE_H_
#include <tvm/runtime/module.h>
#include <memory>
#include <string>
#include <unordered_map>
#include <vector>
#include "../meta_data.h"
namespace tvm {
namespace runtime {
/*! \brief Maximum number of GPU supported in ROCMModule */
static constexpr const int kMaxNumGPUs = 32;
/*!
* \brief create a rocm module from data.
*
* \param data The module data, can be hsaco
* \param fmt The format of the data, can be "hsaco"
* \param fmap The map function information map of each function.
* \param rocm_source Optional, rocm source file
*/
Module ROCMModuleCreate(std::string data, std::string fmt,
std::unordered_map<std::string, FunctionInfo> fmap, std::string rocm_source,
std::string assembly);
} // namespace runtime
} // namespace tvm
#endif // TVM_RUNTIME_ROCM_ROCM_MODULE_H_
| https://github.com/zk-ml/tachikoma |
src/runtime/rpc/rpc_channel.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* \file rpc_channel.h
* \brief Communication endpoints to connect local and remote RPC sessions.
*/
#ifndef TVM_RUNTIME_RPC_RPC_CHANNEL_H_
#define TVM_RUNTIME_RPC_RPC_CHANNEL_H_
#include <tvm/runtime/packed_func.h>
#include <utility>
namespace tvm {
namespace runtime {
/*!
* \brief Abstract channel interface used to create RPCEndpoint.
*/
class RPCChannel {
public:
/*! \brief virtual destructor */
virtual ~RPCChannel() {}
/*!
* \brief Send data over to the channel.
* \param data The data pointer.
* \param size The size fo the data.
* \return The actual bytes sent.
*/
virtual size_t Send(const void* data, size_t size) = 0;
/*!
* \brief Recv data from channel.
*
* \param data The data pointer.
* \param size The size fo the data.
* \return The actual bytes received.
*/
virtual size_t Recv(void* data, size_t size) = 0;
};
/*!
* \brief RPC channel which callback
* frontend (Python/Java/etc.)'s send & recv function
*/
class CallbackChannel final : public RPCChannel {
public:
/*!
* \brief Constructor.
*
* \param fsend The send function, takes in a TVMByteArray and returns the
* number of bytes sent in that array. Returns -1 if error happens.
* \param frecv The recv function, takes an expected maximum size, and return
* a byte array with the actual amount of data received.
*/
explicit CallbackChannel(PackedFunc fsend, PackedFunc frecv)
: fsend_(std::move(fsend)), frecv_(std::move(frecv)) {}
~CallbackChannel() {}
/*!
* \brief Send data over to the channel.
* \param data The data pointer.
* \param size The size fo the data.
* \return The actual bytes sent.
*/
size_t Send(const void* data, size_t size) final;
/*!
* \brief Recv data from channel.
*
* \param data The data pointer.
* \param size The size fo the data.
* \return The actual bytes received.
*/
size_t Recv(void* data, size_t size) final;
private:
PackedFunc fsend_;
PackedFunc frecv_;
};
} // namespace runtime
} // namespace tvm
#endif // TVM_RUNTIME_RPC_RPC_CHANNEL_H_
| https://github.com/zk-ml/tachikoma |
src/runtime/rpc/rpc_channel_logger.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* \file rpc_channel_logger.h
* \brief A wrapper for RPCChannel with a NanoRPCListener for logging the commands.
*/
#ifndef TVM_RUNTIME_RPC_RPC_CHANNEL_LOGGER_H_
#define TVM_RUNTIME_RPC_RPC_CHANNEL_LOGGER_H_
#include <tvm/runtime/c_runtime_api.h>
#include <memory>
#include <utility>
#include "../../support/ssize.h"
#include "../minrpc/minrpc_server_logging.h"
#include "rpc_channel.h"
#define RX_BUFFER_SIZE 65536
namespace tvm {
namespace runtime {
class Buffer {
public:
Buffer(uint8_t* data, size_t data_size_bytes)
: data_{data}, capacity_{data_size_bytes}, num_valid_bytes_{0}, read_cursor_{0} {}
size_t Write(const uint8_t* data, size_t data_size_bytes) {
size_t num_bytes_available = capacity_ - num_valid_bytes_;
size_t num_bytes_to_copy = data_size_bytes;
if (num_bytes_available < num_bytes_to_copy) {
num_bytes_to_copy = num_bytes_available;
}
memcpy(&data_[num_valid_bytes_], data, num_bytes_to_copy);
num_valid_bytes_ += num_bytes_to_copy;
return num_bytes_to_copy;
}
size_t Read(uint8_t* data, size_t data_size_bytes) {
size_t num_bytes_to_copy = data_size_bytes;
size_t num_bytes_available = num_valid_bytes_ - read_cursor_;
if (num_bytes_available < num_bytes_to_copy) {
num_bytes_to_copy = num_bytes_available;
}
memcpy(data, &data_[read_cursor_], num_bytes_to_copy);
read_cursor_ += num_bytes_to_copy;
return num_bytes_to_copy;
}
void Clear() {
num_valid_bytes_ = 0;
read_cursor_ = 0;
}
size_t Size() const { return num_valid_bytes_; }
private:
/*! \brief pointer to data buffer. */
uint8_t* data_;
/*! \brief The total number of bytes available in data_.*/
size_t capacity_;
/*! \brief number of valid bytes in the buffer. */
size_t num_valid_bytes_;
/*! \brief Read cursor position. */
size_t read_cursor_;
};
/*!
* \brief A simple IO handler for MinRPCSniffer.
*
* \tparam Buffer* buffer to store received data.
*/
class SnifferIOHandler {
public:
explicit SnifferIOHandler(Buffer* receive_buffer) : receive_buffer_(receive_buffer) {}
void MessageStart(size_t message_size_bytes) {}
ssize_t PosixWrite(const uint8_t* buf, size_t buf_size_bytes) { return 0; }
void MessageDone() {}
ssize_t PosixRead(uint8_t* buf, size_t buf_size_bytes) {
return receive_buffer_->Read(buf, buf_size_bytes);
}
void Close() {}
void Exit(int code) {}
private:
Buffer* receive_buffer_;
};
/*!
* \brief A simple rpc session that logs the received commands.
*/
class NanoRPCListener {
public:
NanoRPCListener()
: receive_buffer_(receive_storage_, receive_storage_size_bytes_),
io_(&receive_buffer_),
rpc_server_(&io_) {}
void Listen(const uint8_t* data, size_t size) { receive_buffer_.Write(data, size); }
void ProcessTxPacket() {
rpc_server_.ProcessOnePacket();
ClearBuffer();
}
void ProcessRxPacket() {
rpc_server_.ProcessOneResponse();
ClearBuffer();
}
private:
void ClearBuffer() { receive_buffer_.Clear(); }
private:
size_t receive_storage_size_bytes_ = RX_BUFFER_SIZE;
uint8_t receive_storage_[RX_BUFFER_SIZE];
Buffer receive_buffer_;
SnifferIOHandler io_;
MinRPCSniffer<SnifferIOHandler> rpc_server_;
void HandleCompleteMessage() { rpc_server_.ProcessOnePacket(); }
static void HandleCompleteMessageCb(void* context) {
static_cast<NanoRPCListener*>(context)->HandleCompleteMessage();
}
};
/*!
* \brief A wrapper for RPCChannel, that also logs the commands sent.
*
* \tparam std::unique_ptr<RPCChannel>&& underlying RPCChannel unique_ptr.
*/
class RPCChannelLogging : public RPCChannel {
public:
explicit RPCChannelLogging(std::unique_ptr<RPCChannel>&& next) { next_ = std::move(next); }
size_t Send(const void* data, size_t size) {
listener_.ProcessRxPacket();
listener_.Listen((const uint8_t*)data, size);
listener_.ProcessTxPacket();
return next_->Send(data, size);
}
size_t Recv(void* data, size_t size) {
size_t ret = next_->Recv(data, size);
listener_.Listen((const uint8_t*)data, size);
return ret;
}
private:
std::unique_ptr<RPCChannel> next_;
NanoRPCListener listener_;
};
} // namespace runtime
} // namespace tvm
#endif // TVM_RUNTIME_RPC_RPC_CHANNEL_LOGGER_H_
| https://github.com/zk-ml/tachikoma |
src/runtime/rpc/rpc_endpoint.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* \file rpc_endpoint.h
* \brief Communication endpoints to connect local and remote RPC sessions.
*/
#ifndef TVM_RUNTIME_RPC_RPC_ENDPOINT_H_
#define TVM_RUNTIME_RPC_RPC_ENDPOINT_H_
#include <tvm/runtime/packed_func.h>
#include <memory>
#include <mutex>
#include <string>
#include <utility>
#include "../../support/ring_buffer.h"
#include "../minrpc/rpc_reference.h"
#include "rpc_channel.h"
#include "rpc_channel_logger.h"
#include "rpc_session.h"
namespace tvm {
namespace runtime {
// Magic header for RPC data plane
const int kRPCMagic = 0xff271;
// magic header for RPC tracker(control plane)
const int kRPCTrackerMagic = 0x2f271;
// sucess response
const int kRPCSuccess = kRPCMagic + 0;
// cannot found matched key in server
const int kRPCMismatch = kRPCMagic + 2;
/*! \brief Enumeration code for the RPC tracker */
enum class TrackerCode : int {
kFail = -1,
kSuccess = 0,
kPing = 1,
kStop = 2,
kPut = 3,
kRequest = 4,
kUpdateInfo = 5,
kSummary = 6,
kGetPendingMatchKeys = 7
};
/*!
* \brief Communication endpoints to connect local and remote RPC sessions.
* An endpoint can either be a client or a server.
*/
class RPCEndpoint {
public:
/*! \brief virtual destructor
* Closes the connection if the connection hasn't already been closed.
*/
~RPCEndpoint();
/*!
* \brief Shutdown RPC connection.
*
* Shutdown has no effect if the connection has already been shut down.
* Shutdown will wait for all output currently queued from the RPC connection (i.e. The user
* doesn't need to wait for completion before calling Shutdown.) Any further use of objects that
* depended on the endpoint (e.g. A tvm.nd.array allocated on the remote RPC session) may throw an
* exception when used.
*/
void Shutdown();
/*!
* \brief The server loop that server runs to handle RPC calls.
*/
void ServerLoop();
/*!
* \brief Message handling function for an async IO event driven server.
*
* Called when the server receives a message or an IO event update.
* Event driven handler will never call recv on the channel
* and always relies on the ServerIOEventHandler to receive the data.
*
* \param in_bytes The incoming bytes.
* \param event_flag 1: read_available, 2: write_avaiable.
* \return State flag.
* 1: continue running, no need to write,
* 2: need to write
* 0: shutdown
*/
int ServerAsyncIOEventHandler(const std::string& in_bytes, int event_flag);
/*!
* \brief Initalize the session on the remote that will be used to back all the RPC requests.
*
* If no session constructor arguments is passed, LocalSession will be used in the remote.
* Otherwise the remote serving session will be constructed using the arguments
* specified in the session_constructor_args.
*
* The construction rule can be summarized as follows:
*
* \code
*
* auto args = session_constructor_args;
* int n = args.size();
* if (n != 0) {
* std::string constructor = args[0];
* server.serving_session_ = GetGlobalFunc(constructor)(
* args[1], args[2] ... args[n - 1])
* } else {
* server.serving_session_ = LocalSession();
* }
* \endcode
*
* \param session_constructor_args Optional sequence of the remote sesssion constructor.
*/
void InitRemoteSession(TVMArgs session_constructor_args);
/*!
* \brief Call into remote function
* \param handle The function handle
* \param arg_values The argument values.
* \param arg_type_codes the type codes of the argument.
* \param num_args Number of arguments.
* \param fencode_return The function to receive return value encodings.
*/
void CallFunc(RPCSession::PackedFuncHandle handle, const TVMValue* arg_values,
const int* arg_type_codes, int num_args, RPCSession::FEncodeReturn encode_return);
/*!
* \brief Copy bytes into remote array content.
* \param from The source host data.
* \param from_offset The byte offeset in the from.
* \param to The target array.
* \param to_offset The byte offset in the to.
* \param nbytes The size of the memory in bytes.
* \param dev_to The target device.
* \param type_hint Hint of content data type.
*/
void CopyToRemote(void* from_bytes, DLTensor* to, uint64_t nbytes);
/*!
* \brief Copy bytes from remote array content.
* \param from The source host data.
* \param from_offset The byte offeset in the from.
* \param to The target array.
* \param to_offset The byte offset in the to.
* \param nbytes The size of the memory in bytes.
* \param dev_from The source device.
* \param type_hint Hint of content data type.
*/
void CopyFromRemote(DLTensor* from, void* to_bytes, uint64_t nbytes);
/*!
* \brief Call a remote defined system function with arguments.
* \param fcode The function code.
* \param args The arguments
* \return The returned remote value.
*/
template <typename... Args>
inline TVMRetValue SysCallRemote(RPCCode fcode, Args&&... args);
/*!
* \brief Create a RPC session with given channel.
* \param channel The communication channel.
* \param name The local name of the session, used for debug
* \param remote_key The remote key of the session
* if remote_key equals "%toinit", we need to re-intialize
* it by event handler.
* \param fcleanup The cleanup Packed function.
*/
static std::shared_ptr<RPCEndpoint> Create(std::unique_ptr<RPCChannel> channel, std::string name,
std::string remote_key,
TypedPackedFunc<void()> fcleanup = nullptr);
private:
class EventHandler;
// Handle events until receives a return
// Also flushes channels so that the function advances.
RPCCode HandleUntilReturnEvent(bool client_mode, RPCSession::FEncodeReturn setreturn);
// Initalization
void Init();
// Internal channel.
std::unique_ptr<RPCChannel> channel_;
// Internal mutex
std::mutex mutex_;
// Internal ring buffer.
support::RingBuffer reader_, writer_;
// Event handler.
std::shared_ptr<EventHandler> handler_;
// syscall remote with specified function code.
PackedFunc syscall_remote_;
// The name of the session.
std::string name_;
// The remote key
std::string remote_key_;
// Invoked when the RPC session is terminated
TypedPackedFunc<void()> fcleanup_;
};
/*!
* \brief Create an RPC client session from an RPC client endpoint.
* \param endpoint The endpoint.
* \return The created session.
*/
std::shared_ptr<RPCSession> CreateClientSession(std::shared_ptr<RPCEndpoint> endpoint);
// implementation of inline functions
template <typename... Args>
inline TVMRetValue RPCEndpoint::SysCallRemote(RPCCode code, Args&&... args) {
return syscall_remote_(static_cast<int>(code), std::forward<Args>(args)...);
}
/*!
* \brief Calculates overhead size of a CopyToRemote packet.
* \param to DLTensor to copy.
* \param code RPCCode for this transfer.
* \param nbytes Number of bytes to transfer.
* \return The remote-copy packet overhead size.
*/
uint64_t RemoteCopyCalculatePacketOverheadSize(DLTensor* tensor, RPCCode code, uint64_t nbytes);
} // namespace runtime
} // namespace tvm
#endif // TVM_RUNTIME_RPC_RPC_ENDPOINT_H_
| https://github.com/zk-ml/tachikoma |
src/runtime/rpc/rpc_local_session.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* \file rpc_local_session.h
* \brief Local session that directs all request to the local runtime API.
*/
#ifndef TVM_RUNTIME_RPC_RPC_LOCAL_SESSION_H_
#define TVM_RUNTIME_RPC_RPC_LOCAL_SESSION_H_
#include <tvm/runtime/device_api.h>
#include <tvm/runtime/packed_func.h>
#include <functional>
#include <string>
#include <utility>
#include "rpc_session.h"
namespace tvm {
namespace runtime {
/*!
* \brief A local session that directly use the handle repr of the
* local tvm runtime objects on the same process.
*/
class LocalSession : public RPCSession {
public:
// function overrides
PackedFuncHandle GetFunction(const std::string& name) override;
void CallFunc(PackedFuncHandle func, const TVMValue* arg_values, const int* arg_type_codes,
int num_args, const FEncodeReturn& fencode_return) override;
void CopyToRemote(void* from_bytes, DLTensor* to, uint64_t nbytes) override;
void CopyFromRemote(DLTensor* from, void* to_bytes, uint64_t nbytes) override;
void FreeHandle(void* handle, int type_code) override;
DeviceAPI* GetDeviceAPI(Device dev, bool allow_missing = false) override;
bool IsLocalSession() const override { return true; }
protected:
/*!
* \brief internal encode return function.
* \param rv The return value.
* \param encode_return The encoding function.
*/
void EncodeReturn(TVMRetValue rv, const FEncodeReturn& encode_return);
};
} // namespace runtime
} // namespace tvm
#endif // TVM_RUNTIME_RPC_RPC_LOCAL_SESSION_H_
| https://github.com/zk-ml/tachikoma |
src/runtime/rpc/rpc_session.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* \file rpc_session.h
* \brief Base RPC session interface.
*/
#ifndef TVM_RUNTIME_RPC_RPC_SESSION_H_
#define TVM_RUNTIME_RPC_RPC_SESSION_H_
#include <tvm/runtime/device_api.h>
#include <tvm/runtime/packed_func.h>
#include <functional>
#include <memory>
#include <string>
#include "../minrpc/rpc_reference.h"
namespace tvm {
namespace runtime {
/*!
* \brief The interface of all remote RPC sessions.
*
* It contains all the necessary interface to implement
* remote call and resource management.
*
* The interface is designed to allow easy proxy-chaining
* by forward requests to another RPCSession.
*/
class RPCSession {
public:
/*! \brief PackedFunc Handle in the remote. */
using PackedFuncHandle = void*;
/*! \brief Module handle in the remote. */
using ModuleHandle = void*;
/*! \brief NDArray handle in the remote. */
using NDArrayHandle = void*;
/*!
* \brief Callback to send an encoded return values via encode_args.
*
* \param encode_args The arguments that we can encode the return values into.
*
* Encoding convention (as list of arguments):
* - str/float/int/byte: [tcode: int, value: TVMValue] value follows PackedFunc convention.
* - PackedFunc/Module: [tcode: int, handle: void*]
* - NDArray: [tcode: int, meta: DLTensor*, nd_handle: void*]
* DLTensor* contains the meta-data as well as handle into the remote data.
* nd_handle can be used for deletion.
*/
using FEncodeReturn = std::function<void(TVMArgs encoded_args)>;
/*!
* \brief Callback to send an encoded return values via encode_args.
*
* \param status The return status, can be RPCCode::kReturn or RPCCode::kException.
* \param encode_args The arguments that we can encode the return values into.
*/
using FAsyncCallback = std::function<void(RPCCode status, TVMArgs encoded_args)>;
/*! \brief Destructor.*/
virtual ~RPCSession() {}
/*!
* \brief Get function in the session.
* \param name The name of the function.
* \return The function handle.
*/
virtual PackedFuncHandle GetFunction(const std::string& name) = 0;
/*!
* \brief Call into a remote Packed function.
*
* Calling convention:
*
* - type_code is follows the PackedFunc convention.
* - int/float/string/bytes follows the PackedFunc convention, all data are local.
* - PackedFunc/Module and future remote objects: pass remote handle instead.
* - NDArray/DLTensor: pass a DLTensor pointer, the data field of DLTensor
* points to a remote data handle returned by the Device API.
* The meta-data of the DLTensor sits on local.
*
* The caller populates the arguments and manages these arguments.
*
* The callee can change the content of arg_values and arg_type_codes
* if they want to do inplace modify and forward.
*
* The callee need to store the return value into ret_value.
* - PackedFunc/Module are stored as void*
* - NDArray is stored as local NDArray, whose data field is a remote handle.
* Notably the NDArray's deleter won't delete remote handle.
* It is up to the user of the RPCSession to such wrapping.
* - In short, remote handles are "moved" as return values
* and the callee needs to explicitly manage them by calling
* the deleter functions when they are no longer needed.
*
* \param func The function handle.
* \param arg_values The argument values.
* \param arg_type_codes the type codes of the argument.
* \param num_args Number of arguments.
* \param fencode_return The function to set the return value,
* if not called, return value is null.
*/
virtual void CallFunc(PackedFuncHandle func, const TVMValue* arg_values,
const int* arg_type_codes, int num_args,
const FEncodeReturn& fencode_return) = 0;
/*!
* \brief Copy bytes into remote array content.
* \param local_from_bytes The source host data.
* \param remote_to The target array.
* \param nbytes The size of the memory in bytes.
*/
virtual void CopyToRemote(void* local_from_bytes, DLTensor* remote_to, uint64_t nbytes) = 0;
/*!
* \brief Copy bytes from remote array content.
* \param remote_from The source host data.
* \param local_to_bytes The target array.
* \param nbytes The size of the memory in bytes.
*/
virtual void CopyFromRemote(DLTensor* remote_from, void* local_to_bytes, uint64_t nbytes) = 0;
/*!
* \brief Free a remote function.
* \param handle The remote handle, can be NDArray/PackedFunc/Module
* \param type_code The type code of the underlying type.
*/
virtual void FreeHandle(void* handle, int type_code) = 0;
/*!
* \brief Get device API that represents the remote
* actions that can be taken on the remote.
*
* The caller can then call into the Alloc/Free functions
* to allocate free spaces and taking the pointer as the handle.
*
* The device API is guaranteed to be alive during the
* lifetime of the Session.
*
* \param dev The remote device.
* \param allow_missing Whether can we return nullptr if it is not available.
*
* \return The device API.
*/
virtual DeviceAPI* GetDeviceAPI(Device dev, bool allow_missing = false) = 0;
/*!
* \brief Whether the session is a local session and we can directly
* the data handle returned by the session and treat it as pointer
* to the local memory.
*
* This information is useful for RPC server to directly copy into the
* local memory without creating a temporary buffer.
*
* \return Whether it is a local session.
*/
virtual bool IsLocalSession() const = 0;
// Asynchrous variant of API
// These APIs are used by the RPC server to allow sessions that
// have special implementations for the async functions.
//
// In the async APIs, an exception is returned by the passing
// async_error=true, encode_args=[error_msg].
/*!
* \brief Whether the session is async.
*
* If the session is not async, its Aync implementations
* simply calls into the their synchronize counterparts,
* and the callback is guaranteed to be called before the async function finishes.
*
* \return the async state.
*
* \note We can only use async session in an Event driven RPC server.
*/
virtual bool IsAsync() const;
/*!
* \brief Asynchrously call func.
* \param func The function handle.
* \param arg_values The argument values.
* \param arg_type_codes the type codes of the argument.
* \param num_args Number of arguments.
*
* \param callback The callback to pass the return value or exception.
*/
virtual void AsyncCallFunc(PackedFuncHandle func, const TVMValue* arg_values,
const int* arg_type_codes, int num_args, FAsyncCallback callback);
/*!
* \brief Asynchrous version of CopyToRemote.
*
* \param local_from_bytes The source host data.
* \param remote_to The target array.
* \param nbytes The size of the memory in bytes.
* \param on_complete The callback to signal copy complete.
* \note All the allocated memory in local_from, and remote_to
* must stay alive until on_compelete is called.
*/
virtual void AsyncCopyToRemote(void* local_from_bytes, DLTensor* remote_to, uint64_t nbytes,
FAsyncCallback on_complete);
/*!
* \brief Asynchrous version of CopyFromRemote.
*
* \param remote_from The source host data.
* \param local_to_bytes The target array.
* \param nbytes The size of the memory in bytes.
* \param on_complete The callback to signal copy complete.
* \note All the allocated memory in remote_from, and local_to
* must stay alive until on_compelete is called.
*/
virtual void AsyncCopyFromRemote(DLTensor* remote_from, void* local_to_bytes, uint64_t nbytes,
FAsyncCallback on_complete);
/*!
* \brief Asynchrously wait for all events in dev, stream compeletes.
* \param dev The device.
* \param stream The stream to wait on.
* \param on_complete The callback to signal copy complete.
*/
virtual void AsyncStreamWait(Device dev, TVMStreamHandle stream, FAsyncCallback on_compelte);
/*!
* \return The session table index of the session.
*/
int table_index() const { return table_index_; }
/*!
* \brief Try get session from the global session table by table index.
* \param table_index The table index of the session.
* \return The shared_ptr to the session, can be nullptr.
*/
static std::shared_ptr<RPCSession> Get(int table_index);
/*!
* \brief Shutdown RPC connection.
*/
virtual void Shutdown() {}
protected:
/*!
* \brief Send an exception to the callback.
* \param msg The exception message.
*/
void SendException(FAsyncCallback callback, const char* msg);
private:
/*! \brief index of this session in RPC session table */
int table_index_{0};
/*! \brief Insert the current session to the session table.*/
static void InsertToSessionTable(std::shared_ptr<RPCSession> sess);
// friend declaration
friend Module CreateRPCSessionModule(std::shared_ptr<RPCSession> sess);
};
/*!
* \brief Remote space handle cell used by the RPC runtime API.
*
* When we allocate space using a rpc device, the data pointer
* points to an allocated RemoteSpace.
*/
struct RemoteSpace {
/*! \brief The remote data handle. */
void* data;
/*! \brief Reference to the underlying RPC session. */
std::shared_ptr<RPCSession> sess;
};
/*!
* \brief Create a Global RPC module that refers to the session.
* \param sess The RPC session of the global module.
* \return The created module.
*/
Module CreateRPCSessionModule(std::shared_ptr<RPCSession> sess);
/*!
* \brief Get the session module from a RPC session Module.
* \param mod The input module(must be an RPCModule).
* \return The internal RPCSession.
*/
std::shared_ptr<RPCSession> RPCModuleGetSession(Module mod);
} // namespace runtime
} // namespace tvm
#endif // TVM_RUNTIME_RPC_RPC_SESSION_H_
| https://github.com/zk-ml/tachikoma |
src/runtime/rpc/rpc_socket_impl.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* \file rpc_socket_impl.h
* \brief Socket based RPC implementation.
*/
#ifndef TVM_RUNTIME_RPC_RPC_SOCKET_IMPL_H_
#define TVM_RUNTIME_RPC_RPC_SOCKET_IMPL_H_
namespace tvm {
namespace runtime {
/*!
* \brief RPCServerLoop Start the rpc server loop.
* \param sockfd Socket file descriptor
*/
void RPCServerLoop(int sockfd);
} // namespace runtime
} // namespace tvm
#endif // TVM_RUNTIME_RPC_RPC_SOCKET_IMPL_H_
| https://github.com/zk-ml/tachikoma |
src/runtime/runtime_base.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* \file runtime_base.h
* \brief Base of all C APIs
*/
#ifndef TVM_RUNTIME_RUNTIME_BASE_H_
#define TVM_RUNTIME_RUNTIME_BASE_H_
#include <tvm/runtime/c_runtime_api.h>
#include <stdexcept>
/*! \brief macro to guard beginning and end section of all functions */
#define API_BEGIN() try {
/*! \brief every function starts with API_BEGIN();
and finishes with API_END() or API_END_HANDLE_ERROR */
#define API_END() \
} \
catch (::tvm::runtime::EnvErrorAlreadySet & _except_) { \
return -2; \
} \
catch (std::exception & _except_) { \
return TVMAPIHandleException(_except_); \
} \
return 0; // NOLINT(*)
/*!
* \brief every function starts with API_BEGIN();
* and finishes with API_END() or API_END_HANDLE_ERROR
* The finally clause contains procedure to cleanup states when an error happens.
*/
#define API_END_HANDLE_ERROR(Finalize) \
} \
catch (::tvm::runtime::EnvErrorAlreadySet & _except_) { \
return -2; \
} \
catch (std::exception & _except_) { \
Finalize; \
return TVMAPIHandleException(_except_); \
} \
return 0; // NOLINT(*)
/*!
* \brief handle exception throwed out
* \param e the exception
* \return the return value of API after exception is handled
*/
int TVMAPIHandleException(const std::exception& e);
#endif // TVM_RUNTIME_RUNTIME_BASE_H_
| https://github.com/zk-ml/tachikoma |
src/runtime/source_utils.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* \file source_utils.h
* \brief Minimum source manipulation utils for runtime.
*/
#ifndef TVM_RUNTIME_SOURCE_UTILS_H_
#define TVM_RUNTIME_SOURCE_UTILS_H_
#include <string>
#include <unordered_map>
namespace tvm {
namespace runtime {
/*!
* \brief Split the source file on separate kernels by specified delimiter.
* \param source The source code of the kernels.
* \param delimiter The delimiter which is using for splitting kernels.
* \return Mapping from primitive name to kernel source
*/
std::unordered_map<std::string, std::string> SplitKernels(std::string source,
std::string delimiter = "// Function: ");
} // namespace runtime
} // namespace tvm
#endif // TVM_RUNTIME_SOURCE_UTILS_H_
| https://github.com/zk-ml/tachikoma |
src/runtime/stackvm/stackvm.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* \file stackvm.h
* \brief A simple stack-based virtual machine.
*
* This can be used to interepret host side code
* to setup calls into device functions
* when only Runtime compilation for device is available(via NVRTC or OpenCL).
*/
#ifndef TVM_RUNTIME_STACKVM_STACKVM_H_
#define TVM_RUNTIME_STACKVM_STACKVM_H_
#include <tvm/runtime/c_runtime_api.h>
#include <tvm/runtime/module.h>
#include <tvm/runtime/packed_func.h>
#include <string>
#include <vector>
namespace tvm {
namespace runtime {
using runtime::operator<<;
/*!
* \brief A simple stack-based virtual machine program.
*/
class StackVM {
public:
/*!
* \brief Invoke the StackVM program.
* \param args The arguments to the StackVM.
* \param mod_ctx The module context used in running.
*/
void Run(const TVMArgs& args, runtime::ModuleNode* mod_ctx) const;
/*!
* \brief The opcode of stack vm
* \note Notation
* - sp Stack pointer
* - pc Program pointer
*/
enum OpCode {
// integer ops
ADD_I64,
SUB_I64,
MUL_I64,
DIV_I64,
MOD_I64,
EQ_I64,
LT_I64,
LE_I64,
// floating ops
ADD_F64,
SUB_F64,
MUL_F64,
DIV_F64,
EQ_F64,
LT_F64,
LE_F64,
// Pointer comparison
EQ_HANDLE,
/*!
* \brief Routine to load data from address with const offset.
* \code
* stack[sp].v_int64 = ((DType*)stack[sp].v_handle)[code[pc + 1].v_int];
* pc = pc + 2;
* \endcode
*/
ARRAY_LOAD_UINT32,
ARRAY_LOAD_INT32,
ARRAY_LOAD_INT64,
ARRAY_LOAD_FP64,
ARRAY_LOAD_HANDLE,
ARRAY_LOAD_TVMVALUE,
/*!
* \brief Routine to store data from constant offset.
* \code
* ((DType*)stack[sp - 1].v_handle)[code[pc + 1].v_int] = stack[sp];
* pc = pc + 2;
* sp = sp - 2;
* \endcode
*/
ARRAY_STORE_UINT32,
ARRAY_STORE_INT32,
ARRAY_STORE_INT64,
ARRAY_STORE_FP64,
ARRAY_STORE_HANDLE,
ARRAY_STORE_TVMVALUE,
// logical ops
NOT,
/*!
* \brief Add address by an offset.
* \code
* stack[sp - 1].v_handle = ((char*)stack[sp - 1].v_handle + stack[sp].v_int64);
* sp = sp - 1;
* \endcode
*/
ADDR_ADD,
/*!
* \brief push integer fetched from next pc position into stack
* \code
* stack[sp + 1].v_int64 = code[pc + 1].v_int;
* pc = pc + 2;
* sp = sp + 1;
* \endcode
*/
PUSH_I64,
/*!
* \brief push a value given relative index on the stack
* \code
* stack[sp + 1] = stack[sp + code[pc + 1].v_int];
* pc = pc + 2;
* sp = sp + 1;
* \endcode
*/
PUSH_VALUE,
/*!
* \brief Load data from heap to top of stack
* \code
* stack[sp + 1] = heap[code[pc + 1].v_int];
* pc = pc + 2;
* sp = sp + 1;
* \endcode
*/
LOAD_HEAP,
/*!
* \brief Store data to heap
* \code
* heap[code[pc + 1].v_int] = stack[sp];
* sp = sp - 1;
* \endcode
*/
STORE_HEAP,
/*! \brief pop value from top of the stack */
POP,
/*!
* \brief select based on operands.
* \code
* stack[sp - 2] = stack[sp].v_int64 ? stack[sp - 2] : stack[sp - 1]
* sp = sp - 2;
* \endcode
*/
SELECT,
/*!
* \brief Assert condition is true.
* \code
* ICHECK(stack[sp]) << str_data[code[pc + 1].v_int];
* sp = sp - 1;
* \endcode
*/
ASSERT,
/*!
* \brief Relative Jump if the condition is true,
* Does not change the stack status.
* \code
* if (stack[sp]) {
* pc += code[pc + 1].v_int
* } else {
* pc = pc + 2;
* }
* \endcode
*/
RJUMP_IF_TRUE,
/*!
* \brief Relative Jump if the condition is true,
* Does not change the stack status.
* \code
* if (stack[sp]) {
* pc += code[pc + 1].v_int
* } else {
* pc = pc + 2;
* }
* \endcode
*/
RJUMP_IF_FALSE,
/*!
* \brief Relative jump to a location.
* \code
* pc += code[pc + 1].v_int;
* \endcode
*/
RJUMP,
/*!
* \brief debug instruction.
* \code
* ICHECK_EQ(sp, code[pc + 1]).v_int;
* pc += 2;
* \code
*/
ASSERT_SP,
/*!
* \brief call an extern packed function
* \code
* value_stack = stack[sp - 1].v_handle;
* type_stack = stack[sp - 0].v_handle;
* call_fid = code[pc + 1].v_int;
* begin = code[pc + 2].v_int;
* end = code[pc + 3].v_int;
* num_args = end - begin - 1;
* f = extern_func[call_fid];
* stack[sp - 1] = f(&value_stack[begin:end-1], type_stack[begin:end-1], num_args);
* sp = sp - 1;
* // The type codes are hidden in the code space.
* pc = pc + 4
* \endcode
*/
CALL_PACKED_LOWERED,
// Allocate things on stack
/*!
* \brief allocate data from stack.
* \code
* num = code[pc + 1].v_int;
* void* addr = &stack[sp];
* sp = sp + num;
* stack[sp].v_handle = addr;
* pc = pc + 1;
* \endcode
*/
TVM_STACK_ALLOCA_BY_8BYTE,
/*!
* \brief allocate data from device.
* \code
* device_type = stack[sp - 2].v_int64;
* device_id = stack[sp - 1].v_int64;
* nbytes = stack[sp].v_int64;
* stack[sp - 2].v_handle = device_alloca(device_type, device_id, nbytes);
* sp = sp - 2;
* pc = pc + 1;
* \endcode
*/
TVM_DEVICE_ALLOCA,
/*!
* \brief free data into device.
* \code
* device_type = stack[sp - 2].v_int64;
* device_id = stack[sp - 1].v_int64;
* ptr = stack[sp].v_handle;
* stack[sp - 2].v_int64 = device_free(device_type, device_id, ptr);
* sp = sp - 2;
* pc = pc + 1;
* \endcode
*/
TVM_DEVICE_FREE,
/*!
* \brief throw last error
*/
TVM_THROW_LAST_ERROR,
/*!
* \brief get data from structure.
* \code
* index = code[pc + 1].v_int;
* field = code[pc + 2].v_int;
* stack[sp] = ((StructType*)stack[sp].v_handle)[index]->field;
* pc = pc + 3
* \endcode
*/
TVM_STRUCT_GET,
/*!
* \brief set data into structure.
* \code
* index = code[pc + 1].v_int;
* field = code[pc + 2].v_int;
* ((StructType*)stack[sp - 1].v_handle)[index]->field = stack[sp];
* pc = pc + 3
* sp = sp - 1
* \endcode
*/
TVM_STRUCT_SET
};
/*! \brief The kind of structure field info */
enum StructFieldKind : int {
// array head address
kArrAddr,
kArrData,
kArrShape,
kArrStrides,
kArrNDim,
kArrTypeCode,
kArrTypeBits,
kArrTypeLanes,
kArrByteOffset,
kArrDeviceId,
kArrDeviceType,
kArrKindBound_,
// TVMValue field
kTVMValueContent,
kTVMValueKindBound_
};
/*! \brief The code structure */
union Code {
OpCode op_code;
int v_int;
};
/*! \brief The state object of StackVM */
struct State {
/*! \brief The execution stack */
std::vector<TVMValue> stack;
/*! \brief The global heap space */
std::vector<TVMValue> heap;
/*! \brief stack pointer */
int64_t sp{0};
/*! \brief program counter */
int64_t pc{0};
/*! \brief The current module context of stackvm */
runtime::ModuleNode* mod_ctx{nullptr};
};
/*! \brief Initialize local cache*/
void InitCache();
/*!
* \brief Save stackvm program to an output stream
* \param strm The output stream
*/
void Save(dmlc::Stream* strm) const;
/*!
* \brief Load stackvm program from output stream
* \param strm The output stream
*/
bool Load(dmlc::Stream* strm);
/*!
* \brief Print instruction at location pc
* \param os The ostream
* \param pc The pc
* \return the pc to next instruction.
*/
int64_t PrintCode(std::ostream& os, int64_t pc) const; // NOLINT(*)
/*! \brief Get thread local state of the stack VM */
static State* ThreadLocalState();
// The code below are programs
/*! \brief The instructions */
std::vector<Code> code;
/*! \brief constant error messages */
std::vector<std::string> str_data;
/*! \brief Extern functions */
std::vector<std::string> extern_func_name;
/*! \brief name of each heap id */
std::vector<std::string> heap_id_name;
/*! \brief The memory size needed */
size_t heap_size{0};
/*! \brief The stack size required */
size_t stack_size{1024};
/*!
* \brief Convert I64 opcode to F64 Ones
* \param code The op code.
* \return the F64 op code.
*/
static OpCode CodeI64ToF64(OpCode code) {
switch (code) {
case ADD_I64:
return ADD_F64;
case SUB_I64:
return SUB_F64;
case MUL_I64:
return MUL_F64;
case DIV_I64:
return DIV_F64;
case EQ_I64:
return EQ_F64;
case LT_I64:
return LT_F64;
case LE_I64:
return LE_F64;
case MOD_I64:
LOG(FATAL) << "cannot handle mod for float";
return ADD_F64;
default:
LOG(FATAL) << "cannot handle op " << code;
return ADD_F64;
}
}
/*!
* \brief Get load opcode for type t
* \param t the type code.
* \return The load opcode
*/
static OpCode GetLoad(DLDataType t) {
ICHECK_EQ(t.lanes, 1U);
if (t.code == kTVMOpaqueHandle) return ARRAY_LOAD_HANDLE;
if (t.code == kDLInt) {
switch (t.bits) {
case 32:
return ARRAY_LOAD_INT32;
case 64:
return ARRAY_LOAD_INT64;
}
} else if (t.code == kDLUInt) {
switch (t.bits) {
case 32:
return ARRAY_LOAD_UINT32;
}
} else if (t.code == kDLFloat) {
switch (t.bits) {
case 64:
return ARRAY_LOAD_FP64;
}
}
LOG(FATAL) << "Cannot load type " << t;
return ARRAY_LOAD_FP64;
}
/*!
* \brief Get store opcode for type t
* \param t the type code.
* \return The load opcode
*/
static OpCode GetStore(DLDataType t) {
ICHECK_EQ(t.lanes, 1U);
if (t.code == kTVMOpaqueHandle) return ARRAY_STORE_HANDLE;
if (t.code == kDLInt) {
switch (t.bits) {
case 32:
return ARRAY_STORE_INT32;
case 64:
return ARRAY_STORE_INT64;
}
} else if (t.code == kDLUInt) {
switch (t.bits) {
case 32:
return ARRAY_STORE_UINT32;
}
} else if (t.code == kDLFloat) {
switch (t.bits) {
case 64:
return ARRAY_STORE_FP64;
}
}
LOG(FATAL) << "Cannot store type " << t;
return ARRAY_STORE_FP64;
}
friend std::ostream& operator<<(std::ostream& os, const StackVM& vm); // NOLINT(*)
private:
// execute the stack vm with given state
void Run(State* state) const;
// get extern function.
const PackedFunc& GetExtern(State* s, int fid) const;
// cached extern function
mutable std::vector<PackedFunc> extern_func_cache_;
};
} // namespace runtime
} // namespace tvm
namespace dmlc {
DMLC_DECLARE_TRAITS(has_saveload, ::tvm::runtime::StackVM, true);
}
#endif // TVM_RUNTIME_STACKVM_STACKVM_H_
| https://github.com/zk-ml/tachikoma |
src/runtime/stackvm/stackvm_module.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* \file stackvm_module.h
* \brief StackVM module
*/
#ifndef TVM_RUNTIME_STACKVM_STACKVM_MODULE_H_
#define TVM_RUNTIME_STACKVM_STACKVM_MODULE_H_
#include <tvm/runtime/packed_func.h>
#include <string>
#include <unordered_map>
#include "stackvm.h"
namespace tvm {
namespace runtime {
/*!
* \brief create a stackvm module
*
* \param fmap The map from name to function
* \param entry_func The entry function name.
* \return The created module
*/
Module StackVMModuleCreate(std::unordered_map<std::string, StackVM> fmap, std::string entry_func);
} // namespace runtime
} // namespace tvm
#endif // TVM_RUNTIME_STACKVM_STACKVM_MODULE_H_
| https://github.com/zk-ml/tachikoma |
src/runtime/static_library.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* \file runtime/static_library.h
* \brief Represents a generic '.o' static library which can be linked into the final output
* dynamic library by export_library.
*/
#ifndef TVM_RUNTIME_STATIC_LIBRARY_H_
#define TVM_RUNTIME_STATIC_LIBRARY_H_
#include <tvm/runtime/logging.h>
#include <tvm/runtime/module.h>
#include <array>
#include <memory>
#include <set>
#include <string>
#include <unordered_map>
namespace tvm {
namespace runtime {
/*!
* \brief Returns a static library with the contents loaded from filename which exports
* func_names with the usual packed-func calling convention.
*/
Module LoadStaticLibrary(const std::string& filename, Array<String> func_names);
} // namespace runtime
} // namespace tvm
#endif // TVM_RUNTIME_STATIC_LIBRARY_H_
| https://github.com/zk-ml/tachikoma |
src/runtime/texture.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* \file texture.h
* \brief Texture utilities
*/
#ifndef TVM_RUNTIME_TEXTURE_H_
#define TVM_RUNTIME_TEXTURE_H_
#include <tvm/runtime/device_api.h>
#include <memory>
#include <string>
#include <vector>
namespace tvm {
namespace runtime {
/*! \brief Structure to represent flattened texture shape */
template <typename T>
struct Texture2DShape {
T width;
T height;
T channel;
};
/*!
* \param shape_rank Rank N of the Nd-shape
* \param convention Storage scope convention to use for flattening
* \return The axis separator that defines the Nd shape partitioning in 2d
*/
inline size_t DefaultTextureLayoutSeparator(size_t shape_rank,
std::string convention = "global.texture") {
// Texture activation:
// e.g. [N,C,H,W,c] -> Texture2d[N*C*H, W, c]
// Texture weight:
// e.g. [O,I,H,W,c] -> Texture2d[O, I*H*W, c]
size_t separator = 0;
if (convention == "global.texture") {
separator = shape_rank - 2;
} else if (convention == "global.texture-weight") {
separator = 1;
} else if (convention == "global.texture-nhwc") {
if (shape_rank == 3) {
separator = 1;
} else {
separator = 2;
}
} else {
LOG(FATAL) << "Encountered unknown texture lowering convention: " << convention;
}
return separator;
}
/*!
* \param shape Nd shape
* \param rank Number of dimensions N of the Nd shape
* \param axis The axis separator that splits the Nd axes into two sets
* \return Width and height of the 2d shape
*/
template <typename T, typename S>
Texture2DShape<T> ApplyTexture2DFlattening(const S& shape, size_t rank, size_t axis) {
ICHECK(axis < rank)
<< "Number of axes to flatten into rows must be less than shape rank for 2d flattening";
Texture2DShape<T> texture{1, 1, shape[rank - 1]};
for (size_t i = 0; i < rank - 1; i++) {
if (i < axis) {
texture.height *= shape[i];
} else {
texture.width *= shape[i];
}
}
return texture;
}
inline bool IsTextureStorage(std::string scope) {
return scope.find("texture") != std::string::npos;
}
class TVM_DLL Pool2D {
public:
Pool2D() = default;
void* Alloc(Device dev, DeviceAPI* device, size_t width, size_t height, DLDataType type_hint);
void Free(void* data);
// Release all resources immediately
void Release(Device dev, DeviceAPI* device);
protected:
struct Entry {
void* data;
size_t x;
size_t y;
DLDataType type;
};
std::vector<Entry> free_list_;
std::vector<Entry> allocated_;
};
/*!
* \brief A two dimensional storage pool that recycles temporal workspace
* allocations for dynamically allocated texture. See AllocTexture docstring
* for approach to allocation and reuse.
*/
class TVM_DLL TexturePool {
public:
/*!
* \brief Create pool with specific device type and device.
* \param device_type The device type.
* \param device_api The device API.
*/
TexturePool(DLDeviceType device_type, DeviceAPI* device_api);
/*! \brief destructor */
~TexturePool();
/*!
* \brief Allocate a two dimensional temporal texture workspace on device
*
* \note Two dimensional texture workspaces will be grown and reused
* according to the following strategy:
* - Choose the workspace which minimizes the amount of memory required to
* grow the workspace to fit the request.
* - If a set of workspaces exist that fit the current request without
* expansion, choose the workspace of that set which most closely
* matches the request size, minimizing wasted space.
*
* \param dev The context of allocation.
* \param width The width of the 2d texture to be allocated.
* \param height The height of the 2d texture to be allocated.
* \param type_hint The type of elements.
*/
void* AllocTexture(Device dev, size_t width, size_t height, DLDataType type_hint);
/*!
* \brief Free temporal texture in backend execution.
*
* \param dev The context of allocation.
* \param ptr The pointer to be freed.
*/
void FreeTexture(Device dev, void* ptr);
private:
/*! \brief pool of device local array */
std::vector<Pool2D*> array_;
/*! \brief device type this pool support */
DLDeviceType device_type_;
/*! \brief The device API */
DeviceAPI* device_;
};
} // namespace runtime
} // namespace tvm
#endif // TVM_RUNTIME_TEXTURE_H_
| https://github.com/zk-ml/tachikoma |
src/runtime/thread_map.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#ifndef TVM_RUNTIME_THREAD_MAP_H_
#define TVM_RUNTIME_THREAD_MAP_H_
#include <functional>
#include <memory>
#include <mutex>
#include <shared_mutex>
#include <thread>
#include <unordered_map>
#include <utility>
namespace tvm {
namespace runtime {
/*! \brief Container to hold one value per thread
*
* Similar to thread_local, but intended for use as a non-static or
* non-block variable, such as class member variables. All member
* functions are thread-safe to call. If only the current thread's
* value is accessed, no additional synchronization is required. If
* another thread's stored values are accessed, external
* synchronization may be required.
*
* Calls that only require access to already-existing values will not
* block each other. Calls that require constructing a new value will
* block any other calls.
*
* \tparam T The object type to be held. For instantiation of
* ThreadMap<T> and for calls to ThreadMap<T>::Get, only a forward
* declaration is required. For calls to ThreadMap<T>::GetOrMake, a
* full class definition is required.
*/
template <typename T>
class ThreadMap {
public:
ThreadMap() {}
/*! \brief Return the current thread's stored object, if it exists.
*
* \return If it exists, a pointer to the stored object. Otherwise,
* returns nullptr.
*/
const T* Get() const { return this->Get(std::this_thread::get_id()); }
/*! \brief Return the stored object for a given thread, if it exists.
*
* \param id The thread whose object should be returned.
*
* \return If it exists, a pointer to the stored object. Otherwise,
* returns nullptr.
*/
const T* Get(std::thread::id id) const {
std::shared_lock<std::shared_timed_mutex> lock(mutex_);
auto res = values_.find(id);
if (res == values_.end()) {
return nullptr;
} else {
return res->second.get();
}
}
/*! \brief Return the current thread's stored object, if it exists.
*
* \return If it exists, a pointer to the stored object. Otherwise,
* returns nullptr.
*/
T* Get() { return const_cast<T*>(const_cast<const ThreadMap<T>*>(this)->Get()); }
/*! \brief Return the stored object for a given thread, if it exists.
*
* \param id The thread whose object should be returned.
*
* \return If it exists, a pointer to the stored object. Otherwise,
* returns nullptr.
*/
T* Get(std::thread::id id) {
return const_cast<T*>(const_cast<const ThreadMap<T>*>(this)->Get(id));
}
/*! \brief Return the current thread's stored object, making it if
* necessary.
*
* Since this method can modify the stored map, there is no
* non-const version available.
*
* \tparam Params Types of the stored object's constructor arguments
*
* \return A reference to the stored object
*/
template <typename... Params>
T& GetOrMake(Params&&... params) {
return GetOrMake(std::this_thread::get_id(), std::forward<Params>(params)...);
}
/*! \brief Return the stored object for a given thread, making it if
* necessary
*
* Since this method can modify the stored map, there is no
* non-const version available.
*
* \tparam Params Types of the stored object's constructor arguments
*
* \param id The thread whose object should be returned.
*
* \param params Arguments to the stored object's constructor. Only
* used if the specified thread does not currently exist in the map.
*
* \return A reference to the stored object
*/
template <typename... Params>
T& GetOrMake(std::thread::id id, Params&&... params) {
// Try to get stored value first, which would only require shared
// access.
if (T* output = Get(id)) {
return *output;
}
// Not in map, need exclusive lock to write
std::unique_lock<std::shared_timed_mutex> lock(mutex_);
// Check again, in case another thread got the unique lock first
// and already constructed the object.
auto res = values_.find(id);
if (res != values_.end()) {
return *res->second;
}
// No value exists, make one and return it.
std::unique_ptr<T>& new_val = values_[id] =
std::make_unique<T>(std::forward<Params>(params)...);
return *new_val;
}
/*! \brief Clears all values held by the ThreadMap
*
* Calling Clear() invalidates any pointers/references previously
* returned by Get/GetOrMake.
*
*/
void Clear() {
std::unique_lock<std::shared_timed_mutex> lock(mutex_);
values_.clear();
}
private:
//! \brief Mutex to protect values_
mutable std::shared_timed_mutex mutex_;
//! \brief Map containing stored values
std::unordered_map<std::thread::id, std::unique_ptr<T>> values_;
};
} // namespace runtime
} // namespace tvm
#endif // TVM_RUNTIME_THREAD_MAP_H_
| https://github.com/zk-ml/tachikoma |
src/runtime/thread_storage_scope.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* \file thread_storage_scope.h
* \brief Extract launch parameters configuration from TVMArgs.
*/
#ifndef TVM_RUNTIME_THREAD_STORAGE_SCOPE_H_
#define TVM_RUNTIME_THREAD_STORAGE_SCOPE_H_
#include <tvm/runtime/metadata.h>
#include <tvm/runtime/packed_func.h>
#include <string>
#include <vector>
#include "meta_data.h"
namespace tvm {
namespace runtime {
/*!
* \brief Memory hierachy rank in the storage system
* \note The global rank and shared rank have one to one
* correspondence to the thread rank.
*/
enum class StorageRank {
/*! \brief global memory */
kGlobal = 0,
/*! \brief shared memory among thread group */
kShared = 1,
/*!
* \brief reserved for warp memory.
* This is only used by programming model.
* There is no such memory usually in GPU.
* Instead, we can simulate it by registers and shuffle.
*/
kWarp = 2,
/*! \brief thread local memory */
kLocal = 3,
/*! \brief wmma scope memory of matrix_a */
kWMMAMatrixA = 4,
/*! \brief wmma scope memory of matrix_b */
kWMMAMatrixB = 5,
/*! \brief wmma scope memory of accumulator */
kWMMAAccumulator = 6,
/*! \brief global scope texture memory */
kTexture = 7,
};
/*!
* \param thread_scope_rank The thread scope rank
* \return default storage rank given the thread scope
*/
inline StorageRank DefaultStorageRank(int thread_scope_rank) {
switch (thread_scope_rank) {
case -1:
return StorageRank::kGlobal;
case 0:
return StorageRank::kShared;
case 1:
return StorageRank::kLocal;
default: {
LOG(FATAL) << "unknown rank";
return StorageRank::kGlobal;
}
}
}
/*! \brief class to represent storage scope */
struct StorageScope {
/*! \brief The rank of the storage */
StorageRank rank{StorageRank::kGlobal};
/*! \brief tag for special purpose memory. */
std::string tag;
// comparator
inline bool operator==(const StorageScope& other) const {
return rank == other.rank && tag == other.tag;
}
inline bool operator!=(const StorageScope& other) const { return !(*this == other); }
inline std::string to_string() const {
std::string ret;
switch (rank) {
case StorageRank::kGlobal:
return "global" + tag;
case StorageRank::kShared:
return "shared" + tag;
case StorageRank::kWarp:
return "warp" + tag;
case StorageRank::kLocal:
return "local" + tag;
case StorageRank::kWMMAMatrixA:
return "wmma.matrix_a" + tag;
case StorageRank::kWMMAMatrixB:
return "wmma.matrix_b" + tag;
case StorageRank::kWMMAAccumulator:
return "wmma.accumulator" + tag;
case StorageRank::kTexture:
return "texture" + tag;
default:
LOG(FATAL) << "unknown storage scope";
return "";
}
}
/*!
* \brief Create storage scope from string
* \param s The string to be parsed.
* \return The storage scope.
*/
static StorageScope Create(const std::string& s) {
StorageScope r;
if (s.empty()) {
r.rank = StorageRank::kGlobal;
} else if (s.compare(0, 6, "global") == 0) {
r.rank = StorageRank::kGlobal;
r.tag = s.substr(6, std::string::npos);
} else if (s.compare(0, 6, "shared") == 0) {
r.rank = StorageRank::kShared;
r.tag = s.substr(6, std::string::npos);
} else if (s.compare(0, 4, "warp") == 0) {
r.rank = StorageRank::kWarp;
r.tag = s.substr(4, std::string::npos);
} else if (s.compare(0, 5, "local") == 0) {
r.rank = StorageRank::kLocal;
r.tag = s.substr(5, std::string::npos);
} else if (s.compare(0, 13, "wmma.matrix_a") == 0) {
r.rank = StorageRank::kWMMAMatrixA;
r.tag = s.substr(13, std::string::npos);
} else if (s.compare(0, 13, "wmma.matrix_b") == 0) {
r.rank = StorageRank::kWMMAMatrixB;
r.tag = s.substr(13, std::string::npos);
} else if (s.compare(0, 16, "wmma.accumulator") == 0) {
r.rank = StorageRank::kWMMAAccumulator;
r.tag = s.substr(16, std::string::npos);
} else if (s.compare(0, 7, "texture") == 0) {
r.rank = StorageRank::kTexture;
r.tag = s.substr(7, std::string::npos);
} else {
LOG(FATAL) << "unknown storage scope " << s;
}
return r;
}
};
/*! \brief class to represent thread scope */
struct ThreadScope {
/*! \brief The rank of thread scope */
int rank{0};
/*! \brief the dimension index under the rank */
int dim_index{0};
/*!
* \brief Create storage scope from string
* \param s The string to be parsed.
* \return The storage scope.
*/
static ThreadScope Create(const std::string& s) {
ThreadScope r;
if (s.compare(0, 7, "vthread") == 0 || s == "cthread") {
// virtual thread at the same level as local
r.rank = 1;
r.dim_index = -1;
} else if (s.compare(0, 9, "blockIdx.") == 0) {
r.rank = 0;
r.dim_index = static_cast<int>(s[9] - 'x');
} else if (s.compare(0, 10, "threadIdx.") == 0) {
r.rank = 1;
r.dim_index = static_cast<int>(s[10] - 'x');
} else {
LOG(FATAL) << "Unknown threadscope " << s;
}
return r;
}
};
/*! \brief workload specification */
struct ThreadWorkLoad {
// array, first three are thread configuration.
size_t work_size[6];
// Dynamic shared memory allocation size in bytes.
size_t dyn_shmem_size{0};
/*!
* \param i The block dimension.
* \return i-th block dim
*/
inline size_t block_dim(size_t i) const { return work_size[i + 3]; }
/*!
* \param i The grid dimension.
* \return i-th grid dim
*/
inline size_t grid_dim(size_t i) const { return work_size[i]; }
};
/*! \brief Launch parameters configuration */
class LaunchParamConfig {
public:
void Init(size_t base, const std::vector<std::string>& launch_param_tags) {
base_ = base;
std::vector<bool> filled(6, false);
for (size_t i = 0; i < launch_param_tags.size(); ++i) {
const std::string& tag = launch_param_tags[i];
if (tag == launch_param::kUseDynamicSharedMemoryTag) {
ICHECK_EQ(i, launch_param_tags.size() - 1)
<< "kUseDynamicSharedMemoryTag should be the last tag in launch_param_tags.";
use_dyn_shared_memory_ = true;
} else {
ThreadScope ts = ThreadScope::Create(tag);
arg_index_map_.push_back(ts.rank * 3 + ts.dim_index);
filled[ts.rank * 3 + ts.dim_index] = true;
}
}
work_dim_ = 1;
for (int i = 0; i < 3; ++i) {
if (filled[i] || filled[i + 3]) {
work_dim_ = i + 1;
}
}
}
// extract workload from arguments.
ThreadWorkLoad Extract(TVMArgs x) const {
ThreadWorkLoad w;
std::fill(w.work_size, w.work_size + 6, 1);
for (size_t i = 0; i < arg_index_map_.size(); ++i) {
// Dynamic shapes can result in 0 dim size. Guard to ensure that the dim size is at least 1.
size_t size = static_cast<size_t>(x.values[base_ + i].v_int64);
if (size > 0) {
w.work_size[arg_index_map_[i]] = size;
}
}
if (use_dyn_shared_memory_) {
w.dyn_shmem_size = static_cast<size_t>(x.values[base_ + arg_index_map_.size()].v_int64);
}
return w;
}
// return the work dim
size_t work_dim() const { return work_dim_; }
private:
/*! \brief base axis */
size_t base_;
/*! \brief The worker dimension */
size_t work_dim_;
/*! \brief The index mapping. */
std::vector<uint32_t> arg_index_map_;
/*! \brief Whether or not use dynamic shared memory. */
bool use_dyn_shared_memory_{false};
};
} // namespace runtime
} // namespace tvm
namespace std {
template <>
struct hash<::tvm::runtime::StorageScope> {
std::size_t operator()(const ::tvm::runtime::StorageScope& k) const {
return static_cast<size_t>(k.rank);
}
};
} // namespace std
#endif // TVM_RUNTIME_THREAD_STORAGE_SCOPE_H_
| https://github.com/zk-ml/tachikoma |
src/runtime/vm/naive_allocator.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* \file src/runtime/naive_allocator.h
*/
#ifndef TVM_RUNTIME_VM_NAIVE_ALLOCATOR_H_
#define TVM_RUNTIME_VM_NAIVE_ALLOCATOR_H_
#include <tvm/runtime/device_api.h>
#include <tvm/runtime/vm/memory_manager.h>
#include <atomic>
namespace tvm {
namespace runtime {
namespace vm {
class NaiveAllocator final : public Allocator {
public:
explicit NaiveAllocator(Device dev) : Allocator(kNaive), used_memory_(0), device_(dev) {}
Buffer Alloc(size_t nbytes, size_t alignment, DLDataType type_hint) override {
Buffer buf;
buf.device = device_;
buf.size = nbytes;
buf.data = DeviceAPI::Get(device_)->AllocDataSpace(device_, nbytes, alignment, type_hint);
used_memory_.fetch_add(nbytes, std::memory_order_relaxed);
DLOG(INFO) << "allocate " << nbytes << " B, used memory " << used_memory_ << " B";
return buf;
}
void Free(const Buffer& buffer) override {
DeviceAPI::Get(device_)->FreeDataSpace(buffer.device, buffer.data);
used_memory_.fetch_sub(buffer.size, std::memory_order_relaxed);
DLOG(INFO) << "free " << buffer.size << " B, used memory " << used_memory_ << " B";
}
size_t UsedMemory() const override { return used_memory_.load(std::memory_order_relaxed); }
private:
std::atomic<size_t> used_memory_;
Device device_;
};
} // namespace vm
} // namespace runtime
} // namespace tvm
#endif // TVM_RUNTIME_VM_NAIVE_ALLOCATOR_H_
| https://github.com/zk-ml/tachikoma |
src/runtime/vm/pooled_allocator.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* \file runtime/pooled_allocator.h
*/
#ifndef TVM_RUNTIME_VM_POOLED_ALLOCATOR_H_
#define TVM_RUNTIME_VM_POOLED_ALLOCATOR_H_
#include <tvm/runtime/device_api.h>
#include <tvm/runtime/vm/memory_manager.h>
#include <atomic>
#include <mutex>
#include <unordered_map>
#include <vector>
namespace tvm {
namespace runtime {
namespace vm {
class PooledAllocator final : public Allocator {
public:
static constexpr size_t kDefaultPageSize = 4096;
explicit PooledAllocator(Device dev, size_t page_size = kDefaultPageSize)
: Allocator(kPooled), page_size_(page_size), used_memory_(0), device_(dev) {}
~PooledAllocator() { ReleaseAll(); }
Buffer Alloc(size_t nbytes, size_t alignment, DLDataType type_hint) override {
std::lock_guard<std::recursive_mutex> lock(mu_);
size_t size = ((nbytes + page_size_ - 1) / page_size_) * page_size_;
auto&& it = memory_pool_.find(size);
if (it != memory_pool_.end() && !it->second.empty()) {
auto&& pool = it->second;
auto ret = pool.back();
pool.pop_back();
return ret;
}
Buffer buf;
buf.device = device_;
buf.size = size;
try {
buf.data = DeviceAPI::Get(device_)->AllocDataSpace(device_, size, alignment, type_hint);
} catch (InternalError& err) {
LOG(WARNING) << "PooledAllocator got InternalError during allocation: " << err.message();
LOG(WARNING) << "Trying to release all unused memory and reallocate...";
ReleaseAll();
buf.data = DeviceAPI::Get(device_)->AllocDataSpace(device_, size, alignment, type_hint);
}
used_memory_.fetch_add(size, std::memory_order_relaxed);
VLOG(1) << "allocate " << size << " B, used memory " << used_memory_ << " B";
return buf;
}
void Free(const Buffer& buffer) override {
std::lock_guard<std::recursive_mutex> lock(mu_);
if (memory_pool_.find(buffer.size) == memory_pool_.end()) {
memory_pool_.emplace(buffer.size, std::vector<Buffer>{});
}
memory_pool_.at(buffer.size).push_back(buffer);
VLOG(1) << "reclaim buffer " << buffer.size;
}
size_t UsedMemory() const override { return used_memory_.load(std::memory_order_relaxed); }
private:
void ReleaseAll() {
std::lock_guard<std::recursive_mutex> lock(mu_);
for (auto const& it : memory_pool_) {
auto const& pool = it.second;
for (auto const& buf : pool) {
DeviceAPI::Get(buf.device)->FreeDataSpace(buf.device, buf.data);
}
}
memory_pool_.clear();
used_memory_ = 0;
VLOG(1) << "release all buffers";
}
private:
size_t page_size_;
std::atomic<size_t> used_memory_;
std::unordered_map<size_t, std::vector<Buffer>> memory_pool_;
std::recursive_mutex mu_;
Device device_;
};
} // namespace vm
} // namespace runtime
} // namespace tvm
#endif // TVM_RUNTIME_VM_POOLED_ALLOCATOR_H_
| https://github.com/zk-ml/tachikoma |
src/runtime/vm/profiler/vm.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* \file src/runtime/vm/profiler/vm.h
* \brief The Relay debug virtual machine.
*/
#ifndef TVM_RUNTIME_VM_PROFILER_VM_H_
#define TVM_RUNTIME_VM_PROFILER_VM_H_
#include <tvm/runtime/profiling.h>
#include <tvm/runtime/vm/vm.h>
#include <memory>
#include <optional>
#include <string>
#include <unordered_map>
#include <vector>
namespace tvm {
namespace runtime {
namespace vm {
class VirtualMachineDebug : public VirtualMachine {
public:
VirtualMachineDebug() : VirtualMachine(), prof_({}) {}
PackedFunc GetFunction(const std::string& name, const ObjectPtr<Object>& sptr_to_self) final;
void LoadExecutable(const ObjectPtr<Executable>& exec) final;
~VirtualMachineDebug() {}
private:
void InvokePacked(Index packed_index, const PackedFunc& func, Index arg_count, Index output_size,
const std::vector<ObjectRef>& args) final;
void OpStartHook(Instruction instr) final;
void OpStopHook() final;
std::unordered_map<Index, std::string> packed_index_map_;
std::optional<profiling::Profiler> prof_;
};
} // namespace vm
} // namespace runtime
} // namespace tvm
#endif // TVM_RUNTIME_VM_PROFILER_VM_H_
| https://github.com/zk-ml/tachikoma |
src/runtime/vm/serialize_utils.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* \file src/runtime/vm/serialize_utils.h
* \brief Definitions of helpers for serializing and deserializing a Relay VM.
*/
#ifndef TVM_RUNTIME_VM_SERIALIZE_UTILS_H_
#define TVM_RUNTIME_VM_SERIALIZE_UTILS_H_
#include <dmlc/memory_io.h>
#include <tvm/runtime/vm/executable.h>
#include <functional>
#include <string>
#include <vector>
#include "../../support/utils.h"
namespace tvm {
namespace runtime {
namespace vm {
/*! \brief The magic number for the serialized VM bytecode file */
constexpr uint64_t kTVMVMBytecodeMagic = 0xD225DE2F4214151D;
template <typename T>
static inline uint64_t VectorHash(uint64_t key, const std::vector<T>& values) {
for (const auto& it : values) {
key = support::HashCombine(key, it);
}
return key;
}
// A struct to hold the funciton info in the code section.
struct VMFunctionSerializer {
/*! \brief The name of the VMFunction. */
std::string name;
/*! \brief The number of registers used by the VMFunction. */
Index register_file_size;
/*! \brief The number of instructions in the VMFunction. */
size_t num_instructions;
/*! \brief The parameters of the VMFunction. */
std::vector<std::string> params;
/*! \brief The index for the devices holding each parameter of the VMFunction. */
std::vector<Index> param_device_indexes;
VMFunctionSerializer() = default;
VMFunctionSerializer(const std::string& name, Index register_file_size, size_t num_instructions,
const std::vector<std::string>& params,
const std::vector<Index>& param_device_indexes)
: name(name),
register_file_size(register_file_size),
num_instructions(num_instructions),
params(params),
param_device_indexes(param_device_indexes) {}
/*!
* \brief Load the serialized function header.
* \param strm The stream used to load data.
* \return True if successful. Otherwise, false.
*/
bool Load(dmlc::Stream* strm) {
std::vector<std::string> func_info;
if (!strm->Read(&func_info)) return false;
ICHECK_EQ(func_info.size(), 3U) << "Failed to decode the vm function."
<< "\n";
name = func_info[0];
register_file_size = std::stoll(func_info[1]);
// Get the number of instructions.
num_instructions = static_cast<size_t>(std::stoll(func_info[2]));
if (!strm->Read(¶ms)) return false;
if (!strm->Read(¶m_device_indexes)) return false;
return true;
}
/*!
* \brief Save the VM function header into the serialized form.
* \param strm The stream used to save data.
*/
void Save(dmlc::Stream* strm) const {
std::vector<std::string> func_info;
func_info.push_back(name);
func_info.push_back(std::to_string(register_file_size));
func_info.push_back(std::to_string(num_instructions));
strm->Write(func_info);
strm->Write(params);
strm->Write(param_device_indexes);
}
};
struct VMInstructionSerializer {
/*! \brief The opcode of the instruction. */
Index opcode;
/*! \brief The fields of the instruction. */
std::vector<Index> fields;
VMInstructionSerializer() = default;
VMInstructionSerializer(Index opcode, const std::vector<Index>& fields)
: opcode(opcode), fields(fields) {}
/*!
* \brief Compute the hash of the serialized instruction.
* \return The hash that combines the opcode and all fields of the VM
* instruction.
*/
Index Hash() const {
uint64_t key = static_cast<uint64_t>(opcode);
key = VectorHash(key, fields);
return key;
}
/*!
* \brief Load the serialized instruction.
* \param strm The stream used to load data.
* \return True if successful. Otherwise, false.
*/
bool Load(dmlc::Stream* strm) {
std::vector<Index> instr;
if (!strm->Read(&instr)) return false;
ICHECK_GE(instr.size(), 2U);
Index loaded_hash = instr[0];
opcode = instr[1];
for (size_t i = 2; i < instr.size(); i++) {
fields.push_back(instr[i]);
}
Index hash = Hash();
ICHECK_EQ(loaded_hash, hash) << "Found mismatch in hash for opcode: " << opcode << "\n";
return true;
}
/*!
* \brief Save the instruction into the serialized form.
* \param strm The stream used to save data.
*/
void Save(dmlc::Stream* strm) const {
Index hash = Hash();
std::vector<Index> serialized({hash, opcode});
serialized.insert(serialized.end(), fields.begin(), fields.end());
strm->Write(serialized);
}
};
} // namespace vm
} // namespace runtime
} // namespace tvm
#endif // TVM_RUNTIME_VM_SERIALIZE_UTILS_H_
| https://github.com/zk-ml/tachikoma |
src/runtime/vulkan/vulkan_amdrgp.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#ifndef TVM_RUNTIME_VULKAN_VULKAN_AMDRGP_H_
#define TVM_RUNTIME_VULKAN_VULKAN_AMDRGP_H_
namespace tvm {
namespace runtime {
namespace vulkan {
class VulkanDevice;
class VulkanStreamProfiler {
public:
enum state { READY = 0, RUNNING, RESET };
explicit VulkanStreamProfiler(const VulkanDevice* device);
virtual ~VulkanStreamProfiler() {}
virtual void reset() { curr_state_ = RESET; }
virtual void ready() {
if (curr_state_ == RESET) {
curr_state_ = READY;
}
}
virtual void capture() = 0;
protected:
const VulkanDevice* device_;
state curr_state_;
bool available_;
};
class AmdRgpProfiler : public VulkanStreamProfiler {
public:
explicit AmdRgpProfiler(const VulkanDevice* device) : VulkanStreamProfiler(device) {}
void capture();
};
} // namespace vulkan
} // namespace runtime
} // namespace tvm
#endif // TVM_RUNTIME_VULKAN_VULKAN_AMDRGP_H_
| https://github.com/zk-ml/tachikoma |
src/runtime/vulkan/vulkan_buffer.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#ifndef TVM_RUNTIME_VULKAN_VULKAN_BUFFER_H_
#define TVM_RUNTIME_VULKAN_VULKAN_BUFFER_H_
#include <vulkan/vulkan_core.h>
#include <memory>
#include <unordered_map>
namespace tvm {
namespace runtime {
namespace vulkan {
class VulkanDevice;
class VulkanBuffer {
public:
/* \brief Allocate memory on the device
*
* \param device Which device should have the memory allocation.
* The VulkanDevice given should outlive the VulkanBuffer.
*
* \param nbytes Size of the buffer in bytes
*
* \param usage The usage flags for the buffer (e.g. transfer
* source, transfer dest, storage buffer, etc.)
*
* \param mem_type_index The memory type to index. This should be
* an index to a compatible memory located in
* VkPhysicalDeviceMemoryProperties.
*/
VulkanBuffer(const VulkanDevice& device, size_t nbytes, VkBufferUsageFlags usage,
uint32_t mem_type_index);
//! \brief Destructor, deallocates the memory and buffer.
~VulkanBuffer();
// Forbid copy assignment/constructor
VulkanBuffer(const VulkanBuffer&) = delete;
VulkanBuffer& operator=(const VulkanBuffer&) = delete;
// Allow move assignment/constructor
VulkanBuffer(VulkanBuffer&&);
VulkanBuffer& operator=(VulkanBuffer&&);
private:
/*! \brief Whether this buffer should be allocated using dedicated
* allocation
*
* In typical usage, there will be one VkDeviceMemory that has a
* large number of VkBuffers pointing to it. Currently, the TVM
* Vulkan runtime has a single VkBuffer for each VkDeviceMemory. In
* this case, there can be performance benefits by explicitly
* marking this as a dedicated allocation. The function returns
* true if the device supports the dedicated allocation extension,
* and the buffer either requires or has better performance with a
* dedicated allocation.
*
* \param[out] nbytes If using dedicated allocation, the number of
* bytes required for the allocation. If not using dedicated
* allocation, this value is unchanged.
*
* \returns Whether the allocation should use the dedicated
* allocation extension.
*/
static bool UseDedicatedAllocation(const VulkanDevice& device, VkBuffer buffer,
VkDeviceSize* nbytes);
// TODO(elunderberg): Move copy functionality into the buffer class
// so these don't need to be public.
public:
/*! \brief Pointer to the device that owns this buffer.
*
* Assumes that the VulkanBuffer will be destructed before the
* VulkanDevice, and this will never be a dangling reference.
* Stores a VkDevice and not a VulkanDevice, because the
* VulkanDevice may be moved to a different location while the
* VulkanBuffer is alive.
*/
VkDevice device_{VK_NULL_HANDLE};
//! \brief Handle to the logical buffer on the device
VkBuffer buffer{VK_NULL_HANDLE};
//! \brief Handle to the physical device memory
VkDeviceMemory memory{VK_NULL_HANDLE};
friend class VulkanHostVisibleBuffer;
};
/*! \brief A struct to represent Vulkan buffers backed by host visible memory */
class VulkanHostVisibleBuffer {
public:
/* \brief Allocate memory on the device, visible to the host
*
* \param device Which GPU device should have the memory allocation.
* The VulkanDevice specified should outlive the VulkanBuffer.
*
* \param nbytes Size of the buffer in bytes
*
* \param usage The usage flags for the buffer (e.g. transfer
* source, transfer dest, storage buffer, etc.)
*
* \param mem_type_index The memory type to index. This should be
* an index to a compatible memory located in
* VkPhysicalDeviceMemoryProperties.
*/
VulkanHostVisibleBuffer(const VulkanDevice& device, size_t nbytes, VkBufferUsageFlags usage,
uint32_t mem_type_index);
//! \brief Unmap memory and deallocate.
~VulkanHostVisibleBuffer();
// Forbid copy assignment/constructor
VulkanHostVisibleBuffer(const VulkanHostVisibleBuffer&) = delete;
VulkanHostVisibleBuffer& operator=(const VulkanHostVisibleBuffer&) = delete;
// Allow move assignment/constructor
VulkanHostVisibleBuffer(VulkanHostVisibleBuffer&&);
VulkanHostVisibleBuffer& operator=(VulkanHostVisibleBuffer&&);
private:
// TODO(elunderberg): Move copy functionality into the buffer class
// so these don't need to be public.
public:
VulkanBuffer vk_buf;
void* host_addr{nullptr};
size_t size{0};
};
using VulkanStagingBuffer = VulkanHostVisibleBuffer;
using VulkanUniformBuffer = VulkanHostVisibleBuffer;
VulkanHostVisibleBuffer* GetOrAllocate(
int device_id, size_t size, VkBufferUsageFlags usage, uint32_t mem_type_index,
std::unordered_map<size_t, std::unique_ptr<VulkanHostVisibleBuffer>>* buffers_ptr,
bool sync_before_realloc = false);
} // namespace vulkan
} // namespace runtime
} // namespace tvm
#endif // TVM_RUNTIME_VULKAN_VULKAN_BUFFER_H_
| https://github.com/zk-ml/tachikoma |
src/runtime/vulkan/vulkan_common.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#ifndef TVM_RUNTIME_VULKAN_VULKAN_COMMON_H_
#define TVM_RUNTIME_VULKAN_VULKAN_COMMON_H_
#include <tvm/runtime/c_runtime_api.h>
#include <tvm/runtime/device_api.h>
#include <tvm/runtime/logging.h>
#include <tvm/runtime/packed_func.h>
#include <tvm/runtime/registry.h>
#include <vulkan/vulkan.h>
#include <memory>
#include <mutex>
#include <string>
#include <vector>
namespace tvm {
namespace runtime {
namespace vulkan {
/*! \brief Maximum number of GPU supported in VulkanModule. */
static constexpr const int kVulkanMaxNumDevice = 8;
/*! \brief TVM Vulkan binary pack magic number */
static constexpr const int kVulkanModuleMagic = 0x02700027;
const int kMaxPushConstantsBytes = 128;
/*! \brief A mask used when we attach additional information to shaders */
enum ShaderMetaDataFlagMask { kUseUBO = 0 };
inline const char* VKGetErrorString(VkResult error) {
switch (error) {
case VK_SUCCESS:
return "VK_SUCCESS";
case VK_NOT_READY:
return "VK_NOT_READY";
case VK_TIMEOUT:
return "VK_TIMEOUT";
case VK_EVENT_SET:
return "VK_EVENT_SET";
case VK_EVENT_RESET:
return "VK_EVENT_RESET";
case VK_INCOMPLETE:
return "VK_INCOMPLETE";
case VK_ERROR_OUT_OF_HOST_MEMORY:
return "VK_ERROR_OUT_OF_HOST_MEMORY";
case VK_ERROR_OUT_OF_DEVICE_MEMORY:
return "VK_ERROR_OUT_OF_DEVICE_MEMORY";
case VK_ERROR_INITIALIZATION_FAILED:
return "VK_ERROR_INITIALIZATION_FAILED";
case VK_ERROR_DEVICE_LOST:
return "VK_ERROR_DEVICE_LOST";
case VK_ERROR_MEMORY_MAP_FAILED:
return "VK_ERROR_MEMORY_MAP_FAILED";
case VK_ERROR_LAYER_NOT_PRESENT:
return "VK_ERROR_LAYER_NOT_PRESENT";
case VK_ERROR_EXTENSION_NOT_PRESENT:
return "VK_ERROR_EXTENSION_NOT_PRESENT";
case VK_ERROR_FEATURE_NOT_PRESENT:
return "VK_ERROR_FEATURE_NOT_PRESENT";
case VK_ERROR_INCOMPATIBLE_DRIVER:
return "VK_ERROR_INCOMPATIBLE_DRIVER";
case VK_ERROR_TOO_MANY_OBJECTS:
return "VK_ERROR_TOO_MANY_OBJECTS";
case VK_ERROR_FORMAT_NOT_SUPPORTED:
return "VK_ERROR_FORMAT_NOT_SUPPORTED";
case VK_ERROR_FRAGMENTED_POOL:
return "VK_ERROR_FRAGMENTED_POOL";
default:
return "Unknown Vulkan error code";
}
}
/*!
* \brief Protected Vulkan call
* \param func Expression to call.
*/
#define VULKAN_CHECK_ERROR(__e) \
{ \
ICHECK(__e == VK_SUCCESS) << "Vulkan Error, code=" << __e << ": " \
<< vulkan::VKGetErrorString(__e); \
}
#define VULKAN_CALL(func) \
{ \
VkResult __e = (func); \
VULKAN_CHECK_ERROR(__e); \
}
std::vector<const char*> FindEnabledExtensions(const std::vector<VkExtensionProperties>& ext_prop,
const std::vector<const char*>& required_extensions,
const std::vector<const char*>& optional_extensions);
} // namespace vulkan
} // namespace runtime
} // namespace tvm
#endif // TVM_RUNTIME_VULKAN_VULKAN_COMMON_H_
| https://github.com/zk-ml/tachikoma |
src/runtime/vulkan/vulkan_device.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#ifndef TVM_RUNTIME_VULKAN_VULKAN_DEVICE_H_
#define TVM_RUNTIME_VULKAN_VULKAN_DEVICE_H_
#include <tvm/runtime/logging.h>
#include <memory>
#include <mutex>
#include <shared_mutex>
#include <string>
#include <thread>
#include <unordered_map>
#include <vector>
#include "../thread_map.h"
#include "vulkan/vulkan_core.h"
#include "vulkan_buffer.h"
#include "vulkan_stream.h"
namespace tvm {
namespace runtime {
namespace vulkan {
class VulkanInstance;
class VulkanDevice;
struct VulkanDescriptorTemplateKHRFunctions {
explicit VulkanDescriptorTemplateKHRFunctions(VkDevice device);
PFN_vkCreateDescriptorUpdateTemplateKHR vkCreateDescriptorUpdateTemplateKHR{nullptr};
PFN_vkDestroyDescriptorUpdateTemplateKHR vkDestroyDescriptorUpdateTemplateKHR{nullptr};
PFN_vkUpdateDescriptorSetWithTemplateKHR vkUpdateDescriptorSetWithTemplateKHR{nullptr};
PFN_vkCmdPushDescriptorSetWithTemplateKHR vkCmdPushDescriptorSetWithTemplateKHR{nullptr};
};
struct VulkanGetBufferMemoryRequirements2Functions {
explicit VulkanGetBufferMemoryRequirements2Functions(VkDevice device);
PFN_vkGetBufferMemoryRequirements2KHR vkGetBufferMemoryRequirements2KHR{nullptr};
};
struct VulkanQueueInsertDebugUtilsLabelFunctions {
explicit VulkanQueueInsertDebugUtilsLabelFunctions(VkInstance instance);
PFN_vkQueueInsertDebugUtilsLabelEXT vkQueueInsertDebugUtilsLabelEXT{nullptr};
};
/*!
* \brief Stores the capabilities/limits queried from the physical device.
*
* The member variables here have a 1-1 mapping to Target parameters,
* if target->GetTargetDeviceType()==kDLVulkan. A separate struct is used
* to maintain the boundary between the Vulkan runtime in
* libtvm_runtime.so, and the Target object in libtvm.so.
*/
struct VulkanDeviceProperties {
VulkanDeviceProperties() {}
VulkanDeviceProperties(const VulkanInstance& instance, const VulkanDevice& device);
bool supports_float16{false};
bool supports_float32{true};
bool supports_float64{false};
bool supports_int8{false};
bool supports_int16{false};
bool supports_int32{true};
bool supports_int64{false};
bool supports_8bit_buffer{false};
bool supports_16bit_buffer{false};
bool supports_storage_buffer_storage_class{false};
bool supports_push_descriptor{false};
bool supports_dedicated_allocation{false};
bool supports_integer_dot_product{false};
uint32_t supported_subgroup_operations{0};
uint32_t max_num_threads{1};
uint32_t thread_warp_size{1};
uint32_t max_block_size_x{1};
uint32_t max_block_size_y{1};
uint32_t max_block_size_z{1};
uint32_t max_push_constants_size{128};
uint32_t max_uniform_buffer_range{16384};
uint32_t max_storage_buffer_range{1 << 27};
uint32_t max_per_stage_descriptor_storage_buffer{4};
uint32_t max_shared_memory_per_block{16384};
std::string device_type{"unknown_device_type"};
std::string device_name{"unknown_device_name"};
std::string driver_name{"unknown_driver_name"};
uint32_t driver_version{0};
uint32_t vulkan_api_version{VK_API_VERSION_1_0};
uint32_t max_spirv_version{0x10000};
};
/*! \brief Handle to the Vulkan API's VkDevice
*
* Handles all setup and teardown of the class. The owner of the
* VulkanDevice object is responsible for ensuring that it remains
* alive as long as any object that accesses that device is used.
*/
class VulkanDevice {
public:
VulkanDevice(const VulkanInstance& instance, VkPhysicalDevice phy_dev);
~VulkanDevice();
// Allow move constructor/assignment
VulkanDevice(VulkanDevice&&);
VulkanDevice& operator=(VulkanDevice&&);
// Disable copy constructor/assignment
VulkanDevice(const VulkanDevice&) = delete;
VulkanDevice& operator=(const VulkanDevice&) = delete;
/*! \brief Expose the internal VkDevice
*
* Allows the managed class to be passed to Vulkan APIs as if it
* were the VkDevice handler itself.
*/
operator VkDevice() const { return device_; }
/*! \brief Expose the internal VkPhysicalDevice
*
* Allows the managed class to be passed to Vulkan APIs as if it
* were the VkPhysicalDevice handler itself.
*/
operator VkPhysicalDevice() const { return physical_device_; }
/*! \brief Returns whether this device supports Vulkan compute operations.
*
* If the device does not support Vulkan compute operations, it
* should not be used any further.
*/
bool SupportsCompute() const;
/*! \brief Calls vkQueueSubmit to run work on the GPU
*
* Currently only supports submitting a single VkSubmitInfo at a
* time. Handles mutexing internally, safe to call from multiple
* CPU threads.
*
* \param submit_info The job submission information to be passed to
* vkQueueSubmit.
*
* \param fence Optional fence to be passed to vkQueueSubmit,
* signals once the command buffers submitted have completed.
*/
void QueueSubmit(VkSubmitInfo submit_info, VkFence fence) const;
/*! \brief Checks if the device has an extension enabled
*
* Returns true if the device was initialized with the extension
* given.
*
* \param query The name of the extension to check.
*/
bool HasExtension(const char* query) const;
//! \brief Return the VulkanStream for the current CPU thread
VulkanStream& ThreadLocalStream();
//! \brief Return the VulkanStream for the current CPU thread
const VulkanStream& ThreadLocalStream() const;
/*! \brief Return the staging buffer for the current CPU thread
*
* This function may re-allocate the staging buffer depending on the
* size of the previously allocated buffer.
*
* \param min_size The size in bytes of the staging buffer to be
* returned. The buffer may be larger than requested, depending on
* previous use.
*/
VulkanStagingBuffer& ThreadLocalStagingBuffer(size_t min_size);
/*! \brief Allocate the uniform buffer for the current CPU thread
*
* \param min_size The minimum size in bytes of the uniformn buffer
* to be allocated. If a larger uniform buffer has already been
* allocated, no allocation is performed.
*/
void AllocateThreadLocalUniformBuffer(size_t min_size);
/*! \brief Return the uniform buffer for the current CPU thread
*
* Assumes that AllocateThreadLocalUniformBuffer has previously been
* called, with a min_size greater than or equal to the min_size of
* the current call. If this is not the case, will throw an
* exception.
*
* \param min_size The minimum size in bytes of the uniform buffer to be
* returned.
*/
VulkanUniformBuffer& ThreadLocalUniformBuffer(size_t min_size);
// Cached device properties, queried through Vulkan API.
VulkanDeviceProperties device_properties{};
// Memory type index for staging.
uint32_t staging_mtype_index{0};
// whether staging is coherent
bool coherent_staging{false};
std::unique_ptr<VulkanDescriptorTemplateKHRFunctions> descriptor_template_khr_functions{nullptr};
std::unique_ptr<VulkanGetBufferMemoryRequirements2Functions>
get_buffer_memory_requirements_2_functions{nullptr};
std::unique_ptr<VulkanQueueInsertDebugUtilsLabelFunctions>
queue_insert_debug_utils_label_functions{nullptr};
// Memory type index for compute
uint32_t compute_mtype_index{0};
// queue family_index;
uint32_t queue_family_index{uint32_t(-1)};
bool UseImmediate() const { return descriptor_template_khr_functions != nullptr; }
bool UseDebugUtilsLabel() const { return queue_insert_debug_utils_label_functions != nullptr; }
VkQueue Queue() const { return queue; }
private:
/*! \brief Helper function for move assignment/construction
*
* Named "do_swap" instead of "swap" because otherwise cpplint.py
* thinks that it needs the <utility> header include.
*/
void do_swap(VulkanDevice&& other);
/*! \brief Returns a queue family capable of running Vulkan compute
* operations
*/
uint32_t SelectComputeQueueFamily() const;
/*! \brief Returns the extensions to be enabled.
*
* All char* in the returned vector point to static memory
* allocations, and do not require cleanup.
*/
std::vector<const char*> SelectEnabledExtensions() const;
/*! \brief Initialize the VkDevice
*
* Called during VulkanDevice construction. Assumes that
* queue_family_index, device_properties, and enabled_extensions
* have been set.
*/
void CreateVkDevice(const VulkanInstance& instance);
//! \brief Handle to the Vulkan API physical device
VkPhysicalDevice physical_device_{nullptr};
/*! \brief Extensions enabled for this device
*
* Based on supported extensions queried from physical_device_ prior
* to creating device_. Contains only statically allocated string
* literals, no cleanup required.
*/
std::vector<const char*> enabled_extensions;
//! \brief Handle to the Vulkan API logical device
VkDevice device_{nullptr};
//! \brief Mutex to protect access to queue
mutable std::mutex queue_mutex;
/*! \brief Handle to Vulkan API VkQueue.
*
* Work can be executed by submitted to this queue using
* VulkanDevice::QueueSubmit.
*/
VkQueue queue{nullptr};
/*! \brief The VulkanStream for each CPU thread.
*
* To mimic the semantics of cudaSetDevice and cuLaunchKernel, each
* CPU thread must have a separate stream of execution. The
* ThreadMap is declared mutable so that the streams can be lazily
* generated.
*/
mutable ThreadMap<VulkanStream> stream_per_thread;
//! \brief The VulkanStagingBuffer for each CPU thread.
ThreadMap<VulkanStagingBuffer> staging_buffer_per_thread;
//! \brief The VulkanUniformBuffer for each CPU thread.
ThreadMap<VulkanUniformBuffer> uniform_buffer_per_thread;
};
uint32_t FindMemoryType(const VulkanDevice& device, VkBufferCreateInfo info,
VkMemoryPropertyFlags req_prop);
VkBufferCreateInfo MakeBufferCreateInfo(size_t nbytes, VkBufferUsageFlags usage);
} // namespace vulkan
} // namespace runtime
} // namespace tvm
#endif // TVM_RUNTIME_VULKAN_VULKAN_DEVICE_H_
| https://github.com/zk-ml/tachikoma |
src/runtime/vulkan/vulkan_device_api.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#ifndef TVM_RUNTIME_VULKAN_VULKAN_DEVICE_API_H_
#define TVM_RUNTIME_VULKAN_VULKAN_DEVICE_API_H_
#include <tvm/runtime/device_api.h>
#include <vulkan/vulkan_core.h>
#include <string>
#include <vector>
#include "../thread_map.h"
#include "../workspace_pool.h"
#include "vulkan/vulkan_core.h"
#include "vulkan_device.h"
#include "vulkan_instance.h"
namespace tvm {
namespace runtime {
namespace vulkan {
class VulkanDeviceAPI final : public DeviceAPI {
public:
static VulkanDeviceAPI* Global();
VulkanDeviceAPI();
~VulkanDeviceAPI();
// Implement active device
void SetDevice(Device dev) final;
void GetAttr(Device dev, DeviceAttrKind kind, TVMRetValue* rv) final;
// Implement memory management required by DeviceAPI
void* AllocDataSpace(Device dev, size_t nbytes, size_t alignment, DLDataType type_hint) final;
void FreeDataSpace(Device dev, void* ptr) final;
void* AllocWorkspace(Device dev, size_t size, DLDataType type_hint) final;
void FreeWorkspace(Device dev, void* data) final;
// Current vulkan implementation has one "stream" per CPU thread,
// with all commands writing into a single command buffer that is
// submitted on a call to StreamSync. Therefore, for now, these are
// mostly no-ops. If needed in the future, could have multiple
// command buffers to act as multiple streams.
TVMStreamHandle CreateStream(Device dev) final;
void FreeStream(Device dev, TVMStreamHandle stream) final;
void SyncStreamFromTo(Device dev, TVMStreamHandle event_src, TVMStreamHandle event_dst) final;
void StreamSync(Device dev, TVMStreamHandle stream) final;
void SetStream(Device dev, TVMStreamHandle stream) final;
protected:
void CopyDataFromTo(const void* from, size_t from_offset, void* to, size_t to_offset, size_t size,
Device dev_from, Device dev_to, DLDataType type_hint,
TVMStreamHandle stream) final;
// End of required methods for the DeviceAPI interface
public:
/*! \brief Return the currently active VulkanDevice
*
* The active device can be set using VulkanDeviceAPI::SetDevice.
* Each CPU thread has its own active device, mimicking the
* semantics of cudaSetDevice.
*/
VulkanDevice& GetActiveDevice();
/*! \brief Return the currently active VulkanDevice
*
* The active device can be set using VulkanDeviceAPI::SetDevice.
* Each CPU thread has its own active device, mimicking the
* semantics of cudaSetDevice.
*/
int GetActiveDeviceID();
/*! \brief Return the VulkanDevice associated with a specific device_id
*
* These are constructed during VulkanDeviceAPI initialization, so
* this function returns immediately.
*/
const VulkanDevice& device(size_t device_id) const;
/*! \brief Return the VulkanDevice associated with a specific device_id
*
* These are constructed during VulkanDeviceAPI initialization, so
* this function returns immediately.
*/
VulkanDevice& device(size_t device_id);
/*! \brief Returns a property to be stored in a target.
*
* Returns the results of feature/property queries done during the
* device initialization.
*/
void GetTargetProperty(Device dev, const std::string& property, TVMRetValue* rv) final;
private:
std::vector<uint32_t> GetComputeQueueFamilies(VkPhysicalDevice phy_dev);
/*! \brief The Vulkan API instance owned by the VulkanDeviceAPI
*
* Holds and manages VkInstance.
*/
VulkanInstance instance_;
/*! \brief Handles to the Vulkan devices
*
* The physical devices. These are constructed after the instance_,
* and must be destructed before the instance_.
*/
std::vector<VulkanDevice> devices_;
/*! \brief One pool of device memory for each CPU thread.
*
* These allocate memory based on the devices stored in devices_.
* The memory pools must be destructed before devices_.
*/
ThreadMap<WorkspacePool> pool_per_thread;
/*! \brief The index of the active device for each CPU thread.
*
* To mimic the semantics of cudaSetDevice, each CPU thread can set
* the device on which functions should run. If unset, the active
* device defaults to device_id == 0.
*/
ThreadMap<int> active_device_id_per_thread;
};
} // namespace vulkan
} // namespace runtime
} // namespace tvm
#endif // TVM_RUNTIME_VULKAN_VULKAN_DEVICE_API_H_
| https://github.com/zk-ml/tachikoma |
src/runtime/vulkan/vulkan_instance.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#ifndef TVM_RUNTIME_VULKAN_VULKAN_INSTANCE_H_
#define TVM_RUNTIME_VULKAN_VULKAN_INSTANCE_H_
#include <vector>
#include "vulkan/vulkan_core.h"
namespace tvm {
namespace runtime {
namespace vulkan {
class VulkanInstance {
public:
VulkanInstance();
~VulkanInstance();
// Allow move assignment/construction
VulkanInstance(VulkanInstance&&);
VulkanInstance& operator=(VulkanInstance&&);
// Forbid copy assignment/construction
VulkanInstance(const VulkanInstance&) = delete;
VulkanInstance& operator=(const VulkanInstance&) = delete;
/*! \brief Expose the internal VkInstance
*
* Allows the managed class to be passed to Vulkan APIs as if it
* were the VkInstance handler itself.
*/
operator VkInstance() const { return instance_; }
/*! \brief Checks if the device has an extension enabled
*
* Returns true if the device was initialized with the extension
* given.
*
* \param query The name of the extension to check.
*/
bool HasExtension(const char* query) const;
/*! \brief Return all accessible physical devices
*
* Wrapper around vkEnumeratePhysicalDevices.
*/
std::vector<VkPhysicalDevice> GetPhysicalDevices() const;
private:
/*! \brief Helper function for move assignment/construction
*
* Named "do_swap" instead of "swap" because otherwise cpplint.py
* thinks that it needs the <utility> header include.
*/
void do_swap(VulkanInstance&& other);
/*! \brief Extensions enabled for this instance
*
* Based on supported extensions queried through
* vkEnumerateInstanceExtensionProperties, prior to creating
* instance_. Contains only statically allocated string literals,
* no cleanup required.
*/
std::vector<const char*> enabled_extensions_;
//! \brief The Vulkan API instance handle
VkInstance instance_{nullptr};
};
} // namespace vulkan
} // namespace runtime
} // namespace tvm
#endif // TVM_RUNTIME_VULKAN_VULKAN_INSTANCE_H_
| https://github.com/zk-ml/tachikoma |
src/runtime/vulkan/vulkan_module.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#ifndef TVM_RUNTIME_VULKAN_VULKAN_MODULE_H_
#define TVM_RUNTIME_VULKAN_VULKAN_MODULE_H_
#include <string>
#include <unordered_map>
#include "../meta_data.h"
#include "vulkan_shader.h"
namespace tvm {
namespace runtime {
namespace vulkan {
Module VulkanModuleCreate(std::unordered_map<std::string, VulkanShader> smap,
std::unordered_map<std::string, FunctionInfo> fmap, std::string source);
} // namespace vulkan
using vulkan::VulkanModuleCreate;
} // namespace runtime
} // namespace tvm
#endif // TVM_RUNTIME_VULKAN_VULKAN_MODULE_H_
| https://github.com/zk-ml/tachikoma |
src/runtime/vulkan/vulkan_shader.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#ifndef TVM_RUNTIME_VULKAN_VULKAN_SHADER_H_
#define TVM_RUNTIME_VULKAN_VULKAN_SHADER_H_
#include <tvm/runtime/c_runtime_api.h>
#include <tvm/runtime/device_api.h>
#include <tvm/runtime/logging.h>
#include <tvm/runtime/packed_func.h>
#include <vector>
namespace tvm {
namespace runtime {
namespace vulkan {
struct VulkanShader {
/*! \brief header flag */
uint32_t flag{0};
/*! \brief Data segment */
std::vector<uint32_t> data;
void Save(dmlc::Stream* writer) const {
writer->Write(flag);
writer->Write(data);
}
bool Load(dmlc::Stream* reader) {
if (!reader->Read(&flag)) return false;
if (!reader->Read(&data)) return false;
return true;
}
};
} // namespace vulkan
using vulkan::VulkanShader;
} // namespace runtime
} // namespace tvm
namespace dmlc {
DMLC_DECLARE_TRAITS(has_saveload, ::tvm::runtime::vulkan::VulkanShader, true);
} // namespace dmlc
#endif // TVM_RUNTIME_VULKAN_VULKAN_SHADER_H_
| https://github.com/zk-ml/tachikoma |
src/runtime/vulkan/vulkan_stream.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#ifndef TVM_RUNTIME_VULKAN_VULKAN_STREAM_H_
#define TVM_RUNTIME_VULKAN_VULKAN_STREAM_H_
#include <functional>
#include <memory>
#include <unordered_map>
#include <vector>
#include "vulkan_amdrgp.h"
#include "vulkan_common.h"
namespace tvm {
namespace runtime {
namespace vulkan {
class VulkanDevice;
class VulkanStreamState {
public:
VkCommandBuffer cmd_buffer_;
VkFence fence_;
};
// Used to identify state that should only be used once-per-stream.
struct VulkanStreamToken {
VkDescriptorSet descriptor_set_{VK_NULL_HANDLE};
std::vector<VkBuffer> buffers_;
};
/*!
* \brief Wrapper around a vulkan command buffer
*
* The VulkanStream collects commands into a VkCommandBuffer. When a
* newly submitted command requires resources reserved by an
* already-submitted command, all of the queued commands are
* submitted to the GPU, and the CPU waits for all queued commands to
* finish. The queued commands can also be explicitly pushed/waited
* on by calling VulkanStream::Synchronize.
*
* Currently, there exists one VulkanStream for each GPU device, for
* each CPU thread. Each time a VulkanWrappedFunc is called, it is
* submitted to the VulkanStream associated with the submitting CPU
* thread, and associated the thread-specific active device set by
* `DeviceAPI::SetDevice`.
*/
class VulkanStream {
public:
explicit VulkanStream(const VulkanDevice* device);
~VulkanStream();
/*! \brief Push the kernel onto the stream's command buffer.
*
* If device.UseImmediate() is true, the kernel is executed
* immediately to update the command buffer. Otherwise, it is added
* to the list of deferred updates to be pushed onto the command
* buffer.
*
* Assumes that there are no descriptor sets or buffers accessed by this kernel.
*
*/
void Launch(const std::function<void(VulkanStreamState*)>& kernel);
/*! \brief Push the kernel onto the stream's command buffer.
*
* Can only be called if device.UseImmediate() is false. The
* kernel is delayed, and isn't pushed to the command buffer until
* all kernels are collected.
*
* \param deferred_initializer Updates the descriptor set. Only
* called if the deferred_token has differences from
*
* \param deferred_kernel Submits updates to the command buffer.
*
* \param deferred_token Indicates which descriptor set and buffers
* are accessed by this kernel. No two kernels in the command
* buffer can use the same descriptor set.
*
*/
void LaunchDeferred(const std::function<void()>& deferred_initializer,
const std::function<void(VulkanStreamState*)>& deferred_kernel,
const VulkanStreamToken& deferred_token);
// reset profiler state
void ProfilerReset() {
if (profiler_) {
profiler_->reset();
}
}
// set profiler to READY state after reset
void ProfilerReady() {
if (profiler_) {
profiler_->ready();
}
}
// Synchronize the current stream `state_` with respect to the host.
void Synchronize();
private:
const VulkanDevice* device_;
std::unique_ptr<VulkanStreamState> state_;
// An index of deferred tokens, allowing us to efficiently detect duplicated
// deferred_initializer blocks.
std::unordered_map<VkDescriptorSet, std::vector<VulkanStreamToken>> deferred_tokens_;
std::vector<std::function<void(VulkanStreamState*)>> deferred_kernels_;
VkCommandPool cmd_pool_;
VulkanStreamProfiler* profiler_ = nullptr;
};
} // namespace vulkan
} // namespace runtime
} // namespace tvm
#endif // TVM_RUNTIME_VULKAN_VULKAN_STREAM_H_
| https://github.com/zk-ml/tachikoma |
src/runtime/vulkan/vulkan_wrapped_func.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#ifndef TVM_RUNTIME_VULKAN_VULKAN_WRAPPED_FUNC_H_
#define TVM_RUNTIME_VULKAN_VULKAN_WRAPPED_FUNC_H_
#include <array>
#include <memory>
#include <mutex>
#include <string>
#include <unordered_map>
#include <vector>
#include "../meta_data.h"
#include "../pack_args.h"
#include "../thread_storage_scope.h"
#include "vulkan/vulkan_core.h"
#include "vulkan_common.h"
#include "vulkan_device.h"
#include "vulkan_shader.h"
namespace tvm {
namespace runtime {
namespace vulkan {
struct VulkanPipeline {
VulkanDevice* device{nullptr};
VkShaderModule shader{VK_NULL_HANDLE};
VkDescriptorSetLayout descriptor_set_layout{VK_NULL_HANDLE};
VkDescriptorPool descriptor_pool{VK_NULL_HANDLE};
VkDescriptorSet descriptor_set{VK_NULL_HANDLE};
VkPipelineLayout pipeline_layout{VK_NULL_HANDLE};
VkPipeline pipeline{VK_NULL_HANDLE};
VkDescriptorUpdateTemplateKHR descriptor_update_template{VK_NULL_HANDLE};
bool use_ubo{false};
};
class VulkanModuleNode;
// a wrapped function class to get packed func.
class VulkanWrappedFunc {
public:
void Init(VulkanModuleNode* m, ObjectPtr<Object> sptr, const std::string& func_name,
size_t num_buffer_args, size_t num_pack_args,
const std::vector<std::string>& launch_param_tags);
void operator()(TVMArgs args, TVMRetValue* rv, const ArgUnion64* pack_args) const;
private:
// internal module
VulkanModuleNode* m_;
// the resource holder
ObjectPtr<Object> sptr_;
// v The name of the function.
std::string func_name_;
// Number of buffer arguments
size_t num_buffer_args_;
// number of packed arguments.
size_t num_pack_args_;
// launch parameters configuration
LaunchParamConfig launch_param_config_;
// Device state cache per device.
// mark as mutable, to enable lazy initialization
mutable std::array<std::shared_ptr<VulkanPipeline>, kVulkanMaxNumDevice> scache_;
};
class VulkanModuleNode final : public runtime::ModuleNode {
public:
explicit VulkanModuleNode(std::unordered_map<std::string, VulkanShader> smap,
std::unordered_map<std::string, FunctionInfo> fmap, std::string source)
: smap_(smap), fmap_(fmap), source_(source) {}
~VulkanModuleNode();
const char* type_key() const final { return "vulkan"; }
PackedFunc GetFunction(const std::string& name, const ObjectPtr<Object>& sptr_to_self) final;
std::shared_ptr<VulkanPipeline> GetPipeline(size_t device_id, const std::string& func_name,
size_t num_pack_args);
void SaveToFile(const std::string& file_name, const std::string& format) final;
void SaveToBinary(dmlc::Stream* stream) final;
std::string GetSource(const std::string& format) final;
private:
// function information table.
std::unordered_map<std::string, VulkanShader> smap_;
// function information table.
std::unordered_map<std::string, FunctionInfo> fmap_;
// The format
std::string fmt_{"vulkan"};
// The source
std::string source_;
// Guards accesses to `ecache_`
std::mutex mutex_;
std::array<std::unordered_map<std::string, std::shared_ptr<VulkanPipeline>>, kVulkanMaxNumDevice>
ecache_;
};
} // namespace vulkan
} // namespace runtime
} // namespace tvm
#endif // TVM_RUNTIME_VULKAN_VULKAN_WRAPPED_FUNC_H_
| https://github.com/zk-ml/tachikoma |
src/runtime/workspace_pool.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* \file workspace_pool.h
* \brief Workspace pool utility.
*/
#ifndef TVM_RUNTIME_WORKSPACE_POOL_H_
#define TVM_RUNTIME_WORKSPACE_POOL_H_
#include <tvm/runtime/device_api.h>
#include <memory>
#include <vector>
namespace tvm {
namespace runtime {
/*!
* \brief A workspace pool to manage
*
* \note We have the following assumption about backend temporal
* workspace allocation, and will optimize for such assumption,
* some of these assumptions can be enforced by the compiler.
*
* - Only a few allocation will happen, and space will be released after use.
* - The release order is usually in reverse order of allocate
* - Repeative pattern of same allocations over different runs.
*/
class TVM_DLL WorkspacePool {
public:
/*!
* \brief Create pool with specific device type and device.
* \param device_type The device type.
* \param device_api The device API.
*/
WorkspacePool(DLDeviceType device_type, DeviceAPI* device_api);
/*! \brief destructor */
~WorkspacePool();
/*!
* \brief Allocate temporal workspace.
* \param dev The device of allocation.
* \param size The size to be allocated.
*/
void* AllocWorkspace(Device dev, size_t size);
/*!
* \brief Free temporal workspace in backend execution.
*
* \param dev The device of allocation.
* \param ptr The pointer to be freed.
*/
void FreeWorkspace(Device dev, void* ptr);
private:
class Pool;
/*! \brief pool of device local array */
std::vector<Pool*> array_;
/*! \brief device type this pool support */
DLDeviceType device_type_;
/*! \brief The device API */
DeviceAPI* device_;
};
} // namespace runtime
} // namespace tvm
#endif // TVM_RUNTIME_WORKSPACE_POOL_H_
| https://github.com/zk-ml/tachikoma |
src/script/ir_builder/tir/utils.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#ifndef TVM_SCRIPT_IR_BUILDER_TIR_UTILS_H_
#define TVM_SCRIPT_IR_BUILDER_TIR_UTILS_H_
#include <tvm/script/ir_builder/tir/frame.h>
#include <tvm/script/ir_builder/tir/ir.h>
#include <tvm/tir/stmt.h>
namespace tvm {
namespace script {
namespace ir_builder {
namespace tir {
/*!
* \brief Add tir Stmt to the top frame in IRBuilder frame stack.
* \param stmt The Stmt.
*/
inline void AddToParent(tvm::tir::Stmt stmt) {
IRBuilder builder = IRBuilder::Current();
if (builder->frames.empty()) {
ICHECK(!builder->result.defined()) << "ValueError: Builder.result has already been set";
builder->result = stmt;
} else if (const auto* tir_frame = builder->frames.back().as<TIRFrameNode>()) {
GetRef<TIRFrame>(tir_frame)->stmts.push_back(stmt);
} else {
LOG(FATAL) << "TypeError: Unsupported frame type: " << builder->frames.back();
}
}
/*!
* \brief Convert array of tir Stmt to single Stmt.
* \param stmt The array of Stmt.
* \return The SeqStmt.
*/
inline tvm::tir::Stmt AsStmt(const Array<tvm::tir::Stmt>& stmt) {
using namespace tvm::tir;
if (stmt.empty()) {
return tvm::tir::Evaluate(0);
} else if (stmt.size() == 1) {
return stmt[0];
} else {
return SeqStmt(stmt);
}
}
/*!
* \brief Check whether the top frame in IRBuilder frame stack is PrimFuncFrame.
* \param method The method name to be printed when throwing exception.
* \return The top frame of PrimFuncFrame.
*/
inline PrimFuncFrame FindPrimFuncFrame(const String& method) {
if (Optional<PrimFuncFrame> frame = IRBuilder::Current()->GetLastFrame<PrimFuncFrame>()) {
return frame.value();
}
LOG(FATAL) << "ValueError: PrimFunc frame not find. Please ensure '" << method
<< "' is called under T.prim_func()";
throw;
}
/*!
* \brief Check whether the top frame in IRBuilder frame stack is BlockFrame.
* \param method The method name to be printed when throwing exception.
* \return The top frame of BlockFrame.
*/
inline BlockFrame FindBlockFrame(const String& method) {
if (Optional<BlockFrame> frame = IRBuilder::Current()->GetLastFrame<BlockFrame>()) {
return frame.value();
}
LOG(FATAL) << "ValueError: Block frame not find. Please ensure '" << method
<< "' is called under T.block()";
throw;
}
/*!
* \brief Check whether the top frame in IRBuilder frame stack is IfFrame.
* \param method The method name to be printed when throwing exception.
* \return The top frame of IfFrame.
*/
inline IfFrame FindIfFrame(const String& method) {
if (Optional<IfFrame> frame = IRBuilder::Current()->GetLastFrame<IfFrame>()) {
return frame.value();
} else {
LOG(FATAL) << "ValueError: IfThenElse frame not find. Please ensure '" << method
<< "' is called under T.if_()";
}
throw;
}
/*!
* \brief Convert BufferLoad to BufferRegion.
* \param buffer_load The BufferLoad.
* \return The converted BufferRegion.
*/
inline tvm::tir::BufferRegion BufferRegionFromLoad(tvm::tir::BufferLoad buffer_load) {
Array<Range> ranges;
for (const PrimExpr& index : buffer_load->indices) {
ranges.push_back(Range::FromMinExtent(index, IntImm(index->dtype, 1)));
}
return tvm::tir::BufferRegion(buffer_load->buffer, ranges);
}
} // namespace tir
} // namespace ir_builder
} // namespace script
} // namespace tvm
#endif // TVM_SCRIPT_IR_BUILDER_TIR_UTILS_H_
| https://github.com/zk-ml/tachikoma |
src/script/printer/base_doc_printer.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#ifndef TVM_SCRIPT_PRINTER_BASE_DOC_PRINTER_H_
#define TVM_SCRIPT_PRINTER_BASE_DOC_PRINTER_H_
#include <tvm/script/printer/doc.h>
#include <tvm/script/printer/doc_printer.h>
#include <limits>
#include <memory>
#include <ostream>
#include <string>
#include <utility>
#include <vector>
namespace tvm {
namespace script {
namespace printer {
/*! \brief Range of byte offsets in a string */
using ByteSpan = std::pair<size_t, size_t>;
/*! \brief Options to customize DocPrinter's output */
struct DocPrinterOptions {
/*! \brief Number of spaces for one level of indentation */
int indent_spaces = 4;
/*! \brief Whether to print the line numbers */
bool print_line_numbers = false;
/*!
* \brief Number of context lines to print around the underlined text.
*
* If set to a non-default value `n`, only print `n` context lines before and after
* the underlined pieces of text.
*/
size_t num_context_lines = std::numeric_limits<size_t>::max();
};
/*!
* \brief DocPrinter is responsible for printing Doc tree into text format
* \details This is the base class for translating Doc into string.
* Each target language needs to have its subclass of DocPrinter
* to define the actual logic of printing Doc.
*
* \sa Doc
*/
class DocPrinter {
public:
/*!
* \brief The constructor of DocPrinter
*
* \param options the option for printer
*/
explicit DocPrinter(const DocPrinterOptions& options);
virtual ~DocPrinter() = default;
/*!
* \brief Append a doc into the final content
*
* \param doc the Doc to be printed
*
* \sa GetString
*/
void Append(const Doc& doc);
/*!
* \brief Append a doc to the final content
*
* \param doc Doc to be printed
* \param path_to_underline Object path to be underlined
*
* \sa GetString
*/
void Append(const Doc& doc, Optional<ObjectPath> path_to_underline);
/*!
* \brief Get the printed string of all Doc appended
*
* The content of each Doc in the returned string will
* appear in the same order as they are appended.
*
* \sa Append
*/
String GetString() const;
protected:
/*!
* \brief Get the printed string
*
* It will dispatch to the PrintTypedDoc method based on
* the actual type of Doc.
*
* \sa PrintTypedDoc
*/
void PrintDoc(const Doc& doc);
/*!
* \brief Virtual method to print a LiteralDoc
*/
virtual void PrintTypedDoc(const LiteralDoc& doc) = 0;
/*!
* \brief Virtual method to print an IdDoc
*/
virtual void PrintTypedDoc(const IdDoc& doc) = 0;
/*!
* \brief Virtual method to print an AttrAccessDoc
*/
virtual void PrintTypedDoc(const AttrAccessDoc& doc) = 0;
/*!
* \brief Virtual method to print an IndexDoc
*/
virtual void PrintTypedDoc(const IndexDoc& doc) = 0;
/*!
* \brief Virtual method to print an OperationDoc
*/
virtual void PrintTypedDoc(const OperationDoc& doc) = 0;
/*!
* \brief Virtual method to print a CallDoc
*/
virtual void PrintTypedDoc(const CallDoc& doc) = 0;
/*!
* \brief Virtual method to print a LambdaDoc
*/
virtual void PrintTypedDoc(const LambdaDoc& doc) = 0;
/*!
* \brief Virtual method to print a ListDoc
*/
virtual void PrintTypedDoc(const ListDoc& doc) = 0;
/*!
* \brief Virtual method to print a TupleDoc
*/
virtual void PrintTypedDoc(const TupleDoc& doc) = 0;
/*!
* \brief Virtual method to print a DictDoc
*/
virtual void PrintTypedDoc(const DictDoc& doc) = 0;
/*!
* \brief Virtual method to print a SliceDoc
*/
virtual void PrintTypedDoc(const SliceDoc& doc) = 0;
/*!
* \brief Virtual method to print a StmtBlockDoc
*/
virtual void PrintTypedDoc(const StmtBlockDoc& doc) = 0;
/*!
* \brief Virtual method to print an AssignDoc
*/
virtual void PrintTypedDoc(const AssignDoc& doc) = 0;
/*!
* \brief Virtual method to print an IfDoc
*/
virtual void PrintTypedDoc(const IfDoc& doc) = 0;
/*!
* \brief Virtual method to print a WhileDoc
*/
virtual void PrintTypedDoc(const WhileDoc& doc) = 0;
/*!
* \brief Virtual method to print a ForDoc
*/
virtual void PrintTypedDoc(const ForDoc& doc) = 0;
/*!
* \brief Virtual method to print a ScopeDoc
*/
virtual void PrintTypedDoc(const ScopeDoc& doc) = 0;
/*!
* \brief Virtual method to print an ExprStmtDoc
*/
virtual void PrintTypedDoc(const ExprStmtDoc& doc) = 0;
/*!
* \brief Virtual method to print an AssertDoc
*/
virtual void PrintTypedDoc(const AssertDoc& doc) = 0;
/*!
* \brief Virtual method to print a ReturnDoc
*/
virtual void PrintTypedDoc(const ReturnDoc& doc) = 0;
/*!
* \brief Virtual method to print a FunctionDoc
*/
virtual void PrintTypedDoc(const FunctionDoc& doc) = 0;
/*!
* \brief Virtual method to print a ClassDoc
*/
virtual void PrintTypedDoc(const ClassDoc& doc) = 0;
/*!
* \brief Increase the indent level of any content to be
* printed after this call
*/
void IncreaseIndent() { indent_ += options_.indent_spaces; }
/*!
* \brief Decrease the indent level of any content to be
* printed after this call
*/
void DecreaseIndent() { indent_ -= options_.indent_spaces; }
/*!
* \brief Add a new line into the output stream
*
* \sa output_
*/
std::ostream& NewLine() {
output_ << "\n";
line_starts_.push_back(output_.tellp());
output_ << std::string(indent_, ' ');
return output_;
}
/*!
* \brief The output stream of printer
*
* All printed content will be stored in this stream and returned
* when GetString is called.
*
* \sa GetString
*/
std::ostringstream output_;
private:
void MarkSpan(const ByteSpan& span, const ObjectPath& path);
/*! \brief Options to customize certain aspects of the output */
DocPrinterOptions options_;
/*! \brief the current level of indent */
int indent_ = 0;
/*! \brief For each line in the output_, byte offset of its first character */
std::vector<size_t> line_starts_;
/*! \brief Path of the object that we would like to underline */
Optional<ObjectPath> path_to_underline_;
/*!
* \brief Candidate spans to be underlined, until we find a better match.
* (A better match is an object with a longer path that is still a prefix of path_to_underline_.)
*/
std::vector<ByteSpan> current_underline_candidates_;
/*! \brief Path length of the objects that are current candidates for underlining. */
int current_max_path_length_;
/*! \brief Spans that we have already committed to underline. */
std::vector<ByteSpan> underlines_;
};
} // namespace printer
} // namespace script
} // namespace tvm
#endif // TVM_SCRIPT_PRINTER_BASE_DOC_PRINTER_H_
| https://github.com/zk-ml/tachikoma |
src/script/printer/utils.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#ifndef TVM_SCRIPT_PRINTER_UTILS_H_
#define TVM_SCRIPT_PRINTER_UTILS_H_
#include <tvm/script/printer/doc.h>
#include <tvm/script/printer/ir_docsifier.h>
#include <utility>
namespace tvm {
namespace script {
namespace printer {
template <typename DocType, typename NodeType>
Array<DocType> AsDocArray(const TracedArray<NodeType>& refs, const IRDocsifier& ir_docsifier) {
Array<DocType> result;
for (auto ref : refs) {
result.push_back(ir_docsifier->AsExprDoc(ref));
}
return result;
}
template <typename DocType, typename NodeType>
Array<DocType> AsDocArray(std::initializer_list<NodeType>&& refs, const IRDocsifier& ir_docsifier) {
Array<DocType> result;
for (auto& ref : refs) {
result.push_back(ir_docsifier->AsExprDoc(ref));
}
return result;
}
template <typename RefType>
Array<ExprDoc> AsExprDocArray(const TracedArray<RefType>& refs, const IRDocsifier& ir_docsifier) {
return AsDocArray<ExprDoc>(refs, ir_docsifier);
}
template <typename RefType>
Array<ExprDoc> AsExprDocArray(std::initializer_list<RefType>&& refs,
const IRDocsifier& ir_docsifier) {
return AsDocArray<ExprDoc>(std::move(refs), ir_docsifier);
}
inline DictDoc AsDictDoc(const TracedMap<String, ObjectRef>& dict,
const IRDocsifier& ir_docsifier) {
Array<ExprDoc> keys;
Array<ExprDoc> values;
for (auto p : dict) {
keys.push_back(LiteralDoc::Str(p.first));
values.push_back(ir_docsifier->AsExprDoc(p.second));
}
auto doc = DictDoc(keys, values);
doc->source_paths.push_back(dict.GetPath());
return doc;
}
template <typename T>
inline ListDoc AsListDoc(const TracedArray<T>& arr, const IRDocsifier& ir_docsifier) {
auto ret = ListDoc(AsExprDocArray(arr, ir_docsifier));
ret->source_paths.push_back(arr.GetPath());
return ret;
}
template <typename T>
inline TupleDoc AsTupleDoc(const TracedArray<T>& arr, const IRDocsifier& ir_docsifier) {
auto ret = TupleDoc(AsExprDocArray(arr, ir_docsifier));
ret->source_paths.push_back(arr.GetPath());
return ret;
}
} // namespace printer
} // namespace script
} // namespace tvm
#endif // TVM_SCRIPT_PRINTER_UTILS_H_
| https://github.com/zk-ml/tachikoma |
src/support/arena.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
*
* \file arena.h
* \brief Arena allocator that allocates
* memory chunks and frees them all during destruction time.
*/
#ifndef TVM_SUPPORT_ARENA_H_
#define TVM_SUPPORT_ARENA_H_
#include <cstddef>
#include <type_traits>
#include <utility>
#include "generic_arena.h"
namespace tvm {
namespace support {
/*!
* \brief Simple page allocator that uses new and delete.
*/
class SimplePageAllocator {
public:
/*!
* \brief Allocate a new page.
* \param min_size Minimum size of the page.
* \return The allocated page.
* \note This function can return a bigger page to meet the min_size requirement.
*/
ArenaPageHeader* allocate(size_t min_size) {
size_t npages = ((min_size + kPageSize - 1) / kPageSize);
ArenaPageHeader* header = reinterpret_cast<ArenaPageHeader*>(new Page[npages]);
header->size = npages * kPageSize;
header->offset = sizeof(ArenaPageHeader);
return header;
}
/*!
* \brief De-allocate an allocate page.
* \param page The page to be de-allocated.
*/
void deallocate(ArenaPageHeader* page) { delete[] reinterpret_cast<Page*>(page); }
static const constexpr int kPageSize = 16 << 10;
static const constexpr int kPageAlign = 1024;
private:
// page size 16 KB
// The page data type;
using Page = std::aligned_storage<kPageSize, kPageAlign>::type;
};
using Arena = GenericArena<SimplePageAllocator>;
/*!
* \brief Link list node
* \tparam T the content data type
*/
template <typename T>
struct LinkNode {
/*! \brief The content value */
T value;
/*! \brief pointer to the next location */
LinkNode<T>* next{nullptr};
};
/*!
* \brief LinkedList structure
* \tparam T the content data type
* \note This is a simple data structure that can be used together with the arena.
* \sa LinkNode
*/
template <typename T>
struct LinkedList {
/*! \brief Head pointer */
LinkNode<T>* head{nullptr};
/*! \brief Tail pointer */
LinkNode<T>* tail{nullptr};
/*!
* \brief Push a new node to the end of the linked list.
* \param node The node to be pushed.
*/
void Push(LinkNode<T>* node) {
node->next = nullptr;
if (this->tail != nullptr) {
this->tail->next = node;
this->tail = node;
} else {
head = tail = node;
}
}
};
} // namespace support
} // namespace tvm
#endif // TVM_SUPPORT_ARENA_H_
| https://github.com/zk-ml/tachikoma |
src/support/array.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#ifndef TVM_SUPPORT_ARRAY_H_
#define TVM_SUPPORT_ARRAY_H_
#include <tvm/ir/expr.h>
#include <tvm/runtime/container/array.h>
#include <vector>
namespace tvm {
namespace support {
/*!
* \brief Checks if two arrays contain the same objects
* \tparam T The type of objects in the array
* \param a The first array
* \param b The second array
* \return A boolean indicating if they are the same
*/
template <class T>
inline bool ArrayWithSameContent(const Array<T>& a, const Array<T>& b) {
if (a.size() != b.size()) {
return false;
}
int n = a.size();
for (int i = 0; i < n; ++i) {
if (!a[i].same_as(b[i])) {
return false;
}
}
return true;
}
/*!
* \brief Checks if two arrays contain the same objects
* \tparam T The type of objects in the array
* \param a The first array
* \param b The second array
* \return A boolean indicating if they are the same
*/
template <class T>
inline bool ArrayWithSameContent(const std::vector<T*>& a, const std::vector<T*>& b) {
if (a.size() != b.size()) {
return false;
}
int n = a.size();
for (int i = 0; i < n; ++i) {
if (a[i] != b[i]) {
return false;
}
}
return true;
}
/*!
* \brief Convert a tvm::runtime::Array to std::vector
* \tparam TSrc The type of elements in the source Array
* \tparam TDst The type of elements in the result vector
* \return The result vector
*/
template <class TSrc, class TDst>
inline std::vector<TDst> AsVector(const Array<TSrc>& vec);
/*!
* \brief Convert a std::vector to tvm::runtime::Array
* \tparam TSrc The type of elements in the source vector
* \tparam TDst The type of elements in the result Array
* \return The result vector
*/
template <class TSrc, class TDst>
inline Array<TDst> AsArray(const std::vector<TSrc>& vec);
/*!
* \brief Get the shape tuple as array
* \param shape The shape tuple
* \return An array of the shape tuple
*/
inline Array<Integer> AsArray(const ShapeTuple& shape) {
Array<Integer> result;
result.reserve(shape->size);
for (ShapeTuple::index_type i : shape) {
result.push_back(Integer(i));
}
return result;
}
/*!
* \brief Concatenate a list of arrays into a single array
* \tparam T The type of elements in the arrays
* \tparam Iterator The type of the iterator into the list of arrays
* \param begin The begin iterator to the array list
* \param end The end iterator to the array list
* \return The concatenated array
*/
template <class T, class Iterator>
inline Array<T> ConcatArrayList(Iterator begin, Iterator end) {
int size = 0;
for (Iterator it = begin; it != end; ++it) {
size += (*it).size();
}
Array<T> result;
result.reserve(size);
for (Iterator it = begin; it != end; ++it) {
const auto& item = *it;
result.insert(result.end(), item.begin(), item.end());
}
return result;
}
/********** Implementation details of AsVector<TSrc, TDst> **********/
namespace details {
template <class TSrc, class TDst>
struct AsVectorImpl {};
template <class TSrc>
struct AsVectorImpl<TSrc, TSrc> {
inline std::vector<TSrc> operator()(const Array<TSrc>& vec) const {
return std::vector<TSrc>(vec.begin(), vec.end());
}
};
template <class TSrcObjectRef>
struct AsVectorImpl<TSrcObjectRef, int> {
inline std::vector<int> operator()(const Array<TSrcObjectRef>& vec) const {
std::vector<int> results;
for (const TSrcObjectRef& x : vec) {
const auto* n = x.template as<IntImmNode>();
ICHECK(n) << "TypeError: Expects IntImm, but gets: " << x->GetTypeKey();
results.push_back(n->value);
}
return results;
}
};
template <class TSrcObjectRef>
struct AsVectorImpl<TSrcObjectRef, int64_t> {
inline std::vector<int64_t> operator()(const Array<TSrcObjectRef>& vec) const {
std::vector<int64_t> results;
for (const TSrcObjectRef& x : vec) {
const auto* n = x.template as<IntImmNode>();
ICHECK(n) << "TypeError: Expects IntImm, but gets: " << x->GetTypeKey();
results.push_back(n->value);
}
return results;
}
};
template <class TSrcObjectRef>
struct AsVectorImpl<TSrcObjectRef, double> {
inline std::vector<double> operator()(const Array<TSrcObjectRef>& array) const {
std::vector<double> results;
for (const TSrcObjectRef& x : array) {
const auto* n = x.template as<FloatImmNode>();
ICHECK(n) << "TypeError: Expects FloatImm, but gets: " << x->GetTypeKey();
results.push_back(n->value);
}
return results;
}
};
} // namespace details
/********** Implementation details of AsArray<TSrc, TDst> **********/
namespace details {
template <class TSrc, class TDst>
struct AsArrayImpl {};
template <class TSrc>
struct AsArrayImpl<TSrc, TSrc> {
inline Array<TSrc> operator()(const std::vector<TSrc>& vec) const {
return Array<TSrc>(vec.begin(), vec.end());
}
};
template <class TDstObjectRef>
struct AsArrayImpl<int, TDstObjectRef> {
inline Array<TDstObjectRef> operator()(const std::vector<int>& vec) const {
Array<TDstObjectRef> result;
result.reserve(vec.size());
for (int x : vec) {
result.push_back(Integer(x));
}
return result;
}
};
template <class TDstObjectRef>
struct AsArrayImpl<int64_t, TDstObjectRef> {
inline Array<TDstObjectRef> operator()(const std::vector<int64_t>& vec) const {
Array<TDstObjectRef> result;
result.reserve(vec.size());
for (int64_t x : vec) {
result.push_back(Integer(x));
}
return result;
}
};
template <class TDstObjectRef>
struct AsArrayImpl<double, TDstObjectRef> {
inline Array<TDstObjectRef> operator()(const std::vector<double>& vec) const {
Array<TDstObjectRef> result;
result.reserve(vec.size());
for (double x : vec) {
result.push_back(FloatImm(tvm::DataType::Float(64), x));
}
return result;
}
};
} // namespace details
template <class TSrc, class TDst>
inline std::vector<TDst> AsVector(const Array<TSrc>& vec) {
return details::AsVectorImpl<TSrc, TDst>()(vec);
}
template <class TSrc, class TDst>
inline Array<TDst> AsArray(const std::vector<TSrc>& vec) {
return details::AsArrayImpl<TSrc, TDst>()(vec);
}
} // namespace support
} // namespace tvm
#endif // TVM_SUPPORT_ARRAY_H_
| https://github.com/zk-ml/tachikoma |
src/support/base64.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
*
* \file base64.h
* \brief data stream support to input and output from/to base64 stream
* base64 is easier to store and pass as text format in mapreduce
*/
#ifndef TVM_SUPPORT_BASE64_H_
#define TVM_SUPPORT_BASE64_H_
#include <tvm/runtime/logging.h>
#include <cctype>
#include <cstdio>
#include <string>
namespace tvm {
namespace support {
/*! \brief namespace of base64 decoding and encoding table */
namespace base64 {
// decoding table
const char DecodeTable[] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
62, // '+'
0, 0, 0,
63, // '/'
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, // '0'-'9'
0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, // 'A'-'Z'
0, 0, 0, 0, 0, 0, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41,
42, 43, 44, 45, 46, 47, 48, 49, 50, 51, // 'a'-'z'
};
// encoding table
static const char EncodeTable[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
} // namespace base64
/*!
* \brief Buffer reader from stream to avoid
* virtual call overhead on each read.
*/
class StreamBufferReader {
public:
explicit StreamBufferReader(size_t buffer_size) { buffer_.resize(buffer_size); }
/*!
* \brief set input stream
* \param stream The stream to be set
*/
void set_stream(dmlc::Stream* stream) {
stream_ = stream;
read_len_ = read_ptr_ = 1;
}
/*!
* \return allows quick read using get char
*/
int GetChar() {
while (true) {
if (read_ptr_ < read_len_) {
return static_cast<int>(buffer_[read_ptr_++]);
} else {
read_len_ = stream_->Read(&buffer_[0], buffer_.length());
if (read_len_ == 0) return EOF;
read_ptr_ = 0;
}
}
}
/*! \return whether we are reaching the end of file */
bool AtEnd() const { return read_len_ == 0; }
private:
/*! \brief the underlying stream */
dmlc::Stream* stream_{nullptr};
/*! \brief buffer to hold data */
std::string buffer_;
/*! \brief length of valid data in buffer */
size_t read_len_{1};
/*! \brief pointer in the buffer */
size_t read_ptr_{1};
};
/*!
* \brief Input stream from base64 encoding
*/
class Base64InStream : public dmlc::Stream {
public:
explicit Base64InStream(dmlc::Stream* fs) : reader_(256) { reader_.set_stream(fs); }
/*!
* \brief initialize the stream position to beginning of next base64 stream
* \note call this function before actually start read
*/
void InitPosition(void) {
// get a character
do {
temp_ch_ = reader_.GetChar();
} while (isspace(temp_ch_));
}
/*! \brief whether current position is end of a base64 stream */
bool IsEOF(void) const { return num_prev_ == 0 && (temp_ch_ == EOF || isspace(temp_ch_)); }
// override read function.
virtual size_t Read(void* ptr, size_t size) {
using base64::DecodeTable;
if (size == 0) return 0;
// use tlen to record left size
size_t tlen = size;
unsigned char* cptr = static_cast<unsigned char*>(ptr);
// if anything left, load from previous buffered result
if (num_prev_ != 0) {
if (num_prev_ == 2) {
if (tlen >= 2) {
*cptr++ = buf_prev[0];
*cptr++ = buf_prev[1];
tlen -= 2;
num_prev_ = 0;
} else {
// assert tlen == 1
*cptr++ = buf_prev[0];
--tlen;
buf_prev[0] = buf_prev[1];
num_prev_ = 1;
}
} else {
// assert num_prev_ == 1
*cptr++ = buf_prev[0];
--tlen;
num_prev_ = 0;
}
}
if (tlen == 0) return size;
int nvalue;
// note: everything goes with 4 bytes in Base64
// so we process 4 bytes a unit
while (tlen && temp_ch_ != EOF && !isspace(temp_ch_)) {
// first byte
nvalue = DecodeTable[temp_ch_] << 18;
{
// second byte
temp_ch_ = reader_.GetChar();
ICHECK(temp_ch_ != EOF && !isspace(temp_ch_)) << "invalid base64 format";
nvalue |= DecodeTable[temp_ch_] << 12;
*cptr++ = (nvalue >> 16) & 0xFF;
--tlen;
}
{
// third byte
temp_ch_ = reader_.GetChar();
ICHECK(temp_ch_ != EOF && !isspace(temp_ch_)) << "invalid base64 format";
// handle termination
if (temp_ch_ == '=') {
temp_ch_ = reader_.GetChar();
ICHECK(temp_ch_ == '=') << "invalid base64 format";
temp_ch_ = reader_.GetChar();
ICHECK(temp_ch_ == EOF || isspace(temp_ch_)) << "invalid base64 format";
break;
}
nvalue |= DecodeTable[temp_ch_] << 6;
if (tlen) {
*cptr++ = (nvalue >> 8) & 0xFF;
--tlen;
} else {
buf_prev[num_prev_++] = (nvalue >> 8) & 0xFF;
}
}
{
// fourth byte
temp_ch_ = reader_.GetChar();
ICHECK(temp_ch_ != EOF && !isspace(temp_ch_)) << "invalid base64 format";
if (temp_ch_ == '=') {
temp_ch_ = reader_.GetChar();
ICHECK(temp_ch_ == EOF || isspace(temp_ch_)) << "invalid base64 format";
break;
}
nvalue |= DecodeTable[temp_ch_];
if (tlen) {
*cptr++ = nvalue & 0xFF;
--tlen;
} else {
buf_prev[num_prev_++] = nvalue & 0xFF;
}
}
// get next char
temp_ch_ = reader_.GetChar();
}
if (kStrictCheck) {
ICHECK_EQ(tlen, 0) << "Base64InStream: read incomplete";
}
return size - tlen;
}
virtual void Write(const void* ptr, size_t size) {
LOG(FATAL) << "Base64InStream do not support write";
}
private:
// internal reader
StreamBufferReader reader_;
int temp_ch_{0};
int num_prev_{0};
unsigned char buf_prev[2];
// whether we need to do strict check
static const bool kStrictCheck = false;
};
/*!
* \brief Stream to write to base64 format.
*/
class Base64OutStream : public dmlc::Stream {
public:
explicit Base64OutStream(dmlc::Stream* fp) : fp_(fp) {}
virtual void Write(const void* ptr, size_t size) {
using base64::EncodeTable;
size_t tlen = size;
const unsigned char* cptr = static_cast<const unsigned char*>(ptr);
while (tlen) {
while (buf__top_ < 3 && tlen != 0) {
buf_[++buf__top_] = *cptr++;
--tlen;
}
if (buf__top_ == 3) {
// flush 4 bytes out
PutChar(EncodeTable[buf_[1] >> 2]);
PutChar(EncodeTable[((buf_[1] << 4) | (buf_[2] >> 4)) & 0x3F]);
PutChar(EncodeTable[((buf_[2] << 2) | (buf_[3] >> 6)) & 0x3F]);
PutChar(EncodeTable[buf_[3] & 0x3F]);
buf__top_ = 0;
}
}
}
virtual size_t Read(void* ptr, size_t size) {
LOG(FATAL) << "Base64OutStream do not support read";
return 0;
}
/*!
* \brief finish writing of all current base64 stream, do some post processing
* \param endch character to put to end of stream, if it is EOF, then nothing will be appended.
*/
void Finish(int endch = EOF) {
using base64::EncodeTable;
if (buf__top_ == 1) {
PutChar(EncodeTable[buf_[1] >> 2]);
PutChar(EncodeTable[(buf_[1] << 4) & 0x3F]);
PutChar('=');
PutChar('=');
}
if (buf__top_ == 2) {
PutChar(EncodeTable[buf_[1] >> 2]);
PutChar(EncodeTable[((buf_[1] << 4) | (buf_[2] >> 4)) & 0x3F]);
PutChar(EncodeTable[(buf_[2] << 2) & 0x3F]);
PutChar('=');
}
buf__top_ = 0;
if (endch != EOF) PutChar(endch);
this->Flush();
}
private:
static constexpr size_t kBufferSize = 256;
dmlc::Stream* fp_{nullptr};
int buf__top_{0};
unsigned char buf_[4];
std::string out_buf_;
void PutChar(char ch) {
out_buf_ += ch;
if (out_buf_.length() >= kBufferSize) Flush();
}
void Flush(void) {
if (out_buf_.length() != 0) {
fp_->Write(&out_buf_[0], out_buf_.length());
out_buf_.clear();
}
}
};
} // namespace support
} // namespace tvm
#endif // TVM_SUPPORT_BASE64_H_
| https://github.com/zk-ml/tachikoma |
src/support/generic_arena.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
*
* \file arena.h
* \brief Arena allocator that allocates memory chunks and frees them all during destruction time.
*
* NOTE: This file is portable to bare-metal embedded devices. Don't use operator new (without
* placement parameters) or malloc.
*/
#ifndef TVM_SUPPORT_GENERIC_ARENA_H_
#define TVM_SUPPORT_GENERIC_ARENA_H_
#ifndef TVM_ARENA_HAS_DESTRUCTOR
#define TVM_ARENA_HAS_DESTRUCTOR 1
#endif
#include <stddef.h>
#include <utility>
namespace tvm {
namespace support {
namespace {
template <typename T> // For lvalues (T is T&),
T&& forward(T&& param) { // take/return lvalue refs.
return static_cast<T&&>(param); // For rvalues (T is T),
} // take/return rvalue refs.
} // namespace
/*!
* \brief An arena page header.
*/
struct ArenaPageHeader {
/*! \brief points to the next page. */
ArenaPageHeader* next;
/*!
* \brief Total size of the page.
*/
size_t size;
/*! \brief memory allocator offset inside page. */
size_t offset;
};
/*!
* \brief Arena allocator that allocates memory from continuous
* chunk and frees them all only during destruction.
*/
template <typename PageAllocator>
class GenericArena {
public:
explicit GenericArena(PageAllocator alloc = PageAllocator()) : alloc_(alloc) {
// eagerly allocate the first page.
head_ = tail_ = alloc_.allocate(1);
head_->next = nullptr;
}
#if TVM_ARENA_HAS_DESTRUCTOR
~GenericArena() { this->FreeAll(); }
#endif
/*! \brief Free all pages. */
void FreeAll() {
FreePageList(&head_);
FreePageList(&free_list_);
}
/*! \brief Recycle all the pages in the arena */
void RecycleAll() {
// put all the current list to the free list.
tail_->next = free_list_;
// allocate the first in the free list to head
free_list_ = head_->next;
head_->next = nullptr;
// Reset the head.
head_->offset = sizeof(ArenaPageHeader);
tail_ = head_;
}
/*!
* \brief Allocate a space from Arena for type T
* \param T the data type to be allocated
* \param count Numberof elements
* \note The space of T is not initialized.
*/
template <typename T>
T* allocate_(int count = 1) {
static_assert(PageAllocator::kPageAlign % alignof(T) == 0, "To large alignment");
return static_cast<T*>(Alloc(sizeof(T) * count, alignof(T)));
}
/*!
* \brief Create a new instance of type T.
* \param args The constructor argument.
* \tparam T the type to be created.
* \tparam Args Arguments to the constructor.
*
* \return The allocated object.
* \note The type T must be simple type, or only contain
* memory allocated from the same arena.
* Otherwise the destructor needs to be called explicitly.
*/
template <typename T, typename... Args>
T* make(Args&&... args) {
T* ptr = allocate_<T>();
new (ptr) T(forward<Args>(args)...);
return ptr;
}
private:
/*! \brief internal page allocator. */
PageAllocator alloc_;
/* \brief The head of the allocated list. */
ArenaPageHeader* head_{nullptr};
/*! \brief The tail of the allocated list. */
ArenaPageHeader* tail_{nullptr};
/* \brief List of free pages. */
ArenaPageHeader* free_list_{nullptr};
/*!
* \brief Align ptr by upper bound.
* \param offset The offset value.
* \param align The alignment requirement.
*/
size_t UpperAlign(size_t offset, size_t align) {
return offset + (align - (offset % align)) % align;
}
/*!
* \brief Internal aligned alloc function.
* \param size The size of the memory.
* \param align The alignment requirement.
*/
void* Alloc(size_t size, size_t align) {
size_t offset = UpperAlign(head_->offset, align);
if (offset + size <= head_->size) {
head_->offset = offset + size;
return reinterpret_cast<char*>(head_) + offset;
} else {
ArenaPageHeader* new_head;
offset = UpperAlign(sizeof(ArenaPageHeader), align);
if (free_list_ != nullptr && offset + size <= free_list_->size) {
new_head = free_list_;
free_list_ = free_list_->next;
} else {
new_head = alloc_.allocate(offset + size);
}
new_head->next = head_;
new_head->offset = offset + size;
head_ = new_head;
return reinterpret_cast<char*>(head_) + offset;
}
}
/*!
* \brief Free all the pages in the list.
* \param ptr The head ptr.
*/
void FreePageList(ArenaPageHeader** ptr) {
// delete all the allocated pages.
while (ptr[0] != nullptr) {
ArenaPageHeader* temp = ptr[0];
ptr[0] = ptr[0]->next;
alloc_.deallocate(temp);
}
}
};
} // namespace support
} // namespace tvm
#endif // TVM_SUPPORT_GENERIC_ARENA_H_
| https://github.com/zk-ml/tachikoma |
src/support/hexdump.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
*
* \file support/hexdump.h
* \brief Print hex representation of BLOBs.
*/
#ifndef TVM_SUPPORT_HEXDUMP_H_
#define TVM_SUPPORT_HEXDUMP_H_
#include <iomanip>
#include <sstream>
#include <string>
namespace tvm {
namespace support {
/*! \brief generate a hexdump of some binary data.
* \param s Binary data to print.
* \param os stream that receives the hexdump.
*/
void HexDump(const std::string& s, std::ostream& os);
/*! \brief return a string containing a hexdump of the data in s */
inline std::string HexDump(const std::string& s) {
std::stringstream ss;
HexDump(s, ss);
return ss.str();
}
} // namespace support
} // namespace tvm
#endif // TVM_SUPPORT_HEXDUMP_H_
| https://github.com/zk-ml/tachikoma |
src/support/nd_int_set.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#ifndef TVM_SUPPORT_ND_INT_SET_H_
#define TVM_SUPPORT_ND_INT_SET_H_
#include <tvm/arith/int_set.h>
#include <tvm/ir/expr.h>
#include <unordered_map>
#include <vector>
namespace tvm {
namespace support {
/*! \brief An N-dimensional integer set representing a rectangle region */
using NDIntSet = std::vector<arith::IntSet>;
/*!
* \brief Construct an N-dimensional integer set representing a region.
* \param region The region.
* \return The constructed set.
*/
inline NDIntSet NDIntSetFromRegion(const tir::Region& region) {
NDIntSet result;
result.reserve(region.size());
for (const Range& range : region) {
result.push_back(arith::IntSet::FromRange(range));
}
return result;
}
/*!
* \brief Construct an N-dimensional integer set representing a shape.
* \param shape The shape which is an array of the length of each dimension.
* \return The constructed set.
*/
inline NDIntSet NDIntSetFromShape(const Array<PrimExpr>& shape) {
PrimExpr zero = Integer(0);
NDIntSet result;
result.reserve(shape.size());
for (const PrimExpr& extent : shape) {
result.push_back(arith::IntSet::FromMinExtent(zero, extent));
}
return result;
}
/*!
* \brief Construct an N-dimensional integer set representing a point.
* \param indices The N-dimensional indices representing the point.
* \return The constructed set.
*/
inline NDIntSet NDIntSetFromPoint(const Array<PrimExpr>& indices) {
NDIntSet result;
result.reserve(indices.size());
for (const PrimExpr& index : indices) {
result.push_back(arith::IntSet::SinglePoint(index));
}
return result;
}
/*!
* \brief Create a union set of two sets, possibly relaxed. The RHS set will be combined into the
* LHS set.
* \param lhs The first N-dimensional integer set
* \param rhs The second N-dimensional integer set
*/
inline void NDIntSetUnionWith(NDIntSet* lhs, const NDIntSet& rhs) {
ICHECK_EQ(lhs->size(), rhs.size());
int ndim = rhs.size();
for (int i = 0; i < ndim; ++i) {
arith::IntSet& int_set = lhs->at(i);
int_set = arith::Union({int_set, rhs.at(i)});
}
}
/*!
* \brief Union a list of N-dimensional integer sets
* \param nd_int_sets The N-dimensional integer sets to be merged.
* \return The result of the union
*/
inline NDIntSet NDIntSetUnion(const std::vector<NDIntSet>& nd_int_sets) {
ICHECK(!nd_int_sets.empty());
int n = nd_int_sets.size();
if (n == 1) {
return nd_int_sets[0];
}
int ndim = nd_int_sets[0].size();
for (int i = 1; i < n; ++i) {
ICHECK_EQ(nd_int_sets[i].size(), ndim);
}
NDIntSet result;
result.reserve(ndim);
Array<arith::IntSet> int_sets(n, arith::IntSet{nullptr});
for (int dim = 0; dim < ndim; ++dim) {
for (int i = 0; i < n; ++i) {
int_sets.Set(i, nd_int_sets[i][dim]);
}
result.push_back(arith::Union(int_sets));
}
return result;
}
/*!
* \brief Create an empty N-dimensional integer set.
* \param ndim The number of dimensions.
* \return The constructed set.
*/
inline NDIntSet NDIntSetEmpty(int ndim) {
return std::vector<arith::IntSet>(ndim, arith::IntSet::Nothing());
}
/*!
* \brief The N-dimensional version of EvalSet.
* \param nd_int_set The N-dimensional integer set to be evaluated.
* \param dom_map The domain of each variable.
* \return An N-dimensional integer set that can cover all the possible values of the N-dimensional
* integer set.
* \sa EvalSet
*/
inline NDIntSet NDIntSetEval(
const NDIntSet& nd_int_set,
const std::unordered_map<const tir::VarNode*, arith::IntSet>& dom_map) {
NDIntSet ret;
ret.reserve(nd_int_set.size());
for (const arith::IntSet& s : nd_int_set) {
ret.push_back(EvalSet(s, dom_map));
}
return ret;
}
} // namespace support
} // namespace tvm
#endif // TVM_SUPPORT_ND_INT_SET_H_
| https://github.com/zk-ml/tachikoma |
src/support/pipe.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* \file pipe.h
* \brief Platform independent pipe, used for IPC.
*/
#ifndef TVM_SUPPORT_PIPE_H_
#define TVM_SUPPORT_PIPE_H_
#include <dmlc/io.h>
#include <tvm/runtime/logging.h>
#ifdef _WIN32
#include <windows.h>
#else
#include <errno.h>
#include <unistd.h>
#include <cstdlib>
#include <cstring>
#endif
namespace tvm {
namespace support {
/*! \brief Platform independent pipe */
class Pipe : public dmlc::Stream {
public:
#ifdef _WIN32
using PipeHandle = HANDLE;
#else
using PipeHandle = int;
#endif
/*! \brief Construct a pipe from system handle. */
explicit Pipe(int64_t handle) : handle_(static_cast<PipeHandle>(handle)) {}
/*! \brief destructor */
~Pipe() { Flush(); }
using Stream::Read;
using Stream::Write;
/*!
* \brief reads data from a file descriptor
* \param ptr pointer to a memory buffer
* \param size block size
* \return the size of data read
*/
size_t Read(void* ptr, size_t size) final {
if (size == 0) return 0;
#ifdef _WIN32
DWORD nread;
ICHECK(ReadFile(handle_, static_cast<TCHAR*>(ptr), &nread, nullptr))
<< "Read Error: " << GetLastError();
#else
ssize_t nread;
nread = read(handle_, ptr, size);
ICHECK_GE(nread, 0) << "Write Error: " << strerror(errno);
#endif
return static_cast<size_t>(nread);
}
/*!
* \brief write data to a file descriptor
* \param ptr pointer to a memory buffer
* \param size block size
* \return the size of data read
*/
void Write(const void* ptr, size_t size) final {
if (size == 0) return;
#ifdef _WIN32
DWORD nwrite;
ICHECK(WriteFile(handle_, static_cast<const TCHAR*>(ptr), &nwrite, nullptr) &&
static_cast<size_t>(nwrite) == size)
<< "Write Error: " << GetLastError();
#else
ssize_t nwrite;
nwrite = write(handle_, ptr, size);
ICHECK_EQ(static_cast<size_t>(nwrite), size) << "Write Error: " << strerror(errno);
#endif
}
/*!
* \brief Flush the pipe;
*/
void Flush() {
#ifdef _WIN32
FlushFileBuffers(handle_);
#endif
}
/*! \brief close the pipe */
void Close() {
#ifdef _WIN32
CloseHandle(handle_);
#else
close(handle_);
#endif
}
private:
PipeHandle handle_;
};
} // namespace support
} // namespace tvm
#endif // TVM_SUPPORT_PIPE_H_
| https://github.com/zk-ml/tachikoma |
src/support/ring_buffer.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* \file ring_buffer.h
* \brief this file aims to provide a wrapper of sockets
*/
#ifndef TVM_SUPPORT_RING_BUFFER_H_
#define TVM_SUPPORT_RING_BUFFER_H_
#include <algorithm>
#include <cstring>
#include <vector>
namespace tvm {
namespace support {
/*!
* \brief Ring buffer class for data buffering in IO.
* Enables easy usage for sync and async mode.
*/
class RingBuffer {
public:
/*! \brief Initial capacity of ring buffer. */
static const int kInitCapacity = 4 << 10;
/*! \brief constructor */
RingBuffer() : ring_(kInitCapacity) {}
/*! \return number of bytes available in buffer. */
size_t bytes_available() const { return bytes_available_; }
/*! \return Current capacity of buffer. */
size_t capacity() const { return ring_.size(); }
/*!
* Reserve capacity to be at least n.
* Will only increase capacity if n is bigger than current capacity.
*
* The effect of Reserve only lasts before the next call to Reserve.
* Other functions in the ring buffer can also call into the reserve.
*
* \param n The size of capacity.
*/
void Reserve(size_t n) {
if (ring_.size() < n) {
size_t old_size = ring_.size();
size_t new_size = static_cast<size_t>(n * 1.2);
ring_.resize(new_size);
if (head_ptr_ + bytes_available_ > old_size) {
// copy the ring overflow part into the tail.
size_t ncopy = head_ptr_ + bytes_available_ - old_size;
memcpy(&ring_[0] + old_size, &ring_[0], ncopy);
}
} else if (ring_.size() > n * 8 && ring_.size() > kInitCapacity) {
// shrink too large temporary buffer to
// avoid out of memory on some embedded devices
if (bytes_available_ != 0) {
// move existing bytes to the head.
size_t old_bytes = bytes_available_;
std::vector<char> tmp(old_bytes);
Read(&tmp[0], old_bytes);
memcpy(&ring_[0], &tmp[0], old_bytes);
bytes_available_ = old_bytes;
}
// shrink the ring.
size_t new_size = kInitCapacity;
new_size = std::max(new_size, n);
new_size = std::max(new_size, bytes_available_);
ring_.resize(new_size);
ring_.shrink_to_fit();
head_ptr_ = 0;
}
}
/*!
* \brief Perform a non-blocking read from buffer
* size must be smaller than this->bytes_available()
* \param data the data pointer.
* \param size The number of bytes to read.
*/
void Read(void* data, size_t size) {
ICHECK_GE(bytes_available_, size);
size_t ncopy = std::min(size, ring_.size() - head_ptr_);
memcpy(data, &ring_[0] + head_ptr_, ncopy);
if (ncopy < size) {
memcpy(reinterpret_cast<char*>(data) + ncopy, &ring_[0], size - ncopy);
}
head_ptr_ = (head_ptr_ + size) % ring_.size();
bytes_available_ -= size;
}
/*!
* \brief Read data from buffer with and put them to non-blocking send function.
*
* \param fsend A send function handle to put the data to.
* \param max_nbytes Maximum number of bytes can to read.
* \tparam FSend A non-blocking function with signature size_t (const void* data, size_t size);
*/
template <typename FSend>
size_t ReadWithCallback(FSend fsend, size_t max_nbytes) {
size_t size = std::min(max_nbytes, bytes_available_);
ICHECK_NE(size, 0U);
size_t ncopy = std::min(size, ring_.size() - head_ptr_);
size_t nsend = fsend(&ring_[0] + head_ptr_, ncopy);
bytes_available_ -= nsend;
if (ncopy == nsend && ncopy < size) {
size_t nsend2 = fsend(&ring_[0], size - ncopy);
bytes_available_ -= nsend2;
nsend += nsend2;
}
return nsend;
}
/*!
* \brief Write data into buffer, always ensures all data is written.
* \param data The data pointer
* \param size The size of data to be written.
*/
void Write(const void* data, size_t size) {
this->Reserve(bytes_available_ + size);
size_t tail = head_ptr_ + bytes_available_;
if (tail >= ring_.size()) {
memcpy(&ring_[0] + (tail - ring_.size()), data, size);
} else {
size_t ncopy = std::min(ring_.size() - tail, size);
memcpy(&ring_[0] + tail, data, ncopy);
if (ncopy < size) {
memcpy(&ring_[0], reinterpret_cast<const char*>(data) + ncopy, size - ncopy);
}
}
bytes_available_ += size;
}
/*!
* \brief Written data into the buffer by give it a non-blocking callback function.
*
* \param frecv A receive function handle
* \param max_nbytes Maximum number of bytes can write.
* \tparam FRecv A non-blocking function with signature size_t (void* data, size_t size);
*/
template <typename FRecv>
size_t WriteWithCallback(FRecv frecv, size_t max_nbytes) {
this->Reserve(bytes_available_ + max_nbytes);
size_t nbytes = max_nbytes;
size_t tail = head_ptr_ + bytes_available_;
if (tail >= ring_.size()) {
size_t nrecv = frecv(&ring_[0] + (tail - ring_.size()), nbytes);
bytes_available_ += nrecv;
return nrecv;
} else {
size_t ncopy = std::min(ring_.size() - tail, nbytes);
size_t nrecv = frecv(&ring_[0] + tail, ncopy);
bytes_available_ += nrecv;
if (nrecv == ncopy && ncopy < nbytes) {
size_t nrecv2 = frecv(&ring_[0], nbytes - ncopy);
bytes_available_ += nrecv2;
nrecv += nrecv2;
}
return nrecv;
}
}
private:
// buffer head
size_t head_ptr_{0};
// number of bytes occupied in the buffer.
size_t bytes_available_{0};
// The internal data ring.
std::vector<char> ring_;
};
} // namespace support
} // namespace tvm
#endif // TVM_SUPPORT_RING_BUFFER_H_
| https://github.com/zk-ml/tachikoma |
src/support/scalars.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* \file src/support/scalars.h
* \brief Helpers for converting between scalars in native, text, TIR immediate and NDArray forms.
*/
#ifndef TVM_SUPPORT_SCALARS_H_
#define TVM_SUPPORT_SCALARS_H_
#include <string>
#include <utility>
#include "tvm/ir/expr.h"
#include "tvm/relay/expr.h"
#include "tvm/runtime/ndarray.h"
namespace tvm {
namespace support {
/*! \brief Returns true if a tensor of empty shape and given dtype is considered a Relay scalar. */
bool IsSimpleScalarDtype(DataType dtype);
/*! \brief Returns true if \p constant_node is a float/int/bool scalar. */
bool IsSimpleScalar(const relay::ConstantNode* constant_node);
/*! \brief Returns NDArray 'scalar' for given TIR immediate. */
runtime::NDArray IntImmToNDArray(const IntImm& int_imm);
runtime::NDArray FloatImmToNDArray(const FloatImm& float_imm);
runtime::NDArray BoolToNDArray(bool value);
/*! \brief Returns Relay literal text for NDArray 'scalar'. */
std::string NDArrayScalarToString(const runtime::NDArray& data);
/*! \brief Returns Relay literal text for given TIR immediate. */
std::string IntImmToString(const IntImm& int_imm);
std::string FloatImmToString(const FloatImm& float_imm);
/*!
* \brief Returns TIR immediate for given value and width. Result will be null if value is
* out of range in width. Note however for floating point we don't check if the value is
* representable without loss of precision.
*/
IntImm ValueToIntImm(int64_t value, int width);
FloatImm ValueToFloatImm(double value, int width);
// 2^15 * (1 + 1023/1024)
// See https://en.wikipedia.org/wiki/Half-precision_floating-point_format
constexpr double kMaxFloat16 = 65504.0;
} // namespace support
} // namespace tvm
#endif // TVM_SUPPORT_SCALARS_H_
| https://github.com/zk-ml/tachikoma |
src/support/socket.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* \file socket.h
* \brief this file aims to provide a wrapper of sockets
* \author Tianqi Chen
*/
#ifndef TVM_SUPPORT_SOCKET_H_
#define TVM_SUPPORT_SOCKET_H_
#if defined(_WIN32)
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <winsock2.h>
#include <ws2tcpip.h>
#ifdef _MSC_VER
#pragma comment(lib, "Ws2_32.lib")
#endif
#else
#include <arpa/inet.h>
#include <errno.h>
#include <fcntl.h>
#include <netdb.h>
#include <netinet/in.h>
#include <sys/ioctl.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <unistd.h>
#endif
#include <tvm/runtime/logging.h>
#include <tvm/runtime/registry.h>
#include <cstring>
#include <string>
#include <unordered_map>
#include <vector>
#include "../support/ssize.h"
#include "../support/utils.h"
#if defined(_WIN32)
static inline int poll(struct pollfd* pfd, int nfds, int timeout) {
return WSAPoll(pfd, nfds, timeout);
}
#else
#include <sys/poll.h>
#endif // defined(_WIN32)
namespace tvm {
namespace support {
/*!
* \brief Get current host name.
* \return The hostname.
*/
inline std::string GetHostName() {
std::string buf;
buf.resize(256);
ICHECK_NE(gethostname(&buf[0], 256), -1);
return std::string(buf.c_str());
}
/*!
* \brief ValidateIP validates an ip address.
* \param ip The ip address in string format localhost or x.x.x.x format
* \return result of operation.
*/
inline bool ValidateIP(std::string ip) {
if (ip == "localhost") {
return true;
}
struct sockaddr_in sa_ipv4;
struct sockaddr_in6 sa_ipv6;
bool is_ipv4 = inet_pton(AF_INET, ip.c_str(), &(sa_ipv4.sin_addr));
bool is_ipv6 = inet_pton(AF_INET6, ip.c_str(), &(sa_ipv6.sin6_addr));
return is_ipv4 || is_ipv6;
}
/*!
* \brief Common data structure for network address.
*/
struct SockAddr {
sockaddr_storage addr;
SockAddr() {}
/*!
* \brief construct address by url and port
* \param url The url of the address
* \param port The port of the address.
*/
SockAddr(const char* url, int port) { this->Set(url, port); }
/*!
* \brief SockAddr Get the socket address from tracker.
* \param tracker The url containing the ip and port number. Format is ('192.169.1.100', 9090)
* \return SockAddr parsed from url.
*/
explicit SockAddr(const std::string& url) {
size_t sep = url.find(",");
std::string host = url.substr(2, sep - 3);
std::string port = url.substr(sep + 1, url.length() - 1);
ICHECK(ValidateIP(host)) << "Url address is not valid " << url;
if (host == "localhost") {
host = "127.0.0.1";
}
this->Set(host.c_str(), std::stoi(port));
}
/*!
* \brief set the address
* \param host the url of the address
* \param port the port of address
*/
void Set(const char* host, int port) {
addrinfo hints;
memset(&hints, 0, sizeof(hints));
hints.ai_family = PF_UNSPEC;
hints.ai_flags = AI_PASSIVE;
hints.ai_socktype = SOCK_STREAM;
addrinfo* res = nullptr;
int sig = getaddrinfo(host, nullptr, &hints, &res);
ICHECK(sig == 0 && res != nullptr) << "cannot obtain address of " << host;
switch (res->ai_family) {
case AF_INET: {
sockaddr_in* addr4 = reinterpret_cast<sockaddr_in*>(&addr);
memcpy(addr4, res->ai_addr, res->ai_addrlen);
addr4->sin_port = htons(port);
addr4->sin_family = AF_INET;
} break;
case AF_INET6: {
sockaddr_in6* addr6 = reinterpret_cast<sockaddr_in6*>(&addr);
memcpy(addr6, res->ai_addr, res->ai_addrlen);
addr6->sin6_port = htons(port);
addr6->sin6_family = AF_INET6;
} break;
default:
ICHECK(false) << "cannot decode address";
}
freeaddrinfo(res);
}
/*! \brief return port of the address */
int port() const {
return ntohs((addr.ss_family == AF_INET6)
? reinterpret_cast<const sockaddr_in6*>(&addr)->sin6_port
: reinterpret_cast<const sockaddr_in*>(&addr)->sin_port);
}
/*! \brief return the ip address family */
int ss_family() const { return addr.ss_family; }
/*! \return a string representation of the address */
std::string AsString() const {
std::string buf;
buf.resize(256);
const void* sinx_addr = nullptr;
if (addr.ss_family == AF_INET6) {
const in6_addr& addr6 = reinterpret_cast<const sockaddr_in6*>(&addr)->sin6_addr;
sinx_addr = reinterpret_cast<const void*>(&addr6);
} else if (addr.ss_family == AF_INET) {
const in_addr& addr4 = reinterpret_cast<const sockaddr_in*>(&addr)->sin_addr;
sinx_addr = reinterpret_cast<const void*>(&addr4);
} else {
ICHECK(false) << "illegal address";
}
#ifdef _WIN32
const char* s = inet_ntop(addr.ss_family, (PVOID)sinx_addr, // NOLINT(*)
&buf[0], buf.length());
#else
const char* s =
inet_ntop(addr.ss_family, sinx_addr, &buf[0], static_cast<socklen_t>(buf.length()));
#endif
ICHECK(s != nullptr) << "cannot decode address";
std::ostringstream os;
os << s << ":" << port();
return os.str();
}
};
/*!
* \brief base class containing common operations of TCP and UDP sockets
*/
class Socket {
public:
#if defined(_WIN32)
using sock_size_t = int;
using SockType = SOCKET;
#else
using SockType = int;
using sock_size_t = size_t;
static constexpr int INVALID_SOCKET = -1;
#endif
/*! \brief the file descriptor of socket */
SockType sockfd;
/*!
* \brief set this socket to use non-blocking mode
* \param non_block whether set it to be non-block, if it is false
* it will set it back to block mode
*/
void SetNonBlock(bool non_block) {
#ifdef _WIN32
u_long mode = non_block ? 1 : 0;
if (ioctlsocket(sockfd, FIONBIO, &mode) != NO_ERROR) {
Socket::Error("SetNonBlock");
}
#else
int flag = fcntl(sockfd, F_GETFL, 0);
if (flag == -1) {
Socket::Error("SetNonBlock-1");
}
if (non_block) {
flag |= O_NONBLOCK;
} else {
flag &= ~O_NONBLOCK;
}
if (fcntl(sockfd, F_SETFL, flag) == -1) {
Socket::Error("SetNonBlock-2");
}
#endif
}
/*!
* \brief bind the socket to an address
* \param addr The address to be binded
*/
void Bind(const SockAddr& addr) {
if (bind(sockfd, reinterpret_cast<const sockaddr*>(&addr.addr),
(addr.addr.ss_family == AF_INET6 ? sizeof(sockaddr_in6) : sizeof(sockaddr_in))) ==
-1) {
Socket::Error("Bind");
}
}
/*!
* \brief try bind the socket to host, from start_port to end_port
* \param host host address to bind the socket
* \param start_port starting port number to try
* \param end_port ending port number to try
* \return the port successfully bind to, return -1 if failed to bind any port
*/
inline int TryBindHost(std::string host, int start_port, int end_port) {
for (int port = start_port; port < end_port; ++port) {
SockAddr addr(host.c_str(), port);
if (bind(sockfd, reinterpret_cast<sockaddr*>(&addr.addr),
(addr.addr.ss_family == AF_INET6 ? sizeof(sockaddr_in6) : sizeof(sockaddr_in))) ==
0) {
return port;
} else {
LOG(WARNING) << "Bind failed to " << host << ":" << port;
}
#if defined(_WIN32)
if (WSAGetLastError() != WSAEADDRINUSE) {
Socket::Error("TryBindHost");
}
#else
if (errno != EADDRINUSE) {
Socket::Error("TryBindHost");
}
#endif
}
return -1;
}
/*! \brief get last error code if any */
int GetSockError() const {
int error = 0;
socklen_t len = sizeof(error);
if (getsockopt(sockfd, SOL_SOCKET, SO_ERROR, reinterpret_cast<char*>(&error), &len) != 0) {
Error("GetSockError");
}
return error;
}
/*! \brief check if anything bad happens */
bool BadSocket() const {
if (IsClosed()) return true;
int err = GetSockError();
if (err == EBADF || err == EINTR) return true;
return false;
}
/*! \brief check if socket is already closed */
bool IsClosed() const { return sockfd == INVALID_SOCKET; }
/*! \brief close the socket */
void Close() {
if (sockfd != INVALID_SOCKET) {
#ifdef _WIN32
closesocket(sockfd);
#else
close(sockfd);
#endif
sockfd = INVALID_SOCKET;
} else {
Error("Socket::Close double close the socket or close without create");
}
}
/*!
* \return last error of socket operation
*/
static int GetLastError() {
#ifdef _WIN32
return WSAGetLastError();
#else
return errno;
#endif
}
/*! \return whether last error was would block */
static bool LastErrorWouldBlock() {
int errsv = GetLastError();
#ifdef _WIN32
return errsv == WSAEWOULDBLOCK;
#else
return errsv == EAGAIN || errsv == EWOULDBLOCK;
#endif
}
/*!
* \brief start up the socket module
* call this before using the sockets
*/
static void Startup() {
#ifdef _WIN32
WSADATA wsa_data;
if (WSAStartup(MAKEWORD(2, 2), &wsa_data) == -1) {
Socket::Error("Startup");
}
if (LOBYTE(wsa_data.wVersion) != 2 || HIBYTE(wsa_data.wVersion) != 2) {
WSACleanup();
LOG(FATAL) << "Could not find a usable version of Winsock.dll";
}
#endif
}
/*!
* \brief shutdown the socket module after use, all sockets need to be closed
*/
static void Finalize() {
#ifdef _WIN32
WSACleanup();
#endif
}
/*!
* \brief Report an socket error.
* \param msg The error message.
*/
static void Error(const char* msg) {
int errsv = GetLastError();
#ifdef _WIN32
LOG(FATAL) << "Socket " << msg << " Error:WSAError-code=" << errsv;
#else
LOG(FATAL) << "Socket " << msg << " Error:" << strerror(errsv);
#endif
}
/*!
* \brief Call a function and retry if an EINTR error is encountered.
*
* Socket operations can return EINTR when the interrupt handler
* is registered by the execution environment(e.g. python).
* We should retry if there is no KeyboardInterrupt recorded in
* the environment.
*
* \note This function is needed to avoid rare interrupt event
* in long running server code.
*
* \param func The function to retry.
* \return The return code returned by function f or error_value on retry failure.
*/
template <typename FuncType>
ssize_t RetryCallOnEINTR(FuncType func) {
ssize_t ret = func();
// common path
if (ret != -1) return ret;
// less common path
do {
if (GetLastError() == EINTR) {
// Call into env check signals to see if there are
// environment specific(e.g. python) signal exceptions.
// This function will throw an exception if there is
// if the process received a signal that requires TVM to return immediately (e.g. SIGINT).
runtime::EnvCheckSignals();
} else {
// other errors
return ret;
}
ret = func();
} while (ret == -1);
return ret;
}
protected:
explicit Socket(SockType sockfd) : sockfd(sockfd) {}
};
/*!
* \brief a wrapper of TCP socket that hopefully be cross platform
*/
class TCPSocket : public Socket {
public:
TCPSocket() : Socket(INVALID_SOCKET) {}
/*!
* \brief construct a TCP socket from existing descriptor
* \param sockfd The descriptor
*/
explicit TCPSocket(SockType sockfd) : Socket(sockfd) {}
/*!
* \brief enable/disable TCP keepalive
* \param keepalive whether to set the keep alive option on
*/
void SetKeepAlive(bool keepalive) {
int opt = static_cast<int>(keepalive);
if (setsockopt(sockfd, SOL_SOCKET, SO_KEEPALIVE, reinterpret_cast<char*>(&opt), sizeof(opt)) <
0) {
Socket::Error("SetKeepAlive");
}
}
/*!
* \brief create the socket, call this before using socket
* \param af domain
*/
void Create(int af = PF_INET) {
sockfd = socket(af, SOCK_STREAM, 0);
if (sockfd == INVALID_SOCKET) {
Socket::Error("Create");
}
}
/*!
* \brief perform listen of the socket
* \param backlog backlog parameter
*/
void Listen(int backlog = 16) { listen(sockfd, backlog); }
/*!
* \brief get a new connection
* \return The accepted socket connection.
*/
TCPSocket Accept() {
SockType newfd = RetryCallOnEINTR([&]() { return accept(sockfd, nullptr, nullptr); });
if (newfd == INVALID_SOCKET) {
Socket::Error("Accept");
}
return TCPSocket(newfd);
}
/*!
* \brief get a new connection
* \param addr client address from which connection accepted
* \return The accepted socket connection.
*/
TCPSocket Accept(SockAddr* addr) {
socklen_t addrlen = sizeof(addr->addr);
SockType newfd = RetryCallOnEINTR(
[&]() { return accept(sockfd, reinterpret_cast<sockaddr*>(&addr->addr), &addrlen); });
if (newfd == INVALID_SOCKET) {
Socket::Error("Accept");
}
return TCPSocket(newfd);
}
/*!
* \brief decide whether the socket is at OOB mark
* \return 1 if at mark, 0 if not, -1 if an error occurred
*/
int AtMark() const {
#ifdef _WIN32
unsigned long atmark; // NOLINT(*)
if (ioctlsocket(sockfd, SIOCATMARK, &atmark) != NO_ERROR) return -1;
#else
int atmark;
if (ioctl(sockfd, SIOCATMARK, &atmark) == -1) return -1;
#endif
return static_cast<int>(atmark);
}
/*!
* \brief connect to an address
* \param addr the address to connect to
* \return whether connect is successful
*/
bool Connect(const SockAddr& addr) {
return connect(
sockfd, reinterpret_cast<const sockaddr*>(&addr.addr),
(addr.addr.ss_family == AF_INET6 ? sizeof(sockaddr_in6) : sizeof(sockaddr_in))) == 0;
}
/*!
* \brief send data using the socket
* \param buf_ the pointer to the buffer
* \param len the size of the buffer
* \param flag extra flags
* \return size of data actually sent
* return -1 if error occurs
*/
ssize_t Send(const void* buf_, size_t len, int flag = 0) {
const char* buf = reinterpret_cast<const char*>(buf_);
return RetryCallOnEINTR(
[&]() { return send(sockfd, buf, static_cast<sock_size_t>(len), flag); });
}
/*!
* \brief receive data using the socket
* \param buf_ the pointer to the buffer
* \param len the size of the buffer
* \param flags extra flags
* \return size of data actually received
* return -1 if error occurs
*/
ssize_t Recv(void* buf_, size_t len, int flags = 0) {
char* buf = reinterpret_cast<char*>(buf_);
return RetryCallOnEINTR(
[&]() { return recv(sockfd, buf, static_cast<sock_size_t>(len), flags); });
}
/*!
* \brief perform block write that will attempt to send all data out
* can still return smaller than request when error occurs
* \param buf_ the pointer to the buffer
* \param len the size of the buffer
* \return size of data actually sent
*/
size_t SendAll(const void* buf_, size_t len) {
const char* buf = reinterpret_cast<const char*>(buf_);
size_t ndone = 0;
while (ndone < len) {
ssize_t ret = RetryCallOnEINTR(
[&]() { return send(sockfd, buf, static_cast<ssize_t>(len - ndone), 0); });
if (ret == -1) {
if (LastErrorWouldBlock()) return ndone;
Socket::Error("SendAll");
}
buf += ret;
ndone += ret;
}
return ndone;
}
/*!
* \brief perform block read that will attempt to read all data
* can still return smaller than request when error occurs
* \param buf_ the buffer pointer
* \param len length of data to recv
* \return size of data actually sent
*/
size_t RecvAll(void* buf_, size_t len) {
char* buf = reinterpret_cast<char*>(buf_);
size_t ndone = 0;
while (ndone < len) {
ssize_t ret = RetryCallOnEINTR(
[&]() { return recv(sockfd, buf, static_cast<sock_size_t>(len - ndone), MSG_WAITALL); });
if (ret == -1) {
if (LastErrorWouldBlock()) {
LOG(FATAL) << "would block";
return ndone;
}
Socket::Error("RecvAll");
}
if (ret == 0) return ndone;
buf += ret;
ndone += ret;
}
return ndone;
}
/*!
* \brief Send the data to remote.
* \param data The data to be sent.
*/
void SendBytes(std::string data) {
int datalen = data.length();
ICHECK_EQ(SendAll(&datalen, sizeof(datalen)), sizeof(datalen));
ICHECK_EQ(SendAll(data.c_str(), datalen), datalen);
}
/*!
* \brief Receive the data to remote.
* \return The data received.
*/
std::string RecvBytes() {
int datalen = 0;
ICHECK_EQ(RecvAll(&datalen, sizeof(datalen)), sizeof(datalen));
std::string data;
data.resize(datalen);
ICHECK_EQ(RecvAll(&data[0], datalen), datalen);
return data;
}
};
/*! \brief helper data structure to perform poll */
struct PollHelper {
public:
/*!
* \brief add file descriptor to watch for read
* \param fd file descriptor to be watched
*/
inline void WatchRead(TCPSocket::SockType fd) {
auto& pfd = fds[fd];
pfd.fd = fd;
pfd.events |= POLLIN;
}
/*!
* \brief add file descriptor to watch for write
* \param fd file descriptor to be watched
*/
inline void WatchWrite(TCPSocket::SockType fd) {
auto& pfd = fds[fd];
pfd.fd = fd;
pfd.events |= POLLOUT;
}
/*!
* \brief add file descriptor to watch for exception
* \param fd file descriptor to be watched
*/
inline void WatchException(TCPSocket::SockType fd) {
auto& pfd = fds[fd];
pfd.fd = fd;
pfd.events |= POLLPRI;
}
/*!
* \brief Check if the descriptor is ready for read
* \param fd file descriptor to check status
*/
inline bool CheckRead(TCPSocket::SockType fd) const {
const auto& pfd = fds.find(fd);
return pfd != fds.end() && ((pfd->second.events & POLLIN) != 0);
}
/*!
* \brief Check if the descriptor is ready for write
* \param fd file descriptor to check status
*/
inline bool CheckWrite(TCPSocket::SockType fd) const {
const auto& pfd = fds.find(fd);
return pfd != fds.end() && ((pfd->second.events & POLLOUT) != 0);
}
/*!
* \brief Check if the descriptor has any exception
* \param fd file descriptor to check status
*/
inline bool CheckExcept(TCPSocket::SockType fd) const {
const auto& pfd = fds.find(fd);
return pfd != fds.end() && ((pfd->second.events & POLLPRI) != 0);
}
/*!
* \brief wait for exception event on a single descriptor
* \param fd the file descriptor to wait the event for
* \param timeout the timeout counter, can be negative, which means wait until the event happen
* \return 1 if success, 0 if timeout, and -1 if error occurs
*/
inline static int WaitExcept(TCPSocket::SockType fd, long timeout = -1) { // NOLINT(*)
pollfd pfd;
pfd.fd = fd;
pfd.events = POLLPRI;
return poll(&pfd, 1, timeout);
}
/*!
* \brief perform poll on the set defined, read, write, exception
* \param timeout specify timeout in milliseconds(ms) if negative, means poll will block
* \return
*/
inline void Poll(long timeout = -1) { // NOLINT(*)
std::vector<pollfd> fdset;
fdset.reserve(fds.size());
for (auto kv : fds) {
fdset.push_back(kv.second);
}
int ret = poll(fdset.data(), fdset.size(), timeout);
if (ret == -1) {
Socket::Error("Poll");
} else {
for (auto& pfd : fdset) {
auto revents = pfd.revents & pfd.events;
if (!revents) {
fds.erase(pfd.fd);
} else {
fds[pfd.fd].events = revents;
}
}
}
}
std::unordered_map<TCPSocket::SockType, pollfd> fds;
};
} // namespace support
} // namespace tvm
#endif // TVM_SUPPORT_SOCKET_H_
| https://github.com/zk-ml/tachikoma |
src/support/ssize.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* \file ssize.h
* \brief this file aims to define ssize_t for Windows platform
*/
#ifndef TVM_SUPPORT_SSIZE_H_
#define TVM_SUPPORT_SSIZE_H_
#if defined(_MSC_VER)
#if defined(_WIN32)
using ssize_t = int32_t;
#else
using ssize_t = int64_t;
#endif
#endif
#endif // TVM_SUPPORT_SSIZE_H_
| https://github.com/zk-ml/tachikoma |
src/support/str_escape.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
*
* \file support/str_escape.h
* \brief Print escape sequence of a string.
*/
#ifndef TVM_SUPPORT_STR_ESCAPE_H_
#define TVM_SUPPORT_STR_ESCAPE_H_
#include <sstream>
#include <string>
namespace tvm {
namespace support {
/*!
* \brief Create a stream with escape.
* \param data The data
* \param size The size of the string.
* \param use_octal_escape True to use octal escapes instead of hex. If producing C
* strings, use octal escapes to avoid ambiguously-long hex escapes.
* \return the Result string.
*/
inline std::string StrEscape(const char* data, size_t size, bool use_octal_escape = false) {
std::ostringstream stream;
for (size_t i = 0; i < size; ++i) {
unsigned char c = data[i];
if (c >= ' ' && c <= '~' && c != '\\' && c != '"') {
stream << c;
} else {
stream << '\\';
switch (c) {
case '"':
stream << '"';
break;
case '\\':
stream << '\\';
break;
case '\t':
stream << 't';
break;
case '\r':
stream << 'r';
break;
case '\n':
stream << 'n';
break;
default:
if (use_octal_escape) {
stream << static_cast<unsigned char>('0' + ((c >> 6) & 0x03))
<< static_cast<unsigned char>('0' + ((c >> 3) & 0x07))
<< static_cast<unsigned char>('0' + (c & 0x07));
} else {
const char* hex_digits = "0123456789ABCDEF";
stream << 'x' << hex_digits[c >> 4] << hex_digits[c & 0xf];
}
}
}
}
return stream.str();
}
/*!
* \brief Create a stream with escape.
* \param data The data
* \param size The size of the string.
* \return the Result string.
*/
inline std::string StrEscape(const std::string& val) { return StrEscape(val.data(), val.length()); }
} // namespace support
} // namespace tvm
#endif // TVM_SUPPORT_STR_ESCAPE_H_
| https://github.com/zk-ml/tachikoma |
src/support/table_printer.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#ifndef TVM_SUPPORT_TABLE_PRINTER_H_
#define TVM_SUPPORT_TABLE_PRINTER_H_
#include <tvm/runtime/logging.h>
#include <algorithm>
#include <iomanip>
#include <iostream>
#include <numeric>
#include <sstream>
#include <string>
#include <vector>
namespace tvm {
namespace support {
/*!
* \brief TablePrinter is a helper class to print a table.
*
* \code
*
* TablePrinter p;
* p.Row() << "ID"
* << "Latency (ms)"
* << "Speed (GFLOPS)"
* << "Trials";
* p.Separator();
* p.Row() << 0 << 0.072 << 4208.59 << 6656;
* p.Row() << 1 << 0.020 << 3804.24 << 7296;
* p.Row() << 2 << 0.003 << 1368.10 << 320;
* p.Row() << 3 << 0.010 << 117.75 << 128;
* p.Row() << 4 << 0.002 << 23.75 << 320;
* p.Row() << 5 << 0.004 << 1696.18 << 704;
* p.Row() << 6 << 0.002 << 69.89 << 320;
* p.Row() << 7 << 0.047 << 6394.42 << 4352;
* p.Separator();
* std::cout << tab.AsStr();
*
* \endcode
*/
class TablePrinter {
struct Line;
public:
/*! \brief Create a new row */
inline Line Row();
/*! \brief Create a row separator */
inline void Separator();
/*! \brief Converts TablePrinter to a string */
inline std::string AsStr() const;
private:
std::vector<std::vector<std::string>> tab_;
friend struct Line;
/*! \brief A helper class to print a specific row in the table */
struct Line {
inline Line& operator<<(int x);
inline Line& operator<<(int64_t x);
inline Line& operator<<(double x);
inline Line& operator<<(const std::string& x);
private:
TablePrinter* p;
friend class TablePrinter;
};
};
inline TablePrinter::Line& TablePrinter::Line::operator<<(int x) {
p->tab_.back().push_back(std::to_string(x));
return *this;
}
inline TablePrinter::Line& TablePrinter::Line::operator<<(int64_t x) {
p->tab_.back().push_back(std::to_string(x));
return *this;
}
inline TablePrinter::Line& TablePrinter::Line::operator<<(double x) {
std::ostringstream os;
os << std::fixed << std::setprecision(4) << x;
p->tab_.back().push_back(os.str());
return *this;
}
inline TablePrinter::Line& TablePrinter::Line::operator<<(const std::string& x) {
p->tab_.back().push_back(x);
return *this;
}
inline TablePrinter::Line TablePrinter::Row() {
tab_.emplace_back();
Line line;
line.p = this;
return line;
}
inline void TablePrinter::Separator() { tab_.emplace_back(); }
inline std::string TablePrinter::AsStr() const {
constexpr char kRowSep = '-';
constexpr char kColSep = '|';
if (tab_.empty()) return "";
std::vector<size_t> column_width;
for (const std::vector<std::string>& row : tab_) {
if (row.size() > column_width.size()) {
column_width.resize(row.size(), 0);
}
for (size_t i = 0; i < row.size(); ++i) {
column_width[i] = std::max(column_width[i], row[i].size());
}
}
ICHECK(!column_width.empty());
size_t total_width =
std::accumulate(column_width.begin(), column_width.end(), 0) + 3 * column_width.size() - 1;
bool is_first = true;
std::ostringstream os;
for (const std::vector<std::string>& row : tab_) {
if (is_first) {
is_first = false;
} else {
os << '\n';
}
if (row.empty()) {
os << std::string(total_width, kRowSep);
continue;
}
for (size_t i = 0; i < column_width.size(); ++i) {
if (i != 0) {
os << kColSep;
}
std::string s = (i < row.size()) ? row[i] : "";
os << std::string(column_width[i] + 1 - s.size(), ' ') << s << ' ';
}
}
return os.str();
}
} // namespace support
} // namespace tvm
#endif // TVM_SUPPORT_TABLE_PRINTER_H_
| https://github.com/zk-ml/tachikoma |
src/support/utils.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* \file utils.h
* \brief Defines some common utility function..
*/
#ifndef TVM_SUPPORT_UTILS_H_
#define TVM_SUPPORT_UTILS_H_
#include <stdio.h>
#ifndef _WIN32
#include <sys/types.h>
#ifndef __hexagon__
#include <sys/wait.h>
#endif // __hexagon__
#endif // _WIN32
#include <tvm/runtime/container/string.h>
#include <algorithm>
#include <array>
#include <cctype>
#include <cstdlib>
#include <memory>
#include <sstream>
#include <string>
#include <vector>
namespace tvm {
namespace support {
/*!
* \brief TVMPOpen wrapper of popen between windows / unix.
* \param command executed command
* \param type "r" is for reading or "w" for writing.
* \return normal standard stream
*/
#ifndef __hexagon__
inline FILE* TVMPOpen(const char* command, const char* type) {
#if defined(_WIN32)
return _popen(command, type);
#else
return popen(command, type);
#endif
}
#endif // __hexagon__
/*!
* \brief TVMPClose wrapper of pclose between windows / linux
* \param stream the stream needed to be close.
* \return exit status
*/
#ifndef __hexagon__
inline int TVMPClose(FILE* stream) {
#if defined(_WIN32)
return _pclose(stream);
#else
return pclose(stream);
#endif
}
#endif // __hexagon__
/*!
* \brief TVMWifexited wrapper of WIFEXITED between windows / linux
* \param status The status field that was filled in by the wait or waitpid function
* \return the exit code of the child process
*/
#ifndef __hexagon__
inline int TVMWifexited(int status) {
#if defined(_WIN32)
return (status != 3);
#else
return WIFEXITED(status);
#endif
}
#endif // __hexagon__
/*!
* \brief TVMWexitstatus wrapper of WEXITSTATUS between windows / linux
* \param status The status field that was filled in by the wait or waitpid function.
* \return the child process exited normally or not
*/
#ifndef __hexagon__
inline int TVMWexitstatus(int status) {
#if defined(_WIN32)
return status;
#else
return WEXITSTATUS(status);
#endif
}
#endif // __hexagon__
/*!
* \brief IsNumber check whether string is a number.
* \param str input string
* \return result of operation.
*/
inline bool IsNumber(const std::string& str) {
return !str.empty() &&
std::find_if(str.begin(), str.end(), [](char c) { return !std::isdigit(c); }) == str.end();
}
/*!
* \brief split Split the string based on delimiter
* \param str Input string
* \param delim The delimiter.
* \return vector of strings which are splitted.
*/
inline std::vector<std::string> Split(const std::string& str, char delim) {
std::string item;
std::istringstream is(str);
std::vector<std::string> ret;
while (std::getline(is, item, delim)) {
ret.push_back(item);
}
return ret;
}
/*!
* \brief Check whether the string starts with a given prefix.
* \param str The given string.
* \param prefix The given prefix.
* \return Whether the prefix matched.
*/
inline bool StartsWith(const String& str, const char* prefix) {
size_t n = str.length();
for (size_t i = 0; i < n; i++) {
if (prefix[i] == '\0') return true;
if (str.data()[i] != prefix[i]) return false;
}
// return true if the str is equal to the prefix
return prefix[n] == '\0';
}
/*!
* \brief EndsWith check whether the strings ends with
* \param value The full string
* \param end The end substring
* \return bool The result.
*/
inline bool EndsWith(std::string const& value, std::string const& end) {
if (end.size() <= value.size()) {
return std::equal(end.rbegin(), end.rend(), value.rbegin());
}
return false;
}
/*!
* \brief Execute the command
* \param cmd The command we want to execute
* \param err_msg The error message if we have
* \return executed output status
*/
#ifndef __hexagon__
inline int Execute(std::string cmd, std::string* err_msg) {
std::array<char, 128> buffer;
std::string result;
cmd += " 2>&1";
FILE* fd = TVMPOpen(cmd.c_str(), "r");
while (fgets(buffer.data(), buffer.size(), fd) != nullptr) {
*err_msg += buffer.data();
}
int status = TVMPClose(fd);
if (TVMWifexited(status)) {
return TVMWexitstatus(status);
}
return 255;
}
#endif // __hexagon__
/*!
* \brief hash an object and combines uint64_t key with previous keys
*
* This hash function is stable across platforms.
*
* \param key The left operand.
* \param value The right operand.
* \return the combined result.
*/
template <typename T, std::enable_if_t<std::is_convertible<T, uint64_t>::value, bool> = true>
inline uint64_t HashCombine(uint64_t key, const T& value) {
// XXX: do not use std::hash in this function. This hash must be stable
// across different platforms and std::hash is implementation dependent.
return key ^ (uint64_t(value) + 0x9e3779b9 + (key << 6) + (key >> 2));
}
/*!
* \brief Return whether a boolean flag is set as an environment variable.
*
* Returns true if the environment variable is set to a non-zero
* integer, or to a non-empty string that is not an integer.
*
* Returns false if the environment variable is unset, if the
* environment variable is set to the integer zero, or if the
* environment variable is an empty string.
*/
inline bool BoolEnvironmentVar(const char* varname) {
const char* var = std::getenv(varname);
if (!var) {
return false;
}
int x = 0;
std::istringstream is(var);
if (is >> x) {
return x;
}
return *var;
}
} // namespace support
} // namespace tvm
#endif // TVM_SUPPORT_UTILS_H_
| https://github.com/zk-ml/tachikoma |
src/target/build_common.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* Common build utilities
* \file build_common.h
*/
#ifndef TVM_TARGET_BUILD_COMMON_H_
#define TVM_TARGET_BUILD_COMMON_H_
#include <tvm/ir/module.h>
#include <tvm/runtime/registry.h>
#include <tvm/target/codegen.h>
#include <tvm/tir/expr.h>
#include <tvm/tir/function.h>
#include <tvm/tir/stmt.h>
#include <string>
#include <unordered_map>
#include "../runtime/meta_data.h"
namespace tvm {
namespace codegen {
inline std::unordered_map<std::string, runtime::FunctionInfo> ExtractFuncInfo(const IRModule& mod) {
std::unordered_map<std::string, runtime::FunctionInfo> fmap;
for (auto kv : mod->functions) {
ICHECK(kv.second->IsInstance<tir::PrimFuncNode>()) << "Can only lower IR Module with PrimFuncs";
auto f = Downcast<tir::PrimFunc>(kv.second);
runtime::FunctionInfo info;
for (size_t i = 0; i < f->params.size(); ++i) {
info.arg_types.push_back(f->params[i].dtype());
}
if (auto opt = f->GetAttr<Array<tir::IterVar>>(tir::attr::kDeviceThreadAxis)) {
auto thread_axis = opt.value();
for (size_t i = 0; i < thread_axis.size(); ++i) {
info.launch_param_tags.push_back(thread_axis[i]->thread_tag);
}
}
if (auto opt = f->GetAttr<Integer>(tir::attr::kDeviceUseDynSharedMemory)) {
if (opt.value().IntValue() != 0) {
info.launch_param_tags.push_back(runtime::launch_param::kUseDynamicSharedMemoryTag);
}
}
auto global_symbol = f->GetAttr<String>(tvm::attr::kGlobalSymbol);
fmap[static_cast<std::string>(global_symbol.value())] = info;
}
return fmap;
}
} // namespace codegen
} // namespace tvm
#endif // TVM_TARGET_BUILD_COMMON_H_
| https://github.com/zk-ml/tachikoma |
src/target/datatype/registry.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#ifndef TVM_TARGET_DATATYPE_REGISTRY_H_
#define TVM_TARGET_DATATYPE_REGISTRY_H_
#include <tvm/runtime/packed_func.h>
#include <tvm/runtime/registry.h>
#include <string>
#include <unordered_map>
namespace tvm {
namespace datatype {
/*!
* \brief Registry for custom datatypes.
*
* Adding custom datatypes currently requires two steps:
* 1. Register the datatype with the registry via a call to
* datatype::Registry::Register. This can also be done in Python
* directly---see the TVM globals registered in the corresponding .cc file.
* Currently, user should manually choose a type name and a type code,
* ensuring that neither conflict with existing types.
* 2. Use TVM_REGISTER_GLOBAL to register the lowering functions needed to
* lower the custom datatype. In general, these will look like:
* For Casts: tvm.datatype.lower.<target>.Cast.<type>.<src_type>
* Example: tvm.datatype.lower.llvm.Cast.myfloat.float for a Cast from
* float to myfloat.
* For intrinsic Calls: tvm.datatype.lower.<target>.Call.intrin.<name>.<type>
* Example: tvm.datatype.lower.llvm.Call.intrin.sqrt.myfloat
* For other ops: tvm.datatype.lower.<target>.<op>.<type>
* Examples: tvm.datatype.lower.llvm.Add.myfloat
* tvm.datatype.lower.llvm.FloatImm.posit
*/
class Registry {
public:
/*!
* \brief Get the global custom datatype registry singleton
*/
static Registry* Global();
/*!
* \brief Register custom datatype
* Register a custom datatype with the given type name and type code. Currently, the type code is
* manually allocated by the user, and the user must ensure that no two custom types share the
* same code. Generally, this should be straightforward, as the user will be manually registering
* all of their custom types.
* \param type_name The name of the type, e.g. "posites2"
* \param type_code The type code, which should be greater than TVMArgTypeCode::kTVMExtEnd
*/
void Register(const std::string& type_name, uint8_t type_code);
/*!
* \brief Get type code from type name
* \param type_name The type name
* \return The type code
*/
uint8_t GetTypeCode(const std::string& type_name);
/*!
* \brief Get type name from type code
* \param type_code The type code
* \return The type name
*/
std::string GetTypeName(uint8_t type_code);
/*!
* \brief Get bool representing whether type is registered, given the type code
* \param type_code The type code
* \return bool representing whether the type is registered
*/
inline bool GetTypeRegistered(uint8_t type_code) {
return code_to_name_.find(type_code) != code_to_name_.end();
}
/*!
* \brief Get bool representing whether type is registered, given the type name
* \param type_name The type name
* \return bool representing whether the type is registered
*/
inline bool GetTypeRegistered(std::string type_name) {
return name_to_code_.find(type_name) != name_to_code_.end();
}
private:
// TODO(gus) is there a typedef for the code?
std::unordered_map<uint8_t, std::string> code_to_name_;
std::unordered_map<std::string, uint8_t> name_to_code_;
};
/*!
* \brief Convert scalar value to a custom datatype format
* \param type_code The custom datatype to convert to, specified by type code
* \param value The floating point value to convert
* \return The value, encoded in the bits of a uint64_t
*/
uint64_t ConvertConstScalar(uint8_t type_code, double value);
/*!
* \brief Get a function returning the minimum value for a datatype.
* \param type_code The datatype
* \return Function which takes the width of the datatype and returns the min value
*/
const runtime::PackedFunc* GetMinFunc(uint8_t type_code);
/*!
* \brief Get lowering function for Cast ops
* \param target The target we are lowering to, e.g. "llvm"
* \param type_code The datatype being cast to
* \param src_type_code The datatype being cast from
* \return Lowering function for Cast ops for the provided target, type, and source type
*/
const runtime::PackedFunc* GetCastLowerFunc(const std::string& target, uint8_t type_code,
uint8_t src_type_code);
/*!
* \brief Get lowering function for FloatImms
* \param target The target we are lowering to, e.g. "llvm"
* \param type_code The datatype of the FloatImm
* \return Lowering function for FloatImms for the provided target and type
*/
const runtime::PackedFunc* GetFloatImmLowerFunc(const std::string& target, uint8_t type_code);
/*!
* \brief Get lowering function for intrinsic Calls/pure intrinsic Calls
* \param target The target we are lowering to, e.g. "llvm"
* \param type_code The datatype of the Call
* \param name The intrinsic name
* \return Lowering function for intrinsic Calls for the provided target and type
*/
const runtime::PackedFunc* GetIntrinLowerFunc(const std::string& target, const std::string& name,
uint8_t type_code);
/*!
* \brief Get lowering function for other ops
* \param target The target we are lowering to, e.g. "llvm"
* \param type_code The datatype of the op
* \return Lowering function for other ops for the provided target and type
*/
#define DEFINE_GET_LOWER_FUNC_(OP) \
inline const runtime::PackedFunc* Get##OP##LowerFunc(const std::string& target, \
uint8_t type_code) { \
return runtime::Registry::Get("tvm.datatype.lower." + target + "." #OP "." + \
datatype::Registry::Global()->GetTypeName(type_code)); \
}
DEFINE_GET_LOWER_FUNC_(Add)
DEFINE_GET_LOWER_FUNC_(Sub)
DEFINE_GET_LOWER_FUNC_(Mul)
DEFINE_GET_LOWER_FUNC_(Div)
DEFINE_GET_LOWER_FUNC_(Mod)
DEFINE_GET_LOWER_FUNC_(Min)
DEFINE_GET_LOWER_FUNC_(Max)
DEFINE_GET_LOWER_FUNC_(EQ)
DEFINE_GET_LOWER_FUNC_(NE)
DEFINE_GET_LOWER_FUNC_(LT)
DEFINE_GET_LOWER_FUNC_(LE)
DEFINE_GET_LOWER_FUNC_(GT)
DEFINE_GET_LOWER_FUNC_(GE)
// Later changes may need to add more lowering functions as we support workloads with more ops.
} // namespace datatype
} // namespace tvm
#endif // TVM_TARGET_DATATYPE_REGISTRY_H_
| https://github.com/zk-ml/tachikoma |
src/target/func_registry_generator.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* Defines functions that generate FuncRegistry structs for C runtime.
* \file func_registry_generator.h
*/
#ifndef TVM_TARGET_FUNC_REGISTRY_GENERATOR_H_
#define TVM_TARGET_FUNC_REGISTRY_GENERATOR_H_
#include <tvm/runtime/container/array.h>
#include <tvm/runtime/container/string.h>
#include <string>
#include <vector>
using tvm::runtime::Array;
using tvm::runtime::String;
namespace tvm {
namespace target {
std::string GenerateFuncRegistryNames(const Array<String>& function_names);
} // namespace target
} // namespace tvm
#endif // TVM_TARGET_FUNC_REGISTRY_GENERATOR_H_
| https://github.com/zk-ml/tachikoma |
src/target/intrin_rule.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* \file intrin_rule.h
* \brief Utility to generate intrinsic rules
*/
#ifndef TVM_TARGET_INTRIN_RULE_H_
#define TVM_TARGET_INTRIN_RULE_H_
#include <tvm/runtime/registry.h>
#include <tvm/tir/builtin.h>
#include <tvm/tir/expr.h>
#include <string>
namespace tvm {
namespace codegen {
namespace intrin {
using namespace tir;
// Add float suffix to the intrinsics
struct FloatSuffix {
std::string operator()(DataType t, std::string name) const {
if (t == DataType::Float(32)) {
return name + 'f';
} else if (t == DataType::Float(64)) {
return name;
} else {
return "";
}
}
};
// Return the intrinsic name
struct Direct {
std::string operator()(DataType t, std::string name) const { return name; }
};
// Call pure extern function.
template <typename T>
inline PrimExpr DispatchPureExtern(const PrimExpr& e) {
const CallNode* call = e.as<CallNode>();
ICHECK(call != nullptr);
// Use string based dispatch to extern for backward compact
// TODO(tvm-team) replace once the new dispatching system is inplace.
const OpNode* op = call->op.as<OpNode>();
ICHECK(op != nullptr);
std::string name = op->name;
ICHECK_EQ(name.substr(0, 4), "tir.");
name = T()(call->dtype, name.substr(4));
if (name.length() != 0) {
Array<PrimExpr> new_args = {StringImm(name)};
for (auto arg : call->args) {
new_args.push_back(arg);
}
return Call(call->dtype, builtin::call_pure_extern(), new_args);
} else {
return e;
}
}
} // namespace intrin
} // namespace codegen
} // namespace tvm
#endif // TVM_TARGET_INTRIN_RULE_H_
| https://github.com/zk-ml/tachikoma |
src/target/llvm/codegen_blob.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* \file codegen_blob.h
* \brief Code Generation of blob data
*/
#ifndef TVM_TARGET_LLVM_CODEGEN_BLOB_H_
#define TVM_TARGET_LLVM_CODEGEN_BLOB_H_
#ifdef TVM_LLVM_VERSION
#include <memory>
#include <string>
namespace llvm {
class Module;
}
namespace tvm {
namespace codegen {
class LLVMTarget;
/**
* \brief Code Generation of blob data
*
* \param data Blob data
* \param system_lib Whether expose as system library.
* \param target_triple LLVM target triple
*
* \return LLVM module and LLVM context
*/
std::unique_ptr<llvm::Module> CodeGenBlob(const std::string& data, bool system_lib,
LLVMTarget* llvm_target);
} // namespace codegen
} // namespace tvm
#endif // LLVM_VERSION
#endif // TVM_TARGET_LLVM_CODEGEN_BLOB_H_
| https://github.com/zk-ml/tachikoma |
src/target/llvm/codegen_cpu.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* \file codegen_llvm_cpu.h
* \brief Common base class for generating into LLVM IR on CPU host.
*/
#ifndef TVM_TARGET_LLVM_CODEGEN_CPU_H_
#define TVM_TARGET_LLVM_CODEGEN_CPU_H_
#ifdef TVM_LLVM_VERSION
#include <memory>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>
#include "codegen_llvm.h"
namespace llvm {
class BasicBlock;
class Constant;
class DIBuilder;
class DIType;
class Function;
class FunctionType;
class GlobalVariable;
class LLVMContext;
class MDNode;
class StructType;
class TargetMachine;
class Type;
class Value;
// Used in std::unique_ptr
class Module;
} // namespace llvm
namespace tvm {
namespace codegen {
class LLVMTarget;
// CPU host code generation
class CodeGenCPU : public CodeGenLLVM {
public:
CodeGenCPU();
virtual ~CodeGenCPU();
void Init(const std::string& module_name, LLVMTarget* llvm_target, bool system_lib,
bool dynamic_lookup, bool target_c_runtime) override;
void AddFunction(const PrimFunc& f) override;
void AddMainFunction(const std::string& entry_func_name) override;
std::unique_ptr<llvm::Module> Finish() override;
void VisitStmt_(const AssertStmtNode* op) override;
void VisitStmt_(const AttrStmtNode* op) override;
void VisitStmt_(const ForNode* op) override;
llvm::Value* CreateIntrinsic(const CallNode* op) override;
llvm::Value* CreateCallExtern(Type ret_type, String global_symbol, const Array<PrimExpr>& args,
bool skip_first_arg) override;
/*!
* \brief A CPU-specific function to create the FuncRegistry.
* \param func_names List of functions to be included, in order.
*/
void DefineFunctionRegistry(Array<String> func_names);
/*!
* \brief Serialize the metadata object as data, and implement get_c_metadata function.
* \param metadata The metadata which should be serialized.
*/
void DefineMetadata(runtime::metadata::Metadata metadata);
protected:
void AddStartupFunction() final;
// meta data
llvm::MDNode* md_tbaa_ctx_ptr_{nullptr};
// TVM related data types
llvm::Type* t_tvm_shape_index_{nullptr};
llvm::Type* t_tvm_func_handle_{nullptr};
llvm::StructType* t_tvm_device_{nullptr};
llvm::StructType* t_tvm_type_{nullptr};
llvm::StructType* t_tvm_array_{nullptr};
llvm::StructType* t_tvm_value_{nullptr};
llvm::StructType* t_tvm_parallel_group_env_{nullptr};
llvm::FunctionType* ftype_tvm_backend_packed_c_func_{nullptr};
llvm::StructType* t_tvm_crt_func_registry_{nullptr};
llvm::StructType* t_tvm_crt_module_{nullptr};
llvm::FunctionType* ftype_tvm_parallel_lambda_{nullptr};
llvm::FunctionType* ftype_tvm_func_call_{nullptr};
llvm::FunctionType* ftype_tvm_get_func_from_env_{nullptr};
llvm::FunctionType* ftype_tvm_api_set_last_error_{nullptr};
llvm::FunctionType* ftype_tvm_parallel_launch_{nullptr};
llvm::FunctionType* ftype_tvm_parallel_barrier_{nullptr};
llvm::FunctionType* ftype_tvm_register_system_symbol_{nullptr};
// Lazy entry for function call.
llvm::FunctionType* ftype_tvm_static_init_callback_{nullptr};
llvm::FunctionType* ftype_tvm_static_init_{nullptr};
private:
// the parallel group information
struct ParallelEnv {
Var task_id;
Var num_task;
bool stride_pattern{false};
bool in_parallel_loop{false};
int parallel_loop_count{0};
llvm::Value* penv{nullptr};
};
// Get runtime functions
void InitGlobalContext(bool dynamic_lookup);
llvm::GlobalVariable* InitContextPtr(llvm::Type* type, std::string name);
llvm::Value* GetContextPtr(llvm::GlobalVariable* gv);
llvm::Value* RuntimeTVMFuncCall();
llvm::Value* RuntimeTVMGetFuncFromEnv();
llvm::Value* RuntimeTVMAPISetLastError();
llvm::Value* RuntimeTVMParallelLaunch();
llvm::Value* RuntimeTVMParallelBarrier();
llvm::Value* CreateStaticHandle();
llvm::Value* GetPackedFuncHandle(const std::string& str);
TypedPointer PackClosureData(const Array<Var>& fields, uint64_t* num_bytes,
std::string struct_name = "");
TypedPointer CreateStructRefPtr(DataType t, llvm::Value* buffer, llvm::Value* index, int kind);
void UnpackClosureData(TypedPointer cdata, const Array<Var>& fields,
std::unordered_map<const VarNode*, llvm::Value*>* vmap);
// Make packed call.
struct PackedCall {
llvm::Value* ret_value;
llvm::Value* ret_tcode;
llvm::BasicBlock* end_block;
};
PackedCall MakeCallPackedLowered(const Array<PrimExpr>& args, const DataType& r_type,
const int64_t begin, const int64_t end, bool use_string_lookup);
// create call into tvm packed function.
llvm::Value* CreateCallPacked(const CallNode* op, bool use_string_lookup);
// Create trace call into tvm packed function.
llvm::Value* CreateCallTracePacked(const CallNode* op);
// Create static initialization
void CreateStaticInit(const std::string& init_fname, const Stmt& body);
// Create parallel launch
void CreateParallelLaunch(const Stmt& body, int num_task, std::string name = "");
// Create a new compute scope.
void CreateComputeScope(const AttrStmtNode* op);
// Check if the call to packed function is successful
// if not directly finalize function and pass on return code.
// return the end block after the check
llvm::BasicBlock* CheckCallSuccess(llvm::Value* retcode);
// Context for injection lookup
llvm::GlobalVariable* gv_mod_ctx_{nullptr};
llvm::GlobalVariable* gv_tvm_func_call_{nullptr};
llvm::GlobalVariable* gv_tvm_get_func_from_env_{nullptr};
llvm::GlobalVariable* gv_tvm_api_set_last_error_{nullptr};
llvm::GlobalVariable* gv_tvm_parallel_launch_{nullptr};
llvm::GlobalVariable* gv_tvm_parallel_barrier_{nullptr};
std::unordered_map<String, llvm::GlobalVariable*> gv_func_map_;
// context for direct dynamic lookup
llvm::Function* f_tvm_func_call_{nullptr};
llvm::Function* f_tvm_get_func_from_env_{nullptr};
llvm::Function* f_tvm_api_set_last_error_{nullptr};
llvm::Function* f_tvm_parallel_launch_{nullptr};
llvm::Function* f_tvm_parallel_barrier_{nullptr};
llvm::Function* f_tvm_register_system_symbol_{nullptr};
// Current parallel environment scope.
ParallelEnv parallel_env_;
// global to packed function handle
std::unordered_map<std::string, llvm::GlobalVariable*> func_handle_map_;
// List of symbols to be exported to TVM system lib.
std::vector<std::pair<std::string, llvm::Constant*>> export_system_symbols_;
// List of functions to be registered in the FuncRegistry, if generated.
std::vector<std::pair<std::string, llvm::Function*>> registry_functions_;
// internal debug information, to be populated by
std::unique_ptr<DebugInfo> dbg_info_;
bool target_c_runtime_;
bool is_system_lib_;
// Get the DWARF type corresponding to the LLVM type |ty|. The current API in practice only
// generates |int32|, and |int8*|.
llvm::DIType* GetDebugType(const Type& ty_tir, llvm::Type* ty_llvm);
// Adds the DWARF debug information for |function| to |dbg_info_|.
void AddDebugInformation(PrimFunc f_tir, llvm::Function* f_llvm);
};
} // namespace codegen
} // namespace tvm
#endif // TVM_LLVM_VERSION
#endif // TVM_TARGET_LLVM_CODEGEN_CPU_H_
| https://github.com/zk-ml/tachikoma |
src/target/llvm/codegen_llvm.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* \file codegen_llvm.h
* \brief Common base class for generating into LLVM IR
*/
#ifndef TVM_TARGET_LLVM_CODEGEN_LLVM_H_
#define TVM_TARGET_LLVM_CODEGEN_LLVM_H_
#ifdef TVM_LLVM_VERSION
#include <llvm/ADT/ArrayRef.h>
#include <llvm/ADT/StringRef.h>
#include <llvm/IR/BasicBlock.h>
#include <llvm/IR/ConstantFolder.h>
#include <llvm/IR/Constants.h>
#include <llvm/IR/DerivedTypes.h>
#if TVM_LLVM_VERSION >= 150
#include <llvm/IR/FMF.h>
#else
#include <llvm/IR/Operator.h>
#endif
#include <llvm/IR/GlobalValue.h>
#include <llvm/IR/IRBuilder.h>
#include <llvm/IR/Instructions.h>
#include <llvm/IR/Intrinsics.h>
#include <llvm/Support/Casting.h>
#if TVM_LLVM_VERSION >= 140
#include <llvm/MC/TargetRegistry.h>
#else
#include <llvm/Support/TargetRegistry.h>
#endif
#include <tvm/arith/analyzer.h>
#include <tvm/ir/module.h>
#include <tvm/target/codegen.h>
#include <tvm/tir/analysis.h>
#include <tvm/tir/expr.h>
#include <tvm/tir/function.h>
#include <tvm/tir/op.h>
#include <tvm/tir/op_attr_types.h>
#include <tvm/tir/stmt.h>
#include <tvm/tir/stmt_functor.h>
#include <algorithm>
#include <memory>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
#include "../../runtime/thread_storage_scope.h"
#include "../../tir/transforms/ir_utils.h"
#include "codegen_params.h"
namespace llvm {
class Argument;
class CallInst;
class Function;
class GlobalVariable;
class Instruction;
class PassManagerBuilder;
class DIFile;
class DICompileUnit;
class MDNode;
// Used in std::unique_ptr
class Module;
class DataLayout;
class DIBuilder;
class MDBuilder;
} // namespace llvm
namespace tvm {
namespace codegen {
class LLVMTarget;
using namespace tir;
/*!
* \brief A base class to generate a LLVM.
*/
class CodeGenLLVM : public ExprFunctor<llvm::Value*(const PrimExpr&)>,
public StmtFunctor<void(const Stmt&)> {
public:
CodeGenLLVM(); // Do not make it default here.
virtual ~CodeGenLLVM(); // Do not make it default here.
/*!
* \brief Create new code generator based on target machine.
* \param tm The target machine
* \return The created llvm generator.
*/
static std::unique_ptr<CodeGenLLVM> Create(LLVMTarget* llvm_target);
/*!
* \brief Initialize the code generator with given context
* \param module_name The name of the module.
* \param tm Target machine model
* \param ctx The context.
* \param system_lib Whether to insert system library registration.
* \param dynamic_lookup Whether dynamically lookup runtime function
* or use the runtime function table passed by caller.
* \param target_c_runtime If true, generate a module to be executed by the C runtime. In practice
* this option influences whether global ctors are used.
*/
virtual void Init(const std::string& module_name, LLVMTarget* llvm_target, bool system_lib,
bool dynamic_lookup, bool target_c_runtime);
/*!
* \brief Turn on fast math flags for floating point operations.
* \param fmf FastMathFlags to use for code generation.
*/
void SetFastMathFlags(llvm::FastMathFlags fmf);
/*!
* \brief Compile and add function f to the current module.
* \param f The function to be added.
*/
virtual void AddFunction(const PrimFunc& f);
/*!
* \brief Add main function as the entry name
* \param entry_func_name The name of entry function to be added.
*/
virtual void AddMainFunction(const std::string& entry_func_name);
/*!
* \brief Finish current pass of codegen, get the module.
* \return the created module.
*/
virtual std::unique_ptr<llvm::Module> Finish();
/*!
* \brief Add functions from the (unordered) range to the current module in a deterministic order.
* The range consists of objects convertible to PrimFunc.
* \param begin The beginning of the range.
* \param end The end of the range.
* \param pfunc Converter function from the range element type to PrimFunc.
*/
template <typename IterType, typename ConvType>
void AddFunctionsOrdered(IterType begin, IterType end, ConvType pfunc);
/*!
* \brief Add functions from the (unordered) range of elements of type PrimFunc to the current
* module in a deterministic order.
* \param begin The beginning of the range.
* \param end The end of the range.
*/
template <typename IterType>
void AddFunctionsOrdered(IterType begin, IterType end) {
this->AddFunctionsOrdered(begin, end, [](auto f) { return f; });
}
/*!
* \brief Add mod to be linked with the generated module
* \param mod The module to be linked.
*/
void AddLinkModule(std::unique_ptr<llvm::Module>&& mod);
/*!
* \brief Create Value for expression e
* \param e The expression to be created value for.
* \return created value.
*/
llvm::Value* MakeValue(const PrimExpr& e) { return VisitExpr(e); }
// Short hande code to get a constant int 32
llvm::Constant* ConstInt32(int64_t value) const {
return llvm::ConstantInt::getSigned(t_int32_, value);
}
// override codegen
llvm::Value* VisitExpr_(const VarNode* op) override;
llvm::Value* VisitExpr_(const CastNode* op) override;
llvm::Value* VisitExpr_(const IntImmNode* op) override;
llvm::Value* VisitExpr_(const FloatImmNode* op) override;
llvm::Value* VisitExpr_(const StringImmNode* op) override;
llvm::Value* VisitExpr_(const AddNode* op) override;
llvm::Value* VisitExpr_(const SubNode* op) override;
llvm::Value* VisitExpr_(const MulNode* op) override;
llvm::Value* VisitExpr_(const DivNode* op) override;
llvm::Value* VisitExpr_(const ModNode* op) override;
llvm::Value* VisitExpr_(const MinNode* op) override;
llvm::Value* VisitExpr_(const MaxNode* op) override;
llvm::Value* VisitExpr_(const LTNode* op) override;
llvm::Value* VisitExpr_(const LENode* op) override;
llvm::Value* VisitExpr_(const GTNode* op) override;
llvm::Value* VisitExpr_(const GENode* op) override;
llvm::Value* VisitExpr_(const EQNode* op) override;
llvm::Value* VisitExpr_(const NENode* op) override;
llvm::Value* VisitExpr_(const AndNode* op) override;
llvm::Value* VisitExpr_(const OrNode* op) override;
llvm::Value* VisitExpr_(const NotNode* op) override;
llvm::Value* VisitExpr_(const SelectNode* op) override;
llvm::Value* VisitExpr_(const LetNode* op) override;
llvm::Value* VisitExpr_(const LoadNode* op) override;
llvm::Value* VisitExpr_(const BufferLoadNode* op) override;
llvm::Value* VisitExpr_(const CallNode* op) override;
llvm::Value* VisitExpr_(const RampNode* op) override;
llvm::Value* VisitExpr_(const ShuffleNode* op) override;
llvm::Value* VisitExpr_(const BroadcastNode* op) override;
// stmt
void VisitStmt_(const StoreNode* op) override;
void VisitStmt_(const BufferStoreNode* op) override;
void VisitStmt_(const ForNode* op) override;
void VisitStmt_(const WhileNode* op) override;
void VisitStmt_(const IfThenElseNode* op) override;
void VisitStmt_(const AllocateNode* op) override;
void VisitStmt_(const AllocateConstNode* op) override;
void VisitStmt_(const AttrStmtNode* op) override;
void VisitStmt_(const AssertStmtNode* op) override;
void VisitStmt_(const LetStmtNode* op) override;
void VisitStmt_(const SeqStmtNode* op) override;
void VisitStmt_(const EvaluateNode* op) override;
// Get constant string
llvm::Constant* GetConstString(const std::string& str);
llvm::Constant* GetGlobalConstant(
llvm::Constant* const_data, const std::string& name = "",
llvm::GlobalValue::LinkageTypes linkage_type = llvm::GlobalValue::InternalLinkage);
protected:
/*!
* \brief Address and type pair to assist in handling opaque pointers.
*/
struct TypedPointer {
TypedPointer() = default;
TypedPointer(llvm::Type* t, llvm::Value* a) : type(t), addr(a) {}
llvm::Type* type = nullptr; /*!< Type of the value pointed to. */
llvm::Value* addr = nullptr; /*!< Address of the value. */
};
/*! \brief The storage information */
struct StorageInfo {
/*! \brief The alignment of allocation */
int alignment{0};
};
/*!
* \brief Convert tvm::runtime::String into llvm::StringRef
*/
static llvm::StringRef MakeStringRef(const String& string) {
return llvm::StringRef(string.c_str(), string.size());
}
/*!
* \brief Execute falloca at the beginning of the
* currrent function and obtain its return value.
*
* This is a helper function to make sure that
* alloca always happen in the beginning of the function.
*
* \param falloca The allocation function to be executed.
* \tparam F The function to be executed.
* \return The result.
*/
template <typename F>
llvm::AllocaInst* WithFunctionEntry(F falloca) {
llvm::BasicBlock* current = builder_->GetInsertBlock();
llvm::BasicBlock* entry = &(function_->getEntryBlock());
builder_->SetInsertPoint(entry, entry->begin());
llvm::AllocaInst* res = falloca();
builder_->SetInsertPoint(current);
return res;
}
// create intrinstic given call
virtual llvm::Value* CreateIntrinsic(const CallNode* op);
// create extern function call
// skip first arg mode used for call extern intrinsic.
virtual llvm::Value* CreateCallExtern(Type ret_type, String global_symbol,
const Array<PrimExpr>& args, bool skip_first_arg);
/*! \brief Insert a printf() call to the generated LLVM
*
* This is intended solely for debugging purposes. After calling
* printf(), immediately calls fflush() to flush the stdout buffer
* in case of segfault.
*/
virtual void CreatePrintf(const std::string& format, llvm::ArrayRef<llvm::Value*> format_args);
/*! \brief Lookup return address, for debugging purposes
*
* This is intended solely for debugging purposes. Calls the
* `llvm::Intrinsic::returnaddress`, returning the return address of
* the current function call.
*
* \param level Look up the return address of a frame `level` steps
* above the current stack frame.
*/
llvm::Value* CreateLookupReturnAddress(unsigned int level = 0);
// Get the corresponding thread index
virtual llvm::Value* GetThreadIndex(const IterVar& iv);
// Get the corresponding thread index
virtual llvm::Value* CreateStorageSync(const CallNode* op);
// apply optimization on the module.
virtual void InitPassManagerBuilder(llvm::PassManagerBuilder* builder);
// Scalarize by iterating elements of e.
// f is a callback that takes index and v.
void Scalarize(const PrimExpr& e, std::function<void(int i, llvm::Value* v)> f);
/* \brief Helper function for handling buffer access
*
* \param buffer The buffer being accessed
*
* \param indices The indices at which the buffer is being accessed.
*
* \param value_dtype The datatype to be read from (BufferLoad) or
* written to (BufferStore) the buffer.
*
* \param make_instruction A callback function that generates that
* actual call.
*
* - buffer_ptr: A typed pointer to the element being accessed
*
* - subelement_i: The index of a vectorized type to be
* stored/loaded. If -1, indicates that the entire type,
* vector or scalar, should be written.
*
* - alignment: The alignment to be used for the read/write.
*
* - is_volatile: Whether the read/write should be volatile.
*
* - Should return the generated expression.
*/
void BufferAccessHelper(
Buffer buffer, Array<PrimExpr> indices, DataType value_dtype,
std::function<llvm::Instruction*(TypedPointer buffer_ptr, int subelement_i, int alignment,
bool is_volatile)>
make_instruction);
// Initialize target
virtual void InitTarget();
// Add module startup function if needed.
virtual void AddStartupFunction() {}
// apply optimization on the module.
virtual void Optimize();
// Get the maximim storage align bits of buffer pointer given storage scope.
virtual int NativeVectorBits(const runtime::StorageScope& storage_scope) const;
// Get correct address space depending on the backend
virtual unsigned GetGlobalAddressSpace() const;
void AddFunctionInternal(const PrimFunc& f, bool ret_void);
// Create extern call
llvm::CallInst* CreateCallExtern(llvm::Type* ret, const std::string& name,
const std::vector<llvm::Value*>& value);
/*!
* \brief Get the LLVM Type for a given runtime type.
* \param dtype The runtime dtype.
*
* \note Only use this function for dealing with PrimTypes.
* For Call and Var that could have more refined types,
* use GetLLVMType instead.
*
* \return LLVM type of dtype
*/
llvm::Type* DTypeToLLVMType(const DataType& dtype) const;
/*!
* \brief Get the LLVM Type for a given type.
* \param dtype The runtime dtype.
* \param type The corresponding TVM Type.
*/
llvm::Type* GetLLVMType(const Type& type) const;
/*!
* \brief Get the LLVM Type for a given type.
* \param dtype The runtime dtype.
* \param type The corresponding TVM Type.
*/
llvm::Type* GetLLVMType(const PrimExpr& expr) const;
/*!
* \brief Get the declaration of the LLVM intrinsic based on the intrinsic
* id, and the type of the actual call.
*
* \param id The intrinsic id.
* \param ret_type The call return type.
* \param arg_types The types of the call arguments.
*
* \return Return the llvm::Function pointer, or nullptr if the declaration
* could not be generated (e.g. if the argument/return types do not
* match).
*/
llvm::Function* GetIntrinsicDecl(llvm::Intrinsic::ID id, llvm::Type* ret_type,
llvm::ArrayRef<llvm::Type*> arg_types);
/*!
* \brief Set target-related attributes on the LLVM function \p func. This
* includes "target-cpu" and "target-features" if present.
*
* \param func The function to set attributes on.
*/
void SetTargetAttributes(llvm::Function* func);
/*!
* \brief Emit LLVM IR for conversion functions __extendhfsf2 and __truncsfhf2
* into the current llvm::Module.
*
* \param use_float16_abi Whether to use floating-point or integer ABI.
*/
void EmitFloat16ConversionBuiltins(bool use_float16_abi);
/*!
* \brief Get the number of elements in the given vector value.
* \param vec The value, must be of a vector type.
*/
inline int GetVectorNumElements(llvm::Value* vec);
// initialize the function state.
void InitFuncState();
// Get alignment given index.
void GetAlignment(DataType t, const VarNode* buf_var, const PrimExpr& index, int* p_alignment,
int* p_native_bits);
// Returns whether the LLVM type has padding for alignment
bool HasAlignmentPadding(DataType dtype);
// do a scalarize call with f
llvm::Value* CreateScalarizedCall(const CallNode* op, llvm::Function* f,
const std::vector<llvm::Value*>& args);
// handle module import
void HandleImport(const std::string& code);
// cast operatpr
llvm::Value* CreateCast(DataType from, DataType to, llvm::Value* value);
// comparison op
llvm::Value* GetVarValue(const VarNode* v) const;
llvm::Value* CreateLT(DataType t, llvm::Value* a, llvm::Value* b);
llvm::Value* CreateLE(DataType t, llvm::Value* a, llvm::Value* b);
llvm::Value* CreateGT(DataType t, llvm::Value* a, llvm::Value* b);
llvm::Value* CreateGE(DataType t, llvm::Value* a, llvm::Value* b);
llvm::Value* CreateAdd(DataType t, llvm::Value* a, llvm::Value* b);
llvm::Value* CreateSub(DataType t, llvm::Value* a, llvm::Value* b);
llvm::Value* CreateMul(DataType t, llvm::Value* a, llvm::Value* b);
llvm::Value* CreateBroadcast(llvm::Value* value, int lanes);
virtual TypedPointer CreateBufferPtr(llvm::Value* buffer_ptr, DataType buffer_element_dtype,
llvm::ArrayRef<llvm::Value*> indices, DataType value_dtype);
// Vector concatenation.
llvm::Value* CreateVecSlice(llvm::Value* vec, int begin, int extent);
llvm::Value* CreateVecFlip(llvm::Value* vec);
llvm::Value* CreateVecConcat(std::vector<llvm::Value*> vecs);
llvm::Value* CreateVecPad(llvm::Value* vec, int target_lanes);
// Create serial for
void CreateSerialFor(llvm::Value* begin, llvm::Value* end, llvm::Value* stride,
const Var& loop_var, const Stmt& body);
// add alias information.
void AddAliasInfo(llvm::Instruction* inst, const VarNode* buffer_var, PrimExpr index,
DataType access_dtype);
llvm::GlobalVariable* AllocateSharedMemory(DataType dtype, size_t size,
unsigned int shared_address_space, int alignment,
llvm::GlobalValue::LinkageTypes linkage);
/*!
* \brief Get the `i`th argument to the given function, respecting LLVM API changes.
*
* NOTE: in LLVM < 10.0, the underlying API returns a const llvm::Argument*. To provide a uniform
* API, const is removed here. Proper usage of LLVM APIs depends on having a non-const Argument*,
* so we take this appraoch here rather than adding const.
*
* \param function The function containing the arguments.
* \param i The index of the argument to retrieve.
* \return The retrieved argument.
*/
llvm::Argument* GetArg(const llvm::Function* function, int i) const {
#if TVM_LLVM_VERSION >= 100
return function->getArg(i);
#elif TVM_LLVM_VERSION >= 50
return const_cast<llvm::Argument*>(&function->arg_begin()[i]);
#else
return const_cast<llvm::Argument*>(&*std::next(function->arg_begin(), i));
#endif
}
// The IRBuilder.
using IRBuilder = llvm::IRBuilder<llvm::ConstantFolder, llvm::IRBuilderDefaultInserter>;
// The current function
llvm::Function* function_;
// Internal builder
std::unique_ptr<IRBuilder> builder_;
// The module to be returned;
std::unique_ptr<llvm::Module> module_;
std::unique_ptr<llvm::DataLayout> data_layout_;
// Internal metabuilder
std::unique_ptr<llvm::MDBuilder> md_builder_;
// llvm target info
LLVMTarget* llvm_target_{nullptr};
// helpful data types
llvm::Type* t_void_{nullptr};
llvm::PointerType* t_void_p_{nullptr};
llvm::Type* t_int_{nullptr};
llvm::Type* t_char_{nullptr};
llvm::Type* t_int8_{nullptr};
llvm::Type* t_int16_{nullptr};
llvm::Type* t_int32_{nullptr};
llvm::Type* t_int64_{nullptr};
llvm::Type* t_float64_{nullptr};
// meta data
llvm::MDNode* md_very_likely_branch_{nullptr};
llvm::MDNode* md_tbaa_root_{nullptr};
llvm::MDNode* md_tbaa_alias_set_{nullptr};
// modules to be linked.
std::vector<std::unique_ptr<llvm::Module>> link_modules_;
/*! \brief native vector bits of current targetx*/
int native_vector_bits_{0};
/*! \brief the storage scope of allocation */
std::unordered_map<const VarNode*, StorageInfo> alloc_storage_info_;
// The definition of local variable.
std::unordered_map<const VarNode*, llvm::Value*> var_map_;
// global strings
std::unordered_map<std::string, llvm::Constant*> str_map_;
// Whether current function is restricted
bool is_restricted_{true};
// The analyzer information
std::unique_ptr<arith::Analyzer> analyzer_;
// set of var that are not restricted(can alias)
std::unordered_set<const VarNode*> alias_var_set_;
// set of volatile buffer.
std::unordered_set<const VarNode*> volatile_buf_;
// deep comparison of PrimExpr
ExprDeepEqual deep_equal_;
// binding of let variables. Enables duplicate var defs that map to same value
std::unordered_map<Var, const LetNode*, ObjectPtrHash, ObjectPtrEqual> let_binding_;
// Cache potential common path ops to slightly improve lookup time.
// global symbol table.
OpAttrMap<TGlobalSymbol> op_attr_global_symbol_ = Op::GetAttrMap<TGlobalSymbol>("TGlobalSymbol");
const Op& builtin_call_extern_ = builtin::call_extern();
const Op& builtin_call_pure_extern_ = builtin::call_pure_extern();
const Op& builtin_call_llvm_intrin_ = builtin::call_llvm_intrin();
const Op& builtin_call_llvm_pure_intrin_ = builtin::call_llvm_pure_intrin();
const Op& builtin_lookup_param_ = builtin::lookup_param();
const Op& builtin_tvm_call_cpacked_lowered_ = builtin::tvm_call_cpacked_lowered();
/*! \brief Helper struct for debug infos. */
struct DebugInfo {
~DebugInfo(); // Because of the std::unique_ptr.
std::unique_ptr<llvm::DIBuilder> di_builder_;
llvm::DICompileUnit* compilation_unit_{nullptr};
llvm::DIFile* file_{nullptr};
};
/*!
* \brief Create a new DebugInfo struct from the given Module that
* initializes file and compilation_unit_ to TVM defaults.
*/
static std::unique_ptr<DebugInfo> CreateDebugInfo(llvm::Module* module);
};
inline int CodeGenLLVM::GetVectorNumElements(llvm::Value* vec) {
#if TVM_LLVM_VERSION >= 120
return llvm::cast<llvm::FixedVectorType>(vec->getType())->getNumElements();
#else
return llvm::cast<llvm::VectorType>(vec->getType())->getNumElements();
#endif
}
template <typename IterType, typename ConvType>
void CodeGenLLVM::AddFunctionsOrdered(IterType begin, IterType end, ConvType pfunc) {
std::vector<PrimFunc> funcs;
for (auto it = begin; it != end; ++it) {
funcs.push_back(pfunc(*it));
}
std::sort(funcs.begin(), funcs.end(), [](PrimFunc func_a, PrimFunc func_b) {
std::string name_a = func_a->GetAttr<String>(tvm::attr::kGlobalSymbol).value();
std::string name_b = func_b->GetAttr<String>(tvm::attr::kGlobalSymbol).value();
return name_a < name_b;
});
for (auto& f : funcs) {
auto global_symbol = f->GetAttr<String>(tvm::attr::kGlobalSymbol);
AddFunction(f);
}
}
} // namespace codegen
} // namespace tvm
#endif // TVM_LLVM_VERSION
#endif // TVM_TARGET_LLVM_CODEGEN_LLVM_H_
| https://github.com/zk-ml/tachikoma |
src/target/llvm/codegen_params.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* \file codegen_params.h
*/
#ifndef TVM_TARGET_LLVM_CODEGEN_PARAMS_H_
#define TVM_TARGET_LLVM_CODEGEN_PARAMS_H_
#include <tvm/runtime/ndarray.h>
namespace llvm {
class ConstantArray;
class LLVMContext;
} // namespace llvm
namespace tvm {
namespace codegen {
/*!
* \brief Convert an NDArray to an LLVM array of constants.
*
* The supplied NDArray is flattened, and each element is converted to the appropriate LLVM type.
*
* \param ctx LLVM context used to create the various primitive datatypes.
* \param arr NDArray to convert.
* \return LLVM array containing the array data.
*/
llvm::ConstantArray* NDArrayToLLVMArray(llvm::LLVMContext* ctx, tvm::runtime::NDArray arr);
} // namespace codegen
} // namespace tvm
#endif // TVM_TARGET_LLVM_CODEGEN_PARAMS_H_
| https://github.com/zk-ml/tachikoma |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.