#include "channel_quant.hpp" #include namespace channel_quant { namespace { void locate(const Layout &layout, std::size_t linear, std::size_t &address, std::size_t &channel) { address = layout.origin; channel = 0; for (std::size_t i = layout.shape.size(); i-- > 0;) { auto coordinate = linear % layout.shape[i]; linear /= layout.shape[i]; address += coordinate * layout.strides[i]; if (static_cast(i) == layout.axis) channel = coordinate; } } } int inspect_layout(const Tensor &tensor, int axis, Layout &out) { int rank = static_cast(tensor.shape.size()); if (rank < 1 || rank > 4 || tensor.strides.size() != tensor.shape.size()) return -22; for (auto dimension : tensor.shape) if (dimension > 16) return -34; if (axis < -rank || axis >= rank) return -22; int normalized = axis < 0 ? axis + rank : axis; if (tensor.shape[normalized] == 0) return -22; std::size_t elements = 1; for (auto dimension : tensor.shape) elements *= dimension; if (elements > 4096 || tensor.storage.size() > 8192) return -34; for (auto value : tensor.storage) if (value < -1000000000LL || value > 1000000000LL) return -34; if (tensor.origin > tensor.storage.size()) return -34; if (elements) { std::size_t largest = tensor.origin; auto limit = std::numeric_limits::max(); for (std::size_t i = 0; i < tensor.shape.size(); ++i) { auto distance = tensor.shape[i] - 1; if (distance && tensor.strides[i] > (limit - largest) / distance) return -34; largest += distance * tensor.strides[i]; } if (largest >= tensor.storage.size()) return -34; } out = {tensor.shape,tensor.strides,tensor.origin,normalized,elements,tensor.shape[normalized]}; return 0; } int gather(const Tensor &tensor, int axis, std::vector &values, std::vector &channels) { Layout layout{}; int error = inspect_layout(tensor,axis,layout); if (error) return error; std::vector next_values; std::vector next_channels; next_values.reserve(layout.elements); next_channels.reserve(layout.elements); for (std::size_t i = 0; i < layout.elements; ++i) { std::size_t address, channel; locate(layout,i,address,channel); next_values.push_back(tensor.storage[address]); next_channels.push_back(channel); } values.swap(next_values); channels.swap(next_channels); return 0; } int element(const Tensor &tensor, int axis, std::size_t index, std::int64_t &value, std::size_t &channel) { Layout layout{}; int error = inspect_layout(tensor,axis,layout); if (error) return error; if (index >= layout.elements) return -34; std::size_t address, selected; locate(layout,index,address,selected); value = tensor.storage[address]; channel = selected; return 0; } }