Code
stringlengths
131
28.2k
Unit Test
stringlengths
40
32.1k
__index_level_0__
int64
0
2.63k
#ifndef AROLLA_ALGORITHM_CONTROL_FLOW_GRAPH_H_ #define AROLLA_ALGORITHM_CONTROL_FLOW_GRAPH_H_ #include <cstdint> #include <memory> #include <utility> #include <vector> #include "absl/container/flat_hash_set.h" #include "absl/status/statusor.h" #include "absl/types/span.h" namespace arolla { class AcyclicCFG { public: using NodeId = int64_t; static absl::StatusOr<std::unique_ptr<AcyclicCFG>> Create( std::vector<std::vector<int64_t>> deps); int64_t num_nodes() const { return deps_.size(); } absl::Span<const NodeId> deps(NodeId id) const { return deps_[id]; } absl::Span<const NodeId> reverse_deps(NodeId id) const { return reverse_deps_[id]; } private: explicit AcyclicCFG(std::vector<std::vector<NodeId>> deps, std::vector<std::vector<NodeId>> reverse_deps) : deps_(std::move(deps)), reverse_deps_(std::move(reverse_deps)) {} std::vector<std::vector<NodeId>> deps_; std::vector<std::vector<NodeId>> reverse_deps_; }; class DominatorTree { public: using NodeId = AcyclicCFG::NodeId; explicit DominatorTree(const AcyclicCFG& graph); int64_t num_nodes() const { return infos_.size(); } NodeId parent(NodeId node_id) const { return infos_[node_id].parent; } std::vector<NodeId> parents() const { std::vector<NodeId> result(num_nodes()); for (NodeId node_id = 0; node_id != num_nodes(); ++node_id) { result[node_id] = infos_[node_id].parent; } return result; } int64_t depth(NodeId node_id) const { return infos_[node_id].depth; } absl::Span<const NodeId> children(NodeId node_id) const { return infos_[node_id].children; } private: struct Info { NodeId parent; int64_t depth; std::vector<NodeId> children; }; NodeId Lca(NodeId a, NodeId b); NodeId Lca(absl::Span<const NodeId> nodes); std::vector<Info> infos_; }; absl::StatusOr<std::unique_ptr<AcyclicCFG>> ExternalizeNodes( const AcyclicCFG& graph, const DominatorTree& tree, const absl::flat_hash_set<AcyclicCFG::NodeId>& global_nodes = {}); std::vector<bool> FindVerticesWithEmptyDominanceFrontier( const AcyclicCFG& graph, const DominatorTree& tree); } #endif #include "arolla/algorithm/control_flow_graph.h" #include <algorithm> #include <cstdint> #include <memory> #include <utility> #include <vector> #include "absl/container/flat_hash_set.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "absl/types/span.h" namespace arolla { using NodeId = AcyclicCFG::NodeId; absl::StatusOr<std::unique_ptr<AcyclicCFG>> AcyclicCFG::Create( std::vector<std::vector<NodeId>> deps) { const int64_t n = deps.size(); if (n == 0) { return absl::FailedPreconditionError("at least one node is expected"); } std::vector<std::vector<int64_t>> reverse_deps(n); for (NodeId node = 0; node != n; ++node) { for (int64_t dep : deps[node]) { if (dep <= node) { return absl::FailedPreconditionError(absl::StrFormat( "all edges must be directed to the larger index, found %d -> %d", node, dep)); } if (dep >= n) { return absl::FailedPreconditionError( absl::StrFormat("vertex id %d is out of range", dep)); } reverse_deps[dep].push_back(node); } } for (NodeId node = 1; node != n; ++node) { if (reverse_deps[node].empty()) { return absl::FailedPreconditionError(absl::StrFormat( "all vertices must be reachable from root, %d has no reverse deps", node)); } } return std::unique_ptr<AcyclicCFG>( new AcyclicCFG(std::move(deps), std::move(reverse_deps))); } DominatorTree::DominatorTree(const AcyclicCFG& graph) : infos_(graph.num_nodes()) { const int64_t n = graph.num_nodes(); infos_[0].parent = 0; infos_[0].depth = 0; for (NodeId node = 1; node != n; ++node) { auto& info = infos_[node]; info.parent = Lca(graph.reverse_deps(node)); info.depth = depth(info.parent) + 1; infos_[info.parent].children.push_back(node); } } NodeId DominatorTree::Lca(NodeId a, NodeId b) { if (depth(a) < depth(b)) { using std::swap; swap(a, b); } while (depth(a) > depth(b)) { a = parent(a); } while (a != b) { a = parent(a); b = parent(b); } return a; } NodeId DominatorTree::Lca(absl::Span<const NodeId> nodes) { auto res = nodes[0]; for (const auto& node : nodes) { res = Lca(res, node); } return res; } absl::StatusOr<std::unique_ptr<AcyclicCFG>> ExternalizeNodes( const AcyclicCFG& graph, const DominatorTree& tree, const absl::flat_hash_set<NodeId>& global_nodes) { const int64_t n = graph.num_nodes(); std::vector<std::vector<NodeId>> deps(n); for (NodeId node_id = 0; node_id < n; ++node_id) { if (global_nodes.contains(node_id) && node_id != 0) { deps[tree.parent(node_id)].push_back(node_id); } deps[node_id].reserve(graph.deps(node_id).size()); for (NodeId dep : graph.deps(node_id)) { if (!global_nodes.contains(dep)) { deps[node_id].push_back(dep); } } } return AcyclicCFG::Create(std::move(deps)); } std::vector<bool> FindVerticesWithEmptyDominanceFrontier( const AcyclicCFG& graph, const DominatorTree& tree) { int64_t n = graph.num_nodes(); std::vector<int64_t> min_over_deps_dominator_depth(n); std::vector<bool> empty_frontier(n); for (NodeId node_id = n - 1; node_id >= 0; --node_id) { int64_t min_depth = tree.depth(node_id); for (NodeId dep : graph.deps(node_id)) { min_depth = std::min(min_depth, std::min(min_over_deps_dominator_depth[dep], tree.depth(dep) - 1)); } empty_frontier[node_id] = (min_depth == tree.depth(node_id)); min_over_deps_dominator_depth[node_id] = min_depth; } return empty_frontier; } }
#include "arolla/algorithm/control_flow_graph.h" #include <cstddef> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "arolla/util/testing/status_matchers_backport.h" namespace arolla { namespace { using ::arolla::testing::StatusIs; using ::testing::ElementsAre; using ::testing::HasSubstr; using ::testing::IsEmpty; TEST(AcyclicCFG, Empty) { ASSERT_OK_AND_ASSIGN(auto g, AcyclicCFG::Create({{}})); EXPECT_EQ(g->num_nodes(), 1); EXPECT_THAT(g->deps(0), IsEmpty()); EXPECT_THAT(g->reverse_deps(0), IsEmpty()); } TEST(AcyclicCFG, Simple) { ASSERT_OK_AND_ASSIGN(auto g, AcyclicCFG::Create({ {1, 3}, {2, 3}, {}, {}, })); EXPECT_EQ(g->num_nodes(), 4); EXPECT_THAT(g->deps(0), ElementsAre(1, 3)); EXPECT_THAT(g->deps(1), ElementsAre(2, 3)); EXPECT_THAT(g->deps(2), IsEmpty()); EXPECT_THAT(g->deps(3), IsEmpty()); EXPECT_THAT(g->reverse_deps(0), IsEmpty()); EXPECT_THAT(g->reverse_deps(1), ElementsAre(0)); EXPECT_THAT(g->reverse_deps(2), ElementsAre(1)); EXPECT_THAT(g->reverse_deps(3), ElementsAre(0, 1)); } TEST(AcyclicCFG, Errors) { EXPECT_THAT( AcyclicCFG::Create({{0}}).status(), StatusIs(absl::StatusCode::kFailedPrecondition, HasSubstr("directed"))); EXPECT_THAT(AcyclicCFG::Create({{1}}).status(), StatusIs(absl::StatusCode::kFailedPrecondition, HasSubstr("out of range"))); EXPECT_THAT( AcyclicCFG::Create({{1}, {0}}).status(), StatusIs(absl::StatusCode::kFailedPrecondition, HasSubstr("directed"))); EXPECT_THAT( AcyclicCFG::Create({{1}, {}, {}}).status(), StatusIs(absl::StatusCode::kFailedPrecondition, HasSubstr("reachable"))); } TEST(DominatorTree, Chain) { ASSERT_OK_AND_ASSIGN(auto graph, AcyclicCFG::Create({{1}, {2}, {3}, {}})); DominatorTree tree(*graph); auto empty_frontier = FindVerticesWithEmptyDominanceFrontier(*graph, tree); for (size_t i = 0; i != graph->num_nodes(); ++i) { EXPECT_EQ(tree.depth(i), i); EXPECT_EQ(tree.parent(i), i == 0 ? i : i - 1) << i; if (i + 1 != graph->num_nodes()) { EXPECT_THAT(tree.children(i), ElementsAre(i + 1)); } else { EXPECT_THAT(tree.children(i), IsEmpty()) << i; } EXPECT_TRUE(empty_frontier[i]) << i; } } TEST(DominatorTree, WikiTest) { ASSERT_OK_AND_ASSIGN(auto graph, AcyclicCFG::Create({ {1}, {2, 3, 5}, {4}, {4}, {}, {} })); DominatorTree tree(*graph); auto empty_frontier = FindVerticesWithEmptyDominanceFrontier(*graph, tree); EXPECT_EQ(tree.depth(0), 0); EXPECT_EQ(tree.parent(0), 0); EXPECT_THAT(tree.children(0), ElementsAre(1)); EXPECT_TRUE(empty_frontier[0]); EXPECT_EQ(tree.depth(1), 1); EXPECT_EQ(tree.parent(1), 0); EXPECT_THAT(tree.children(1), ElementsAre(2, 3, 4, 5)); EXPECT_TRUE(empty_frontier[1]); for (size_t i = 2; i != 6; ++i) { EXPECT_EQ(tree.depth(i), 2) << i; EXPECT_EQ(tree.parent(i), 1) << i; EXPECT_THAT(tree.children(i), IsEmpty()) << i; } EXPECT_FALSE(empty_frontier[2]); EXPECT_FALSE(empty_frontier[3]); EXPECT_TRUE(empty_frontier[4]); EXPECT_TRUE(empty_frontier[5]); } TEST(DominatorTree, TwoChainsConnectedNearTheMiddle) { ASSERT_OK_AND_ASSIGN(auto graph, AcyclicCFG::Create({ {1}, {2, 6}, {3}, {4}, {5, 7}, {8}, {7}, {8}, {9}, {}, })); DominatorTree tree(*graph); auto empty_frontier = FindVerticesWithEmptyDominanceFrontier(*graph, tree); EXPECT_THAT(tree.parents(), ElementsAre(0, 0, 1, 2, 3, 4, 1, 1, 1, 8)); EXPECT_THAT(empty_frontier, ElementsAre(true, true, false, false, false, false, false, false, true, true)); } TEST(FindVerticesWithEmptyDominanceFrontier, ExternalizeLeaves) { ASSERT_OK_AND_ASSIGN(auto graph, AcyclicCFG::Create({ {1, 2}, {3}, {3}, {}, })); DominatorTree tree(*graph); ASSERT_OK_AND_ASSIGN(auto extern3_graph, ExternalizeNodes(*graph, tree, {3})); EXPECT_THAT(extern3_graph->deps(0), ElementsAre(1, 2, 3)); EXPECT_THAT(extern3_graph->deps(1), IsEmpty()); EXPECT_THAT(extern3_graph->deps(2), IsEmpty()); EXPECT_THAT(extern3_graph->deps(3), IsEmpty()); EXPECT_THAT(tree.parents(), ElementsAre(0, 0, 0, 0)); EXPECT_THAT(FindVerticesWithEmptyDominanceFrontier(*extern3_graph, tree), ElementsAre(true, true, true, true)); } TEST(FindVerticesWithEmptyDominanceFrontier, ExternalizeInternalNode) { ASSERT_OK_AND_ASSIGN(auto graph, AcyclicCFG::Create({ {1, 2}, {3}, {3}, {4}, {}, })); DominatorTree tree(*graph); EXPECT_THAT(tree.parents(), ElementsAre(0, 0, 0, 0, 3)); ASSERT_OK_AND_ASSIGN(auto extern3_graph, ExternalizeNodes(*graph, tree, {3})); EXPECT_THAT(extern3_graph->deps(0), ElementsAre(1, 2, 3)); EXPECT_THAT(extern3_graph->deps(1), IsEmpty()); EXPECT_THAT(extern3_graph->deps(2), IsEmpty()); EXPECT_THAT(extern3_graph->deps(3), ElementsAre(4)); EXPECT_THAT(extern3_graph->deps(4), IsEmpty()); EXPECT_THAT(FindVerticesWithEmptyDominanceFrontier(*extern3_graph, tree), ElementsAre(true, true, true, true, true)); } } }
2,387
#ifndef AROLLA_UTIL_TYPES_H_ #define AROLLA_UTIL_TYPES_H_ #include <cstddef> #include <type_traits> namespace arolla { using signed_size_t = typename std::make_signed<size_t>::type; } #endif #include "arolla/codegen/expr/types.h" #include <cstdint> #include <functional> #include <sstream> #include <string> #include <utility> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "absl/strings/str_join.h" #include "absl/strings/string_view.h" #include "absl/synchronization/mutex.h" #include "double-conversion/double-to-string.h" #include "double-conversion/utils.h" #include "arolla/dense_array/dense_array.h" #include "arolla/dense_array/edge.h" #include "arolla/dense_array/qtype/types.h" #include "arolla/memory/optional_value.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/optional_qtype.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/tuple_qtype.h" #include "arolla/qtype/typed_ref.h" #include "arolla/util/bytes.h" #include "arolla/util/indestructible.h" #include "arolla/util/string.h" #include "arolla/util/text.h" #include "arolla/util/unit.h" #include "arolla/util/status_macros_backport.h" namespace arolla::codegen { namespace { std::string CppLiteralReprImpl(Unit) { return "::arolla::kUnit"; } std::string CppLiteralReprImpl(bool value) { return value ? "true" : "false"; } std::string CppLiteralReprImpl(int32_t value) { return absl::StrFormat("int32_t{%d}", value); } std::string CppLiteralReprImpl(int64_t value) { return absl::StrFormat("int64_t{%d}", value); } std::string CppLiteralReprImpl(uint64_t value) { return absl::StrFormat("uint64_t{%dull}", value); } using double_conversion::DoubleToStringConverter; std::string CppLiteralReprImpl(float value) { static const DoubleToStringConverter converter( DoubleToStringConverter::EMIT_TRAILING_DECIMAL_POINT, "std::numeric_limits<float>::infinity()", "std::numeric_limits<float>::quiet_NaN()", 'e', -8, 21, 6, 0); char buf[128]; double_conversion::StringBuilder builder(buf, sizeof(buf)); builder.AddString("float{"); converter.ToShortestSingle(value, &builder); builder.AddString("}"); return builder.Finalize(); } std::string CppLiteralReprImpl(double value) { static const DoubleToStringConverter converter( DoubleToStringConverter::EMIT_TRAILING_DECIMAL_POINT, "std::numeric_limits<double>::infinity()", "std::numeric_limits<double>::quiet_NaN()", 'e', -12, 21, 6, 0); char buf[128]; double_conversion::StringBuilder builder(buf, sizeof(buf)); builder.AddString("double{"); converter.ToShortest(value, &builder); builder.AddString("}"); return builder.Finalize(); } const char kRawStringDelimiter[] = "RL_CODEGEN_DELIM"; std::string CppRawStringLiteral(absl::string_view view) { return absl::StrFormat("R\"%s(%s)%s\"", kRawStringDelimiter, view, kRawStringDelimiter); } std::string CppLiteralReprImpl(const Bytes& bytes) { return absl::StrFormat("::arolla::Bytes(%s)", CppRawStringLiteral(bytes)); } std::string CppLiteralReprImpl(const Text& text) { return absl::StrFormat("::arolla::Text(%s)", CppRawStringLiteral(text.view())); } absl::StatusOr<std::string> DefaultConstructedCppLiteralRepr(QTypePtr qtype) { ASSIGN_OR_RETURN(std::string type_name, CppTypeName(qtype)); return absl::StrFormat("%s{}", type_name); } absl::StatusOr<std::string> OptionalCppLiteralRepr(TypedRef value) { auto qtype = value.GetType(); if (IsScalarQType(DecayOptionalQType(qtype))) { bool is_correct_optional = (qtype == GetQType<OptionalUnit>() && value.GetFieldCount() == 1) || (qtype != GetQType<OptionalUnit>() && value.GetFieldCount() == 2); if (!is_correct_optional) { return absl::InternalError(absl::StrFormat( "Wrong number of fields in optional type %s", qtype->name())); } ASSIGN_OR_RETURN(bool present, value.GetField(0).As<bool>()); if (!present) { return DefaultConstructedCppLiteralRepr(qtype); } else { ASSIGN_OR_RETURN(std::string type_name, CppTypeName(qtype)); ASSIGN_OR_RETURN(std::string value_repr, qtype == GetQType<OptionalUnit>() ? CppLiteralReprImpl(kUnit) : CppLiteralRepr(value.GetField(1))); return absl::StrFormat("::arolla::MakeOptionalValue(%s)", value_repr); } } return absl::UnimplementedError( absl::StrFormat("CppLiteralRepr is unknown for type %s", qtype->name())); } template <class T> absl::StatusOr<std::string> CppLiteralReprImpl(const DenseArray<T>& values) { std::vector<std::string> values_str; values_str.reserve(values.size()); for (int64_t i = 0; i != values.size(); ++i) { OptionalValue<T> value; if (values.present(i)) { value = T(values.values[i]); } ASSIGN_OR_RETURN(auto value_str, OptionalCppLiteralRepr(TypedRef::FromValue(value))); values_str.push_back(value_str); } ASSIGN_OR_RETURN(std::string type_name, CppTypeName(GetQType<T>())); return absl::StrFormat("::arolla::CreateDenseArray<%s>({%s})", type_name, absl::StrJoin(values_str, ",")); } template <class T> absl::StatusOr<std::string> CppLiteralReprImpl( const absl::StatusOr<std::reference_wrapper<T>>& value_or) { ASSIGN_OR_RETURN(auto value, value_or); return CppLiteralReprImpl(value.get()); } #define RETURN_CPP_LITERAL_IF_SAME_TYPE(_, CTYPE) \ if (GetQType<CTYPE>() == value.GetType()) { \ return CppLiteralReprImpl(value.As<CTYPE>().value()); \ } absl::StatusOr<std::string> NonOptionalCppLiteralRepr(TypedRef value) { AROLLA_FOREACH_BASE_TYPE(RETURN_CPP_LITERAL_IF_SAME_TYPE); RETURN_CPP_LITERAL_IF_SAME_TYPE(UNIT, Unit); return absl::FailedPreconditionError(absl::StrFormat( "Unsupported literal QType: %s", value.GetType()->name())); } #define RETURN_CPP_LITERAL_IF_SAME_DENSE_ARRAY_TYPE(_, CTYPE) \ if (GetQType<DenseArray<CTYPE>>() == value.GetType()) { \ return CppLiteralReprImpl(value.As<DenseArray<CTYPE>>()); \ } absl::StatusOr<std::string> DenseArrayCppLiteralRepr(TypedRef value) { AROLLA_FOREACH_BASE_TYPE(RETURN_CPP_LITERAL_IF_SAME_DENSE_ARRAY_TYPE); return absl::UnimplementedError(absl::StrFormat( "CppLiteralRepr is unknown for type %s", value.GetType()->name())); } #undef RETURN_CPP_LITERAL_IF_SAME_DENSE_ARRAY_TYPE absl::StatusOr<std::string> DenseArrayEdgeCppLiteralRepr(DenseArrayEdge edge) { auto wrap_as_lambda = [](absl::string_view x) { return absl::StrFormat("[]() { return %s; }()", x); }; if (edge.edge_type() == DenseArrayEdge::SPLIT_POINTS) { ASSIGN_OR_RETURN(std::string split_points, CppLiteralReprImpl(edge.edge_values())); return wrap_as_lambda(absl::StrFormat( "::arolla::DenseArrayEdge::FromSplitPoints(%s).value()", split_points)); } else if (edge.edge_type() == DenseArrayEdge::MAPPING) { ASSIGN_OR_RETURN(std::string mapping, CppLiteralReprImpl(edge.edge_values())); return wrap_as_lambda( absl::StrFormat("::arolla::DenseArrayEdge::FromMapping(%s, %d).value()", mapping, edge.parent_size())); } return absl::UnimplementedError(absl::StrFormat( "CppLiteralRepr is unknown for %d DenseArrayEdge edge_type", edge.edge_type())); } struct TypeMap { absl::Mutex lock; absl::flat_hash_map<QTypePtr, std::string> cpp_type_name; absl::flat_hash_map<QTypePtr, std::function<absl::StatusOr<std::string>(TypedRef)>> cpp_literal_repr_fn; }; TypeMap& GetTypeMap() { static Indestructible<TypeMap> kTypeMap; return *kTypeMap; } absl::StatusOr<std::string> CppTupleLiteralRepr(TypedRef value) { if (!IsTupleQType(value.GetType())) { return absl::InternalError("expected tuple QType"); } std::ostringstream res; res << "::arolla::MakeTupleFromFields("; bool first = true; for (int64_t i = 0; i != value.GetFieldCount(); ++i) { TypedRef f_slot = value.GetField(i); ASSIGN_OR_RETURN(std::string value, CppLiteralRepr(f_slot)); res << NonFirstComma(first) << value; } res << ")"; return res.str(); } absl::StatusOr<std::string> CppTupleQTypeConstruction(QTypePtr qtype) { if (!IsTupleQType(qtype)) { return absl::InternalError("expected tuple QType"); } std::ostringstream res; res << "::arolla::MakeTupleQType({"; bool first = true; for (const auto& f_slot : qtype->type_fields()) { ASSIGN_OR_RETURN(std::string qtype, CppQTypeConstruction(f_slot.GetType())); res << NonFirstComma(first) << qtype; } res << "})"; return res.str(); } } absl::Status RegisterCppType( QTypePtr qtype, absl::string_view cpp_type_name, std::function<absl::StatusOr<std::string>(TypedRef)> cpp_literal_repr) { TypeMap& type_map = GetTypeMap(); absl::MutexLock l(&type_map.lock); if (type_map.cpp_type_name.contains(qtype) || type_map.cpp_literal_repr_fn.contains(qtype)) { return absl::FailedPreconditionError( absl::StrFormat("RegisterCppType called twice for %s", qtype->name())); } type_map.cpp_type_name.emplace(qtype, std::string(cpp_type_name)); type_map.cpp_literal_repr_fn.emplace(qtype, std::move(cpp_literal_repr)); return absl::OkStatus(); } absl::StatusOr<std::string> CppTypeName(QTypePtr qtype) { const TypeMap& type_map = GetTypeMap(); if (auto it = type_map.cpp_type_name.find(qtype); it != type_map.cpp_type_name.end()) { return it->second; } if (IsScalarQType(qtype)) { if (qtype == GetQType<bool>()) { return "bool"; } if (qtype == GetQType<int32_t>()) { return "int32_t"; } if (qtype == GetQType<int64_t>()) { return "int64_t"; } if (qtype == GetQType<float>()) { return "float"; } if (qtype == GetQType<double>()) { return "double"; } if (qtype == GetQType<uint64_t>()) { return "uint64_t"; } if (qtype == GetQType<Unit>()) { return "::arolla::Unit"; } if (qtype == GetQType<Bytes>()) { return "::arolla::Bytes"; } if (qtype == GetQType<Text>()) { return "::arolla::Text"; } } if (IsOptionalQType(qtype)) { if (qtype == GetOptionalQType<Unit>()) { return "::arolla::OptionalUnit"; } if (IsScalarQType(qtype->value_qtype())) { ASSIGN_OR_RETURN(auto value_type_name, CppTypeName(DecayOptionalQType(qtype))); return absl::StrFormat("::arolla::OptionalValue<%s>", value_type_name); } } if (IsDenseArrayQType(qtype)) { if (IsScalarQType(qtype->value_qtype())) { ASSIGN_OR_RETURN(auto value_type_name, CppTypeName(qtype->value_qtype())); return absl::StrFormat("::arolla::DenseArray<%s>", value_type_name); } } if (qtype == GetQType<DenseArrayShape>()) { return "::arolla::DenseArrayShape"; } if (qtype == GetQType<DenseArrayEdge>()) { return "::arolla::DenseArrayEdge"; } if (qtype == GetQType<DenseArrayGroupScalarEdge>()) { return "::arolla::DenseArrayGroupScalarEdge"; } if (IsTupleQType(qtype)) { return "::arolla::TypedValue"; } return absl::UnimplementedError( absl::StrFormat("CppTypeName is unknown for type %s", qtype->name())); } absl::StatusOr<std::string> CppQTypeConstruction(QTypePtr qtype) { if (IsTupleQType(qtype)) { return CppTupleQTypeConstruction(qtype); } ASSIGN_OR_RETURN(std::string type_name, CppTypeName(qtype)); return absl::StrFormat("::arolla::GetQType<%s>()", type_name); } absl::StatusOr<std::string> CppLiteralRepr(TypedRef value) { auto qtype = value.GetType(); const TypeMap& type_map = GetTypeMap(); if (auto it = type_map.cpp_literal_repr_fn.find(qtype); it != type_map.cpp_literal_repr_fn.end()) { return it->second(value); } if (IsScalarQType(qtype)) { return NonOptionalCppLiteralRepr(value); } if (IsOptionalQType(qtype)) { return OptionalCppLiteralRepr(value); } if (IsDenseArrayQType(qtype)) { return DenseArrayCppLiteralRepr(value); } if (qtype == GetQType<DenseArrayShape>()) { return absl::StrFormat("::arolla::DenseArrayShape{%d}", value.UnsafeAs<DenseArrayShape>().size); } if (qtype == GetQType<DenseArrayEdge>()) { ASSIGN_OR_RETURN(auto edge, value.As<DenseArrayEdge>()); return DenseArrayEdgeCppLiteralRepr(edge); } if (qtype == GetQType<DenseArrayGroupScalarEdge>()) { return absl::StrFormat( "::arolla::DenseArrayGroupScalarEdge{%d}", value.UnsafeAs<DenseArrayGroupScalarEdge>().child_size()); } if (IsTupleQType(qtype)) { return CppTupleLiteralRepr(value); } return absl::UnimplementedError( absl::StrFormat("CppLiteralRepr is unknown for type %s", qtype->name())); } }
#include "arolla/codegen/expr/types.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/simple_qtype.h" #include "arolla/qtype/typed_ref.h" #include "arolla/util/fingerprint.h" #include "arolla/util/testing/status_matchers_backport.h" namespace arolla { namespace { struct NonExistentFake {}; } AROLLA_DECLARE_FINGERPRINT_HASHER_TRAITS(NonExistentFake); void FingerprintHasherTraits<NonExistentFake>::operator()( FingerprintHasher* hasher, const NonExistentFake&) const { hasher->Combine(7); } AROLLA_DECLARE_SIMPLE_QTYPE(FAKE_TEST, NonExistentFake); AROLLA_DEFINE_SIMPLE_QTYPE(FAKE_TEST, NonExistentFake); } namespace arolla::codegen { namespace { using ::arolla::testing::IsOk; using ::arolla::testing::IsOkAndHolds; TEST(CppTypeName, Sanity) { EXPECT_THAT(CppTypeName(GetQType<float>()), IsOkAndHolds("float")); } TEST(CppLiteralRepr, Sanity) { EXPECT_THAT(CppLiteralRepr(TypedRef::FromValue(1)), IsOkAndHolds("int32_t{1}")); } TEST(RegisterCppType, Sanity) { EXPECT_THAT( RegisterCppType(GetQType<NonExistentFake>(), "::arolla::NonExistentFake", [](TypedRef) { return "::arolla::NonExistentFake{}"; }), IsOk()); EXPECT_THAT(CppTypeName(GetQType<NonExistentFake>()), IsOkAndHolds("::arolla::NonExistentFake")); EXPECT_THAT(CppLiteralRepr(TypedRef::FromValue(NonExistentFake{})), IsOkAndHolds("::arolla::NonExistentFake{}")); } } }
2,388
#ifndef AROLLA_PROTO_QTYPE_PROTO_QTYPE_MAP_H_ #define AROLLA_PROTO_QTYPE_PROTO_QTYPE_MAP_H_ #include "absl/status/statusor.h" #include "google/protobuf/descriptor.h" #include "arolla/qtype/qtype.h" namespace arolla::proto { absl::StatusOr<arolla::QTypePtr> ProtoFieldTypeToQType( google::protobuf::FieldDescriptor::Type field_type); } #endif #include <cstdint> #include <string> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "google/protobuf/descriptor.h" #include "arolla/proto/types.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/util/bytes.h" namespace arolla::proto { using ::arolla::GetQType; using ::arolla::QTypePtr; using ::google::protobuf::FieldDescriptor; absl::StatusOr<QTypePtr> ProtoFieldTypeToQType( FieldDescriptor::Type field_type) { switch (field_type) { case FieldDescriptor::TYPE_INT32: case FieldDescriptor::TYPE_SINT32: case FieldDescriptor::TYPE_SFIXED32: return GetQType<arolla_single_value_t<int32_t>>(); case FieldDescriptor::TYPE_INT64: case FieldDescriptor::TYPE_SINT64: case FieldDescriptor::TYPE_SFIXED64: return GetQType<arolla_single_value_t<int64_t>>(); case FieldDescriptor::TYPE_UINT32: case FieldDescriptor::TYPE_FIXED32: return GetQType<arolla_single_value_t<uint32_t>>(); case FieldDescriptor::TYPE_UINT64: case FieldDescriptor::TYPE_FIXED64: return GetQType<arolla_single_value_t<uint64_t>>(); case FieldDescriptor::TYPE_DOUBLE: return GetQType<arolla_single_value_t<double>>(); case FieldDescriptor::TYPE_FLOAT: return GetQType<arolla_single_value_t<float>>(); case FieldDescriptor::TYPE_BOOL: return GetQType<arolla_single_value_t<bool>>(); case FieldDescriptor::TYPE_STRING: return GetQType<arolla_single_value_t<std::string>>(); case FieldDescriptor::TYPE_BYTES: return GetQType<arolla::Bytes>(); case FieldDescriptor::TYPE_ENUM: return GetQType<arolla_single_value_t<int32_t>>(); default: return absl::InvalidArgumentError( absl::StrCat("type ", field_type, " is not supported")); } } }
#include "arolla/proto/qtype/proto_qtype_map.h" #include <cstdint> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "google/protobuf/descriptor.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/util/bytes.h" #include "arolla/util/testing/status_matchers_backport.h" namespace arolla::proto { namespace { using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::StatusIs; TEST(ProtoFieldTypeToQTypeTest, Get) { EXPECT_THAT(ProtoFieldTypeToQType(google::protobuf::FieldDescriptor::TYPE_SFIXED32), IsOkAndHolds(arolla::GetQType<int32_t>())); EXPECT_THAT(ProtoFieldTypeToQType(google::protobuf::FieldDescriptor::TYPE_FIXED32), IsOkAndHolds(arolla::GetQType<int64_t>())); EXPECT_THAT(ProtoFieldTypeToQType(google::protobuf::FieldDescriptor::TYPE_SFIXED64), IsOkAndHolds(arolla::GetQType<int64_t>())); EXPECT_THAT(ProtoFieldTypeToQType(google::protobuf::FieldDescriptor::TYPE_FIXED64), IsOkAndHolds(arolla::GetQType<uint64_t>())); EXPECT_THAT(ProtoFieldTypeToQType(google::protobuf::FieldDescriptor::TYPE_FLOAT), IsOkAndHolds(arolla::GetQType<float>())); EXPECT_THAT(ProtoFieldTypeToQType(google::protobuf::FieldDescriptor::TYPE_DOUBLE), IsOkAndHolds(arolla::GetQType<double>())); EXPECT_THAT(ProtoFieldTypeToQType(google::protobuf::FieldDescriptor::TYPE_BOOL), IsOkAndHolds(arolla::GetQType<bool>())); EXPECT_THAT(ProtoFieldTypeToQType(google::protobuf::FieldDescriptor::TYPE_ENUM), IsOkAndHolds(arolla::GetQType<int32_t>())); EXPECT_THAT(ProtoFieldTypeToQType(google::protobuf::FieldDescriptor::TYPE_STRING), IsOkAndHolds(arolla::GetQType<arolla::Bytes>())); EXPECT_THAT(ProtoFieldTypeToQType(google::protobuf::FieldDescriptor::TYPE_BYTES), IsOkAndHolds(arolla::GetQType<arolla::Bytes>())); EXPECT_THAT(ProtoFieldTypeToQType(google::protobuf::FieldDescriptor::TYPE_MESSAGE), StatusIs(absl::StatusCode::kInvalidArgument)); } } }
2,389
#ifndef AROLLA_PROTO_REFLECTION_READER_H_ #define AROLLA_PROTO_REFLECTION_READER_H_ #include <cstddef> #include <functional> #include <memory> #include <utility> #include <variant> #include <vector> #include "absl/status/statusor.h" #include "absl/types/span.h" #include "google/protobuf/descriptor.h" #include "google/protobuf/message.h" #include "arolla/memory/frame.h" #include "arolla/proto/types.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/typed_slot.h" namespace arolla::proto { struct RegularFieldAccess {}; struct RepeatedFieldIndexAccess { explicit RepeatedFieldIndexAccess(size_t idx) : idx(idx) {} size_t idx; }; struct RepeatedFieldAccess {}; struct RepeatedFieldSizeAccess {}; using ProtoFieldAccessInfo = std::variant<RegularFieldAccess, RepeatedFieldIndexAccess, RepeatedFieldAccess, RepeatedFieldSizeAccess>; class ProtoTypeReader { public: using BoundReadFn = std::function<void(const google::protobuf::Message&, FramePtr)>; static absl::StatusOr<std::unique_ptr<ProtoTypeReader>> CreateOptionalReader( absl::Span<const google::protobuf::FieldDescriptor* const> fields, std::vector<ProtoFieldAccessInfo> access_infos, proto::StringFieldType string_type = StringFieldType::kText); static absl::StatusOr<std::unique_ptr<ProtoTypeReader>> CreateDenseArrayShapeReader( absl::Span<const google::protobuf::FieldDescriptor* const> fields, std::vector<ProtoFieldAccessInfo> access_infos, proto::StringFieldType string_type = StringFieldType::kText); static absl::StatusOr<std::unique_ptr<ProtoTypeReader>> CreateDenseArrayReader( absl::Span<const google::protobuf::FieldDescriptor* const> fields, std::vector<ProtoFieldAccessInfo> access_infos, proto::StringFieldType string_type = StringFieldType::kText); ProtoTypeReader( QTypePtr qtype, std::function<absl::StatusOr<BoundReadFn>(TypedSlot)> read_fn_factory) : qtype_(qtype), read_fn_factory_(std::move(read_fn_factory)) {} QTypePtr qtype() const { return qtype_; } absl::StatusOr<BoundReadFn> BindReadFn(TypedSlot slot) const { return read_fn_factory_(slot); } private: QTypePtr qtype_; std::function<absl::StatusOr<BoundReadFn>(TypedSlot)> read_fn_factory_; }; } #endif #include "arolla/proto/reflection/reader.h" #include <algorithm> #include <cstddef> #include <cstdint> #include <functional> #include <memory> #include <optional> #include <string> #include <type_traits> #include <utility> #include <variant> #include <vector> #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "absl/types/span.h" #include "google/protobuf/descriptor.h" #include "google/protobuf/reflection.h" #include "arolla/dense_array/dense_array.h" #include "arolla/dense_array/qtype/types.h" #include "arolla/memory/buffer.h" #include "arolla/memory/frame.h" #include "arolla/proto/types.h" #include "arolla/qtype/optional_qtype.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/util/bytes.h" #include "arolla/util/text.h" #include "arolla/util/status_macros_backport.h" namespace { using ::google::protobuf::FieldDescriptor; using ::google::protobuf::Message; using ::google::protobuf::Reflection; using ::absl::StatusOr; using ::arolla::Bytes; using ::arolla::FrameLayout; using ::arolla::FramePtr; using ::arolla::GetDenseArrayQType; using ::arolla::GetOptionalQType; using ::arolla::GetQType; using ::arolla::OptionalValue; using ::arolla::QTypePtr; using ::arolla::Text; using ::arolla::TypedSlot; using ::arolla::DenseArrayShape; using ::arolla::proto::arolla_size_t; using ::arolla::proto::ProtoFieldAccessInfo; using ::arolla::proto::ProtoTypeReader; using ::arolla::proto::RegularFieldAccess; using ::arolla::proto::RepeatedFieldAccess; using ::arolla::proto::RepeatedFieldIndexAccess; using ::arolla::proto::RepeatedFieldSizeAccess; using ::arolla::proto::StringFieldType; using ReadValueFn = std::function<void(const Message&, void*)>; template <class T, class ProtoGetFn> struct ByIndexReader { void operator()(const Message& m, void* res_void) const { auto* res = reinterpret_cast<OptionalValue<T>*>(res_void); const auto* ref = m.GetReflection(); if (access_info.idx < ref->FieldSize(m, field)) { *res = static_cast<T>( getter.GetFromRepeated(ref, m, field, access_info.idx)); } else { *res = std::nullopt; } } const FieldDescriptor* field; RepeatedFieldIndexAccess access_info; ProtoGetFn getter; }; template <class T, class ProtoGetFn> struct FieldReader { void operator()(const Message& m, void* res_void) const { auto* res = reinterpret_cast<OptionalValue<T>*>(res_void); const auto* ref = m.GetReflection(); if (ref->HasField(m, field)) { *res = static_cast<T>(getter.GetSingular(ref, m, field)); } else { *res = std::nullopt; } } const FieldDescriptor* field; ProtoGetFn getter; }; using PushbackFn = std::function<void(const Message&, void*)>; template <class T, class ProtoGetFn> struct ManyPushBackFn { void operator()(const Message& m, void* res_void) const { auto* res = reinterpret_cast<std::vector<OptionalValue<T>>*>(res_void); const auto* ref = m.GetReflection(); for (const auto& val : getter.GetRepeated(ref, m, field)) { res->push_back(static_cast<T>(val)); } } const FieldDescriptor* field; ProtoGetFn getter; }; struct SizePushBackFn { void operator()(const Message& m, void* res_void) const { auto* res = reinterpret_cast<std::vector<arolla_size_t>*>(res_void); const auto* ref = m.GetReflection(); res->push_back(ref->FieldSize(m, field)); } const FieldDescriptor* field; }; struct SizeToShapeFn { void operator()(const Message& m, void* res_void) const { auto* res = reinterpret_cast<DenseArrayShape*>(res_void); const auto* ref = m.GetReflection(); res->size = ref->FieldSize(m, field); } const FieldDescriptor* field; }; template <class ResultT> struct SinglePushBackFn { void operator()(const Message& m, void* res_void) const { auto* res = reinterpret_cast<std::vector<OptionalValue<ResultT>>*>(res_void); res->emplace_back(); get_fn(m, &res->back()); } ReadValueFn get_fn; }; #define PROTO_GETTER_OBJ(TYPE, CPP_TYPE) \ struct PFG##TYPE { \ auto GetSingular(const Reflection* ref, const Message& m, \ const FieldDescriptor* field) const { \ return ref->Get##TYPE(m, field); \ } \ auto GetFromRepeated(const Reflection* ref, const Message& m, \ const FieldDescriptor* field, int index) const { \ return ref->GetRepeated##TYPE(m, field, index); \ } \ auto GetRepeated(const Reflection* ref, const Message& m, \ const FieldDescriptor* field) const { \ return ref->GetRepeatedFieldRef<CPP_TYPE>(m, field); \ } \ }; \ constexpr auto kProtoGetter##TYPE = PFG##TYPE{}; PROTO_GETTER_OBJ(Int32, int32_t); PROTO_GETTER_OBJ(Int64, int64_t); PROTO_GETTER_OBJ(UInt32, uint32_t); PROTO_GETTER_OBJ(UInt64, uint64_t); PROTO_GETTER_OBJ(Float, float); PROTO_GETTER_OBJ(Double, double); PROTO_GETTER_OBJ(Bool, bool); PROTO_GETTER_OBJ(String, std::string); PROTO_GETTER_OBJ(EnumValue, int32_t); #undef PROTO_GETTER_OBJ absl::Status CheckAccessInfo(const FieldDescriptor* field, const ProtoFieldAccessInfo& info, bool allow_repeated, bool is_last) { if (field == nullptr) { return absl::FailedPreconditionError( "field is nullptr (incorrect name passed into FindFieldByName?)"); } if (field->is_repeated()) { if (std::holds_alternative<RepeatedFieldIndexAccess>(info)) { return absl::OkStatus(); } if (allow_repeated && std::holds_alternative<RepeatedFieldAccess>(info)) { return absl::OkStatus(); } if (allow_repeated && is_last && std::holds_alternative<RepeatedFieldSizeAccess>(info)) { return absl::OkStatus(); } return absl::FailedPreconditionError(absl::StrCat( "incorrect access to the repeated field: ", field->full_name())); } else { if (!std::holds_alternative<RegularFieldAccess>(info)) { return absl::FailedPreconditionError(absl::StrCat( "incorrect access to the regular field: ", field->full_name())); } } return absl::OkStatus(); } class Traverser { public: Traverser(std::vector<const FieldDescriptor*> fields, std::vector<ProtoFieldAccessInfo> access_infos) : fields_(std::move(fields)), access_infos_(std::move(access_infos)) { DCHECK_EQ(fields_.size(), access_infos_.size()); } const Message* GetLastSubMessage(const Message& m) const { const Message* current_message = &m; for (size_t i = 0; i != fields_.size(); ++i) { current_message = GetSubMessage(*current_message, i); if (current_message == nullptr) { return nullptr; } } return current_message; } void TraverseSubmessages(const Message& m, PushbackFn callback, void* res) const { using IndexedMessage = std::pair<const Message*, size_t>; std::vector<IndexedMessage> stack; stack.emplace_back(&m, 0); while (!stack.empty()) { auto [current_message, i] = stack.back(); stack.pop_back(); if (i != fields_.size()) { size_t end_id = stack.size(); const auto* field = fields_[i]; const auto& access_info = access_infos_[i]; DCHECK(!std::holds_alternative<RepeatedFieldSizeAccess>(access_info)); if (std::holds_alternative<RepeatedFieldAccess>(access_info)) { const auto* ref = m.GetReflection(); for (const Message& sub_message : ref->GetRepeatedFieldRef<Message>(m, field)) { stack.emplace_back(&sub_message, i + 1); } } else { stack.emplace_back(GetSubMessage(m, i), i + 1); } std::reverse(stack.begin() + end_id, stack.end()); } else { callback(*current_message, res); } } } private: const Message* GetSubMessage(const Message& m, int i) const { const auto* field = fields_[i]; const auto& access_info = access_infos_[i]; DCHECK(!std::holds_alternative<RepeatedFieldAccess>(access_info)); const auto* ref = m.GetReflection(); if (field->is_repeated()) { auto& access = *std::get_if<RepeatedFieldIndexAccess>(&access_info); if (access.idx < ref->FieldSize(m, field)) { return &ref->GetRepeatedMessage(m, field, access.idx); } else { return nullptr; } } else { if (ref->HasField(m, field)) { return &ref->GetMessage(m, field); } else { return nullptr; } } } std::vector<const FieldDescriptor*> fields_; std::vector<ProtoFieldAccessInfo> access_infos_; }; template <class T> struct OptionalReader { void operator()(const Message& m, FramePtr frame) const { const Message* last_message = traverser.GetLastSubMessage(m); if (last_message == nullptr) { frame.Set(slot, {}); } else { get_fn(*last_message, frame.GetMutable(slot)); } } Traverser traverser; FrameLayout::Slot<OptionalValue<T>> slot; ReadValueFn get_fn; }; template <class T> struct OptionalReaderFactory { absl::StatusOr<ProtoTypeReader::BoundReadFn> operator()( TypedSlot typed_slot) const { ASSIGN_OR_RETURN(auto slot, typed_slot.ToSlot<OptionalValue<T>>()); return OptionalReader<T>{traverser, slot, get_fn}; } Traverser traverser; ReadValueFn get_fn; }; struct ArraySizeReader { void operator()(const Message& m, FramePtr frame) const { std::vector<arolla_size_t> res; traverser.TraverseSubmessages(m, last_push_back_fn, &res); frame.Set(slot, ::arolla::DenseArray<arolla_size_t>{ ::arolla::Buffer<arolla_size_t>::Create(std::move(res))}); } Traverser traverser; FrameLayout::Slot<::arolla::DenseArray<arolla_size_t>> slot; PushbackFn last_push_back_fn; }; struct ArraySizeReaderFactory { absl::StatusOr<ProtoTypeReader::BoundReadFn> operator()( TypedSlot typed_slot) const { ASSIGN_OR_RETURN(auto slot, typed_slot.ToSlot<::arolla::DenseArray<arolla_size_t>>()); return ArraySizeReader{traverser, slot, SizePushBackFn{last_field}}; } Traverser traverser; const FieldDescriptor* last_field; }; struct ShapeSizeReader { void operator()(const Message& m, FramePtr frame) const { DenseArrayShape res; traverser.TraverseSubmessages(m, last_push_back_fn, &res); frame.Set(slot, res); } Traverser traverser; FrameLayout::Slot<::arolla::DenseArrayShape> slot; PushbackFn last_push_back_fn; }; struct ShapeSizeReaderFactory { absl::StatusOr<ProtoTypeReader::BoundReadFn> operator()( TypedSlot typed_slot) const { ASSIGN_OR_RETURN(auto slot, typed_slot.ToSlot<::arolla::DenseArrayShape>()); return ShapeSizeReader{traverser, slot, SizeToShapeFn{last_field}}; } Traverser traverser; const FieldDescriptor* last_field; }; template <class T> struct DenseArrayReader { void operator()(const Message& m, FramePtr frame) const { std::vector<OptionalValue<T>> res; traverser.TraverseSubmessages(m, last_push_back_fn, &res); frame.Set(slot, ::arolla::CreateDenseArray<T>(res)); } Traverser traverser; FrameLayout::Slot<::arolla::DenseArray<T>> slot; PushbackFn last_push_back_fn; }; template <class T> struct DenseArrayReaderFactory { absl::StatusOr<ProtoTypeReader::BoundReadFn> operator()( TypedSlot typed_slot) const { ASSIGN_OR_RETURN(auto slot, typed_slot.ToSlot<::arolla::DenseArray<T>>()); return DenseArrayReader<T>{traverser, slot, last_push_back_fn}; } Traverser traverser; PushbackFn last_push_back_fn; }; template <class CallBackFn> auto SwitchByProtoType(FieldDescriptor::Type type, CallBackFn callback, StringFieldType string_type) -> decltype(std::declval<CallBackFn>()(std::decay<int32_t>(), kProtoGetterInt32)) { switch (type) { case FieldDescriptor::TYPE_INT32: case FieldDescriptor::TYPE_SINT32: case FieldDescriptor::TYPE_SFIXED32: return callback(std::decay<int32_t>{}, kProtoGetterInt32); case FieldDescriptor::TYPE_INT64: case FieldDescriptor::TYPE_SINT64: case FieldDescriptor::TYPE_SFIXED64: return callback(std::decay<int64_t>{}, kProtoGetterInt64); case FieldDescriptor::TYPE_UINT32: case FieldDescriptor::TYPE_FIXED32: return callback(std::decay<int64_t>{}, kProtoGetterUInt32); case FieldDescriptor::TYPE_UINT64: case FieldDescriptor::TYPE_FIXED64: return callback(std::decay<uint64_t>{}, kProtoGetterUInt64); case FieldDescriptor::TYPE_DOUBLE: return callback(std::decay<double>{}, kProtoGetterDouble); case FieldDescriptor::TYPE_FLOAT: return callback(std::decay<float>{}, kProtoGetterFloat); case FieldDescriptor::TYPE_BOOL: return callback(std::decay<bool>{}, kProtoGetterBool); case FieldDescriptor::TYPE_STRING: { switch (string_type) { case StringFieldType::kText: return callback(std::decay<Text>{}, kProtoGetterString); case StringFieldType::kBytes: return callback(std::decay<Bytes>{}, kProtoGetterString); } } case FieldDescriptor::TYPE_BYTES: return callback(std::decay<Bytes>{}, kProtoGetterString); case FieldDescriptor::TYPE_ENUM: return callback(std::decay<int32_t>{}, kProtoGetterEnumValue); default: return absl::FailedPreconditionError( absl::StrCat("type ", type, " is not supported")); } } absl::Status VerifyFieldsAndAccessInfos( absl::Span<const FieldDescriptor* const> fields, const std::vector<ProtoFieldAccessInfo>& access_infos, bool allow_repeated = false) { if (fields.empty()) { return absl::FailedPreconditionError("fields must be non empty"); } if (fields.size() != access_infos.size()) { return absl::FailedPreconditionError( "fields and access_info must be same size if access_info is not empty"); } for (size_t i = 0; i != fields.size(); ++i) { RETURN_IF_ERROR(CheckAccessInfo(fields[i], access_infos[i], allow_repeated, i + 1 == fields.size())); } return absl::OkStatus(); } class OptionalReaderCallback { public: OptionalReaderCallback(absl::Span<const FieldDescriptor* const> fields, absl::Span<const ProtoFieldAccessInfo> access_infos) : fields_(fields), access_infos_(access_infos), traverser_( std::vector(fields_.begin(), fields_.end() - 1), std::vector(access_infos_.begin(), access_infos_.end() - 1)) {} template <class ResultMetaFn, class ProtoFieldGetter> absl::StatusOr<std::unique_ptr<ProtoTypeReader>> operator()( ResultMetaFn, ProtoFieldGetter last_field_getter) const { using ResultT = typename ResultMetaFn::type; ProtoFieldAccessInfo last_access_info = access_infos_.back(); const FieldDescriptor* last_field = fields_.back(); ReadValueFn read_fn; if (last_field->is_repeated()) { DCHECK( std::holds_alternative<RepeatedFieldIndexAccess>(last_access_info)); read_fn = ByIndexReader<ResultT, ProtoFieldGetter>{ last_field, *std::get_if<RepeatedFieldIndexAccess>(&last_access_info), last_field_getter}; } else { read_fn = FieldReader<ResultT, ProtoFieldGetter>{last_field, last_field_getter}; } return std::make_unique<ProtoTypeReader>( GetOptionalQType<ResultT>(), OptionalReaderFactory<ResultT>{traverser_, read_fn}); } absl::StatusOr<std::unique_ptr<ProtoTypeReader>> CreateSizeAccessor() const { ProtoFieldAccessInfo last_access_info = access_infos_.back(); if (!std::holds_alternative<RepeatedFieldSizeAccess>(last_access_info)) { return absl::InternalError("size accessor creation expected"); } const FieldDescriptor* last_field = fields_.back(); return std::make_unique<ProtoTypeReader>( GetQType<DenseArrayShape>(), ShapeSizeReaderFactory{traverser_, last_field}); } private: absl::Span<const FieldDescriptor* const> fields_; absl::Span<const ProtoFieldAccessInfo> access_infos_; Traverser traverser_; }; class DenseArrayReaderCallback { public: DenseArrayReaderCallback(absl::Span<const FieldDescriptor* const> fields, absl::Span<const ProtoFieldAccessInfo> access_infos) : fields_(fields), access_infos_(access_infos), traverser_( std::vector(fields_.begin(), fields_.end() - 1), std::vector(access_infos_.begin(), access_infos_.end() - 1)) {} absl::StatusOr<std::unique_ptr<ProtoTypeReader>> CreateSizeAccessor() const { ProtoFieldAccessInfo last_access_info = access_infos_.back(); if (!std::holds_alternative<RepeatedFieldSizeAccess>(last_access_info)) { return absl::InternalError("size accessor creation expected"); } const FieldDescriptor* last_field = fields_.back(); return std::make_unique<ProtoTypeReader>( GetDenseArrayQType<arolla_size_t>(), ArraySizeReaderFactory{traverser_, last_field}); } template <class ResultMetaFn, class ProtoFieldGetter> absl::StatusOr<std::unique_ptr<ProtoTypeReader>> operator()( ResultMetaFn, ProtoFieldGetter last_field_getter) const { using ResultT = typename ResultMetaFn::type; using DenseArrayResultT = ::arolla::DenseArray<ResultT>; ProtoFieldAccessInfo last_access_info = access_infos_.back(); const FieldDescriptor* last_field = fields_.back(); PushbackFn pb_fn; if (std::holds_alternative<RepeatedFieldAccess>(last_access_info)) { pb_fn = ManyPushBackFn<ResultT, ProtoFieldGetter>{last_field, last_field_getter}; } else if (std::holds_alternative<RepeatedFieldSizeAccess>( last_access_info)) { return absl::InternalError( "size accessor must be created with CreateSizeAccessor"); } else if (last_field->is_repeated()) { DCHECK( std::holds_alternative<RepeatedFieldIndexAccess>(last_access_info)); pb_fn = SinglePushBackFn<ResultT>{ByIndexReader<ResultT, ProtoFieldGetter>{ last_field, *std::get_if<RepeatedFieldIndexAccess>(&last_access_info), last_field_getter}}; } else { pb_fn = SinglePushBackFn<ResultT>{FieldReader<ResultT, ProtoFieldGetter>{ last_field, last_field_getter}}; } return std::make_unique<ProtoTypeReader>( GetQType<DenseArrayResultT>(), DenseArrayReaderFactory<ResultT>{traverser_, pb_fn}); } private: absl::Span<const FieldDescriptor* const> fields_; absl::Span<const ProtoFieldAccessInfo> access_infos_; Traverser traverser_; }; } namespace arolla::proto { absl::StatusOr<std::unique_ptr<ProtoTypeReader>> ProtoTypeReader::CreateOptionalReader( absl::Span<const FieldDescriptor* const> fields, std::vector<ProtoFieldAccessInfo> access_infos, proto::StringFieldType string_type) { RETURN_IF_ERROR(VerifyFieldsAndAccessInfos(fields, access_infos)); const FieldDescriptor* last_field = fields.back(); return SwitchByProtoType( last_field->type(), OptionalReaderCallback(fields, std::move(access_infos)), string_type); } absl::StatusOr<std::unique_ptr<ProtoTypeReader>> ProtoTypeReader::CreateDenseArrayShapeReader( absl::Span<const FieldDescriptor* const> fields, std::vector<ProtoFieldAccessInfo> access_infos, proto::StringFieldType string_type) { RETURN_IF_ERROR(VerifyFieldsAndAccessInfos(fields, access_infos, true)); return OptionalReaderCallback(fields, std::move(access_infos)) .CreateSizeAccessor(); } absl::StatusOr<std::unique_ptr<ProtoTypeReader>> ProtoTypeReader::CreateDenseArrayReader( absl::Span<const FieldDescriptor* const> fields, std::vector<ProtoFieldAccessInfo> access_infos, proto::StringFieldType string_type) { RETURN_IF_ERROR(VerifyFieldsAndAccessInfos(fields, access_infos, true)); const FieldDescriptor* last_field = fields.back(); auto last_access = access_infos.back(); DenseArrayReaderCallback callback(fields, std::move(access_infos)); if (std::holds_alternative<proto::RepeatedFieldSizeAccess>(last_access)) { return callback.CreateSizeAccessor(); } else { return SwitchByProtoType(last_field->type(), callback, string_type); } } }
#include "arolla/proto/reflection/reader.h" #include <cstddef> #include <cstdint> #include <optional> #include <string> #include <utility> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "absl/strings/str_join.h" #include "google/protobuf/descriptor.h" #include "arolla/dense_array/dense_array.h" #include "arolla/dense_array/qtype/types.h" #include "arolla/memory/frame.h" #include "arolla/memory/memory_allocation.h" #include "arolla/memory/optional_value.h" #include "arolla/proto/test.pb.h" #include "arolla/proto/types.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/typed_slot.h" #include "arolla/util/bytes.h" #include "arolla/util/testing/status_matchers_backport.h" #include "arolla/util/text.h" #include "arolla/util/status_macros_backport.h" namespace arolla::proto { namespace { using ::arolla::testing::IsOkAndHolds; using ::testing::ElementsAre; using ::testing::IsEmpty; using ProtoRoot = ::testing_namespace::Root; const auto* kRootDescr = ProtoRoot::descriptor(); auto BuildDescriptorSequence(const std::vector<std::string>& field_names) { std::vector<const google::protobuf::FieldDescriptor*> fields; const google::protobuf::Descriptor* root_descriptor = kRootDescr; for (const auto& name : field_names) { CHECK(root_descriptor != nullptr) << "incorrect test fields: " << absl::StrJoin(field_names, ","); const google::protobuf::FieldDescriptor* field_descriptor = root_descriptor->FindFieldByName(name); fields.push_back(field_descriptor); root_descriptor = field_descriptor->message_type(); } return fields; } template <class T> absl::StatusOr<T> ReadValue(const ProtoTypeReader& reader, const google::protobuf::Message& m, T garbage = T{}) { if (reader.qtype() != GetQType<T>()) { return absl::FailedPreconditionError( absl::StrFormat("QType mismatch: expected %s, found %s", GetQType<T>()->name(), reader.qtype()->name())); } FrameLayout::Builder layout_builder; auto slot = layout_builder.AddSlot<T>(); ASSIGN_OR_RETURN(auto read_fn, reader.BindReadFn(TypedSlot::FromSlot(slot))); FrameLayout memory_layout = std::move(layout_builder).Build(); MemoryAllocation alloc(&memory_layout); FramePtr frame = alloc.frame(); frame.Set(slot, garbage); read_fn(m, frame); return frame.Get(slot); } template <class T> absl::StatusOr<OptionalValue<T>> ReadOptionalValue( const ProtoTypeReader& reader, const google::protobuf::Message& m) { return ReadValue<OptionalValue<T>>(reader, m, T{}); } template <class T> absl::StatusOr<OptionalValue<T>> ReadOptionalTopLevelValue( const std::string& field_name, const google::protobuf::Message& m) { ASSIGN_OR_RETURN(auto reader, ProtoTypeReader::CreateOptionalReader( {kRootDescr->FindFieldByName(field_name)}, {{}})); return ReadValue<OptionalValue<T>>(*reader, m); } TEST(TopLevelOptionalReaderTest, All) { ::testing_namespace::Root m; EXPECT_THAT(ReadOptionalTopLevelValue<int32_t>("x", m), IsOkAndHolds(std::nullopt)); m.set_x(19); EXPECT_THAT(ReadOptionalTopLevelValue<int32_t>("x", m), IsOkAndHolds(19)); m.set_x_enum(ProtoRoot::SECOND_VALUE); EXPECT_THAT(ReadOptionalTopLevelValue<int32_t>("x_enum", m), IsOkAndHolds(ProtoRoot::SECOND_VALUE)); m.set_str("19"); EXPECT_THAT(ReadOptionalTopLevelValue<Text>("str", m), IsOkAndHolds(Text{"19"})); m.set_raw_bytes("19"); EXPECT_THAT(ReadOptionalTopLevelValue<Bytes>("raw_bytes", m), IsOkAndHolds(Bytes{"19"})); m.set_x_int64(19); EXPECT_THAT(ReadOptionalTopLevelValue<int64_t>("x_int64", m), IsOkAndHolds(19)); m.set_x_uint32(19); EXPECT_THAT(ReadOptionalTopLevelValue<int64_t>("x_uint32", m), IsOkAndHolds(19)); m.set_x_uint64(19); EXPECT_THAT(ReadOptionalTopLevelValue<uint64_t>("x_uint64", m), IsOkAndHolds(19)); m.set_x_float(19.0f); EXPECT_THAT(ReadOptionalTopLevelValue<float>("x_float", m), IsOkAndHolds(19.0f)); m.set_x_double(19.0); EXPECT_THAT(ReadOptionalTopLevelValue<double>("x_double", m), IsOkAndHolds(19.0)); m.set_x_fixed64(19); EXPECT_THAT(ReadOptionalTopLevelValue<uint64_t>("x_fixed64", m), IsOkAndHolds(19)); { ASSERT_OK_AND_ASSIGN(auto reader, ProtoTypeReader::CreateOptionalReader( {kRootDescr->FindFieldByName("raw_bytes")}, {{}}, StringFieldType::kBytes)); m.set_raw_bytes("19"); EXPECT_THAT(ReadOptionalValue<Bytes>(*reader, m), IsOkAndHolds(Bytes("19"))); } { ASSERT_OK_AND_ASSIGN(auto reader, ProtoTypeReader::CreateOptionalReader( {kRootDescr->FindFieldByName("str")}, {{}}, StringFieldType::kBytes)); m.set_str("19"); EXPECT_THAT(ReadOptionalValue<Bytes>(*reader, m), IsOkAndHolds(Bytes("19"))); } } template <class T> absl::StatusOr<::arolla::DenseArray<T>> ReadDenseArrayValue( const ProtoTypeReader& reader, const google::protobuf::Message& m) { return ReadValue<::arolla::DenseArray<T>>( reader, m, ::arolla::CreateDenseArray<T>({T{}, T{}})); } template <class T> absl::StatusOr<::arolla::DenseArray<T>> ReadDenseArrayValue( const std::vector<std::string>& field_names, std::vector<ProtoFieldAccessInfo> access_infos, const google::protobuf::Message& m) { ASSIGN_OR_RETURN(auto reader, ProtoTypeReader::CreateDenseArrayReader( BuildDescriptorSequence(field_names), access_infos)); return ReadDenseArrayValue<T>(*reader, m); } TEST(ProtoTypeReader, CreateTopLevelDenseArrayReaderNonRepeatedField) { ::testing_namespace::Root m; EXPECT_THAT(ReadDenseArrayValue<int32_t>({"x"}, {{}}, m), IsOkAndHolds(ElementsAre(std::nullopt))); m.set_x(19); EXPECT_THAT(ReadDenseArrayValue<int32_t>({"x"}, {{}}, m), IsOkAndHolds(ElementsAre(19))); m.set_str("19"); EXPECT_THAT(ReadDenseArrayValue<Text>({"str"}, {{}}, m), IsOkAndHolds(ElementsAre("19"))); m.set_raw_bytes("19"); EXPECT_THAT(ReadDenseArrayValue<Bytes>({"raw_bytes"}, {{}}, m), IsOkAndHolds(ElementsAre("19"))); m.set_x_int64(19); EXPECT_THAT(ReadDenseArrayValue<int64_t>({"x_int64"}, {{}}, m), IsOkAndHolds(ElementsAre(19))); m.set_x_uint32(19); EXPECT_THAT(ReadDenseArrayValue<int64_t>({"x_uint32"}, {{}}, m), IsOkAndHolds(ElementsAre(19))); m.set_x_uint64(19); EXPECT_THAT(ReadDenseArrayValue<uint64_t>({"x_uint64"}, {{}}, m), IsOkAndHolds(ElementsAre(19))); m.set_x_float(19.0f); EXPECT_THAT(ReadDenseArrayValue<float>({"x_float"}, {{}}, m), IsOkAndHolds(ElementsAre(19.0f))); m.set_x_double(19.0); EXPECT_THAT(ReadDenseArrayValue<double>({"x_double"}, {{}}, m), IsOkAndHolds(ElementsAre(19.0))); { ASSERT_OK_AND_ASSIGN(auto reader, ProtoTypeReader::CreateDenseArrayReader( {kRootDescr->FindFieldByName("raw_bytes")}, {{}}, StringFieldType::kBytes)); m.set_raw_bytes("19"); EXPECT_THAT(ReadDenseArrayValue<Bytes>(*reader, m), IsOkAndHolds(ElementsAre("19"))); } { ASSERT_OK_AND_ASSIGN(auto reader, ProtoTypeReader::CreateDenseArrayReader( {kRootDescr->FindFieldByName("str")}, {{}}, StringFieldType::kBytes)); m.set_str("19"); EXPECT_THAT(ReadDenseArrayValue<Bytes>(*reader, m), IsOkAndHolds(ElementsAre("19"))); } } template <class T> absl::StatusOr<OptionalValue<T>> ReadOptionalValue( const std::vector<std::string>& field_names, std::vector<ProtoFieldAccessInfo> access_infos, const google::protobuf::Message& m) { std::vector<const google::protobuf::FieldDescriptor*> fields = BuildDescriptorSequence(field_names); ASSIGN_OR_RETURN(auto reader, ProtoTypeReader::CreateOptionalReader(fields, access_infos)); return ReadValue<OptionalValue<T>>(*reader, m); } template <class T> absl::StatusOr<OptionalValue<T>> ReadOptionalValue( const std::vector<std::string>& field_names, const google::protobuf::Message& m) { return ReadOptionalValue<T>( field_names, std::vector<ProtoFieldAccessInfo>(field_names.size()), m); } TEST(ProtoTypeReader, CreateInnerOptionalReader) { ::testing_namespace::Root m; EXPECT_THAT(ReadOptionalValue<int32_t>({"inner", "a"}, m), IsOkAndHolds(std::nullopt)); m.mutable_inner()->set_a(19); EXPECT_THAT(ReadOptionalValue<int32_t>({"inner", "a"}, m), IsOkAndHolds(19)); EXPECT_THAT(ReadOptionalValue<int32_t>({"inner", "inner2", "z"}, m), IsOkAndHolds(std::nullopt)); m.mutable_inner()->mutable_inner2(); EXPECT_THAT(ReadOptionalValue<int32_t>({"inner", "inner2", "z"}, m), IsOkAndHolds(std::nullopt)); m.mutable_inner()->mutable_inner2()->set_z(19); EXPECT_THAT(ReadOptionalValue<int32_t>({"inner", "inner2", "z"}, m), IsOkAndHolds(19)); } template <class T> absl::StatusOr<OptionalValue<T>> ReadOptionalTopLevelFromRepeatedValue( const std::string& field_name, const google::protobuf::Message& m, size_t index = 0) { return ReadOptionalValue<T>({field_name}, {RepeatedFieldIndexAccess{index}}, m); } TEST(ProtoTypeReader, CreateRepeatedIndexAccessOptionalReader) { ::testing_namespace::Root m; auto read_ys = [](const auto& m) { return ReadOptionalValue<int32_t>({"ys"}, {RepeatedFieldIndexAccess{1}}, m); }; EXPECT_THAT(read_ys(m), IsOkAndHolds(std::nullopt)); m.add_ys(89); EXPECT_THAT(read_ys(m), IsOkAndHolds(std::nullopt)); m.add_ys(77); EXPECT_THAT(read_ys(m), IsOkAndHolds(77)); auto read_inners_a = [](const auto& m) { return ReadOptionalValue<int32_t>({"inners", "a"}, {RepeatedFieldIndexAccess{1}, {}}, m); }; EXPECT_THAT(read_inners_a(m), IsOkAndHolds(std::nullopt)); m.add_inners(); EXPECT_THAT(read_inners_a(m), IsOkAndHolds(std::nullopt)); m.add_inners()->set_a(7); EXPECT_THAT(read_inners_a(m), IsOkAndHolds(7)); auto read_inners_as = [](const auto& m) { return ReadOptionalValue<int32_t>( {"inners", "as"}, {RepeatedFieldIndexAccess{1}, RepeatedFieldIndexAccess{1}}, m); }; m.mutable_inners(1)->add_as(0); EXPECT_THAT(read_inners_as(m), IsOkAndHolds(std::nullopt)); m.mutable_inners(1)->add_as(57); EXPECT_THAT(read_inners_as(m), IsOkAndHolds(57)); *m.add_repeated_str() = "19"; EXPECT_THAT(ReadOptionalTopLevelFromRepeatedValue<Text>("repeated_str", m), IsOkAndHolds(Text("19"))); *m.add_repeated_raw_bytes() = "19"; EXPECT_THAT( ReadOptionalTopLevelFromRepeatedValue<Bytes>("repeated_raw_bytes", m), IsOkAndHolds(Bytes("19"))); m.add_repeated_floats(19.0f); EXPECT_THAT( ReadOptionalTopLevelFromRepeatedValue<float>("repeated_floats", m), IsOkAndHolds(19.0f)); m.add_repeated_doubles(19.0); EXPECT_THAT( ReadOptionalTopLevelFromRepeatedValue<double>("repeated_doubles", m), IsOkAndHolds(19.0)); m.add_repeated_int32s(19); EXPECT_THAT(ReadOptionalTopLevelFromRepeatedValue<int>("repeated_int32s", m), IsOkAndHolds(19)); m.add_repeated_int64s(19); EXPECT_THAT( ReadOptionalTopLevelFromRepeatedValue<int64_t>("repeated_int64s", m), IsOkAndHolds(19)); m.add_repeated_uint32s(19); EXPECT_THAT( ReadOptionalTopLevelFromRepeatedValue<int64_t>("repeated_uint32s", m), IsOkAndHolds(19)); m.add_repeated_uint64s(19); EXPECT_THAT( ReadOptionalTopLevelFromRepeatedValue<uint64_t>("repeated_uint64s", m), IsOkAndHolds(19)); m.add_repeated_bools(true); EXPECT_THAT(ReadOptionalTopLevelFromRepeatedValue<bool>("repeated_bools", m), IsOkAndHolds(true)); m.add_repeated_enums(ProtoRoot::SECOND_VALUE); EXPECT_THAT(ReadOptionalTopLevelFromRepeatedValue<int>("repeated_enums", m), IsOkAndHolds(ProtoRoot::SECOND_VALUE)); } template <class T> absl::StatusOr<::arolla::DenseArray<T>> ReadDenseArrayTopLevelValue( const std::string& field_name, const google::protobuf::Message& m) { return ReadDenseArrayValue<T>({field_name}, {RepeatedFieldAccess{}}, m); } TEST(ProtoTypeReader, CreateRepeatedAccessOptionalReader) { ::testing_namespace::Root m; EXPECT_THAT(ReadDenseArrayTopLevelValue<int>("ys", m), IsOkAndHolds(IsEmpty())); m.add_ys(89); m.add_ys(57); EXPECT_THAT(ReadDenseArrayTopLevelValue<int>("ys", m), IsOkAndHolds(ElementsAre(89, 57))); auto read_inners_a = [](const auto& m) { return ReadDenseArrayValue<int32_t>({"inners", "a"}, {RepeatedFieldAccess{}, {}}, m); }; EXPECT_THAT(read_inners_a(m), IsOkAndHolds(IsEmpty())); m.add_inners(); EXPECT_THAT(read_inners_a(m), IsOkAndHolds(ElementsAre(std::nullopt))); m.add_inners()->set_a(7); EXPECT_THAT(read_inners_a(m), IsOkAndHolds(ElementsAre(std::nullopt, 7))); m.add_inners()->set_a(37); EXPECT_THAT(read_inners_a(m), IsOkAndHolds(ElementsAre(std::nullopt, 7, 37))); auto read_inners_as = [](const auto& m) { return ReadDenseArrayValue<int32_t>( {"inners", "as"}, {RepeatedFieldAccess{}, RepeatedFieldAccess{}}, m); }; EXPECT_THAT(read_inners_as(m), IsOkAndHolds(IsEmpty())); m.mutable_inners(0)->add_as(0); m.mutable_inners(0)->add_as(57); m.mutable_inners(2)->add_as(19); m.mutable_inners(2)->add_as(3); m.mutable_inners(2)->add_as(17); EXPECT_THAT(read_inners_as(m), IsOkAndHolds(ElementsAre(0, 57, 19, 3, 17))); *m.add_repeated_str() = "19"; *m.add_repeated_str() = "17"; EXPECT_THAT(ReadDenseArrayTopLevelValue<Text>("repeated_str", m), IsOkAndHolds(ElementsAre("19", "17"))); *m.add_repeated_raw_bytes() = "17"; *m.add_repeated_raw_bytes() = "19"; EXPECT_THAT(ReadDenseArrayTopLevelValue<Bytes>("repeated_raw_bytes", m), IsOkAndHolds(ElementsAre("17", "19"))); m.add_repeated_floats(19.0f); m.add_repeated_floats(17.0f); EXPECT_THAT(ReadDenseArrayTopLevelValue<float>("repeated_floats", m), IsOkAndHolds(ElementsAre(19.0f, 17.0f))); m.add_repeated_doubles(19.0); m.add_repeated_doubles(17.0); EXPECT_THAT(ReadDenseArrayTopLevelValue<double>("repeated_doubles", m), IsOkAndHolds(ElementsAre(19.0, 17.0))); m.add_repeated_int32s(19); m.add_repeated_int32s(17); EXPECT_THAT(ReadDenseArrayTopLevelValue<int>("repeated_int32s", m), IsOkAndHolds(ElementsAre(19, 17))); m.add_repeated_int64s(19); m.add_repeated_int64s(17); EXPECT_THAT(ReadDenseArrayTopLevelValue<int64_t>("repeated_int64s", m), IsOkAndHolds(ElementsAre(19, 17))); m.add_repeated_uint32s(19); m.add_repeated_uint32s(17); EXPECT_THAT(ReadDenseArrayTopLevelValue<int64_t>("repeated_uint32s", m), IsOkAndHolds(ElementsAre(19, 17))); m.add_repeated_uint64s(19); m.add_repeated_uint64s(17); EXPECT_THAT(ReadDenseArrayTopLevelValue<uint64_t>("repeated_uint64s", m), IsOkAndHolds(ElementsAre(19, 17))); m.add_repeated_bools(true); m.add_repeated_bools(false); EXPECT_THAT(ReadDenseArrayTopLevelValue<bool>("repeated_bools", m), IsOkAndHolds(ElementsAre(true, false))); m.add_repeated_enums(ProtoRoot::SECOND_VALUE); m.add_repeated_enums(ProtoRoot::DEFAULT); EXPECT_THAT( ReadDenseArrayTopLevelValue<int>("repeated_enums", m), IsOkAndHolds(ElementsAre(ProtoRoot::SECOND_VALUE, ProtoRoot::DEFAULT))); } absl::StatusOr<::arolla::DenseArray<proto::arolla_size_t>> ReadTopLevelSizeAsArray(const std::string& field_name, const google::protobuf::Message& m) { return ReadDenseArrayValue<proto::arolla_size_t>( {field_name}, {RepeatedFieldSizeAccess{}}, m); } absl::StatusOr<::arolla::DenseArrayShape> ReadTopLevelSizeAsShape( const std::string& field_name, const google::protobuf::Message& m) { ASSIGN_OR_RETURN(auto reader, ProtoTypeReader::CreateDenseArrayShapeReader( {kRootDescr->FindFieldByName(field_name)}, {RepeatedFieldSizeAccess{}})); return ReadValue<::arolla::DenseArrayShape>(*reader, m); } TEST(ProtoTypeReader, CreateRepeatedSizeAccessReader) { ::testing_namespace::Root m; EXPECT_THAT(ReadTopLevelSizeAsArray("ys", m), IsOkAndHolds(ElementsAre(0))); EXPECT_THAT(ReadTopLevelSizeAsShape("ys", m), IsOkAndHolds(DenseArrayShape{0})); m.add_ys(89); m.add_ys(57); EXPECT_THAT(ReadTopLevelSizeAsArray("ys", m), IsOkAndHolds(ElementsAre(2))); EXPECT_THAT(ReadTopLevelSizeAsShape("ys", m), IsOkAndHolds(DenseArrayShape{2})); EXPECT_THAT(ReadTopLevelSizeAsArray("inners", m), IsOkAndHolds(ElementsAre(0))); EXPECT_THAT(ReadTopLevelSizeAsShape("inners", m), IsOkAndHolds(DenseArrayShape{0})); m.add_inners(); EXPECT_THAT(ReadTopLevelSizeAsArray("inners", m), IsOkAndHolds(ElementsAre(1))); EXPECT_THAT(ReadTopLevelSizeAsShape("inners", m), IsOkAndHolds(DenseArrayShape{1})); m.add_inners(); EXPECT_THAT(ReadTopLevelSizeAsArray("inners", m), IsOkAndHolds(ElementsAre(2))); EXPECT_THAT(ReadTopLevelSizeAsShape("inners", m), IsOkAndHolds(DenseArrayShape{2})); m.clear_inners(); auto read_inners_as_size = [](const auto& m) { return ReadDenseArrayValue<proto::arolla_size_t>( {"inners", "as"}, {RepeatedFieldAccess{}, RepeatedFieldSizeAccess{}}, m); }; EXPECT_THAT(read_inners_as_size(m), IsOkAndHolds(IsEmpty())); m.add_inners(); m.mutable_inners(0)->add_as(0); m.mutable_inners(0)->add_as(57); m.add_inners(); m.add_inners(); m.mutable_inners(2)->add_as(19); m.mutable_inners(2)->add_as(3); m.mutable_inners(2)->add_as(17); EXPECT_THAT(read_inners_as_size(m), IsOkAndHolds(ElementsAre(2, 0, 3))); } } }
2,390
#ifndef AROLLA_DENSE_ARRAY_EDGE_H_ #define AROLLA_DENSE_ARRAY_EDGE_H_ #include <cstdint> #include <utility> #include "absl/status/statusor.h" #include "absl/types/span.h" #include "arolla/dense_array/dense_array.h" #include "arolla/memory/raw_buffer_factory.h" #include "arolla/util/api.h" #include "arolla/util/fingerprint.h" namespace arolla { class AROLLA_API DenseArrayEdge { public: DenseArrayEdge() : edge_type_(MAPPING), parent_size_(0), child_size_(0) {} static absl::StatusOr<DenseArrayEdge> FromSplitPoints( DenseArray<int64_t> split_points); static absl::StatusOr<DenseArrayEdge> FromMapping(DenseArray<int64_t> mapping, int64_t parent_size); static absl::StatusOr<DenseArrayEdge> FromUniformGroups( int64_t parent_size, int64_t group_size, RawBufferFactory& buf_factory = *GetHeapBufferFactory()); static DenseArrayEdge UnsafeFromMapping(DenseArray<int64_t> mapping, int64_t parent_size); static DenseArrayEdge UnsafeFromSplitPoints(DenseArray<int64_t> split_points); static absl::StatusOr<DenseArrayEdge> ComposeEdges( absl::Span<const DenseArrayEdge> edges, RawBufferFactory& buf_factory = *GetHeapBufferFactory()); enum EdgeType { MAPPING = 1, SPLIT_POINTS = 2, }; EdgeType edge_type() const { return edge_type_; } int64_t parent_size() const { return parent_size_; } int64_t child_size() const { return child_size_; } const DenseArray<int64_t>& edge_values() const { return edge_values_; } absl::StatusOr<DenseArrayEdge> ToSplitPointsEdge( RawBufferFactory& buf_factory = *GetHeapBufferFactory()) const; DenseArrayEdge ToMappingEdge( RawBufferFactory& buf_factory = *GetHeapBufferFactory()) const; bool IsEquivalentTo(const DenseArrayEdge& other) const; private: friend class ArrayEdge; DenseArrayEdge(EdgeType edge_values_type, int64_t parent_size, int64_t child_size, DenseArray<int64_t> edge_values) : edge_type_(edge_values_type), parent_size_(parent_size), child_size_(child_size), edge_values_(std::move(edge_values)) {} EdgeType edge_type_; int64_t parent_size_; int64_t child_size_; DenseArray<int64_t> edge_values_; }; class AROLLA_API DenseArrayGroupScalarEdge { public: DenseArrayGroupScalarEdge() : size_(0) {} explicit DenseArrayGroupScalarEdge(int64_t size) : size_{size} {} int64_t child_size() const { return size_; } private: int64_t size_; }; AROLLA_DECLARE_FINGERPRINT_HASHER_TRAITS(DenseArrayEdge); AROLLA_DECLARE_FINGERPRINT_HASHER_TRAITS(DenseArrayGroupScalarEdge); } #endif #include "arolla/dense_array/edge.h" #include <algorithm> #include <cstddef> #include <cstdint> #include <utility> #include <vector> #include "absl/base/optimization.h" #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "absl/types/span.h" #include "arolla/dense_array/dense_array.h" #include "arolla/memory/buffer.h" #include "arolla/memory/raw_buffer_factory.h" #include "arolla/util/fingerprint.h" #include "arolla/util/status_macros_backport.h" namespace arolla { namespace { absl::StatusOr<DenseArrayEdge> ComposeMappingEdge( absl::Span<const DenseArrayEdge> edges, RawBufferFactory& buf_factory) { DCHECK_GE(edges.size(), 2); DenseArray<int64_t> mapping = edges.back().ToMappingEdge(buf_factory).edge_values(); for (int i = edges.size() - 2; i >= 0; --i) { const auto mapping_edge = edges[i].ToMappingEdge(buf_factory); DenseArrayBuilder<int64_t> bldr(edges.back().child_size(), &buf_factory); mapping.ForEachPresent([&bldr, &mapping_edge](int64_t id, int64_t value) { bldr.Set(id, mapping_edge.edge_values()[value]); }); mapping = std::move(bldr).Build(); } return DenseArrayEdge::UnsafeFromMapping(std::move(mapping), edges.front().parent_size()); } absl::StatusOr<DenseArrayEdge> ComposeSplitPointsEdge( absl::Span<const DenseArrayEdge> edges, RawBufferFactory& buf_factory) { DCHECK_GE(edges.size(), 2); Buffer<int64_t>::Builder bldr(edges.front().edge_values().size(), &buf_factory); auto mut_bldr_span = bldr.GetMutableSpan(); auto previous_split_points = edges.front().edge_values().values.span(); for (size_t i = 1; i < edges.size(); ++i) { auto split_points = edges[i].edge_values().values.span(); for (size_t j = 0; j < mut_bldr_span.size(); ++j) { mut_bldr_span[j] = split_points[previous_split_points[j]]; } previous_split_points = mut_bldr_span; } return DenseArrayEdge::UnsafeFromSplitPoints({std::move(bldr).Build()}); } } absl::StatusOr<DenseArrayEdge> DenseArrayEdge::FromSplitPoints( DenseArray<int64_t> split_points) { if (!split_points.IsFull()) { return absl::InvalidArgumentError("split points must be full"); } if (split_points.empty()) { return absl::InvalidArgumentError( "split points array must have at least 1 element"); } if (split_points.values[0] != 0) { return absl::InvalidArgumentError( "split points array must have first element equal to 0"); } int64_t parent_size = split_points.size() - 1; int64_t child_size = split_points.values.back(); if (!std::is_sorted(split_points.values.begin(), split_points.values.end())) { return absl::InvalidArgumentError("split points must be sorted"); } return DenseArrayEdge(DenseArrayEdge::SPLIT_POINTS, parent_size, child_size, std::move(split_points)); } absl::StatusOr<DenseArrayEdge> DenseArrayEdge::FromMapping( DenseArray<int64_t> mapping, int64_t parent_size) { if (parent_size < 0) { return absl::InvalidArgumentError("parent_size can not be negative"); } int64_t max_value = -1; bool negative = false; mapping.ForEach([&max_value, &negative](int64_t, bool present, int64_t v) { if (present) { max_value = std::max(max_value, v); if (v < 0) negative = true; } }); if (negative) { return absl::InvalidArgumentError("mapping can't contain negative values"); } if (max_value >= parent_size) { return absl::InvalidArgumentError(absl::StrFormat( "parent_size=%d, but parent id %d is used", parent_size, max_value)); } return UnsafeFromMapping(std::move(mapping), parent_size); } absl::StatusOr<DenseArrayEdge> DenseArrayEdge::FromUniformGroups( int64_t parent_size, int64_t group_size, RawBufferFactory& buf_factory) { if (parent_size < 0 || group_size < 0) { return absl::InvalidArgumentError( "parent_size and group_size cannot be negative"); } Buffer<int64_t>::Builder split_points_builder(parent_size + 1, &buf_factory); auto inserter = split_points_builder.GetInserter(); for (int64_t i = 0; i <= parent_size; ++i) inserter.Add(i * group_size); return UnsafeFromSplitPoints({std::move(split_points_builder).Build()}); } DenseArrayEdge DenseArrayEdge::UnsafeFromMapping(DenseArray<int64_t> mapping, int64_t parent_size) { int64_t child_size = mapping.size(); return DenseArrayEdge(DenseArrayEdge::MAPPING, parent_size, child_size, std::move(mapping)); } DenseArrayEdge DenseArrayEdge::UnsafeFromSplitPoints( DenseArray<int64_t> split_points) { int64_t parent_size = split_points.size() - 1; int64_t child_size = split_points.values.back(); return DenseArrayEdge(DenseArrayEdge::SPLIT_POINTS, parent_size, child_size, std::move(split_points)); } DenseArrayEdge DenseArrayEdge::ToMappingEdge( RawBufferFactory& buf_factory) const { switch (edge_type()) { case DenseArrayEdge::MAPPING: return *this; case DenseArrayEdge::SPLIT_POINTS: { Buffer<int64_t>::Builder bldr(child_size(), &buf_factory); int64_t* mapping = bldr.GetMutableSpan().begin(); const int64_t* splits = edge_values().values.begin(); for (int64_t parent_id = 0; parent_id < parent_size(); ++parent_id) { std::fill(mapping + splits[parent_id], mapping + splits[parent_id + 1], parent_id); } return DenseArrayEdge::UnsafeFromMapping({std::move(bldr).Build()}, parent_size()); } } ABSL_UNREACHABLE(); } absl::StatusOr<DenseArrayEdge> DenseArrayEdge::ToSplitPointsEdge( RawBufferFactory& buf_factory) const { if (edge_type() == DenseArrayEdge::SPLIT_POINTS) return *this; if (!edge_values().IsFull()) { return absl::InvalidArgumentError("expected a full mapping"); } Buffer<int64_t>::Builder split_points_builder(parent_size() + 1, &buf_factory); auto inserter = split_points_builder.GetInserter(); inserter.Add(0); int64_t current_bin = 0; auto values = edge_values().values.span(); for (size_t i = 0; i < values.size(); ++i) { DCHECK_LE(values[i], parent_size()); if (values[i] < current_bin) { return absl::InvalidArgumentError("expected a sorted mapping"); } for (; current_bin < values[i]; ++current_bin) inserter.Add(i); } for (; current_bin < parent_size(); ++current_bin) { inserter.Add(edge_values().size()); } return DenseArrayEdge::UnsafeFromSplitPoints( DenseArray<int64_t>{std::move(split_points_builder).Build()}); } bool DenseArrayEdge::IsEquivalentTo(const DenseArrayEdge& other) const { if (parent_size() != other.parent_size() || child_size() != other.child_size()) { return false; } if (edge_type() == other.edge_type()) { return ArraysAreEquivalent(edge_values(), other.edge_values()); } ASSIGN_OR_RETURN(auto this_edge, ToSplitPointsEdge(), _.With([](const auto&) { return false; })); ASSIGN_OR_RETURN(auto other_edge, other.ToSplitPointsEdge(), _.With([](const auto&) { return false; })); return ArraysAreEquivalent(this_edge.edge_values(), other_edge.edge_values()); } absl::StatusOr<DenseArrayEdge> DenseArrayEdge::ComposeEdges( absl::Span<const DenseArrayEdge> edges, RawBufferFactory& buf_factory) { if (edges.empty()) { return absl::InvalidArgumentError("at least one edge must be present"); } if (edges.size() == 1) return edges[0]; int64_t prior_child_size = edges[0].parent_size(); for (size_t i = 0; i < edges.size(); ++i) { if (edges[i].parent_size() != prior_child_size) { return absl::InvalidArgumentError( absl::StrFormat("incompatible edges: edges[%d].child_size (%d) != " "edges[%d].parent_size (%d)", i - 1, prior_child_size, i, edges[i].parent_size())); } prior_child_size = edges[i].child_size(); } std::vector<DenseArrayEdge> transformed_edges; transformed_edges.reserve(edges.size()); size_t i = 0; while (i < edges.size()) { size_t split_points_end = i; while (split_points_end < edges.size() && edges[split_points_end].edge_type() == DenseArrayEdge::SPLIT_POINTS) { split_points_end++; } if (split_points_end - i >= 2) { ASSIGN_OR_RETURN(auto composed_edge, ComposeSplitPointsEdge( absl::MakeSpan(edges.begin() + i, edges.begin() + split_points_end), buf_factory)); transformed_edges.push_back(std::move(composed_edge)); i = split_points_end; } else { transformed_edges.push_back(edges[i]); i++; } } if (transformed_edges.size() == 1) { return std::move(transformed_edges[0]); } else { return ComposeMappingEdge(transformed_edges, buf_factory); } } void FingerprintHasherTraits<DenseArrayEdge>::operator()( FingerprintHasher* hasher, const DenseArrayEdge& value) const { hasher->Combine(value.edge_type(), value.parent_size(), value.child_size(), value.edge_values()); } void FingerprintHasherTraits<DenseArrayGroupScalarEdge>::operator()( FingerprintHasher* hasher, const DenseArrayGroupScalarEdge& value) const { hasher->Combine(value.child_size()); } }
#include "arolla/dense_array/edge.h" #include <cstdint> #include <optional> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "absl/types/span.h" #include "arolla/dense_array/dense_array.h" #include "arolla/memory/buffer.h" #include "arolla/memory/raw_buffer_factory.h" #include "arolla/util/fingerprint.h" #include "arolla/util/testing/status_matchers_backport.h" using ::arolla::testing::StatusIs; using ::testing::ElementsAre; using ::testing::Eq; namespace arolla { namespace { TEST(DenseArrayEdgeTest, FromSplitPoints) { DenseArray<int64_t> split_points{CreateBuffer<int64_t>({0, 10, 20})}; ASSERT_OK_AND_ASSIGN(auto edge, DenseArrayEdge::FromSplitPoints(split_points)); EXPECT_THAT(edge.edge_type(), Eq(DenseArrayEdge::SPLIT_POINTS)); EXPECT_THAT(edge.edge_values().values, ElementsAre(0, 10, 20)); EXPECT_EQ(edge.parent_size(), 2); EXPECT_EQ(edge.child_size(), 20); } TEST(DenseArrayEdgeTest, FromSplitPointsEmptyGroup) { DenseArray<int64_t> split_points{CreateBuffer<int64_t>({0})}; ASSERT_OK_AND_ASSIGN(auto edge, DenseArrayEdge::FromSplitPoints(split_points)); EXPECT_THAT(edge.edge_type(), Eq(DenseArrayEdge::SPLIT_POINTS)); EXPECT_THAT(edge.edge_values().values, ElementsAre(0)); EXPECT_EQ(edge.parent_size(), 0); EXPECT_EQ(edge.child_size(), 0); } TEST(DenseArrayEdgeTest, FromSplitPointsNotFull) { auto split_points = CreateDenseArray<int64_t>({0, 3, std::nullopt, 10}); EXPECT_THAT(DenseArrayEdge::FromSplitPoints(split_points), StatusIs(absl::StatusCode::kInvalidArgument, ::testing::HasSubstr("split points must be full"))); } TEST(DenseArrayEdgeTest, FromSplitPointsTooFew) { EXPECT_THAT(DenseArrayEdge::FromSplitPoints(DenseArray<int64_t>()), StatusIs(absl::StatusCode::kInvalidArgument, ::testing::HasSubstr( "split points array must have at least 1 element"))); } TEST(DenseArrayEdgeTest, FromSplitPointsInBadOrder) { EXPECT_THAT( DenseArrayEdge::FromSplitPoints({CreateBuffer<int64_t>({10, 20, 30})}), StatusIs(absl::StatusCode::kInvalidArgument, ::testing::HasSubstr( "split points array must have first element equal to 0"))); EXPECT_THAT( DenseArrayEdge::FromSplitPoints({CreateBuffer<int64_t>({0, 40, 10})}), StatusIs(absl::StatusCode::kInvalidArgument, ::testing::HasSubstr("split points must be sorted"))); } TEST(DenseArrayEdgeTest, FromMapping) { DenseArray<int64_t> mapping{ CreateBuffer<int64_t>({0, 1, 2, 0, 1, 2, 0, 1, 2})}; DenseArray<int64_t> bad_mapping{ CreateBuffer<int64_t>({0, -1, 2, 0, 1, 2, 0, 1, 2})}; EXPECT_THAT( DenseArrayEdge::FromMapping(mapping, -1), StatusIs(absl::StatusCode::kInvalidArgument, ::testing::HasSubstr("parent_size can not be negative"))); EXPECT_THAT( DenseArrayEdge::FromMapping(mapping, 2), StatusIs(absl::StatusCode::kInvalidArgument, ::testing::HasSubstr("parent_size=2, but parent id 2 is used"))); EXPECT_THAT( DenseArrayEdge::FromMapping(bad_mapping, 3), StatusIs(absl::StatusCode::kInvalidArgument, ::testing::HasSubstr("mapping can't contain negative values"))); ASSERT_OK_AND_ASSIGN(auto edge, DenseArrayEdge::FromMapping(mapping, 3)); EXPECT_THAT(edge.edge_type(), Eq(DenseArrayEdge::MAPPING)); EXPECT_THAT(edge.edge_values().values, Eq(mapping.values)); EXPECT_EQ(edge.parent_size(), 3); EXPECT_EQ(edge.child_size(), 9); } TEST(DenseArrayEdgeTest, FromUniformGroups) { { ASSERT_OK_AND_ASSIGN(auto edge, DenseArrayEdge::FromUniformGroups(0, 5)); EXPECT_THAT(edge.edge_type(), DenseArrayEdge::SPLIT_POINTS); EXPECT_EQ(edge.parent_size(), 0); EXPECT_EQ(edge.child_size(), 0); EXPECT_THAT(edge.edge_values(), ElementsAre(0)); } { ASSERT_OK_AND_ASSIGN(auto edge, DenseArrayEdge::FromUniformGroups(3, 0)); EXPECT_THAT(edge.edge_type(), DenseArrayEdge::SPLIT_POINTS); EXPECT_EQ(edge.parent_size(), 3); EXPECT_EQ(edge.child_size(), 0); EXPECT_THAT(edge.edge_values(), ElementsAre(0, 0, 0, 0)); } { ASSERT_OK_AND_ASSIGN(auto edge, DenseArrayEdge::FromUniformGroups(3, 4)); EXPECT_THAT(edge.edge_type(), DenseArrayEdge::SPLIT_POINTS); EXPECT_EQ(edge.parent_size(), 3); EXPECT_EQ(edge.child_size(), 12); EXPECT_THAT(edge.edge_values(), ElementsAre(0, 4, 8, 12)); } { EXPECT_THAT(DenseArrayEdge::FromUniformGroups(-1, 3), StatusIs(absl::StatusCode::kInvalidArgument, "parent_size and group_size cannot be negative")); EXPECT_THAT(DenseArrayEdge::FromUniformGroups(3, -1), StatusIs(absl::StatusCode::kInvalidArgument, "parent_size and group_size cannot be negative")); } { ASSERT_OK_AND_ASSIGN(auto edge, DenseArrayEdge::FromUniformGroups(1, 1)); EXPECT_TRUE(edge.edge_values().values.is_owner()); } { UnsafeArenaBufferFactory arena{128}; ASSERT_OK_AND_ASSIGN(auto edge, DenseArrayEdge::FromUniformGroups(1, 1, arena)); EXPECT_FALSE(edge.edge_values().values.is_owner()); } } TEST(DenseArrayEdgeTest, DefaultEdge) { DenseArrayEdge edge; EXPECT_THAT(edge.edge_type(), Eq(DenseArrayEdge::MAPPING)); EXPECT_THAT(edge.edge_values().values, ElementsAre()); EXPECT_EQ(edge.parent_size(), 0); EXPECT_EQ(edge.child_size(), 0); } TEST(DenseArrayEdgeTest, Fingerprint) { const auto mapping = CreateDenseArray<int64_t>({0, 0, 0, 1, 1}); const auto split_points = CreateDenseArray<int64_t>({0, 3, 5}); ASSERT_OK_AND_ASSIGN(auto edge_from_mapping_1, DenseArrayEdge::FromMapping(mapping, 2)); ASSERT_OK_AND_ASSIGN(auto edge_from_mapping_2, DenseArrayEdge::FromMapping(mapping, 2)); ASSERT_OK_AND_ASSIGN(auto edge_from_split_points, DenseArrayEdge::FromSplitPoints(split_points)); EXPECT_EQ(FingerprintHasher("salt").Combine(edge_from_mapping_1).Finish(), FingerprintHasher("salt").Combine(edge_from_mapping_2).Finish()); EXPECT_NE(FingerprintHasher("salt").Combine(edge_from_mapping_1).Finish(), FingerprintHasher("salt").Combine(edge_from_split_points).Finish()); } TEST(DenseArrayEdgeTest, ToSplitPointsEdge_Success) { { const auto split_points = CreateDenseArray<int64_t>({0, 3, 5}); ASSERT_OK_AND_ASSIGN(auto edge, DenseArrayEdge::FromSplitPoints(split_points)); ASSERT_OK_AND_ASSIGN(auto edge2, edge.ToSplitPointsEdge()); EXPECT_EQ(edge.parent_size(), edge2.parent_size()); EXPECT_EQ(edge.child_size(), edge2.child_size()); EXPECT_EQ(edge2.edge_type(), DenseArrayEdge::SPLIT_POINTS); EXPECT_THAT(edge2.edge_values().values, ElementsAre(0, 3, 5)); } { const auto mapping = CreateDenseArray<int64_t>({0, 0, 1, 1, 3, 5}); ASSERT_OK_AND_ASSIGN(auto mapping_edge, DenseArrayEdge::FromMapping(mapping, 8)); ASSERT_OK_AND_ASSIGN(auto split_point_edge, mapping_edge.ToSplitPointsEdge()); EXPECT_EQ(mapping_edge.parent_size(), split_point_edge.parent_size()); EXPECT_EQ(mapping_edge.child_size(), split_point_edge.child_size()); EXPECT_EQ(split_point_edge.edge_type(), DenseArrayEdge::SPLIT_POINTS); EXPECT_THAT(split_point_edge.edge_values().values, ElementsAre(0, 2, 4, 4, 5, 5, 6, 6, 6)); } } TEST(DenseArrayEdgeTest, ToSplitPointsEdge_Errors) { { const auto mapping = CreateDenseArray<int64_t>({0, std::nullopt}); ASSERT_OK_AND_ASSIGN(auto mapping_edge, DenseArrayEdge::FromMapping(mapping, 2)); EXPECT_THAT(mapping_edge.ToSplitPointsEdge(), StatusIs(absl::StatusCode::kInvalidArgument, "expected a full mapping")); } { const auto mapping = CreateDenseArray<int64_t>({1, 0}); ASSERT_OK_AND_ASSIGN(auto mapping_edge, DenseArrayEdge::FromMapping(mapping, 2)); EXPECT_THAT(mapping_edge.ToSplitPointsEdge(), StatusIs(absl::StatusCode::kInvalidArgument, "expected a sorted mapping")); } } TEST(DenseArrayEdgeTest, ToSplitPointsEdge_BufferFactory) { { const auto mapping = CreateDenseArray<int64_t>({0, 0, 1, 1, 3, 5}); ASSERT_OK_AND_ASSIGN(auto mapping_edge, DenseArrayEdge::FromMapping(mapping, 8)); ASSERT_OK_AND_ASSIGN(auto split_point_edge, mapping_edge.ToSplitPointsEdge()); EXPECT_TRUE(split_point_edge.edge_values().values.is_owner()); } { const auto mapping = CreateDenseArray<int64_t>({0, 0, 1, 1, 3, 5}); ASSERT_OK_AND_ASSIGN(auto mapping_edge, DenseArrayEdge::FromMapping(mapping, 8)); UnsafeArenaBufferFactory arena{128}; ASSERT_OK_AND_ASSIGN(auto split_point_edge, mapping_edge.ToSplitPointsEdge(arena)); EXPECT_FALSE(split_point_edge.edge_values().values.is_owner()); } } TEST(DenseArrayEdgeTest, ToMappingEdge) { { const auto mapping = CreateDenseArray<int64_t>({0, 1, 0, std::nullopt, 3, 5}); ASSERT_OK_AND_ASSIGN(auto edge, DenseArrayEdge::FromMapping(mapping, 8)); auto edge2 = edge.ToMappingEdge(); EXPECT_EQ(edge.parent_size(), edge2.parent_size()); EXPECT_EQ(edge.child_size(), edge2.child_size()); EXPECT_EQ(edge2.edge_type(), DenseArrayEdge::MAPPING); EXPECT_THAT(edge2.edge_values(), ElementsAre(0, 1, 0, std::nullopt, 3, 5)); } { const auto split_points = CreateDenseArray<int64_t>({0, 3, 5}); ASSERT_OK_AND_ASSIGN(auto split_points_edge, DenseArrayEdge::FromSplitPoints(split_points)); auto mapping_edge = split_points_edge.ToMappingEdge(); EXPECT_EQ(split_points_edge.parent_size(), mapping_edge.parent_size()); EXPECT_EQ(split_points_edge.child_size(), mapping_edge.child_size()); EXPECT_EQ(mapping_edge.edge_type(), DenseArrayEdge::MAPPING); EXPECT_THAT(mapping_edge.edge_values(), ElementsAre(0, 0, 0, 1, 1)); } { const auto split_points = CreateDenseArray<int64_t>({0, 3, 5}); ASSERT_OK_AND_ASSIGN(auto split_points_edge, DenseArrayEdge::FromSplitPoints(split_points)); auto mapping_edge = split_points_edge.ToMappingEdge(); EXPECT_TRUE(mapping_edge.edge_values().values.is_owner()); UnsafeArenaBufferFactory arena{128}; mapping_edge = split_points_edge.ToMappingEdge(arena); EXPECT_FALSE(mapping_edge.edge_values().values.is_owner()); } } TEST(DenseArrayEdgeTest, IsEquivalentTo) { { const auto split_points = CreateDenseArray<int64_t>({0, 3, 5}); ASSERT_OK_AND_ASSIGN(auto edge1, DenseArrayEdge::FromSplitPoints(split_points)); ASSERT_OK_AND_ASSIGN(auto edge2, DenseArrayEdge::FromSplitPoints(split_points)); EXPECT_TRUE(edge1.IsEquivalentTo(edge2)); } { const auto mapping = CreateDenseArray<int64_t>({0, 0, std::nullopt, 1, 3, 5}); ASSERT_OK_AND_ASSIGN(auto edge1, DenseArrayEdge::FromMapping(mapping, 8)); ASSERT_OK_AND_ASSIGN(auto edge2, DenseArrayEdge::FromMapping(mapping, 8)); EXPECT_TRUE(edge1.IsEquivalentTo(edge2)); } { const auto mapping = CreateDenseArray<int64_t>({0, 0, 0, 1, 1}); ASSERT_OK_AND_ASSIGN(auto edge1, DenseArrayEdge::FromMapping(mapping, 2)); const auto split_points = CreateDenseArray<int64_t>({0, 3, 5}); ASSERT_OK_AND_ASSIGN(auto edge2, DenseArrayEdge::FromSplitPoints(split_points)); EXPECT_TRUE(edge1.IsEquivalentTo(edge2)); } { const auto mapping = CreateDenseArray<int64_t>({0, 0, 1, 0, 1}); ASSERT_OK_AND_ASSIGN(auto edge1, DenseArrayEdge::FromMapping(mapping, 2)); const auto split_points = CreateDenseArray<int64_t>({0, 3, 5}); ASSERT_OK_AND_ASSIGN(auto edge2, DenseArrayEdge::FromSplitPoints(split_points)); EXPECT_FALSE(edge1.IsEquivalentTo(edge2)); } { const auto mapping = CreateDenseArray<int64_t>({0, 0, 0, 1, 1}); ASSERT_OK_AND_ASSIGN(auto edge1, DenseArrayEdge::FromMapping(mapping, 2)); ASSERT_OK_AND_ASSIGN(auto edge2, DenseArrayEdge::FromMapping(mapping, 3)); EXPECT_FALSE(edge1.IsEquivalentTo(edge2)); } { const auto mapping1 = CreateDenseArray<int64_t>({0, 0, 0, 1, 1}); ASSERT_OK_AND_ASSIGN(auto edge1, DenseArrayEdge::FromMapping(mapping1, 2)); const auto mapping2 = CreateDenseArray<int64_t>({0, 1, 1}); ASSERT_OK_AND_ASSIGN(auto edge2, DenseArrayEdge::FromMapping(mapping2, 2)); EXPECT_FALSE(edge1.IsEquivalentTo(edge2)); } { const auto mapping1 = CreateDenseArray<int64_t>({0, 0, 0, 1, 1}); ASSERT_OK_AND_ASSIGN(auto edge1, DenseArrayEdge::FromMapping(mapping1, 2)); const auto mapping2 = CreateDenseArray<int64_t>({0, 0, 1, 1, 1}); ASSERT_OK_AND_ASSIGN(auto edge2, DenseArrayEdge::FromMapping(mapping2, 2)); EXPECT_FALSE(edge1.IsEquivalentTo(edge2)); } } TEST(DenseArrayEdgeTest, ComposeEdges_SplitPoint) { ASSERT_OK_AND_ASSIGN(auto edge1, DenseArrayEdge::FromSplitPoints( CreateDenseArray<int64_t>({0, 2}))); ASSERT_OK_AND_ASSIGN(auto edge2, DenseArrayEdge::FromSplitPoints( CreateDenseArray<int64_t>({0, 1, 3}))); ASSERT_OK_AND_ASSIGN( auto edge3, DenseArrayEdge::FromSplitPoints(CreateDenseArray<int64_t>({0, 1, 2, 4}))); ASSERT_OK_AND_ASSIGN(auto edge4, DenseArrayEdge::FromSplitPoints( CreateDenseArray<int64_t>({0, 3, 4, 11, 12}))); { ASSERT_OK_AND_ASSIGN(auto composed_edge, DenseArrayEdge::ComposeEdges( {edge1, edge2, edge3, edge4})); EXPECT_EQ(composed_edge.edge_type(), DenseArrayEdge::SPLIT_POINTS); EXPECT_THAT(composed_edge.edge_values(), ElementsAre(0, 12)); } { ASSERT_OK_AND_ASSIGN(auto composed_edge, DenseArrayEdge::ComposeEdges({edge2, edge3, edge4})); EXPECT_EQ(composed_edge.edge_type(), DenseArrayEdge::SPLIT_POINTS); EXPECT_THAT(composed_edge.edge_values(), ElementsAre(0, 3, 12)); } { ASSERT_OK_AND_ASSIGN(auto composed_edge, DenseArrayEdge::ComposeEdges({edge3, edge4})); EXPECT_EQ(composed_edge.edge_type(), DenseArrayEdge::SPLIT_POINTS); EXPECT_THAT(composed_edge.edge_values(), ElementsAre(0, 3, 4, 12)); } { ASSERT_OK_AND_ASSIGN(auto composed_edge, DenseArrayEdge::ComposeEdges({edge4})); EXPECT_EQ(composed_edge.edge_type(), DenseArrayEdge::SPLIT_POINTS); EXPECT_THAT(composed_edge.edge_values(), ElementsAre(0, 3, 4, 11, 12)); } { EXPECT_THAT(DenseArrayEdge::ComposeEdges({}), StatusIs(absl::StatusCode::kInvalidArgument, "at least one edge must be present")); } { EXPECT_THAT(DenseArrayEdge::ComposeEdges({edge1, edge3}), StatusIs(absl::StatusCode::kInvalidArgument, "incompatible edges: edges[0].child_size (2) != " "edges[1].parent_size (3)")); } } TEST(DenseArrayEdgeTest, ComposeEdges_Mapping) { ASSERT_OK_AND_ASSIGN(auto edge1, DenseArrayEdge::FromMapping( CreateDenseArray<int64_t>({0, std::nullopt}), 5)); ASSERT_OK_AND_ASSIGN(auto edge2, DenseArrayEdge::FromMapping( CreateDenseArray<int64_t>({0, 1, std::nullopt}), 2)); ASSERT_OK_AND_ASSIGN( auto edge3, DenseArrayEdge::FromMapping(CreateDenseArray<int64_t>({1, 2, 0, 2}), 3)); ASSERT_OK_AND_ASSIGN(auto edge4, DenseArrayEdge::FromSplitPoints( CreateDenseArray<int64_t>({0, 3, 4, 11, 12}))); ASSERT_OK_AND_ASSIGN( auto edge5, DenseArrayEdge::FromSplitPoints(CreateDenseArray<int64_t>( {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}))); { ASSERT_OK_AND_ASSIGN( auto composed_edge, DenseArrayEdge::ComposeEdges({edge1, edge2, edge3, edge4, edge5})); EXPECT_EQ(composed_edge.edge_type(), DenseArrayEdge::MAPPING); EXPECT_EQ(composed_edge.parent_size(), 5); EXPECT_THAT(composed_edge.edge_values(), ElementsAre(std::nullopt, std::nullopt, std::nullopt, std::nullopt, 0, 0, 0, 0, 0, 0, 0, std::nullopt)); } { ASSERT_OK_AND_ASSIGN(auto composed_edge, DenseArrayEdge::ComposeEdges({edge2, edge3, edge4})); EXPECT_EQ(composed_edge.edge_type(), DenseArrayEdge::MAPPING); EXPECT_EQ(composed_edge.parent_size(), 2); EXPECT_THAT( composed_edge.edge_values(), ElementsAre(1, 1, 1, std::nullopt, 0, 0, 0, 0, 0, 0, 0, std::nullopt)); } { ASSERT_OK_AND_ASSIGN(auto composed_edge, DenseArrayEdge::ComposeEdges({edge3, edge4})); EXPECT_EQ(composed_edge.edge_type(), DenseArrayEdge::MAPPING); EXPECT_EQ(composed_edge.parent_size(), 3); EXPECT_THAT(composed_edge.edge_values(), ElementsAre(1, 1, 1, 2, 0, 0, 0, 0, 0, 0, 0, 2)); } { ASSERT_OK_AND_ASSIGN( auto composed_edge, DenseArrayEdge::ComposeEdges({edge4, edge5.ToMappingEdge()})); EXPECT_EQ(composed_edge.edge_type(), DenseArrayEdge::MAPPING); EXPECT_EQ(composed_edge.parent_size(), 4); EXPECT_THAT(composed_edge.edge_values(), ElementsAre(0, 0, 0, 1, 2, 2, 2, 2, 2, 2, 2, 3)); } { ASSERT_OK_AND_ASSIGN(auto composed_edge, DenseArrayEdge::ComposeEdges({edge2, edge3})); EXPECT_EQ(composed_edge.edge_type(), DenseArrayEdge::MAPPING); EXPECT_EQ(composed_edge.parent_size(), 2); EXPECT_THAT(composed_edge.edge_values(), ElementsAre(1, std::nullopt, 0, std::nullopt)); } { ASSERT_OK_AND_ASSIGN(auto composed_edge, DenseArrayEdge::ComposeEdges({edge4.ToMappingEdge()})); EXPECT_EQ(composed_edge.edge_type(), DenseArrayEdge::MAPPING); EXPECT_EQ(composed_edge.parent_size(), 4); EXPECT_THAT(composed_edge.edge_values(), ElementsAre(0, 0, 0, 1, 2, 2, 2, 2, 2, 2, 2, 3)); } { EXPECT_THAT(DenseArrayEdge::ComposeEdges({}), StatusIs(absl::StatusCode::kInvalidArgument, "at least one edge must be present")); } { EXPECT_THAT(DenseArrayEdge::ComposeEdges({edge1, edge3}), StatusIs(absl::StatusCode::kInvalidArgument, "incompatible edges: edges[0].child_size (2) != " "edges[1].parent_size (3)")); } } TEST(DenseArrayEdgeTest, ComposeEdges_BufferFactory) { ASSERT_OK_AND_ASSIGN(auto edge1, DenseArrayEdge::FromSplitPoints( CreateDenseArray<int64_t>({0, 2}))); ASSERT_OK_AND_ASSIGN(auto edge2, DenseArrayEdge::FromSplitPoints( CreateDenseArray<int64_t>({0, 1, 3}))); { ASSERT_OK_AND_ASSIGN(auto composed_edge, DenseArrayEdge::ComposeEdges({edge1, edge2})); EXPECT_TRUE(composed_edge.edge_values().values.is_owner()); } { UnsafeArenaBufferFactory arena{128}; ASSERT_OK_AND_ASSIGN(auto composed_edge, DenseArrayEdge::ComposeEdges({edge1, edge2}, arena)); EXPECT_FALSE(composed_edge.edge_values().values.is_owner()); } } } }
2,391
#ifndef AROLLA_ARRAY_ARRAY_H_ #define AROLLA_ARRAY_ARRAY_H_ #include <algorithm> #include <cstddef> #include <cstdint> #include <cstring> #include <iterator> #include <optional> #include <type_traits> #include <utility> #include "absl/base/attributes.h" #include "absl/log/check.h" #include "absl/types/span.h" #include "arolla/array/id_filter.h" #include "arolla/dense_array/bitmap.h" #include "arolla/dense_array/dense_array.h" #include "arolla/memory/buffer.h" #include "arolla/memory/optional_value.h" #include "arolla/memory/raw_buffer_factory.h" #include "arolla/util/api.h" #include "arolla/util/fingerprint.h" #include "arolla/util/iterator.h" #include "arolla/util/repr.h" #include "arolla/util/view_types.h" namespace arolla { template <class T> class AROLLA_API Array { public: explicit Array(int64_t size = 0, OptionalValue<T> value = std::nullopt) : size_(size), id_filter_(IdFilter::kEmpty), missing_id_value_(std::move(value)) { DCHECK_GE(size_, 0); } explicit Array(DenseArray<T> data) : size_(data.size()), id_filter_(IdFilter::kFull), dense_data_(std::move(data)) { DCHECK(dense_data_.CheckBitmapMatchesValues()); } explicit Array(Buffer<T> data) : size_(data.size()), id_filter_(IdFilter::kFull), dense_data_(DenseArray<T>{std::move(data)}) {} explicit Array(int64_t size, IdFilter ids, DenseArray<T> data, OptionalValue<T> missing_id_value = std::nullopt) : size_(size), id_filter_(std::move(ids)), dense_data_(std::move(data)), missing_id_value_(std::move(missing_id_value)) { DCHECK_GE(size_, 0); DCHECK(dense_data_.CheckBitmapMatchesValues()); switch (id_filter_.type()) { case IdFilter::kEmpty: DCHECK(dense_data_.empty()); break; case IdFilter::kPartial: DCHECK_LT(id_filter_.ids().size(), size_); DCHECK_EQ(id_filter_.ids().size(), dense_data_.size()); DCHECK_LT(id_filter_.ids().back() - id_filter_.ids_offset(), size_); break; case IdFilter::kFull: DCHECK_EQ(dense_data_.size(), size_); missing_id_value_ = std::nullopt; break; } } int64_t size() const { return size_; } bool empty() const { return size_ == 0; } const IdFilter& id_filter() const { return id_filter_; } const DenseArray<T>& dense_data() const { return dense_data_; } const OptionalValue<T>& missing_id_value() const { return missing_id_value_; } const OptionalValue<view_type_t<T>> operator[]( int64_t index) const { DCHECK_GE(index, 0); DCHECK_LT(index, size_); OptionalValue<int64_t> offset = id_filter_.IdToOffset(index); if (offset.present) { return dense_data_[offset.value]; } else { return missing_id_value_; } } bool IsConstForm() const { return id_filter_.type() == IdFilter::kEmpty; } bool IsDenseForm() const { return id_filter_.type() == IdFilter::kFull; } bool IsSparseForm() const { return id_filter_.type() == IdFilter::kPartial; } bool IsAllMissingForm() const { return IsConstForm() && !missing_id_value_.present; } bool IsFullForm() const { return IsDenseForm() && dense_data_.bitmap.empty(); } bool HasMissingIdValue() const { return !IsDenseForm() && missing_id_value_.present && size_ > 0; } Array WithIds(const IdFilter& ids, const OptionalValue<T>& missing_id_value, RawBufferFactory* buf_factory = GetHeapBufferFactory()) const; Array ToDenseForm( RawBufferFactory* buf_factory = GetHeapBufferFactory()) const { return WithIds(IdFilter::kFull, std::nullopt, buf_factory); } Array ToSparseForm( OptionalValue<T> missing_id_value = std::nullopt, RawBufferFactory* buf_factory = GetHeapBufferFactory()) const; bool is_owned() const { return dense_data_.is_owned() && (id_filter_.type() != IdFilter::kPartial || id_filter_.ids().is_owner()); } Array MakeOwned( RawBufferFactory* buf_factory = GetHeapBufferFactory()) const { IdFilter ids = id_filter_.type() == IdFilter::kPartial ? IdFilter(size_, id_filter_.ids().DeepCopy(buf_factory), id_filter_.ids_offset()) : id_filter_; return Array(size_, std::move(ids), dense_data_.MakeOwned(buf_factory), missing_id_value_); } Array Slice(int64_t start_id, int64_t row_count) const { DCHECK_GE(start_id, 0); DCHECK_GE(row_count, 0); DCHECK_LE(start_id + row_count, size_); if (id_filter_.type() == IdFilter::kEmpty) { return Array(row_count, missing_id_value_); } IdFilter filter = IdFilter::kFull; int64_t start_offset = start_id; int64_t dense_count = row_count; if (id_filter_.type() == IdFilter::kPartial) { int64_t new_ids_offset = id_filter_.ids_offset() + start_id; const Buffer<int64_t>& ids = id_filter_.ids(); auto iter_start = std::lower_bound(ids.begin(), ids.end(), new_ids_offset); auto iter_end = std::lower_bound(ids.begin(), ids.end(), new_ids_offset + row_count); start_offset = std::distance(ids.begin(), iter_start); dense_count = std::distance(iter_start, iter_end); filter = IdFilter(row_count, ids.Slice(start_offset, dense_count), new_ids_offset); } return Array(row_count, std::move(filter), dense_data_.Slice(start_offset, dense_count), missing_id_value_); } int64_t PresentCount() const { int64_t res = bitmap::CountBits( dense_data_.bitmap, dense_data_.bitmap_bit_offset, dense_data_.size()); if (HasMissingIdValue()) res += size_ - dense_data_.size(); return res; } using base_type = T; using value_type = OptionalValue<view_type_t<T>>; using size_type = int64_t; using const_iterator = ConstArrayIterator<Array<T>>; using difference_type = int64_t; using offset_type = int64_t; const_iterator begin() const { return const_iterator{this, 0}; } const_iterator end() const { return const_iterator{this, size()}; } template <typename Fn, typename RepeatedFn> void ForEach(Fn&& fn, RepeatedFn&& repeated_fn) const { if (IsConstForm()) { repeated_fn(0, size_, missing_id_value_.present, missing_id_value_.value); return; } if (IsDenseForm()) { dense_data_.ForEach(fn); return; } int64_t id = 0; dense_data_.ForEach([&](int64_t offset, bool present, view_type_t<T> v) { int64_t new_id = id_filter_.IdsOffsetToId(offset); if (id < new_id) repeated_fn(id, new_id - id, missing_id_value_.present, missing_id_value_.value); fn(id_filter_.IdsOffsetToId(offset), present, v); id = new_id + 1; }); if (id < size_) { repeated_fn(id, size_ - id, missing_id_value_.present, missing_id_value_.value); } } template <typename Fn> void ForEach(Fn&& fn) const { ForEach(fn, [&](int64_t first_id, int64_t count, bool present, view_type_t<T> value) { for (int64_t i = 0; i < count; ++i) { fn(first_id + i, present, value); } }); } template <typename Fn, typename RepeatedFn> void ForEachPresent(Fn&& fn, RepeatedFn&& repeated_fn) const { if (IsAllMissingForm()) return; if (IsConstForm()) { repeated_fn(0, size_, missing_id_value_.value); return; } if (IsDenseForm()) { dense_data_.ForEach([&fn](int64_t id, bool present, view_type_t<T> v) { if (present) fn(id, v); }); return; } if (HasMissingIdValue()) { int64_t id = 0; dense_data_.ForEach([&](int64_t offset, bool present, view_type_t<T> v) { int64_t new_id = id_filter_.IdsOffsetToId(offset); if (id < new_id) repeated_fn(id, new_id - id, missing_id_value_.value); if (present) fn(id_filter_.IdsOffsetToId(offset), v); id = new_id + 1; }); if (id < size_) { repeated_fn(id, size_ - id, missing_id_value_.value); } } else { dense_data_.ForEach( [this, &fn](int64_t offset, bool present, view_type_t<T> v) { if (present) fn(id_filter_.IdsOffsetToId(offset), v); }); } } template <typename Fn> void ForEachPresent(Fn&& fn) const { ForEachPresent(fn, [&](int64_t first_id, int64_t count, view_type_t<T> value) { for (int64_t i = 0; i < count; ++i) { fn(first_id + i, value); } }); } private: DenseArray<T> WithIdsFromSparse(const IdFilter& ids, RawBufferFactory* buf_factory) const; DenseArray<T> WithIdsDenseToSparse(const IdFilter& ids, RawBufferFactory* buf_factory) const; Array<T> ToSparseFormWithChangedMissedIdValue( OptionalValue<T> missing_id_value, RawBufferFactory* buf_factory) const; Array<T> ToSparseFormWithMissedIdValue(const T& missing_id_value, RawBufferFactory* buf_factory) const; Array<T> ToSparseFormWithoutMissedIdValue( RawBufferFactory* buf_factory) const; int64_t size_; IdFilter id_filter_; DenseArray<T> dense_data_; OptionalValue<T> missing_id_value_; }; template <typename T> bool ArraysAreEquivalent(const Array<T>& lhs, const Array<T>& rhs) { if (lhs.size() != rhs.size()) return false; if (lhs.IsDenseForm() && rhs.IsDenseForm()) { return ArraysAreEquivalent(lhs.dense_data(), rhs.dense_data()); } IdFilter id_union = IdFilter::UpperBoundMerge( lhs.size(), GetHeapBufferFactory(), lhs.id_filter(), rhs.id_filter()); auto lhs_transformed = lhs.WithIds(id_union, lhs.missing_id_value()); auto rhs_transformed = rhs.WithIds(id_union, rhs.missing_id_value()); return lhs_transformed.missing_id_value() == rhs_transformed.missing_id_value() && ArraysAreEquivalent(lhs_transformed.dense_data(), rhs_transformed.dense_data()); } template <class T> Array<T> CreateArray(absl::Span<const OptionalValue<T>> data) { return Array<T>(CreateDenseArray<T>(data)); } template <class T, class ValueT = T> Array<T> CreateArray(int64_t size, absl::Span<const int64_t> ids, absl::Span<const ValueT> values) { DCHECK_EQ(ids.size(), values.size()); DCHECK_LE(values.size(), size); if (values.size() > size * IdFilter::kDenseSparsityLimit) { DenseArrayBuilder<T> bldr(size); for (int64_t i = 0; i < values.size(); ++i) { bldr.Set(ids[i], values[i]); } return Array<T>(std::move(bldr).Build()); } else { Buffer<int64_t>::Builder ids_bldr(ids.size()); DenseArrayBuilder<T> values_bldr(values.size()); for (int64_t i = 0; i < values.size(); ++i) { ids_bldr.Set(i, ids[i]); values_bldr.Set(i, values[i]); } return Array<T>(size, IdFilter(size, std::move(ids_bldr).Build()), std::move(values_bldr).Build()); } } template <class T> using AsArray = Array<strip_optional_t<std::decay_t<T>>>; struct AROLLA_API ArrayShape { int64_t size; bool operator==(const ArrayShape& other) const { return size == other.size; } }; AROLLA_DECLARE_REPR(ArrayShape); AROLLA_DECLARE_FINGERPRINT_HASHER_TRAITS(ArrayShape); template <class T> Array<T> Array<T>::WithIds(const IdFilter& ids, const OptionalValue<T>& missing_id_value, RawBufferFactory* buf_factory) const { if (ids.type() == IdFilter::kEmpty || size_ == 0) { return Array(size_, missing_id_value); } if (id_filter_.IsSame(ids)) { return Array(size_, ids, dense_data_, missing_id_value); } DenseArray<T> new_data; switch (id_filter_.type()) { case IdFilter::kEmpty: { int64_t data_size = ids.type() == IdFilter::kPartial ? ids.ids().size() : size_; if (missing_id_value_.present) { new_data = CreateConstDenseArray<T>(data_size, missing_id_value_.value, buf_factory); } else { new_data = CreateEmptyDenseArray<T>(data_size, buf_factory); } } break; case IdFilter::kPartial: { new_data = WithIdsFromSparse(ids, buf_factory); } break; case IdFilter::kFull: { new_data = WithIdsDenseToSparse(ids, buf_factory); } break; } return Array(size_, ids, std::move(new_data), missing_id_value); } template <class T> ABSL_ATTRIBUTE_NOINLINE DenseArray<T> Array<T>::WithIdsFromSparse( const IdFilter& ids, RawBufferFactory* buf_factory) const { DCHECK_EQ(id_filter_.type(), IdFilter::kPartial); DCHECK_NE(ids.type(), IdFilter::kEmpty); size_t data_size = ids.type() == IdFilter::kPartial ? ids.ids().size() : size_; typename Buffer<T>::ReshuffleBuilder values_bldr( data_size, dense_data_.values, missing_id_value_, buf_factory); bitmap::RawBuilder bitmap_bldr(bitmap::BitmapSize(data_size), buf_factory); auto bitmap = bitmap_bldr.GetMutableSpan(); std::memset(bitmap.begin(), missing_id_value_.present ? 0xff : 0, bitmap.size() * sizeof(bitmap::Word)); if (ids.type() == IdFilter::kPartial) { IdFilter::IntersectPartial_ForEach( id_filter_, ids, [&](int64_t , int64_t old_offset, int64_t new_offset) { if (dense_data_.present(old_offset)) { values_bldr.CopyValue(new_offset, old_offset); bitmap::SetBit(bitmap.begin(), new_offset); } else { bitmap::UnsetBit(bitmap.begin(), new_offset); } }); } else if (missing_id_value_.present) { DCHECK_EQ(ids.type(), IdFilter::kFull); dense_data_.ForEach([&](int64_t offset, bool present, view_type_t<T>) { int64_t new_offset = id_filter_.IdsOffsetToId(offset); if (present) { values_bldr.CopyValue(new_offset, offset); } else { bitmap::UnsetBit(bitmap.begin(), new_offset); } }); } else { DCHECK_EQ(ids.type(), IdFilter::kFull); dense_data_.ForEach([&](int64_t offset, bool present, view_type_t<T>) { int64_t new_offset = id_filter_.IdsOffsetToId(offset); if (present) { values_bldr.CopyValue(new_offset, offset); bitmap::SetBit(bitmap.begin(), new_offset); } }); } if (bitmap::AreAllBitsSet(bitmap.begin(), data_size)) { return {std::move(values_bldr).Build()}; } else { return {std::move(values_bldr).Build(), std::move(bitmap_bldr).Build()}; } } template <class T> ABSL_ATTRIBUTE_NOINLINE DenseArray<T> Array<T>::WithIdsDenseToSparse( const IdFilter& ids, RawBufferFactory* buf_factory) const { DCHECK_EQ(id_filter_.type(), IdFilter::kFull); DCHECK_EQ(ids.type(), IdFilter::kPartial); typename Buffer<T>::ReshuffleBuilder values_bldr( ids.ids().size(), dense_data_.values, std::nullopt, buf_factory); int64_t index = 0; if (dense_data_.bitmap.empty()) { for (IdFilter::IdWithOffset id : ids.ids()) { values_bldr.CopyValue(index++, id - ids.ids_offset()); } return {std::move(values_bldr).Build()}; } else { bitmap::Builder bitmap_bldr(ids.ids().size(), buf_factory); bitmap_bldr.AddForEach(ids.ids(), [&](IdFilter::IdWithOffset id_with_offset) { int64_t id = id_with_offset - ids.ids_offset(); values_bldr.CopyValue(index++, id); return dense_data_.present(id); }); return {std::move(values_bldr).Build(), std::move(bitmap_bldr).Build()}; } } template <class T> Array<T> Array<T>::ToSparseForm(OptionalValue<T> missing_id_value, RawBufferFactory* buf_factory) const { if (!IsDenseForm() && missing_id_value != missing_id_value_) { return ToSparseFormWithChangedMissedIdValue(missing_id_value, buf_factory); } else if (missing_id_value.present) { return ToSparseFormWithMissedIdValue(missing_id_value.value, buf_factory); } else { return ToSparseFormWithoutMissedIdValue(buf_factory); } } template <class T> Array<T> Array<T>::ToSparseFormWithChangedMissedIdValue( OptionalValue<T> missing_id_value, RawBufferFactory* buf_factory) const { DCHECK(!IsDenseForm() && missing_id_value != missing_id_value_); Buffer<IdFilter::IdWithOffset>::Builder bldr(size_, buf_factory); auto inserter = bldr.GetInserter(); int64_t next_id = 0; dense_data_.ForEach([&](int64_t offset, bool presence, view_type_t<T> value) { int64_t id = id_filter_.IdsOffsetToId(offset); while (next_id < id) inserter.Add(next_id++); if (presence != missing_id_value.present || (presence && missing_id_value.value != value)) { inserter.Add(id); } next_id = id + 1; }); while (next_id < size_) inserter.Add(next_id++); return WithIds(IdFilter(size_, std::move(bldr).Build(inserter)), missing_id_value, buf_factory); } template <class T> Array<T> Array<T>::ToSparseFormWithMissedIdValue( const T& missing_id_value, RawBufferFactory* buf_factory) const { DCHECK(IsDenseForm() || missing_id_value_ == missing_id_value); Buffer<IdFilter::IdWithOffset>::Builder ids_bldr(dense_data_.size(), buf_factory); auto ids_inserter = ids_bldr.GetInserter(); if (IsDenseForm() && !dense_data_.bitmap.empty()) { dense_data_.ForEach( [&](int64_t offset, bool presence, view_type_t<T> value) { if (!presence || value != missing_id_value) { ids_inserter.Add(offset); } }); return WithIds(IdFilter(size_, std::move(ids_bldr).Build(ids_inserter)), missing_id_value, buf_factory); } typename Buffer<T>::ReshuffleBuilder values_bldr( dense_data_.size(), dense_data_.values, std::nullopt, buf_factory); bitmap::Bitmap bitmap; int64_t new_offset = 0; if (dense_data_.bitmap.empty()) { if (IsDenseForm()) { for (int64_t offset = 0; offset < dense_data_.size(); ++offset) { if (dense_data_.values[offset] != missing_id_value) { ids_inserter.Add(offset); values_bldr.CopyValue(new_offset++, offset); } } } else { for (int64_t offset = 0; offset < dense_data_.size(); ++offset) { if (dense_data_.values[offset] != missing_id_value) { ids_inserter.Add(id_filter_.IdsOffsetToId(offset)); values_bldr.CopyValue(new_offset++, offset); } } } } else { bitmap::AlmostFullBuilder bitmap_bldr(dense_data_.size(), buf_factory); dense_data_.ForEach( [&](int64_t offset, bool presence, view_type_t<T> value) { if (presence && value == missing_id_value) return; ids_inserter.Add(id_filter_.IdsOffsetToId(offset)); if (presence) { values_bldr.CopyValue(new_offset++, offset); } else { bitmap_bldr.AddMissed(new_offset++); } }); bitmap = std::move(bitmap_bldr).Build(new_offset); } IdFilter id_filter(size_, std::move(ids_bldr).Build(ids_inserter)); Buffer<T> values = std::move(values_bldr).Build(new_offset); return Array(size_, std::move(id_filter), {std::move(values), std::move(bitmap)}, missing_id_value); } template <class T> Array<T> Array<T>::ToSparseFormWithoutMissedIdValue( RawBufferFactory* buf_factory) const { DCHECK(!HasMissingIdValue()); if (dense_data_.bitmap.empty()) return *this; Buffer<IdFilter::IdWithOffset>::Builder ids_bldr(dense_data_.size(), buf_factory); typename Buffer<T>::ReshuffleBuilder values_bldr( dense_data_.size(), dense_data_.values, std::nullopt, buf_factory); auto ids_inserter = ids_bldr.GetInserter(); int64_t new_offset = 0; if (IsDenseForm()) { dense_data_.ForEach([&](int64_t offset, bool presence, view_type_t<T>) { if (presence) { ids_inserter.Add(offset); values_bldr.CopyValue(new_offset++, offset); } }); } else { dense_data_.ForEach([&](int64_t offset, bool presence, view_type_t<T>) { if (presence) { ids_inserter.Add(id_filter_.IdsOffsetToId(offset)); values_bldr.CopyValue(new_offset++, offset); } }); } IdFilter id_filter(size_, std::move(ids_bldr).Build(ids_inserter)); Buffer<T> values = std::move(values_bldr).Build(new_offset); return Array(size_, std::move(id_filter), {std::move(values)}); } template <typename T> struct ArenaTraits<Array<T>> { static Array<T> MakeOwned(Array<T>&& v, RawBufferFactory* buf_factory) { return v.MakeOwned(buf_factory); } }; template <typename T> struct FingerprintHasherTraits<Array<T>> { void operator()(FingerprintHasher* hasher, const Array<T>& arg) const { hasher->Combine(arg.size(), arg.dense_data(), arg.missing_id_value(), arg.id_filter()); } }; template <typename T> class SparseArrayBuilder { public: explicit SparseArrayBuilder( int64_t size, int64_t max_present_count, RawBufferFactory* buf_factory = GetHeapBufferFactory()) : size_(size), dense_builder_(max_present_count, buf_factory), ids_builder_(max_present_count, buf_factory) {} template <typename V> void Add(int64_t id, const V& v) { dense_builder_.Set(offset_, v); AddId(id); } void AddId(int64_t id) { DCHECK(id >= 0 && id < size_); DCHECK(offset_ == 0 || ids_builder_.GetMutableSpan()[offset_ - 1] < id); ids_builder_.Set(offset_++, id); } int64_t NextOffset() const { return offset_; } template <typename V> void SetByOffset(int64_t offset, const V& v) { dense_builder_.Set(offset, v); } Array<T> Build() && { return Array<T>(size_, IdFilter(size_, std::move(ids_builder_).Build(offset_)), std::move(dense_builder_).Build(offset_)); } private: int64_t size_; int64_t offset_ = 0; DenseArrayBuilder<T> dense_builder_; Buffer<int64_t>::Builder ids_builder_; }; } #endif #include "arolla/array/array.h" #include "absl/strings/str_cat.h" #include "arolla/util/fingerprint.h" #include "arolla/util/repr.h" namespace arolla { void FingerprintHasherTraits<ArrayShape>::operator()( FingerprintHasher* hasher, const ArrayShape& value) const { hasher->Combine(value.size); } ReprToken ReprTraits<ArrayShape>::operator()(const ArrayShape& value) const { return ReprToken{absl::StrCat("array_shape{size=", value.size, "}")}; } }
#include "arolla/array/array.h" #include <cstdint> #include <optional> #include <type_traits> #include <utility> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/strings/string_view.h" #include "arolla/array/id_filter.h" #include "arolla/dense_array/dense_array.h" #include "arolla/memory/buffer.h" #include "arolla/memory/optional_value.h" #include "arolla/memory/raw_buffer_factory.h" #include "arolla/util/bytes.h" #include "arolla/util/repr.h" #include "arolla/util/testing/repr_token_eq.h" namespace arolla { namespace { using ::arolla::testing::ReprTokenEq; using ::testing::ElementsAre; struct TryCompileAssignment { template <typename T> auto operator()(T v) -> decltype(v[0] = std::nullopt) { return v[0]; } }; struct TryCompileMutation { template <typename A, typename V> auto operator()(A a, V v) -> decltype(a[0].value = V()) { return a[0].value; } }; static_assert(!std::is_invocable_v<TryCompileAssignment, Array<int>>); static_assert( !std::is_invocable_v<TryCompileMutation, Array<Bytes>, absl::string_view>); TEST(DenseArrayTest, ArrayShapeRepr) { EXPECT_THAT(GenReprToken(ArrayShape{5}), ReprTokenEq("array_shape{size=5}")); } TEST(ArrayTest, BaseType) { static_assert(std::is_same_v<int, Array<int>::base_type>); static_assert(std::is_same_v<float, Array<float>::base_type>); } TEST(ArrayTest, Const) { { Array<int> block(0, {}); EXPECT_EQ(block.size(), 0); EXPECT_EQ(block.id_filter().type(), IdFilter::kEmpty); EXPECT_TRUE(block.IsConstForm()); EXPECT_TRUE(block.IsAllMissingForm()); EXPECT_FALSE(block.IsDenseForm()); } { Array<int> block(5, {}); EXPECT_EQ(block.id_filter().type(), IdFilter::kEmpty); EXPECT_TRUE(block.IsConstForm()); EXPECT_TRUE(block.IsAllMissingForm()); EXPECT_FALSE(block.IsDenseForm()); EXPECT_THAT(block, ElementsAre(std::nullopt, std::nullopt, std::nullopt, std::nullopt, std::nullopt)); } { Array<int> block(5, 3); EXPECT_EQ(block.id_filter().type(), IdFilter::kEmpty); EXPECT_TRUE(block.IsConstForm()); EXPECT_FALSE(block.IsAllMissingForm()); EXPECT_FALSE(block.IsDenseForm()); EXPECT_FALSE(block.IsSparseForm()); EXPECT_TRUE(block.HasMissingIdValue()); EXPECT_THAT(block, ElementsAre(3, 3, 3, 3, 3)); } } TEST(ArrayTest, Dense) { { Array<int> block = CreateArray<int>({2, 3, std::nullopt, 7}); EXPECT_EQ(block.id_filter().type(), IdFilter::kFull); EXPECT_FALSE(block.IsAllMissingForm()); EXPECT_FALSE(block.IsConstForm()); EXPECT_TRUE(block.IsDenseForm()); EXPECT_FALSE(block.IsFullForm()); EXPECT_FALSE(block.IsSparseForm()); EXPECT_FALSE(block.HasMissingIdValue()); EXPECT_THAT(block, ElementsAre(2, 3, std::nullopt, 7)); } { auto buffer = CreateBuffer<int>({2, 3, 5, 7}); Array<int> block(buffer); EXPECT_EQ(block.size(), buffer.size()); EXPECT_EQ(block.id_filter().type(), IdFilter::kFull); EXPECT_FALSE(block.IsAllMissingForm()); EXPECT_FALSE(block.IsConstForm()); EXPECT_TRUE(block.IsDenseForm()); EXPECT_TRUE(block.IsFullForm()); for (int i = 0; i < buffer.size(); ++i) { EXPECT_EQ(block[i], buffer[i]); } } } TEST(ArrayTest, Sparse) { IdFilter id_filter(8, CreateBuffer<int64_t>({101, 104, 105, 106}), 100); auto dense_data = CreateDenseArray<int>({2, 3, std::nullopt, 7}); Array<int> block(8, id_filter, dense_data, -1); EXPECT_EQ(block.size(), 8); EXPECT_EQ(block.id_filter().type(), IdFilter::kPartial); EXPECT_FALSE(block.IsConstForm()); EXPECT_FALSE(block.IsDenseForm()); EXPECT_TRUE(block.IsSparseForm()); EXPECT_TRUE(block.HasMissingIdValue()); EXPECT_THAT(block, ElementsAre(-1, 2, -1, -1, 3, std::nullopt, 7, -1)); } TEST(ArrayTest, SparseArrayBuilder) { SparseArrayBuilder<int> bldr(8, 4); bldr.Add(1, 2); bldr.AddId(4); bldr.Add(5, OptionalValue<int>()); bldr.Add(6, 7); bldr.SetByOffset(1, 3); Array<int> res = std::move(bldr).Build(); EXPECT_EQ(res.size(), 8); EXPECT_TRUE(res.IsSparseForm()); EXPECT_THAT(res, ElementsAre(std::nullopt, 2, std::nullopt, std::nullopt, 3, std::nullopt, 7, std::nullopt)); } TEST(ArrayTest, CreateFromIdsAndValues) { constexpr auto NA = std::nullopt; { auto array = CreateArray<int>(10, {1, 4}, {3, 7}); EXPECT_TRUE(array.IsSparseForm()); EXPECT_THAT(array, ElementsAre(NA, 3, NA, NA, 7, NA, NA, NA, NA, NA)); } { auto array = CreateArray<int>(10, {1, 4, 5}, {3, 7, 0}); EXPECT_TRUE(array.IsDenseForm()); EXPECT_THAT(array, ElementsAre(NA, 3, NA, NA, 7, 0, NA, NA, NA, NA)); } { auto array = CreateArray<int, OptionalValue<int>>(10, {1, 4, 5}, {3, NA, 0}); EXPECT_TRUE(array.IsDenseForm()); EXPECT_THAT(array, ElementsAre(NA, 3, NA, NA, NA, 0, NA, NA, NA, NA)); } } TEST(ArrayTest, ForEach) { struct V { bool repeated; int64_t id; int64_t count; OptionalValue<int64_t> value; bool operator==(const V& v) const { return repeated == v.repeated && id == v.id && count == v.count && value == v.value; } }; std::vector<V> res; auto fn = [&res](int64_t id, bool present, int64_t v) { res.push_back({false, id, 1, {present, v}}); }; auto repeated_fn = [&res](int64_t id, int64_t count, bool present, int64_t v) { res.push_back({true, id, count, {present, v}}); }; { res.clear(); Array<int64_t> block(10, std::nullopt); block.ForEach(fn, repeated_fn); EXPECT_THAT(res, ElementsAre(V{true, 0, 10, std::nullopt})); } { res.clear(); Array<int64_t> block(10, 5); block.ForEach(fn, repeated_fn); EXPECT_THAT(res, ElementsAre(V{true, 0, 10, 5})); } { res.clear(); auto block = CreateArray<int64_t>({2, 1, std::nullopt, std::nullopt, 3}); block.ForEach(fn, repeated_fn); EXPECT_THAT(res, ElementsAre(V{false, 0, 1, 2}, V{false, 1, 1, 1}, V{false, 2, 1, {}}, V{false, 3, 1, {}}, V{false, 4, 1, 3})); } { res.clear(); auto block = CreateArray<int64_t>({2, 1, std::nullopt, std::nullopt, 3}) .ToSparseForm(); block.ForEach(fn, repeated_fn); EXPECT_THAT(res, ElementsAre(V{false, 0, 1, 2}, V{false, 1, 1, 1}, V{true, 2, 2, {}}, V{false, 4, 1, 3})); } { res.clear(); auto block = CreateArray<int64_t>({2, 1, 4, 4, 3, 4}).ToSparseForm(4); block.ForEach(fn, repeated_fn); EXPECT_THAT(res, ElementsAre(V{false, 0, 1, 2}, V{false, 1, 1, 1}, V{true, 2, 2, 4}, V{false, 4, 1, 3}, V{true, 5, 1, 4})); } { res.clear(); auto block = CreateArray<int64_t>({2, 1, 4, 4, 3, 4}).ToSparseForm(4); block.ForEach(fn); EXPECT_THAT(res, ElementsAre(V{false, 0, 1, 2}, V{false, 1, 1, 1}, V{false, 2, 1, 4}, V{false, 3, 1, 4}, V{false, 4, 1, 3}, V{false, 5, 1, 4})); } } TEST(ArrayTest, ForEachPresent) { struct V { bool repeated; int64_t id, count, value; bool operator==(const V& v) const { return repeated == v.repeated && id == v.id && count == v.count && value == v.value; } }; std::vector<V> res; auto fn = [&res](int64_t id, int64_t v) { res.push_back({false, id, 1, v}); }; auto repeated_fn = [&res](int64_t id, int64_t count, int64_t v) { res.push_back({true, id, count, v}); }; { res.clear(); Array<int64_t> block(10, std::nullopt); block.ForEachPresent(fn, repeated_fn); EXPECT_THAT(res, ElementsAre()); } { res.clear(); Array<int64_t> block(10, 5); block.ForEachPresent(fn, repeated_fn); EXPECT_THAT(res, ElementsAre(V{true, 0, 10, 5})); } { res.clear(); auto block = CreateArray<int64_t>({2, 1, std::nullopt, std::nullopt, 3}); block.ForEachPresent(fn, repeated_fn); EXPECT_THAT(res, ElementsAre(V{false, 0, 1, 2}, V{false, 1, 1, 1}, V{false, 4, 1, 3})); } { res.clear(); auto block = CreateArray<int64_t>({2, 1, std::nullopt, std::nullopt, 3}) .ToSparseForm(); block.ForEachPresent(fn, repeated_fn); EXPECT_THAT(res, ElementsAre(V{false, 0, 1, 2}, V{false, 1, 1, 1}, V{false, 4, 1, 3})); } { res.clear(); auto block = CreateArray<int64_t>({2, 1, 4, 4, 3, 4}).ToSparseForm(4); block.ForEachPresent(fn, repeated_fn); EXPECT_THAT( res, ElementsAre(V{false, 0, 1, 2}, V{false, 1, 1, 1}, V{true, 2, 2, 4}, V{false, 4, 1, 3}, V{true, 5, 1, 4})); } { res.clear(); auto block = CreateArray<int64_t>({2, 1, 4, 4, 3, 4}).ToSparseForm(4); block.ForEachPresent(fn); EXPECT_THAT(res, ElementsAre(V{false, 0, 1, 2}, V{false, 1, 1, 1}, V{false, 2, 1, 4}, V{false, 3, 1, 4}, V{false, 4, 1, 3}, V{false, 5, 1, 4})); } } TEST(ArrayTest, WithIds_Empty) { { Array<int> original_block(10, std::nullopt); IdFilter filter(10, CreateBuffer<int64_t>({101, 104, 105, 106}), 100); auto block = original_block.WithIds(filter, 0); EXPECT_TRUE(block.id_filter().IsSame(filter)); EXPECT_THAT(block, ElementsAre(0, std::nullopt, 0, 0, std::nullopt, std::nullopt, std::nullopt, 0, 0, 0)); } { Array<int> original_block(10, 1); auto block = original_block.WithIds({IdFilter::kFull}, 0); EXPECT_TRUE(block.IsDenseForm()); EXPECT_THAT(block, ElementsAre(1, 1, 1, 1, 1, 1, 1, 1, 1, 1)); } } TEST(ArrayTest, WithIds_Sparse) { IdFilter original_filter(8, CreateBuffer<int64_t>({101, 104, 105, 106}), 100); auto original_data = CreateDenseArray<int>({2, 3, std::nullopt, 7}); Array<int> original_block(8, original_filter, original_data, -1); { auto block = original_block.WithIds({IdFilter::kEmpty}, std::nullopt); EXPECT_EQ(block.size(), original_block.size()); EXPECT_TRUE(block.IsAllMissingForm()); } { auto block = original_block.WithIds(original_block.id_filter(), 0); EXPECT_EQ(block.size(), original_block.size()); EXPECT_EQ(block.dense_data().values.begin(), original_block.dense_data().values.begin()); EXPECT_EQ(block.dense_data().bitmap.begin(), original_block.dense_data().bitmap.begin()); EXPECT_THAT(block, ElementsAre(0, 2, 0, 0, 3, std::nullopt, 7, 0)); } { IdFilter new_ids(8, CreateBuffer<int64_t>({10, 11, 12, 16}), 10); auto block = original_block.WithIds(new_ids, std::nullopt); EXPECT_THAT(block, ElementsAre(-1, 2, -1, std::nullopt, std::nullopt, std::nullopt, 7, std::nullopt)); } } TEST(ArrayTest, WithIds_Dense) { IdFilter filter(8, CreateBuffer<int64_t>({101, 104, 105, 106}), 100); { Array<int> original_block = CreateArray<int>({1, 2, 3, 4, std::nullopt, 6, 7, 8}); auto block = original_block.WithIds(filter, 0); EXPECT_TRUE(block.id_filter().IsSame(filter)); EXPECT_THAT(block, ElementsAre(0, 2, 0, 0, std::nullopt, 6, 7, 0)); } { DenseArray<int> array{CreateBuffer<int>({1, 2, 3, 4, 5, 6, 7, 8})}; Array<int> original_block(array); auto block = original_block.WithIds(filter, 0); EXPECT_TRUE(block.id_filter().IsSame(filter)); EXPECT_THAT(block, ElementsAre(0, 2, 0, 0, 5, 6, 7, 0)); } } TEST(ArrayTest, WithIds_Strings) { IdFilter original_filter(8, CreateBuffer<int64_t>({101, 104, 105, 106}), 100); IdFilter new_filter(8, CreateBuffer<int64_t>({10, 11, 12, 16}), 10); auto original_data = CreateDenseArray<Bytes>( {Bytes("22"), Bytes("333"), std::nullopt, Bytes("7")}); using V = absl::string_view; { Array<Bytes> original_block(8, original_filter, original_data); auto block = original_block.WithIds(new_filter, std::nullopt); EXPECT_EQ(block.dense_data().values.characters().begin(), original_data.values.characters().begin()); EXPECT_THAT(block, ElementsAre(std::nullopt, V("22"), std::nullopt, std::nullopt, std::nullopt, std::nullopt, V("7"), std::nullopt)); } { Array<Bytes> original_block(8, original_filter, original_data, Bytes("")); auto block = original_block.WithIds(new_filter, std::nullopt); EXPECT_EQ(block.dense_data().values.characters().begin(), original_data.values.characters().begin()); EXPECT_THAT(block, ElementsAre(V(""), V("22"), V(""), std::nullopt, std::nullopt, std::nullopt, V("7"), std::nullopt)); } { Array<Bytes> original_block(8, original_filter, original_data, Bytes("abc")); auto block = original_block.WithIds(new_filter, std::nullopt); EXPECT_NE(block.dense_data().values.characters().begin(), original_data.values.characters().begin()); EXPECT_THAT(block, ElementsAre(V("abc"), V("22"), V("abc"), std::nullopt, std::nullopt, std::nullopt, V("7"), std::nullopt)); } } TEST(ArrayTest, ToSparseForm_FromEmpty) { Array<int> block(5, 1); { auto res = block.ToSparseForm(); EXPECT_TRUE(res.IsFullForm()); EXPECT_THAT(res, ElementsAre(1, 1, 1, 1, 1)); } { auto res = block.ToSparseForm(2); EXPECT_TRUE(res.IsFullForm()); EXPECT_THAT(res, ElementsAre(1, 1, 1, 1, 1)); } { auto res = block.ToSparseForm(1); EXPECT_TRUE(res.IsConstForm()); EXPECT_THAT(res, ElementsAre(1, 1, 1, 1, 1)); } } TEST(ArrayTest, ToSparseForm_FromDense) { Array<int> block = CreateArray<int>({1, 2, 3, std::nullopt, 2, std::nullopt, 2}); { auto res = block.ToSparseForm(); EXPECT_THAT(res.id_filter().ids(), ElementsAre(0, 1, 2, 4, 6)); EXPECT_THAT(res.dense_data(), ElementsAre(1, 2, 3, 2, 2)); EXPECT_TRUE(res.dense_data().bitmap.empty()); } { auto res = block.ToSparseForm(2); EXPECT_THAT(res.id_filter().ids(), ElementsAre(0, 2, 3, 5)); EXPECT_THAT(res.dense_data(), ElementsAre(1, 3, std::nullopt, std::nullopt)); } { Array<int> block2 = CreateArray<int>({1, 2, 3, 4, 2, 5, 2}); auto res = block2.ToSparseForm(2); EXPECT_THAT(res.id_filter().ids(), ElementsAre(0, 2, 3, 5)); EXPECT_THAT(res.dense_data(), ElementsAre(1, 3, 4, 5)); } } TEST(ArrayTest, ToSparseForm_FromSparse) { IdFilter filter(8, CreateBuffer<int64_t>({101, 104, 105, 106}), 100); auto data = CreateDenseArray<int>({1, 2, 3, std::nullopt}); { DenseArray<int> d{CreateBuffer<int>({1, 2, 3, 4})}; Array<int> block(8, filter, d, std::nullopt); auto res = block.ToSparseForm(); EXPECT_TRUE(filter.IsSame(res.id_filter())); EXPECT_EQ(d.values.begin(), res.dense_data().values.begin()); EXPECT_TRUE(res.dense_data().bitmap.empty()); } { Array<int> block(8, filter, data); auto res = block.ToSparseForm(); EXPECT_THAT(res.id_filter().ids(), ElementsAre(1, 4, 5)); EXPECT_THAT(res.dense_data(), ElementsAre(1, 2, 3)); EXPECT_TRUE(res.dense_data().bitmap.empty()); } { Array<int> block(8, filter, data, 2); auto res = block.ToSparseForm(2); EXPECT_THAT(res.id_filter().ids(), ElementsAre(1, 5, 6)); EXPECT_THAT(res.dense_data(), ElementsAre(1, 3, std::nullopt)); } { auto data2 = CreateDenseArray<int>({1, 2, 3, 4}); Array<int> block(8, filter, data2, 2); auto res = block.ToSparseForm(2); EXPECT_THAT(res.id_filter().ids(), ElementsAre(1, 5, 6)); EXPECT_THAT(res.dense_data(), ElementsAre(1, 3, 4)); } { Array<int> block(8, filter, data, 4); auto res = block.ToSparseForm(); EXPECT_THAT(res.id_filter().ids(), ElementsAre(0, 1, 2, 3, 4, 5, 7)); EXPECT_THAT(res.dense_data(), ElementsAre(4, 1, 4, 4, 2, 3, 4)); EXPECT_TRUE(res.dense_data().bitmap.empty()); } { Array<int> block(8, filter, data); auto res = block.ToSparseForm(2); EXPECT_THAT(res.id_filter().ids(), ElementsAre(0, 1, 2, 3, 5, 6, 7)); EXPECT_THAT(res.dense_data(), ElementsAre(std::nullopt, 1, std::nullopt, std::nullopt, 3, std::nullopt, std::nullopt)); } { Array<int> block(8, filter, data, 3); auto res = block.ToSparseForm(2); EXPECT_THAT(res.id_filter().ids(), ElementsAre(0, 1, 2, 3, 5, 6, 7)); EXPECT_THAT(res.dense_data(), ElementsAre(3, 1, 3, 3, 3, std::nullopt, 3)); } } TEST(ArrayTest, MakeOwned) { std::vector<int> values{1, 2, 3, 4, 5}; std::vector<uint32_t> bitmap{0x15}; std::vector<int64_t> ids{0, 2, 3, 4, 5}; DenseArray<int> data{Buffer<int>(nullptr, values), Buffer<uint32_t>(nullptr, bitmap)}; Array<int> dense(data); Array<int> sparse(7, IdFilter(7, Buffer<int64_t>(nullptr, ids)), data); EXPECT_FALSE(dense.is_owned()); EXPECT_FALSE(sparse.is_owned()); dense = ArenaTraits<Array<int>>::MakeOwned(std::move(dense), GetHeapBufferFactory()); sparse = ArenaTraits<Array<int>>::MakeOwned(std::move(sparse), GetHeapBufferFactory()); EXPECT_TRUE(dense.is_owned()); EXPECT_THAT(dense, ElementsAre(1, std::nullopt, 3, std::nullopt, 5)); EXPECT_TRUE(sparse.is_owned()); EXPECT_THAT(sparse, ElementsAre(1, std::nullopt, std::nullopt, 3, std::nullopt, 5, std::nullopt)); } TEST(ArrayTest, Slice) { EXPECT_THAT(Array<int>(7, 3).Slice(2, 4), ElementsAre(3, 3, 3, 3)); EXPECT_THAT(CreateArray<int>({5, 4, 3, 2, 1}).Slice(1, 3), ElementsAre(4, 3, 2)); { auto array = CreateArray<int>({5, std::nullopt, 3, std::nullopt, 1}); array = array.ToSparseForm(); auto sliced = array.Slice(1, 3); EXPECT_EQ(sliced.dense_data().size(), 1); EXPECT_EQ(sliced.id_filter().type(), IdFilter::kPartial); EXPECT_EQ(sliced.id_filter().ids_offset(), 1); EXPECT_THAT(sliced, ElementsAre(std::nullopt, 3, std::nullopt)); } } TEST(ArrayTest, PresentCount) { auto block = CreateArray<int>({1, 2, 1, 3, std::nullopt, 2, std::nullopt}); EXPECT_EQ(block.PresentCount(), 5); EXPECT_EQ(block.ToSparseForm().PresentCount(), 5); EXPECT_EQ(block.ToSparseForm(1).PresentCount(), 5); EXPECT_EQ(Array<int>(10, std::nullopt).PresentCount(), 0); EXPECT_EQ(Array<int>(10, 0).PresentCount(), 10); } TEST(ArrayTest, ArraysAreEquivalent) { { Array<int32_t> array1; Array<int32_t> array2; EXPECT_TRUE(ArraysAreEquivalent(array1, array2)); } { auto array1 = CreateArray<int>({1, 2}); auto array2 = CreateArray<int>({1}); EXPECT_FALSE(ArraysAreEquivalent(array1, array2)); } { auto array1 = Array<int32_t>(3, 1); auto array2 = Array<int32_t>(3, 1); ASSERT_TRUE(array1.IsConstForm()); EXPECT_TRUE(ArraysAreEquivalent(array1, array2)); auto array3 = Array<int32_t>(3, 0); EXPECT_FALSE(ArraysAreEquivalent(array1, array3)); } { Array<int32_t> array1 = CreateArray<int32_t>({2, 3, std::nullopt, 7}); Array<int32_t> array2 = CreateArray<int32_t>({2, 3, std::nullopt, 7}); ASSERT_TRUE(array1.IsDenseForm()); EXPECT_TRUE(ArraysAreEquivalent(array1, array2)); Array<int32_t> array3 = CreateArray<int32_t>({3, 4, std::nullopt, 1}); EXPECT_FALSE(ArraysAreEquivalent(array1, array3)); } { IdFilter id_filter(8, CreateBuffer<int64_t>({101, 104, 105, 106}), 100); auto dense_data = CreateDenseArray<int32_t>({2, 3, std::nullopt, 7}); Array<int32_t> array1(8, id_filter, dense_data, -1); Array<int32_t> array2(8, id_filter, dense_data, -1); ASSERT_TRUE(array1.IsSparseForm() && !array1.IsDenseForm() && !array1.IsConstForm()); EXPECT_TRUE(ArraysAreEquivalent(array1, array2)); auto dense_data2 = CreateDenseArray<int32_t>({3, 4, std::nullopt, 1}); Array<int32_t> array3(8, id_filter, dense_data2, -1); EXPECT_FALSE(ArraysAreEquivalent(array1, array3)); } } } }
2,392
#ifndef AROLLA_ARRAY_ID_FILTER_H_ #define AROLLA_ARRAY_ID_FILTER_H_ #include <algorithm> #include <cstdint> #include <iterator> #include <utility> #include "absl/base/attributes.h" #include "absl/log/check.h" #include "absl/types/span.h" #include "arolla/memory/buffer.h" #include "arolla/memory/optional_value.h" #include "arolla/memory/raw_buffer_factory.h" #include "arolla/util/fingerprint.h" namespace arolla { class IdFilter { public: using IdWithOffset = int64_t; enum Type { kEmpty, kPartial, kFull }; static constexpr double kDenseSparsityLimit = 0.25; IdFilter(Type type) : type_(type) { DCHECK_NE(type, kPartial); } explicit IdFilter(int64_t size, Buffer<IdWithOffset> ids, int64_t ids_offset = 0) : type_(kPartial), ids_(std::move(ids)), ids_offset_(ids_offset) { if (ids.empty()) { type_ = kEmpty; ids_offset_ = 0; } else if (ids.size() == size) { type_ = kFull; ids_ = Buffer<IdWithOffset>(); ids_offset_ = 0; } else { DCHECK_GE(ids.front(), ids_offset); #ifndef NDEBUG for (int64_t i = 1; i < ids.size(); ++i) { DCHECK_LT(ids[i - 1], ids[i]); } #endif DCHECK_LT(ids.back(), ids_offset + size); } } OptionalValue<int64_t> IdToOffset(int64_t id) const { switch (type_) { case kFull: return id; case kPartial: { auto iter = std::lower_bound(ids_.begin(), ids_.end(), id + ids_offset_); int64_t offset = std::distance(ids_.begin(), iter); bool present = iter != ids_.end() && ids_[offset] == id + ids_offset_; return {present, offset}; } case kEmpty: default: return {}; } } int64_t IdsOffsetToId(int64_t offset) const { DCHECK_EQ(type_, kPartial); DCHECK_GE(offset, 0); DCHECK_LT(offset, ids_.size()); return ids_[offset] - ids_offset_; } bool IsSame(const IdFilter& other) const { if (type_ != other.type_) return false; if (type_ == kPartial) { return ids_.begin() == other.ids_.begin() && ids_.end() == other.ids_.end() && ids_offset_ == other.ids_offset_; } else { return true; } } Type type() const { return type_; } const Buffer<IdWithOffset>& ids() const { DCHECK_NE(type_, kFull) << "Requesting ids on full filter is error prone. Ids are empty, which " "can be used incorrectly."; return ids_; } int64_t ids_offset() const { return ids_offset_; } template <class Id1, class Id2, class Fn> static void ForEachCommonId(absl::Span<const Id1> f1, Id1 ids_offset1, absl::Span<const Id2> f2, Id2 ids_offset2, Fn&& fn); template <class Fn> static void IntersectPartial_ForEach(const IdFilter& f1, const IdFilter& f2, Fn&& fn) { DCHECK_EQ(f1.type_, kPartial); DCHECK_EQ(f2.type_, kPartial); ForEachCommonId(f1.ids_.span(), f1.ids_offset_, f2.ids_.span(), f2.ids_offset_, std::forward<Fn>(fn)); } template <class... IdFilters> static IdFilter UpperBoundMerge(int64_t size, RawBufferFactory* buf_factory, const IdFilter& f, const IdFilters&... fs); template <class... IdFilters> static const IdFilter& UpperBoundIntersect(const IdFilter& f, const IdFilters&... fs); private: static IdFilter UpperBoundMergeImpl(int64_t size, RawBufferFactory* buf_factory, const IdFilter& a, const IdFilter& b); static const IdFilter& UpperBoundIntersectImpl(const IdFilter& a, const IdFilter& b); Type type_; Buffer<IdWithOffset> ids_; int64_t ids_offset_ = 0; }; template <class Id1, class Id2, class Fn> ABSL_ATTRIBUTE_ALWAYS_INLINE inline void IdFilter::ForEachCommonId( absl::Span<const Id1> f1, Id1 ids_offset1, absl::Span<const Id2> f2, Id2 ids_offset2, Fn&& fn) { DCHECK(!f1.empty()); DCHECK(!f2.empty()); auto iter1 = f1.begin(); auto iter2 = f2.begin(); int64_t id1 = *iter1 - ids_offset1; int64_t id2 = *iter2 - ids_offset2; int64_t max_id = std::min<int64_t>(f1.back() - ids_offset1, f2.back() - ids_offset2); while (id1 < max_id && id2 < max_id) { if (id1 == id2) { fn(id1, iter1 - f1.begin(), iter2 - f2.begin()); id1 = *(++iter1) - ids_offset1; id2 = *(++iter2) - ids_offset2; } while (id1 < std::min(max_id, id2)) { id1 = *(++iter1) - ids_offset1; } if (id2 < std::min(max_id, id1)) { id2 = *(++iter2) - ids_offset2; } } while (id1 < max_id) { id1 = *(++iter1) - ids_offset1; } while (id2 < max_id) { id2 = *(++iter2) - ids_offset2; } if (id1 == id2) { fn(id1, iter1 - f1.begin(), iter2 - f2.begin()); } } template <class... IdFilters> IdFilter IdFilter::UpperBoundMerge( int64_t size ABSL_ATTRIBUTE_UNUSED, RawBufferFactory* buf_factory ABSL_ATTRIBUTE_UNUSED, const IdFilter& f, const IdFilters&... fs) { if constexpr (sizeof...(fs) == 0) { return f; } else { return UpperBoundMergeImpl(size, buf_factory, f, UpperBoundMerge(size, buf_factory, fs...)); } } template <class... IdFilters> const IdFilter& IdFilter::UpperBoundIntersect(const IdFilter& f, const IdFilters&... fs) { if constexpr (sizeof...(fs) == 0) { return f; } else { return UpperBoundIntersectImpl(f, UpperBoundIntersect(fs...)); } } inline const IdFilter& IdFilter::UpperBoundIntersectImpl(const IdFilter& a, const IdFilter& b) { if (a.type() == kEmpty || b.type() == kFull) return a; if (b.type() == kEmpty || a.type() == kFull) return b; return a.ids().size() < b.ids().size() ? a : b; } AROLLA_DECLARE_FINGERPRINT_HASHER_TRAITS(IdFilter); } #endif #include "arolla/array/id_filter.h" #include <algorithm> #include <cstdint> #include <utility> #include "arolla/memory/buffer.h" #include "arolla/memory/raw_buffer_factory.h" #include "arolla/util/fingerprint.h" namespace arolla { IdFilter IdFilter::UpperBoundMergeImpl(int64_t size, RawBufferFactory* buf_factory, const IdFilter& a, const IdFilter& b) { if (a.type() == kEmpty || b.type() == kFull) return b; if (b.type() == kEmpty || a.type() == kFull) return a; if (a.IsSame(b)) return a; if (std::max(a.ids().size(), b.ids().size()) >= size * kDenseSparsityLimit) { return kFull; } Buffer<int64_t>::Builder bldr(a.ids().size() + b.ids().size(), buf_factory); auto inserter = bldr.GetInserter(); auto ia = a.ids().begin(); auto ib = b.ids().begin(); while (ia != a.ids().end() && ib != b.ids().end()) { int64_t va = *ia - a.ids_offset(); int64_t vb = *ib - b.ids_offset(); int64_t v = std::min(va, vb); if (va == v) ia++; if (vb == v) ib++; inserter.Add(v); } while (ia != a.ids().end()) inserter.Add(*(ia++) - a.ids_offset()); while (ib != b.ids().end()) inserter.Add(*(ib++) - b.ids_offset()); return IdFilter(size, std::move(bldr).Build(inserter)); } void FingerprintHasherTraits<IdFilter>::operator()( FingerprintHasher* hasher, const IdFilter& value) const { hasher->Combine(value.type()); if (value.type() != IdFilter::Type::kFull) { hasher->Combine(value.ids()); } } }
#include "arolla/array/id_filter.h" #include <cstdint> #include <tuple> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "arolla/memory/buffer.h" #include "arolla/memory/raw_buffer_factory.h" namespace arolla { namespace { TEST(IdFilterTest, UpperBoundIntersect) { IdFilter empty(IdFilter::kEmpty); IdFilter full(IdFilter::kFull); IdFilter a = IdFilter(5, CreateBuffer<int64_t>({3, 4})); IdFilter b = IdFilter(5, CreateBuffer<int64_t>({0, 2, 3})); IdFilter c = IdFilter(5, CreateBuffer<int64_t>({0, 1, 3, 4})); EXPECT_TRUE(IdFilter::UpperBoundIntersect(a).IsSame(a)); EXPECT_TRUE(IdFilter::UpperBoundIntersect(a, empty).IsSame(empty)); EXPECT_TRUE(IdFilter::UpperBoundIntersect(empty, a).IsSame(empty)); EXPECT_TRUE(IdFilter::UpperBoundIntersect(a, full).IsSame(a)); EXPECT_TRUE(IdFilter::UpperBoundIntersect(full, a).IsSame(a)); EXPECT_TRUE(IdFilter::UpperBoundIntersect(a, b).IsSame(a)); EXPECT_TRUE(IdFilter::UpperBoundIntersect(b, a).IsSame(a)); EXPECT_TRUE(IdFilter::UpperBoundIntersect(a, b, c).IsSame(a)); EXPECT_TRUE(IdFilter::UpperBoundIntersect(c, b, a).IsSame(a)); EXPECT_TRUE(IdFilter::UpperBoundIntersect(a, empty, c).IsSame(empty)); EXPECT_TRUE(IdFilter::UpperBoundIntersect(full, b, c).IsSame(b)); } TEST(IdFilterTest, UpperBoundMerge) { IdFilter empty(IdFilter::kEmpty); IdFilter full(IdFilter::kFull); IdFilter a = IdFilter(5, CreateBuffer<int64_t>({3, 4})); IdFilter b = IdFilter(5, CreateBuffer<int64_t>({0, 2, 3})); RawBufferFactory* bf = GetHeapBufferFactory(); EXPECT_TRUE(IdFilter::UpperBoundMerge(5, bf, a).IsSame(a)); EXPECT_TRUE(IdFilter::UpperBoundMerge(5, bf, a, empty).IsSame(a)); EXPECT_TRUE(IdFilter::UpperBoundMerge(5, bf, empty, a).IsSame(a)); EXPECT_TRUE(IdFilter::UpperBoundMerge(25, bf, a, full).IsSame(full)); EXPECT_TRUE(IdFilter::UpperBoundMerge(25, bf, a, full, b).IsSame(full)); EXPECT_TRUE(IdFilter::UpperBoundMerge(5, bf, a, b).IsSame(full)); EXPECT_THAT(IdFilter::UpperBoundMerge(25, bf, a, b).ids(), testing::ElementsAre(0, 2, 3, 4)); } TEST(IdFilterTest, IntersectPartial_ForEach) { IdFilter a = IdFilter(5, CreateBuffer<int64_t>({3, 4})); IdFilter b = IdFilter(5, CreateBuffer<int64_t>({0, 2, 3})); IdFilter c = IdFilter(5, CreateBuffer<int64_t>({0, 1, 3, 4})); using FnArgs = std::tuple<int64_t, int64_t, int64_t>; std::vector<FnArgs> res; auto fn = [&](int64_t id, int64_t offset1, int64_t offset2) { res.push_back({id, offset1, offset2}); }; IdFilter::IntersectPartial_ForEach(a, b, fn); EXPECT_EQ(res, (std::vector<FnArgs>{{3, 0, 2}})); res.clear(); IdFilter::IntersectPartial_ForEach(b, a, fn); EXPECT_EQ(res, (std::vector<FnArgs>{{3, 2, 0}})); res.clear(); IdFilter::IntersectPartial_ForEach(a, c, fn); EXPECT_EQ(res, (std::vector<FnArgs>{{3, 0, 2}, {4, 1, 3}})); res.clear(); IdFilter::IntersectPartial_ForEach(c, a, fn); EXPECT_EQ(res, (std::vector<FnArgs>{{3, 2, 0}, {4, 3, 1}})); res.clear(); IdFilter::IntersectPartial_ForEach(b, c, fn); EXPECT_EQ(res, (std::vector<FnArgs>{{0, 0, 0}, {3, 2, 2}})); res.clear(); IdFilter::IntersectPartial_ForEach(c, b, fn); EXPECT_EQ(res, (std::vector<FnArgs>{{0, 0, 0}, {3, 2, 2}})); res.clear(); } } }
2,393
#ifndef AROLLA_ARRAY_ARRAY_UTIL_H_ #define AROLLA_ARRAY_ARRAY_UTIL_H_ #include <cstdint> #include <utility> #include <vector> #include "absl/base/attributes.h" #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/types/span.h" #include "arolla/array/array.h" #include "arolla/array/id_filter.h" #include "arolla/dense_array/bitmap.h" #include "arolla/dense_array/dense_array.h" #include "arolla/memory/buffer.h" #include "arolla/memory/optional_value.h" #include "arolla/util/unit.h" namespace arolla { template <typename T> Array<Unit> ToArrayMask(const Array<T>& array) { DenseArray<Unit> dense{VoidBuffer(array.dense_data().size()), array.dense_data().bitmap, array.dense_data().bitmap_bit_offset}; return Array<Unit>(array.size(), array.id_filter(), std::move(dense), OptionalUnit(array.missing_id_value().present)); } template <typename T> DenseArray<T> ToDenseArray(const Array<T>& array) { return array.ToDenseForm().dense_data().ForceNoBitmapBitOffset(); } template <typename T> absl::StatusOr<Buffer<T>> ToBuffer(const Array<T>& array) { DenseArray<T> dense_array = array.ToDenseForm().dense_data(); if (dense_array.IsFull()) { return dense_array.values; } else { return absl::InvalidArgumentError( "Array with missing values can not be converted to a Buffer"); } } std::vector<int64_t> ArrayFirstPresentIds(const Array<Unit>& array, int64_t max_count); std::vector<int64_t> ArrayLastPresentIds(const Array<Unit>& array, int64_t max_count); namespace array_foreach_in_subset_impl { template <class T, class IdT, class Fn> ABSL_ATTRIBUTE_NOINLINE void SparseArrayForEachInSubset( const Array<T>& a, absl::Span<const IdT> subset, int64_t subset_ids_offset, Fn&& fn) { const Buffer<T>& values = a.dense_data().values; const IdFilter& f = a.id_filter(); auto array_it = f.ids().begin(); auto subset_it = subset.begin(); while (subset_it != subset.end() && array_it != f.ids().end()) { int64_t id_in_subset = *subset_it - subset_ids_offset; int64_t id_in_array = *array_it - f.ids_offset(); if (id_in_array == id_in_subset) { int64_t offset = array_it - f.ids().begin(); fn(id_in_subset, a.dense_data().present(offset), values[offset]); array_it++; subset_it++; } else if (id_in_array < id_in_subset) { array_it++; } else { fn(id_in_subset, a.missing_id_value().present, a.missing_id_value().value); subset_it++; } } for (; subset_it != subset.end(); ++subset_it) { int64_t id_in_subset = *subset_it - subset_ids_offset; fn(id_in_subset, a.missing_id_value().present, a.missing_id_value().value); } } } template <class T, class IdT, class Fn> void ArrayForEachInSubset(const Array<T>& a, absl::Span<const IdT> subset, int64_t subset_ids_offset, Fn&& fn) { if (a.IsConstForm()) { for (IdT s : subset) { fn(s - subset_ids_offset, a.missing_id_value().present, a.missing_id_value().value); } } else if (a.IsFullForm()) { const Buffer<T>& values = a.dense_data().values; for (IdT s : subset) { DCHECK(0 <= s - subset_ids_offset && s - subset_ids_offset < values.size()); int64_t id = std::clamp<int64_t>(s - subset_ids_offset, 0, values.size() - 1); fn(id, true, values[id]); } } else if (a.IsDenseForm()) { const Buffer<T>& values = a.dense_data().values; DCHECK_GE( a.dense_data().bitmap.size(), bitmap::BitmapSize(values.size() + a.dense_data().bitmap_bit_offset)); const bitmap::Word* presence = a.dense_data().bitmap.begin(); for (IdT s : subset) { DCHECK(0 <= s - subset_ids_offset && s - subset_ids_offset < values.size()); int64_t id = std::clamp<int64_t>(s - subset_ids_offset, 0, values.size() - 1); fn(id, bitmap::GetBit(presence, id + a.dense_data().bitmap_bit_offset), values[id]); } } else { array_foreach_in_subset_impl::SparseArrayForEachInSubset( a, subset, subset_ids_offset, std::forward<Fn>(fn)); } } } #endif #include "arolla/array/array_util.h" #include <cstdint> #include <vector> #include "arolla/array/array.h" #include "arolla/util/unit.h" namespace arolla { std::vector<int64_t> ArrayFirstPresentIds(const Array<Unit>& array, int64_t max_count) { std::vector<int64_t> res; if (max_count <= 0) { return res; } res.reserve(max_count); if (array.IsDenseForm() || array.HasMissingIdValue()) { int64_t index = 0; while (index < array.size() && res.size() < max_count) { if (array[index].present) res.push_back(index); index++; } } else { int64_t offset = 0; while (offset < array.dense_data().size() && res.size() < max_count) { if (array.dense_data().present(offset)) { res.push_back(array.id_filter().IdsOffsetToId(offset)); } offset++; } } return res; } std::vector<int64_t> ArrayLastPresentIds(const Array<Unit>& array, int64_t max_count) { std::vector<int64_t> res; if (max_count <= 0) { return res; } res.reserve(max_count); if (array.IsDenseForm() || array.HasMissingIdValue()) { int64_t index = array.size() - 1; while (index >= 0 && res.size() < max_count) { if (array[index].present) res.push_back(index); index--; } } else { int64_t offset = array.dense_data().size() - 1; while (offset >= 0 && res.size() < max_count) { if (array.dense_data().present(offset)) { res.push_back(array.id_filter().IdsOffsetToId(offset)); } offset--; } } return res; } }
#include "arolla/array/array_util.h" #include <cstdint> #include <optional> #include <utility> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "absl/types/span.h" #include "arolla/array/array.h" #include "arolla/dense_array/dense_array.h" #include "arolla/memory/optional_value.h" #include "arolla/util/testing/status_matchers_backport.h" #include "arolla/util/unit.h" using ::testing::ElementsAre; namespace arolla::testing { TEST(ArrayUtilTest, ToArrayMask) { Array<int> array = CreateArray<int>({1, 2, 3, std::nullopt, 1, 1, std::nullopt, 2}) .ToSparseForm(1); array = array.Slice(1, 7); Array<Unit> mask = ToArrayMask(array); EXPECT_THAT(mask, ElementsAre(kUnit, kUnit, std::nullopt, kUnit, kUnit, std::nullopt, kUnit)); } TEST(ArrayUtilTest, ToDenseArray) { Array<int> array = CreateArray<int>({1, 2, 3, std::nullopt, 1, 1, std::nullopt, 2}) .ToSparseForm(1); array = array.Slice(1, 7); DenseArray<int> dense_array = ToDenseArray(array); EXPECT_THAT(dense_array, ElementsAre(2, 3, std::nullopt, 1, 1, std::nullopt, 2)); } TEST(ArrayUtilTest, ToBuffer) { EXPECT_THAT( ToBuffer(CreateArray<int>({1, 2, std::nullopt})), StatusIs( absl::StatusCode::kInvalidArgument, ::testing::HasSubstr( "Array with missing values can not be converted to a Buffer"))); EXPECT_THAT(ToBuffer(CreateArray<int>({1, 2, 3})), IsOkAndHolds(ElementsAre(1, 2, 3))); } TEST(ArrayUtilTest, FirstAndLastPresentIds) { { Array<Unit> array(5, std::nullopt); EXPECT_THAT(ArrayFirstPresentIds(array, 3), ElementsAre()); EXPECT_THAT(ArrayLastPresentIds(array, 3), ElementsAre()); } { Array<Unit> array(5, kUnit); EXPECT_THAT(ArrayFirstPresentIds(array, 3), ElementsAre(0, 1, 2)); EXPECT_THAT(ArrayLastPresentIds(array, 3), ElementsAre(4, 3, 2)); EXPECT_THAT(ArrayFirstPresentIds(array, 10), ElementsAre(0, 1, 2, 3, 4)); EXPECT_THAT(ArrayLastPresentIds(array, 10), ElementsAre(4, 3, 2, 1, 0)); } { Array<Unit> array = CreateArray<Unit>({kUnit, kUnit, kUnit}); EXPECT_THAT(ArrayFirstPresentIds(array, 2), ElementsAre(0, 1)); EXPECT_THAT(ArrayLastPresentIds(array, 2), ElementsAre(2, 1)); } { Array<Unit> array = CreateArray<Unit>({kUnit, std::nullopt, kUnit}); EXPECT_THAT(ArrayFirstPresentIds(array, 2), ElementsAre(0, 2)); EXPECT_THAT(ArrayLastPresentIds(array, 2), ElementsAre(2, 0)); } { Array<Unit> array = CreateArray<Unit>({kUnit, std::nullopt, kUnit, std::nullopt, kUnit}) .ToSparseForm(); EXPECT_THAT(ArrayFirstPresentIds(array, 2), ElementsAre(0, 2)); EXPECT_THAT(ArrayLastPresentIds(array, 2), ElementsAre(4, 2)); } { Array<Unit> array = CreateArray<Unit>({kUnit, std::nullopt, kUnit, std::nullopt, kUnit}) .ToSparseForm(kUnit); EXPECT_THAT(ArrayFirstPresentIds(array, 2), ElementsAre(0, 2)); EXPECT_THAT(ArrayLastPresentIds(array, 2), ElementsAre(4, 2)); } { Array<Unit> array; EXPECT_THAT(ArrayFirstPresentIds(array, -1), ElementsAre()); EXPECT_THAT(ArrayLastPresentIds(array, -1), ElementsAre()); } } TEST(ArrayUtilTest, ArrayForEachInSubset) { using V = std::pair<int64_t, OptionalValue<float>>; std::vector<V> res; auto fn = [&res](int64_t id, bool present, float v) { res.push_back({id, {present, v}}); }; auto check = [&res](absl::Span<const V> expected) { ASSERT_EQ(res.size(), expected.size()); for (int i = 0; i < res.size(); ++i) { EXPECT_EQ(res[i].first, expected[i].first); EXPECT_EQ(res[i].second, expected[i].second); } res.clear(); }; { Array<float> array(5, std::nullopt); ArrayForEachInSubset<float, int>(array, {40, 41, 43}, 40, fn); check({{0, std::nullopt}, {1, std::nullopt}, {3, std::nullopt}}); } { Array<float> array(5, 7.0); ArrayForEachInSubset<float, int>(array, {40, 41, 43}, 40, fn); check({{0, 7.0}, {1, 7.0}, {3, 7.0}}); } { Array<float> array = CreateArray<float>({7.0, 8.0, 7.5, 8.5, 9.0}); ArrayForEachInSubset<float, int>(array, {40, 41, 43}, 40, fn); check({{0, 7.0}, {1, 8.0}, {3, 8.5}}); } { Array<float> array = CreateArray<float>({7.0, std::nullopt, std::nullopt, 8.5, 9.0}); ArrayForEachInSubset<float, int>(array, {40, 41, 43}, 40, fn); check({{0, 7.0}, {1, std::nullopt}, {3, 8.5}}); } { Array<float> array = CreateArray<float>({7.0, std::nullopt, std::nullopt, 8.5, 9.0}) .ToSparseForm(); ArrayForEachInSubset<float, int>(array, {40, 41, 43}, 40, fn); check({{0, 7.0}, {1, std::nullopt}, {3, 8.5}}); } { Array<float> array = CreateArray<float>({7.0, std::nullopt, std::nullopt, 8.5, 9.0}) .ToSparseForm(7.0); ArrayForEachInSubset<float, int>(array, {40, 41, 43}, 40, fn); check({{0, 7.0}, {1, std::nullopt}, {3, 8.5}}); } } }
2,394
#ifndef AROLLA_DECISION_FOREST_DECISION_FOREST_H_ #define AROLLA_DECISION_FOREST_DECISION_FOREST_H_ #include <cstdint> #include <memory> #include <string> #include <utility> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/container/flat_hash_set.h" #include "absl/log/check.h" #include "absl/status/statusor.h" #include "absl/types/span.h" #include "arolla/decision_forest/split_condition.h" #include "arolla/memory/frame.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/util/fingerprint.h" namespace arolla { class DecisionTreeNodeId { public: static DecisionTreeNodeId SplitNodeId(int64_t split_node_index) { DecisionTreeNodeId n; n.val_ = split_node_index; return n; } static DecisionTreeNodeId AdjustmentId(int64_t adjustment_index) { DecisionTreeNodeId n; n.val_ = -adjustment_index - 1; return n; } bool is_leaf() const { return val_ < 0; } int64_t split_node_index() const { DCHECK(!is_leaf()); return val_; } int64_t adjustment_index() const { DCHECK(is_leaf()); return -val_ - 1; } int64_t raw_index() const { return val_; } bool operator==(const DecisionTreeNodeId& other) const { return val_ == other.val_; } bool operator!=(const DecisionTreeNodeId& other) const { return val_ != other.val_; } private: int64_t val_ = 0; }; struct SplitNode { DecisionTreeNodeId child_if_false; DecisionTreeNodeId child_if_true; std::shared_ptr<const SplitCondition> condition; }; struct DecisionTree { std::vector<SplitNode> split_nodes; std::vector<float> adjustments; float weight = 1.0f; struct Tag { int step = 0; int submodel_id = 0; }; Tag tag; }; inline DecisionTreeNodeId GetTreeRootId(const DecisionTree& tree) { return tree.split_nodes.empty() ? DecisionTreeNodeId::AdjustmentId(0) : DecisionTreeNodeId::SplitNodeId(0); } struct TreeFilter { bool operator()(const DecisionTree::Tag& tree) const { return tree.step >= step_range_from && (step_range_to == -1 || tree.step < step_range_to) && (submodels.empty() || submodels.contains(tree.submodel_id)); } int step_range_from = 0; int step_range_to = -1; absl::flat_hash_set<int> submodels; }; class DecisionForest { public: static absl::StatusOr<std::unique_ptr<DecisionForest>> FromTrees( std::vector<DecisionTree>&& trees); absl::Status ValidateInputSlots( absl::Span<const TypedSlot> input_slots) const; const absl::flat_hash_map<int, QTypePtr>& GetRequiredQTypes() const { return required_qtypes_; } absl::Span<const DecisionTree> GetTrees() const { return trees_; } std::vector<DecisionTree> TreesCopy() const { return trees_; } int submodel_count() const { return submodel_count_; } int step_count() const { return step_count_; } Fingerprint fingerprint() const { return fingerprint_; } private: explicit DecisionForest(std::vector<DecisionTree>&& trees) : trees_(std::move(trees)) {} absl::Status Initialize(); std::vector<DecisionTree> trees_; absl::flat_hash_map<int, QTypePtr> required_qtypes_; Fingerprint fingerprint_; int submodel_count_; int step_count_; }; std::string ToDebugString(const DecisionTree& tree); std::string ToDebugString(const DecisionForest& forest); float DecisionForestNaiveEvaluation(const DecisionForest& forest, const ConstFramePtr ctx, absl::Span<const TypedSlot> inputs, const TreeFilter& filter = {}); using DecisionForestPtr = std::shared_ptr<const DecisionForest>; AROLLA_DECLARE_FINGERPRINT_HASHER_TRAITS(SplitNode); AROLLA_DECLARE_FINGERPRINT_HASHER_TRAITS(TreeFilter); AROLLA_DECLARE_FINGERPRINT_HASHER_TRAITS(DecisionForestPtr); AROLLA_DECLARE_QTYPE(DecisionForestPtr); AROLLA_DECLARE_QTYPE(TreeFilter); } #endif #include "arolla/decision_forest/decision_forest.h" #include <algorithm> #include <cstddef> #include <map> #include <memory> #include <string> #include <utility> #include <vector> #include "absl/algorithm/container.h" #include "absl/log/check.h" #include "absl/memory/memory.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" #include "absl/types/span.h" #include "arolla/memory/frame.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/simple_qtype.h" #include "arolla/util/fingerprint.h" #include "arolla/util/status_macros_backport.h" namespace arolla { using NodeId = DecisionTreeNodeId; float DecisionForestNaiveEvaluation(const DecisionForest& forest, const ConstFramePtr ctx, absl::Span<const TypedSlot> inputs, const TreeFilter& filter) { DCHECK_OK(forest.ValidateInputSlots(inputs)); double res = 0; for (const auto& tree : forest.GetTrees()) { if (!filter(tree.tag)) continue; NodeId node_id = GetTreeRootId(tree); while (!node_id.is_leaf()) { DCHECK(node_id.split_node_index() >= 0 && node_id.split_node_index() < tree.split_nodes.size()); const auto& node = tree.split_nodes[node_id.split_node_index()]; if (node.condition->EvaluateCondition(ctx, inputs)) { node_id = node.child_if_true; } else { node_id = node.child_if_false; } } DCHECK(node_id.adjustment_index() >= 0 && node_id.adjustment_index() < tree.adjustments.size()); res += tree.adjustments[node_id.adjustment_index()] * tree.weight; } return res; } namespace { std::string NodeIdToString(DecisionTreeNodeId id) { if (id.is_leaf()) { return absl::StrFormat("adjustments[%d]", id.adjustment_index()); } else { return absl::StrFormat("goto %d", id.split_node_index()); } } } std::string ToDebugString(const DecisionTree& tree) { std::string res = " DecisionTree {\n"; absl::StrAppendFormat(&res, " tag { step: %d submodel_id: %d }\n", tree.tag.step, tree.tag.submodel_id); absl::StrAppendFormat(&res, " weight: %f\n", tree.weight); absl::StrAppend(&res, " split_nodes {\n"); for (size_t i = 0; i < tree.split_nodes.size(); ++i) { const SplitNode& node = tree.split_nodes[i]; absl::StrAppendFormat(&res, " %d: IF %s THEN %s ELSE %s\n", i, node.condition->ToString(), NodeIdToString(node.child_if_true), NodeIdToString(node.child_if_false)); } absl::StrAppend(&res, " }\n"); absl::StrAppend(&res, " adjustments:"); for (float adj : tree.adjustments) { absl::StrAppendFormat(&res, " %f", adj); } absl::StrAppend(&res, "\n }"); return res; } std::string ToDebugString(const DecisionForest& forest) { std::string res = "DecisionForest {\n"; auto required_qtypes = forest.GetRequiredQTypes(); for (const auto& [k, v] : std::map<int, QTypePtr>(required_qtypes.begin(), required_qtypes.end())) { absl::StrAppendFormat(&res, " input #%d: %s\n", k, v->name()); } for (const auto& tree : forest.GetTrees()) { absl::StrAppend(&res, ToDebugString(tree), "\n"); } absl::StrAppend(&res, "}"); return res; } absl::StatusOr<std::unique_ptr<DecisionForest>> DecisionForest::FromTrees( std::vector<DecisionTree>&& trees) { auto forest = absl::WrapUnique(new DecisionForest(std::move(trees))); RETURN_IF_ERROR(forest->Initialize()); return forest; } absl::Status DecisionForest::ValidateInputSlots( absl::Span<const TypedSlot> input_slots) const { for (const auto& kv : required_qtypes_) { if (kv.first >= input_slots.size()) { return absl::InvalidArgumentError("not enough arguments"); } if (input_slots[kv.first].GetType() != kv.second) { return absl::InvalidArgumentError("type mismatch"); } } return absl::OkStatus(); } absl::Status DecisionForest::Initialize() { FingerprintHasher hasher("::arolla::DecisionForest"); hasher.Combine(trees_.size()); submodel_count_ = 0; step_count_ = 0; for (const auto& tree : trees_) { hasher.CombineSpan(tree.split_nodes) .CombineSpan(tree.adjustments) .Combine(tree.weight, tree.tag.step, tree.tag.submodel_id); if (tree.tag.submodel_id < 0) { return absl::InvalidArgumentError("submodel_id can not be negative"); } if (tree.tag.step < 0) { return absl::InvalidArgumentError("step can not be negative"); } submodel_count_ = std::max(submodel_count_, tree.tag.submodel_id + 1); step_count_ = std::max(step_count_, tree.tag.step + 1); if (tree.split_nodes.size() + 1 != tree.adjustments.size()) { return absl::InvalidArgumentError("incorrect number of regions"); } for (const auto& node : tree.split_nodes) { bool is_correct = true; DecisionTreeNodeId child = node.child_if_false; if (child.is_leaf()) { is_correct &= child.adjustment_index() < tree.adjustments.size(); } else { is_correct &= child.split_node_index() < tree.split_nodes.size(); } child = node.child_if_true; if (child.is_leaf()) { is_correct &= child.adjustment_index() < tree.adjustments.size(); } else { is_correct &= child.split_node_index() < tree.split_nodes.size(); } if (!is_correct) return absl::InvalidArgumentError("incorrect split node"); for (auto id_type : node.condition->GetInputSignatures()) { auto it = required_qtypes_.emplace(id_type.id, id_type.type); if (it.first->second != id_type.type) { return absl::InvalidArgumentError( "types mismatch in decision forest"); } } } } fingerprint_ = std::move(hasher).Finish(); return absl::OkStatus(); } void FingerprintHasherTraits<SplitNode>::operator()( FingerprintHasher* hasher, const SplitNode& value) const { hasher->Combine(value.child_if_false.raw_index(), value.child_if_true.raw_index()); value.condition->CombineToFingerprintHasher(hasher); } void FingerprintHasherTraits<TreeFilter>::operator()( FingerprintHasher* hasher, const TreeFilter& value) const { std::vector<int> submodels(value.submodels.begin(), value.submodels.end()); absl::c_sort(submodels); hasher->Combine(value.step_range_from, value.step_range_to) .CombineSpan(submodels); } void FingerprintHasherTraits<DecisionForestPtr>::operator()( FingerprintHasher* hasher, const DecisionForestPtr& value) const { hasher->Combine(value->fingerprint()); } AROLLA_DEFINE_SIMPLE_QTYPE(DECISION_FOREST, DecisionForestPtr); AROLLA_DEFINE_SIMPLE_QTYPE(TREE_FILTER, TreeFilter); }
#include "arolla/decision_forest/decision_forest.h" #include <cmath> #include <cstdint> #include <limits> #include <utility> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "arolla/decision_forest/split_conditions/interval_split_condition.h" #include "arolla/decision_forest/split_conditions/set_of_values_split_condition.h" #include "arolla/memory/frame.h" #include "arolla/memory/memory_allocation.h" #include "arolla/memory/optional_value.h" #include "arolla/qtype/typed_slot.h" #include "arolla/util/testing/status_matchers_backport.h" namespace arolla::testing { namespace { using ::arolla::testing::StatusIs; using ::testing::HasSubstr; using ::testing::Test; constexpr float inf = std::numeric_limits<float>::infinity(); constexpr auto S = DecisionTreeNodeId::SplitNodeId; constexpr auto A = DecisionTreeNodeId::AdjustmentId; TEST(DecisionForestTest, ForestValidation) { DecisionTree tree1; tree1.adjustments = {0.5, 1.5, 2.5, 3.5}; tree1.split_nodes = {{S(1), S(2), IntervalSplit(0, 1.5, inf)}, {A(0), A(1), SetOfValuesSplit<int64_t>(1, {5}, false)}, {A(2), A(3), IntervalSplit(0, -inf, 10)}}; DecisionTree tree2; tree2.adjustments = {1., 2.}; tree2.split_nodes = {{A(0), A(1), IntervalSplit(0, 1.5, inf)}}; DecisionTree tree3; tree3.adjustments = {1., 2., 3.}; tree3.split_nodes = {{A(0), A(1), IntervalSplit(0, 1.5, inf)}}; DecisionTree tree4; tree4.adjustments = {1., 2.}; tree4.split_nodes = { {A(0), A(1), IntervalSplit(1, 1.5, inf)}}; EXPECT_OK(DecisionForest::FromTrees({tree1, tree2})); EXPECT_THAT(DecisionForest::FromTrees({tree1, tree3}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("incorrect number of regions"))); EXPECT_THAT(DecisionForest::FromTrees({tree1, tree4}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("types mismatch in decision forest"))); } TEST(DecisionForestTest, Fingerprint) { DecisionTree tree; tree.adjustments = {0.5, 1.5, 2.5, 3.5}; tree.split_nodes = {{S(1), S(2), IntervalSplit(0, 1.5, inf)}, {A(0), A(1), SetOfValuesSplit<int64_t>(1, {5}, false)}, {A(2), A(3), IntervalSplit(0, -inf, 10)}}; ASSERT_OK_AND_ASSIGN(auto forest1, DecisionForest::FromTrees({tree})); ASSERT_OK_AND_ASSIGN(auto forest2, DecisionForest::FromTrees({tree})); tree.adjustments[1] += 0.1; ASSERT_OK_AND_ASSIGN(auto forest3, DecisionForest::FromTrees({tree})); EXPECT_EQ(forest1->fingerprint(), forest2->fingerprint()); EXPECT_NE(forest1->fingerprint(), forest3->fingerprint()); } TEST(DecisionForestTest, ToDebugString) { std::vector<DecisionTree> trees(2); trees[0].adjustments = {0.5, 1.5, 2.5, 3.5}; trees[0].split_nodes = { {S(1), S(2), IntervalSplit(0, 1.5, inf)}, {A(0), A(1), SetOfValuesSplit<int64_t>(1, {5}, false)}, {A(2), A(3), IntervalSplit(0, -inf, 10)}}; trees[1].adjustments = {5}; trees[1].tag.step = 1; ASSERT_OK_AND_ASSIGN(auto forest, DecisionForest::FromTrees(std::move(trees))); EXPECT_EQ(ToDebugString(*forest), "DecisionForest {\n" " input #0: OPTIONAL_FLOAT32\n" " input #1: OPTIONAL_INT64\n" " DecisionTree {\n" " tag { step: 0 submodel_id: 0 }\n" " weight: 1.000000\n" " split_nodes {\n" " 0: IF #0 in range [1.500000 inf] THEN goto 2 ELSE goto 1\n" " 1: IF #1 in set [5] " "THEN adjustments[1] ELSE adjustments[0]\n" " 2: IF #0 in range [-inf 10.000000] " "THEN adjustments[3] ELSE adjustments[2]\n" " }\n" " adjustments: 0.500000 1.500000 2.500000 3.500000\n" " }\n" " DecisionTree {\n" " tag { step: 1 submodel_id: 0 }\n" " weight: 1.000000\n" " split_nodes {\n" " }\n" " adjustments: 5.000000\n" " }\n" "}"); } TEST(DecisionForestTest, InputsValidation) { std::vector<DecisionTree> trees(1); DecisionTree& tree = trees[0]; tree.adjustments = {0.5, 1.5, 2.5, 3.5}; tree.split_nodes = {{S(1), S(2), IntervalSplit(0, 1.5, inf)}, {A(0), A(1), SetOfValuesSplit<int64_t>(1, {5}, false)}, {A(2), A(3), IntervalSplit(0, -inf, 10)}}; FrameLayout::Builder bldr; auto slot_float = bldr.AddSlot<OptionalValue<float>>(); auto slot_int64 = bldr.AddSlot<OptionalValue<int64_t>>(); FrameLayout layout = std::move(bldr).Build(); ASSERT_OK_AND_ASSIGN(auto forest, DecisionForest::FromTrees(std::move(trees))); EXPECT_OK(forest->ValidateInputSlots( {TypedSlot::FromSlot(slot_float), TypedSlot::FromSlot(slot_int64)})); EXPECT_THAT(forest->ValidateInputSlots({}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("not enough arguments"))); EXPECT_THAT( forest->ValidateInputSlots( {TypedSlot::FromSlot(slot_float), TypedSlot::FromSlot(slot_float)}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("type mismatch"))); } TEST(DecisionForestTest, TreeFilter) { DecisionTree::Tag t0{.step = 0, .submodel_id = 0}; DecisionTree::Tag t1{.step = 1, .submodel_id = 1}; DecisionTree::Tag t2{.step = 2, .submodel_id = 0}; TreeFilter f0{}; TreeFilter f1{.submodels = {0}}; TreeFilter f2{.submodels = {1}}; TreeFilter f3{.submodels = {0, 1}}; TreeFilter f4{.step_range_from = 1}; TreeFilter f5{.step_range_to = 2}; TreeFilter f6{.step_range_from = 1, .step_range_to = 2, .submodels = {0}}; EXPECT_EQ((std::vector<bool>{f0(t0), f0(t1), f0(t2)}), (std::vector<bool>{true, true, true})); EXPECT_EQ((std::vector<bool>{f1(t0), f1(t1), f1(t2)}), (std::vector<bool>{true, false, true})); EXPECT_EQ((std::vector<bool>{f2(t0), f2(t1), f2(t2)}), (std::vector<bool>{false, true, false})); EXPECT_EQ((std::vector<bool>{f3(t0), f3(t1), f3(t2)}), (std::vector<bool>{true, true, true})); EXPECT_EQ((std::vector<bool>{f4(t0), f4(t1), f4(t2)}), (std::vector<bool>{false, true, true})); EXPECT_EQ((std::vector<bool>{f5(t0), f5(t1), f5(t2)}), (std::vector<bool>{true, true, false})); EXPECT_EQ((std::vector<bool>{f6(t0), f6(t1), f6(t2)}), (std::vector<bool>{false, false, false})); } TEST(DecisionForestTest, GetTreeRootId) { DecisionTree tree1; tree1.adjustments = {1.0}; EXPECT_TRUE(GetTreeRootId(tree1).is_leaf()); DecisionTree tree2; tree2.split_nodes = {{A(0), A(1), IntervalSplit(0, 1, 2)}}; tree2.adjustments = {1.0, 2.0}; EXPECT_FALSE(GetTreeRootId(tree2).is_leaf()); } TEST(DecisionForestTest, NaiveEvaluation) { std::vector<DecisionTree> trees(3); trees[0].adjustments = {0.5, 1.5, 2.5, 3.5}; trees[0].split_nodes = { {S(1), S(2), IntervalSplit(0, 1.5, inf)}, {A(0), A(1), SetOfValuesSplit<int64_t>(1, {5}, false)}, {A(2), A(3), IntervalSplit(0, -inf, 10)}}; trees[1].adjustments = {5.0}; trees[1].tag = {1, 1}; trees[2].adjustments = {2.0}; trees[2].tag = {2, 0}; ASSERT_OK_AND_ASSIGN(auto forest, DecisionForest::FromTrees(std::move(trees))); EXPECT_EQ(forest->step_count(), 3); EXPECT_EQ(forest->submodel_count(), 2); FrameLayout::Builder bldr; auto input1_slot = bldr.AddSlot<OptionalValue<float>>(); auto input2_slot = bldr.AddSlot<OptionalValue<int64_t>>(); std::vector<TypedSlot> slots = {TypedSlot::FromSlot(input1_slot), TypedSlot::FromSlot(input2_slot)}; FrameLayout layout = std::move(bldr).Build(); MemoryAllocation alloc(&layout); FramePtr frame = alloc.frame(); frame.Set(input1_slot, 1.0f); frame.Set(input2_slot, 5); EXPECT_EQ(DecisionForestNaiveEvaluation(*forest, frame, slots), 8.5); frame.Set(input1_slot, NAN); frame.Set(input2_slot, {}); EXPECT_EQ(DecisionForestNaiveEvaluation(*forest, frame, slots), 7.5); frame.Set(input1_slot, 2.0f); frame.Set(input2_slot, 4); EXPECT_EQ(DecisionForestNaiveEvaluation(*forest, frame, slots), 10.5); EXPECT_EQ(DecisionForestNaiveEvaluation(*forest, frame, slots, TreeFilter{.submodels = {0}}), 5.5); EXPECT_EQ(DecisionForestNaiveEvaluation(*forest, frame, slots, TreeFilter{.submodels = {1}}), 5.0); EXPECT_EQ(DecisionForestNaiveEvaluation(*forest, frame, slots, TreeFilter{.submodels = {0, 1}}), 10.5); EXPECT_EQ(DecisionForestNaiveEvaluation(*forest, frame, slots, TreeFilter{.step_range_from = 1}), 7.0); EXPECT_EQ(DecisionForestNaiveEvaluation(*forest, frame, slots, TreeFilter{.step_range_to = 2}), 8.5); } } }
2,395
#ifndef AROLLA_DECISION_FOREST_TEST_UTIL_TEST_UTIL_H_ #define AROLLA_DECISION_FOREST_TEST_UTIL_TEST_UTIL_H_ #include <cstdint> #include <memory> #include <vector> #include "absl/random/random.h" #include "absl/status/status.h" #include "absl/types/span.h" #include "arolla/decision_forest/decision_forest.h" #include "arolla/memory/frame.h" #include "arolla/qtype/qtype.h" namespace arolla { absl::Status FillWithRandomValue(TypedSlot tslot, FramePtr ctx, absl::BitGen* rnd, double missed_prob = 0); absl::Status FillArrayWithRandomValues(int64_t size, TypedSlot tslot, FramePtr ctx, absl::BitGen* rnd, double missed_prob = 0); void CreateSlotsForForest(const DecisionForest& forest, FrameLayout::Builder* layout_builder, std::vector<TypedSlot>* slots); absl::Status CreateArraySlotsForForest(const DecisionForest& forest, FrameLayout::Builder* layout_builder, std::vector<TypedSlot>* slots); DecisionTree CreateRandomFloatTree(absl::BitGen* rnd, int num_features, bool interactions, int num_splits, double range_split_prob = 0.0, double equality_split_prob = 0.0); std::unique_ptr<const DecisionForest> CreateRandomFloatForest( absl::BitGen* rnd, int num_features, bool interactions, int min_num_splits, int max_num_splits, int num_trees); DecisionTree CreateRandomTree(absl::BitGen* rnd, bool interactions, int num_splits, std::vector<QTypePtr>* feature_types); DecisionTree CreateRandomObliviousTree(absl::BitGen* rnd, int depth, std::vector<QTypePtr>* feature_types); std::unique_ptr<const DecisionForest> CreateRandomForest( absl::BitGen* rnd, int num_features, bool interactions, int min_num_splits, int max_num_splits, int num_trees, absl::Span<const QTypePtr> feature_types = {}); } #endif #include "arolla/decision_forest/testing/test_util.h" #include <algorithm> #include <cmath> #include <cstdint> #include <limits> #include <memory> #include <string> #include <utility> #include <vector> #include "absl/container/flat_hash_set.h" #include "absl/random/distributions.h" #include "absl/random/random.h" #include "absl/status/status.h" #include "absl/types/span.h" #include "arolla/decision_forest/decision_forest.h" #include "arolla/decision_forest/split_condition.h" #include "arolla/decision_forest/split_conditions/interval_split_condition.h" #include "arolla/decision_forest/split_conditions/set_of_values_split_condition.h" #include "arolla/dense_array/dense_array.h" #include "arolla/dense_array/qtype/types.h" #include "arolla/memory/frame.h" #include "arolla/memory/optional_value.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/optional_qtype.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/typed_slot.h" namespace arolla { namespace { constexpr int kSetOfValuesSize = 10; template <typename ConditionFactoryFn> DecisionTree CreateRandomTreeImpl(absl::BitGen* rnd, int num_features, bool interactions, int num_splits, ConditionFactoryFn condition_factory) { DecisionTree tree; tree.adjustments.resize(num_splits + 1); for (float& val : tree.adjustments) { val = absl::Uniform<uint8_t>(*rnd); } int single_feature_id = absl::Uniform<int32_t>(*rnd, 0, num_features); for (int i = 0; i < num_splits; ++i) { auto child1 = i * 2 + 1 < num_splits ? DecisionTreeNodeId::SplitNodeId(i * 2 + 1) : DecisionTreeNodeId::AdjustmentId(i * 2 + 1 - num_splits); auto child2 = i * 2 + 2 < num_splits ? DecisionTreeNodeId::SplitNodeId(i * 2 + 2) : DecisionTreeNodeId::AdjustmentId(i * 2 + 2 - num_splits); int feature_id; if (interactions) { feature_id = absl::Uniform<int32_t>(*rnd, 0, num_features); } else { feature_id = single_feature_id; } tree.split_nodes.push_back({child1, child2, condition_factory(feature_id)}); } return tree; } } absl::Status FillWithRandomValue(TypedSlot tslot, FramePtr ctx, absl::BitGen* rnd, double missed_prob) { if (tslot.byte_offset() == FrameLayout::Slot<float>::kUninitializedOffset) { return absl::OkStatus(); } bool missed = (absl::Uniform<float>(*rnd, 0, 1) < missed_prob); if (tslot.GetType() == GetOptionalQType<float>()) { auto slot = tslot.ToSlot<OptionalValue<float>>().value(); auto val = OptionalValue<float>(absl::Uniform<float>(*rnd, 0, 1)); ctx.Set(slot, missed ? OptionalValue<float>{} : val); } else if (tslot.GetType() == GetOptionalQType<int64_t>()) { auto slot = tslot.ToSlot<OptionalValue<int64_t>>().value(); auto val = OptionalValue<int64_t>(absl::Uniform<int64_t>(*rnd, 0, 1000)); ctx.Set(slot, missed ? OptionalValue<int64_t>{} : val); } else { return absl::UnimplementedError(std::string("Unimplemented for type: ") + std::string(tslot.GetType()->name())); } return absl::OkStatus(); } absl::Status FillArrayWithRandomValues(int64_t size, TypedSlot tslot, FramePtr ctx, absl::BitGen* rnd, double missed_prob) { if (tslot.byte_offset() == FrameLayout::Slot<float>::kUninitializedOffset) { return absl::OkStatus(); } if (tslot.GetType() == GetDenseArrayQType<float>()) { auto slot = tslot.UnsafeToSlot<DenseArray<float>>(); DenseArrayBuilder<float> bldr(size); for (int64_t i = 0; i < size; ++i) { bool missed = (absl::Uniform<float>(*rnd, 0, 1) < missed_prob); if (!missed) { bldr.Set(i, absl::Uniform<float>(*rnd, 0, 1)); } } ctx.Set(slot, std::move(bldr).Build()); } else if (tslot.GetType() == GetDenseArrayQType<int64_t>()) { auto slot = tslot.UnsafeToSlot<DenseArray<int64_t>>(); DenseArrayBuilder<int64_t> bldr(size); for (int64_t i = 0; i < size; ++i) { bool missed = (absl::Uniform<float>(*rnd, 0, 1) < missed_prob); if (!missed) { bldr.Set(i, absl::Uniform<int64_t>(*rnd, 0, 1000)); } } ctx.Set(slot, std::move(bldr).Build()); } else { return absl::UnimplementedError(std::string("Unimplemented for type: ") + std::string(tslot.GetType()->name())); } return absl::OkStatus(); } void CreateSlotsForForest(const DecisionForest& forest, FrameLayout::Builder* layout_builder, std::vector<TypedSlot>* slots) { auto placeholder = TypedSlot::FromSlot(FrameLayout::Slot<float>::UnsafeUninitializedSlot()); for (auto id_qtype : forest.GetRequiredQTypes()) { while (slots->size() <= id_qtype.first) { slots->push_back(placeholder); } QTypePtr qtype = id_qtype.second; (*slots)[id_qtype.first] = AddSlot(qtype, layout_builder); } } absl::Status CreateArraySlotsForForest(const DecisionForest& forest, FrameLayout::Builder* layout_builder, std::vector<TypedSlot>* slots) { auto placeholder = TypedSlot::FromSlot(FrameLayout::Slot<float>::UnsafeUninitializedSlot()); for (auto id_qtype : forest.GetRequiredQTypes()) { while (slots->size() <= id_qtype.first) { slots->push_back(placeholder); } QTypePtr qtype = id_qtype.second; if (qtype == GetOptionalQType<float>()) { (*slots)[id_qtype.first] = TypedSlot::FromSlot(layout_builder->AddSlot<DenseArray<float>>()); } else if (qtype == GetOptionalQType<int64_t>()) { (*slots)[id_qtype.first] = TypedSlot::FromSlot(layout_builder->AddSlot<DenseArray<int64_t>>()); } else { return absl::UnimplementedError(std::string("Unimplemented for type: ") + std::string(qtype->name())); } } if (slots->empty()) { slots->push_back( TypedSlot::FromSlot(layout_builder->AddSlot<DenseArray<float>>())); } return absl::OkStatus(); } DecisionTree CreateRandomFloatTree(absl::BitGen* rnd, int num_features, bool interactions, int num_splits, double range_split_prob, double equality_split_prob) { return CreateRandomTreeImpl( rnd, num_features, interactions, num_splits, [&](int feature_id) { float split_type_rnd = absl::Uniform<float>(*rnd, 0, 1); if (split_type_rnd < range_split_prob + equality_split_prob) { float sp0 = absl::Uniform<uint8_t>(*rnd) / 256.0; float sp1 = split_type_rnd < range_split_prob ? absl::Uniform<uint8_t>(*rnd) / 256.0 : sp0; return IntervalSplit(feature_id, std::min(sp0, sp1), std::max(sp0, sp1)); } else { float split_point = absl::Uniform<uint8_t>(*rnd) / 256.0; if (absl::Bernoulli(*rnd, 0.5)) { return IntervalSplit(feature_id, -INFINITY, split_point); } else { return IntervalSplit(feature_id, split_point, +INFINITY); } } }); } std::unique_ptr<const DecisionForest> CreateRandomFloatForest( absl::BitGen* rnd, int num_features, bool interactions, int min_num_splits, int max_num_splits, int num_trees) { std::vector<DecisionTree> trees; trees.reserve(num_trees); for (int i = 0; i < num_trees; ++i) { int num_splits = absl::Uniform<int32_t>(*rnd, min_num_splits, max_num_splits); trees.push_back( CreateRandomFloatTree(rnd, num_features, interactions, num_splits)); } return DecisionForest::FromTrees(std::move(trees)).value(); } DecisionTree CreateRandomTree(absl::BitGen* rnd, bool interactions, int num_splits, std::vector<QTypePtr>* feature_types) { const float inf = std::numeric_limits<float>::infinity(); return CreateRandomTreeImpl( rnd, feature_types->size(), interactions, num_splits, [&](int feature_id) -> std::shared_ptr<SplitCondition> { QTypePtr& type = (*feature_types)[feature_id]; if (!type) { type = absl::Bernoulli(*rnd, 0.5) ? GetOptionalQType<float>() : GetOptionalQType<int64_t>(); } if (type == GetOptionalQType<float>()) { float split_point = absl::Uniform<uint8_t>(*rnd) / 256.0; if (absl::Bernoulli(*rnd, 0.5)) { return IntervalSplit(feature_id, -inf, split_point); } else { return IntervalSplit(feature_id, split_point, +inf); } } else { absl::flat_hash_set<int64_t> values; for (int i = 0; i < kSetOfValuesSize; ++i) { values.insert(absl::Uniform<int64_t>(*rnd, 0, 1000)); } return SetOfValuesSplit<int64_t>(feature_id, values, absl::Bernoulli(*rnd, 0.5)); } }); } DecisionTree CreateRandomObliviousTree(absl::BitGen* rnd, int depth, std::vector<QTypePtr>* feature_types) { const float inf = std::numeric_limits<float>::infinity(); std::vector<std::shared_ptr<SplitCondition>> conditions(depth); for (int i = 0; i < depth; ++i) { int feature_id = absl::Uniform<int32_t>(*rnd, 0, feature_types->size()); QTypePtr& type = (*feature_types)[feature_id]; if (!type) { type = absl::Bernoulli(*rnd, 0.5) ? GetOptionalQType<float>() : GetOptionalQType<int64_t>(); } if (type == GetOptionalQType<float>()) { float split_point = absl::Uniform<uint8_t>(*rnd) / 256.0; if (absl::Bernoulli(*rnd, 0.5)) { conditions[i] = IntervalSplit(feature_id, -inf, split_point); } else { conditions[i] = IntervalSplit(feature_id, split_point, +inf); } } else { absl::flat_hash_set<int64_t> values; for (int i = 0; i < kSetOfValuesSize; ++i) { values.insert(absl::Uniform<int64_t>(*rnd, 0, 1000)); } conditions[i] = SetOfValuesSplit<int64_t>(feature_id, values, absl::Bernoulli(*rnd, 0.5)); } } int cond_id = 0; int node_id = 0; return CreateRandomTreeImpl(rnd, feature_types->size(), false, (1 << depth) - 1, [&](int) { node_id++; bool last_in_the_row = node_id & (node_id + 1); if (last_in_the_row) { return conditions[cond_id]; } else { return conditions[cond_id++]; } }); } std::unique_ptr<const DecisionForest> CreateRandomForest( absl::BitGen* rnd, int num_features, bool interactions, int min_num_splits, int max_num_splits, int num_trees, absl::Span<const QTypePtr> feature_types) { std::vector<QTypePtr> types; for (int feature_id = 0; feature_id < num_features; feature_id++) { if (feature_id < feature_types.size() && feature_types[feature_id]) { types.push_back(feature_types[feature_id]); } else { types.push_back(nullptr); } } std::vector<DecisionTree> trees; trees.reserve(num_trees); for (int i = 0; i < num_trees; ++i) { int num_splits = absl::Uniform<int32_t>(*rnd, min_num_splits, max_num_splits); trees.push_back(CreateRandomTree(rnd, interactions, num_splits, &types)); } return DecisionForest::FromTrees(std::move(trees)).value(); } }
#include "arolla/decision_forest/testing/test_util.h" #include <cstddef> #include <cstdint> #include <utility> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/log/check.h" #include "absl/random/random.h" #include "arolla/decision_forest/decision_forest.h" #include "arolla/memory/frame.h" #include "arolla/memory/optional_value.h" #include "arolla/qexpr/eval_context.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/typed_slot.h" namespace arolla { namespace { TEST(TestUtilTest, FillWithRandomValue) { absl::BitGen rnd; FrameLayout::Builder bldr; auto opt_float_slot = bldr.AddSlot<OptionalValue<float>>(); auto opt_int64_slot = bldr.AddSlot<OptionalValue<int64_t>>(); auto layout = std::move(bldr).Build(); RootEvaluationContext ctx(&layout); ctx.Set(opt_float_slot, OptionalValue<float>(-1.0)); ctx.Set(opt_int64_slot, OptionalValue<int64_t>(-1)); CHECK_OK(FillWithRandomValue(TypedSlot::FromSlot(opt_float_slot), ctx.frame(), &rnd)); CHECK_OK(FillWithRandomValue(TypedSlot::FromSlot(opt_int64_slot), ctx.frame(), &rnd)); EXPECT_NE(OptionalValue<float>(-1.0), ctx.Get(opt_float_slot)); EXPECT_NE(OptionalValue<int64_t>(-1), ctx.Get(opt_int64_slot)); } TEST(TestUtilTest, CreateSlotsForForest) { absl::BitGen rnd; auto forest = CreateRandomForest(&rnd, 5, true, 1, 64, 16); FrameLayout::Builder bldr; std::vector<TypedSlot> slots; CreateSlotsForForest(*forest, &bldr, &slots); EXPECT_OK(forest->ValidateInputSlots(slots)); } TEST(TestUtilTest, CreateRandomFloatTree) { absl::BitGen rnd; for (size_t depth = 0; depth <= 15; ++depth) { auto tree = CreateRandomFloatTree(&rnd, 5, true, (1 << depth) - 1); EXPECT_EQ(tree.adjustments.size(), 1 << depth); EXPECT_EQ(tree.split_nodes.size(), (1 << depth) - 1); } } TEST(TestUtilTest, CreateRandomFloatForest) { absl::BitGen rnd; auto forest = CreateRandomFloatForest(&rnd, 5, true, 1, 64, 16); EXPECT_EQ(forest->GetTrees().size(), 16); EXPECT_GE(forest->GetRequiredQTypes().size(), 1); EXPECT_LE(forest->GetRequiredQTypes().size(), 5); for (const DecisionTree& tree : forest->GetTrees()) { EXPECT_LE(tree.split_nodes.size(), 64); } } TEST(TestUtilTest, CreateRandomForest) { absl::BitGen rnd; auto forest = CreateRandomForest(&rnd, 5, true, 1, 64, 16); EXPECT_EQ(forest->GetTrees().size(), 16); EXPECT_GE(forest->GetRequiredQTypes().size(), 1); EXPECT_LE(forest->GetRequiredQTypes().size(), 5); for (const DecisionTree& tree : forest->GetTrees()) { EXPECT_LE(tree.split_nodes.size(), 64); } } TEST(TestUtilTest, CreateRandomObliviousTree) { absl::BitGen rnd; std::vector<QTypePtr> types(10); auto tree = CreateRandomObliviousTree(&rnd, 3, &types); ASSERT_EQ(tree.split_nodes.size(), 7); EXPECT_EQ(tree.split_nodes[1].condition, tree.split_nodes[2].condition); EXPECT_EQ(tree.split_nodes[3].condition, tree.split_nodes[4].condition); EXPECT_EQ(tree.split_nodes[4].condition, tree.split_nodes[5].condition); EXPECT_EQ(tree.split_nodes[5].condition, tree.split_nodes[6].condition); } TEST(TestUtilTest, CreateRandomForestWithoutInteractions) { absl::BitGen rnd; auto forest = CreateRandomForest(&rnd, 5, false, 512, 512, 1); EXPECT_EQ(forest->GetTrees().size(), 1); EXPECT_EQ(forest->GetRequiredQTypes().size(), 1); } } }
2,396
#ifndef AROLLA_DECISION_FOREST_POINTWISE_EVALUATION_FOREST_EVALUATOR_H_ #define AROLLA_DECISION_FOREST_POINTWISE_EVALUATION_FOREST_EVALUATOR_H_ #include <cstdint> #include <functional> #include <memory> #include <utility> #include <vector> #include "absl/container/inlined_vector.h" #include "absl/log/check.h" #include "absl/status/statusor.h" #include "absl/types/span.h" #include "arolla/decision_forest/decision_forest.h" #include "arolla/decision_forest/pointwise_evaluation/bitmask_eval.h" #include "arolla/decision_forest/pointwise_evaluation/bound_split_conditions.h" #include "arolla/decision_forest/pointwise_evaluation/pointwise.h" #include "arolla/decision_forest/pointwise_evaluation/single_input_eval.h" #include "arolla/memory/frame.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/typed_slot.h" #include "arolla/util/status_macros_backport.h" namespace arolla { class ForestEvaluator { public: struct CompilationParams { static constexpr CompilationParams Default() { return {}; } bool enable_regular_eval = true; bool enable_bitmask_eval = true; bool enable_single_input_eval = true; }; struct Output { TreeFilter filter; FrameLayout::Slot<float> slot; }; static absl::StatusOr<ForestEvaluator> Compile( const DecisionForest& decision_forest, absl::Span<const TypedSlot> input_slots, absl::Span<const Output> outputs, CompilationParams params = CompilationParams::Default()); void Eval(ConstFramePtr input_ctx, FramePtr output_ctx) const; private: template <class T> using Predictor = BoostedPredictor<float, T, std::plus<double>, int>; template <class T> using PredictorCompiler = BoostedPredictorCompiler<float, T, std::plus<double>, int>; using UniversalBoundCondition = VariantBoundCondition<IntervalBoundCondition, SetOfValuesBoundCondition<int64_t>, VirtualBoundCondition>; struct RegularPredictors { Predictor<UniversalBoundCondition> universal_predictor; Predictor<IntervalBoundCondition> interval_splits_predictor; float Predict(ConstFramePtr input_ctx) const { return universal_predictor.Predict(input_ctx, 0.0) + interval_splits_predictor.Predict(input_ctx, 0.0); } }; using RegularPredictorsList = absl::InlinedVector<RegularPredictors, 2>; class RegularPredictorsBuilder; explicit ForestEvaluator(std::vector<FrameLayout::Slot<float>>&& output_slots, RegularPredictorsList&& predictors, std::unique_ptr<BitmaskEval>&& bitmask_predictor, SingleInputEval&& single_input_predictor) : output_slots_(std::move(output_slots)), regular_predictors_(std::move(predictors)), bitmask_predictor_(std::move(bitmask_predictor)), single_input_predictor_(std::move(single_input_predictor)) {} std::vector<FrameLayout::Slot<float>> output_slots_; RegularPredictorsList regular_predictors_; std::unique_ptr<BitmaskEval> bitmask_predictor_; SingleInputEval single_input_predictor_; }; class SimpleForestEvaluator { public: static absl::StatusOr<SimpleForestEvaluator> Compile( const DecisionForest& decision_forest, absl::Span<const TypedSlot> input_slots, ForestEvaluator::CompilationParams params = ForestEvaluator::CompilationParams::Default()) { DCHECK(GetQType<float>()->type_layout().HasField(0, typeid(float))); ForestEvaluator::Output output{ .filter = {}, .slot = FrameLayout::Slot<float>::UnsafeSlotFromOffset(0)}; ASSIGN_OR_RETURN(auto evaluator, ForestEvaluator::Compile(decision_forest, input_slots, {output}, params)); return SimpleForestEvaluator(std::move(evaluator)); } float Eval(ConstFramePtr ctx) const { float res; FramePtr output_ctx(&res, &GetQType<float>()->type_layout()); evaluator_.Eval(ctx, output_ctx); return res; } private: explicit SimpleForestEvaluator(ForestEvaluator&& evaluator) : evaluator_(std::move(evaluator)) {} ForestEvaluator evaluator_; }; } #endif #include "arolla/decision_forest/pointwise_evaluation/forest_evaluator.h" #include <algorithm> #include <cstddef> #include <cstdint> #include <map> #include <memory> #include <optional> #include <utility> #include <vector> #include "absl/container/inlined_vector.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "absl/types/span.h" #include "arolla/decision_forest/decision_forest.h" #include "arolla/decision_forest/pointwise_evaluation/bitmask_builder.h" #include "arolla/decision_forest/pointwise_evaluation/bound_split_conditions.h" #include "arolla/decision_forest/pointwise_evaluation/oblivious.h" #include "arolla/decision_forest/pointwise_evaluation/single_input_eval.h" #include "arolla/decision_forest/split_condition.h" #include "arolla/decision_forest/split_conditions/interval_split_condition.h" #include "arolla/memory/frame.h" #include "arolla/qtype/typed_slot.h" #include "arolla/util/fast_dynamic_downcast_final.h" #include "arolla/util/status_macros_backport.h" namespace arolla { namespace { bool HasOnlyIntervalSplitConditions(const DecisionTree& tree) { for (const auto& split_node : tree.split_nodes) { if (!fast_dynamic_downcast_final<const IntervalSplitCondition*>( split_node.condition.get())) return false; } return true; } absl::StatusOr<std::vector<int>> SplitTreesByGroups( absl::Span<const DecisionTree> trees, absl::Span<const ForestEvaluator::Output> outputs) { if (outputs.empty()) { return absl::InvalidArgumentError("at least one output is expected"); } std::vector<int> tree2group(trees.size(), -1); for (int group_id = 0; group_id < outputs.size(); ++group_id) { for (int tree_id = 0; tree_id < trees.size(); ++tree_id) { if (!outputs[group_id].filter(trees[tree_id].tag)) continue; if (tree2group[tree_id] != -1) { return absl::InvalidArgumentError(absl::StrFormat( "intersection of groups for outputs #%d and #%d is not empty", tree2group[tree_id], group_id)); } tree2group[tree_id] = group_id; } } return tree2group; } std::optional<SplitCondition::InputSignature> GetSingleInputSignature( const DecisionTree& tree) { std::optional<SplitCondition::InputSignature> input_signature; for (const auto& node : tree.split_nodes) { auto signatures = node.condition->GetInputSignatures(); if (signatures.size() != 1 || (input_signature && input_signature->id != signatures[0].id)) { return std::nullopt; } input_signature = signatures[0]; } return input_signature; } } class ForestEvaluator::RegularPredictorsBuilder { public: RegularPredictorsBuilder(int group_count, absl::Span<const TypedSlot> input_slots) : group_count_(group_count), input_slots_(input_slots.begin(), input_slots.end()), universal_compilers_(group_count), interval_splits_compilers_(group_count) {} absl::Status AddTree(const DecisionTree& tree, int group_id) { if (HasOnlyIntervalSplitConditions(tree)) { return AddTreeToRegularForestCompiler( tree, [this](const std::shared_ptr<const SplitCondition>& cond) { auto interval_cond = std::static_pointer_cast<const IntervalSplitCondition>(cond); return IntervalBoundCondition::Create(interval_cond, input_slots_); }, &interval_splits_compilers_[group_id]); } else { return AddTreeToRegularForestCompiler( tree, [this](const std::shared_ptr<const SplitCondition>& cond) { return UniversalBoundCondition::Create(cond, input_slots_); }, &universal_compilers_[group_id]); } } absl::StatusOr<RegularPredictorsList> Build() && { RegularPredictorsList res; res.reserve(group_count_); for (int i = 0; i < group_count_; ++i) { ASSIGN_OR_RETURN(auto universal_predictor, universal_compilers_[i].Compile()); ASSIGN_OR_RETURN(auto interval_splits_predictor, interval_splits_compilers_[i].Compile()); res.push_back({std::move(universal_predictor), std::move(interval_splits_predictor)}); } return res; } private: template <typename ForestCompiler, typename CreateConditionFunc> absl::Status AddTreeToRegularForestCompiler(const DecisionTree& tree, CreateConditionFunc create_cond, ForestCompiler* forest_compiler) { auto tree_compiler = forest_compiler->AddTree( tree.split_nodes.size() + tree.adjustments.size(), tree.tag.submodel_id); for (int64_t id = 0; id < tree.split_nodes.size(); ++id) { const auto& split_node = tree.split_nodes[id]; auto child_if_false = split_node.child_if_false.is_leaf() ? split_node.child_if_false.adjustment_index() + tree.split_nodes.size() : split_node.child_if_false.split_node_index(); auto child_if_true = split_node.child_if_true.is_leaf() ? split_node.child_if_true.adjustment_index() + tree.split_nodes.size() : split_node.child_if_true.split_node_index(); ASSIGN_OR_RETURN(auto cond, create_cond(split_node.condition)); RETURN_IF_ERROR( tree_compiler.SetNode(id, child_if_true, child_if_false, cond)); } for (int64_t i = 0; i < tree.adjustments.size(); ++i) { RETURN_IF_ERROR(tree_compiler.SetLeaf(i + tree.split_nodes.size(), tree.adjustments[i] * tree.weight)); } return absl::OkStatus(); } int group_count_; std::vector<TypedSlot> input_slots_; std::vector<PredictorCompiler<UniversalBoundCondition>> universal_compilers_; std::vector<PredictorCompiler<IntervalBoundCondition>> interval_splits_compilers_; }; absl::StatusOr<ForestEvaluator> ForestEvaluator::Compile( const DecisionForest& decision_forest, absl::Span<const TypedSlot> input_slots, absl::Span<const Output> outputs, CompilationParams params) { ASSIGN_OR_RETURN(auto tree2group, SplitTreesByGroups(decision_forest.GetTrees(), outputs)); std::vector<FrameLayout::Slot<float>> output_slots; output_slots.reserve(outputs.size()); for (const auto& output : outputs) { output_slots.push_back(output.slot); } RegularPredictorsBuilder regular_builder(outputs.size(), input_slots); BitmaskBuilder bitmask_builder(input_slots, output_slots); SingleInputBuilder single_input_builder(input_slots, output_slots); std::vector<std::map<int, double>> consts(outputs.size()); if (tree2group.size() != decision_forest.GetTrees().size()) { return absl::InternalError("size of tree2group doesn't match trees"); } for (size_t i = 0; i < decision_forest.GetTrees().size(); ++i) { if (tree2group[i] == -1) { continue; } if (tree2group[i] < 0 || tree2group[i] >= outputs.size()) { return absl::InternalError("invalid tree2group mapping"); } const DecisionTree& tree = decision_forest.GetTrees()[i]; if (params.enable_regular_eval && tree.split_nodes.empty()) { consts[tree2group[i]][tree.tag.submodel_id] += tree.adjustments[0] * tree.weight; continue; } if (params.enable_single_input_eval) { if (std::optional<SplitCondition::InputSignature> input_signature = GetSingleInputSignature(tree)) { if (single_input_builder.IsInputTypeSupported(input_signature->type)) { RETURN_IF_ERROR(single_input_builder.AddTree(tree, *input_signature, tree2group[i])); continue; } } } if (params.enable_bitmask_eval && std::all_of(tree.split_nodes.begin(), tree.split_nodes.end(), BitmaskBuilder::IsSplitNodeSupported)) { auto oblivious = ToObliviousTree(tree); if (oblivious.has_value() && (oblivious->layer_splits.size() <= BitmaskBuilder::kMaxRegionsForBitmask)) { bitmask_builder.AddObliviousTree(std::move(*oblivious), tree2group[i]); continue; } if (tree.adjustments.size() <= BitmaskBuilder::kMaxRegionsForBitmask) { bitmask_builder.AddSmallTree(tree, tree2group[i]); continue; } } if (params.enable_regular_eval) { RETURN_IF_ERROR(regular_builder.AddTree(tree, tree2group[i])); } else { return absl::InvalidArgumentError( "No suitable evaluator. Use enable_regular_eval=true."); } } for (int group_id = 0; group_id < consts.size(); ++group_id) { for (const auto& [submodel_id, value] : consts[group_id]) { DecisionTree tree; tree.adjustments = {static_cast<float>(value)}; tree.tag.submodel_id = submodel_id; RETURN_IF_ERROR(regular_builder.AddTree(tree, group_id)); } } ASSIGN_OR_RETURN(auto regular_predictors, std::move(regular_builder).Build()); ASSIGN_OR_RETURN(auto bitmask_predictor, std::move(bitmask_builder).Build()); ASSIGN_OR_RETURN(auto single_input_predictor, std::move(single_input_builder).Build()); return ForestEvaluator(std::move(output_slots), std::move(regular_predictors), std::move(bitmask_predictor), std::move(single_input_predictor)); } void ForestEvaluator::Eval(const ConstFramePtr input_ctx, FramePtr output_ctx) const { for (size_t i = 0; i < output_slots_.size(); ++i) { *output_ctx.GetMutable(output_slots_[i]) = regular_predictors_[i].Predict(input_ctx); } if (bitmask_predictor_) { bitmask_predictor_->IncrementalEval(input_ctx, output_ctx); } single_input_predictor_.IncrementalEval(input_ctx, output_ctx); } }
#include "arolla/decision_forest/pointwise_evaluation/forest_evaluator.h" #include <cmath> #include <cstdint> #include <limits> #include <memory> #include <string> #include <utility> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/random/distributions.h" #include "absl/random/random.h" #include "absl/status/status.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" #include "absl/types/span.h" #include "arolla/decision_forest/decision_forest.h" #include "arolla/decision_forest/split_condition.h" #include "arolla/decision_forest/split_conditions/interval_split_condition.h" #include "arolla/decision_forest/split_conditions/set_of_values_split_condition.h" #include "arolla/decision_forest/testing/test_util.h" #include "arolla/memory/frame.h" #include "arolla/memory/memory_allocation.h" #include "arolla/memory/optional_value.h" #include "arolla/qtype/optional_qtype.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/typed_slot.h" #include "arolla/util/bytes.h" #include "arolla/util/testing/status_matchers_backport.h" namespace arolla { namespace { using ::arolla::testing::StatusIs; using ::testing::HasSubstr; constexpr float kInf = std::numeric_limits<float>::infinity(); constexpr auto S = DecisionTreeNodeId::SplitNodeId; constexpr auto A = DecisionTreeNodeId::AdjustmentId; const ForestEvaluator::CompilationParams kDefaultEval{ .enable_regular_eval = true, .enable_bitmask_eval = true, .enable_single_input_eval = true}; const ForestEvaluator::CompilationParams kRegularEval{ .enable_regular_eval = true, .enable_bitmask_eval = false, .enable_single_input_eval = false}; const ForestEvaluator::CompilationParams kBitmaskEval{ .enable_regular_eval = false, .enable_bitmask_eval = true, .enable_single_input_eval = false}; const ForestEvaluator::CompilationParams kSingleInputEval{ .enable_regular_eval = false, .enable_bitmask_eval = false, .enable_single_input_eval = true}; void FillArgs(FramePtr ctx, int row_id, absl::Span<const TypedSlot> slots) {} template <typename T, typename... Tn> void FillArgs(FramePtr frame, int row_id, absl::Span<const TypedSlot> slots, const std::vector<OptionalValue<T>>& inputs1, const std::vector<OptionalValue<Tn>>&... inputsN) { auto slot = slots[0].ToSlot<OptionalValue<T>>().value(); frame.Set(slot, inputs1[row_id]); FillArgs(frame, row_id, slots.subspan(1), inputsN...); } class SourceLocation { public: SourceLocation(int line, const char* filename) : line_(line), file_name_(filename) {} const char* file_name() { return file_name_.c_str(); } constexpr int line() const { return line_; } static SourceLocation current(int line = __builtin_LINE(), const char* file_name = __builtin_FILE()) { return SourceLocation(line, file_name); } private: int line_ = 0; std::string file_name_; }; std::string ErrFormat(SourceLocation loc, ForestEvaluator::CompilationParams params, const std::string& msg, int row_id) { return absl::StrFormat( "%s Test at %s:%d, row_id=%d, params = " "{enable_regular_eval=%d, enable_bitmask_eval=%d, " "enable_single_input_eval=%d}", msg, loc.file_name(), loc.line(), row_id, params.enable_regular_eval, params.enable_bitmask_eval, params.enable_single_input_eval); } template <typename... T> void TestCases(SourceLocation loc, const DecisionForest& forest, absl::Span<const TreeFilter> groups, ForestEvaluator::CompilationParams params, absl::Span<const std::vector<float>> expected_outputs, const std::vector<OptionalValue<T>>&... inputs) { ASSERT_TRUE(((expected_outputs.size() == inputs.size()) && ...)) << absl::StrCat( "Input and output vector sizes are different: (", absl::StrJoin({expected_outputs.size(), inputs.size()...}, ", "), ")"); std::vector<TypedSlot> input_slots; std::vector<ForestEvaluator::Output> outputs; FrameLayout::Builder layout_builder; CreateSlotsForForest(forest, &layout_builder, &input_slots); outputs.reserve(groups.size()); for (const TreeFilter& filter : groups) { outputs.push_back({filter, layout_builder.AddSlot<float>()}); } FrameLayout layout = std::move(layout_builder).Build(); ASSERT_OK_AND_ASSIGN( auto evaluator, ForestEvaluator::Compile(forest, input_slots, outputs, params)); MemoryAllocation alloc(&layout); auto frame = alloc.frame(); for (int i = 0; i < expected_outputs.size(); ++i) { FillArgs(frame, i, input_slots, inputs...); evaluator.Eval(frame, frame); for (int j = 0; j < outputs.size(); ++j) { EXPECT_EQ(frame.Get(outputs[j].slot), expected_outputs[i][j]) << ErrFormat(loc, params, "Incorrect output.", i); } } } void RandomTestAgainstReferenceImplementation( SourceLocation loc, std::vector<DecisionTree> trees, const std::vector<ForestEvaluator::CompilationParams>& params, absl::BitGen* rnd) { for (int i = 0; i < trees.size(); ++i) { trees[i].tag.submodel_id = i % 4; } TreeFilter group0{.submodels{0, 3}}; TreeFilter group1{.submodels{1, 2}}; ASSERT_OK_AND_ASSIGN(auto forest, DecisionForest::FromTrees(std::move(trees))); std::vector<TypedSlot> input_slots; std::vector<ForestEvaluator::Output> outputs; FrameLayout::Builder layout_builder; CreateSlotsForForest(*forest, &layout_builder, &input_slots); outputs.push_back({group0, layout_builder.AddSlot<float>()}); outputs.push_back({group1, layout_builder.AddSlot<float>()}); FrameLayout layout = std::move(layout_builder).Build(); std::vector<ForestEvaluator> evaluators; for (auto p : params) { ASSERT_OK_AND_ASSIGN(auto evaluator, ForestEvaluator::Compile( *forest, input_slots, outputs, p)); evaluators.push_back(std::move(evaluator)); } MemoryAllocation alloc(&layout); FramePtr frame = alloc.frame(); for (int item_id = 0; item_id < 15; ++item_id) { for (auto slot : input_slots) { ASSERT_OK(FillWithRandomValue(slot, frame, rnd, 0.25)); } float reference_implementation_res0 = DecisionForestNaiveEvaluation(*forest, frame, input_slots, group0); float reference_implementation_res1 = DecisionForestNaiveEvaluation(*forest, frame, input_slots, group1); for (int eval_id = 0; eval_id < evaluators.size(); ++eval_id) { const ForestEvaluator& evaluator = evaluators[eval_id]; frame.Set(outputs[0].slot, 0.0f); frame.Set(outputs[1].slot, 0.0f); evaluator.Eval(frame, frame); EXPECT_FLOAT_EQ(reference_implementation_res0, frame.Get(outputs[0].slot)) << ErrFormat(loc, params[eval_id], "Incorrect output #0 in Eval", item_id); EXPECT_FLOAT_EQ(reference_implementation_res1, frame.Get(outputs[1].slot)) << ErrFormat(loc, params[eval_id], "Incorrect output #1 in Eval", item_id); } } } TEST(ForestEvaluator, GroupsValidation) { std::vector<DecisionTree> trees(3); trees[0].tag.submodel_id = 3; trees[0].adjustments = {1.0}; trees[1].tag.submodel_id = 2; trees[1].adjustments = {1.0}; trees[2].tag.submodel_id = 1; trees[2].adjustments = {1.0}; ASSERT_OK_AND_ASSIGN(auto forest, DecisionForest::FromTrees(std::move(trees))); EXPECT_THAT(ForestEvaluator::Compile(*forest, {}, {}).status(), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("at least one output is expected"))); auto fake_slot = FrameLayout::Slot<float>::UnsafeUninitializedSlot(); EXPECT_THAT( ForestEvaluator::Compile( *forest, {}, {ForestEvaluator::Output{{.submodels = {1, 3}}, fake_slot}, ForestEvaluator::Output{{.submodels = {2, 3}}, fake_slot}}) .status(), StatusIs( absl::StatusCode::kInvalidArgument, HasSubstr( "intersection of groups for outputs #0 and #1 is not empty"))); EXPECT_OK(ForestEvaluator::Compile( *forest, {}, {ForestEvaluator::Output{{.submodels = {1, 3}}, fake_slot}, ForestEvaluator::Output{{.submodels = {2}}, fake_slot}}) .status()); EXPECT_OK(ForestEvaluator::Compile( *forest, {}, {ForestEvaluator::Output{{.submodels = {1}}, fake_slot}, ForestEvaluator::Output{{.submodels = {2}}, fake_slot}}) .status()); } TEST(ForestEvaluator, EmptyForest) { ASSERT_OK_AND_ASSIGN(auto forest, DecisionForest::FromTrees({})); for (auto params : {kDefaultEval, kRegularEval, kBitmaskEval, kSingleInputEval}) { TestCases<>(SourceLocation::current(), *forest, {{.submodels = {0}}, {.submodels = {1}}}, params, {{0.0, 0.0}}); } } TEST(ForestEvaluator, Constant) { std::vector<DecisionTree> trees(2); trees[0].tag = {.submodel_id = 0}; trees[0].adjustments = {1.5}; trees[1].tag = {.submodel_id = 1}; trees[1].adjustments = {2.5}; ASSERT_OK_AND_ASSIGN(auto forest, DecisionForest::FromTrees(std::move(trees))); for (auto params : {kDefaultEval, kRegularEval, kBitmaskEval}) { TestCases<>(SourceLocation::current(), *forest, {{.submodels = {0}}, {.submodels = {1}}}, params, {{1.5, 2.5}}); } } TEST(ForestEvaluator, SmallForest) { std::vector<DecisionTree> trees(2); trees[0].tag = {.submodel_id = 0}; trees[0].adjustments = {0.5, 1.5, 2.5, 3.5}; trees[0].split_nodes = { {S(1), S(2), IntervalSplit(0, 1.5, kInf)}, {A(0), A(2), SetOfValuesSplit<int64_t>(1, {1, 2}, false)}, {A(1), A(3), IntervalSplit(0, -kInf, 10)}}; trees[1].tag = {.submodel_id = 1}; trees[1].adjustments = {-1.0, 1.0}; trees[1].split_nodes = {{A(0), A(1), IntervalSplit(0, 1, 5)}}; ASSERT_OK_AND_ASSIGN(auto forest, DecisionForest::FromTrees(std::move(trees))); for (auto params : {kDefaultEval, kRegularEval, kBitmaskEval}) { TestCases<float, int64_t>( SourceLocation::current(), *forest, {{.submodels = {0}}, {.submodels = {1}}}, params, {{0.5, -1}, {2.5, -1}, {2.5, 1}, {3.5, 1}, {3.5, -1}, {1.5, -1}, {2.5, -1}, {0.5, -1}}, {0, 0, 1.2, 1.6, 7.0, 13.5, NAN, {}}, {3, 1, 1, 1, 1, 1, 1, {}}); } } TEST(ForestEvaluator, RangesSplits) { DecisionTree tree; tree.split_nodes = {{S(2), S(1), IntervalSplit(0, -1.0, 1.0)}, {A(1), A(2), IntervalSplit(0, 0.5, 0.5)}, {A(0), A(3), IntervalSplit(0, 2.5, 3.5)}}; tree.adjustments = {0.0, 1.0, 2.0, 3.0}; ASSERT_OK_AND_ASSIGN(auto forest, DecisionForest::FromTrees({tree})); for (auto params : {kDefaultEval, kRegularEval, kBitmaskEval, kSingleInputEval}) { TestCases<float>( SourceLocation::current(), *forest, {{}}, params, {{0}, {0}, {0}, {1}, {2}, {3}, {3}, {3}}, {{}, -5, 5, -1, 0.5, 2.5, 3.0, 3.5}); } } TEST(ForestEvaluator, EqualSplits) { DecisionTree tree; tree.split_nodes = {{S(2), S(1), IntervalSplit(0, 1.0, 1.0)}, {A(1), A(2), IntervalSplit(1, 5.0, 5.0)}, {A(0), A(3), IntervalSplit(1, -5.0, -5.0)}}; tree.adjustments = {0.0, 1.0, 2.0, 3.0}; ASSERT_OK_AND_ASSIGN(auto forest, DecisionForest::FromTrees({tree})); for (auto params : {kDefaultEval, kRegularEval, kBitmaskEval}) { TestCases<float, float>( SourceLocation::current(), *forest, {{}}, params, {{0}, {0}, {0}, {1}, {1}, {2}, {3}, {3}}, {{}, 0.0, -5.0, 1.0, 1.0, 1.0, 0.0, {}}, {{}, {}, {}, {}, -5.0, +5.0, -5.0, -5.0}); } } TEST(ForestEvaluator, BytesInput) { DecisionTree tree; tree.split_nodes = { {A(0), A(1), SetOfValuesSplit<Bytes>(0, {Bytes("X")}, false)}}; tree.adjustments = {0.0, 1.0}; ASSERT_OK_AND_ASSIGN(auto forest, DecisionForest::FromTrees({tree})); for (auto params : {kDefaultEval, kRegularEval}) { TestCases<Bytes>(SourceLocation::current(), *forest, {{}}, params, {{0}, {1}, {0}}, {{}, Bytes("X"), Bytes("Y")}); } } TEST(ForestEvaluator, BitmaskNotPossible) { absl::BitGen rnd; auto forest = CreateRandomForest(&rnd, 10, true, 70, 70, 1); std::vector<TypedSlot> slots; FrameLayout::Builder layout_builder; CreateSlotsForForest(*forest, &layout_builder, &slots); EXPECT_THAT( SimpleForestEvaluator::Compile(*forest, slots, kBitmaskEval), StatusIs( absl::StatusCode::kInvalidArgument, HasSubstr("No suitable evaluator. Use enable_regular_eval=true."))); } TEST(ForestEvaluator, SingleInputEvalNotPossible) { DecisionTree tree; tree.split_nodes = {{S(2), S(1), IntervalSplit(0, 1.0, 1.0)}, {A(1), A(2), IntervalSplit(1, 5.0, 5.0)}, {A(0), A(3), IntervalSplit(1, -5.0, -5.0)}}; tree.adjustments = {0.0, 1.0, 2.0, 3.0}; ASSERT_OK_AND_ASSIGN(auto forest, DecisionForest::FromTrees({tree})); std::vector<TypedSlot> slots; FrameLayout::Builder layout_builder; CreateSlotsForForest(*forest, &layout_builder, &slots); EXPECT_THAT( SimpleForestEvaluator::Compile(*forest, slots, kSingleInputEval), StatusIs( absl::StatusCode::kInvalidArgument, HasSubstr("No suitable evaluator. Use enable_regular_eval=true."))); } TEST(ForestEvaluator, ObliviousTree) { DecisionTree tree; std::vector<std::shared_ptr<SplitCondition>> conditions = { IntervalSplit(0, -5, 5), IntervalSplit(1, 0, kInf), SetOfValuesSplit<int64_t>(2, {1, 2}, false), IntervalSplit(3, -kInf, 3.0), SetOfValuesSplit<int64_t>(4, {4, 2}, true), IntervalSplit(5, -1, 7), IntervalSplit(6, -kInf, -5)}; int layer_size = 1; for (int layer = 0; layer < conditions.size(); ++layer) { int layer_offset = tree.split_nodes.size() + layer_size; for (int i = 0; i < layer_size; ++i) { auto left = (layer == conditions.size() - 1) ? A(i * 2) : S(layer_offset + i * 2); auto right = (layer == conditions.size() - 1) ? A(i * 2 + 1) : S(layer_offset + i * 2 + 1); tree.split_nodes.push_back({left, right, conditions[layer]}); } layer_size *= 2; } for (int i = 0; i < layer_size; ++i) { tree.adjustments.push_back(i); } ASSERT_OK_AND_ASSIGN(auto forest, DecisionForest::FromTrees({tree})); for (auto params : {kDefaultEval, kRegularEval, kBitmaskEval}) { TestCases<float, float, int64_t, float, int64_t, float, float>( SourceLocation::current(), *forest, {{}}, params, {{58}, {86}, {12}, {39}, {112}}, {{}, 3, -7, 15, -4}, {10, -1, {}, 25, 1}, {2, 1, 3, {}, 1}, {0, {}, -5, 8, 14}, {1, 2, {}, 4, 5}, {0, 4, -3, 7, {}}, {10, 5, -3, -8, {}}); } } TEST(ForestEvaluator, TestAgainstReferenceOnSmallTrees) { absl::BitGen rnd; std::vector<QTypePtr> types; for (int input_id = 0; input_id < 10; input_id++) { types.push_back(GetOptionalQType<float>()); } for (int input_id = 10; input_id < 15; input_id++) { types.push_back(GetOptionalQType<int64_t>()); } for (int iteration = 0; iteration < 10; ++iteration) { std::vector<DecisionTree> trees; for (int i = 0; i < 10; ++i) { int num_splits = absl::Uniform<int32_t>(rnd, 0, 32); trees.push_back( CreateRandomTree(&rnd, true, num_splits, &types)); } RandomTestAgainstReferenceImplementation( SourceLocation::current(), trees, {kDefaultEval, kRegularEval, kBitmaskEval}, &rnd); } } TEST(ForestEvaluator, TestAgainstReferenceOnSingleInputTrees) { absl::BitGen rnd; std::vector<QTypePtr> types; for (int input_id = 0; input_id < 10; input_id++) { types.push_back(GetOptionalQType<float>()); } for (int input_id = 10; input_id < 15; input_id++) { types.push_back(GetOptionalQType<int64_t>()); } for (int iteration = 0; iteration < 10; ++iteration) { std::vector<DecisionTree> trees; for (int i = 0; i < 10; ++i) { int num_splits = absl::Uniform<int32_t>(rnd, 1, 1024); trees.push_back( CreateRandomTree(&rnd, false, num_splits, &types)); } RandomTestAgainstReferenceImplementation( SourceLocation::current(), trees, {kDefaultEval, kRegularEval, kSingleInputEval}, &rnd); } } TEST(ForestEvaluator, TestAgainstReference) { absl::BitGen rnd; std::vector<QTypePtr> types; for (int feature_id = 0; feature_id < 10; feature_id++) { types.push_back(GetOptionalQType<float>()); } for (int feature_id = 10; feature_id < 15; feature_id++) { types.push_back(GetOptionalQType<int64_t>()); } for (int iteration = 0; iteration < 5; ++iteration) { std::vector<DecisionTree> trees; for (int i = 0; i < 10; ++i) { int num_splits = absl::Uniform<int32_t>(rnd, 0, 1024); trees.push_back( CreateRandomTree(&rnd, true, num_splits, &types)); } for (int i = 0; i < 10; ++i) { int num_splits = absl::Uniform<int32_t>(rnd, 0, 1024); trees.push_back( CreateRandomTree(&rnd, false, num_splits, &types)); } for (int i = 0; i < 10; ++i) { int num_splits = absl::Uniform<int32_t>(rnd, 0, 1024); trees.push_back(CreateRandomFloatTree( &rnd, 10, true, num_splits, 0.4, 0.4)); } for (int i = 0; i < 10; ++i) { int num_splits = absl::Uniform<int32_t>(rnd, 0, 32); trees.push_back( CreateRandomTree(&rnd, true, num_splits, &types)); } for (int i = 0; i < 5; ++i) { int depth = absl::Uniform<int32_t>(rnd, 1, 20); trees.push_back(CreateRandomObliviousTree(&rnd, depth, &types)); } RandomTestAgainstReferenceImplementation( SourceLocation::current(), trees, {kDefaultEval, kRegularEval}, &rnd); } } } }
2,397
#ifndef AROLLA_DECISION_FOREST_POINTWISE_EVALUATION_OBLIVIOUS_H_ #define AROLLA_DECISION_FOREST_POINTWISE_EVALUATION_OBLIVIOUS_H_ #include <memory> #include <optional> #include <vector> #include "arolla/decision_forest/decision_forest.h" #include "arolla/decision_forest/split_condition.h" namespace arolla { struct ObliviousDecisionTree { DecisionTree::Tag tag; std::vector<std::shared_ptr<const SplitCondition>> layer_splits; std::vector<float> adjustments; }; std::optional<ObliviousDecisionTree> ToObliviousTree(const DecisionTree& tree); } #endif #include "arolla/decision_forest/pointwise_evaluation/oblivious.h" #include <cstddef> #include <memory> #include <optional> #include <utility> #include <vector> #include "absl/log/check.h" #include "arolla/decision_forest/decision_forest.h" #include "arolla/decision_forest/split_condition.h" namespace arolla { namespace { bool IsPowerOf2(size_t x) { return (x & (x - 1)) == 0; } struct StackEntry { DecisionTreeNodeId node_id; int depth; }; template <typename CallbackFn> bool TraverseTree(const DecisionTree& tree, CallbackFn callback) { std::vector<StackEntry> stack; stack.reserve(32); stack.push_back(StackEntry{GetTreeRootId(tree), 0}); while (!stack.empty()) { auto [node_id, depth] = stack.back(); stack.pop_back(); if (!callback(node_id, depth)) { return false; } if (!node_id.is_leaf()) { const auto& node = tree.split_nodes[node_id.split_node_index()]; stack.push_back(StackEntry{node.child_if_true, depth + 1}); stack.push_back(StackEntry{node.child_if_false, depth + 1}); } } return true; } } std::optional<ObliviousDecisionTree> ToObliviousTree(const DecisionTree& tree) { size_t region_count = tree.adjustments.size(); if (!IsPowerOf2(region_count)) { return std::nullopt; } size_t depth = region_count ? __builtin_ctz(region_count) : 0; std::vector<std::shared_ptr<const SplitCondition>> layer_splits; layer_splits.reserve(depth); std::vector<float> adjustments; adjustments.reserve(region_count); auto process_node = [&](DecisionTreeNodeId node_id, int current_depth) { if (node_id.is_leaf()) { if (current_depth != depth) { return false; } adjustments.push_back(tree.adjustments[node_id.adjustment_index()] * tree.weight); } else { if (current_depth >= depth) { return false; } const auto& node = tree.split_nodes[node_id.split_node_index()]; if (layer_splits.size() == current_depth) { layer_splits.push_back(node.condition); } else { DCHECK_LT(current_depth, layer_splits.size()); if (*layer_splits[current_depth] != *node.condition) { return false; } } } return true; }; if (!TraverseTree(tree, process_node)) { return std::nullopt; } return ObliviousDecisionTree{tree.tag, std::move(layer_splits), std::move(adjustments)}; } }
#include "arolla/decision_forest/pointwise_evaluation/oblivious.h" #include <limits> #include <memory> #include <optional> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "arolla/decision_forest/decision_forest.h" #include "arolla/decision_forest/split_condition.h" #include "arolla/decision_forest/split_conditions/interval_split_condition.h" namespace arolla { namespace { using ::testing::ElementsAre; constexpr auto S = DecisionTreeNodeId::SplitNodeId; constexpr auto A = DecisionTreeNodeId::AdjustmentId; constexpr float inf = std::numeric_limits<float>::infinity(); std::shared_ptr<SplitCondition> Cond(int input_id, float left, float right) { return std::make_shared<IntervalSplitCondition>(input_id, left, right); } TEST(ObliviousTest, Errors) { { DecisionTree tree; tree.split_nodes = {{A(0), S(1), Cond(0, -inf, 1.0)}, {A(1), A(2), Cond(0, -1.0, inf)}}; tree.adjustments = {0.0, 1.0, 2.0}; EXPECT_EQ(ToObliviousTree(tree), std::nullopt); } { DecisionTree tree; tree.split_nodes = {{A(0), S(1), Cond(0, -inf, 1.0)}, {S(2), A(2), Cond(0, -1.0, inf)}, {A(1), A(3), Cond(0, -1.0, inf)}}; tree.adjustments = {0.0, 1.0, 2.0, 3.0}; EXPECT_EQ(ToObliviousTree(tree), std::nullopt); } { DecisionTree tree; tree.split_nodes = {{S(2), S(1), Cond(0, -inf, 1.0)}, {A(1), A(2), Cond(0, -1.0, inf)}, {A(0), A(3), Cond(0, 1.0, inf)}}; tree.adjustments = {0.0, 1.0, 2.0, 3.0}; EXPECT_EQ(ToObliviousTree(tree), std::nullopt); } } TEST(ObliviousTest, Ok) { { DecisionTree tree; tree.adjustments = {2.0}; tree.weight = 0.5; auto oblivious_tree = ToObliviousTree(tree); ASSERT_TRUE(oblivious_tree.has_value()); EXPECT_THAT(oblivious_tree->layer_splits, ElementsAre()); EXPECT_THAT(oblivious_tree->adjustments, ElementsAre(1.0)); } { DecisionTree tree; tree.split_nodes = {{A(0), A(1), Cond(0, -inf, 1.0)}}; tree.adjustments = {7.0, 3.0}; tree.weight = 2.0; auto oblivious_tree = ToObliviousTree(tree); ASSERT_TRUE(oblivious_tree.has_value()); EXPECT_EQ(oblivious_tree->layer_splits.size(), 1); EXPECT_EQ(*oblivious_tree->layer_splits[0], *Cond(0, -inf, 1.0)); EXPECT_THAT(oblivious_tree->adjustments, ElementsAre(14.0, 6.0)); } { DecisionTree tree; tree.split_nodes = {{S(2), S(1), Cond(0, -inf, 1.0)}, {A(1), A(2), Cond(0, -1.0, inf)}, {A(0), A(3), Cond(0, -1.0, inf)}}; tree.adjustments = {0.0, 1.0, 2.0, 3.0}; auto oblivious_tree = ToObliviousTree(tree); ASSERT_TRUE(oblivious_tree.has_value()); EXPECT_EQ(oblivious_tree->layer_splits.size(), 2); EXPECT_EQ(*oblivious_tree->layer_splits[0], *Cond(0, -inf, 1.0)); EXPECT_EQ(*oblivious_tree->layer_splits[1], *Cond(0, -1.0, inf)); EXPECT_THAT(oblivious_tree->adjustments, ElementsAre(0.0, 3.0, 1.0, 2.0)); } } } }
2,398
#ifndef AROLLA_DECISION_FOREST_BATCHED_EVALUATION_BATCHED_FOREST_EVALUATOR_H_ #define AROLLA_DECISION_FOREST_BATCHED_EVALUATION_BATCHED_FOREST_EVALUATOR_H_ #include <algorithm> #include <cstdint> #include <memory> #include <optional> #include <utility> #include <vector> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/types/span.h" #include "arolla/decision_forest/decision_forest.h" #include "arolla/decision_forest/pointwise_evaluation/forest_evaluator.h" #include "arolla/memory/frame.h" #include "arolla/memory/raw_buffer_factory.h" #include "arolla/qtype/typed_ref.h" #include "arolla/qtype/typed_slot.h" #include "arolla/util/indestructible.h" #include "arolla/util/threading.h" namespace arolla { class BatchedForestEvaluator { public: struct CompilationParams { static constexpr CompilationParams Default() { return {}; } int64_t optimal_splits_per_evaluator = 500000; }; struct SlotMapping { int input_index; TypedSlot pointwise_slot; }; static absl::StatusOr<std::unique_ptr<BatchedForestEvaluator>> Compile( const DecisionForest& decision_forest, absl::Span<const TreeFilter> groups = {{}}, const CompilationParams& params = CompilationParams::Default()); absl::Status EvalBatch(absl::Span<const TypedSlot> input_slots, absl::Span<const TypedSlot> output_slots, FramePtr frame, RawBufferFactory* = GetHeapBufferFactory(), std::optional<int64_t> row_count = {}) const; static void SetThreading(std::unique_ptr<ThreadingInterface> threading, int64_t min_rows_per_thread = 128) { *threading_ = std::move(threading); min_rows_per_thread_ = min_rows_per_thread; } private: static ::arolla::Indestructible<std::unique_ptr<ThreadingInterface>> threading_; static int64_t min_rows_per_thread_; BatchedForestEvaluator(FrameLayout&& pointwise_layout, std::vector<SlotMapping>&& input_mapping, std::vector<TypedSlot>&& output_pointwise_slots, std::vector<ForestEvaluator>&& pointwise_evaluators) : pointwise_layout_(std::move(pointwise_layout)), input_mapping_(std::move(input_mapping)), output_pointwise_slots_(output_pointwise_slots), pointwise_evaluators_(std::move(pointwise_evaluators)) { input_pointwise_slots_.reserve(input_mapping_.size()); input_count_ = 0; for (const auto& m : input_mapping_) { input_pointwise_slots_.push_back(m.pointwise_slot); input_count_ = std::max(input_count_, m.input_index + 1); } } absl::Status GetInputsFromSlots(absl::Span<const TypedSlot> input_slots, ConstFramePtr frame, std::vector<TypedRef>* input_arrays) const; FrameLayout pointwise_layout_; std::vector<SlotMapping> input_mapping_; std::vector<TypedSlot> input_pointwise_slots_; std::vector<TypedSlot> output_pointwise_slots_; int input_count_; std::vector<ForestEvaluator> pointwise_evaluators_; }; } #endif #include "arolla/decision_forest/batched_evaluation/batched_forest_evaluator.h" #include <algorithm> #include <cstdint> #include <memory> #include <optional> #include <utility> #include <vector> #include "absl/log/check.h" #include "absl/memory/memory.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "absl/types/span.h" #include "arolla/array/array.h" #include "arolla/array/qtype/types.h" #include "arolla/decision_forest/decision_forest.h" #include "arolla/decision_forest/pointwise_evaluation/forest_evaluator.h" #include "arolla/dense_array/dense_array.h" #include "arolla/dense_array/qtype/types.h" #include "arolla/memory/buffer.h" #include "arolla/memory/frame.h" #include "arolla/memory/raw_buffer_factory.h" #include "arolla/qtype/array_like/array_like_qtype.h" #include "arolla/qtype/array_like/frame_iter.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/typed_ref.h" #include "arolla/qtype/typed_slot.h" #include "arolla/qtype/typed_value.h" #include "arolla/util/indestructible.h" #include "arolla/util/threading.h" #include "arolla/util/status_macros_backport.h" namespace arolla { namespace { absl::StatusOr<TypedValue> AddFullFloatArrays(TypedRef a, TypedRef b) { if (a.GetType() == GetDenseArrayQType<float>() && b.GetType() == GetDenseArrayQType<float>()) { const auto& va = a.UnsafeAs<DenseArray<float>>(); const auto& vb = b.UnsafeAs<DenseArray<float>>(); DCHECK_EQ(va.size(), vb.size()); DCHECK(va.IsFull() && vb.IsFull()); Buffer<float>::Builder bldr(va.size()); auto sa = va.values.span(); auto sb = vb.values.span(); auto sr = bldr.GetMutableSpan(); for (int64_t i = 0; i < va.size(); ++i) { sr[i] = sa[i] + sb[i]; } return TypedValue::FromValue(DenseArray<float>{std::move(bldr).Build()}); } else if (a.GetType() == GetArrayQType<float>() && b.GetType() == GetArrayQType<float>()) { const auto& va = a.UnsafeAs<Array<float>>(); const auto& vb = b.UnsafeAs<Array<float>>(); DCHECK_EQ(va.size(), vb.size()); DCHECK(va.IsFullForm() && vb.IsFullForm()); Buffer<float>::Builder bldr(va.size()); auto sa = va.dense_data().values.span(); auto sb = vb.dense_data().values.span(); auto sr = bldr.GetMutableSpan(); for (int64_t i = 0; i < va.size(); ++i) { sr[i] = sa[i] + sb[i]; } return TypedValue::FromValue(Array<float>{std::move(bldr).Build()}); } else { return absl::InternalError("Invalid type in BatchedForestEvaluator/Add"); } } absl::StatusOr<std::vector<ForestEvaluator>> CreatePointwiseEvaluators( const BatchedForestEvaluator::CompilationParams& params, const DecisionForest& decision_forest, const std::vector<TypedSlot>& inputs, const std::vector<ForestEvaluator::Output>& outputs) { int64_t split_count = 0; for (const auto& tree : decision_forest.GetTrees()) { split_count += tree.split_nodes.size(); } int64_t evaluator_count = std::max<int64_t>( 1, (split_count + params.optimal_splits_per_evaluator - 1) / params.optimal_splits_per_evaluator); std::vector<ForestEvaluator> evaluators; evaluators.reserve(evaluator_count); if (evaluator_count == 1) { ASSIGN_OR_RETURN(auto evaluator, ForestEvaluator::Compile(decision_forest, inputs, outputs)); evaluators.push_back(std::move(evaluator)); return evaluators; } int64_t splits_per_evaluator = (split_count + evaluator_count - 1) / evaluator_count; int64_t estimated_trees_per_evaluator = (decision_forest.GetTrees().size() + evaluator_count - 1) / evaluator_count; std::vector<DecisionTree> trees; trees.reserve(estimated_trees_per_evaluator); int64_t current_split_count = 0; for (const auto& tree : decision_forest.GetTrees()) { trees.push_back(tree); current_split_count += tree.split_nodes.size(); if (current_split_count >= splits_per_evaluator) { ASSIGN_OR_RETURN(auto partial_forest, DecisionForest::FromTrees(std::move(trees))); ASSIGN_OR_RETURN(auto evaluator, ForestEvaluator::Compile( *partial_forest, inputs, outputs)); evaluators.push_back(std::move(evaluator)); trees.clear(); trees.reserve(estimated_trees_per_evaluator); current_split_count = 0; } } if (!trees.empty()) { ASSIGN_OR_RETURN(auto partial_forest, DecisionForest::FromTrees(std::move(trees))); ASSIGN_OR_RETURN(auto evaluator, ForestEvaluator::Compile(*partial_forest, inputs, outputs)); evaluators.push_back(std::move(evaluator)); } return evaluators; } } Indestructible<std::unique_ptr<ThreadingInterface>> BatchedForestEvaluator::threading_; int64_t BatchedForestEvaluator::min_rows_per_thread_; absl::StatusOr<std::unique_ptr<BatchedForestEvaluator>> BatchedForestEvaluator::Compile(const DecisionForest& decision_forest, absl::Span<const TreeFilter> groups, const CompilationParams& params) { FrameLayout::Builder bldr; std::vector<SlotMapping> input_slots_mapping; TypedSlot placeholder = TypedSlot::FromSlot(FrameLayout::Slot<float>::UnsafeUninitializedSlot()); std::vector<TypedSlot> input_pointwise_slots; for (const auto& kv : decision_forest.GetRequiredQTypes()) { TypedSlot pointwise_slot = AddSlot(kv.second, &bldr); while (input_pointwise_slots.size() <= kv.first) { input_pointwise_slots.push_back(placeholder); } input_pointwise_slots[kv.first] = pointwise_slot; input_slots_mapping.push_back({kv.first, pointwise_slot}); } std::vector<ForestEvaluator::Output> pointwise_outputs; std::vector<TypedSlot> output_pointwise_slots; pointwise_outputs.reserve(groups.size()); output_pointwise_slots.reserve(groups.size()); for (const TreeFilter& filter : groups) { auto slot = bldr.AddSlot<float>(); pointwise_outputs.push_back({filter, slot}); output_pointwise_slots.push_back(TypedSlot::FromSlot(slot)); } auto pointwise_layout = std::move(bldr).Build(); ASSIGN_OR_RETURN( std::vector<ForestEvaluator> pointwise_evaluators, CreatePointwiseEvaluators(params, decision_forest, input_pointwise_slots, pointwise_outputs)); return absl::WrapUnique(new BatchedForestEvaluator( std::move(pointwise_layout), std::move(input_slots_mapping), std::move(output_pointwise_slots), std::move(pointwise_evaluators))); } absl::Status BatchedForestEvaluator::GetInputsFromSlots( absl::Span<const TypedSlot> input_slots, ConstFramePtr frame, std::vector<TypedRef>* input_arrays) const { if (input_slots.size() < input_count_) { return absl::InvalidArgumentError( absl::StrFormat("not enough inputs: at least %d expected, %d found", input_count_, input_slots.size())); } for (auto m : input_mapping_) { input_arrays->push_back( TypedRef::FromSlot(input_slots[m.input_index], frame)); } return absl::OkStatus(); } absl::Status BatchedForestEvaluator::EvalBatch( absl::Span<const TypedSlot> input_slots, absl::Span<const TypedSlot> output_slots, FramePtr frame, RawBufferFactory* buffer_factory, std::optional<int64_t> row_count) const { std::vector<TypedRef> input_arrays; input_arrays.reserve(input_mapping_.size()); RETURN_IF_ERROR(GetInputsFromSlots(input_slots, frame, &input_arrays)); if (!row_count.has_value()) { if (!input_arrays.empty()) { ASSIGN_OR_RETURN(row_count, GetArraySize(input_arrays[0])); } else if (!input_slots.empty()) { ASSIGN_OR_RETURN(row_count, GetArraySize(TypedRef::FromSlot(input_slots[0], frame))); } } int thread_count = 1; auto run_evaluator = [&](const ForestEvaluator& eval) -> absl::Status { ASSIGN_OR_RETURN( auto frame_iterator, FrameIterator::Create( input_arrays, {input_pointwise_slots_.data(), input_arrays.size()}, output_slots, output_pointwise_slots_, &pointwise_layout_, FrameIterator::Options{.row_count = row_count, .frame_buffer_count = 64 * thread_count, .buffer_factory = buffer_factory})); if (thread_count > 1) { frame_iterator.ForEachFrame([&eval](FramePtr f) { eval.Eval(f, f); }, **threading_, thread_count); } else { frame_iterator.ForEachFrame([&eval](FramePtr f) { eval.Eval(f, f); }); } return frame_iterator.StoreOutput(frame); }; if (pointwise_evaluators_.size() == 1) { return run_evaluator(pointwise_evaluators_.front()); } else { std::vector<TypedValue> res_sum; res_sum.reserve(output_slots.size()); RETURN_IF_ERROR(run_evaluator(pointwise_evaluators_.front())); for (const auto& s : output_slots) { res_sum.push_back(TypedValue::FromSlot(s, frame)); } for (int eval_id = 1; eval_id < pointwise_evaluators_.size() - 1; ++eval_id) { RETURN_IF_ERROR(run_evaluator(pointwise_evaluators_[eval_id])); for (int i = 0; i < output_slots.size(); ++i) { ASSIGN_OR_RETURN( res_sum[i], AddFullFloatArrays(res_sum[i].AsRef(), TypedRef::FromSlot(output_slots[i], frame))); } } RETURN_IF_ERROR(run_evaluator(pointwise_evaluators_.back())); for (int i = 0; i < output_slots.size(); ++i) { ASSIGN_OR_RETURN( TypedValue full_sum, AddFullFloatArrays(res_sum[i].AsRef(), TypedRef::FromSlot(output_slots[i], frame))); RETURN_IF_ERROR(full_sum.CopyToSlot(output_slots[i], frame)); } return absl::OkStatus(); } } }
#include "arolla/decision_forest/batched_evaluation/batched_forest_evaluator.h" #include <cmath> #include <cstdint> #include <limits> #include <memory> #include <utility> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/random/distributions.h" #include "absl/random/random.h" #include "absl/status/statusor.h" #include "arolla/array/array.h" #include "arolla/array/qtype/types.h" #include "arolla/decision_forest/decision_forest.h" #include "arolla/decision_forest/split_conditions/interval_split_condition.h" #include "arolla/decision_forest/split_conditions/set_of_values_split_condition.h" #include "arolla/decision_forest/testing/test_util.h" #include "arolla/dense_array/dense_array.h" #include "arolla/dense_array/qtype/types.h" #include "arolla/memory/frame.h" #include "arolla/memory/memory_allocation.h" #include "arolla/qtype/typed_slot.h" #include "arolla/util/threading.h" namespace arolla { namespace { absl::StatusOr<DecisionForestPtr> CreateTestForest() { constexpr float kInf = std::numeric_limits<float>::infinity(); constexpr auto S = DecisionTreeNodeId::SplitNodeId; constexpr auto A = DecisionTreeNodeId::AdjustmentId; std::vector<DecisionTree> trees(2); trees[0].tag = {.submodel_id = 0}; trees[0].adjustments = {0.5, 1.5, 2.5, 3.5}; trees[0].split_nodes = { {S(1), S(2), IntervalSplit(0, 1.5, kInf)}, {A(0), A(2), SetOfValuesSplit<int64_t>(1, {1, 2}, false)}, {A(1), A(3), IntervalSplit(0, -kInf, 10)}}; trees[1].tag = {.submodel_id = 1}; trees[1].adjustments = {-1.0, 1.0}; trees[1].split_nodes = {{A(0), A(1), IntervalSplit(0, 1, 5)}}; return DecisionForest::FromTrees(std::move(trees)); } TEST(BatchedForestEvaluator, EvalBatch) { ASSERT_OK_AND_ASSIGN(auto forest, CreateTestForest()); std::vector<TreeFilter> groups{{.submodels = {0}}, {.submodels = {1}}}; ASSERT_OK_AND_ASSIGN(auto eval, BatchedForestEvaluator::Compile(*forest, groups)); FrameLayout::Builder bldr; auto in1_slot = bldr.AddSlot<DenseArray<float>>(); auto in2_slot = bldr.AddSlot<DenseArray<int64_t>>(); auto out1_slot = bldr.AddSlot<DenseArray<float>>(); auto out2_slot = bldr.AddSlot<DenseArray<float>>(); FrameLayout layout = std::move(bldr).Build(); MemoryAllocation alloc(&layout); FramePtr frame = alloc.frame(); frame.Set(in1_slot, CreateDenseArray<float>({0, 0, 1.2, 1.6, 7.0, 13.5, NAN})); frame.Set(in2_slot, CreateDenseArray<int64_t>({3, 1, 1, 1, 1, 1, {}})); { ASSERT_OK(eval->EvalBatch( {TypedSlot::FromSlot(in1_slot), TypedSlot::FromSlot(in2_slot)}, {TypedSlot::FromSlot(out1_slot), TypedSlot::FromSlot(out2_slot)}, frame)); EXPECT_THAT(frame.Get(out1_slot), ::testing::ElementsAre(0.5, 2.5, 2.5, 3.5, 3.5, 1.5, 0.5)); EXPECT_THAT(frame.Get(out2_slot), ::testing::ElementsAre(-1, -1, 1, 1, -1, -1, -1)); } frame.Set(out1_slot, DenseArray<float>()); frame.Set(out2_slot, DenseArray<float>()); { BatchedForestEvaluator::SetThreading(std::make_unique<StdThreading>(2)); ASSERT_OK(eval->EvalBatch( {TypedSlot::FromSlot(in1_slot), TypedSlot::FromSlot(in2_slot)}, {TypedSlot::FromSlot(out1_slot), TypedSlot::FromSlot(out2_slot)}, frame)); EXPECT_THAT(frame.Get(out1_slot), ::testing::ElementsAre(0.5, 2.5, 2.5, 3.5, 3.5, 1.5, 0.5)); EXPECT_THAT(frame.Get(out2_slot), ::testing::ElementsAre(-1, -1, 1, 1, -1, -1, -1)); BatchedForestEvaluator::SetThreading(nullptr); } frame.Set(out1_slot, DenseArray<float>()); frame.Set(out2_slot, DenseArray<float>()); { BatchedForestEvaluator::SetThreading(std::make_unique<StdThreading>(2), 1); ASSERT_OK(eval->EvalBatch( {TypedSlot::FromSlot(in1_slot), TypedSlot::FromSlot(in2_slot)}, {TypedSlot::FromSlot(out1_slot), TypedSlot::FromSlot(out2_slot)}, frame)); EXPECT_THAT(frame.Get(out1_slot), ::testing::ElementsAre(0.5, 2.5, 2.5, 3.5, 3.5, 1.5, 0.5)); EXPECT_THAT(frame.Get(out2_slot), ::testing::ElementsAre(-1, -1, 1, 1, -1, -1, -1)); BatchedForestEvaluator::SetThreading(nullptr); } } TEST(BatchedForestEvaluator, UnusedInputs) { constexpr auto A = DecisionTreeNodeId::AdjustmentId; DecisionTree tree; tree.adjustments = {-1, 1}; tree.split_nodes = {{A(0), A(1), IntervalSplit(2, 0, 1)}}; ASSERT_OK_AND_ASSIGN(auto forest, DecisionForest::FromTrees({tree})); ASSERT_OK_AND_ASSIGN(auto eval, BatchedForestEvaluator::Compile(*forest)); FrameLayout::Builder bldr; auto unused1_slot = bldr.AddSlot<DenseArray<int64_t>>(); auto unused2_slot = bldr.AddSlot<DenseArray<int64_t>>(); auto in_slot = bldr.AddSlot<DenseArray<float>>(); auto out_slot = bldr.AddSlot<DenseArray<float>>(); FrameLayout layout = std::move(bldr).Build(); MemoryAllocation alloc(&layout); FramePtr frame = alloc.frame(); frame.Set(in_slot, CreateDenseArray<float>({-1, 0.5, 2})); ASSERT_OK(eval->EvalBatch( {TypedSlot::FromSlot(unused1_slot), TypedSlot::FromSlot(unused2_slot), TypedSlot::FromSlot(in_slot)}, {TypedSlot::FromSlot(out_slot)}, frame)); EXPECT_THAT(frame.Get(out_slot), ::testing::ElementsAre(-1, 1, -1)); } TEST(BatchedForestEvaluator, AllInputUnused) { std::vector<DecisionTree> trees(1); trees[0].adjustments = {1.5}; ASSERT_OK_AND_ASSIGN(DecisionForestPtr forest, DecisionForest::FromTrees(std::move(trees))); std::vector<TreeFilter> groups{{.submodels = {0}}}; ASSERT_OK_AND_ASSIGN(auto eval, BatchedForestEvaluator::Compile(*forest, groups)); FrameLayout::Builder bldr; auto in1_slot = bldr.AddSlot<DenseArray<float>>(); auto in2_slot = bldr.AddSlot<DenseArray<int64_t>>(); auto out_slot = bldr.AddSlot<DenseArray<float>>(); FrameLayout layout = std::move(bldr).Build(); MemoryAllocation alloc(&layout); FramePtr frame = alloc.frame(); frame.Set(in1_slot, CreateDenseArray<float>({0, 0, 1.2, 1.6, 7.0, 13.5, NAN})); frame.Set(in2_slot, CreateDenseArray<int64_t>({3, 1, 1, 1, 1, 1, {}})); ASSERT_OK(eval->EvalBatch( {TypedSlot::FromSlot(in1_slot), TypedSlot::FromSlot(in2_slot)}, {TypedSlot::FromSlot(out_slot)}, frame)); EXPECT_THAT(frame.Get(out_slot), ::testing::ElementsAre(1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5)); } TEST(BatchedForestEvaluator, SplitCountPerEvaluator) { constexpr int64_t min_num_splits = 10; constexpr int64_t max_num_splits = 30; constexpr int64_t num_trees = 100; constexpr int64_t batch_size = 10; absl::BitGen rnd; constexpr int64_t min_total_split_count = num_trees * min_num_splits; int64_t split_count_per_evaluator = absl::Uniform<int64_t>( rnd, min_total_split_count / 5, min_total_split_count * 4 / 5); auto forest = CreateRandomFloatForest(&rnd, 10, true, min_num_splits, max_num_splits, num_trees); ASSERT_OK_AND_ASSIGN(auto evaluator, BatchedForestEvaluator::Compile(*forest)); ASSERT_OK_AND_ASSIGN( auto subdivided_evaluator, BatchedForestEvaluator::Compile(*forest, {TreeFilter()}, {split_count_per_evaluator})); std::vector<TypedSlot> slots; FrameLayout::Builder layout_builder; ASSERT_OK(CreateArraySlotsForForest(*forest, &layout_builder, &slots)); auto dense_array_output_slot = layout_builder.AddSlot<DenseArray<float>>(); auto array_output_slot = layout_builder.AddSlot<Array<float>>(); FrameLayout layout = std::move(layout_builder).Build(); MemoryAllocation ctx(&layout); FramePtr frame = ctx.frame(); for (auto slot : slots) { ASSERT_OK(FillArrayWithRandomValues(batch_size, slot, frame, &rnd)); } ASSERT_OK(evaluator->EvalBatch(slots, {TypedSlot::FromSlot(dense_array_output_slot)}, frame, nullptr, batch_size)); ASSERT_OK(evaluator->EvalBatch(slots, {TypedSlot::FromSlot(array_output_slot)}, frame, nullptr, batch_size)); DenseArray<float> dense_array1 = frame.Get(dense_array_output_slot); Array<float> array1 = frame.Get(array_output_slot); frame.Set(dense_array_output_slot, DenseArray<float>()); frame.Set(array_output_slot, Array<float>()); ASSERT_OK(subdivided_evaluator->EvalBatch( slots, {TypedSlot::FromSlot(dense_array_output_slot)}, frame, nullptr, batch_size)); ASSERT_OK(subdivided_evaluator->EvalBatch( slots, {TypedSlot::FromSlot(array_output_slot)}, frame, nullptr, batch_size)); DenseArray<float> dense_array2 = frame.Get(dense_array_output_slot); Array<float> array2 = frame.Get(array_output_slot); ASSERT_EQ(dense_array1.size(), batch_size); ASSERT_EQ(array1.size(), batch_size); ASSERT_EQ(dense_array2.size(), batch_size); ASSERT_EQ(array2.size(), batch_size); for (int64_t i = 0; i < batch_size; ++i) { bool present = array1[i].present; EXPECT_EQ(array2[i].present, present); EXPECT_EQ(dense_array1[i].present, present); EXPECT_EQ(dense_array2[i].present, present); if (present) { float value = array1[i].value; EXPECT_FLOAT_EQ(array2[i].value, value); EXPECT_FLOAT_EQ(dense_array1[i].value, value); EXPECT_FLOAT_EQ(dense_array2[i].value, value); } } } } }
2,399
#ifndef AROLLA_DECISION_FOREST_EXPR_OPERATOR_FOREST_MODEL_H_ #define AROLLA_DECISION_FOREST_EXPR_OPERATOR_FOREST_MODEL_H_ #include <cstddef> #include <map> #include <memory> #include <optional> #include <string> #include <utility> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "arolla/decision_forest/decision_forest.h" #include "arolla/expr/basic_expr_operator.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/qtype/qtype.h" #include "arolla/util/fingerprint.h" namespace arolla { constexpr absl::string_view kForestModelQValueSpecializationKey = "::arolla::ForestModel"; class ForestModel; using ForestModelPtr = std::shared_ptr<const ForestModel>; class ForestModel : public expr::BasicExprOperator { public: using SubmodelIds = std::map<std::string, std::vector<int>>; struct Parameter { std::string name; expr::ExprNodePtr preprocessing = nullptr; }; struct ConstructorArgs { DecisionForestPtr forest; SubmodelIds submodel_ids; std::vector<Parameter> inputs; expr::ExprNodePtr expression; std::optional<std::vector<expr::ExprNodePtr>> oob_filters; std::optional<size_t> truncation_step; }; static absl::StatusOr<ForestModelPtr> Create(ConstructorArgs args); absl::StatusOr<expr::ExprNodePtr> ToLowerLevel( const expr::ExprNodePtr& node) const override; absl::StatusOr<std::vector<expr::ExprNodePtr>> PreprocessInputs( const expr::ExprNodePtr& node) const; absl::StatusOr<expr::ExprNodePtr> ApplyPostprocessing( const expr::ExprNodePtr& node, const expr::ExprNodePtr& raw_result) const; absl::StatusOr<expr::ExprNodePtr> CreatePartialEvaluator( absl::Span<const std::pair<int, int>> step_ranges, absl::Span<const expr::ExprNodePtr> preprocessed_inputs) const; DecisionForestPtr forest() const { return forest_; } const SubmodelIds& submodel_ids() const { return submodel_ids_; } const std::optional<std::vector<expr::ExprNodePtr>>& oob_filters() const { return oob_filters_; } size_t bag_count() const { return bag_count_; } std::optional<size_t> truncation_step() const { return truncation_step_; } const std::vector<Parameter>& inputs() const { return inputs_; } expr::ExprNodePtr expression() const { return expression_; } absl::string_view py_qvalue_specialization_key() const override; private: ForestModel(expr::ExprOperatorSignature&& signature, Fingerprint&& fingerprint, ConstructorArgs&& args); absl::Status Initialize(); absl::StatusOr<QTypePtr> GetOutputQType( absl::Span<const QTypePtr> input_qtypes) const override; struct ExpressionAnalysisResult { bool plain_sum = true; int bag_count = 0; std::vector<expr::ExprNodePtr> submodel_nodes; std::vector<expr::ExprNodePtr> plain_sum_nodes; }; absl::StatusOr<ExpressionAnalysisResult> AnalyzeExpression() const; absl::Status HandlePlainSumExpression( const std::vector<expr::ExprNodePtr>& submodel_nodes, std::vector<expr::ExprNodePtr>&& plain_sum_nodes); absl::Status HandleExpressionWithoutBags(); absl::Status HandleExpressionWithBags(); absl::StatusOr<expr::ExprNodePtr> UsedBagCountExpr() const; absl::StatusOr<expr::ExprOperatorPtr> CreateDecisionForestOperator( std::vector<TreeFilter> tree_filters) const; absl::StatusOr<expr::ExprNodePtr> ApplyEvaluator( expr::ExprNodePtr forest_evaluator, absl::Span<const expr::ExprNodePtr> args) const; absl::StatusOr<expr::ExprNodePtr> CastAndValidateArgType( int input_id, expr::ExprNodePtr arg) const; absl::StatusOr<QTypePtr> InferTypeOfFirstForestInputAfterPreprocessing( absl::Span<const QTypePtr> input_qtypes) const; DecisionForestPtr forest_; SubmodelIds submodel_ids_; std::optional<std::vector<expr::ExprNodePtr>> oob_filters_; std::optional<size_t> truncation_step_; std::vector<Parameter> inputs_; expr::ExprNodePtr expression_; std::optional<std::string> res_tuple_key_; std::vector<TreeFilter> tree_filters_; expr::ExprNodePtr processed_expression_; bool is_plain_sum_ = false; absl::flat_hash_map<int, float> submodel_weight_multipliers_; size_t bag_count_; std::optional<int> first_forest_input_id_; }; } #endif #include "arolla/decision_forest/expr_operator/forest_model.h" #include <algorithm> #include <cstddef> #include <cstdint> #include <memory> #include <optional> #include <string> #include <utility> #include <vector> #include "absl/algorithm/container.h" #include "absl/container/flat_hash_map.h" #include "absl/container/flat_hash_set.h" #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" #include "absl/strings/str_join.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "arolla/decision_forest/decision_forest.h" #include "arolla/decision_forest/expr_operator/decision_forest_operator.h" #include "arolla/expr/annotation_utils.h" #include "arolla/expr/basic_expr_operator.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_attributes.h" #include "arolla/expr/expr_debug_string.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/expr/expr_visitor.h" #include "arolla/expr/lambda_expr_operator.h" #include "arolla/expr/registered_expr_operator.h" #include "arolla/expr/visitors/substitution.h" #include "arolla/memory/optional_value.h" #include "arolla/qtype/array_like/array_like_qtype.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/optional_qtype.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/standard_type_properties/properties.h" #include "arolla/util/fingerprint.h" #include "arolla/util/text.h" #include "arolla/util/status_macros_backport.h" namespace arolla { namespace { absl::Status ValidateExpression( const expr::ExprNodePtr& expression, const ForestModel::SubmodelIds& submodel_ids, const absl::flat_hash_set<std::string>& input_names) { absl::flat_hash_set<std::string> unused_submodels; for (const auto& [k, _] : submodel_ids) unused_submodels.insert(k); for (const auto& node : expr::VisitorOrder(expression)) { if (node->is_leaf()) { return absl::InvalidArgumentError( "leaves are not allowed in an expression"); } if (node->is_placeholder()) { if (submodel_ids.count(node->placeholder_key()) > 0) { unused_submodels.erase(node->placeholder_key()); } else if (!input_names.contains(node->placeholder_key())) { return absl::InvalidArgumentError(absl::StrFormat( "P.%s doesn't correspond to any input and it is not " "found in submodel_ids", node->placeholder_key())); } } } if (!unused_submodels.empty()) { std::vector<std::string> unused_vec(unused_submodels.begin(), unused_submodels.end()); absl::c_sort(unused_vec); return absl::InvalidArgumentError( absl::StrFormat("submodels [%s] are not used in the expression, but " "are mentioned in submodel_ids", absl::StrJoin(unused_vec, ", "))); } return absl::OkStatus(); } absl::Status ValidateInputs(const DecisionForestPtr& forest, const ForestModel::SubmodelIds& submodel_ids, const std::vector<ForestModel::Parameter>& inputs) { for (const auto& input : inputs) { if (submodel_ids.count(input.name) > 0) { return absl::InvalidArgumentError(absl::StrFormat( "name collision of an input and a submodel: '%s'", input.name)); } } for (const auto& [key, unused] : forest->GetRequiredQTypes()) { if (key >= inputs.size()) { return absl::InvalidArgumentError(absl::StrFormat( "not enough args: used_input_index=%d size=%d", key, inputs.size())); } } return absl::OkStatus(); } absl::Status ValidateOOBFilters( const std::vector<expr::ExprNodePtr>& oob_filters, const DecisionForestPtr& forest, const absl::flat_hash_set<std::string>& input_names) { for (const expr::ExprNodePtr& filter : oob_filters) { if (filter == nullptr) { return absl::InvalidArgumentError("OOB filter can't be nullptr"); } for (const auto& node : expr::VisitorOrder(filter)) { if (node->is_leaf()) { return absl::InvalidArgumentError( "leaves are not allowed in an OOB filter expressing"); } if (node->is_placeholder() && !input_names.contains(node->placeholder_key())) { return absl::InvalidArgumentError( absl::StrCat("no input matches P.", node->placeholder_key(), " in OOB filter ", expr::ToDebugString(node))); } } } return absl::OkStatus(); } absl::StatusOr<expr::ExprNodePtr> AddAll( const expr::ExprNodePtr& first, absl::Span<const expr::ExprNodePtr> nodes) { auto res = first; for (const auto& node : nodes) { ASSIGN_OR_RETURN(res, expr::CallOp("math.add", {res, node})); } return res; } using NodeCountMap = absl::flat_hash_map<Fingerprint, int>; NodeCountMap GetNodeCountMap(const expr::ExprNodePtr& expr) { return PostOrderTraverse(expr, [&](const expr::ExprNodePtr& node, absl::Span<const NodeCountMap* const> visits) { NodeCountMap res{{node->fingerprint(), 1}}; for (const NodeCountMap* visit : visits) { for (const auto& [k, v] : *visit) { if (res.contains(k)) { res[k] += v; } else { res[k] = v; } } } return res; }); } } absl::StatusOr<ForestModelPtr> ForestModel::Create( ForestModel::ConstructorArgs args) { expr::ExprOperatorSignature signature; signature.parameters.reserve(args.inputs.size()); for (const Parameter& param : args.inputs) { signature.parameters.push_back({param.name}); } RETURN_IF_ERROR(expr::ValidateSignature(signature)); RETURN_IF_ERROR(ValidateInputs(args.forest, args.submodel_ids, args.inputs)); absl::flat_hash_set<std::string> input_names; input_names.reserve(args.inputs.size()); for (const auto& input : args.inputs) { input_names.insert(input.name); } RETURN_IF_ERROR( ValidateExpression(args.expression, args.submodel_ids, input_names)); if (args.oob_filters.has_value()) { RETURN_IF_ERROR( ValidateOOBFilters(*args.oob_filters, args.forest, input_names)); } FingerprintHasher hasher("d18261c6a5414ee8e5b0af80dc480ea8"); hasher.Combine(args.forest->fingerprint(), args.expression->fingerprint(), signature); hasher.Combine(args.submodel_ids.size()); for (const auto& [k, v] : args.submodel_ids) { hasher.Combine(k).CombineSpan(v); } hasher.Combine(args.inputs.size()); for (const auto& input : args.inputs) { if (input.preprocessing != nullptr) { hasher.Combine(input.preprocessing->fingerprint()); } else { hasher.Combine(Fingerprint{}); } } if (args.oob_filters.has_value()) { for (const auto& oob_filter : *args.oob_filters) { hasher.Combine(oob_filter->fingerprint()); } } else { hasher.Combine(Fingerprint{}); } if (args.truncation_step.has_value()) { hasher.Combine(*args.truncation_step); } else { hasher.Combine(Fingerprint{}); } std::shared_ptr<ForestModel> model(new ForestModel( std::move(signature), std::move(hasher).Finish(), std::move(args))); RETURN_IF_ERROR(model->Initialize()); return model; } absl::StatusOr<std::vector<expr::ExprNodePtr>> ForestModel::PreprocessInputs( const expr::ExprNodePtr& node) const { RETURN_IF_ERROR(ValidateNodeDepsCount(*node)); std::vector<expr::ExprNodePtr> args(inputs_.size()); for (int i = 0; i < inputs_.size(); ++i) { expr::ExprNodePtr arg = node->node_deps()[i]; if (inputs_[i].preprocessing != nullptr) { ASSIGN_OR_RETURN(auto lambda, expr::LambdaOperator::Make(inputs_[i].preprocessing)); ASSIGN_OR_RETURN(arg, expr::CallOp(lambda, {arg})); ASSIGN_OR_RETURN(arg, expr::ToLowerNode(arg)); } if (arg->qtype() == nullptr) { return absl::InternalError( absl::StrFormat("invalid preprocessing for input #%d: QType metadata " "can not be propagated", i)); } ASSIGN_OR_RETURN(args[i], CastAndValidateArgType(i, std::move(arg))); } return args; } absl::StatusOr<expr::ExprNodePtr> ForestModel::ApplyPostprocessing( const expr::ExprNodePtr& node, const expr::ExprNodePtr& raw_result) const { RETURN_IF_ERROR(ValidateNodeDepsCount(*node)); absl::flat_hash_map<std::string, expr::ExprNodePtr> expression_params; expression_params.reserve(inputs_.size() + 1); for (int i = 0; i < inputs_.size(); ++i) { expression_params[inputs_[i].name] = node->node_deps()[i]; } if (res_tuple_key_) { if (raw_result == nullptr) { return absl::InvalidArgumentError( "raw_result can be nullptr only if expression doesn't use decision " "forest"); } expression_params[*res_tuple_key_] = raw_result; } ASSIGN_OR_RETURN(auto result, SubstitutePlaceholders( processed_expression_, expression_params, true)); if (IsNameAnnotation(node)) { return expr::CallOp( "annotation.name", {result, expr::Literal(Text(expr::ReadNameAnnotation(node)))}); } return result; } absl::StatusOr<expr::ExprNodePtr> ForestModel::ToLowerLevel( const expr::ExprNodePtr& node) const { RETURN_IF_ERROR(ValidateNodeDepsCount(*node)); for (size_t i = 0; i < inputs_.size(); ++i) { if (node->node_deps()[i]->qtype() == nullptr) { return node; } } if (!res_tuple_key_) { return ApplyPostprocessing(node, nullptr); } ASSIGN_OR_RETURN(std::vector<expr::ExprNodePtr> args, PreprocessInputs(node)); ASSIGN_OR_RETURN(auto op, CreateDecisionForestOperator(tree_filters_)); ASSIGN_OR_RETURN(auto res_tuple, expr::MakeOpNode(op, std::move(args))); return ApplyPostprocessing(node, res_tuple); } absl::StatusOr<expr::ExprNodePtr> ForestModel::CreatePartialEvaluator( absl::Span<const std::pair<int, int>> step_ranges, absl::Span<const expr::ExprNodePtr> preprocessed_inputs) const { std::vector<TreeFilter> filters; filters.reserve(step_ranges.size() * tree_filters_.size()); for (auto& [from, to] : step_ranges) { for (const TreeFilter& filter : tree_filters_) { if ((filter.step_range_from > from) || (filter.step_range_to >= 0 && filter.step_range_to < to)) { return absl::InvalidArgumentError("requested range is not available"); } filters.push_back({from, to, filter.submodels}); } } ASSIGN_OR_RETURN(auto op, CreateDecisionForestOperator(std::move(filters))); return expr::MakeOpNode( op, std::vector(preprocessed_inputs.begin(), preprocessed_inputs.end())); } absl::StatusOr<QTypePtr> ForestModel::InferTypeOfFirstForestInputAfterPreprocessing( absl::Span<const QTypePtr> input_qtypes) const { if (!first_forest_input_id_.has_value()) { return absl::FailedPreconditionError("forest has no inputs"); } QTypePtr in_type = input_qtypes[*first_forest_input_id_]; if (inputs_[*first_forest_input_id_].preprocessing != nullptr) { ASSIGN_OR_RETURN(auto lambda, expr::LambdaOperator::Make( inputs_[*first_forest_input_id_].preprocessing)); ASSIGN_OR_RETURN(expr::ExprAttributes attr, lambda->InferAttributes({expr::ExprAttributes(in_type)})); if (attr.qtype() == nullptr) { return absl::InternalError("can't infer preprocessed input type"); } return attr.qtype(); } else { return in_type; } } absl::StatusOr<QTypePtr> ForestModel::GetOutputQType( absl::Span<const QTypePtr> input_qtypes) const { QTypePtr out_type = GetQType<float>(); if (first_forest_input_id_.has_value()) { ASSIGN_OR_RETURN( QTypePtr in_type, InferTypeOfFirstForestInputAfterPreprocessing(input_qtypes)); if (IsArrayLikeQType(in_type)) { ASSIGN_OR_RETURN(const ArrayLikeQType* array_qtype, ToArrayLikeQType(in_type)); ASSIGN_OR_RETURN(out_type, array_qtype->WithValueQType(GetQType<float>())); } } ASSIGN_OR_RETURN(auto fake_res, expr::CallOp("annotation.qtype", {expr::Leaf("fake_res"), expr::Literal(out_type)})); ASSIGN_OR_RETURN( auto fake_res_tuple, expr::BindOp( "core.make_tuple", std::vector<expr::ExprNodePtr>(tree_filters_.size(), fake_res), {})); absl::flat_hash_map<std::string, expr::ExprNodePtr> expression_params; if (res_tuple_key_) { expression_params[*res_tuple_key_] = fake_res_tuple; } for (int i = 0; i < inputs_.size(); ++i) { ASSIGN_OR_RETURN( expression_params[inputs_[i].name], expr::CallOp("annotation.qtype", {expr::Leaf("fake_input"), expr::Literal(input_qtypes[i])})); } ASSIGN_OR_RETURN(auto expr, SubstitutePlaceholders( processed_expression_, expression_params, true)); const auto result = expr->qtype(); if (result == nullptr) { return absl::FailedPreconditionError("unable to deduce output qtype"); } return result; } absl::StatusOr<expr::ExprNodePtr> ForestModel::CastAndValidateArgType( int input_id, expr::ExprNodePtr arg) const { const auto& required_qtypes = forest_->GetRequiredQTypes(); auto required_qtype_iter = required_qtypes.find(input_id); if (required_qtype_iter == required_qtypes.end()) { return arg; } QTypePtr required_qtype = required_qtype_iter->second; QTypePtr required_scalar_qtype = DecayOptionalQType(required_qtype); ASSIGN_OR_RETURN(QTypePtr actual_scalar_qtype, GetScalarQType(arg->qtype())); if (required_scalar_qtype == GetQType<float>() && actual_scalar_qtype != GetQType<float>() && IsNumericScalarQType(actual_scalar_qtype)) { ASSIGN_OR_RETURN(arg, expr::BindOp("core.to_float32", {std::move(arg)}, {})); } else if (required_scalar_qtype != actual_scalar_qtype) { return absl::InvalidArgumentError( absl::StrFormat("value type of input #%d (%s) doesn't match: " "expected to be compatible with %s, got %s", input_id, expr::GetDebugSnippet(arg), required_qtype->name(), arg->qtype()->name())); } if (IsScalarQType(arg->qtype()) && IsOptionalQType(required_qtype)) { ASSIGN_OR_RETURN(arg, expr::BindOp("core.to_optional", {std::move(arg)}, {})); } return arg; } absl::StatusOr<ForestModel::ExpressionAnalysisResult> ForestModel::AnalyzeExpression() const { ExpressionAnalysisResult res; ASSIGN_OR_RETURN(auto expression, expr::ToLowest(expression_)); for (const auto& node : expr::VisitorOrder(expression)) { if (node->is_op()) { ASSIGN_OR_RETURN(auto op, expr::DecayRegisteredOperator(node->op())); res.plain_sum = res.plain_sum && expr::IsBackendOperator(op, "math.add"); } else if (node->is_placeholder() && submodel_ids_.count(node->placeholder_key()) > 0) { res.submodel_nodes.push_back(node); const auto& submodels = submodel_ids_.at(node->placeholder_key()); if (submodels.empty()) { return absl::InvalidArgumentError(absl::StrFormat( "submodel_ids[%s] is empty", node->placeholder_key())); } if (res.bag_count != 0 && res.bag_count != submodels.size()) { return absl::InvalidArgumentError( "all submodels should have the same number of bags"); } res.bag_count = submodels.size(); } else { res.plain_sum_nodes.push_back(node); } } res.bag_count = std::max(res.bag_count, 1); return res; } absl::Status ForestModel::HandlePlainSumExpression( const std::vector<expr::ExprNodePtr>& submodel_nodes, std::vector<expr::ExprNodePtr>&& plain_sum_nodes) { ASSIGN_OR_RETURN( processed_expression_, expr::CallOp("core.get_first", {expr::Placeholder(*res_tuple_key_)})); auto count_map = GetNodeCountMap(expression_); for (auto& node : plain_sum_nodes) { int count = count_map[node->fingerprint()]; if (count > 1) { ASSIGN_OR_RETURN(node, expr::CallOp("math.multiply", {node, expr::Literal<float>(count)})); } } ASSIGN_OR_RETURN(processed_expression_, AddAll(processed_expression_, plain_sum_nodes)); TreeFilter used_trees; for (const auto& node : submodel_nodes) { int count = count_map[node->fingerprint()]; for (int submodel_id : submodel_ids_[node->placeholder_key()]) { used_trees.submodels.insert(submodel_id); if (count > 1) submodel_weight_multipliers_[submodel_id] = count; } } tree_filters_.push_back(used_trees); return absl::OkStatus(); } absl::Status ForestModel::HandleExpressionWithoutBags() { absl::flat_hash_map<std::string, expr::ExprNodePtr> params; for (const auto& [key, submodels] : submodel_ids_) { ASSIGN_OR_RETURN( params[key], expr::CallOp("core.get_nth", {expr::Placeholder(*res_tuple_key_), expr::Literal<int64_t>(tree_filters_.size())})); TreeFilter filter; filter.submodels.insert(submodels.begin(), submodels.end()); tree_filters_.push_back(std::move(filter)); } ASSIGN_OR_RETURN(processed_expression_, SubstitutePlaceholders(expression_, params)); return absl::OkStatus(); } absl::StatusOr<expr::ExprNodePtr> ForestModel::UsedBagCountExpr() const { DCHECK_GT(bag_count_, 0); if (!oob_filters_.has_value()) { return expr::Literal<float>(bag_count_); } expr::ExprNodePtr used_bag_count = nullptr; for (int bag_id = 0; bag_id < bag_count_; ++bag_id) { ASSIGN_OR_RETURN(expr::ExprNodePtr used, expr::CallOp("core.where", {(*oob_filters_)[bag_id], expr::Literal<float>(1), expr::Literal<float>(0)})); if (used_bag_count != nullptr) { ASSIGN_OR_RETURN(used_bag_count, expr::CallOp("math.add", {used_bag_count, used})); } else { used_bag_count = used; } } ASSIGN_OR_RETURN( used_bag_count, expr::CallOp( "core.where", {expr::CallOp("core.greater", {used_bag_count, expr::Literal<float>(0)}), used_bag_count, expr::Literal<OptionalValue<float>>(std::nullopt)})); return used_bag_count; } absl::Status ForestModel::HandleExpressionWithBags() { std::vector<expr::ExprNodePtr> bags(bag_count_); for (int bag_id = 0; bag_id < bag_count_; ++bag_id) { absl::flat_hash_map<std::string, expr::ExprNodePtr> params; for (const auto& [key, submodels] : submodel_ids_) { expr::ExprNodePtr& param = params[key]; ASSIGN_OR_RETURN( param, expr::CallOp("core.get_nth", {expr::Placeholder(*res_tuple_key_), expr::Literal<int64_t>(tree_filters_.size())})); TreeFilter filter; if (submodels.size() <= bag_id) { return absl::InternalError("invalid submodel_ids"); } filter.submodels.insert(submodels[bag_id]); tree_filters_.push_back(std::move(filter)); submodel_weight_multipliers_[submodels[bag_id]] = bag_count_; } ASSIGN_OR_RETURN(bags[bag_id], SubstitutePlaceholders(expression_, params)); if (oob_filters_.has_value()) { ASSIGN_OR_RETURN( bags[bag_id], expr::CallOp("core.where", {(*oob_filters_)[bag_id], bags[bag_id], expr::Literal<float>(0)})); } } ASSIGN_OR_RETURN( auto sum, AddAll(bags[0], absl::Span<expr::ExprNodePtr>(bags.data() + 1, bag_count_ - 1))); ASSIGN_OR_RETURN(processed_expression_, expr::CallOp("math.divide", {sum, UsedBagCountExpr()})); return absl::OkStatus(); } absl::Status ForestModel::Initialize() { if (submodel_ids_.empty()) { res_tuple_key_ = std::nullopt; processed_expression_ = expression_; bag_count_ = 1; return absl::OkStatus(); } else { res_tuple_key_ = submodel_ids_.begin()->first; } ASSIGN_OR_RETURN(auto info, AnalyzeExpression()); is_plain_sum_ = info.plain_sum; bag_count_ = info.bag_count; if (oob_filters_.has_value() && oob_filters_->size() != bag_count_) { return absl::FailedPreconditionError( "if oob_filters is prese
#include "arolla/decision_forest/expr_operator/forest_model.h" #include <cstdint> #include <limits> #include <string> #include <tuple> #include <utility> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "arolla/decision_forest/decision_forest.h" #include "arolla/decision_forest/split_conditions/interval_split_condition.h" #include "arolla/decision_forest/split_conditions/set_of_values_split_condition.h" #include "arolla/dense_array/dense_array.h" #include "arolla/dense_array/qtype/types.h" #include "arolla/expr/annotation_utils.h" #include "arolla/expr/eval/eval.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/registered_expr_operator.h" #include "arolla/expr/testing/testing.h" #include "arolla/expr/tuple_expr_operator.h" #include "arolla/memory/frame.h" #include "arolla/memory/optional_value.h" #include "arolla/qexpr/eval_context.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/typed_slot.h" #include "arolla/serving/expr_compiler.h" #include "arolla/util/indestructible.h" #include "arolla/util/init_arolla.h" #include "arolla/util/testing/status_matchers_backport.h" #include "arolla/util/status_macros_backport.h" namespace arolla { namespace { using ::arolla::testing::EqualsExpr; using ::arolla::testing::IsOk; using ::arolla::testing::StatusIs; using ::arolla::testing::WithNameAnnotation; using ::testing::ElementsAre; using ::testing::Eq; using ::testing::HasSubstr; using ::testing::NotNull; using ::testing::WhenDynamicCastTo; constexpr float inf = std::numeric_limits<float>::infinity(); constexpr auto S = DecisionTreeNodeId::SplitNodeId; constexpr auto A = DecisionTreeNodeId::AdjustmentId; absl::StatusOr<DecisionForestPtr> CreateForest() { std::vector<DecisionTree> trees(2); trees[0].adjustments = {0.5, 1.5, 2.5, 3.5}; trees[0].tag.submodel_id = 0; trees[0].split_nodes = { {S(1), S(2), IntervalSplit(0, 1.5, inf)}, {A(0), A(1), SetOfValuesSplit<int64_t>(1, {5}, false)}, {A(2), A(3), IntervalSplit(0, -inf, 10)}}; trees[1].adjustments = {5}; trees[1].tag.submodel_id = 1; return DecisionForest::FromTrees(std::move(trees)); } absl::StatusOr<ForestModelPtr> CreateForestModelOp() { ForestModel::SubmodelIds submodel_ids = {{"X", {0}}, {"Y", {1}}}; ASSIGN_OR_RETURN(auto preprocessing, expr::CallOp("math.add", {expr::Placeholder("arg"), expr::Literal<int64_t>(1)})); ASSIGN_OR_RETURN(auto expression, expr::CallOp("math.add", {expr::Placeholder("X"), expr::Placeholder("Y")})); ASSIGN_OR_RETURN(auto forest, CreateForest()); return ForestModel::Create({.forest = std::move(forest), .submodel_ids = std::move(submodel_ids), .inputs = {{"p1"}, {"p2", preprocessing}}, .expression = expression}); } absl::Status InitAlias() { static Indestructible<absl::Status> init_status( expr::RegisterOperatorAlias("alias_math.add", "math.add").status()); return *init_status; } class ForestModelTest : public ::testing::Test { void SetUp() override { CHECK_OK(InitArolla()); CHECK_OK(InitAlias()); } }; TEST_F(ForestModelTest, NotEnoughArgs) { ForestModel::ConstructorArgs model_data; model_data.submodel_ids = {{"X", {0}}, {"Y", {1}}}; ASSERT_OK_AND_ASSIGN(model_data.expression, expr::CallOp("math.add", {expr::Placeholder("X"), expr::Placeholder("Y")})); ASSERT_OK_AND_ASSIGN(model_data.forest, CreateForest()); model_data.inputs = {{"p1"}}; EXPECT_THAT(ForestModel::Create(model_data), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("not enough args"))); } TEST_F(ForestModelTest, ParameterNameCollision) { ForestModel::ConstructorArgs model_data; model_data.submodel_ids = {{"X", {0}}, {"Y", {1}}}; ASSERT_OK_AND_ASSIGN( auto preprocessing, expr::CallOp("math.add", {expr::Placeholder("arg"), expr::Literal<OptionalValue<int64_t>>(1)})); ASSERT_OK_AND_ASSIGN(model_data.expression, expr::CallOp("math.add", {expr::Placeholder("X"), expr::Placeholder("Y")})); ASSERT_OK_AND_ASSIGN(model_data.forest, CreateForest()); model_data.inputs = {{"p1"}, {"p1", preprocessing}}; EXPECT_THAT(ForestModel::Create(model_data), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("non-unique parameter name: 'p1'"))); model_data.inputs = {{"X"}, {"p2", preprocessing}}; EXPECT_THAT( ForestModel::Create(model_data), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("name collision of an input and a submodel: 'X'"))); } TEST_F(ForestModelTest, IncorrectExpression) { ASSERT_OK_AND_ASSIGN(DecisionForestPtr forest, DecisionForest::FromTrees({})); { ASSERT_OK_AND_ASSIGN(expr::ExprNodePtr expression, expr::CallOp("math.add", {expr::Placeholder("X"), expr::Placeholder("Y")})); EXPECT_THAT(ForestModel::Create({.forest = forest, .submodel_ids = {{"X", {0}}}, .inputs = {{"p1"}, {"p2"}}, .expression = expression}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("P.Y doesn't correspond to any input and it " "is not found in submodel_ids"))); } { expr::ExprNodePtr expression = expr::Placeholder("X"); EXPECT_THAT( ForestModel::Create({.forest = forest, .submodel_ids = {{"X", {0}}, {"Y", {1}}}, .expression = expression}), StatusIs( absl::StatusCode::kInvalidArgument, HasSubstr("submodels [Y] are not used in the expression, but are " "mentioned in submodel_ids"))); } { expr::ExprNodePtr expression = expr::Leaf("X"); EXPECT_THAT( ForestModel::Create({.forest = forest, .expression = expression}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("leaves are not allowed in an expression"))); } } TEST_F(ForestModelTest, UsingInputInExpression) { ASSERT_OK_AND_ASSIGN(auto expression, expr::CallOp("math.add", {expr::Placeholder("X"), expr::Placeholder("p1")})); auto f1 = expr::Literal<float>(1.0); auto i5 = expr::Literal<int64_t>(5); ASSERT_OK_AND_ASSIGN(auto forest, CreateForest()); ASSERT_OK_AND_ASSIGN(auto model_op, ForestModel::Create({.forest = forest, .submodel_ids = {{"X", {0}}}, .inputs = {{"p1"}, {"p2"}}, .expression = expression})); ASSERT_OK_AND_ASSIGN(auto model, expr::CallOp(model_op, {f1, i5})); ASSERT_OK_AND_ASSIGN(auto expanded_model, expr::ToLowest(model)); ASSERT_TRUE(expanded_model->is_op()); EXPECT_TRUE(IsRegisteredOperator(expanded_model->op())); EXPECT_TRUE(IsBackendOperator(*DecayRegisteredOperator(expanded_model->op()), "math.add")); EXPECT_THAT(expanded_model->node_deps()[1], EqualsExpr(f1)); } TEST_F(ForestModelTest, QTypePropagation) { ASSERT_OK_AND_ASSIGN(auto model_op, CreateForestModelOp()); ASSERT_OK_AND_ASSIGN( auto model, expr::CallOp(model_op, {expr::Literal<OptionalValue<float>>(1.0), expr::Literal<int64_t>(5)})); EXPECT_EQ(model->qtype(), GetQType<float>()); } TEST_F(ForestModelTest, QTypePropagationUsesPreprocessing) { ForestModel::ConstructorArgs model_data; model_data.submodel_ids = {{"X", {0, 1}}}; ASSERT_OK_AND_ASSIGN(auto preprocessing, expr::CallOp("core.const_with_shape", {expr::Literal<DenseArrayShape>({5}), expr::Placeholder("arg")})); model_data.expression = expr::Placeholder("X"); ASSERT_OK_AND_ASSIGN(model_data.forest, CreateForest()); model_data.inputs = {{"p1", preprocessing}, {"p2", preprocessing}}; ASSERT_OK_AND_ASSIGN(auto model_op, ForestModel::Create(model_data)); ASSERT_OK_AND_ASSIGN( auto model, expr::CallOp(model_op, {expr::Literal<OptionalValue<float>>(1.0), expr::Literal<int64_t>(5)})); EXPECT_EQ(model->qtype(), GetDenseArrayQType<float>()); } TEST_F(ForestModelTest, QTypePropagationPlainSumWithBroadcasting) { ForestModel::ConstructorArgs model_data; model_data.submodel_ids = {{"X", {0, 1}}}; ASSERT_OK_AND_ASSIGN( model_data.expression, expr::CallOp("math.add", {expr::Literal(CreateDenseArray<float>({1., 2., 3.})), expr::Placeholder("X")})); ASSERT_OK_AND_ASSIGN(model_data.forest, CreateForest()); model_data.inputs = {{"p1"}, {"p2"}}; ASSERT_OK_AND_ASSIGN(auto model_op, ForestModel::Create(model_data)); ASSERT_OK_AND_ASSIGN( auto model, expr::CallOp(model_op, {expr::Literal<OptionalValue<float>>(1.0), expr::Literal<int64_t>(5)})); EXPECT_EQ(model->qtype(), GetDenseArrayQType<float>()); ASSERT_OK_AND_ASSIGN(auto lowered, expr::ToLowest(model)); EXPECT_EQ(lowered->qtype(), GetDenseArrayQType<float>()); } TEST_F(ForestModelTest, EmptyForest) { ASSERT_OK_AND_ASSIGN(auto forest, DecisionForest::FromTrees({})); expr::ExprNodePtr expression = expr::Literal<float>(0.5); ASSERT_OK_AND_ASSIGN(auto model_op, ForestModel::Create({.forest = std::move(forest), .expression = expression})); ASSERT_OK_AND_ASSIGN(auto model, expr::CallOp(model_op, {})); ASSERT_OK_AND_ASSIGN(auto expanded_model, expr::ToLowest(model)); EXPECT_THAT(expanded_model, EqualsExpr(expression)); } TEST_F(ForestModelTest, ToLower) { ASSERT_OK_AND_ASSIGN(auto model_op, CreateForestModelOp()); { ASSERT_OK_AND_ASSIGN(auto model, expr::CallOp(model_op, {expr::Literal<float>(1.0), expr::Literal<int64_t>(5)})); ASSERT_OK_AND_ASSIGN(model, WithNameAnnotation(model, "forest")); ASSERT_OK_AND_ASSIGN(auto expanded_model, expr::ToLowest(model)); EXPECT_NE(model->fingerprint(), expanded_model->fingerprint()); EXPECT_EQ(ReadNameAnnotation(expanded_model), "forest"); } { ASSERT_OK_AND_ASSIGN( auto model, expr::CallOp(model_op, {expr::Leaf("f"), expr::Leaf("i")})); ASSERT_OK_AND_ASSIGN(auto expanded_model, expr::ToLowest(model)); EXPECT_EQ(model->fingerprint(), expanded_model->fingerprint()); } } absl::StatusOr<expr::ExprNodePtr> GetExpressionForTest(std::string A, std::string B, std::string C, std::string op) { return expr::CallOp( "alias_math.add", {expr::Placeholder(A), expr::CallOp(op, {expr::Placeholder(B), expr::Placeholder(C)})}); } TEST_F(ForestModelTest, ToLowerMergeSubmodels) { ASSERT_OK_AND_ASSIGN(auto forest, DecisionForest::FromTrees({})); ASSERT_OK_AND_ASSIGN(auto expression, GetExpressionForTest("input", "X", "Y", "math.add")); ASSERT_OK_AND_ASSIGN( auto model_op, ForestModel::Create({.forest = std::move(forest), .submodel_ids = {{"X", {0, 2}}, {"Y", {1, 3}}}, .inputs = {{"input"}}, .expression = expression})); ASSERT_OK_AND_ASSIGN(auto model, expr::CallOp(model_op, {expr::Literal<float>(1.0)})); ASSERT_OK_AND_ASSIGN(auto expanded_model, expr::ToLowest(model)); EXPECT_TRUE(IsRegisteredOperator(expanded_model->op())); EXPECT_TRUE(IsBackendOperator(*DecayRegisteredOperator(expanded_model->op()), "math.add")); EXPECT_THAT(expanded_model->node_deps()[0]->op().get(), WhenDynamicCastTo<const expr::GetNthOperator*>(NotNull())); } TEST_F(ForestModelTest, MergeDuplicatedSubmodels) { std::vector<DecisionTree> trees(2); trees[0].adjustments = {1.0}; trees[0].tag.submodel_id = 0; trees[1].adjustments = {3.0}; trees[1].tag.submodel_id = 1; ASSERT_OK_AND_ASSIGN(auto forest, DecisionForest::FromTrees({std::move(trees)})); ASSERT_OK_AND_ASSIGN(auto expression, GetExpressionForTest("X", "Y", "X", "math.add")); ASSERT_OK_AND_ASSIGN( auto model_op, ForestModel::Create({.forest = std::move(forest), .submodel_ids = {{"X", {0}}, {"Y", {1}}}, .expression = expression})); ASSERT_OK_AND_ASSIGN(auto model, expr::CallOp(model_op, {})); FrameLayout::Builder layout_builder; ASSERT_OK_AND_ASSIGN( auto executable_model, CompileAndBindForDynamicEvaluation(expr::DynamicEvaluationEngineOptions(), &layout_builder, model, {})); FrameLayout layout = std::move(layout_builder).Build(); ASSERT_OK_AND_ASSIGN(const FrameLayout::Slot<float> output, executable_model->output_slot().ToSlot<float>()); RootEvaluationContext ctx(&layout); EXPECT_OK(executable_model->InitializeLiterals(&ctx)); EXPECT_THAT(executable_model->Execute(&ctx), IsOk()); EXPECT_THAT(ctx.Get(output), Eq(5.0f)); } TEST_F(ForestModelTest, DuplicatedNodes) { ASSERT_OK_AND_ASSIGN(auto forest, DecisionForest::FromTrees({})); ASSERT_OK_AND_ASSIGN(auto expression, GetExpressionForTest("input", "X", "input", "math.add")); ASSERT_OK_AND_ASSIGN(auto model_op, ForestModel::Create({.forest = std::move(forest), .submodel_ids = {{"X", {0}}}, .inputs = {{"input"}}, .expression = expression})); ASSERT_OK_AND_ASSIGN(auto model, expr::CallOp(model_op, {expr::Leaf("input")})); FrameLayout::Builder layout_builder; auto input_slot = layout_builder.AddSlot<float>(); ASSERT_OK_AND_ASSIGN( auto executable_model, CompileAndBindForDynamicEvaluation( expr::DynamicEvaluationEngineOptions(), &layout_builder, model, {{"input", TypedSlot::FromSlot(input_slot)}})); FrameLayout layout = std::move(layout_builder).Build(); ASSERT_OK_AND_ASSIGN(const FrameLayout::Slot<float> output, executable_model->output_slot().ToSlot<float>()); RootEvaluationContext ctx(&layout); EXPECT_OK(executable_model->InitializeLiterals(&ctx)); ctx.Set(input_slot, 3.1f); EXPECT_THAT(executable_model->Execute(&ctx), IsOk()); EXPECT_FLOAT_EQ(ctx.Get(output), 6.2f); } TEST_F(ForestModelTest, ToLowerSingleBag) { ASSERT_OK_AND_ASSIGN(auto forest, DecisionForest::FromTrees({})); ASSERT_OK_AND_ASSIGN( auto expression, GetExpressionForTest("input", "X", "Y", "math.multiply")); ASSERT_OK_AND_ASSIGN( auto model_op, ForestModel::Create({.forest = std::move(forest), .submodel_ids = {{"X", {0}}, {"Y", {1}}}, .inputs = {{"input"}}, .expression = expression})); ASSERT_OK_AND_ASSIGN(auto model, expr::CallOp(model_op, {expr::Literal<float>(1.0)})); ASSERT_OK_AND_ASSIGN(auto expanded_model, expr::ToLowest(model)); EXPECT_TRUE(IsRegisteredOperator(expanded_model->op())); EXPECT_TRUE(IsBackendOperator(*DecayRegisteredOperator(expanded_model->op()), "math.add")); EXPECT_TRUE(expanded_model->node_deps()[0]->is_literal()); EXPECT_TRUE(IsRegisteredOperator(expanded_model->node_deps()[1]->op())); EXPECT_TRUE(IsBackendOperator( *DecayRegisteredOperator(expanded_model->node_deps()[1]->op()), "math.multiply")); } TEST_F(ForestModelTest, ToLowerExpandBags) { std::vector<DecisionTree> trees(4); trees[0].adjustments = {1.0}; trees[0].tag.submodel_id = 0; trees[1].adjustments = {2.0}; trees[1].tag.submodel_id = 1; trees[2].adjustments = {4.0}; trees[2].tag.submodel_id = 2; trees[3].adjustments = {8.0}; trees[3].tag.submodel_id = 3; ASSERT_OK_AND_ASSIGN(auto forest, DecisionForest::FromTrees({std::move(trees)})); ASSERT_OK_AND_ASSIGN( auto expression, GetExpressionForTest("input", "X", "Y", "math.multiply")); ASSERT_OK_AND_ASSIGN( auto model_op, ForestModel::Create({.forest = std::move(forest), .submodel_ids = {{"X", {0, 2}}, {"Y", {1, 3}}}, .inputs = {{"input"}}, .expression = expression})); ASSERT_OK_AND_ASSIGN(auto model, expr::CallOp(model_op, {expr::Literal<float>(1.2)})); ASSERT_OK_AND_ASSIGN(auto expanded_model, expr::ToLowest(model)); EXPECT_TRUE(IsBackendOperator(*DecayRegisteredOperator(expanded_model->op()), "math.divide")); ASSERT_OK_AND_ASSIGN( auto model_fn, (ExprCompiler<std::tuple<float>, float>()).CompileOperator(model_op)); ASSERT_OK_AND_ASSIGN(float res, model_fn(1.2)); EXPECT_FLOAT_EQ(res, 69.2f); } TEST_F(ForestModelTest, OutOfBagFilters) { std::vector<DecisionTree> trees(4); trees[0].adjustments = {1.0}; trees[0].tag.submodel_id = 0; trees[1].adjustments = {2.0}; trees[1].tag.submodel_id = 1; trees[2].adjustments = {4.0}; trees[2].tag.submodel_id = 2; trees[3].adjustments = {8.0}; trees[3].tag.submodel_id = 3; ASSERT_OK_AND_ASSIGN(auto forest, DecisionForest::FromTrees({std::move(trees)})); ASSERT_OK_AND_ASSIGN( auto expression, GetExpressionForTest("input", "X", "Y", "math.multiply")); ASSERT_OK_AND_ASSIGN(auto filter0, expr::CallOp("core.less", {expr::Placeholder("input"), expr::Literal(2.0f)})); ASSERT_OK_AND_ASSIGN(auto filter1, expr::CallOp("core.less", {expr::Literal(2.0f), expr::Placeholder("input")})); ASSERT_OK_AND_ASSIGN( auto model_op, ForestModel::Create({.forest = std::move(forest), .submodel_ids = {{"X", {0, 2}}, {"Y", {1, 3}}}, .inputs = {{"input"}}, .expression = expression, .oob_filters = std::vector{filter0, filter1}})); ASSERT_OK_AND_ASSIGN(auto model, expr::CallOp(model_op, {expr::Literal<float>(1.2)})); ASSERT_OK_AND_ASSIGN(auto expanded_model, expr::ToLowest(model)); EXPECT_TRUE(IsBackendOperator(*DecayRegisteredOperator(expanded_model->op()), "math.divide")); ASSERT_OK_AND_ASSIGN(auto model_fn, (ExprCompiler<std::tuple<float>, OptionalValue<float>>()) .CompileOperator(model_op)); { ASSERT_OK_AND_ASSIGN(OptionalValue<float> res, model_fn(1)); EXPECT_EQ(res, 9.0f); } { ASSERT_OK_AND_ASSIGN(OptionalValue<float> res, model_fn(2)); EXPECT_EQ(res, OptionalValue<float>{}); } { ASSERT_OK_AND_ASSIGN(OptionalValue<float> res, model_fn(3)); EXPECT_EQ(res, 131.0f); } } TEST_F(ForestModelTest, BagsAndTruncation) { std::vector<DecisionTree> trees(4); trees[0].adjustments = {1.0}; trees[0].tag = {.step = 0, .submodel_id = 0}; trees[1].adjustments = {2.0}; trees[1].tag = {.step = 0, .submodel_id = 1}; trees[2].adjustments = {4.0}; trees[2].tag = {.step = 1, .submodel_id = 2}; trees[3].adjustments = {8.0}; trees[3].tag = {.step = 1, .submodel_id = 3}; ASSERT_OK_AND_ASSIGN(auto forest, DecisionForest::FromTrees({std::move(trees)})); ASSERT_OK_AND_ASSIGN( auto expression, GetExpressionForTest("input", "X", "Y", "math.multiply")); ASSERT_OK_AND_ASSIGN( auto model_op, ForestModel::Create({.forest = std::move(forest), .submodel_ids = {{"X", {0, 2}}, {"Y", {1, 3}}}, .inputs = {{"input"}}, .expression = expression, .truncation_step = 1})); ASSERT_OK_AND_ASSIGN( auto model_fn, (ExprCompiler<std::tuple<float>, float>()).CompileOperator(model_op)); ASSERT_OK_AND_ASSIGN(float res, model_fn(1.2)); EXPECT_FLOAT_EQ(res, 5.2f); } TEST_F(ForestModelTest, ConversionToOptional) { ASSERT_OK_AND_ASSIGN(const auto model_op, CreateForestModelOp()); const auto input = expr::Literal<float>(1.0); ASSERT_OK_AND_ASSIGN(const auto converted_input, expr::CallOp("core.to_optional", {input})); ASSERT_OK_AND_ASSIGN( auto model, expr::CallOp(model_op, {input, expr::Literal<int64_t>(5)})); ASSERT_OK_AND_ASSIGN(auto expanded_model, expr::ToLowest(model)); ASSERT_OK_AND_ASSIGN( auto model_with_converted_input, expr::CallOp(model_op, {converted_input, expr::Literal<int64_t>(5)})); ASSERT_OK_AND_ASSIGN(auto expanded_model_with_converted_input, expr::ToLowest(model_with_converted_input)); EXPECT_THAT(expanded_model_with_converted_input, EqualsExpr(expanded_model)); } TEST_F(ForestModelTest, ConversionFromDouble) { ASSERT_OK_AND_ASSIGN(const auto model_op, CreateForestModelOp()); const auto input = expr::Literal<double>(1.0); ASSERT_OK_AND_ASSIGN(const auto converted_input, expr::CallOp("core.to_float32", {input})); ASSERT_OK_AND_ASSIGN( auto model, expr::CallOp(model_op, {input, expr::Literal<int64_t>(5)})); ASSERT_OK_AND_ASSIGN(auto expanded_model, expr::ToLowest(model)); ASSERT_OK_AND_ASSIGN( auto model_with_converted_input, expr::CallOp(model_op, {converted_input, expr::Literal<int64_t>(5)})); ASSERT_OK_AND_ASSIGN(auto expanded_model_with_converted_input, expr::ToLowest(model_with_converted_input)); EXPECT_THAT(expanded_model_with_converted_input, EqualsExpr(expanded_model)); } TEST_F(ForestModelTest, ConversionFromInteger) { ASSERT_OK_AND_ASSIGN(const auto model_op, CreateForestModelOp()); const auto input = expr::Literal<int>(1); ASSERT_OK_AND_ASSIGN(const auto converted_input, expr::CallOp("core.to_float32", {input})); ASSERT_OK_AND_ASSIGN( auto model, expr::CallOp(model_op, {input, expr::Literal<int64_t>(5)})); ASSERT_OK_AND_ASSIGN(auto expanded_model, expr::ToLowest(model)); ASSERT_OK_AND_ASSIGN( auto model_with_converted_input, expr::CallOp(model_op, {converted_input, expr::Literal<int64_t>(5)})); ASSERT_OK_AND_ASSIGN(auto expanded_model_with_converted_input, expr::ToLowest(model_with_converted_input)); EXPECT_THAT(expanded_model_with_converted_input, EqualsExpr(expanded_model)); } TEST_F(ForestModelTest, EvaluateOnScalars) { ASSERT_OK_AND_ASSIGN(auto forest_model, CreateForestModelOp()); ASSERT_OK_AND_ASSIGN( auto model, expr::CallOp(forest_model, {expr::Leaf("f"), expr::Leaf("i")})); FrameLayout::Builder layout_builder; auto f_slot = layout_builder.AddSlot<float>(); auto i_slot = layout_builder.AddSlot<int64_t>(); ASSERT_OK_AND_ASSIGN( auto executable_model, CompileAndBindForDynamicEvaluation(expr::DynamicEvaluationEngineOptions(), &layout_builder, model, {{"f", TypedSlot::FromSlot(f_slot)}, {"i", TypedSlot::FromSlot(i_slot)}})); FrameLayout layout = std::move(layout_builder).Build(); ASSERT_OK_AND_ASSIGN(const FrameLayout::Slot<float> output, executable_model->output_slot().ToSlot<float>()); RootEvaluationContext ctx(&layout); EXPECT_OK(executable_model->InitializeLiterals(&ctx)); ctx.Set(f_slot, 1.0f); ctx.Set(i_slot, 5); EXPECT_THAT(executable_model->Execute(&ctx), IsOk()); EXPECT_FLOAT_EQ(ctx.Get(output), 5.5f); ctx.Set(f_slot, 3.0f); ctx.Set(i_slot, 0); EXPECT_THAT(executable_model->Execute(&ctx), IsOk()); EXPECT_FLOAT_EQ(ctx.Get(output), 8.5f); } TEST_F(ForestModelTest, EvaluateOnScalarAndArray) { ASSERT_OK_AND_ASSIGN(auto forest_model, CreateForestModelOp()); ASSERT_OK_AND_ASSIGN( auto model, expr::CallOp(forest_model, {expr::Leaf("f"), expr::Leaf("i")})); FrameLayout::Builder layout_builder; auto f_slot = layout_builder.AddSlot<DenseArray<float>>(); auto i_slot = layout_builder.AddSlot<int64_t>(); EXPECT_THAT( CompileAndBindForDynamicEvaluation(expr::DynamicEvaluationEngineOptions(), &layout_builder, model, {{"f", TypedSlot::FromSlot(f_slot)}, {"i", TypedSlot::FromSlot(i_slot)}}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("either all forest inputs must be scalars or all " "forest inputs must be arrays, but arg[0] is " "DENSE_ARRAY_FLOAT32 and " "arg[1] is OPTIONAL_INT64"))); } TEST_F(ForestModelTest, EvaluateOnDenseArrays) { ASSERT_OK_AND_ASSIGN(const auto model_op, CreateForestModelOp()); ASSERT_OK_AND_ASSIGN( auto model, expr::CallOp(model_op, {expr::Leaf("f"), expr::Leaf("i")})); FrameLayout::Builder layout_builder; auto f_slot = layout_builder.AddSlot<DenseArray<float>>(); auto i_slot = layout_builder.AddSlot<DenseArray<int64_t>>(); ASSERT_OK_AND_ASSIGN( auto executable_model, CompileAndBindForDynamicEvaluation(expr::DynamicEvaluationEngineOptions(), &layout_builder, model, {{"f", TypedSlot::FromSlot(f_slot)}, {"i", TypedSlot::FromSlot(i_slot)}})); FrameLayout layout = std::move(layout_builder).Build(); ASSERT_OK_AND_ASSIGN( const FrameLayout::Slot<DenseArray<float>> output, executable_model->output_slot().ToSlot<DenseArray<float>>()); RootEvaluationContext ctx(&layout); EXPECT_OK(executable_model->InitializeLiterals(&ctx)); ctx.Set(f_slot, CreateDenseArray<float>({1.0f, 3.0f})); ctx.Set(i_slot, CreateDenseArray<int64_t>({5, 0})); EXPECT_THAT(executable_model->Execute(&ctx), IsOk()); EXPECT_THAT(ctx.Get(output), ElementsAre(5.5f, 8.5f)); } } }
2,400
#ifndef AROLLA_DECISION_FOREST_EXPR_OPERATOR_DECISION_FOREST_OPERATOR_H_ #define AROLLA_DECISION_FOREST_EXPR_OPERATOR_DECISION_FOREST_OPERATOR_H_ #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "arolla/decision_forest/decision_forest.h" #include "arolla/expr/basic_expr_operator.h" #include "arolla/expr/expr_operator.h" #include "arolla/qtype/qtype.h" namespace arolla { class DecisionForestOperator : public expr::BasicExprOperator, public expr::BuiltinExprOperatorTag { public: DecisionForestOperator(DecisionForestPtr forest, std::vector<TreeFilter> tree_filters); DecisionForestOperator( DecisionForestPtr forest, std::vector<TreeFilter> tree_filters, const absl::flat_hash_map<int, QTypePtr>& required_types); absl::StatusOr<QTypePtr> GetOutputQType( absl::Span<const QTypePtr> input_qtypes) const final; DecisionForestPtr forest() const { return forest_; } const std::vector<TreeFilter>& tree_filters() const { return tree_filters_; } absl::string_view py_qvalue_specialization_key() const final { return "::arolla::DecisionForestOperator"; } private: DecisionForestOperator(std::vector<int> required_input_ids, DecisionForestPtr forest, std::vector<TreeFilter> tree_filters); DecisionForestPtr forest_; std::vector<TreeFilter> tree_filters_; std::vector<int> required_input_ids_; }; } #endif #include "arolla/decision_forest/expr_operator/decision_forest_operator.h" #include <algorithm> #include <utility> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "absl/types/span.h" #include "arolla/decision_forest/decision_forest.h" #include "arolla/expr/basic_expr_operator.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/qtype/array_like/array_like_qtype.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/tuple_qtype.h" #include "arolla/util/fingerprint.h" #include "arolla/util/status_macros_backport.h" namespace arolla { namespace { std::vector<int> GetRequiredInputIds( const absl::flat_hash_map<int, QTypePtr>& required_types) { std::vector<int> result; result.reserve(required_types.size()); for (const auto& [id, _] : required_types) { result.push_back(id); } return result; } } DecisionForestOperator::DecisionForestOperator( DecisionForestPtr forest, std::vector<TreeFilter> tree_filters) : DecisionForestOperator(GetRequiredInputIds(forest->GetRequiredQTypes()), forest, std::move(tree_filters)) {} DecisionForestOperator::DecisionForestOperator( DecisionForestPtr forest, std::vector<TreeFilter> tree_filters, const absl::flat_hash_map<int, QTypePtr>& required_types) : DecisionForestOperator(GetRequiredInputIds(required_types), std::move(forest), std::move(tree_filters)) {} DecisionForestOperator::DecisionForestOperator( std::vector<int> required_input_ids, DecisionForestPtr forest, std::vector<TreeFilter> tree_filters) : BasicExprOperator( "anonymous.decision_forest_operator", expr::ExprOperatorSignature::MakeVariadicArgs(), "Evaluates decision forest stored in the operator state.", FingerprintHasher("::arolla::DecisionForestOperator") .Combine(forest->fingerprint()) .CombineSpan(tree_filters) .Finish()), forest_(std::move(forest)), tree_filters_(std::move(tree_filters)), required_input_ids_(std::move(required_input_ids)) { std::sort(required_input_ids_.begin(), required_input_ids_.end()); } absl::StatusOr<QTypePtr> DecisionForestOperator::GetOutputQType( absl::Span<const QTypePtr> input_qtypes) const { int last_forest_input_id = required_input_ids_.empty() ? -1 : required_input_ids_.back(); if (last_forest_input_id >= static_cast<int>(input_qtypes.size())) { return absl::InvalidArgumentError(absl::StrFormat( "not enough arguments for the decision forest: expected at least %d, " "got %d", last_forest_input_id + 1, input_qtypes.size())); } bool batched = !input_qtypes.empty() && !required_input_ids_.empty() && IsArrayLikeQType(input_qtypes[required_input_ids_[0]]); for (int id : required_input_ids_) { if (IsArrayLikeQType(input_qtypes[id]) != batched) { DCHECK(!required_input_ids_.empty()); return absl::InvalidArgumentError(absl::StrFormat( "either all forest inputs must be scalars or all forest inputs " "must be arrays, but arg[%d] is %s and arg[%d] is %s", required_input_ids_[0], input_qtypes[required_input_ids_[0]]->name(), id, input_qtypes[id]->name())); } } QTypePtr output_type; if (batched) { DCHECK(!required_input_ids_.empty()); ASSIGN_OR_RETURN(const ArrayLikeQType* array_type, ToArrayLikeQType(input_qtypes[required_input_ids_[0]])); ASSIGN_OR_RETURN(output_type, array_type->WithValueQType(GetQType<float>())); } else { output_type = GetQType<float>(); } return MakeTupleQType( std::vector<QTypePtr>(tree_filters_.size(), output_type)); } }
#include "arolla/decision_forest/expr_operator/decision_forest_operator.h" #include <cstdint> #include <limits> #include <memory> #include <utility> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "arolla/decision_forest/decision_forest.h" #include "arolla/decision_forest/split_conditions/interval_split_condition.h" #include "arolla/decision_forest/split_conditions/set_of_values_split_condition.h" #include "arolla/dense_array/qtype/types.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/tuple_qtype.h" #include "arolla/util/init_arolla.h" #include "arolla/util/testing/status_matchers_backport.h" namespace arolla { namespace { using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::StatusIs; using ::testing::HasSubstr; constexpr float inf = std::numeric_limits<float>::infinity(); constexpr auto S = DecisionTreeNodeId::SplitNodeId; constexpr auto A = DecisionTreeNodeId::AdjustmentId; absl::StatusOr<DecisionForestPtr> CreateForest() { std::vector<DecisionTree> trees(2); trees[0].adjustments = {0.5, 1.5, 2.5, 3.5}; trees[0].tag.submodel_id = 0; trees[0].split_nodes = { {S(1), S(2), IntervalSplit(0, 1.5, inf)}, {A(0), A(1), SetOfValuesSplit<int64_t>(1, {5}, false)}, {A(2), A(3), IntervalSplit(0, -inf, 10)}}; trees[1].adjustments = {5}; trees[1].tag.submodel_id = 1; return DecisionForest::FromTrees(std::move(trees)); } class DecisionForestOperatorTest : public ::testing::Test { void SetUp() override { CHECK_OK(InitArolla()); } }; TEST_F(DecisionForestOperatorTest, GetOutputQType) { ASSERT_OK_AND_ASSIGN(const DecisionForestPtr forest, CreateForest()); { auto forest_op = std::make_shared<DecisionForestOperator>( forest, std::vector<TreeFilter>{}); EXPECT_THAT(forest_op->GetOutputQType({GetQType<float>()}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("not enough arguments for the decision " "forest: expected at least 2, got 1"))); EXPECT_THAT( forest_op->GetOutputQType( {GetQType<float>(), GetDenseArrayQType<float>()}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("either all forest inputs must be scalars or all " "forest inputs must be arrays, but arg[0] is " "FLOAT32 and arg[1] is DENSE_ARRAY_FLOAT32"))); EXPECT_THAT( forest_op->GetOutputQType({GetQType<float>(), GetQType<float>()}), IsOkAndHolds(MakeTupleQType({}))); } { auto forest_op = std::make_shared<DecisionForestOperator>( forest, std::vector<TreeFilter>{TreeFilter{.submodels = {0}}, TreeFilter{.submodels = {1, 2}}}); EXPECT_THAT(forest_op->GetOutputQType({GetQType<float>()}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("not enough arguments for the decision " "forest: expected at least 2, got 1"))); EXPECT_THAT( forest_op->GetOutputQType( {GetQType<float>(), GetDenseArrayQType<float>()}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("either all forest inputs must be scalars or all " "forest inputs must be arrays, but arg[0] is " "FLOAT32 and arg[1] is DENSE_ARRAY_FLOAT32"))); EXPECT_THAT( forest_op->GetOutputQType({GetQType<float>(), GetQType<float>()}), IsOkAndHolds(MakeTupleQType({GetQType<float>(), GetQType<float>()}))); } } } }
2,401
#ifndef AROLLA_DENSE_ARRAY_DENSE_ARRAY_H_ #define AROLLA_DENSE_ARRAY_DENSE_ARRAY_H_ #include <cstdint> #include <cstring> #include <initializer_list> #include <optional> #include <type_traits> #include <utility> #include <vector> #include "absl/log/check.h" #include "absl/types/span.h" #include "arolla/dense_array/bitmap.h" #include "arolla/memory/buffer.h" #include "arolla/memory/optional_value.h" #include "arolla/memory/raw_buffer_factory.h" #include "arolla/util/api.h" #include "arolla/util/bits.h" #include "arolla/util/fingerprint.h" #include "arolla/util/iterator.h" #include "arolla/util/unit.h" #include "arolla/util/view_types.h" namespace arolla { template <typename T> struct AROLLA_API DenseArray { using base_type = T; using value_type = OptionalValue<view_type_t<T>>; using size_type = int64_t; using const_iterator = ConstArrayIterator<DenseArray<T>>; using difference_type = int64_t; using offset_type = int64_t; Buffer<T> values; Buffer<bitmap::Word> bitmap; int bitmap_bit_offset = 0; int64_t size() const { return values.size(); } bool empty() const { return values.empty(); } bool IsFull() const { return PresentCount() == size(); } int64_t PresentCount() const { return bitmap::CountBits(bitmap, bitmap_bit_offset, size()); } bool IsAllMissing() const { return PresentCount() == 0; } bool IsAllPresent() const { return bitmap.empty() || PresentCount() == size(); } bool present(int64_t offset) const { DCHECK_GE(offset, 0); DCHECK_LT(offset, size()); DCHECK(CheckBitmapMatchesValues()); return bitmap::GetBit(bitmap, offset + bitmap_bit_offset); } const OptionalValue<view_type_t<T>> operator[]( int64_t offset) const { if (present(offset)) { return values[offset]; } else { return std::nullopt; } } bool is_owned() const { return values.is_owner() && bitmap.is_owner(); } DenseArray MakeOwned( RawBufferFactory* buf_factory = GetHeapBufferFactory()) const { return {values.DeepCopy(buf_factory), bitmap.DeepCopy(buf_factory), bitmap_bit_offset}; } DenseArray MakeUnowned() const { return {values.ShallowCopy(), bitmap.ShallowCopy(), bitmap_bit_offset}; } DenseArray Slice(int64_t start_id, int64_t row_count) const { DCHECK_GE(start_id, 0); DCHECK_GE(row_count, 0); DCHECK_LE(start_id + row_count, size()); DenseArray res; res.values = values.Slice(start_id, row_count); if (!bitmap.empty()) { res.bitmap_bit_offset = (start_id + bitmap_bit_offset) & (bitmap::kWordBitCount - 1); int64_t b_start = (start_id + bitmap_bit_offset) / bitmap::kWordBitCount; int64_t b_size = bitmap::BitmapSize(res.bitmap_bit_offset + row_count); res.bitmap = bitmap.Slice(b_start, b_size); } return res; } DenseArray ForceNoBitmapBitOffset( RawBufferFactory* factory = GetHeapBufferFactory()) && { if (bitmap_bit_offset > 0) { int64_t bitmap_size = bitmap::BitmapSize(size()); bitmap::Bitmap::Builder bldr(bitmap_size, factory); for (int64_t i = 0; i < bitmap_size; ++i) { bldr.Set(i, bitmap::GetWordWithOffset(bitmap, i, bitmap_bit_offset)); } bitmap = std::move(bldr).Build(); bitmap_bit_offset = 0; } return std::move(*this); } DenseArray ForceNoBitmapBitOffset( RawBufferFactory* factory = GetHeapBufferFactory()) const& { DenseArray copy = *this; return std::move(copy).ForceNoBitmapBitOffset(factory); } template <typename Fn> void ForEach(Fn&& fn) const { DCHECK(CheckBitmapMatchesValues()); if (bitmap.empty()) { auto iter = values.begin(); for (int64_t id = 0; id < size(); ++id) fn(id, true, *(iter++)); } else { bitmap::IterateByGroups( bitmap.begin(), bitmap_bit_offset, size(), [&](int64_t offset) { auto values_group = values.begin() + offset; return [&fn, values_group, offset](int i, bool present) { fn(offset + i, present, values_group[i]); }; }); } } template <typename Fn> void ForEachPresent(Fn&& fn) const { ForEach([&](int64_t id, bool presence, view_type_t<T> value) { if (presence) { fn(id, value); } }); } template <typename Fn> void ForEachByGroups(Fn init_group_fn) const { DCHECK(CheckBitmapMatchesValues()); if (bitmap.empty()) { auto fn = init_group_fn(0); auto iter = values.begin(); for (int64_t id = 0; id < size(); ++id) fn(id, true, *(iter++)); } else { bitmap::IterateByGroups(bitmap.begin(), bitmap_bit_offset, size(), [&](int64_t offset) { auto values_group = values.begin() + offset; auto fn = init_group_fn(offset); return [=](int i, bool present) mutable { fn(offset + i, present, values_group[i]); }; }); } } const_iterator begin() const { return const_iterator{this, 0}; } const_iterator end() const { return const_iterator{this, size()}; } bool CheckBitmapMatchesValues() const { return bitmap.empty() || bitmap.size() == bitmap::BitmapSize(values.size() + bitmap_bit_offset); } }; template <typename T> bool ArraysAreEquivalent(const DenseArray<T>& lhs, const DenseArray<T>& rhs) { if (lhs.bitmap.empty() && rhs.bitmap.empty()) { return lhs.values == rhs.values; } if (lhs.size() != rhs.size()) return false; for (int64_t i = 0; i < lhs.size(); ++i) { if (lhs[i] != rhs[i]) return false; } return true; } template <class T> using AsDenseArray = DenseArray<strip_optional_t<std::decay_t<T>>>; struct AROLLA_API DenseArrayShape { int64_t size; bool operator==(const DenseArrayShape& other) const { return size == other.size; } }; template <typename T> class DenseArrayBuilder { public: using base_type = T; explicit DenseArrayBuilder(int64_t size, RawBufferFactory* factory = GetHeapBufferFactory()) : values_bldr_(size, factory), bitmap_bldr_(bitmap::BitmapSize(size), factory) { bitmap_ = bitmap_bldr_.GetMutableSpan().begin(); std::memset(bitmap_, 0, bitmap_bldr_.GetMutableSpan().size() * sizeof(bitmap::Word)); } template <typename ValueT> void Set(int64_t id, const ValueT& v) { if constexpr (std::is_same_v<ValueT, std::nullopt_t>) { return; } else if constexpr (is_optional_v<ValueT>) { if (!v.present) return; values_bldr_.Set(id, v.value); } else if constexpr (meta::is_wrapped_with_v<std::optional, ValueT>) { if (!v) return; if constexpr (!std::is_same_v<T, Unit>) { values_bldr_.Set(id, *v); } } else { values_bldr_.Set(id, v); } SetBit(bitmap_, id); } template <typename ValueT> void SetNConst(int64_t id, int64_t count, const ValueT& v) { if constexpr (std::is_same_v<ValueT, std::nullopt_t>) { return; } else if constexpr (is_optional_v<ValueT>) { if (!v.present) return; values_bldr_.SetNConst(id, count, v.value); } else if constexpr (meta::is_wrapped_with_v<std::optional, ValueT>) { if (!v) return; if constexpr (!std::is_same_v<T, Unit>) { values_bldr_.SetNConst(id, count, *v); } } else { values_bldr_.SetNConst(id, count, v); } SetBitsInRange(bitmap_, id, id + count); } template <typename ValueT> void Add(int64_t id, const ValueT& v) { Set(id, v); } DenseArray<T> Build() && { return {std::move(values_bldr_).Build(), std::move(bitmap_bldr_).Build()}; } DenseArray<T> Build(int64_t size) && { return {std::move(values_bldr_).Build(size), std::move(bitmap_bldr_).Build(bitmap::BitmapSize(size))}; } private: typename Buffer<T>::Builder values_bldr_; bitmap::Bitmap::Builder bitmap_bldr_; bitmap::Word* bitmap_; }; template <typename T> DenseArray<T> CreateDenseArray( absl::Span<const OptionalValue<T>> data, RawBufferFactory* factory = GetHeapBufferFactory()) { typename Buffer<T>::Builder values_builder(data.size(), factory); auto values_inserter = values_builder.GetInserter(); bitmap::Builder bitmap_builder(data.size(), factory); bitmap_builder.AddForEach(data, [&](OptionalValue<T> v) { values_inserter.Add(v.value); return v.present; }); return {std::move(values_builder).Build(), std::move(bitmap_builder).Build()}; } template <typename DestType, class InputIt> DenseArray<DestType> CreateDenseArray( InputIt start, InputIt end, RawBufferFactory* factory = GetHeapBufferFactory()) { static_assert( std::is_same_v<typename InputIt::value_type, std::optional<typename InputIt::value_type::value_type>>, "InputIt should be iterator to container of std::optional of some " "type."); static_assert( std::is_same_v<DestType, Unit> || std::is_constructible_v<DestType, typename InputIt::value_type::value_type>, "Source type is not convertible to destination type."); auto size = std::distance(start, end); bitmap::Builder bitmap_builder(size, factory); typename Buffer<DestType>::Builder values_builder(size, factory); bitmap_builder.AddForEach( start, end, [inserter = values_builder.GetInserter()](const auto& v) mutable { if (v.has_value()) { if constexpr (std::is_same_v<DestType, Unit>) { inserter.Add(kUnit); } else { inserter.Add(static_cast<view_type_t<DestType>>(*v)); } } else { inserter.SkipN(1); } return v.has_value(); }); return DenseArray<DestType>{std::move(values_builder).Build(), std::move(bitmap_builder).Build()}; } template <typename T, typename InputIt> DenseArray<T> CreateFullDenseArray( InputIt start, InputIt end, RawBufferFactory* factory = GetHeapBufferFactory()) { return {Buffer<T>::Create(start, end, factory), Buffer<bitmap::Word>()}; } template <typename T> DenseArray<T> CreateFullDenseArray( std::initializer_list<T> data, RawBufferFactory* factory = GetHeapBufferFactory()) { return CreateFullDenseArray<T>(data.begin(), data.end(), factory); } template <typename T> DenseArray<T> CreateFullDenseArray( const std::vector<T>& data, RawBufferFactory* factory = GetHeapBufferFactory()) { return CreateFullDenseArray<T>(data.begin(), data.end(), factory); } template <typename T> DenseArray<T> CreateFullDenseArray(std::vector<T>&& data, RawBufferFactory* = GetHeapBufferFactory()) { return {Buffer<T>::Create(std::move(data)), Buffer<bitmap::Word>()}; } template <typename T> DenseArray<T> CreateConstDenseArray( int64_t size, view_type_t<T> value, RawBufferFactory* buf_factory = GetHeapBufferFactory()) { typename Buffer<T>::Builder values_builder(size, buf_factory); values_builder.SetNConst(0, size, value); return DenseArray<T>{std::move(values_builder).Build()}; } template <typename T> DenseArray<T> CreateEmptyDenseArray( int64_t size, RawBufferFactory* buf_factory = GetHeapBufferFactory()) { return {Buffer<T>::CreateUninitialized(size, buf_factory), bitmap::CreateEmptyBitmap(size, buf_factory)}; } AROLLA_DECLARE_FINGERPRINT_HASHER_TRAITS(DenseArrayShape); template <typename T> struct FingerprintHasherTraits<DenseArray<T>> { void operator()(FingerprintHasher* hasher, const DenseArray<T>& arg) const { hasher->Combine(arg.size()); for (int64_t i = 0; i < arg.size(); ++i) { hasher->Combine(arg[i]); } } }; template <typename T> struct ArenaTraits<DenseArray<T>> { static DenseArray<T> MakeOwned(DenseArray<T>&& v, RawBufferFactory* buf_factory) { return v.MakeOwned(buf_factory); } }; } #endif #include "arolla/dense_array/dense_array.h" #include "arolla/util/fingerprint.h" namespace arolla { void FingerprintHasherTraits<DenseArrayShape>::operator()( FingerprintHasher* hasher, const DenseArrayShape& value) const { hasher->Combine(value.size); } }
#include "arolla/dense_array/dense_array.h" #include <cstdint> #include <optional> #include <string> #include <type_traits> #include <utility> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/strings/string_view.h" #include "arolla/memory/buffer.h" #include "arolla/memory/optional_value.h" #include "arolla/memory/raw_buffer_factory.h" #include "arolla/util/bytes.h" #include "arolla/util/text.h" #include "arolla/util/unit.h" namespace arolla { namespace { using ::testing::ElementsAre; using ::testing::ElementsAreArray; TEST(DenseArrayTest, BaseType) { static_assert(std::is_same_v<int, DenseArray<int>::base_type>); static_assert(std::is_same_v<float, DenseArray<float>::base_type>); } struct TryCompileAssignment { template <typename T> auto operator()(T v) -> decltype(v[0] = std::nullopt) { return v[0]; } }; struct TryCompileMutation { template <typename A, typename V> auto operator()(A a, V v) -> decltype(a[0].value = V()) { return a[0].value; } }; static_assert(!std::is_invocable_v<TryCompileAssignment, DenseArray<int>>); static_assert(!std::is_invocable_v<TryCompileMutation, DenseArray<Text>, absl::string_view>); TEST(DenseArrayTest, Builder) { DenseArrayBuilder<float> builder(5); EXPECT_TRUE((std::is_same_v<DenseArrayBuilder<float>::base_type, float>)); builder.Set(1, 3.0); builder.Set(2, std::optional<float>()); builder.Set(3, OptionalValue<float>(2.0)); builder.Set(4, std::nullopt); DenseArray<float> res = std::move(builder).Build(); EXPECT_THAT(res, ElementsAre(std::nullopt, 3.0, std::nullopt, 2.0, std::nullopt)); } TEST(DenseArrayTest, BuilderResizing) { DenseArrayBuilder<float> builder(10); builder.Set(1, 3.0); builder.Set(2, std::optional<float>()); builder.Set(3, OptionalValue<float>(2.0)); builder.Set(4, std::nullopt); DenseArray<float> res = std::move(builder).Build(5); EXPECT_THAT(res, ElementsAre(std::nullopt, 3.0, std::nullopt, 2.0, std::nullopt)); } TEST(DenseArrayTest, ForEach) { auto arr = CreateDenseArray<int>({2, 3, std::nullopt, 7}); int64_t expected_id = 0; arr.ForEach([&](int64_t id, bool present, int v) { EXPECT_EQ(id, expected_id); EXPECT_EQ((OptionalValue<int>{present, v}), arr[id]); EXPECT_EQ(present, arr.present(id)); if (present) { EXPECT_EQ(v, arr.values[id]); } expected_id++; }); EXPECT_EQ(expected_id, arr.size()); } TEST(DenseArrayTest, ForEachPresent) { auto arr = CreateDenseArray<int>({2, 3, std::nullopt, 7}); std::vector<int64_t> ids; std::vector<int> values; arr.ForEachPresent([&](int64_t id, int v) { ids.push_back(id); values.push_back(v); }); EXPECT_THAT(ids, ElementsAre(0, 1, 3)); EXPECT_THAT(values, ElementsAre(2, 3, 7)); } TEST(DenseArrayTest, ForEachByGroups) { constexpr int size = 100; auto gen_fn = [](int i) { return OptionalValue<int>{i % 2 == 1, i * 2}; }; DenseArrayBuilder<int> bldr(size); for (int i = 0; i < size; ++i) bldr.Set(i, gen_fn(i)); DenseArray<int> arr = std::move(bldr).Build(); int64_t expected_id = 0; int64_t expected_offset = 0; arr.ForEachByGroups([&](int64_t offset) { EXPECT_EQ(offset, expected_offset); expected_offset += 32; return [&, offset](int64_t id, bool present, int v) { EXPECT_EQ(id, expected_id); EXPECT_LT(id - offset, 32); EXPECT_EQ((OptionalValue<int>{present, v}), gen_fn(id)); expected_id++; }; }); EXPECT_EQ(expected_id, arr.size()); } TEST(DenseArrayTest, RangeFor) { auto arr = CreateDenseArray<int>({2, 3, std::nullopt, 7}); std::vector<OptionalValue<int>> res; res.reserve(arr.size()); for (const auto& v : arr) res.push_back(v); EXPECT_EQ(res.size(), arr.size()); for (int64_t i = 0; i < arr.size(); ++i) { EXPECT_EQ(res[i], arr[i]); } } TEST(DenseArrayTest, ElementsAre) { auto test_array = CreateDenseArray<float>({10.0, 20.0, 30.0, std::nullopt}); EXPECT_THAT(test_array, ElementsAre(10.0, 20.0, 30.0, std::nullopt)); } TEST(DenseArrayTest, IsFull) { { DenseArray<float> array; EXPECT_TRUE(array.IsFull()); array.values = CreateBuffer<float>({1, 2, 3}); EXPECT_TRUE(array.IsFull()); array.bitmap = CreateBuffer<uint32_t>({1}); EXPECT_FALSE(array.IsFull()); array.bitmap = CreateBuffer<uint32_t>({7}); EXPECT_TRUE(array.IsFull()); } { auto array = CreateDenseArray<float>({10.0, 20.0, 30.0, std::nullopt}); EXPECT_FALSE(array.IsFull()); } { auto array = CreateDenseArray<float>({10.0, 20.0, 30.0}); EXPECT_TRUE(array.IsFull()); } { DenseArray<float> array; array.values = CreateBuffer<float>({1.0, 2.0, 3.0}); array.bitmap = CreateBuffer<uint32_t>({7}); EXPECT_TRUE(array.IsFull()); array.bitmap_bit_offset = 1; EXPECT_FALSE(array.IsFull()); } } TEST(DenseArrayTest, AllMissing) { { DenseArray<float> array; EXPECT_TRUE(array.IsAllMissing()); array.values = CreateBuffer<float>({1, 2, 3}); EXPECT_FALSE(array.IsAllMissing()); array.bitmap = CreateBuffer<uint32_t>({1}); EXPECT_FALSE(array.IsAllMissing()); array.bitmap = CreateBuffer<uint32_t>({0}); EXPECT_TRUE(array.IsAllMissing()); } { auto array = CreateDenseArray<float>({std::nullopt, std::nullopt}); EXPECT_TRUE(array.IsAllMissing()); } { auto array = CreateDenseArray<float>({10.0, 20.0, std::nullopt}); EXPECT_FALSE(array.IsAllMissing()); } { DenseArray<float> array; array.values = CreateBuffer<float>({1.0, 2.0, 3.0}); array.bitmap = CreateBuffer<uint32_t>({5}); EXPECT_FALSE(array.IsAllMissing()); array.bitmap_bit_offset = 3; EXPECT_TRUE(array.IsAllMissing()); } } TEST(DenseArrayTest, AllPresent) { { DenseArray<float> array; EXPECT_TRUE(array.IsAllPresent()); array.values = CreateBuffer<float>({1, 2, 3}); EXPECT_TRUE(array.IsAllPresent()); array.bitmap = CreateBuffer<uint32_t>({1}); EXPECT_FALSE(array.IsAllPresent()); array.bitmap = CreateBuffer<uint32_t>({0}); EXPECT_FALSE(array.IsAllPresent()); array.bitmap = CreateBuffer<uint32_t>({0b111}); EXPECT_TRUE(array.IsAllPresent()); } { auto array = CreateDenseArray<float>({1.0f, 2.0f}); EXPECT_TRUE(array.IsAllPresent()); } { auto array = CreateDenseArray<float>({10.0, 20.0, std::nullopt}); EXPECT_FALSE(array.IsAllPresent()); } { DenseArray<float> array; array.values = CreateBuffer<float>({1.0, 2.0, 3.0}); array.bitmap = CreateBuffer<uint32_t>({0b111}); EXPECT_TRUE(array.IsAllPresent()); array.bitmap_bit_offset = 1; EXPECT_FALSE(array.IsAllPresent()); } } TEST(DenseArrayTest, PresentCount) { { DenseArray<float> array; EXPECT_EQ(array.PresentCount(), 0); array.values = CreateBuffer<float>({1, 2, 3}); EXPECT_EQ(array.PresentCount(), 3); array.bitmap = CreateBuffer<uint32_t>({1}); EXPECT_EQ(array.PresentCount(), 1); array.bitmap = CreateBuffer<uint32_t>({4}); EXPECT_EQ(array.PresentCount(), 1); array.bitmap = CreateBuffer<uint32_t>({5}); EXPECT_EQ(array.PresentCount(), 2); array.bitmap = CreateBuffer<uint32_t>({3}); EXPECT_EQ(array.PresentCount(), 2); array.bitmap = CreateBuffer<uint32_t>({7}); EXPECT_EQ(array.PresentCount(), 3); } { auto array = CreateDenseArray<float>({10.0, 20.0, 30.0, std::nullopt}); EXPECT_EQ(array.PresentCount(), 3); } { auto array = CreateDenseArray<float>({10.0, 20.0, 30.0}); EXPECT_EQ(array.PresentCount(), 3); } { DenseArray<float> array; array.values = CreateBuffer<float>({1.0, 2.0, 3.0}); array.bitmap = CreateBuffer<uint32_t>({7}); EXPECT_EQ(array.PresentCount(), 3); array.bitmap_bit_offset = 1; EXPECT_EQ(array.PresentCount(), 2); } } TEST(DenseArrayTest, MakeOwned) { std::vector<int> values{1, 2, 3, 4, 5}; std::vector<uint32_t> bitmap{0x15}; DenseArray<int> array{Buffer<int>(nullptr, values), Buffer<uint32_t>(nullptr, bitmap)}; EXPECT_FALSE(array.is_owned()); array = ArenaTraits<DenseArray<int>>::MakeOwned(std::move(array), GetHeapBufferFactory()); EXPECT_TRUE(array.is_owned()); EXPECT_THAT(array.values, ElementsAre(1, 2, 3, 4, 5)); EXPECT_THAT(array.bitmap, ElementsAre(0x15)); } TEST(DenseArrayTest, MakeUnowned) { DenseArray<int> arr = CreateDenseArray<int>({1, 2, std::nullopt, 3}); DenseArray<int> arr2 = arr.MakeUnowned(); EXPECT_TRUE(arr.is_owned()); EXPECT_FALSE(arr2.is_owned()); EXPECT_FALSE(arr2.values.is_owner()); EXPECT_FALSE(arr2.bitmap.is_owner()); EXPECT_THAT(arr2, ElementsAre(1, 2, std::nullopt, 3)); } TEST(DenseArrayTest, Slice) { DenseArray<int> full = CreateDenseArray<int>({5, 1, 3, 4, 5}); DenseArray<int> dense = CreateDenseArray<int>({5, 1, {}, {}, 5}); EXPECT_THAT(full.Slice(1, 3), ElementsAre(1, 3, 4)); EXPECT_THAT(dense.Slice(1, 4), ElementsAre(1, std::nullopt, std::nullopt, 5)); EXPECT_THAT(dense.Slice(1, 4).Slice(2, 2), ElementsAre(std::nullopt, 5)); EXPECT_THAT(dense.Slice(3, 0), ElementsAre()); EXPECT_THAT(dense.Slice(0, 3), ElementsAre(5, 1, std::nullopt)); } TEST(DenseArrayTest, ForceNoBitmapBitOffset) { DenseArray<int> with_offset = CreateDenseArray<int>({5, 1, {}, {}, 5}).Slice(1, 4); ASSERT_THAT(with_offset.bitmap_bit_offset, 1); ASSERT_THAT(with_offset, ElementsAre(1, std::nullopt, std::nullopt, 5)); DenseArray<int> without_offset = with_offset.ForceNoBitmapBitOffset(); EXPECT_THAT(without_offset.bitmap_bit_offset, 0); EXPECT_THAT(without_offset, ElementsAre(1, std::nullopt, std::nullopt, 5)); } TEST(DenseArrayTest, CreateDenseArray) { { std::vector<std::optional<int>> v{1, std::nullopt, 2, 3, std::nullopt}; auto test_array = CreateDenseArray<int64_t>(v.begin(), v.end()); EXPECT_THAT(test_array, ElementsAre(1, std::nullopt, 2, 3, std::nullopt)); EXPECT_TRUE(test_array.is_owned()); } { std::vector<std::optional<std::string>> v{"Hello", "world", std::nullopt}; auto test_array = CreateDenseArray<Bytes>(v.begin(), v.end()); EXPECT_THAT(test_array, ElementsAre("Hello", "world", std::nullopt)); } { std::vector<std::optional<absl::string_view>> v{"Hello", "world", std::nullopt}; auto test_array = CreateDenseArray<Bytes>(v.begin(), v.end()); EXPECT_THAT(test_array, ElementsAre("Hello", "world", std::nullopt)); } { std::vector<std::optional<bool>> v{false, true, std::nullopt}; auto test_array = CreateDenseArray<Unit>(v.begin(), v.end()); EXPECT_THAT(test_array, ElementsAre(kUnit, kUnit, std::nullopt)); } { UnsafeArenaBufferFactory factory(1000); std::vector<std::optional<int>> v{1, std::nullopt, 2, 3, std::nullopt}; auto test_array = CreateDenseArray<int64_t>(v.begin(), v.end(), &factory); EXPECT_THAT(test_array, ElementsAre(1, std::nullopt, 2, 3, std::nullopt)); EXPECT_FALSE(test_array.is_owned()); } } TEST(DenseArrayTest, CreateFullDenseArray) { { std::vector<int64_t> v{1, 2, 3}; DenseArray<int64_t> test_array = CreateFullDenseArray(v); EXPECT_THAT(test_array, ElementsAre(1, 2, 3)); EXPECT_TRUE(test_array.is_owned()); EXPECT_TRUE(test_array.IsFull()); } { std::vector<int> v{1, 2, 3}; auto test_array = CreateFullDenseArray<int64_t>(v.begin(), v.end()); EXPECT_THAT(test_array, ElementsAre(1, 2, 3)); EXPECT_TRUE(test_array.is_owned()); EXPECT_TRUE(test_array.IsFull()); } { std::vector<std::string> v{"Hello", "world"}; auto test_array = CreateFullDenseArray<Bytes>(v.begin(), v.end()); EXPECT_THAT(test_array, ElementsAre("Hello", "world")); EXPECT_TRUE(test_array.IsFull()); } { std::vector<absl::string_view> v{"Hello", "world"}; auto test_array = CreateFullDenseArray<Bytes>(v.begin(), v.end()); EXPECT_THAT(test_array, ElementsAre("Hello", "world")); EXPECT_TRUE(test_array.IsFull()); } { std::vector<bool> v{false, true}; auto test_array = CreateFullDenseArray<Unit>(v.begin(), v.end()); EXPECT_THAT(test_array, ElementsAre(kUnit, kUnit)); EXPECT_TRUE(test_array.IsFull()); } { UnsafeArenaBufferFactory factory(1000); std::vector<int64_t> v{1, 2, 3}; auto test_array = CreateFullDenseArray<int64_t>(v, &factory); EXPECT_THAT(test_array, ElementsAre(1, 2, 3)); EXPECT_FALSE(test_array.is_owned()); EXPECT_TRUE(test_array.IsFull()); } { std::vector<int64_t> v{1, 2, 3}; const int64_t* data = v.data(); auto test_array = CreateFullDenseArray<int64_t>(std::move(v)); EXPECT_THAT(test_array, ElementsAre(1, 2, 3)); EXPECT_EQ(test_array.values.span().data(), data); EXPECT_TRUE(test_array.is_owned()); EXPECT_TRUE(test_array.IsFull()); } { auto test_array = CreateFullDenseArray({Bytes("Hello"), Bytes("world")}); static_assert(std::is_same_v<decltype(test_array), DenseArray<Bytes>>); EXPECT_THAT(test_array, ElementsAre("Hello", "world")); EXPECT_TRUE(test_array.IsFull()); } } TEST(DenseArrayTest, ArraysAreEquivalent) { { DenseArray<int32_t> array1; DenseArray<int32_t> array2; EXPECT_TRUE(ArraysAreEquivalent(array1, array2)); } { auto array1 = CreateDenseArray<int32_t>({1, 2, std::nullopt}); auto array2 = CreateDenseArray<int32_t>({1, 2, std::nullopt}); EXPECT_TRUE(ArraysAreEquivalent(array1, array2)); } { auto array1 = CreateDenseArray<int32_t>({1, 2, std::nullopt}); auto array2 = CreateDenseArray<int32_t>({1, 3, std::nullopt}); EXPECT_FALSE(ArraysAreEquivalent(array1, array2)); } { auto array1 = CreateDenseArray<int32_t>({1, 2, std::nullopt}); auto array2 = CreateDenseArray<int32_t>({1, 2}); EXPECT_FALSE(ArraysAreEquivalent(array1, array2)); } { auto array1 = CreateDenseArray<int32_t>({1, 2, std::nullopt}); auto array2 = CreateDenseArray<int32_t>({1, 2, 3}); EXPECT_FALSE(ArraysAreEquivalent(array1, array2)); } { DenseArray<int32_t> array1; array1.values = CreateBuffer<int32_t>({1, 2, 3}); array1.bitmap = CreateBuffer<uint32_t>({7}); DenseArray<int32_t> array2; array2.values = CreateBuffer<int32_t>({1, 2, 3}); array2.bitmap = CreateBuffer<uint32_t>({14}); EXPECT_FALSE(ArraysAreEquivalent(array1, array2)); array2.bitmap_bit_offset = 1; EXPECT_TRUE(ArraysAreEquivalent(array1, array2)); } { DenseArray<int32_t> array1; array1.values = CreateBuffer<int32_t>({1, 2, 3}); EXPECT_TRUE(array1.bitmap.empty()); auto array2 = array1; EXPECT_TRUE(ArraysAreEquivalent(array1, array2)); array1.bitmap = CreateBuffer<uint32_t>({6}); EXPECT_FALSE(ArraysAreEquivalent(array1, array2)); array1.bitmap = CreateBuffer<uint32_t>({7}); EXPECT_TRUE(ArraysAreEquivalent(array1, array2)); array2.bitmap = CreateBuffer<uint32_t>({7}); EXPECT_TRUE(ArraysAreEquivalent(array1, array2)); } } template <typename T> class DenseArrayTypedTest : public ::testing::Test { public: typedef T value_type; }; using ArrayTypes = testing::Types<int, float, int64_t, double, uint64_t, Bytes, Text, Unit>; TYPED_TEST_SUITE(DenseArrayTypedTest, ArrayTypes); TYPED_TEST(DenseArrayTypedTest, CreateEmptyDenseArray) { using T = typename TestFixture::value_type; for (int64_t size = 0; size < (1ull << 20); size = size * 2 + 1) { DenseArray<T> test_array = CreateEmptyDenseArray<T>(size); EXPECT_THAT(test_array, ElementsAreArray(std::vector<std::nullopt_t>( size, std::nullopt))); EXPECT_TRUE(test_array.IsAllMissing()); } } } }
2,402
#ifndef AROLLA_DENSE_ARRAY_BITMAP_H_ #define AROLLA_DENSE_ARRAY_BITMAP_H_ #include <algorithm> #include <cstddef> #include <cstdint> #include <cstdlib> #include <cstring> #include <utility> #include "absl/base/attributes.h" #include "absl/base/optimization.h" #include "absl/log/check.h" #include "absl/types/span.h" #include "arolla/memory/buffer.h" #include "arolla/memory/raw_buffer_factory.h" #include "arolla/util/preallocated_buffers.h" namespace arolla::bitmap { using Word = uint32_t; constexpr int kWordBitCount = sizeof(Word) * 8; constexpr Word kFullWord = ~Word(0); using Bitmap = Buffer<Word>; inline int64_t BitmapSize(int64_t bit_count) { return (bit_count + kWordBitCount - 1) / kWordBitCount; } inline Word GetWord(const Bitmap& bitmap, int64_t index) { if (bitmap.size() <= index) { return kFullWord; } else { return bitmap[index]; } } inline Word GetWordWithOffset(const Bitmap& bitmap, int64_t index, int offset) { DCHECK_LT(offset, kWordBitCount); if (bitmap.size() <= index) return kFullWord; Word mask = bitmap[index] >> offset; if (offset == 0 || index + 1 == bitmap.size()) { return mask; } else { return mask | (bitmap[index + 1] << (kWordBitCount - offset)); } } bool AreAllBitsSet(const Word* bitmap, int64_t bitCount); inline bool AreAllBitsUnset(const Word* bitmap, int64_t bitCount) { for (size_t i = 0; i < static_cast<size_t>(bitCount) / kWordBitCount; ++i) { if (*(bitmap++) != 0) return false; } size_t suffixBitCount = static_cast<size_t>(bitCount) % kWordBitCount; return suffixBitCount == 0 || ((*bitmap >> suffixBitCount) << suffixBitCount) == *bitmap; } ABSL_ATTRIBUTE_ALWAYS_INLINE inline void Intersect(const Bitmap& a, const Bitmap& b, absl::Span<Word> result) { DCHECK_EQ(a.size(), b.size()); DCHECK_EQ(a.size(), result.size()); Word* res = result.begin(); const Word* ra = a.begin(); const Word* rb = b.begin(); for (int64_t i = 0; i < a.size(); ++i) { res[i] = ra[i] & rb[i]; } } ABSL_ATTRIBUTE_ALWAYS_INLINE inline void Intersect(const Bitmap& a, const Bitmap& b, int bit_offset_a, int bit_offset_b, absl::Span<Word> result) { DCHECK_EQ(std::min(a.size(), b.size()), result.size()); if (bit_offset_a == bit_offset_b) { Intersect(a, b, result); } else { Word* res = result.begin(); const Word* first = a.begin(); const Word* second = b.begin(); int64_t size1 = a.size(); int64_t size2 = b.size(); if (bit_offset_a > bit_offset_b) { first = b.begin(); second = a.begin(); size1 = b.size(); size2 = a.size(); } const int offset = std::abs(bit_offset_b - bit_offset_a); for (int64_t i = 0; i < std::min(size1, size2 - 1); ++i) { Word second_shifted = (second[i] >> offset) | (second[i + 1] << (kWordBitCount - offset)); res[i] = first[i] & second_shifted; } if (size2 > 0 && size2 - 1 < size1) { res[size2 - 1] = first[size2 - 1] & (second[size2 - 1] >> offset); } } } inline bool GetBit(Word word, int bit) { return word & (Word(1) << bit); } inline bool GetBit(const Word* bitmap, int64_t bit_index) { Word word = bitmap[bit_index / kWordBitCount]; int bit = bit_index & (kWordBitCount - 1); return GetBit(word, bit); } inline bool GetBit(const Bitmap& bitmap, int64_t bit_index) { DCHECK_GE(bit_index, 0); DCHECK(bitmap.empty() || bit_index / kWordBitCount < bitmap.size()); if (bitmap.empty()) return true; Word word = bitmap[bit_index / kWordBitCount]; int bit = bit_index & (kWordBitCount - 1); return GetBit(word, bit); } inline void SetBit(Word* bitmap, int64_t bit_index) { bitmap[static_cast<size_t>(bit_index) / kWordBitCount] |= Word{1} << (bit_index & (kWordBitCount - 1)); } inline void UnsetBit(Word* bitmap, int64_t bit_index) { bitmap[static_cast<size_t>(bit_index) / kWordBitCount] &= ~(Word{1} << (bit_index & (kWordBitCount - 1))); } template <class Fn> void IterateWord(Word word, Fn&& fn, int count = kWordBitCount) { DCHECK_LE(count, kWordBitCount); for (int i = 0; i < count; ++i) { fn(i, GetBit(word, i)); } } template <class Fn> void IterateByGroups(const Word* bitmap, int64_t first_bit, int64_t count, Fn&& init_group_fn) { bitmap += static_cast<size_t>(first_bit) / kWordBitCount; int64_t bit_offset = first_bit & (kWordBitCount - 1); int64_t group_offset = 0; if (bit_offset > 0 && count > 0) { int first_word_size = std::min(count, kWordBitCount - bit_offset); bitmap::IterateWord(*(bitmap++) >> bit_offset, init_group_fn(group_offset), first_word_size); group_offset = first_word_size; } for (; group_offset <= count - kWordBitCount; group_offset += kWordBitCount) { bitmap::IterateWord(*(bitmap++), init_group_fn(group_offset)); } if (group_offset != count) { bitmap::IterateWord(*bitmap, init_group_fn(group_offset), count - group_offset); } } template <class Fn> void Iterate(const Bitmap& bitmap, int64_t first_bit, int64_t count, Fn&& fn) { if (bitmap.empty()) { for (int64_t i = 0; i < count; ++i) fn(true); } else { DCHECK_GE(bitmap.size(), BitmapSize(first_bit + count)); auto wrapped_fn = [&fn](int, bool present) { fn(present); }; IterateByGroups(bitmap.begin(), first_bit, count, [&](int64_t) { return wrapped_fn; }); } } int64_t CountBits(const Bitmap& bitmap, int64_t offset, int64_t size); using RawBuilder = Buffer<Word>::Builder; inline Bitmap CreateEmptyBitmap( int64_t bit_count, RawBufferFactory* buf_factory = GetHeapBufferFactory()) { if (bit_count <= kZeroInitializedBufferSize * 8) { return Buffer<Word>( nullptr, absl::Span<const Word>( static_cast<const Word*>(GetZeroInitializedBuffer()), BitmapSize(bit_count))); } int64_t bitmap_size = BitmapSize(bit_count); RawBuilder bldr(bitmap_size, buf_factory); std::memset(bldr.GetMutableSpan().data(), 0, bitmap_size * sizeof(Word)); return std::move(bldr).Build(); } class AlmostFullBuilder { public: explicit AlmostFullBuilder( int64_t bit_count, RawBufferFactory* buf_factory = GetHeapBufferFactory()) : bit_count_(bit_count), factory_(buf_factory) {} void AddMissed(int64_t id) { DCHECK_GE(id, 0); DCHECK_LT(id, bit_count_); if (ABSL_PREDICT_FALSE(!bitmap_)) { CreateFullBitmap(); } UnsetBit(bitmap_, id); } Bitmap Build() && { return std::move(bitmap_buffer_); } Bitmap Build(int64_t size) && { return std::move(bitmap_buffer_).Slice(0, BitmapSize(size)); } private: void CreateFullBitmap(); int64_t bit_count_; RawBufferFactory* factory_; Word* bitmap_ = nullptr; Bitmap bitmap_buffer_; }; class Builder { public: explicit Builder(int64_t bit_count, RawBufferFactory* buf_factory = GetHeapBufferFactory()) : bldr_(BitmapSize(bit_count), buf_factory) {} template <typename Fn> void AddByGroups(int64_t count, Fn&& init_group_fn) { DCHECK_LE(current_bit_ + count, bldr_.GetMutableSpan().size() * kWordBitCount); int bit_offset = current_bit_ & (kWordBitCount - 1); int64_t offset = 0; if (bit_offset == 0) { Word* data = bldr_.GetMutableSpan().begin() + (current_bit_ / kWordBitCount); for (; offset + kWordBitCount <= count; offset += kWordBitCount) { *(data++) = Group(kWordBitCount, init_group_fn(offset)); } if (offset < count) { *data = Group(count - offset, init_group_fn(offset)); } } else { absl::Span<Word> data = bldr_.GetMutableSpan(); auto add_word_fn = [&](Word w) { size_t word_id = (current_bit_ + offset) / kWordBitCount; data[word_id] |= w << bit_offset; if (word_id + 1 < data.size()) { data[word_id + 1] = w >> (kWordBitCount - bit_offset); } }; for (; offset + kWordBitCount <= count; offset += kWordBitCount) { add_word_fn(Group(kWordBitCount, init_group_fn(offset))); } if (offset < count) { add_word_fn(Group(count - offset, init_group_fn(offset))); } } current_bit_ += count; } template <typename Container, typename Fn> void AddForEach(const Container& c, Fn&& fn) { AddByGroups(std::size(c), [&](int64_t offset) { auto g = std::begin(c) + offset; return [&fn, g](int i) { return fn(g[i]); }; }); } template <typename Iterator, typename Fn> void AddForEach(Iterator from, Iterator to, Fn&& fn) { AddByGroups(to - from, [&](int64_t offset) { auto g = from + offset; return [&fn, g](int i) { return fn(g[i]); }; }); } Bitmap Build() && { if (all_present_) return Bitmap(); return std::move(bldr_).Build(); } private: template <typename Fn> Word Group(int count, Fn&& fn) { Word res = 0; for (int i = 0; i < count; ++i) { if (fn(i)) { res |= (1 << i); } else { all_present_ = false; } } return res; } Bitmap::Builder bldr_; uint64_t current_bit_ = 0; bool all_present_ = true; }; } #endif #include "arolla/dense_array/bitmap.h" #include <algorithm> #include <cstdint> #include <cstring> #include <utility> #include "absl/log/check.h" #include "arolla/util/bits.h" namespace arolla::bitmap { bool AreAllBitsSet(const Word* bitmap, int64_t bitCount) { while (bitCount >= kWordBitCount) { if (*bitmap != kFullWord) return false; bitmap++; bitCount -= kWordBitCount; } if (bitCount > 0) { auto mask = kFullWord >> (kWordBitCount - bitCount); return (*bitmap & mask) == mask; } return true; } int64_t CountBits(const Bitmap& bitmap, int64_t offset, int64_t size) { DCHECK_GE(size, 0); const int64_t begin = std::max<int64_t>( 0, std::min<int64_t>(bitmap.size() * kWordBitCount, offset)); const int64_t end = std::max<int64_t>( begin, std::min<int64_t>(bitmap.size() * kWordBitCount, offset + size)); return size - (end - begin) + GetOnesCountInRange(bitmap.span().data(), begin, end); } void AlmostFullBuilder::CreateFullBitmap() { Bitmap::Builder bldr(BitmapSize(bit_count_), factory_); auto span = bldr.GetMutableSpan(); bitmap_ = span.begin(); std::memset(bitmap_, 0xff, span.size() * sizeof(Word)); int64_t last_bits = bit_count_ & (kWordBitCount - 1); if (last_bits != 0) { span.back() &= ((Word{1} << last_bits) - 1); } bitmap_buffer_ = std::move(bldr).Build(); } }
#include "arolla/dense_array/bitmap.h" #include <algorithm> #include <cstdint> #include <memory> #include <utility> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/random/distributions.h" #include "absl/random/random.h" #include "absl/types/span.h" #include "arolla/memory/buffer.h" namespace arolla::bitmap { namespace { TEST(BitmapTest, BitmapSize) { EXPECT_EQ(BitmapSize(0), 0); EXPECT_EQ(BitmapSize(1), 1); EXPECT_EQ(BitmapSize(32), 1); EXPECT_EQ(BitmapSize(33), 2); EXPECT_EQ(BitmapSize(320), 10); EXPECT_EQ(BitmapSize(351), 11); } TEST(BitmapTest, SetBit) { Word bitmap[3] = {0, kFullWord, 0}; SetBit(bitmap, 3); UnsetBit(bitmap, 32); SetBit(bitmap, 64); UnsetBit(bitmap, 65); EXPECT_EQ(bitmap[0], 8); EXPECT_EQ(bitmap[1], kFullWord - 1); EXPECT_EQ(bitmap[2], 1); } TEST(BitmapTest, GetBit) { Word bitmap[3] = {8, kFullWord - 1, 1}; EXPECT_TRUE(GetBit(bitmap, 3)); EXPECT_FALSE(GetBit(bitmap, 32)); EXPECT_TRUE(GetBit(bitmap, 64)); EXPECT_FALSE(GetBit(bitmap, 65)); } TEST(BitmapTest, AreAllBitsSet) { Word bitmap[4] = {kFullWord, kFullWord, 3, kFullWord}; EXPECT_TRUE(AreAllBitsSet(bitmap, 64)); EXPECT_TRUE(AreAllBitsSet(bitmap, 65)); EXPECT_TRUE(AreAllBitsSet(bitmap, 66)); EXPECT_FALSE(AreAllBitsSet(bitmap, 67)); EXPECT_FALSE(AreAllBitsSet(bitmap, 128)); } TEST(BitmapTest, AreAllBitsUnset) { Word bitmap[4] = {0, 0, 12}; EXPECT_TRUE(AreAllBitsUnset(bitmap, 0)); EXPECT_TRUE(AreAllBitsUnset(bitmap, 64)); EXPECT_TRUE(AreAllBitsUnset(bitmap, 65)); EXPECT_TRUE(AreAllBitsUnset(bitmap, 66)); EXPECT_FALSE(AreAllBitsUnset(bitmap, 67)); EXPECT_FALSE(AreAllBitsUnset(bitmap, 95)); EXPECT_FALSE(AreAllBitsUnset(bitmap, 96)); } TEST(BitmapTest, Empty) { Bitmap bitmap; EXPECT_EQ(GetWord(bitmap, 0), kFullWord); EXPECT_EQ(GetWord(bitmap, 13), kFullWord); EXPECT_EQ(GetWordWithOffset(bitmap, 0, 7), kFullWord); EXPECT_EQ(GetWordWithOffset(bitmap, 13, 7), kFullWord); EXPECT_TRUE(GetBit(bitmap, 0)); EXPECT_TRUE(GetBit(bitmap, 1)); EXPECT_TRUE(GetBit(bitmap, 999)); int64_t count = 0; auto check_fn = [&](bool v) { count++; EXPECT_TRUE(v); }; Iterate(bitmap, 0, 0, check_fn); EXPECT_EQ(count, 0); Iterate(bitmap, 2, 17, check_fn); EXPECT_EQ(count, 17); count = 0; Iterate(bitmap, 99, 138, check_fn); EXPECT_EQ(count, 138); } TEST(BitmapTest, CreateEmpty) { for (int64_t size = 0; size < (1 << 20); size = (size + 1) * 2) { Bitmap bitmap = CreateEmptyBitmap(size); for (int64_t i = 0; i < BitmapSize(size); ++i) { EXPECT_EQ(GetWord(bitmap, i), 0); } for (int64_t i = 0; i < size; ++i) { EXPECT_FALSE(GetBit(bitmap, i)); } EXPECT_TRUE(AreAllBitsUnset(bitmap.span().data(), size)); } } TEST(BitmapTest, Iterate) { Bitmap bitmap = CreateBuffer<Word>({0xffff4321, 0x0, 0xf0f0f0f0, 0xffffffff}); EXPECT_EQ(GetWord(bitmap, 0), 0xffff4321); EXPECT_EQ(GetWord(bitmap, 2), 0xf0f0f0f0); EXPECT_EQ(GetWordWithOffset(bitmap, 0, 0), 0xffff4321); EXPECT_EQ(GetWordWithOffset(bitmap, 0, 31), 0x1); EXPECT_EQ(GetWordWithOffset(bitmap, 2, 8), 0xfff0f0f0); EXPECT_TRUE(GetBit(bitmap, 0)); EXPECT_FALSE(GetBit(bitmap, 1)); EXPECT_TRUE(GetBit(bitmap, 31)); EXPECT_FALSE(GetBit(bitmap, 32)); EXPECT_FALSE(GetBit(bitmap, 67)); EXPECT_TRUE(GetBit(bitmap, 68)); EXPECT_TRUE(GetBit(bitmap, 127)); int64_t bit = 0; std::unique_ptr<int> x; auto check_fn = [&, x(std::move(x))](bool v) { EXPECT_EQ(v, GetBit(bitmap, bit)); bit++; }; Iterate(bitmap, 0, 0, check_fn); EXPECT_EQ(bit, 0); Iterate(bitmap, 0, 17, check_fn); EXPECT_EQ(bit, 17); Iterate(bitmap, 17, 32, check_fn); EXPECT_EQ(bit, 17 + 32); Iterate(bitmap, 17 + 32, 69, check_fn); EXPECT_EQ(bit, 17 + 32 + 69); } TEST(BitmapTest, Intersect) { Bitmap b1 = CreateBuffer<Word>({0xffff4321, 0x0, 0xf0f0f0f0, 0xffffffff}); Bitmap b2 = CreateBuffer<Word>({0x43214321, 0x1, 0x0f0ff0f0, 0xffffffff}); Bitmap b3 = CreateBuffer<Word>({0x43214321, 0x1, 0x0f0ff0f0, 0xffffffff, 0x8}); { std::vector<Word> res(4); Intersect(b1, b2, {res.data(), res.size()}); EXPECT_THAT(res, testing::ElementsAre(0x43214321, 0x0, 0xf0f0, 0xffffffff)); } { std::vector<Word> res(4); Intersect(b1, b2, 5, 5, {res.data(), res.size()}); EXPECT_THAT(res, testing::ElementsAre(0x43214321, 0x0, 0xf0f0, 0xffffffff)); } { std::vector<Word> res(4); Intersect(b1, b3, 4, 8, {res.data(), res.size()}); EXPECT_THAT(res, testing::ElementsAre(0x14320020, 0x0, 0xf0f0f000, 0x8fffffff)); } { std::vector<Word> res(4); Intersect(b3, b1, 8, 4, {res.data(), res.size()}); EXPECT_THAT(res, testing::ElementsAre(0x14320020, 0x0, 0xf0f0f000, 0x8fffffff)); } } TEST(CountBits, Trivial) { const std::vector<uint32_t> bitmap = {1664460009U, 1830791933U, 2649253042U, 1615775603U}; const auto bit = [&](int64_t i) { return (bitmap[i / 32] >> (i % 32)) & 1; }; const auto bitmap_buffer = CreateBuffer(bitmap); const int64_t n = 32 * bitmap.size(); for (int64_t i = 0; i <= n; ++i) { int64_t count = 0; for (int64_t j = i; j < n; ++j) { ASSERT_EQ(count, CountBits(bitmap_buffer, i, j - i)) << i << ' ' << j; count += bit(j); } ASSERT_EQ(count, CountBits(bitmap_buffer, i, n - i)); } } TEST(CountBits, OutOfRange) { const auto bitmap_buffer = CreateBuffer({0xffff0000}); ASSERT_EQ(CountBits(bitmap_buffer, -30, 24), 24); ASSERT_EQ(CountBits(bitmap_buffer, -20, 24), 20); ASSERT_EQ(CountBits(bitmap_buffer, -10, 24), 10); ASSERT_EQ(CountBits(bitmap_buffer, -5, 24), 8); ASSERT_EQ(CountBits(bitmap_buffer, 0, 24), 8); ASSERT_EQ(CountBits(bitmap_buffer, 5, 24), 13); ASSERT_EQ(CountBits(bitmap_buffer, 10, 24), 18); ASSERT_EQ(CountBits(bitmap_buffer, 20, 24), 24); ASSERT_EQ(CountBits(bitmap_buffer, 30, 24), 24); ASSERT_EQ(CountBits(bitmap_buffer, 40, 24), 24); } TEST(BuilderTest, AddByGroups) { int64_t size = 16384; absl::BitGen gen; std::vector<bool> bits; Builder bldr(size); auto add_fn = [&](int) { bool v = absl::Bernoulli(gen, 0.5); bits.push_back(v); return v; }; for (int64_t remaining_count = size; remaining_count > 0;) { int64_t count = std::min(remaining_count, absl::Uniform<int64_t>(gen, 0, 256)); remaining_count -= count; bldr.AddByGroups(count, [&](int64_t) { return add_fn; }); } Bitmap bitmap = std::move(bldr).Build(); EXPECT_EQ(size, bits.size()); for (int64_t i = 0; i < bits.size(); ++i) { EXPECT_EQ(GetBit(bitmap, i), bits[i]); } } TEST(BuilderTest, AddForEachNeverCopyAFunction) { int cont[1]{0}; { std::unique_ptr<int> x; Builder b(1); b.AddForEach(cont, [x(std::move(x))](int) { return true; }); } { std::unique_ptr<int> x; Builder b(1); const auto fn = [x(std::move(x))](int) { return true; }; b.AddForEach(cont, fn); } { std::unique_ptr<int> x; int cnt = 0; Builder b(1); auto fn = [&cnt, x(std::move(x))](int) mutable { ++cnt; return true; }; b.AddForEach(cont, fn); EXPECT_EQ(cnt, 1); } } #define TEST_BITS(bitmap_expr, fn, N) \ Bitmap bitmap = bitmap_expr; \ ASSERT_EQ(bitmap.size(), BitmapSize(N)); \ for (int i = 0; i < (N); ++i) { \ ASSERT_EQ(GetBit(bitmap, i), fn(i)) << i << " of " << N; \ } TEST(BuilderTest, AddForEachSingle) { constexpr int kMaxN = 1000; std::vector<int> v(kMaxN); for (int n = 0; n < kMaxN; ++n) { v[n] = n; } auto is_5_divisible = [](int x) { return x % 5 == 0; }; for (int n = 2; n < kMaxN; ++n) { { Builder b(n); b.AddForEach(std::vector(v.begin(), v.begin() + n), is_5_divisible); TEST_BITS(std::move(b).Build(), is_5_divisible, n); } { Builder b(n); b.AddForEach(absl::MakeConstSpan(v.data(), n), is_5_divisible); TEST_BITS(std::move(b).Build(), is_5_divisible, n); } } } TEST(BuilderTest, AddForEachMany) { constexpr int kMaxN = 4027; std::vector<int> v(kMaxN); for (int n = 0; n < kMaxN; ++n) { v[n] = n; } auto is_5_divisible = [](int x) { return x % 5 == 0; }; Builder b(kMaxN); int beg = 0; for (int cnt : {2, 3, 4, 6, 9, 13, 18, 27, 47, 94, 188, 376, 752, kMaxN}) { b.AddForEach( absl::MakeConstSpan(v.data() + beg, std::min(cnt, kMaxN - beg)), is_5_divisible); beg += cnt; } TEST_BITS(std::move(b).Build(), is_5_divisible, kMaxN); } TEST(BuilderTest, Full) { Builder builder(10); builder.AddForEach(std::vector<int>(10), [](int) { return true; }); EXPECT_TRUE(std::move(builder).Build().empty()); } TEST(AlmostFullBuilderTest, Full) { AlmostFullBuilder builder(555); EXPECT_TRUE(std::move(builder).Build().empty()); } TEST(AlmostFullBuilderTest, Empty) { int64_t size = 555; AlmostFullBuilder builder(size); for (int64_t i = 0; i < size; ++i) { builder.AddMissed(i); } auto bitmap = std::move(builder).Build(); ASSERT_EQ(bitmap.size(), BitmapSize(size)); EXPECT_TRUE(AreAllBitsUnset(bitmap.span().data(), size)); for (int64_t i = 0; i < size; ++i) { EXPECT_EQ(GetBit(bitmap, i), 0); } } TEST(AlmostFullBuilderTest, NotFull) { int64_t size = 555; AlmostFullBuilder builder(size); for (int64_t i = 0; i < size; ++i) { if (i % 5 == 1) builder.AddMissed(i); } auto bitmap = std::move(builder).Build(); EXPECT_EQ(bitmap.size(), BitmapSize(size)); for (int64_t i = 0; i < size; ++i) { EXPECT_EQ(GetBit(bitmap, i), i % 5 != 1); } } TEST(AlmostFullBuilderTest, EmptyThanFull) { int64_t size = 155; for (int64_t split_point = 1; split_point < size; ++split_point) { AlmostFullBuilder builder(size); for (int64_t i = 0; i < split_point; ++i) { builder.AddMissed(i); } auto bitmap = std::move(builder).Build(); EXPECT_EQ(bitmap.size(), BitmapSize(size)); for (int64_t i = 0; i < size; ++i) { ASSERT_EQ(GetBit(bitmap, i), i >= split_point) << i << " " << split_point; } } } TEST(AlmostFullBuilderTest, EmptyConsequentlyAtStartAndAFewMissed) { int64_t size = 155; int64_t split_point = 71; AlmostFullBuilder builder(size); for (int64_t i = 0; i < split_point; ++i) { builder.AddMissed(i); } builder.AddMissed(93); builder.AddMissed(107); auto bitmap = std::move(builder).Build(); EXPECT_EQ(bitmap.size(), BitmapSize(size)); for (int64_t i = 0; i < size; ++i) { bool present = (i >= split_point) && (i != 93) && (i != 107); ASSERT_EQ(GetBit(bitmap, i), present) << i; } } } }
2,403
#ifndef AROLLA_EXPR_QTYPE_UTILS_H_ #define AROLLA_EXPR_QTYPE_UTILS_H_ #include <optional> #include <string> #include <vector> #include "absl/base/nullability.h" #include "absl/container/flat_hash_map.h" #include "absl/functional/function_ref.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "arolla/expr/expr_attributes.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_visitor.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/typed_value.h" namespace arolla::expr { absl::StatusOr<absl::flat_hash_map<std::string, QTypePtr>> CollectLeafQTypes( ExprNodePtr expr); absl::StatusOr<absl::flat_hash_map<std::string, QTypePtr>> CollectLeafQTypesOnPostOrder(const PostOrder& post_order); absl::StatusOr<ExprNodePtr> PopulateQTypes( ExprNodePtr expr, absl::FunctionRef<absl::Nullable<const QType*>(absl::string_view)> get_qtype, bool allow_incomplete_type_information = false); absl::StatusOr<ExprNodePtr> PopulateQTypes( ExprNodePtr expr, const absl::flat_hash_map<std::string, QTypePtr>& leaf_qtypes, bool allow_incomplete_type_information = false); std::vector<const QType*> GetExprQTypes(absl::Span<const ExprNodePtr> nodes); std::vector<std::optional<TypedValue>> GetExprQValues( absl::Span<const ExprNodePtr> nodes); bool IsDefaultEdgeArg(const ExprNodePtr& arg); absl::StatusOr<bool> IsGroupScalarEdge(const ExprNodePtr& edge); std::vector<ExprAttributes> GetExprAttrs(absl::Span<const ExprNodePtr> nodes); std::vector<const QType* > GetAttrQTypes( absl::Span<const ExprAttributes> attrs); std::vector<const QType* > GetValueQTypes( absl::Span<const QTypePtr> qtypes); bool HasAllAttrQTypes(absl::Span<const ExprAttributes> attrs); } #endif #include "arolla/expr/qtype_utils.h" #include <cstddef> #include <optional> #include <set> #include <string> #include <utility> #include <vector> #include "absl/base/nullability.h" #include "absl/container/flat_hash_map.h" #include "absl/functional/function_ref.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "absl/strings/str_join.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "arolla/expr/annotation_expr_operators.h" #include "arolla/expr/annotation_utils.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_attributes.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_visitor.h" #include "arolla/qtype/array_like/array_like_qtype.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/shape_qtype.h" #include "arolla/qtype/typed_value.h" #include "arolla/util/unit.h" #include "arolla/util/status_macros_backport.h" namespace arolla::expr { absl::StatusOr<absl::flat_hash_map<std::string, QTypePtr>> CollectLeafQTypes( ExprNodePtr expr) { return CollectLeafQTypesOnPostOrder(PostOrder(expr)); } absl::StatusOr<absl::flat_hash_map<std::string, QTypePtr>> CollectLeafQTypesOnPostOrder(const PostOrder& post_order) { absl::flat_hash_map<std::string, QTypePtr> result; std::vector<absl::string_view> leaf_keys(post_order.nodes_size()); for (size_t i = 0; i < post_order.nodes_size(); ++i) { const auto node = post_order.node(i); if (node->is_leaf()) { leaf_keys[i] = node->leaf_key(); continue; } const auto node_dep_indices = post_order.dep_indices(i); if (node_dep_indices.empty() || leaf_keys[node_dep_indices[0]].empty()) { continue; } const absl::string_view leaf_key = leaf_keys[node_dep_indices[0]]; ASSIGN_OR_RETURN(bool is_annotation, IsAnnotation(node)); if (is_annotation) { leaf_keys[i] = leaf_key; } auto* qtype = ReadQTypeAnnotation(node); if (qtype == nullptr) { continue; } if (auto it = result.try_emplace(leaf_key, qtype).first; it->second != qtype) { return absl::InvalidArgumentError( absl::StrFormat("inconsistent qtype annotations for L.%s: %s != %s", leaf_key, qtype->name(), it->second->name())); } } return result; } absl::StatusOr<ExprNodePtr> PopulateQTypes( ExprNodePtr expr, absl::FunctionRef<absl::Nullable<const QType*>(absl::string_view)> get_qtype, bool allow_incomplete_type_information) { const auto post_order = PostOrder(expr); ASSIGN_OR_RETURN(auto expr_leaf_qtypes, CollectLeafQTypesOnPostOrder(post_order)); std::set<absl::string_view> untyped_leaves; ASSIGN_OR_RETURN( ExprNodePtr result, TransformOnPostOrder( post_order, [&](ExprNodePtr node) -> absl::StatusOr<ExprNodePtr> { if (node->is_leaf()) { if (auto qtype = get_qtype(node->leaf_key()); qtype != nullptr) { return CallOp(QTypeAnnotation::Make(), {std::move(node), Literal(qtype)}); } if (auto it = expr_leaf_qtypes.find(node->leaf_key()); it != expr_leaf_qtypes.end()) { return CallOp(QTypeAnnotation::Make(), {std::move(node), Literal(it->second)}); } if (!allow_incomplete_type_information) { untyped_leaves.insert(node->leaf_key()); } return node; } if (IsQTypeAnnotation(node) && !node->node_deps().empty()) { const auto& arg = node->node_deps().front(); if (arg->qtype() != nullptr) { return arg; } } return node; })); if (!untyped_leaves.empty()) { return absl::InvalidArgumentError( absl::StrFormat("QType for the leaves {%s} are missing, which may be " "caused by missing input features", absl::StrJoin(untyped_leaves, ", "))); } return result; } absl::StatusOr<ExprNodePtr> PopulateQTypes( ExprNodePtr expr, const absl::flat_hash_map<std::string, QTypePtr>& leaf_qtypes, bool allow_incomplete_type_information) { return PopulateQTypes( expr, [&](absl::string_view leaf_key) { auto it = leaf_qtypes.find(leaf_key); return it == leaf_qtypes.end() ? nullptr : it->second; }, allow_incomplete_type_information); } const QType* GetExprQType(ExprNodePtr node) { return node->qtype(); } std::vector<const QType*> GetExprQTypes(absl::Span<const ExprNodePtr> nodes) { std::vector<const QType*> qtypes; qtypes.reserve(nodes.size()); for (const auto& dep : nodes) { qtypes.push_back(dep->qtype()); } return qtypes; } std::vector<std::optional<TypedValue>> GetExprQValues( absl::Span<const ExprNodePtr> nodes) { std::vector<std::optional<TypedValue>> result; result.reserve(nodes.size()); for (const auto& dep : nodes) { result.emplace_back(dep->qvalue()); } return result; } namespace { bool IsDefaultEdgeQType(const QTypePtr& arg_qtype) { return arg_qtype == GetQType<Unit>(); } } bool IsDefaultEdgeArg(const ExprNodePtr& arg) { return IsDefaultEdgeQType(arg->qtype()); } absl::StatusOr<bool> IsGroupScalarEdge(const ExprNodePtr& edge) { if (edge == nullptr) { return absl::FailedPreconditionError( "Null node pointer passed to IsGroupScalarEdge."); } auto edge_type = edge->qtype(); ASSIGN_OR_RETURN(auto identified_edge_type, ToEdgeQType(edge_type)); ASSIGN_OR_RETURN(auto shape_type, ToShapeQType(identified_edge_type->parent_shape_qtype())); return shape_type == GetQType<OptionalScalarShape>(); } std::vector<ExprAttributes> GetExprAttrs(absl::Span<const ExprNodePtr> nodes) { std::vector<ExprAttributes> result; result.reserve(nodes.size()); for (const auto& node : nodes) { result.push_back(node->attr()); } return result; } std::vector<const QType*> GetAttrQTypes( absl::Span<const ExprAttributes> attrs) { std::vector<const QType*> result; result.reserve(attrs.size()); for (const auto& attr : attrs) { result.push_back(attr.qtype()); } return result; } std::vector<const QType*> GetValueQTypes(absl::Span<const QTypePtr> qtypes) { std::vector<const QType*> result; result.reserve(qtypes.size()); for (const auto qtype : qtypes) { result.push_back(qtype->value_qtype()); } return result; } bool HasAllAttrQTypes(absl::Span<const ExprAttributes> attrs) { for (const auto& attr : attrs) { if (!attr.qtype()) { return false; } } return true; } }
#include "arolla/expr/qtype_utils.h" #include <cstdint> #include <optional> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "absl/strings/string_view.h" #include "arolla/expr/annotation_expr_operators.h" #include "arolla/expr/basic_expr_operator.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_attributes.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/expr/lambda_expr_operator.h" #include "arolla/expr/testing/testing.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/optional_qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/testing/qtype.h" #include "arolla/qtype/typed_value.h" #include "arolla/util/init_arolla.h" #include "arolla/util/testing/status_matchers_backport.h" namespace arolla::expr { namespace { using ::arolla::testing::EqualsAttr; using ::arolla::testing::EqualsExpr; using ::arolla::testing::IsOk; using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::StatusIs; using ::arolla::testing::TypedValueWith; using ::arolla::testing::WithNameAnnotation; using ::arolla::testing::WithQTypeAnnotation; using ::testing::ElementsAre; using ::testing::Eq; using ::testing::HasSubstr; using ::testing::IsNull; using ::testing::Optional; using ::testing::Pair; using ::testing::UnorderedElementsAre; using Attr = ::arolla::expr::ExprAttributes; class QTypeMetadataTest : public ::testing::Test { void SetUp() override { ASSERT_OK(InitArolla()); } }; TEST_F(QTypeMetadataTest, GetExprQType_LeafWithoutQType) { ExprNodePtr leaf = Leaf("a"); EXPECT_THAT(leaf->qtype(), IsNull()); } TEST_F(QTypeMetadataTest, GetExprQType_LeafWithQType) { ASSERT_OK_AND_ASSIGN(ExprNodePtr leaf_with_qtype, WithQTypeAnnotation(Leaf("a"), GetQType<float>())); EXPECT_EQ(leaf_with_qtype->qtype(), GetQType<float>()); } TEST_F(QTypeMetadataTest, GetExprQType_ArgumentlessOperator) { ASSERT_OK_AND_ASSIGN( auto argumentless_operator, MakeLambdaOperator(ExprOperatorSignature{}, Literal(1.f))); ASSERT_OK_AND_ASSIGN(ExprNodePtr node, BindOp(argumentless_operator, {}, {})); EXPECT_THAT(node->qtype(), GetQType<float>()); } TEST_F(QTypeMetadataTest, GetExprQType) { ExprNodePtr leaf = Leaf("a"); ASSERT_OK_AND_ASSIGN(ExprNodePtr leaf_with_qtype, WithQTypeAnnotation(Leaf("a"), GetQType<float>())); ExprNodePtr literal = Literal<int64_t>(57); EXPECT_THAT(GetExprQTypes({leaf, leaf_with_qtype, literal}), ElementsAre(nullptr, GetQType<float>(), GetQType<int64_t>())); } TEST_F(QTypeMetadataTest, GetExprQValues) { ExprNodePtr literal = Literal<int64_t>(57); ExprNodePtr leaf = Leaf("a"); ASSERT_OK_AND_ASSIGN( auto argumentless_operator, MakeLambdaOperator(ExprOperatorSignature{}, Literal(1.f))); ASSERT_OK_AND_ASSIGN(ExprNodePtr argumentless_node, BindOp(argumentless_operator, {}, {})); EXPECT_THAT( GetExprQValues({literal, leaf, argumentless_node}), ElementsAre(Optional(TypedValueWith<int64_t>(57)), Eq(std::nullopt), Optional(TypedValueWith<float>(1.f)))); } TEST_F(QTypeMetadataTest, CollectLeafQTypes_Basic) { ASSERT_OK_AND_ASSIGN( ExprNodePtr expr, CallOp("test.power", {WithQTypeAnnotation(Leaf("x"), GetQType<float>()), WithQTypeAnnotation(WithNameAnnotation(Leaf("y"), "name"), GetQType<float>())})); EXPECT_THAT(CollectLeafQTypes(expr), IsOkAndHolds(UnorderedElementsAre(Pair("x", GetQType<float>()), Pair("y", GetQType<float>())))); } TEST_F(QTypeMetadataTest, CollectLeafQTypes_Partial) { ASSERT_OK_AND_ASSIGN( ExprNodePtr expr, CallOp("test.power", {WithQTypeAnnotation(Leaf("x"), GetQType<float>()), Leaf("y")})); EXPECT_THAT(CollectLeafQTypes(expr), IsOkAndHolds(UnorderedElementsAre(Pair("x", GetQType<float>())))); } TEST_F(QTypeMetadataTest, CollectLeafQTypes_Duplicate) { ASSERT_OK_AND_ASSIGN( ExprNodePtr expr, CallOp("test.power", {WithQTypeAnnotation(Leaf("x"), GetQType<float>()), WithQTypeAnnotation(WithNameAnnotation(Leaf("x"), "x"), GetQType<float>())})); EXPECT_THAT(CollectLeafQTypes(expr), IsOkAndHolds(UnorderedElementsAre(Pair("x", GetQType<float>())))); } TEST_F(QTypeMetadataTest, CollectLeafQTypes_Inconsistent) { ASSERT_OK_AND_ASSIGN( ExprNodePtr expr, CallOp("test.power", {WithQTypeAnnotation(Leaf("x"), GetQType<float>()), WithQTypeAnnotation(Leaf("x"), GetQType<int32_t>())})); EXPECT_THAT( CollectLeafQTypes(expr), StatusIs(absl::StatusCode::kInvalidArgument, "inconsistent qtype annotations for L.x: INT32 != FLOAT32")); } TEST_F(QTypeMetadataTest, CollectLeafQTypes_InconsistentNested) { auto leaf_x = Leaf("x"); auto literal_float32_qtype = Literal(GetQType<float>()); auto literal_int32_qtype = Literal(GetQType<int32_t>()); auto sub_expr = ExprNode::UnsafeMakeOperatorNode( QTypeAnnotation::Make(), {leaf_x, literal_float32_qtype}, ExprAttributes{}); auto expr = ExprNode::UnsafeMakeOperatorNode(QTypeAnnotation::Make(), {sub_expr, literal_int32_qtype}, ExprAttributes{}); EXPECT_THAT(CollectLeafQTypes(expr), StatusIs(absl::StatusCode::kInvalidArgument, "inconsistent qtype annotations for L.x: " "INT32 != FLOAT32")); } TEST_F(QTypeMetadataTest, PopulateQTypes) { ASSERT_OK_AND_ASSIGN(ExprNodePtr expr, CallOp("test.add3", {Leaf("a"), Leaf("b"), Leaf("a")})); EXPECT_THAT(PopulateQTypes(expr, {{"a", GetQType<float>()}}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("QType for the leaves {b} are missing"))); EXPECT_THAT(PopulateQTypes(expr, {}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("QType for the leaves {a, b} are missing"))); EXPECT_THAT(PopulateQTypes(expr, {{"a", GetQType<float>()}}, true), IsOk()); ASSERT_OK_AND_ASSIGN(ExprNodePtr expr_float, PopulateQTypes(expr, {{"a", GetQType<float>()}, {"b", GetQType<float>()}})); EXPECT_EQ(expr_float->qtype(), GetQType<float>()); } TEST_F(QTypeMetadataTest, PopulateQTypes_WithGetter) { ASSERT_OK_AND_ASSIGN(ExprNodePtr expr, CallOp("test.add3", {Leaf("a"), Leaf("b"), Leaf("a")})); EXPECT_THAT(PopulateQTypes(expr, [](auto) { return nullptr; }), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("QType for the leaves {a, b} are missing"))); EXPECT_THAT(PopulateQTypes(expr, [](absl::string_view leaf_name) { return leaf_name == "a" ? GetQType<float>() : nullptr; }), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("QType for the leaves {b} are missing"))); EXPECT_THAT(PopulateQTypes( expr, [](auto) { return nullptr; }, true), IsOk()); ASSERT_OK_AND_ASSIGN(ExprNodePtr expr_float, PopulateQTypes(expr, [](auto) { return GetQType<float>(); })); EXPECT_EQ(expr_float->qtype(), GetQType<float>()); } TEST_F(QTypeMetadataTest, PopulateQTypes_CollectingQTypesFromExpr) { ASSERT_OK_AND_ASSIGN( auto expr, CallOp("test.add3", {WithQTypeAnnotation(Leaf("a"), GetQType<float>()), Leaf("b"), Leaf("a")})); ASSERT_OK_AND_ASSIGN(auto actual_expr, PopulateQTypes(expr, {{"b", GetQType<double>()}})); ASSERT_OK_AND_ASSIGN( auto expected_expr, CallOp("test.add3", {CallOp(QTypeAnnotation::Make(), {Leaf("a"), Literal(GetQType<float>())}), CallOp(QTypeAnnotation::Make(), {Leaf("b"), Literal(GetQType<double>())}), CallOp(QTypeAnnotation::Make(), {Leaf("a"), Literal(GetQType<float>())})})); EXPECT_THAT(actual_expr, EqualsExpr(expected_expr)); } TEST_F(QTypeMetadataTest, PopulateQType_QTypeMismatch) { ASSERT_OK_AND_ASSIGN(ExprNodePtr expr, WithQTypeAnnotation(Leaf("a"), GetQType<int32_t>())); EXPECT_THAT( PopulateQTypes(expr, {{"a", GetQType<float>()}}), StatusIs( absl::StatusCode::kInvalidArgument, HasSubstr( "inconsistent annotation.qtype(expr: FLOAT32, qtype=INT32)"))); } TEST_F(QTypeMetadataTest, BackendWrappingOperator) { ASSERT_OK_AND_ASSIGN(ExprNodePtr expr, CallOp("math.add", {Leaf("a"), Leaf("b")})); { ASSERT_OK_AND_ASSIGN(ExprNodePtr typed_expr, PopulateQTypes(expr, {{"a", GetQType<double>()}, {"b", GetQType<float>()}})); EXPECT_EQ(typed_expr->qtype(), GetQType<double>()); } { ASSERT_OK_AND_ASSIGN(ExprNodePtr typed_expr, PopulateQTypes(expr, {{"a", GetQType<float>()}, {"b", GetQType<float>()}})); EXPECT_EQ(typed_expr->qtype(), GetQType<float>()); } { EXPECT_THAT( PopulateQTypes(expr, {{"a", GetQType<int32_t>()}, {"b", GetQType<float>()}}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("incompatible types x: INT32 and y: FLOAT32"))); } } TEST_F(QTypeMetadataTest, GetExprAttrs) { ASSERT_OK_AND_ASSIGN(ExprNodePtr a, WithQTypeAnnotation(Leaf("a"), GetQType<int32_t>())); ExprNodePtr b = Literal(1.0f); ExprNodePtr c = Placeholder("c"); EXPECT_THAT(GetExprAttrs({}), ElementsAre()); EXPECT_THAT(GetExprAttrs({a, b, c}), ElementsAre(EqualsAttr(GetQType<int32_t>()), EqualsAttr(TypedValue::FromValue(1.0f)), EqualsAttr(nullptr))); } TEST_F(QTypeMetadataTest, GetAttrQTypes) { EXPECT_THAT(GetAttrQTypes({}), ElementsAre()); EXPECT_THAT(GetAttrQTypes({Attr{}}), ElementsAre(nullptr)); EXPECT_THAT(GetAttrQTypes( {Attr(GetQType<int32_t>()), Attr(GetQType<float>()), Attr{}}), ElementsAre(GetQType<int32_t>(), GetQType<float>(), nullptr)); } TEST_F(QTypeMetadataTest, GetValueQTypes) { EXPECT_THAT(GetValueQTypes({}), ElementsAre()); EXPECT_THAT(GetValueQTypes({GetQType<int32_t>()}), ElementsAre(nullptr)); EXPECT_THAT(GetValueQTypes({GetOptionalQType<int32_t>(), GetOptionalQType<float>(), GetQType<float>()}), ElementsAre(GetQType<int32_t>(), GetQType<float>(), nullptr)); } TEST_F(QTypeMetadataTest, HasAllAttrQTypes) { EXPECT_TRUE(HasAllAttrQTypes({})); EXPECT_TRUE( HasAllAttrQTypes({Attr(GetQType<int32_t>()), Attr(GetQType<float>())})); EXPECT_FALSE(HasAllAttrQTypes({Attr{}})); EXPECT_FALSE(HasAllAttrQTypes( {Attr(GetQType<int32_t>()), Attr(GetQType<float>()), Attr{}})); } } }
2,404
#ifndef AROLLA_CODEGEN_OPERATOR_PACKAGE_LOAD_OPERATOR_PACKAGE_H_ #define AROLLA_CODEGEN_OPERATOR_PACKAGE_LOAD_OPERATOR_PACKAGE_H_ #include "absl/status/status.h" #include "absl/strings/string_view.h" #include "arolla/codegen/operator_package/operator_package.pb.h" namespace arolla::operator_package { absl::Status ParseEmbeddedOperatorPackage( absl::string_view embedded_zlib_data, OperatorPackageProto* operator_package_proto); absl::Status LoadOperatorPackage( const OperatorPackageProto& operator_package_proto); } #endif #include "arolla/codegen/operator_package/load_operator_package.h" #include <set> #include "absl/status/status.h" #include "absl/strings/str_format.h" #include "absl/strings/str_join.h" #include "absl/strings/string_view.h" #include "google/protobuf/io/gzip_stream.h" #include "google/protobuf/io/zero_copy_stream_impl_lite.h" #include "arolla/codegen/operator_package/operator_package.pb.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/registered_expr_operator.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/serialization/decode.h" #include "arolla/util/status_macros_backport.h" namespace arolla::operator_package { using ::arolla::expr::ExprOperatorPtr; using ::arolla::expr::ExprOperatorRegistry; absl::Status ParseEmbeddedOperatorPackage( absl::string_view embedded_zlib_data, OperatorPackageProto* operator_package_proto) { ::google::protobuf::io::ArrayInputStream input_stream(embedded_zlib_data.data(), embedded_zlib_data.size()); ::google::protobuf::io::GzipInputStream gzip_input_stream(&input_stream); if (!operator_package_proto->ParseFromZeroCopyStream(&gzip_input_stream) || gzip_input_stream.ZlibErrorMessage() != nullptr) { return absl::InternalError("unable to parse an embedded operator package"); } return absl::OkStatus(); } absl::Status LoadOperatorPackage( const OperatorPackageProto& operator_package_proto) { if (operator_package_proto.version() != 1) { return absl::InvalidArgumentError( absl::StrFormat("expected operator_package_proto.version=1, got %d", operator_package_proto.version())); } auto* const operator_registry = ExprOperatorRegistry::GetInstance(); auto check_registered_operator_presence = [&](absl::string_view name) { return operator_registry->LookupOperatorOrNull(name) != nullptr; }; std::set<absl::string_view> missing_operators; for (absl::string_view operator_name : operator_package_proto.required_registered_operators()) { if (!check_registered_operator_presence(operator_name)) { missing_operators.insert(operator_name); } } if (!missing_operators.empty()) { return absl::FailedPreconditionError( "missing dependencies: M." + absl::StrJoin(missing_operators, ", M.")); } std::set<absl::string_view> already_registered_operators; for (const auto& operator_proto : operator_package_proto.operators()) { if (check_registered_operator_presence( operator_proto.registration_name())) { already_registered_operators.insert(operator_proto.registration_name()); } } if (!already_registered_operators.empty()) { return absl::FailedPreconditionError( "already present in the registry: M." + absl::StrJoin(already_registered_operators, ", M.")); } for (int i = 0; i < operator_package_proto.operators_size(); ++i) { const auto& operator_proto = operator_package_proto.operators(i); ASSIGN_OR_RETURN(auto decode_result, serialization::Decode(operator_proto.implementation()), _ << "operators[" << i << "].registration_name=" << operator_proto.registration_name()); if (decode_result.values.size() != 1 || !decode_result.exprs.empty()) { return absl::InvalidArgumentError(absl::StrFormat( "expected to get a value, got %d values and %d exprs; " "operators[%d].registration_name=%s", decode_result.values.size(), decode_result.exprs.size(), i, operator_proto.registration_name())); } const auto& qvalue = decode_result.values[0]; if (qvalue.GetType() != GetQType<ExprOperatorPtr>()) { return absl::InvalidArgumentError(absl::StrFormat( "expected to get %s, got %s; operators[%d].registration_name=%s", GetQType<ExprOperatorPtr>()->name(), qvalue.GetType()->name(), i, operator_proto.registration_name())); } RETURN_IF_ERROR(operator_registry ->Register(operator_proto.registration_name(), qvalue.UnsafeAs<ExprOperatorPtr>()) .status()); } return absl::OkStatus(); } }
#include "arolla/codegen/operator_package/load_operator_package.h" #include <cstdint> #include <string> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "arolla/codegen/operator_package/operator_package.pb.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/lambda_expr_operator.h" #include "arolla/expr/registered_expr_operator.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/typed_value.h" #include "arolla/serialization/encode.h" #include "arolla/util/init_arolla.h" #include "arolla/util/testing/status_matchers_backport.h" namespace arolla::operator_package { namespace { using ::arolla::expr::ExprOperatorPtr; using ::arolla::expr::LookupOperator; using ::arolla::expr::Placeholder; using ::arolla::testing::StatusIs; using ::testing::HasSubstr; class ParseEmbeddedOperatorPackageTest : public ::testing::Test { protected: void SetUp() override { ASSERT_OK(InitArolla()); } }; TEST_F(ParseEmbeddedOperatorPackageTest, TrivialOperatorPackage) { OperatorPackageProto operator_package_proto; ASSERT_OK(ParseEmbeddedOperatorPackage("x\x9c\xe3`\x04\x00\x00\x13\x00\n", &operator_package_proto)); EXPECT_THAT(operator_package_proto.version(), 1); } TEST_F(ParseEmbeddedOperatorPackageTest, ZLibError) { OperatorPackageProto operator_package_proto; EXPECT_THAT(ParseEmbeddedOperatorPackage("abc", &operator_package_proto), StatusIs(absl::StatusCode::kInternal, "unable to parse an embedded operator package")); } TEST_F(ParseEmbeddedOperatorPackageTest, ProtoError) { OperatorPackageProto operator_package_proto; EXPECT_THAT( ParseEmbeddedOperatorPackage("x\xda\xe3\x98\x06\x00\x00\xa8\x00\x9f", &operator_package_proto), StatusIs(absl::StatusCode::kInternal, "unable to parse an embedded operator package")); } class LoadOperatorPackageTest : public ::testing::Test { protected: void SetUp() override { ASSERT_OK(InitArolla()); } template <typename Proto> static absl::StatusOr<std::string> SerializeToString(const Proto& proto) { if (std::string result; proto.SerializeToString(&result)) { return result; } return absl::InvalidArgumentError("unable to serialize a proto message"); } }; TEST_F(LoadOperatorPackageTest, Registration) { ASSERT_OK_AND_ASSIGN(ExprOperatorPtr op, MakeLambdaOperator(Placeholder("x"))); OperatorPackageProto operator_package_proto; operator_package_proto.set_version(1); auto* operator_proto = operator_package_proto.add_operators(); operator_proto->set_registration_name("foo.bar.registration"); ASSERT_OK_AND_ASSIGN(*operator_proto->mutable_implementation(), serialization::Encode({TypedValue::FromValue(op)}, {})); EXPECT_OK(LoadOperatorPackage(operator_package_proto)); ASSERT_OK_AND_ASSIGN(auto reg_op, LookupOperator("foo.bar.registration")); ASSERT_OK_AND_ASSIGN(auto op_impl, reg_op->GetImplementation()); ASSERT_NE(op_impl, nullptr); EXPECT_EQ(op_impl->fingerprint(), op->fingerprint()); } TEST_F(LoadOperatorPackageTest, ErrorAlreadyRegistered) { ASSERT_OK_AND_ASSIGN(ExprOperatorPtr op, MakeLambdaOperator(Placeholder("x"))); OperatorPackageProto operator_package_proto; operator_package_proto.set_version(1); auto* operator_proto = operator_package_proto.add_operators(); operator_proto->set_registration_name("foo.bar.already_registered"); ASSERT_OK_AND_ASSIGN(*operator_proto->mutable_implementation(), serialization::Encode({TypedValue::FromValue(op)}, {})); EXPECT_OK(LoadOperatorPackage(operator_package_proto)); EXPECT_THAT(LoadOperatorPackage(operator_package_proto), StatusIs(absl::StatusCode::kFailedPrecondition, "already present in the registry: " "M.foo.bar.already_registered")); } TEST_F(LoadOperatorPackageTest, ErrorUnexpectedFormatVersion) { OperatorPackageProto operator_package_proto; EXPECT_THAT(LoadOperatorPackage(operator_package_proto), StatusIs(absl::StatusCode::kInvalidArgument, "expected operator_package_proto.version=1, got 0")); } TEST_F(LoadOperatorPackageTest, ErrorMissingDependency) { OperatorPackageProto operator_package_proto; operator_package_proto.set_version(1); operator_package_proto.add_required_registered_operators("foo.bar"); operator_package_proto.add_required_registered_operators("far.boo"); EXPECT_THAT(LoadOperatorPackage(operator_package_proto), StatusIs(absl::StatusCode::kFailedPrecondition, "missing dependencies: M.far.boo, M.foo.bar")); } TEST_F(LoadOperatorPackageTest, ErrorBrokenOperatorImplementation) { OperatorPackageProto operator_package_proto; operator_package_proto.set_version(1); operator_package_proto.add_operators()->set_registration_name("foo.bar"); EXPECT_THAT(LoadOperatorPackage(operator_package_proto), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("; operators[0].registration_name=foo.bar"))); } TEST_F(LoadOperatorPackageTest, ErrorNoValueInOperatorImplementation) { OperatorPackageProto operator_package_proto; operator_package_proto.set_version(1); auto* operator_proto = operator_package_proto.add_operators(); operator_proto->set_registration_name("foo.bar"); ASSERT_OK_AND_ASSIGN(*operator_proto->mutable_implementation(), serialization::Encode({}, {})); EXPECT_THAT( LoadOperatorPackage(operator_package_proto), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("expected to get a value, got 0 values and 0 exprs; " "operators[0].registration_name=foo.bar"))); } TEST_F(LoadOperatorPackageTest, ErrorUnexpectedValueInOperatorImplementation) { OperatorPackageProto operator_package_proto; operator_package_proto.set_version(1); auto* operator_proto = operator_package_proto.add_operators(); operator_proto->set_registration_name("foo.bar"); ASSERT_OK_AND_ASSIGN( *operator_proto->mutable_implementation(), serialization::Encode({TypedValue::FromValue<int64_t>(0)}, {})); EXPECT_THAT(LoadOperatorPackage(operator_package_proto), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("expected to get EXPR_OPERATOR, got INT64; " "operators[0].registration_name=foo.bar"))); } } }
2,405
#ifndef AROLLA_CODEGEN_IO_MULTI_LOADER_H_ #define AROLLA_CODEGEN_IO_MULTI_LOADER_H_ #include <cstddef> #include <cstdint> #include <limits> #include <optional> #include <string> #include <utility> #include <vector> #include "absl/types/span.h" #include "google/protobuf/repeated_ptr_field.h" #include "arolla/dense_array/dense_array.h" #include "arolla/memory/optional_value.h" #include "arolla/proto/types.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/typed_slot.h" namespace arolla::codegen::io { constexpr size_t kSkippedOffset = std::numeric_limits<size_t>::max(); struct HierarchicalSingleValueClearInfo { uint16_t range_begin = std::numeric_limits<uint16_t>::max(); uint16_t range_end = 0; bool operator==(const HierarchicalSingleValueClearInfo& other) const { return range_begin == other.range_begin && range_end == other.range_end; } }; template <size_t kLeafCount, size_t kNodeCount> struct HierarchicalRequestedInputsData { size_t leaf_frame_offsets[kLeafCount]; bool node_requested[kNodeCount - kLeafCount] = {false}; }; template <size_t kLeafCount, size_t kNodeCount> struct HierarchicalSingleValueRequestedInputsData { template <class T> using value_type = ::arolla::OptionalValue<::arolla::proto::arolla_single_value_t<T>>; using size_type = ::arolla::DenseArrayShape; HierarchicalRequestedInputsData<kLeafCount, kNodeCount> common; HierarchicalSingleValueClearInfo node_optional_clear_infos[kNodeCount - kLeafCount]; size_t requested_offsets[kLeafCount]; HierarchicalSingleValueClearInfo node_size_clear_infos[kNodeCount - kLeafCount]; }; template <size_t kLeafCount, size_t kNodeCount> struct HierarchicalMultiValueRequestedInputsData { template <class T> using value_type = ::arolla::DenseArray<::arolla::proto::arolla_single_value_t<T>>; using size_type = ::arolla::DenseArray<::arolla::proto::arolla_size_t>; HierarchicalRequestedInputsData<kLeafCount, kNodeCount> common; }; namespace multi_loader_internal { struct HierarchicalRequestedInputsDataView { absl::Span<size_t> leaf_frame_offsets; absl::Span<bool> node_requested; }; struct HierarchicalSingleValueRequestedInputsDataView { absl::Span<HierarchicalSingleValueClearInfo> node_optional_clear_infos; absl::Span<size_t> requested_offsets; absl::Span<HierarchicalSingleValueClearInfo> node_size_clear_infos; }; void CreateHierarchicalRequestedInputs( const std::vector<std::optional<TypedSlot>>& leaf_slots, const std::vector<std::vector<size_t>>& tree, HierarchicalRequestedInputsDataView output); void CreateHierarchicalSingleValueRequestedInputs( const std::vector<std::optional<TypedSlot>>& leaf_slots, const std::vector<size_t>& size_leaves, const std::vector<std::vector<size_t>>& tree, HierarchicalSingleValueRequestedInputsDataView output); template <size_t kLeafCount, size_t kNodeCount> void CreateHierarchicalRequestedInputs( const std::vector<std::optional<TypedSlot>>& leaf_slots, const std::vector<std::vector<size_t>>& tree, HierarchicalRequestedInputsData<kLeafCount, kNodeCount>* inputs) { static_assert(kLeafCount < (1 << 16), "Too many input leaves for generated code"); multi_loader_internal::CreateHierarchicalRequestedInputs( leaf_slots, tree, multi_loader_internal::HierarchicalRequestedInputsDataView{ absl::MakeSpan(inputs->leaf_frame_offsets), absl::MakeSpan(inputs->node_requested)}); } } template <size_t kLeafCount, size_t kNodeCount> void CreateHierarchicalSingleValueRequestedInputs( const std::vector<std::optional<TypedSlot>>& leaf_slots, const std::vector<size_t>& size_leaves, const std::vector<std::vector<size_t>>& tree, HierarchicalSingleValueRequestedInputsData<kLeafCount, kNodeCount>* inputs) { static_assert(kLeafCount < (1 << 16), "Too many input leaves for generated code"); multi_loader_internal::CreateHierarchicalRequestedInputs(leaf_slots, tree, &inputs->common); multi_loader_internal::CreateHierarchicalSingleValueRequestedInputs( leaf_slots, size_leaves, tree, multi_loader_internal::HierarchicalSingleValueRequestedInputsDataView{ absl::MakeSpan(inputs->node_optional_clear_infos), absl::MakeSpan(inputs->requested_offsets), absl::MakeSpan(inputs->node_size_clear_infos)}); } template <size_t kLeafCount, size_t kNodeCount> void CreateHierarchicalMultiValueRequestedInputs( const std::vector<std::optional<TypedSlot>>& leaf_slots, const std::vector<std::vector<size_t>>& tree, HierarchicalMultiValueRequestedInputsData<kLeafCount, kNodeCount>* inputs) { static_assert(kLeafCount < (1 << 16), "Too many input leaves for generated code"); multi_loader_internal::CreateHierarchicalRequestedInputs(leaf_slots, tree, &inputs->common); } template <class T> void ResizeRepeatedProtoField(google::protobuf::RepeatedPtrField<T>* field, size_t size) { arolla::proto::ResizeContainer(*field, size); } } #endif #include "arolla/codegen/io/multi_loader.h" #include <algorithm> #include <cstddef> #include <optional> #include <vector> #include "absl/log/check.h" #include "arolla/qtype/optional_qtype.h" #include "arolla/qtype/qtype.h" namespace arolla::codegen::io { namespace multi_loader_internal { void CreateHierarchicalRequestedInputs( const std::vector<std::optional<TypedSlot>>& leaf_slots, const std::vector<std::vector<size_t>>& tree, HierarchicalRequestedInputsDataView output) { CHECK_LT(leaf_slots.size(), 1 << 16) << "Too many input leaves for generated code"; std::vector<size_t> leaf_frame_offsets; std::vector<char> node_requested; node_requested.resize(tree.size(), false); for (size_t node_id = 0; node_id != tree.size(); ++node_id) { const std::vector<size_t>& children = tree[node_id]; if (children.empty()) { size_t leaf_id = leaf_frame_offsets.size(); const std::optional<TypedSlot>& slot = leaf_slots[leaf_id]; size_t offset = slot.has_value() ? slot->byte_offset() : kSkippedOffset; leaf_frame_offsets.push_back(offset); node_requested[node_id] = slot.has_value(); } else { node_requested[node_id] = false; for (size_t child : children) { CHECK_LT(child, node_id); node_requested[node_id] |= node_requested[child]; } } } std::copy(leaf_frame_offsets.begin(), leaf_frame_offsets.end(), output.leaf_frame_offsets.begin()); size_t intermediate_id = 0; for (size_t i = 0; i != tree.size(); ++i) { if (tree[i].empty()) { continue; } CHECK_LT(intermediate_id, output.node_requested.size()); output.node_requested[intermediate_id++] = node_requested[i]; } } void CreateHierarchicalSingleValueRequestedInputs( const std::vector<std::optional<TypedSlot>>& leaf_slots, const std::vector<size_t>& size_leaves, const std::vector<std::vector<size_t>>& tree, HierarchicalSingleValueRequestedInputsDataView output) { CHECK_LT(leaf_slots.size(), 1 << 16) << "Too many input leaves for generated code"; std::vector<HierarchicalSingleValueClearInfo> node_optional_clear_infos; std::vector<HierarchicalSingleValueClearInfo> node_size_clear_infos; std::vector<size_t> presence_offsets; std::vector<size_t> size_offsets; node_optional_clear_infos.resize(tree.size(), HierarchicalSingleValueClearInfo{}); node_size_clear_infos.resize(tree.size(), HierarchicalSingleValueClearInfo{}); size_t leaf_id = 0; for (size_t node_id = 0; node_id != tree.size(); ++node_id) { const std::vector<size_t>& children = tree[node_id]; auto& node_optional_clear_info = node_optional_clear_infos[node_id]; auto& node_size_clear_info = node_size_clear_infos[node_id]; if (children.empty()) { const std::optional<TypedSlot>& slot = leaf_slots[leaf_id]; size_t offset = slot.has_value() ? slot->byte_offset() : kSkippedOffset; node_optional_clear_info.range_begin = presence_offsets.size(); node_size_clear_info.range_begin = size_offsets.size(); if (offset != kSkippedOffset) { if (std::binary_search(size_leaves.begin(), size_leaves.end(), leaf_id)) { size_offsets.push_back(offset); } else if (::arolla::IsOptionalQType(slot->GetType())) { presence_offsets.push_back(offset); } } node_optional_clear_info.range_end = presence_offsets.size(); node_size_clear_info.range_end = size_offsets.size(); ++leaf_id; } else { node_optional_clear_info.range_begin = node_optional_clear_infos[children.front()].range_begin; node_optional_clear_info.range_end = node_optional_clear_infos[children.back()].range_end; node_size_clear_info.range_begin = node_size_clear_infos[children.front()].range_begin; node_size_clear_info.range_end = node_size_clear_infos[children.back()].range_end; } } CHECK_GE(output.requested_offsets.size(), presence_offsets.size() + size_offsets.size()); std::copy(presence_offsets.begin(), presence_offsets.end(), output.requested_offsets.begin()); std::copy(size_offsets.begin(), size_offsets.end(), output.requested_offsets.begin() + presence_offsets.size()); std::fill(output.requested_offsets.begin() + presence_offsets.size() + size_offsets.size(), output.requested_offsets.end(), kSkippedOffset); size_t leaf_count = 0; for (size_t i = 0; i != tree.size(); ++i) { if (tree[i].empty()) { ++leaf_count; continue; } size_t intermediate_id = i - leaf_count; output.node_optional_clear_infos[intermediate_id] = node_optional_clear_infos[i]; output.node_size_clear_infos[intermediate_id] = node_size_clear_infos[i]; output.node_size_clear_infos[intermediate_id].range_begin += presence_offsets.size(); output.node_size_clear_infos[intermediate_id].range_end += presence_offsets.size(); } } } }
#include "arolla/codegen/io/multi_loader.h" #include <optional> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "arolla/dense_array/dense_array.h" #include "arolla/dense_array/qtype/types.h" #include "arolla/memory/frame.h" #include "arolla/memory/optional_value.h" #include "arolla/proto/test.pb.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/typed_slot.h" namespace arolla::codegen::io { namespace { using ::testing::ElementsAre; TEST(SingleValueTest, CreateHierarchicalSingleValueRequestedInputsTrivialAllRequested) { FrameLayout::Builder layout_builder; auto a_slot = layout_builder.AddSlot<OptionalValue<int>>(); auto b_slot = layout_builder.AddSlot<OptionalValue<int>>(); auto c_slot = layout_builder.AddSlot<OptionalValue<int>>(); HierarchicalSingleValueRequestedInputsData<3, 4> inputs; CreateHierarchicalSingleValueRequestedInputs( {TypedSlot::FromSlot(a_slot), TypedSlot::FromSlot(b_slot), TypedSlot::FromSlot(c_slot)}, {1}, {{}, {}, {}, {0, 1, 2}}, &inputs); EXPECT_THAT(inputs.common.leaf_frame_offsets, ElementsAre(a_slot.byte_offset(), b_slot.byte_offset(), c_slot.byte_offset())); EXPECT_THAT(inputs.common.node_requested, ElementsAre(true)); EXPECT_THAT(inputs.requested_offsets, ElementsAre(a_slot.byte_offset(), c_slot.byte_offset(), b_slot.byte_offset())); EXPECT_THAT(inputs.node_optional_clear_infos, ElementsAre(HierarchicalSingleValueClearInfo{0, 2})); EXPECT_THAT(inputs.node_size_clear_infos, ElementsAre(HierarchicalSingleValueClearInfo{2, 3})); } TEST(SingleValueTest, CreateHierarchicalSingleValueRequestedInputsTrivialNothingRequested) { HierarchicalSingleValueRequestedInputsData<3, 4> inputs; CreateHierarchicalSingleValueRequestedInputs( {std::nullopt, std::nullopt, std::nullopt}, {1}, {{}, {}, {}, {0, 1, 2}}, &inputs); EXPECT_THAT(inputs.common.leaf_frame_offsets, ElementsAre(kSkippedOffset, kSkippedOffset, kSkippedOffset)); EXPECT_THAT(inputs.common.node_requested, ElementsAre(false)); EXPECT_THAT(inputs.requested_offsets, ElementsAre(kSkippedOffset, kSkippedOffset, kSkippedOffset)); EXPECT_THAT(inputs.node_optional_clear_infos, ElementsAre(HierarchicalSingleValueClearInfo{0, 0})); EXPECT_THAT(inputs.node_size_clear_infos, ElementsAre(HierarchicalSingleValueClearInfo{0, 0})); } TEST(SingleValueTest, CreateHierarchicalSingleValueRequestedInputsTrivialSizeRequested) { FrameLayout::Builder layout_builder; auto b_slot = layout_builder.AddSlot<OptionalValue<int>>(); HierarchicalSingleValueRequestedInputsData<3, 4> inputs; CreateHierarchicalSingleValueRequestedInputs( {std::nullopt, TypedSlot::FromSlot(b_slot), std::nullopt}, {1}, {{}, {}, {}, {0, 1, 2}}, &inputs); EXPECT_THAT( inputs.common.leaf_frame_offsets, ElementsAre(kSkippedOffset, b_slot.byte_offset(), kSkippedOffset)); EXPECT_THAT(inputs.common.node_requested, ElementsAre(true)); EXPECT_THAT( inputs.requested_offsets, ElementsAre(b_slot.byte_offset(), kSkippedOffset, kSkippedOffset)); EXPECT_THAT(inputs.node_optional_clear_infos, ElementsAre(HierarchicalSingleValueClearInfo{0, 0})); EXPECT_THAT(inputs.node_size_clear_infos, ElementsAre(HierarchicalSingleValueClearInfo{0, 1})); } TEST(SingleValueTest, CreateHierarchicalSingleValueRequestedInputsTrivialOptionalRequested) { FrameLayout::Builder layout_builder; auto a_slot = layout_builder.AddSlot<OptionalValue<int>>(); HierarchicalSingleValueRequestedInputsData<3, 4> inputs; CreateHierarchicalSingleValueRequestedInputs( {TypedSlot::FromSlot(a_slot), std::nullopt, std::nullopt}, {1}, {{}, {}, {}, {0, 1, 2}}, &inputs); EXPECT_THAT( inputs.common.leaf_frame_offsets, ElementsAre(a_slot.byte_offset(), kSkippedOffset, kSkippedOffset)); EXPECT_THAT(inputs.common.node_requested, ElementsAre(true)); EXPECT_THAT( inputs.requested_offsets, ElementsAre(a_slot.byte_offset(), kSkippedOffset, kSkippedOffset)); EXPECT_THAT(inputs.node_optional_clear_infos, ElementsAre(HierarchicalSingleValueClearInfo{0, 1})); EXPECT_THAT(inputs.node_size_clear_infos, ElementsAre(HierarchicalSingleValueClearInfo{1, 1})); } TEST(SingleValueTest, CreateHierarchicalSingleValueRequestedInputsHierarchyAllRequested) { FrameLayout::Builder layout_builder; auto a_slot = layout_builder.AddSlot<OptionalValue<int>>(); auto b_slot = layout_builder.AddSlot<DenseArrayShape>(); auto c_slot = layout_builder.AddSlot<OptionalValue<int>>(); auto d_slot = layout_builder.AddSlot<OptionalValue<int>>(); HierarchicalSingleValueRequestedInputsData<4, 7> inputs; CreateHierarchicalSingleValueRequestedInputs( {TypedSlot::FromSlot(a_slot), TypedSlot::FromSlot(b_slot), TypedSlot::FromSlot(c_slot), TypedSlot::FromSlot(d_slot)}, {1}, {{}, {}, {0, 1}, {}, {3}, {}, {2, 4, 5}}, &inputs); EXPECT_THAT(inputs.common.leaf_frame_offsets, ElementsAre(a_slot.byte_offset(), b_slot.byte_offset(), c_slot.byte_offset(), d_slot.byte_offset())); EXPECT_THAT(inputs.common.node_requested, ElementsAre(true, true, true)); EXPECT_THAT(inputs.requested_offsets, ElementsAre(a_slot.byte_offset(), c_slot.byte_offset(), d_slot.byte_offset(), b_slot.byte_offset())); using CI = HierarchicalSingleValueClearInfo; EXPECT_THAT(inputs.node_optional_clear_infos, ElementsAre(CI{0, 1}, CI{1, 2}, CI{0, 3})); EXPECT_THAT(inputs.node_size_clear_infos, ElementsAre(CI{3, 4}, CI{4, 4}, CI{3, 4})); } TEST(SingleValueTest, CreateHierarchicalSingleValueRequestedInputsAFewRequestedWithFullValue) { FrameLayout::Builder layout_builder; auto a_slot = layout_builder.AddSlot<OptionalValue<int>>(); auto c_slot = layout_builder.AddSlot<int>(); HierarchicalSingleValueRequestedInputsData<4, 7> inputs; CreateHierarchicalSingleValueRequestedInputs( {TypedSlot::FromSlot(a_slot), std::nullopt, TypedSlot::FromSlot(c_slot), std::nullopt}, {1}, {{}, {}, {0, 1}, {}, {3}, {}, {2, 4, 5}}, &inputs); EXPECT_THAT(inputs.common.leaf_frame_offsets, ElementsAre(a_slot.byte_offset(), kSkippedOffset, c_slot.byte_offset(), kSkippedOffset)); EXPECT_THAT(inputs.common.node_requested, ElementsAre(true, true, true)); EXPECT_THAT(inputs.requested_offsets, ElementsAre(a_slot.byte_offset(), kSkippedOffset, kSkippedOffset, kSkippedOffset)); using CI = HierarchicalSingleValueClearInfo; EXPECT_THAT(inputs.node_optional_clear_infos, ElementsAre(CI{0, 1}, CI{1, 1}, CI{0, 1})); EXPECT_THAT(inputs.node_size_clear_infos, ElementsAre(CI{1, 1}, CI{1, 1}, CI{1, 1})); } TEST(SingleValueTest, CreateHierarchicalSingleValueRequestedInputsAllRequestedWithFullValue) { FrameLayout::Builder layout_builder; auto a_slot = layout_builder.AddSlot<OptionalValue<int>>(); auto b_slot = layout_builder.AddSlot<DenseArrayShape>(); auto c_slot = layout_builder.AddSlot<int>(); auto d_slot = layout_builder.AddSlot<OptionalValue<int>>(); HierarchicalSingleValueRequestedInputsData<4, 7> inputs; CreateHierarchicalSingleValueRequestedInputs( {TypedSlot::FromSlot(a_slot), TypedSlot::FromSlot(b_slot), TypedSlot::FromSlot(c_slot), TypedSlot::FromSlot(d_slot)}, {1}, {{}, {}, {0, 1}, {}, {3}, {}, {2, 4, 5}}, &inputs); EXPECT_THAT(inputs.common.leaf_frame_offsets, ElementsAre(a_slot.byte_offset(), b_slot.byte_offset(), c_slot.byte_offset(), d_slot.byte_offset())); EXPECT_THAT(inputs.common.node_requested, ElementsAre(true, true, true)); EXPECT_THAT(inputs.requested_offsets, ElementsAre(a_slot.byte_offset(), d_slot.byte_offset(), b_slot.byte_offset(), kSkippedOffset)); using CI = HierarchicalSingleValueClearInfo; EXPECT_THAT(inputs.node_optional_clear_infos, ElementsAre(CI{0, 1}, CI{1, 1}, CI{0, 2})); EXPECT_THAT(inputs.node_size_clear_infos, ElementsAre(CI{2, 3}, CI{3, 3}, CI{2, 3})); } TEST(SingleValueTest, CreateHierarchicalSingleValueRequestedInputsHierarchySizeRequested) { FrameLayout::Builder layout_builder; auto b_slot = layout_builder.AddSlot<OptionalValue<int>>(); HierarchicalSingleValueRequestedInputsData<4, 7> inputs; CreateHierarchicalSingleValueRequestedInputs( {std::nullopt, TypedSlot::FromSlot(b_slot), std::nullopt, std::nullopt}, {1}, {{}, {}, {0, 1}, {}, {3}, {}, {2, 4}}, &inputs); EXPECT_THAT(inputs.common.leaf_frame_offsets, ElementsAre(kSkippedOffset, b_slot.byte_offset(), kSkippedOffset, kSkippedOffset)); EXPECT_THAT(inputs.common.node_requested, ElementsAre(true, false, true)); EXPECT_THAT(inputs.requested_offsets, ElementsAre(b_slot.byte_offset(), kSkippedOffset, kSkippedOffset, kSkippedOffset)); using CI = HierarchicalSingleValueClearInfo; EXPECT_THAT(inputs.node_optional_clear_infos, ElementsAre(CI{0, 0}, CI{0, 0}, CI{0, 0})); EXPECT_THAT(inputs.node_size_clear_infos, ElementsAre(CI{0, 1}, CI{1, 1}, CI{0, 1})); } TEST(SingleValueTest, CreateHierarchicalSingleValueRequestedInputsHierarchyOptionalRequested) { FrameLayout::Builder layout_builder; auto c_slot = layout_builder.AddSlot<OptionalValue<int>>(); HierarchicalSingleValueRequestedInputsData<4, 7> inputs; CreateHierarchicalSingleValueRequestedInputs( {std::nullopt, std::nullopt, TypedSlot::FromSlot(c_slot), std::nullopt}, {1}, {{}, {}, {0, 1}, {}, {3}, {}, {2, 4}}, &inputs); EXPECT_THAT(inputs.common.leaf_frame_offsets, ElementsAre(kSkippedOffset, kSkippedOffset, c_slot.byte_offset(), kSkippedOffset)); EXPECT_THAT(inputs.common.node_requested, ElementsAre(false, true, true)); EXPECT_THAT(inputs.requested_offsets, ElementsAre(c_slot.byte_offset(), kSkippedOffset, kSkippedOffset, kSkippedOffset)); using CI = HierarchicalSingleValueClearInfo; EXPECT_THAT(inputs.node_optional_clear_infos, ElementsAre(CI{0, 0}, CI{0, 1}, CI{0, 1})); EXPECT_THAT(inputs.node_size_clear_infos, ElementsAre(CI{1, 1}, CI{1, 1}, CI{1, 1})); } TEST(ResizeRepeatedProtoFieldTest, MessageResize) { testing_namespace::Root root; ResizeRepeatedProtoField(root.mutable_inners(), 5); EXPECT_EQ(root.inners_size(), 5); EXPECT_FALSE(root.inners(0).has_a()); root.mutable_inners(0)->set_a(13); ResizeRepeatedProtoField(root.mutable_inners(), 7); EXPECT_EQ(root.inners_size(), 7); EXPECT_TRUE(root.inners(0).has_a()); EXPECT_EQ(root.inners(0).a(), 13); ResizeRepeatedProtoField(root.mutable_inners(), 3); EXPECT_EQ(root.inners_size(), 3); EXPECT_TRUE(root.inners(0).has_a()); EXPECT_EQ(root.inners(0).a(), 13); ResizeRepeatedProtoField(root.mutable_inners(), 3); EXPECT_EQ(root.inners_size(), 3); EXPECT_TRUE(root.inners(0).has_a()); EXPECT_EQ(root.inners(0).a(), 13); } } }
2,406
#ifndef AROLLA_CODEGEN_EXPR_CODEGEN_OPERATOR_H_ #define AROLLA_CODEGEN_EXPR_CODEGEN_OPERATOR_H_ #include <cstddef> #include <cstdint> #include <map> #include <ostream> #include <set> #include <string> #include <utility> #include <vector> #include "absl/status/statusor.h" #include "absl/strings/str_join.h" #include "absl/strings/string_view.h" #include "arolla/expr/expr_node.h" #include "arolla/qtype/qtype.h" namespace arolla::codegen { namespace codegen_impl { bool IsInlinableLiteralType(const QType* qtype); } enum struct LValueKind : int { kLiteral, kInput, kLocal, }; struct LValue { std::string type_name; bool is_entire_expr_status_or; bool is_local_expr_status_or; QTypePtr qtype; LValueKind kind; absl::StatusOr<std::string> QTypeConstruction() const; friend std::ostream& operator<<(std::ostream& out, const LValue& v) { return out << static_cast<int>(v.kind) << " " << v.qtype->name() << " is_entire_expr_status_or=" << v.is_entire_expr_status_or << " is_local_expr_status_or=" << v.is_local_expr_status_or; } friend bool operator==(const LValue& a, const LValue& b) { return a.type_name == b.type_name && a.is_entire_expr_status_or == b.is_entire_expr_status_or && a.is_local_expr_status_or == b.is_local_expr_status_or && a.qtype == b.qtype && a.kind == b.kind; } }; using LValueId = int64_t; enum struct RValueKind : int { kInput, kVerbatim, kFunctionCall, kFunctionWithContextCall, kFirst, kOutput, }; struct RValue { RValueKind kind; bool operator_returns_status_or; std::string code; std::vector<LValueId> argument_ids; std::vector<int> argument_as_function_offsets = {}; std::string comment; static RValue CreateInput() { return RValue{.kind = RValueKind::kInput, .operator_returns_status_or = false, .code = "", .argument_ids = {}}; } static RValue CreateLiteral(std::string code) { return RValue{.kind = RValueKind::kVerbatim, .operator_returns_status_or = false, .code = std::move(code), .argument_ids = {}}; } friend std::ostream& operator<<(std::ostream& out, const RValue& v) { return out << static_cast<int>(v.kind) << "returns_status_or=" << v.operator_returns_status_or << " " << v.code << " {" << absl::StrJoin(v.argument_ids, ",") << "}"; } friend bool operator==(const RValue& a, const RValue& b) { return a.kind == b.kind && a.operator_returns_status_or == b.operator_returns_status_or && a.code == b.code && a.argument_ids == b.argument_ids; } }; class Assignment { public: Assignment() = default; Assignment(LValue lvalue, RValue rvalue, bool inlinable = false) : lvalue_(std::move(lvalue)), rvalue_(std::move(rvalue)), inlinable_(inlinable) {} const LValue& lvalue() const { return lvalue_; } LValue& lvalue() { return lvalue_; } const RValue& rvalue() const { return rvalue_; } RValue& rvalue() { return rvalue_; } bool is_inlinable() const { return inlinable_; } void set_inlinable(bool inlinable) { inlinable_ = inlinable; } friend std::ostream& operator<<(std::ostream& out, const Assignment& s) { return out << s.lvalue_ << " = " << s.rvalue_ << ";"; } private: LValue lvalue_; RValue rvalue_; bool inlinable_; }; struct Function { std::vector<LValueId> assignment_ids; LValueId output_id; bool is_result_status_or; }; struct OperatorCodegenData { std::vector<LValueId> literal_ids() const { std::vector<LValueId> res; for (int64_t i = 0; i != assignments.size(); ++i) { if (assignments[i].lvalue().kind == LValueKind::kLiteral) { res.push_back(i); } } return res; } std::map<LValueId, std::string> input_id_to_name() const { std::map<LValueId, std::string> res; for (const auto& [name, id] : inputs) { res.emplace(id, name); } return res; } std::map<LValueId, int64_t> function_entry_points() const { std::map<LValueId, int64_t> res; size_t fn_id = 0; for (const auto& fn : functions) { res.emplace(fn.output_id, fn_id++); } return res; } std::set<std::string> deps; std::set<std::string> headers; std::map<std::string, LValueId> inputs; std::vector<std::pair<std::string, LValueId>> side_outputs; std::vector<Assignment> assignments; std::vector<Function> functions; std::vector<Function> lambdas; LValueId output_id; }; absl::StatusOr<OperatorCodegenData> GenerateOperatorCode( expr::ExprNodePtr expr, bool inputs_are_cheap_to_read); } #endif #include "arolla/codegen/expr/codegen_operator.h" #include <algorithm> #include <cstddef> #include <cstdint> #include <functional> #include <memory> #include <optional> #include <string> #include <utility> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/container/flat_hash_set.h" #include "absl/flags/flag.h" #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" #include "absl/types/span.h" #include "arolla/algorithm/control_flow_graph.h" #include "arolla/codegen/expr/optimizations.h" #include "arolla/codegen/expr/types.h" #include "arolla/expr/annotation_utils.h" #include "arolla/expr/basic_expr_operator.h" #include "arolla/expr/derived_qtype_cast_operator.h" #include "arolla/expr/eval/eval.h" #include "arolla/expr/eval/prepare_expression.h" #include "arolla/expr/eval/side_output.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_debug_string.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/expr/expr_visitor.h" #include "arolla/expr/registered_expr_operator.h" #include "arolla/qexpr/operator_metadata.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/derived_qtype.h" #include "arolla/qtype/optional_qtype.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/util/bytes.h" #include "arolla/util/fast_dynamic_downcast_final.h" #include "arolla/util/fingerprint.h" #include "arolla/util/map.h" #include "arolla/util/text.h" #include "arolla/util/status_macros_backport.h" ABSL_FLAG(int64_t, arolla_codegen_min_local_variables_per_lambda, 50, R"""( Minimum number of local variables required in order to create lambda. There are several things to consider for tuning this parameter. 1. maximum depth of braces is limited in C++, so we shouldn't create too deep structure. 2. C++ compiler can be not good in optimizing too many lambda functions. 3. On other hand smaller number can eliminate stack usage more. 4. It is not clear whenever compiler can successfully reuse stack memory for several variables with the same type. )"""); ABSL_FLAG(int64_t, arolla_codegen_max_allowed_inline_depth, 50, R"""( Maximim depth in inlining function calls that used only once. There are several things to consider for tuning this parameter. 1. Inlining may help compiler to optimize better and take advantage of temporary variables, save stack pressure. 2. Inlining making code slightly more readable. 3. maximum depth of braces is limited in C++, so we shouldn't create too deep structure. )"""); namespace arolla::codegen { namespace codegen_impl { bool IsInlinableLiteralType(const QType* qtype) { auto is_primitive_type = [](const QType* type) { return IsScalarQType(type) && type != GetQType<Text>() && type != GetQType<Bytes>(); }; return qtype != nullptr && is_primitive_type(DecayOptionalQType(qtype)); } } namespace { using expr::BackendExprOperatorTag; using expr::DecayRegisteredOperator; using expr::ExprNodePtr; using expr::ExprNodeType; using expr::ExprOperatorPtr; using expr::ExprOperatorSignature; using expr::UnnamedExprOperator; using expr::eval_internal::InternalRootOperator; using NodeId = AcyclicCFG::NodeId; class InternalNamedOutputExportOperator final : public UnnamedExprOperator { public: explicit InternalNamedOutputExportOperator(int64_t export_id) : UnnamedExprOperator( ExprOperatorSignature({{"x"}}), FingerprintHasher("codegen::InternalNamedOutputExportOperator") .Combine(export_id) .Finish()), export_id_(export_id) {} absl::StatusOr<QTypePtr> GetOutputQType( absl::Span<const QTypePtr> input_qtypes) const final { return input_qtypes[0]; } int64_t ExportId() const { return export_id_; } private: int64_t export_id_; }; std::optional<int64_t> MaybeGetExportId(const ExprNodePtr& node) { if (auto* export_op = fast_dynamic_downcast_final<const InternalNamedOutputExportOperator*>( node->op().get())) { return export_op->ExportId(); } return std::nullopt; } absl::StatusOr<std::vector<QTypePtr>> DependencyTypes( const ExprNodePtr& node, std::function<absl::StatusOr<QTypePtr>(const ExprNodePtr&)> qtype_from_expr_fn) { std::vector<QTypePtr> result; result.reserve(node->node_deps().size()); for (const ExprNodePtr& dep : node->node_deps()) { ASSIGN_OR_RETURN(result.emplace_back(), qtype_from_expr_fn(dep)); } return result; } absl::StatusOr<std::optional<QExprOperatorMetadata>> GetOperatorMetadata( const QExprOperatorMetadataRegistry& op_registry, const ExprNodePtr& node, std::function<absl::StatusOr<QTypePtr>(const ExprNodePtr&)> qtype_from_expr_fn) { ASSIGN_OR_RETURN(auto op, DecayRegisteredOperator(node->op())); if (op == InternalRootOperator()) { return std::nullopt; } if (expr::IsQTypeAnnotation(node)) { return std::nullopt; } if (auto export_id_opt = MaybeGetExportId(node); export_id_opt.has_value()) { return std::nullopt; } if (typeid(*op) == typeid(expr::DerivedQTypeUpcastOperator) || typeid(*op) == typeid(expr::DerivedQTypeDowncastOperator)) { return std::nullopt; } if (dynamic_cast<const BackendExprOperatorTag*>(op.get()) == nullptr) { return absl::InvalidArgumentError(absl::StrCat( node->op()->display_name(), " is not a backend ExprOperator")); } ASSIGN_OR_RETURN(auto dependency_types, DependencyTypes(node, qtype_from_expr_fn)); ASSIGN_OR_RETURN( auto metadata, op_registry.LookupOperatorMetadata(op->display_name(), dependency_types), _ << "while processing: " << expr::GetDebugSnippet(node)); return {metadata}; } absl::StatusOr<std::pair<std::unique_ptr<AcyclicCFG>, std::vector<ExprNodePtr>>> BuildEvalCfg(const ExprNodePtr& entry_node) { auto nodes_order = expr::VisitorOrder(entry_node); std::reverse(nodes_order.begin(), nodes_order.end()); absl::flat_hash_map<Fingerprint, NodeId> node_id; node_id.reserve(nodes_order.size()); for (const auto& node : nodes_order) { NodeId id = node_id.size(); node_id[node->fingerprint()] = id; } std::vector<std::vector<NodeId>> deps; deps.reserve(nodes_order.size()); for (const auto& node : nodes_order) { std::vector<NodeId> cur_deps; cur_deps.reserve(node->node_deps().size()); for (const auto& dep : node->node_deps()) { cur_deps.push_back(node_id[dep->fingerprint()]); } deps.push_back(std::move(cur_deps)); } ASSIGN_OR_RETURN(auto graph, AcyclicCFG::Create(std::move(deps))); return {std::pair{std::move(graph), std::move(nodes_order)}}; } std::vector<bool> FindInlinableNodes(const AcyclicCFG& graph) { std::vector<bool> inlinable(graph.num_nodes(), false); std::vector<size_t> inline_depth(graph.num_nodes(), 0); for (NodeId node_id = graph.num_nodes() - 1; node_id > 0; --node_id) { bool used_once = graph.reverse_deps(node_id).size() == 1; if (used_once) { size_t max_inline_depth = 0; for (NodeId dep : graph.deps(node_id)) { max_inline_depth = std::max(max_inline_depth, inline_depth[dep]); } if (max_inline_depth < absl::GetFlag(FLAGS_arolla_codegen_max_allowed_inline_depth)) { inlinable[node_id] = true; inline_depth[node_id] = max_inline_depth + 1; } } } inlinable[0] = true; return inlinable; } class Codegen { public: Codegen(const QExprOperatorMetadataRegistry& op_registry, const AcyclicCFG& graph, std::vector<ExprNodePtr> exprs, absl::flat_hash_map<Fingerprint, QTypePtr> node_qtypes, std::vector<std::string> side_output_names, bool inputs_are_cheap_to_read) : op_registry_(op_registry), graph_(graph), dominator_tree_(graph_), exprs_(std::move(exprs)), node_qtypes_(std::move(node_qtypes)), side_output_names_(std::move(side_output_names)), inputs_are_cheap_to_read_(inputs_are_cheap_to_read) {} absl::StatusOr<OperatorCodegenData> Process() { std::vector<bool> inlinable = FindInlinableNodes(graph_); OperatorCodegenData data; data.side_outputs.reserve(side_output_names_.size()); for (const auto& name : side_output_names_) { data.side_outputs.emplace_back(name, -1); } for (NodeId node_id = graph_.num_nodes() - 1; node_id >= 0; --node_id) { RETURN_IF_ERROR(ProcessSingleNode(node_id, inlinable[node_id], &data)); } for (const auto& [name, assignment_id] : data.side_outputs) { if (assignment_id == -1) { return absl::InternalError(absl::StrFormat( "named output `%s` is lost in transformations", name)); } } ASSIGN_OR_RETURN(data.functions, SplitOnFunctions(data)); FilterArgumentsAsFunction(data); LambdifyFunctions(data); ComputeLocalExprStatus(data); data.output_id = ToAssignmentId(0); return data; } private: absl::StatusOr<QTypePtr> QTypeFromExpr(const ExprNodePtr& node) const { DCHECK(node_qtypes_.contains(node->fingerprint())); auto qtype = node_qtypes_.at(node->fingerprint()); if (qtype == nullptr) { return absl::FailedPreconditionError(absl::StrFormat( "unable to deduce QType for %s", expr::ToDebugString(node))); } return qtype; } LValueId ToAssignmentId(NodeId node_id) const { return graph_.num_nodes() - node_id - 1; } NodeId ToNodeId(LValueId assignment_id) const { return graph_.num_nodes() - assignment_id - 1; } bool IsLiteralNode(NodeId node_id) const { return exprs_[node_id]->is_literal(); } bool IsLeafNode(NodeId node_id) const { return exprs_[node_id]->is_leaf(); } absl::StatusOr<std::vector<bool>> FindSeparableNodes() const { int64_t n = graph_.num_nodes(); absl::flat_hash_set<NodeId> global_nodes; for (int64_t node_id = 0; node_id != n; ++node_id) { if (IsLiteralNode(node_id) || (inputs_are_cheap_to_read_ && IsLeafNode(node_id))) { global_nodes.insert(node_id); } } ASSIGN_OR_RETURN(auto externalized_graph, ExternalizeNodes(graph_, dominator_tree_, global_nodes)); auto is_separable = FindVerticesWithEmptyDominanceFrontier( *externalized_graph, dominator_tree_); for (NodeId node_id = 0; node_id != n; ++node_id) { if (IsLiteralNode(node_id) || IsLeafNode(node_id)) { is_separable[node_id] = false; } } return is_separable; } absl::StatusOr<std::vector<Function>> SplitOnFunctions( OperatorCodegenData& data) const { int64_t n = graph_.num_nodes(); ASSIGN_OR_RETURN(auto is_separable, FindSeparableNodes()); CHECK(is_separable[0] || IsLiteralNode(0) || IsLeafNode(0)) << "InternalError: entry node should be always separable"; std::vector<Function> functions; constexpr int64_t kUndefined = -1; std::vector<int64_t> function_id(n, kUndefined); for (NodeId node_id = n - 1; node_id >= 0; --node_id) { if (is_separable[node_id]) { function_id[node_id] = functions.size(); Function new_fn; new_fn.output_id = ToAssignmentId(node_id); new_fn.is_result_status_or = data.assignments[new_fn.output_id] .lvalue() .is_entire_expr_status_or; functions.push_back(std::move(new_fn)); } } CHECK((function_id[0] != kUndefined) || IsLiteralNode(0) || IsLeafNode(0)) << "InternalError: entry node should be assigned to the function"; for (NodeId node_id = 0; node_id != n; ++node_id) { for (NodeId dep : graph_.deps(node_id)) { if (function_id[dep] == kUndefined) { function_id[dep] = function_id[node_id]; } } } for (NodeId node_id = n - 1; node_id >= 0; --node_id) { LValueId assignment_id = ToAssignmentId(node_id); int64_t cur_function_id = function_id[node_id]; if (IsLiteralNode(node_id)) { continue; } if ((inputs_are_cheap_to_read_ || node_id == 0) && IsLeafNode(node_id)) { continue; } if (!is_separable[node_id]) { functions[cur_function_id].assignment_ids.push_back(assignment_id); for (NodeId rdep : graph_.reverse_deps(node_id)) { CHECK_EQ(function_id[rdep], cur_function_id) << "InternalError: only separable nodes can be used by other " "functions"; } continue; } int64_t rdep_function = kUndefined; for (NodeId rdep : graph_.reverse_deps(node_id)) { if (function_id[rdep] != cur_function_id) { if (rdep_function == kUndefined) { rdep_function = function_id[rdep]; functions[rdep_function].assignment_ids.push_back(assignment_id); } else { CHECK_EQ(rdep_function, function_id[rdep]) << "InternalError: non leaf function node must be used by not " "more than one other function"; } } } } return functions; } void LambdifyFunctions(OperatorCodegenData& data) const { for (Function& function : data.functions) { LambdifyFunction(data, function); } } void ComputeLocalExprStatus(OperatorCodegenData& data) const { absl::flat_hash_map<LValueId, int64_t> id2lambda; for (int64_t i = 0; i < data.lambdas.size(); ++i) { id2lambda.emplace(data.lambdas[i].output_id, i); } absl::flat_hash_map<LValueId, int64_t> id2function; for (int64_t i = 0; i < data.functions.size(); ++i) { id2function.emplace(data.functions[i].output_id, i); } for (LValueId assignment_id = 0; assignment_id != data.assignments.size(); ++assignment_id) { auto& assignment = data.assignments[assignment_id]; bool is_local_expr_status_or = assignment.rvalue().operator_returns_status_or; if (id2function.contains(assignment_id)) { is_local_expr_status_or = data.functions[id2function[assignment_id]].is_result_status_or; } else { std::vector<LValueId> output_assignments = DependencyArgs(ToNodeId(assignment_id)); for (LValueId dep_id : output_assignments) { is_local_expr_status_or = is_local_expr_status_or || (data.assignments[dep_id].is_inlinable() && data.assignments[dep_id].lvalue().is_local_expr_status_or); } if (id2lambda.contains(assignment_id)) { Function& lambda = data.lambdas[id2lambda[assignment_id]]; for (LValueId assignment_id : lambda.assignment_ids) { is_local_expr_status_or |= data.assignments[assignment_id] .lvalue() .is_local_expr_status_or; } lambda.is_result_status_or = is_local_expr_status_or; } } assignment.lvalue().is_local_expr_status_or = is_local_expr_status_or; } } void FilterArgumentsAsFunction(OperatorCodegenData& data) const { for (Assignment& assignment : data.assignments) { RValue& rvalue = assignment.rvalue(); if (rvalue.kind != RValueKind::kFunctionCall && rvalue.kind != RValueKind::kFunctionWithContextCall) { continue; } if (rvalue.argument_as_function_offsets.empty()) { continue; } auto new_end = std::remove_if( rvalue.argument_as_function_offsets.begin(), rvalue.argument_as_function_offsets.end(), [&](int offset) { const Assignment& cur_assignment = data.assignments[rvalue.argument_ids[offset]]; return !cur_assignment.is_inlinable() || cur_assignment.lvalue().kind == LValueKind::kLiteral; }); rvalue.argument_as_function_offsets.erase( new_end, rvalue.argument_as_function_offsets.end()); } } bool IsInlinableAsFunctionArgument(LValueId assignment_id, const OperatorCodegenData& data) const { auto& cur_assignment = data.assignments[assignment_id]; if (cur_assignment.lvalue().kind == LValueKind::kLiteral) { return false; } if (!cur_assignment.is_inlinable()) { return false; } NodeId dominator_node_id = dominator_tree_.parent(ToNodeId(assignment_id)); LValueId dominator_assignment_id = ToAssignmentId(dominator_node_id); auto& parent_assignment = data.assignments[dominator_assignment_id]; const std::vector<LValueId>& parent_arg_ids = parent_assignment.rvalue().argument_ids; int arg_in_parent_id = std::find(parent_arg_ids.begin(), parent_arg_ids.end(), assignment_id) - parent_arg_ids.begin(); const std::vector<int>& argument_as_function_offsets = parent_assignment.rvalue().argument_as_function_offsets; return std::count(argument_as_function_offsets.begin(), argument_as_function_offsets.end(), arg_in_parent_id) != 0; } void LambdifyFunction(OperatorCodegenData& data, Function& function) const { absl::flat_hash_map<int64_t, std::vector<LValueId>> lambda_local_assignments; for (LValueId assignment_id : function.assignment_ids) { auto& cur_assignment = data.assignments[assignment_id]; NodeId node_id = ToNodeId(assignment_id); NodeId dominator_node_id = dominator_tree_.parent(node_id); LValueId dominator_assignment_id = ToAssignmentId(dominator_node_id); auto cur_lambda_assignments = std::move(lambda_local_assignments[assignmen
#include "arolla/codegen/expr/codegen_operator.h" #include <cstdint> #include <initializer_list> #include <set> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/statusor.h" #include "arolla/dense_array/qtype/types.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/expr/lambda_expr_operator.h" #include "arolla/expr/testing/testing.h" #include "arolla/qtype/optional_qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/weak_qtype.h" #include "arolla/util/bytes.h" #include "arolla/util/init_arolla.h" #include "arolla/util/text.h" #include "arolla/util/unit.h" namespace arolla::codegen { namespace { using ::arolla::expr::Leaf; using ::arolla::expr::Literal; using ::arolla::testing::WithExportAnnotation; using ::arolla::testing::WithQTypeAnnotation; using ::testing::_; using ::testing::ElementsAre; using ::testing::Eq; using ::testing::IsEmpty; using ::testing::Pair; using ::testing::UnorderedElementsAre; int64_t MinUnused(std::set<int64_t> used) { for (int64_t i = 0; i != used.size(); ++i) { if (used.count(i) == 0) { return i; } } return used.size(); } class CodegenTest : public ::testing::Test { void SetUp() override { ASSERT_OK(InitArolla()); } }; TEST_F(CodegenTest, IsInlinableLiteralTypeTest) { EXPECT_TRUE(codegen_impl::IsInlinableLiteralType(GetQType<int>())); EXPECT_TRUE(codegen_impl::IsInlinableLiteralType(GetQType<float>())); EXPECT_TRUE(codegen_impl::IsInlinableLiteralType(GetQType<double>())); EXPECT_TRUE(codegen_impl::IsInlinableLiteralType(GetQType<int64_t>())); EXPECT_TRUE(codegen_impl::IsInlinableLiteralType(GetQType<uint64_t>())); EXPECT_TRUE(codegen_impl::IsInlinableLiteralType(GetQType<bool>())); EXPECT_TRUE(codegen_impl::IsInlinableLiteralType(GetQType<Unit>())); EXPECT_FALSE(codegen_impl::IsInlinableLiteralType(GetQType<Bytes>())); EXPECT_FALSE(codegen_impl::IsInlinableLiteralType(GetQType<Text>())); EXPECT_TRUE(codegen_impl::IsInlinableLiteralType(GetOptionalQType<int>())); EXPECT_TRUE(codegen_impl::IsInlinableLiteralType(GetOptionalQType<float>())); EXPECT_TRUE(codegen_impl::IsInlinableLiteralType(GetOptionalQType<double>())); EXPECT_TRUE( codegen_impl::IsInlinableLiteralType(GetOptionalQType<int64_t>())); EXPECT_TRUE( codegen_impl::IsInlinableLiteralType(GetOptionalQType<uint64_t>())); EXPECT_TRUE(codegen_impl::IsInlinableLiteralType(GetOptionalQType<bool>())); EXPECT_TRUE(codegen_impl::IsInlinableLiteralType(GetOptionalQType<Unit>())); EXPECT_FALSE(codegen_impl::IsInlinableLiteralType(GetOptionalQType<Bytes>())); EXPECT_FALSE(codegen_impl::IsInlinableLiteralType(GetOptionalQType<Text>())); EXPECT_FALSE( codegen_impl::IsInlinableLiteralType(GetDenseArrayQType<bool>())); EXPECT_FALSE(codegen_impl::IsInlinableLiteralType(GetDenseArrayQType<int>())); EXPECT_FALSE( codegen_impl::IsInlinableLiteralType(GetDenseArrayQType<float>())); EXPECT_FALSE( codegen_impl::IsInlinableLiteralType(GetDenseArrayQType<double>())); } TEST_F(CodegenTest, SmokeTest) { ASSERT_OK_AND_ASSIGN( auto expr, expr::CallOp("math.add", {expr::CallOp("math.add", {WithQTypeAnnotation( Leaf("x"), GetQType<float>()), Literal(1.f)}), WithQTypeAnnotation(Leaf("y"), GetQType<float>())})); ASSERT_OK_AND_ASSIGN( OperatorCodegenData op, GenerateOperatorCode(expr, true)); EXPECT_THAT(op.headers, ElementsAre( "arolla/" "qexpr/operators/math/arithmetic.h")); EXPECT_THAT(op.deps, ElementsAre(" "arolla/" "qexpr/operators/math:lib")); EXPECT_THAT(op.inputs, ElementsAre(Pair("x", _), Pair("y", _))); int64_t input_x_id = op.inputs["x"]; EXPECT_THAT(op.assignments[input_x_id].lvalue(), Eq(LValue{.type_name = "float", .is_entire_expr_status_or = false, .qtype = GetQType<float>(), .kind = LValueKind::kInput})); EXPECT_THAT(op.assignments[input_x_id].rvalue(), Eq(RValue::CreateInput())); EXPECT_TRUE(op.assignments[input_x_id].is_inlinable()); int64_t input_y_id = op.inputs["y"]; EXPECT_THAT(op.assignments[input_y_id].lvalue(), Eq(LValue{.type_name = "float", .is_entire_expr_status_or = false, .qtype = GetQType<float>(), .kind = LValueKind::kInput})); EXPECT_THAT(op.assignments[input_y_id].rvalue(), Eq(RValue::CreateInput())); EXPECT_TRUE(op.assignments[input_x_id].is_inlinable()); EXPECT_EQ(op.assignments.size(), 3 + 2 ); int64_t literal_id = MinUnused({input_x_id, input_y_id}); ASSERT_LT(literal_id, op.assignments.size()); EXPECT_THAT(op.assignments[literal_id].lvalue(), Eq(LValue{.type_name = "float", .is_entire_expr_status_or = false, .qtype = GetQType<float>(), .kind = LValueKind::kLiteral})); EXPECT_THAT(op.assignments[literal_id].rvalue(), Eq(RValue::CreateLiteral("float{1.}"))); int64_t tmp0_id = MinUnused({input_x_id, input_y_id, literal_id}); ASSERT_LT(tmp0_id, op.assignments.size()); EXPECT_TRUE(op.assignments[tmp0_id].is_inlinable()); EXPECT_THAT(op.assignments[tmp0_id].lvalue(), Eq(LValue{.type_name = "float", .is_entire_expr_status_or = false, .qtype = GetQType<float>(), .kind = LValueKind::kLocal})); EXPECT_THAT(op.assignments[tmp0_id].rvalue(), Eq(RValue{.kind = RValueKind::kFunctionCall, .operator_returns_status_or = false, .code = "::arolla::AddOp{}", .argument_ids = {input_x_id, literal_id}})); int64_t tmp1_id = 4; EXPECT_THAT(op.assignments[tmp1_id].lvalue(), Eq(LValue{.type_name = "float", .is_entire_expr_status_or = false, .qtype = GetQType<float>(), .kind = LValueKind::kLocal})); EXPECT_THAT(op.assignments[tmp1_id].rvalue(), Eq(RValue{.kind = RValueKind::kFunctionCall, .operator_returns_status_or = false, .code = "::arolla::AddOp{}", .argument_ids = {tmp0_id, input_y_id}})); EXPECT_EQ(op.output_id, tmp1_id); EXPECT_THAT(op.function_entry_points(), UnorderedElementsAre(Pair(tmp0_id, 0), Pair(tmp1_id, 1))); } TEST_F(CodegenTest, SmokeWithNonGlobalInputsTest) { ASSERT_OK_AND_ASSIGN(auto x, WithQTypeAnnotation(Leaf("x"), GetQType<float>())); ASSERT_OK_AND_ASSIGN( auto expr, expr::CallOp("math.add", {expr::CallOp("math.add", {x, x}), WithQTypeAnnotation( Leaf("y"), GetQType<float>())})); ASSERT_OK_AND_ASSIGN( OperatorCodegenData op, GenerateOperatorCode(expr, false)); EXPECT_THAT(op.headers, ElementsAre( "arolla/" "qexpr/operators/math/arithmetic.h")); EXPECT_THAT(op.deps, ElementsAre(" "arolla/" "qexpr/operators/math:lib")); EXPECT_THAT(op.inputs, ElementsAre(Pair("x", _), Pair("y", _))); int64_t input_x_id = op.inputs["x"]; EXPECT_THAT(op.assignments[input_x_id].lvalue(), Eq(LValue{.type_name = "float", .is_entire_expr_status_or = false, .qtype = GetQType<float>(), .kind = LValueKind::kInput})); EXPECT_THAT(op.assignments[input_x_id].rvalue(), Eq(RValue::CreateInput())); EXPECT_FALSE(op.assignments[input_x_id].is_inlinable()); int64_t input_y_id = op.inputs["y"]; EXPECT_THAT(op.assignments[input_y_id].lvalue(), Eq(LValue{.type_name = "float", .is_entire_expr_status_or = false, .qtype = GetQType<float>(), .kind = LValueKind::kInput})); EXPECT_THAT(op.assignments[input_y_id].rvalue(), Eq(RValue::CreateInput())); EXPECT_TRUE(op.assignments[input_y_id].is_inlinable()); ASSERT_EQ(op.assignments.size(), 2 + 2 ); int64_t tmp0_id = 1; ASSERT_LT(tmp0_id, op.assignments.size()); EXPECT_TRUE(op.assignments[tmp0_id].is_inlinable()); EXPECT_THAT(op.assignments[tmp0_id].lvalue(), Eq(LValue{.type_name = "float", .is_entire_expr_status_or = false, .qtype = GetQType<float>(), .kind = LValueKind::kLocal})); EXPECT_THAT(op.assignments[tmp0_id].rvalue(), Eq(RValue{.kind = RValueKind::kFunctionCall, .operator_returns_status_or = false, .code = "::arolla::AddOp{}", .argument_ids = {input_x_id, input_x_id}})); int64_t tmp1_id = 3; EXPECT_THAT(op.assignments[tmp1_id].lvalue(), Eq(LValue{.type_name = "float", .is_entire_expr_status_or = false, .qtype = GetQType<float>(), .kind = LValueKind::kLocal})); EXPECT_THAT(op.assignments[tmp1_id].rvalue(), Eq(RValue{.kind = RValueKind::kFunctionCall, .operator_returns_status_or = false, .code = "::arolla::AddOp{}", .argument_ids = {tmp0_id, input_y_id}})); EXPECT_EQ(op.output_id, tmp1_id); EXPECT_THAT(op.function_entry_points(), UnorderedElementsAre(Pair(tmp0_id, 0), Pair(tmp1_id, 1))); } TEST_F(CodegenTest, SmokeWithStatusOrTest) { ASSERT_OK_AND_ASSIGN(auto x, WithQTypeAnnotation(Leaf("x"), GetQType<float>())); ASSERT_OK_AND_ASSIGN(auto y, WithQTypeAnnotation(Leaf("y"), GetQType<float>())); ASSERT_OK_AND_ASSIGN(auto floor_div, expr::CallOp("math.floordiv", {x, y})); ASSERT_OK_AND_ASSIGN(auto expr, expr::CallOp("math.add", {floor_div, y})); ASSERT_OK_AND_ASSIGN( OperatorCodegenData op, GenerateOperatorCode(expr, true)); EXPECT_THAT(op.headers, ElementsAre( "arolla/" "qexpr/operators/math/arithmetic.h")); EXPECT_THAT(op.deps, ElementsAre(" "arolla/" "qexpr/operators/math:lib")); EXPECT_THAT(op.inputs, ElementsAre(Pair("x", _), Pair("y", _))); int64_t input_x_id = op.inputs["x"]; EXPECT_THAT(op.assignments[input_x_id].lvalue(), Eq(LValue{.type_name = "float", .is_entire_expr_status_or = false, .is_local_expr_status_or = false, .qtype = GetQType<float>(), .kind = LValueKind::kInput})); EXPECT_THAT(op.assignments[input_x_id].rvalue(), Eq(RValue::CreateInput())); int64_t input_y_id = op.inputs["y"]; EXPECT_THAT(op.assignments[input_y_id].lvalue(), Eq(LValue{.type_name = "float", .is_entire_expr_status_or = false, .is_local_expr_status_or = false, .qtype = GetQType<float>(), .kind = LValueKind::kInput})); EXPECT_THAT(op.assignments[input_y_id].rvalue(), Eq(RValue::CreateInput())); EXPECT_EQ(op.assignments.size(), 2 + 2 ); int64_t tmp0_id = 2; ASSERT_LT(tmp0_id, op.assignments.size()); EXPECT_TRUE(op.assignments[tmp0_id].is_inlinable()); EXPECT_THAT(op.assignments[tmp0_id].lvalue(), Eq(LValue{.type_name = "float", .is_entire_expr_status_or = true, .is_local_expr_status_or = true, .qtype = GetQType<float>(), .kind = LValueKind::kLocal})); EXPECT_THAT(op.assignments[tmp0_id].rvalue(), Eq(RValue{.kind = RValueKind::kFunctionCall, .operator_returns_status_or = true, .code = "::arolla::FloorDivOp{}", .argument_ids = {input_x_id, input_y_id}})); int64_t tmp1_id = 3; ASSERT_LT(tmp1_id, op.assignments.size()); EXPECT_TRUE(op.assignments[tmp1_id].is_inlinable()); EXPECT_THAT(op.assignments[tmp1_id].lvalue(), Eq(LValue{.type_name = "float", .is_entire_expr_status_or = true, .is_local_expr_status_or = true, .qtype = GetQType<float>(), .kind = LValueKind::kLocal})); EXPECT_THAT(op.assignments[tmp1_id].rvalue(), Eq(RValue{.kind = RValueKind::kFunctionCall, .operator_returns_status_or = false, .code = "::arolla::AddOp{}", .argument_ids = {tmp0_id, input_y_id}})); EXPECT_EQ(op.output_id, tmp1_id); } TEST_F(CodegenTest, SmokeWithContextTest) { ASSERT_OK_AND_ASSIGN( auto x, WithQTypeAnnotation(Leaf("x"), GetDenseArrayQType<float>())); ASSERT_OK_AND_ASSIGN( auto y, WithQTypeAnnotation(Leaf("y"), GetDenseArrayQType<float>())); ASSERT_OK_AND_ASSIGN(auto expr, expr::CallOp("math.add", {x, y})); ASSERT_OK_AND_ASSIGN( OperatorCodegenData op, GenerateOperatorCode(expr, true)); EXPECT_THAT(op.headers, ElementsAre( "arolla/" "dense_array/qtype/types.h", "arolla/" "qexpr/operators/dense_array/lifter.h", "arolla/" "qexpr/operators/math/arithmetic.h")); EXPECT_THAT(op.deps, ElementsAre( " "arolla/" "dense_array/qtype", " "arolla/" "qexpr/operators/dense_array:lib", " "arolla/" "qexpr/operators/math:lib")); EXPECT_THAT(op.inputs, ElementsAre(Pair("x", _), Pair("y", _))); int64_t input_x_id = op.inputs["x"]; EXPECT_THAT(op.assignments[input_x_id].lvalue(), Eq(LValue{.type_name = "::arolla::DenseArray<float>", .is_entire_expr_status_or = false, .is_local_expr_status_or = false, .qtype = GetDenseArrayQType<float>(), .kind = LValueKind::kInput})); EXPECT_THAT(op.assignments[input_x_id].rvalue(), Eq(RValue::CreateInput())); int64_t input_y_id = op.inputs["y"]; EXPECT_THAT(op.assignments[input_y_id].lvalue(), Eq(LValue{.type_name = "::arolla::DenseArray<float>", .is_entire_expr_status_or = false, .is_local_expr_status_or = false, .qtype = GetDenseArrayQType<float>(), .kind = LValueKind::kInput})); EXPECT_THAT(op.assignments[input_y_id].rvalue(), Eq(RValue::CreateInput())); EXPECT_EQ(op.assignments.size(), 1 + 2 ); int64_t tmp0_id = 2; ASSERT_LT(tmp0_id, op.assignments.size()); EXPECT_TRUE(op.assignments[tmp0_id].is_inlinable()); EXPECT_THAT(op.assignments[tmp0_id].lvalue(), Eq(LValue{.type_name = "::arolla::DenseArray<float>", .is_entire_expr_status_or = true, .is_local_expr_status_or = true, .qtype = GetDenseArrayQType<float>(), .kind = LValueKind::kLocal})); EXPECT_THAT(op.assignments[tmp0_id].rvalue(), Eq(RValue{.kind = RValueKind::kFunctionWithContextCall, .operator_returns_status_or = true, .code = "::arolla::DenseArrayLifter<::arolla::AddOp, " "::arolla::meta::type_list<float, float>, " "true>{}", .argument_ids = {input_x_id, input_y_id}})); EXPECT_EQ(op.output_id, tmp0_id); } TEST_F(CodegenTest, SmokeTestWithExport) { ASSERT_OK_AND_ASSIGN( auto expr, expr::CallOp( "math.add", {WithExportAnnotation( expr::CallOp("math.add", {WithQTypeAnnotation(Leaf("x"), GetQType<float>()), Literal(1.f)}), "output"), WithQTypeAnnotation(Leaf("y"), GetQType<float>())})); ASSERT_OK_AND_ASSIGN( OperatorCodegenData op, GenerateOperatorCode(expr, true)); EXPECT_THAT(op.headers, ElementsAre( "arolla/" "qexpr/operators/math/arithmetic.h")); EXPECT_THAT(op.deps, ElementsAre(" "arolla/" "qexpr/operators/math:lib")); EXPECT_THAT(op.inputs, ElementsAre(Pair("x", _), Pair("y", _))); int64_t input_x_id = op.inputs["x"]; EXPECT_THAT(op.assignments[input_x_id].lvalue(), Eq(LValue{.type_name = "float", .is_entire_expr_status_or = false, .qtype = GetQType<float>(), .kind = LValueKind::kInput})); EXPECT_THAT(op.assignments[input_x_id].rvalue(), Eq(RValue::CreateInput())); int64_t input_y_id = op.inputs["y"]; EXPECT_THAT(op.assignments[input_y_id].lvalue(), Eq(LValue{.type_name = "float", .is_entire_expr_status_or = false, .qtype = GetQType<float>(), .kind = LValueKind::kInput})); EXPECT_THAT(op.assignments[input_y_id].rvalue(), Eq(RValue::CreateInput())); EXPECT_EQ(op.assignments.size(), 4 + 2 ); int64_t literal_id = MinUnused({input_x_id, input_y_id}); ASSERT_LT(literal_id, op.assignments.size()); EXPECT_THAT(op.assignments[literal_id].lvalue(), Eq(LValue{.type_name = "float", .is_entire_expr_status_or = false, .qtype = GetQType<float>(), .kind = LValueKind::kLiteral})); EXPECT_THAT(op.assignments[literal_id].rvalue(), Eq(RValue::CreateLiteral("float{1.}"))); int64_t tmp0_id = MinUnused({input_x_id, input_y_id, literal_id}); ASSERT_LT(tmp0_id, op.assignments.size()); EXPECT_TRUE(op.assignments[tmp0_id].is_inlinable()) << "used for output, but export is inside of the expression"; EXPECT_THAT(op.assignments[tmp0_id].lvalue(), Eq(LValue{.type_name = "float", .is_entire_expr_status_or = false, .qtype = GetQType<float>(), .kind = LValueKind::kLocal})); EXPECT_THAT(op.assignments[tmp0_id].rvalue(), Eq(RValue{.kind = RValueKind::kFunctionCall, .operator_returns_status_or = false, .code = "::arolla::AddOp{}", .argument_ids = {input_x_id, literal_id}})); int64_t tmp1_id = MinUnused({input_x_id, input_y_id, literal_id, tmp0_id}); ASSERT_LT(tmp1_id, op.assignments.size()); EXPECT_TRUE(op.assignments[tmp1_id].is_inlinable()); EXPECT_THAT(op.assignments[tmp1_id].lvalue(), Eq(LValue{.type_name = "float", .is_entire_expr_status_or = false, .qtype = GetQType<float>(), .kind = LValueKind::kLocal})); EXPECT_THAT(op.assignments[tmp1_id].rvalue(), Eq(RValue{.kind = RValueKind::kOutput, .operator_returns_status_or = false, .code = "0", .argument_ids = {tmp0_id}})); int64_t tmp2_id = 5; EXPECT_THAT(op.assignments[tmp2_id].lvalue(), Eq(LValue{.type_name = "float", .is_entire_expr_status_or = false, .qtype = GetQType<float>(), .kind = LValueKind::kLocal})); EXPECT_THAT(op.assignments[tmp2_id].rvalue(), Eq(RValue{.kind = RValueKind::kFunctionCall, .operator_returns_status_or = false, .code = "::arolla::AddOp{}", .argument_ids = {tmp1_id, input_y_id}})); EXPECT_EQ(op.output_id, tmp2_id); EXPECT_THAT(op.side_outputs, ElementsAre(Pair("output", tmp1_id))); } TEST_F(CodegenTest, SmokeTestWithDerivedQTypeDowncast) { ASSERT_OK_AND_ASSIGN( auto expr, expr::CallOp("derived_qtype.downcast", {Literal(GetWeakFloatQType()), WithQTypeAnnotation(Leaf("x"), GetQType<double>())})); ASSERT_OK_AND_ASSIGN( OperatorCodegenData op, GenerateOperatorCode(expr, true)); EXPECT_THAT(op.inputs, ElementsAre(Pair("x", _))); int64_t input_x_id = op.inputs["x"]; EXPECT_THAT(op.assignments[input_x_id].lvalue(), Eq(LValue{.type_name = "double", .is_entire_expr_status_or = false, .qtype = GetQType<double>(), .kind = LValueKind::kInput})); EXPECT_THAT(op.assignments[input_x_id].rvalue(), Eq(RValue::CreateInput())); EXPECT_EQ(op.assignments.size(), 1 + 1 ); int64_t tmp0_id = MinUnused({input_x_id}); ASSERT_LT(tmp0_id, op.assignments.size()); EXPECT_TRUE(op.assignments[tmp0_id].is_inlinable()) << "used for output, but export is inside of the expression"; EXPECT_THAT(op.assignments[tmp0_id].lvalue(), Eq(LValue{.type_name = "double", .is_entire_expr_status_or = false, .qtype = GetQType<double>(), .kind = LValueKind::kLocal})); EXPECT_THAT(op.assignments[tmp0_id].rvalue(), Eq(RValue{.kind = RValueKind::kFirst, .operator_returns_status_or = false, .code = "", .argument_ids = {input_x_id}})); EXPECT_EQ(op.output_id, tmp0_id); } TEST_F(CodegenTest, SmokeTestWithExportUnusedForMainOutput) { ASSERT_OK_AND_ASSIGN( auto get_first_op, expr::MakeLambdaOperator(expr::ExprOperatorSignature({{"x"}, {"y"}}), expr::Placeholder("x"))); ASSERT_OK_AND_ASSIGN( auto expr, expr::CallOp( get_first_op, {WithExportAnnotation( WithQTypeAnnotation(Leaf("y"), GetQType<float>()), "named_main_output"), WithExportAnnotation( expr::CallOp("math.add", {WithQTypeAnnotation(Leaf("x"), GetQType<float>()), Literal(1.f)}), "output")})); ASSERT_OK_AND_ASSIGN( OperatorCodegenData op, GenerateOperatorCode(expr, true)); EXPECT_THAT(op.headers, ElementsAre( "arolla/" "qexpr/operators/math/arithmetic.h")); EXPECT_THAT(op.deps, ElementsAre(" "arolla/" "qexpr/operators/math:lib")); EXPECT_THAT(op.inputs, ElementsAre(Pair("x", _), Pair("y", _))); int64_t input_x_id = op.inputs["x"]; EXPECT_THAT(op.assignments[input_x_id].lvalue(), Eq(LValue{.type_name = "float", .is_entire_expr_status_or = false, .qtype = GetQType<float>(), .kind = LValueKind::kInput})); EXPECT_THAT(op.assignments[input_x_id].rvalue(), Eq(RValue::CreateInput())); int64_t input_y_id = op.inputs["y"]; EXPECT_THAT(op.assignments[input_y_id].lvalue(), Eq(LValue{.type_name = "float", .is_entire_expr_status_or = false, .qtype = GetQType<float>(), .kind = LValueKind::kInput})); EXPECT_THAT(op.assignments[input_y_id].rvalue(), Eq(RValue::CreateInput())); EXPECT_EQ(op.assignments.size(), 5 + 2 ); int64_t tmp0_id = MinUnused({input_x_id, input_y_id}); ASSERT_LT(tmp0_id, op.assignments.size()); EXPECT_TRUE(op.assignments[tmp0_id].is_inlinable()) << "used for output, but export is inside of the expression"; EXPECT_THAT(op.assignments[tmp0_id].lvalue(), Eq(LValue{.type_name = "float", .is_entire_expr_status_or = false, .qtype = GetQType<float>(), .kind = LValueKind::kLocal})); EXPECT_THAT(op.assignments[tmp0_id].rvalue(), Eq(RValue{.kind = RValueKind::kOutput, .operator_returns_status_or = false, .code = "0", .argument_ids = {input_y_id}})); int64_t literal_id = MinUnused({input_x_id, input_y_id, tmp0_id}); ASSERT_LT(literal_id, op.assignments.size()); EXPECT_THAT(op.assignments[literal_id].lvalue(), Eq(LValue{.type_name = "float", .is_entire_expr_status_or = false, .qtype = GetQType<float>(), .kind = LValueKind::kLiteral})); EXPECT_THAT(op.assignments[literal_id].rvalue(), Eq(RValue::CreateLiteral("float{1.}"))); int64_t tmp1_id = MinUnused({input_x_id, input_y_id, literal_id, tmp0_id}); ASSERT_LT(tmp1_id, op.assignments.size()); EXPECT_TRUE(op.assignments[tmp1_id].is_inlinable()); EXPECT_THAT(op.assignments[tmp1_id].lvalue(), Eq(LValue{.type_name = "float", .is_entire_expr_status_or = false, .qtype = GetQType<float>(), .kind = LValueKind::kLocal})); EXPECT_THAT(op.assignments[tmp1_id].rvalue(), Eq(RValue{.kind = RValueKind::kFunctionCall, .operator_returns_status_or = false, .code = "::arolla::AddOp{}", .argument_ids = {input_x_id, literal_id}})); int64_t tmp2_id = 5; EXPECT_THAT(op.assignments[tmp2_id].lvalue(), Eq(LValue{.type_name = "float", .is_entire_expr_status_or = false, .qtype = GetQType<float>(), .kind = LValueKind::kLocal})); EXPECT_THAT(op.assignments[tmp2_id].rvalue(), Eq(RValue{.kind = RValueKind::kOutput, .operator_returns_status_or = false, .code = "1", .argument_ids = {tmp1_id}})); int64_t tmp3_id = 6; EXPECT_THAT(op.assignments[tmp3_id].lvalue(), Eq(LValue{.type_name = "float", .is_entire_expr_status_or = false, .qtype = GetQType<float>(), .kind = LValueKind::kLocal})); EXPECT_THAT(op.assignments[tmp3_id].rvalue(), Eq(RValue{.kind = RValueKind::kFirst, .operator_returns_status_or = false, .code = "", .argument_ids = {tmp0_id, tmp2_id}})); EXPECT_EQ(op.output_id, tmp3_id); EXPECT_THAT(op.side_outputs, ElementsAre(Pair("named_main_output", tmp0_id), Pair("output", tmp2_id))); } TEST_F(CodegenTest, LambdaAndFunctionSinityTest) { auto lx = WithQTypeAnnotation(Leaf("x"), GetQType<float>()); auto ly = WithQTypeAnnotation(Leaf("y"), GetQType<float>()); auto x = expr::CallOp("math.add", {lx, ly}); auto y = expr::CallOp("math.subtract", {lx, ly}); auto a = expr::CallOp("math.add", {x, y}); auto b = expr::CallOp("math.subtract", {x, y}); constexpr int64_t kChainLength = 500; for (int i = 0; i != kChainLength; ++i) { auto na = expr::CallOp("math.mod", {a, x}); x = a; a = na; auto nb = expr::CallOp("math.mod", {b, y}); y = b; b = nb; } ASSERT_OK_AND_ASSIGN(auto expr, expr::CallOp("math.add", {a, b})); ASSERT_OK_AND_ASSIGN( OperatorCodegenData op, GenerateOperatorCode(expr, true)); EXPECT_THAT(op.functions.size(), Eq(3)); for (int i = 0; i != 2; ++i) { EXPECT_THAT(op.functions[i].assignment_ids, IsEmpty()) << i; } EXPECT_THAT(op.functions[2].assignment_ids.size(), Eq(4)); EXPECT_THAT(op.lambdas.size(), Eq(2)); EXPECT_THAT(op.lambdas[0].assignment_ids.size(), Eq(kChainLength - 1)); EXPECT_THAT(op.lambdas[1].assignment_ids.size(), Eq(kChainLength - 1)); } } }
2,407
#ifndef AROLLA_CODEGEN_EXPR_OPTIMIZATIONS_H_ #define AROLLA_CODEGEN_EXPR_OPTIMIZATIONS_H_ #include <string> #include "absl/flags/declare.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "arolla/expr/optimization/optimizer.h" ABSL_DECLARE_FLAG(std::string, arolla_codegen_optimizer_name); namespace arolla::codegen { absl::Status RegisterOptimization(absl::string_view optimization_name, expr::Optimizer optimizer); absl::StatusOr<expr::Optimizer> GetOptimizer(absl::string_view name); } #endif #include "arolla/codegen/expr/optimizations.h" #include <string> #include "absl/base/thread_annotations.h" #include "absl/container/flat_hash_map.h" #include "absl/flags/flag.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "absl/strings/string_view.h" #include "absl/synchronization/mutex.h" #include "arolla/expr/optimization/default/default_optimizer.h" #include "arolla/expr/optimization/optimizer.h" #include "arolla/util/indestructible.h" ABSL_FLAG(std::string, arolla_codegen_optimizer_name, "", "Name of the optimizer, which must be registered using " "RegisterOptimization at initialization time."); namespace arolla::codegen { namespace { struct OptimizationMap { absl::Mutex lock; absl::flat_hash_map<std::string, expr::Optimizer> optimizers ABSL_GUARDED_BY(lock); }; OptimizationMap& GetOptimizationMap() { static Indestructible<OptimizationMap> kOptMap; return *kOptMap; } } absl::Status RegisterOptimization(absl::string_view optimization_name, expr::Optimizer optimizer) { OptimizationMap& opt_map = GetOptimizationMap(); absl::MutexLock l(&opt_map.lock); if (opt_map.optimizers.contains(optimization_name)) { return absl::FailedPreconditionError(absl::StrFormat( "RegisterOptimization called twice for %s", optimization_name)); } opt_map.optimizers.emplace(std::string(optimization_name), optimizer); return absl::OkStatus(); } absl::StatusOr<expr::Optimizer> GetOptimizer(absl::string_view name) { if (name.empty()) { return expr::CodegenOptimizer(); } OptimizationMap& opt_map = GetOptimizationMap(); absl::MutexLock l(&opt_map.lock); if (auto it = opt_map.optimizers.find(name); it != opt_map.optimizers.end()) { return it->second; } return absl::NotFoundError( absl::StrFormat("unrecognized optimization name: %s", name)); } }
#include "arolla/codegen/expr/optimizations.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_node.h" #include "arolla/util/testing/status_matchers_backport.h" namespace arolla::codegen { namespace { using ::arolla::testing::IsOk; using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::StatusIs; using ::testing::_; using ::testing::HasSubstr; TEST(GetOptimizer, DefaultIsOk) { EXPECT_THAT(GetOptimizer(""), IsOkAndHolds(_)); } TEST(GetOptimizer, Unknown) { EXPECT_THAT(GetOptimizer("unknown_name").status(), StatusIs(absl::StatusCode::kNotFound, HasSubstr("unknown_name"))); } TEST(GetOptimizer, Register) { EXPECT_THAT(RegisterOptimization( "new_opt", [](expr::ExprNodePtr) -> absl::StatusOr<expr::ExprNodePtr> { return absl::InternalError("fake optimization"); }), IsOk()); ASSERT_OK_AND_ASSIGN(auto optimizer, GetOptimizer("new_opt")); EXPECT_THAT( optimizer(expr::Leaf("x")).status(), StatusIs(absl::StatusCode::kInternal, HasSubstr("fake optimization"))); } } }
2,408
#ifndef AROLLA_SEQUENCE_SEQUENCE_H_ #define AROLLA_SEQUENCE_SEQUENCE_H_ #include <algorithm> #include <cstddef> #include <memory> #include <utility> #include "absl/log/check.h" #include "absl/types/span.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/typed_ref.h" #include "arolla/util/api.h" #include "arolla/util/demangle.h" #include "arolla/util/fingerprint.h" #include "arolla/util/repr.h" namespace arolla { class AROLLA_API Sequence { public: Sequence() = default; Sequence(QTypePtr value_qtype, size_t size, std::shared_ptr<const void>&& data) : value_qtype_(value_qtype), size_(size), data_(std::move(data)) { DCHECK_NE(value_qtype, nullptr); } Sequence(const Sequence&) = default; Sequence(Sequence&&) = default; Sequence& operator=(const Sequence&) = default; Sequence& operator=(Sequence&&) = default; QTypePtr value_qtype() const; size_t size() const; const void* RawData() const; const void* RawAt(size_t i, size_t element_alloc_size) const; template <typename T> absl::Span<const T> UnsafeSpan() const; TypedRef GetRef(size_t i) const; Sequence subsequence(size_t offset, size_t count) const; private: QTypePtr value_qtype_ = GetNothingQType(); size_t size_ = 0; std::shared_ptr<const void> data_; }; inline QTypePtr Sequence::value_qtype() const { return value_qtype_; } inline size_t Sequence::size() const { return size_; } inline const void* Sequence::RawData() const { return data_.get(); } inline const void* Sequence::RawAt(size_t i, size_t element_alloc_size) const { DCHECK_LT(i, size_) << "index is out of range: " << i << " >= size=" << size_; DCHECK_EQ(element_alloc_size, value_qtype_->type_layout().AllocSize()) << "element size mismatched: expected " << value_qtype_->type_layout().AllocSize() << ", got " << element_alloc_size; return reinterpret_cast<const char*>(RawData()) + i * element_alloc_size; } template <typename T> absl::Span<const T> Sequence::UnsafeSpan() const { DCHECK(typeid(T) == value_qtype_->type_info()) << "element type mismatched: expected " << TypeName(value_qtype_->type_info()) << ", got " << TypeName<T>(); return absl::Span<const T>(reinterpret_cast<const T*>(data_.get()), size_); } inline TypedRef Sequence::GetRef(size_t i) const { DCHECK_LT(i, size_) << "index is out of range: " << i << " >= size=" << size_; const char* const data = reinterpret_cast<const char*>(data_.get()); return TypedRef::UnsafeFromRawPointer( value_qtype_, data + i * value_qtype_->type_layout().AllocSize()); } inline Sequence Sequence::subsequence(size_t offset, size_t count) const { DCHECK_LE(offset, size_) << "offset is out of range: " << offset << " > size=" << size_; count = std::min(count, size_ - offset); if (count == 0) { return Sequence(value_qtype_, 0, nullptr); } const char* const data = reinterpret_cast<const char*>(data_.get()); return Sequence( value_qtype_, count, std::shared_ptr<const void>( data_, data + offset * value_qtype_->type_layout().AllocSize())); } AROLLA_DECLARE_FINGERPRINT_HASHER_TRAITS(Sequence); AROLLA_DECLARE_REPR(Sequence); } #endif #include "arolla/sequence/sequence.h" #include <algorithm> #include <cstddef> #include <sstream> #include <utility> #include "arolla/qtype/qtype.h" #include "arolla/util/fingerprint.h" #include "arolla/util/repr.h" namespace arolla { void FingerprintHasherTraits<Sequence>::operator()( FingerprintHasher* hasher, const Sequence& sequence) const { const QTypePtr value_qtype = sequence.value_qtype(); const size_t value_byte_size = value_qtype->type_layout().AllocSize(); hasher->Combine(value_qtype, sequence.size()); for (size_t i = 0; i < sequence.size(); ++i) { value_qtype->UnsafeCombineToFingerprintHasher( sequence.RawAt(i, value_byte_size), hasher); } } ReprToken ReprTraits<Sequence>::operator()(const Sequence& sequence) const { std::ostringstream result; result << "sequence("; const auto n = std::min<size_t>(sequence.size(), 10); for (size_t i = 0; i < n; ++i) { result << sequence.GetRef(i).Repr() << ", "; } if (n < sequence.size()) { result << "..., size=" << sequence.size() << ", "; } result << "value_qtype=" << sequence.value_qtype()->name() << ")"; return ReprToken{std::move(result).str()}; } }
#include "arolla/sequence/sequence.h" #include <algorithm> #include <cstdint> #include <utility> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/types/span.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/sequence/mutable_sequence.h" #include "arolla/util/fingerprint.h" #include "arolla/util/init_arolla.h" #include "arolla/util/repr.h" #include "arolla/util/testing/repr_token_eq.h" #include "arolla/util/unit.h" namespace arolla { namespace { using ::arolla::testing::ReprTokenEq; class SequenceTest : public ::testing::Test { void SetUp() override { ASSERT_OK(InitArolla()); } }; TEST_F(SequenceTest, DefaultConstructor) { Sequence seq; EXPECT_EQ(seq.value_qtype(), GetNothingQType()); EXPECT_EQ(seq.size(), 0); EXPECT_EQ(seq.RawData(), nullptr); } TEST_F(SequenceTest, MakeSize1) { ASSERT_OK_AND_ASSIGN(auto mutable_seq, MutableSequence::Make(GetQType<int32_t>(), 1)); const auto seq = std::move(mutable_seq).Finish(); EXPECT_EQ(seq.value_qtype(), GetQType<int32_t>()); EXPECT_EQ(seq.size(), 1); EXPECT_NE(seq.RawData(), nullptr); } TEST_F(SequenceTest, RawAt) { ASSERT_OK_AND_ASSIGN(auto mutable_seq, MutableSequence::Make(GetQType<int32_t>(), 100)); const auto seq = std::move(mutable_seq).Finish(); for (int i = 0; i < 100; i += 10) { EXPECT_EQ(seq.RawAt(i, sizeof(int32_t)), static_cast<const char*>(seq.RawData()) + i * sizeof(int32_t)); } } TEST_F(SequenceTest, UnsafeSpan) { ASSERT_OK_AND_ASSIGN(auto mutable_seq, MutableSequence::Make(GetQType<float>(), 100)); const auto seq = std::move(mutable_seq).Finish(); absl::Span<const float> span = seq.UnsafeSpan<float>(); EXPECT_EQ(span.data(), seq.RawData()); EXPECT_EQ(span.size(), 100); } TEST_F(SequenceTest, GetRef) { ASSERT_OK_AND_ASSIGN(auto mutable_seq, MutableSequence::Make(GetQType<double>(), 100)); const auto seq = std::move(mutable_seq).Finish(); for (int i = 0; i < 100; i += 10) { auto ref = seq.GetRef(i); EXPECT_EQ(ref.GetType(), GetQType<double>()); EXPECT_EQ(ref.GetRawPointer(), seq.RawAt(i, sizeof(double))); } } TEST_F(SequenceTest, subsequence) { ASSERT_OK_AND_ASSIGN(auto mutable_seq, MutableSequence::Make(GetQType<int32_t>(), 100)); const auto seq = std::move(mutable_seq).Finish(); for (int offset = 0; offset < 100; offset += 10) { for (int count = 10; count <= 100; count += 30) { const auto subseq = seq.subsequence(offset, count); EXPECT_EQ(subseq.value_qtype(), GetQType<int32_t>()); EXPECT_EQ(subseq.size(), std::min(count, 100 - offset)); EXPECT_EQ( static_cast<const char*>(subseq.RawData()), static_cast<const char*>(seq.RawData()) + offset * sizeof(int32_t)); } } for (int offset = 0; offset < 100; offset += 10) { const auto subseq = seq.subsequence(offset, 0); EXPECT_EQ(subseq.size(), 0); EXPECT_EQ(subseq.RawData(), nullptr); EXPECT_EQ(subseq.value_qtype(), GetQType<int32_t>()); } for (int count = 0; count <= 100; count += 25) { const auto subseq = seq.subsequence(100, count); EXPECT_EQ(subseq.size(), 0); EXPECT_EQ(subseq.RawData(), nullptr); EXPECT_EQ(subseq.value_qtype(), GetQType<int32_t>()); } } #ifndef NDEBUG using SequenceDeathTest = SequenceTest; TEST_F(SequenceDeathTest, RawAtDCheckIndexIsOutOfRange) { ASSERT_OK_AND_ASSIGN(auto mutable_seq, MutableSequence::Make(GetQType<int32_t>(), 100)); const auto seq = std::move(mutable_seq).Finish(); EXPECT_DEATH(seq.RawAt(100, sizeof(int32_t)), "index is out of range: 100 >= size=100"); } TEST_F(SequenceDeathTest, RawAtDCheckElementSizeMismatch) { ASSERT_OK_AND_ASSIGN(auto mutable_seq, MutableSequence::Make(GetQType<int32_t>(), 100)); const auto seq = std::move(mutable_seq).Finish(); EXPECT_DEATH(seq.RawAt(0, 3), "element size mismatched: expected 4, got 3"); } TEST_F(SequenceDeathTest, UnsafeSpanDCheckElementTypeMismatch) { ASSERT_OK_AND_ASSIGN(auto mutable_seq, MutableSequence::Make(GetQType<int>(), 100)); const auto seq = std::move(mutable_seq).Finish(); EXPECT_DEATH(seq.UnsafeSpan<float>(), "element type mismatched: expected int, got float"); } TEST_F(SequenceDeathTest, GetRefDCheckIndexIsOutOfRange) { ASSERT_OK_AND_ASSIGN(auto mutable_seq, MutableSequence::Make(GetQType<int32_t>(), 100)); const auto seq = std::move(mutable_seq).Finish(); EXPECT_DEATH(seq.GetRef(100), "index is out of range: 100 >= size=100"); } #endif TEST_F(SequenceTest, ReprEmpty) { EXPECT_THAT(GenReprToken(Sequence()), ReprTokenEq("sequence(value_qtype=NOTHING)")); } TEST_F(SequenceTest, Repr) { ASSERT_OK_AND_ASSIGN(auto mutable_seq, MutableSequence::Make(GetQTypeQType(), 4)); auto mutable_span = mutable_seq.UnsafeSpan<QTypePtr>(); mutable_span[0] = GetQType<Unit>(); mutable_span[1] = GetQType<bool>(); mutable_span[2] = GetQType<int32_t>(); mutable_span[3] = GetQType<float>(); auto seq = std::move(mutable_seq).Finish(); EXPECT_THAT( GenReprToken(seq), ReprTokenEq( "sequence(UNIT, BOOLEAN, INT32, FLOAT32, value_qtype=QTYPE)")); } TEST_F(SequenceTest, ReprLarge) { ASSERT_OK_AND_ASSIGN(auto mutable_seq, MutableSequence::Make(GetQTypeQType(), 11)); for (auto& x : mutable_seq.UnsafeSpan<QTypePtr>()) { x = GetQType<Unit>(); } auto seq = std::move(mutable_seq).Finish(); EXPECT_THAT( GenReprToken(seq), ReprTokenEq( "sequence(UNIT, UNIT, UNIT, UNIT, UNIT, UNIT, UNIT, UNIT, UNIT, " "UNIT, ..., size=11, value_qtype=QTYPE)")); } TEST_F(SequenceTest, Fingerprint) { std::vector<Sequence> sequences; { sequences.push_back(Sequence()); } { ASSERT_OK_AND_ASSIGN(auto mutable_seq, MutableSequence::Make(GetQTypeQType(), 0)); sequences.push_back(std::move(mutable_seq).Finish()); } { ASSERT_OK_AND_ASSIGN(auto mutable_seq, MutableSequence::Make(GetQType<int32_t>(), 2)); auto mutable_span = mutable_seq.UnsafeSpan<int32_t>(); mutable_span[0] = 0; mutable_span[1] = 1; sequences.push_back(std::move(mutable_seq).Finish()); } { ASSERT_OK_AND_ASSIGN(auto mutable_seq, MutableSequence::Make(GetQType<int32_t>(), 2)); auto mutable_span = mutable_seq.UnsafeSpan<int32_t>(); mutable_span[0] = 0; mutable_span[1] = 0; sequences.push_back(std::move(mutable_seq).Finish()); } for (auto& s0 : sequences) { for (auto& s1 : sequences) { const auto f0 = FingerprintHasher("salt").Combine(s0).Finish(); const auto f1 = FingerprintHasher("salt").Combine( Sequence(s1)).Finish(); if (&s0 == &s1) { EXPECT_EQ(f0, f1) << Repr(s0) << ".fingerprint != " << Repr(s1) << ".fingerprint"; } else { EXPECT_NE(f0, f1) << Repr(s0) << ".fingerprint != " << Repr(s1) << ".fingerprint"; } } } } } }
2,409
#ifndef AROLLA_SEQUENCE_SEQUENCE_QTYPE_H_ #define AROLLA_SEQUENCE_SEQUENCE_QTYPE_H_ #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" namespace arolla { bool IsSequenceQType(const QType* qtype); QTypePtr GetSequenceQType(QTypePtr value_qtype); template <typename T> QTypePtr GetSequenceQType() { return GetSequenceQType(GetQType<T>()); } } #endif #include "arolla/sequence/sequence_qtype.h" #include <memory> #include <string> #include "absl/base/thread_annotations.h" #include "absl/container/flat_hash_map.h" #include "absl/synchronization/mutex.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/simple_qtype.h" #include "arolla/sequence/sequence.h" #include "arolla/util/fast_dynamic_downcast_final.h" #include "arolla/util/indestructible.h" #include "arolla/util/meta.h" namespace arolla { namespace { class SequenceQType final : public SimpleQType { public: explicit SequenceQType(QTypePtr value_qtype) : SimpleQType(meta::type<Sequence>(), "SEQUENCE[" + std::string(value_qtype->name()) + "]", value_qtype, "::arolla::SequenceQType") {} }; class SequenceQTypeRegistry { public: QTypePtr GetSequenceQType(QTypePtr value_qtype) { absl::WriterMutexLock l(&lock_); auto& result = registry_[value_qtype]; if (!result) { result = std::make_unique<SequenceQType>(value_qtype); } return result.get(); } private: absl::Mutex lock_; absl::flat_hash_map<QTypePtr, std::unique_ptr<SequenceQType>> registry_ ABSL_GUARDED_BY(lock_); }; } bool IsSequenceQType(const QType* qtype) { return fast_dynamic_downcast_final<const SequenceQType*>(qtype) != nullptr; } QTypePtr GetSequenceQType(QTypePtr value_qtype) { static Indestructible<SequenceQTypeRegistry> registry; return registry->GetSequenceQType(value_qtype); } }
#include "arolla/sequence/sequence_qtype.h" #include <cstdint> #include <utility> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/typed_value.h" #include "arolla/sequence/mutable_sequence.h" #include "arolla/sequence/sequence.h" #include "arolla/util/init_arolla.h" #include "arolla/util/testing/repr_token_eq.h" namespace arolla { namespace { using ::arolla::testing::ReprTokenEq; class SequenceQTypeTest : public ::testing::Test { void SetUp() override { ASSERT_OK(InitArolla()); } }; TEST_F(SequenceQTypeTest, Basics) { const auto* qtype = GetSequenceQType<QTypePtr>(); EXPECT_EQ(qtype->name(), "SEQUENCE[QTYPE]"); EXPECT_EQ(qtype->type_info(), typeid(Sequence)); EXPECT_EQ(qtype->type_layout().AllocSize(), sizeof(Sequence)); EXPECT_EQ(qtype->type_layout().AllocAlignment().value, alignof(Sequence)); EXPECT_TRUE(qtype->type_fields().empty()); EXPECT_EQ(qtype->value_qtype(), GetQTypeQType()); EXPECT_EQ(qtype->qtype_specialization_key(), "::arolla::SequenceQType"); } TEST_F(SequenceQTypeTest, IsSequenceQType) { EXPECT_TRUE(IsSequenceQType(GetSequenceQType<QTypePtr>())); EXPECT_TRUE(IsSequenceQType(GetSequenceQType<int32_t>())); EXPECT_TRUE(IsSequenceQType(GetSequenceQType<float>())); EXPECT_FALSE(IsSequenceQType(GetQTypeQType())); EXPECT_FALSE(IsSequenceQType(GetQType<int32_t>())); EXPECT_FALSE(IsSequenceQType(GetQType<float>())); } TEST_F(SequenceQTypeTest, TypedValue) { ASSERT_OK_AND_ASSIGN(auto mutable_seq, MutableSequence::Make(GetQType<int32_t>(), 3)); auto mutable_span = mutable_seq.UnsafeSpan<int32_t>(); mutable_span[0] = 1; mutable_span[1] = 2; mutable_span[2] = 3; ASSERT_OK_AND_ASSIGN(auto typed_value, TypedValue::FromValueWithQType( std::move(mutable_seq).Finish(), GetSequenceQType<int32_t>())); EXPECT_EQ(typed_value.GetType()->name(), "SEQUENCE[INT32]"); EXPECT_THAT(typed_value.GenReprToken(), ReprTokenEq("sequence(1, 2, 3, value_qtype=INT32)")); } } }
2,410
#ifndef AROLLA_SEQUENCE_MUTABLE_SEQUENCE_H_ #define AROLLA_SEQUENCE_MUTABLE_SEQUENCE_H_ #include <cstddef> #include <memory> #include <utility> #include "absl/log/check.h" #include "absl/status/statusor.h" #include "absl/types/span.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/typed_ref.h" #include "arolla/sequence/sequence.h" #include "arolla/util/demangle.h" namespace arolla { class MutableSequence { public: static absl::StatusOr<MutableSequence> Make(QTypePtr value_qtype, size_t size); MutableSequence() = default; MutableSequence(const MutableSequence&) = delete; MutableSequence& operator=(const MutableSequence&) = delete; MutableSequence(MutableSequence&&) = default; MutableSequence& operator=(MutableSequence&&) = default; QTypePtr value_qtype() const; size_t size() const; void* RawData(); void* RawAt(size_t i, size_t element_alloc_size); template <typename T> absl::Span<T> UnsafeSpan(); TypedRef GetRef(size_t i); void UnsafeSetRef(size_t i, TypedRef value); [[nodiscard]] Sequence Finish() &&; private: QTypePtr value_qtype_ = GetNothingQType(); size_t size_ = 0; std::shared_ptr<void> data_; }; inline QTypePtr MutableSequence::value_qtype() const { return value_qtype_; } inline size_t MutableSequence::size() const { return size_; } inline void* MutableSequence::RawData() { return data_.get(); } inline void* MutableSequence::RawAt(size_t i, size_t element_alloc_size) { DCHECK_LT(i, size_) << "index is out of range: " << i << " >= size=" << size_; DCHECK_EQ(element_alloc_size, value_qtype_->type_layout().AllocSize()) << "element size mismatched: expected " << value_qtype_->type_layout().AllocSize() << ", got " << element_alloc_size; return reinterpret_cast<char*>(RawData()) + i * element_alloc_size; } template <typename T> absl::Span<T> MutableSequence::UnsafeSpan() { DCHECK(typeid(T) == value_qtype_->type_info()) << "element type mismatched: expected " << TypeName(value_qtype_->type_info()) << ", got " << TypeName<T>(); return absl::Span<T>(reinterpret_cast<T*>(data_.get()), size_); } inline TypedRef MutableSequence::GetRef(size_t i) { DCHECK_LT(i, size_) << "index is out of range: " << i << " >= size=" << size_; const char* const data = reinterpret_cast<const char*>(data_.get()); return TypedRef::UnsafeFromRawPointer( value_qtype_, data + i * value_qtype_->type_layout().AllocSize()); } inline void MutableSequence::UnsafeSetRef(size_t i, TypedRef value) { DCHECK_LT(i, size_) << "index is out of range: " << i << " >= size=" << size_; DCHECK_EQ(value.GetType(), value_qtype_) << "element qtype mismatched: expected " << value_qtype_->name() << ", got " << value.GetType()->name(); char* const data = reinterpret_cast<char*>(data_.get()); value_qtype_->UnsafeCopy(value.GetRawPointer(), data + i * value_qtype_->type_layout().AllocSize()); } inline Sequence MutableSequence::Finish() && { return Sequence(value_qtype_, size_, std::move(data_)); } } #endif #include "arolla/sequence/mutable_sequence.h" #include <cstddef> #include <memory> #include <utility> #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "arolla/memory/frame.h" #include "arolla/qtype/qtype.h" #include "arolla/util/memory.h" namespace arolla { absl::StatusOr<MutableSequence> MutableSequence::Make(QTypePtr value_qtype, size_t size) { DCHECK_NE(value_qtype, nullptr); DCHECK_GE(size, 0); MutableSequence result; result.value_qtype_ = value_qtype; if (size <= 0) { return result; } result.size_ = size; const auto& element_layout = value_qtype->type_layout(); const auto total_byte_size = element_layout.AllocSize() * size; auto memory = AlignedAlloc(element_layout.AllocAlignment(), total_byte_size); if (memory == nullptr) { return absl::InvalidArgumentError(absl::StrFormat( "AlignedAlloc has failed: alignment=%d, total_size=%d", element_layout.AllocAlignment().value, total_byte_size)); } element_layout.InitializeAlignedAllocN(memory.get(), size); auto memory_deleter = memory.get_deleter(); auto* memory_ptr = memory.release(); result.data_ = std::shared_ptr<void>( memory_ptr, [value_qtype, size, memory_deleter = std::move(memory_deleter)](void* ptr) { value_qtype->type_layout().DestroyAllocN(ptr, size); memory_deleter(ptr); }); return result; } }
#include "arolla/sequence/mutable_sequence.h" #include <cstddef> #include <cstdint> #include <utility> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/simple_qtype.h" #include "arolla/qtype/typed_ref.h" #include "arolla/qtype/typed_value.h" #include "arolla/sequence/sequence.h" #include "arolla/util/fingerprint.h" #include "arolla/util/init_arolla.h" namespace arolla { namespace { class MutableSequenceTest : public ::testing::Test { void SetUp() override { ASSERT_OK(InitArolla()); } }; TEST_F(MutableSequenceTest, DefaultConstructor) { MutableSequence seq; EXPECT_EQ(seq.value_qtype(), GetNothingQType()); EXPECT_EQ(seq.size(), 0); EXPECT_EQ(seq.RawData(), nullptr); } TEST_F(MutableSequenceTest, MakeEmpty) { ASSERT_OK_AND_ASSIGN(auto seq, MutableSequence::Make(GetQTypeQType(), 0)); EXPECT_EQ(seq.value_qtype(), GetQTypeQType()); EXPECT_EQ(seq.size(), 0); EXPECT_EQ(seq.RawData(), nullptr); } TEST_F(MutableSequenceTest, MakeSize1) { ASSERT_OK_AND_ASSIGN(auto seq, MutableSequence::Make(GetQType<int32_t>(), 1)); EXPECT_EQ(seq.value_qtype(), GetQType<int32_t>()); EXPECT_EQ(seq.size(), 1); EXPECT_NE(seq.RawData(), nullptr); } TEST_F(MutableSequenceTest, RawAt) { ASSERT_OK_AND_ASSIGN(auto seq, MutableSequence::Make(GetQType<int32_t>(), 100)); for (int i = 0; i < 100; i += 10) { EXPECT_EQ(seq.RawAt(i, sizeof(int32_t)), static_cast<char*>(seq.RawData()) + i * sizeof(int32_t)); } } TEST_F(MutableSequenceTest, UnsafeSpan) { ASSERT_OK_AND_ASSIGN(auto seq, MutableSequence::Make(GetQType<float>(), 100)); absl::Span<float> span = seq.UnsafeSpan<float>(); EXPECT_EQ(span.data(), seq.RawData()); EXPECT_EQ(span.size(), 100); } TEST_F(MutableSequenceTest, GetRef) { ASSERT_OK_AND_ASSIGN(auto seq, MutableSequence::Make(GetQType<double>(), 100)); for (int i = 0; i < 100; i += 10) { auto ref = seq.GetRef(i); EXPECT_EQ(ref.GetType(), GetQType<double>()); EXPECT_EQ(ref.GetRawPointer(), seq.RawAt(i, sizeof(double))); } } TEST_F(MutableSequenceTest, SetRef) { ASSERT_OK_AND_ASSIGN(auto seq, MutableSequence::Make(GetQType<double>(), 100)); for (int i = 0; i < 100; i += 10) { auto val = TypedValue::FromValue<double>(i); seq.UnsafeSetRef(i, val.AsRef()); } for (int i = 0; i < 100; i += 10) { EXPECT_EQ(seq.UnsafeSpan<double>()[i], i); } } TEST_F(MutableSequenceTest, Finish) { ASSERT_OK_AND_ASSIGN(auto seq, MutableSequence::Make(GetQType<int32_t>(), 100)); auto span = seq.UnsafeSpan<int32_t>(); for (size_t i = 0; i < span.size(); ++i) { span[i] = i; } const auto immutable_seq = std::move(seq).Finish(); EXPECT_EQ(immutable_seq.value_qtype(), GetQType<int32_t>()); EXPECT_EQ(immutable_seq.size(), 100); EXPECT_NE(immutable_seq.RawData(), nullptr); const auto immutable_span = immutable_seq.UnsafeSpan<int32_t>(); for (size_t i = 0; i < 100; i += 10) { EXPECT_EQ(immutable_span[i], i); } } struct CountedType { static int counter; CountedType() { counter += 1; } ~CountedType() { counter -= 1; } CountedType(const CountedType&) { counter += 1; } CountedType& operator=(const CountedType&) { counter += 1; return *this; } }; int CountedType::counter = 0; } AROLLA_DECLARE_FINGERPRINT_HASHER_TRAITS(CountedType); AROLLA_DECLARE_SIMPLE_QTYPE(COUNTED, CountedType); AROLLA_DEFINE_SIMPLE_QTYPE(COUNTED, CountedType); void FingerprintHasherTraits<CountedType>::operator()( FingerprintHasher* hasher, const CountedType&) const { hasher->Combine(absl::string_view("counted_value")); } namespace { TEST_F(MutableSequenceTest, ConstructorDestructor) { { ASSERT_OK_AND_ASSIGN(auto seq, MutableSequence::Make(GetQType<CountedType>(), 100)); EXPECT_EQ(CountedType::counter, 100); } EXPECT_EQ(CountedType::counter, 0); } TEST_F(MutableSequenceTest, ConstructorFinishDestructor) { Sequence immutable_seq; { ASSERT_OK_AND_ASSIGN(auto seq, MutableSequence::Make(GetQType<CountedType>(), 100)); EXPECT_EQ(CountedType::counter, 100); auto immutable_seq = std::move(seq).Finish(); EXPECT_EQ(CountedType::counter, 100); } EXPECT_EQ(CountedType::counter, 0); } #ifndef NDEBUG using MutableSequenceDeathTest = MutableSequenceTest; TEST_F(MutableSequenceDeathTest, RawAtDCheckIndexIsOutOfRange) { ASSERT_OK_AND_ASSIGN(auto seq, MutableSequence::Make(GetQType<int32_t>(), 100)); EXPECT_DEATH(seq.RawAt(100, sizeof(int32_t)), "index is out of range: 100 >= size=100"); } TEST_F(MutableSequenceDeathTest, RawAtDCheckElementSizeMismatch) { ASSERT_OK_AND_ASSIGN(auto seq, MutableSequence::Make(GetQType<int32_t>(), 100)); EXPECT_DEATH(seq.RawAt(0, 3), "element size mismatched: expected 4, got 3"); } TEST_F(MutableSequenceDeathTest, UnsafeSpanDCheckElementTypeMismatch) { ASSERT_OK_AND_ASSIGN(auto seq, MutableSequence::Make(GetQType<int>(), 100)); EXPECT_DEATH(seq.UnsafeSpan<float>(), "element type mismatched: expected int, got float"); } TEST_F(MutableSequenceDeathTest, GetRefDCheckIndexIsOutOfRange) { ASSERT_OK_AND_ASSIGN(auto seq, MutableSequence::Make(GetQType<int32_t>(), 100)); EXPECT_DEATH(seq.GetRef(100), "index is out of range: 100 >= size=100"); } TEST_F(MutableSequenceDeathTest, UnsafeSetRefDCheckIndexIsOutOfRange) { ASSERT_OK_AND_ASSIGN(auto seq, MutableSequence::Make(GetQType<int32_t>(), 100)); EXPECT_DEATH(seq.UnsafeSetRef(100, TypedRef::FromValue<int32_t>(0)), "index is out of range: 100 >= size=100"); } TEST_F(MutableSequenceDeathTest, UnsafeSetRefDCheckElementQTypeMismatch) { ASSERT_OK_AND_ASSIGN(auto seq, MutableSequence::Make(GetQType<int32_t>(), 100)); EXPECT_DEATH(seq.UnsafeSetRef(0, TypedRef::FromValue<float>(0.)), "element qtype mismatched: expected INT32, got FLOAT32"); } #endif } }
2,411
#ifndef AROLLA_IO_SLOT_LISTENER_H_ #define AROLLA_IO_SLOT_LISTENER_H_ #include <algorithm> #include <initializer_list> #include <memory> #include <optional> #include <string> #include <utility> #include <vector> #include "absl/base/nullability.h" #include "absl/container/flat_hash_map.h" #include "absl/functional/any_invocable.h" #include "absl/log/die_if_null.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "arolla/memory/frame.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/typed_slot.h" #include "arolla/util/status_macros_backport.h" namespace arolla { template <class OutputT> using BoundSlotListener = absl::AnyInvocable<absl::Status(ConstFramePtr, OutputT*) const>; class SlotListenerBase { public: virtual ~SlotListenerBase() = default; virtual absl::Nullable<const QType*> GetQTypeOf( absl::string_view name, absl::Nullable<const QType*> desired_qtype) const = 0; absl::Nullable<const QType*> GetQTypeOf(absl::string_view name) const { return GetQTypeOf(name, nullptr); } virtual std::vector<std::string> SuggestAvailableNames() const = 0; protected: absl::flat_hash_map<std::string, TypedSlot> FindSupportedSlots( const absl::flat_hash_map<std::string, TypedSlot>& slots) const; absl::Status ValidateSlotTypes( const absl::flat_hash_map<std::string, TypedSlot>& slots) const; }; template <class T> class SlotListener : public SlotListenerBase { public: using Output = T; absl::StatusOr<BoundSlotListener<Output>> Bind( const absl::flat_hash_map<std::string, TypedSlot>& slots) const { RETURN_IF_ERROR(ValidateSlotTypes(slots)); if (slots.empty()) { return BoundSlotListener<Output>( [](ConstFramePtr, Output*) { return absl::OkStatus(); }); } return BindImpl(slots); } absl::StatusOr<std::optional<BoundSlotListener<Output>>> PartialBind( const absl::flat_hash_map<std::string, TypedSlot>& slots) const { absl::flat_hash_map<std::string, TypedSlot> partial_slots = FindSupportedSlots(slots); if (partial_slots.empty()) { return std::nullopt; } return Bind(partial_slots); } protected: virtual absl::StatusOr<BoundSlotListener<Output>> BindImpl( const absl::flat_hash_map<std::string, TypedSlot>& slots) const = 0; }; template <class T> class StaticSlotListener : public SlotListener<T> { public: using Output = T; StaticSlotListener( std::initializer_list<std::pair<std::string, QTypePtr>> types_in_order) : StaticSlotListener(std::vector(types_in_order)) {} explicit StaticSlotListener( std::vector<std::pair<std::string, QTypePtr>> types_in_order) : types_in_order_(std::move(types_in_order)), types_(types_in_order_.begin(), types_in_order_.end()) {} explicit StaticSlotListener(absl::flat_hash_map<std::string, QTypePtr> types) : types_in_order_(types.begin(), types.end()), types_(std::move(types)) { std::sort(types_in_order_.begin(), types_in_order_.end()); } absl::Nullable<const QType*> GetQTypeOf( absl::string_view name, absl::Nullable<const QType*>) const final { auto it = types_.find(name); return it != types_.end() ? it->second : nullptr; } std::vector<std::string> SuggestAvailableNames() const final { std::vector<std::string> names; names.reserve(types_in_order_.size()); for (const auto& [name, _] : types_in_order_) { names.emplace_back(name); } return names; } absl::Span<const std::pair<std::string, QTypePtr>> types_in_order() const { return types_in_order_; } private: std::vector<std::pair<std::string, QTypePtr>> types_in_order_; absl::flat_hash_map<std::string, QTypePtr> types_; }; namespace slot_listener_impl { template <typename T> class NotOwningSlotListener final : public SlotListener<T> { public: explicit NotOwningSlotListener(const SlotListener<T>* slot_listener) : slot_listener_(ABSL_DIE_IF_NULL(slot_listener)) {} absl::Nullable<const QType*> GetQTypeOf( absl::string_view name, absl::Nullable<const QType*> desired_qtype) const final { return slot_listener_->GetQTypeOf(name, desired_qtype); } std::vector<std::string> SuggestAvailableNames() const final { return slot_listener_->SuggestAvailableNames(); } private: absl::StatusOr<BoundSlotListener<T>> BindImpl( const absl::flat_hash_map<std::string, TypedSlot>& slots) const final { return slot_listener_->Bind(slots); } const SlotListener<T>* slot_listener_; }; } template <typename T> std::unique_ptr<SlotListener<T>> MakeNotOwningSlotListener( const SlotListener<T>* slot_listener) { return std::unique_ptr<SlotListener<T>>( new slot_listener_impl::NotOwningSlotListener<T>(slot_listener)); } namespace slot_listener_impl { template <typename T> class SharedOwningSlotListener final : public SlotListener<T> { public: explicit SharedOwningSlotListener( std::shared_ptr<const SlotListener<T>> slot_listener) : slot_listener_(std::move(ABSL_DIE_IF_NULL(slot_listener))) {} absl::Nullable<const QType*> GetQTypeOf( absl::string_view name, absl::Nullable<const QType*> desired_qtype) const final { return slot_listener_->GetQTypeOf(name, desired_qtype); } std::vector<std::string> SuggestAvailableNames() const final { return slot_listener_->SuggestAvailableNames(); } private: absl::StatusOr<BoundSlotListener<T>> BindImpl( const absl::flat_hash_map<std::string, TypedSlot>& slots) const final { return slot_listener_->Bind(slots); } std::shared_ptr<const SlotListener<T>> slot_listener_; }; } template <typename T> std::unique_ptr<SlotListener<T>> MakeSharedOwningSlotListener( std::shared_ptr<const SlotListener<T>> slot_listener) { return std::unique_ptr<SlotListener<T>>( new slot_listener_impl::SharedOwningSlotListener<T>( std::move(slot_listener))); } } #endif #include "arolla/io/slot_listener.h" #include <set> #include <string> #include "absl/container/flat_hash_map.h" #include "absl/status/status.h" #include "absl/strings/str_format.h" #include "absl/strings/str_join.h" #include "absl/strings/string_view.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/typed_slot.h" #include "arolla/util/string.h" namespace arolla { absl::Status SlotListenerBase::ValidateSlotTypes( const absl::flat_hash_map<std::string, TypedSlot>& slots) const { absl::flat_hash_map<std::string, QTypePtr> types; types.reserve(slots.size()); std::set<absl::string_view> unknown_types; for (const auto& [name, slot] : slots) { if (auto qtype = GetQTypeOf(name, slot.GetType()); qtype != nullptr) { types.emplace(name, qtype); } else { unknown_types.emplace(name); } } if (!unknown_types.empty()) { return absl::InvalidArgumentError(absl::StrFormat( "unknown outputs: %s (available: %s)", Truncate(absl::StrJoin(unknown_types, ", "), 200), Truncate(absl::StrJoin(SuggestAvailableNames(), ", "), 200))); } return VerifySlotTypes(types, slots, true, false); } absl::flat_hash_map<std::string, TypedSlot> SlotListenerBase::FindSupportedSlots( const absl::flat_hash_map<std::string, TypedSlot>& slots) const { absl::flat_hash_map<std::string, TypedSlot> partial_slots; for (const auto& [name, slot] : slots) { if (GetQTypeOf(name, slot.GetType()) != nullptr) { partial_slots.emplace(name, slot); } } return partial_slots; } }
#include "arolla/io/slot_listener.h" #include <memory> #include <utility> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "arolla/io/accessors_slot_listener.h" #include "arolla/memory/frame.h" #include "arolla/memory/memory_allocation.h" #include "arolla/qtype/typed_slot.h" namespace arolla { namespace { using ::testing::Eq; struct TestStruct { int a; double b; }; TEST(SlotListenerTest, MakeNotOwningSlotListener) { ASSERT_OK_AND_ASSIGN( std::unique_ptr<SlotListener<TestStruct>> wrapped_listener, CreateAccessorsSlotListener<TestStruct>( "a", [](int a, TestStruct* s) { s->a = a; })); std::unique_ptr<SlotListener<TestStruct>> not_owning_listener = MakeNotOwningSlotListener(wrapped_listener.get()); EXPECT_THAT(not_owning_listener->GetQTypeOf("a"), Eq(wrapped_listener->GetQTypeOf("a"))); EXPECT_THAT(not_owning_listener->SuggestAvailableNames(), Eq(wrapped_listener->SuggestAvailableNames())); FrameLayout::Builder layout_builder; auto a_slot = layout_builder.AddSlot<int>(); FrameLayout memory_layout = std::move(layout_builder).Build(); ASSERT_OK_AND_ASSIGN( BoundSlotListener<TestStruct> bound_slot_listener, not_owning_listener->Bind({{"a", TypedSlot::FromSlot(a_slot)}})); MemoryAllocation alloc(&memory_layout); alloc.frame().Set(a_slot, 57); TestStruct s; ASSERT_OK(bound_slot_listener(alloc.frame(), &s)); EXPECT_EQ(s.a, 57); } TEST(SlotListenerTest, MakeSharedOwningSlotListener) { std::unique_ptr<SlotListener<TestStruct>> shared_owning_listener; { ASSERT_OK_AND_ASSIGN( std::shared_ptr<const SlotListener<TestStruct>> wrapped_listener, CreateAccessorsSlotListener<TestStruct>( "a", [](int a, TestStruct* s) { s->a = a; })); shared_owning_listener = MakeSharedOwningSlotListener(wrapped_listener); EXPECT_THAT(shared_owning_listener->GetQTypeOf("a"), Eq(wrapped_listener->GetQTypeOf("a"))); EXPECT_THAT(shared_owning_listener->SuggestAvailableNames(), Eq(wrapped_listener->SuggestAvailableNames())); } FrameLayout::Builder layout_builder; auto a_slot = layout_builder.AddSlot<int>(); FrameLayout memory_layout = std::move(layout_builder).Build(); ASSERT_OK_AND_ASSIGN( BoundSlotListener<TestStruct> bound_slot_listener, shared_owning_listener->Bind({{"a", TypedSlot::FromSlot(a_slot)}})); MemoryAllocation alloc(&memory_layout); alloc.frame().Set(a_slot, 57); TestStruct s; ASSERT_OK(bound_slot_listener(alloc.frame(), &s)); EXPECT_EQ(s.a, 57); } } }
2,412
#ifndef AROLLA_IO_INPUT_LOADER_H_ #define AROLLA_IO_INPUT_LOADER_H_ #include <algorithm> #include <cstddef> #include <functional> #include <initializer_list> #include <memory> #include <string> #include <utility> #include <vector> #include "absl/base/macros.h" #include "absl/base/nullability.h" #include "absl/container/flat_hash_map.h" #include "absl/container/flat_hash_set.h" #include "absl/functional/any_invocable.h" #include "absl/functional/bind_front.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "arolla/memory/frame.h" #include "arolla/memory/raw_buffer_factory.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/typed_slot.h" #include "arolla/util/status_macros_backport.h" namespace arolla { template <class Input> class BoundInputLoader { public: using FnType = absl::AnyInvocable<absl::Status(const Input&, FramePtr, RawBufferFactory*) const>; explicit BoundInputLoader(FnType&& fn) : fn_(std::forward<FnType>(fn)) {} absl::Status operator()( const Input& input, FramePtr frame, RawBufferFactory* factory = GetHeapBufferFactory()) const { return fn_(input, frame, factory); } private: FnType fn_; }; class InputLoaderBase { public: virtual ~InputLoaderBase() {} virtual absl::Nullable<const QType*> GetQTypeOf( absl::string_view name) const = 0; virtual std::vector<std::string> SuggestAvailableNames() const = 0; protected: absl::Status ValidateSlotTypes( const absl::flat_hash_map<std::string, TypedSlot>& slots) const; absl::flat_hash_map<std::string, TypedSlot> ExtractSupportedSlots( absl::Nonnull<absl::flat_hash_map<std::string, TypedSlot>*> slots) const; }; template <class T> class InputLoader : public InputLoaderBase { public: using Input = T; absl::StatusOr<BoundInputLoader<Input>> Bind( const absl::flat_hash_map<std::string, TypedSlot>& slots) const { RETURN_IF_ERROR(ValidateSlotTypes(slots)); if (slots.empty()) { return BoundInputLoader<Input>( [](const Input&, FramePtr, RawBufferFactory*) { return absl::OkStatus(); }); } return BindImpl(slots); } absl::StatusOr<BoundInputLoader<Input>> PartialBind( absl::Nonnull<absl::flat_hash_map<std::string, TypedSlot>*> slots) const { return Bind(ExtractSupportedSlots(slots)); } protected: virtual absl::StatusOr<BoundInputLoader<Input>> BindImpl( const absl::flat_hash_map<std::string, TypedSlot>& output_slots) const = 0; }; template <typename T> using InputLoaderPtr = std::unique_ptr<InputLoader<T>>; inline auto QTypeGetter(const InputLoaderBase& input_loader) { return [&input_loader](absl::string_view name) { return input_loader.GetQTypeOf(name); }; } absl::StatusOr<absl::flat_hash_map<std::string, QTypePtr>> GetInputLoaderQTypes( const InputLoaderBase& input_loader, absl::Span<const std::string> names); template <class T> class StaticInputLoader : public InputLoader<T> { protected: StaticInputLoader( std::initializer_list<std::pair<std::string, QTypePtr>> types_in_order) : StaticInputLoader(std::vector(types_in_order)) {} explicit StaticInputLoader( std::vector<std::pair<std::string, QTypePtr>> types_in_order) : types_in_order_(std::move(types_in_order)), types_(types_in_order_.begin(), types_in_order_.end()) {} explicit StaticInputLoader(absl::flat_hash_map<std::string, QTypePtr> types) : types_in_order_(types.begin(), types.end()), types_(std::move(types)) { std::sort(types_in_order_.begin(), types_in_order_.end()); } absl::Span<const std::pair<std::string, QTypePtr>> types_in_order() const { return types_in_order_; } public: absl::Nullable<const QType*> GetQTypeOf(absl::string_view name) const final { auto it = types_.find(name); return it != types_.end() ? it->second : nullptr; } std::vector<std::string> SuggestAvailableNames() const final { std::vector<std::string> names; names.reserve(types_.size()); for (const auto& [name, _] : types_in_order_) { names.emplace_back(name); } return names; } private: std::vector<std::pair<std::string, QTypePtr>> types_in_order_; absl::flat_hash_map<std::string, QTypePtr> types_; }; namespace input_loader_impl { template <typename T> class NotOwningInputLoader final : public InputLoader<T> { public: explicit NotOwningInputLoader(const InputLoader<T>* input_loader) : input_loader_(input_loader) {} absl::Nullable<const QType*> GetQTypeOf(absl::string_view name) const final { return input_loader_->GetQTypeOf(name); } std::vector<std::string> SuggestAvailableNames() const { return input_loader_->SuggestAvailableNames(); } private: absl::StatusOr<BoundInputLoader<T>> BindImpl( const absl::flat_hash_map<std::string, TypedSlot>& output_slots) const final { return input_loader_->Bind(output_slots); } const InputLoader<T>* input_loader_; }; } template <typename T> InputLoaderPtr<T> MakeNotOwningInputLoader(const InputLoader<T>* input_loader) { return std::unique_ptr<InputLoader<T>>( new input_loader_impl::NotOwningInputLoader<T>(input_loader)); } namespace input_loader_impl { template <typename T> class SharedOwningInputLoader final : public InputLoader<T> { public: explicit SharedOwningInputLoader( std::shared_ptr<const InputLoader<T>> input_loader) : input_loader_(std::move(input_loader)) {} absl::Nullable<const QType*> GetQTypeOf(absl::string_view name) const final { return input_loader_->GetQTypeOf(name); } std::vector<std::string> SuggestAvailableNames() const { return input_loader_->SuggestAvailableNames(); } private: absl::StatusOr<BoundInputLoader<T>> BindImpl( const absl::flat_hash_map<std::string, TypedSlot>& output_slots) const final { return input_loader_->Bind(output_slots); } std::shared_ptr<const InputLoader<T>> input_loader_; }; } template <typename T> InputLoaderPtr<T> MakeSharedOwningInputLoader( std::shared_ptr<const InputLoader<T>> input_loader) { return std::unique_ptr<InputLoader<T>>( new input_loader_impl::SharedOwningInputLoader<T>(input_loader)); } namespace input_loader_impl { template <typename T> class FilteringInputLoader final : public InputLoader<T> { public: explicit FilteringInputLoader( std::unique_ptr<InputLoader<T>> input_loader, std::function<bool(absl::string_view)> filter_fn) : input_loader_(std::move(input_loader)), filter_fn_(std::move(filter_fn)) {} absl::Nullable<const QType*> GetQTypeOf(absl::string_view name) const final { if (filter_fn_(name)) { return input_loader_->GetQTypeOf(name); } return nullptr; } std::vector<std::string> SuggestAvailableNames() const { std::vector<std::string> suggested = input_loader_->SuggestAvailableNames(); suggested.erase(std::remove_if(suggested.begin(), suggested.end(), std::not_fn(filter_fn_)), suggested.end()); return suggested; } private: absl::StatusOr<BoundInputLoader<T>> BindImpl( const absl::flat_hash_map<std::string, TypedSlot>& output_slots) const final { return input_loader_->Bind(output_slots); } std::unique_ptr<InputLoader<T>> input_loader_; std::function<bool(absl::string_view)> filter_fn_; }; } template <typename T> std::unique_ptr<InputLoader<T>> MakeFilteringInputLoader( std::unique_ptr<InputLoader<T>> input_loader, std::function<bool(absl::string_view)> filter_fn) { return std::unique_ptr<InputLoader<T>>( new input_loader_impl::FilteringInputLoader<T>(std::move(input_loader), std::move(filter_fn))); } template <typename T> std::unique_ptr<InputLoader<T>> MakeFilteringInputLoader( std::unique_ptr<InputLoader<T>> input_loader, absl::Span<const std::string> allowed_names) { return MakeFilteringInputLoader( std::move(input_loader), [allowed_names = absl::flat_hash_set<std::string>(allowed_names.begin(), allowed_names.end())]( absl::string_view input) { return allowed_names.contains(input); }); } using OutputTypesSpan = absl::Span<const std::pair<std::string, QTypePtr>>; absl::Status ValidateDuplicatedNames(OutputTypesSpan output_types_in_order); template <class Input> absl::StatusOr<std::vector<BoundInputLoader<Input>>> BindInputLoaderList( absl::Span<const InputLoaderPtr<Input>> loaders, const absl::flat_hash_map<std::string, TypedSlot>& output_slots) { std::vector<BoundInputLoader<Input>> bound_loaders; bound_loaders.reserve(loaders.size()); auto partial_output_slots = output_slots; for (const auto& loader : loaders) { size_t slot_count = partial_output_slots.size(); ASSIGN_OR_RETURN(auto bound_loader, loader->PartialBind(&partial_output_slots)); if (slot_count != partial_output_slots.size()) { bound_loaders.push_back(std::move(bound_loader)); } } if (!partial_output_slots.empty()) { return absl::FailedPreconditionError("not all slots were bound"); } return bound_loaders; } template <class Input> class ChainInputLoader final : public InputLoader<Input> { public: template <class... Loaders> static absl::StatusOr<InputLoaderPtr<Input>> Build( std::unique_ptr<Loaders>... loaders) { std::vector<InputLoaderPtr<Input>> loaders_vec; (loaders_vec.push_back(std::move(loaders)), ...); return Build(std::move(loaders_vec)); } static absl::StatusOr<InputLoaderPtr<Input>> Build( std::vector<InputLoaderPtr<Input>> loaders) { return InputLoaderPtr<Input>(static_cast<InputLoader<Input>*>( new ChainInputLoader(std::move(loaders)))); } using InvokeBoundLoadersFn = std::function<absl::Status( absl::Span<const BoundInputLoader<Input>>, const Input& input, FramePtr frame, RawBufferFactory* factory)>; static absl::Status InvokeBoundLoaders( absl::Span<const BoundInputLoader<Input>> bound_loaders, const Input& input, FramePtr frame, RawBufferFactory* factory) { for (const auto& loader : bound_loaders) { RETURN_IF_ERROR(loader(input, frame, factory)); } return absl::OkStatus(); } static absl::StatusOr<InputLoaderPtr<Input>> Build( std::vector<InputLoaderPtr<Input>> loaders, InvokeBoundLoadersFn invoke_bound_loaders_fn) { return InputLoaderPtr<Input>( static_cast<InputLoader<Input>*>(new ChainInputLoader( std::move(loaders), std::move(invoke_bound_loaders_fn)))); } absl::Nullable<const QType*> GetQTypeOf(absl::string_view name) const final { for (const auto& loader : loaders_) { if (auto qtype = loader->GetQTypeOf(name); qtype != nullptr) { return qtype; } } return nullptr; } std::vector<std::string> SuggestAvailableNames() const final { std::vector<std::string> names; for (const auto& loader : loaders_) { auto available = loader->SuggestAvailableNames(); names.insert(names.end(), available.begin(), available.end()); } return names; } private: explicit ChainInputLoader(std::vector<InputLoaderPtr<Input>> loaders) : loaders_(std::move(loaders)) {} explicit ChainInputLoader(std::vector<InputLoaderPtr<Input>> loaders, InvokeBoundLoadersFn invoke_bound_loaders_fn) : loaders_(std::move(loaders)), invoke_bound_loaders_fn_(std::move(invoke_bound_loaders_fn)) {} absl::StatusOr<BoundInputLoader<Input>> BindImpl( const absl::flat_hash_map<std::string, TypedSlot>& output_slots) const final { ASSIGN_OR_RETURN(std::vector<BoundInputLoader<Input>> bound_loaders, BindInputLoaderList<Input>(loaders_, output_slots)); if (bound_loaders.empty()) { return absl::InternalError( "no slots were bound, must be processed in Bind"); } if (bound_loaders.size() == 1) { return std::move(bound_loaders[0]); } if (invoke_bound_loaders_fn_) { return BoundInputLoader<Input>( absl::bind_front(invoke_bound_loaders_fn_, std::move(bound_loaders))); } return BoundInputLoader<Input>( [bound_loaders(std::move(bound_loaders))]( const Input& input, FramePtr frame, RawBufferFactory* factory) -> absl::Status { return ChainInputLoader<Input>::InvokeBoundLoaders( bound_loaders, input, frame, factory); }); } std::vector<InputLoaderPtr<Input>> loaders_; InvokeBoundLoadersFn invoke_bound_loaders_fn_ = nullptr; }; } #endif #include "arolla/io/input_loader.h" #include <algorithm> #include <cstddef> #include <set> #include <string> #include <vector> #include "absl/base/nullability.h" #include "absl/container/flat_hash_map.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" #include "absl/strings/str_join.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/typed_slot.h" #include "arolla/util/string.h" #include "arolla/util/status_macros_backport.h" namespace arolla { absl::Status ValidateDuplicatedNames(OutputTypesSpan output_types) { absl::flat_hash_map<std::string, size_t> names_count; std::vector<std::string> duplicated_names; for (const auto& [name, type] : output_types) { size_t& count = names_count[name]; if (count == 1) { duplicated_names.push_back(name); } ++count; } if (duplicated_names.empty()) { return absl::OkStatus(); } std::sort(duplicated_names.begin(), duplicated_names.end()); return absl::FailedPreconditionError( absl::StrCat("accessors have duplicated names: ", absl::StrJoin(duplicated_names, ", "))); } absl::StatusOr<absl::flat_hash_map<std::string, QTypePtr>> GetInputLoaderQTypes( const InputLoaderBase& input_loader, absl::Span<const std::string> names) { absl::flat_hash_map<std::string, QTypePtr> types; types.reserve(names.size()); std::set<absl::string_view> unknown_types; for (const auto& name : names) { if (auto qtype = input_loader.GetQTypeOf(name); qtype != nullptr) { types.emplace(name, qtype); } else { unknown_types.emplace(name); } } if (!unknown_types.empty()) { return absl::InvalidArgumentError(absl::StrFormat( "unknown inputs: %s (available: %s)", Truncate(absl::StrJoin(unknown_types, ", "), 200), Truncate(absl::StrJoin(input_loader.SuggestAvailableNames(), ", "), 200))); } return types; } absl::Status InputLoaderBase::ValidateSlotTypes( const absl::flat_hash_map<std::string, TypedSlot>& slots) const { std::vector<std::string> names; names.reserve(slots.size()); for (const auto& [name, _] : slots) { names.emplace_back(name); } ASSIGN_OR_RETURN(auto types, GetInputLoaderQTypes(*this, names)); return VerifySlotTypes(types, slots, true, false); } absl::flat_hash_map<std::string, TypedSlot> InputLoaderBase::ExtractSupportedSlots( absl::Nonnull<absl::flat_hash_map<std::string, TypedSlot>*> slots) const { absl::flat_hash_map<std::string, TypedSlot> partial_slots; for (const auto& [name, slot] : *slots) { if (GetQTypeOf(name) == nullptr) { continue; } partial_slots.emplace(name, slot); } for (const auto& [name, _] : partial_slots) { slots->erase(name); } return partial_slots; } }
#include "arolla/io/input_loader.h" #include <cstdint> #include <memory> #include <utility> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/container/flat_hash_map.h" #include "absl/status/status.h" #include "absl/types/span.h" #include "arolla/io/accessors_input_loader.h" #include "arolla/io/testing/matchers.h" #include "arolla/memory/frame.h" #include "arolla/memory/memory_allocation.h" #include "arolla/memory/raw_buffer_factory.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/util/testing/status_matchers_backport.h" namespace arolla { namespace { using ::arolla::testing::InputLoaderSupports; using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::StatusIs; using ::testing::Eq; using ::testing::HasSubstr; using ::testing::IsEmpty; using ::testing::IsNull; using ::testing::Pair; using ::testing::UnorderedElementsAre; struct TestStruct { int a; double b; }; TEST(InputLoaderTest, GetInputLoaderTypes) { ASSERT_OK_AND_ASSIGN(auto loader, CreateAccessorsInputLoader<TestStruct>( "a", [](const TestStruct& s) { return s.a; }, "b", [](const TestStruct& s) { return s.b; })); EXPECT_THAT(GetInputLoaderQTypes(*loader, {}), IsOkAndHolds(IsEmpty())); EXPECT_THAT( GetInputLoaderQTypes(*loader, {"a"}), IsOkAndHolds(UnorderedElementsAre(Pair("a", GetQType<int32_t>())))); EXPECT_THAT( GetInputLoaderQTypes(*loader, {"a", "b"}), IsOkAndHolds(UnorderedElementsAre(Pair("a", GetQType<int32_t>()), Pair("b", GetQType<double>())))); EXPECT_THAT(GetInputLoaderQTypes(*loader, {"a", "b", "c"}), StatusIs(absl::StatusCode::kInvalidArgument, "unknown inputs: c (available: a, b)")); } TEST(InputLoaderTest, ChainInputLoaderConflict) { ASSERT_OK_AND_ASSIGN(auto loader1, CreateAccessorsInputLoader<TestStruct>( "a", [](const TestStruct& s) { return s.a; }, "b", [](const TestStruct& s) { return s.b; })); ASSERT_OK_AND_ASSIGN(auto loader2, CreateAccessorsInputLoader<TestStruct>( "b", [](const TestStruct& s) { return 2 * s.b; }, "c", [](const TestStruct& s) { return s.b * s.b; })); ASSERT_OK_AND_ASSIGN(auto chain_loader, ChainInputLoader<TestStruct>::Build(std::move(loader1), std::move(loader2))); FrameLayout::Builder layout_builder; auto a_slot = layout_builder.AddSlot<int>(); auto b_slot = layout_builder.AddSlot<double>(); FrameLayout memory_layout = std::move(layout_builder).Build(); ASSERT_OK_AND_ASSIGN( BoundInputLoader<TestStruct> bound_input_loader, chain_loader->Bind({{"a", TypedSlot::FromSlot(a_slot)}, {"b", TypedSlot::FromSlot(b_slot)}})); MemoryAllocation alloc(&memory_layout); ASSERT_OK(bound_input_loader({5, 3.5}, alloc.frame())); EXPECT_EQ(alloc.frame().Get(b_slot), 3.5); } TEST(InputLoaderTest, MakeNotOwningInputLoader) { ASSERT_OK_AND_ASSIGN(std::unique_ptr<InputLoader<TestStruct>> wrapped_loader, CreateAccessorsInputLoader<TestStruct>( "a", [](const TestStruct& s) { return s.a; })); std::unique_ptr<InputLoader<TestStruct>> not_owning_loader = MakeNotOwningInputLoader(wrapped_loader.get()); EXPECT_THAT(not_owning_loader->GetQTypeOf("a"), Eq(GetQType<int32_t>())); EXPECT_THAT(not_owning_loader->GetQTypeOf("b"), IsNull()); FrameLayout::Builder layout_builder; auto a_slot = layout_builder.AddSlot<int>(); FrameLayout memory_layout = std::move(layout_builder).Build(); ASSERT_OK_AND_ASSIGN( BoundInputLoader<TestStruct> bound_input_loader, not_owning_loader->Bind({{"a", TypedSlot::FromSlot(a_slot)}})); MemoryAllocation alloc(&memory_layout); ASSERT_OK(bound_input_loader({5, 3.5}, alloc.frame())); EXPECT_EQ(alloc.frame().Get(a_slot), 5); } TEST(InputLoaderTest, MakeSharedOwningInputLoader) { std::unique_ptr<InputLoader<TestStruct>> shared_owning_loader; { ASSERT_OK_AND_ASSIGN( std::shared_ptr<const InputLoader<TestStruct>> wrapped_loader, CreateAccessorsInputLoader<TestStruct>( "a", [](const TestStruct& s) { return s.a; })); shared_owning_loader = MakeSharedOwningInputLoader(wrapped_loader); } EXPECT_THAT(shared_owning_loader->GetQTypeOf("a"), Eq(GetQType<int32_t>())); EXPECT_THAT(shared_owning_loader->GetQTypeOf("b"), IsNull()); FrameLayout::Builder layout_builder; auto a_slot = layout_builder.AddSlot<int>(); FrameLayout memory_layout = std::move(layout_builder).Build(); ASSERT_OK_AND_ASSIGN( BoundInputLoader<TestStruct> bound_input_loader, shared_owning_loader->Bind({{"a", TypedSlot::FromSlot(a_slot)}})); MemoryAllocation alloc(&memory_layout); ASSERT_OK(bound_input_loader({5, 3.5}, alloc.frame())); EXPECT_EQ(alloc.frame().Get(a_slot), 5); } TEST(InputLoaderTest, BindInputLoaderList) { FrameLayout::Builder layout_builder; auto a_slot = layout_builder.AddSlot<int>(); auto b_slot = layout_builder.AddSlot<double>(); auto c_slot = layout_builder.AddSlot<double>(); FrameLayout memory_layout = std::move(layout_builder).Build(); std::vector<std::unique_ptr<InputLoader<TestStruct>>> input_loaders; ASSERT_OK_AND_ASSIGN(input_loaders.emplace_back(), CreateAccessorsInputLoader<TestStruct>( "a", [](const TestStruct& s) { return s.a; })); ASSERT_OK_AND_ASSIGN(input_loaders.emplace_back(), CreateAccessorsInputLoader<TestStruct>( "b", [](const TestStruct& s) { return s.b; })); ASSERT_OK_AND_ASSIGN(input_loaders.emplace_back(), CreateAccessorsInputLoader<TestStruct>( "b", [](const TestStruct& s) { return int{0}; }, "c", [](const TestStruct& s) { return s.b * s.b; })); ASSERT_OK_AND_ASSIGN( std::vector<BoundInputLoader<TestStruct>> bound_input_loaders, BindInputLoaderList<TestStruct>(input_loaders, { {"a", TypedSlot::FromSlot(a_slot)}, {"b", TypedSlot::FromSlot(b_slot)}, {"c", TypedSlot::FromSlot(c_slot)}, })); MemoryAllocation alloc(&memory_layout); TestStruct input{5, 3.5}; for (const auto& bound_input_loader : bound_input_loaders) { ASSERT_OK(bound_input_loader(input, alloc.frame())); } EXPECT_EQ(alloc.frame().Get(a_slot), 5); EXPECT_EQ(alloc.frame().Get(b_slot), 3.5); EXPECT_EQ(alloc.frame().Get(c_slot), 3.5 * 3.5); } TEST(InputLoaderTest, BindInputLoaderListErrors) { FrameLayout::Builder layout_builder; auto a_slot = layout_builder.AddSlot<int>(); auto b_slot = layout_builder.AddSlot<double>(); auto c_slot = layout_builder.AddSlot<double>(); FrameLayout memory_layout = std::move(layout_builder).Build(); std::vector<std::unique_ptr<InputLoader<TestStruct>>> input_loaders; ASSERT_OK_AND_ASSIGN(input_loaders.emplace_back(), CreateAccessorsInputLoader<TestStruct>( "a", [](const TestStruct& s) { return s.a; })); ASSERT_OK_AND_ASSIGN(input_loaders.emplace_back(), CreateAccessorsInputLoader<TestStruct>( "b", [](const TestStruct& s) { return s.b; })); EXPECT_THAT( BindInputLoaderList<TestStruct>(input_loaders, { {"a", TypedSlot::FromSlot(a_slot)}, {"b", TypedSlot::FromSlot(b_slot)}, {"c", TypedSlot::FromSlot(c_slot)}, }), StatusIs(absl::StatusCode::kFailedPrecondition, HasSubstr("not all"))); } TEST(InputLoaderTest, FilteringInputLoader) { auto i32 = GetQType<int32_t>(); auto f64 = GetQType<double>(); ASSERT_OK_AND_ASSIGN(auto inner_loader, CreateAccessorsInputLoader<TestStruct>( "a", [](const TestStruct& s) { return s.a; }, "b", [](const TestStruct& s) { return s.b; })); EXPECT_THAT(inner_loader->GetQTypeOf("a"), Eq(i32)); EXPECT_THAT(inner_loader->GetQTypeOf("b"), Eq(f64)); auto filtered_loader = MakeFilteringInputLoader(std::move(inner_loader), {"a"}); EXPECT_THAT(filtered_loader->GetQTypeOf("a"), Eq(i32)); EXPECT_THAT(filtered_loader->GetQTypeOf("b"), IsNull()); FrameLayout::Builder layout_builder; auto a_slot = layout_builder.AddSlot<int>(); auto b_slot = layout_builder.AddSlot<double>(); FrameLayout memory_layout = std::move(layout_builder).Build(); EXPECT_THAT(filtered_loader->Bind({{"a", TypedSlot::FromSlot(a_slot)}, {"b", TypedSlot::FromSlot(b_slot)}}), StatusIs(absl::StatusCode::kInvalidArgument, "unknown inputs: b (available: a)")); ASSERT_OK_AND_ASSIGN( BoundInputLoader<TestStruct> bound_input_loader, filtered_loader->Bind({{"a", TypedSlot::FromSlot(a_slot)}})); MemoryAllocation alloc(&memory_layout); ASSERT_OK(bound_input_loader({5, 3.5}, alloc.frame())); EXPECT_EQ(alloc.frame().Get(a_slot), 5); } TEST(InputLoaderTest, ChainInputLoader) { auto i32 = GetQType<int32_t>(); auto f64 = GetQType<double>(); std::unique_ptr<InputLoader<TestStruct>> chain_input_loader; { ASSERT_OK_AND_ASSIGN(auto loader1, CreateAccessorsInputLoader<TestStruct>( "a", [](const TestStruct& s) { return s.a; })); ASSERT_OK_AND_ASSIGN(auto loader2, CreateAccessorsInputLoader<TestStruct>( "b", [](const TestStruct& s) { return s.b; })); ASSERT_OK_AND_ASSIGN( auto loader3, CreateAccessorsInputLoader<TestStruct>( "c", [](const TestStruct& s) { return s.b * s.b; })); ASSERT_OK_AND_ASSIGN( chain_input_loader, ChainInputLoader<TestStruct>::Build( std::move(loader1), std::move(loader2), std::move(loader3))); } FrameLayout::Builder layout_builder; auto a_slot = layout_builder.AddSlot<int>(); auto b_slot = layout_builder.AddSlot<double>(); auto c_slot = layout_builder.AddSlot<double>(); FrameLayout memory_layout = std::move(layout_builder).Build(); EXPECT_THAT(*chain_input_loader, InputLoaderSupports({{"a", i32}, {"b", f64}, {"c", f64}})); ASSERT_OK_AND_ASSIGN(BoundInputLoader<TestStruct> bound_input_loader, chain_input_loader->Bind({ {"a", TypedSlot::FromSlot(a_slot)}, {"b", TypedSlot::FromSlot(b_slot)}, {"c", TypedSlot::FromSlot(c_slot)}, })); MemoryAllocation alloc(&memory_layout); ASSERT_OK(bound_input_loader({5, 3.5}, alloc.frame())); EXPECT_EQ(alloc.frame().Get(a_slot), 5); EXPECT_EQ(alloc.frame().Get(b_slot), 3.5); EXPECT_EQ(alloc.frame().Get(c_slot), 3.5 * 3.5); } TEST(InputLoaderTest, ChainInputLoaderFactoryPropagated) { auto qbool = GetQType<bool>(); std::unique_ptr<InputLoader<TestStruct>> input_loader; UnsafeArenaBufferFactory global_factory1(1000); UnsafeArenaBufferFactory global_factory2(1000); { ASSERT_OK_AND_ASSIGN(auto loader1, CreateAccessorsInputLoader<TestStruct>( "a", [&](const TestStruct&, RawBufferFactory* factory) { return factory == &global_factory1; })); ASSERT_OK_AND_ASSIGN(auto loader2, CreateAccessorsInputLoader<TestStruct>( "b", [&](const TestStruct&, RawBufferFactory* factory) { return factory == &global_factory2; })); ASSERT_OK_AND_ASSIGN( input_loader, ChainInputLoader<TestStruct>::Build(std::move(loader1), std::move(loader2))); } FrameLayout::Builder layout_builder; auto a_slot = layout_builder.AddSlot<bool>(); auto b_slot = layout_builder.AddSlot<bool>(); FrameLayout memory_layout = std::move(layout_builder).Build(); EXPECT_THAT(input_loader, InputLoaderSupports({{"a", qbool}, {"b", qbool}})); ASSERT_OK_AND_ASSIGN(BoundInputLoader<TestStruct> bound_input_loader, input_loader->Bind({ {"a", TypedSlot::FromSlot(a_slot)}, {"b", TypedSlot::FromSlot(b_slot)}, })); MemoryAllocation alloc(&memory_layout); ASSERT_OK(bound_input_loader({5, 3.5}, alloc.frame(), &global_factory1)); EXPECT_TRUE(alloc.frame().Get(a_slot)); EXPECT_FALSE(alloc.frame().Get(b_slot)); ASSERT_OK(bound_input_loader({5, 3.5}, alloc.frame(), &global_factory2)); EXPECT_FALSE(alloc.frame().Get(a_slot)); EXPECT_TRUE(alloc.frame().Get(b_slot)); } TEST(InputLoaderTest, ChainInputLoaderWithCustomInvoke) { auto i32 = GetQType<int32_t>(); auto f64 = GetQType<double>(); std::unique_ptr<InputLoader<TestStruct>> chain_input_loader; FrameLayout::Builder layout_builder; auto a_slot = layout_builder.AddSlot<int>(); auto b_slot = layout_builder.AddSlot<double>(); auto c_slot = layout_builder.AddSlot<double>(); FrameLayout memory_layout = std::move(layout_builder).Build(); int64_t number_of_loaders = -1; { std::vector<std::unique_ptr<InputLoader<TestStruct>>> input_loaders; ASSERT_OK_AND_ASSIGN(input_loaders.emplace_back(), CreateAccessorsInputLoader<TestStruct>( "a", [](const TestStruct& s) { return s.a; })); ASSERT_OK_AND_ASSIGN(input_loaders.emplace_back(), CreateAccessorsInputLoader<TestStruct>( "b", [](const TestStruct& s) { return s.b; })); ASSERT_OK_AND_ASSIGN( input_loaders.emplace_back(), CreateAccessorsInputLoader<TestStruct>( "c", [](const TestStruct& s) { return s.b * s.b; })); ASSERT_OK_AND_ASSIGN( chain_input_loader, ChainInputLoader<TestStruct>::Build( std::move(input_loaders), [&number_of_loaders]( absl::Span<const BoundInputLoader<TestStruct>> loaders, const TestStruct& input, FramePtr frame, RawBufferFactory* factory) { number_of_loaders = loaders.size(); return ChainInputLoader<TestStruct>::InvokeBoundLoaders( loaders, input, frame, factory); })); EXPECT_THAT(*chain_input_loader, InputLoaderSupports({{"a", i32}, {"b", f64}, {"c", f64}})); } BoundInputLoader<TestStruct> bound_input_loader(nullptr); { ASSERT_OK_AND_ASSIGN(bound_input_loader, chain_input_loader->Bind({ {"a", TypedSlot::FromSlot(a_slot)}, {"b", TypedSlot::FromSlot(b_slot)}, {"c", TypedSlot::FromSlot(c_slot)}, })); } MemoryAllocation alloc(&memory_layout); ASSERT_OK(bound_input_loader({5, 3.5}, alloc.frame())); EXPECT_EQ(number_of_loaders, 3); EXPECT_EQ(alloc.frame().Get(a_slot), 5); EXPECT_EQ(alloc.frame().Get(b_slot), 3.5); EXPECT_EQ(alloc.frame().Get(c_slot), 3.5 * 3.5); } TEST(InputLoaderTest, ChainInputLoaderWithCustomInvokeOptimized) { auto i32 = GetQType<int32_t>(); auto f64 = GetQType<double>(); std::unique_ptr<InputLoader<TestStruct>> chain_input_loader; FrameLayout::Builder layout_builder; auto a_slot = layout_builder.AddSlot<int>(); FrameLayout memory_layout = std::move(layout_builder).Build(); int64_t number_of_loaders = -1; { std::vector<std::unique_ptr<InputLoader<TestStruct>>> input_loaders; ASSERT_OK_AND_ASSIGN(input_loaders.emplace_back(), CreateAccessorsInputLoader<TestStruct>( "a", [](const TestStruct& s) { return s.a; })); ASSERT_OK_AND_ASSIGN(input_loaders.emplace_back(), CreateAccessorsInputLoader<TestStruct>( "b", [](const TestStruct& s) { return s.b; })); ASSERT_OK_AND_ASSIGN( chain_input_loader, ChainInputLoader<TestStruct>::Build( std::move(input_loaders), [&number_of_loaders]( absl::Span<const BoundInputLoader<TestStruct>> loaders, const TestStruct& input, FramePtr frame, RawBufferFactory* factory) { number_of_loaders = loaders.size(); return ChainInputLoader<TestStruct>::InvokeBoundLoaders( loaders, input, frame, factory); })); EXPECT_THAT(*chain_input_loader, InputLoaderSupports({{"a", i32}, {"b", f64}})); } BoundInputLoader<TestStruct> bound_input_loader(nullptr); { ASSERT_OK_AND_ASSIGN(bound_input_loader, chain_input_loader->Bind({ {"a", TypedSlot::FromSlot(a_slot)}, })); } MemoryAllocation alloc(&memory_layout); ASSERT_OK(bound_input_loader({5, 3.5}, alloc.frame())); EXPECT_EQ(number_of_loaders, -1); EXPECT_EQ(alloc.frame().Get(a_slot), 5); } } }
2,413
#ifndef AROLLA_IO_STRING_SLOT_LISTENER_H_ #define AROLLA_IO_STRING_SLOT_LISTENER_H_ #include <memory> #include <string> #include <vector> #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "arolla/io/slot_listener.h" namespace arolla { absl::StatusOr<std::unique_ptr<SlotListener<std::string>>> BytesSlotListener( absl::string_view side_output_name); absl::StatusOr<std::unique_ptr<SlotListener<std::vector<std::string>>>> BytesArraySlotListener(absl::string_view side_output_name); } #endif #include "arolla/io/string_slot_listener.h" #include <memory> #include <string> #include <string_view> #include <vector> #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "arolla/dense_array/dense_array.h" #include "arolla/dense_array/qtype/types.h" #include "arolla/io/accessors_slot_listener.h" #include "arolla/io/slot_listener.h" #include "arolla/memory/optional_value.h" #include "arolla/util/bytes.h" namespace arolla { absl::StatusOr<std::unique_ptr<SlotListener<std::string>>> BytesSlotListener( absl::string_view side_output_name) { return CreateAccessorsSlotListener<std::string>( side_output_name, [](const OptionalValue<Bytes>& b, std::string* out) { *out = b.present ? b.value : ""; }); } absl::StatusOr<std::unique_ptr<SlotListener<std::vector<std::string>>>> BytesArraySlotListener(absl::string_view side_output_name) { return CreateAccessorsSlotListener<std::vector<std::string>>( side_output_name, [](const DenseArray<Bytes>& arr, std::vector<std::string>* out) { out->clear(); out->reserve(arr.size()); arr.ForEach([&](auto _, bool is_present, absl::string_view value) { out->push_back(is_present ? std::string(value) : ""); }); }); } }
#include "arolla/io/string_slot_listener.h" #include <optional> #include <string> #include <utility> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "arolla/dense_array/dense_array.h" #include "arolla/dense_array/qtype/types.h" #include "arolla/io/slot_listener.h" #include "arolla/memory/frame.h" #include "arolla/memory/memory_allocation.h" #include "arolla/memory/optional_value.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/optional_qtype.h" #include "arolla/qtype/typed_slot.h" #include "arolla/util/bytes.h" namespace arolla { namespace { using ::testing::ElementsAre; using ::testing::Eq; using ::testing::IsEmpty; TEST(StringSlotListenerTest, BytesSlotListener) { ASSERT_OK_AND_ASSIGN(auto slot_listener, BytesSlotListener("debug_html")); EXPECT_THAT(slot_listener->GetQTypeOf("debug_html"), Eq(GetOptionalQType<Bytes>())); FrameLayout::Builder layout_builder; auto bytes_slot = layout_builder.AddSlot<OptionalValue<Bytes>>(); ASSERT_OK_AND_ASSIGN(BoundSlotListener<std::string> bound_slot_listener, slot_listener->Bind({ {"debug_html", TypedSlot::FromSlot(bytes_slot)}, })); FrameLayout memory_layout = std::move(layout_builder).Build(); MemoryAllocation alloc(&memory_layout); std::string side_output; ASSERT_OK(bound_slot_listener(alloc.frame(), &side_output)); EXPECT_THAT(side_output, Eq("")); alloc.frame().Set(bytes_slot, Bytes{"fifty seven"}); ASSERT_OK(bound_slot_listener(alloc.frame(), &side_output)); EXPECT_THAT(side_output, Eq("fifty seven")); } TEST(StringSlotListenerTest, BytesArraySlotListener) { ASSERT_OK_AND_ASSIGN(auto slot_listener, BytesArraySlotListener("debug_htmls")); EXPECT_THAT(slot_listener->GetQTypeOf("debug_htmls"), Eq(GetDenseArrayQType<Bytes>())); FrameLayout::Builder layout_builder; auto bytes_array_slot = layout_builder.AddSlot<DenseArray<Bytes>>(); ASSERT_OK_AND_ASSIGN( BoundSlotListener<std::vector<std::string>> bound_slot_listener, slot_listener->Bind({ {"debug_htmls", TypedSlot::FromSlot(bytes_array_slot)}, })); FrameLayout memory_layout = std::move(layout_builder).Build(); MemoryAllocation alloc(&memory_layout); std::vector<std::string> side_output; ASSERT_OK(bound_slot_listener(alloc.frame(), &side_output)); EXPECT_THAT(side_output, IsEmpty()); alloc.frame().Set(bytes_array_slot, CreateDenseArray<Bytes>({Bytes("fifty"), Bytes(""), Bytes("seven"), std::nullopt})); ASSERT_OK(bound_slot_listener(alloc.frame(), &side_output)); EXPECT_THAT(side_output, ElementsAre("fifty", "", "seven", "")); } } }
2,414
#ifndef AROLLA_IO_STRUCT_IO_H_ #define AROLLA_IO_STRUCT_IO_H_ #include <cstddef> #include <memory> #include <string> #include <utility> #include <vector> #include "absl/base/nullability.h" #include "absl/container/flat_hash_map.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "arolla/io/input_loader.h" #include "arolla/io/slot_listener.h" #include "arolla/memory/frame.h" #include "arolla/memory/raw_buffer_factory.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/typed_slot.h" #include "arolla/util/status_macros_backport.h" namespace arolla { namespace struct_io_impl { class StructIO { public: explicit StructIO( const absl::flat_hash_map<std::string, TypedSlot>& struct_slots, const absl::flat_hash_map<std::string, TypedSlot>& frame_slots); void CopyStructToFrame(const void* struct_ptr, FramePtr frame) const; void CopyFrameToStruct(ConstFramePtr frame, void* struct_ptr) const; private: using Offsets = std::vector<std::pair<size_t, size_t>>; Offsets offsets_bool_; Offsets offsets_32bits_; Offsets offsets_64bits_; absl::flat_hash_map<QTypePtr, Offsets> offsets_other_; }; std::vector<std::string> SuggestAvailableNames( const absl::flat_hash_map<std::string, TypedSlot>& slots); absl::Status ValidateStructSlots( const absl::flat_hash_map<std::string, TypedSlot>& slots, size_t struct_size); } template <typename T> class StructInputLoader final : public InputLoader<T> { public: static absl::StatusOr<InputLoaderPtr<T>> Create( absl::flat_hash_map<std::string, TypedSlot> struct_slots) { RETURN_IF_ERROR( struct_io_impl::ValidateStructSlots(struct_slots, sizeof(T))); return InputLoaderPtr<T>(new StructInputLoader(std::move(struct_slots))); } absl::Nullable<const QType*> GetQTypeOf(absl::string_view name) const final { auto it = struct_slots_.find(name); return it != struct_slots_.end() ? it->second.GetType() : nullptr; } std::vector<std::string> SuggestAvailableNames() const final { return struct_io_impl::SuggestAvailableNames(struct_slots_); } private: explicit StructInputLoader( absl::flat_hash_map<std::string, TypedSlot> struct_slots) : struct_slots_(std::move(struct_slots)) {} absl::StatusOr<BoundInputLoader<T>> BindImpl( const absl::flat_hash_map<std::string, TypedSlot>& slots) const final { return BoundInputLoader<T>( [io = struct_io_impl::StructIO(struct_slots_, slots)]( const T& input, FramePtr frame, RawBufferFactory*) -> absl::Status { io.CopyStructToFrame(&input, frame); return absl::OkStatus(); }); } absl::flat_hash_map<std::string, TypedSlot> struct_slots_; }; template <typename T> class StructSlotListener final : public SlotListener<T> { public: static absl::StatusOr<std::unique_ptr<SlotListener<T>>> Create( absl::flat_hash_map<std::string, TypedSlot> struct_slots) { RETURN_IF_ERROR( struct_io_impl::ValidateStructSlots(struct_slots, sizeof(T))); return std::unique_ptr<SlotListener<T>>( new StructSlotListener(std::move(struct_slots))); } absl::Nullable<const QType*> GetQTypeOf( absl::string_view name, absl::Nullable<const QType*>) const final { auto it = struct_slots_.find(name); return it != struct_slots_.end() ? it->second.GetType() : nullptr; } std::vector<std::string> SuggestAvailableNames() const final { return struct_io_impl::SuggestAvailableNames(struct_slots_); } private: explicit StructSlotListener( absl::flat_hash_map<std::string, TypedSlot> struct_slots) : struct_slots_(std::move(struct_slots)) {} absl::StatusOr<BoundSlotListener<T>> BindImpl( const absl::flat_hash_map<std::string, TypedSlot>& slots) const final { return BoundSlotListener<T>( [io = struct_io_impl::StructIO(struct_slots_, slots)]( ConstFramePtr frame, T* output) -> absl::Status { io.CopyFrameToStruct(frame, output); return absl::OkStatus(); }); } absl::flat_hash_map<std::string, TypedSlot> struct_slots_; }; } #endif #include "arolla/io/struct_io.h" #include <algorithm> #include <cstddef> #include <cstdint> #include <cstring> #include <string> #include <type_traits> #include <utility> #include <vector> #include "absl/algorithm/container.h" #include "absl/container/flat_hash_map.h" #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/strings/str_cat.h" #include "arolla/memory/frame.h" #include "arolla/memory/optional_value.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/optional_qtype.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/typed_slot.h" namespace arolla::struct_io_impl { std::vector<std::string> SuggestAvailableNames( const absl::flat_hash_map<std::string, TypedSlot>& slots) { std::vector<std::string> names; names.reserve(slots.size()); for (const auto& [name, _] : slots) { names.emplace_back(name); } return names; } absl::Status ValidateStructSlots( const absl::flat_hash_map<std::string, TypedSlot>& slots, size_t struct_size) { for (const auto& [name, slot] : slots) { if (slot.byte_offset() + slot.GetType()->type_layout().AllocSize() > struct_size) { return absl::InvalidArgumentError( absl::StrCat("slot '", name, "' is not within the struct")); } } return absl::OkStatus(); } StructIO::StructIO( const absl::flat_hash_map<std::string, TypedSlot>& struct_slots, const absl::flat_hash_map<std::string, TypedSlot>& frame_slots) { QTypePtr b = GetQType<bool>(); std::vector<QTypePtr> types32{GetQType<float>(), GetQType<int32_t>()}; std::vector<QTypePtr> types64{GetQType<double>(), GetQType<int64_t>(), GetQType<uint64_t>(), GetOptionalQType<float>(), GetOptionalQType<int32_t>()}; static_assert(sizeof(OptionalValue<float>) == 8); static_assert(sizeof(OptionalValue<int32_t>) == 8); static_assert(std::is_trivially_copyable_v<OptionalValue<float>>); static_assert(std::is_trivially_copyable_v<OptionalValue<int32_t>>); for (const auto& [name, frame_slot] : frame_slots) { QTypePtr t = frame_slot.GetType(); size_t struct_offset = struct_slots.at(name).byte_offset(); size_t frame_offset = frame_slot.byte_offset(); if (t == b) { offsets_bool_.emplace_back(struct_offset, frame_offset); } else if (absl::c_find(types32, t) != types32.end()) { DCHECK_EQ(t->type_layout().AllocSize(), 4); offsets_32bits_.emplace_back(struct_offset, frame_offset); } else if (absl::c_find(types64, t) != types64.end()) { DCHECK_EQ(t->type_layout().AllocSize(), 8); offsets_64bits_.emplace_back(struct_offset, frame_offset); } else { offsets_other_[t].emplace_back(struct_offset, frame_offset); } } std::sort(offsets_bool_.begin(), offsets_bool_.end()); std::sort(offsets_32bits_.begin(), offsets_32bits_.end()); std::sort(offsets_64bits_.begin(), offsets_64bits_.end()); for (auto& [_, v] : offsets_other_) { std::sort(v.begin(), v.end()); } } void StructIO::CopyStructToFrame(const void* struct_ptr, FramePtr frame) const { const char* src_base = reinterpret_cast<const char*>(struct_ptr); for (const auto& [src, dst] : offsets_bool_) { std::memcpy(frame.GetRawPointer(dst), src_base + src, sizeof(bool)); } for (const auto& [src, dst] : offsets_32bits_) { std::memcpy(frame.GetRawPointer(dst), src_base + src, 4); } for (const auto& [src, dst] : offsets_64bits_) { std::memcpy(frame.GetRawPointer(dst), src_base + src, 8); } for (const auto& [t, offsets] : offsets_other_) { for (const auto& [src, dst] : offsets) { t->UnsafeCopy(src_base + src, frame.GetRawPointer(dst)); } } } void StructIO::CopyFrameToStruct(ConstFramePtr frame, void* struct_ptr) const { char* dst_base = reinterpret_cast<char*>(struct_ptr); for (const auto& [dst, src] : offsets_bool_) { std::memcpy(dst_base + dst, frame.GetRawPointer(src), sizeof(bool)); } for (const auto& [dst, src] : offsets_32bits_) { std::memcpy(dst_base + dst, frame.GetRawPointer(src), 4); } for (const auto& [dst, src] : offsets_64bits_) { std::memcpy(dst_base + dst, frame.GetRawPointer(src), 8); } for (const auto& [t, offsets] : offsets_other_) { for (const auto& [dst, src] : offsets) { t->UnsafeCopy(frame.GetRawPointer(src), dst_base + dst); } } } }
#include "arolla/io/struct_io.h" #include <cstddef> #include <cstdint> #include <optional> #include <string> #include <utility> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/container/flat_hash_map.h" #include "absl/status/status.h" #include "arolla/dense_array/dense_array.h" #include "arolla/dense_array/qtype/types.h" #include "arolla/memory/frame.h" #include "arolla/memory/memory_allocation.h" #include "arolla/memory/optional_value.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/typed_slot.h" #include "arolla/util/bytes.h" #include "arolla/util/testing/status_matchers_backport.h" namespace arolla { namespace { using ::arolla::testing::StatusIs; using ::testing::ElementsAre; using ::testing::UnorderedElementsAreArray; struct TestStruct { int32_t a = 1; bool b = true; float c = 3.0f; int32_t d = 4; int32_t j = 10; DenseArray<int32_t> e; Bytes f; double g = 7.0; int64_t h = 8; OptionalValue<int32_t> i = 9; OptionalValue<float> k = 11.0f; }; #define STRUCT_SLOT(STRUCT, FIELD) \ { \ #FIELD, TypedSlot::UnsafeFromOffset(GetQType<typeof(STRUCT::FIELD)>(), \ offsetof(STRUCT, FIELD)) \ } absl::flat_hash_map<std::string, TypedSlot> GetStructSlots() { return absl::flat_hash_map<std::string, TypedSlot>{ STRUCT_SLOT(TestStruct, a), STRUCT_SLOT(TestStruct, b), STRUCT_SLOT(TestStruct, c), STRUCT_SLOT(TestStruct, d), STRUCT_SLOT(TestStruct, e), STRUCT_SLOT(TestStruct, f), STRUCT_SLOT(TestStruct, g), STRUCT_SLOT(TestStruct, h), STRUCT_SLOT(TestStruct, i), STRUCT_SLOT(TestStruct, j), STRUCT_SLOT(TestStruct, k), }; } TEST(StructIO, GetNamesAndTypes) { ASSERT_OK_AND_ASSIGN(auto input_loader, StructInputLoader<TestStruct>::Create(GetStructSlots())); ASSERT_OK_AND_ASSIGN( auto slot_listener, StructSlotListener<TestStruct>::Create(GetStructSlots())); std::vector<std::string> expected_names{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k"}; EXPECT_THAT(input_loader->SuggestAvailableNames(), UnorderedElementsAreArray(expected_names)); EXPECT_THAT(slot_listener->SuggestAvailableNames(), UnorderedElementsAreArray(expected_names)); EXPECT_EQ(input_loader->GetQTypeOf("e"), GetDenseArrayQType<int32_t>()); EXPECT_EQ(slot_listener->GetQTypeOf("g"), GetQType<double>()); } TEST(StructIO, BasicTest) { ASSERT_OK_AND_ASSIGN(auto input_loader, StructInputLoader<TestStruct>::Create(GetStructSlots())); ASSERT_OK_AND_ASSIGN( auto slot_listener, StructSlotListener<TestStruct>::Create(GetStructSlots())); FrameLayout::Builder bldr; auto a_slot = bldr.AddSlot<int32_t>(); auto d_slot = bldr.AddSlot<int32_t>(); auto j_slot = bldr.AddSlot<int32_t>(); auto k_slot = bldr.AddSlot<OptionalValue<float>>(); auto b_slot = bldr.AddSlot<bool>(); auto c_slot = bldr.AddSlot<float>(); auto i_slot = bldr.AddSlot<OptionalValue<int32_t>>(); FrameLayout layout = std::move(bldr).Build(); absl::flat_hash_map<std::string, TypedSlot> frame_slots{ {"a", TypedSlot::FromSlot(a_slot)}, {"d", TypedSlot::FromSlot(d_slot)}, {"j", TypedSlot::FromSlot(j_slot)}, {"b", TypedSlot::FromSlot(b_slot)}, {"c", TypedSlot::FromSlot(c_slot)}, {"i", TypedSlot::FromSlot(i_slot)}, {"k", TypedSlot::FromSlot(k_slot)}, }; ASSERT_OK_AND_ASSIGN(auto bound_loader, input_loader->Bind(frame_slots)); ASSERT_OK_AND_ASSIGN(auto bound_listener, slot_listener->Bind(frame_slots)); MemoryAllocation alloc(&layout); FramePtr frame = alloc.frame(); TestStruct ts; ASSERT_OK(bound_loader(ts, frame)); EXPECT_EQ(frame.Get(a_slot), 1); EXPECT_EQ(frame.Get(b_slot), true); EXPECT_EQ(frame.Get(c_slot), 3.0f); EXPECT_EQ(frame.Get(d_slot), 4); EXPECT_EQ(frame.Get(i_slot), 9); EXPECT_EQ(frame.Get(j_slot), 10); EXPECT_EQ(frame.Get(k_slot), 11.0f); frame.Set(a_slot, 100); frame.Set(b_slot, false); frame.Set(c_slot, 3.14f); frame.Set(d_slot, 57); frame.Set(i_slot, std::nullopt); frame.Set(j_slot, 19); frame.Set(k_slot, 0.5f); ASSERT_OK(bound_listener(frame, &ts)); EXPECT_EQ(ts.a, 100); EXPECT_EQ(ts.b, false); EXPECT_EQ(ts.c, 3.14f); EXPECT_EQ(ts.d, 57); EXPECT_EQ(ts.i, std::nullopt); EXPECT_EQ(ts.j, 19); EXPECT_EQ(ts.k, 0.5f); } TEST(StructIO, ComplicatedQType) { ASSERT_OK_AND_ASSIGN(auto input_loader, StructInputLoader<TestStruct>::Create(GetStructSlots())); ASSERT_OK_AND_ASSIGN( auto slot_listener, StructSlotListener<TestStruct>::Create(GetStructSlots())); FrameLayout::Builder bldr; auto f_slot = bldr.AddSlot<Bytes>(); auto e_slot = bldr.AddSlot<DenseArray<int32_t>>(); FrameLayout layout = std::move(bldr).Build(); absl::flat_hash_map<std::string, TypedSlot> frame_slots{ {"e", TypedSlot::FromSlot(e_slot)}, {"f", TypedSlot::FromSlot(f_slot)}, }; ASSERT_OK_AND_ASSIGN(auto bound_loader, input_loader->Bind(frame_slots)); ASSERT_OK_AND_ASSIGN(auto bound_listener, slot_listener->Bind(frame_slots)); MemoryAllocation alloc(&layout); FramePtr frame = alloc.frame(); TestStruct ts; ts.e = CreateDenseArray<int32_t>({1, 2, 3}); ts.f = Bytes("abacaba"); ASSERT_OK(bound_loader(ts, frame)); ts.e = DenseArray<int32_t>(); ts.f = Bytes(); EXPECT_THAT(frame.Get(e_slot), ElementsAre(1, 2, 3)); EXPECT_EQ(frame.Get(f_slot), Bytes("abacaba")); ASSERT_OK(bound_listener(frame, &ts)); EXPECT_THAT(ts.e, ElementsAre(1, 2, 3)); EXPECT_EQ(ts.f, Bytes("abacaba")); } TEST(StructIO, Errors) { absl::flat_hash_map<std::string, TypedSlot> struct_slots1{ {"a", TypedSlot::UnsafeFromOffset(GetQType<int32_t>(), 0)}, {"b", TypedSlot::UnsafeFromOffset(GetQType<int32_t>(), 5)}, {"c", TypedSlot::UnsafeFromOffset(GetQType<int32_t>(), 100500)}, }; EXPECT_THAT(StructInputLoader<TestStruct>::Create(struct_slots1), StatusIs(absl::StatusCode::kInvalidArgument, "slot 'c' is not within the struct")); absl::flat_hash_map<std::string, TypedSlot> struct_slots2{ {"a", TypedSlot::UnsafeFromOffset(GetQType<int32_t>(), 4)}, {"b", TypedSlot::UnsafeFromOffset(GetQType<int32_t>(), sizeof(TestStruct) - 3)}, {"c", TypedSlot::UnsafeFromOffset(GetQType<int32_t>(), 0)}, }; EXPECT_THAT(StructSlotListener<TestStruct>::Create(struct_slots2), StatusIs(absl::StatusCode::kInvalidArgument, "slot 'b' is not within the struct")); } } }
2,415
#ifndef AROLLA_IO_TYPED_VALUES_INPUT_LOADER_H_ #define AROLLA_IO_TYPED_VALUES_INPUT_LOADER_H_ #include <string> #include <utility> #include <vector> #include "absl/types/span.h" #include "arolla/io/input_loader.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/typed_ref.h" namespace arolla { InputLoaderPtr<absl::Span<const TypedRef>> CreateTypedRefsInputLoader( const std::vector<std::pair<std::string, QTypePtr>>& args); } #endif #include "arolla/io/typed_refs_input_loader.h" #include <cstddef> #include <memory> #include <string> #include <utility> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "absl/types/span.h" #include "arolla/io/input_loader.h" #include "arolla/memory/frame.h" #include "arolla/memory/raw_buffer_factory.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/typed_ref.h" #include "arolla/util/status_macros_backport.h" namespace arolla { namespace { using Input = absl::Span<const TypedRef>; class TypedRefsInputLoader : public StaticInputLoader<Input> { public: explicit TypedRefsInputLoader( std::vector<std::pair<std::string, QTypePtr>> args) : StaticInputLoader<Input>(std::move(args)) {} private: absl::StatusOr<BoundInputLoader<Input>> BindImpl( const absl::flat_hash_map<std::string, TypedSlot>& output_slots) const override { std::vector<size_t> element_ids; std::vector<TypedSlot> slots; element_ids.reserve(output_slots.size()); slots.reserve(output_slots.size()); for (size_t i = 0; i != types_in_order().size(); ++i) { if (auto it = output_slots.find(types_in_order()[i].first); it != output_slots.end()) { element_ids.push_back(i); slots.push_back(it->second); } } return BoundInputLoader<Input>( [slots = std::move(slots), element_ids = std::move(element_ids), expected_input_size = types_in_order().size()]( const Input& input, FramePtr frame, RawBufferFactory*) -> absl::Status { if (input.size() != expected_input_size) { return absl::InvalidArgumentError( absl::StrFormat("unexpected input count: expected %d, got %d", expected_input_size, input.size())); } for (size_t i = 0; i < slots.size(); ++i) { size_t id = element_ids[i]; DCHECK_LT(id, input.size()); RETURN_IF_ERROR(input[id].CopyToSlot(slots[i], frame)); } return absl::OkStatus(); }); } }; } std::unique_ptr<InputLoader<Input>> CreateTypedRefsInputLoader( const std::vector<std::pair<std::string, QTypePtr>>& args) { return std::make_unique<TypedRefsInputLoader>(args); } }
#include "arolla/io/typed_refs_input_loader.h" #include <utility> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/types/span.h" #include "arolla/io/input_loader.h" #include "arolla/io/testing/matchers.h" #include "arolla/memory/frame.h" #include "arolla/memory/memory_allocation.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/typed_ref.h" #include "arolla/qtype/typed_slot.h" #include "arolla/qtype/typed_value.h" #include "arolla/util/testing/status_matchers_backport.h" namespace arolla { namespace { using ::arolla::testing::InputLoaderSupports; using ::arolla::testing::IsOk; using ::testing::Eq; TEST(TupleInputLoaderTest, Scalars) { using Input = absl::Span<const TypedRef>; std::unique_ptr<InputLoader<Input>> input_loader = CreateTypedRefsInputLoader( {{"a", GetQType<float>()}, {"b", GetQType<int>()}}); EXPECT_THAT(input_loader, InputLoaderSupports({{"a", GetQType<float>()}, {"b", GetQType<int>()}})); FrameLayout::Builder layout_builder; auto a_slot = layout_builder.AddSlot<float>(); auto b_slot = layout_builder.AddSlot<int>(); ASSERT_OK_AND_ASSIGN(BoundInputLoader<Input> bound_input_loader, input_loader->Bind({ {"a", TypedSlot::FromSlot(a_slot)}, {"b", TypedSlot::FromSlot(b_slot)}, })); FrameLayout memory_layout = std::move(layout_builder).Build(); MemoryAllocation alloc(&memory_layout); TypedValue tv_a = TypedValue::FromValue<float>(5); TypedValue tv_b = TypedValue::FromValue<int>(7); ASSERT_THAT(bound_input_loader({tv_a.AsRef(), tv_b.AsRef()}, alloc.frame()), IsOk()); EXPECT_THAT(alloc.frame().Get(a_slot), Eq(5)); EXPECT_THAT(alloc.frame().Get(b_slot), Eq(7)); ASSERT_OK_AND_ASSIGN(BoundInputLoader<Input> bound_b_input_loader, input_loader->Bind({ {"b", TypedSlot::FromSlot(b_slot)}, })); alloc.frame().Set(a_slot, 42); alloc.frame().Set(b_slot, 57); ASSERT_THAT(bound_b_input_loader({tv_a.AsRef(), tv_b.AsRef()}, alloc.frame()), IsOk()); EXPECT_THAT(alloc.frame().Get(a_slot), Eq(42)); EXPECT_THAT(alloc.frame().Get(b_slot), Eq(7)); } } }
2,416
#ifndef AROLLA_IO_WILDCARD_INPUT_LOADER_H_ #define AROLLA_IO_WILDCARD_INPUT_LOADER_H_ #include <algorithm> #include <functional> #include <optional> #include <string> #include <tuple> #include <type_traits> #include <utility> #include <vector> #include "absl/base/attributes.h" #include "absl/base/nullability.h" #include "absl/container/flat_hash_map.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "absl/strings/string_view.h" #include "arolla/io/input_loader.h" #include "arolla/memory/frame.h" #include "arolla/memory/raw_buffer_factory.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/typed_ref.h" #include "arolla/qtype/typed_slot.h" #include "arolla/util/meta.h" #include "arolla/util/status.h" #include "arolla/util/status_macros_backport.h" namespace arolla { template <class Accessor, class Input, class Key, class Output> ABSL_ATTRIBUTE_ALWAYS_INLINE inline absl::Status InvokeWildcardInputLoaderAccessor(const Accessor& accessor, const Input& input, const Key& key, RawBufferFactory* factory, Output* output) { if constexpr (std::is_invocable_v<const Accessor&, const Input&, const Key&, RawBufferFactory*, Output*>) { accessor(input, key, factory, output); } else if constexpr (std::is_invocable_v<const Accessor&, const Input&, const Key&, Output*>) { ((void)(factory)); accessor(input, key, output); } else if constexpr (std::is_invocable_v<const Accessor&, const Input&, const Key&, RawBufferFactory*>) { if constexpr (IsStatusOrT<decltype(accessor(input, key, factory))>::value) { ASSIGN_OR_RETURN(*output, accessor(input, key, factory)); } else { *output = accessor(input, key, factory); } } else if constexpr (std::is_invocable_v<const Accessor&, const Input&, const Key&>) { ((void)(factory)); if constexpr (IsStatusOrT<decltype(accessor(input, key))>::value) { ASSIGN_OR_RETURN(*output, accessor(input, key)); } else { *output = accessor(input, key); } } return absl::OkStatus(); } namespace input_loader_impl { template <class Accessor, class Input, class Key> ABSL_ATTRIBUTE_ALWAYS_INLINE inline auto InvokeWildcardInputLoaderAccessorTypeMeta() { if constexpr (std::is_invocable_v<const Accessor&, const Input&, const Key&, RawBufferFactory*>) { return std::invoke_result<const Accessor&, const Input&, const Key&, RawBufferFactory*>(); } else if constexpr (std::is_invocable_v<const Accessor&, const Input&, const Key&>) { return std::invoke_result<const Accessor&, const Input&, const Key&>(); } else { using info = meta::function_traits<std::decay_t<Accessor>>; if constexpr (info::arity == 3) { using Output = std::remove_pointer_t< std::tuple_element_t<2, typename info::arg_types::tuple>>; static_assert(std::is_invocable_v<const Accessor&, const Input&, const Key&, Output*>, "Unexpected accessor signature."); return meta::type<Output>(); } else { using Output = std::remove_pointer_t< std::tuple_element_t<3, typename info::arg_types::tuple>>; static_assert(std::is_invocable_v<const Accessor&, const Input&, const Key&, RawBufferFactory*, Output*>, "Unexpected accessor signature."); return meta::type<Output>(); } } } std::function<std::optional<std::string>(absl::string_view)> MakeNameToKeyFn( const absl::ParsedFormat<'s'>& format); } template <class Accessor, class Input, class Key> using WildcardAccessorResultType = std::decay_t<strip_statusor_t< typename decltype(input_loader_impl:: InvokeWildcardInputLoaderAccessorTypeMeta< const Accessor&, const Input&, const Key&>())::type>>; class WildcardInputLoaderCallback { public: WildcardInputLoaderCallback(TypedSlot slot, FramePtr frame) : slot_(slot), frame_(frame) {} absl::Status operator()(TypedRef ref) const { RETURN_IF_ERROR(ref.CopyToSlot(slot_, frame_)) << kErrorContext; return absl::OkStatus(); } template <class T> absl::Status operator()(const T& value) const { ASSIGN_OR_RETURN(auto slot, slot_.ToSlot<T>(), _ << kErrorContext); frame_.Set(slot, value); return absl::OkStatus(); } private: static constexpr absl::string_view kErrorContext = "type provided in WildcardInputLoader construction doesn't match the one " "provided in WildcardInputLoaderCallback"; TypedSlot slot_; FramePtr frame_; }; template <class Input> class WildcardInputLoader final : public InputLoader<Input> { public: using CallbackAccessorFn = std::function<absl::Status(const Input& input, const std::string& key, WildcardInputLoaderCallback callback)>; template <class AccessFn> static absl::StatusOr<InputLoaderPtr<Input>> Build( AccessFn accessor, absl::ParsedFormat<'s'> name_format = absl::ParsedFormat<'s'>("%s")) { std::string name_suggestion = absl::StrFormat(name_format, "*"); return BuildImpl(std::move(accessor), input_loader_impl::MakeNameToKeyFn(name_format), {std::move(name_suggestion)}); } template <class AccessFn, class Name2KeyFn> static absl::StatusOr<InputLoaderPtr<Input>> Build( AccessFn accessor, Name2KeyFn name2key, std::vector<std::string> name_suggestions = {}) { return BuildImpl(std::move(accessor), name2key, std::move(name_suggestions)); } static absl::StatusOr<InputLoaderPtr<Input>> BuildFromCallbackAccessorFn( CallbackAccessorFn accessor, absl::flat_hash_map<std::string, QTypePtr> key_types, absl::ParsedFormat<'s'> name_format = absl::ParsedFormat<'s'>("%s")) { std::vector<std::string> name_suggestions; name_suggestions.reserve(key_types.size()); for (const auto& [key, _] : key_types) { name_suggestions.emplace_back(absl::StrFormat(name_format, key)); } std::sort(name_suggestions.begin(), name_suggestions.end()); return BuildFromCallbackImpl( std::move(accessor), input_loader_impl::MakeNameToKeyFn(name_format), [key_types = std::move(key_types)](absl::string_view name) { auto it = key_types.find(name); return it != key_types.end() ? it->second : nullptr; }, std::move(name_suggestions)); } template <typename Name2KeyFn, typename Key2TypeFn> static absl::StatusOr<InputLoaderPtr<Input>> BuildFromCallbackAccessorFn( CallbackAccessorFn accessor, Name2KeyFn name2key, Key2TypeFn key2type, std::vector<std::string> name_suggestions = {}) { return BuildFromCallbackImpl(std::move(accessor), std::move(name2key), std::move(key2type), std::move(name_suggestions)); } absl::Nullable<const QType*> GetQTypeOf(absl::string_view name) const final { return get_qtype_of_fn_(name); } std::vector<std::string> SuggestAvailableNames() const final { return name_suggestions_; } private: explicit WildcardInputLoader( std::function<absl::StatusOr<BoundInputLoader<Input>>( const absl::flat_hash_map<std::string, TypedSlot>&)> bind_fn, std::function<absl::Nullable<const QType*>(absl::string_view)> get_output_type_fn, std::vector<std::string> name_suggestions) : bind_fn_(std::move(bind_fn)), get_qtype_of_fn_(get_output_type_fn), name_suggestions_(std::move(name_suggestions)) {} absl::StatusOr<BoundInputLoader<Input>> BindImpl( const absl::flat_hash_map<std::string, TypedSlot>& output_slots) const final { return bind_fn_(output_slots); } template <typename AccessFn, typename Name2KeyFn> static absl::StatusOr<InputLoaderPtr<Input>> BuildImpl( AccessFn accessor_fn, Name2KeyFn name2key, std::vector<std::string> name_suggestions) { using KeyT = meta::strip_template_t< std::optional, std::decay_t<decltype(name2key(std::declval<std::string>()))>>; using OutT = WildcardAccessorResultType<AccessFn, Input, KeyT>; auto get_output_qtype_fn = [name2key](absl::string_view name) { return name2key(name).has_value() ? GetQType<OutT>() : nullptr; }; return InputLoaderPtr<Input>( static_cast<InputLoader<Input>*>(new WildcardInputLoader( CreateBindFn<AccessFn, KeyT, Name2KeyFn>(std::move(accessor_fn), std::move(name2key)), std::move(get_output_qtype_fn), std::move(name_suggestions)))); } template <typename Key2TypeFn, typename Name2KeyFn> static absl::StatusOr<InputLoaderPtr<Input>> BuildFromCallbackImpl( CallbackAccessorFn accessor_fn, Name2KeyFn name2key, Key2TypeFn key2type, std::vector<std::string> name_suggestions) { auto get_output_qtype_fn = [name2key, key2type = std::move(key2type)]( absl::string_view name) -> const QType* { auto key = name2key(name); return key.has_value() ? key2type(*key) : nullptr; }; return InputLoaderPtr<Input>( static_cast<InputLoader<Input>*>(new WildcardInputLoader( CreateBindFnFromCallbackAccessorFn(std::move(accessor_fn), std::move(name2key)), get_output_qtype_fn, std::move(name_suggestions)))); } template <typename AccessFn, typename Key, typename Name2KeyFn> static auto CreateBindFn(AccessFn accessor_fn, Name2KeyFn name2key) { return [accessor(std::move(accessor_fn)), name2key(std::move(name2key))]( const absl::flat_hash_map<std::string, TypedSlot>& output_slots) -> absl::StatusOr<BoundInputLoader<Input>> { using OutT = WildcardAccessorResultType<AccessFn, Input, Key>; std::vector<std::pair<Key, FrameLayout::Slot<OutT>>> keyed_slots; for (const auto& [slot_name, typed_slot] : output_slots) { auto key = name2key(slot_name); if (!key.has_value()) { continue; } ASSIGN_OR_RETURN(auto slot, typed_slot.template ToSlot<OutT>()); keyed_slots.emplace_back(*std::move(key), slot); } std::sort(keyed_slots.begin(), keyed_slots.end(), [](const auto& a, const auto& b) { return a.first < b.first; }); return BoundInputLoader<Input>( [keyed_slots_(keyed_slots), accessor_(accessor)]( const Input& input, FramePtr frame, RawBufferFactory* factory) -> absl::Status { for (const auto& [key, slot] : keyed_slots_) { RETURN_IF_ERROR(InvokeWildcardInputLoaderAccessor( accessor_, input, key, factory, frame.GetMutable(slot))); } return absl::OkStatus(); }); }; } template <typename Name2KeyFn> static auto CreateBindFnFromCallbackAccessorFn(CallbackAccessorFn accessor_fn, Name2KeyFn name2key) { return [accessor(std::move(accessor_fn)), name2key(std::move(name2key))]( const absl::flat_hash_map<std::string, TypedSlot>& output_slots) -> absl::StatusOr<BoundInputLoader<Input>> { std::vector<std::pair<std::string, TypedSlot>> keyed_slots; for (const auto& [slot_name, typed_slot] : output_slots) { if (auto key = name2key(slot_name); key.has_value()) { keyed_slots.emplace_back(*std::move(key), typed_slot); } } std::sort(keyed_slots.begin(), keyed_slots.end(), [](const auto& a, const auto& b) { return a.first < b.first; }); return BoundInputLoader<Input>( [keyed_slots_(std::move(keyed_slots)), accessor_(std::move(accessor))](const Input& input, FramePtr frame, RawBufferFactory*) -> absl::Status { for (const auto& [key, slot] : keyed_slots_) { RETURN_IF_ERROR(accessor_( input, key, WildcardInputLoaderCallback(slot, frame))) << absl::StrFormat("key: `%s`", key); } return absl::OkStatus(); }); }; } std::function<absl::StatusOr<BoundInputLoader<Input>>( const absl::flat_hash_map<std::string, TypedSlot>&)> bind_fn_; std::function<absl::Nullable<const QType*>(absl::string_view)> get_qtype_of_fn_; std::vector<std::string> name_suggestions_; }; } #endif #include "arolla/io/wildcard_input_loader.h" #include <cstddef> #include <functional> #include <optional> #include <string> #include <utility> #include "absl/log/check.h" #include "absl/strings/str_format.h" #include "absl/strings/string_view.h" #include "absl/strings/strip.h" namespace arolla::input_loader_impl { std::function<std::optional<std::string>(absl::string_view)> MakeNameToKeyFn( const absl::ParsedFormat<'s'>& format) { constexpr absl::string_view kUniqueString = "unique_string_5a7cf4c5ed2d49068302b641bad242aa"; auto formatted = absl::StrFormat(format, kUniqueString); size_t prefix_end = formatted.find(kUniqueString); DCHECK(prefix_end != absl::string_view::npos); std::string prefix = formatted.substr(0, prefix_end); size_t suffix_begin = prefix_end + kUniqueString.size(); DCHECK(suffix_begin <= formatted.size()); std::string suffix = formatted.substr(suffix_begin); return [prefix = std::move(prefix), suffix = std::move(suffix)]( absl::string_view name) -> std::optional<std::string> { if (!absl::ConsumePrefix(&name, prefix)) { return std::nullopt; } if (!absl::ConsumeSuffix(&name, suffix)) { return std::nullopt; } return std::string(name); }; } }
#include "arolla/io/wildcard_input_loader.h" #include <cstddef> #include <cstdint> #include <functional> #include <optional> #include <string> #include <type_traits> #include <utility> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/container/flat_hash_map.h" #include "absl/container/flat_hash_set.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/numbers.h" #include "absl/strings/str_format.h" #include "absl/strings/string_view.h" #include "absl/strings/strip.h" #include "absl/types/optional.h" #include "arolla/io/input_loader.h" #include "arolla/io/testing/matchers.h" #include "arolla/memory/frame.h" #include "arolla/memory/memory_allocation.h" #include "arolla/memory/optional_value.h" #include "arolla/memory/raw_buffer_factory.h" #include "arolla/qtype/optional_qtype.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/typed_ref.h" #include "arolla/qtype/typed_value.h" #include "arolla/util/testing/status_matchers_backport.h" namespace arolla { namespace { using ::arolla::testing::InputLoaderSupports; using ::arolla::testing::StatusIs; using ::testing::ElementsAre; using ::testing::Eq; using ::testing::HasSubstr; using ::testing::IsNull; using ::testing::MatchesRegex; struct DummyInput {}; TEST(WildcardInputLoaderCombinationTest, MakeNameToKeyFn) { { auto fn = input_loader_impl::MakeNameToKeyFn(absl::ParsedFormat<'s'>("%s")); EXPECT_THAT(fn(""), Eq("")); EXPECT_THAT(fn("foo"), Eq("foo")); EXPECT_THAT(fn("foobarbaz\\[.*\"]"), Eq("foobarbaz\\[.*\"]")); } { auto fn = input_loader_impl::MakeNameToKeyFn( absl::ParsedFormat<'s'>("%s_only_suffix")); EXPECT_THAT(fn(""), Eq(std::nullopt)); EXPECT_THAT(fn("_only_suffix"), Eq("")); EXPECT_THAT(fn("foo_only_suffix"), Eq("foo")); } { auto fn = input_loader_impl::MakeNameToKeyFn( absl::ParsedFormat<'s'>("only_prefix_%s")); EXPECT_THAT(fn(""), Eq(std::nullopt)); EXPECT_THAT(fn("only_prefix_"), Eq("")); EXPECT_THAT(fn("only_prefix_foo"), Eq("foo")); } { auto fn = input_loader_impl::MakeNameToKeyFn( absl::ParsedFormat<'s'>("prefix_%s_and_suffix")); EXPECT_THAT(fn(""), Eq(std::nullopt)); EXPECT_THAT(fn("prefix_"), Eq(std::nullopt)); EXPECT_THAT(fn("_and_suffix"), Eq(std::nullopt)); EXPECT_THAT(fn("prefix__and_suffix"), Eq("")); EXPECT_THAT(fn("prefix_foo_and_suffix"), Eq("foo")); } } TEST(InputLoaderTest, InputLoaderAccessorResultType) { using Input = absl::flat_hash_map<std::string, int>; { auto accessor = [](const Input& input, const std::string& key) { return 1; }; static_assert( std::is_same_v< WildcardAccessorResultType<decltype(accessor), Input, std::string>, int>); } { auto accessor = [](const Input& input, const std::string& key) -> absl::StatusOr<int> { return 1; }; static_assert( std::is_same_v< WildcardAccessorResultType<decltype(accessor), Input, std::string>, int>); } { auto accessor = [](const Input& input, const std::string& key, RawBufferFactory*) { return 1; }; static_assert( std::is_same_v< WildcardAccessorResultType<decltype(accessor), Input, std::string>, int>); } { auto accessor = [](const Input& input, const std::string& key, RawBufferFactory*) -> absl::StatusOr<int> { return 1; }; static_assert( std::is_same_v< WildcardAccessorResultType<decltype(accessor), Input, std::string>, int>); } { auto accessor = [](const Input& input, const std::string& key, int* res) { *res = 1; }; static_assert( std::is_same_v< WildcardAccessorResultType<decltype(accessor), Input, std::string>, int>); } { auto accessor = [](const Input& input, const std::string& key, RawBufferFactory*, int* res) { *res = 1; }; static_assert( std::is_same_v< WildcardAccessorResultType<decltype(accessor), Input, std::string>, int>); } } TEST(WildcardInputLoaderTest, FromMapNoError) { using OInt = OptionalValue<int>; auto oi32 = GetQType<OInt>(); using Input = absl::flat_hash_map<std::string, int>; auto accessor = [](const Input& input, const std::string& key) -> OInt { if (auto it = input.find(key); it != input.end()) { return it->second; } else { return std::nullopt; } }; ASSERT_OK_AND_ASSIGN(auto input_loader, WildcardInputLoader<Input>::Build( accessor, absl::ParsedFormat<'s'>("from_map_%s"))); EXPECT_THAT(input_loader, InputLoaderSupports( {{"from_map_a", oi32}, {"from_map_b", oi32}})); EXPECT_THAT(input_loader->SuggestAvailableNames(), ElementsAre("from_map_*")); FrameLayout::Builder layout_builder; auto a_slot = layout_builder.AddSlot<OInt>(); auto b_slot = layout_builder.AddSlot<OInt>(); ASSERT_OK_AND_ASSIGN(BoundInputLoader<Input> bound_input_loader, input_loader->Bind({ {"from_map_a", TypedSlot::FromSlot(a_slot)}, {"from_map_b", TypedSlot::FromSlot(b_slot)}, })); FrameLayout memory_layout = std::move(layout_builder).Build(); MemoryAllocation alloc(&memory_layout); ASSERT_OK(bound_input_loader({{"a", 5}, {"b", 7}}, alloc.frame())); EXPECT_EQ(alloc.frame().Get(a_slot), 5); EXPECT_EQ(alloc.frame().Get(b_slot), 7); ASSERT_OK(bound_input_loader({{"a", 7}}, alloc.frame())); EXPECT_EQ(alloc.frame().Get(a_slot), 7); EXPECT_EQ(alloc.frame().Get(b_slot), std::nullopt); } TEST(WildcardInputLoaderTest, AccessorExecutionOrderIsDetemenistic) { std::vector<std::string> accessor_calls_order; auto accessor = [&](const DummyInput& input, const std::string& key) -> int { accessor_calls_order.push_back(key); return 1; }; ASSERT_OK_AND_ASSIGN(auto input_loader, WildcardInputLoader<DummyInput>::Build(accessor)); EXPECT_THAT(input_loader, InputLoaderSupports({{"a", GetQType<int>()}, {"b", GetQType<int>()}, {"c", GetQType<int>()}})); FrameLayout::Builder layout_builder; auto a_slot = layout_builder.AddSlot<int>(); auto b_slot = layout_builder.AddSlot<int>(); auto c_slot = layout_builder.AddSlot<int>(); ASSERT_OK_AND_ASSIGN(BoundInputLoader<DummyInput> bound_input_loader, input_loader->Bind({ {"a", TypedSlot::FromSlot(a_slot)}, {"b", TypedSlot::FromSlot(b_slot)}, {"c", TypedSlot::FromSlot(c_slot)}, })); FrameLayout memory_layout = std::move(layout_builder).Build(); MemoryAllocation alloc(&memory_layout); ASSERT_OK(bound_input_loader(DummyInput{}, alloc.frame())); EXPECT_THAT(accessor_calls_order, ElementsAre("a", "b", "c")); } TEST(WildcardInputLoaderTest, FromMapNoErrorName2KeyFn) { using OInt = OptionalValue<int>; auto oi32 = GetQType<OInt>(); using Input = absl::flat_hash_map<std::string, int>; auto accessor = [](const Input& input, const std::string& key) -> OInt { if (auto it = input.find(key); it != input.end()) { return it->second; } else { return std::nullopt; } }; auto name2key = [](absl::string_view name) -> std::optional<std::string> { if (!absl::ConsumePrefix(&name, "from_map_")) { return std::nullopt; } if (name != "a" && name != "b") { return std::nullopt; } return std::string(name); }; ASSERT_OK_AND_ASSIGN(auto input_loader, WildcardInputLoader<Input>::Build(accessor, name2key)); EXPECT_THAT(input_loader, InputLoaderSupports( {{"from_map_a", oi32}, {"from_map_b", oi32}})); EXPECT_THAT(input_loader->GetQTypeOf("from_map_x"), IsNull()); FrameLayout::Builder layout_builder; auto a_slot = layout_builder.AddSlot<OInt>(); auto b_slot = layout_builder.AddSlot<OInt>(); ASSERT_OK_AND_ASSIGN(BoundInputLoader<Input> bound_input_loader, input_loader->Bind({ {"from_map_a", TypedSlot::FromSlot(a_slot)}, {"from_map_b", TypedSlot::FromSlot(b_slot)}, })); FrameLayout memory_layout = std::move(layout_builder).Build(); MemoryAllocation alloc(&memory_layout); ASSERT_OK(bound_input_loader({{"a", 5}, {"b", 7}}, alloc.frame())); EXPECT_EQ(alloc.frame().Get(a_slot), 5); EXPECT_EQ(alloc.frame().Get(b_slot), 7); ASSERT_OK(bound_input_loader({{"a", 7}}, alloc.frame())); EXPECT_EQ(alloc.frame().Get(a_slot), 7); EXPECT_EQ(alloc.frame().Get(b_slot), std::nullopt); } TEST(WildcardInputLoaderTest, FromMapOutputArg) { using OInt = OptionalValue<int>; auto oi32 = GetQType<OInt>(); using Input = absl::flat_hash_map<std::string, int>; auto accessor = [](const Input& input, const std::string& key, OInt* output) { if (auto it = input.find(key); it != input.end()) { *output = it->second; } else { *output = std::nullopt; } }; ASSERT_OK_AND_ASSIGN(auto input_loader, WildcardInputLoader<Input>::Build( accessor, absl::ParsedFormat<'s'>("from_map_%s"))); EXPECT_THAT(input_loader, InputLoaderSupports( {{"from_map_a", oi32}, {"from_map_b", oi32}})); EXPECT_THAT(input_loader->SuggestAvailableNames(), ElementsAre("from_map_*")); FrameLayout::Builder layout_builder; auto a_slot = layout_builder.AddSlot<OInt>(); auto b_slot = layout_builder.AddSlot<OInt>(); ASSERT_OK_AND_ASSIGN(BoundInputLoader<Input> bound_input_loader, input_loader->Bind({ {"from_map_a", TypedSlot::FromSlot(a_slot)}, {"from_map_b", TypedSlot::FromSlot(b_slot)}, })); FrameLayout memory_layout = std::move(layout_builder).Build(); MemoryAllocation alloc(&memory_layout); ASSERT_OK(bound_input_loader({{"a", 5}, {"b", 7}}, alloc.frame())); EXPECT_EQ(alloc.frame().Get(a_slot), 5); EXPECT_EQ(alloc.frame().Get(b_slot), 7); ASSERT_OK(bound_input_loader({{"a", 7}}, alloc.frame())); EXPECT_EQ(alloc.frame().Get(a_slot), 7); EXPECT_EQ(alloc.frame().Get(b_slot), std::nullopt); } TEST(WildcardInputLoaderTest, FromMapError) { auto i32 = GetQType<int32_t>(); using Input = absl::flat_hash_map<std::string, int>; auto accessor = [](const Input& input, const std::string& key) -> absl::StatusOr<int> { if (auto it = input.find(key); it != input.end()) { return it->second; } return absl::FailedPreconditionError( absl::StrFormat("key `%s` is not found", key)); }; ASSERT_OK_AND_ASSIGN(auto input_loader, WildcardInputLoader<Input>::Build( accessor, absl::ParsedFormat<'s'>("from_map_%s"))); EXPECT_THAT(input_loader, InputLoaderSupports({{"from_map_a", i32}, {"from_map_b", i32}})); EXPECT_THAT(input_loader->SuggestAvailableNames(), ElementsAre("from_map_*")); FrameLayout::Builder layout_builder; auto a_slot = layout_builder.AddSlot<int>(); auto b_slot = layout_builder.AddSlot<int>(); ASSERT_OK_AND_ASSIGN(BoundInputLoader<Input> bound_input_loader, input_loader->Bind({ {"from_map_a", TypedSlot::FromSlot(a_slot)}, {"from_map_b", TypedSlot::FromSlot(b_slot)}, })); FrameLayout memory_layout = std::move(layout_builder).Build(); MemoryAllocation alloc(&memory_layout); ASSERT_OK(bound_input_loader({{"a", 5}, {"b", 7}}, alloc.frame())); EXPECT_EQ(alloc.frame().Get(a_slot), 5); EXPECT_EQ(alloc.frame().Get(b_slot), 7); EXPECT_THAT(bound_input_loader({{"a", 7}}, alloc.frame()), StatusIs(absl::StatusCode::kFailedPrecondition, HasSubstr("key `b` is not found"))); } TEST(InputLoaderTest, BufferFactoryPropagated) { UnsafeArenaBufferFactory global_factory(1000); auto accessor = [&](int input, const std::string& key, RawBufferFactory* factory) -> bool { return &global_factory == factory; }; ASSERT_OK_AND_ASSIGN(auto input_loader, WildcardInputLoader<int>::Build(accessor)); FrameLayout::Builder layout_builder; auto a_slot = layout_builder.AddSlot<bool>(); ASSERT_OK_AND_ASSIGN(BoundInputLoader<int> bound_input_loader, input_loader->Bind({ {"a", TypedSlot::FromSlot(a_slot)}, })); FrameLayout memory_layout = std::move(layout_builder).Build(); MemoryAllocation alloc(&memory_layout); ASSERT_OK(bound_input_loader(0, alloc.frame(), &global_factory)); EXPECT_TRUE(alloc.frame().Get(a_slot)); UnsafeArenaBufferFactory global_factory2(1000); ASSERT_OK(bound_input_loader(0, alloc.frame(), &global_factory2)); EXPECT_FALSE(alloc.frame().Get(a_slot)); } TEST(InputLoaderTest, BufferFactoryPropagatedOutputArg) { UnsafeArenaBufferFactory global_factory(1000); auto accessor = [&](int input, const std::string& key, RawBufferFactory* factory, bool* output) { *output = (&global_factory == factory); }; ASSERT_OK_AND_ASSIGN(auto input_loader, WildcardInputLoader<int>::Build(accessor)); FrameLayout::Builder layout_builder; auto a_slot = layout_builder.AddSlot<bool>(); ASSERT_OK_AND_ASSIGN(BoundInputLoader<int> bound_input_loader, input_loader->Bind({ {"a", TypedSlot::FromSlot(a_slot)}, })); FrameLayout memory_layout = std::move(layout_builder).Build(); MemoryAllocation alloc(&memory_layout); ASSERT_OK(bound_input_loader(0, alloc.frame(), &global_factory)); EXPECT_TRUE(alloc.frame().Get(a_slot)); UnsafeArenaBufferFactory global_factory2(1000); ASSERT_OK(bound_input_loader(0, alloc.frame(), &global_factory2)); EXPECT_FALSE(alloc.frame().Get(a_slot)); } TEST(WildcardInputLoaderTest, BuildFromCallbackAccessorFnFromStruct) { using Input = std::pair<int, float>; auto accessor = [](const Input& input, const std::string& key, WildcardInputLoaderCallback callback) -> absl::Status { if (key == "x") { return callback(input.first); } if (key == "y") { return callback(TypedRef::FromValue(input.second)); } return absl::FailedPreconditionError( absl::StrFormat("key `%s` is not found", key)); }; ASSERT_OK_AND_ASSIGN( auto input_loader, WildcardInputLoader<Input>::BuildFromCallbackAccessorFn( accessor, {{"x", GetQType<int32_t>()}, {"y", GetQType<float>()}})); EXPECT_THAT(input_loader, InputLoaderSupports({{"x", GetQType<int32_t>()}, {"y", GetQType<float>()}})); EXPECT_THAT(input_loader->GetQTypeOf("z"), IsNull()); EXPECT_THAT(input_loader->SuggestAvailableNames(), ElementsAre("x", "y")); FrameLayout::Builder layout_builder; auto a_slot = layout_builder.AddSlot<int>(); auto b_slot = layout_builder.AddSlot<float>(); ASSERT_OK_AND_ASSIGN(BoundInputLoader<Input> bound_input_loader, input_loader->Bind({ {"x", TypedSlot::FromSlot(a_slot)}, {"y", TypedSlot::FromSlot(b_slot)}, })); FrameLayout memory_layout = std::move(layout_builder).Build(); MemoryAllocation alloc(&memory_layout); ASSERT_OK(bound_input_loader({5, 7.f}, alloc.frame())); EXPECT_EQ(alloc.frame().Get(a_slot), 5); EXPECT_EQ(alloc.frame().Get(b_slot), 7.f); } TEST(WildcardInputLoaderTest, BuildFromCallbackAccessorFnFromMap) { auto i32 = GetQType<int32_t>(); auto f32 = GetQType<float>(); using Input = absl::flat_hash_map<std::string, TypedValue>; auto accessor = [](const Input& input, const std::string& key, WildcardInputLoaderCallback callback) -> absl::Status { if (auto it = input.find(key); it != input.end()) { return callback(it->second.AsRef()); } return absl::FailedPreconditionError( absl::StrFormat("key `%s` is not found", key)); }; ASSERT_OK_AND_ASSIGN( auto input_loader, WildcardInputLoader<Input>::BuildFromCallbackAccessorFn( accessor, {{"a", GetQType<int32_t>()}, {"b", GetQType<float>()}}, absl::ParsedFormat<'s'>("from_map_%s"))); EXPECT_THAT(*input_loader, InputLoaderSupports({{"from_map_a", i32}, {"from_map_b", f32}})); EXPECT_THAT(input_loader->GetQTypeOf("from_map_c"), IsNull()); EXPECT_THAT(input_loader->SuggestAvailableNames(), ElementsAre("from_map_a", "from_map_b")); FrameLayout::Builder layout_builder; auto a_slot = layout_builder.AddSlot<int>(); auto b_slot = layout_builder.AddSlot<float>(); ASSERT_OK_AND_ASSIGN(BoundInputLoader<Input> bound_input_loader, input_loader->Bind({ {"from_map_a", TypedSlot::FromSlot(a_slot)}, {"from_map_b", TypedSlot::FromSlot(b_slot)}, })); FrameLayout memory_layout = std::move(layout_builder).Build(); MemoryAllocation alloc(&memory_layout); ASSERT_OK(bound_input_loader( {{"a", TypedValue::FromValue(5)}, {"b", TypedValue::FromValue(7.f)}}, alloc.frame())); EXPECT_EQ(alloc.frame().Get(a_slot), 5); EXPECT_EQ(alloc.frame().Get(b_slot), 7.f); EXPECT_THAT( bound_input_loader({{"a", TypedValue::FromValue(5)}}, alloc.frame()), StatusIs(absl::StatusCode::kFailedPrecondition, HasSubstr("key `b` is not found"))); EXPECT_THAT(bound_input_loader({{"a", TypedValue::FromValue(5.)}, {"b", TypedValue::FromValue(5.f)}}, alloc.frame()), StatusIs(absl::StatusCode::kInvalidArgument, MatchesRegex(".*type does not match.*expected " "FLOAT64, got INT32.*key: `a`"))); } TEST(WildcardInputLoaderTest, FromVector) { auto i32 = GetQType<int32_t>(); using Input = std::vector<int>; auto accessor = [](const Input& input, const size_t& key) -> absl::StatusOr<int> { return key < input.size() ? input[key] : -1; }; auto name2key = [](absl::string_view key) -> std::optional<int64_t> { if (!absl::ConsumePrefix(&key, "from_vector_")) { return std::nullopt; } int64_t id; if (!absl::SimpleAtoi(key, &id)) { return std::nullopt; } return id; }; ASSERT_OK_AND_ASSIGN(auto input_loader, WildcardInputLoader<Input>::Build(accessor, name2key)); EXPECT_THAT(input_loader, InputLoaderSupports({{"from_vector_0", i32}, {"from_vector_1", i32}})); FrameLayout::Builder layout_builder; auto a_slot = layout_builder.AddSlot<int>(); auto b_slot = layout_builder.AddSlot<int>(); ASSERT_OK_AND_ASSIGN(BoundInputLoader<Input> bound_input_loader, input_loader->Bind({ {"from_vector_0", TypedSlot::FromSlot(a_slot)}, {"from_vector_1", TypedSlot::FromSlot(b_slot)}, })); FrameLayout memory_layout = std::move(layout_builder).Build(); MemoryAllocation alloc(&memory_layout); ASSERT_OK(bound_input_loader({5, 7}, alloc.frame())); EXPECT_EQ(alloc.frame().Get(a_slot), 5); EXPECT_EQ(alloc.frame().Get(b_slot), 7); ASSERT_OK(bound_input_loader({7}, alloc.frame())); EXPECT_EQ(alloc.frame().Get(a_slot), 7); EXPECT_EQ(alloc.frame().Get(b_slot), -1); } struct SeparateSparsityInput { absl::flat_hash_set<std::string> presents; absl::flat_hash_map<std::string, float> values; }; TEST(WildcardInputLoaderTest, FromTwoMapsSeparateSparsity) { auto of32 = GetOptionalQType<float>(); using Input = SeparateSparsityInput; auto accessor = [](const Input& input, const std::string& key) -> absl::StatusOr<OptionalValue<float>> { if (!input.presents.contains(key)) { return std::nullopt; } if (auto it = input.values.find(key); it != input.values.end()) { return {it->second}; } return std::nullopt; }; ASSERT_OK_AND_ASSIGN(auto input_loader, WildcardInputLoader<Input>::Build( accessor, absl::ParsedFormat<'s'>("from_map_%s"))); EXPECT_THAT(input_loader, InputLoaderSupports( {{"from_map_a", of32}, {"from_map_b", of32}})); EXPECT_THAT(input_loader->SuggestAvailableNames(), ElementsAre("from_map_*")); FrameLayout::Builder layout_builder; auto a_slot = layout_builder.AddSlot<OptionalValue<float>>(); auto b_slot = layout_builder.AddSlot<OptionalValue<float>>(); ASSERT_OK_AND_ASSIGN(BoundInputLoader<Input> bound_input_loader, input_loader->Bind({ {"from_map_a", TypedSlot::FromSlot(a_slot)}, {"from_map_b", TypedSlot::FromSlot(b_slot)}, })); FrameLayout memory_layout = std::move(layout_builder).Build(); MemoryAllocation alloc(&memory_layout); ASSERT_OK(bound_input_loader({{"a", "b"}, {{"a", 5.f}, {"b", 7.f}}}, alloc.frame())); EXPECT_EQ(alloc.frame().Get(a_slot), 5.f); EXPECT_EQ(alloc.frame().Get(b_slot), 7.f); ASSERT_OK( bound_input_loader({{"a"}, {{"a", 5.f}, {"b", 7.f}}}, alloc.frame())); EXPECT_EQ(alloc.frame().Get(a_slot), 5.f); EXPECT_EQ(alloc.frame().Get(b_slot), std::nullopt); } } }
2,417
#ifndef AROLLA_IO_PROTO_PROTO_INPUT_LOADER_H_ #define AROLLA_IO_PROTO_PROTO_INPUT_LOADER_H_ #include <string> #include <vector> #include "absl/base/nullability.h" #include "absl/container/flat_hash_map.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "google/protobuf/descriptor.h" #include "google/protobuf/message.h" #include "arolla/io/input_loader.h" #include "arolla/proto/types.h" #include "arolla/qtype/qtype.h" namespace arolla { class ProtoFieldsLoader : public InputLoader<google::protobuf::Message> { struct PrivateConstructorTag {}; public: static absl::StatusOr<InputLoaderPtr<google::protobuf::Message>> Create( const google::protobuf::Descriptor* descr, proto::StringFieldType string_type = proto::StringFieldType::kText); absl::Nullable<const QType*> GetQTypeOf(absl::string_view name) const final; std::vector<std::string> SuggestAvailableNames() const final; explicit ProtoFieldsLoader(PrivateConstructorTag, const google::protobuf::Descriptor* descr, proto::StringFieldType string_type); private: absl::StatusOr<BoundInputLoader<google::protobuf::Message>> BindImpl( const absl::flat_hash_map<std::string, TypedSlot>& output_slots) const override; const google::protobuf::Descriptor* descr_; proto::StringFieldType string_type_; }; } #endif #include "arolla/io/proto/proto_input_loader.h" #include <algorithm> #include <cstddef> #include <memory> #include <string> #include <utility> #include <variant> #include <vector> #include "absl/base/nullability.h" #include "absl/container/flat_hash_map.h" #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/match.h" #include "absl/strings/numbers.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" #include "absl/strings/str_split.h" #include "absl/strings/string_view.h" #include "absl/strings/strip.h" #include "absl/types/span.h" #include "google/protobuf/descriptor.h" #include "google/protobuf/message.h" #include "arolla/io/input_loader.h" #include "arolla/memory/frame.h" #include "arolla/memory/raw_buffer_factory.h" #include "arolla/proto/reflection/reader.h" #include "arolla/proto/types.h" #include "arolla/qtype/qtype.h" #include "arolla/util/status_macros_backport.h" namespace arolla { namespace { using proto::ProtoTypeReader; using proto::StringFieldType; absl::StatusOr<std::unique_ptr<ProtoTypeReader>> CreateReaderWithStringType( absl::Span<const google::protobuf::FieldDescriptor* const> fields, std::vector<proto::ProtoFieldAccessInfo> access_infos, StringFieldType string_type) { auto repeated_it = std::find_if( access_infos.begin(), access_infos.end(), [](proto::ProtoFieldAccessInfo v) { return std::holds_alternative<proto::RepeatedFieldAccess>(v); }); if (repeated_it == access_infos.end()) { if (!access_infos.empty() && std::holds_alternative<proto::RepeatedFieldSizeAccess>( access_infos.back())) { return proto::ProtoTypeReader::CreateDenseArrayShapeReader( fields, std::move(access_infos), string_type); } else { return proto::ProtoTypeReader::CreateOptionalReader( fields, std::move(access_infos), string_type); } } else { return proto::ProtoTypeReader::CreateDenseArrayReader( fields, std::move(access_infos), string_type); } } absl::StatusOr<std::pair<std::string, proto::ProtoFieldAccessInfo>> ParseProtopathElement(absl::string_view path_element) { bool is_size_element = absl::ConsumeSuffix(&path_element, "@size"); if (!absl::StrContains(path_element, '[') && !absl::StrContains(path_element, ']')) { if (is_size_element) { return std::pair{std::string(path_element), proto::RepeatedFieldSizeAccess{}}; } else { return std::pair{std::string(path_element), proto::ProtoFieldAccessInfo{}}; } } if (is_size_element) { return absl::FailedPreconditionError(absl::StrFormat( "@size accessor does not accept field access by index, got %s", path_element)); } std::vector<absl::string_view> splits = absl::StrSplit(path_element, absl::ByAnyChar("[]"), absl::SkipEmpty()); auto error = [&]() { return absl::FailedPreconditionError(absl::StrCat( "cannot parse access by index protopath element: ", path_element)); }; if (splits.size() != 2) { return error(); } std::string field_name(splits[0]); size_t idx = static_cast<size_t>(-1); if (!absl::SimpleAtoi(splits[1], &idx)) { return error(); } if (absl::StrFormat("%s[%d]", field_name, idx) != path_element) { return error(); } return std::pair{field_name, proto::RepeatedFieldIndexAccess{idx}}; } absl::StatusOr<std::unique_ptr<proto::ProtoTypeReader>> ParseProtopathToReader( const google::protobuf::Descriptor* const descr, absl::string_view protopath, proto::StringFieldType string_type) { if (!absl::ConsumePrefix(&protopath, "/")) { return absl::FailedPreconditionError(absl::StrFormat( "protopath must start with '/', got: \"%s\"", protopath)); } std::vector<std::string> elements = absl::StrSplit(protopath, '/'); if (elements.empty()) { return absl::FailedPreconditionError( absl::StrFormat("empty protopath: %s", protopath)); } if (elements.back() == "@size" && elements.size() > 1) { elements.pop_back(); elements.back().append("@size"); } std::vector<const google::protobuf::FieldDescriptor*> fields; std::vector<proto::ProtoFieldAccessInfo> access_infos; const google::protobuf::FieldDescriptor* previous_field = nullptr; for (absl::string_view path_element : elements) { ASSIGN_OR_RETURN((auto [field_name, access_info]), ParseProtopathElement(path_element)); const google::protobuf::Descriptor* current_descr; if (previous_field != nullptr) { current_descr = previous_field->message_type(); if (current_descr == nullptr) { return absl::FailedPreconditionError(absl::StrFormat( "unexpected type of the field `%s` in the protopath " "`%s`: expected a message", previous_field->name(), protopath)); } } else { current_descr = descr; } const google::protobuf::FieldDescriptor* field_descriptor = current_descr->FindFieldByName(field_name); if (field_descriptor == nullptr) { return absl::FailedPreconditionError(absl::StrFormat( "unknown field `%s` in the message `%s` in the protopath `%s`.", field_name, current_descr->full_name(), protopath)); } if (field_descriptor->enum_type() != nullptr || field_descriptor->is_extension()) { return absl::FailedPreconditionError(absl::StrFormat( "unsupported type `%s` of the field `%s` in the protopath `%s`.", field_descriptor->type_name(), field_descriptor->name(), protopath)); } if (field_descriptor->is_repeated() && std::holds_alternative<proto::RegularFieldAccess>(access_info)) { access_info = proto::RepeatedFieldAccess{}; } fields.push_back(field_descriptor); access_infos.push_back(access_info); previous_field = field_descriptor; } bool is_size_protopath = std::holds_alternative<proto::RepeatedFieldSizeAccess>( access_infos.back()); if (previous_field->message_type() != nullptr && !is_size_protopath) { return absl::FailedPreconditionError(absl::StrCat( "unexpected type of the last field in protopath `%s`", protopath)); } return CreateReaderWithStringType(fields, std::move(access_infos), string_type); } } ProtoFieldsLoader::ProtoFieldsLoader(ProtoFieldsLoader::PrivateConstructorTag, const google::protobuf::Descriptor* descr, proto::StringFieldType string_type) : descr_(descr), string_type_(std::move(string_type)) {} absl::StatusOr<std::unique_ptr<InputLoader<google::protobuf::Message>>> ProtoFieldsLoader::Create(const google::protobuf::Descriptor* descr, proto::StringFieldType string_type) { return std::make_unique<ProtoFieldsLoader>(PrivateConstructorTag{}, descr, string_type); } absl::Nullable<const QType*> ProtoFieldsLoader::GetQTypeOf( absl::string_view name) const { ASSIGN_OR_RETURN(const auto& reader, ParseProtopathToReader(descr_, name, string_type_), nullptr); return reader->qtype(); } std::vector<std::string> ProtoFieldsLoader::SuggestAvailableNames() const { return {}; } absl::StatusOr<BoundInputLoader<google::protobuf::Message>> ProtoFieldsLoader::BindImpl( const absl::flat_hash_map<std::string, TypedSlot>& output_slots) const { std::vector<ProtoTypeReader::BoundReadFn> readers; for (const auto& [name, slot] : output_slots) { ASSIGN_OR_RETURN(const auto& reader, ParseProtopathToReader(descr_, name, string_type_)); if (reader->qtype() != slot.GetType()) { return absl::FailedPreconditionError( absl::StrFormat("invalid type for slot %s: expected %s, got %s", name, slot.GetType()->name(), reader->qtype()->name())); } ASSIGN_OR_RETURN(auto read_fn, reader->BindReadFn(slot)); readers.push_back(read_fn); } return BoundInputLoader<google::protobuf::Message>( [descr_(this->descr_), readers_(std::move(readers))]( const google::protobuf::Message& m, FramePtr frame, RawBufferFactory*) -> absl::Status { if (descr_ != m.GetDescriptor()) { return absl::FailedPreconditionError( "message must have the same descriptor as provided during " "construction of ProtoFieldsLoader"); } for (const auto& r : readers_) { r(m, frame); } return absl::OkStatus(); }); } }
#include "arolla/io/proto/proto_input_loader.h" #include <memory> #include <optional> #include <string> #include <utility> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "google/protobuf/message.h" #include "arolla/dense_array/dense_array.h" #include "arolla/dense_array/qtype/types.h" #include "arolla/io/input_loader.h" #include "arolla/io/testing/matchers.h" #include "arolla/memory/frame.h" #include "arolla/memory/memory_allocation.h" #include "arolla/memory/optional_value.h" #include "arolla/naming/table.h" #include "arolla/proto/test.pb.h" #include "arolla/proto/types.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/util/bytes.h" #include "arolla/util/text.h" namespace arolla { namespace { using ::arolla::testing::InputLoaderSupports; using ::testing::ElementsAre; using ::testing::Eq; using ::testing::IsEmpty; using ::testing::IsNull; template <typename T> class ProtoLoaderTest : public ::testing::Test { public: using StringType = T; }; using StringTypes = ::testing::Types<Text, Bytes>; TYPED_TEST_SUITE(ProtoLoaderTest, StringTypes); TYPED_TEST(ProtoLoaderTest, LoadScalars) { using StringType = TypeParam; proto::StringFieldType string_type = std::is_same_v<StringType, Text> ? proto::StringFieldType::kText : proto::StringFieldType::kBytes; ASSERT_OK_AND_ASSIGN( auto input_loader_ptr, ProtoFieldsLoader::Create(::testing_namespace::Root::descriptor(), string_type)); const InputLoader<google::protobuf::Message>& input_loader = *input_loader_ptr; using OInt = ::arolla::OptionalValue<int>; using OBytes = ::arolla::OptionalValue<Bytes>; using OText = ::arolla::OptionalValue<StringType>; auto oi32 = GetQType<OInt>(); auto obytes = GetQType<OBytes>(); auto otxt = GetQType<OText>(); std::string x_def_name(naming::TablePath().Column("x").FullName()); std::string inner_a_def_name( naming::TablePath("inner").Column("a").FullName()); std::string inner_inner2_z_def_name( naming::TablePath("inner").Child("inner2").Column("z").FullName()); std::string str_def_name(naming::TablePath().Column("str").FullName()); std::string raw_bytes_def_name( naming::TablePath().Column("raw_bytes").FullName()); EXPECT_THAT(input_loader, InputLoaderSupports({{x_def_name, oi32}, {inner_a_def_name, oi32}, {inner_inner2_z_def_name, oi32}, {str_def_name, otxt}, {raw_bytes_def_name, obytes}})); FrameLayout::Builder layout_builder; auto x_def_slot = layout_builder.AddSlot<OInt>(); auto inner_a_def_slot = layout_builder.AddSlot<OInt>(); auto inner_inner2_z_def_slot = layout_builder.AddSlot<OInt>(); auto str_def_slot = layout_builder.AddSlot<OText>(); auto raw_bytes_def_slot = layout_builder.AddSlot<OBytes>(); ASSERT_OK_AND_ASSIGN( auto bound_input_loader, input_loader.Bind({ {x_def_name, TypedSlot::FromSlot(x_def_slot)}, {inner_a_def_name, TypedSlot::FromSlot(inner_a_def_slot)}, {inner_inner2_z_def_name, TypedSlot::FromSlot(inner_inner2_z_def_slot)}, {str_def_name, TypedSlot::FromSlot(str_def_slot)}, {raw_bytes_def_name, TypedSlot::FromSlot(raw_bytes_def_slot)}, })); FrameLayout memory_layout = std::move(layout_builder).Build(); MemoryAllocation alloc(&memory_layout); FramePtr frame = alloc.frame(); ::testing_namespace::Root r; r.set_x(19); r.set_str("3"); r.set_raw_bytes("37"); r.mutable_inner()->set_a(57); r.mutable_inner()->mutable_inner2()->set_z(2); ASSERT_OK(bound_input_loader(r, frame)); EXPECT_EQ(frame.Get(x_def_slot), 19); EXPECT_EQ(frame.Get(inner_a_def_slot), 57); EXPECT_EQ(frame.Get(inner_inner2_z_def_slot), 2); EXPECT_EQ(frame.Get(str_def_slot), StringType("3")); EXPECT_EQ(frame.Get(raw_bytes_def_slot), arolla::Bytes("37")); r.clear_x(); r.clear_str(); r.clear_inner(); ASSERT_OK(bound_input_loader(r, frame)); EXPECT_EQ(frame.Get(x_def_slot), std::nullopt); EXPECT_EQ(frame.Get(inner_a_def_slot), std::nullopt); EXPECT_EQ(frame.Get(inner_inner2_z_def_slot), std::nullopt); EXPECT_EQ(frame.Get(str_def_slot), std::nullopt); } TEST(ProtoFieldsLoaderTest, ProtopathIndexAccess) { ASSERT_OK_AND_ASSIGN( auto input_loader, ProtoFieldsLoader::Create(::testing_namespace::Root::descriptor())); using oint = ::arolla::OptionalValue<int>; auto oi32 = GetQType<oint>(); std::string ys_def_name( naming::TablePath().Column(naming::ArrayAccess("ys", 0)).FullName()); std::string inners_a_def_name(naming::TablePath() .Child(naming::ArrayAccess("inners", 0)) .Column("a") .FullName()); std::string inners_as_def_name(naming::TablePath() .Child(naming::ArrayAccess("inners", 1)) .Column(naming::ArrayAccess("as", 0)) .FullName()); EXPECT_THAT(input_loader, InputLoaderSupports({{ys_def_name, oi32}, {inners_a_def_name, oi32}, {inners_as_def_name, oi32}})); FrameLayout::Builder layout_builder; auto ys_def_slot = layout_builder.AddSlot<oint>(); auto inners_a_def_slot = layout_builder.AddSlot<oint>(); auto inners_as_def_slot = layout_builder.AddSlot<oint>(); ASSERT_OK_AND_ASSIGN( auto bound_input_loader, input_loader->Bind({ {ys_def_name, TypedSlot::FromSlot(ys_def_slot)}, {inners_a_def_name, TypedSlot::FromSlot(inners_a_def_slot)}, {inners_as_def_name, TypedSlot::FromSlot(inners_as_def_slot)}, })); FrameLayout memory_layout = std::move(layout_builder).Build(); MemoryAllocation alloc(&memory_layout); FramePtr frame = alloc.frame(); ::testing_namespace::Root r; r.add_ys(19); r.add_inners()->set_a(17); r.add_inners()->add_as(57); ASSERT_OK(bound_input_loader(r, frame)); EXPECT_EQ(frame.Get(ys_def_slot), 19); EXPECT_EQ(frame.Get(inners_a_def_slot), 17); EXPECT_EQ(frame.Get(inners_as_def_slot), 57); r.clear_ys(); r.clear_inners(); ASSERT_OK(bound_input_loader(r, frame)); EXPECT_EQ(frame.Get(ys_def_slot), std::nullopt); EXPECT_EQ(frame.Get(inners_a_def_slot), std::nullopt); EXPECT_EQ(frame.Get(inners_as_def_slot), std::nullopt); } TEST(ProtoFieldsLoaderTest, ProtopathRepeatedAccess) { ASSERT_OK_AND_ASSIGN( auto input_loader, ProtoFieldsLoader::Create(::testing_namespace::Root::descriptor())); using OInt = ::arolla::OptionalValue<int>; using DAInt = arolla::DenseArray<int>; auto dai32 = GetDenseArrayQType<int>(); std::string ys_def_name(naming::TablePath().Column("ys").FullName()); std::string inners_a_def_name( naming::TablePath().Child("inners").Column("a").FullName()); std::string inners_as_def_name( naming::TablePath().Child("inners").Column("as").FullName()); EXPECT_THAT(input_loader, InputLoaderSupports({{ys_def_name, dai32}, {inners_a_def_name, dai32}, {inners_as_def_name, dai32}})); FrameLayout::Builder layout_builder; auto ys_def_slot = layout_builder.AddSlot<DAInt>(); auto inners_a_def_slot = layout_builder.AddSlot<DAInt>(); auto inners_as_def_slot = layout_builder.AddSlot<DAInt>(); ASSERT_OK_AND_ASSIGN( auto bound_input_loader, input_loader->Bind({ {ys_def_name, TypedSlot::FromSlot(ys_def_slot)}, {inners_a_def_name, TypedSlot::FromSlot(inners_a_def_slot)}, {inners_as_def_name, TypedSlot::FromSlot(inners_as_def_slot)}, })); FrameLayout memory_layout = std::move(layout_builder).Build(); MemoryAllocation alloc(&memory_layout); FramePtr frame = alloc.frame(); ::testing_namespace::Root r; r.add_ys(19); r.add_ys(3); auto inners_0 = r.add_inners(); inners_0->set_a(17); inners_0->add_as(57); inners_0->add_as(37); r.add_inners(); auto inners_2 = r.add_inners(); inners_2->set_a(3); inners_2->add_as(17); ASSERT_OK(bound_input_loader(r, frame)); EXPECT_THAT(frame.Get(ys_def_slot), ElementsAre(OInt{19}, OInt{3})); EXPECT_THAT(frame.Get(inners_a_def_slot), ElementsAre(OInt{17}, std::nullopt, OInt{3})); EXPECT_THAT(frame.Get(inners_as_def_slot), ElementsAre(OInt{57}, OInt{37}, OInt{17})); r.clear_ys(); r.clear_inners(); ASSERT_OK(bound_input_loader(r, frame)); EXPECT_THAT(frame.Get(ys_def_slot), IsEmpty()); EXPECT_THAT(frame.Get(inners_a_def_slot), IsEmpty()); EXPECT_THAT(frame.Get(inners_as_def_slot), IsEmpty()); } TEST(SizeAccessLoaderTest, ProtopathRepeatedSizeAccess) { ASSERT_OK_AND_ASSIGN( auto input_loader, ProtoFieldsLoader::Create(::testing_namespace::Root::descriptor())); using Size = proto::arolla_size_t; using VSize = ::arolla::DenseArray<Size>; auto root_size = GetQType<DenseArrayShape>(); auto v_size = GetDenseArrayQType<Size>(); std::string ys_size_name(naming::TablePath().Size("ys").FullName()); std::string inners_size_name(naming::TablePath().Size("inners").FullName()); std::string inners_as_size_name( naming::TablePath().Child("inners").Size("as").FullName()); EXPECT_THAT(*input_loader, InputLoaderSupports({{ys_size_name, root_size}, {inners_size_name, root_size}, {inners_as_size_name, v_size}})); FrameLayout::Builder layout_builder; auto ys_size_slot = layout_builder.AddSlot<DenseArrayShape>(); auto inners_size_slot = layout_builder.AddSlot<DenseArrayShape>(); auto inners_as_size_slot = layout_builder.AddSlot<VSize>(); ASSERT_OK_AND_ASSIGN( auto bound_input_loader, input_loader->Bind({ {ys_size_name, TypedSlot::FromSlot(ys_size_slot)}, {inners_size_name, TypedSlot::FromSlot(inners_size_slot)}, {inners_as_size_name, TypedSlot::FromSlot(inners_as_size_slot)}, })); FrameLayout memory_layout = std::move(layout_builder).Build(); MemoryAllocation alloc(&memory_layout); FramePtr frame = alloc.frame(); ::testing_namespace::Root r; r.add_ys(19); r.add_ys(3); auto inners_0 = r.add_inners(); inners_0->add_as(57); inners_0->add_as(37); r.add_inners(); auto inners_2 = r.add_inners(); inners_2->add_as(17); ASSERT_OK(bound_input_loader(r, frame)); EXPECT_THAT(frame.Get(ys_size_slot), Eq(DenseArrayShape{.size = 2})); EXPECT_THAT(frame.Get(inners_size_slot), Eq(DenseArrayShape{.size = 3})); EXPECT_THAT(frame.Get(inners_as_size_slot), ElementsAre(2, 0, 1)); r.clear_ys(); r.clear_inners(); ASSERT_OK(bound_input_loader(r, frame)); EXPECT_THAT(frame.Get(ys_size_slot), Eq(DenseArrayShape{.size = 0})); EXPECT_THAT(frame.Get(inners_size_slot), Eq(DenseArrayShape{.size = 0})); EXPECT_THAT(frame.Get(inners_as_size_slot), IsEmpty()); } TYPED_TEST(ProtoLoaderTest, LoadDenseArrays) { using StringType = TypeParam; proto::StringFieldType string_type = std::is_same_v<StringType, Text> ? proto::StringFieldType::kText : proto::StringFieldType::kBytes; ASSERT_OK_AND_ASSIGN( auto input_loader_ptr, ProtoFieldsLoader::Create(::testing_namespace::Root::descriptor(), string_type)); const InputLoader<google::protobuf::Message>& input_loader = *input_loader_ptr; using OText = ::arolla::OptionalValue<StringType>; using OBytes = ::arolla::OptionalValue<Bytes>; using DAText = ::arolla::DenseArray<StringType>; using DABytes = ::arolla::DenseArray<Bytes>; std::string str_name(naming::TablePath().Column("repeated_str").FullName()); std::string bytes_name( naming::TablePath().Column("repeated_raw_bytes").FullName()); EXPECT_THAT(input_loader, InputLoaderSupports({{str_name, GetQType<DAText>()}, {bytes_name, GetQType<DABytes>()}})); FrameLayout::Builder layout_builder; auto str_slot = layout_builder.AddSlot<DAText>(); auto bytes_slot = layout_builder.AddSlot<DABytes>(); ASSERT_OK_AND_ASSIGN(auto bound_input_loader, input_loader.Bind({ {str_name, TypedSlot::FromSlot(str_slot)}, {bytes_name, TypedSlot::FromSlot(bytes_slot)}, })); FrameLayout memory_layout = std::move(layout_builder).Build(); MemoryAllocation alloc(&memory_layout); FramePtr frame = alloc.frame(); ::testing_namespace::Root r; *r.add_repeated_str() = "19"; *r.add_repeated_str() = "3"; *r.add_repeated_raw_bytes() = "3"; *r.add_repeated_raw_bytes() = "19"; ASSERT_OK(bound_input_loader(r, frame)); EXPECT_THAT(frame.Get(str_slot), ElementsAre(OText{StringType{"19"}}, OText{StringType{"3"}})); EXPECT_THAT(frame.Get(bytes_slot), ElementsAre(OBytes{Bytes{"3"}}, OBytes{Bytes{"19"}})); r.clear_repeated_str(); r.clear_repeated_raw_bytes(); ASSERT_OK(bound_input_loader(r, frame)); EXPECT_THAT(frame.Get(str_slot), IsEmpty()); EXPECT_THAT(frame.Get(bytes_slot), IsEmpty()); } TEST(SizeAccessErrorsLoaderTest, CreateFromProtopathsErrors) { ASSERT_OK_AND_ASSIGN( auto input_loader_ptr, ProtoFieldsLoader::Create(::testing_namespace::Root::descriptor())); EXPECT_THAT(input_loader_ptr->GetQTypeOf(""), IsNull()); EXPECT_THAT(input_loader_ptr->GetQTypeOf("/"), IsNull()); EXPECT_THAT(input_loader_ptr->GetQTypeOf("x"), IsNull()); EXPECT_THAT(input_loader_ptr->GetQTypeOf("/i_am_not_here"), IsNull()); EXPECT_THAT(input_loader_ptr->GetQTypeOf("/x[:]"), IsNull()); EXPECT_THAT(input_loader_ptr->GetQTypeOf("/x[0]"), IsNull()); EXPECT_THAT(input_loader_ptr->GetQTypeOf("/x/y"), IsNull()); EXPECT_THAT(input_loader_ptr->GetQTypeOf("/ys/x"), IsNull()); for (auto ppath : {"/ys[]", "/ys[-1]", "/ys[a]", "/ys[0x0]", "/ys[\"0\"]", "/ys[00]", "/ys[ 0 ]"}) { EXPECT_THAT(input_loader_ptr->GetQTypeOf(ppath), IsNull()) << "ppath=" << ppath; } } TEST(SizeAccessErrorsLoaderTest, CreateFromSizeProtopathsErrors) { ASSERT_OK_AND_ASSIGN( auto input_loader_ptr, ProtoFieldsLoader::Create(::testing_namespace::Root::descriptor())); EXPECT_THAT(input_loader_ptr->GetQTypeOf("/i_am_not_here/@size"), IsNull()); EXPECT_THAT(input_loader_ptr->GetQTypeOf("/@size"), IsNull()); EXPECT_THAT(input_loader_ptr->GetQTypeOf("/x/@size"), IsNull()); EXPECT_THAT(input_loader_ptr->GetQTypeOf("/ys[0]/@size"), IsNull()); EXPECT_THAT(input_loader_ptr->GetQTypeOf("/inners/@size/a"), IsNull()); } } }
2,418
#ifndef AROLLA_EXPR_REGISTERED_EXPR_OPERATOR_H_ #define AROLLA_EXPR_REGISTERED_EXPR_OPERATOR_H_ #include <atomic> #include <cstdint> #include <memory> #include <string> #include <utility> #include <vector> #include "absl/base/thread_annotations.h" #include "absl/container/flat_hash_map.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "absl/synchronization/mutex.h" #include "absl/types/span.h" #include "arolla/expr/expr_attributes.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/util/repr.h" #include "arolla/util/thread_safe_shared_ptr.h" namespace arolla::expr { class RegisteredOperator; using RegisteredOperatorPtr = std::shared_ptr<RegisteredOperator>; absl::StatusOr<RegisteredOperatorPtr> LookupOperator(absl::string_view name); bool IsRegisteredOperator(const ExprOperatorPtr& op); absl::StatusOr<ExprOperatorPtr> DecayRegisteredOperator( ExprOperatorPtr op); absl::StatusOr<ExprOperatorPtr> RegisterOperator( absl::string_view name, absl::StatusOr<ExprOperatorPtr> op_or_status); absl::StatusOr<ExprOperatorPtr> RegisterOperatorAlias( absl::string_view alias_name, absl::string_view original_operator_name); template <typename ExprOperatorT, typename... Args> absl::StatusOr<ExprOperatorPtr> RegisterOperator(absl::string_view name, Args&&... args) { return RegisterOperator( name, std::make_shared<ExprOperatorT>(std::forward<Args>(args)...)); } class ExprOperatorRegistry final { public: static ExprOperatorRegistry* GetInstance(); ExprOperatorRegistry(); ExprOperatorRegistry(const ExprOperatorRegistry&) = delete; ExprOperatorRegistry& operator=(const ExprOperatorRegistry&) = delete; absl::StatusOr<RegisteredOperatorPtr> Register(absl::string_view name, ExprOperatorPtr op_impl) ABSL_LOCKS_EXCLUDED(mx_); RegisteredOperatorPtr LookupOperatorOrNull( absl::string_view name) const ABSL_LOCKS_EXCLUDED(mx_); std::vector<absl::string_view> ListRegisteredOperators() const ABSL_LOCKS_EXCLUDED(mx_); class OperatorImplementationFn; OperatorImplementationFn AcquireOperatorImplementationFn( absl::string_view name) ABSL_LOCKS_EXCLUDED(mx_); class RevisionIdFn; RevisionIdFn AcquireRevisionIdFn(absl::string_view name) ABSL_LOCKS_EXCLUDED(mx_); void UnsafeUnregister(absl::string_view name) ABSL_LOCKS_EXCLUDED(mx_); private: struct Record { explicit Record(absl::string_view name); Record(const Record&) = delete; Record& operator=(const Record&) = delete; const std::string name; const RegisteredOperatorPtr registered_operator; Record* parent = nullptr; std::atomic<int64_t> revision_id = 0; ThreadSafeSharedPtr<const ExprOperator> operator_implementation; }; Record& LookupOrCreateRecordSingleton(absl::string_view name) ABSL_LOCKS_EXCLUDED(mx_); Record* LookupRecordSingleton(absl::string_view name) const ABSL_LOCKS_EXCLUDED(mx_); void UpdateRevisionIds(Record& record) ABSL_LOCKS_EXCLUDED(mx_); absl::flat_hash_map<absl::string_view, std::unique_ptr<Record>> registry_ ABSL_GUARDED_BY(mx_); std::vector<absl::string_view> registered_operators_ ABSL_GUARDED_BY(mx_); mutable absl::Mutex mx_; }; class ExprOperatorRegistry::RevisionIdFn { public: explicit RevisionIdFn(const Record& record_singleton) : record_singleton_(record_singleton) {} int64_t operator()() const { return record_singleton_.revision_id.load(); } private: const Record& record_singleton_; }; class ExprOperatorRegistry::OperatorImplementationFn { public: explicit OperatorImplementationFn(const Record& record_singleton) : record_singleton_(record_singleton) {} ExprOperatorPtr operator()() const { return record_singleton_.operator_implementation.load(); } private: const Record& record_singleton_; }; class RegisteredOperator final : public ExprOperator { struct PrivateConstructorTag {}; public: explicit RegisteredOperator(absl::string_view name); RegisteredOperator(PrivateConstructorTag, absl::string_view name, ExprOperatorRegistry::OperatorImplementationFn op_impl_fn); absl::StatusOr<ExprOperatorPtr> GetImplementation() const; absl::StatusOr<ExprOperatorSignature> GetSignature() const final; absl::StatusOr<std::string> GetDoc() const final; absl::StatusOr<ExprAttributes> InferAttributes( absl::Span<const ExprAttributes> inputs) const final; absl::StatusOr<ExprNodePtr> ToLowerLevel(const ExprNodePtr& node) const final; ReprToken GenReprToken() const final; absl::string_view py_qvalue_specialization_key() const final { return "::arolla::expr::RegisteredOperator"; } private: ExprOperatorRegistry::OperatorImplementationFn op_impl_fn_; friend class ExprOperatorRegistry; }; } #endif #include "arolla/expr/registered_expr_operator.h" #include <algorithm> #include <memory> #include <sstream> #include <string> #include <utility> #include <vector> #include "absl/base/attributes.h" #include "absl/base/optimization.h" #include "absl/container/flat_hash_map.h" #include "absl/container/flat_hash_set.h" #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/escaping.h" #include "absl/strings/str_format.h" #include "absl/strings/string_view.h" #include "absl/synchronization/mutex.h" #include "absl/types/span.h" #include "arolla/expr/expr_attributes.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/util/fast_dynamic_downcast_final.h" #include "arolla/util/fingerprint.h" #include "arolla/util/indestructible.h" #include "arolla/util/operator_name.h" #include "arolla/util/repr.h" #include "arolla/util/string.h" #include "arolla/util/status_macros_backport.h" namespace arolla::expr { namespace { class CircularDependencyDetector final { public: static constexpr int kIgnoreDepth = 24; CircularDependencyDetector(const CircularDependencyDetector&) = delete; CircularDependencyDetector& operator=(const CircularDependencyDetector&) = delete; template <typename... Args> ABSL_ATTRIBUTE_ALWAYS_INLINE explicit CircularDependencyDetector( Args&&... args) { if (ABSL_PREDICT_FALSE(++thread_local_depth_ > kIgnoreDepth)) { Push(std::forward<Args>(args)...); } } ABSL_ATTRIBUTE_ALWAYS_INLINE ~CircularDependencyDetector() { if (ABSL_PREDICT_FALSE(thread_local_depth_-- > kIgnoreDepth)) { Pop(); } } ABSL_ATTRIBUTE_ALWAYS_INLINE bool ok() const { return ABSL_PREDICT_TRUE(thread_local_depth_ <= kIgnoreDepth) || (token_ != kFail); } private: static constexpr Fingerprint kFail = {0}; ABSL_ATTRIBUTE_NOINLINE void Push(const Fingerprint& token) { DCHECK_NE(token, kFail); if (thread_local_visited_.emplace(token).second) { token_ = token; } } ABSL_ATTRIBUTE_NOINLINE void Push(absl::string_view registered_operator_name, absl::Span<const ExprAttributes> inputs) { Push(FingerprintHasher(registered_operator_name) .Combine(0) .CombineSpan(inputs) .Finish()); } ABSL_ATTRIBUTE_NOINLINE void Push(absl::string_view registered_operator_name, const ExprNodePtr& node) { Push(FingerprintHasher(registered_operator_name) .Combine(1, node->fingerprint()) .Finish()); } ABSL_ATTRIBUTE_NOINLINE void Pop() { thread_local_visited_.erase(token_); } Fingerprint token_ = kFail; static thread_local int thread_local_depth_; static thread_local absl::flat_hash_set<Fingerprint> thread_local_visited_; }; thread_local int CircularDependencyDetector::thread_local_depth_ = 0; thread_local absl::flat_hash_set<Fingerprint> CircularDependencyDetector::thread_local_visited_; } absl::StatusOr<RegisteredOperatorPtr> LookupOperator(absl::string_view name) { if (auto op = ExprOperatorRegistry::GetInstance()->LookupOperatorOrNull(name)) { return op; } return absl::NotFoundError( absl::StrFormat("operator '%s' not found", absl::CEscape(name))); } bool IsRegisteredOperator(const ExprOperatorPtr& op) { return fast_dynamic_downcast_final<const RegisteredOperator*>(op.get()) != nullptr; } absl::StatusOr<ExprOperatorPtr> DecayRegisteredOperator( ExprOperatorPtr op) { for (int depth = 0; depth < CircularDependencyDetector::kIgnoreDepth; ++depth) { const auto* reg_op = fast_dynamic_downcast_final<const RegisteredOperator*>(op.get()); if (reg_op == nullptr) { return op; } ASSIGN_OR_RETURN(op, reg_op->GetImplementation()); } absl::flat_hash_set<Fingerprint> visited; for (;;) { if (!visited.emplace(op->fingerprint()).second) { return absl::FailedPreconditionError( absl::StrFormat("arolla::expr::DecayRegisteredOperator: " "detected a circular dependency: op_name=%s", op->display_name())); } const auto* reg_op = fast_dynamic_downcast_final<const RegisteredOperator*>(op.get()); if (reg_op == nullptr) { return op; } ASSIGN_OR_RETURN(op, reg_op->GetImplementation()); } } absl::StatusOr<ExprOperatorPtr> RegisterOperator( absl::string_view name, absl::StatusOr<ExprOperatorPtr> op_or_status) { if (!op_or_status.ok()) { return op_or_status; } return ExprOperatorRegistry::GetInstance()->Register( name, *std::move(op_or_status)); } absl::StatusOr<ExprOperatorPtr> RegisterOperatorAlias( absl::string_view alias_name, absl::string_view original_operator_name) { return RegisterOperator(alias_name, LookupOperator(original_operator_name)); } RegisteredOperator::RegisteredOperator(absl::string_view name) : RegisteredOperator( PrivateConstructorTag{}, name, ExprOperatorRegistry::GetInstance()->AcquireOperatorImplementationFn( name)) {} RegisteredOperator::RegisteredOperator( PrivateConstructorTag, absl::string_view name, ExprOperatorRegistry::OperatorImplementationFn op_impl_fn) : ExprOperator(name, FingerprintHasher("arolla::expr::RegisteredOperator") .Combine(name) .Finish()), op_impl_fn_(std::move(op_impl_fn)) {} absl::StatusOr<ExprOperatorPtr> RegisteredOperator::GetImplementation() const { auto result = op_impl_fn_(); if (result == nullptr) { return absl::NotFoundError(absl::StrFormat("operator '%s' not found", absl::CEscape(display_name()))); } return result; } absl::StatusOr<ExprOperatorSignature> RegisteredOperator::GetSignature() const { CircularDependencyDetector guard(fingerprint()); if (ABSL_PREDICT_FALSE(!guard.ok())) { return absl::FailedPreconditionError( absl::StrFormat("arolla::expr::RegisteredOperator::GetSignature: " "detected a circular dependency: op_name=%s", display_name())); } ASSIGN_OR_RETURN(auto op_impl, GetImplementation()); return op_impl->GetSignature(); } absl::StatusOr<std::string> RegisteredOperator::GetDoc() const { CircularDependencyDetector guard(fingerprint()); if (ABSL_PREDICT_FALSE(!guard.ok())) { return absl::FailedPreconditionError( absl::StrFormat("arolla::expr::RegisteredOperator::GetDoc: " "detected a circular dependency: op_name=%s", display_name())); } ASSIGN_OR_RETURN(auto op_impl, GetImplementation()); return op_impl->GetDoc(); } absl::StatusOr<ExprAttributes> RegisteredOperator::InferAttributes( absl::Span<const ExprAttributes> inputs) const { CircularDependencyDetector guard(display_name(), inputs); if (ABSL_PREDICT_FALSE(!guard.ok())) { std::ostringstream message; message << "arolla::expr::RegisteredOperator::InferAttributes: " "detected a circular dependency: op_name=" << display_name() << ", inputs=["; bool first = true; for (const auto& input : inputs) { message << NonFirstComma(first) << input; } message << "]"; return absl::FailedPreconditionError(std::move(message).str()); } ASSIGN_OR_RETURN(auto op_impl, GetImplementation()); return op_impl->InferAttributes(inputs); } absl::StatusOr<ExprNodePtr> RegisteredOperator::ToLowerLevel( const ExprNodePtr& node) const { CircularDependencyDetector guard(display_name(), node); if (ABSL_PREDICT_FALSE(!guard.ok())) { std::ostringstream message; message << "arolla::expr::RegisteredOperator::ToLowerLevel: " "detected a circular dependency: op_name=" << display_name() << ", inputs=["; bool first = true; for (const auto& node_dep : node->node_deps()) { message << NonFirstComma(first) << node_dep->attr(); } message << "]"; return absl::FailedPreconditionError(std::move(message).str()); } ASSIGN_OR_RETURN(auto op_impl, GetImplementation()); return op_impl->ToLowerLevel(node); } ReprToken RegisteredOperator::GenReprToken() const { return {absl::StrFormat("<RegisteredOperator '%s'>", absl::CEscape(display_name()))}; } ExprOperatorRegistry* ExprOperatorRegistry::GetInstance() { static Indestructible<ExprOperatorRegistry> kInstance; return kInstance.get(); } ExprOperatorRegistry::ExprOperatorRegistry() { registry_[""] = std::make_unique<Record>(""); } absl::StatusOr<RegisteredOperatorPtr> ExprOperatorRegistry::Register( absl::string_view name, ExprOperatorPtr op_impl) { if (op_impl == nullptr) { return absl::InvalidArgumentError("op_impl=nullptr"); } if (!IsOperatorName(name)) { return absl::InvalidArgumentError(absl::StrFormat( "attempt to register an operator with invalid name: '%s'", absl::CEscape(name))); } auto& record_singleton = LookupOrCreateRecordSingleton(name); if (record_singleton.operator_implementation != nullptr) { return absl::AlreadyExistsError( absl::StrFormat("operator '%s' already exists", name)); } record_singleton.operator_implementation.store(std::move(op_impl)); UpdateRevisionIds(record_singleton); { absl::MutexLock lock(&mx_); registered_operators_.emplace_back(record_singleton.name); } return record_singleton.registered_operator; } void ExprOperatorRegistry::UnsafeUnregister(absl::string_view name) { auto* record_singleton = LookupRecordSingleton(name); if (record_singleton == nullptr || record_singleton->operator_implementation == nullptr) { return; } record_singleton->operator_implementation.store(nullptr); UpdateRevisionIds(*record_singleton); { absl::MutexLock lock(&mx_); registered_operators_.erase(std::remove(registered_operators_.begin(), registered_operators_.end(), name), registered_operators_.end()); } } RegisteredOperatorPtr ExprOperatorRegistry::LookupOperatorOrNull( absl::string_view name) const { auto* record_singleton = LookupRecordSingleton(name); if (ABSL_PREDICT_FALSE(record_singleton == nullptr) || ABSL_PREDICT_FALSE(record_singleton->operator_implementation == nullptr)) { return nullptr; } return record_singleton->registered_operator; } std::vector<absl::string_view> ExprOperatorRegistry::ListRegisteredOperators() const { absl::MutexLock lock(&mx_); return registered_operators_; } ExprOperatorRegistry::OperatorImplementationFn ExprOperatorRegistry::AcquireOperatorImplementationFn(absl::string_view name) { return OperatorImplementationFn(LookupOrCreateRecordSingleton(name)); } ExprOperatorRegistry::RevisionIdFn ExprOperatorRegistry::AcquireRevisionIdFn( absl::string_view name) { return RevisionIdFn(LookupOrCreateRecordSingleton(name)); } ExprOperatorRegistry::Record::Record(absl::string_view name) : name(name), registered_operator(std::make_shared<RegisteredOperator>( RegisteredOperator::PrivateConstructorTag{}, name, OperatorImplementationFn(*this))) {} ExprOperatorRegistry::Record& ExprOperatorRegistry::LookupOrCreateRecordSingleton(absl::string_view name) { absl::MutexLock lock(&mx_); auto it = registry_.find(name); if (ABSL_PREDICT_TRUE(it != registry_.end())) { return *it->second; } if (!IsQualifiedIdentifier(name)) { static Indestructible<Record> kStub("!bad name!"); return *kStub; } auto record = std::make_unique<Record>(name); auto& result = *record; registry_[record->name] = std::move(record); for (auto* child = &result;;) { const auto idx = name.rfind('.'); name = name.substr(0, (idx == absl::string_view::npos ? 0 : idx)); it = registry_.find(name); if (it != registry_.end()) { child->parent = it->second.get(); return result; } record = std::make_unique<Record>(name); auto* parent = record.get(); registry_[record->name] = std::move(record); child->parent = parent; child = parent; } } ExprOperatorRegistry::Record* ExprOperatorRegistry::LookupRecordSingleton(absl::string_view name) const { absl::MutexLock lock(&mx_); auto it = registry_.find(name); if (it != registry_.end()) { return it->second.get(); } return nullptr; } void ExprOperatorRegistry::UpdateRevisionIds(Record& record) { ++record.revision_id; for (auto* parent = record.parent; parent != nullptr; parent = parent->parent) { ++parent->revision_id; } } }
#include "arolla/expr/registered_expr_operator.h" #include <memory> #include <utility> #include <vector> #include "benchmark/benchmark.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "absl/types/span.h" #include "arolla/expr/backend_wrapping_operator.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_attributes.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/expr/lambda_expr_operator.h" #include "arolla/expr/testing/test_operators.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/typed_value.h" #include "arolla/util/init_arolla.h" #include "arolla/util/testing/repr_token_eq.h" #include "arolla/util/testing/status_matchers_backport.h" #include "arolla/util/unit.h" namespace arolla::expr { namespace { using ::arolla::expr::ExprOperatorSignature; using ::arolla::expr::testing::DummyOp; using ::arolla::expr::testing::PowerOp; using ::arolla::testing::IsOk; using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::ReprTokenEq; using ::arolla::testing::StatusIs; using ::testing::Contains; using ::testing::ElementsAre; using ::testing::HasSubstr; using ::testing::IsNull; using ::testing::Not; using ::testing::NotNull; class RegisteredOperatorTest : public ::testing::Test { protected: void SetUp() override { ASSERT_OK(InitArolla()); } }; TEST_F(RegisteredOperatorTest, CommonPath) { ExprOperatorRegistry registry; EXPECT_THAT(registry.LookupOperatorOrNull("math.add"), IsNull()); BackendWrappingOperator::TypeMetaEvalStrategy dummy_strategy = [](absl::Span<const QTypePtr> types) { return nullptr; }; EXPECT_THAT( registry.Register( "math.add", std::make_shared<BackendWrappingOperator>( "math.add", ExprOperatorSignature::MakeVariadicArgs(), dummy_strategy)), IsOk()); EXPECT_THAT(registry.LookupOperatorOrNull("math.add"), NotNull()); EXPECT_THAT( registry.Register( "math.add", std::make_shared<BackendWrappingOperator>( "math.add", ExprOperatorSignature::MakeVariadicArgs(), dummy_strategy)), StatusIs(absl::StatusCode::kAlreadyExists, "operator 'math.add' already exists")); } TEST_F(RegisteredOperatorTest, RegisterOperator_GetSignature) { ASSERT_OK_AND_ASSIGN( auto op, RegisterOperator("test.dummy_op_with_signature", std::make_shared<DummyOp>( "dummy_op", ExprOperatorSignature::MakeArgsN(3), "dummy_docstring"))); ASSERT_OK_AND_ASSIGN(auto signature, op->GetSignature()); EXPECT_EQ(signature.parameters.size(), 3); EXPECT_EQ(signature.parameters[0].name, "arg1"); EXPECT_EQ(signature.parameters[1].name, "arg2"); EXPECT_EQ(signature.parameters[2].name, "arg3"); } TEST_F(RegisteredOperatorTest, RegisterOperator_GetDoc) { ASSERT_OK_AND_ASSIGN( auto op, RegisterOperator( "test.dummy_op_with_doc", std::make_shared<DummyOp>( "dummy_op", ExprOperatorSignature::MakeVariadicArgs(), "dummy_docstring"))); ASSERT_THAT(op->GetDoc(), IsOkAndHolds("dummy_docstring")); } TEST_F(RegisteredOperatorTest, OpNullPtr) { ExprOperatorRegistry registry; ASSERT_THAT(registry.Register("op.name_1", nullptr), StatusIs(absl::StatusCode::kInvalidArgument)); } TEST_F(RegisteredOperatorTest, RegistrationOrder) { ExprOperatorRegistry registry; ASSERT_OK_AND_ASSIGN(auto op, MakeLambdaOperator(Placeholder("x"))); ASSERT_THAT(registry.Register("op.name_1", op), IsOk()); ASSERT_THAT(registry.Register("op.name_3", op), IsOk()); ASSERT_THAT(registry.Register("op.name_2", op), IsOk()); EXPECT_THAT(registry.ListRegisteredOperators(), ElementsAre("op.name_1", "op.name_3", "op.name_2")); } TEST_F(RegisteredOperatorTest, Repr) { auto op = std::make_shared<RegisteredOperator>("foo'bar"); EXPECT_THAT(op->GenReprToken(), ReprTokenEq("<RegisteredOperator 'foo\\'bar'>")); } TEST_F(RegisteredOperatorTest, IsRegisteredOperator) { { EXPECT_FALSE(IsRegisteredOperator(nullptr)); } { ASSERT_OK_AND_ASSIGN(const auto lambda_op, LambdaOperator::Make("foo.bar", {}, Literal(1))); EXPECT_FALSE(IsRegisteredOperator(lambda_op)); } { ASSERT_OK_AND_ASSIGN(ExprNodePtr original_expr, CallOp("test.power", {Leaf("x"), Leaf("y")})); EXPECT_TRUE(IsRegisteredOperator(original_expr->op())); } { ASSERT_OK_AND_ASSIGN(ExprNodePtr original_expr, CallOp("math.add", {Leaf("x"), Leaf("y")})); EXPECT_TRUE(IsRegisteredOperator(original_expr->op())); EXPECT_FALSE(IsBackendOperator(original_expr->op(), "math.add")); } } TEST_F(RegisteredOperatorTest, DecayRegisteredOperator) { { ASSERT_OK_AND_ASSIGN(auto reg_op, LookupOperator("test.power")); ASSERT_OK_AND_ASSIGN(auto op, DecayRegisteredOperator(reg_op)); EXPECT_EQ(typeid(*op), typeid(PowerOp)); } { ASSERT_OK_AND_ASSIGN( auto alias_op, RegisterOperatorAlias("alias_test.power", "test.power")); ASSERT_OK_AND_ASSIGN(auto op, DecayRegisteredOperator(alias_op)); EXPECT_EQ(typeid(*op), typeid(PowerOp)); } } TEST_F(RegisteredOperatorTest, UnsafeUnregister) { ExprOperatorRegistry registry; ASSERT_THAT(registry.Register( "op.dummy_op_for_unregistration", std::make_shared<DummyOp>( "dummy_op", ExprOperatorSignature::MakeVariadicArgs(), "dummy_docstring")), IsOk()); ASSERT_THAT(registry.LookupOperatorOrNull("op.dummy_op_for_unregistration"), NotNull()); ASSERT_THAT(registry.ListRegisteredOperators(), Contains("op.dummy_op_for_unregistration")); registry.UnsafeUnregister("op.dummy_op_for_unregistration"); ASSERT_THAT(registry.LookupOperatorOrNull("op.dummy_op_for_unregistration"), IsNull()); ASSERT_THAT(registry.ListRegisteredOperators(), Not(Contains("op.dummy_op_for_unregistration"))); } TEST_F(RegisteredOperatorTest, RevisionId) { auto& registry = *ExprOperatorRegistry::GetInstance(); const auto rev_id_fn = registry.AcquireRevisionIdFn(""); const auto a_rev_id_fn = registry.AcquireRevisionIdFn("a"); const auto a_b_rev_id_fn = registry.AcquireRevisionIdFn("a.b"); const auto a_b_op_rev_id_fn = registry.AcquireRevisionIdFn("a.b.op"); auto op = std::make_shared<DummyOp>( "dummy_op", ExprOperatorSignature::MakeVariadicArgs(), "dummy_docstring"); const auto a_b_op_rev_id_0 = a_b_op_rev_id_fn(); const auto a_b_rev_id_0 = a_b_rev_id_fn(); const auto a_rev_id_0 = a_rev_id_fn(); const auto rev_id_0 = rev_id_fn(); ASSERT_THAT(registry.Register("a.b.op", op), IsOk()); const auto a_b_op_rev_id_1 = a_b_op_rev_id_fn(); const auto a_b_rev_id_1 = a_b_rev_id_fn(); const auto a_rev_id_1 = a_rev_id_fn(); const auto rev_id_1 = rev_id_fn(); ASSERT_NE(a_b_op_rev_id_1, a_b_op_rev_id_0); ASSERT_NE(a_b_rev_id_1, a_b_rev_id_0); ASSERT_NE(a_rev_id_1, a_rev_id_0); ASSERT_NE(rev_id_1, rev_id_0); ASSERT_THAT(registry.Register("op.null", nullptr), StatusIs(absl::StatusCode::kInvalidArgument)); ASSERT_THAT(registry.Register("!@#", op), StatusIs(absl::StatusCode::kInvalidArgument)); ASSERT_THAT(registry.Register("a.b.op", op), StatusIs(absl::StatusCode::kAlreadyExists)); ASSERT_EQ(a_b_op_rev_id_fn(), a_b_op_rev_id_1); ASSERT_EQ(a_b_rev_id_fn(), a_b_rev_id_1); ASSERT_EQ(a_rev_id_fn(), a_rev_id_1); ASSERT_EQ(rev_id_fn(), rev_id_1); ASSERT_THAT(registry.Register("a.c.op", op), IsOk()); const auto a_b_op_rev_id_2 = a_b_op_rev_id_fn(); const auto a_b_rev_id_2 = a_b_rev_id_fn(); const auto a_rev_id_2 = a_rev_id_fn(); const auto rev_id_2 = rev_id_fn(); ASSERT_EQ(a_b_op_rev_id_2, a_b_op_rev_id_1); ASSERT_EQ(a_b_rev_id_2, a_b_rev_id_1); ASSERT_NE(a_rev_id_2, a_rev_id_1); ASSERT_NE(rev_id_2, rev_id_1); registry.UnsafeUnregister("a.b.no_op"); ASSERT_EQ(a_b_op_rev_id_fn(), a_b_op_rev_id_2); ASSERT_EQ(a_b_rev_id_fn(), a_b_rev_id_2); ASSERT_EQ(a_rev_id_fn(), a_rev_id_2); ASSERT_EQ(rev_id_fn(), rev_id_2); registry.UnsafeUnregister("a.c.op"); const auto a_b_op_rev_id_3 = a_b_op_rev_id_fn(); const auto a_b_rev_id_3 = a_b_rev_id_fn(); const auto a_rev_id_3 = a_rev_id_fn(); const auto rev_id_3 = rev_id_fn(); ASSERT_EQ(a_b_op_rev_id_3, a_b_op_rev_id_2); ASSERT_EQ(a_b_rev_id_3, a_b_rev_id_2); ASSERT_NE(a_rev_id_3, a_rev_id_2); ASSERT_NE(rev_id_3, rev_id_2); registry.UnsafeUnregister("a.b.op"); const auto a_b_op_rev_id_4 = a_b_op_rev_id_fn(); const auto a_b_rev_id_4 = a_b_rev_id_fn(); const auto a_rev_id_4 = a_rev_id_fn(); const auto rev_id_4 = rev_id_fn(); ASSERT_NE(a_b_op_rev_id_4, a_b_op_rev_id_3); ASSERT_NE(a_b_rev_id_4, a_b_rev_id_3); ASSERT_NE(a_rev_id_4, a_rev_id_3); ASSERT_NE(rev_id_4, rev_id_3); } TEST_F(RegisteredOperatorTest, CircularDepenndencyDetector) { auto op_a = std::make_shared<RegisteredOperator>("circular_dependency_detector.A"); auto op_b = std::make_shared<RegisteredOperator>("circular_dependency_detector.B"); ASSERT_OK(RegisterOperator("circular_dependency_detector.A", op_b)); ASSERT_OK(RegisterOperator("circular_dependency_detector.B", op_a)); EXPECT_THAT(DecayRegisteredOperator(op_a), StatusIs(absl::StatusCode::kFailedPrecondition, HasSubstr("arolla::expr::DecayRegisteredOperator: " "detected a circular dependency: " "op_name=circular_dependency_detector.A"))); EXPECT_THAT( op_a->GetSignature(), StatusIs(absl::StatusCode::kFailedPrecondition, HasSubstr("arolla::expr::RegisteredOperator::GetSignature: " "detected a circular dependency: " "op_name=circular_dependency_detector.A"))); EXPECT_THAT(op_a->GetDoc(), StatusIs(absl::StatusCode::kFailedPrecondition, HasSubstr("arolla::expr::RegisteredOperator::GetDoc: " "detected a circular dependency: " "op_name=circular_dependency_detector.A"))); EXPECT_THAT( op_a->InferAttributes({}), StatusIs(absl::StatusCode::kFailedPrecondition, HasSubstr("arolla::expr::RegisteredOperator::InferAttributes: " "detected a circular dependency: " "op_name=circular_dependency_detector.A, inputs=[]"))); EXPECT_THAT( op_a->InferAttributes({ExprAttributes(GetQType<QTypePtr>())}), StatusIs(absl::StatusCode::kFailedPrecondition, HasSubstr("arolla::expr::RegisteredOperator::InferAttributes: " "detected a circular dependency: " "op_name=circular_dependency_detector.A, " "inputs=[Attr(qtype=QTYPE)]"))); EXPECT_THAT( op_a->InferAttributes({ExprAttributes(GetQType<QTypePtr>()), ExprAttributes(TypedValue::FromValue(Unit{}))}), StatusIs(absl::StatusCode::kFailedPrecondition, HasSubstr("arolla::expr::RegisteredOperator::InferAttributes: " "detected a circular dependency: " "op_name=circular_dependency_detector.A, " "inputs=[Attr(qtype=QTYPE), Attr(qvalue=unit)]"))); EXPECT_THAT( ToLowerNode(ExprNode::UnsafeMakeOperatorNode(op_a, {}, {})), StatusIs(absl::StatusCode::kFailedPrecondition, HasSubstr("arolla::expr::RegisteredOperator::ToLowerLevel: " "detected a circular dependency: " "op_name=circular_dependency_detector.A, " "inputs=[]"))); EXPECT_THAT( ToLowerNode(ExprNode::UnsafeMakeOperatorNode( op_a, {Leaf("x"), Literal(Unit{})}, {})), StatusIs(absl::StatusCode::kFailedPrecondition, HasSubstr("arolla::expr::RegisteredOperator::ToLowerLevel: " "detected a circular dependency: " "op_name=circular_dependency_detector.A, " "inputs=[Attr{}, Attr(qvalue=unit)]"))); } TEST_F(RegisteredOperatorTest, LongDependencyChain) { auto op = std::make_shared<DummyOp>( "dummy_op", ExprOperatorSignature::MakeVariadicArgs()); ASSERT_OK_AND_ASSIGN(auto reg_op, RegisterOperator("long_dependency_chain._0", op)); for (int i = 1; i < 200; ++i) { ASSERT_OK_AND_ASSIGN( reg_op, RegisterOperator( absl::StrFormat("long_dependency_chain._%d", i), reg_op)); } EXPECT_THAT(DecayRegisteredOperator(reg_op), IsOkAndHolds(op)); EXPECT_THAT(reg_op->GetDoc(), op->doc()); EXPECT_THAT(reg_op->GetSignature(), IsOk()); EXPECT_THAT(reg_op->InferAttributes({}), IsOk()); EXPECT_THAT( ToLowerNode(ExprNode::UnsafeMakeOperatorNode(std::move(reg_op), {}, {})), IsOk()); } absl::StatusOr<ExprOperatorPtr> GetChainOp(int n) { static const bool once = ([]{ ExprOperatorPtr op = std::make_shared<DummyOp>( "dummy_op", ExprOperatorSignature::MakeVariadicArgs()); for (int i = 1; i < 100; ++i) { ASSERT_OK_AND_ASSIGN( op, RegisterOperator(absl::StrFormat("benchmark.chain_op._%d", i), op)); } }(), true); (void)once; return LookupOperator(absl::StrFormat("benchmark.chain_op._%d", n)); } void BM_DecayRegisteredOperator(benchmark::State& state) { CHECK_OK(InitArolla()); ASSERT_OK_AND_ASSIGN(auto op, GetChainOp(state.range(0))); for (auto _ : state) { auto tmp = DecayRegisteredOperator(op).ok(); benchmark::DoNotOptimize(tmp); } } void BM_GetDoc(benchmark::State& state) { CHECK_OK(InitArolla()); ASSERT_OK_AND_ASSIGN(auto op, GetChainOp(state.range(0))); for (auto _ : state) { auto tmp = op->GetDoc(); benchmark::DoNotOptimize(tmp); } } void BM_InferAttr(benchmark::State& state) { CHECK_OK(InitArolla()); ASSERT_OK_AND_ASSIGN(auto op, GetChainOp(state.range(0))); std::vector inputs = {ExprAttributes(), ExprAttributes()}; for (auto _ : state) { auto tmp = op->InferAttributes(inputs); benchmark::DoNotOptimize(tmp); } } void BM_ToLowerLevel(benchmark::State& state) { CHECK_OK(InitArolla()); ASSERT_OK_AND_ASSIGN(auto op, GetChainOp(state.range(0))); ASSERT_OK_AND_ASSIGN(auto expr, CallOp(op, {Leaf("x"), Leaf("y")})); std::vector inputs = {ExprAttributes(), ExprAttributes()}; for (auto _ : state) { auto tmp = ToLowerNode(expr); benchmark::DoNotOptimize(tmp); } } BENCHMARK(BM_DecayRegisteredOperator)->Arg(1)->Arg(2)->Arg(20); BENCHMARK(BM_GetDoc)->Arg(1)->Arg(2)->Arg(20); BENCHMARK(BM_InferAttr)->Arg(1)->Arg(2)->Arg(20); BENCHMARK(BM_ToLowerLevel)->Arg(1)->Arg(2)->Arg(20); } }
2,419
#ifndef AROLLA_EXPR_QUOTE_H_ #define AROLLA_EXPR_QUOTE_H_ #include <utility> #include "absl/base/nullability.h" #include "absl/status/statusor.h" #include "arolla/dense_array/qtype/types.h" #include "arolla/expr/expr_node.h" #include "arolla/qtype/optional_qtype.h" #include "arolla/qtype/simple_qtype.h" #include "arolla/util/fingerprint.h" #include "arolla/util/refcount_ptr.h" #include "arolla/util/repr.h" namespace arolla::expr { class ExprQuote { public: ExprQuote() = default; explicit ExprQuote(ExprNodePtr expr) : expr_(std::move(expr)) {} bool has_expr() const { return expr_ != nullptr; } absl::StatusOr<ExprNodePtr> expr() const; const absl::Nullable<RefcountPtr<const ExprNode>>& operator*() const { return expr_; } const absl::Nullable<RefcountPtr<const ExprNode>>* operator->() const { return &expr_; } Fingerprint expr_fingerprint() const; friend bool operator==(const ExprQuote& lhs, const ExprQuote& rhs) { return lhs.expr_fingerprint() == rhs.expr_fingerprint(); } friend bool operator!=(const ExprQuote& lhs, const ExprQuote& rhs) { return lhs.expr_fingerprint() != rhs.expr_fingerprint(); } template <typename H> friend H AbslHashValue(H h, const ExprQuote& expr_quote) { return H::combine(std::move(h), expr_quote.expr_fingerprint()); } private: absl::Nullable<RefcountPtr<const ExprNode>> expr_ = nullptr; }; } namespace arolla { AROLLA_DECLARE_FINGERPRINT_HASHER_TRAITS(expr::ExprQuote); AROLLA_DECLARE_REPR(expr::ExprQuote); AROLLA_DECLARE_SIMPLE_QTYPE(EXPR_QUOTE, expr::ExprQuote); AROLLA_DECLARE_OPTIONAL_QTYPE(EXPR_QUOTE, expr::ExprQuote); AROLLA_DECLARE_DENSE_ARRAY_QTYPE(EXPR_QUOTE, expr::ExprQuote); } #endif #include "arolla/expr/quote.h" #include "absl/log/check.h" #include "absl/numeric/int128.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/escaping.h" #include "absl/strings/str_format.h" #include "absl/strings/string_view.h" #include "arolla/dense_array/qtype/types.h" #include "arolla/expr/expr_debug_string.h" #include "arolla/expr/expr_node.h" #include "arolla/qtype/optional_qtype.h" #include "arolla/qtype/simple_qtype.h" #include "arolla/util/fingerprint.h" #include "arolla/util/repr.h" namespace arolla::expr { constexpr Fingerprint kEmptyQuoteHash{ absl::MakeUint128(0x5466dba2e1989659, 0x6f2834ee88b8b08b)}; absl::StatusOr<ExprNodePtr> ExprQuote::expr() const { if (expr_ == nullptr) { return absl::InvalidArgumentError("uninitialized ExprQuote"); } return expr_; } Fingerprint ExprQuote::expr_fingerprint() const { return expr_ != nullptr ? expr_->fingerprint() : kEmptyQuoteHash; } } namespace arolla { void FingerprintHasherTraits<expr::ExprQuote>::operator()( FingerprintHasher* hasher, const expr::ExprQuote& value) const { hasher->Combine(absl::string_view("::arolla::expr::ExprQuote"), value.expr_fingerprint()); } ReprToken ReprTraits<expr::ExprQuote>::operator()( const expr::ExprQuote& value) const { if (!value.has_expr()) { return ReprToken{"ExprQuote(nullptr)"}; } return ReprToken{absl::StrFormat( "ExprQuote('%s')", absl::Utf8SafeCHexEscape(ToDebugString(*value)))}; } AROLLA_DEFINE_SIMPLE_QTYPE(EXPR_QUOTE, expr::ExprQuote); AROLLA_DEFINE_OPTIONAL_QTYPE(EXPR_QUOTE, expr::ExprQuote); AROLLA_DEFINE_DENSE_ARRAY_QTYPE(EXPR_QUOTE, expr::ExprQuote); }
#include "arolla/expr/quote.h" #include <memory> #include <optional> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/hash/hash_testing.h" #include "absl/status/status.h" #include "arolla/dense_array/dense_array.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/expr/testing/test_operators.h" #include "arolla/util/fingerprint.h" #include "arolla/util/init_arolla.h" #include "arolla/util/repr.h" #include "arolla/util/testing/status_matchers_backport.h" #include "arolla/util/text.h" namespace arolla::expr { namespace { using ::arolla::expr::testing::DummyOp; using ::arolla::testing::IsOk; using ::arolla::testing::StatusIs; using ::testing::Eq; using ::testing::IsFalse; using ::testing::IsTrue; using ::testing::Ne; class ExprQuoteTest : public ::testing::Test { void SetUp() override { ASSERT_OK(InitArolla()); } protected: ExprOperatorPtr op_ = std::make_shared<DummyOp>( "op", ExprOperatorSignature::MakeVariadicArgs()); }; TEST_F(ExprQuoteTest, Empty) { ExprQuote quote; EXPECT_THAT(quote.has_expr(), IsFalse()); EXPECT_THAT(quote.expr(), StatusIs(absl::StatusCode::kInvalidArgument, "uninitialized ExprQuote")); } TEST_F(ExprQuoteTest, NotEmpty) { ASSERT_OK_AND_ASSIGN(auto expr, CallOp(op_, {Leaf("x")})); ExprQuote quote(expr); EXPECT_THAT(quote.has_expr(), IsTrue()); ASSERT_THAT(quote.expr(), IsOk()); EXPECT_THAT(quote.expr()->get(), Eq(expr.get())); EXPECT_THAT(quote->get(), Eq(expr.get())); } TEST_F(ExprQuoteTest, DenseArray) { ASSERT_OK_AND_ASSIGN(auto expr_1, CallOp(op_, {Leaf("x")})); ASSERT_OK_AND_ASSIGN(auto expr_2, CallOp(op_, {Leaf("y")})); auto array = CreateDenseArray<expr::ExprQuote>( {ExprQuote(expr_1), std::nullopt, ExprQuote(expr_2)}); EXPECT_TRUE(array[0].present); EXPECT_FALSE(array[1].present); EXPECT_TRUE(array[2].present); EXPECT_EQ(array[0].value, ExprQuote(expr_1)); EXPECT_EQ(array[2].value, ExprQuote(expr_2)); } TEST_F(ExprQuoteTest, AbslHash) { ASSERT_OK_AND_ASSIGN(auto expr_1, CallOp(op_, {Leaf("x")})); ASSERT_OK_AND_ASSIGN(auto expr_2, CallOp(op_, {Leaf("y")})); ASSERT_OK_AND_ASSIGN(auto expr_3, CallOp(op_, {Leaf("z")})); ASSERT_OK_AND_ASSIGN(auto expr_4, CallOp(op_, {Leaf("x")})); std::vector cases{ ExprQuote(expr_1), ExprQuote(expr_2), ExprQuote(expr_3), ExprQuote(expr_4), }; EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(cases)); } TEST_F(ExprQuoteTest, Fingerprint) { ASSERT_OK_AND_ASSIGN(auto expr, CallOp(op_, {Leaf("x")})); EXPECT_THAT(ExprQuote(expr).expr_fingerprint(), Eq(expr->fingerprint())); EXPECT_THAT(ExprQuote().expr_fingerprint(), Ne(expr->fingerprint())); } TEST_F(ExprQuoteTest, FingerprintHasher) { ASSERT_OK_AND_ASSIGN(auto expr, CallOp(op_, {Leaf("x")})); ExprQuote quote(expr); auto quote_fingerprint = FingerprintHasher("").Combine(quote).Finish(); EXPECT_THAT(quote_fingerprint, Ne(expr->fingerprint())); EXPECT_THAT(FingerprintHasher("").Combine(quote).Finish(), Eq(quote_fingerprint)); } TEST_F(ExprQuoteTest, Repr) { EXPECT_THAT(Repr(ExprQuote()), Eq("ExprQuote(nullptr)")); Text text_with_quote{"some\"\ntext"}; ASSERT_OK_AND_ASSIGN(auto expr, CallOp(op_, {Leaf("x"), Literal(text_with_quote)})); ExprQuote quote{expr}; EXPECT_THAT(Repr(text_with_quote), Eq("'some\\\"\\ntext'")); EXPECT_THAT(Repr(quote), Eq("ExprQuote('op(L.x, \\'some\\\\\\\"\\\\ntext\\')')")); } } }
2,420
#ifndef AROLLA_EXPR_ANNOTATION_EXPR_OPERATORS_H_ #define AROLLA_EXPR_ANNOTATION_EXPR_OPERATORS_H_ #include "absl/status/statusor.h" #include "absl/types/span.h" #include "arolla/expr/basic_expr_operator.h" #include "arolla/expr/expr_attributes.h" #include "arolla/expr/expr_operator.h" namespace arolla::expr { class QTypeAnnotation final : public expr::AnnotationExprOperatorTag, public expr::ExprOperatorWithFixedSignature { public: static ExprOperatorPtr Make(); QTypeAnnotation(); absl::StatusOr<ExprAttributes> InferAttributes( absl::Span<const ExprAttributes> inputs) const final; }; class NameAnnotation final : public AnnotationExprOperatorTag, public ExprOperatorWithFixedSignature { public: static ExprOperatorPtr Make(); NameAnnotation(); absl::StatusOr<ExprAttributes> InferAttributes( absl::Span<const ExprAttributes> inputs) const final; }; class ExportAnnotation : public AnnotationExprOperatorTag, public ExprOperatorWithFixedSignature { public: static ExprOperatorPtr Make(); ExportAnnotation(); absl::StatusOr<ExprAttributes> InferAttributes( absl::Span<const ExprAttributes> inputs) const final; }; class ExportValueAnnotation : public AnnotationExprOperatorTag, public ExprOperatorWithFixedSignature { public: static ExprOperatorPtr Make(); ExportValueAnnotation(); absl::StatusOr<ExprAttributes> InferAttributes( absl::Span<const ExprAttributes> inputs) const final; }; } #endif #include "arolla/expr/annotation_expr_operators.h" #include <memory> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "absl/types/span.h" #include "arolla/expr/basic_expr_operator.h" #include "arolla/expr/expr_attributes.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/util/fingerprint.h" #include "arolla/util/indestructible.h" #include "arolla/util/text.h" #include "arolla/util/status_macros_backport.h" namespace arolla::expr { ExprOperatorPtr QTypeAnnotation::Make() { static const Indestructible<ExprOperatorPtr> result( std::make_shared<QTypeAnnotation>()); return *result; } QTypeAnnotation::QTypeAnnotation() : ExprOperatorWithFixedSignature( "annotation.qtype", ExprOperatorSignature{{"expr"}, {"qtype"}}, "QType annotation.", FingerprintHasher("::arolla::expr::QTypeAnnotation").Finish()) {} absl::StatusOr<ExprAttributes> QTypeAnnotation::InferAttributes( absl::Span<const ExprAttributes> inputs) const { RETURN_IF_ERROR(ValidateOpInputsCount(inputs)); if (!inputs[1].qtype()) { return inputs[0]; } if (inputs[1].qtype() != GetQTypeQType()) { return absl::InvalidArgumentError(absl::StrFormat( "expected QTYPE, got qtype: %s", inputs[1].qtype()->name())); } if (!inputs[1].qvalue()) { return absl::InvalidArgumentError("`qtype` must be a literal"); } const QTypePtr output_qtype = inputs[1].qvalue()->UnsafeAs<QTypePtr>(); if (inputs[0].qtype() && inputs[0].qtype() != output_qtype) { return absl::InvalidArgumentError( absl::StrFormat("inconsistent annotation.qtype(expr: %s, qtype=%s)", inputs[0].qtype()->name(), output_qtype->name())); } return ExprAttributes(output_qtype, inputs[0].qvalue()); } ExprOperatorPtr NameAnnotation::Make() { static const Indestructible<ExprOperatorPtr> result( std::make_shared<NameAnnotation>()); return *result; } NameAnnotation::NameAnnotation() : ExprOperatorWithFixedSignature( "annotation.name", ExprOperatorSignature{{"expr"}, {"name"}}, "Name annotation.", FingerprintHasher("::arolla::expr::NameAnnotation").Finish()) {} absl::StatusOr<ExprAttributes> NameAnnotation::InferAttributes( absl::Span<const ExprAttributes> inputs) const { RETURN_IF_ERROR(ValidateOpInputsCount(inputs)); if (inputs[1].qtype() && inputs[1].qtype() != GetQType<Text>()) { return absl::InvalidArgumentError(absl::StrFormat( "expected a TEXT literal, got name: %s", inputs[1].qtype()->name())); } if (!inputs[1].qvalue()) { return absl::InvalidArgumentError("`name` must be a TEXT literal"); } return inputs[0]; } ExprOperatorPtr ExportAnnotation::Make() { static const Indestructible<ExprOperatorPtr> result( std::make_shared<ExportAnnotation>()); return *result; } ExportAnnotation::ExportAnnotation() : ExprOperatorWithFixedSignature( "annotation.export", ExprOperatorSignature{{"expr"}, {"export_tag"}}, "Side-channel output annotation.", FingerprintHasher("::arolla::expr::ExportAnnotation").Finish()) {} absl::StatusOr<ExprAttributes> ExportAnnotation::InferAttributes( absl::Span<const ExprAttributes> inputs) const { RETURN_IF_ERROR(ValidateOpInputsCount(inputs)); if (inputs[1].qtype() && inputs[1].qtype() != GetQType<Text>()) { return absl::InvalidArgumentError(absl::StrFormat( "expected TEXT, got export_tag: %s", inputs[1].qtype()->name())); } if (!inputs[1].qvalue()) { return absl::InvalidArgumentError("`export_tag` must be a TEXT literal"); } if (inputs[1].qvalue()->UnsafeAs<Text>().view().empty()) { return absl::InvalidArgumentError("`export_tag` must be non-empty"); } return inputs[0]; } ExprOperatorPtr ExportValueAnnotation::Make() { static const Indestructible<ExprOperatorPtr> result( std::make_shared<ExportValueAnnotation>()); return *result; } ExportValueAnnotation::ExportValueAnnotation() : ExprOperatorWithFixedSignature( "annotation.export_value", ExprOperatorSignature{{"expr"}, {"export_tag"}, {"value"}}, "Side-channel output annotation.", FingerprintHasher("::arolla::expr::ExportValueAnnotation").Finish()) { } absl::StatusOr<ExprAttributes> ExportValueAnnotation::InferAttributes( absl::Span<const ExprAttributes> inputs) const { RETURN_IF_ERROR(ValidateOpInputsCount(inputs)); if (inputs[1].qtype() && inputs[1].qtype() != GetQType<Text>()) { return absl::InvalidArgumentError(absl::StrFormat( "expected TEXT, got export_tag: %s", inputs[1].qtype()->name())); } if (!inputs[1].qvalue()) { return absl::InvalidArgumentError("`export_tag` must be a TEXT literal"); } if (inputs[1].qvalue()->UnsafeAs<Text>().view().empty()) { return absl::InvalidArgumentError("`export_tag` must be non-empty"); } return inputs[0]; } }
#include "arolla/expr/annotation_expr_operators.h" #include <cstdint> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "arolla/expr/expr_attributes.h" #include "arolla/expr/testing/testing.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/typed_value.h" #include "arolla/util/init_arolla.h" #include "arolla/util/testing/status_matchers_backport.h" #include "arolla/util/text.h" namespace arolla::expr { namespace { using ::arolla::testing::EqualsAttr; using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::StatusIs; class AnnotationExprOperatorsTest : public ::testing::Test { void SetUp() override { ASSERT_OK(InitArolla()); } }; TEST_F(AnnotationExprOperatorsTest, QTypeAnnotation) { auto annotation_qtype = QTypeAnnotation::Make(); EXPECT_THAT(annotation_qtype->InferAttributes({}), StatusIs(absl::StatusCode::kInvalidArgument, "incorrect number of dependencies passed to an operator " "node: expected 2 but got 0")); EXPECT_THAT( annotation_qtype->InferAttributes({ExprAttributes{GetQType<int64_t>()}, ExprAttributes{GetQType<int64_t>()}}), StatusIs(absl::StatusCode::kInvalidArgument, "expected QTYPE, got qtype: INT64")); EXPECT_THAT( annotation_qtype->InferAttributes({ExprAttributes{GetQType<int64_t>()}, ExprAttributes{GetQType<QTypePtr>()}}), StatusIs(absl::StatusCode::kInvalidArgument, "`qtype` must be a literal")); EXPECT_THAT(annotation_qtype->InferAttributes( {ExprAttributes{}, ExprAttributes{TypedValue::FromValue(GetQType<int64_t>())}}), IsOkAndHolds(EqualsAttr(GetQType<int64_t>()))); EXPECT_THAT(annotation_qtype->InferAttributes( {ExprAttributes{GetQType<int64_t>()}, ExprAttributes{TypedValue::FromValue(GetQType<int64_t>())}}), IsOkAndHolds(EqualsAttr(GetQType<int64_t>()))); EXPECT_THAT( annotation_qtype->InferAttributes( {ExprAttributes{GetQType<int64_t>()}, ExprAttributes{TypedValue::FromValue(GetQType<Text>())}}), StatusIs(absl::StatusCode::kInvalidArgument, "inconsistent annotation.qtype(expr: INT64, qtype=TEXT)")); } TEST_F(AnnotationExprOperatorsTest, NameAnnotation) { auto annotation_name = NameAnnotation::Make(); EXPECT_THAT(annotation_name->InferAttributes({}), StatusIs(absl::StatusCode::kInvalidArgument, "incorrect number of dependencies passed to an operator " "node: expected 2 but got 0")); EXPECT_THAT( annotation_name->InferAttributes({ExprAttributes{GetQType<int64_t>()}, ExprAttributes{GetQType<int64_t>()}}), StatusIs(absl::StatusCode::kInvalidArgument, "expected a TEXT literal, got name: INT64")); EXPECT_THAT(annotation_name->InferAttributes( {ExprAttributes{GetQType<int64_t>()}, ExprAttributes{}}), StatusIs(absl::StatusCode::kInvalidArgument, "`name` must be a TEXT literal")); EXPECT_THAT( annotation_name->InferAttributes({ExprAttributes{GetQType<int64_t>()}, ExprAttributes{GetQType<Text>()}}), StatusIs(absl::StatusCode::kInvalidArgument, "`name` must be a TEXT literal")); EXPECT_THAT(annotation_name->InferAttributes( {ExprAttributes{GetQType<int64_t>()}, ExprAttributes{TypedValue::FromValue(Text("foo"))}}), IsOkAndHolds(EqualsAttr(GetQType<int64_t>()))); } TEST_F(AnnotationExprOperatorsTest, ExportAnnotation) { auto annotation_export = ExportAnnotation::Make(); EXPECT_THAT(annotation_export->InferAttributes({}), StatusIs(absl::StatusCode::kInvalidArgument, "incorrect number of dependencies passed to an operator " "node: expected 2 but got 0")); EXPECT_THAT( annotation_export->InferAttributes({ExprAttributes{GetQType<int64_t>()}, ExprAttributes{GetQType<int64_t>()}}), StatusIs(absl::StatusCode::kInvalidArgument, "expected TEXT, got export_tag: INT64")); EXPECT_THAT( annotation_export->InferAttributes({ExprAttributes{GetQType<int64_t>()}, ExprAttributes{GetQType<Text>()}}), StatusIs(absl::StatusCode::kInvalidArgument, "`export_tag` must be a TEXT literal")); EXPECT_THAT(annotation_export->InferAttributes( {ExprAttributes{GetQType<int64_t>()}, ExprAttributes{}}), StatusIs(absl::StatusCode::kInvalidArgument, "`export_tag` must be a TEXT literal")); EXPECT_THAT(annotation_export->InferAttributes( {ExprAttributes{GetQType<int64_t>()}, ExprAttributes{TypedValue::FromValue(Text(""))}}), StatusIs(absl::StatusCode::kInvalidArgument, "`export_tag` must be non-empty")); EXPECT_THAT(annotation_export->InferAttributes( {ExprAttributes{GetQType<int64_t>()}, ExprAttributes{TypedValue::FromValue(Text("foo"))}}), IsOkAndHolds(EqualsAttr(GetQType<int64_t>()))); } TEST_F(AnnotationExprOperatorsTest, ExportValueAnnotation) { auto annotation_export_value = ExportValueAnnotation::Make(); EXPECT_THAT(annotation_export_value->InferAttributes({}), StatusIs(absl::StatusCode::kInvalidArgument, "incorrect number of dependencies passed to an operator " "node: expected 3 but got 0")); EXPECT_THAT(annotation_export_value->InferAttributes( {ExprAttributes{GetQType<int64_t>()}, ExprAttributes{GetQType<int64_t>()}, ExprAttributes{GetQType<int64_t>()}}), StatusIs(absl::StatusCode::kInvalidArgument, "expected TEXT, got export_tag: INT64")); EXPECT_THAT(annotation_export_value->InferAttributes( {ExprAttributes{GetQType<int64_t>()}, ExprAttributes{}, ExprAttributes{GetQType<int64_t>()}}), StatusIs(absl::StatusCode::kInvalidArgument, "`export_tag` must be a TEXT literal")); EXPECT_THAT(annotation_export_value->InferAttributes( {ExprAttributes{GetQType<int64_t>()}, ExprAttributes{GetQType<Text>()}, ExprAttributes{GetQType<int64_t>()}}), StatusIs(absl::StatusCode::kInvalidArgument, "`export_tag` must be a TEXT literal")); EXPECT_THAT(annotation_export_value->InferAttributes( {ExprAttributes{GetQType<int64_t>()}, ExprAttributes{TypedValue::FromValue(Text(""))}, ExprAttributes{GetQType<int64_t>()}}), StatusIs(absl::StatusCode::kInvalidArgument, "`export_tag` must be non-empty")); EXPECT_THAT(annotation_export_value->InferAttributes( {ExprAttributes{GetQType<int64_t>()}, ExprAttributes{TypedValue::FromValue(Text("foo"))}, ExprAttributes{GetQType<int64_t>()}}), IsOkAndHolds(EqualsAttr(GetQType<int64_t>()))); } } }
2,421
#ifndef AROLLA_EXPR_ANNOTATION_UTILS_H_ #define AROLLA_EXPR_ANNOTATION_UTILS_H_ #include <string_view> #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "arolla/expr/expr_node.h" #include "arolla/qtype/qtype.h" namespace arolla::expr { absl::StatusOr<bool> IsAnnotation(const ExprNodePtr& node); absl::StatusOr<bool> IsDetachedAnnotation(const ExprNodePtr& node); absl::StatusOr<ExprNodePtr> GetDetachedAnnotation(ExprNodePtr node); absl::StatusOr<ExprNodePtr> AttachAnnotation(const ExprNodePtr& node, const ExprNodePtr& annotation); absl::StatusOr<ExprNodePtr> AttachAnnotations( const ExprNodePtr& node, absl::Span<const ExprNodePtr> annotations); absl::StatusOr<ExprNodePtr> StripTopmostAnnotations(const ExprNodePtr& expr); absl::StatusOr<ExprNodePtr> StripAnnotations(const ExprNodePtr& expr); bool IsQTypeAnnotation(const ExprNodePtr& node); bool IsNameAnnotation(const ExprNodePtr& node); bool IsExportAnnotation(const ExprNodePtr& node); const QType* ReadQTypeAnnotation(const ExprNodePtr& node); absl::string_view ReadNameAnnotation(const ExprNodePtr& node); absl::string_view ReadExportAnnotationTag(const ExprNodePtr& node); ExprNodePtr ReadExportAnnotationValue(const ExprNodePtr& node); } #endif #include "arolla/expr/annotation_utils.h" #include <utility> #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "arolla/expr/annotation_expr_operators.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_debug_string.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/expr_visitor.h" #include "arolla/expr/registered_expr_operator.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/util/text.h" #include "arolla/util/status_macros_backport.h" namespace arolla::expr { absl::StatusOr<bool> IsAnnotation(const ExprNodePtr& node) { ASSIGN_OR_RETURN(auto op, DecayRegisteredOperator(node->op())); return !node->node_deps().empty() && dynamic_cast<const AnnotationExprOperatorTag*>(op.get()) != nullptr; } absl::StatusOr<bool> IsDetachedAnnotation(const ExprNodePtr& node) { ASSIGN_OR_RETURN(bool is_annotation, IsAnnotation(node)); DCHECK(!is_annotation || !node->node_deps().empty()); return is_annotation && node->node_deps()[0]->is_placeholder(); } absl::StatusOr<ExprNodePtr> GetDetachedAnnotation(ExprNodePtr node) { ASSIGN_OR_RETURN(bool is_annotation, IsAnnotation(node)); if (!is_annotation) { return absl::InvalidArgumentError( absl::StrCat("can not detach annotation from ", GetDebugSnippet(node), " that is not a valid annotation node")); } auto new_deps = node->node_deps(); DCHECK(!new_deps.empty()); new_deps[0] = Placeholder("_"); return WithNewDependencies(node, std::move(new_deps)); } absl::StatusOr<ExprNodePtr> AttachAnnotation(const ExprNodePtr& node, const ExprNodePtr& annotation) { ASSIGN_OR_RETURN(bool is_detached_annotation, IsDetachedAnnotation(annotation)); if (!is_detached_annotation) { return absl::InvalidArgumentError(absl::StrCat( "can not attach a node that is not a detached annotation: %s", GetDebugSnippet(node))); } auto new_deps = annotation->node_deps(); DCHECK(!new_deps.empty()); new_deps[0] = node; return WithNewDependencies(annotation, std::move(new_deps)); } absl::StatusOr<ExprNodePtr> AttachAnnotations( const ExprNodePtr& node, absl::Span<const ExprNodePtr> annotations) { ExprNodePtr annotated_node = node; for (const auto& anno : annotations) { ASSIGN_OR_RETURN(annotated_node, AttachAnnotation(annotated_node, anno)); } return annotated_node; } absl::StatusOr<ExprNodePtr> StripTopmostAnnotations(const ExprNodePtr& expr) { ExprNodePtr annotationless_expr = expr; ASSIGN_OR_RETURN(bool is_annotation, IsAnnotation(annotationless_expr)); while (is_annotation) { if (annotationless_expr->node_deps().empty()) { return absl::FailedPreconditionError( absl::StrFormat("incorrect annotation node %s", GetDebugSnippet(annotationless_expr))); } annotationless_expr = annotationless_expr->node_deps()[0]; ASSIGN_OR_RETURN(is_annotation, IsAnnotation(annotationless_expr)); } return annotationless_expr; } absl::StatusOr<ExprNodePtr> StripAnnotations(const ExprNodePtr& expr) { return Transform( expr, [](const ExprNodePtr& node) -> absl::StatusOr<ExprNodePtr> { ASSIGN_OR_RETURN(bool is_annotation, IsAnnotation(node)); DCHECK(!is_annotation || !node->node_deps().empty()); return is_annotation ? node->node_deps()[0] : node; }); } bool IsQTypeAnnotation(const ExprNodePtr& node) { auto op = DecayRegisteredOperator(node->op()).value_or(nullptr); return op != nullptr && typeid(*op) == typeid(QTypeAnnotation) && node->node_deps().size() == 2; } bool IsNameAnnotation(const ExprNodePtr& node) { auto op = DecayRegisteredOperator(node->op()).value_or(nullptr); return op != nullptr && typeid(*op) == typeid(NameAnnotation) && node->node_deps().size() == 2; } bool IsExportAnnotation(const ExprNodePtr& node) { auto op = DecayRegisteredOperator(node->op()).value_or(nullptr); return op != nullptr && ((typeid(*op) == typeid(ExportAnnotation) && node->node_deps().size() == 2) || (typeid(*op) == typeid(ExportValueAnnotation) && node->node_deps().size() == 3)); } const QType* ReadQTypeAnnotation(const ExprNodePtr& node) { if (IsQTypeAnnotation(node)) { DCHECK_EQ(node->node_deps().size(), 2); if (const auto& qvalue = node->node_deps()[1]->qvalue()) { if (qvalue->GetType() == GetQTypeQType()) { return qvalue->UnsafeAs<QTypePtr>(); } } } return nullptr; } absl::string_view ReadNameAnnotation(const ExprNodePtr& node) { if (IsNameAnnotation(node)) { DCHECK_EQ(node->node_deps().size(), 2); if (const auto& qvalue = node->node_deps()[1]->qvalue()) { if (qvalue->GetType() == GetQType<Text>()) { return qvalue->UnsafeAs<Text>().view(); } } } return ""; } absl::string_view ReadExportAnnotationTag(const ExprNodePtr& node) { if (IsExportAnnotation(node)) { DCHECK_GE(node->node_deps().size(), 2); if (node->node_deps()[1]->qvalue().has_value() && node->node_deps()[1]->qvalue()->GetType() == GetQType<Text>()) { return node->node_deps()[1]->qvalue()->UnsafeAs<Text>().view(); } } return {}; } ExprNodePtr ReadExportAnnotationValue(const ExprNodePtr& node) { if (IsExportAnnotation(node)) { if (node->node_deps().size() == 2) { return node->node_deps()[0]; } else if (node->node_deps().size() == 3) { return node->node_deps()[2]; } } return nullptr; } }
#include "arolla/expr/annotation_utils.h" #include <memory> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/types/span.h" #include "arolla/expr/annotation_expr_operators.h" #include "arolla/expr/basic_expr_operator.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/expr/testing/testing.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/util/fingerprint.h" #include "arolla/util/init_arolla.h" #include "arolla/util/testing/status_matchers_backport.h" #include "arolla/util/text.h" namespace arolla::expr { namespace { using ::arolla::testing::EqualsExpr; using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::StatusIs; using ::testing::Eq; using ::testing::HasSubstr; class AnnotationOperatorTest : public ::testing::Test { void SetUp() override { ASSERT_OK(InitArolla()); } }; class IdentityAnnotation : public AnnotationExprOperatorTag, public BasicExprOperator { public: IdentityAnnotation() : BasicExprOperator( "id", ExprOperatorSignature::MakeArgsN(1), "", FingerprintHasher("arolla::expr::IdentityAnnotation").Finish()) {} absl::StatusOr<QTypePtr> GetOutputQType( absl::Span<const QTypePtr> input_qtypes) const override { return input_qtypes[0]; } }; TEST_F(AnnotationOperatorTest, SmokeTest) { const auto with_annotation = std::make_shared<IdentityAnnotation>(); ASSERT_OK_AND_ASSIGN(auto expr, CallOp(with_annotation, {Leaf("x")})); ASSERT_OK_AND_ASSIGN(auto lower_expr, ToLowerNode(expr)); EXPECT_THAT(lower_expr, EqualsExpr(expr)); ASSERT_OK_AND_ASSIGN(auto typed_expr, CallOp(with_annotation, {Literal<float>(1.0)})); EXPECT_EQ(typed_expr->qtype(), GetQType<float>()); } TEST_F(AnnotationOperatorTest, StripAnnotations) { const auto id_anno = std::make_shared<IdentityAnnotation>(); { ASSERT_OK_AND_ASSIGN( ExprNodePtr expr, CallOp(id_anno, {CallOp("math.add", {CallOp(id_anno, {Leaf("x")}), Leaf("y")})})); ASSERT_OK_AND_ASSIGN(ExprNodePtr actual, StripAnnotations(expr)); ASSERT_OK_AND_ASSIGN(ExprNodePtr expected, CallOp("math.add", {Leaf("x"), Leaf("y")})); EXPECT_THAT(actual, EqualsExpr(expected)); } { ASSERT_OK_AND_ASSIGN(ExprNodePtr expr, CallOp(id_anno, {CallOp(id_anno, {Leaf("x")})})); ASSERT_OK_AND_ASSIGN(ExprNodePtr actual, StripAnnotations(expr)); ExprNodePtr expected = Leaf("x"); EXPECT_THAT(actual, EqualsExpr(expected)); } } TEST_F(AnnotationOperatorTest, StripTopmostAnnotations) { const auto id_anno = std::make_shared<IdentityAnnotation>(); { ASSERT_OK_AND_ASSIGN( ExprNodePtr expr, CallOp(id_anno, {CallOp("math.add", {CallOp(id_anno, {Leaf("x")}), Leaf("y")})})); EXPECT_THAT(StripTopmostAnnotations(expr), IsOkAndHolds(EqualsExpr(CallOp( "math.add", {CallOp(id_anno, {Leaf("x")}), Leaf("y")})))); } { ASSERT_OK_AND_ASSIGN(ExprNodePtr expr, CallOp(id_anno, {CallOp(id_anno, {Leaf("x")})})); EXPECT_THAT(StripTopmostAnnotations(expr), IsOkAndHolds(EqualsExpr(Leaf("x")))); } } class IdentityAnnotation2 : public AnnotationExprOperatorTag, public BasicExprOperator { public: IdentityAnnotation2() : BasicExprOperator( "id2", ExprOperatorSignature::MakeArgsN(1), "", FingerprintHasher("arolla::expr::IdentityAnnotation2").Finish()) {} absl::StatusOr<QTypePtr> GetOutputQType( absl::Span<const QTypePtr> input_qtypes) const override { return input_qtypes[0]; } }; TEST_F(AnnotationOperatorTest, AttachAnnotations) { ExprNodePtr expr = Leaf("x"); EXPECT_THAT(AttachAnnotation(expr, expr), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("not a detached annotation"))); const auto id_anno = std::make_shared<IdentityAnnotation>(); const auto id_anno2 = std::make_shared<IdentityAnnotation2>(); ASSERT_OK_AND_ASSIGN(auto anno1, CallOp(id_anno, {Placeholder("_")})); ASSERT_OK_AND_ASSIGN(auto anno2, CallOp(id_anno2, {Placeholder("_")})); std::vector<ExprNodePtr> annotations = {anno1, anno2}; ASSERT_OK_AND_ASSIGN(auto anno_expr, AttachAnnotations(expr, annotations)); ASSERT_OK_AND_ASSIGN(ExprNodePtr expected_anno_expr, CallOp(id_anno2, {CallOp(id_anno, {Leaf("x")})})); EXPECT_THAT(anno_expr, EqualsExpr(expected_anno_expr)); ASSERT_OK_AND_ASSIGN(auto detached, StripAnnotations(anno_expr)); EXPECT_THAT(detached, EqualsExpr(expr)); } TEST_F(AnnotationOperatorTest, AnnotationExport) { ASSERT_OK_AND_ASSIGN( ExprNodePtr expr, CallOp(ExportAnnotation::Make(), {Leaf("a"), Literal(Text{"b"})})); ASSERT_TRUE(IsExportAnnotation(expr)); auto expected_value = Leaf("a"); EXPECT_THAT(ReadExportAnnotationTag(expr), Eq("b")); EXPECT_THAT(ReadExportAnnotationValue(expr), EqualsExpr(expected_value)); } TEST_F(AnnotationOperatorTest, AnnotationExportValue) { ASSERT_OK_AND_ASSIGN(ExprNodePtr expr, CallOp(ExportValueAnnotation::Make(), {Leaf("a"), Literal(Text{"b"}), Leaf("c")})); ASSERT_TRUE(IsExportAnnotation(expr)); auto expected_value = Leaf("c"); EXPECT_THAT(ReadExportAnnotationTag(expr), Eq("b")); EXPECT_THAT(ReadExportAnnotationValue(expr), EqualsExpr(expected_value)); } TEST_F(AnnotationOperatorTest, AnnotationExportArbitraryNode) { ExprNodePtr expr = Leaf("a"); ASSERT_FALSE(IsExportAnnotation(expr)); EXPECT_EQ(ReadExportAnnotationTag(expr), ""); EXPECT_EQ(ReadExportAnnotationValue(expr), nullptr); } } }
2,422
#ifndef AROLLA_EXPR_EXPR_VISITOR_H_ #define AROLLA_EXPR_EXPR_VISITOR_H_ #include <cstddef> #include <optional> #include <type_traits> #include <utility> #include <vector> #include "absl/algorithm/container.h" #include "absl/base/attributes.h" #include "absl/functional/function_ref.h" #include "absl/log/check.h" #include "absl/status/statusor.h" #include "absl/types/span.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_debug_string.h" #include "arolla/expr/expr_node.h" #include "arolla/util/meta.h" #include "arolla/util/status_macros_backport.h" namespace arolla::expr { class PostOrder { public: PostOrder() = default; explicit PostOrder(const ExprNodePtr& root); absl::Span<const ExprNodePtr> nodes() const { return nodes_; } size_t nodes_size() const { return nodes_.size(); } const ExprNodePtr& node(size_t node_index) const ABSL_ATTRIBUTE_LIFETIME_BOUND { return nodes_[node_index]; } absl::Span<const size_t> dep_indices(size_t node_index) const { DCHECK(node_index < nodes_.size()); return absl::Span<const size_t>( adjacency_array_.data() + adjacency_array_[node_index], adjacency_array_[node_index + 1] - adjacency_array_[node_index]); } private: std::vector<ExprNodePtr> nodes_; std::vector<size_t> adjacency_array_; }; std::vector<ExprNodePtr> VisitorOrder(ExprNodePtr root); std::vector<std::pair<bool, ExprNodePtr>> PreAndPostVisitorOrder( ExprNodePtr root); template <typename VisitorResultType> struct ExprVisitorResultTraits; template <typename Visitor> auto PostOrderTraverse(const PostOrder& post_order, Visitor visitor) { using Traits = ExprVisitorResultTraits< typename meta::function_traits<Visitor>::return_type>; using T = typename Traits::ResultType; static_assert(std::is_invocable_r_v<absl::StatusOr<T>, Visitor, ExprNodePtr, absl::Span<const T* const>>, "Visitor has an unexpected signature."); struct WrappedT { T value; WrappedT(T&& value) : value(std::move(value)) {} WrappedT(WrappedT&&) = default; WrappedT& operator=(WrappedT&&) = default; }; std::vector<WrappedT> results; results.reserve(post_order.nodes_size()); std::vector<const T*> args; const auto invoke_visitor = [&](size_t node_index) { const auto dep_indices = post_order.dep_indices(node_index); args.resize(dep_indices.size()); for (size_t j = 0; j < dep_indices.size(); ++j) { args[j] = &results[dep_indices[j]].value; } return visitor(post_order.node(node_index), absl::MakeConstSpan(args)); }; for (size_t i = 0; i + 1 < post_order.nodes_size(); ++i) { auto visit_result = invoke_visitor(i); if (!Traits::ok(visit_result)) { return visit_result; } results.emplace_back(Traits::value(std::move(visit_result))); } return invoke_visitor(post_order.nodes_size() - 1); } template <typename Visitor> auto PostOrderTraverse(const ExprNodePtr& root, Visitor visitor) { return PostOrderTraverse(PostOrder(root), visitor); } template <typename TransformFn> absl::StatusOr<ExprNodePtr> Transform(const ExprNodePtr& root, TransformFn transform_fn) { return TransformOnPostOrder(PostOrder(root), std::move(transform_fn)); } template <typename TransformFn> absl::StatusOr<ExprNodePtr> TransformOnPostOrder(const PostOrder& post_order, TransformFn transform_fn) { using Traits = ExprVisitorResultTraits< typename meta::function_traits<TransformFn>::return_type>; static_assert(std::is_invocable_r_v<absl::StatusOr<ExprNodePtr>, TransformFn, ExprNodePtr>, "TransformFn has an unexpected signature."); std::vector<ExprNodePtr> results(post_order.nodes_size()); for (size_t i = 0; i < post_order.nodes_size(); ++i) { const auto& node = post_order.node(i); const auto& dep_indices = post_order.dep_indices(i); bool has_modified_dep = node->is_op() && absl::c_any_of(dep_indices, [&](size_t k) { return results[k] != nullptr; }); ExprNodePtr transform_fn_input_node; if (has_modified_dep) { const auto& deps = node->node_deps(); std::vector<ExprNodePtr> new_deps(dep_indices.size()); for (size_t j = 0; j < dep_indices.size(); ++j) { const size_t k = dep_indices[j]; if (results[k] != nullptr) { new_deps[j] = results[k]; } else { new_deps[j] = deps[j]; } } ASSIGN_OR_RETURN(transform_fn_input_node, MakeOpNode(node->op(), std::move(new_deps)), _ << "while processing " << GetDebugSnippet(node)); } else { transform_fn_input_node = node; } auto transform_fn_result = transform_fn(std::move(transform_fn_input_node)); if (!Traits::ok(transform_fn_result)) { return transform_fn_result; } auto new_node = Traits::value(std::move(transform_fn_result)); if (new_node->fingerprint() != node->fingerprint()) { results[i] = Traits::value(std::move(new_node)); } } if (results.back() != nullptr) { return std::move(results.back()); } else { return post_order.nodes().back(); } } enum class DeepTransformStage { kWithNewDeps, kNewChildAfterTransformation }; using LogTransformationFn = absl::FunctionRef<void( ExprNodePtr new_node, ExprNodePtr old_node, DeepTransformStage stage)>; absl::StatusOr<ExprNodePtr> DeepTransform( const ExprNodePtr& root, absl::FunctionRef<absl::StatusOr<ExprNodePtr>(ExprNodePtr)> transform_fn, std::optional<LogTransformationFn> log_transformation_fn = std::nullopt, size_t processed_node_limit = 10'000'000); template <typename VisitorResultType> struct ExprVisitorResultTraits { using ResultType = VisitorResultType; static constexpr bool ok(const VisitorResultType&) { return true; } static constexpr ResultType value(VisitorResultType&& input) { return input; } }; template <typename T> struct ExprVisitorResultTraits<absl::StatusOr<T>> { using ResultType = T; static bool ok(const absl::StatusOr<T>& input) { return input.ok(); } static ResultType value(absl::StatusOr<T>&& input) { return *std::move(input); } }; template <typename T> std::vector<T> DereferenceVisitPointers(absl::Span<const T* const> visits) { std::vector<T> res; res.reserve(visits.size()); for (const T* ptr : visits) { res.push_back(*ptr); } return res; } } #endif #include "arolla/expr/expr_visitor.h" #include <cstddef> #include <limits> #include <optional> #include <stack> #include <utility> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/container/flat_hash_set.h" #include "absl/functional/function_ref.h" #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_debug_string.h" #include "arolla/expr/expr_node.h" #include "arolla/util/fingerprint.h" #include "arolla/util/status_macros_backport.h" namespace arolla::expr { namespace { template <class PrevisitFn, class PostVisitFn> void VisitorOrderImpl(const ExprNodePtr& root, PrevisitFn previsit_fn, PostVisitFn postvisit_fn) { struct Frame { const ExprNodePtr& node; size_t processed_deps_count = 0; }; absl::flat_hash_set<Fingerprint> visited = {root->fingerprint()}; std::vector<Frame> stack = {Frame{root}}; while (!stack.empty()) { auto& frame = stack.back(); if (frame.processed_deps_count == 0) { previsit_fn(frame.node); } const auto& node_deps = frame.node->node_deps(); if (frame.processed_deps_count == node_deps.size()) { postvisit_fn(frame.node); stack.pop_back(); continue; } const auto& dep = node_deps[frame.processed_deps_count++]; if (visited.insert(dep->fingerprint()).second) { stack.push_back(Frame{dep}); } } } } std::vector<ExprNodePtr> VisitorOrder(ExprNodePtr root) { std::vector<ExprNodePtr> res_visits; VisitorOrderImpl( root, [](auto) {}, [&res_visits](const auto& node) { res_visits.push_back(node); }); return res_visits; } std::vector<std::pair<bool, ExprNodePtr>> PreAndPostVisitorOrder( ExprNodePtr root) { std::vector<std::pair<bool, ExprNodePtr>> res_visits; VisitorOrderImpl( root, [&res_visits](const auto& node) { res_visits.emplace_back(true, node); }, [&res_visits](const auto& node) { res_visits.emplace_back(false, node); }); return res_visits; } PostOrder::PostOrder(const ExprNodePtr& root) { struct Frame { const ExprNodePtr& node; size_t dep_idx = 0; }; absl::flat_hash_map<Fingerprint, size_t> node_indices; { std::vector<Frame> stack; stack.push_back(Frame{root}); while (!stack.empty()) { auto& frame = stack.back(); const auto& deps = frame.node->node_deps(); while (frame.dep_idx < deps.size() && node_indices.contains(deps[frame.dep_idx]->fingerprint())) { ++frame.dep_idx; } if (frame.dep_idx < deps.size()) { stack.push_back(Frame{deps[frame.dep_idx++]}); } else { node_indices.emplace(frame.node->fingerprint(), nodes_.size()); nodes_.push_back(frame.node); stack.pop_back(); } } } { size_t total_arc_count = 0; for (const auto& node : nodes_) { total_arc_count += node->node_deps().size(); } adjacency_array_.resize(nodes_.size() + 1 + total_arc_count); size_t i = 0; size_t j = nodes_.size() + 1; while (i < nodes_.size()) { adjacency_array_[i] = j; for (const auto& dep : nodes_[i++]->node_deps()) { adjacency_array_[j++] = node_indices.at(dep->fingerprint()); } } adjacency_array_[nodes_.size()] = j; } } absl::StatusOr<ExprNodePtr> DeepTransform( const ExprNodePtr& root, absl::FunctionRef<absl::StatusOr<ExprNodePtr>(ExprNodePtr)> transform_fn, std::optional<LogTransformationFn> log_transformation_fn, size_t processed_node_limit) { constexpr size_t kSkipFirstStage = std::numeric_limits<size_t>::max(); constexpr auto infinite_loop_error = [](const ExprNodePtr& node) { return absl::FailedPreconditionError(absl::StrFormat( "infinite loop of node transformations containing node %s", GetDebugSnippet(node))); }; struct Frame { ExprNodePtr node; size_t dep_idx = 0; Fingerprint new_node_fingerprint; Fingerprint transformed_new_node_fingerprint; std::optional<ExprNodePtr> original_node = std::nullopt; }; absl::flat_hash_map<Fingerprint, ExprNodePtr> cache; std::stack<Frame> stack; cache.emplace(root->fingerprint(), nullptr); stack.emplace(Frame{.node = root}); while (!stack.empty()) { auto& frame = stack.top(); if (cache.size() > processed_node_limit) { return absl::FailedPreconditionError(absl::StrFormat( "too many processed nodes (%i), this probably means an infinite " "transformation. Possibly caused by node %s", cache.size(), GetDebugSnippet(frame.node))); } if (frame.dep_idx != kSkipFirstStage) { const auto& deps = frame.node->node_deps(); while ( frame.dep_idx < deps.size() && !cache.emplace(deps[frame.dep_idx]->fingerprint(), nullptr).second) { ++frame.dep_idx; } if (frame.dep_idx < deps.size()) { if (log_transformation_fn.has_value() && frame.original_node != std::nullopt) { (*log_transformation_fn)( deps[frame.dep_idx], frame.node, DeepTransformStage::kNewChildAfterTransformation); } stack.emplace(Frame{.node = deps[frame.dep_idx++], .original_node = frame.original_node}); continue; } std::vector<ExprNodePtr> new_deps(deps.size()); for (size_t i = 0; i < deps.size(); ++i) { new_deps[i] = cache[deps[i]->fingerprint()]; if (new_deps[i] == nullptr) { return infinite_loop_error(frame.node); } } ASSIGN_OR_RETURN(auto new_node, WithNewDependencies(frame.node, std::move(new_deps))); if (log_transformation_fn.has_value()) { (*log_transformation_fn)(new_node, frame.node, DeepTransformStage::kWithNewDeps); } if (new_node->fingerprint() != frame.node->fingerprint()) { if (auto [it, miss] = cache.emplace(new_node->fingerprint(), nullptr); !miss) { if (it->second == nullptr) { return infinite_loop_error(frame.node); } cache[frame.node->fingerprint()] = it->second; stack.pop(); continue; } } ASSIGN_OR_RETURN( auto transformed_new_node, transform_fn(new_node), _ << "while transforming " << GetDebugSnippet(frame.node)); DCHECK_NE(transformed_new_node, nullptr); if (transformed_new_node->fingerprint() == new_node->fingerprint()) { cache[frame.node->fingerprint()] = std::move(transformed_new_node); if (new_node->fingerprint() != frame.node->fingerprint()) { cache[new_node->fingerprint()] = std::move(new_node); } stack.pop(); continue; } if (auto [it, miss] = cache.emplace(transformed_new_node->fingerprint(), nullptr); !miss) { if (it->second == nullptr) { return infinite_loop_error(frame.node); } cache[frame.node->fingerprint()] = it->second; if (new_node->fingerprint() != frame.node->fingerprint()) { cache[new_node->fingerprint()] = it->second; } stack.pop(); continue; } frame.dep_idx = kSkipFirstStage; frame.new_node_fingerprint = new_node->fingerprint(); frame.transformed_new_node_fingerprint = transformed_new_node->fingerprint(); stack.emplace(Frame{.node = transformed_new_node, .original_node = transformed_new_node}); continue; } const auto& node_result = cache.at(frame.transformed_new_node_fingerprint); DCHECK_NE(node_result, nullptr); cache[frame.node->fingerprint()] = node_result; if (frame.new_node_fingerprint != frame.node->fingerprint()) { cache[frame.new_node_fingerprint] = node_result; } stack.pop(); } auto& root_result = cache.at(root->fingerprint()); DCHECK_NE(root_result, nullptr); return std::move(root_result); } }
#include "arolla/expr/expr_visitor.h" #include <cstddef> #include <functional> #include <memory> #include <optional> #include <string> #include <utility> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/container/flat_hash_set.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/types/span.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_debug_string.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/expr/testing/test_operators.h" #include "arolla/expr/testing/testing.h" #include "arolla/util/fingerprint.h" #include "arolla/util/init_arolla.h" #include "arolla/util/testing/status_matchers_backport.h" namespace arolla::expr { namespace { using ::arolla::expr::testing::DummyOp; using ::arolla::testing::EqualsExpr; using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::StatusIs; using ::testing::ElementsAre; using ::testing::Eq; using ::testing::HasSubstr; using ::testing::Pair; using ::testing::Pointer; size_t CountNodes(const ExprNodePtr& expr) { size_t result = 0; return PostOrderTraverse( expr, [&](const ExprNodePtr& , absl::Span<const size_t* const> ) { return ++result; }); } class ExprVisitorTest : public ::testing::Test { public: template <typename... Args> ExprNodePtr Bar(Args&&... args) { return CallOp(bar_, {std::forward<Args>(args)...}).value(); } template <typename... Args> ExprNodePtr Baz(Args&&... args) { return CallOp(baz_, {std::forward<Args>(args)...}).value(); } template <typename... Args> ExprNodePtr Qux(Args&&... args) { return CallOp(qux_, {std::forward<Args>(args)...}).value(); } protected: void SetUp() override { ASSERT_OK(InitArolla()); } ExprOperatorPtr bar_ = std::make_shared<DummyOp>( "bar", ExprOperatorSignature::MakeVariadicArgs()); ExprOperatorPtr baz_ = std::make_shared<DummyOp>( "baz", ExprOperatorSignature::MakeVariadicArgs()); ExprOperatorPtr qux_ = std::make_shared<DummyOp>( "qux", ExprOperatorSignature::MakeVariadicArgs()); }; TEST_F(ExprVisitorTest, PostOrder_Trivial) { auto x0 = Leaf("x0"); PostOrder post_order(x0); ASSERT_THAT(post_order.nodes(), ElementsAre(Pointer(x0.get()))); ASSERT_THAT(post_order.dep_indices(0), ElementsAre()); } TEST_F(ExprVisitorTest, PostOrder) { auto x0 = Leaf("x0"); auto x1 = Leaf("x1"); auto x2 = Leaf("x2"); auto add01 = Bar(x0, x1); auto add012 = Bar(add01, x0, x1, x2); PostOrder post_order(add012); ASSERT_THAT( post_order.nodes(), ElementsAre(Pointer(x0.get()), Pointer(x1.get()), Pointer(add01.get()), Pointer(x2.get()), Pointer(add012.get()))); ASSERT_THAT(post_order.dep_indices(0), ElementsAre()); ASSERT_THAT(post_order.dep_indices(1), ElementsAre()); ASSERT_THAT(post_order.dep_indices(2), ElementsAre(0, 1)); ASSERT_THAT(post_order.dep_indices(3), ElementsAre()); ASSERT_THAT(post_order.dep_indices(4), ElementsAre(2, 0, 1, 3)); } TEST_F(ExprVisitorTest, VisitOrder) { auto x0 = Leaf("x0"); auto x1 = Leaf("x1"); auto x2 = Leaf("x2"); auto add01 = Bar(x0, x1); auto add012 = Bar(add01, x2); std::vector<ExprNodePtr> actual_order = VisitorOrder(add012); ASSERT_THAT(actual_order, ElementsAre(Pointer(x0.get()), Pointer(x1.get()), Pointer(add01.get()), Pointer(x2.get()), Pointer(add012.get()))); } TEST_F(ExprVisitorTest, PreAndPostVisitorOrder) { auto x0 = Leaf("x0"); auto x1 = Leaf("x1"); auto x2 = Leaf("x2"); auto add01 = Bar(x0, x1); auto add012 = Bar(add01, x2); std::vector<std::pair<bool, ExprNodePtr>> actual_order = PreAndPostVisitorOrder(add012); ASSERT_THAT( actual_order, ElementsAre( Pair(true, Pointer(add012.get())), Pair(true, Pointer(add01.get())), Pair(true, Pointer(x0.get())), Pair(false, Pointer(x0.get())), Pair(true, Pointer(x1.get())), Pair(false, Pointer(x1.get())), Pair(false, Pointer(add01.get())), Pair(true, Pointer(x2.get())), Pair(false, Pointer(x2.get())), Pair(false, Pointer(add012.get())))); } TEST_F(ExprVisitorTest, PostOrderTraverseBool) { ASSERT_TRUE(PostOrderTraverse( Leaf("x"), [](ExprNodePtr, absl::Span<bool const* const>) -> bool { return true; })); } TEST_F(ExprVisitorTest, PostOrderTraverseStatusOrBool) { ASSERT_THAT(PostOrderTraverse(Leaf("x"), [](ExprNodePtr, absl::Span<bool const* const>) { return absl::StatusOr<bool>(true); }), IsOkAndHolds(true)); } TEST_F(ExprVisitorTest, VisitLeaf) { ASSERT_EQ(CountNodes(Leaf("x")), 1); } TEST_F(ExprVisitorTest, VisitOperator) { ASSERT_EQ(CountNodes(Bar(Leaf("x"), Leaf("y"))), 3); } TEST_F(ExprVisitorTest, LargeAst) { ASSERT_EQ(CountNodes(Bar(Bar(Leaf("x"), Leaf("y")), Leaf("x"))), 4); } TEST_F(ExprVisitorTest, Transform_WithStatusOrFn) { auto expr = Bar(Bar(Baz(Leaf("a"), Leaf("b")), Leaf("c")), Leaf("d")); ASSERT_OK_AND_ASSIGN( ExprNodePtr expr_with_qux, Transform(expr, [&](ExprNodePtr node) -> absl::StatusOr<ExprNodePtr> { if (node->op() == bar_) { return WithNewOperator(node, qux_); } return node; })); ASSERT_THAT( expr_with_qux, EqualsExpr(Qux(Qux(Baz(Leaf("a"), Leaf("b")), Leaf("c")), Leaf("d")))); EXPECT_THAT(expr_with_qux->node_deps()[0]->node_deps()[0].get(), Eq(expr->node_deps()[0]->node_deps()[0].get())); } TEST_F(ExprVisitorTest, Transform_WithNoStatusFn) { auto expr = Bar(Bar(Baz(Leaf("a"), Leaf("b")), Leaf("c")), Leaf("d")); EXPECT_THAT(Transform(expr, [&](ExprNodePtr node) -> ExprNodePtr { if (node->op() == bar_) { return node->node_deps()[0]; } else { return node; } }), IsOkAndHolds(EqualsExpr(expr->node_deps()[0]->node_deps()[0]))); } TEST_F(ExprVisitorTest, Transform_NoChangeRequired) { auto expr = Baz(Bar(Baz(Leaf("a"), Leaf("b")), Leaf("c")), Leaf("d")); EXPECT_THAT(Transform(expr, [](ExprNodePtr node) { return node; }), IsOkAndHolds(EqualsExpr(expr))); } class DeepTransformTest : public ::testing::Test { public: template <typename... Args> ExprNodePtr A(Args&&... args) { return CallOp(a_, {std::forward<Args>(args)...}).value(); } template <typename... Args> ExprNodePtr B(Args&&... args) { return CallOp(b_, {std::forward<Args>(args)...}).value(); } template <typename... Args> ExprNodePtr S(Args&&... args) { return CallOp(s_, {std::forward<Args>(args)...}).value(); } template <typename... Args> ExprNodePtr C(Args&&... args) { return CallOp(c_, {std::forward<Args>(args)...}).value(); } auto SabTransform() -> std::function<absl::StatusOr<ExprNodePtr>(ExprNodePtr)> { return [this, visited = absl::flat_hash_set<Fingerprint>()]( ExprNodePtr node) mutable -> absl::StatusOr<ExprNodePtr> { EXPECT_TRUE(visited.emplace(node->fingerprint()).second) << "duplicate call to transform_fn"; if (node->op() == s_) { std::vector<absl::StatusOr<ExprNodePtr>> new_deps; for (auto& dep : node->node_deps()) { new_deps.push_back(WithNewOperator(dep, s_)); } return CallOp(a_, new_deps); } if (node->op() == a_) { std::vector<absl::StatusOr<ExprNodePtr>> new_deps; for (auto& dep : node->node_deps()) { new_deps.push_back(WithNewOperator(dep, s_)); } return CallOp(b_, new_deps); } if (node->op() == c_) { std::vector<absl::StatusOr<ExprNodePtr>> new_deps; for (auto& dep : node->node_deps()) { new_deps.push_back(CallOp(b_, {dep})); } return CallOp(b_, new_deps); } return node; }; } private: void SetUp() override { ASSERT_OK(InitArolla()); } ExprOperatorPtr a_ = std::make_shared<DummyOp>("a", ExprOperatorSignature::MakeVariadicArgs()); ExprOperatorPtr b_ = std::make_shared<DummyOp>("b", ExprOperatorSignature::MakeVariadicArgs()); ExprOperatorPtr c_ = std::make_shared<DummyOp>("c", ExprOperatorSignature::MakeVariadicArgs()); ExprOperatorPtr s_ = std::make_shared<DummyOp>("s", ExprOperatorSignature::MakeVariadicArgs()); }; TEST_F(DeepTransformTest, Trivial) { ASSERT_THAT(DeepTransform(A(), SabTransform()), IsOkAndHolds(EqualsExpr(B()))); ASSERT_THAT(DeepTransform(B(), SabTransform()), IsOkAndHolds(EqualsExpr(B()))); ASSERT_THAT(DeepTransform(S(), SabTransform()), IsOkAndHolds(EqualsExpr(B()))); } TEST_F(DeepTransformTest, CacheHitCoverage) { { auto expr = B(A(A()), A(S())); auto expected = B(B(B()), B(B())); ASSERT_THAT(DeepTransform(expr, SabTransform()), IsOkAndHolds(EqualsExpr(expected))); } { auto expr = B(B(S()), A(S())); auto expected = B(B(B()), B(B())); ASSERT_THAT(DeepTransform(expr, SabTransform()), IsOkAndHolds(EqualsExpr(expected))); } } TEST_F(DeepTransformTest, TooManyProcessedNodes) { ASSERT_THAT(DeepTransform( Literal<int>(0), [](ExprNodePtr node) { return Literal<int>(node->qvalue()->UnsafeAs<int>() + 1); }, std::nullopt, 1000), StatusIs(absl::StatusCode::kFailedPrecondition, HasSubstr("too many processed nodes"))); } TEST_F(DeepTransformTest, LogTransformationFn) { std::string trace; auto transformations_logger = [&trace](ExprNodePtr a, ExprNodePtr b, DeepTransformStage stage) { if (stage == DeepTransformStage::kWithNewDeps) { if (a->fingerprint() != b->fingerprint()) { trace += GetDebugSnippet(b) + " got new dependencies: " + GetDebugSnippet(a) + "\n"; } } else if (stage == DeepTransformStage::kNewChildAfterTransformation) { trace += GetDebugSnippet(b) + " contains " + GetDebugSnippet(a) + "\n"; } }; ASSERT_OK(DeepTransform(C(A()), SabTransform(), transformations_logger)); EXPECT_EQ( "c(a():INT32):INT32 got new dependencies: c(b():INT32):INT32\n" "b(b(...):INT32):INT32 contains b(b():INT32):INT32\n", trace); } TEST_F(DeepTransformTest, InfiniteLoop) { ASSERT_THAT(DeepTransform(S(), [&](ExprNodePtr) { return S(S()); }), StatusIs(absl::StatusCode::kFailedPrecondition, HasSubstr("infinite loop of node transformations " "containing node s(s():INT32):INT32"))); } TEST_F(DeepTransformTest, UnaryRecursion) { auto expr = S(); auto expected = B(); for (int i = 0; i < 10; ++i) { expr = S(expr); expected = B(expected); } ASSERT_THAT(DeepTransform(expr, SabTransform()), IsOkAndHolds(EqualsExpr(expected))); } TEST_F(DeepTransformTest, UnaryRecursionStress) { auto expr = S(); auto expected = B(); for (int i = 0; i < 1000; ++i) { expr = S(expr); expected = B(expected); } ASSERT_THAT(DeepTransform(expr, SabTransform()), IsOkAndHolds(EqualsExpr(expected))); } TEST_F(DeepTransformTest, BinaryRecursion) { auto expr = S(); auto expected = B(); for (int i = 0; i < 10; ++i) { expr = S(expr, expr); expected = B(expected, expected); } ASSERT_THAT(DeepTransform(expr, SabTransform()), IsOkAndHolds(EqualsExpr(expected))); } TEST_F(DeepTransformTest, BinaryRecursionStress) { auto expr = S(); auto expected = B(); for (int i = 0; i < 1000; ++i) { expr = S(expr, expr); expected = B(expected, expected); } ASSERT_THAT(DeepTransform(expr, SabTransform()), IsOkAndHolds(EqualsExpr(expected))); } TEST_F(DeepTransformTest, TernaryRecursionStress) { auto expr = S(); auto expected = B(); for (int i = 0; i < 1000; ++i) { expr = S(expr, expr, expr); expected = B(expected, expected, expected); } ASSERT_THAT(DeepTransform(expr, SabTransform()), IsOkAndHolds(EqualsExpr(expected))); } TEST_F(DeepTransformTest, ComplexRecursionStress) { auto expr = S(); auto expected = B(); for (int i = 0; i < 1000; ++i) { expr = S(A(expr), B(expr, expected), expr); expected = B(B(expected), B(expected, expected), expected); } ASSERT_THAT(DeepTransform(expr, SabTransform()), IsOkAndHolds(EqualsExpr(expected))); } } }
2,423
#ifndef AROLLA_EXPR_EXPR_H_ #define AROLLA_EXPR_EXPR_H_ #include <initializer_list> #include <string> #include <utility> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_operator.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/typed_value.h" namespace arolla::expr { absl::StatusOr<ExprNodePtr> ToLowerNode(const ExprNodePtr& node); absl::StatusOr<ExprNodePtr> ToLowest(const ExprNodePtr& expr); template <typename T> ExprNodePtr Literal(T&& value) { return ExprNode::MakeLiteralNode( TypedValue::FromValue(std::forward<T>(value))); } template <typename T> ExprNodePtr Literal(const T& value) { return ExprNode::MakeLiteralNode(TypedValue::FromValue(value)); } inline ExprNodePtr Literal(const TypedValue& qvalue) { return ExprNode::MakeLiteralNode(TypedValue(qvalue)); } inline ExprNodePtr Literal(TypedValue& qvalue) { return ExprNode::MakeLiteralNode(TypedValue(qvalue)); } inline ExprNodePtr Literal(TypedValue&& qvalue) { return ExprNode::MakeLiteralNode(std::move(qvalue)); } inline ExprNodePtr Leaf(absl::string_view leaf_key) { return ExprNode::MakeLeafNode(leaf_key); } inline ExprNodePtr Placeholder(absl::string_view placeholder_key) { return ExprNode::MakePlaceholderNode(placeholder_key); } absl::StatusOr<ExprNodePtr> BindOp( ExprOperatorPtr op, absl::Span<const ExprNodePtr> args, const absl::flat_hash_map<std::string, ExprNodePtr>& kwargs); absl::StatusOr<ExprNodePtr> BindOp( absl::string_view op_name, absl::Span<const ExprNodePtr> args, const absl::flat_hash_map<std::string, ExprNodePtr>& kwargs); absl::StatusOr<ExprNodePtr> CallOp( absl::StatusOr<ExprOperatorPtr> status_or_op, std::initializer_list<absl::StatusOr<ExprNodePtr>> status_or_args, std::initializer_list<std::pair<std::string, absl::StatusOr<ExprNodePtr>>> status_or_kwargs = {}); absl::StatusOr<ExprNodePtr> CallOp( absl::StatusOr<ExprOperatorPtr> status_or_op, std::vector<absl::StatusOr<ExprNodePtr>> status_or_args, absl::flat_hash_map<std::string, absl::StatusOr<ExprNodePtr>> status_or_kwargs = {}); absl::StatusOr<ExprNodePtr> CallOp( absl::string_view op_name, std::initializer_list<absl::StatusOr<ExprNodePtr>> status_or_args, std::initializer_list<std::pair<std::string, absl::StatusOr<ExprNodePtr>>> status_or_kwargs = {}); absl::StatusOr<ExprNodePtr> CallOp( absl::string_view op_name, std::vector<absl::StatusOr<ExprNodePtr>> status_or_args, absl::flat_hash_map<std::string, absl::StatusOr<ExprNodePtr>> status_or_kwargs = {}); absl::StatusOr<ExprNodePtr> MakeOpNode(ExprOperatorPtr op, std::vector<ExprNodePtr> deps); absl::StatusOr<ExprNodePtr> WithNewOperator(const ExprNodePtr& node, ExprOperatorPtr op); absl::StatusOr<ExprNodePtr> WithNewDependencies(const ExprNodePtr& node, std::vector<ExprNodePtr> deps); std::vector<std::string> GetLeafKeys(const ExprNodePtr& expr); std::vector<std::string> GetPlaceholderKeys(const ExprNodePtr& expr); } #endif #include "arolla/expr/expr.h" #include <algorithm> #include <cstddef> #include <initializer_list> #include <memory> #include <string> #include <utility> #include <vector> #include "absl/algorithm/container.h" #include "absl/container/flat_hash_map.h" #include "absl/container/flat_hash_set.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" #include "absl/strings/str_join.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "arolla/expr/expr_attributes.h" #include "arolla/expr/expr_debug_string.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/expr/expr_visitor.h" #include "arolla/expr/qtype_utils.h" #include "arolla/expr/registered_expr_operator.h" #include "arolla/util/status.h" #include "arolla/util/status_macros_backport.h" namespace arolla::expr { absl::StatusOr<ExprNodePtr> ToLowerNode(const ExprNodePtr& node) { const auto& op = node->op(); if (op == nullptr) { return node; } ASSIGN_OR_RETURN(auto result, op->ToLowerLevel(node), _ << "while processing node " << GetDebugSnippet(node)); if (!node->attr().IsSubsetOf(result->attr())) { return absl::FailedPreconditionError(absl::StrFormat( "expression %s attributes changed in ToLower from %s to " "%s; this indicates incorrect InferAttributes() or GetOutputType() " "of the operator %s", GetDebugSnippet(node), absl::FormatStreamed(node->attr()), absl::FormatStreamed(result->attr()), op->display_name())); } return result; } absl::StatusOr<ExprNodePtr> ToLowest(const ExprNodePtr& expr) { return DeepTransform(expr, &ToLowerNode); } namespace { struct ExprNodeFormatter { void operator()(std::string* out, ExprNodePtr node) const { absl::StrAppend(out, GetDebugSnippet(node)); } }; bool AreExprAttributesTheSame(absl::Span<const ExprNodePtr> lexprs, absl::Span<const ExprNodePtr> rexprs) { if (lexprs.size() != rexprs.size()) { return false; } for (size_t i = 0; i != lexprs.size(); ++i) { if (!lexprs[i]->attr().IsIdenticalTo(rexprs[i]->attr())) { return false; } } return true; } } absl::StatusOr<ExprNodePtr> MakeOpNode(ExprOperatorPtr op, std::vector<ExprNodePtr> deps) { ASSIGN_OR_RETURN(auto output_attr, op->InferAttributes(GetExprAttrs(deps)), _ << "while calling " << op->display_name() << " with args {" << absl::StrJoin(deps, ", ", ExprNodeFormatter()) << "}"); return ExprNode::UnsafeMakeOperatorNode(std::move(op), std::move(deps), std::move(output_attr)); } absl::StatusOr<ExprNodePtr> BindOp( ExprOperatorPtr op, absl::Span<const ExprNodePtr> args, const absl::flat_hash_map<std::string, ExprNodePtr>& kwargs) { ASSIGN_OR_RETURN(auto signature, op->GetSignature()); ASSIGN_OR_RETURN( auto bound_args, BindArguments(signature, args, kwargs), _ << "while binding operator '" << op->display_name() << "'"); return MakeOpNode(std::move(op), std::move(bound_args)); } absl::StatusOr<ExprNodePtr> BindOp( absl::string_view op_name, absl::Span<const ExprNodePtr> args, const absl::flat_hash_map<std::string, ExprNodePtr>& kwargs) { ASSIGN_OR_RETURN(auto op, LookupOperator(op_name)); return BindOp(std::move(op), args, kwargs); } absl::StatusOr<ExprNodePtr> WithNewOperator(const ExprNodePtr& node, ExprOperatorPtr op) { if (!node->is_op()) { return absl::InvalidArgumentError( "WithNewOperator works only with operator nodes"); } return MakeOpNode(std::move(op), node->node_deps()); } absl::StatusOr<ExprNodePtr> WithNewDependencies(const ExprNodePtr& node, std::vector<ExprNodePtr> deps) { const auto& old_deps = node->node_deps(); if (absl::c_equal(old_deps, deps, [](const auto& lhs, const auto& rhs) { return lhs->fingerprint() == rhs->fingerprint(); })) { return node; } if (node->is_op()) { if (AreExprAttributesTheSame(old_deps, deps)) { return ExprNode::UnsafeMakeOperatorNode(ExprOperatorPtr(node->op()), std::move(deps), ExprAttributes(node->attr())); } else { return MakeOpNode(node->op(), std::move(deps)); } } if (!deps.empty()) { return absl::InvalidArgumentError( "only operator nodes can have dependencies"); } return node; } namespace { template <typename Strings> std::vector<std::string> SortedStrings(const Strings& strings) { std::vector<std::string> result; result.reserve(strings.size()); for (const auto& str : strings) { result.emplace_back(str); } std::sort(result.begin(), result.end()); return result; } } std::vector<std::string> GetLeafKeys(const ExprNodePtr& expr) { absl::flat_hash_set<absl::string_view> result; for (const auto& node : VisitorOrder(expr)) { if (node->is_leaf()) { result.emplace(node->leaf_key()); } } return SortedStrings(result); } std::vector<std::string> GetPlaceholderKeys(const ExprNodePtr& expr) { absl::flat_hash_set<absl::string_view> result; for (const auto& node : VisitorOrder(expr)) { if (node->is_placeholder()) { result.emplace(node->placeholder_key()); } } return SortedStrings(result); } absl::StatusOr<ExprNodePtr> CallOp( absl::StatusOr<ExprOperatorPtr> status_or_op, std::initializer_list<absl::StatusOr<ExprNodePtr>> status_or_args, std::initializer_list<std::pair<std::string, absl::StatusOr<ExprNodePtr>>> status_or_kwargs) { ASSIGN_OR_RETURN(auto op, std::move(status_or_op)); ASSIGN_OR_RETURN(std::vector<ExprNodePtr> args, LiftStatusUp(absl::Span<const absl::StatusOr<ExprNodePtr>>( status_or_args))); ASSIGN_OR_RETURN((absl::flat_hash_map<std::string, ExprNodePtr> kwargs), LiftStatusUp(status_or_kwargs)); return BindOp(op, args, kwargs); } absl::StatusOr<ExprNodePtr> CallOp( absl::StatusOr<ExprOperatorPtr> status_or_op, std::vector<absl::StatusOr<ExprNodePtr>> status_or_args, absl::flat_hash_map<std::string, absl::StatusOr<ExprNodePtr>> status_or_kwargs) { ASSIGN_OR_RETURN(auto op, std::move(status_or_op)); ASSIGN_OR_RETURN(auto args, LiftStatusUp(absl::Span<const absl::StatusOr<ExprNodePtr>>( status_or_args))); ASSIGN_OR_RETURN((absl::flat_hash_map<std::string, ExprNodePtr> kwargs), LiftStatusUp(status_or_kwargs)); return BindOp(op, args, kwargs); } absl::StatusOr<ExprNodePtr> CallOp( absl::string_view op_name, std::initializer_list<absl::StatusOr<ExprNodePtr>> status_or_args, std::initializer_list<std::pair<std::string, absl::StatusOr<ExprNodePtr>>> status_or_kwargs) { ASSIGN_OR_RETURN(auto args, LiftStatusUp(absl::Span<const absl::StatusOr<ExprNodePtr>>( status_or_args))); ASSIGN_OR_RETURN((absl::flat_hash_map<std::string, ExprNodePtr> kwargs), LiftStatusUp(status_or_kwargs)); return BindOp(op_name, args, kwargs); } absl::StatusOr<ExprNodePtr> CallOp( absl::string_view op_name, std::vector<absl::StatusOr<ExprNodePtr>> status_or_args, absl::flat_hash_map<std::string, absl::StatusOr<ExprNodePtr>> status_or_kwargs) { ASSIGN_OR_RETURN(auto args, LiftStatusUp(absl::Span<const absl::StatusOr<ExprNodePtr>>( status_or_args))); ASSIGN_OR_RETURN((absl::flat_hash_map<std::string, ExprNodePtr> kwargs), LiftStatusUp(status_or_kwargs)); return BindOp(op_name, args, kwargs); } }
#include "arolla/expr/expr.h" #include <cstdint> #include <memory> #include <utility> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "arolla/expr/annotation_utils.h" #include "arolla/expr/expr_attributes.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/expr/registered_expr_operator.h" #include "arolla/expr/testing/test_operators.h" #include "arolla/expr/testing/testing.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/typed_value.h" #include "arolla/util/bytes.h" #include "arolla/util/init_arolla.h" #include "arolla/util/testing/status_matchers_backport.h" #include "arolla/util/unit.h" namespace arolla::expr { namespace { using ::arolla::testing::EqualsExpr; using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::StatusIs; using ::arolla::testing::WithNameAnnotation; using ::arolla::testing::WithQTypeAnnotation; using ::testing::ElementsAre; using ::testing::Not; using ::testing::Eq; class ExprTest : public ::testing::Test { void SetUp() override { ASSERT_OK(InitArolla()); } }; TEST_F(ExprTest, CallOp) { ASSERT_OK_AND_ASSIGN(auto op, LookupOperator("math.add")); EXPECT_TRUE(IsRegisteredOperator(op)); ASSERT_OK_AND_ASSIGN(auto expr, CallOp(op, {Leaf("a"), Leaf("b")})); EXPECT_TRUE(expr->is_op()); EXPECT_TRUE(IsRegisteredOperator(expr->op())); ASSERT_OK_AND_ASSIGN(auto expected_expr, CallOp(op, {Leaf("a"), Leaf("b")})); EXPECT_THAT(expr, EqualsExpr(expected_expr)); } TEST_F(ExprTest, AdvancedCallOp) { auto x = Leaf("x"); auto y = Leaf("y"); auto z = Leaf("z"); auto w = Leaf("w"); auto def = Literal(kUnit); absl::StatusOr<ExprNodePtr> x_or(x); absl::StatusOr<ExprNodePtr> y_or(y); absl::StatusOr<ExprNodePtr> z_or(z); absl::StatusOr<ExprNodePtr> w_or(w); ASSERT_OK_AND_ASSIGN(const auto sig, ExprOperatorSignature::Make("p0, p1=, *tail", kUnit)); const auto op = std::make_shared<testing::DummyOp>( "test.expr_test.advanced_callop.dummy_op", sig); EXPECT_THAT( CallOp(op, {}), StatusIs(absl::StatusCode::kInvalidArgument)); { ASSERT_OK_AND_ASSIGN(auto expected_expr, MakeOpNode(op, {x, def})); EXPECT_THAT(CallOp(op, {x_or}), IsOkAndHolds(EqualsExpr(expected_expr))); } { ASSERT_OK_AND_ASSIGN(auto expected_expr, MakeOpNode(op, {x, y})); EXPECT_THAT(CallOp(op, {x_or, y_or}), IsOkAndHolds(EqualsExpr(expected_expr))); } { ASSERT_OK_AND_ASSIGN(auto expected_expr, MakeOpNode(op, {x, y, z})); EXPECT_THAT(CallOp(op, {x_or, y_or, z_or}), IsOkAndHolds(EqualsExpr(expected_expr))); } { ASSERT_OK_AND_ASSIGN(auto expected_expr, MakeOpNode(op, {x, y, z, w})); EXPECT_THAT(CallOp(op, {x_or, y_or, z_or, w_or}), IsOkAndHolds(EqualsExpr(expected_expr))); } { ASSERT_OK_AND_ASSIGN(auto expected_expr, MakeOpNode(op, {x, y})); EXPECT_THAT(CallOp(op, {x_or}, {{"p1", y_or}}), IsOkAndHolds(EqualsExpr(expected_expr))); } } TEST_F(ExprTest, LiftStatus) { auto x = Leaf("x"); auto y = Leaf("y"); ASSERT_OK_AND_ASSIGN(auto expected_expr, CallOp("math.add", {x, y})); EXPECT_THAT(CallOp("math.add", {Leaf("x"), Leaf("y")}), IsOkAndHolds(EqualsExpr(expected_expr))); EXPECT_THAT( CallOp("math.add", {Leaf("x"), absl::InvalidArgumentError("error")}), StatusIs(absl::StatusCode::kInvalidArgument)); } TEST_F(ExprTest, Literal) { const Bytes bytes("a long string literal to ensure memory allocation"); const TypedValue qvalue = TypedValue::FromValue(bytes); { auto x = Literal(bytes); ASSERT_OK_AND_ASSIGN(Bytes x_bytes, x->qvalue()->As<Bytes>()); EXPECT_THAT(x_bytes, Eq(bytes)); } { auto x = Literal<Bytes>(bytes); ASSERT_OK_AND_ASSIGN(Bytes x_bytes, x->qvalue()->As<Bytes>()); EXPECT_THAT(x_bytes, Eq(bytes)); } { auto copy = bytes; auto *data_raw_ptr = absl::string_view(copy).data(); auto x = Literal(std::move(copy)); EXPECT_EQ(absl::string_view(x->qvalue()->UnsafeAs<Bytes>()).data(), data_raw_ptr); } { auto copy = bytes; auto *data_raw_ptr = absl::string_view(copy).data(); auto x = Literal<Bytes>(std::move(copy)); EXPECT_EQ(absl::string_view(x->qvalue()->UnsafeAs<Bytes>()).data(), data_raw_ptr); } { auto x = Literal(qvalue); EXPECT_EQ(x->qvalue()->GetType(), qvalue.GetType()); EXPECT_EQ(x->qvalue()->GetRawPointer(), qvalue.GetRawPointer()); } { auto fn = [&]() { return qvalue; }; auto x = Literal(fn()); EXPECT_EQ(x->qvalue()->GetType(), qvalue.GetType()); EXPECT_EQ(x->qvalue()->GetRawPointer(), qvalue.GetRawPointer()); } { auto x = Literal(TypedValue(qvalue)); EXPECT_EQ(x->qvalue()->GetType(), qvalue.GetType()); EXPECT_EQ(x->qvalue()->GetRawPointer(), qvalue.GetRawPointer()); } } TEST_F(ExprTest, LiteralHash) { auto x = Literal(1.0); auto x1 = Literal(1.0); auto y = Literal(2.0); auto z = Literal(1); EXPECT_THAT(x, EqualsExpr(x1)); EXPECT_THAT(x, Not(EqualsExpr(y))); EXPECT_THAT(x, Not(EqualsExpr(z))); } TEST_F(ExprTest, WithNewOperator) { ASSERT_OK_AND_ASSIGN(auto op1, LookupOperator("math.add")); ASSERT_OK_AND_ASSIGN(auto op2, LookupOperator("math.multiply")); ASSERT_OK_AND_ASSIGN(auto actual_value, CallOp(op1, {Leaf("x"), Leaf("y")})); ASSERT_OK_AND_ASSIGN(actual_value, WithNewOperator(actual_value, op2)); ASSERT_OK_AND_ASSIGN(auto expected_value, CallOp(op2, {Leaf("x"), Leaf("y")})); EXPECT_THAT(actual_value, EqualsExpr(expected_value)); } TEST_F(ExprTest, WithName) { ASSERT_OK_AND_ASSIGN(auto named_literal, WithNameAnnotation(Literal(1.0), "a")); EXPECT_EQ(ReadNameAnnotation(named_literal), "a"); ASSERT_OK_AND_ASSIGN(auto named_leaf, WithNameAnnotation(Leaf("x"), "a")); EXPECT_EQ(ReadNameAnnotation(named_leaf), "a"); EXPECT_EQ(named_leaf->node_deps()[0]->leaf_key(), "x"); ASSERT_OK_AND_ASSIGN(auto named_placeholder, WithNameAnnotation(Placeholder("x"), "a")); EXPECT_EQ(ReadNameAnnotation(named_placeholder), "a"); EXPECT_EQ(named_placeholder->node_deps()[0]->placeholder_key(), "x"); } TEST_F(ExprTest, LeafHash) { auto x = Leaf("x"); auto x1 = Leaf("x"); auto y = Leaf("y"); ASSERT_OK_AND_ASSIGN(auto float_x, WithQTypeAnnotation(x, GetQType<float>())); ASSERT_OK_AND_ASSIGN(auto float_x1, WithQTypeAnnotation(x1, GetQType<float>())); ASSERT_OK_AND_ASSIGN(auto int_x, WithQTypeAnnotation(x, GetQType<int32_t>())); EXPECT_THAT(x, EqualsExpr(x1)); EXPECT_THAT(float_x, EqualsExpr(float_x1)); EXPECT_THAT(x, Not(EqualsExpr(y))); EXPECT_THAT(x, Not(EqualsExpr(float_x))); EXPECT_THAT(int_x, Not(EqualsExpr(float_x))); } TEST_F(ExprTest, PlaceholderHash) { auto x = Placeholder("x"); auto x1 = Placeholder("x"); auto y = Placeholder("y"); EXPECT_THAT(x, EqualsExpr(x1)); EXPECT_THAT(x, Not(EqualsExpr(y))); } TEST_F(ExprTest, GetLeafKeys) { auto l_a = Leaf("a"); auto l_b = Leaf("b"); auto p_a = Placeholder("a"); auto p_b = Placeholder("b"); { ASSERT_OK_AND_ASSIGN(const auto expr, CallOp("math.add", {p_a, p_b})); EXPECT_THAT(GetLeafKeys(expr), ElementsAre()); } { ASSERT_OK_AND_ASSIGN(const auto expr, CallOp("math.add", {l_a, p_b})); EXPECT_THAT(GetLeafKeys(expr), ElementsAre("a")); } { ASSERT_OK_AND_ASSIGN(const auto expr, CallOp("math.add", {p_a, l_b})); EXPECT_THAT(GetLeafKeys(expr), ElementsAre("b")); } { ASSERT_OK_AND_ASSIGN(const auto expr, CallOp("math.add", {l_a, l_b})); EXPECT_THAT(GetLeafKeys(expr), ElementsAre("a", "b")); } } TEST_F(ExprTest, GetPlaceholderKeys) { auto l_a = Leaf("a"); auto l_b = Leaf("b"); auto p_a = Placeholder("a"); auto p_b = Placeholder("b"); { ASSERT_OK_AND_ASSIGN(const auto expr, CallOp("math.add", {p_a, p_b})); EXPECT_THAT(GetPlaceholderKeys(expr), ElementsAre("a", "b")); } { ASSERT_OK_AND_ASSIGN(const auto expr, CallOp("math.add", {l_a, p_b})); EXPECT_THAT(GetPlaceholderKeys(expr), ElementsAre("b")); } { ASSERT_OK_AND_ASSIGN(const auto expr, CallOp("math.add", {p_a, l_b})); EXPECT_THAT(GetPlaceholderKeys(expr), ElementsAre("a")); } { ASSERT_OK_AND_ASSIGN(const auto expr, CallOp("math.add", {l_a, l_b})); EXPECT_THAT(GetPlaceholderKeys(expr), ElementsAre()); } } TEST_F(ExprTest, WithNewDependencies) { auto l_a = Leaf("a"); auto p_b = Placeholder("b"); auto lit = Literal(3.14); ASSERT_OK_AND_ASSIGN(const auto expr, CallOp("math.add", {l_a, p_b})); EXPECT_THAT(WithNewDependencies(l_a, {}), IsOkAndHolds(EqualsExpr(l_a))); EXPECT_THAT(WithNewDependencies(p_b, {}), IsOkAndHolds(EqualsExpr(p_b))); EXPECT_THAT(WithNewDependencies(lit, {}), IsOkAndHolds(EqualsExpr(lit))); ASSERT_OK_AND_ASSIGN(const auto actual_expr, WithNewDependencies(expr, {p_b, l_a})); ASSERT_OK_AND_ASSIGN(const auto expected_expr, CallOp("math.add", {p_b, l_a})); EXPECT_THAT(actual_expr, EqualsExpr(expected_expr)); } TEST_F(ExprTest, WithNewDependenciesOptimizations) { auto l_a = Leaf("a"); auto l_b = Leaf("b"); auto l_a2 = Leaf("a"); ASSERT_OK_AND_ASSIGN(const auto expr, CallOp("math.add", {l_a, l_a})); ASSERT_OK_AND_ASSIGN(const auto expr2, WithNewDependencies(expr, {l_a2, l_a2})); EXPECT_EQ(expr.get(), expr2.get()); ASSERT_OK_AND_ASSIGN(const auto expr3, WithNewDependencies(expr, {l_b, l_a})); EXPECT_NE(expr.get(), expr3.get()); } TEST_F(ExprTest, WithNewDependenciesAttr) { auto l_a = Leaf("a"); ASSERT_OK_AND_ASSIGN( const auto l_a_int, CallOp("annotation.qtype", {l_a, Literal(GetQType<int>())})); ASSERT_OK_AND_ASSIGN(const auto expr, CallOp("math.add", {l_a, l_a})); EXPECT_TRUE(expr->attr().IsIdenticalTo(ExprAttributes{})); ASSERT_OK_AND_ASSIGN(const auto expr_int, WithNewDependencies(expr, {l_a_int, l_a_int})); EXPECT_TRUE(expr_int->attr().IsIdenticalTo(ExprAttributes(GetQType<int>()))); ASSERT_OK_AND_ASSIGN(const auto expr2, WithNewDependencies(expr_int, {l_a_int, l_a})); EXPECT_TRUE(expr2->attr().IsIdenticalTo(ExprAttributes{})); } TEST_F(ExprTest, RegisterOperatorAlias) { CHECK_OK(RegisterOperatorAlias("alias_test.add3", "test.add3").status()); CHECK_OK(RegisterOperatorAlias("alias_test.power", "test.power").status()); { ASSERT_OK_AND_ASSIGN(auto expr, CallOp("alias_test.power", {Leaf("x"), Leaf("y")})); EXPECT_THAT(ToLowerNode(expr), IsOkAndHolds(EqualsExpr(expr))); } { ASSERT_OK_AND_ASSIGN(auto expr, CallOp("alias_test.add3", {Leaf("x"), Leaf("y"), Leaf("z")})); ASSERT_OK_AND_ASSIGN( auto expected_expr, CallOp("test.add3", {Leaf("x"), Leaf("y"), Leaf("z")})); ASSERT_OK_AND_ASSIGN(expected_expr, ToLowerNode(expected_expr)); EXPECT_THAT(ToLowerNode(expr), IsOkAndHolds(EqualsExpr(expected_expr))); } { ASSERT_OK_AND_ASSIGN( auto expr, CallOp("alias_test.add3", {Literal(5), Literal(6), Literal(7)})); EXPECT_EQ(expr->qtype(), GetQType<int>()); } { ASSERT_OK_AND_ASSIGN(auto alias_op, LookupOperator("alias_test.add3")); ASSERT_OK_AND_ASSIGN(auto op, LookupOperator("test.add3")); ASSERT_OK_AND_ASSIGN(auto actual_docstring, alias_op->GetDoc()); ASSERT_OK_AND_ASSIGN(auto expected_docstring, op->GetDoc()); EXPECT_EQ(actual_docstring, expected_docstring); ASSERT_OK_AND_ASSIGN(auto actual_signature, alias_op->GetSignature()); ASSERT_OK_AND_ASSIGN(auto expected_signature, op->GetSignature()); EXPECT_EQ(GetExprOperatorSignatureSpec(actual_signature), GetExprOperatorSignatureSpec(expected_signature)); } } TEST_F(ExprTest, ToLowerNode) { auto x = Leaf("x"); auto y = Leaf("y"); auto z = Leaf("z"); ASSERT_OK_AND_ASSIGN(auto expr, CallOp("test.add3", {x, y, z})); ASSERT_OK_AND_ASSIGN(auto actual_expr, ToLowerNode(expr)); ASSERT_OK_AND_ASSIGN(auto xy, CallOp("math.add", {x, y})); ASSERT_OK_AND_ASSIGN(auto expected_expr, CallOp("math.add", {xy, z})); EXPECT_THAT(actual_expr, EqualsExpr(expected_expr)); } TEST_F(ExprTest, ToLowest) { auto a = Leaf("a"); auto b = Leaf("b"); auto c = Leaf("c"); auto d = Leaf("d"); ASSERT_OK_AND_ASSIGN(auto expr, CallOp("test.add4", {a, b, c, d})); ASSERT_OK_AND_ASSIGN(auto actual_expr, ToLowest(expr)); ASSERT_OK_AND_ASSIGN(auto ab, CallOp("math.add", {a, b})); ASSERT_OK_AND_ASSIGN(auto abc, CallOp("math.add", {ab, c})); ASSERT_OK_AND_ASSIGN(auto abcd, CallOp("math.add", {abc, d})); EXPECT_THAT(actual_expr, EqualsExpr(abcd)); } } }
2,424
#ifndef AROLLA_EXPR_OPERATOR_REPR_FUNCTIONS_H_ #define AROLLA_EXPR_OPERATOR_REPR_FUNCTIONS_H_ #include <functional> #include <optional> #include <string> #include "absl/container/flat_hash_map.h" #include "arolla/expr/expr_node.h" #include "arolla/util/fingerprint.h" #include "arolla/util/repr.h" namespace arolla::expr { using OperatorReprFn = std::function<std::optional<ReprToken>( const ExprNodePtr&, const absl::flat_hash_map<Fingerprint, ReprToken>&)>; void RegisterOpReprFnByQValueSpecializationKey( std::string qvalue_specialization_key, OperatorReprFn op_repr_fn); void RegisterOpReprFnByByRegistrationName(std::string op_name, OperatorReprFn op_repr_fn); std::optional<ReprToken> FormatOperatorNodePretty( const ExprNodePtr& node, const absl::flat_hash_map<Fingerprint, ReprToken>& node_tokens); } #endif #include "arolla/expr/operator_repr_functions.h" #include <cstddef> #include <cstdint> #include <optional> #include <string> #include <utility> #include <vector> #include "absl/base/thread_annotations.h" #include "absl/container/flat_hash_map.h" #include "absl/log/check.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "absl/synchronization/mutex.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/registered_expr_operator.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/typed_value.h" #include "arolla/qtype/unspecified_qtype.h" #include "arolla/util/fingerprint.h" #include "arolla/util/indestructible.h" #include "arolla/util/repr.h" #include "arolla/util/string.h" #include "arolla/util/text.h" namespace arolla::expr { namespace { struct InfixOp { enum Kind : int8_t { kUnary, kBinary } kind; ReprToken::Precedence precedence; absl::string_view symbol; }; static const auto* const kUnaryInfixOps = new absl::flat_hash_map<absl::string_view, InfixOp>{ {"math.pos", {InfixOp::kUnary, {1, 1}, "+"}}, {"math.neg", {InfixOp::kUnary, {1, 1}, "-"}}, {"core.presence_not", {InfixOp::kUnary, {1, 1}, "~"}}, }; static const auto* const kBinaryInfixOps = new absl::flat_hash_map<absl::string_view, InfixOp>{ {"math.pow", {InfixOp::kBinary, {1, 2}, " ** "}}, {"math.multiply", {InfixOp::kBinary, {3, 2}, " * "}}, {"math.divide", {InfixOp::kBinary, {3, 2}, " / "}}, {"math.floordiv", {InfixOp::kBinary, {3, 2}, " {"math.mod", {InfixOp::kBinary, {3, 2}, " % "}}, {"math.add", {InfixOp::kBinary, {5, 4}, " + "}}, {"math.subtract", {InfixOp::kBinary, {5, 4}, " - "}}, {"core.presence_and", {InfixOp::kBinary, {7, 6}, " & "}}, {"core.presence_or", {InfixOp::kBinary, {9, 8}, " | "}}, {"core.less", {InfixOp::kBinary, {10, 10}, " < "}}, {"core.less_equal", {InfixOp::kBinary, {10, 10}, " <= "}}, {"core.equal", {InfixOp::kBinary, {10, 10}, " == "}}, {"core.not_equal", {InfixOp::kBinary, {10, 10}, " != "}}, {"core.greater_equal", {InfixOp::kBinary, {10, 10}, " >= "}}, {"core.greater", {InfixOp::kBinary, {10, 10}, " > "}}, }; std::vector<const ReprToken*> GetNodeDepsTokens( const ExprNodePtr& node, const absl::flat_hash_map<Fingerprint, ReprToken>& node_tokens) { std::vector<const ReprToken*> inputs(node->node_deps().size()); for (size_t i = 0; i < node->node_deps().size(); ++i) { inputs[i] = &node_tokens.at(node->node_deps()[i]->fingerprint()); } return inputs; } std::optional<ReprToken> UnaryReprFn( const ExprNodePtr& node, const absl::flat_hash_map<Fingerprint, ReprToken>& node_tokens) { auto it = kUnaryInfixOps->find(node->op()->display_name()); const auto inputs = GetNodeDepsTokens(node, node_tokens); if (it == kUnaryInfixOps->end() || inputs.size() != 1) { return std::nullopt; } const auto& infix_op = it->second; ReprToken result; if (inputs[0]->precedence.left < infix_op.precedence.right) { result.str = absl::StrCat(infix_op.symbol, inputs[0]->str); } else { result.str = absl::StrCat(infix_op.symbol, "(", inputs[0]->str, ")"); } result.precedence.left = infix_op.precedence.left; result.precedence.right = infix_op.precedence.right; return result; } std::optional<ReprToken> BinaryReprFn( const ExprNodePtr& node, const absl::flat_hash_map<Fingerprint, ReprToken>& node_tokens) { auto it = kBinaryInfixOps->find(node->op()->display_name()); const auto inputs = GetNodeDepsTokens(node, node_tokens); if (it == kBinaryInfixOps->end() || inputs.size() != 2) { return std::nullopt; } const auto& infix_op = it->second; ReprToken result; const bool left_precedence = (inputs[0]->precedence.right < infix_op.precedence.left); const bool right_precedence = (inputs[1]->precedence.left < infix_op.precedence.right); if (left_precedence && right_precedence) { result.str = absl::StrCat(inputs[0]->str, infix_op.symbol, inputs[1]->str); } else if (left_precedence && !right_precedence) { result.str = absl::StrCat(inputs[0]->str, infix_op.symbol, "(", inputs[1]->str, ")"); } else if (!left_precedence && right_precedence) { result.str = absl::StrCat("(", inputs[0]->str, ")", infix_op.symbol, inputs[1]->str); } else { result.str = absl::StrCat("(", inputs[0]->str, ")", infix_op.symbol, "(", inputs[1]->str, ")"); } result.precedence.left = infix_op.precedence.left; result.precedence.right = infix_op.precedence.right; return result; } std::optional<ReprToken> GetAttrReprFn( const ExprNodePtr& node, const absl::flat_hash_map<Fingerprint, ReprToken>& node_tokens) { DCHECK_EQ(node->op()->display_name(), "core.getattr"); constexpr ReprToken::Precedence kGetAttrPrecedence{0, -1}; const auto& node_deps = node->node_deps(); if (node_deps.size() != 2 || !node_deps[1]->is_literal()) { return std::nullopt; } const auto& attr = node_deps[1]->qvalue(); if (!attr.has_value() || attr->GetType() != GetQType<Text>() || !IsIdentifier(attr->UnsafeAs<Text>().view())) { return std::nullopt; } ReprToken result; const auto inputs = GetNodeDepsTokens(node, node_tokens); DCHECK_EQ(inputs.size(), 2); if (inputs[0]->precedence.right < kGetAttrPrecedence.left) { result.str = absl::StrCat(inputs[0]->str, ".", attr->UnsafeAs<Text>().view()); } else { result.str = absl::StrCat("(", inputs[0]->str, ").", attr->UnsafeAs<Text>().view()); } result.precedence = kGetAttrPrecedence; return result; } std::optional<std::string> MakeSliceRepr( const ExprNodePtr& node, const absl::flat_hash_map<Fingerprint, ReprToken>& node_tokens) { if (!IsRegisteredOperator(node->op()) || node->op()->display_name() != "core.make_slice") { return std::nullopt; } auto is_unspecified = [](const ExprNodePtr& node) { return node->is_literal() && node->qtype() == GetUnspecifiedQType(); }; constexpr ReprToken::Precedence kSlicePrecedence{11, 11}; const auto& node_deps = node->node_deps(); if (node_deps.size() != 3) { return std::nullopt; } std::string result; const auto inputs = GetNodeDepsTokens(node, node_tokens); DCHECK_EQ(inputs.size(), 3); if (is_unspecified(node_deps[0])) { result = ":"; } else if (inputs[0]->precedence.right < kSlicePrecedence.left) { result = absl::StrCat(inputs[0]->str, ":"); } else { result = absl::StrCat("(", inputs[0]->str, "):"); } if (!is_unspecified(node_deps[1])) { if (inputs[1]->precedence.left < kSlicePrecedence.right && (inputs[1]->precedence.right < kSlicePrecedence.left || is_unspecified(node_deps[2]))) { absl::StrAppend(&result, inputs[1]->str); } else { absl::StrAppend(&result, "(", inputs[1]->str, ")"); } } if (!is_unspecified(node_deps[2])) { if (inputs[2]->precedence.left < kSlicePrecedence.right) { absl::StrAppend(&result, ":", inputs[2]->str); } else { absl::StrAppend(&result, ":(", inputs[2]->str, ")"); } } return result; } std::optional<ReprToken> GetItemReprFn( const ExprNodePtr& node, const absl::flat_hash_map<Fingerprint, ReprToken>& node_tokens) { DCHECK_EQ(node->op()->display_name(), "core.getitem"); constexpr ReprToken::Precedence kGetItemPrecedence{0, -1}; if (node->node_deps().size() != 2) { return std::nullopt; } const auto& lhs = node_tokens.at(node->node_deps()[0]->fingerprint()); const auto maybe_slice = MakeSliceRepr(node->node_deps()[1], node_tokens); const std::string& rhs_str = maybe_slice ? *maybe_slice : node_tokens.at(node->node_deps()[1]->fingerprint()).str; ReprToken result; if (lhs.precedence.right < kGetItemPrecedence.left) { result.str = absl::StrCat(lhs.str, "[", rhs_str, "]"); } else { result.str = absl::StrCat("(", lhs.str, ")[", rhs_str, "]"); } result.precedence = kGetItemPrecedence; return result; } class OpReprRegistry { public: void Set(std::string key, OperatorReprFn op_repr_fn) ABSL_LOCKS_EXCLUDED(mutex_) { absl::MutexLock lock(&mutex_); registry_[std::move(key)] = std::move(op_repr_fn); } OperatorReprFn Get(absl::string_view key) const ABSL_LOCKS_EXCLUDED(mutex_) { absl::MutexLock lock(&mutex_); if (const auto it = registry_.find(key); it != registry_.end()) { return it->second; } return nullptr; } private: mutable absl::Mutex mutex_; absl::flat_hash_map<std::string, OperatorReprFn> registry_ ABSL_GUARDED_BY(mutex_); }; OpReprRegistry* GetOpReprRegistryForRegisteredOp() { static Indestructible<OpReprRegistry> result([](void* self) { new (self) OpReprRegistry; auto* registry = static_cast<OpReprRegistry*>(self); for (const auto& [key, _] : *kUnaryInfixOps) { registry->Set(std::string(key), UnaryReprFn); } for (const auto& [key, _] : *kBinaryInfixOps) { registry->Set(std::string(key), BinaryReprFn); } registry->Set("core.getattr", GetAttrReprFn); registry->Set("core.getitem", GetItemReprFn); }); return result.get(); } std::optional<ReprToken> RegisteredOperatorReprFn( const ExprNodePtr& expr_node, const absl::flat_hash_map<Fingerprint, ReprToken>& node_tokens) { DCHECK(expr_node->is_op() && IsRegisteredOperator(expr_node->op())); if (auto op_repr_fn = GetOpReprRegistryForRegisteredOp()->Get( expr_node->op()->display_name()); op_repr_fn != nullptr) { return op_repr_fn(expr_node, node_tokens); } return std::nullopt; } OpReprRegistry* GetOpReprRegistryForQValueSpecialization() { static Indestructible<OpReprRegistry> result([](void* self) { new (self) OpReprRegistry; auto* registry = static_cast<OpReprRegistry*>(self); registry->Set("::arolla::expr::RegisteredOperator", RegisteredOperatorReprFn); }); return result.get(); } } void RegisterOpReprFnByQValueSpecializationKey( std::string qvalue_specialization_key, OperatorReprFn op_repr_fn) { GetOpReprRegistryForQValueSpecialization()->Set( std::move(qvalue_specialization_key), std::move(op_repr_fn)); } void RegisterOpReprFnByByRegistrationName(std::string op_name, OperatorReprFn op_repr_fn) { GetOpReprRegistryForRegisteredOp()->Set(std::move(op_name), std::move(op_repr_fn)); } std::optional<ReprToken> FormatOperatorNodePretty( const ExprNodePtr& node, const absl::flat_hash_map<Fingerprint, ReprToken>& node_tokens) { if (auto op_repr_fn = GetOpReprRegistryForQValueSpecialization()->Get( node->op()->py_qvalue_specialization_key()); op_repr_fn != nullptr) { if (auto res = op_repr_fn(node, node_tokens)) { return std::move(*res); } } return std::nullopt; } }
#include "arolla/expr/operator_repr_functions.h" #include <memory> #include <optional> #include <string> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/container/flat_hash_map.h" #include "absl/strings/str_format.h" #include "absl/strings/string_view.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_attributes.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/expr/registered_expr_operator.h" #include "arolla/expr/testing/test_operators.h" #include "arolla/util/fingerprint.h" #include "arolla/util/init_arolla.h" #include "arolla/util/repr.h" #include "arolla/util/testing/repr_token_eq.h" namespace arolla::expr { namespace { using ::arolla::expr::testing::DummyOp; using ::arolla::testing::ReprTokenEq; using ::testing::Optional; class OperatorReprFunctionsTest : public ::testing::Test { protected: void SetUp() override { ASSERT_OK(InitArolla()); } }; std::optional<ReprToken> AddRepr( const ExprNodePtr& node, const absl::flat_hash_map<Fingerprint, ReprToken>& node_tokens) { const auto& x_token = node_tokens.at(node->node_deps()[0]->fingerprint()); const auto& y_token = node_tokens.at(node->node_deps()[1]->fingerprint()); return ReprToken{.str = absl::StrFormat("%s + %s", x_token.str, y_token.str), .precedence = ReprToken::kSafeForSubscription}; } std::optional<ReprToken> SubtractRepr( const ExprNodePtr& node, const absl::flat_hash_map<Fingerprint, ReprToken>& node_tokens) { const auto& x_token = node_tokens.at(node->node_deps()[0]->fingerprint()); const auto& y_token = node_tokens.at(node->node_deps()[1]->fingerprint()); return ReprToken{.str = absl::StrFormat("%s - %s", x_token.str, y_token.str), .precedence = ReprToken::kSafeForArithmetic}; } TEST_F(OperatorReprFunctionsTest, OpClass) { auto x = Leaf("x"); auto y = Leaf("y"); auto expr = ExprNode::UnsafeMakeOperatorNode( std::make_shared<DummyOp>("custom.add", ExprOperatorSignature({{"x"}, {"y"}})), {x, y}, ExprAttributes()); absl::flat_hash_map<Fingerprint, ReprToken> node_tokens = { {x->fingerprint(), ReprToken{.str = "L.x"}}, {y->fingerprint(), ReprToken{.str = "L.y"}}, }; absl::string_view specialization_key = expr->op()->py_qvalue_specialization_key(); { EXPECT_EQ(FormatOperatorNodePretty(expr, node_tokens), std::nullopt); } { RegisterOpReprFnByQValueSpecializationKey(std::string(specialization_key), AddRepr); EXPECT_THAT( FormatOperatorNodePretty(expr, node_tokens), Optional(ReprTokenEq("L.x + L.y", ReprToken::kSafeForSubscription))); } { RegisterOpReprFnByQValueSpecializationKey(std::string(specialization_key), SubtractRepr); EXPECT_THAT( FormatOperatorNodePretty(expr, node_tokens), Optional(ReprTokenEq("L.x - L.y", ReprToken::kSafeForArithmetic))); } } TEST_F(OperatorReprFunctionsTest, RegisteredOp) { auto x = Leaf("x"); auto y = Leaf("y"); auto expr = ExprNode::UnsafeMakeOperatorNode( std::make_shared<RegisteredOperator>("test.add"), {x, y}, ExprAttributes()); absl::flat_hash_map<Fingerprint, ReprToken> node_tokens = { {x->fingerprint(), ReprToken{.str = "L.x"}}, {y->fingerprint(), ReprToken{.str = "L.y"}}, }; { EXPECT_EQ(FormatOperatorNodePretty(expr, node_tokens), std::nullopt); } { RegisterOpReprFnByByRegistrationName("test.add", AddRepr); EXPECT_THAT( FormatOperatorNodePretty(expr, node_tokens), Optional(ReprTokenEq("L.x + L.y", ReprToken::kSafeForSubscription))); } { RegisterOpReprFnByByRegistrationName("test.add", SubtractRepr); EXPECT_THAT( FormatOperatorNodePretty(expr, node_tokens), Optional(ReprTokenEq("L.x - L.y", ReprToken::kSafeForArithmetic))); } } } }
2,425
#ifndef AROLLA_EXPR_TUPLE_EXPR_OPERATOR_H_ #define AROLLA_EXPR_TUPLE_EXPR_OPERATOR_H_ #include <cstdint> #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "arolla/expr/basic_expr_operator.h" #include "arolla/expr/expr_attributes.h" #include "arolla/expr/expr_operator.h" namespace arolla::expr { class MakeTupleOperator final : public BackendExprOperatorTag, public ExprOperatorWithFixedSignature { public: static ExprOperatorPtr Make(); MakeTupleOperator(); absl::StatusOr<ExprAttributes> InferAttributes( absl::Span<const ExprAttributes> inputs) const final; static ExprAttributes StaticInferAttributes( absl::Span<const ExprAttributes> inputs); }; class GetNthOperator final : public BuiltinExprOperatorTag, public ExprOperatorWithFixedSignature { public: static absl::StatusOr<ExprOperatorPtr> Make(int64_t index); explicit GetNthOperator(int64_t index); int64_t index() const { return index_; } absl::StatusOr<ExprAttributes> InferAttributes( absl::Span<const ExprAttributes> inputs) const final; absl::string_view py_qvalue_specialization_key() const final; static absl::StatusOr<ExprAttributes> StaticInferAttributes( int64_t index, const ExprAttributes& input); private: int64_t index_; }; } #endif #include "arolla/expr/tuple_expr_operator.h" #include <cstddef> #include <cstdint> #include <memory> #include <string> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "arolla/expr/basic_expr_operator.h" #include "arolla/expr/expr_attributes.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/expr/qtype_utils.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/tuple_qtype.h" #include "arolla/util/fingerprint.h" #include "arolla/util/indestructible.h" #include "arolla/util/status_macros_backport.h" namespace arolla::expr { ExprOperatorPtr MakeTupleOperator::Make() { static const Indestructible<ExprOperatorPtr> result( std::make_shared<MakeTupleOperator>()); return *result; } MakeTupleOperator::MakeTupleOperator() : ExprOperatorWithFixedSignature( "core.make_tuple", ExprOperatorSignature::MakeVariadicArgs(), "Returns a tuple constructed from the given arguments.", FingerprintHasher("::arolla::expr::MakeTupleOperator").Finish()) {} ExprAttributes MakeTupleOperator::StaticInferAttributes( absl::Span<const ExprAttributes> inputs) { if (!HasAllAttrQTypes(inputs)) { return ExprAttributes{}; } return ExprAttributes(MakeTupleQType(GetAttrQTypes(inputs))); } absl::StatusOr<ExprAttributes> MakeTupleOperator::InferAttributes( absl::Span<const ExprAttributes> inputs) const { RETURN_IF_ERROR(ValidateOpInputsCount(inputs)); return StaticInferAttributes(inputs); } absl::StatusOr<ExprOperatorPtr> GetNthOperator::Make(int64_t index) { if (index < 0) { return absl::InvalidArgumentError( absl::StrFormat("expected a non-negative index, got %d", index)); } return std::make_shared<GetNthOperator>(index); } namespace { std::string GetNthOperatorDocstring(int64_t index) { if (index == 0) { return "Returns the first field of a compound value."; } else if (index == 1) { return "Returns the second field of a compound value."; } else if (index == 2) { return "Returns the third field of a compound value."; } else { return absl::StrFormat("Returns the %dth field of a compound value.", index + 1); } } } GetNthOperator::GetNthOperator(int64_t index) : ExprOperatorWithFixedSignature( absl::StrFormat("get_nth[%d]", index), ExprOperatorSignature{{"value"}}, GetNthOperatorDocstring(index), FingerprintHasher("::arolla::expr::GetNthOperator") .Combine(index) .Finish()), index_(index) {} absl::StatusOr<ExprAttributes> GetNthOperator::StaticInferAttributes( int64_t index, const ExprAttributes& input) { if (!input.qtype()) { return ExprAttributes{}; } const auto& fields = input.qtype()->type_fields(); if (fields.empty() && !IsTupleQType(input.qtype())) { return absl::InvalidArgumentError(absl::StrFormat( "expected a compound type, got value: %s", input.qtype()->name())); } if (index < 0 || static_cast<size_t>(index) >= fields.size()) { return absl::InvalidArgumentError( absl::StrFormat("index out of range: n=%d, value.field_count=%d", index, fields.size())); } if (!input.qvalue()) { return ExprAttributes(fields[index].GetType()); } return ExprAttributes(input.qvalue()->GetField(index)); } absl::StatusOr<ExprAttributes> GetNthOperator::InferAttributes( absl::Span<const ExprAttributes> inputs) const { RETURN_IF_ERROR(ValidateOpInputsCount(inputs)); return StaticInferAttributes(index_, inputs[0]); } absl::string_view GetNthOperator::py_qvalue_specialization_key() const { return "::arolla::expr::GetNthOperator"; } }
#include "arolla/expr/tuple_expr_operator.h" #include <cstdint> #include <memory> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "arolla/expr/expr.h" #include "arolla/expr/testing/testing.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/tuple_qtype.h" #include "arolla/qtype/typed_value.h" #include "arolla/util/init_arolla.h" #include "arolla/util/testing/status_matchers_backport.h" namespace arolla::expr { namespace { using ::arolla::testing::InvokeExprOperator; using ::arolla::testing::IsOkAndHolds; class TupleExprOperatorTest : public ::testing::Test { void SetUp() override { ASSERT_OK(InitArolla()); } }; TEST_F(TupleExprOperatorTest, Basics) { ASSERT_OK_AND_ASSIGN(auto tuple, CallOp(MakeTupleOperator::Make(), {Literal<float>(2.f), Literal<int64_t>(3)})); ASSERT_OK_AND_ASSIGN(auto first, CallOp(std::make_shared<GetNthOperator>(0), {tuple})); ASSERT_OK_AND_ASSIGN(auto second, CallOp(std::make_shared<GetNthOperator>(1), {tuple})); EXPECT_EQ(first->qtype(), GetQType<float>()); EXPECT_EQ(second->qtype(), GetQType<int64_t>()); } TEST_F(TupleExprOperatorTest, InvokeMakeTuple) { ASSERT_OK_AND_ASSIGN( auto tuple, InvokeExprOperator<TypedValue>(MakeTupleOperator::Make(), 2.f, int64_t{3})); EXPECT_EQ(tuple.GetType(), MakeTupleQType({GetQType<float>(), GetQType<int64_t>()})); EXPECT_EQ(tuple.GetFieldCount(), 2); EXPECT_THAT(tuple.GetField(0).As<float>(), IsOkAndHolds(2.f)); EXPECT_THAT(tuple.GetField(1).As<int64_t>(), IsOkAndHolds(3)); } } }
2,426
#ifndef AROLLA_EXPR_LAMBDA_EXPR_OPERATOR_H_ #define AROLLA_EXPR_LAMBDA_EXPR_OPERATOR_H_ #include <cstddef> #include <memory> #include <vector> #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "arolla/expr/basic_expr_operator.h" #include "arolla/expr/expr_attributes.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/expr/expr_visitor.h" #include "arolla/util/fingerprint.h" #include "arolla/util/status.h" #include "arolla/util/status_macros_backport.h" namespace arolla::expr { class LambdaOperator final : public ExprOperatorWithFixedSignature { struct PrivateConstrutorTag {}; public: static absl::StatusOr<std::shared_ptr<LambdaOperator>> Make( ExprNodePtr lambda_body); static absl::StatusOr<std::shared_ptr<LambdaOperator>> Make( absl::string_view operator_name, ExprNodePtr lambda_body); static absl::StatusOr<std::shared_ptr<LambdaOperator>> Make( const ExprOperatorSignature& lambda_signature, ExprNodePtr lambda_body); static absl::StatusOr<std::shared_ptr<LambdaOperator>> Make( absl::string_view operator_name, const ExprOperatorSignature& lambda_signature, ExprNodePtr lambda_body); static absl::StatusOr<std::shared_ptr<LambdaOperator>> Make( absl::string_view operator_name, const ExprOperatorSignature& lambda_signature, ExprNodePtr lambda_body, absl::string_view doc); LambdaOperator(PrivateConstrutorTag, absl::string_view name, const ExprOperatorSignature& signature, PostOrder lambda_body_post_order, absl::string_view doc, Fingerprint fingerprint); const ExprNodePtr& lambda_body() const { return lambda_body_post_order_.nodes().back(); } absl::StatusOr<ExprAttributes> InferAttributes( absl::Span<const ExprAttributes> inputs) const final; absl::StatusOr<ExprNodePtr> ToLowerLevel(const ExprNodePtr& node) const final; absl::string_view py_qvalue_specialization_key() const final; private: PostOrder lambda_body_post_order_; std::vector<size_t> lambda_param_indices_; }; template <class... Args> absl::StatusOr<std::shared_ptr<LambdaOperator>> MakeLambdaOperator( Args&&... args) { RETURN_IF_ERROR(CheckInputStatus(args...)); return LambdaOperator::Make(UnStatus(std::forward<Args>(args))...); } absl::StatusOr<ExprNodePtr> SuppressUnusedWarning( absl::string_view unused_parameters, absl::StatusOr<ExprNodePtr> expr); } #endif #include "arolla/expr/lambda_expr_operator.h" #include <cstddef> #include <limits> #include <memory> #include <optional> #include <utility> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/container/flat_hash_set.h" #include "absl/log/check.h" #include "absl/log/log.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/match.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" #include "absl/strings/str_join.h" #include "absl/strings/str_split.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "arolla/expr/basic_expr_operator.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_attributes.h" #include "arolla/expr/expr_debug_string.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/expr/expr_visitor.h" #include "arolla/expr/qtype_utils.h" #include "arolla/expr/tuple_expr_operator.h" #include "arolla/util/fingerprint.h" #include "arolla/util/indestructible.h" #include "arolla/util/status_macros_backport.h" namespace arolla::expr { namespace { constexpr absl::string_view kDefaultLambdaOperatorName = "anonymous.lambda"; absl::Status ValidateLambdaBody(const PostOrder& lambda_body_post_order) { for (const auto& node : lambda_body_post_order.nodes()) { if (node->is_leaf()) { return absl::InvalidArgumentError( "leaf nodes are not permitted within the lambda body"); } } for (const auto& node : lambda_body_post_order.nodes()) { if (node->is_placeholder() && !node->node_deps().empty()) { return absl::InvalidArgumentError( "no placeholder nodes with dependencies permitted within the " "lambda " "body"); } } absl::flat_hash_set<absl::string_view> placeholder_keys; for (const auto& node : lambda_body_post_order.nodes()) { if (node->is_placeholder() && !placeholder_keys.emplace(node->placeholder_key()).second) { return absl::InternalError( "placeholder's key must unique identify the node"); } } return absl::OkStatus(); } } absl::StatusOr<std::shared_ptr<LambdaOperator>> LambdaOperator::Make( ExprNodePtr lambda_body) { return LambdaOperator::Make(kDefaultLambdaOperatorName, std::move(lambda_body)); } absl::StatusOr<std::shared_ptr<LambdaOperator>> LambdaOperator::Make( absl::string_view operator_name, ExprNodePtr lambda_body) { auto placeholders = GetPlaceholderKeys(lambda_body); if (placeholders.empty()) { return absl::InvalidArgumentError( "exactly one placeholder expected, but none were found"); } else if (placeholders.size() > 1) { return absl::InvalidArgumentError(absl::StrFormat( "exactly one placeholder expected, but %d are found: P.%s", placeholders.size(), absl::StrJoin(placeholders, ", P."))); } return LambdaOperator::Make(operator_name, ExprOperatorSignature{{placeholders[0]}}, std::move(lambda_body), ""); } absl::StatusOr<std::shared_ptr<LambdaOperator>> LambdaOperator::Make( const ExprOperatorSignature& lambda_signature, ExprNodePtr lambda_body) { return LambdaOperator::Make(kDefaultLambdaOperatorName, lambda_signature, std::move(lambda_body), ""); } absl::StatusOr<std::shared_ptr<LambdaOperator>> LambdaOperator::Make( absl::string_view operator_name, const ExprOperatorSignature& lambda_signature, ExprNodePtr lambda_body) { return LambdaOperator::Make(operator_name, lambda_signature, std::move(lambda_body), ""); } absl::StatusOr<std::shared_ptr<LambdaOperator>> LambdaOperator::Make( absl::string_view operator_name, const ExprOperatorSignature& lambda_signature, ExprNodePtr lambda_body, absl::string_view doc) { RETURN_IF_ERROR(ValidateSignature(lambda_signature)); auto lambda_body_post_order = PostOrder(lambda_body); RETURN_IF_ERROR(ValidateLambdaBody(lambda_body_post_order)); absl::flat_hash_map<absl::string_view, bool> lambda_param_used; for (const auto& param : lambda_signature.parameters) { lambda_param_used.emplace(param.name, false); } for (const auto& node : lambda_body_post_order.nodes()) { if (!node->is_placeholder()) { continue; } const auto it = lambda_param_used.find(node->placeholder_key()); if (it == lambda_param_used.end()) { return absl::InvalidArgumentError( absl::StrCat("P.", node->placeholder_key(), " is missing in the list of lambda parameters")); } it->second = true; } for (const auto& param : lambda_signature.parameters) { if (!(absl::StartsWith(param.name, "unused") || absl::StartsWith(param.name, "_")) && !lambda_param_used[param.name]) { LOG(WARNING) << "Unused lambda parameter: '" << param.name << "' in " << operator_name; } } auto fingerprint = FingerprintHasher("arolla::expr::LambdaOperator") .Combine(operator_name, lambda_signature, lambda_body->fingerprint(), doc) .Finish(); return std::make_shared<LambdaOperator>( PrivateConstrutorTag{}, operator_name, lambda_signature, std::move(lambda_body_post_order), doc, fingerprint); } LambdaOperator::LambdaOperator(PrivateConstrutorTag, absl::string_view name, const ExprOperatorSignature& signature, PostOrder lambda_body_post_order, absl::string_view doc, Fingerprint fingerprint) : ExprOperatorWithFixedSignature(name, signature, doc, fingerprint), lambda_body_post_order_(std::move(lambda_body_post_order)) { absl::flat_hash_map<absl::string_view, size_t> sig_param_indices; sig_param_indices.reserve(signature.parameters.size()); for (size_t i = 0; i < signature.parameters.size(); ++i) { sig_param_indices[signature.parameters[i].name] = i; } lambda_param_indices_.resize(signature.parameters.size(), std::numeric_limits<size_t>::max()); for (size_t i = 0; i < lambda_body_post_order_.nodes_size(); ++i) { const auto& node = lambda_body_post_order_.node(i); if (node->is_placeholder()) { lambda_param_indices_[sig_param_indices.at(node->placeholder_key())] = i; } } } namespace { absl::StatusOr<ExprNodePtr> WrapAsTuple(absl::Span<const ExprNodePtr> fields) { return MakeOpNode(MakeTupleOperator::Make(), std::vector<ExprNodePtr>(fields.begin(), fields.end())); } ExprAttributes WrapAsTuple(absl::Span<const ExprAttributes> field_attrs) { return MakeTupleOperator::StaticInferAttributes(field_attrs); } } absl::StatusOr<ExprNodePtr> LambdaOperator::ToLowerLevel( const ExprNodePtr& node) const { RETURN_IF_ERROR(ValidateNodeDepsCount(*node)); std::vector<ExprNodePtr> result(lambda_body_post_order_.nodes_size()); if (!lambda_param_indices_.empty()) { const auto inputs = absl::MakeConstSpan(node->node_deps()); for (size_t i = 0; i + 1 < lambda_param_indices_.size(); ++i) { if (lambda_param_indices_[i] != std::numeric_limits<size_t>::max()) { result[lambda_param_indices_[i]] = inputs[i]; } } if (lambda_param_indices_.back() != std::numeric_limits<size_t>::max()) { if (HasVariadicParameter(signature())) { ASSIGN_OR_RETURN( result[lambda_param_indices_.back()], WrapAsTuple(inputs.subspan(lambda_param_indices_.size() - 1))); } else { result[lambda_param_indices_.back()] = inputs.back(); } } } for (size_t i = 0; i < lambda_body_post_order_.nodes_size(); ++i) { const auto& original_node = lambda_body_post_order_.node(i); if (original_node->is_placeholder()) { continue; } if (original_node->is_literal()) { result[i] = original_node; continue; } DCHECK(original_node->is_op()); const auto& dep_indices = lambda_body_post_order_.dep_indices(i); std::vector<ExprNodePtr> deps(dep_indices.size()); for (size_t j = 0; j < dep_indices.size(); ++j) { deps[j] = result[dep_indices[j]]; } if (i + 1 < lambda_body_post_order_.nodes_size() || node->attr().IsEmpty()) { ASSIGN_OR_RETURN(result[i], WithNewDependencies(original_node, std::move(deps))); } else { #ifndef NDEBUG auto attr = original_node->op()->InferAttributes(GetExprAttrs(deps)); DCHECK(attr.ok() && attr->IsIdenticalTo(node->attr())); #endif result[i] = ExprNode::UnsafeMakeOperatorNode( ExprOperatorPtr(original_node->op()), std::move(deps), ExprAttributes(node->attr())); } } return result.back(); } absl::StatusOr<ExprAttributes> LambdaOperator::InferAttributes( absl::Span<const ExprAttributes> inputs) const { RETURN_IF_ERROR(ValidateOpInputsCount(inputs)); std::vector<ExprAttributes> results(lambda_body_post_order_.nodes_size()); if (!lambda_param_indices_.empty()) { for (size_t i = 0; i + 1 < lambda_param_indices_.size(); ++i) { if (lambda_param_indices_[i] != std::numeric_limits<size_t>::max()) { results[lambda_param_indices_[i]] = inputs[i]; } } if (lambda_param_indices_.back() != std::numeric_limits<size_t>::max()) { if (HasVariadicParameter(signature())) { results[lambda_param_indices_.back()] = WrapAsTuple(inputs.subspan(lambda_param_indices_.size() - 1)); } else { results[lambda_param_indices_.back()] = inputs.back(); } } } std::vector<ExprAttributes> deps; for (size_t i = 0; i < lambda_body_post_order_.nodes_size(); ++i) { const auto& original_node = lambda_body_post_order_.node(i); if (original_node->is_placeholder()) { continue; } if (const auto& attr = original_node->attr(); attr.qvalue().has_value()) { results[i] = attr; continue; } DCHECK(original_node->is_op()); const auto& dep_indices = lambda_body_post_order_.dep_indices(i); deps.resize(dep_indices.size()); for (size_t j = 0; j < dep_indices.size(); ++j) { deps[j] = results[dep_indices[j]]; } ASSIGN_OR_RETURN(results[i], original_node->op()->InferAttributes(deps), _ << "while deducing output type for " << GetDebugSnippet(original_node)); } return results.back(); } absl::string_view LambdaOperator::py_qvalue_specialization_key() const { return "::arolla::expr::LambdaOperator"; } namespace { absl::StatusOr<ExprOperatorPtr> IgnoreUnusedParametersOp() { static const Indestructible<absl::StatusOr<ExprOperatorPtr>> result( MakeLambdaOperator("ignore_unused_parameters", ExprOperatorSignature::Make("expr, *unused"), Placeholder("expr"))); return *result; } } absl::StatusOr<ExprNodePtr> SuppressUnusedWarning( absl::string_view unused_parameters, absl::StatusOr<ExprNodePtr> expr) { std::vector<absl::string_view> unused_parameter_names = absl::StrSplit( unused_parameters, absl::ByAnyChar(", "), absl::SkipEmpty()); std::vector<absl::StatusOr<ExprNodePtr>> args; args.reserve(1 + unused_parameter_names.size()); args.push_back(std::move(expr)); for (absl::string_view name : unused_parameter_names) { args.push_back(Placeholder(name)); } return CallOp(IgnoreUnusedParametersOp(), std::move(args)); } }
#include "arolla/expr/lambda_expr_operator.h" #include <cstdint> #include <memory> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "arolla/expr/annotation_expr_operators.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_attributes.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/expr/testing/testing.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/tuple_qtype.h" #include "arolla/qtype/typed_ref.h" #include "arolla/qtype/typed_value.h" #include "arolla/util/bytes.h" #include "arolla/util/init_arolla.h" #include "arolla/util/testing/status_matchers_backport.h" #include "arolla/util/unit.h" namespace arolla::expr { namespace { using ::arolla::testing::EqualsAttr; using ::arolla::testing::EqualsExpr; using ::arolla::testing::InvokeExprOperator; using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::StatusIs; using ::arolla::testing::WithQTypeAnnotation; using ::testing::ElementsAre; using ::testing::HasSubstr; using Attr = ExprAttributes; class LambdaOperatorTest : public ::testing::Test { void SetUp() override { ASSERT_OK(InitArolla()); } }; TEST_F(LambdaOperatorTest, NoParameters) { auto foobar = Literal<int32_t>(0xf00baa); ASSERT_OK_AND_ASSIGN( const auto lambda_op, LambdaOperator::Make("foo.bar", ExprOperatorSignature{}, foobar)); EXPECT_EQ(lambda_op->display_name(), "foo.bar"); { EXPECT_THAT(CallOp(lambda_op, {Leaf("x")}), StatusIs(absl::StatusCode::kInvalidArgument)); } ASSERT_OK_AND_ASSIGN(const auto folded_expr, CallOp(lambda_op, {})); ASSERT_OK_AND_ASSIGN(const auto expected_folded_expr, MakeOpNode(lambda_op, {})); EXPECT_THAT(folded_expr, EqualsExpr(expected_folded_expr)); ASSERT_OK_AND_ASSIGN(const auto unfolded_expr, ToLowerNode(folded_expr)); EXPECT_THAT(unfolded_expr, EqualsExpr(foobar)); EXPECT_EQ(lambda_op->doc(), ""); EXPECT_THAT(lambda_op->GetDoc(), IsOkAndHolds("")); } TEST_F(LambdaOperatorTest, SingleArgument) { auto f1 = Literal<float>(1.0); auto p0 = Placeholder("p0"); auto p1 = Placeholder("p1"); { EXPECT_THAT(LambdaOperator::Make(f1), StatusIs(absl::StatusCode::kInvalidArgument)); } { ASSERT_OK_AND_ASSIGN(auto lambda_body, CallOp("math.add", {p0, p1})); EXPECT_THAT(LambdaOperator::Make(lambda_body), StatusIs(absl::StatusCode::kInvalidArgument)); } { ASSERT_OK_AND_ASSIGN(auto lambda_body, CallOp("math.add", {p0, f1})); ASSERT_OK_AND_ASSIGN(auto lambda_op, LambdaOperator::Make(lambda_body)); ASSERT_OK_AND_ASSIGN( const auto expected_lambda_op, LambdaOperator::Make(ExprOperatorSignature{{"p0"}}, lambda_body)); EXPECT_EQ(lambda_op->fingerprint(), expected_lambda_op->fingerprint()); } { ASSERT_OK_AND_ASSIGN(auto lambda_body, CallOp("math.add", {p0, f1})); ASSERT_OK_AND_ASSIGN(auto lambda_op, LambdaOperator::Make("op.name", lambda_body)); ASSERT_OK_AND_ASSIGN( const auto expected_lambda_op, LambdaOperator::Make("op.name", ExprOperatorSignature{{"p0"}}, lambda_body)); EXPECT_EQ(lambda_op->fingerprint(), expected_lambda_op->fingerprint()); EXPECT_EQ(lambda_op->display_name(), "op.name"); } } TEST_F(LambdaOperatorTest, General) { auto x = Leaf("x"); auto y = Leaf("y"); auto u = Literal(kUnit); auto p0 = Placeholder("p0"); auto p1 = Placeholder("p1"); ASSERT_OK_AND_ASSIGN(auto lambda_signature, ExprOperatorSignature::Make("p0, p1=", kUnit)); ASSERT_OK_AND_ASSIGN(auto lambda_body, CallOp("math.add", {p0, p1})); ASSERT_OK_AND_ASSIGN(auto lambda_op, LambdaOperator::Make(lambda_signature, lambda_body)); EXPECT_EQ(lambda_op->display_name(), "anonymous.lambda"); EXPECT_THAT(lambda_op->lambda_body(), EqualsExpr(lambda_body)); { EXPECT_THAT(CallOp(lambda_op, {}), StatusIs(absl::StatusCode::kInvalidArgument)); } { EXPECT_THAT(CallOp(lambda_op, {x, x, x}), StatusIs(absl::StatusCode::kInvalidArgument)); } { ASSERT_OK_AND_ASSIGN(auto folded_expr, CallOp(lambda_op, {x})); ASSERT_OK_AND_ASSIGN(auto expected_folded_expr, MakeOpNode(lambda_op, {x, u})); EXPECT_THAT(folded_expr, EqualsExpr(expected_folded_expr)); ASSERT_OK_AND_ASSIGN(auto unfolded_expr, ToLowerNode(folded_expr)); ASSERT_OK_AND_ASSIGN(auto expected_unfolded_expr, CallOp("math.add", {x, u})); EXPECT_THAT(unfolded_expr, EqualsExpr(expected_unfolded_expr)); } { ASSERT_OK_AND_ASSIGN(auto folded_expr, CallOp(lambda_op, {x, y})); ASSERT_OK_AND_ASSIGN(auto expected_folded_expr, MakeOpNode(lambda_op, {x, y})); EXPECT_THAT(folded_expr, EqualsExpr(expected_folded_expr)); ASSERT_OK_AND_ASSIGN(auto unfolded_expr, ToLowerNode(folded_expr)); ASSERT_OK_AND_ASSIGN(auto expected_unfolded_expr, CallOp("math.add", {x, y})); EXPECT_THAT(unfolded_expr, EqualsExpr(expected_unfolded_expr)); } } TEST_F(LambdaOperatorTest, MakeLambdaOperator) { ASSERT_OK_AND_ASSIGN( auto lambda_op, MakeLambdaOperator( ExprOperatorSignature::Make("x, y"), CallOp("math.add", {Placeholder("x"), Placeholder("y")}))); EXPECT_EQ(lambda_op->display_name(), "anonymous.lambda"); EXPECT_THAT( MakeLambdaOperator( absl::StatusOr<ExprOperatorSignature>( absl::FailedPreconditionError("~~~")), CallOp("math.add", {Placeholder("x"), Placeholder("y")})), StatusIs(absl::StatusCode::kFailedPrecondition, HasSubstr("~~~"))); } TEST_F(LambdaOperatorTest, QTypePropagation) { ASSERT_OK_AND_ASSIGN(auto lambda_signature, ExprOperatorSignature::Make("x, y")); ASSERT_OK_AND_ASSIGN( auto lambda_body, CallOp("math.add", {Placeholder("x"), Placeholder("y")})); ASSERT_OK_AND_ASSIGN(lambda_body, CallOp("math.add", {lambda_body, Placeholder("y")})); ASSERT_OK_AND_ASSIGN( auto lambda_op, LambdaOperator::Make("test.lambda", lambda_signature, lambda_body)); ASSERT_OK_AND_ASSIGN( const auto called_lambda, CallOp(lambda_op, {Literal<int64_t>(57), Literal<int64_t>(57)})); EXPECT_THAT(called_lambda->qtype(), GetQType<int64_t>()); EXPECT_THAT( CallOp(lambda_op, {Literal(Bytes{""}), Literal<int64_t>(57)}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr( "while deducing output type for M.math.add(P.x, P.y); while " "calling test.lambda with args {b'', int64{57}}"))); } TEST_F(LambdaOperatorTest, QValuePropagation) { ASSERT_OK_AND_ASSIGN(auto op, MakeLambdaOperator("test.lambda", Placeholder("x"))); ASSERT_OK_AND_ASSIGN(auto expr, CallOp(op, {Literal(1)})); EXPECT_THAT(expr->attr(), EqualsAttr(TypedRef::FromValue(1))); } TEST_F(LambdaOperatorTest, BadLambdaBody) { const ExprOperatorSignature lambda_signature{{"p"}}; EXPECT_OK(LambdaOperator::Make(lambda_signature, Placeholder("p"))); EXPECT_THAT( LambdaOperator::Make(lambda_signature, Placeholder("missing_parameter")), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT(LambdaOperator::Make(lambda_signature, Leaf("p")), StatusIs(absl::StatusCode::kInvalidArgument)); } TEST_F(LambdaOperatorTest, VariadicArg) { ASSERT_OK_AND_ASSIGN( auto head_op, MakeLambdaOperator(ExprOperatorSignature::Make("head, *_tail"), Placeholder("head"))); ASSERT_OK_AND_ASSIGN( auto tail_op, MakeLambdaOperator(ExprOperatorSignature::Make("_head, *tail"), Placeholder("tail"))); ASSERT_OK_AND_ASSIGN(auto h, InvokeExprOperator<TypedValue>(head_op, 0.f, 1.f, 2.f)); ASSERT_OK_AND_ASSIGN(auto t, InvokeExprOperator<TypedValue>(tail_op, 0.f, 1.f, 2.f)); EXPECT_THAT(h.As<float>(), IsOkAndHolds(0.f)); EXPECT_EQ(t.GetType(), MakeTupleQType({GetQType<float>(), GetQType<float>()})); EXPECT_EQ(t.GetFieldCount(), 2); EXPECT_THAT(t.GetField(0).As<float>(), IsOkAndHolds(1.f)); EXPECT_THAT(t.GetField(1).As<float>(), IsOkAndHolds(2.f)); EXPECT_THAT( head_op->InferAttributes( {Attr(GetQType<float>()), Attr(TypedValue::FromValue(1.f)), Attr{}}), IsOkAndHolds(EqualsAttr(GetQType<float>()))); EXPECT_THAT( tail_op->InferAttributes( {Attr(GetQType<float>()), Attr(TypedValue::FromValue(1.f)), Attr{}}), IsOkAndHolds(EqualsAttr(nullptr))); } TEST_F(LambdaOperatorTest, VariadicArgInferAttributes) { ASSERT_OK_AND_ASSIGN(auto op, MakeLambdaOperator(ExprOperatorSignature::Make("*args"), Placeholder("args"))); { ASSERT_OK_AND_ASSIGN(auto expr, CallOp(op, {})); ASSERT_OK_AND_ASSIGN(auto lowered_expr, ToLowest(expr)); ASSERT_THAT(expr->attr(), EqualsAttr(lowered_expr->attr())); } { auto v0 = Placeholder("x"); ASSERT_OK_AND_ASSIGN( auto v1, WithQTypeAnnotation(Placeholder("x"), GetQType<int>())); auto v2 = Literal(1.5f); for (const auto& a0 : {v0, v1, v2}) { for (const auto& a1 : {v0, v1, v2}) { ASSERT_OK_AND_ASSIGN(auto expr, CallOp(op, {a0, a1})); ASSERT_OK_AND_ASSIGN(auto lowered_expr, ToLowest(expr)); ASSERT_THAT(expr->attr(), EqualsAttr(lowered_expr->attr())); } } } } TEST_F(LambdaOperatorTest, OutputQTypeRequiresLiteral) { { ASSERT_OK_AND_ASSIGN(auto lambda_signature, ExprOperatorSignature::Make("x, y")); ASSERT_OK_AND_ASSIGN( auto lambda_body, CallOp(QTypeAnnotation::Make(), {Placeholder("x"), Placeholder("y")})); ASSERT_OK_AND_ASSIGN(auto lambda_op, LambdaOperator::Make(lambda_signature, lambda_body)); ASSERT_OK_AND_ASSIGN( const auto called_lambda, CallOp(lambda_op, {Leaf("a"), Literal<QTypePtr>(GetQType<int64_t>())})); EXPECT_EQ(called_lambda->qtype(), GetQType<int64_t>()); } { ASSERT_OK_AND_ASSIGN(auto lambda_signature, ExprOperatorSignature::Make("x")); ASSERT_OK_AND_ASSIGN( auto lambda_body, WithQTypeAnnotation(Placeholder("x"), GetQType<int64_t>())); ASSERT_OK_AND_ASSIGN(auto lambda_op, LambdaOperator::Make(lambda_signature, lambda_body)); EXPECT_THAT(lambda_op->InferAttributes({Attr{}}), IsOkAndHolds(EqualsAttr(GetQType<int64_t>()))); } } TEST_F(LambdaOperatorTest, GetDoc) { auto lambda_body = Placeholder("x"); ASSERT_OK_AND_ASSIGN( auto op, LambdaOperator::Make("lambda_op_with_docstring", ExprOperatorSignature{{"x"}}, lambda_body, "doc-string")); ASSERT_EQ(op->doc(), "doc-string"); ASSERT_THAT(op->GetDoc(), IsOkAndHolds("doc-string")); } TEST_F(LambdaOperatorTest, SuppressUnusedWarning) { { ASSERT_OK_AND_ASSIGN( auto expr, CallOp("math.add", {Placeholder("x"), Placeholder("y")})); ASSERT_OK_AND_ASSIGN(auto wrapped_expr, SuppressUnusedWarning("", expr)); EXPECT_THAT(GetPlaceholderKeys(wrapped_expr), ElementsAre("x", "y")); EXPECT_THAT(ToLowerNode(wrapped_expr), IsOkAndHolds(EqualsExpr(expr))); } { ASSERT_OK_AND_ASSIGN( auto expr, CallOp("math.add", {Placeholder("x"), Placeholder("y")})); ASSERT_OK_AND_ASSIGN(auto wrapped_expr, SuppressUnusedWarning("a, b, c", expr)); EXPECT_THAT(GetPlaceholderKeys(wrapped_expr), ElementsAre("a", "b", "c", "x", "y")); EXPECT_THAT(ToLowest(wrapped_expr), IsOkAndHolds(EqualsExpr(expr))); } } } }
2,427
#ifndef AROLLA_EXPR_OVERLOADED_EXPR_OPERATOR_H_ #define AROLLA_EXPR_OVERLOADED_EXPR_OPERATOR_H_ #include <memory> #include <string> #include <tuple> #include <utility> #include <vector> #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "arolla/expr/expr_attributes.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/util/status.h" #include "arolla/util/status_macros_backport.h" namespace arolla::expr { class OverloadedOperator final : public ExprOperator { public: OverloadedOperator(absl::string_view name, std::vector<ExprOperatorPtr> base_ops); absl::StatusOr<ExprOperatorSignature> GetSignature() const final; absl::StatusOr<std::string> GetDoc() const final; absl::Span<const ExprOperatorPtr> base_ops() const; absl::StatusOr<ExprOperatorPtr> LookupOp( absl::Span<const ExprAttributes> inputs) const; absl::StatusOr<ExprAttributes> InferAttributes( absl::Span<const ExprAttributes> inputs) const final; absl::StatusOr<ExprNodePtr> ToLowerLevel(const ExprNodePtr& node) const final; absl::string_view py_qvalue_specialization_key() const final; private: absl::StatusOr<std::tuple<ExprOperatorPtr, ExprAttributes>> LookupImpl( absl::Span<const ExprAttributes> inputs) const; std::vector<ExprOperatorPtr> base_ops_; }; template <class... Args> absl::StatusOr<ExprOperatorPtr> MakeOverloadedOperator(absl::string_view name, Args&&... args) { RETURN_IF_ERROR(CheckInputStatus(args...)); std::vector<ExprOperatorPtr> base_ops( {UnStatus(std::forward<Args>(args))...}); return std::make_shared<OverloadedOperator>(name, std::move(base_ops)); } } #endif #include "arolla/expr/overloaded_expr_operator.h" #include <string> #include <tuple> #include <utility> #include <vector> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "absl/strings/str_replace.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "arolla/expr/expr_attributes.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/expr/qtype_utils.h" #include "arolla/qtype/qtype.h" #include "arolla/util/fingerprint.h" namespace arolla::expr { OverloadedOperator::OverloadedOperator(absl::string_view name, std::vector<ExprOperatorPtr> base_ops) : ExprOperator( name, [name, &base_ops] { FingerprintHasher hasher("arolla::expr::OverloadedOperator"); hasher.Combine(name, base_ops.size()); for (const auto& base_op : base_ops) { hasher.Combine(base_op->fingerprint()); } return std::move(hasher).Finish(); }()), base_ops_(std::move(base_ops)) {} absl::StatusOr<ExprOperatorSignature> OverloadedOperator::GetSignature() const { if (base_ops_.empty()) { return absl::InvalidArgumentError("no base operators"); } return base_ops_.front()->GetSignature(); } absl::StatusOr<std::string> OverloadedOperator::GetDoc() const { if (base_ops_.empty()) { return absl::InvalidArgumentError("no base operators"); } return base_ops_.front()->GetDoc(); } absl::Span<const ExprOperatorPtr> OverloadedOperator::base_ops() const { return base_ops_; } absl::StatusOr<ExprOperatorPtr> OverloadedOperator::LookupOp( absl::Span<const ExprAttributes> inputs) const { auto lookup_result = LookupImpl(inputs); if (!lookup_result.ok()) { return std::move(lookup_result).status(); } return std::get<ExprOperatorPtr>(*lookup_result); } absl::StatusOr<ExprAttributes> OverloadedOperator::InferAttributes( absl::Span<const ExprAttributes> inputs) const { auto lookup_result = LookupImpl(inputs); if (!lookup_result.ok()) { return std::move(lookup_result).status(); } return std::get<ExprAttributes>(*lookup_result); } absl::StatusOr<ExprNodePtr> OverloadedOperator::ToLowerLevel( const ExprNodePtr& node) const { auto lookup_result = LookupImpl(GetExprAttrs(node->node_deps())); if (!lookup_result.ok()) { return std::move(lookup_result).status(); } auto& op = std::get<ExprOperatorPtr>(*lookup_result); auto& attr = std::get<ExprAttributes>(*lookup_result); if (op == nullptr) { return node; } return ExprNode::UnsafeMakeOperatorNode( std::move(op), std::vector(node->node_deps()), std::move(attr)); } absl::StatusOr<std::tuple<ExprOperatorPtr, ExprAttributes>> OverloadedOperator::LookupImpl(absl::Span<const ExprAttributes> inputs) const { for (const auto& base_op : base_ops_) { auto status_or = base_op->InferAttributes(inputs); if (absl::IsInvalidArgument(status_or.status())) { continue; } if (!status_or.ok()) { return status_or.status(); } if (!status_or->qtype()) { return std::make_tuple(ExprOperatorPtr{}, ExprAttributes{}); } return std::make_tuple(base_op, *std::move(status_or)); } if (inputs.size() == 1) { return absl::InvalidArgumentError( absl::StrFormat("unsupported argument type %s", inputs[0].qtype() ? inputs[0].qtype()->name() : "*")); } return absl::InvalidArgumentError( absl::StrFormat("unsupported argument types (%s)", absl::StrReplaceAll(JoinTypeNames(GetAttrQTypes(inputs)), {{"NULL", "*"}}))); } absl::string_view OverloadedOperator::py_qvalue_specialization_key() const { return "::arolla::expr::OverloadedOperator"; } }
#include "arolla/expr/overloaded_expr_operator.h" #include <cstdint> #include <memory> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "arolla/expr/annotation_expr_operators.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_attributes.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/expr/lambda_expr_operator.h" #include "arolla/expr/registered_expr_operator.h" #include "arolla/expr/testing/test_operators.h" #include "arolla/expr/testing/testing.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/typed_value.h" #include "arolla/util/bytes.h" #include "arolla/util/init_arolla.h" #include "arolla/util/testing/status_matchers_backport.h" namespace arolla::expr { namespace { using ::arolla::expr::testing::DummyOp; using ::arolla::testing::EqualsAttr; using ::arolla::testing::EqualsExpr; using ::arolla::testing::InvokeExprOperator; using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::StatusIs; using ::testing::HasSubstr; using Attr = ExprAttributes; class OverloadedOperatorTest : public ::testing::Test { void SetUp() override { ASSERT_OK(InitArolla()); } }; TEST_F(OverloadedOperatorTest, SmokeTest) { ASSERT_OK_AND_ASSIGN( auto double_op, MakeOverloadedOperator( "Double", MakeLambdaOperator( CallOp("math.add", {Placeholder("x"), Placeholder("x")})), MakeLambdaOperator( CallOp("strings.join", {Placeholder("x"), Placeholder("x")})))); EXPECT_THAT(InvokeExprOperator<int>(double_op, 1), IsOkAndHolds(2)); EXPECT_THAT(InvokeExprOperator<double>(double_op, 1.5), IsOkAndHolds(3.)); EXPECT_THAT(InvokeExprOperator<Bytes>(double_op, Bytes("abc")), IsOkAndHolds(Bytes("abcabc"))); EXPECT_THAT(double_op->InferAttributes({Attr(GetQType<bool>())}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("unsupported argument type BOOLEAN"))); EXPECT_THAT(double_op->InferAttributes( {Attr(GetQType<int32_t>()), Attr(GetQType<int64_t>())}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("unsupported argument types (INT32,INT64)"))); } TEST_F(OverloadedOperatorTest, UsingLiteralValues) { ASSERT_OK_AND_ASSIGN(auto lambda_signature, ExprOperatorSignature::Make("x, y")); ASSERT_OK_AND_ASSIGN( auto with_qtype_op, MakeOverloadedOperator( "WithQType", MakeLambdaOperator(lambda_signature, CallOp(QTypeAnnotation::Make(), {Placeholder("x"), Placeholder("y")})), MakeLambdaOperator( lambda_signature, CallOp("strings.join", {Placeholder("x"), Placeholder("y")})))); EXPECT_THAT(with_qtype_op->InferAttributes( {Attr{}, Attr(TypedValue::FromValue(GetQType<int32_t>()))}), IsOkAndHolds(EqualsAttr(GetQType<int>()))); EXPECT_THAT(with_qtype_op->InferAttributes( {Attr(GetQType<Bytes>()), Attr(GetQType<Bytes>())}), IsOkAndHolds(EqualsAttr(GetQType<Bytes>()))); EXPECT_THAT(with_qtype_op->InferAttributes({Attr{}, Attr{}}), IsOkAndHolds(EqualsAttr(nullptr))); EXPECT_THAT( with_qtype_op->InferAttributes({Attr(GetQType<Bytes>()), Attr{}, Attr{}}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("unsupported argument types (BYTES,*,*)"))); } TEST_F(OverloadedOperatorTest, GetDoc) { auto op_1 = std::make_shared<testing::DummyOp>( "dummy_op_1", ExprOperatorSignature::MakeVariadicArgs(), "dummy_docstring_1"); auto op_2 = std::make_shared<testing::DummyOp>( "dummy_op_2", ExprOperatorSignature::MakeVariadicArgs(), "dummy_docstring_2"); OverloadedOperator op("overloaded_op", {op_1, op_2}); ASSERT_THAT(op.GetDoc(), IsOkAndHolds("dummy_docstring_1")); } TEST_F(OverloadedOperatorTest, Empty) { OverloadedOperator op("empty", {}); ASSERT_THAT(op.GetSignature(), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("no base operators"))); ASSERT_THAT(op.GetDoc(), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("no base operators"))); } TEST_F(OverloadedOperatorTest, ResolutionOrder) { ASSERT_OK_AND_ASSIGN( auto op, MakeOverloadedOperator( "dispatch", LookupOperator("core.identity"), MakeLambdaOperator(ExprOperatorSignature::Make("_"), Literal(1)))); ASSERT_OK_AND_ASSIGN(auto expr, CallOp(op, {Placeholder("x")})); EXPECT_EQ(expr->qtype(), nullptr); } TEST_F(OverloadedOperatorTest, Lowering) { ASSERT_OK_AND_ASSIGN(auto double_add_op, MakeLambdaOperator(CallOp( "math.add", {Placeholder("x"), Placeholder("x")}))); ASSERT_OK_AND_ASSIGN( auto double_op, MakeOverloadedOperator( "Double", double_add_op, MakeLambdaOperator( CallOp("strings.join", {Placeholder("x"), Placeholder("x")})))); ASSERT_OK_AND_ASSIGN(auto expr, CallOp(double_op, {Literal(1.0)})); EXPECT_THAT(ToLowerNode(expr), IsOkAndHolds(EqualsExpr(CallOp(double_add_op, {Literal(1.0)})))); } } }
2,428
#ifndef AROLLA_EXPR_EXPR_ATTRIBUTES_H_ #define AROLLA_EXPR_EXPR_ATTRIBUTES_H_ #include <iosfwd> #include <optional> #include <ostream> #include <utility> #include "absl/log/check.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/typed_ref.h" #include "arolla/qtype/typed_value.h" #include "arolla/util/fingerprint.h" namespace arolla::expr { class ExprAttributes { public: ExprAttributes() noexcept = default; ExprAttributes(ExprAttributes&&) noexcept = default; ExprAttributes& operator=(ExprAttributes&&) noexcept = default; ExprAttributes(const ExprAttributes&) noexcept = default; ExprAttributes& operator=(const ExprAttributes&) noexcept = default; explicit ExprAttributes(const QType* qtype) : qtype_(qtype) {} explicit ExprAttributes(TypedRef qvalue) : qtype_(qvalue.GetType()), qvalue_(qvalue) {} explicit ExprAttributes(TypedValue&& qvalue) : qtype_(qvalue.GetType()), qvalue_(std::move(qvalue)) {} explicit ExprAttributes(const TypedValue& qvalue) : qtype_(qvalue.GetType()), qvalue_(qvalue) {} ExprAttributes(QTypePtr qtype, TypedValue&& qvalue) : qtype_(qtype), qvalue_(std::move(qvalue)) { DCHECK_EQ(qtype_, qvalue_->GetType()); } ExprAttributes(QTypePtr qtype, const TypedValue& qvalue) : qtype_(qtype), qvalue_(qvalue) { DCHECK_EQ(qtype_, qvalue_->GetType()); } ExprAttributes(const QType* qtype, std::optional<TypedValue>&& qvalue) : qtype_(qtype), qvalue_(std::move(qvalue)) { if (qvalue_.has_value()) { DCHECK_EQ(qtype_, qvalue_->GetType()); } } ExprAttributes(const QType* qtype, const std::optional<TypedValue>& qvalue) : qtype_(qtype), qvalue_(qvalue) { if (qvalue_.has_value()) { DCHECK_EQ(qtype_, qvalue_->GetType()); } } const QType* qtype() const { return qtype_; } const std::optional<TypedValue>& qvalue() const { return qvalue_; } bool IsEmpty() const { return qtype_ == nullptr; } bool IsIdenticalTo(const ExprAttributes& other) const { if (qtype_ != other.qtype_) { return false; } if (qvalue_.has_value() != other.qvalue_.has_value()) { return false; } if (!qvalue_.has_value() || !other.qvalue_.has_value()) { return true; } return qvalue_->GetFingerprint() == other.qvalue_->GetFingerprint(); } bool IsSubsetOf(const ExprAttributes& other) const { if (qtype_ != nullptr && qtype_ != other.qtype_) { return false; } if (!qvalue_.has_value()) { return true; } return (other.qvalue_.has_value() && qvalue_->GetFingerprint() == other.qvalue_->GetFingerprint()); } private: const QType* qtype_ = nullptr; std::optional<TypedValue> qvalue_; }; std::ostream& operator<<(std::ostream& ostream, const ExprAttributes& attr); } namespace arolla { AROLLA_DECLARE_FINGERPRINT_HASHER_TRAITS(expr::ExprAttributes); } #endif #include "arolla/expr/expr_attributes.h" #include <ostream> #include "arolla/util/fingerprint.h" namespace arolla::expr { std::ostream& operator<<(std::ostream& ostream, const ExprAttributes& attr) { if (attr.qvalue()) { ostream << "Attr(qvalue=" << attr.qvalue()->Repr() << ")"; } else if (attr.qtype()) { ostream << "Attr(qtype=" << attr.qtype()->name() << ")"; } else { ostream << "Attr{}"; } return ostream; } } namespace arolla { void FingerprintHasherTraits<expr::ExprAttributes>::operator()( FingerprintHasher* hasher, const expr::ExprAttributes& attr) const { hasher->Combine(attr.qtype()); hasher->Combine(attr.qvalue().has_value() ? attr.qvalue()->GetFingerprint() : Fingerprint{}); } }
#include "arolla/expr/expr_attributes.h" #include <cstdint> #include <optional> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/container/flat_hash_set.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/typed_value.h" #include "arolla/util/fingerprint.h" #include "arolla/util/init_arolla.h" #include "arolla/util/testing/status_matchers_backport.h" namespace arolla::expr { namespace { using ::arolla::testing::IsOkAndHolds; using ::testing::PrintToString; using Attr = ::arolla::expr::ExprAttributes; class ExprAttributesTest : public ::testing::Test { protected: void SetUp() override { ASSERT_OK(InitArolla()); } }; TEST_F(ExprAttributesTest, Default) { const Attr attr; EXPECT_EQ(attr.qtype(), nullptr); EXPECT_EQ(attr.qvalue(), std::nullopt); EXPECT_EQ(PrintToString(attr), "Attr{}"); } TEST_F(ExprAttributesTest, QTypeNullptr) { const Attr attr(nullptr); EXPECT_EQ(attr.qtype(), nullptr); EXPECT_EQ(attr.qvalue(), std::nullopt); EXPECT_EQ(PrintToString(attr), "Attr{}"); } TEST_F(ExprAttributesTest, QType) { const Attr attr(GetQTypeQType()); EXPECT_EQ(attr.qtype(), GetQTypeQType()); EXPECT_EQ(attr.qvalue(), std::nullopt); EXPECT_EQ(PrintToString(attr), "Attr(qtype=QTYPE)"); } TEST_F(ExprAttributesTest, QValue) { const Attr attr(TypedValue::FromValue(GetNothingQType())); EXPECT_EQ(attr.qtype(), GetQTypeQType()); EXPECT_THAT(attr.qvalue()->As<QTypePtr>(), IsOkAndHolds(GetNothingQType())); EXPECT_EQ(PrintToString(attr), "Attr(qvalue=NOTHING)"); } TEST_F(ExprAttributesTest, NoQTypeNoQValue) { const Attr attr(nullptr, std::nullopt); EXPECT_EQ(attr.qtype(), nullptr); EXPECT_EQ(attr.qvalue(), std::nullopt); EXPECT_EQ(PrintToString(attr), "Attr{}"); } TEST_F(ExprAttributesTest, QTypeNoQValue) { const Attr attr(GetQTypeQType(), std::nullopt); EXPECT_EQ(attr.qtype(), GetQTypeQType()); EXPECT_EQ(attr.qvalue(), std::nullopt); EXPECT_EQ(PrintToString(attr), "Attr(qtype=QTYPE)"); } TEST_F(ExprAttributesTest, QValueQValue) { std::optional<TypedValue> qvalue = TypedValue::FromValue(GetNothingQType()); const Attr attr(GetQTypeQType(), qvalue); EXPECT_EQ(attr.qtype(), GetQTypeQType()); EXPECT_THAT(attr.qvalue()->As<QTypePtr>(), IsOkAndHolds(GetNothingQType())); EXPECT_EQ(PrintToString(attr), "Attr(qvalue=NOTHING)"); } TEST_F(ExprAttributesTest, Fingerprints) { absl::flat_hash_set<Fingerprint> fingerprints; EXPECT_TRUE( fingerprints .insert(FingerprintHasher("").Combine(ExprAttributes()).Finish()) .second); EXPECT_FALSE( fingerprints .insert(FingerprintHasher("").Combine(ExprAttributes()).Finish()) .second); EXPECT_TRUE(fingerprints .insert(FingerprintHasher("") .Combine(ExprAttributes(GetQType<int64_t>())) .Finish()) .second); EXPECT_FALSE(fingerprints .insert(FingerprintHasher("") .Combine(ExprAttributes(GetQType<int64_t>())) .Finish()) .second); EXPECT_TRUE(fingerprints .insert(FingerprintHasher("") .Combine(ExprAttributes( TypedValue::FromValue<int64_t>(57))) .Finish()) .second); EXPECT_FALSE(fingerprints .insert(FingerprintHasher("") .Combine(ExprAttributes( TypedValue::FromValue<int64_t>(57))) .Finish()) .second); } TEST_F(ExprAttributesTest, IsIdenticalToEmpty) { const Attr attr1; const Attr attr2; EXPECT_TRUE(attr1.IsIdenticalTo(attr1)); EXPECT_TRUE(attr1.IsIdenticalTo(attr2)); EXPECT_TRUE(attr2.IsIdenticalTo(attr2)); } TEST_F(ExprAttributesTest, IsIdenticalToGeneral) { const Attr attr0; const Attr attr1(GetQTypeQType()); EXPECT_FALSE(attr0.IsIdenticalTo(attr1)); const Attr attr2(TypedValue::FromValue(GetNothingQType())); EXPECT_FALSE(attr0.IsIdenticalTo(attr2)); EXPECT_FALSE(attr1.IsIdenticalTo(attr2)); const Attr attr3(GetQTypeQType(), TypedValue::FromValue(GetNothingQType())); EXPECT_FALSE(attr0.IsIdenticalTo(attr3)); EXPECT_FALSE(attr1.IsIdenticalTo(attr3)); EXPECT_TRUE(attr2.IsIdenticalTo(attr3)); const Attr attr4(TypedValue::FromValue(GetQType<int64_t>())); EXPECT_FALSE(attr0.IsIdenticalTo(attr4)); EXPECT_FALSE(attr1.IsIdenticalTo(attr4)); EXPECT_FALSE(attr2.IsIdenticalTo(attr4)); EXPECT_FALSE(attr3.IsIdenticalTo(attr4)); } TEST_F(ExprAttributesTest, IsSubsetOfEmpty) { const Attr attr1; const Attr attr2; EXPECT_TRUE(attr1.IsSubsetOf(attr1)); EXPECT_TRUE(attr1.IsSubsetOf(attr2)); EXPECT_TRUE(attr2.IsSubsetOf(attr2)); } TEST_F(ExprAttributesTest, IsSubsetOf) { const Attr attr0; const Attr attr1(GetQTypeQType()); const Attr attr2(TypedValue::FromValue(GetNothingQType())); const Attr attr3(TypedValue::FromValue(GetQTypeQType())); EXPECT_TRUE(attr0.IsSubsetOf(attr0)); EXPECT_TRUE(attr0.IsSubsetOf(attr1)); EXPECT_TRUE(attr0.IsSubsetOf(attr2)); EXPECT_TRUE(attr0.IsSubsetOf(attr3)); EXPECT_FALSE(attr1.IsSubsetOf(attr0)); EXPECT_TRUE(attr1.IsSubsetOf(attr1)); EXPECT_TRUE(attr1.IsSubsetOf(attr2)); EXPECT_TRUE(attr1.IsSubsetOf(attr3)); EXPECT_FALSE(attr2.IsSubsetOf(attr0)); EXPECT_FALSE(attr2.IsSubsetOf(attr1)); EXPECT_TRUE(attr2.IsSubsetOf(attr2)); EXPECT_FALSE(attr2.IsSubsetOf(attr3)); EXPECT_FALSE(attr3.IsSubsetOf(attr0)); EXPECT_FALSE(attr3.IsSubsetOf(attr1)); EXPECT_FALSE(attr3.IsSubsetOf(attr2)); EXPECT_TRUE(attr3.IsSubsetOf(attr3)); } } }
2,429
#ifndef AROLLA_EXPR_EXPR_OPERATOR_H_ #define AROLLA_EXPR_EXPR_OPERATOR_H_ #include <memory> #include <string> #include "absl/base/attributes.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "arolla/expr/expr_attributes.h" #include "arolla/expr/expr_node_ptr.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/util/api.h" #include "arolla/util/fingerprint.h" #include "arolla/util/repr.h" namespace arolla::expr { class AROLLA_API ExprOperator { public: virtual ~ExprOperator() = default; ExprOperator(const ExprOperator&) = delete; ExprOperator& operator=(const ExprOperator&) = delete; absl::string_view display_name() const { return display_name_; } const Fingerprint& fingerprint() const { return fingerprint_; } virtual absl::StatusOr<ExprOperatorSignature> GetSignature() const = 0; virtual absl::StatusOr<std::string> GetDoc() const; virtual absl::StatusOr<ExprAttributes> InferAttributes( absl::Span<const ExprAttributes> inputs) const = 0; virtual absl::StatusOr<ExprNodePtr> ToLowerLevel( const ExprNodePtr& node) const; virtual ReprToken GenReprToken() const; virtual absl::string_view py_qvalue_specialization_key() const ABSL_ATTRIBUTE_LIFETIME_BOUND; protected: ExprOperator(absl::string_view display_name, Fingerprint fingerprint) : display_name_(display_name), fingerprint_(fingerprint) {} private: std::string display_name_; Fingerprint fingerprint_; }; using ExprOperatorPtr = std::shared_ptr<const ExprOperator>; struct BackendExprOperatorTag {}; struct BuiltinExprOperatorTag {}; struct AnnotationExprOperatorTag : BuiltinExprOperatorTag {}; inline bool HasBackendExprOperatorTag(const ExprOperatorPtr& op) { return dynamic_cast<const BackendExprOperatorTag*>(op.get()) != nullptr; } inline bool HasBuiltinExprOperatorTag(const ExprOperatorPtr& op) { return dynamic_cast<const BuiltinExprOperatorTag*>(op.get()) != nullptr; } inline bool HasAnnotationExprOperatorTag(const ExprOperatorPtr& op) { return dynamic_cast<const AnnotationExprOperatorTag*>(op.get()) != nullptr; } bool IsBackendOperator(const ExprOperatorPtr& op, absl::string_view name); } namespace arolla { AROLLA_DECLARE_FINGERPRINT_HASHER_TRAITS(expr::ExprOperatorPtr); AROLLA_DECLARE_REPR(expr::ExprOperatorPtr); AROLLA_DECLARE_QTYPE(expr::ExprOperatorPtr); } #endif #include "arolla/expr/expr_operator.h" #include <memory> #include <string> #include "absl/log/check.h" #include "absl/status/statusor.h" #include "absl/strings/escaping.h" #include "absl/strings/str_format.h" #include "absl/strings/string_view.h" #include "arolla/expr/expr_node.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/simple_qtype.h" #include "arolla/util/demangle.h" #include "arolla/util/fingerprint.h" #include "arolla/util/indestructible.h" #include "arolla/util/meta.h" #include "arolla/util/repr.h" namespace arolla::expr { absl::StatusOr<std::string> ExprOperator::GetDoc() const { return ""; } absl::StatusOr<ExprNodePtr> ExprOperator::ToLowerLevel( const ExprNodePtr& node) const { return node; } ReprToken ExprOperator::GenReprToken() const { const auto name = absl::CEscape(display_name_); const auto hash = fingerprint_.PythonHash(); const auto cxx_type = TypeName(typeid(*this)); const auto short_cxx_type = cxx_type.substr(cxx_type.rfind(':') + 1); const auto key = absl::CEscape(py_qvalue_specialization_key()); struct ReprToken result; if (key.empty()) { result.str = absl::StrFormat("<Operator with name='%s', hash=0x%x, cxx_type='%s'>", name, hash, short_cxx_type); } else { result.str = absl::StrFormat( "<Operator with name='%s', hash=0x%x, cxx_type='%s', key='%s'>", name, hash, short_cxx_type, key); } return result; } absl::string_view ExprOperator::py_qvalue_specialization_key() const { return ""; } bool IsBackendOperator(const ExprOperatorPtr& op, absl::string_view name) { return HasBackendExprOperatorTag(op) && op->display_name() == name; } } namespace arolla { using ::arolla::expr::ExprOperatorPtr; void FingerprintHasherTraits<ExprOperatorPtr>::operator()( FingerprintHasher* hasher, const ExprOperatorPtr& value) const { hasher->Combine(value->fingerprint()); } ReprToken ReprTraits<ExprOperatorPtr>::operator()( const ExprOperatorPtr& value) const { DCHECK(value != nullptr); if (value == nullptr) { return ReprToken{"<Operator nullptr>"}; } return value->GenReprToken(); } QTypePtr QTypeTraits<ExprOperatorPtr>::type() { struct ExprOperatorQType final : SimpleQType { ExprOperatorQType() : SimpleQType(meta::type<ExprOperatorPtr>(), "EXPR_OPERATOR") {} absl::string_view UnsafePyQValueSpecializationKey( const void* source) const final { if (const auto& op = *static_cast<const ExprOperatorPtr*>(source)) { return op->py_qvalue_specialization_key(); } return ""; } }; static const Indestructible<ExprOperatorQType> result; return result.get(); } }
#include "arolla/expr/expr_operator.h" #include <memory> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "arolla/expr/backend_wrapping_operator.h" #include "arolla/expr/basic_expr_operator.h" #include "arolla/expr/expr_attributes.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/expr/registered_expr_operator.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/util/fingerprint.h" #include "arolla/util/init_arolla.h" #include "arolla/util/repr.h" #include "arolla/util/testing/status_matchers_backport.h" namespace arolla::expr { namespace { using ::arolla::testing::IsOkAndHolds; using ::testing::MatchesRegex; class ExprOperatorTest : public ::testing::Test { protected: void SetUp() override { ASSERT_OK(InitArolla()); } }; TEST_F(ExprOperatorTest, IsBackendOperator) { { EXPECT_FALSE(IsBackendOperator(nullptr, "math.add")); } { ASSERT_OK_AND_ASSIGN(auto op, LookupOperator("math.add")); EXPECT_FALSE(IsBackendOperator(op, "math.add")); } { BackendWrappingOperator::TypeMetaEvalStrategy dummy_strategy = [](absl::Span<const QTypePtr> types) { return nullptr; }; auto op = std::make_shared<BackendWrappingOperator>( "math.add", ExprOperatorSignature::MakeVariadicArgs(), dummy_strategy); EXPECT_TRUE(IsBackendOperator(op, "math.add")); EXPECT_FALSE(IsBackendOperator(op, "foo.bar")); } } TEST_F(ExprOperatorTest, ReprWithoutPyQValueSpecializationKey) { class OperatorWithoutPythonWrapperKey final : public BasicExprOperator { public: OperatorWithoutPythonWrapperKey() : BasicExprOperator("op'name", ExprOperatorSignature{}, "", Fingerprint{0x0123456701234567}) {} absl::StatusOr<QTypePtr> GetOutputQType( absl::Span<const QTypePtr>) const final { return GetQType<float>(); } }; ExprOperatorPtr op = std::make_shared<OperatorWithoutPythonWrapperKey>(); EXPECT_THAT( Repr(op), MatchesRegex("<Operator with name='op\\\\'name', hash=0x[0-9a-f]+, " "cxx_type='OperatorWithoutPythonWrapperKey'>")); } TEST_F(ExprOperatorTest, ReprWithPyQValueSpecializationKey) { class OperatorWithPythonWrapperKey final : public BasicExprOperator { public: OperatorWithPythonWrapperKey() : BasicExprOperator("op'name", ExprOperatorSignature{}, "", Fingerprint{0x0123456701234567}) {} absl::StatusOr<QTypePtr> GetOutputQType( absl::Span<const QTypePtr>) const final { return GetQType<float>(); } absl::string_view py_qvalue_specialization_key() const final { return "foo'bar"; } }; ExprOperatorPtr op = std::make_shared<OperatorWithPythonWrapperKey>(); EXPECT_THAT( Repr(op), MatchesRegex( "<Operator with name='op\\\\'name', hash=0x[0-9a-f]+, " "cxx_type='OperatorWithPythonWrapperKey', key='foo\\\\'bar'>")); } TEST_F(ExprOperatorTest, GetDoc) { class OperatorWithoutGetDoc final : public ExprOperator { public: OperatorWithoutGetDoc() : ExprOperator("op'name", Fingerprint{0x0123456701234567}) {} absl::StatusOr<ExprOperatorSignature> GetSignature() const override { return ExprOperatorSignature{}; } absl::StatusOr<ExprAttributes> InferAttributes( absl::Span<const ExprAttributes>) const override { return ExprAttributes(); } }; EXPECT_THAT(OperatorWithoutGetDoc().GetDoc(), IsOkAndHolds("")); } } }
2,430
#ifndef AROLLA_EXPR_EXPR_STACK_TRACE_H_ #define AROLLA_EXPR_EXPR_STACK_TRACE_H_ #include <cstdint> #include <memory> #include <optional> #include <string> #include <utility> #include <vector> #include "absl/container/flat_hash_map.h" #include "arolla/dense_array/dense_array.h" #include "arolla/expr/expr_node.h" #include "arolla/util/fingerprint.h" #include "arolla/util/text.h" namespace arolla::expr { enum class TransformationType { kUntraced = 0, kLowering = 1, kOptimization = 2, kChildTransform = 3, kCausedByAncestorTransform = 4, }; inline std::string TransformationString(TransformationType t) { switch (t) { case TransformationType::kLowering: return "was lowered to"; case TransformationType::kOptimization: return "was optimized to"; case TransformationType::kUntraced: return "untraced"; case TransformationType::kChildTransform: return "had transformations applied to its children"; case TransformationType::kCausedByAncestorTransform: return "which contains"; default: return "unknown"; } } class ExprStackTrace { public: virtual ~ExprStackTrace() = default; virtual void AddTrace(ExprNodePtr target_node, ExprNodePtr source_node, TransformationType t) = 0; virtual std::string FullTrace(Fingerprint fp) const = 0; }; class DetailedExprStackTrace : public ExprStackTrace { public: void AddTrace(ExprNodePtr target_node, ExprNodePtr source_node, TransformationType t) final; std::string FullTrace(Fingerprint fp) const final; private: struct Transformation { Fingerprint target_fp; Fingerprint source_fp; TransformationType type; }; std::optional<std::pair<Fingerprint, TransformationType>> GetTrace( Fingerprint fp) const; std::string GetRepr(Fingerprint fp) const; std::vector<Transformation> GetTransformations(Fingerprint fp) const; absl::flat_hash_map<Fingerprint, std::pair<Fingerprint, TransformationType>> traceback_; absl::flat_hash_map<Fingerprint, ExprNodePtr> repr_; }; class LightweightExprStackTrace : public ExprStackTrace { public: void AddTrace(ExprNodePtr target_node, ExprNodePtr source_node, TransformationType t) final; std::string FullTrace(Fingerprint fp) const final; void AddRepresentations(ExprNodePtr compiled_node, ExprNodePtr original_node); private: std::string GetRepr(Fingerprint fp) const; absl::flat_hash_map<Fingerprint, Fingerprint> original_node_mapping_; absl::flat_hash_map<Fingerprint, ExprNodePtr> repr_; }; class BoundExprStackTraceBuilder { public: explicit BoundExprStackTraceBuilder( std::shared_ptr<const ExprStackTrace> expr_stack_trace); void RegisterIp(int64_t ip, const ExprNodePtr& node); DenseArray<Text> Build(int64_t num_operators) const; private: std::shared_ptr<const ExprStackTrace> stack_trace_; absl::flat_hash_map<int64_t, Fingerprint> ip_to_fingerprint_; }; } #endif #include "arolla/expr/expr_stack_trace.h" #include <algorithm> #include <cstdint> #include <memory> #include <optional> #include <string> #include <utility> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/container/flat_hash_set.h" #include "absl/log/check.h" #include "absl/strings/str_cat.h" #include "arolla/dense_array/dense_array.h" #include "arolla/expr/expr_debug_string.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_visitor.h" #include "arolla/util/fingerprint.h" #include "arolla/util/text.h" namespace arolla::expr { void DetailedExprStackTrace::AddTrace(ExprNodePtr target_node, ExprNodePtr source_node, TransformationType t) { if (!target_node->is_op()) { return; } if (target_node->fingerprint() == source_node->fingerprint()) { return; } traceback_.insert( {target_node->fingerprint(), {source_node->fingerprint(), t}}); if (traceback_.find(source_node->fingerprint()) == traceback_.end()) { repr_[source_node->fingerprint()] = source_node; } if (t != TransformationType::kUntraced) { repr_[target_node->fingerprint()] = target_node; } } std::optional<std::pair<Fingerprint, TransformationType>> DetailedExprStackTrace::GetTrace(Fingerprint fp) const { auto it = traceback_.find(fp); if (it == traceback_.end()) { return std::nullopt; } return it->second; } std::string DetailedExprStackTrace::GetRepr(Fingerprint fp) const { if (auto it = repr_.find(fp); it != repr_.end()) { return GetDebugSnippet(it->second); } else { return absl::StrCat("Could not find representation for node ", fp.AsString()); } } std::vector<DetailedExprStackTrace::Transformation> DetailedExprStackTrace::GetTransformations(Fingerprint fp) const { auto current_fp = fp; std::vector<Transformation> transformations; absl::flat_hash_set<Fingerprint> visited; visited.insert(current_fp); auto nxt = GetTrace(current_fp); while (nxt.has_value()) { if (nxt->second != TransformationType::kUntraced) { transformations.push_back({current_fp, nxt->first, nxt->second}); } current_fp = nxt->first; if (!visited.insert(current_fp).second) { break; } nxt = GetTrace(current_fp); } std::reverse(transformations.begin(), transformations.end()); if (!transformations.empty()) { transformations.begin()->source_fp = current_fp; } return transformations; } std::string DetailedExprStackTrace::FullTrace(Fingerprint fp) const { auto transformations = GetTransformations(fp); if (transformations.empty()) return ""; std::string stack_trace = absl::StrCat( "ORIGINAL NODE: ", GetRepr(transformations.front().source_fp), "\nCOMPILED NODE: ", GetRepr(transformations.back().target_fp)); if (transformations.size() == 1) return stack_trace; stack_trace += absl::StrCat("\nDETAILED STACK TRACE:\n", GetRepr(transformations.begin()->source_fp)); for (auto it = transformations.begin(); it != transformations.end(); ++it) { stack_trace += absl::StrCat("\n ", TransformationString(it->type), "\n", GetRepr(it->target_fp)); } return stack_trace; } void LightweightExprStackTrace::AddTrace(ExprNodePtr target_node, ExprNodePtr source_node, TransformationType t) { if (!target_node->is_op()) { return; } if (target_node->fingerprint() == source_node->fingerprint()) { return; } auto original_it = original_node_mapping_.find(source_node->fingerprint()); bool source_node_is_original = (original_it == original_node_mapping_.end()); if (source_node_is_original) { original_node_mapping_.insert( {target_node->fingerprint(), source_node->fingerprint()}); } else { DCHECK(!original_node_mapping_.contains(original_it->second)); original_node_mapping_.insert( {target_node->fingerprint(), original_it->second}); } } void LightweightExprStackTrace::AddRepresentations(ExprNodePtr compiled_node, ExprNodePtr original_node) { auto compiled_post_order = PostOrder(compiled_node); for (const auto& node : compiled_post_order.nodes()) { repr_.insert({node->fingerprint(), node}); } auto original_post_order = PostOrder(original_node); for (const auto& node : original_post_order.nodes()) { repr_.insert({node->fingerprint(), node}); } } std::string LightweightExprStackTrace::GetRepr(Fingerprint fp) const { if (auto it = repr_.find(fp); it != repr_.end()) { return GetDebugSnippet(it->second); } else { return "?"; } } std::string LightweightExprStackTrace::FullTrace(Fingerprint fp) const { if (auto it = original_node_mapping_.find(fp); it != original_node_mapping_.end()) { return absl::StrCat("ORIGINAL NODE: ", GetRepr(it->second), "\nCOMPILED NODE: ", GetRepr(fp)); } else { return absl::StrCat("NODE: ", GetRepr(fp)); } } BoundExprStackTraceBuilder::BoundExprStackTraceBuilder( std::shared_ptr<const ExprStackTrace> stack_trace) : stack_trace_(stack_trace) {} void BoundExprStackTraceBuilder::RegisterIp(int64_t ip, const ExprNodePtr& node) { ip_to_fingerprint_.insert({ip, node->fingerprint()}); } DenseArray<Text> BoundExprStackTraceBuilder::Build( int64_t num_operators) const { DenseArrayBuilder<Text> traces_array_builder(num_operators); for (int64_t i = 0; i < num_operators; ++i) { if (auto it = ip_to_fingerprint_.find(i); it != ip_to_fingerprint_.end()) { traces_array_builder.Add(i, Text{stack_trace_->FullTrace(it->second)}); } } return std::move(traces_array_builder).Build(); } }
#include "arolla/expr/expr_stack_trace.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "arolla/util/fingerprint.h" #include "arolla/util/init_arolla.h" namespace arolla::expr { namespace { class ExprStackTraceTest : public ::testing::Test { protected: void SetUp() override { ASSERT_OK(InitArolla()); } }; TEST_F(ExprStackTraceTest, ExprStackTraceSafeReturnsOnUnregisteredFingerprint) { DetailedExprStackTrace stack_trace; EXPECT_EQ(stack_trace.FullTrace(Fingerprint{0}), ""); } } }
2,431
#ifndef AROLLA_EXPR_EXPR_DEBUG_STRING_H_ #define AROLLA_EXPR_EXPR_DEBUG_STRING_H_ #include <string> #include "arolla/expr/expr_node.h" namespace arolla::expr { std::string ToDebugString(ExprNodePtr root, bool verbose = false); std::string GetDebugSnippet(const ExprNodePtr& node); } #endif #include "arolla/expr/expr_debug_string.h" #include <algorithm> #include <cstddef> #include <optional> #include <string> #include <string_view> #include <utility> #include <vector> #include "absl/base/optimization.h" #include "absl/container/flat_hash_map.h" #include "absl/container/inlined_vector.h" #include "absl/log/check.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_join.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "arolla/expr/annotation_utils.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/expr_visitor.h" #include "arolla/expr/operator_repr_functions.h" #include "arolla/expr/registered_expr_operator.h" #include "arolla/util/fingerprint.h" #include "arolla/util/repr.h" #include "arolla/util/string.h" namespace arolla::expr { namespace { std::vector<ExprNodePtr> SelectStatementNodes(const PostOrder& post_order) { const size_t kCriticalDepth = 3; std::vector<size_t> node_parent_count(post_order.nodes_size(), 0); for (size_t i = 0; i < post_order.nodes_size(); ++i) { for (size_t j : post_order.dep_indices(i)) { node_parent_count[j] += 1; } } std::vector<ExprNodePtr> result; std::vector<size_t> node_depth(post_order.nodes_size()); for (size_t i = 0; i < post_order.nodes_size(); ++i) { size_t depth = 1; for (size_t j : post_order.dep_indices(i)) { depth = std::max(depth, 1 + node_depth[j]); } const auto& node = post_order.node(i); const bool is_statement = IsNameAnnotation(node) || (node_parent_count[i] > 1 && depth >= kCriticalDepth); if (is_statement) { result.push_back(node); depth = 1; } node_depth[i] = depth; } return result; } constexpr bool IsSafeStatementName(absl::string_view str) { return IsQualifiedIdentifier(str) && !(str.size() > 1 && str[0] == '_' && std::find_if_not(str.begin() + 1, str.end(), IsDigit) == str.end()); } absl::flat_hash_map<Fingerprint, std::string> GenStatementNames( const PostOrder& post_order) { const auto statement_nodes = SelectStatementNodes(post_order); absl::flat_hash_map<absl::string_view, size_t> name_counts; name_counts.reserve(statement_nodes.size()); for (const auto& node : statement_nodes) { if (auto name = ReadNameAnnotation(node); IsSafeStatementName(name)) { name_counts[name] += 1; } } for (auto& [_, v] : name_counts) { v = (v > 1); } absl::flat_hash_map<Fingerprint, std::string> result; result.reserve(statement_nodes.size()); size_t anonymous_count = 1; for (const auto& node : statement_nodes) { const auto name = ReadNameAnnotation(node); if (!IsSafeStatementName(name)) { result.emplace(node->fingerprint(), absl::StrCat("_", anonymous_count++)); continue; } auto& name_count = name_counts[name]; if (name_count == 0) { result.emplace(node->fingerprint(), name); } else { result.emplace(node->fingerprint(), absl::StrCat(name, "._", name_count++)); } } return result; } std::vector<const ReprToken*> GetNodeDepsTokens( const ExprNodePtr& node, const absl::flat_hash_map<Fingerprint, ReprToken>& node_tokens) { std::vector<const ReprToken*> inputs(node->node_deps().size()); for (size_t i = 0; i < node->node_deps().size(); ++i) { inputs[i] = &node_tokens.at(node->node_deps()[i]->fingerprint()); } return inputs; } ReprToken FormatLiteral(const ExprNodePtr& node) { if (auto literal = node->qvalue()) { return literal->GenReprToken(); } else { return ReprToken{"<broken_literal>"}; } } ReprToken FormatLeaf(const ExprNodePtr& node) { return ReprToken{absl::StrCat("L", ContainerAccessString(node->leaf_key()))}; } ReprToken FormatPlaceholder(const ExprNodePtr& node) { return ReprToken{ absl::StrCat("P", ContainerAccessString(node->placeholder_key()))}; } ReprToken FormatOperatorCanonical(const ExprNodePtr& node, absl::Span<const ReprToken* const> inputs) { ReprToken result; if (IsRegisteredOperator(node->op())) { absl::StrAppend(&result.str, "M."); } absl::StrAppend(&result.str, node->op()->display_name(), "("); for (size_t i = 0; i < inputs.size(); ++i) { if (i > 0) { absl::StrAppend(&result.str, ", "); } absl::StrAppend(&result.str, inputs[i]->str); } absl::StrAppend(&result.str, ")"); return result; } ReprToken FormatOperatorVerbose(const ExprNodePtr& node, absl::Span<const ReprToken* const> inputs) { ReprToken result = FormatOperatorCanonical(node, inputs); if (!IsQTypeAnnotation(node)) { if (auto* qtype = node->qtype()) { absl::StrAppend(&result.str, ":", qtype->name()); } } return result; } ReprToken FormatOperatorPretty( const ExprNodePtr& node, const absl::flat_hash_map<Fingerprint, ReprToken>& node_tokens) { if (auto repr = FormatOperatorNodePretty(node, node_tokens)) { return std::move(*repr); } return FormatOperatorCanonical(node, GetNodeDepsTokens(node, node_tokens)); } ReprToken FormatVerbose(const ExprNodePtr& node, absl::Span<const ReprToken* const> inputs) { switch (node->type()) { case ExprNodeType::kLiteral: return FormatLiteral(node); case ExprNodeType::kLeaf: return FormatLeaf(node); case ExprNodeType::kPlaceholder: return FormatPlaceholder(node); case ExprNodeType::kOperator: return FormatOperatorVerbose(node, inputs); } ABSL_UNREACHABLE(); } ReprToken FormatPretty( const ExprNodePtr& node, const absl::flat_hash_map<Fingerprint, ReprToken>& node_tokens) { switch (node->type()) { case ExprNodeType::kLiteral: return FormatLiteral(node); case ExprNodeType::kLeaf: return FormatLeaf(node); case ExprNodeType::kPlaceholder: return FormatPlaceholder(node); case ExprNodeType::kOperator: return FormatOperatorPretty(node, node_tokens); } ABSL_UNREACHABLE(); } ReprToken FormatWithHiddenInputs(const ExprNodePtr& node) { const ReprToken kDots{.str = "..."}; std::vector<const ReprToken*> inputs(node->node_deps().size(), &kDots); return FormatVerbose(node, inputs); } } std::string ToDebugString(ExprNodePtr root, bool verbose) { const PostOrder post_order(root); const auto statement_names = GenStatementNames(post_order); std::vector<std::string> result; absl::flat_hash_map<Fingerprint, ReprToken> node_tokens( post_order.nodes_size()); auto format = verbose ? []( const ExprNodePtr& node, const absl::flat_hash_map<Fingerprint, ReprToken>& node_tokens) { return FormatVerbose(node, GetNodeDepsTokens(node, node_tokens)); }: FormatPretty; for (const auto& node : post_order.nodes()) { auto it = statement_names.find(node->fingerprint()); if (it == statement_names.end()) { node_tokens[node->fingerprint()] = format(node, node_tokens); continue; } const auto& statement_name = it->second; if (IsSafeStatementName(ReadNameAnnotation(node))) { DCHECK_EQ(node->node_deps().size(), 2); const auto& res = node_tokens[node->node_deps()[0]->fingerprint()]; result.push_back(absl::StrCat(statement_name, " = ", res.str)); } else { result.push_back( absl::StrCat(statement_name, " = ", format(node, node_tokens).str)); } node_tokens[node->fingerprint()] = ReprToken{.str = statement_name}; } result.push_back(std::move(node_tokens[root->fingerprint()].str)); return absl::StrJoin(result, "\n"); } constexpr int kMaxDebugSnippetSize = 200; std::string GetDebugSnippet(const ExprNodePtr& node) { const auto& node_deps = node->node_deps(); absl::InlinedVector<ReprToken, 4> dep_snippets(node_deps.size()); absl::InlinedVector<const ReprToken*, 4> dep_snippet_ptrs(node_deps.size()); for (size_t i = 0; i < node_deps.size(); ++i) { dep_snippets[i] = FormatWithHiddenInputs(node_deps[i]); dep_snippet_ptrs[i] = &dep_snippets[i]; } std::string snippet = FormatVerbose(node, dep_snippet_ptrs).str; return Truncate(std::move(snippet), kMaxDebugSnippetSize); } }
#include "arolla/expr/expr_debug_string.h" #include <cstdint> #include <memory> #include <optional> #include <string> #include <utility> #include "benchmark/benchmark.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/container/flat_hash_map.h" #include "absl/log/check.h" #include "absl/strings/str_format.h" #include "absl/strings/string_view.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_attributes.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/expr/operator_repr_functions.h" #include "arolla/expr/registered_expr_operator.h" #include "arolla/expr/testing/test_operators.h" #include "arolla/expr/testing/testing.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/testing/dummy_types.h" #include "arolla/qtype/unspecified_qtype.h" #include "arolla/util/bytes.h" #include "arolla/util/fingerprint.h" #include "arolla/util/init_arolla.h" #include "arolla/util/repr.h" #include "arolla/util/text.h" namespace arolla::expr { namespace { using ::arolla::testing::WithNameAnnotation; using ::arolla::testing::WithQTypeAnnotation; class ExprDebugStringTest : public ::testing::Test { protected: void SetUp() override { ASSERT_OK(InitArolla()); } ExprNodePtr Pos(ExprNodePtr x) { return CallOp("math.pos", {x}).value(); } ExprNodePtr Neg(ExprNodePtr x) { return CallOp("math.neg", {x}).value(); } ExprNodePtr Invert(ExprNodePtr x) { return CallOp("core.presence_not", {x}).value(); } ExprNodePtr Pow(ExprNodePtr lhs, ExprNodePtr rhs) { return CallOp("math.pow", {lhs, rhs}).value(); } ExprNodePtr Mul(ExprNodePtr lhs, ExprNodePtr rhs) { return CallOp("math.multiply", {lhs, rhs}).value(); } ExprNodePtr TrueDiv(ExprNodePtr lhs, ExprNodePtr rhs) { return CallOp("math.divide", {lhs, rhs}).value(); } ExprNodePtr FloorDiv(ExprNodePtr lhs, ExprNodePtr rhs) { return CallOp("math.floordiv", {lhs, rhs}).value(); } ExprNodePtr Mod(ExprNodePtr lhs, ExprNodePtr rhs) { return CallOp("math.mod", {lhs, rhs}).value(); } ExprNodePtr Add(ExprNodePtr lhs, ExprNodePtr rhs) { return CallOp("math.add", {lhs, rhs}).value(); } ExprNodePtr Sub(ExprNodePtr lhs, ExprNodePtr rhs) { return CallOp("math.subtract", {lhs, rhs}).value(); } ExprNodePtr And(ExprNodePtr lhs, ExprNodePtr rhs) { return CallOp("core.presence_and", {lhs, rhs}).value(); } ExprNodePtr Or(ExprNodePtr lhs, ExprNodePtr rhs) { return CallOp("core.presence_or", {lhs, rhs}).value(); } ExprNodePtr Lt(ExprNodePtr lhs, ExprNodePtr rhs) { return CallOp("core.less", {lhs, rhs}).value(); } ExprNodePtr Le(ExprNodePtr lhs, ExprNodePtr rhs) { return CallOp("core.less_equal", {lhs, rhs}).value(); } ExprNodePtr Eq(ExprNodePtr lhs, ExprNodePtr rhs) { return CallOp("core.equal", {lhs, rhs}).value(); } ExprNodePtr Neq(ExprNodePtr lhs, ExprNodePtr rhs) { return CallOp("core.not_equal", {lhs, rhs}).value(); } ExprNodePtr Ge(ExprNodePtr lhs, ExprNodePtr rhs) { return CallOp("core.greater_equal", {lhs, rhs}).value(); } ExprNodePtr Gt(ExprNodePtr lhs, ExprNodePtr rhs) { return CallOp("core.greater", {lhs, rhs}).value(); } ExprNodePtr GetAttr(ExprNodePtr lhs, ExprNodePtr rhs) { return ExprNode::UnsafeMakeOperatorNode( std::make_shared<RegisteredOperator>("core.getattr"), {lhs, rhs}, ExprAttributes()); } ExprNodePtr GetItem(ExprNodePtr lhs, ExprNodePtr rhs) { return ExprNode::UnsafeMakeOperatorNode( std::make_shared<RegisteredOperator>("core.getitem"), {lhs, rhs}, ExprAttributes()); } ExprNodePtr MakeSlice(ExprNodePtr a, ExprNodePtr b, ExprNodePtr c) { return ExprNode::UnsafeMakeOperatorNode( std::make_shared<RegisteredOperator>("core.make_slice"), {a, b, c}, ExprAttributes()); } ExprNodePtr Dummy(ExprNodePtr lhs, ExprNodePtr rhs) { return ExprNode::UnsafeMakeOperatorNode( std::make_shared<testing::DummyOp>( "custom.add", ExprOperatorSignature({{"x"}, {"y"}})), {lhs, rhs}, ExprAttributes()); } }; TEST_F(ExprDebugStringTest, Literal) { { auto expr = Literal(int32_t{271828182}); EXPECT_EQ("271828182", ToDebugString(expr)); } { auto expr = Literal(int64_t{3417201710}); EXPECT_EQ("int64{3417201710}", ToDebugString(expr)); } { auto expr = Literal(Bytes("Hello, World!")); EXPECT_EQ("b'Hello, World!'", ToDebugString(expr)); } { ASSERT_OK_AND_ASSIGN(auto expr, WithNameAnnotation(Literal(Bytes("Foo")), "Bar")); EXPECT_EQ("Bar = b'Foo'\nBar", ToDebugString(expr)); } } TEST_F(ExprDebugStringTest, Leaf) { EXPECT_THAT(ToDebugString(Leaf("")), "L['']"); EXPECT_THAT(ToDebugString(Leaf("x")), "L.x"); EXPECT_THAT(ToDebugString(Leaf("'Hello, World!'")), "L['\\'Hello, World!\\'']"); ASSERT_OK_AND_ASSIGN(auto y, WithQTypeAnnotation(Leaf("y"), GetQType<double>())); EXPECT_THAT(ToDebugString(y), "M.annotation.qtype(L.y, FLOAT64)"); EXPECT_THAT(ToDebugString(y, true), "M.annotation.qtype(L.y, FLOAT64)"); } TEST_F(ExprDebugStringTest, Placeholder) { EXPECT_EQ("P['']", ToDebugString(Placeholder(""))); EXPECT_EQ("P.foo", ToDebugString(Placeholder("foo"))); EXPECT_EQ("P[':)']", ToDebugString(Placeholder(":)"))); } TEST_F(ExprDebugStringTest, Operator) { EXPECT_EQ(ToDebugString(CallOp("math.max", {Leaf("x"), Leaf("y")}).value()), "M.math.max(L.x, L.y)"); EXPECT_EQ(ToDebugString(Add(Leaf("x"), Leaf("y"))), "L.x + L.y"); } TEST_F(ExprDebugStringTest, Trivial) { ASSERT_OK_AND_ASSIGN( auto abc, CallOp("test.add3", {Literal(0.f), Literal(2.7182f), Literal(3.1415f)})); ASSERT_OK_AND_ASSIGN(auto expr, CallOp("test.add3", {abc, Leaf("x"), Leaf("y")})); EXPECT_EQ("M.test.add3(M.test.add3(0., 2.7182, 3.1415), L.x, L.y)", ToDebugString(expr)); } TEST_F(ExprDebugStringTest, UniqueStatements) { auto a = Leaf("a"); auto b = Leaf("b"); auto c = Leaf("c"); ASSERT_OK_AND_ASSIGN( auto d, WithNameAnnotation( Pow(Sub(Mul(b, b), Mul(Literal(4.f), Mul(a, c))), Literal(0.5f)), "D")); ASSERT_OK_AND_ASSIGN( auto x0, WithNameAnnotation(TrueDiv(TrueDiv(Add(b, d), Literal(-2.f)), a), "x0")); ASSERT_OK_AND_ASSIGN(auto x1, WithNameAnnotation(TrueDiv(TrueDiv(c, a), x0), "x1")); EXPECT_EQ(("D = (L.b * L.b - 4. * (L.a * L.c)) ** 0.5\n" "x0 = (L.b + D) / -2. / L.a\n" "x1 = L.c / L.a / x0\n" "x0 * x1"), ToDebugString(Mul(x0, x1))); } TEST_F(ExprDebugStringTest, LeafKeyNameCollisions) { ASSERT_OK_AND_ASSIGN(auto expr, WithNameAnnotation(Add(Leaf("a"), Leaf("a")), "a")); EXPECT_EQ(ToDebugString(expr), "a = L.a + L.a\na"); } TEST_F(ExprDebugStringTest, PlaceholderKeyNameCollisions) { ASSERT_OK_AND_ASSIGN( auto expr, WithNameAnnotation( CallOp("math.min", {Placeholder("a"), Placeholder("a")}), "a")); EXPECT_EQ(ToDebugString(expr), "a = M.math.min(P.a, P.a)\na"); } TEST_F(ExprDebugStringTest, UnsafeStatements) { auto expr = Leaf("a"); ASSERT_OK_AND_ASSIGN(expr, WithNameAnnotation(Add(expr, expr), "_")); ASSERT_OK_AND_ASSIGN(expr, WithNameAnnotation(Add(expr, expr), "")); ASSERT_OK_AND_ASSIGN(expr, WithNameAnnotation(Add(expr, expr), "_1")); ASSERT_OK_AND_ASSIGN(expr, WithNameAnnotation(Add(expr, expr), "_X")); ASSERT_OK_AND_ASSIGN(expr, WithNameAnnotation(Add(expr, expr), "_Y")); ASSERT_OK_AND_ASSIGN(expr, WithNameAnnotation(Add(expr, expr), "_Y")); ASSERT_OK_AND_ASSIGN(expr, WithNameAnnotation(Add(expr, expr), "quick' fox")); ASSERT_OK_AND_ASSIGN(expr, WithNameAnnotation(Add(expr, expr), "foo.bar")); ASSERT_OK_AND_ASSIGN(expr, WithNameAnnotation(Add(expr, expr), "abc.")); ASSERT_OK_AND_ASSIGN(expr, WithNameAnnotation(Add(expr, expr), ".def")); ASSERT_OK_AND_ASSIGN(expr, WithNameAnnotation(Add(expr, expr), "fake..name")); ASSERT_OK_AND_ASSIGN(expr, WithNameAnnotation(Add(expr, expr), "a.1")); EXPECT_EQ(ToDebugString(expr), "_ = L.a + L.a\n" "_1 = M.annotation.name(_ + _, '')\n" "_2 = M.annotation.name(_1 + _1, '_1')\n" "_X = _2 + _2\n" "_Y._1 = _X + _X\n" "_Y._2 = _Y._1 + _Y._1\n" "_3 = M.annotation.name(_Y._2 + _Y._2, 'quick\\' fox')\n" "foo.bar = _3 + _3\n" "_4 = M.annotation.name(foo.bar + foo.bar, 'abc.')\n" "_5 = M.annotation.name(_4 + _4, '.def')\n" "_6 = M.annotation.name(_5 + _5, 'fake..name')\n" "_7 = M.annotation.name(_6 + _6, 'a.1')\n" "_7"); } TEST_F(ExprDebugStringTest, UnnamedStatements) { auto expr = Leaf("a"); for (int i = 0; i < 10; ++i) { expr = Add(expr, expr); } EXPECT_EQ(ToDebugString(expr), "_1 = L.a + L.a + (L.a + L.a)\n" "_2 = _1 + _1 + (_1 + _1)\n" "_3 = _2 + _2 + (_2 + _2)\n" "_4 = _3 + _3 + (_3 + _3)\n" "_4 + _4 + (_4 + _4)"); } TEST_F(ExprDebugStringTest, NonUniqueStatements) { auto expr = Leaf("a"); for (int i = 0; i < 5; ++i) { ASSERT_OK_AND_ASSIGN(expr, WithNameAnnotation(Add(expr, expr), "a")); } EXPECT_EQ(ToDebugString(expr), "a._1 = L.a + L.a\n" "a._2 = a._1 + a._1\n" "a._3 = a._2 + a._2\n" "a._4 = a._3 + a._3\n" "a._5 = a._4 + a._4\n" "a._5"); } TEST_F(ExprDebugStringTest, ExponentionalBlow) { auto expr = Leaf("a"); for (int i = 0; i < 100; ++i) { expr = Add(expr, expr); } EXPECT_LT(ToDebugString(expr).size(), 10000); } TEST_F(ExprDebugStringTest, Infix_Brackets) { EXPECT_EQ(ToDebugString(Neg(Add(Leaf("u"), Leaf("v")))), "-(L.u + L.v)"); EXPECT_EQ(ToDebugString(Neg(Leaf("u"))), "-L.u"); EXPECT_EQ(ToDebugString(Mul(Leaf("u"), Leaf("x"))), "L.u * L.x"); EXPECT_EQ(ToDebugString(Mul(Add(Leaf("u"), Leaf("v")), Leaf("x"))), "(L.u + L.v) * L.x"); EXPECT_EQ(ToDebugString(Mul(Leaf("u"), Add(Leaf("x"), Leaf("y")))), "L.u * (L.x + L.y)"); EXPECT_EQ( ToDebugString(Mul(Add(Leaf("u"), Leaf("v")), Add(Leaf("x"), Leaf("y")))), "(L.u + L.v) * (L.x + L.y)"); } TEST_F(ExprDebugStringTest, Infix_Unary_IncorrectArity) { auto x = Leaf("x"); ASSERT_OK_AND_ASSIGN(auto op, LookupOperator("math.pos")); EXPECT_EQ(ToDebugString(ExprNode::UnsafeMakeOperatorNode(op, {x}, {})), "+L.x"); EXPECT_EQ(ToDebugString(ExprNode::UnsafeMakeOperatorNode(op, {x, x}, {})), "M.math.pos(L.x, L.x)"); } TEST_F(ExprDebugStringTest, Infix_Binary_IncorrectArity) { auto x = Leaf("x"); ASSERT_OK_AND_ASSIGN(auto op, LookupOperator("math.add")); EXPECT_EQ(ToDebugString(ExprNode::UnsafeMakeOperatorNode(op, {x, x}, {})), "L.x + L.x"); EXPECT_EQ(ToDebugString(ExprNode::UnsafeMakeOperatorNode(op, {x, x, x}, {})), "M.math.add(L.x, L.x, L.x)"); } TEST_F(ExprDebugStringTest, Infix_NonRegisteredOperator) { auto x = Leaf("x"); ASSERT_OK_AND_ASSIGN(auto op, LookupOperator("math.add")); ASSERT_OK_AND_ASSIGN(auto op_impl, DecayRegisteredOperator(op)); EXPECT_EQ(ToDebugString( ExprNode::UnsafeMakeOperatorNode(std::move(op), {x, x}, {})), "L.x + L.x"); EXPECT_EQ(ToDebugString(ExprNode::UnsafeMakeOperatorNode(std::move(op_impl), {x, x}, {})), "math.add(L.x, L.x)"); } TEST_F(ExprDebugStringTest, Infix_Unary_NegGroup) { auto x = Leaf("x"); EXPECT_EQ(ToDebugString(Pos(x)), "+L.x"); EXPECT_EQ(ToDebugString(Pos(Pos(x))), "+(+L.x)"); EXPECT_EQ(ToDebugString(Neg(x)), "-L.x"); EXPECT_EQ(ToDebugString(Neg(Neg(x))), "-(-L.x)"); EXPECT_EQ(ToDebugString(Invert(x)), "~L.x"); EXPECT_EQ(ToDebugString(Invert(Invert(x))), "~(~L.x)"); EXPECT_EQ(ToDebugString(Pos(Neg(Invert(x)))), "+(-(~L.x))"); EXPECT_EQ(ToDebugString(Pos(Neg(Invert(Pos(Neg(Invert(x))))))), "+(-(~(+(-(~L.x)))))"); } TEST_F(ExprDebugStringTest, Infix_Binary_Pow) { auto x = Leaf("x"); auto y = Leaf("y"); auto z = Leaf("z"); EXPECT_EQ(ToDebugString(Pow(x, y)), "L.x ** L.y"); EXPECT_EQ(ToDebugString(Pow(Pow(x, y), z)), "(L.x ** L.y) ** L.z"); EXPECT_EQ(ToDebugString(Pow(x, Pow(y, z))), "L.x ** L.y ** L.z"); EXPECT_EQ(ToDebugString(Neg(Pow(x, y))), "-(L.x ** L.y)"); EXPECT_EQ(ToDebugString(Pow(Neg(x), y)), "(-L.x) ** L.y"); EXPECT_EQ(ToDebugString(Pow(x, Neg(y))), "L.x ** -L.y"); } TEST_F(ExprDebugStringTest, Infix_Binary_MulGroup) { auto x = Leaf("x"); auto y = Leaf("y"); auto z = Leaf("z"); EXPECT_EQ(ToDebugString(Mul(x, y)), "L.x * L.y"); EXPECT_EQ(ToDebugString(Mul(Mul(x, y), z)), "L.x * L.y * L.z"); EXPECT_EQ(ToDebugString(Mul(x, Mul(y, z))), "L.x * (L.y * L.z)"); EXPECT_EQ(ToDebugString(TrueDiv(x, y)), "L.x / L.y"); EXPECT_EQ(ToDebugString(TrueDiv(TrueDiv(x, y), z)), "L.x / L.y / L.z"); EXPECT_EQ(ToDebugString(TrueDiv(x, TrueDiv(y, z))), "L.x / (L.y / L.z)"); EXPECT_EQ(ToDebugString(FloorDiv(x, y)), "L.x EXPECT_EQ(ToDebugString(FloorDiv(FloorDiv(x, y), z)), "L.x EXPECT_EQ(ToDebugString(FloorDiv(x, FloorDiv(y, z))), "L.x EXPECT_EQ(ToDebugString(Mod(x, y)), "L.x % L.y"); EXPECT_EQ(ToDebugString(Mod(Mod(x, y), z)), "L.x % L.y % L.z"); EXPECT_EQ(ToDebugString(Mod(x, Mod(y, z))), "L.x % (L.y % L.z)"); EXPECT_EQ(ToDebugString(TrueDiv(Mul(x, y), z)), "L.x * L.y / L.z"); EXPECT_EQ(ToDebugString(Mul(x, TrueDiv(y, z))), "L.x * (L.y / L.z)"); EXPECT_EQ(ToDebugString(Mul(TrueDiv(x, y), z)), "L.x / L.y * L.z"); EXPECT_EQ(ToDebugString(TrueDiv(x, Mul(y, z))), "L.x / (L.y * L.z)"); EXPECT_EQ(ToDebugString(FloorDiv(Mul(x, y), z)), "L.x * L.y EXPECT_EQ(ToDebugString(Mul(x, FloorDiv(y, z))), "L.x * (L.y EXPECT_EQ(ToDebugString(Mul(FloorDiv(x, y), z)), "L.x EXPECT_EQ(ToDebugString(FloorDiv(x, Mul(y, z))), "L.x EXPECT_EQ(ToDebugString(Mod(Mul(x, y), z)), "L.x * L.y % L.z"); EXPECT_EQ(ToDebugString(Mul(x, Mod(y, z))), "L.x * (L.y % L.z)"); EXPECT_EQ(ToDebugString(Mul(Mod(x, y), z)), "L.x % L.y * L.z"); EXPECT_EQ(ToDebugString(Mod(x, Mul(y, z))), "L.x % (L.y * L.z)"); EXPECT_EQ(ToDebugString(Pow(Mul(x, y), z)), "(L.x * L.y) ** L.z"); EXPECT_EQ(ToDebugString(Mul(x, Pow(y, z))), "L.x * L.y ** L.z"); EXPECT_EQ(ToDebugString(Mul(Pow(x, y), z)), "L.x ** L.y * L.z"); EXPECT_EQ(ToDebugString(Pow(x, Mul(y, z))), "L.x ** (L.y * L.z)"); EXPECT_EQ(ToDebugString(Neg(Mul(x, y))), "-(L.x * L.y)"); EXPECT_EQ(ToDebugString(Mul(Neg(x), y)), "-L.x * L.y"); EXPECT_EQ(ToDebugString(Mul(x, Neg(y))), "L.x * -L.y"); } TEST_F(ExprDebugStringTest, Infix_Binary_AddGroup) { auto x = Leaf("x"); auto y = Leaf("y"); auto z = Leaf("z"); EXPECT_EQ(ToDebugString(Add(x, y)), "L.x + L.y"); EXPECT_EQ(ToDebugString(Add(Add(x, y), z)), "L.x + L.y + L.z"); EXPECT_EQ(ToDebugString(Add(x, Add(y, z))), "L.x + (L.y + L.z)"); EXPECT_EQ(ToDebugString(Sub(x, y)), "L.x - L.y"); EXPECT_EQ(ToDebugString(Sub(Sub(x, y), z)), "L.x - L.y - L.z"); EXPECT_EQ(ToDebugString(Sub(x, Sub(y, z))), "L.x - (L.y - L.z)"); EXPECT_EQ(ToDebugString(Sub(Add(x, y), z)), "L.x + L.y - L.z"); EXPECT_EQ(ToDebugString(Add(x, Sub(y, z))), "L.x + (L.y - L.z)"); EXPECT_EQ(ToDebugString(Add(Sub(x, y), z)), "L.x - L.y + L.z"); EXPECT_EQ(ToDebugString(Sub(x, Add(y, z))), "L.x - (L.y + L.z)"); EXPECT_EQ(ToDebugString(Mul(Add(x, y), z)), "(L.x + L.y) * L.z"); EXPECT_EQ(ToDebugString(Add(x, Mul(y, z))), "L.x + L.y * L.z"); EXPECT_EQ(ToDebugString(Add(Mul(x, y), z)), "L.x * L.y + L.z"); EXPECT_EQ(ToDebugString(Mul(x, Add(y, z))), "L.x * (L.y + L.z)"); EXPECT_EQ(ToDebugString(Pow(Add(x, y), z)), "(L.x + L.y) ** L.z"); EXPECT_EQ(ToDebugString(Add(x, Pow(y, z))), "L.x + L.y ** L.z"); EXPECT_EQ(ToDebugString(Add(Pow(x, y), z)), "L.x ** L.y + L.z"); EXPECT_EQ(ToDebugString(Pow(x, Add(y, z))), "L.x ** (L.y + L.z)"); EXPECT_EQ(ToDebugString(Neg(Add(x, y))), "-(L.x + L.y)"); EXPECT_EQ(ToDebugString(Add(Neg(x), y)), "-L.x + L.y"); EXPECT_EQ(ToDebugString(Add(x, Neg(y))), "L.x + -L.y"); } TEST_F(ExprDebugStringTest, Infix_Binary_And) { auto x = Leaf("x"); auto y = Leaf("y"); auto z = Leaf("z"); EXPECT_EQ(ToDebugString(And(x, y)), "L.x & L.y"); EXPECT_EQ(ToDebugString(And(And(x, y), z)), "L.x & L.y & L.z"); EXPECT_EQ(ToDebugString(And(x, And(y, z))), "L.x & (L.y & L.z)"); EXPECT_EQ(ToDebugString(Add(And(x, y), z)), "(L.x & L.y) + L.z"); EXPECT_EQ(ToDebugString(And(x, Add(y, z))), "L.x & L.y + L.z"); EXPECT_EQ(ToDebugString(And(Add(x, y), z)), "L.x + L.y & L.z"); EXPECT_EQ(ToDebugString(Add(x, And(y, z))), "L.x + (L.y & L.z)"); EXPECT_EQ(ToDebugString(Mul(And(x, y), z)), "(L.x & L.y) * L.z"); EXPECT_EQ(ToDebugString(And(x, Mul(y, z))), "L.x & L.y * L.z"); EXPECT_EQ(ToDebugString(And(Mul(x, y), z)), "L.x * L.y & L.z"); EXPECT_EQ(ToDebugString(Mul(x, And(y, z))), "L.x * (L.y & L.z)"); EXPECT_EQ(ToDebugString(Pow(And(x, y), z)), "(L.x & L.y) ** L.z"); EXPECT_EQ(ToDebugString(And(x, Pow(y, z))), "L.x & L.y ** L.z"); EXPECT_EQ(ToDebugString(And(Pow(x, y), z)), "L.x ** L.y & L.z"); EXPECT_EQ(ToDebugString(Pow(x, And(y, z))), "L.x ** (L.y & L.z)"); EXPECT_EQ(ToDebugString(Neg(And(x, y))), "-(L.x & L.y)"); EXPECT_EQ(ToDebugString(And(Neg(x), y)), "-L.x & L.y"); EXPECT_EQ(ToDebugString(And(x, Neg(y))), "L.x & -L.y"); } TEST_F(ExprDebugStringTest, Infix_Binary_Or) { auto x = Leaf("x"); auto y = Leaf("y"); auto z = Leaf("z"); EXPECT_EQ(ToDebugString(Or(x, y)), "L.x | L.y"); EXPECT_EQ(ToDebugString(Or(Or(x, y), z)), "L.x | L.y | L.z"); EXPECT_EQ(ToDebugString(Or(x, Or(y, z))), "L.x | (L.y | L.z)"); EXPECT_EQ(ToDebugString(And(Or(x, y), z)), "(L.x | L.y) & L.z"); EXPECT_EQ(ToDebugString(Or(x, And(y, z))), "L.x | L.y & L.z"); EXPECT_EQ(ToDebugString(Or(And(x, y), z)), "L.x & L.y | L.z"); EXPECT_EQ(ToDebugString(And(x, Or(y, z))), "L.x & (L.y | L.z)"); EXPECT_EQ(ToDebugString(Add(Or(x, y), z)), "(L.x | L.y) + L.z"); EXPECT_EQ(ToDebugString(Or(x, Add(y, z))), "L.x | L.y + L.z"); EXPECT_EQ(ToDebugString(Or(Add(x, y), z)), "L.x + L.y | L.z"); EXPECT_EQ(ToDebugString(Add(x, Or(y, z))), "L.x + (L.y | L.z)"); EXPECT_EQ(ToDebugString(Mul(Or(x, y), z)), "(L.x | L.y) * L.z"); EXPECT_EQ(ToDebugString(Or(x, Mul(y, z))), "L.x | L.y * L.z"); EXPECT_EQ(ToDebugString(Or(Mul(x, y), z)), "L.x * L.y | L.z"); EXPECT_EQ(ToDebugString(Mul(x, Or(y, z))), "L.x * (L.y | L.z)"); EXPECT_EQ(ToDebugString(Pow(Or(x, y), z)), "(L.x | L.y) ** L.z"); EXPECT_EQ(ToDebugString(Or(x, Pow(y, z))), "L.x | L.y ** L.z"); EXPECT_EQ(ToDebugString(Or(Pow(x, y), z)), "L.x ** L.y | L.z"); EXPECT_EQ(ToDebugString(Pow(x, Or(y, z))), "L.x ** (L.y | L.z)"); EXPECT_EQ(ToDebugString(Neg(Or(x, y))), "-(L.x | L.y)"); EXPECT_EQ(ToDebugString(Or(Neg(x), y)), "-L.x | L.y"); EXPECT_EQ(ToDebugString(Or(x, Neg(y))), "L.x | -L.y"); } TEST_F(ExprDebugStringTest, Infix_Binary_LtGroup) { auto x = Leaf("x"); auto y = Leaf("y"); auto z = Leaf("z"); EXPECT_EQ(ToDebugString(Lt(x, y)), "L.x < L.y"); EXPECT_EQ(ToDebugString(Lt(Lt(x, y), z)), "(L.x < L.y) < L.z"); EXPECT_EQ(ToDebugString(Lt(x, Lt(y, z))), "L.x < (L.y < L.z)"); EXPECT_EQ(ToDebugString(Le(x, y)), "L.x <= L.y"); EXPECT_EQ(ToDebugString(Le(Le(x, y), z)), "(L.x <= L.y) <= L.z"); EXPECT_EQ(ToDebugString(Le(x, Le(y, z))), "L.x <= (L.y <= L.z)"); EXPECT_EQ(ToDebugString(Eq(x, y)), "L.x == L.y"); EXPECT_EQ(ToDebugString(Eq(Eq(x, y), z)), "(L.x == L.y) == L.z"); EXPECT_EQ(ToDebugString(Eq(x, Eq(y, z))), "L.x == (L.y == L.z)"); EXPECT_EQ(ToDebugString(Neq(x, y)), "L.x != L.y"); EXPECT_EQ(ToDebugString(Neq(Neq(x, y), z)), "(L.x != L.y) != L.z"); EXPECT_EQ(ToDebugString(Neq(x, Neq(y, z))), "L.x != (L.y != L.z)"); EXPECT_EQ(ToDebugString(Ge(x, y)), "L.x >= L.y"); EXPECT_EQ(ToDebugString(Ge(Ge(x, y), z)), "(L.x >= L.y) >= L.z"); EXPECT_EQ(ToDebugString(Ge(x, Ge(y, z))), "L.x >= (L.y >= L.z)"); EXPECT_EQ(ToDebugString(Gt(x, y)), "L.x > L.y"); EXPECT_EQ(ToDebugString(Gt(Gt(x, y), z)), "(L.x > L.y) > L.z"); EXPECT_EQ(ToDebugString(Gt(x, Gt(y, z))), "L.x > (L.y > L.z)"); EXPECT_EQ(ToDebugString(Le(Lt(x, y), z)), "(L.x < L.y) <= L.z"); EXPECT_EQ(ToDebugString(Lt(x, Le(y, z))), "L.x < (L.y <= L.z)"); EXPECT_EQ(ToDebugString(Lt(Le(x, y), z)), "(L.x <= L.y) < L.z"); EXPECT_EQ(ToDebugString(Le(x, Lt(y, z))), "L.x <= (L.y < L.z)"); EXPECT_EQ(ToDebugString(Eq(Lt(x, y), z)), "(L.x < L.y) == L.z"); EXPECT_EQ(ToDebugString(Lt(x, Eq(y, z))), "L.x < (L.y == L.z)"); EXPECT_EQ(ToDebugString(Lt(Eq(x, y), z)), "(L.x == L.y) < L.z"); EXPECT_EQ(ToDebugString(Eq(x, Lt(y, z))), "L.x == (L.y < L.z)"); EXPECT_EQ(ToDebugString(Neq(Lt(x, y), z)), "(L.x < L.y) != L.z"); EXPECT_EQ(ToDebugString(Lt(x, Neq(y, z))), "L.x < (L.y != L.z)"); EXPECT_EQ(ToDebugString(Lt(Neq(x, y), z)), "(L.x != L.y) < L.z"); EXPECT_EQ(ToDebugString(Neq(x, Lt(y, z))), "L.x != (L.y < L.z)"); EXPECT_EQ(ToDebugString(Ge(Lt(x, y), z)), "(L.x < L.y) >= L.z"); EXPECT_EQ(ToDebugString(Lt(x, Ge(y, z))), "L.x < (L.y >= L.z)"); EXPECT_EQ(ToDebugString(Lt(Ge(x, y), z)), "(L.x >= L.y) < L.z"); EXPECT_EQ(ToDebugString(Ge(x, Lt(y, z))), "L.x >= (L.y < L.z)"); EXPECT_EQ(ToDebugString(Gt(Lt(x, y), z)), "(L.x < L.y) > L.z"); EXPECT_EQ(ToDebugString(Lt(x, Gt(y, z))), "L.x < (L.y > L.z)"); EXPECT_EQ(ToDebugString(Lt(Gt(x, y), z)), "(L.x > L.y) < L.z"); EXPECT_EQ(ToDebugString(Gt(x, Lt(y, z))), "L.x > (L.y < L.z)"); EXPECT_EQ(ToDebugString(Or(Lt(x, y), z)), "(L.x < L.y) | L.z"); EXPECT_EQ(ToDebugString(Lt(x, Or(y, z))), "L.x < L.y | L.z"); EXPECT_EQ(ToDebugString(Lt(Or(x, y), z)), "L.x | L.y < L.z"); EXPECT_EQ(ToDebugString(Or(x, Lt(y, z))), "L.x | (L.y < L.z)"); EXPECT_EQ(ToDebugString(And(Lt(x, y), z)), "(L.x < L.y) & L.z"); EXPECT_EQ(ToDebugString(Lt(x, And(y, z))), "L.x < L.y & L.z"); EXPECT_EQ(ToDebugString(Lt(And(x, y), z)), "L.x & L.y < L.z"); EXPECT_EQ(ToDebugString(And(x, Lt(y, z))), "L.x & (L.y < L.z)"); EXPECT_EQ(ToDebugString(Add(Lt(x, y), z)), "(L.x < L.y) + L.z"); EXPECT_EQ(ToDebugString(Lt(x, Add(y, z))), "L.x < L.y + L.z"); EXPECT_EQ(ToDebugString(Lt(Add(x, y), z)), "L.x + L.y < L.z"); EXPECT_EQ(ToDebugString(Add(x, Lt(y, z))), "L.x + (L.y < L.z)"); EXPECT_EQ(ToDebugString(Mul(Lt(x, y), z)), "(L.x < L.y) * L.z"); EXPECT_EQ(ToDebugString(Lt(x, Mul(y, z))), "L.x < L.y * L.z"); EXPECT_EQ(ToDebugString(Lt(Mul(x, y), z)), "L.x * L.y < L.z"); EXPECT_EQ(ToDebugString(Mul(x, Lt(y, z))), "L.x * (L.y < L.z)"); EXPECT_EQ(ToDebugString(Pow(Lt(x, y), z)), "(L.x < L.y) ** L.z"); EXPECT_EQ(ToDebugString(Lt(x, Pow(y, z))), "L.x < L.y ** L.z"); EXPECT_EQ(ToDebugString(Lt(Pow(x, y), z)), "L.x ** L.y < L.z"); EXPECT_EQ(ToDebugString(Pow(x, Lt(y, z))), "L.x ** (L.y < L.z)"); EXPECT_EQ(ToDebugString(Neg(Lt(x, y))), "-(L.x < L.y)"); EXPECT_EQ(ToDebugString(Lt(Neg(x), y)), "-L.x < L.y"); EXPECT_EQ(ToDebugString(Lt(x, Neg(y))), "L.x < -L.y"); } TEST_F(ExprDebugStringTest, Infix_GetAttr) { auto x = Leaf("x"); auto y = Leaf("y"); auto one = Literal<int>(1); auto foo = Literal(Text("foo")); auto bar = Literal(Text("bar")); EXPECT_EQ(ToDebugString(GetAttr(x, foo)), "L.x.foo"); EXPECT_EQ(ToDebugString(GetAttr(GetAttr(x, foo), bar)), "L.x.foo.bar"); EXPECT_EQ(ToDebugString(GetAttr(one, foo)), "(1).foo"); EXPECT_EQ(ToDebugString(GetAttr(foo, bar)), "'foo'.bar"); EXPECT_EQ(ToDebugString(Lt(GetAttr(x, foo), y)), "L.x.foo < L.y"); EXPECT_EQ(ToDebugString(Lt(x, GetAttr(y, bar))), "L.x < L.y.bar"); EXPECT_EQ(ToDebugString(GetAttr(Lt(x, y), foo)), "(L.x < L.y).foo"); EXPECT_EQ(ToDebugString(Or(GetAttr(x, foo), y)), "L.x.foo | L.y"); EXPECT_EQ(ToDebugString(Or(x, GetAttr(y, bar))), "L.x | L.y.bar"); EXPECT_EQ(ToDebugString(GetAttr(Or(x, y), foo)), "(L.x | L.y).foo"); EXPECT_EQ(ToDebugString(And(GetAttr(x, foo), y)), "L.x.foo & L.y"); EXPECT_EQ(ToDebugString(And(x, GetAttr(y, bar))), "L.x & L.y.bar"); EXPECT_EQ(ToDebugString(GetAttr(And(x, y), foo)), "(L.x & L.y).foo"); EXPECT_EQ(ToDebugString(Add(GetAttr(x, foo), y)), "L.x.foo + L.y"); EXPECT_EQ(ToDebugString(Add(x, GetAttr(y, bar))), "L.x + L.y.bar"); EXPECT_EQ(ToDebugString(GetAttr(Add(x, y), foo)), "(L.x + L.y).foo"); EXPECT_EQ(ToDebugString(Mul(GetAttr(x, foo), y)), "L.x.foo * L.y"); EXPECT_EQ(ToDebugString(Mul(x, GetAttr(y, bar))), "L.x * L.y.bar"); EXPECT_EQ(ToDebugString(GetAttr(Mul(x, y), foo)), "(L.x * L.y).foo"); EXPECT_EQ(ToDebugString(Pow(GetAttr(x, foo), y)), "L.x.foo ** L.y"); EXPECT_EQ(ToDebugString(Pow(x, GetAttr(y, bar))), "L.x ** L.y.bar"); EXPECT_EQ(ToDebugString(GetAttr(Pow(x, y), foo)), "(L.x ** L.y).foo"); EXPECT_EQ(ToDebugString(Neg(GetAttr(x, foo))), "-L.x.foo"); EXPECT_EQ(ToDebugString(GetAttr(Neg(x), foo)), "(-L.x).foo"); } TEST_F(ExprDebugStringTest, Infix_GetItem) { auto x = Leaf("x"); auto y = Leaf("y"); auto one = Literal<int>(1); auto foo = Literal(Text("foo")); auto bar = Literal(Text("bar")); EXPECT_EQ(ToDebugString(GetItem(x, foo)), "L.x['foo']"); EXPECT_EQ(ToDebugString(GetItem(x, y)), "L.x[L.y]"); EXPECT_EQ(ToDebugString(GetItem(GetItem(x, foo), bar)), "L.x['foo']['bar']"); EXPECT_EQ(ToDebugString(GetItem(one, foo)), "(1)['foo']"); EXPECT_EQ(ToDebugString(GetItem(foo, bar)), "'foo'['bar']"); EXPECT_EQ(ToDebugString(GetItem(CallOp("math.max", {x, y}).value(), bar)), "M.math.max(L.x, L.y)['bar']"); EXPECT_EQ(ToDebugString(Lt(GetItem(x, foo), y)), "L.x['foo'] < L.y"); EXPECT_EQ(ToDebugString(Lt(x, GetItem(y, bar))), "L.x < L.y['bar']"); EXPECT_EQ(ToDebugString(GetItem(Lt(x, y), foo)), "(L.x < L.y)['foo']"); EXPECT_EQ(ToDebugString(Or(GetItem(x, foo), y)), "L.x['foo'] | L.y"); EXPECT_EQ(ToDebugString(Or(x, GetItem(y, bar))), "L.x | L.y['bar']"); EXPECT_EQ(ToDebugString(GetItem(Or(x, y), foo)), "(L.x | L.y)['foo']"); EXPECT_EQ(ToDebugString(And(GetItem(x, foo), y)), "L.x['foo'] & L.y"); EXPECT_EQ(ToDebugString(And(x, GetItem(y, bar))), "L.x & L.y['bar']"); EXPECT_EQ(ToDebugString(GetItem(And(x, y), foo)), "(L.x & L.y)['foo']"); EXPECT_EQ(ToDebugString(Add(GetItem(x, foo), y)), "L.x['foo'] + L.y"); EXPECT_EQ(ToDebugString(Add(x, GetItem(y, bar))), "L.x + L.y['bar']"); EXPECT_EQ(ToDebugString(GetItem(Add(x, y), foo)), "(L.x + L.y)['foo']"); EXPECT_EQ(ToDebugString(Mul(GetItem(x, foo), y)), "L.x['foo'] * L.y"); EXPECT_EQ(ToDebugString(Mul(x, GetItem(y, bar))), "L.x * L.y['bar']"); EXPECT_EQ(ToDebugString(GetItem(Mul(x, y), foo)), "(L.x * L.y)['foo']"); EXPECT_EQ(ToDebugString(Pow(GetItem(x, foo), y)), "L.x['foo'] ** L.y"); EXPECT_EQ(ToDebugString(Pow(x, GetItem(y, bar))), "L.x ** L.y['bar']"); EXPECT_EQ(ToDebugString(GetItem(Pow(x, y), foo)), "(L.x ** L.y)['foo']"); EXPECT_EQ(ToDebugString(Neg(GetItem(x, foo))), "-L.x['foo']"); EXPECT_EQ(ToDebugString(GetItem(Neg(x), foo)), "(-L.x)['foo']"); EXPECT_EQ(ToDebugString(GetAttr(GetItem(x, foo), bar)), "L.x['foo'].bar"); EXPECT_EQ(ToDebugString(GetItem(x, GetAttr(y, foo))), "L.x[L.y.foo]"); EXPECT_EQ(ToDebugString(GetItem(GetAttr(x, foo), bar)), "L.x.foo['bar']"); EXPECT_EQ(ToDebugString(GetItem(x, MakeSlice(one, foo, bar))), "L.x[1:'foo':'bar']"); } TEST_F(ExprDebugStringTest, Infix_MakeSlice) { auto x = Leaf("x"); auto y = Leaf("y"); auto u = Literal(GetUnspecifiedQValue()); auto one = Literal<int>(1); auto two = Literal<int>(2); auto three = Literal<int>(3); EXPECT_EQ(ToDebugString(MakeSlice(u, u, u)), "M.core.make_slice(unspecified, unspecified, unspecified)"); EXPECT_EQ(ToDebugString(MakeSlice(one, two, three)), "M.core.make_slice(1, 2, 3)"); EXPECT_EQ(ToDebugString(GetItem(x, MakeSlice(u, u, u))), "L.x[:]"); EXPECT_EQ(ToDebugString(GetItem(x, MakeSlice(one, u, u))), "L.x[1:]"); EXPECT_EQ(ToDebugString(GetItem(x, MakeSlice(u, one, u))), "L.x[:1]"); EXPECT_EQ(ToDebugString(GetItem(x, MakeSlice(u, u, one))), "L.x[::1]"); EXPECT_EQ(ToDebugString(GetItem(x, MakeSlice(one, two, u))), "L.x[1:2]"); EXPECT_EQ(ToDebugString(GetItem(x, MakeSlice(one, u, two))), "L.x[1::2]"); EXPECT_EQ(ToDebugString(GetItem(x, MakeSlice(u, one, two))), "L.x[:1:2]"); EXPECT_EQ(ToDebugString(GetItem(x, MakeSlice(one, two, three))), "L.x[1:2:3]"); EXPECT_EQ(ToDebugString(GetItem(x, MakeSlice(Add(one, x), two, three))), "L.x[1 + L.x:2:3]"); EXPECT_EQ(ToDebugString(GetItem(x, MakeSlice(one, Add(two, x), three))), "L.x[1:2 + L.x:3]"); EXPECT_EQ(ToDebugString(GetItem(x, MakeSlice(one, two, Add(three, x)))), "L.x[1:2:3 + L.x]"); EXPECT_EQ(ToDebugString(GetItem(x, MakeSlice(Gt(one, x), two, three))), "L.x[1 > L.x:2:3]"); EXPECT_EQ(ToDebugString(GetItem(x, MakeSlice(one, Gt(two, x), three))), "L.x[1:2 > L.x:3]"); EXPECT_EQ(ToDebugString(GetItem(x, MakeSlice(one, two, Gt(three, x)))), "L.x[1:2:3 > L.x]"); auto d = Literal(DummyWithPrecedence{}); EXPECT_EQ(ToDebugString(GetItem(x, MakeSlice(d, u, u))), "L.x[dummy-with-precedence:]"); EXPECT_EQ(ToDebugString(GetItem(x, MakeSlice(u, d, u))), "L.x[:dummy-with-precedence]"); EXPECT_EQ(ToDebugString(GetItem(x, MakeSlice(u, u, d))), "L.x[::dummy-with-precedence]"); auto d11 = Literal(DummyWithPrecedence{.precedence = ReprToken::Precedence{11, 11}}); EXPECT_EQ(ToDebugString(GetItem(x, MakeSlice(d11, u, u))), "L.x[(dummy-with-precedence):]"); EXPECT_EQ(ToDebugString(GetItem(x, MakeSlice(u, d11, u))), "L.x[:(dummy-with-precedence)]"); EXPECT_EQ(ToDebugString(GetItem(x, MakeSlice(u, u, d11))), "L.x[::(dummy-with-precedence)]"); EXPECT_EQ(ToDebugString(GetItem(x, MakeSlice(d11, d11, u))), "L.x[(dummy-with-precedence):(dummy-with-precedence)]"); EXPECT_EQ(ToDebugString(GetItem(x, MakeSlice(d11, u, d11))), "L.x[(dummy-with-precedence)::(dummy-with-precedence)]"); EXPECT_EQ(ToDebugString(GetItem(x, MakeSlice(u, d11, d11))), "L.x[:(dummy-with-precedence):(dummy-with-precedence)]"); EXPECT_EQ(ToDebugString(GetItem(x, MakeSlice(d11, d11, d11))), "L.x[(dummy-with-precedence):(dummy-with-precedence):(dummy-with-" "precedence)]"); } TEST_F(ExprDebugStringTest, Infix_Binary_NonInfix) { auto x = Leaf("x"); auto foo = Literal(Text("foo")); ASSERT_OK_AND_ASSIGN(auto op, LookupOperator("core.getattr")); EXPECT_EQ(ToDebugString(ExprNode::UnsafeMakeOperatorNode(op, {x, x}, {})), "M.core.getattr(L.x, L.x)"); EXPECT_EQ(ToDebugString(ExprNode::UnsafeM
2,432
#ifndef AROLLA_EXPR_DERIVED_CAST_OPERATOR_H_ #define AROLLA_EXPR_DERIVED_CAST_OPERATOR_H_ #include "absl/status/statusor.h" #include "absl/types/span.h" #include "arolla/expr/basic_expr_operator.h" #include "arolla/expr/expr_operator.h" #include "arolla/qtype/qtype.h" namespace arolla::expr { class DerivedQTypeUpcastOperator final : public BuiltinExprOperatorTag, public BasicExprOperator { public: static absl::StatusOr<QTypePtr> GetOutputQType(QTypePtr derived_qtype, QTypePtr value_qtype); explicit DerivedQTypeUpcastOperator(QTypePtr derived_qtype); absl::StatusOr<QTypePtr> GetOutputQType( absl::Span<const QTypePtr> input_qtypes) const final; QTypePtr derived_qtype() const; private: QTypePtr derived_qtype_; }; class DerivedQTypeDowncastOperator final : public BuiltinExprOperatorTag, public BasicExprOperator { public: static absl::StatusOr<QTypePtr> GetOutputQType(QTypePtr derived_qtype, QTypePtr value_qtype); explicit DerivedQTypeDowncastOperator(QTypePtr derived_qtype); absl::StatusOr<QTypePtr> GetOutputQType( absl::Span<const QTypePtr> input_qtypes) const final; QTypePtr derived_qtype() const; private: QTypePtr derived_qtype_; }; } #endif #include "arolla/expr/derived_qtype_cast_operator.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "absl/types/span.h" #include "arolla/expr/basic_expr_operator.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/qtype/derived_qtype.h" #include "arolla/qtype/qtype.h" #include "arolla/util/fingerprint.h" namespace arolla::expr { absl::StatusOr<QTypePtr> DerivedQTypeUpcastOperator::GetOutputQType( QTypePtr derived_qtype, QTypePtr value_qtype) { if (value_qtype == derived_qtype) { return DecayDerivedQType(derived_qtype); } return absl::InvalidArgumentError( absl::StrFormat("expected %s, got value: %s", derived_qtype->name(), value_qtype->name())); } DerivedQTypeUpcastOperator::DerivedQTypeUpcastOperator(QTypePtr derived_qtype) : BasicExprOperator( absl::StrFormat("derived_qtype.upcast[%s]", derived_qtype->name()), ExprOperatorSignature{{"value"}}, "Casts a derived value to the base type.", FingerprintHasher("arolla::expr::DerivedQTypeUpcastOperator") .Combine(derived_qtype) .Finish()), derived_qtype_(derived_qtype) {} absl::StatusOr<QTypePtr> DerivedQTypeUpcastOperator::GetOutputQType( absl::Span<const QTypePtr> input_qtypes) const { return DerivedQTypeUpcastOperator::GetOutputQType(derived_qtype_, input_qtypes[0]); } QTypePtr DerivedQTypeUpcastOperator::derived_qtype() const { return derived_qtype_; } absl::StatusOr<QTypePtr> DerivedQTypeDowncastOperator::GetOutputQType( QTypePtr derived_qtype, QTypePtr value_qtype) { const auto* base_qtype = DecayDerivedQType(derived_qtype); if (value_qtype == base_qtype) { return derived_qtype; } return absl::InvalidArgumentError(absl::StrFormat( "expected %s, got value: %s", base_qtype->name(), value_qtype->name())); } DerivedQTypeDowncastOperator::DerivedQTypeDowncastOperator( QTypePtr derived_qtype) : BasicExprOperator( absl::StrFormat("derived_qtype.downcast[%s]", derived_qtype->name()), ExprOperatorSignature{{"value"}}, "Casts a base qtype value to the derived qtype.", FingerprintHasher("arolla::expr::DerivedQTypeDowncastOperator") .Combine(derived_qtype) .Finish()), derived_qtype_(derived_qtype) {} absl::StatusOr<QTypePtr> DerivedQTypeDowncastOperator::GetOutputQType( absl::Span<const QTypePtr> input_qtypes) const { return DerivedQTypeDowncastOperator::GetOutputQType(derived_qtype_, input_qtypes[0]); } QTypePtr DerivedQTypeDowncastOperator::derived_qtype() const { return derived_qtype_; } }
#include "arolla/expr/derived_qtype_cast_operator.h" #include <memory> #include <string> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/testing/testing.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/derived_qtype.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/typed_value.h" #include "arolla/util/indestructible.h" #include "arolla/util/init_arolla.h" #include "arolla/util/repr.h" #include "arolla/util/testing/repr_token_eq.h" #include "arolla/util/testing/status_matchers_backport.h" namespace arolla::expr { namespace { using ::arolla::testing::InvokeExprOperator; using ::arolla::testing::ReprTokenEq; using ::arolla::testing::StatusIs; using ::testing::HasSubstr; struct TimeQType final : BasicDerivedQType { TimeQType() : BasicDerivedQType(ConstructorArgs{ .name = "TIME", .base_qtype = GetQType<float>(), }) {} ReprToken UnsafeReprToken(const void* source) const override { auto result = GetBaseQType()->UnsafeReprToken(source); result.str += "s"; return result; } static QTypePtr get() { static const Indestructible<TimeQType> result; return result.get(); } }; struct DistanceQType final : BasicDerivedQType { DistanceQType() : BasicDerivedQType(ConstructorArgs{ .name = "DISTANCE", .base_qtype = GetQType<float>(), }) {} ReprToken UnsafeReprToken(const void* source) const override { auto result = GetBaseQType()->UnsafeReprToken(source); result.str += "m"; return result; } static QTypePtr get() { static const Indestructible<DistanceQType> result; return result.get(); } }; class DerivedQTypeCastOperatorTests : public ::testing::Test { void SetUp() override { ASSERT_OK(InitArolla()); } }; TEST_F(DerivedQTypeCastOperatorTests, UpcastDistance_WithDistanceInput) { ExprOperatorPtr upcast_distance = std::make_shared<DerivedQTypeUpcastOperator>(DistanceQType::get()); ASSERT_OK_AND_ASSIGN( auto d, TypedValue::FromValueWithQType(6.28f, DistanceQType::get())); ASSERT_OK_AND_ASSIGN(auto f32, InvokeExprOperator<TypedValue>(upcast_distance, d)); EXPECT_EQ(f32.GetType(), GetQType<float>()); EXPECT_THAT(f32.GenReprToken(), ReprTokenEq("6.28", ReprToken::kSafeForNegation)); } TEST_F(DerivedQTypeCastOperatorTests, UpcastDistance_WithFloat32Input) { ExprOperatorPtr upcast_distance = std::make_shared<DerivedQTypeUpcastOperator>(DistanceQType::get()); EXPECT_THAT(InvokeExprOperator<TypedValue>(upcast_distance, 6.28f), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("expected DISTANCE, got value: FLOAT32"))); } TEST_F(DerivedQTypeCastOperatorTests, UpcastFloat32_WithDistanceInput) { ExprOperatorPtr upcast_float32 = std::make_shared<DerivedQTypeUpcastOperator>(GetQType<float>()); ASSERT_OK_AND_ASSIGN( auto d, TypedValue::FromValueWithQType(6.28f, DistanceQType::get())); EXPECT_THAT(InvokeExprOperator<TypedValue>(upcast_float32, d), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("expected FLOAT32, got value: DISTANCE"))); } TEST_F(DerivedQTypeCastOperatorTests, UpcastFloat32_WithFloat32Input) { ExprOperatorPtr upcast_float32 = std::make_shared<DerivedQTypeUpcastOperator>(GetQType<float>()); ASSERT_OK_AND_ASSIGN(auto f32, InvokeExprOperator<TypedValue>(upcast_float32, 6.28f)); EXPECT_EQ(f32.GetType(), GetQType<float>()); EXPECT_THAT(f32.GenReprToken(), ReprTokenEq("6.28", ReprToken::kSafeForNegation)); } TEST_F(DerivedQTypeCastOperatorTests, DowncastDistance_WithDistanceInput) { ExprOperatorPtr downcast_distance = std::make_shared<DerivedQTypeDowncastOperator>(DistanceQType::get()); ASSERT_OK_AND_ASSIGN( auto d, TypedValue::FromValueWithQType(6.28f, DistanceQType::get())); EXPECT_THAT(InvokeExprOperator<TypedValue>(downcast_distance, d), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("expected FLOAT32, got value: DISTANCE"))); } TEST_F(DerivedQTypeCastOperatorTests, DowncastDistance_WithFloat32Input) { ExprOperatorPtr downcast_distance = std::make_shared<DerivedQTypeDowncastOperator>(DistanceQType::get()); ASSERT_OK_AND_ASSIGN( auto d, InvokeExprOperator<TypedValue>(downcast_distance, 6.28f)); EXPECT_EQ(d.GetType(), DistanceQType::get()); EXPECT_THAT(d.GenReprToken(), ReprTokenEq("6.28m", ReprToken::kSafeForNegation)); } TEST_F(DerivedQTypeCastOperatorTests, DowncastFloat32_WithDistanceInput) { ExprOperatorPtr downcast_float32 = std::make_shared<DerivedQTypeDowncastOperator>(GetQType<float>()); ASSERT_OK_AND_ASSIGN( auto d, TypedValue::FromValueWithQType(6.28f, DistanceQType::get())); EXPECT_THAT(InvokeExprOperator<TypedValue>(downcast_float32, d), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("expected FLOAT32, got value: DISTANCE"))); } TEST_F(DerivedQTypeCastOperatorTests, DowncastFloat32_WithFloat32Input) { ExprOperatorPtr downcast_float32 = std::make_shared<DerivedQTypeDowncastOperator>(GetQType<float>()); ASSERT_OK_AND_ASSIGN(auto f32, InvokeExprOperator<TypedValue>(downcast_float32, 6.28f)); EXPECT_EQ(f32.GetType(), GetQType<float>()); EXPECT_THAT(f32.GenReprToken(), ReprTokenEq("6.28", ReprToken::kSafeForNegation)); } } }
2,433
#ifndef AROLLA_EXPR_EXPR_OPERATOR_SIGNATURE_H_ #define AROLLA_EXPR_EXPR_OPERATOR_SIGNATURE_H_ #include <cstddef> #include <initializer_list> #include <optional> #include <string> #include <type_traits> #include <vector> #include "absl/base/attributes.h" #include "absl/container/flat_hash_map.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "arolla/expr/expr_node_ptr.h" #include "arolla/qtype/typed_value.h" #include "arolla/util/fingerprint.h" namespace arolla::expr { struct ExprOperatorSignature { struct Parameter { enum class Kind { kPositionalOrKeyword, kVariadicPositional, }; std::string name; std::optional<TypedValue> default_value; Kind kind = {Kind::kPositionalOrKeyword}; }; std::vector<Parameter> parameters; std::string aux_policy; ExprOperatorSignature() = default; ExprOperatorSignature(std::initializer_list<Parameter> parameters) : parameters(parameters) {} static ExprOperatorSignature MakeArgsN(size_t n); static ExprOperatorSignature MakeVariadicArgs(); static absl::StatusOr<ExprOperatorSignature> Make( absl::string_view signature_spec, absl::Span<const TypedValue> default_values); template <typename... DefaultValues> static auto Make(absl::string_view signature_spec, DefaultValues&&... default_values) -> std::enable_if_t<!(std::is_convertible_v< DefaultValues, absl::Span<const TypedValue>> && ... && (sizeof...(DefaultValues) == 1)), absl::StatusOr<ExprOperatorSignature>> { constexpr auto wrap_arg ABSL_ATTRIBUTE_UNUSED = [](const auto& arg) -> TypedValue { if constexpr (std::is_same_v<decltype(arg), const TypedValue&>) { return arg; } else { return TypedValue::FromValue(arg); } }; return ExprOperatorSignature::Make( signature_spec, std::initializer_list<TypedValue>{wrap_arg(default_values)...}); } }; absl::Status ValidateSignature(const ExprOperatorSignature& signature); absl::Status ValidateDepsCount(const ExprOperatorSignature& signature, size_t deps_count, absl::StatusCode error_code); bool HasVariadicParameter(const ExprOperatorSignature& signature); absl::StatusOr<std::vector<ExprNodePtr>> BindArguments( const ExprOperatorSignature& signature, absl::Span<const ExprNodePtr> args, const absl::flat_hash_map<std::string, ExprNodePtr>& kwargs); std::string GetExprOperatorSignatureSpec( const ExprOperatorSignature& signature); } namespace arolla { AROLLA_DECLARE_FINGERPRINT_HASHER_TRAITS(arolla::expr::ExprOperatorSignature); } #endif #include "arolla/expr/expr_operator_signature.h" #include <algorithm> #include <cstddef> #include <optional> #include <sstream> #include <string> #include <utility> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/container/flat_hash_set.h" #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/ascii.h" #include "absl/strings/escaping.h" #include "absl/strings/match.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" #include "absl/strings/str_join.h" #include "absl/strings/str_split.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_node.h" #include "arolla/qtype/typed_value.h" #include "arolla/util/fingerprint.h" #include "arolla/util/string.h" #include "arolla/util/status_macros_backport.h" namespace arolla::expr { namespace { using Param = ExprOperatorSignature::Parameter; absl::Status ValidateSignatureParameterNames( const ExprOperatorSignature& signature) { for (const auto& param : signature.parameters) { if (!IsIdentifier(param.name)) { return absl::InvalidArgumentError(absl::StrCat( "illegal parameter name: '", absl::CEscape(param.name), "'")); } } absl::flat_hash_set<absl::string_view> param_names; param_names.reserve(signature.parameters.size()); for (const auto& param : signature.parameters) { if (!param_names.insert(param.name).second) { return absl::InvalidArgumentError( absl::StrCat("non-unique parameter name: '", param.name, "'")); } } return absl::OkStatus(); } absl::Status ValidateSignatureParameterKinds( const ExprOperatorSignature& signature) { for (const auto& param : signature.parameters) { if (param.kind != Param::Kind::kPositionalOrKeyword && param.kind != Param::Kind::kVariadicPositional) { return absl::InvalidArgumentError( absl::StrCat("parameter '", param.name, "' has illegal kind: ", static_cast<int>(param.kind))); } } return absl::OkStatus(); } absl::Status ValidateSignaturePositionalOrKeywordParameters( const ExprOperatorSignature& signature) { bool had_default_value = false; for (const auto& param : signature.parameters) { if (param.kind != Param::Kind::kPositionalOrKeyword) { break; } if (!param.default_value.has_value()) { if (had_default_value) { return absl::InvalidArgumentError( "parameter without a default value goes after a parameter with " "a default value"); } } else { had_default_value = true; } } return absl::OkStatus(); } absl::Status ValidateSignatureVariadicParameters( const ExprOperatorSignature& signature) { for (size_t i = 0; i + 1 < signature.parameters.size(); ++i) { if (signature.parameters[i].kind == Param::Kind::kVariadicPositional) { return absl::InvalidArgumentError("variadic parameter must be the last"); } } if (!signature.parameters.empty() && signature.parameters.back().kind == Param::Kind::kVariadicPositional && signature.parameters.back().default_value.has_value()) { return absl::InvalidArgumentError( "variadic parameter cannot have a default value"); } return absl::OkStatus(); } } absl::Status ValidateSignature(const ExprOperatorSignature& signature) { RETURN_IF_ERROR(ValidateSignatureParameterNames(signature)); RETURN_IF_ERROR(ValidateSignatureParameterKinds(signature)); RETURN_IF_ERROR(ValidateSignaturePositionalOrKeywordParameters(signature)); RETURN_IF_ERROR(ValidateSignatureVariadicParameters(signature)); return absl::OkStatus(); } bool HasVariadicParameter(const ExprOperatorSignature& signature) { return !signature.parameters.empty() && signature.parameters.back().kind == Param::Kind::kVariadicPositional; } namespace { absl::Status MultipleValuesForArgumentError(absl::string_view name) { return absl::InvalidArgumentError( absl::StrCat("multiple values for argument: '", name, "'")); } absl::Status UnexpectedParameterKindError(Param::Kind kind) { return absl::InternalError( absl::StrCat("unexpected parameter kind: ", static_cast<int>(kind))); } absl::Status UnexpectedKeywordArgumentsError( std::vector<absl::string_view> unexpected_keyword_arguments) { if (unexpected_keyword_arguments.size() == 1) { return absl::InvalidArgumentError( absl::StrCat("unexpected keyword argument: '", unexpected_keyword_arguments[0], "'")); } std::sort(unexpected_keyword_arguments.begin(), unexpected_keyword_arguments.end()); return absl::InvalidArgumentError( absl::StrCat("unexpected keyword arguments: '", absl::StrJoin(unexpected_keyword_arguments, "', '"), "'")); } absl::Status MissingArgumentsError( absl::Span<const absl::string_view> missing_arguments) { if (missing_arguments.size() == 1) { return absl::InvalidArgumentError(absl::StrCat( "missing 1 required argument: '", missing_arguments[0], "'")); } return absl::InvalidArgumentError(absl::StrCat( "missing ", missing_arguments.size(), " required arguments: '", absl::StrJoin(missing_arguments, "', '"), "'")); } } absl::Status ValidateDepsCount(const ExprOperatorSignature& signature, size_t deps_count, absl::StatusCode error_code) { const bool has_variadic_param = HasVariadicParameter(signature); size_t count_required_params = has_variadic_param ? signature.parameters.size() - 1 : signature.parameters.size(); if (deps_count < count_required_params || (!has_variadic_param && deps_count > count_required_params)) { return absl::Status( error_code, absl::StrFormat("incorrect number of dependencies passed to an " "operator node: expected %d but got %d", count_required_params, deps_count)); } return absl::OkStatus(); } absl::StatusOr<std::vector<ExprNodePtr>> BindArguments( const ExprOperatorSignature& signature, absl::Span<const ExprNodePtr> args, const absl::flat_hash_map<std::string, ExprNodePtr>& kwargs) { DCHECK_OK(ValidateSignature(signature)); std::vector<ExprNodePtr> result; result.reserve(args.size() + kwargs.size()); size_t paramIdx = 0; size_t argIdx = 0; for (; paramIdx < signature.parameters.size() && argIdx < args.size(); ++paramIdx) { const auto& param = signature.parameters[paramIdx]; if (param.kind == Param::Kind::kPositionalOrKeyword) { if (kwargs.count(param.name) != 0) { return MultipleValuesForArgumentError(param.name); } result.push_back(args[argIdx++]); } else if (param.kind == Param::Kind::kVariadicPositional) { result.insert(result.end(), args.begin() + argIdx, args.end()); argIdx = args.size(); } else { return UnexpectedParameterKindError(param.kind); } } if (argIdx < args.size()) { return absl::InvalidArgumentError(absl::StrCat( "too many positional arguments passed: expected maximumum is ", result.size(), " but got ", args.size())); } std::vector<absl::string_view> missing_arguments; absl::flat_hash_set<absl::string_view> used_kwargs; used_kwargs.reserve(args.size() + kwargs.size()); for (; paramIdx < signature.parameters.size(); ++paramIdx) { const auto& param = signature.parameters[paramIdx]; if (param.kind == Param::Kind::kPositionalOrKeyword) { if (const auto it = kwargs.find(param.name); it != kwargs.end()) { used_kwargs.insert(param.name); result.push_back(it->second); } else if (param.default_value.has_value()) { result.push_back(Literal(*param.default_value)); } else { missing_arguments.push_back(param.name); } } else if (param.kind != Param::Kind::kVariadicPositional) { return UnexpectedParameterKindError(param.kind); } } std::vector<absl::string_view> unexpected_keyword_arguments; for (const auto& kv : kwargs) { if (!used_kwargs.contains(kv.first)) { unexpected_keyword_arguments.push_back(kv.first); } } if (!unexpected_keyword_arguments.empty()) { return UnexpectedKeywordArgumentsError( std::move(unexpected_keyword_arguments)); } if (!missing_arguments.empty()) { return MissingArgumentsError(missing_arguments); } return result; } ExprOperatorSignature ExprOperatorSignature::MakeArgsN(size_t n) { ExprOperatorSignature result; if (n == 1) { result.parameters.push_back({absl::StrCat("arg")}); } else { for (size_t i = 0; i < n; ++i) { result.parameters.push_back({absl::StrCat("arg", i + 1)}); } } return result; } ExprOperatorSignature ExprOperatorSignature::MakeVariadicArgs() { return ExprOperatorSignature{ {"args", std::nullopt, ExprOperatorSignature::Parameter::Kind::kVariadicPositional}}; } absl::StatusOr<ExprOperatorSignature> ExprOperatorSignature::Make( absl::string_view signature_spec, absl::Span<const TypedValue> default_values) { ExprOperatorSignature result; signature_spec = absl::StripAsciiWhitespace(signature_spec); if (auto pos = signature_spec.rfind('|'); pos < signature_spec.size()) { result.aux_policy = std::string(absl::StripAsciiWhitespace(signature_spec.substr(pos + 1))); signature_spec = absl::StripAsciiWhitespace(signature_spec.substr(0, pos)); } std::vector<absl::string_view> param_defs; if (!signature_spec.empty()) { param_defs = absl::StrSplit(signature_spec, ','); } size_t i = 0; for (auto param_def : param_defs) { Param param; param_def = absl::StripAsciiWhitespace(param_def); if (absl::StartsWith(param_def, "*")) { param_def = absl::StripLeadingAsciiWhitespace(param_def.substr(1)); param.kind = Param::Kind::kVariadicPositional; } else { param.kind = Param::Kind::kPositionalOrKeyword; } if (absl::EndsWith(param_def, "=")) { param_def = absl::StripTrailingAsciiWhitespace( param_def.substr(0, param_def.size() - 1)); if (i >= default_values.size()) { return absl::InvalidArgumentError(absl::StrCat( "default value expected, but not provided for parameter: '", param_def, "'")); } param.default_value = default_values[i]; i += 1; } param.name = std::string(param_def); result.parameters.push_back(std::move(param)); } if (i != default_values.size()) { return absl::InvalidArgumentError( "some of the provided default values left unused"); } RETURN_IF_ERROR(ValidateSignature(result)); return result; } std::string GetExprOperatorSignatureSpec( const ExprOperatorSignature& signature) { std::ostringstream result; bool first = true; for (const auto& param : signature.parameters) { result << NonFirstComma(first); switch (param.kind) { case Param::Kind::kPositionalOrKeyword: break; case Param::Kind::kVariadicPositional: result << '*'; } result << param.name; if (param.default_value.has_value()) { result << '='; } } if (!signature.aux_policy.empty()) { result << "|" << signature.aux_policy; } return std::move(result).str(); } } namespace arolla { void FingerprintHasherTraits<expr::ExprOperatorSignature>::operator()( FingerprintHasher* hasher, const expr::ExprOperatorSignature& signature) const { hasher->Combine(signature.parameters.size()); for (const auto& param : signature.parameters) { hasher->Combine(param.name, param.kind); hasher->Combine(param.default_value ? param.default_value->GetFingerprint() : Fingerprint{}); } hasher->Combine(signature.aux_policy); } }
#include "arolla/expr/expr_operator_signature.h" #include <cstddef> #include <optional> #include <string> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/container/flat_hash_map.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_join.h" #include "absl/strings/str_split.h" #include "absl/strings/string_view.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_debug_string.h" #include "arolla/expr/expr_node.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/testing/qtype.h" #include "arolla/util/fingerprint.h" #include "arolla/util/testing/status_matchers_backport.h" #include "arolla/util/unit.h" #include "arolla/util/status_macros_backport.h" namespace arolla::expr { namespace { using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::StatusIs; using ::arolla::testing::TypedValueWith; using ::testing::HasSubstr; using ::testing::Optional; TEST(ExprOperatorSignature, HasVariadicParameter) { ExprOperatorSignature sig; EXPECT_FALSE(HasVariadicParameter(sig)); sig.parameters.push_back({"arg"}); EXPECT_FALSE(HasVariadicParameter(sig)); sig.parameters.push_back( {"*args", std::nullopt, ExprOperatorSignature::Parameter::Kind::kVariadicPositional}); EXPECT_TRUE(HasVariadicParameter(sig)); } TEST(ExprOperatorSignature, ExprOperatorSignature_MakeArgsN) { using Kind = ExprOperatorSignature::Parameter::Kind; { const auto sig = ExprOperatorSignature::MakeArgsN(0); EXPECT_TRUE(sig.parameters.empty()); EXPECT_TRUE(sig.aux_policy.empty()); } { const auto sig = ExprOperatorSignature::MakeArgsN(1); EXPECT_EQ(sig.parameters.size(), 1); EXPECT_EQ(sig.parameters[0].name, "arg"); EXPECT_EQ(sig.parameters[0].default_value, std::nullopt); EXPECT_EQ(sig.parameters[0].kind, Kind::kPositionalOrKeyword); EXPECT_TRUE(sig.aux_policy.empty()); } { const auto sig = ExprOperatorSignature::MakeArgsN(3); EXPECT_EQ(sig.parameters.size(), 3); EXPECT_EQ(sig.parameters[0].name, "arg1"); EXPECT_EQ(sig.parameters[0].default_value, std::nullopt); EXPECT_EQ(sig.parameters[0].kind, Kind::kPositionalOrKeyword); EXPECT_EQ(sig.parameters[1].name, "arg2"); EXPECT_EQ(sig.parameters[1].default_value, std::nullopt); EXPECT_EQ(sig.parameters[1].kind, Kind::kPositionalOrKeyword); EXPECT_EQ(sig.parameters[2].name, "arg3"); EXPECT_EQ(sig.parameters[2].default_value, std::nullopt); EXPECT_EQ(sig.parameters[2].kind, Kind::kPositionalOrKeyword); EXPECT_TRUE(sig.aux_policy.empty()); } } TEST(ExprOperatorSignature, ExprOperatorSignature_MakeVariadicArgs) { using Kind = ExprOperatorSignature::Parameter::Kind; const auto sig = ExprOperatorSignature::MakeVariadicArgs(); EXPECT_EQ(sig.parameters.size(), 1); EXPECT_EQ(sig.parameters[0].name, "args"); EXPECT_EQ(sig.parameters[0].default_value, std::nullopt); EXPECT_EQ(sig.parameters[0].kind, Kind::kVariadicPositional); EXPECT_TRUE(sig.aux_policy.empty()); } TEST(ExprOperatorSignature, ExprOperatorSignature_Make) { using Sig = ExprOperatorSignature; using Kind = ExprOperatorSignature::Parameter::Kind; { ASSERT_OK_AND_ASSIGN(const auto sig, Sig::Make("")); EXPECT_TRUE(sig.parameters.empty()); EXPECT_TRUE(sig.aux_policy.empty()); } { ASSERT_OK_AND_ASSIGN(const auto sig, Sig::Make("arg")); EXPECT_EQ(sig.parameters.size(), 1); EXPECT_EQ(sig.parameters[0].name, "arg"); EXPECT_EQ(sig.parameters[0].default_value, std::nullopt); EXPECT_EQ(sig.parameters[0].kind, Kind::kPositionalOrKeyword); EXPECT_TRUE(sig.aux_policy.empty()); } { ASSERT_OK_AND_ASSIGN(const auto sig, Sig::Make("arg=", kUnit)); EXPECT_EQ(sig.parameters.size(), 1); EXPECT_EQ(sig.parameters[0].name, "arg"); EXPECT_THAT(*sig.parameters[0].default_value, TypedValueWith<Unit>(kUnit)); EXPECT_EQ(sig.parameters[0].kind, Kind::kPositionalOrKeyword); EXPECT_TRUE(sig.aux_policy.empty()); } { ASSERT_OK_AND_ASSIGN(const auto sig, Sig::Make("*args")); EXPECT_EQ(sig.parameters.size(), 1); EXPECT_EQ(sig.parameters[0].name, "args"); EXPECT_EQ(sig.parameters[0].default_value, std::nullopt); EXPECT_EQ(sig.parameters[0].kind, Kind::kVariadicPositional); EXPECT_TRUE(sig.aux_policy.empty()); } { ASSERT_OK_AND_ASSIGN(const auto sig, ExprOperatorSignature::Make( "arg1, arg2=, *args", kUnit)); EXPECT_EQ(sig.parameters.size(), 3); EXPECT_EQ(sig.parameters[0].name, "arg1"); EXPECT_EQ(sig.parameters[0].default_value, std::nullopt); EXPECT_EQ(sig.parameters[0].kind, Kind::kPositionalOrKeyword); EXPECT_EQ(sig.parameters[1].name, "arg2"); EXPECT_THAT(sig.parameters[1].default_value, Optional(TypedValueWith<Unit>(kUnit))); EXPECT_EQ(sig.parameters[1].kind, Kind::kPositionalOrKeyword); EXPECT_EQ(sig.parameters[2].name, "args"); EXPECT_EQ(sig.parameters[2].default_value, std::nullopt); EXPECT_EQ(sig.parameters[2].kind, Kind::kVariadicPositional); EXPECT_TRUE(sig.aux_policy.empty()); } { ASSERT_OK_AND_ASSIGN(const auto sig, ExprOperatorSignature::Make("|")); EXPECT_TRUE(sig.parameters.empty()); EXPECT_TRUE(sig.aux_policy.empty()); } { ASSERT_OK_AND_ASSIGN(const auto sig, ExprOperatorSignature::Make("|policy")); EXPECT_TRUE(sig.parameters.empty()); EXPECT_EQ(sig.aux_policy, "policy"); } { ASSERT_OK_AND_ASSIGN( const auto sig, ExprOperatorSignature::Make("arg1, arg2=, *args|policy", kUnit)); EXPECT_EQ(sig.parameters.size(), 3); EXPECT_EQ(sig.parameters[0].name, "arg1"); EXPECT_EQ(sig.parameters[0].default_value, std::nullopt); EXPECT_EQ(sig.parameters[0].kind, Kind::kPositionalOrKeyword); EXPECT_EQ(sig.parameters[1].name, "arg2"); EXPECT_THAT(sig.parameters[1].default_value, Optional(TypedValueWith<Unit>(kUnit))); EXPECT_EQ(sig.parameters[1].kind, Kind::kPositionalOrKeyword); EXPECT_EQ(sig.parameters[2].name, "args"); EXPECT_EQ(sig.parameters[2].default_value, std::nullopt); EXPECT_EQ(sig.parameters[2].kind, Kind::kVariadicPositional); EXPECT_EQ(sig.aux_policy, "policy"); } EXPECT_THAT( ExprOperatorSignature::Make("arg1, arg2="), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("'arg2'"))); EXPECT_THAT( ExprOperatorSignature::Make("arg1, arg2=", kUnit, kUnit), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("unused"))); { ASSERT_OK_AND_ASSIGN(const auto sig, Sig::Make("|policy")); EXPECT_TRUE(sig.parameters.empty()); EXPECT_EQ(sig.aux_policy, "policy"); } } TEST(ExprOperatorSignature, ValidateSignature_IsValidParamName) { constexpr auto validate_param_name = [](absl::string_view name) { return ValidateSignature(ExprOperatorSignature{{std::string(name)}}); }; EXPECT_THAT(validate_param_name(""), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_OK(validate_param_name("_")); EXPECT_OK(validate_param_name("A")); EXPECT_OK(validate_param_name("Z")); EXPECT_OK(validate_param_name("a")); EXPECT_OK(validate_param_name("z")); EXPECT_THAT(validate_param_name("0"), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT(validate_param_name("$"), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT(validate_param_name("/"), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT(validate_param_name("*"), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_OK(validate_param_name("_AZaz_09")); EXPECT_THAT(validate_param_name("_$"), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT(validate_param_name("_/"), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT(validate_param_name("_*"), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT(validate_param_name("*_"), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT(validate_param_name("**_"), StatusIs(absl::StatusCode::kInvalidArgument)); } TEST(ExprOperatorSignature, Make_ValidateSignature) { constexpr auto validate_signature = [](absl::string_view signature, auto&&... defaultValues) { return ExprOperatorSignature::Make(signature, defaultValues...); }; EXPECT_OK(validate_signature("")); EXPECT_OK(validate_signature("arg")); EXPECT_OK(validate_signature("arg=", kUnit)); EXPECT_OK(validate_signature("arg0, arg1=", kUnit)); EXPECT_OK(validate_signature("arg0=, arg1=", kUnit, kUnit)); EXPECT_OK(validate_signature("*args")); EXPECT_OK(validate_signature("arg, *args")); EXPECT_OK(validate_signature("arg=, *args", kUnit)); EXPECT_OK(validate_signature("arg0, arg1=, *args", kUnit)); EXPECT_OK(validate_signature("arg0=, arg1=, *args", kUnit, kUnit)); EXPECT_OK(validate_signature("|policy")); EXPECT_OK(validate_signature("arg0=, arg1=, *args|policy", kUnit, kUnit)); EXPECT_THAT(validate_signature("arg0=, arg1", kUnit), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT(validate_signature("*args=", kUnit), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT(validate_signature("arg, arg"), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT(validate_signature("arg, *arg"), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT(validate_signature("*args, arg"), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT(validate_signature("*args0, *args1"), StatusIs(absl::StatusCode::kInvalidArgument)); } TEST(ExprOperatorSignature, ValidateSignature_FormattedErrorMessages) { EXPECT_THAT(ExprOperatorSignature::Make("$"), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("illegal parameter name: '$'"))); EXPECT_THAT(ExprOperatorSignature::Make("x, x"), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("non-unique parameter name: 'x'"))); } TEST(ExprOperatorSignature, BindArguments) { constexpr auto bind_arguments = [](const ExprOperatorSignature& signature, absl::string_view args_def) -> absl::StatusOr<std::string> { std::vector<ExprNodePtr> args; absl::flat_hash_map<std::string, ExprNodePtr> kwargs; for (absl::string_view arg : absl::StrSplit(args_def, ' ', absl::SkipEmpty())) { if (size_t pos = arg.find('='); pos == absl::string_view::npos) { args.push_back(Leaf(arg)); } else { std::string kw(arg.substr(0, pos)); kwargs[kw] = Leaf(arg.substr(pos + 1)); } } ASSIGN_OR_RETURN(auto bound_args, BindArguments(signature, args, kwargs)); std::vector<std::string> result; result.reserve(bound_args.size()); for (const auto& node : bound_args) { if (node->is_leaf()) { result.push_back(node->leaf_key()); } else { result.push_back(ToDebugString(node)); } } return absl::StrJoin(result, " "); }; const auto x = Leaf("x"); { ASSERT_OK_AND_ASSIGN(const auto sig, ExprOperatorSignature::Make( "arg0, arg1=, *args", kUnit)); EXPECT_THAT(bind_arguments(sig, ""), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT(bind_arguments(sig, "u"), IsOkAndHolds("u unit")); EXPECT_THAT(bind_arguments(sig, "u v"), IsOkAndHolds("u v")); EXPECT_THAT(bind_arguments(sig, "u v w"), IsOkAndHolds("u v w")); EXPECT_THAT(bind_arguments(sig, "u v w y"), IsOkAndHolds("u v w y")); } { ASSERT_OK_AND_ASSIGN(const auto sig, ExprOperatorSignature::Make("arg=, *args", kUnit)); EXPECT_THAT(bind_arguments(sig, ""), IsOkAndHolds("unit")); EXPECT_THAT(bind_arguments(sig, "u"), IsOkAndHolds("u")); EXPECT_THAT(bind_arguments(sig, "u v"), IsOkAndHolds("u v")); EXPECT_THAT(bind_arguments(sig, "u v w"), IsOkAndHolds("u v w")); } { ASSERT_OK_AND_ASSIGN(const auto sig, ExprOperatorSignature::Make("arg, *args")); EXPECT_THAT(bind_arguments(sig, ""), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT(bind_arguments(sig, "u"), IsOkAndHolds("u")); EXPECT_THAT(bind_arguments(sig, "u v"), IsOkAndHolds("u v")); EXPECT_THAT(bind_arguments(sig, "u v w"), IsOkAndHolds("u v w")); } { ASSERT_OK_AND_ASSIGN(const auto sig, ExprOperatorSignature::Make("arg0, arg1=", kUnit)); EXPECT_THAT(bind_arguments(sig, ""), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT(bind_arguments(sig, "u"), IsOkAndHolds("u unit")); EXPECT_THAT(bind_arguments(sig, "u v"), IsOkAndHolds("u v")); EXPECT_THAT(bind_arguments(sig, "u v w"), StatusIs(absl::StatusCode::kInvalidArgument)); } { ASSERT_OK_AND_ASSIGN( const auto sig, ExprOperatorSignature::Make("arg0, arg1=, arg2=", kUnit, kUnit)); EXPECT_THAT(bind_arguments(sig, ""), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT(bind_arguments(sig, "u"), IsOkAndHolds("u unit unit")); EXPECT_THAT(bind_arguments(sig, "arg0=u"), IsOkAndHolds("u unit unit")); EXPECT_THAT(bind_arguments(sig, "arg1=v"), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT(bind_arguments(sig, "arg2=w"), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT(bind_arguments(sig, "u v"), IsOkAndHolds("u v unit")); EXPECT_THAT(bind_arguments(sig, "v arg0=u"), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT(bind_arguments(sig, "u arg1=v"), IsOkAndHolds("u v unit")); EXPECT_THAT(bind_arguments(sig, "u arg2=w"), IsOkAndHolds("u unit w")); EXPECT_THAT(bind_arguments(sig, "arg0=u arg1=v"), IsOkAndHolds("u v unit")); EXPECT_THAT(bind_arguments(sig, "arg0=u arg2=w"), IsOkAndHolds("u unit w")); EXPECT_THAT(bind_arguments(sig, "arg1=v arg2=w"), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT(bind_arguments(sig, "u v w"), IsOkAndHolds("u v w")); EXPECT_THAT(bind_arguments(sig, "v w arg0=u"), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT(bind_arguments(sig, "u w arg1=v"), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT(bind_arguments(sig, "u v arg2=w"), IsOkAndHolds("u v w")); EXPECT_THAT(bind_arguments(sig, "w arg0=u arg1=v"), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT(bind_arguments(sig, "v arg0=u arg2=w"), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT(bind_arguments(sig, "u arg1=v arg2=w"), IsOkAndHolds("u v w")); EXPECT_THAT(bind_arguments(sig, "arg0=u arg1=v arg2=w"), IsOkAndHolds("u v w")); } { ASSERT_OK_AND_ASSIGN(const auto sig, ExprOperatorSignature::Make("arg0, *args")); EXPECT_THAT(bind_arguments(sig, "arg0=u"), IsOkAndHolds("u")); EXPECT_THAT(bind_arguments(sig, "arg0=u, args=v"), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT(bind_arguments(sig, "v arg0=u"), StatusIs(absl::StatusCode::kInvalidArgument)); } } TEST(ExprOperatorSignature, BindArguments_FormattedErrorMessages) { const auto x = Leaf("x"); { ASSERT_OK_AND_ASSIGN(const auto sig, ExprOperatorSignature::Make( "arg0, arg1, arg2, arg3=", kUnit)); EXPECT_THAT(BindArguments(sig, {}, {}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("missing 3 required arguments: " "'arg0', 'arg1', 'arg2'"))); EXPECT_THAT( BindArguments(sig, {x}, {}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("missing 2 required arguments: 'arg1', 'arg2'"))); EXPECT_THAT(BindArguments(sig, {x, x}, {}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("missing 1 required argument: 'arg2'"))); EXPECT_THAT(BindArguments(sig, {x, x, x, x, x}, {}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("too many positional arguments passed: " "expected maximumum is 4 but got 5"))); } { ASSERT_OK_AND_ASSIGN(const auto sig, ExprOperatorSignature::Make("arg0, *args")); EXPECT_THAT(BindArguments(sig, {x}, {{"arg0", x}}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("multiple values for argument: 'arg0'"))); EXPECT_THAT(BindArguments(sig, {x}, {{"args", x}}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("unexpected keyword argument: 'args'"))); EXPECT_THAT( BindArguments(sig, {x}, {{"args", x}, {"arg1", x}}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("unexpected keyword arguments: 'arg1', 'args'"))); } } TEST(ExprOperatorSignature, GetExprOperatorSignatureSpec) { EXPECT_EQ(GetExprOperatorSignatureSpec(ExprOperatorSignature{}), ""); { ASSERT_OK_AND_ASSIGN( const auto sig, ExprOperatorSignature::Make("arg0, arg1=, *args|policy", kUnit)); EXPECT_EQ(GetExprOperatorSignatureSpec(sig), "arg0, arg1=, *args|policy"); } } TEST(ExprOperatorSignature, Fingerprint) { constexpr auto fgpt = [](absl::StatusOr<ExprOperatorSignature> sig) -> Fingerprint { return FingerprintHasher("dummy-salt").Combine(*sig).Finish(); }; const auto signatures = { ExprOperatorSignature::Make(""), ExprOperatorSignature::Make("x"), ExprOperatorSignature::Make("*x"), ExprOperatorSignature::Make("x|policy"), ExprOperatorSignature::Make("y"), ExprOperatorSignature::Make("x, y"), ExprOperatorSignature::Make("x=", kUnit), ExprOperatorSignature::Make("x=", GetQTypeQType()), }; for (auto& sig1 : signatures) { for (auto& sig2 : signatures) { if (&sig1 == &sig2) { EXPECT_EQ(fgpt(sig1), fgpt(sig2)); } else { EXPECT_NE(fgpt(sig1), fgpt(sig2)); } } } } } }
2,434
#ifndef AROLLA_EXPR_EXPR_NODE_H_ #define AROLLA_EXPR_EXPR_NODE_H_ #include <cstdint> #include <iosfwd> #include <optional> #include <string> #include <vector> #include "absl/strings/string_view.h" #include "arolla/expr/expr_attributes.h" #include "arolla/expr/expr_node_ptr.h" #include "arolla/expr/expr_operator.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/typed_value.h" #include "arolla/util/fingerprint.h" #include "arolla/util/refcount_ptr.h" namespace arolla::expr { enum class ExprNodeType : uint8_t { kLiteral = 0, kLeaf = 1, kOperator = 2, kPlaceholder = 3, }; std::ostream& operator<<(std::ostream& os, ExprNodeType t); class ExprNode : public RefcountedBase { struct PrivateConstructorTag {}; public: static ExprNodePtr MakeLiteralNode(TypedValue&& qvalue); static ExprNodePtr MakeLeafNode(absl::string_view leaf_key); static ExprNodePtr MakePlaceholderNode(absl::string_view placeholder_key); static ExprNodePtr UnsafeMakeOperatorNode( ExprOperatorPtr&& op, std::vector<ExprNodePtr>&& node_deps, ExprAttributes&& attr); explicit ExprNode(PrivateConstructorTag) {} ~ExprNode(); ExprNodeType type() const { return type_; } bool is_literal() const { return type_ == ExprNodeType::kLiteral; } bool is_leaf() const { return type_ == ExprNodeType::kLeaf; } bool is_op() const { return type_ == ExprNodeType::kOperator; } bool is_placeholder() const { return type_ == ExprNodeType::kPlaceholder; } const ExprAttributes& attr() const { return attr_; } const QType* qtype() const { return attr_.qtype(); } const std::optional<TypedValue>& qvalue() const { return attr_.qvalue(); } const std::string& leaf_key() const { return leaf_key_; } const std::string& placeholder_key() const { return placeholder_key_; } const ExprOperatorPtr& op() const { return op_; } const std::vector<ExprNodePtr>& node_deps() const { return node_deps_; } const Fingerprint& fingerprint() const { return fingerprint_; } private: ExprNodeType type_; std::string leaf_key_; std::string placeholder_key_; ExprOperatorPtr op_; std::vector<ExprNodePtr> node_deps_; ExprAttributes attr_; Fingerprint fingerprint_; }; } #endif #include "arolla/expr/expr_node.h" #include <cstddef> #include <deque> #include <memory> #include <ostream> #include <string> #include <utility> #include <vector> #include "absl/base/no_destructor.h" #include "absl/cleanup/cleanup.h" #include "absl/log/check.h" #include "absl/strings/string_view.h" #include "arolla/expr/expr_attributes.h" #include "arolla/expr/expr_operator.h" #include "arolla/qtype/typed_value.h" #include "arolla/util/fingerprint.h" namespace arolla::expr { std::ostream& operator<<(std::ostream& os, ExprNodeType t) { switch (t) { case expr::ExprNodeType::kLiteral: { return os << "kLiteral"; } case expr::ExprNodeType::kLeaf: { return os << "kLeaf"; } case expr::ExprNodeType::kOperator: { return os << "kOperator"; } case expr::ExprNodeType::kPlaceholder: { return os << "kPlaceholder"; } } return os << "ExprNodeType(" << static_cast<int>(t) << ")"; } ExprNodePtr ExprNode::MakeLiteralNode(TypedValue&& qvalue) { FingerprintHasher hasher("LiteralNode"); hasher.Combine(qvalue.GetFingerprint()); auto self = std::make_unique<ExprNode>(PrivateConstructorTag()); self->type_ = ExprNodeType::kLiteral; self->attr_ = ExprAttributes(std::move(qvalue)); self->fingerprint_ = std::move(hasher).Finish(); return ExprNodePtr::Own(std::move(self)); } ExprNodePtr ExprNode::MakeLeafNode(absl::string_view leaf_key) { auto self = std::make_unique<ExprNode>(PrivateConstructorTag()); self->type_ = ExprNodeType::kLeaf; self->leaf_key_ = std::string(leaf_key); self->fingerprint_ = FingerprintHasher("LeafNode").Combine(leaf_key).Finish(); return ExprNodePtr::Own(std::move(self)); } ExprNodePtr ExprNode::MakePlaceholderNode(absl::string_view placeholder_key) { auto self = std::make_unique<ExprNode>(PrivateConstructorTag()); self->type_ = ExprNodeType::kPlaceholder; self->placeholder_key_ = std::string(placeholder_key); self->fingerprint_ = FingerprintHasher("PlaceholderNode").Combine(placeholder_key).Finish(); return ExprNodePtr::Own(std::move(self)); } ExprNodePtr ExprNode::UnsafeMakeOperatorNode( ExprOperatorPtr&& op, std::vector<ExprNodePtr>&& node_deps, ExprAttributes&& attr) { FingerprintHasher hasher("OpNode"); DCHECK(op); hasher.Combine(op->fingerprint()); for (const auto& node_dep : node_deps) { DCHECK(node_dep != nullptr); hasher.Combine(node_dep->fingerprint()); } hasher.Combine(attr); auto self = std::make_unique<ExprNode>(PrivateConstructorTag()); self->type_ = ExprNodeType::kOperator; self->op_ = std::move(op); self->node_deps_ = std::move(node_deps); self->attr_ = std::move(attr); self->fingerprint_ = std::move(hasher).Finish(); return ExprNodePtr::Own(std::move(self)); } ExprNode::~ExprNode() { if (node_deps_.empty()) { return; } constexpr size_t kMaxDepth = 32; thread_local absl::NoDestructor<std::deque<std::vector<ExprNodePtr>>> deps; thread_local size_t destructor_depth = 0; if (destructor_depth > kMaxDepth) { deps->push_back(std::move(node_deps_)); return; } destructor_depth++; absl::Cleanup decrease_depth = [&] { --destructor_depth; }; node_deps_.clear(); if (destructor_depth == 1 && !deps->empty()) { while (!deps->empty()) { auto tmp = std::move(deps->back()); deps->pop_back(); } deps->shrink_to_fit(); } } }
#include "arolla/expr/expr_node.h" #include <memory> #include <sstream> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/expr/testing/test_operators.h" #include "arolla/util/init_arolla.h" namespace arolla::expr { namespace { using ::arolla::expr::testing::DummyOp; class ExprNodeTest : public ::testing::Test { protected: void SetUp() override { ASSERT_OK(InitArolla()); } }; TEST_F(ExprNodeTest, ExprNodeTypeIsConvertibleToString) { std::stringstream ss; ss << ExprNodeType::kLiteral; EXPECT_EQ(ss.str(), "kLiteral"); ss.str(""); ss << ExprNodeType::kLeaf; EXPECT_EQ(ss.str(), "kLeaf"); ss.str(""); ss << ExprNodeType::kOperator; EXPECT_EQ(ss.str(), "kOperator"); ss.str(""); ss << ExprNodeType::kPlaceholder; EXPECT_EQ(ss.str(), "kPlaceholder"); ss.str(""); ss << static_cast<ExprNodeType>(255); EXPECT_EQ(ss.str(), "ExprNodeType(255)"); } TEST_F(ExprNodeTest, DeepTreeNoStackOverflow) { #ifndef NDEBUG constexpr int depth = 50000; #else constexpr int depth = 1000000; #endif ExprOperatorPtr op = std::make_shared<DummyOp>( "op.name", ExprOperatorSignature::MakeVariadicArgs()); auto a = ExprNode::MakeLeafNode("a"); auto deep = a; for (int i = depth; i != 0; --i) { deep = ExprNode::UnsafeMakeOperatorNode(ExprOperatorPtr(op), {deep, a}, {}); } } using ExprNodeMsanTest = ::testing::TestWithParam<ExprNodePtr>; TEST_P(ExprNodeMsanTest, Msan) { const auto& expr = GetParam(); ASSERT_NE(expr, nullptr); } INSTANTIATE_TEST_SUITE_P(ExprNodeMsanTestSuite, ExprNodeMsanTest, ::testing::ValuesIn([]() -> std::vector<ExprNodePtr> { constexpr int depth = 64; ExprOperatorPtr op = std::make_shared<DummyOp>( "op.name", ExprOperatorSignature::MakeVariadicArgs()); auto expr = ExprNode::MakeLeafNode("a"); for (int i = depth; i != 0; --i) { expr = ExprNode::UnsafeMakeOperatorNode( ExprOperatorPtr(op), {expr}, {}); } return {{expr}}; }())); } }
2,435
#ifndef AROLLA_EXPR_OPERATORS_STRINGS_REGISTER_OPERATORS_H_ #define AROLLA_EXPR_OPERATORS_STRINGS_REGISTER_OPERATORS_H_ #include "absl/status/status.h" #include "arolla/expr/operators/registration.h" namespace arolla::expr_operators { absl::Status InitStrings(); AROLLA_DECLARE_EXPR_OPERATOR(StringsCompileRegex); AROLLA_DECLARE_EXPR_OPERATOR(StringsContainsRegex); AROLLA_DECLARE_EXPR_OPERATOR(StringsExtractRegex); AROLLA_DECLARE_EXPR_OPERATOR(StringsJoin); AROLLA_DECLARE_EXPR_OPERATOR(StringsJoinWithSeparator); } #endif #include "arolla/expr/operators/strings/register_operators.h" #include <memory> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "arolla/expr/backend_wrapping_operator.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/expr/operators/dynamic_lifting.h" #include "arolla/expr/operators/register_operators.h" #include "arolla/expr/operators/registration.h" #include "arolla/expr/operators/strings/string_operators.h" #include "arolla/expr/operators/type_meta_eval_strategies.h" #include "arolla/expr/registered_expr_operator.h" #include "arolla/qtype/strings/regex.h" #include "arolla/util/indestructible.h" #include "arolla/util/text.h" #include "arolla/util/status_macros_backport.h" namespace arolla::expr_operators { namespace { using ::arolla::expr::ExprOperatorSignature; using ::arolla::expr::RegisterOperator; namespace tm = ::arolla::expr_operators::type_meta; using tm::Binary; using tm::CallableStrategy; using tm::Chain; using tm::Is; using tm::LiftNthType; using tm::Nth; using tm::NthMatch; using tm::Returns; using tm::ScalarOrOptional; using tm::ScalarTypeIs; using tm::String; using tm::ToOptional; using tm::ToTestResult; using tm::Unary; } AROLLA_DEFINE_EXPR_OPERATOR(StringsCompileRegex, RegisterBackendOperator("strings._compile_regex", Chain(Unary, Is<Text>, Returns<Regex>))); AROLLA_DEFINE_EXPR_OPERATOR( StringsJoinWithSeparator, RegisterOperator( "strings._join_with_separator", LiftDynamically(std::make_shared<expr::BackendWrappingOperator>( "strings._join_with_separator", ExprOperatorSignature::MakeVariadicArgs(), CallableStrategy(Chain(ScalarOrOptional, String, LiftNthType(0))))))); AROLLA_DEFINE_EXPR_OPERATOR( StringsContainsRegex, []() -> absl::StatusOr<expr::ExprOperatorPtr> { RETURN_IF_ERROR( RegisterOperator( "strings._contains_regex", LiftDynamically(std::make_shared<expr::BackendWrappingOperator>( "strings._contains_regex", ExprOperatorSignature{{"s"}, {"regex"}}, CallableStrategy(Chain(Binary, NthMatch(1, Is<Regex>), Nth(0), ScalarOrOptional, ScalarTypeIs<Text>, ToTestResult))))) .status()); return RegisterOperator("strings.contains_regex", MakeContainsRegexOp()); }()); AROLLA_DEFINE_EXPR_OPERATOR( StringsExtractRegex, []() -> absl::StatusOr<expr::ExprOperatorPtr> { RETURN_IF_ERROR( RegisterOperator( "strings._extract_regex", LiftDynamically(std::make_shared<expr::BackendWrappingOperator>( "strings._extract_regex", ExprOperatorSignature{{"s"}, {"regex"}}, CallableStrategy(Chain(Binary, NthMatch(1, Is<Regex>), Nth(0), ScalarOrOptional, ScalarTypeIs<Text>, ToOptional))))) .status()); return RegisterOperator("strings.extract_regex", MakeExtractRegexOp()); }()); AROLLA_DEFINE_EXPR_OPERATOR(StringsJoin, RegisterOperator("strings.join", MakeJoinOp())); absl::Status InitStrings() { static Indestructible<absl::Status> init_status([]() -> absl::Status { RETURN_IF_ERROR(InitCore()); RETURN_IF_ERROR(InitArray()); RETURN_IF_ERROR(RegisterStringsCompileRegex()); RETURN_IF_ERROR(RegisterStringsJoinWithSeparator()); RETURN_IF_ERROR(RegisterStringsContainsRegex()); RETURN_IF_ERROR(RegisterStringsExtractRegex()); RETURN_IF_ERROR(RegisterStringsJoin()); return absl::OkStatus(); }()); return *init_status; } }
#include <cstdint> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/types/span.h" #include "arolla/dense_array/qtype/types.h" #include "arolla/expr/expr_attributes.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/registered_expr_operator.h" #include "arolla/memory/optional_value.h" #include "arolla/qtype/optional_qtype.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/util/init_arolla.h" #include "arolla/util/testing/status_matchers_backport.h" #include "arolla/util/unit.h" #include "arolla/util/status_macros_backport.h" namespace arolla::expr_operators { namespace { using ::arolla::expr::ExprAttributes; using ::arolla::expr::ExprOperatorPtr; using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::StatusIs; using ::testing::HasSubstr; absl::StatusOr<QTypePtr> GetOutputQType( const ExprOperatorPtr& op, absl::Span<const QTypePtr> input_qtypes) { std::vector<ExprAttributes> inputs; inputs.reserve(input_qtypes.size()); for (auto* input_qtype : input_qtypes) { inputs.emplace_back(input_qtype); } ASSIGN_OR_RETURN(auto output, op->InferAttributes(inputs)); return output.qtype(); } class RegisterOperatorsTest : public ::testing::Test { protected: void SetUp() override { ASSERT_OK(InitArolla()); } }; TEST_F(RegisterOperatorsTest, PresenceAndOr) { ASSERT_OK_AND_ASSIGN(auto pand_or, expr::LookupOperator("core._presence_and_or")); auto f64 = GetQType<double>(); auto i64 = GetQType<int64_t>(); auto i32 = GetQType<int32_t>(); EXPECT_THAT(GetOutputQType(pand_or, {i64, GetQType<OptionalUnit>(), i64}), IsOkAndHolds(i64)); EXPECT_THAT(GetOutputQType(pand_or, {i64, GetQType<OptionalUnit>(), i32}), IsOkAndHolds(i64)); EXPECT_THAT(GetOutputQType(pand_or, {i32, GetQType<OptionalUnit>(), i64}), IsOkAndHolds(i64)); EXPECT_THAT(GetOutputQType(pand_or, {i32, GetQType<OptionalUnit>(), i32}), IsOkAndHolds(i32)); auto oi64 = GetOptionalQType<int64_t>(); auto oi32 = GetOptionalQType<int32_t>(); EXPECT_THAT(GetOutputQType(pand_or, {oi32, GetQType<OptionalUnit>(), i64}), IsOkAndHolds(i64)); EXPECT_THAT(GetOutputQType(pand_or, {oi64, GetQType<OptionalUnit>(), i32}), IsOkAndHolds(i64)); EXPECT_THAT(GetOutputQType(pand_or, {i32, GetQType<OptionalUnit>(), oi64}), IsOkAndHolds(oi64)); auto daunit = GetDenseArrayQType<Unit>(); auto dai64 = GetDenseArrayQType<int64_t>(); EXPECT_THAT( GetOutputQType(pand_or, {oi32, daunit, dai64}), StatusIs( absl::StatusCode::kInvalidArgument, HasSubstr("expected all arguments to be scalar or optional scalar, " "but got DENSE_ARRAY_UNIT for 1-th argument"))); EXPECT_THAT(GetOutputQType(pand_or, {GetQType<Unit>()}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("expected 3 but got 1"))); EXPECT_THAT(GetOutputQType(pand_or, {i64, GetQType<OptionalUnit>(), f64}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("no common QType for (INT64,FLOAT64)"))); } TEST_F(RegisterOperatorsTest, PresenceAnd) { ASSERT_OK_AND_ASSIGN(auto presence_and, expr::LookupOperator("core.presence_and")); EXPECT_THAT( GetOutputQType(presence_and, {GetQType<int32_t>(), GetQType<bool>()}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("expected scalar type to be UNIT"))); } TEST_F(RegisterOperatorsTest, ShortCircuitWhere) { ASSERT_OK_AND_ASSIGN(auto where, expr::LookupOperator("core._short_circuit_where")); EXPECT_THAT(GetOutputQType(where, {GetQType<OptionalUnit>(), GetQType<int64_t>(), GetQType<int64_t>()}), IsOkAndHolds(GetQType<int64_t>())); EXPECT_THAT(GetOutputQType(where, {GetQType<OptionalUnit>(), GetQType<float>(), GetQType<double>()}), IsOkAndHolds(GetQType<double>())); EXPECT_THAT(GetOutputQType(where, {GetQType<OptionalUnit>(), GetQType<int64_t>(), GetQType<float>()}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("no common QType for (INT64,FLOAT32)"))); } } }
2,436
#ifndef AROLLA_EXPR_EVAL_INVOKE_H_ #define AROLLA_EXPR_EVAL_INVOKE_H_ #include <string> #include "absl/container/flat_hash_map.h" #include "absl/status/statusor.h" #include "arolla/expr/eval/eval.h" #include "arolla/expr/expr_node.h" #include "arolla/qtype/typed_value.h" namespace arolla::expr { absl::StatusOr<TypedValue> Invoke( const ExprNodePtr& expr, const absl::flat_hash_map<std::string, TypedValue>& leaf_values, DynamicEvaluationEngineOptions options = DynamicEvaluationEngineOptions()); } #endif #include "arolla/expr/eval/invoke.h" #include <string> #include <utility> #include "absl/container/flat_hash_map.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "arolla/expr/eval/eval.h" #include "arolla/expr/expr_node.h" #include "arolla/memory/frame.h" #include "arolla/qexpr/eval_context.h" #include "arolla/qexpr/evaluation_engine.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/typed_slot.h" #include "arolla/qtype/typed_value.h" #include "arolla/util/status_macros_backport.h" namespace arolla::expr { absl::StatusOr<TypedValue> Invoke( const ExprNodePtr& expr, const absl::flat_hash_map<std::string, TypedValue>& leaf_values, DynamicEvaluationEngineOptions options) { absl::flat_hash_map<std::string, QTypePtr> leaf_types; leaf_types.reserve(leaf_values.size()); for (const auto& [name, value] : leaf_values) { leaf_types.emplace(name, value.GetType()); } ASSIGN_OR_RETURN(auto compiled_expr, CompileForDynamicEvaluation(options, expr, leaf_types)); FrameLayout::Builder layout_builder; const auto leaf_slots = AddSlotsMap(compiled_expr->input_types(), &layout_builder); ASSIGN_OR_RETURN(auto executable_expr, compiled_expr->Bind( &layout_builder, leaf_slots, AddSlot(compiled_expr->output_type(), &layout_builder))); FrameLayout layout = std::move(layout_builder).Build(); RootEvaluationContext ctx(&layout); RETURN_IF_ERROR(executable_expr->InitializeLiterals(&ctx)); for (const auto& [name, slot] : leaf_slots) { if (!leaf_values.contains(name)) { return absl::InvalidArgumentError( absl::StrFormat("value was not specified for leaf %s", name)); } RETURN_IF_ERROR(leaf_values.at(name).CopyToSlot(slot, ctx.frame())); } RETURN_IF_ERROR(executable_expr->Execute(&ctx)); return TypedValue::FromSlot(executable_expr->output_slot(), ctx.frame()); } }
#include "arolla/expr/eval/invoke.h" #include <cstdint> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_node.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/testing/qtype.h" #include "arolla/qtype/typed_value.h" #include "arolla/util/init_arolla.h" #include "arolla/util/testing/status_matchers_backport.h" namespace arolla::expr { namespace { using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::StatusIs; using ::arolla::testing::TypedValueWith; using ::testing::Eq; class InvokeTest : public ::testing::Test { protected: void SetUp() override { ASSERT_OK(InitArolla()); } }; TEST_F(InvokeTest, SimpleAST) { ASSERT_OK_AND_ASSIGN( ExprNodePtr expr, CallOp("math.add", {CallOp("math.multiply", {Leaf("x"), Leaf("y")}), Leaf("z")})); EXPECT_THAT(Invoke(expr, {{"x", TypedValue::FromValue(5)}, {"y", TypedValue::FromValue(10)}, {"z", TypedValue::FromValue(7)}}), IsOkAndHolds(TypedValueWith<int32_t>(Eq(57)))); EXPECT_THAT(Invoke(expr, {{"x", TypedValue::FromValue(5)}, {"y", TypedValue::FromValue(10)}}), StatusIs(absl::StatusCode::kInvalidArgument)); } } }
2,437
#ifndef AROLLA_EXPR_OPERATORS_TYPE_META_EVAL_STRATEGIES_H_ #define AROLLA_EXPR_OPERATORS_TYPE_META_EVAL_STRATEGIES_H_ #include <cstddef> #include <functional> #include <initializer_list> #include <string> #include <vector> #include "absl/container/inlined_vector.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "arolla/expr/backend_wrapping_operator.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/qtype/array_like/array_like_qtype.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/shape_qtype.h" #include "arolla/qtype/standard_type_properties/properties.h" #include "arolla/util/status_macros_backport.h" namespace arolla::expr_operators { namespace type_meta { using QTypes = absl::InlinedVector<QTypePtr, 2>; using Strategy = std::function<absl::StatusOr<QTypes>(absl::Span<const QTypePtr>)>; absl::StatusOr<QTypePtr> ApplyStrategy(const Strategy& strategy, absl::Span<const QTypePtr> qtypes); expr::BackendWrappingOperator::TypeMetaEvalStrategy CallableStrategy( type_meta::Strategy strategy); template <typename... Funcs> Strategy Chain(Funcs... strategies) { std::vector<Strategy> s{strategies...}; return Chain(absl::Span<const Strategy>(s)); } template <> Strategy Chain(absl::Span<const Strategy> strategies); template <typename... Funcs> Strategy Or(Funcs... strategies) { std::vector<Strategy> s{strategies...}; return Or(absl::Span<const Strategy>(s)); } template <> Strategy Or(absl::Span<const Strategy> strategies); absl::StatusOr<QTypes> AllSame(absl::Span<const QTypePtr> types); absl::StatusOr<QTypes> AllSameScalarType(absl::Span<const QTypePtr> types); absl::StatusOr<QTypes> Array(absl::Span<const QTypePtr> types); absl::StatusOr<QTypes> Numeric(absl::Span<const QTypePtr> types); absl::StatusOr<QTypes> Integral(absl::Span<const QTypePtr> types); absl::StatusOr<QTypes> Floating(absl::Span<const QTypePtr> types); absl::StatusOr<QTypes> Boolean(absl::Span<const QTypePtr> types); absl::StatusOr<QTypes> String(absl::Span<const QTypePtr> types); absl::StatusOr<QTypes> Optional(absl::Span<const QTypePtr> types); absl::StatusOr<QTypes> OptionalLike(absl::Span<const QTypePtr> types); absl::StatusOr<QTypes> Scalar(absl::Span<const QTypePtr> types); absl::StatusOr<QTypes> ScalarOrOptional(absl::Span<const QTypePtr> types); absl::StatusOr<QTypes> IntegralScalar(absl::Span<const QTypePtr> types); absl::StatusOr<QTypes> FloatingScalar(absl::Span<const QTypePtr> types); absl::StatusOr<QTypes> Unary(absl::Span<const QTypePtr> types); absl::StatusOr<QTypes> Binary(absl::Span<const QTypePtr> types); absl::StatusOr<QTypes> Ternary(absl::Span<const QTypePtr> types); Strategy ArgCount(int n); absl::StatusOr<QTypes> CommonType(absl::Span<const QTypePtr> types); Strategy FirstMatchingTypeStrategy(std::function<bool(QTypePtr)> predicate_fn, Strategy default_fn); Strategy Nth(std::initializer_list<int> index_list); inline Strategy Nth(int index) { return Nth({index}); } absl::StatusOr<QTypes> ToOptional(absl::Span<const QTypePtr> types); absl::StatusOr<QTypes> ToTestResult(absl::Span<const QTypePtr> types); absl::StatusOr<QTypes> ToShape(absl::Span<const QTypePtr> types); template <typename Dst> absl::StatusOr<QTypes> To(absl::Span<const QTypePtr> types) { QTypes result(types.size(), nullptr); for (size_t i = 0; i < types.size(); ++i) { ASSIGN_OR_RETURN(result[i], WithScalarQType(types[i], GetQType<Dst>()), _ << " in argument " << i); } return result; } Strategy Is(QTypePtr desired_type); Strategy IsNot(QTypePtr undesired_type); template <typename T> absl::StatusOr<QTypes> Is(absl::Span<const QTypePtr> types) { return Is(GetQType<T>())(types); } template <typename T> absl::StatusOr<QTypes> IsNot(absl::Span<const QTypePtr> types) { return IsNot(GetQType<T>())(types); } absl::StatusOr<QTypes> IsShape(absl::Span<const QTypePtr> qtypes); absl::StatusOr<QTypes> IsArrayShape(absl::Span<const QTypePtr> qtypes); absl::StatusOr<QTypes> IsEdge(absl::Span<const QTypePtr> qtypes); absl::StatusOr<QTypes> IsArray(absl::Span<const QTypePtr> qtypes); absl::StatusOr<QTypes> IsDenseArray(absl::Span<const QTypePtr> qtypes); template <typename T> absl::StatusOr<QTypes> Shaped(absl::Span<const QTypePtr> shape_qtypes) { const auto value_qtype = GetQType<T>(); QTypes result; result.reserve(shape_qtypes.size()); for (size_t i = 0; i < shape_qtypes.size(); ++i) { auto shape_qtype = dynamic_cast<const ShapeQType*>(shape_qtypes[i]); if (shape_qtype == nullptr) { return absl::InvalidArgumentError(absl::StrFormat( "expected all arguments to be shapes, got %s in argument %d", shape_qtypes[i]->name(), i)); } ASSIGN_OR_RETURN(auto shaped_qtype, shape_qtype->WithValueQType(value_qtype), _ << " in argument " << i); result.push_back(shaped_qtype); } return result; } Strategy NthMatch(int n, Strategy strategy); Strategy NthMatch(std::initializer_list<int> index_list, Strategy strategy); Strategy NthApply(int n, Strategy strategy); Strategy NthApply(std::initializer_list<int> index_list, Strategy strategy); template <typename T> absl::StatusOr<QTypes> Returns(absl::Span<const QTypePtr>) { return QTypes{GetQType<T>()}; } Strategy LiftResultType(QTypePtr scalar_type); Strategy LiftNthType(int n); absl::StatusOr<QTypes> Broadcast(absl::Span<const QTypePtr> qtypes); template <typename T> absl::StatusOr<QTypes> ScalarTypeIs(absl::Span<const QTypePtr> types) { for (size_t i = 0; i < types.size(); ++i) { ASSIGN_OR_RETURN(auto scalar_type, GetScalarQType(types[i]), _ << " in argument " << i); if (scalar_type != GetQType<T>()) { std::string arg_msg = types.size() == 1 ? "" : absl::StrFormat(" of argument %d", i); return absl::Status( absl::StatusCode::kInvalidArgument, absl::StrFormat("expected scalar type%s to be %s, got %s", arg_msg, GetQType<T>()->name(), scalar_type->name())); } } return QTypes{types.begin(), types.end()}; } absl::StatusOr<QTypes> EdgeParentShapeQType(absl::Span<const QTypePtr> types); template <typename T> absl::StatusOr<QTypes> ArrayShapeToArray(absl::Span<const QTypePtr> types) { QTypes result(types.size(), nullptr); for (size_t i = 0; i < types.size(); ++i) { if (auto shape_type = dynamic_cast<const ArrayLikeShapeQType*>(types[i]); shape_type != nullptr) { ASSIGN_OR_RETURN(result[i], shape_type->WithValueQType(GetQType<T>())); } else { return absl::InvalidArgumentError(absl::StrFormat( "invalid argument %d: expected an array shape, got %s", i, types[i]->name())); } } return result; } absl::StatusOr<QTypes> PresenceOrType(absl::Span<const QTypePtr> types); } absl::StatusOr<expr::ExprOperatorPtr> RegisterBackendOperator( absl::string_view op_name, type_meta::Strategy strategy, absl::string_view doc = ""); absl::StatusOr<expr::ExprOperatorPtr> RegisterBackendOperator( absl::string_view op_name, const expr::ExprOperatorSignature& signature, type_meta::Strategy strategy, absl::string_view doc = ""); bool IsIntegral(QTypePtr qtype); bool IsNumeric(QTypePtr qtype); bool IsFloatingPoint(QTypePtr qtype); bool IsBoolean(QTypePtr qtype); bool IsString(QTypePtr qtype); } #endif #include "arolla/expr/operators/type_meta_eval_strategies.h" #include <algorithm> #include <cstddef> #include <functional> #include <initializer_list> #include <string> #include <utility> #include <vector> #include "absl/container/inlined_vector.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" #include "absl/strings/str_join.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "arolla/array/qtype/types.h" #include "arolla/dense_array/qtype/types.h" #include "arolla/expr/backend_wrapping_operator.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/expr/operators/casting_registry.h" #include "arolla/qtype/array_like/array_like_qtype.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/optional_qtype.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/shape_qtype.h" #include "arolla/qtype/standard_type_properties/properties.h" #include "arolla/util/bytes.h" #include "arolla/util/text.h" #include "arolla/util/status_macros_backport.h" namespace arolla::expr_operators { using ::arolla::expr::BackendWrappingOperator; using ::arolla::expr::ExprNodePtr; using ::arolla::expr::ExprOperatorPtr; using ::arolla::expr_operators::CastingRegistry; bool IsIntegral(const QType* qtype) { return IsIntegralScalarQType(GetScalarQType(qtype).value_or(nullptr)); } bool IsFloatingPoint(QTypePtr qtype) { return IsFloatingPointScalarQType(GetScalarQType(qtype).value_or(nullptr)); } bool IsNumeric(const QType* qtype) { return IsNumericScalarQType(GetScalarQType(qtype).value_or(nullptr)); } bool IsBoolean(QTypePtr qtype) { return GetScalarQType(qtype).value_or(nullptr) == GetQType<bool>(); } bool IsString(QTypePtr qtype) { ASSIGN_OR_RETURN(qtype, GetScalarQType(qtype), false); return qtype == GetQType<Bytes>() || qtype == GetQType<Text>(); } bool IsText(QTypePtr qtype) { return GetScalarQType(qtype).value_or(nullptr) == GetQType<Text>(); } namespace { absl::Status InvalidArgTypeError(absl::Span<const QTypePtr> qtypes, int index, absl::string_view msg) { absl::string_view name = qtypes[index] == nullptr ? "null" : qtypes[index]->name(); return absl::InvalidArgumentError(absl::StrFormat( "expected all arguments to %s, but got %s for %i-th argument", msg, name, index)); } } namespace type_meta { Strategy ArgCount(int n) { return [n](absl::Span<const QTypePtr> types) -> absl::StatusOr<QTypes> { if (types.size() != n) { return absl::InvalidArgumentError(absl::StrFormat( "expected to have %d arguments, got %d", n, types.size())); } return QTypes(types.begin(), types.end()); }; } absl::StatusOr<QTypePtr> ApplyStrategy(const Strategy& strategy, absl::Span<const QTypePtr> qtypes) { if (std::find(qtypes.begin(), qtypes.end(), nullptr) != qtypes.end()) { return nullptr; } ASSIGN_OR_RETURN(auto result, strategy(qtypes)); if (result.size() != 1) { return absl::FailedPreconditionError(absl::StrFormat( "unexpected number of resulting qtypes from MetaEval strategy: " "expected 1, got %d; probably the strategy is incorrect", result.size())); } return result[0]; } BackendWrappingOperator::TypeMetaEvalStrategy CallableStrategy( type_meta::Strategy strategy) { return [strategy = std::move(strategy)](absl::Span<const QTypePtr> ts) { return type_meta::ApplyStrategy(strategy, ts); }; } template <> Strategy Chain(absl::Span<const Strategy> strategies) { return [strategies_ = std::vector<Strategy>(strategies.begin(), strategies.end())]( absl::Span<const QTypePtr> types) -> absl::StatusOr<QTypes> { QTypes result(types.begin(), types.end()); for (const auto& s : strategies_) { ASSIGN_OR_RETURN(result, s(result)); } return result; }; } template <> Strategy Or(absl::Span<const Strategy> strategies) { return [strategies_ = std::vector<Strategy>{strategies.begin(), strategies.end()}]( absl::Span<const QTypePtr> types) -> absl::StatusOr<QTypes> { QTypes result(types.begin(), types.end()); std::vector<std::string> errors; for (const auto& s : strategies_) { auto result = s(types); if (result.ok()) { return result; } errors.push_back(result.status().ToString()); } return absl::InvalidArgumentError( absl::StrFormat("none of meta eval strategies matches types %s: %s", FormatTypeVector(types), absl::StrJoin(errors, "; "))); }; } namespace { absl::StatusOr<QTypes> AllTypesAre( absl::Span<const QTypePtr> types, std::function<bool(QTypePtr qtype)> predicate, absl::string_view predicate_str) { for (size_t i = 0; i < types.size(); ++i) { if (!predicate(types[i])) { return InvalidArgTypeError(types, i, absl::StrFormat("be %s", predicate_str)); } } return QTypes(types.begin(), types.end()); } } absl::StatusOr<QTypes> AllSame(absl::Span<const QTypePtr> types) { if (types.empty()) return QTypes{}; for (size_t i = 1; i < types.size(); ++i) { if (types[i] != types[0]) { return absl::Status( absl::StatusCode::kInvalidArgument, absl::StrFormat("expected all types to be equal, got %s and %s", types[0]->name(), types[i]->name())); } } return QTypes{types.begin(), types.end()}; } absl::StatusOr<QTypes> AllSameScalarType(absl::Span<const QTypePtr> types) { if (types.empty()) return QTypes{}; ASSIGN_OR_RETURN(auto qtype_0, GetScalarQType(types[0])); for (size_t i = 1; i < types.size(); ++i) { ASSIGN_OR_RETURN(auto qtype, GetScalarQType(types[i])); if (qtype != qtype_0) { return absl::Status( absl::StatusCode::kInvalidArgument, absl::StrFormat( "expected all scalar types to be equal, got %s and %s", types[0]->name(), types[i]->name())); } } return QTypes{types.begin(), types.end()}; } absl::StatusOr<QTypes> Array(absl::Span<const QTypePtr> types) { return AllTypesAre(types, IsArrayLikeQType, "array"); } absl::StatusOr<QTypes> Numeric(absl::Span<const QTypePtr> types) { return AllTypesAre(types, IsNumeric, "numeric"); } absl::StatusOr<QTypes> Integral(absl::Span<const QTypePtr> types) { return AllTypesAre(types, IsIntegral, "integral"); } absl::StatusOr<QTypes> Floating(absl::Span<const QTypePtr> types) { return AllTypesAre(types, IsFloatingPoint, "floating point"); } absl::StatusOr<QTypes> Boolean(absl::Span<const QTypePtr> types) { return AllTypesAre(types, IsBoolean, "boolean"); } absl::StatusOr<QTypes> String(absl::Span<const QTypePtr> types) { return AllTypesAre(types, IsString, "Text or Bytes"); } absl::StatusOr<QTypes> Text(absl::Span<const QTypePtr> types) { return AllTypesAre(types, IsText, "Text"); } absl::StatusOr<QTypes> Optional(absl::Span<const QTypePtr> types) { return AllTypesAre(types, IsOptionalQType, "optional"); } absl::StatusOr<QTypes> OptionalLike(absl::Span<const QTypePtr> types) { return AllTypesAre(types, IsOptionalLikeQType, "optional"); } absl::StatusOr<QTypes> Scalar(absl::Span<const QTypePtr> types) { return AllTypesAre(types, IsScalarQType, "scalar"); } absl::StatusOr<QTypes> ScalarOrOptional(absl::Span<const QTypePtr> types) { return AllTypesAre( types, [](QTypePtr t) { return IsScalarQType(t) || IsOptionalQType(t); }, "scalar or optional scalar"); } absl::StatusOr<QTypes> IntegralScalar(absl::Span<const QTypePtr> types) { return AllTypesAre(types, IsIntegralScalarQType, "integral"); } absl::StatusOr<QTypes> FloatingScalar(absl::Span<const QTypePtr> types) { return AllTypesAre(types, IsFloatingPointScalarQType, "floating point"); } absl::StatusOr<QTypes> Unary(absl::Span<const QTypePtr> types) { if (types.size() != 1) { return absl::InvalidArgumentError( absl::StrCat("expected to have one argument, got ", types.size())); } return QTypes(types.begin(), types.end()); } absl::StatusOr<QTypes> Binary(absl::Span<const QTypePtr> types) { if (types.size() != 2) { return absl::InvalidArgumentError( absl::StrCat("expected to have two arguments, got ", types.size())); } return QTypes(types.begin(), types.end()); } absl::StatusOr<QTypes> Ternary(absl::Span<const QTypePtr> types) { if (types.size() != 3) { return absl::InvalidArgumentError( absl::StrCat("expected to have three arguments, got ", types.size())); } return QTypes(types.begin(), types.end()); } absl::StatusOr<QTypes> CommonType(absl::Span<const QTypePtr> types) { const CastingRegistry* registry = CastingRegistry::GetInstance(); ASSIGN_OR_RETURN(auto common_type, registry->CommonType(types, true)); return QTypes{common_type}; } namespace { absl::StatusOr<QTypes> TakeArguments(absl::Span<const int> index_list, absl::Span<const QTypePtr> types) { if (index_list.empty()) { return QTypes{}; } QTypes arg_types; arg_types.reserve(index_list.size()); for (int arg : index_list) { if (arg < 0) { return absl::InvalidArgumentError( absl::StrFormat("invalid argument index: %d", arg)); } if (arg >= types.size()) { size_t max_i = *std::max_element(index_list.begin(), index_list.end()); return absl::Status( absl::StatusCode::kInvalidArgument, absl::StrFormat("expected to have at least %d argument(s), got %d", max_i + 1, types.size())); } arg_types.push_back(types[arg]); } return arg_types; } } Strategy Nth(std::initializer_list<int> index_list) { absl::InlinedVector<int, 8> indexes(index_list); return [indexes](absl::Span<const QTypePtr> types) -> absl::StatusOr<QTypes> { return TakeArguments(indexes, types); }; } Strategy NthMatch(std::initializer_list<int> index_list, Strategy strategy) { absl::InlinedVector<int, 8> indexes(index_list); return [indexes, strategy]( absl::Span<const QTypePtr> types) -> absl::StatusOr<QTypes> { ASSIGN_OR_RETURN(auto arg_types, TakeArguments(indexes, types)); RETURN_IF_ERROR(strategy(arg_types).status()) << "for arguments (" << absl::StrJoin(indexes, ", ") << ")"; return QTypes{types.begin(), types.end()}; }; } Strategy NthMatch(int n, Strategy strategy) { return NthMatch({n}, strategy); } Strategy NthApply(std::initializer_list<int> index_list, Strategy strategy) { absl::InlinedVector<int, 8> indexes(index_list); return [indexes, strategy]( absl::Span<const QTypePtr> types) -> absl::StatusOr<QTypes> { ASSIGN_OR_RETURN(auto arg_types, TakeArguments(indexes, types)); ASSIGN_OR_RETURN( auto applied_args, strategy(arg_types), _ << "for arguments (" << absl::StrJoin(indexes, ", ") << ")"); QTypes res(types.begin(), types.end()); for (int i = 0; i < indexes.size(); i++) { res[indexes[i]] = applied_args[i]; } return res; }; } Strategy NthApply(int n, Strategy strategy) { return NthApply({n}, strategy); } Strategy FirstMatchingTypeStrategy(std::function<bool(QTypePtr)> predicate_fn, Strategy default_fn) { return [=](absl::Span<const QTypePtr> types) -> absl::StatusOr<QTypes> { if (auto it = std::find_if(types.begin(), types.end(), predicate_fn); it != types.end()) { return QTypes{*it}; } else { return default_fn(types); } }; } absl::StatusOr<QTypes> ToOptional(absl::Span<const QTypePtr> types) { QTypes result(types.size(), nullptr); for (size_t i = 0; i < types.size(); ++i) { ASSIGN_OR_RETURN(result[i], ToOptionalLikeQType(types[i]), _ << "in argument " << i); } return result; } absl::StatusOr<QTypes> ToTestResult(absl::Span<const QTypePtr> types) { QTypes result(types.size(), nullptr); for (size_t i = 0; i < types.size(); ++i) { ASSIGN_OR_RETURN(auto opt_type, ToOptionalLikeQType(types[i]), _ << "in argument " << i); ASSIGN_OR_RETURN(result[i], GetPresenceQType(opt_type), _ << "in argument " << i); } return result; } absl::StatusOr<QTypes> ToShape(absl::Span<const QTypePtr> types) { QTypes result(types.size(), nullptr); for (size_t i = 0; i < types.size(); ++i) { ASSIGN_OR_RETURN(result[i], GetShapeQType(types[i]), _ << "in argument " << i); } return result; } absl::StatusOr<QTypes> IsShape(absl::Span<const QTypePtr> qtypes) { for (auto qtype : qtypes) { if (!IsShapeQType(qtype)) { return absl::InvalidArgumentError(absl::StrFormat( "expected all arguments to be shapes, got %s", qtype->name())); } } return QTypes{qtypes.begin(), qtypes.end()}; } absl::StatusOr<QTypes> IsArrayShape(absl::Span<const QTypePtr> qtypes) { for (auto qtype : qtypes) { if (!IsArrayLikeShapeQType(qtype)) { return absl::InvalidArgumentError(absl::StrFormat( "expected all arguments to be array shapes, got %s", qtype->name())); } } return QTypes{qtypes.begin(), qtypes.end()}; } absl::StatusOr<QTypes> IsEdge(absl::Span<const QTypePtr> qtypes) { for (auto qtype : qtypes) { if (dynamic_cast<const EdgeQType*>(qtype) == nullptr) { return absl::InvalidArgumentError(absl::StrFormat( "expected all arguments to be edges, got %s", qtype->name())); } } return QTypes{qtypes.begin(), qtypes.end()}; } absl::StatusOr<QTypes> IsArray(absl::Span<const QTypePtr> qtypes) { for (auto qtype : qtypes) { if (!IsArrayQType(qtype)) { return absl::InvalidArgumentError(absl::StrFormat( "expected all arguments to be Arrays, got %s", qtype->name())); } } return QTypes{qtypes.begin(), qtypes.end()}; } absl::StatusOr<QTypes> IsDenseArray(absl::Span<const QTypePtr> qtypes) { for (auto qtype : qtypes) { if (!IsDenseArrayQType(qtype)) { return absl::InvalidArgumentError(absl::StrFormat( "expected all arguments to be DenseArrays, got %s", qtype->name())); } } return QTypes{qtypes.begin(), qtypes.end()}; } Strategy LiftResultType(QTypePtr scalar_type) { return [scalar_type]( absl::Span<const QTypePtr> types) -> absl::StatusOr<QTypes> { for (auto type : types) { if (IsArrayLikeQType(type)) { ASSIGN_OR_RETURN(auto result_type, WithScalarQType(type, scalar_type)); return QTypes{result_type}; } } for (auto type : types) { if (IsOptionalLikeQType(type)) { ASSIGN_OR_RETURN(auto result_type, WithScalarQType(type, scalar_type)); return QTypes{result_type}; } } return QTypes{scalar_type}; }; } Strategy LiftNthType(int n) { return [n](absl::Span<const QTypePtr> types) -> absl::StatusOr<QTypes> { if (n >= types.size()) { return absl::Status( absl::StatusCode::kInvalidArgument, absl::StrFormat("expected at least %d arguments, got %d", n + 1, types.size())); } ASSIGN_OR_RETURN(auto scalar_type, GetScalarQType(types[n])); return LiftResultType(scalar_type)(types); }; } absl::StatusOr<QTypes> Broadcast(absl::Span<const QTypePtr> qtypes) { const auto is_scalar_like_shape_qtype = [](const ShapeQType* qtype) { return qtype == GetQType<ScalarShape>() || qtype == GetQType<OptionalScalarShape>(); }; const auto combine_shape_qtypes = [&](const ShapeQType* lhs, const ShapeQType* rhs) -> absl::StatusOr<const ShapeQType*> { if (lhs == rhs) { return lhs; } if (is_scalar_like_shape_qtype(lhs)) { return rhs; } else if (is_scalar_like_shape_qtype(rhs)) { return lhs; } return absl::InvalidArgumentError("unable to broadcast arguments"); }; const ShapeQType* common_shape_qtype = static_cast<const ShapeQType*>(GetQType<ScalarShape>()); for (auto qtype : qtypes) { ASSIGN_OR_RETURN(const ShapeQType* shape_qtype, GetShapeQType(qtype)); ASSIGN_OR_RETURN(common_shape_qtype, combine_shape_qtypes(common_shape_qtype, shape_qtype), _ << JoinTypeNames(qtypes)); } if (is_scalar_like_shape_qtype(common_shape_qtype)) { return QTypes{qtypes.begin(), qtypes.end()}; } QTypes result; result.reserve(qtypes.size()); for (QTypePtr qtype : qtypes) { ASSIGN_OR_RETURN(qtyp
#include "arolla/expr/operators/type_meta_eval_strategies.h" #include <cstdint> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "arolla/array/array.h" #include "arolla/array/edge.h" #include "arolla/array/qtype/types.h" #include "arolla/dense_array/dense_array.h" #include "arolla/dense_array/edge.h" #include "arolla/dense_array/qtype/types.h" #include "arolla/memory/optional_value.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/optional_qtype.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/shape_qtype.h" #include "arolla/util/bytes.h" #include "arolla/util/init_arolla.h" #include "arolla/util/testing/status_matchers_backport.h" #include "arolla/util/text.h" namespace arolla::expr_operators { namespace { using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::StatusIs; using ::testing::ElementsAre; using ::testing::ElementsAreArray; using ::testing::HasSubstr; using ::arolla::expr_operators::type_meta::AllSame; using ::arolla::expr_operators::type_meta::AllSameScalarType; using ::arolla::expr_operators::type_meta::ArgCount; using ::arolla::expr_operators::type_meta::Broadcast; using ::arolla::expr_operators::type_meta::CallableStrategy; using ::arolla::expr_operators::type_meta::FirstMatchingTypeStrategy; using ::arolla::expr_operators::type_meta::Is; using ::arolla::expr_operators::type_meta::IsArrayShape; using ::arolla::expr_operators::type_meta::IsDenseArray; using ::arolla::expr_operators::type_meta::IsEdge; using ::arolla::expr_operators::type_meta::IsNot; using ::arolla::expr_operators::type_meta::IsShape; using ::arolla::expr_operators::type_meta::LiftResultType; using ::arolla::expr_operators::type_meta::Nth; using ::arolla::expr_operators::type_meta::NthApply; using ::arolla::expr_operators::type_meta::NthMatch; using ::arolla::expr_operators::type_meta::Optional; using ::arolla::expr_operators::type_meta::OptionalLike; using ::arolla::expr_operators::type_meta::Scalar; using ::arolla::expr_operators::type_meta::ScalarOrOptional; using ::arolla::expr_operators::type_meta::ScalarTypeIs; using ::arolla::expr_operators::type_meta::ToOptional; using ::arolla::expr_operators::type_meta::ToShape; using ::arolla::expr_operators::type_meta::Unary; class TypeMetaEvalStrategiesTest : public ::testing::Test { protected: void SetUp() override { ASSERT_OK(InitArolla()); } }; TEST_F(TypeMetaEvalStrategiesTest, ArgCount) { std::vector<QTypePtr> i32_types = {GetQType<int32_t>(), GetQType<int32_t>(), GetQType<int32_t>()}; std::vector<QTypePtr> empty = {}; EXPECT_THAT(ArgCount(3)(i32_types), IsOkAndHolds(ElementsAreArray(i32_types))); EXPECT_THAT(ArgCount(1)(empty), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("expected to have 1 arguments, got 0"))); EXPECT_THAT(ArgCount(0)(i32_types), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("expected to have 0 arguments, got 3"))); } TEST_F(TypeMetaEvalStrategiesTest, NthSingleArg) { auto second_type = CallableStrategy(Nth(1)); EXPECT_THAT(second_type({GetQType<int32_t>(), GetQType<int64_t>()}), IsOkAndHolds(GetQType<int64_t>())); EXPECT_THAT( second_type({}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("expected to have at least 2 argument(s), got 0"))); } TEST_F(TypeMetaEvalStrategiesTest, NthMultipleArgs) { auto i32 = GetQType<int32_t>(); auto oi32 = GetQType<OptionalValue<int32_t>>(); auto f32 = GetQType<float>(); auto of32 = GetQType<OptionalValue<float>>(); std::vector<QTypePtr> types = {i32, oi32, f32, of32}; EXPECT_THAT((Nth({0, 2})(types)), IsOkAndHolds(ElementsAre(i32, f32))); EXPECT_THAT((Nth({1, 3})(types)), IsOkAndHolds(ElementsAre(oi32, of32))); EXPECT_THAT((Nth({0, 2, 4})(types)), StatusIs(absl::StatusCode::kInvalidArgument, "expected to have at least 5 argument(s), got 4")); } TEST_F(TypeMetaEvalStrategiesTest, Scalar) { EXPECT_THAT( Scalar({GetQType<int32_t>(), GetQType<float>()}), IsOkAndHolds(ElementsAre(GetQType<int32_t>(), GetQType<float>()))); EXPECT_THAT( Scalar({GetQType<int32_t>(), GetOptionalQType<int32_t>()}), StatusIs( absl::StatusCode::kInvalidArgument, HasSubstr( "expected all arguments to be scalar, but got OPTIONAL_INT32"))); EXPECT_THAT(Scalar({GetQType<int32_t>(), GetDenseArrayQType<int32_t>()}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("expected all arguments to be scalar, but got " "DENSE_ARRAY_INT32"))); } TEST_F(TypeMetaEvalStrategiesTest, Optional) { EXPECT_THAT( Optional({GetOptionalQType<int32_t>(), GetOptionalQType<float>()}), IsOkAndHolds( ElementsAre(GetOptionalQType<int32_t>(), GetOptionalQType<float>()))); EXPECT_THAT( Optional({GetOptionalQType<int32_t>(), GetQType<int32_t>()}), StatusIs( absl::StatusCode::kInvalidArgument, HasSubstr("expected all arguments to be optional, but got INT32"))); EXPECT_THAT( Optional({GetOptionalQType<int32_t>(), GetDenseArrayQType<int32_t>()}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("expected all arguments to be optional, but got " "DENSE_ARRAY_INT32"))); } TEST_F(TypeMetaEvalStrategiesTest, ScalarOrOptional) { EXPECT_THAT( ScalarOrOptional({GetOptionalQType<int32_t>(), GetQType<float>()}), IsOkAndHolds( ElementsAre(GetOptionalQType<int32_t>(), GetQType<float>()))); EXPECT_THAT( ScalarOrOptional( {GetOptionalQType<int32_t>(), GetDenseArrayQType<int32_t>()}), StatusIs( absl::StatusCode::kInvalidArgument, HasSubstr( "expected all arguments to be scalar or optional scalar, but got " "DENSE_ARRAY_INT32"))); } TEST_F(TypeMetaEvalStrategiesTest, OptionalLike) { EXPECT_THAT(OptionalLike( {GetOptionalQType<int32_t>(), GetDenseArrayQType<int32_t>()}), IsOkAndHolds(ElementsAre(GetOptionalQType<int32_t>(), GetDenseArrayQType<int32_t>()))); EXPECT_THAT( OptionalLike({GetOptionalQType<int32_t>(), GetQType<int32_t>()}), StatusIs( absl::StatusCode::kInvalidArgument, HasSubstr("expected all arguments to be optional, but got INT32"))); EXPECT_THAT( OptionalLike({GetOptionalQType<int32_t>(), GetQType<DenseArrayEdge>()}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("expected all arguments to be optional, but got " "DENSE_ARRAY_EDGE"))); } TEST_F(TypeMetaEvalStrategiesTest, FirstMatchingTypeStrategy) { auto first_numeric = CallableStrategy(FirstMatchingTypeStrategy(IsNumeric, Nth(0))); EXPECT_THAT(first_numeric({GetQType<int32_t>(), GetQType<int64_t>()}), IsOkAndHolds(GetQType<int32_t>())); EXPECT_THAT(first_numeric({GetQType<Text>(), GetQType<int64_t>()}), IsOkAndHolds(GetQType<int64_t>())); EXPECT_THAT(first_numeric({GetQType<int32_t>(), GetQType<Text>()}), IsOkAndHolds(GetQType<int32_t>())); EXPECT_THAT(first_numeric({GetQType<Text>(), GetQType<Text>()}), IsOkAndHolds(GetQType<Text>())); EXPECT_THAT( first_numeric({}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("expected to have at least 1 argument(s), got 0"))); } TEST_F(TypeMetaEvalStrategiesTest, IsNumeric) { EXPECT_TRUE(IsNumeric(GetQType<int32_t>())); EXPECT_TRUE(IsNumeric(GetQType<float>())); EXPECT_TRUE(IsNumeric(GetOptionalQType<float>())); EXPECT_TRUE(IsNumeric(GetArrayQType<float>())); EXPECT_TRUE(IsNumeric(GetDenseArrayQType<float>())); EXPECT_FALSE(IsNumeric(GetQType<bool>())); EXPECT_FALSE(IsNumeric(GetQType<Bytes>())); EXPECT_FALSE(IsNumeric(GetArrayQType<bool>())); EXPECT_FALSE(IsNumeric(GetDenseArrayQType<bool>())); EXPECT_FALSE(IsNumeric(GetOptionalQType<bool>())); } TEST_F(TypeMetaEvalStrategiesTest, NthMatch) { std::vector<QTypePtr> i32_types = {GetQType<int32_t>(), GetQType<int32_t>(), GetQType<int32_t>()}; std::vector<QTypePtr> i32_type = {GetQType<int32_t>()}; std::vector<QTypePtr> i32_types_len_2 = {GetQType<int32_t>(), GetQType<int32_t>()}; EXPECT_THAT((NthMatch(1, Is<int32_t>)(i32_types)), IsOkAndHolds(ElementsAreArray(i32_types))); EXPECT_THAT( (NthMatch(1, Is<int64_t>)(i32_types)), StatusIs(absl::StatusCode::kInvalidArgument, "expected type to be INT64, got INT32; for arguments (1)")); EXPECT_THAT((NthMatch(1, Is<int64_t>)(i32_type)), StatusIs(absl::StatusCode::kInvalidArgument, "expected to have at least 2 argument(s), got 1")); EXPECT_THAT((NthMatch(2, Is<int32_t>)(i32_types)), IsOkAndHolds(ElementsAreArray(i32_types))); EXPECT_THAT( (NthMatch(2, Is<int64_t>)(i32_types)), StatusIs(absl::StatusCode::kInvalidArgument, "expected type to be INT64, got INT32; for arguments (2)")); EXPECT_THAT((NthMatch(2, Is<int64_t>)(i32_types_len_2)), StatusIs(absl::StatusCode::kInvalidArgument, "expected to have at least 3 argument(s), got 2")); std::vector<QTypePtr> types1 = {GetQType<int32_t>(), GetQType<int32_t>(), GetQType<OptionalValue<int32_t>>(), GetQType<OptionalValue<int32_t>>(), GetQType<float>()}; EXPECT_THAT((NthMatch({0, 1}, AllSame)(types1)), IsOkAndHolds(ElementsAreArray(types1))); EXPECT_THAT((NthMatch({2, 3}, AllSame)(types1)), IsOkAndHolds(ElementsAreArray(types1))); EXPECT_THAT((NthMatch({0, 1, 2, 3}, AllSameScalarType)(types1)), IsOkAndHolds(ElementsAreArray(types1))); EXPECT_THAT((NthMatch({0, 2}, AllSame)(types1)), StatusIs(absl::StatusCode::kInvalidArgument, "expected all types to be equal, got INT32 and " "OPTIONAL_INT32; for arguments (0, 2)")); EXPECT_THAT((NthMatch({0, 2}, AllSame)({GetQType<int32_t>()})), StatusIs(absl::StatusCode::kInvalidArgument, "expected to have at least 3 argument(s), got 1")); } TEST_F(TypeMetaEvalStrategiesTest, NthApply) { std::vector<QTypePtr> types = {GetQType<int32_t>(), GetDenseArrayQType<int32_t>(), GetArrayQType<int32_t>()}; { std::vector<QTypePtr> res_types = {GetDenseArrayQType<int32_t>(), GetDenseArrayQType<int32_t>(), GetArrayQType<int32_t>()}; EXPECT_THAT(NthApply({0, 1}, Broadcast)(types), IsOkAndHolds(ElementsAreArray(res_types))); } { std::vector<QTypePtr> res_types = {GetArrayQType<int32_t>(), GetDenseArrayQType<int32_t>(), GetArrayQType<int32_t>()}; EXPECT_THAT(NthApply({0, 2}, Broadcast)(types), IsOkAndHolds(ElementsAreArray(res_types))); } { std::vector<QTypePtr> res_types = {GetOptionalQType<int32_t>(), GetDenseArrayQType<int32_t>(), GetArrayQType<int32_t>()}; EXPECT_THAT(NthApply(0, ToOptional)(types), IsOkAndHolds(ElementsAreArray(res_types))); } EXPECT_THAT(NthApply({1, 2}, Broadcast)(types), StatusIs(absl::StatusCode::kInvalidArgument, "unable to broadcast arguments; " "DENSE_ARRAY_INT32,ARRAY_INT32; for arguments (1, 2)")); EXPECT_THAT(NthApply({2, 3}, Broadcast)(types), StatusIs(absl::StatusCode::kInvalidArgument, "expected to have at least 4 argument(s), got 3")); } TEST_F(TypeMetaEvalStrategiesTest, LiftResultType) { auto i32 = GetQType<int32_t>(); auto f32 = GetQType<float>(); auto oi32 = GetOptionalQType<int32_t>(); auto of32 = GetOptionalQType<float>(); auto ai32 = GetArrayQType<int32_t>(); auto af32 = GetArrayQType<float>(); auto lift_f32 = CallableStrategy(LiftResultType(f32)); EXPECT_THAT(lift_f32({}), IsOkAndHolds(f32)); EXPECT_THAT(lift_f32({i32}), IsOkAndHolds(f32)); EXPECT_THAT(lift_f32({i32, f32}), IsOkAndHolds(f32)); EXPECT_THAT(lift_f32({oi32}), IsOkAndHolds(of32)); EXPECT_THAT(lift_f32({i32, oi32}), IsOkAndHolds(of32)); EXPECT_THAT(lift_f32({ai32}), IsOkAndHolds(af32)); EXPECT_THAT(lift_f32({oi32, ai32}), IsOkAndHolds(af32)); EXPECT_THAT(lift_f32({i32, oi32, ai32}), IsOkAndHolds(af32)); } TEST_F(TypeMetaEvalStrategiesTest, Broadcast) { auto i32 = GetQType<int32_t>(); auto f32 = GetQType<float>(); auto oi32 = GetOptionalQType<int32_t>(); auto ai32 = GetArrayQType<int32_t>(); auto af32 = GetArrayQType<float>(); auto di32 = GetDenseArrayQType<int32_t>(); auto df32 = GetDenseArrayQType<float>(); EXPECT_THAT(Broadcast({}), IsOkAndHolds(ElementsAre())); EXPECT_THAT(Broadcast({i32}), IsOkAndHolds(ElementsAre(i32))); EXPECT_THAT(Broadcast({i32, f32}), IsOkAndHolds(ElementsAre(i32, f32))); EXPECT_THAT(Broadcast({i32, oi32}), IsOkAndHolds(ElementsAre(i32, oi32))); EXPECT_THAT(Broadcast({ai32}), IsOkAndHolds(ElementsAre(ai32))); EXPECT_THAT(Broadcast({ai32, f32}), IsOkAndHolds(ElementsAre(ai32, af32))); EXPECT_THAT(Broadcast({i32, oi32, af32}), IsOkAndHolds(ElementsAre(ai32, ai32, af32))); EXPECT_THAT(Broadcast({i32, oi32, af32, ai32}), IsOkAndHolds(ElementsAre(ai32, ai32, af32, ai32))); EXPECT_THAT( Broadcast({df32, GetQType<int32_t>(), GetOptionalQType<int32_t>()}), IsOkAndHolds(ElementsAre(df32, di32, di32))); EXPECT_THAT(Broadcast({af32, df32}), StatusIs(absl::StatusCode::kInvalidArgument)); } TEST_F(TypeMetaEvalStrategiesTest, Is) { std::vector<QTypePtr> i32_types = {GetQType<int32_t>(), GetQType<int32_t>()}; EXPECT_THAT(Is<int32_t>(i32_types), IsOkAndHolds(ElementsAreArray(i32_types))); EXPECT_THAT(Is(GetQType<int32_t>())(i32_types), IsOkAndHolds(ElementsAreArray(i32_types))); EXPECT_THAT(Is<int64_t>(i32_types), StatusIs(absl::StatusCode::kInvalidArgument, "expected type of argument 0 to be INT64, got INT32")); EXPECT_THAT(Is(GetQType<int64_t>())(i32_types), StatusIs(absl::StatusCode::kInvalidArgument, "expected type of argument 0 to be INT64, got INT32")); } TEST_F(TypeMetaEvalStrategiesTest, IsNot) { std::vector<QTypePtr> i32_types = {GetQType<int32_t>(), GetQType<int32_t>()}; EXPECT_THAT(IsNot<int64_t>(i32_types), IsOkAndHolds(ElementsAreArray(i32_types))); EXPECT_THAT(IsNot(GetQType<int64_t>())(i32_types), IsOkAndHolds(ElementsAreArray(i32_types))); EXPECT_THAT(IsNot<int32_t>(i32_types), StatusIs(absl::StatusCode::kInvalidArgument, "expected type of argument 0 to be not INT32")); EXPECT_THAT(IsNot(GetQType<int32_t>())(i32_types), StatusIs(absl::StatusCode::kInvalidArgument, "expected type of argument 0 to be not INT32")); } TEST_F(TypeMetaEvalStrategiesTest, ScalarTypeIs) { std::vector<QTypePtr> i32_types = { GetQType<int32_t>(), GetOptionalQType<int32_t>(), GetDenseArrayQType<int32_t>(), GetDenseArrayQType<int32_t>(), GetArrayQType<int32_t>()}; EXPECT_THAT(ScalarTypeIs<int32_t>(i32_types), IsOkAndHolds(ElementsAreArray(i32_types))); EXPECT_THAT( ScalarTypeIs<int64_t>(i32_types), StatusIs(absl::StatusCode::kInvalidArgument, "expected scalar type of argument 0 to be INT64, got INT32")); } TEST_F(TypeMetaEvalStrategiesTest, Unary) { auto single_arg_type = CallableStrategy(Unary); EXPECT_THAT(single_arg_type({GetQType<int32_t>()}), IsOkAndHolds(GetQType<int32_t>())); EXPECT_THAT(single_arg_type({GetQType<int32_t>(), GetQType<int32_t>()}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("expected to have one argument"))); } TEST_F(TypeMetaEvalStrategiesTest, ToShape) { auto shape_type = CallableStrategy(ToShape); EXPECT_THAT(shape_type({GetQType<int32_t>()}), IsOkAndHolds(GetQType<ScalarShape>())); EXPECT_THAT(shape_type({GetArrayQType<bool>()}), IsOkAndHolds(GetQType<ArrayShape>())); EXPECT_THAT(shape_type({GetDenseArrayQType<bool>()}), IsOkAndHolds(GetQType<DenseArrayShape>())); EXPECT_THAT(shape_type({GetQType<OptionalValue<bool>>()}), IsOkAndHolds(GetQType<OptionalScalarShape>())); EXPECT_THAT(shape_type({GetQType<OptionalScalarShape>()}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("no shape type for"))); } TEST_F(TypeMetaEvalStrategiesTest, ToOptional) { auto to_optional = CallableStrategy(ToOptional); EXPECT_THAT(to_optional({GetArrayQType<int32_t>()}), IsOkAndHolds(GetArrayQType<int32_t>())); EXPECT_THAT( to_optional({GetQType<ArrayEdge>()}), StatusIs( absl::StatusCode::kInvalidArgument, HasSubstr("no optional-like qtype for ARRAY_EDGE; in argument 0"))); } TEST_F(TypeMetaEvalStrategiesTest, AllSame) { EXPECT_THAT(AllSame({GetArrayQType<int32_t>(), GetArrayQType<int32_t>()}), IsOkAndHolds(ElementsAreArray( {GetArrayQType<int32_t>(), GetArrayQType<int32_t>()}))); EXPECT_THAT(AllSame({}), IsOkAndHolds(ElementsAre())); EXPECT_THAT(AllSame({GetArrayQType<int32_t>(), GetArrayQType<int64_t>()}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("expected all types to be equal, got " "ARRAY_INT32 and ARRAY_INT64"))); } TEST_F(TypeMetaEvalStrategiesTest, AllSameScalarType) { EXPECT_THAT(AllSameScalarType( {GetQType<int32_t>(), GetQType<OptionalValue<int32_t>>()}), IsOkAndHolds(ElementsAre(GetQType<int32_t>(), GetQType<OptionalValue<int32_t>>()))); EXPECT_THAT(AllSameScalarType({}), IsOkAndHolds(ElementsAre())); EXPECT_THAT(AllSameScalarType({GetQType<int32_t>(), GetQType<float>()}), StatusIs(absl::StatusCode::kInvalidArgument, "expected all scalar types to be equal, got INT32 and " "FLOAT32")); } TEST_F(TypeMetaEvalStrategiesTest, IsShape) { auto shape_qtypes = {GetQType<ScalarShape>(), GetQType<ArrayShape>()}; auto non_shape_qtypes = {GetQType<OptionalScalarShape>(), GetQType<int32_t>()}; EXPECT_THAT(IsShape(shape_qtypes), IsOkAndHolds(ElementsAreArray(shape_qtypes))); EXPECT_THAT( IsShape(non_shape_qtypes), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("expected all arguments to be shapes, got INT32"))); } TEST_F(TypeMetaEvalStrategiesTest, IsArrayShape) { auto shape_qtypes = {GetQType<ArrayShape>(), GetQType<DenseArrayShape>()}; auto non_shape_qtypes = {GetQType<ArrayShape>(), GetQType<ScalarShape>()}; EXPECT_THAT(IsArrayShape(shape_qtypes), IsOkAndHolds(ElementsAreArray(shape_qtypes))); EXPECT_THAT( IsArrayShape(non_shape_qtypes), StatusIs( absl::StatusCode::kInvalidArgument, HasSubstr( "expected all arguments to be array shapes, got SCALAR_SHAPE"))); } TEST_F(TypeMetaEvalStrategiesTest, IsEdge) { auto edge_qtypes = {GetQType<ArrayEdge>(), GetQType<DenseArrayEdge>()}; EXPECT_THAT(IsEdge(edge_qtypes), IsOkAndHolds(ElementsAreArray(edge_qtypes))); EXPECT_THAT( IsEdge({GetQType<ArrayEdge>(), GetQType<int32_t>()}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("expected all arguments to be edges, got INT32"))); } TEST_F(TypeMetaEvalStrategiesTest, IsDenseArray) { auto da_qtypes = {GetDenseArrayQType<int64_t>(), GetDenseArrayQType<float>()}; EXPECT_THAT(IsDenseArray(da_qtypes), IsOkAndHolds(ElementsAreArray(da_qtypes))); EXPECT_THAT( IsDenseArray({GetArrayQType<int64_t>(), GetDenseArrayQType<int64_t>()}), StatusIs( absl::StatusCode::kInvalidArgument, HasSubstr( "expected all arguments to be DenseArrays, got ARRAY_INT64"))); } TEST_F(TypeMetaEvalStrategiesTest, EdgeParentShapeQType) { auto edge_qtypes = {GetQType<ArrayEdge>(), GetQType<DenseArrayEdge>(), GetQType<ArrayGroupScalarEdge>(), GetQType<DenseArrayGroupScalarEdge>()}; auto shape_qtypes = {GetQType<ArrayShape>(), GetQType<DenseArrayShape>(), GetQType<OptionalScalarShape>(), GetQType<OptionalScalarShape>()}; EXPECT_THAT(type_meta::EdgeParentShapeQType(edge_qtypes), IsOkAndHolds(ElementsAreArray(shape_qtypes))); EXPECT_THAT( type_meta::EdgeParentShapeQType({GetArrayQType<int64_t>()}), StatusIs( absl::StatusCode::kInvalidArgument, HasSubstr("invalid argument 0: expected an edge, got ARRAY_INT64"))); } } }
2,438
#ifndef AROLLA_EXPR_OPERATORS_CASTING_REGISTRY_H_ #define AROLLA_EXPR_OPERATORS_CASTING_REGISTRY_H_ #include <optional> #include "absl/container/flat_hash_map.h" #include "absl/status/statusor.h" #include "absl/types/span.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_operator.h" #include "arolla/qtype/qtype.h" namespace arolla::expr_operators { class CastingRegistry { public: static CastingRegistry* GetInstance(); absl::StatusOr<expr::ExprNodePtr> GetCast( expr::ExprNodePtr node, QTypePtr to_qtype, bool implicit_only, std::optional<expr::ExprNodePtr> shape_for_broadcasting = std::nullopt) const; absl::StatusOr<QTypePtr> CommonType(absl::Span<const QTypePtr> arg_types, bool enable_broadcasting = false) const; private: CastingRegistry(); absl::flat_hash_map<QTypePtr, expr::ExprOperatorPtr> cast_to_ops_; }; } #endif #include "arolla/expr/operators/casting_registry.h" #include <cstdint> #include <memory> #include <optional> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "arolla/expr/derived_qtype_cast_operator.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_debug_string.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/registered_expr_operator.h" #include "arolla/qtype/array_like/array_like_qtype.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/optional_qtype.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/standard_type_properties/common_qtype.h" #include "arolla/qtype/standard_type_properties/properties.h" #include "arolla/qtype/weak_qtype.h" #include "arolla/util/indestructible.h" #include "arolla/util/status_macros_backport.h" namespace arolla::expr_operators { using ::arolla::expr::CallOp; using ::arolla::expr::ExprNodePtr; using ::arolla::expr::RegisteredOperator; CastingRegistry* CastingRegistry::GetInstance() { static Indestructible<CastingRegistry> instance( [](auto* self) { new (self) CastingRegistry; }); return instance.get(); } CastingRegistry::CastingRegistry() { cast_to_ops_ = { {GetQType<bool>(), std::make_shared<RegisteredOperator>("core.to_bool")}, {GetQType<int32_t>(), std::make_shared<RegisteredOperator>("core.to_int32")}, {GetQType<int64_t>(), std::make_shared<RegisteredOperator>("core.to_int64")}, {GetQType<float>(), std::make_shared<RegisteredOperator>("core.to_float32")}, {GetQType<double>(), std::make_shared<RegisteredOperator>("core.to_float64")}, {GetWeakFloatQType(), std::make_shared<RegisteredOperator>("core._to_weak_float")}, {GetQType<uint64_t>(), std::make_shared<RegisteredOperator>("core.to_uint64")}, }; } absl::StatusOr<ExprNodePtr> CastingRegistry::GetCast( ExprNodePtr node, QTypePtr to_qtype, bool implicit_only, std::optional<ExprNodePtr> shape_for_broadcasting) const { const QType* from_qtype = node->qtype(); if (from_qtype == nullptr) { return absl::FailedPreconditionError(absl::StrFormat( "cannot cast expression %s with unknown QType", GetDebugSnippet(node))); } if (from_qtype == to_qtype) { return node; } if (implicit_only && !CanCastImplicitly( from_qtype, to_qtype, shape_for_broadcasting.has_value())) { return absl::InvalidArgumentError( absl::StrFormat("implicit casting from %s to %s is not allowed", from_qtype->name(), to_qtype->name())); } ASSIGN_OR_RETURN(auto from_scalar_qtype, GetScalarQType(from_qtype)); ASSIGN_OR_RETURN(auto to_scalar_qtype, GetScalarQType(to_qtype)); if (from_scalar_qtype == GetWeakFloatQType() && from_scalar_qtype != to_scalar_qtype) { const auto upcast_op = std::make_shared<expr::DerivedQTypeUpcastOperator>(node->qtype()); ASSIGN_OR_RETURN(node, CallOp(upcast_op, {node})); from_scalar_qtype = GetQType<double>(); } if (from_scalar_qtype != to_scalar_qtype) { if (!cast_to_ops_.contains(to_scalar_qtype)) { return absl::InvalidArgumentError( absl::StrFormat("unable to find a cast from %s to %s", from_qtype->name(), to_qtype->name())); } ASSIGN_OR_RETURN(node, CallOp(cast_to_ops_.at(to_scalar_qtype), {node})); if (node->qtype() == to_qtype) { return node; } } if (!IsArrayLikeQType(node->qtype()) && IsArrayLikeQType(to_qtype)) { if (!shape_for_broadcasting.has_value()) { return absl::InvalidArgumentError( absl::StrFormat("unable to cast non-array type %s into an array type " "%s without shape for broadcasting provided", from_qtype->name(), to_qtype->name())); } ASSIGN_OR_RETURN( node, CallOp("core.const_with_shape", {*shape_for_broadcasting, node})); if (node->qtype() == to_qtype) { return node; } } if (!IsOptionalQType(node->qtype()) && IsOptionalQType(to_qtype)) { ASSIGN_OR_RETURN(node, CallOp("core.to_optional", {node})); } if (node->qtype() == to_qtype) { return node; } else { return absl::InvalidArgumentError( absl::StrFormat("unable to find a cast from %s to %s", from_qtype->name(), to_qtype->name())); } } absl::StatusOr<QTypePtr> CastingRegistry::CommonType( absl::Span<const QTypePtr> arg_types, bool enable_broadcasting) const { if (arg_types.empty()) { return absl::InvalidArgumentError( "empty arg_types list passed to CommonType"); } const QType* result_qtype = CommonQType(arg_types, enable_broadcasting); if (result_qtype == nullptr) { if (enable_broadcasting || !CommonType(arg_types, true).ok()) { return absl::InvalidArgumentError( absl::StrCat("no common QType for ", FormatTypeVector(arg_types))); } else { return absl::InvalidArgumentError( absl::StrCat("no common QType without broadcasting for ", FormatTypeVector(arg_types))); } } return result_qtype; } }
#include "arolla/expr/operators/casting_registry.h" #include <cstdint> #include <memory> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "arolla/dense_array/dense_array.h" #include "arolla/dense_array/qtype/types.h" #include "arolla/expr/derived_qtype_cast_operator.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/operators/bootstrap_operators.h" #include "arolla/expr/testing/testing.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/optional_qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/weak_qtype.h" #include "arolla/util/bytes.h" #include "arolla/util/init_arolla.h" #include "arolla/util/testing/status_matchers_backport.h" namespace arolla::expr_operators { namespace { using ::arolla::expr::CallOp; using ::arolla::expr::Leaf; using ::arolla::testing::EqualsExpr; using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::StatusIs; using ::arolla::testing::WithQTypeAnnotation; using ::testing::HasSubstr; class CastingRegistryTest : public ::testing::Test { protected: void SetUp() override { ASSERT_OK(InitArolla()); } }; TEST_F(CastingRegistryTest, CommonType) { const CastingRegistry* reg = CastingRegistry::GetInstance(); EXPECT_THAT(reg->CommonType({GetQType<int32_t>(), GetQType<int32_t>()}), IsOkAndHolds(GetQType<int32_t>())); EXPECT_THAT(reg->CommonType({GetQType<uint64_t>(), GetQType<uint64_t>()}), IsOkAndHolds(GetQType<uint64_t>())); EXPECT_THAT(reg->CommonType({GetQType<int32_t>(), GetQType<int64_t>()}), IsOkAndHolds(GetQType<int64_t>())); EXPECT_THAT( reg->CommonType({GetQType<int32_t>(), GetOptionalQType<int32_t>()}), IsOkAndHolds(GetOptionalQType<int32_t>())); EXPECT_THAT( reg->CommonType({GetQType<uint64_t>(), GetOptionalQType<uint64_t>()}), IsOkAndHolds(GetOptionalQType<uint64_t>())); EXPECT_THAT( reg->CommonType({GetQType<int32_t>(), GetOptionalQType<int64_t>()}), IsOkAndHolds(GetOptionalQType<int64_t>())); EXPECT_THAT(reg->CommonType({GetQType<int32_t>(), GetQType<Bytes>()}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("no common QType for (INT32,BYTES)"))); EXPECT_THAT(reg->CommonType({GetQType<int32_t>(), GetQType<uint64_t>()}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("no common QType for (INT32,UINT64)"))); EXPECT_THAT(reg->CommonType({GetQType<int32_t>(), GetQType<int64_t>()}), IsOkAndHolds(GetQType<int64_t>())); EXPECT_THAT( reg->CommonType({GetQType<int32_t>(), GetQType<Bytes>()}).status(), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT( reg->CommonType({GetOptionalQType<int32_t>(), GetQType<int64_t>()}), IsOkAndHolds(GetOptionalQType<int64_t>())); } TEST_F(CastingRegistryTest, GetCast) { const CastingRegistry* reg = CastingRegistry::GetInstance(); ASSERT_OK_AND_ASSIGN(auto x, WithQTypeAnnotation(Leaf("x"), GetQType<int32_t>())); EXPECT_THAT(reg->GetCast(x, GetOptionalQType<int64_t>(), true), IsOkAndHolds(EqualsExpr( CallOp("core.to_optional", {CallOp("core.to_int64", {x})})))); } TEST_F(CastingRegistryTest, GetCastWithBroadcasting) { const CastingRegistry* reg = CastingRegistry::GetInstance(); GetDenseArrayQType<int64_t>(); ASSERT_OK_AND_ASSIGN(auto x, WithQTypeAnnotation(Leaf("x"), GetQType<int32_t>())); ASSERT_OK_AND_ASSIGN( auto shape, WithQTypeAnnotation(Leaf("shape"), GetQType<DenseArrayShape>())); EXPECT_THAT( reg->GetCast(x, GetDenseArrayQType<int64_t>(), true, shape), IsOkAndHolds(EqualsExpr(CallOp("core.const_with_shape", {shape, CallOp("core.to_int64", {x})})))); } TEST_F(CastingRegistryTest, GetCastFromWeakType) { const CastingRegistry* reg = CastingRegistry::GetInstance(); expr::ExprOperatorPtr upcast_op = std::make_shared<expr::DerivedQTypeUpcastOperator>(GetWeakFloatQType()); { ASSERT_OK_AND_ASSIGN(auto x, WithQTypeAnnotation(Leaf("x"), GetWeakFloatQType())); EXPECT_THAT(reg->GetCast(x, GetOptionalQType<double>(), true), IsOkAndHolds(EqualsExpr( CallOp("core.to_optional", {CallOp(upcast_op, {x})})))); } { expr::ExprOperatorPtr opt_upcast_op = std::make_shared<expr::DerivedQTypeUpcastOperator>( GetOptionalWeakFloatQType()); ASSERT_OK_AND_ASSIGN( auto x, WithQTypeAnnotation(Leaf("x"), GetOptionalWeakFloatQType())); EXPECT_THAT(reg->GetCast(x, GetOptionalQType<double>(), true), IsOkAndHolds(EqualsExpr(CallOp(opt_upcast_op, {x})))); } { ASSERT_OK_AND_ASSIGN(auto x, WithQTypeAnnotation(Leaf("x"), GetWeakFloatQType())); EXPECT_THAT(reg->GetCast(x, GetOptionalWeakFloatQType(), true), IsOkAndHolds(EqualsExpr(CallOp("core.to_optional", {x})))); } { ASSERT_OK_AND_ASSIGN(auto x, WithQTypeAnnotation(Leaf("x"), GetWeakFloatQType())); ASSERT_OK_AND_ASSIGN( auto shape, WithQTypeAnnotation(Leaf("shape"), GetQType<DenseArrayShape>())); GetDenseArrayQType<float>(); EXPECT_THAT( reg->GetCast(x, GetDenseArrayQType<float>(), true, shape), IsOkAndHolds(EqualsExpr(CallOp( "core.const_with_shape", {shape, CallOp("core.to_float32", {CallOp(upcast_op, {x})})})))); } } TEST_F(CastingRegistryTest, GetCastToWeakType) { const CastingRegistry* reg = CastingRegistry::GetInstance(); ASSERT_OK_AND_ASSIGN(auto x, WithQTypeAnnotation(Leaf("x"), GetQType<float>())); { ASSERT_OK_AND_ASSIGN(auto x, WithQTypeAnnotation(Leaf("x"), GetQType<float>())); EXPECT_THAT(reg->GetCast(x, GetWeakFloatQType(), false), IsOkAndHolds(EqualsExpr(CoreToWeakFloat(x)))); } { ASSERT_OK_AND_ASSIGN( auto x, WithQTypeAnnotation(Leaf("x"), GetOptionalQType<float>())); EXPECT_THAT(reg->GetCast(x, GetOptionalWeakFloatQType(), false), IsOkAndHolds(EqualsExpr(CoreToWeakFloat(x)))); } { ASSERT_OK_AND_ASSIGN(auto x, WithQTypeAnnotation(Leaf("x"), GetQType<float>())); EXPECT_THAT(reg->GetCast(x, GetOptionalWeakFloatQType(), false), IsOkAndHolds(EqualsExpr( CallOp("core.to_optional", {CoreToWeakFloat(x)})))); } { GetDenseArrayQType<float>(); GetDenseArrayWeakFloatQType(); ASSERT_OK_AND_ASSIGN( auto x, WithQTypeAnnotation(Leaf("x"), GetDenseArrayQType<float>())); EXPECT_THAT(reg->GetCast(x, GetDenseArrayWeakFloatQType(), false), IsOkAndHolds(EqualsExpr(CoreToWeakFloat(x)))); } { ASSERT_OK_AND_ASSIGN(auto x, WithQTypeAnnotation(Leaf("x"), GetQType<float>())); EXPECT_THAT( reg->GetCast(x, GetWeakFloatQType(), true), StatusIs( absl::StatusCode::kInvalidArgument, HasSubstr( "implicit casting from FLOAT32 to WEAK_FLOAT is not allowed"))); } } } }
2,439
#ifndef AROLLA_EXPR_OPERATORS_AGGREGATION_H_ #define AROLLA_EXPR_OPERATORS_AGGREGATION_H_ #include "absl/status/statusor.h" #include "absl/types/span.h" #include "arolla/expr/basic_expr_operator.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_operator.h" #include "arolla/qtype/qtype.h" namespace arolla::expr_operators { class TakeOperator : public expr::BackendExprOperatorTag, public expr::BasicExprOperator { public: TakeOperator(); absl::StatusOr<QTypePtr> GetOutputQType( absl::Span<const QTypePtr> input_qtypes) const override; absl::StatusOr<expr::ExprNodePtr> ToLowerLevel( const expr::ExprNodePtr& node) const override; }; } #endif #include "arolla/expr/operators/aggregation.h" #include <vector> #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "absl/types/span.h" #include "arolla/expr/basic_expr_operator.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/expr/qtype_utils.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/typed_value.h" #include "arolla/util/fingerprint.h" #include "arolla/util/unit.h" #include "arolla/util/status_macros_backport.h" namespace arolla::expr_operators { using ::arolla::expr::CallOp; using ::arolla::expr::ExprNodePtr; using ::arolla::expr::ExprOperatorPtr; using ::arolla::expr::ExprOperatorSignature; using ::arolla::expr::IsDefaultEdgeArg; using ::arolla::expr::IsGroupScalarEdge; TakeOperator::TakeOperator() : BasicExprOperator( "array.take", ExprOperatorSignature( {{"x"}, {"ids"}, {.name = "over", .default_value = TypedValue::FromValue(kUnit)}, {.name = "ids_over", .default_value = TypedValue::FromValue(kUnit)}}), "", FingerprintHasher("arolla::expr_operators::TakeOperator").Finish()) {} absl::StatusOr<ExprNodePtr> TakeOperator::ToLowerLevel( const ExprNodePtr& node) const { RETURN_IF_ERROR(ValidateNodeDepsCount(*node)); const auto& node_deps = node->node_deps(); DCHECK_GE(node_deps.size(), 4); const ExprNodePtr& values = node_deps[0]; const ExprNodePtr& offsets = node_deps[1]; ExprNodePtr values_edge = node_deps[2]; ExprNodePtr offsets_edge = node_deps[3]; bool is_scalar_values_edge = IsDefaultEdgeArg(values_edge); if (!is_scalar_values_edge) { ASSIGN_OR_RETURN(is_scalar_values_edge, IsGroupScalarEdge(values_edge)); } bool is_scalar_offsets_edge = IsDefaultEdgeArg(offsets_edge); if (!is_scalar_offsets_edge) { ASSIGN_OR_RETURN(is_scalar_offsets_edge, IsGroupScalarEdge(offsets_edge)); } if (is_scalar_values_edge != is_scalar_offsets_edge) { return absl::InvalidArgumentError(absl::StrFormat( "Two edges must share the parent side but only one of them is an edge " "to scalar. is_scalar_values_edge(=%d) != is_scalar_offsets_edge(=%d)", is_scalar_values_edge, is_scalar_offsets_edge)); } if (is_scalar_values_edge) { return CallOp("array.at", {values, offsets}); } if (values_edge->fingerprint() == offsets_edge->fingerprint()) { return CallOp("array._take_over", {values, offsets, values_edge}); } return CallOp("array._take_over_over", {values, offsets, values_edge, offsets_edge}); } absl::StatusOr<QTypePtr> TakeOperator::GetOutputQType( absl::Span<const QTypePtr> input_qtypes) const { return input_qtypes[0]; } }
#include <cmath> #include <cstdint> #include <limits> #include <optional> #include <set> #include <utility> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/numbers.h" #include "absl/strings/string_view.h" #include "absl/strings/substitute.h" #include "arolla/memory/optional_value.h" #include "arolla/qexpr/aggregation_ops_interface.h" #include "arolla/qexpr/operators/aggregation/group_op_accumulators.h" #include "arolla/util/bytes.h" #include "arolla/util/meta.h" #include "arolla/util/testing/status_matchers_backport.h" namespace arolla { namespace { using ::arolla::testing::StatusIs; using ::testing::FloatEq; using ::testing::HasSubstr; struct TestAccumulator : Accumulator<AccumulatorType::kAggregator, int, meta::type_list<>, meta::type_list<int>> { explicit TestAccumulator(int init = 0) : init_val(init) {} void Reset() final { res = init_val; }; void Add(int v) final { res += v; } int GetResult() final { return res; } int init_val; int res; }; struct TestAccumulator2 : public TestAccumulator { static TestAccumulator2 Create(int init = 0) { return TestAccumulator2(init); } static absl::StatusOr<TestAccumulator2> Create(absl::string_view init) { int init_val; if (!absl::SimpleAtoi(init, &init_val)) { return absl::InvalidArgumentError( absl::Substitute("Expected integer, got '$0'", init)); } return TestAccumulator2(init_val); } private: explicit TestAccumulator2(int init) : TestAccumulator(init) {} }; TEST(Accumulator, AddN) { TestAccumulator acc; acc.Reset(); acc.AddN(10, 5); EXPECT_EQ(acc.GetResult(), 50); } TEST(OpInterface, CreateWithConstructor) { ASSERT_OK_AND_ASSIGN(TestAccumulator default_accumulator, CreateAccumulator<TestAccumulator>()); EXPECT_EQ(default_accumulator.init_val, 0); ASSERT_OK_AND_ASSIGN(TestAccumulator init_accumulator, CreateAccumulator<TestAccumulator>(5)); EXPECT_EQ(init_accumulator.init_val, 5); } TEST(OpInterface, CreateWithMethod) { ASSERT_OK_AND_ASSIGN(TestAccumulator2 default_accumulator, CreateAccumulator<TestAccumulator2>()); EXPECT_EQ(default_accumulator.init_val, 0); ASSERT_OK_AND_ASSIGN(TestAccumulator2 init_accumulator, CreateAccumulator<TestAccumulator2>("5")); EXPECT_EQ(init_accumulator.init_val, 5); EXPECT_THAT(CreateAccumulator<TestAccumulator2>("foo"), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("Expected integer, got 'foo'"))); } TEST(Accumulator, LogicalAdd) { LogicalAllAggregator acc; acc.Reset(); EXPECT_EQ(acc.GetResult(), true); acc.Reset(); acc.AddN(2, std::nullopt); EXPECT_EQ(acc.GetResult(), std::nullopt); acc.Reset(); acc.AddN(2, std::nullopt); acc.Add(false); EXPECT_EQ(acc.GetResult(), false); acc.Reset(); acc.Add(std::nullopt); acc.AddN(2, true); EXPECT_EQ(acc.GetResult(), std::nullopt); acc.Reset(); acc.AddN(2, true); EXPECT_EQ(acc.GetResult(), true); } TEST(Accumulator, LogicalOr) { LogicalAnyAggregator acc; acc.Reset(); EXPECT_EQ(acc.GetResult(), false); acc.Reset(); acc.AddN(2, std::nullopt); EXPECT_EQ(acc.GetResult(), std::nullopt); acc.Reset(); acc.AddN(2, std::nullopt); acc.Add(false); EXPECT_EQ(acc.GetResult(), std::nullopt); acc.Reset(); acc.Add(std::nullopt); acc.AddN(2, true); EXPECT_EQ(acc.GetResult(), true); acc.Reset(); acc.AddN(2, true); EXPECT_EQ(acc.GetResult(), true); } TEST(Accumulator, InverseMapping) { InverseMappingAccumulator acc; acc.Add(1); acc.Add(3); acc.Add(2); acc.Add(0); acc.FinalizeFullGroup(); EXPECT_EQ(acc.GetResult(), int64_t{3}); EXPECT_EQ(acc.GetResult(), int64_t{0}); EXPECT_EQ(acc.GetResult(), int64_t{2}); EXPECT_EQ(acc.GetResult(), int64_t{1}); EXPECT_EQ(acc.GetStatus(), absl::OkStatus()); acc.Reset(); acc.Add(std::nullopt); acc.Add(4); acc.Add(0); acc.Add(std::nullopt); acc.Add(2); acc.FinalizeFullGroup(); EXPECT_EQ(acc.GetResult(), int64_t{2}); EXPECT_EQ(acc.GetResult(), std::nullopt); EXPECT_EQ(acc.GetResult(), int64_t{4}); EXPECT_EQ(acc.GetResult(), std::nullopt); EXPECT_EQ(acc.GetResult(), int64_t{1}); EXPECT_EQ(acc.GetStatus(), absl::OkStatus()); acc.Reset(); acc.Add(0); acc.Add(2); acc.FinalizeFullGroup(); acc.GetResult(); acc.GetResult(); EXPECT_THAT( acc.GetStatus(), StatusIs( absl::StatusCode::kInvalidArgument, ::testing::HasSubstr( "unable to compute array.inverse_mapping: invalid permutation, " "element 2 is not a valid element of a permutation of size 2"))); acc.Reset(); EXPECT_THAT( acc.GetStatus(), StatusIs( absl::StatusCode::kInvalidArgument, ::testing::HasSubstr( "unable to compute array.inverse_mapping: invalid permutation, " "element 2 is not a valid element of a permutation of size 2"))); acc.Reset(); acc.Add(0); acc.Add(0); acc.FinalizeFullGroup(); acc.GetResult(); acc.GetResult(); EXPECT_THAT( acc.GetStatus(), StatusIs( absl::StatusCode::kInvalidArgument, HasSubstr( "unable to compute array.inverse_mapping: invalid permutation, " "element 0 appears twice in the permutation"))); } TEST(Accumulator, GroupBy) { int64_t group_counter = 10; GroupByAccumulator<float> acc(&group_counter); acc.Reset(); acc.Add(2.0f); EXPECT_EQ(acc.GetResult(), 10); acc.Add(3.0f); EXPECT_EQ(acc.GetResult(), 11); acc.Add(2.0f); EXPECT_EQ(acc.GetResult(), 10); acc.Reset(); acc.Add(3.0f); EXPECT_EQ(acc.GetResult(), 12); acc.Add(2.0f); EXPECT_EQ(acc.GetResult(), 13); acc.Add(3.0f); EXPECT_EQ(acc.GetResult(), 12); acc.Add(2.0f); EXPECT_EQ(acc.GetResult(), 13); } TEST(Accumulator, PermuteInt) { ArrayTakeOverAccumulator<int> acc; acc.Add(0, 2); acc.Add(1, 0); acc.Add(2, 1); acc.FinalizeFullGroup(); EXPECT_EQ(acc.GetResult(), 2); EXPECT_EQ(acc.GetResult(), 0); EXPECT_EQ(acc.GetResult(), 1); EXPECT_EQ(acc.GetStatus(), absl::OkStatus()); acc.Reset(); acc.Add(10, std::nullopt); acc.Add(std::nullopt, 1); acc.Add(20, 0); acc.FinalizeFullGroup(); EXPECT_EQ(acc.GetResult(), std::nullopt); EXPECT_EQ(acc.GetResult(), std::nullopt); EXPECT_EQ(acc.GetResult(), 10); EXPECT_EQ(acc.GetStatus(), absl::OkStatus()); acc.Reset(); acc.Add(0, 0); acc.Add(1, 2); acc.FinalizeFullGroup(); acc.GetResult(); acc.GetResult(); EXPECT_THAT(acc.GetStatus(), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("invalid offsets: 2 is not a valid offset of " "an array of size 2"))); acc.Reset(); EXPECT_THAT(acc.GetStatus(), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("invalid offsets: 2 is not a valid offset of " "an array of size 2"))); } TEST(Accumulator, PermuteBytes) { ArrayTakeOverAccumulator<Bytes> acc; std::vector<std::pair<OptionalValue<Bytes>, OptionalValue<int64_t>>> inputs( {{Bytes("the"), 4}, {Bytes("clone"), 0}, {Bytes("war"), 1}, {Bytes("has"), 2}, {Bytes("begun"), 3}}); for (const auto& add : inputs) { acc.Add(add.first, add.second); } acc.FinalizeFullGroup(); EXPECT_EQ(acc.GetResult(), "begun"); EXPECT_EQ(acc.GetResult(), "the"); EXPECT_EQ(acc.GetResult(), "clone"); EXPECT_EQ(acc.GetResult(), "war"); EXPECT_EQ(acc.GetResult(), "has"); EXPECT_EQ(acc.GetStatus(), absl::OkStatus()); } TEST(Accumulator, CDF) { WeightedCDFAccumulator<float, float> acc; acc.Add(0.1, 0.1); acc.Add(0.2, 0.2); acc.Add(0.20001, 0.1); acc.Add(0.1, 0.2); acc.Add(-0.1, 0.3); acc.Add(-0.2, 0.1); acc.FinalizeFullGroup(); EXPECT_THAT(acc.GetResult(), FloatEq(0.7)); EXPECT_THAT(acc.GetResult(), FloatEq(0.9)); EXPECT_THAT(acc.GetResult(), FloatEq(1)); EXPECT_THAT(acc.GetResult(), FloatEq(0.7)); EXPECT_THAT(acc.GetResult(), FloatEq(0.4)); EXPECT_THAT(acc.GetResult(), FloatEq(0.1)); acc.Reset(); acc.Add(1, 1); acc.Add(0, 1); acc.FinalizeFullGroup(); EXPECT_THAT(acc.GetResult(), FloatEq(1)); EXPECT_THAT(acc.GetResult(), FloatEq(0.5)); acc.Reset(); acc.FinalizeFullGroup(); } TEST(Accumulator, CDFBig) { WeightedCDFAccumulator<float, float> acc; for (int i = 0; i < 18000000; ++i) { acc.Add(0.0, 1.0); } for (int i = 0; i < 2000000; ++i) { acc.Add(i, 1.0); } acc.FinalizeFullGroup(); EXPECT_THAT(acc.GetResult(), FloatEq(0.9)); } TEST(Accumulator, OrdinalRank) { OrdinalRankAccumulator<float, int64_t> acc; acc.Add(7, 10); acc.Add(7, 9); acc.Add(1, 7); acc.Add(2, 10); acc.Add(2, 11); acc.Add(2, 10); acc.FinalizeFullGroup(); EXPECT_EQ(acc.GetResult(), 5); EXPECT_EQ(acc.GetResult(), 4); EXPECT_EQ(acc.GetResult(), 0); EXPECT_EQ(acc.GetResult(), 1); EXPECT_EQ(acc.GetResult(), 3); EXPECT_EQ(acc.GetResult(), 2); } TEST(Accumulator, OrdinalRank_Descending) { OrdinalRankAccumulator<float, int> acc(true); acc.Add(7, 10); acc.Add(7, 9); acc.Add(std::numeric_limits<float>::quiet_NaN(), 10); acc.Add(1, 10); acc.Add(2, 10); acc.Add(2, 10); acc.FinalizeFullGroup(); EXPECT_EQ(acc.GetResult(), 1); EXPECT_EQ(acc.GetResult(), 0); EXPECT_EQ(acc.GetResult(), 5); EXPECT_EQ(acc.GetResult(), 4); EXPECT_EQ(acc.GetResult(), 2); EXPECT_EQ(acc.GetResult(), 3); } TEST(Accumulator, DenseRank) { DenseRankAccumulator<int> acc; acc.Add(7); acc.Add(7); acc.Add(1); acc.Add(2); acc.Add(2); acc.FinalizeFullGroup(); EXPECT_EQ(acc.GetResult(), 2); EXPECT_EQ(acc.GetResult(), 2); EXPECT_EQ(acc.GetResult(), 0); EXPECT_EQ(acc.GetResult(), 1); EXPECT_EQ(acc.GetResult(), 1); acc.Reset(); acc.Add(3); acc.Add(0); acc.Add(2); acc.Add(1); acc.FinalizeFullGroup(); EXPECT_EQ(acc.GetResult(), 3); EXPECT_EQ(acc.GetResult(), 0); EXPECT_EQ(acc.GetResult(), 2); EXPECT_EQ(acc.GetResult(), 1); } TEST(Accumulator, DenseRankWithNan) { DenseRankAccumulator<float> acc; acc.Add(7); acc.Add(2); acc.Add(std::numeric_limits<float>::quiet_NaN()); acc.Add(7); acc.Add(1); acc.Add(std::numeric_limits<float>::quiet_NaN()); acc.Add(2); acc.FinalizeFullGroup(); std::set<int64_t> ranks_of_nan; EXPECT_EQ(acc.GetResult(), 2); EXPECT_EQ(acc.GetResult(), 1); ranks_of_nan.insert(acc.GetResult()); EXPECT_EQ(acc.GetResult(), 2); EXPECT_EQ(acc.GetResult(), 0); ranks_of_nan.insert(acc.GetResult()); EXPECT_EQ(acc.GetResult(), 1); EXPECT_EQ(ranks_of_nan, (std::set<int64_t>{3, 4})); } TEST(Accumulator, DenseRank_Descending) { DenseRankAccumulator<float> acc(true); acc.Add(7); acc.Add(7); acc.Add(1); acc.Add(2); acc.Add(2); acc.FinalizeFullGroup(); EXPECT_EQ(acc.GetResult(), 0); EXPECT_EQ(acc.GetResult(), 0); EXPECT_EQ(acc.GetResult(), 2); EXPECT_EQ(acc.GetResult(), 1); EXPECT_EQ(acc.GetResult(), 1); acc.Reset(); acc.Add(3); acc.Add(0); acc.Add(std::numeric_limits<float>::quiet_NaN()); acc.Add(1); acc.FinalizeFullGroup(); EXPECT_EQ(acc.GetResult(), 0); EXPECT_EQ(acc.GetResult(), 2); EXPECT_EQ(acc.GetResult(), 3); EXPECT_EQ(acc.GetResult(), 1); } TEST(Accumulator, AggMedian) { MedianAggregator<int> acc; EXPECT_EQ(acc.GetResult(), std::nullopt); acc.Reset(); acc.Add(7); acc.Add(1); acc.Add(1); acc.Add(2); EXPECT_EQ(acc.GetResult(), 1); acc.Reset(); acc.Add(7); acc.Add(1); acc.Add(2); EXPECT_EQ(acc.GetResult(), 2); } TEST(Accumulator, AggMedianNan) { MedianAggregator<float> acc; acc.Add(7); acc.Add(1); acc.Add(2); acc.Add(std::numeric_limits<float>::quiet_NaN()); EXPECT_TRUE(std::isnan(acc.GetResult().value)); } } }
2,440
#ifndef AROLLA_EXPR_OPERATORS_FACTORY_OPERATORS_H_ #define AROLLA_EXPR_OPERATORS_FACTORY_OPERATORS_H_ #include "absl/status/statusor.h" #include "arolla/expr/expr_operator.h" namespace arolla::expr_operators { absl::StatusOr<expr::ExprOperatorPtr> MakeEmptyLikeOp(); } #endif #include "arolla/expr/operators/factory_operators.h" #include <cstdint> #include <memory> #include "absl/status/statusor.h" #include "absl/types/span.h" #include "arolla/expr/basic_expr_operator.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/qtype/optional_qtype.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/standard_type_properties/properties.h" #include "arolla/util/fingerprint.h" #include "arolla/util/status_macros_backport.h" namespace arolla::expr_operators { namespace { using ::arolla::expr::CallOp; using ::arolla::expr::ExprNodePtr; using ::arolla::expr::ExprOperatorPtr; using ::arolla::expr::ExprOperatorSignature; using ::arolla::expr::Literal; using NarrowestNumericType = int32_t; class EmptyLikeOp final : public expr::BasicExprOperator { public: EmptyLikeOp() : BasicExprOperator( "core.empty_like", ExprOperatorSignature{{"target"}}, "Creates an empty value with shape and (optional) type like " "target.", FingerprintHasher("arolla::expr_operators::EmptyLikeOp").Finish()) { } absl::StatusOr<expr::ExprNodePtr> ToLowerLevel( const expr::ExprNodePtr& node) const final { RETURN_IF_ERROR(ValidateNodeDepsCount(*node)); auto target_qtype = node->node_deps()[0]->qtype(); ASSIGN_OR_RETURN(auto scalar_qtype, GetScalarQType(target_qtype)); ASSIGN_OR_RETURN(auto optional_scalar_qtype, ToOptionalQType(scalar_qtype)); ASSIGN_OR_RETURN(auto missing, CreateMissingValue(optional_scalar_qtype)); return CallOp("core.const_like", {node->node_deps()[0], Literal(missing)}); } absl::StatusOr<QTypePtr> GetOutputQType( absl::Span<const QTypePtr> input_qtypes) const final { return ToOptionalLikeQType(input_qtypes[0]); } }; } absl::StatusOr<ExprOperatorPtr> MakeEmptyLikeOp() { return std::make_shared<EmptyLikeOp>(); } }
#include <optional> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "arolla/dense_array/qtype/types.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/testing/testing.h" #include "arolla/memory/optional_value.h" #include "arolla/qtype/optional_qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/util/init_arolla.h" #include "arolla/util/testing/status_matchers_backport.h" namespace arolla::expr_operators { namespace { using ::arolla::expr::CallOp; using ::arolla::expr::ExprNodePtr; using ::arolla::expr::Leaf; using ::arolla::expr::Literal; using ::arolla::testing::EqualsExpr; using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::WithQTypeAnnotation; using ::testing::Eq; class FactoryTest : public ::testing::Test { protected: void SetUp() override { ASSERT_OK(InitArolla()); } }; TEST_F(FactoryTest, EmptyLike) { ASSERT_OK_AND_ASSIGN(auto scalar_leaf, WithQTypeAnnotation(Leaf("scalar"), GetQType<float>())); ASSERT_OK_AND_ASSIGN(auto empty_like_scalar, CallOp("core.empty_like", {scalar_leaf})); EXPECT_THAT(empty_like_scalar->qtype(), Eq(GetOptionalQType<float>())); EXPECT_THAT( ToLowerNode(empty_like_scalar), IsOkAndHolds(EqualsExpr( CallOp("core.const_like", {scalar_leaf, Literal<OptionalValue<float>>(std::nullopt)})))); ASSERT_OK_AND_ASSIGN( auto array_leaf, WithQTypeAnnotation(Leaf("array"), GetDenseArrayQType<float>())); ASSERT_OK_AND_ASSIGN(auto empty_like_array, CallOp("core.empty_like", {array_leaf})); EXPECT_THAT(empty_like_array->qtype(), Eq(GetDenseArrayQType<float>())); EXPECT_THAT(ToLowerNode(empty_like_array), IsOkAndHolds(EqualsExpr(CallOp( "core.const_like", {array_leaf, Literal<OptionalValue<float>>(std::nullopt)})))); } } }
2,441
#ifndef AROLLA_EXPR_OPERATORS_DYNAMIC_LIFTING_H_ #define AROLLA_EXPR_OPERATORS_DYNAMIC_LIFTING_H_ #include "absl/status/statusor.h" #include "arolla/expr/expr_operator.h" namespace arolla::expr_operators { absl::StatusOr<expr::ExprOperatorPtr> LiftDynamically( const absl::StatusOr<expr::ExprOperatorPtr>& op_or); } #endif #include "arolla/expr/operators/dynamic_lifting.h" #include <utility> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/types/span.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/expr/lambda_expr_operator.h" #include "arolla/expr/operators/restricted_operator.h" #include "arolla/expr/operators/type_meta_eval_strategies.h" #include "arolla/expr/overloaded_expr_operator.h" #include "arolla/expr/registered_expr_operator.h" #include "arolla/qtype/array_like/array_like_qtype.h" #include "arolla/qtype/qtype.h" #include "arolla/util/status_macros_backport.h" namespace arolla::expr_operators { namespace { using ::arolla::expr::ExprOperatorPtr; using ::arolla::expr::ExprOperatorSignature; using ::arolla::expr::Literal; using ::arolla::expr::MakeOverloadedOperator; using ::arolla::expr::Placeholder; using ::arolla::expr_operators::type_meta::QTypes; absl::StatusOr<QTypes> NoArrayArgs(absl::Span<const QTypePtr> types) { for (QTypePtr t : types) { if (IsArrayLikeQType(t)) { return absl::InvalidArgumentError("array argument found"); } } return QTypes{types.begin(), types.end()}; } } absl::StatusOr<ExprOperatorPtr> LiftDynamically( const absl::StatusOr<ExprOperatorPtr>& op_or) { ASSIGN_OR_RETURN(const ExprOperatorPtr& op, op_or); ASSIGN_OR_RETURN(ExprOperatorPtr map_op, expr::LookupOperator("core.map")); return MakeOverloadedOperator( op->display_name(), RestrictOperator(op, NoArrayArgs), MakeLambdaOperator( ExprOperatorSignature::Make("*args"), ::arolla::expr::CallOp( "core.apply_varargs", {Literal(std::move(map_op)), Literal(op), Placeholder("args")}))); } }
#include "arolla/expr/operators/dynamic_lifting.h" #include <memory> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/log/check.h" #include "absl/status/statusor.h" #include "arolla/dense_array/qtype/types.h" #include "arolla/expr/backend_wrapping_operator.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/expr/operators/type_meta_eval_strategies.h" #include "arolla/expr/registered_expr_operator.h" #include "arolla/expr/testing/testing.h" #include "arolla/expr/tuple_expr_operator.h" #include "arolla/qtype/optional_qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/util/init_arolla.h" #include "arolla/util/testing/status_matchers_backport.h" namespace arolla::expr_operators { namespace { using ::arolla::expr::BackendWrappingOperator; using ::arolla::expr::CallOp; using ::arolla::expr::ExprNodePtr; using ::arolla::expr::ExprOperatorPtr; using ::arolla::expr::ExprOperatorSignature; using ::arolla::expr::Leaf; using ::arolla::expr::Literal; using ::arolla::expr_operators::type_meta::CallableStrategy; using ::arolla::expr_operators::type_meta::Chain; using ::arolla::expr_operators::type_meta::CommonType; using ::arolla::expr_operators::type_meta::Ternary; using ::arolla::testing::EqualsExpr; using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::WithQTypeAnnotation; using ::testing::ElementsAre; using ::testing::Eq; using ::testing::Field; class DynamicLiftingTest : public ::testing::Test { public: static void SetUpTestSuite() { CHECK_OK(InitArolla()); } }; TEST_F(DynamicLiftingTest, LiftDynamically) { ASSERT_OK_AND_ASSIGN(auto scalar_signature, ExprOperatorSignature::Make("a, b, c")); auto scalar_operator = std::make_shared<BackendWrappingOperator>( "test.scalar_operator", scalar_signature, CallableStrategy(Chain(Ternary, CommonType))); ASSERT_OK_AND_ASSIGN(auto lifted_operator, LiftDynamically(scalar_operator)); EXPECT_THAT(lifted_operator->display_name(), Eq("test.scalar_operator")); EXPECT_THAT( lifted_operator->GetSignature(), IsOkAndHolds(Field( &ExprOperatorSignature::parameters, ElementsAre(Field(&ExprOperatorSignature::Parameter::name, "a"), Field(&ExprOperatorSignature::Parameter::name, "b"), Field(&ExprOperatorSignature::Parameter::name, "c"))))); { auto scalar_args = { WithQTypeAnnotation(Leaf("a"), GetQType<float>()), WithQTypeAnnotation(Leaf("b"), GetOptionalQType<float>()), WithQTypeAnnotation(Leaf("c"), GetQType<double>())}; ASSERT_OK_AND_ASSIGN(auto scalar_expr, CallOp(lifted_operator, scalar_args)); EXPECT_THAT(scalar_expr->qtype(), Eq(GetOptionalQType<double>())); ASSERT_OK_AND_ASSIGN(auto expected_expr, CallOp(scalar_operator, scalar_args)); EXPECT_THAT(ToLowest(scalar_expr), IsOkAndHolds(EqualsExpr(ToLowest(expected_expr)))); } { std::vector<absl::StatusOr<ExprNodePtr>> array_args = { WithQTypeAnnotation(Leaf("a"), GetQType<float>()), WithQTypeAnnotation(Leaf("b"), GetDenseArrayQType<float>()), WithQTypeAnnotation(Leaf("c"), GetOptionalQType<double>())}; ASSERT_OK_AND_ASSIGN(auto array_expr, CallOp(lifted_operator, array_args)); EXPECT_THAT(array_expr->qtype(), Eq(GetDenseArrayQType<double>())); ASSERT_OK_AND_ASSIGN(ExprOperatorPtr map_op, expr::LookupOperator("core.map")); ASSERT_OK_AND_ASSIGN( auto expected_expr, CallOp("core.apply_varargs", {Literal(map_op), Literal<ExprOperatorPtr>(scalar_operator), CallOp(expr::MakeTupleOperator::Make(), array_args)})); EXPECT_THAT(ToLowest(array_expr), IsOkAndHolds(EqualsExpr(ToLowest(expected_expr)))); } } } }
2,442
#ifndef AROLLA_EXPR_OPERATORS_STD_FUNCTION_OPERATOR_H_ #define AROLLA_EXPR_OPERATORS_STD_FUNCTION_OPERATOR_H_ #include <functional> #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "arolla/expr/basic_expr_operator.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/typed_ref.h" #include "arolla/qtype/typed_value.h" namespace arolla::expr_operators { class StdFunctionOperator : public expr::BasicExprOperator, public expr::BuiltinExprOperatorTag { public: using OutputQTypeFn = std::function<absl::StatusOr<QTypePtr>(absl::Span<const QTypePtr>)>; using EvalFn = std::function<absl::StatusOr<TypedValue>(absl::Span<const TypedRef>)>; StdFunctionOperator(absl::string_view name, expr::ExprOperatorSignature signature, absl::string_view doc, OutputQTypeFn output_qtype_fn, EvalFn eval_fn); absl::StatusOr<QTypePtr> GetOutputQType( absl::Span<const QTypePtr> input_qtypes) const final; const OutputQTypeFn& GetOutputQTypeFn() const; const EvalFn& GetEvalFn() const; private: OutputQTypeFn output_qtype_fn_; EvalFn eval_fn_; }; } #endif #include "arolla/expr/operators/std_function_operator.h" #include <utility> #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "arolla/expr/basic_expr_operator.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/qtype/qtype.h" #include "arolla/util/fingerprint.h" namespace arolla::expr_operators { using ::arolla::expr::ExprOperatorPtr; using ::arolla::expr::ExprOperatorSignature; StdFunctionOperator::StdFunctionOperator(absl::string_view name, ExprOperatorSignature signature, absl::string_view doc, OutputQTypeFn output_qtype_fn, EvalFn eval_fn) : BasicExprOperator(name, signature, doc, RandomFingerprint()), output_qtype_fn_(std::move(output_qtype_fn)), eval_fn_(std::move(eval_fn)) {} absl::StatusOr<QTypePtr> StdFunctionOperator::GetOutputQType( absl::Span<const QTypePtr> input_qtypes) const { return output_qtype_fn_(input_qtypes); } const StdFunctionOperator::OutputQTypeFn& StdFunctionOperator::GetOutputQTypeFn() const { return output_qtype_fn_; } const StdFunctionOperator::EvalFn& StdFunctionOperator::GetEvalFn() const { return eval_fn_; } }
#include "arolla/expr/operators/std_function_operator.h" #include <cstdint> #include <functional> #include <memory> #include <utility> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/types/span.h" #include "arolla/array/qtype/types.h" #include "arolla/expr/eval/invoke.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/typed_ref.h" #include "arolla/qtype/typed_value.h" #include "arolla/util/init_arolla.h" #include "arolla/util/testing/status_matchers_backport.h" #include "arolla/util/unit.h" #include "arolla/util/status_macros_backport.h" namespace arolla::expr_operators { namespace { using ::arolla::expr::ExprOperatorSignature; using ::arolla::expr::Leaf; using ::arolla::expr::Literal; using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::StatusIs; using ::testing::HasSubstr; class StdFunctionOperatorTest : public ::testing::Test { protected: void SetUp() override { ASSERT_OK(InitArolla()); } }; absl::StatusOr<TypedValue> GetFirst(absl::Span<const TypedRef> inputs) { return TypedValue(inputs[0]); } absl::StatusOr<QTypePtr> FirstQType(absl::Span<const QTypePtr> input_qtypes) { return input_qtypes[0]; } absl::StatusOr<TypedValue> Add(absl::Span<const TypedRef> inputs) { ASSIGN_OR_RETURN(int32_t x, inputs[0].As<int32_t>()); ASSIGN_OR_RETURN(int32_t y, inputs[1].As<int32_t>()); return TypedValue::FromValue(x + y); } TEST_F(StdFunctionOperatorTest, GetName) { StdFunctionOperator op("get_first_fn", ExprOperatorSignature{{"x"}, {"y"}}, "dummy op docstring", FirstQType, GetFirst); ASSERT_THAT(op.display_name(), "get_first_fn"); } TEST_F(StdFunctionOperatorTest, GetDoc) { StdFunctionOperator op("get_first_fn", ExprOperatorSignature{{"x"}, {"y"}}, "dummy op docstring", FirstQType, GetFirst); ASSERT_THAT(op.GetDoc(), IsOkAndHolds("dummy op docstring")); } TEST_F(StdFunctionOperatorTest, GetEvalFn) { StdFunctionOperator op("add_fn", ExprOperatorSignature{{"x"}, {"y"}}, "dummy op docstring", FirstQType, Add); int32_t x = 1; int32_t y = 2; auto res = op.GetEvalFn()({TypedRef::FromValue(x), TypedRef::FromValue(y)}); EXPECT_OK(res); EXPECT_THAT(res.value().As<int32_t>(), IsOkAndHolds(x + y)); } TEST_F(StdFunctionOperatorTest, GetOutputQTypeFn) { StdFunctionOperator op("add_fn", ExprOperatorSignature{{"x"}, {"y"}}, "dummy op docstring", FirstQType, Add); auto output_qtype_fn = op.GetOutputQTypeFn(); auto res = output_qtype_fn({GetArrayQType<int32_t>(), GetQType<int32_t>()}); EXPECT_THAT(res, IsOkAndHolds(GetArrayQType<int32_t>())); } TEST_F(StdFunctionOperatorTest, GetOutputQType) { { StdFunctionOperator op("get_first_fn", ExprOperatorSignature{{"x"}, {"y"}}, "dummy op docstring", FirstQType, GetFirst); EXPECT_THAT( op.GetOutputQType({GetArrayQType<int32_t>(), GetQType<int32_t>()}), IsOkAndHolds(GetArrayQType<int32_t>())); } { auto get_snd = [](absl::Span<const QTypePtr> inputs) -> absl::StatusOr<QTypePtr> { return inputs[1]; }; StdFunctionOperator op("add_fn", ExprOperatorSignature{{"x"}, {"y"}}, "dummy op docstring", std::move(get_snd), Add); EXPECT_THAT( op.GetOutputQType({GetArrayQType<int32_t>(), GetQType<float>()}), IsOkAndHolds(GetQType<float>())); } { auto status_fn = [](absl::Span<const QTypePtr> inputs) -> absl::StatusOr<QTypePtr> { return absl::InvalidArgumentError("foo bar"); }; StdFunctionOperator op("add_fn", ExprOperatorSignature{{"x"}, {"y"}}, "dummy op docstring", std::move(status_fn), Add); EXPECT_THAT( op.GetOutputQType({GetArrayQType<int32_t>(), GetQType<float>()}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("foo bar"))); } } TEST_F(StdFunctionOperatorTest, QTypeInference) { { auto op = std::make_shared<StdFunctionOperator>( "my_dummy_op", ExprOperatorSignature{{"x"}, {"y"}}, "dummy op docstring", FirstQType, GetFirst); ASSERT_OK_AND_ASSIGN(auto expr, CallOp(op, {Literal(1.5f), Literal(kUnit)})); EXPECT_EQ(expr->qtype(), GetQType<float>()); } { auto get_snd = [](absl::Span<const QTypePtr> inputs) -> absl::StatusOr<QTypePtr> { return inputs[1]; }; auto op = std::make_shared<StdFunctionOperator>( "my_dummy_op", ExprOperatorSignature{{"x"}, {"y"}}, "dummy op docstring", std::move(get_snd), GetFirst); ASSERT_OK_AND_ASSIGN(auto expr, CallOp(op, {Literal(1.5f), Literal(kUnit)})); EXPECT_EQ(expr->qtype(), GetQType<Unit>()); } { auto op = std::make_shared<StdFunctionOperator>( "my_dummy_op", ExprOperatorSignature{{"x"}, {"y"}}, "dummy op docstring", FirstQType, GetFirst); ASSERT_OK_AND_ASSIGN(auto expr, CallOp(op, {Leaf("x"), Leaf("y")})); EXPECT_EQ(expr->qtype(), nullptr); } } TEST_F(StdFunctionOperatorTest, Eval) { { auto op = std::make_shared<StdFunctionOperator>( "get_first", ExprOperatorSignature{{"x"}, {"y"}}, "dummy op docstring", FirstQType, GetFirst); ASSERT_OK_AND_ASSIGN(auto expr, CallOp(op, {Literal(1), Literal(2)})); auto res = Invoke(expr, {}); EXPECT_OK(res.status()); EXPECT_THAT(res.value().As<int32_t>(), IsOkAndHolds(1)); } { auto op = std::make_shared<StdFunctionOperator>( "add", ExprOperatorSignature{{"x"}, {"y"}}, "dummy op docstring", FirstQType, Add); ASSERT_OK_AND_ASSIGN(auto expr, CallOp(op, {Literal(1), Literal(2)})); auto res = Invoke(expr, {}); EXPECT_OK(res.status()); EXPECT_THAT(res.value().As<int32_t>(), IsOkAndHolds(3)); } { auto op = std::make_shared<StdFunctionOperator>( "add", ExprOperatorSignature{{"x"}, {"y"}}, "dummy op docstring", FirstQType, Add); ASSERT_OK_AND_ASSIGN(auto expr, CallOp(op, {Leaf("x"), Leaf("y")})); auto res = Invoke(expr, {{"x", TypedValue::FromValue(1)}, {"y", TypedValue::FromValue(2)}}); EXPECT_OK(res.status()); EXPECT_THAT(res.value().As<int32_t>(), IsOkAndHolds(3)); } } TEST_F(StdFunctionOperatorTest, VariadicInput) { ASSERT_OK_AND_ASSIGN(auto signature, ExprOperatorSignature::Make("*args")); auto op = std::make_shared<StdFunctionOperator>( "add", signature, "dummy op docstring", FirstQType, Add); ASSERT_OK_AND_ASSIGN(auto expr, CallOp(op, {Literal(1), Literal(2)})); auto res = Invoke(expr, {}); EXPECT_OK(res.status()); EXPECT_THAT(res.value().As<int32_t>(), IsOkAndHolds(3)); } TEST_F(StdFunctionOperatorTest, IncorrectFnOutput) { auto op = std::make_shared<StdFunctionOperator>( "get_first", ExprOperatorSignature{{"x"}}, "dummy op docstring", [](absl::Span<const QTypePtr> input_qtypes) { return GetQType<int32_t>(); }, GetFirst); ASSERT_OK_AND_ASSIGN(auto expr, CallOp(op, {Literal(1.0)})); EXPECT_THAT( Invoke(expr, {}), StatusIs( absl::StatusCode::kInvalidArgument, HasSubstr("expected the result to have qtype INT32, got FLOAT64"))); } TEST_F(StdFunctionOperatorTest, FnRaises) { auto op = std::make_shared<StdFunctionOperator>( "get_first", ExprOperatorSignature{{"x"}}, "dummy op docstring", FirstQType, [](absl::Span<const TypedRef> inputs) { return absl::InvalidArgumentError("foo bar"); }); ASSERT_OK_AND_ASSIGN(auto expr, CallOp(op, {Literal(1)})); EXPECT_THAT(Invoke(expr, {}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("foo bar"))); } TEST_F(StdFunctionOperatorTest, Fingerprint) { StdFunctionOperator op1("my_dummy_op", ExprOperatorSignature{{"x"}, {"y"}}, "dummy op docstring", FirstQType, GetFirst); { StdFunctionOperator op2("my_dummy_op", ExprOperatorSignature{{"x"}, {"y"}}, "dummy op docstring", FirstQType, GetFirst); EXPECT_NE(op1.fingerprint(), op2.fingerprint()); } { StdFunctionOperator op2("another_name", ExprOperatorSignature{{"x"}, {"y"}}, "dummy op docstring", FirstQType, GetFirst); EXPECT_NE(op1.fingerprint(), op2.fingerprint()); } { StdFunctionOperator op2("my_dummy_op", ExprOperatorSignature{{"x"}}, "dummy op docstring", FirstQType, GetFirst); EXPECT_NE(op1.fingerprint(), op2.fingerprint()); } { StdFunctionOperator op2("my_dummy_op", ExprOperatorSignature{{"x"}, {"y"}}, "another docstring", FirstQType, GetFirst); EXPECT_NE(op1.fingerprint(), op2.fingerprint()); } { StdFunctionOperator op2( "my_dummy_op", ExprOperatorSignature{{"x"}, {"y"}}, "dummy op docstring", [](absl::Span<const QTypePtr> input_qtypes) { return GetQType<float>(); }, GetFirst); EXPECT_NE(op1.fingerprint(), op2.fingerprint()); } { StdFunctionOperator op2( "my_dummy_op", ExprOperatorSignature{{"x"}, {"y"}}, "dummy op docstring", FirstQType, [](absl::Span<const TypedRef> inputs) -> absl::StatusOr<TypedValue> { return TypedValue(inputs[1]); }); EXPECT_NE(op1.fingerprint(), op2.fingerprint()); } } } }
2,443
#ifndef AROLLA_EXPR_OPERATORS_RESTRICTED_OPERATOR_H_ #define AROLLA_EXPR_OPERATORS_RESTRICTED_OPERATOR_H_ #include "absl/status/statusor.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/operators/type_meta_eval_strategies.h" namespace arolla::expr_operators { expr::ExprOperatorPtr RestrictOperator(expr::ExprOperatorPtr wrapped_op, type_meta::Strategy restriction); absl::StatusOr<expr::ExprOperatorPtr> RestrictOperator( absl::StatusOr<expr::ExprOperatorPtr> wrapped_op, absl::StatusOr<type_meta::Strategy> restriction); } #endif #include "arolla/expr/operators/restricted_operator.h" #include <memory> #include <utility> #include "absl/status/statusor.h" #include "absl/types/span.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_attributes.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/expr/operators/type_meta_eval_strategies.h" #include "arolla/expr/qtype_utils.h" #include "arolla/util/fingerprint.h" #include "arolla/util/status_macros_backport.h" namespace arolla::expr_operators { namespace { using ::arolla::expr::ExprAttributes; using ::arolla::expr::ExprNodePtr; using ::arolla::expr::ExprOperator; using ::arolla::expr::ExprOperatorPtr; using ::arolla::expr::ExprOperatorSignature; using ::arolla::expr::GetAttrQTypes; using ::arolla::expr::HasAllAttrQTypes; using ::arolla::expr::WithNewOperator; class RestrictedOp final : public ExprOperator { public: RestrictedOp(ExprOperatorPtr wrapped_op, type_meta::Strategy restriction) : ExprOperator(wrapped_op->display_name(), FingerprintHasher("::arolla::expr_operators::RestrictedOp") .Combine(wrapped_op) .Finish()), wrapped_op_(std::move(wrapped_op)), restriction_(std::move(restriction)) {} absl::StatusOr<ExprOperatorSignature> GetSignature() const final { return wrapped_op_->GetSignature(); } absl::StatusOr<ExprNodePtr> ToLowerLevel( const ExprNodePtr& node) const final { if (!node->qtype()) { return node; } ASSIGN_OR_RETURN(auto unwrapped_node, WithNewOperator(node, wrapped_op_)); return wrapped_op_->ToLowerLevel(unwrapped_node); } absl::StatusOr<ExprAttributes> InferAttributes( absl::Span<const ExprAttributes> inputs) const final { if (!HasAllAttrQTypes(inputs)) { return ExprAttributes{}; } RETURN_IF_ERROR(restriction_(GetAttrQTypes(inputs)).status()) << "in restriction for " << display_name() << " operator"; return wrapped_op_->InferAttributes(inputs); } private: ExprOperatorPtr wrapped_op_; type_meta::Strategy restriction_; }; } ExprOperatorPtr RestrictOperator(ExprOperatorPtr wrapped_op, type_meta::Strategy restriction) { return std::make_shared<RestrictedOp>(std::move(wrapped_op), std::move(restriction)); } absl::StatusOr<ExprOperatorPtr> RestrictOperator( absl::StatusOr<ExprOperatorPtr> wrapped_op, absl::StatusOr<type_meta::Strategy> restriction) { RETURN_IF_ERROR(wrapped_op.status()); RETURN_IF_ERROR(restriction.status()); return RestrictOperator(*wrapped_op, *restriction); } }
#include "arolla/expr/operators/restricted_operator.h" #include <cstdint> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "arolla/expr/eval/invoke.h" #include "arolla/expr/expr.h" #include "arolla/expr/operators/type_meta_eval_strategies.h" #include "arolla/expr/overloaded_expr_operator.h" #include "arolla/expr/registered_expr_operator.h" #include "arolla/expr/testing/testing.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/testing/qtype.h" #include "arolla/util/init_arolla.h" namespace arolla::expr_operators { namespace { using ::arolla::expr::CallOp; using ::arolla::expr::Literal; using ::arolla::expr_operators::type_meta::Floating; using ::arolla::expr_operators::type_meta::Integral; using ::arolla::testing::InvokeExprOperator; using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::StatusIs; using ::arolla::testing::TypedValueWith; using ::testing::Eq; using ::testing::HasSubstr; class RestrictedOperatorTest : public ::testing::Test { protected: void SetUp() override { ASSERT_OK(InitArolla()); } }; TEST_F(RestrictedOperatorTest, RestrictSimpleOperator) { ASSERT_OK_AND_ASSIGN( auto add_ints_op, RestrictOperator(expr::LookupOperator("math.add"), Integral)); ASSERT_OK_AND_ASSIGN( auto add_ints, CallOp(add_ints_op, {Literal<int64_t>(50), Literal<int64_t>(7)})); EXPECT_THAT(add_ints->qtype(), Eq(GetQType<int64_t>())); EXPECT_THAT(expr::Invoke(add_ints, {}), IsOkAndHolds(TypedValueWith<int64_t>(57))); EXPECT_THAT( CallOp(add_ints_op, {Literal<float>(50), Literal<float>(7)}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr( "expected all arguments to be integral, but got FLOAT32 for " "0-th argument; in restriction for math.add operator"))); } TEST_F(RestrictedOperatorTest, WorksWithOverloadedOperator) { ASSERT_OK_AND_ASSIGN( auto add_or_mul, expr::MakeOverloadedOperator( "test.add_or_mul", RestrictOperator(expr::LookupOperator("math.add"), Integral), RestrictOperator(expr::LookupOperator("math.multiply"), Floating))); EXPECT_THAT(InvokeExprOperator<int32_t>(add_or_mul, 50, 7), IsOkAndHolds(57)); EXPECT_THAT(InvokeExprOperator<float>(add_or_mul, 3.f, 19.f), IsOkAndHolds(57.f)); } } }
2,444
#ifndef AROLLA_EXPR_OPERATORS_WEAK_QTYPE_OPERATORS_H_ #define AROLLA_EXPR_OPERATORS_WEAK_QTYPE_OPERATORS_H_ #include "absl/status/statusor.h" #include "arolla/expr/expr_operator.h" namespace arolla::expr_operators { absl::StatusOr<expr::ExprOperatorPtr> MakeCoreToWeakFloatOperator(); } #endif #include "arolla/expr/operators/weak_qtype_operators.h" #include <cstdint> #include <memory> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "absl/types/span.h" #include "arolla/expr/basic_expr_operator.h" #include "arolla/expr/derived_qtype_cast_operator.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/expr/operators/type_meta_eval_strategies.h" #include "arolla/qtype/array_like/array_like_qtype.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/optional_qtype.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/standard_type_properties/properties.h" #include "arolla/qtype/weak_qtype.h" #include "arolla/util/fingerprint.h" #include "arolla/util/status_macros_backport.h" namespace arolla::expr_operators { namespace { using ::arolla::expr::CallOp; using ::arolla::expr::ExprNodePtr; using ::arolla::expr::ExprOperatorPtr; using ::arolla::expr::ExprOperatorSignature; class CoreToWeakFloatOp final : public expr::BasicExprOperator { public: CoreToWeakFloatOp() : expr::BasicExprOperator( "core.to_weak_float", ExprOperatorSignature{{"x"}}, "Casts a floating point value to the corresponding weak float " "type.", FingerprintHasher("::arolla::expr_operators::CoreToWeakFloatOp") .Finish()) {} absl::StatusOr<QTypePtr> GetOutputQType( absl::Span<const QTypePtr> inputs) const override { ASSIGN_OR_RETURN(auto scalar_type, GetScalarQType(inputs[0])); if (!(IsNumeric(scalar_type) || IsBoolean(scalar_type) || scalar_type == GetQType<uint64_t>())) { return absl::InvalidArgumentError(absl::StrFormat( "expected a numeric or boolean number, got: %s", inputs[0]->name())); } if (IsOptionalQType(inputs[0])) { return GetOptionalWeakFloatQType(); } if (IsArrayLikeQType(inputs[0])) { ASSIGN_OR_RETURN(auto shape_qtype, GetShapeQType(inputs[0])); return shape_qtype->WithValueQType(GetWeakFloatQType()); } return GetWeakFloatQType(); } absl::StatusOr<ExprNodePtr> ToLowerLevel( const ExprNodePtr& node) const final { RETURN_IF_ERROR(ValidateNodeDepsCount(*node)); auto op = std::make_shared<expr::DerivedQTypeDowncastOperator>(node->qtype()); return CallOp(op, {CallOp("core.to_float64", {node->node_deps()[0]})}); } }; } absl::StatusOr<ExprOperatorPtr> MakeCoreToWeakFloatOperator() { return std::make_shared<CoreToWeakFloatOp>(); } }
#include <optional> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "arolla/array/array.h" #include "arolla/array/qtype/types.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/operators/bootstrap_operators.h" #include "arolla/expr/testing/testing.h" #include "arolla/memory/optional_value.h" #include "arolla/qtype/typed_value.h" #include "arolla/qtype/weak_qtype.h" #include "arolla/util/init_arolla.h" namespace arolla::expr_operators { namespace { using ::arolla::expr::ExprOperatorPtr; using ::arolla::testing::InvokeExprOperator; class WeakQTypeOperatorsTest : public ::testing::Test { protected: void SetUp() override { ASSERT_OK(InitArolla()); } }; TEST_F(WeakQTypeOperatorsTest, ToWeakFloat) { ASSERT_OK_AND_ASSIGN(ExprOperatorPtr to_weak_float, GetCoreToWeakFloat()); ASSERT_OK_AND_ASSIGN(auto res, InvokeExprOperator<TypedValue>(to_weak_float, 1.0)); EXPECT_EQ(res.GetType(), GetWeakFloatQType()); } TEST_F(WeakQTypeOperatorsTest, ToWeakFloat_Float32) { ASSERT_OK_AND_ASSIGN(ExprOperatorPtr to_weak_float, GetCoreToWeakFloat()); ASSERT_OK_AND_ASSIGN(auto res, InvokeExprOperator<TypedValue>(to_weak_float, 1.0f)); EXPECT_EQ(res.GetType(), GetWeakFloatQType()); } TEST_F(WeakQTypeOperatorsTest, ToWeakFloat_Optional) { ASSERT_OK_AND_ASSIGN(ExprOperatorPtr to_weak_float, GetCoreToWeakFloat()); ASSERT_OK_AND_ASSIGN(auto res, InvokeExprOperator<TypedValue>( to_weak_float, OptionalValue<float>(1.0))); EXPECT_EQ(res.GetType(), GetOptionalWeakFloatQType()); } TEST_F(WeakQTypeOperatorsTest, ToWeakFloat_Array) { GetArrayWeakFloatQType(); ASSERT_OK_AND_ASSIGN(ExprOperatorPtr to_weak_float, GetCoreToWeakFloat()); auto values = CreateArray<float>({1, std::nullopt, std::nullopt, 2}); ASSERT_OK_AND_ASSIGN(auto res, InvokeExprOperator<TypedValue>(to_weak_float, values)); EXPECT_EQ(res.GetType(), GetArrayWeakFloatQType()); } } }
2,445
#ifndef AROLLA_EXPR_OPERATORS_STRINGS_STRING_OPERATORS_H_ #define AROLLA_EXPR_OPERATORS_STRINGS_STRING_OPERATORS_H_ #include "absl/status/statusor.h" #include "arolla/expr/expr_operator.h" namespace arolla::expr_operators { absl::StatusOr<expr::ExprOperatorPtr> MakeContainsRegexOp(); absl::StatusOr<expr::ExprOperatorPtr> MakeExtractRegexOp(); absl::StatusOr<expr::ExprOperatorPtr> MakeJoinOp(); } #endif #include "arolla/expr/operators/strings/string_operators.h" #include <memory> #include <vector> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "absl/types/span.h" #include "arolla/expr/basic_expr_operator.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/expr/lambda_expr_operator.h" #include "arolla/expr/operators/type_meta_eval_strategies.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/standard_type_properties/properties.h" #include "arolla/util/bytes.h" #include "arolla/util/fingerprint.h" #include "arolla/util/text.h" #include "arolla/util/status_macros_backport.h" namespace arolla::expr_operators { namespace { using ::arolla::expr::BasicExprOperator; using ::arolla::expr::CallOp; using ::arolla::expr::ExprNodePtr; using ::arolla::expr::ExprOperatorPtr; using ::arolla::expr::ExprOperatorSignature; using ::arolla::expr::Literal; using ::arolla::expr::Placeholder; namespace tm = ::arolla::expr_operators::type_meta; using tm::CallableStrategy; absl::StatusOr<ExprNodePtr> GetEmptyStringLiteral(QTypePtr type) { if (type == GetQType<Text>()) { return Literal(Text("")); } if (type == GetQType<Bytes>()) { return Literal(Bytes("")); } return absl::Status( absl::StatusCode::kInvalidArgument, absl::StrFormat("expected Bytes or Text, got %s", type->name())); } class JoinOp final : public BasicExprOperator { public: JoinOp() : BasicExprOperator( "strings.join", ExprOperatorSignature::MakeVariadicArgs(), "", FingerprintHasher("::arolla::expr_operators::JoinOp").Finish()) {} absl::StatusOr<ExprNodePtr> ToLowerLevel( const ExprNodePtr& node) const final { const auto& deps = node->node_deps(); if (deps.empty()) { return absl::InvalidArgumentError( "strings.join operator requires at least one argument"); } auto arg_type = deps[0]->qtype(); if (arg_type == nullptr) { return node; } ASSIGN_OR_RETURN(auto string_type, GetScalarQType(arg_type)); ASSIGN_OR_RETURN(auto empty_string, GetEmptyStringLiteral(string_type)); std::vector<ExprNodePtr> new_deps = {empty_string}; new_deps.insert(new_deps.end(), deps.begin(), deps.end()); return BindOp("strings._join_with_separator", new_deps, {}); } absl::StatusOr<QTypePtr> GetOutputQType( absl::Span<const QTypePtr> input_qtypes) const final { auto strategy = CallableStrategy( tm::Chain(tm::String, tm::AllSameScalarType, tm::LiftNthType(0))); return strategy(input_qtypes); } }; } absl::StatusOr<ExprOperatorPtr> MakeJoinOp() { return std::make_shared<JoinOp>(); } absl::StatusOr<ExprOperatorPtr> MakeContainsRegexOp() { auto s = Placeholder("s"); auto pattern = Placeholder("pattern"); return expr::MakeLambdaOperator( ExprOperatorSignature::Make("s, pattern"), CallOp("strings._contains_regex", {s, CallOp("strings._compile_regex", {pattern})})); } absl::StatusOr<ExprOperatorPtr> MakeExtractRegexOp() { auto s = Placeholder("s"); auto pattern = Placeholder("pattern"); return expr::MakeLambdaOperator( ExprOperatorSignature::Make("s, pattern"), CallOp("strings._extract_regex", {s, CallOp("strings._compile_regex", {pattern})})); } }
#include <optional> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/log/check.h" #include "absl/status/status.h" #include "arolla/dense_array/dense_array.h" #include "arolla/dense_array/qtype/types.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/testing/testing.h" #include "arolla/memory/optional_value.h" #include "arolla/util/init_arolla.h" #include "arolla/util/testing/status_matchers_backport.h" #include "arolla/util/text.h" #include "arolla/util/unit.h" namespace arolla::expr_operators { namespace { using ::arolla::expr::ExprOperatorPtr; using ::arolla::testing::InvokeExprOperator; using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::StatusIs; using ::testing::ElementsAre; using ::testing::HasSubstr; class StringOperatorsTest : public ::testing::Test { public: static void SetUpTestSuite() { CHECK_OK(InitArolla()); } }; TEST_F(StringOperatorsTest, ContainsRegex) { EXPECT_THAT(InvokeExprOperator<OptionalUnit>("strings.contains_regex", Text{"aaabccc"}, Text{"a.c"}), IsOkAndHolds(kPresent)); EXPECT_THAT(InvokeExprOperator<OptionalUnit>("strings.contains_regex", Text{"cccbaaa"}, Text{"a.c"}), IsOkAndHolds(kMissing)); EXPECT_THAT(InvokeExprOperator<OptionalUnit>("strings.contains_regex", OptionalValue<Text>{"aaabccc"}, Text{"a.c"}), IsOkAndHolds(kPresent)); EXPECT_THAT(InvokeExprOperator<OptionalUnit>( "strings.contains_regex", OptionalValue<Text>{}, Text{"a.c"}), IsOkAndHolds(kMissing)); EXPECT_THAT(InvokeExprOperator<DenseArray<Unit>>( "strings.contains_regex", CreateDenseArray<Text>({Text("aaabccc"), Text("cccbaaa"), Text("ac"), std::nullopt}), Text{"a.c"}), IsOkAndHolds(ElementsAre(kUnit, std::nullopt, std::nullopt, std::nullopt))); } TEST_F(StringOperatorsTest, ExtractRegex) { EXPECT_THAT( InvokeExprOperator<OptionalValue<Text>>("strings.extract_regex", Text{"aaabccc"}, Text{"a.c"}), StatusIs( absl::StatusCode::kInvalidArgument, HasSubstr("expected regular expression with exactly one capturing " "group; got `a.c` which contains 0 capturing groups"))); EXPECT_THAT(InvokeExprOperator<OptionalValue<Text>>( "strings.extract_regex", Text{"aaabccc"}, Text{"(a.c)"}), IsOkAndHolds("abc")); EXPECT_THAT(InvokeExprOperator<OptionalValue<Text>>( "strings.extract_regex", Text{"cccbaaa"}, Text{"(a.c)"}), IsOkAndHolds(std::nullopt)); EXPECT_THAT(InvokeExprOperator<OptionalValue<Text>>( "strings.extract_regex", OptionalValue<Text>{"aaabccc"}, Text{"(a.c)"}), IsOkAndHolds("abc")); EXPECT_THAT( InvokeExprOperator<OptionalValue<Text>>( "strings.extract_regex", OptionalValue<Text>{}, Text{"(a.c)"}), IsOkAndHolds(std::nullopt)); EXPECT_THAT(InvokeExprOperator<DenseArray<Text>>( "strings.extract_regex", CreateDenseArray<Text>({Text("aaabccc"), Text("cccbaaa"), Text("ac"), std::nullopt}), Text{"(a.c)"}), IsOkAndHolds(ElementsAre("abc", std::nullopt, std::nullopt, std::nullopt))); } } }
2,446
#ifndef AROLLA_EXPR_OPERATORS_WHILE_LOOP_WHILE_LOOP_H_ #define AROLLA_EXPR_OPERATORS_WHILE_LOOP_WHILE_LOOP_H_ #include <memory> #include <string> #include "absl/container/flat_hash_map.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "arolla/expr/basic_expr_operator.h" #include "arolla/expr/expr_attributes.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/expr_operator_signature.h" namespace arolla::expr_operators { using NamedExpressions = absl::flat_hash_map<std::string, expr::ExprNodePtr>; absl::StatusOr<expr::ExprNodePtr> MakeWhileLoop(NamedExpressions initial_state, expr::ExprNodePtr condition, NamedExpressions body); class WhileLoopOperator final : public expr::BuiltinExprOperatorTag, public expr::ExprOperatorWithFixedSignature { struct PrivateConstrutorTag {}; public: static absl::StatusOr<std::shared_ptr<WhileLoopOperator>> Make( const expr::ExprOperatorSignature& signature, const expr::ExprOperatorPtr& condition, const expr::ExprOperatorPtr& body); static absl::StatusOr<std::shared_ptr<WhileLoopOperator>> Make( absl::string_view name, const expr::ExprOperatorSignature& signature, const expr::ExprOperatorPtr& condition, const expr::ExprOperatorPtr& body); WhileLoopOperator(PrivateConstrutorTag, absl::string_view name, const expr::ExprOperatorSignature& signature, const expr::ExprOperatorPtr& condition, const expr::ExprOperatorPtr& body); absl::StatusOr<expr::ExprAttributes> InferAttributes( absl::Span<const expr::ExprAttributes> inputs) const final; const expr::ExprOperatorPtr& condition() const { return condition_; } const expr::ExprOperatorPtr& body() const { return body_; } absl::string_view py_qvalue_specialization_key() const final { return "::arolla::expr_operators::WhileLoopOperator"; } private: expr::ExprOperatorPtr condition_; expr::ExprOperatorPtr body_; }; } #endif #include "arolla/expr/operators/while_loop/while_loop.h" #include <algorithm> #include <cstddef> #include <cstdint> #include <iterator> #include <memory> #include <string> #include <utility> #include <vector> #include "absl/algorithm/container.h" #include "absl/container/flat_hash_map.h" #include "absl/container/flat_hash_set.h" #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/match.h" #include "absl/strings/str_format.h" #include "absl/strings/str_join.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "arolla/expr/basic_expr_operator.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_attributes.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/expr/lambda_expr_operator.h" #include "arolla/expr/operators/while_loop/while_loop_impl.h" #include "arolla/expr/qtype_utils.h" #include "arolla/expr/visitors/substitution.h" #include "arolla/memory/optional_value.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/util/fingerprint.h" #include "arolla/util/text.h" #include "arolla/util/status_macros_backport.h" namespace arolla::expr_operators { namespace { using ::arolla::expr::CallOp; using ::arolla::expr::ExprAttributes; using ::arolla::expr::ExprNodePtr; using ::arolla::expr::ExprOperatorPtr; using ::arolla::expr::ExprOperatorSignature; using ::arolla::expr::GetAttrQTypes; using ::arolla::expr::Literal; using ::arolla::expr::Placeholder; constexpr absl::string_view kDefaultOperatorName = "anonymous.while_loop"; constexpr absl::string_view kLoopStatePlaceholderName = "loop_state"; std::vector<std::string> ExpressionNames( const NamedExpressions& named_expressions) { std::vector<std::string> names_order; names_order.reserve(named_expressions.size()); for (const auto& [k, _] : named_expressions) { names_order.push_back(k); } std::sort(names_order.begin(), names_order.end()); return names_order; } absl::StatusOr<NamedExpressions> MakeNamedAccessors( const ExprNodePtr& tuple_node, absl::Span<const std::string> names_order) { NamedExpressions named_accessors; named_accessors.reserve(names_order.size()); for (size_t i = 0; i < names_order.size(); ++i) { ASSIGN_OR_RETURN( auto nth_field, expr::CallOp("core.get_nth", {tuple_node, expr::Literal<int64_t>(i)})); named_accessors.emplace(names_order[i], std::move(nth_field)); } return named_accessors; } absl::StatusOr<ExprNodePtr> WrapAsTuple( const NamedExpressions& named_expressions, absl::Span<const std::string> names_order) { std::vector<ExprNodePtr> deps; deps.reserve(names_order.size() + 1); deps.emplace_back(Literal(Text(absl::StrJoin(names_order, ",")))); for (const auto& f : names_order) { if (!named_expressions.contains(f)) { return absl::InvalidArgumentError(absl::StrFormat( "value for the state variable %s is not specified", f)); } deps.push_back(named_expressions.at(f)); } return BindOp("namedtuple.make", deps, {}); } absl::StatusOr<NamedExpressions> AddImplicitCastsToInitialState( const NamedExpressions& initial_state, const NamedExpressions& body) { NamedExpressions new_initial_state = initial_state; for (auto& [name, expr] : body) { ASSIGN_OR_RETURN(auto expr_after_one_iteration, SubstitutePlaceholders(expr, initial_state)); ASSIGN_OR_RETURN(new_initial_state[name], CallOp("core.cast", {initial_state.at(name), CallOp("qtype.qtype_of", {expr_after_one_iteration}), Literal(true)}), _ << "while casting initial state for P." << name); } return new_initial_state; } absl::Status MoveImmutablesIntoInitialState(NamedExpressions& initial_state, ExprNodePtr& condition, NamedExpressions& body) { constexpr absl::string_view kImmutableNamePrefix = "_while_loop_immutable"; for (auto& [name, _] : body) { if (absl::StartsWith(name, kImmutableNamePrefix)) { return absl::InvalidArgumentError(absl::StrFormat( "expression names starting with '%s' are forbidden in while_loop", kImmutableNamePrefix)); } } absl::flat_hash_map<Fingerprint, std::string> immutable_names; auto immutable_naming_function = [&](const ExprNodePtr& node) -> std::string { if (auto it = immutable_names.find(node->fingerprint()); it != immutable_names.end()) { return it->second; } std::string name = absl::StrFormat("%s_%d", kImmutableNamePrefix, immutable_names.size()); immutable_names.emplace(node->fingerprint(), name); return name; }; for (auto& [name, expr] : body) { ASSIGN_OR_RETURN( (auto [converted_expr, immutables]), while_loop_impl::ExtractImmutables(expr, immutable_naming_function)); expr = std::move(converted_expr); initial_state.merge(std::move(immutables)); } ASSIGN_OR_RETURN( (auto [converted_condition, condition_immutables]), while_loop_impl::ExtractImmutables(condition, immutable_naming_function)); condition = std::move(converted_condition); initial_state.merge(std::move(condition_immutables)); return absl::OkStatus(); } absl::Status CheckAllStateFieldsAreInitialized( const std::vector<std::string>& all_field_names, const std::vector<std::string>& requested_field_names) { absl::flat_hash_set<absl::string_view> all_field_names_set( all_field_names.begin(), all_field_names.end()); for (const auto& name : requested_field_names) { if (!all_field_names_set.contains(name)) { return absl::InvalidArgumentError(absl::StrFormat( "no initial value given for the loop state variable `%s`", name)); } } return absl::OkStatus(); } } absl::StatusOr<ExprNodePtr> MakeWhileLoop(NamedExpressions initial_state, ExprNodePtr condition, NamedExpressions body) { RETURN_IF_ERROR( MoveImmutablesIntoInitialState(initial_state, condition, body)); auto state_field_names = ExpressionNames(initial_state); auto mutable_state_field_names = ExpressionNames(body); RETURN_IF_ERROR(CheckAllStateFieldsAreInitialized(state_field_names, mutable_state_field_names)); RETURN_IF_ERROR(CheckAllStateFieldsAreInitialized( state_field_names, expr::GetPlaceholderKeys(condition))); for (const auto& [_, expr] : body) { RETURN_IF_ERROR(CheckAllStateFieldsAreInitialized( state_field_names, expr::GetPlaceholderKeys(expr))); } ASSIGN_OR_RETURN(initial_state, AddImplicitCastsToInitialState(initial_state, body)); std::vector<std::string> immutable_state_field_names; immutable_state_field_names.reserve(state_field_names.size() - mutable_state_field_names.size()); absl::c_set_difference(state_field_names, mutable_state_field_names, std::back_inserter(immutable_state_field_names)); ASSIGN_OR_RETURN(auto init_mutable_state_tuple, WrapAsTuple(initial_state, mutable_state_field_names)); ASSIGN_OR_RETURN(auto body_mutable_state_tuple, WrapAsTuple(body, mutable_state_field_names)); ExprOperatorSignature operators_signature; operators_signature.parameters.reserve(1 + immutable_state_field_names.size()); operators_signature.parameters.push_back( ExprOperatorSignature::Parameter{std::string{kLoopStatePlaceholderName}}); std::vector<ExprNodePtr> init_deps; init_deps.reserve(1 + immutable_state_field_names.size()); init_deps.emplace_back(init_mutable_state_tuple); for (const auto& name : immutable_state_field_names) { operators_signature.parameters.push_back( ExprOperatorSignature::Parameter{name}); DCHECK(initial_state.contains(name)) << "Internal inconsistency: no initializer for node " << name; init_deps.emplace_back(initial_state.at(name)); } auto state_placeholder = Placeholder(kLoopStatePlaceholderName); ASSIGN_OR_RETURN( auto state_fields, MakeNamedAccessors(state_placeholder, mutable_state_field_names)); ASSIGN_OR_RETURN(auto condition_op, MakeLambdaOperator( "anonymous.loop_condition", operators_signature, SubstitutePlaceholders(condition, state_fields, false))); ASSIGN_OR_RETURN(auto body_op, MakeLambdaOperator( "anonymous.loop_body", operators_signature, SubstitutePlaceholders( body_mutable_state_tuple, state_fields, false))); ASSIGN_OR_RETURN( ExprOperatorPtr while_op, WhileLoopOperator::Make(operators_signature, condition_op, body_op)); ASSIGN_OR_RETURN(auto while_node, BindOp(while_op, init_deps, {})); return while_node; } absl::StatusOr<std::shared_ptr<WhileLoopOperator>> WhileLoopOperator::Make( const ExprOperatorSignature& signature, const ExprOperatorPtr& condition, const ExprOperatorPtr& body) { return Make(kDefaultOperatorName, signature, condition, body); } absl::StatusOr<std::shared_ptr<WhileLoopOperator>> WhileLoopOperator::Make( absl::string_view name, const ExprOperatorSignature& signature, const ExprOperatorPtr& condition, const ExprOperatorPtr& body) { if (signature.parameters.empty()) { return absl::InvalidArgumentError( "WhileLoopOperator must at least have one parameter, got 0"); } ASSIGN_OR_RETURN(auto condition_signature, condition->GetSignature()); ASSIGN_OR_RETURN(auto body_signature, body->GetSignature()); auto signature_spec = GetExprOperatorSignatureSpec(signature); auto body_signature_spec = GetExprOperatorSignatureSpec(body_signature); if (signature_spec != body_signature_spec) { return absl::InvalidArgumentError(absl::StrFormat( "loop signature does not match its body signature: `%s` vs `%s`", signature_spec, body_signature_spec)); } auto condition_signature_spec = GetExprOperatorSignatureSpec(condition_signature); if (signature_spec != condition_signature_spec) { return absl::InvalidArgumentError(absl::StrFormat( "loop signature does not match its condition signature: `%s` vs `%s`", signature_spec, condition_signature_spec)); } return std::make_shared<WhileLoopOperator>(PrivateConstrutorTag(), name, signature, condition, body); } WhileLoopOperator::WhileLoopOperator(PrivateConstrutorTag, absl::string_view name, const ExprOperatorSignature& signature, const ExprOperatorPtr& condition, const ExprOperatorPtr& body) : ExprOperatorWithFixedSignature( name, signature, "", FingerprintHasher("arolla::expr_operators::WhileLoopOperator") .Combine(name, condition->fingerprint(), body->fingerprint()) .Finish()), condition_(condition), body_(body) {} absl::StatusOr<ExprAttributes> WhileLoopOperator::InferAttributes( absl::Span<const ExprAttributes> inputs) const { RETURN_IF_ERROR(ValidateOpInputsCount(inputs)); DCHECK_GE(inputs.size(), 1); if (!inputs[0].qtype()) { return ExprAttributes{}; } std::vector<ExprAttributes> new_inputs; new_inputs.reserve(inputs.size()); new_inputs.emplace_back(inputs[0].qtype()); new_inputs.insert(new_inputs.end(), inputs.begin() + 1, inputs.end()); ASSIGN_OR_RETURN( auto condition_attr, condition_->InferAttributes(new_inputs), _ << "in condition of `" << display_name() << "` while loop"); if (condition_attr.qtype() && condition_attr.qtype() != GetQType<OptionalUnit>()) { return absl::FailedPreconditionError(absl::StrFormat( "incorrect return type of the condition of `%s` while loop for input " "types %s: expected %s, got %s", display_name(), FormatTypeVector(GetAttrQTypes(inputs)), GetQType<OptionalUnit>()->name(), condition_attr.qtype()->name())); } ASSIGN_OR_RETURN(auto body_attr, body_->InferAttributes(new_inputs), _ << "in body of `" << display_name() << "` while loop"); if (body_attr.qtype() && body_attr.qtype() != inputs[0].qtype()) { return absl::FailedPreconditionError(absl::StrFormat( "incorrect return type of the body of `%s` while loop for input types " "%s: expected %s, got %s", display_name(), FormatTypeVector(GetAttrQTypes(inputs)), inputs[0].qtype()->name(), body_attr.qtype()->name())); } return ExprAttributes(inputs[0].qtype()); } }
#include "arolla/expr/operators/while_loop/while_loop.h" #include <cstdint> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_attributes.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/expr/lambda_expr_operator.h" #include "arolla/expr/testing/testing.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/tuple_qtype.h" #include "arolla/util/bytes.h" #include "arolla/util/init_arolla.h" #include "arolla/util/testing/status_matchers_backport.h" #include "arolla/util/text.h" namespace arolla::expr_operators { namespace { using ::arolla::expr::CallOp; using ::arolla::expr::ExprNodePtr; using ::arolla::expr::ExprOperatorSignature; using ::arolla::expr::LambdaOperator; using ::arolla::expr::Leaf; using ::arolla::expr::Literal; using ::arolla::expr::Placeholder; using ::arolla::testing::EqualsAttr; using ::arolla::testing::EqualsExpr; using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::StatusIs; using ::testing::ElementsAre; using ::testing::Eq; using ::testing::HasSubstr; using ::testing::NotNull; using Attr = ::arolla::expr::ExprAttributes; class WhileLoopTest : public ::testing::Test { protected: void SetUp() override { ASSERT_OK(InitArolla()); } }; TEST_F(WhileLoopTest, WhileLoopOperatorMake) { ASSERT_OK_AND_ASSIGN(auto body, MakeLambdaOperator(Placeholder("param"))); ASSERT_OK_AND_ASSIGN( auto condition, MakeLambdaOperator( CallOp("core.equal", {Placeholder("param"), Placeholder("param")}))); ASSERT_OK_AND_ASSIGN(auto good_loop_operator, WhileLoopOperator::Make( condition->GetSignature().value(), condition, body)); EXPECT_THAT(good_loop_operator->display_name(), Eq("anonymous.while_loop")); EXPECT_THAT(good_loop_operator->condition(), Eq(condition)); EXPECT_THAT(good_loop_operator->body(), Eq(body)); EXPECT_THAT(good_loop_operator->InferAttributes({Attr(GetQType<int64_t>())}), IsOkAndHolds(EqualsAttr(GetQType<int64_t>()))); EXPECT_THAT(good_loop_operator->InferAttributes( {Attr(GetQType<int64_t>()), Attr(GetQType<int64_t>())}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("incorrect number of dependencies passed to " "an operator node: expected 1 but got 2"))); } TEST_F(WhileLoopTest, WhileLoopOperatorMakeValidation) { ASSERT_OK_AND_ASSIGN( auto condition, MakeLambdaOperator( CallOp("core.equal", {Placeholder("param"), Placeholder("param")}))); ASSERT_OK_AND_ASSIGN( auto too_many_args_body, MakeLambdaOperator( ExprOperatorSignature::Make("x, y"), CallOp("math.add", {Placeholder("x"), Placeholder("y")}))); EXPECT_THAT(WhileLoopOperator::Make(condition->GetSignature().value(), condition, too_many_args_body), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("loop signature does not match its body " "signature: `param` vs `x, y`"))); } TEST_F(WhileLoopTest, WhileLoopOperatorWrongCondition) { ASSERT_OK_AND_ASSIGN(auto good_body, MakeLambdaOperator(Placeholder("param"))); const auto& wrong_type_condition = good_body; ASSERT_OK_AND_ASSIGN( auto wrong_condition_operator, WhileLoopOperator::Make(wrong_type_condition->GetSignature().value(), wrong_type_condition, good_body)); EXPECT_THAT( wrong_condition_operator->InferAttributes({Attr(GetQType<int64_t>())}), StatusIs(absl::StatusCode::kFailedPrecondition, HasSubstr("incorrect return type of the condition of " "`anonymous.while_loop` while loop for input types " "(INT64): expected OPTIONAL_UNIT, got INT64"))); } TEST_F(WhileLoopTest, WhileLoopOperatorWrongBody) { ASSERT_OK_AND_ASSIGN( auto condition, MakeLambdaOperator( CallOp("core.equal", {Placeholder("param"), Placeholder("param")}))); ASSERT_OK_AND_ASSIGN( auto wrong_type_body, MakeLambdaOperator(CallOp("core.to_float64", {Placeholder("param")}))); ASSERT_OK_AND_ASSIGN( auto wrong_body_operator, WhileLoopOperator::Make(condition->GetSignature().value(), condition, wrong_type_body)); EXPECT_THAT( wrong_body_operator->InferAttributes({Attr(GetQType<int64_t>())}), StatusIs(absl::StatusCode::kFailedPrecondition, HasSubstr("incorrect return type of the body of " "`anonymous.while_loop` while loop for input types " "(INT64): expected INT64, got FLOAT64"))); } TEST_F(WhileLoopTest, MakeWhileLoop) { auto init_x = Leaf("x"); auto init_y = Leaf("y"); ASSERT_OK_AND_ASSIGN( auto loop_condition, CallOp("core.not_equal", {Placeholder("y"), Literal<int64_t>(0)})); auto new_x = Placeholder("y"); ASSERT_OK_AND_ASSIGN( auto new_y, CallOp("math.mod", {Placeholder("x"), Literal<int64_t>(57)})); ASSERT_OK_AND_ASSIGN( ExprNodePtr while_loop, MakeWhileLoop({{"x", init_x}, {"y", init_y}}, loop_condition, {{"x", new_x}, {"y", new_y}})); EXPECT_THAT( while_loop->node_deps(), ElementsAre(EqualsExpr(CallOp( "namedtuple.make", {Literal(Text("x,y")), CallOp("core.cast", {Leaf("x"), CallOp("qtype.qtype_of", {Leaf("y")}), Literal(true)}), CallOp( "core.cast", {Leaf("y"), CallOp("qtype.qtype_of", {CallOp("math.mod", {Leaf("x"), Literal<int64_t>(57)})}), Literal(true)})})))); auto while_loop_op = dynamic_cast<const WhileLoopOperator*>(while_loop->op().get()); ASSERT_THAT(while_loop_op, NotNull()); ASSERT_OK_AND_ASSIGN( auto state_field_0, CallOp("core.get_nth", {Placeholder("loop_state"), Literal<int64_t>(0)})); ASSERT_OK_AND_ASSIGN( auto state_field_1, CallOp("core.get_nth", {Placeholder("loop_state"), Literal<int64_t>(1)})); auto condition_op = dynamic_cast<const LambdaOperator*>(while_loop_op->condition().get()); ASSERT_THAT(condition_op, NotNull()); EXPECT_THAT(condition_op->lambda_body(), EqualsExpr(CallOp("core.not_equal", {state_field_1, Literal<int64_t>(0)}))); auto body_op = dynamic_cast<const LambdaOperator*>(while_loop_op->body().get()); ASSERT_THAT(body_op, NotNull()); EXPECT_THAT( body_op->lambda_body(), EqualsExpr( CallOp("namedtuple.make", {Literal(Text("x,y")), state_field_1, CallOp("math.mod", {state_field_0, Literal<int64_t>(57)})}))); ASSERT_OK_AND_ASSIGN( QTypePtr good_state_type, MakeNamedTupleQType({"x", "y"}, MakeTupleQType({GetQType<int64_t>(), GetQType<int64_t>()}))); EXPECT_THAT(while_loop_op->InferAttributes({Attr(good_state_type)}), IsOkAndHolds(EqualsAttr(good_state_type))); ASSERT_OK_AND_ASSIGN( QTypePtr wrong_state_type, MakeNamedTupleQType({"x", "y"}, MakeTupleQType({GetQType<int64_t>(), GetQType<Bytes>()}))); EXPECT_THAT(while_loop_op->InferAttributes({Attr(wrong_state_type)}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("in condition of `anonymous.while_loop` " "while loop"))); } TEST_F(WhileLoopTest, MakeWhileLoopErrors) { auto leaf_x = Leaf("x"); ASSERT_OK_AND_ASSIGN( auto condition_with_x, CallOp("core.not_equal", {Placeholder("x"), Literal<int64_t>(0)})); auto placeholder_x = Placeholder("x"); auto placeholder_y = Placeholder("y"); EXPECT_THAT( MakeWhileLoop({{"x", leaf_x}}, condition_with_x, {{"x", placeholder_x}, {"y", placeholder_x}}), StatusIs( absl::StatusCode::kInvalidArgument, HasSubstr("no initial value given for the loop state variable `y`"))); EXPECT_THAT( MakeWhileLoop({{"x", leaf_x}}, condition_with_x, {{"x", placeholder_y}}), StatusIs( absl::StatusCode::kInvalidArgument, HasSubstr("no initial value given for the loop state variable `y`"))); ASSERT_OK_AND_ASSIGN( auto condition_with_y, CallOp("core.not_equal", {Placeholder("y"), Literal<int64_t>(0)})); EXPECT_THAT( MakeWhileLoop({{"x", leaf_x}}, condition_with_y, {{"x", placeholder_x}}), StatusIs( absl::StatusCode::kInvalidArgument, HasSubstr("no initial value given for the loop state variable `y`"))); } } }
2,447
#ifndef AROLLA_EXPR_OPERATORS_WHILE_LOOP_WHILE_LOOP_IMPL_H_ #define AROLLA_EXPR_OPERATORS_WHILE_LOOP_WHILE_LOOP_IMPL_H_ #include <functional> #include <string> #include <utility> #include "absl/status/statusor.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/operators/while_loop/while_loop.h" namespace arolla::expr_operators::while_loop_impl { absl::StatusOr<std::pair<expr::ExprNodePtr, NamedExpressions>> ExtractImmutables( const expr::ExprNodePtr& expr, std::function<std::string(const expr::ExprNodePtr& node)> naming_function); } #endif #include "arolla/expr/operators/while_loop/while_loop_impl.h" #include <algorithm> #include <functional> #include <string> #include <utility> #include <vector> #include "absl/log/check.h" #include "absl/status/statusor.h" #include "absl/types/span.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/expr_visitor.h" #include "arolla/expr/operators/while_loop/while_loop.h" #include "arolla/util/status_macros_backport.h" namespace arolla::expr_operators::while_loop_impl { using ::arolla::expr::ExprNodePtr; using ::arolla::expr::ExprOperatorPtr; using ::arolla::expr::Placeholder; absl::StatusOr<std::pair<ExprNodePtr, NamedExpressions>> ExtractImmutables( const ExprNodePtr& expr, std::function<std::string(const ExprNodePtr& node)> immutable_naming_function) { NamedExpressions immutables; struct Visit { ExprNodePtr expr; bool has_placeholder_dep; bool has_leaf_dep; }; ASSIGN_OR_RETURN( (auto [converted_expr, has_placeholder_dep, has_leaf_dep]), expr::PostOrderTraverse( expr, [&](const ExprNodePtr& node, absl::Span<const Visit* const> visits) -> absl::StatusOr<Visit> { if (node->is_placeholder()) { return Visit{.expr = node, .has_placeholder_dep = true, .has_leaf_dep = false}; } if (node->is_leaf()) { return Visit{.expr = node, .has_placeholder_dep = false, .has_leaf_dep = true}; } bool has_placeholder_dep = std::any_of( visits.begin(), visits.end(), [](const auto& v) { return v->has_placeholder_dep; }); bool has_leaf_dep = std::any_of(visits.begin(), visits.end(), [](const auto& v) { return v->has_leaf_dep; }); if (!has_placeholder_dep) { return Visit{.expr = node, .has_placeholder_dep = false, .has_leaf_dep = has_leaf_dep}; } std::vector<ExprNodePtr> new_deps; new_deps.reserve(visits.size()); for (const auto& visit : visits) { if (visit->has_placeholder_dep || !visit->has_leaf_dep) { new_deps.push_back(visit->expr); } else { auto placeholder_key = immutable_naming_function(visit->expr); new_deps.emplace_back(Placeholder(placeholder_key)); immutables.emplace(std::move(placeholder_key), visit->expr); } } ASSIGN_OR_RETURN(auto new_node, expr::WithNewDependencies( node, std::move(new_deps))); return Visit{.expr = new_node, .has_placeholder_dep = true, .has_leaf_dep = has_leaf_dep}; })); if (!has_placeholder_dep) { DCHECK(immutables.empty()); auto placeholder_key = immutable_naming_function(converted_expr); immutables.emplace(placeholder_key, converted_expr); converted_expr = Placeholder(placeholder_key); } return {{std::move(converted_expr), std::move(immutables)}}; } }
#include "arolla/expr/operators/while_loop/while_loop_impl.h" #include <cstdint> #include <string> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/container/flat_hash_map.h" #include "absl/strings/str_format.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/testing/testing.h" #include "arolla/util/fingerprint.h" #include "arolla/util/init_arolla.h" #include "arolla/util/testing/status_matchers_backport.h" namespace arolla::expr_operators::while_loop_impl { namespace { using ::arolla::expr::CallOp; using ::arolla::expr::ExprNodePtr; using ::arolla::expr::Leaf; using ::arolla::expr::Literal; using ::arolla::expr::Placeholder; using ::arolla::testing::EqualsExpr; using ::arolla::testing::IsOkAndHolds; using ::testing::IsEmpty; using ::testing::Pair; using ::testing::UnorderedElementsAre; class WhileLoopImplTest : public ::testing::Test { protected: void SetUp() override { ASSERT_OK(InitArolla()); } }; TEST_F(WhileLoopImplTest, ExtractImmutables) { absl::flat_hash_map<Fingerprint, std::string> immutable_names; auto immutable_naming_function = [&](const ExprNodePtr& node) -> std::string { if (auto it = immutable_names.find(node->fingerprint()); it != immutable_names.end()) { return it->second; } std::string name = absl::StrFormat("_immutable_%d", immutable_names.size()); immutable_names.emplace(node->fingerprint(), name); return name; }; { auto expr = Literal(int64_t{1}); EXPECT_THAT(ExtractImmutables(expr, immutable_naming_function), IsOkAndHolds(Pair( EqualsExpr(Placeholder("_immutable_0")), UnorderedElementsAre(Pair( "_immutable_0", EqualsExpr(Literal<int64_t>(1))))))); } { auto expr = Leaf("fifty"); EXPECT_THAT( ExtractImmutables(expr, immutable_naming_function), IsOkAndHolds(Pair(EqualsExpr(Placeholder("_immutable_1")), UnorderedElementsAre(Pair( "_immutable_1", EqualsExpr(Leaf("fifty"))))))); } { auto expr = Placeholder("seven"); EXPECT_THAT(ExtractImmutables(expr, immutable_naming_function), IsOkAndHolds(Pair(EqualsExpr(expr), IsEmpty()))); } { ASSERT_OK_AND_ASSIGN( auto expr, CallOp("math.add", {Leaf("two"), CallOp("math.add", {Placeholder("fifty"), Leaf("seven")})})); EXPECT_THAT(ExtractImmutables(expr, immutable_naming_function), IsOkAndHolds(Pair( EqualsExpr(CallOp( "math.add", {Placeholder("_immutable_3"), CallOp("math.add", {Placeholder("fifty"), Placeholder("_immutable_2")})})), UnorderedElementsAre( Pair("_immutable_3", EqualsExpr(Leaf("two"))), Pair("_immutable_2", EqualsExpr(Leaf("seven"))))))); } { ASSERT_OK_AND_ASSIGN(auto expr, CallOp("math.add", {Placeholder("fifty"), Literal<int64_t>(7)})); EXPECT_THAT( ExtractImmutables(expr, immutable_naming_function), IsOkAndHolds(Pair(EqualsExpr(CallOp("math.add", {Placeholder("fifty"), Literal<int64_t>(7)})), IsEmpty()))); } { ASSERT_OK_AND_ASSIGN( auto expr57, CallOp("math.add", {Leaf("fifty"), Literal<int64_t>(7)})); ASSERT_OK_AND_ASSIGN(auto expr, CallOp("math.add", {expr57, Placeholder("two")})); EXPECT_THAT( ExtractImmutables(expr, immutable_naming_function), IsOkAndHolds(Pair( EqualsExpr(CallOp( "math.add", {Placeholder("_immutable_4"), Placeholder("two")})), UnorderedElementsAre(Pair("_immutable_4", EqualsExpr(expr57)))))); } { ASSERT_OK_AND_ASSIGN( auto expr, CallOp("math.add", {CallOp("math.add", {Placeholder("fifty"), Leaf("seven")}), Leaf("seven")})); EXPECT_THAT( ExtractImmutables(expr, immutable_naming_function), IsOkAndHolds(Pair( EqualsExpr(CallOp( "math.add", {CallOp("math.add", {Placeholder("fifty"), Placeholder("_immutable_2")}), Placeholder("_immutable_2")})), UnorderedElementsAre( Pair("_immutable_2", EqualsExpr(Leaf("seven"))))))); } { ASSERT_OK_AND_ASSIGN( auto expr, CallOp("math.add", {CallOp("math.add", {Literal<int64_t>(1), Leaf("fifty")}), Placeholder("seven")})); EXPECT_THAT(ExtractImmutables(expr, immutable_naming_function), IsOkAndHolds(Pair( EqualsExpr(CallOp("math.add", {Placeholder("_immutable_5"), Placeholder("seven")})), UnorderedElementsAre(Pair( "_immutable_5", EqualsExpr(CallOp("math.add", {Literal<int64_t>(1), Leaf("fifty")}))))))); } } } }
2,448
#ifndef AROLLA_EXPR_OPTIMIZATION_PEEPHOLE_OPTIMIZER_H_ #define AROLLA_EXPR_OPTIMIZATION_PEEPHOLE_OPTIMIZER_H_ #include <functional> #include <initializer_list> #include <memory> #include <optional> #include <string> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "arolla/expr/expr_attributes.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/util/fingerprint.h" namespace arolla::expr { class ReferenceToRegisteredOperator final : public ExprOperator { public: explicit ReferenceToRegisteredOperator(absl::string_view name); absl::StatusOr<ExprOperatorSignature> GetSignature() const final; absl::StatusOr<ExprAttributes> InferAttributes( absl::Span<const ExprAttributes> inputs) const final; }; absl::StatusOr<ExprNodePtr> CallOpReference( absl::string_view op_name, std::initializer_list<absl::StatusOr<ExprNodePtr>> status_or_args); class PeepholeOptimization { public: class PatternKey { public: explicit PatternKey(const ExprNodePtr& expr); bool operator==(const PatternKey& other) const; bool operator!=(const PatternKey& other) const; template <typename H> friend H AbslHashValue(H h, const PatternKey& key) { return H::combine(std::move(h), key.tpe_, key.fingerprint_); } private: enum class Type { kLiteral, kOperator, kOther, }; Type tpe_ = Type::kOther; Fingerprint fingerprint_; }; virtual std::optional<PatternKey> GetKey() const { return std::nullopt; } using NodeMatcher = std::function<bool(const ExprNodePtr&)>; virtual ~PeepholeOptimization() = default; virtual absl::StatusOr<ExprNodePtr> ApplyToRoot( const ExprNodePtr& root) const = 0; static absl::StatusOr<std::unique_ptr<PeepholeOptimization>> CreatePatternOptimization( ExprNodePtr from, ExprNodePtr to, absl::flat_hash_map<std::string, NodeMatcher> placeholder_matchers = {}); static absl::StatusOr<std::unique_ptr<PeepholeOptimization>> CreateTransformOptimization( std::function<absl::StatusOr<ExprNodePtr>(ExprNodePtr)> transform_fn); }; using PeepholeOptimizationPack = std::vector<std::unique_ptr<PeepholeOptimization>>; class PeepholeOptimizer { public: absl::StatusOr<ExprNodePtr> Apply(ExprNodePtr root) const; absl::StatusOr<ExprNodePtr> ApplyToNode(ExprNodePtr node) const; static absl::StatusOr<std::unique_ptr<PeepholeOptimizer>> Create( PeepholeOptimizationPack optimizations); ~PeepholeOptimizer(); private: struct Data; explicit PeepholeOptimizer(std::unique_ptr<Data> data); std::unique_ptr<Data> data_; }; using PeepholeOptimizationPackFactory = std::function<absl::StatusOr<PeepholeOptimizationPack>()>; absl::StatusOr<std::unique_ptr<PeepholeOptimizer>> CreatePeepholeOptimizer( absl::Span<const PeepholeOptimizationPackFactory> optimization_pack_factories); } #endif #include "arolla/expr/optimization/peephole_optimizer.h" #include <algorithm> #include <cstdint> #include <functional> #include <initializer_list> #include <iterator> #include <memory> #include <optional> #include <queue> #include <string> #include <utility> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/container/flat_hash_set.h" #include "absl/log/check.h" #include "absl/log/log.h" #include "absl/memory/memory.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "absl/strings/str_join.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_attributes.h" #include "arolla/expr/expr_debug_string.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/expr/expr_visitor.h" #include "arolla/expr/registered_expr_operator.h" #include "arolla/util/fingerprint.h" #include "arolla/util/status_macros_backport.h" namespace arolla::expr { namespace { struct MatchingCandidate { const ExprNodePtr& candidate; const ExprNodePtr& pattern; }; using MatchersMap = absl::flat_hash_map<std::string, PeepholeOptimization::NodeMatcher>; bool PlaceholderMatches(absl::string_view key, const MatchersMap& placeholder_matchers, const ExprNodePtr& candidate) { if (auto matcher_it = placeholder_matchers.find(key); matcher_it != placeholder_matchers.end()) { const auto& matcher = matcher_it->second; return matcher(candidate); } return true; } absl::StatusOr<ExprNodePtr> DecayReferencesToRegisteredOperator( const PostOrder& node_visitor_order, const absl::flat_hash_map<std::string, ExprNodePtr>& subs) { return TransformOnPostOrder( node_visitor_order, [&](ExprNodePtr node) -> absl::StatusOr<ExprNodePtr> { if (node->is_op() && typeid(*node->op()) == typeid(ReferenceToRegisteredOperator)) { return BindOp(node->op()->display_name(), node->node_deps(), {}); } if (node->is_placeholder()) { if (subs.contains(node->placeholder_key())) { return subs.at(node->placeholder_key()); } else { return absl::InvalidArgumentError(absl::StrFormat( "No value was provided for P.%s.", node->placeholder_key())); } } return node; }); } struct PatternOptimizationData { ExprNodePtr from; PostOrder to_visitor_order; MatchersMap placeholder_matchers; PeepholeOptimization::PatternKey key; }; class PatternOptimization : public PeepholeOptimization { public: explicit PatternOptimization(PatternOptimizationData data) : data_(std::move(data)) {} std::optional<PeepholeOptimization::PatternKey> GetKey() const final { return data_.key; } absl::StatusOr<ExprNodePtr> ApplyToRoot( const ExprNodePtr& root) const override { absl::flat_hash_map<Fingerprint, Fingerprint> opt2root; std::queue<MatchingCandidate> queue; queue.push({.candidate = root, .pattern = data_.from}); auto add_to_queue = [&](MatchingCandidate candidate) -> bool { if (auto [it, success] = opt2root.emplace(candidate.pattern->fingerprint(), candidate.candidate->fingerprint()); !success) { return it->second == candidate.candidate->fingerprint(); } queue.push(std::move(candidate)); return true; }; absl::flat_hash_map<std::string, ExprNodePtr> placeholder_subs; while (!queue.empty()) { MatchingCandidate candidate = queue.front(); queue.pop(); if (candidate.pattern->is_literal()) { if (!candidate.candidate->is_literal() || (candidate.pattern->fingerprint() != candidate.candidate->fingerprint())) { return root; } continue; } if (candidate.pattern->is_leaf()) { LOG(FATAL) << "Internal error: leaves are not expected."; return root; } if (candidate.pattern->is_placeholder()) { absl::string_view key = candidate.pattern->placeholder_key(); if (!PlaceholderMatches(key, data_.placeholder_matchers, candidate.candidate)) { return root; } auto [it, success] = placeholder_subs.emplace(key, candidate.candidate); DCHECK(success) << "Internal error: each node of the pattern with the same " "fingerprint must be added to the queue only once."; continue; } DCHECK(candidate.pattern->is_op()) << "Internal error: unexpected node type: " << ToDebugString(candidate.pattern); if (!candidate.candidate->is_op()) { return root; } if (candidate.pattern->op()->display_name() != candidate.candidate->op()->display_name()) { return root; } ASSIGN_OR_RETURN(auto decayed_op, DecayRegisteredOperator(candidate.candidate->op())); if (!HasBackendExprOperatorTag(decayed_op) && !HasBuiltinExprOperatorTag(decayed_op)) { return absl::InvalidArgumentError(absl::StrFormat( "tried applying a peephole optimization to operator %s." " which is neither backend nor builtin. Is " "your peephole optimization correct?", decayed_op->display_name())); } const auto& opt_deps = candidate.pattern->node_deps(); const auto& root_deps = candidate.candidate->node_deps(); if (opt_deps.size() != root_deps.size()) { return root; } for (int64_t dep_id = 0; dep_id != root_deps.size(); ++dep_id) { if (!add_to_queue({.candidate = root_deps[dep_id], .pattern = opt_deps[dep_id]})) { return root; } } } return DecayReferencesToRegisteredOperator(data_.to_visitor_order, placeholder_subs); } private: PatternOptimizationData data_; }; class TransformOptimization : public PeepholeOptimization { public: explicit TransformOptimization( std::function<absl::StatusOr<ExprNodePtr>(ExprNodePtr)> transform_fn) : transform_fn_(std::move(transform_fn)) {} absl::StatusOr<ExprNodePtr> ApplyToRoot(const ExprNodePtr& root) const final { return transform_fn_(root); } private: std::function<absl::StatusOr<ExprNodePtr>(ExprNodePtr)> transform_fn_; }; } ReferenceToRegisteredOperator::ReferenceToRegisteredOperator( absl::string_view name) : ExprOperator( name, FingerprintHasher("arolla::expr::ReferenceToRegisteredOperator") .Combine(name) .Finish()) {} absl::StatusOr<ExprOperatorSignature> ReferenceToRegisteredOperator::GetSignature() const { return ExprOperatorSignature::MakeVariadicArgs(); } absl::StatusOr<ExprAttributes> ReferenceToRegisteredOperator::InferAttributes( absl::Span<const ExprAttributes> ) const { return ExprAttributes{}; } absl::StatusOr<ExprNodePtr> CallOpReference( absl::string_view op_name, std::initializer_list<absl::StatusOr<ExprNodePtr>> status_or_args) { return CallOp(std::make_shared<ReferenceToRegisteredOperator>(op_name), status_or_args); } PeepholeOptimization::PatternKey::PatternKey(const ExprNodePtr& expr) { if (expr->is_op()) { tpe_ = Type::kOperator; fingerprint_ = FingerprintHasher("").Combine(expr->op()->display_name()).Finish(); } else if (expr->is_literal()) { tpe_ = Type::kLiteral; fingerprint_ = expr->qvalue()->GetFingerprint(); } else { tpe_ = Type::kOther; fingerprint_ = expr->fingerprint(); } } bool PeepholeOptimization::PatternKey::operator==( const PatternKey& other) const { return tpe_ == other.tpe_ && fingerprint_ == other.fingerprint_; } bool PeepholeOptimization::PatternKey::operator!=( const PatternKey& other) const { return !(*this == other); } absl::StatusOr<std::unique_ptr<PeepholeOptimization>> PeepholeOptimization::CreatePatternOptimization( ExprNodePtr from, ExprNodePtr to, absl::flat_hash_map<std::string, NodeMatcher> placeholder_matchers) { if (from->is_placeholder()) { return absl::FailedPreconditionError( absl::StrFormat("from EXPRession is placeholder, which would match " "everything: %s -> %s", ToDebugString(from), ToDebugString(to))); } if (!GetLeafKeys(from).empty() || !GetLeafKeys(to).empty()) { return absl::FailedPreconditionError( absl::StrFormat("leaves are not allowed in optimizations: %s -> %s", ToDebugString(from), ToDebugString(to))); } absl::flat_hash_set<std::string> from_keys_set; for (const auto& key : GetPlaceholderKeys(from)) { from_keys_set.insert(key); } std::vector<std::string> unknown_to_keys; for (const auto& key : GetPlaceholderKeys(to)) { if (!from_keys_set.contains(key)) { unknown_to_keys.push_back(key); } } if (!unknown_to_keys.empty()) { return absl::FailedPreconditionError( absl::StrFormat("unknown placeholder keys in to expression: %s, %s->%s", absl::StrJoin(unknown_to_keys, ","), ToDebugString(from), ToDebugString(to))); } std::vector<std::string> unknown_matcher_keys; for (const auto& [key, _] : placeholder_matchers) { if (!from_keys_set.contains(key)) { unknown_matcher_keys.push_back(key); } } if (!unknown_matcher_keys.empty()) { return absl::FailedPreconditionError( absl::StrFormat("unknown placeholder matcher keys: %s, %s->%s", absl::StrJoin(unknown_matcher_keys, ","), ToDebugString(from), ToDebugString(to))); } PatternKey key(from); return std::make_unique<PatternOptimization>(PatternOptimizationData{ std::move(from), PostOrder(to), std::move(placeholder_matchers), key}); } absl::StatusOr<std::unique_ptr<PeepholeOptimization>> PeepholeOptimization::CreateTransformOptimization( std::function<absl::StatusOr<ExprNodePtr>(ExprNodePtr)> transform_fn) { return std::make_unique<TransformOptimization>(std::move(transform_fn)); } struct PeepholeOptimizer::Data { absl::flat_hash_map<PeepholeOptimization::PatternKey, std::vector<std::unique_ptr<PeepholeOptimization>>> pattern_optimizations; std::vector<std::unique_ptr<PeepholeOptimization>> transform_optimizations; }; absl::StatusOr<ExprNodePtr> PeepholeOptimizer::ApplyToNode( ExprNodePtr node) const { const auto& pattern_optimizations = data_->pattern_optimizations; PeepholeOptimization::PatternKey key(node); if (auto it = pattern_optimizations.find(key); it != pattern_optimizations.end()) { for (const auto& optimization : it->second) { ASSIGN_OR_RETURN(node, optimization->ApplyToRoot(node)); } } for (const auto& optimization : data_->transform_optimizations) { ASSIGN_OR_RETURN(node, optimization->ApplyToRoot(node)); } return node; } absl::StatusOr<ExprNodePtr> PeepholeOptimizer::Apply(ExprNodePtr root) const { return Transform(root, [this](ExprNodePtr node) -> absl::StatusOr<ExprNodePtr> { return ApplyToNode(node); }); } PeepholeOptimizer::~PeepholeOptimizer() = default; PeepholeOptimizer::PeepholeOptimizer(std::unique_ptr<Data> data) : data_(std::move(data)) {} absl::StatusOr<std::unique_ptr<PeepholeOptimizer>> PeepholeOptimizer::Create( std::vector<std::unique_ptr<PeepholeOptimization>> optimizations) { auto data = std::make_unique<Data>(); for (auto& opt : optimizations) { std::optional<PeepholeOptimization::PatternKey> key = opt->GetKey(); if (key.has_value()) { auto& opt_list = data->pattern_optimizations[*key]; opt_list.push_back(std::move(opt)); } else { data->transform_optimizations.push_back(std::move(opt)); } } return absl::WrapUnique(new PeepholeOptimizer(std::move(data))); } absl::StatusOr<std::unique_ptr<PeepholeOptimizer>> CreatePeepholeOptimizer( absl::Span<const PeepholeOptimizationPackFactory> optimization_pack_factories) { PeepholeOptimizationPack optimizations; for (const auto& factory : optimization_pack_factories) { ASSIGN_OR_RETURN(PeepholeOptimizationPack pack, factory()); optimizations.reserve(optimizations.size() + pack.size()); std::move(pack.begin(), pack.end(), std::back_inserter(optimizations)); } return PeepholeOptimizer::Create(std::move(optimizations)); } }
#include "arolla/expr/optimization/peephole_optimizer.h" #include <cstdint> #include <memory> #include <string> #include <utility> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/container/flat_hash_map.h" #include "absl/hash/hash_testing.h" #include "absl/random/random.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/registered_expr_operator.h" #include "arolla/expr/testing/testing.h" #include "arolla/expr/visitors/substitution.h" #include "arolla/memory/optional_value.h" #include "arolla/util/init_arolla.h" #include "arolla/util/testing/status_matchers_backport.h" #include "arolla/util/status_macros_backport.h" namespace arolla::expr { namespace { using ::arolla::testing::EqualsExpr; using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::StatusIs; using ::testing::Eq; using ::testing::HasSubstr; using ::testing::Ne; class Optimization : public ::testing::Test { void SetUp() override { ASSERT_OK(InitArolla()); } }; TEST_F(Optimization, Errors) { ExprNodePtr leaf = Leaf("x"); ExprNodePtr px = Placeholder("x"); ASSERT_OK_AND_ASSIGN(ExprNodePtr opx, CallOp("math.add", {px, px})); ExprNodePtr py = Placeholder("y"); ASSERT_OK_AND_ASSIGN(ExprNodePtr opy, CallOp("math.add", {py, py})); EXPECT_THAT(PeepholeOptimization::CreatePatternOptimization(opx, leaf), StatusIs(absl::StatusCode::kFailedPrecondition, HasSubstr("leaves are not allowed"))); EXPECT_THAT(PeepholeOptimization::CreatePatternOptimization(leaf, opx), StatusIs(absl::StatusCode::kFailedPrecondition, HasSubstr("leaves are not allowed"))); EXPECT_THAT(PeepholeOptimization::CreatePatternOptimization(opy, opx), StatusIs(absl::StatusCode::kFailedPrecondition, HasSubstr("unknown placeholder keys"))); EXPECT_THAT(PeepholeOptimization::CreatePatternOptimization(px, opx), StatusIs(absl::StatusCode::kFailedPrecondition, HasSubstr("match everything"))); EXPECT_THAT(PeepholeOptimization::CreatePatternOptimization( opx, opx, {{"y", [](auto) { return true; }}}), StatusIs(absl::StatusCode::kFailedPrecondition, HasSubstr("unknown placeholder matcher keys"))); } absl::StatusOr<std::unique_ptr<PeepholeOptimization>> Plus2MinusOptimization() { ASSIGN_OR_RETURN( ExprNodePtr apb, CallOpReference("math.add", {Placeholder("a"), Placeholder("b")})); ASSIGN_OR_RETURN( ExprNodePtr amb, CallOpReference("math.subtract", {Placeholder("a"), Placeholder("b")})); return PeepholeOptimization::CreatePatternOptimization(apb, amb); } absl::StatusOr<std::unique_ptr<PeepholeOptimization>> Pair2FirstOptimization() { ASSIGN_OR_RETURN( ExprNodePtr from, CallOpReference("core.make_tuple", {Placeholder("a"), Placeholder("b")})); ExprNodePtr to = Placeholder("a"); return PeepholeOptimization::CreatePatternOptimization(from, to); } TEST_F(Optimization, NoOptimizations) { ASSERT_OK_AND_ASSIGN(auto optimization, Plus2MinusOptimization()); { ASSERT_OK_AND_ASSIGN(ExprNodePtr expr, CallOp("math.multiply", {Leaf("a"), Leaf("b")})); EXPECT_THAT(optimization->ApplyToRoot(expr), IsOkAndHolds(EqualsExpr(expr))); } { ASSERT_OK_AND_ASSIGN(ExprNodePtr expr, CallOp("math.subtract", {Leaf("a"), Leaf("b")})); EXPECT_THAT(optimization->ApplyToRoot(expr), IsOkAndHolds(EqualsExpr(expr))); } { ExprNodePtr expr = Placeholder("x"); EXPECT_THAT(optimization->ApplyToRoot(expr), IsOkAndHolds(EqualsExpr(expr))); } { ExprNodePtr expr = Placeholder("x"); EXPECT_THAT(optimization->ApplyToRoot(expr), IsOkAndHolds(EqualsExpr(expr))); } { ExprNodePtr expr = Literal(1.); EXPECT_THAT(optimization->ApplyToRoot(expr), IsOkAndHolds(EqualsExpr(expr))); } ASSERT_OK_AND_ASSIGN(auto pair_optimization, Pair2FirstOptimization()); { ASSERT_OK_AND_ASSIGN(ExprNodePtr expr, CallOp("core.make_tuple", {Leaf("x")})); EXPECT_THAT(pair_optimization->ApplyToRoot(expr), IsOkAndHolds(EqualsExpr(expr))); } } TEST_F(Optimization, Key) { ASSERT_OK_AND_ASSIGN(auto optimization, Plus2MinusOptimization()); ASSERT_OK_AND_ASSIGN(ExprNodePtr plus, CallOp("math.add", {Leaf("x"), Leaf("y")})); ASSERT_OK_AND_ASSIGN(ExprNodePtr minus, CallOp("math.subtract", {Leaf("x"), Leaf("y")})); ExprNodePtr leaf = Leaf("x"); ExprNodePtr leaf2 = Leaf("y"); ExprNodePtr placeholder = Placeholder("x"); ExprNodePtr placeholder2 = Placeholder("y"); ExprNodePtr literal = Literal(1.0); ExprNodePtr literal2 = Literal(1.0f); EXPECT_THAT(optimization->GetKey(), Eq(PeepholeOptimization::PatternKey(plus))); EXPECT_THAT(optimization->GetKey(), Ne(PeepholeOptimization::PatternKey(minus))); EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly({ PeepholeOptimization::PatternKey(plus), PeepholeOptimization::PatternKey(minus), PeepholeOptimization::PatternKey(leaf), PeepholeOptimization::PatternKey(leaf2), PeepholeOptimization::PatternKey(literal), PeepholeOptimization::PatternKey(literal2), PeepholeOptimization::PatternKey(placeholder), PeepholeOptimization::PatternKey(placeholder2), })); } TEST_F(Optimization, SimpleOptimizations) { ASSERT_OK_AND_ASSIGN(auto optimization, Plus2MinusOptimization()); { ASSERT_OK_AND_ASSIGN(ExprNodePtr expr, CallOp("math.add", {Leaf("x"), Leaf("y")})); ASSERT_OK_AND_ASSIGN(ExprNodePtr expected_expr, CallOp("math.subtract", {Leaf("x"), Leaf("y")})); EXPECT_THAT(optimization->ApplyToRoot(expr), IsOkAndHolds(EqualsExpr(expected_expr))); } { ASSERT_OK_AND_ASSIGN(ExprNodePtr expr, CallOp("math.add", {Leaf("x"), Leaf("x")})); ASSERT_OK_AND_ASSIGN(ExprNodePtr expected_expr, CallOp("math.subtract", {Leaf("x"), Leaf("x")})); EXPECT_THAT(optimization->ApplyToRoot(expr), IsOkAndHolds(EqualsExpr(expected_expr))); } { ASSERT_OK_AND_ASSIGN(ExprNodePtr subexpr, CallOp("math.multiply", {Leaf("a"), Leaf("b")})); ASSERT_OK_AND_ASSIGN(ExprNodePtr expr, CallOp("math.add", {Placeholder("x"), subexpr})); ASSERT_OK_AND_ASSIGN(ExprNodePtr expected_expr, CallOp("math.subtract", {Placeholder("x"), subexpr})); EXPECT_THAT(optimization->ApplyToRoot(expr), IsOkAndHolds(EqualsExpr(expected_expr))); } { ASSERT_OK_AND_ASSIGN(ExprNodePtr expr, CallOp("math.add", {Literal(1.f), Literal(2.f)})); ASSERT_OK_AND_ASSIGN(ExprNodePtr expected_expr, CallOp("math.subtract", {Literal(1.f), Literal(2.f)})); EXPECT_THAT(optimization->ApplyToRoot(expr), IsOkAndHolds(EqualsExpr(expected_expr))); } } TEST_F(Optimization, BackendWrapperOperatorOptimizations) { ASSERT_OK_AND_ASSIGN(auto optimization, Plus2MinusOptimization()); { ASSERT_OK_AND_ASSIGN( auto add_backend, DecayRegisteredOperator(LookupOperator("math.add").value())); ASSERT_TRUE(dynamic_cast<const BackendExprOperatorTag*>( add_backend.get()) != nullptr); ASSERT_OK_AND_ASSIGN(ExprNodePtr expr, CallOp(add_backend, {Leaf("x"), Leaf("y")})); ASSERT_OK_AND_ASSIGN(ExprNodePtr expected_expr, CallOp("math.subtract", {Leaf("x"), Leaf("y")})); EXPECT_THAT(optimization->ApplyToRoot(expr), IsOkAndHolds(EqualsExpr(expected_expr))); } } constexpr auto kIsLiteral = [](const ExprNodePtr& expr) { return expr->is_literal(); }; absl::StatusOr<std::unique_ptr<PeepholeOptimization>> HasLiteralOptimization() { ASSIGN_OR_RETURN( ExprNodePtr from, CallOpReference("core.has._array", {CallOpReference("core.presence_or", {Placeholder("a"), Placeholder("b")})})); ASSIGN_OR_RETURN( ExprNodePtr to, CallOpReference("core.presence_or", {CallOpReference("core.has", {Placeholder("a")}), CallOpReference("core.has", {Placeholder("b")})})); return PeepholeOptimization::CreatePatternOptimization(from, to, {{"b", kIsLiteral}}); } TEST_F(Optimization, RestrictedOptimizations) { ASSERT_OK_AND_ASSIGN(auto optimization, HasLiteralOptimization()); OptionalValue<float> opt1 = 1.0f; { ASSERT_OK_AND_ASSIGN( ExprNodePtr expr, CallOp("core.has._array", {CallOp("core.presence_or", {Leaf("x"), Leaf("y")})})); ASSERT_OK_AND_ASSIGN(expr, ToLowest(expr)); EXPECT_THAT(optimization->ApplyToRoot(expr), IsOkAndHolds(EqualsExpr(expr))); } { ASSERT_OK_AND_ASSIGN( ExprNodePtr expr, CallOp("core.has._array", {CallOp("core.presence_or", {Leaf("x"), Literal(opt1)})})); ASSERT_OK_AND_ASSIGN(expr, ToLowest(expr)); ASSERT_OK_AND_ASSIGN( ExprNodePtr expected_expr, CallOp("core.presence_or", {CallOp("core.has", {Leaf("x")}), CallOp("core.has", {Literal(opt1)})})); EXPECT_THAT(optimization->ApplyToRoot(expr), IsOkAndHolds(EqualsExpr(expected_expr))); } } absl::StatusOr<std::unique_ptr<PeepholeOptimization>> SquareA2AxAOptimization() { ASSIGN_OR_RETURN( ExprNodePtr square_a, CallOpReference("math._pow", {Placeholder("a"), Literal(2.f)})); ASSIGN_OR_RETURN( ExprNodePtr axa, CallOpReference("math.multiply", {Placeholder("a"), Placeholder("a")})); return PeepholeOptimization::CreatePatternOptimization(square_a, axa); } TEST_F(Optimization, LiteralOptimizations) { ASSERT_OK_AND_ASSIGN(auto optimization, SquareA2AxAOptimization()); { ASSERT_OK_AND_ASSIGN(ExprNodePtr expr, CallOp("math._pow", {Leaf("x"), Literal(2.f)})); ASSERT_OK_AND_ASSIGN(ExprNodePtr expected_expr, CallOp("math.multiply", {Leaf("x"), Leaf("x")})); EXPECT_THAT(optimization->ApplyToRoot(expr), IsOkAndHolds(EqualsExpr(expected_expr))); } { ASSERT_OK_AND_ASSIGN(ExprNodePtr expr, CallOp("math._pow", {Leaf("x"), Literal(3.f)})); EXPECT_THAT(optimization->ApplyToRoot(expr), IsOkAndHolds(EqualsExpr(expr))); } { ASSERT_OK_AND_ASSIGN(ExprNodePtr expr, CallOp("math._pow", {Leaf("x"), Literal(2.)})); EXPECT_THAT(optimization->ApplyToRoot(expr), IsOkAndHolds(EqualsExpr(expr))); } } absl::StatusOr<std::unique_ptr<PeepholeOptimization>> ApBxAmBOptimization() { ASSIGN_OR_RETURN( ExprNodePtr from, CallOpReference( "math.multiply", {CallOpReference("math.add", {Placeholder("a"), Placeholder("b")}), CallOpReference("math.subtract", {Placeholder("a"), Placeholder("b")})})); ASSIGN_OR_RETURN( ExprNodePtr to, CallOpReference("math.subtract", {CallOpReference("math.multiply", {Placeholder("a"), Placeholder("a")}), CallOpReference("math.multiply", {Placeholder("b"), Placeholder("b")})})); return PeepholeOptimization::CreatePatternOptimization(from, to); } TEST_F(Optimization, SamePartsInOptimization) { ASSERT_OK_AND_ASSIGN(auto optimization, ApBxAmBOptimization()); { ASSERT_OK_AND_ASSIGN( ExprNodePtr expr, CallOp("math.multiply", {CallOp("math.add", {Leaf("x"), Leaf("y")}), CallOp("math.subtract", {Leaf("x"), Leaf("y")})})); ASSERT_OK_AND_ASSIGN( ExprNodePtr expected_expr, CallOp("math.subtract", {CallOp("math.multiply", {Leaf("x"), Leaf("x")}), CallOp("math.multiply", {Leaf("y"), Leaf("y")})})); EXPECT_THAT(optimization->ApplyToRoot(expr), IsOkAndHolds(EqualsExpr(expected_expr))); } { ASSERT_OK_AND_ASSIGN( ExprNodePtr expr, CallOp("math.multiply", {CallOp("math.add", {Leaf("x"), Leaf("y")}), CallOp("math.subtract", {Leaf("x"), Leaf("c")})})); EXPECT_THAT(optimization->ApplyToRoot(expr), IsOkAndHolds(EqualsExpr(expr))); } { ASSERT_OK_AND_ASSIGN( ExprNodePtr expr, CallOp("math.multiply", {CallOp("math.add", {Leaf("x"), Leaf("y")}), CallOp("math.subtract", {Leaf("x"), Leaf("x")})})); EXPECT_THAT(optimization->ApplyToRoot(expr), IsOkAndHolds(EqualsExpr(expr))); } } absl::StatusOr<std::unique_ptr<PeepholeOptimization>> ApBPowerNOptimization( int64_t n) { ASSIGN_OR_RETURN( ExprNodePtr apb, CallOpReference("math.add", {Placeholder("a"), Placeholder("b")})); ExprNodePtr from = apb; for (int64_t i = 1; i != n; ++i) { ASSIGN_OR_RETURN(from, CallOpReference("math.multiply", {from, apb})); } ASSIGN_OR_RETURN(ExprNodePtr to, CallOpReference("math._pow", {apb, Literal<int64_t>(n)})); return PeepholeOptimization::CreatePatternOptimization(from, to); } TEST_F(Optimization, ManySimilarNodes) { constexpr int64_t n = 25; ASSERT_OK_AND_ASSIGN(auto optimization, ApBPowerNOptimization(n)); { ASSERT_OK_AND_ASSIGN(ExprNodePtr xpy, CallOp("math.add", {Leaf("x"), Leaf("y")})); ExprNodePtr expr = xpy; for (int64_t i = 1; i != n; ++i) { ASSERT_OK_AND_ASSIGN(expr, CallOp("math.multiply", {expr, xpy})); } ASSERT_OK_AND_ASSIGN(ExprNodePtr expected_expr, CallOp("math._pow", {xpy, Literal<int64_t>(n)})); EXPECT_THAT(optimization->ApplyToRoot(expr), IsOkAndHolds(EqualsExpr(expected_expr))); } { ASSERT_OK_AND_ASSIGN(ExprNodePtr xpy, CallOp("math.add", {Leaf("x"), Leaf("y")})); ASSERT_OK_AND_ASSIGN(ExprNodePtr ypx, CallOp("math.add", {Leaf("y"), Leaf("x")})); ExprNodePtr expr = xpy; for (int64_t i = 1; i != n - 2; ++i) { ASSERT_OK_AND_ASSIGN(expr, CallOp("math.multiply", {expr, xpy})); } ASSERT_OK_AND_ASSIGN(expr, CallOp("math.multiply", {expr, ypx})); ASSERT_OK_AND_ASSIGN(expr, CallOp("math.multiply", {expr, xpy})); EXPECT_THAT(optimization->ApplyToRoot(expr), IsOkAndHolds(EqualsExpr(expr))); } } absl::StatusOr<ExprNodePtr> BigRandomExpr(int64_t placeholder_count, int64_t op_count) { std::vector<ExprNodePtr> exprs; for (int64_t i = 0; i != placeholder_count; ++i) { exprs.push_back(Placeholder(std::to_string(i))); } absl::BitGen gen; auto binary_op = [&]() -> std::string { std::vector<std::string> names = {"math.add", "math.multiply", "math._pow"}; return names[absl::Uniform(gen, 0u, names.size())]; }; for (int64_t i = 0; i != op_count; ++i) { auto x = exprs[absl::Uniform(gen, 0u, exprs.size())]; auto y = exprs[absl::Uniform(gen, 0u, exprs.size())]; ASSIGN_OR_RETURN(ExprNodePtr op, CallOp(binary_op(), {x, y})); } auto unary_op = [&]() -> std::string { std::vector<std::string> names = {"math.neg", "math.log", "math.log1p"}; return names[absl::Uniform(gen, 0u, names.size())]; }; ExprNodePtr res = exprs.back(); for (const ExprNodePtr& expr : exprs) { ASSIGN_OR_RETURN(res, CallOp(binary_op(), {CallOp(unary_op(), {res}), CallOp(unary_op(), {expr})})); } return res; } TEST_F(Optimization, StressTest) { for (int64_t placeholder_count = 1; placeholder_count <= 64; placeholder_count *= 4) { for (int64_t op_count = 1; op_count <= 256; op_count *= 4) { ASSERT_OK_AND_ASSIGN(ExprNodePtr from, BigRandomExpr(placeholder_count, op_count)); ASSERT_OK_AND_ASSIGN(ExprNodePtr to, BigRandomExpr(placeholder_count, op_count)); ASSERT_OK_AND_ASSIGN( auto optimization, PeepholeOptimization::CreatePatternOptimization(from, to)); absl::flat_hash_map<std::string, ExprNodePtr> subs; for (int i = 0; i != placeholder_count; ++i) { ASSERT_OK_AND_ASSIGN(ExprNodePtr sub, BigRandomExpr(i + 1, i * 2 + 1)); subs.emplace(std::to_string(i), sub); } ASSERT_OK_AND_ASSIGN(ExprNodePtr expr, SubstitutePlaceholders(from, subs)); ASSERT_OK_AND_ASSIGN(ExprNodePtr expected_expr, SubstitutePlaceholders(to, subs)); EXPECT_THAT(optimization->ApplyToRoot(expr), IsOkAndHolds(EqualsExpr(expected_expr))); } } } TEST_F(Optimization, TwoOptimizations) { std::vector<std::unique_ptr<PeepholeOptimization>> optimizations; ASSERT_OK_AND_ASSIGN(auto a2_opt, SquareA2AxAOptimization()); optimizations.push_back(std::move(a2_opt)); ASSERT_OK_AND_ASSIGN(auto a3_opt, ApBPowerNOptimization(3)); optimizations.push_back(std::move(a3_opt)); ASSERT_OK_AND_ASSIGN(ExprNodePtr square, CallOp("math._pow", {Leaf("x"), Literal(2.f)})); ASSERT_OK_AND_ASSIGN(ExprNodePtr square2, CallOp("math.add", {square, square})); ASSERT_OK_AND_ASSIGN( ExprNodePtr cubic_square2, CallOp("math.multiply", {CallOp("math.multiply", {square2, square2}), square2})); ASSERT_OK_AND_ASSIGN(ExprNodePtr x2, CallOp("math.multiply", {Leaf("x"), Leaf("x")})); ASSERT_OK_AND_ASSIGN( ExprNodePtr expected_cubic_square2_optimized, CallOp("math._pow", {CallOp("math.add", {x2, x2}), Literal(int64_t{3})})); ASSERT_OK_AND_ASSIGN(auto optimizer, PeepholeOptimizer::Create(std::move(optimizations))); EXPECT_THAT(optimizer->Apply(cubic_square2), IsOkAndHolds(EqualsExpr(expected_cubic_square2_optimized))); EXPECT_THAT(optimizer->Apply(expected_cubic_square2_optimized), IsOkAndHolds(EqualsExpr(expected_cubic_square2_optimized))); } absl::StatusOr<std::unique_ptr<PeepholeOptimization>> RemoveArithmeticOptimization() { return PeepholeOptimization::CreateTransformOptimization( [](ExprNodePtr expr) { if (!expr->is_op()) { return expr; } if (expr->op()->display_name() == "math.add" || expr->op()->display_name() == "math.multiply") { return expr->node_deps().empty() ? expr : expr->node_deps()[0]; } return expr; }); } TEST_F(Optimization, TransformOptimization) { std::vector<std::unique_ptr<PeepholeOptimization>> optimizations; ASSERT_OK_AND_ASSIGN(auto opt, RemoveArithmeticOptimization()); optimizations.push_back(std::move(opt)); ASSERT_OK_AND_ASSIGN(auto optimizer, PeepholeOptimizer::Create(std::move(optimizations))); ExprNodePtr z = Leaf("z"); ASSERT_OK_AND_ASSIGN(ExprNodePtr zx1, CallOp("math.multiply", {z, Literal(1.f)})); ASSERT_OK_AND_ASSIGN(ExprNodePtr zx1p0, CallOp("math.add", {zx1, Literal(0.f)})); EXPECT_THAT(optimizer->Apply(zx1), IsOkAndHolds(EqualsExpr(z))); EXPECT_THAT(optimizer->Apply(zx1p0), IsOkAndHolds(EqualsExpr(z))); } } }
2,449
#ifndef AROLLA_EXPR_OPTIMIZATION_OPTIMIZER_H_ #define AROLLA_EXPR_OPTIMIZATION_OPTIMIZER_H_ #include <functional> #include <memory> #include "absl/status/statusor.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/optimization/peephole_optimizer.h" namespace arolla::expr { using Optimizer = std::function<absl::StatusOr<ExprNodePtr>(ExprNodePtr)>; Optimizer MakeOptimizer(std::unique_ptr<PeepholeOptimizer> peephole_optimizer); } #endif #include "arolla/expr/optimization/optimizer.h" #include <memory> #include <utility> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "arolla/expr/expr_debug_string.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/optimization/peephole_optimizer.h" #include "arolla/util/status_macros_backport.h" namespace arolla::expr { namespace { constexpr int kPeepholeOptimizerIterationsLimit = 100; } Optimizer MakeOptimizer(std::unique_ptr<PeepholeOptimizer> peephole_optimizer) { return [peephole_optimizer = std::shared_ptr<PeepholeOptimizer>( std::move(peephole_optimizer))]( ExprNodePtr expr) -> absl::StatusOr<ExprNodePtr> { ExprNodePtr previous_expr; int iteration = 0; do { if (++iteration > kPeepholeOptimizerIterationsLimit) { return absl::InternalError(absl::StrFormat( "too many iterations of peephole optimizer; this may indicate that " "the set of optimizations contains cycles, or just too big " "expression unsupported by the optimizer (last iterations: %s vs " "%s)", GetDebugSnippet(previous_expr), GetDebugSnippet(expr))); } previous_expr = expr; ASSIGN_OR_RETURN(expr, peephole_optimizer->ApplyToNode(expr)); if (expr->qtype() != previous_expr->qtype()) { return absl::InternalError(absl::StrFormat( "expression %s was optimized into %s, which changed its output " "type from %s to %s; this indicates incorrect optimization", GetDebugSnippet(previous_expr), GetDebugSnippet(expr), previous_expr->qtype() != nullptr ? previous_expr->qtype()->name() : "NULL", expr->qtype() != nullptr ? expr->qtype()->name() : "NULL")); } } while (previous_expr->fingerprint() != expr->fingerprint()); return expr; }; } }
#include "arolla/expr/optimization/optimizer.h" #include <cstdint> #include <memory> #include <utility> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/optimization/peephole_optimizer.h" #include "arolla/expr/testing/testing.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/util/init_arolla.h" #include "arolla/util/testing/status_matchers_backport.h" #include "arolla/util/status_macros_backport.h" namespace arolla::expr { namespace { using ::arolla::testing::StatusIs; using ::arolla::testing::WithQTypeAnnotation; class Optimizer : public ::testing::Test { void SetUp() override { ASSERT_OK(InitArolla()); } }; absl::StatusOr<PeepholeOptimizationPack> ChangeTypeOptimizations() { PeepholeOptimizationPack result; { ASSIGN_OR_RETURN(ExprNodePtr from, WithQTypeAnnotation(Placeholder("x"), GetQType<float>())); ASSIGN_OR_RETURN(ExprNodePtr to, WithQTypeAnnotation(Placeholder("x"), GetQType<int32_t>())); ASSIGN_OR_RETURN(result.emplace_back(), PeepholeOptimization::CreatePatternOptimization(from, to)); } { ASSIGN_OR_RETURN(ExprNodePtr from, WithQTypeAnnotation(Placeholder("x"), GetQType<double>())); ExprNodePtr to = Placeholder("x"); ASSIGN_OR_RETURN(result.emplace_back(), PeepholeOptimization::CreatePatternOptimization(from, to)); } return result; } TEST_F(Optimizer, TypeChangesAreNotAllowed) { ASSERT_OK_AND_ASSIGN(auto peephole_optimizer, CreatePeepholeOptimizer({ChangeTypeOptimizations})); auto optimizer = MakeOptimizer(std::move(peephole_optimizer)); ASSERT_OK_AND_ASSIGN(ExprNodePtr float_x, WithQTypeAnnotation(Leaf("x"), GetQType<float>())); EXPECT_THAT( optimizer(float_x), StatusIs(absl::StatusCode::kInternal, "expression M.annotation.qtype(L.x, FLOAT32) was optimized into " "M.annotation.qtype(L.x, INT32), which changed its output type " "from FLOAT32 to INT32; this indicates incorrect optimization")); ASSERT_OK_AND_ASSIGN(ExprNodePtr double_x, WithQTypeAnnotation(Leaf("x"), GetQType<double>())); EXPECT_THAT( optimizer(double_x), StatusIs(absl::StatusCode::kInternal, "expression M.annotation.qtype(L.x, FLOAT64) was optimized into " "L.x, which changed its output type from FLOAT64 to NULL; this " "indicates incorrect optimization")); } } }
2,450
#ifndef AROLLA_EXPR_OPTIMIZATION_PEEPHOLE_OPTIMIZATIONS_ARITHMETIC_H_ #define AROLLA_EXPR_OPTIMIZATION_PEEPHOLE_OPTIMIZATIONS_ARITHMETIC_H_ #include "absl/status/statusor.h" #include "arolla/expr/optimization/peephole_optimizer.h" namespace arolla::expr { absl::StatusOr<PeepholeOptimizationPack> ArithmeticOptimizations(); } #endif #include "arolla/expr/optimization/peephole_optimizations/arithmetic.h" #include <cstdint> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/optimization/peephole_optimizer.h" #include "arolla/memory/optional_value.h" #include "arolla/util/meta.h" #include "arolla/util/status_macros_backport.h" namespace arolla::expr { namespace { absl::Status RemoveAddOptimizationsImpl( const ExprNodePtr& zero, PeepholeOptimizationPack& optimizations) { auto same_qtype = [qtype = zero->qtype()](const ExprNodePtr& expr) { return expr->qtype() == qtype; }; ExprNodePtr a = Placeholder("a"); ASSIGN_OR_RETURN(ExprNodePtr from1, CallOpReference("math.add", {a, zero})); ASSIGN_OR_RETURN(ExprNodePtr from2, CallOpReference("math.add", {zero, a})); for (const auto& from : {from1, from2}) { ASSIGN_OR_RETURN(optimizations.emplace_back(), PeepholeOptimization::CreatePatternOptimization( from, a, {{"a", same_qtype}})); } return absl::OkStatus(); } template <class T> absl::Status RemoveAddOptimizationsImpl( PeepholeOptimizationPack& optimizations) { return RemoveAddOptimizationsImpl(Literal(T(0)), optimizations); } absl::Status RemoveAddOptimizations(PeepholeOptimizationPack& optimizations) { absl::Status res_status; meta::foreach_type<meta::type_list<float, double, int32_t, int64_t>>( [&](auto meta_type) { using type = typename decltype(meta_type)::type; auto status = RemoveAddOptimizationsImpl<type>(optimizations); if (!status.ok()) res_status = status; status = RemoveAddOptimizationsImpl<OptionalValue<type>>(optimizations); if (!status.ok()) res_status = status; }); return res_status; } absl::Status RemoveMulOptimizationsImpl( const ExprNodePtr& one, PeepholeOptimizationPack& optimizations) { ExprNodePtr a = Placeholder("a"); auto same_qtype = [qtype = one->qtype()](const ExprNodePtr& expr) { return expr->qtype() == qtype; }; ASSIGN_OR_RETURN(ExprNodePtr to_a1, CallOpReference("math.multiply", {a, one})); ASSIGN_OR_RETURN(ExprNodePtr to_a2, CallOpReference("math.multiply", {one, a})); for (const auto& from : {to_a1, to_a2}) { ASSIGN_OR_RETURN(optimizations.emplace_back(), PeepholeOptimization::CreatePatternOptimization( from, a, {{"a", same_qtype}})); } return absl::OkStatus(); } template <class T> absl::Status RemoveMulOptimizationsImpl( PeepholeOptimizationPack& optimizations) { return RemoveMulOptimizationsImpl(Literal<T>(1), optimizations); } absl::Status RemoveMulOptimizations(PeepholeOptimizationPack& optimizations) { absl::Status res_status; meta::foreach_type<meta::type_list<float, double, int32_t, int64_t>>( [&](auto meta_type) { using type = typename decltype(meta_type)::type; auto status = RemoveMulOptimizationsImpl<type>(optimizations); if (!status.ok()) res_status = status; status = RemoveMulOptimizationsImpl<OptionalValue<type>>(optimizations); if (!status.ok()) res_status = status; }); return res_status; } } absl::StatusOr<PeepholeOptimizationPack> ArithmeticOptimizations() { PeepholeOptimizationPack optimizations; RETURN_IF_ERROR(RemoveAddOptimizations(optimizations)); RETURN_IF_ERROR(RemoveMulOptimizations(optimizations)); return optimizations; } }
#include "arolla/expr/optimization/peephole_optimizations/arithmetic.h" #include <utility> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/statusor.h" #include "arolla/dense_array/qtype/types.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_visitor.h" #include "arolla/expr/optimization/optimizer.h" #include "arolla/expr/optimization/peephole_optimizer.h" #include "arolla/expr/testing/testing.h" #include "arolla/memory/optional_value.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/optional_qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/util/init_arolla.h" #include "arolla/util/testing/status_matchers_backport.h" namespace arolla::expr { namespace { using ::arolla::testing::EqualsExpr; using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::WithQTypeAnnotation; class ArithmeticOptimizationsTest : public ::testing::Test { protected: void SetUp() override { ASSERT_OK(InitArolla()); ASSERT_OK_AND_ASSIGN(auto peephole_optimizer, CreatePeepholeOptimizer({ArithmeticOptimizations})); optimizer_ = MakeOptimizer(std::move(peephole_optimizer)); } absl::StatusOr<ExprNodePtr> ApplyOptimizer(ExprNodePtr expr) const { return DeepTransform(expr, optimizer_); } Optimizer optimizer_; }; TEST_F(ArithmeticOptimizationsTest, AddZeroRemoval) { ExprNodePtr x_no_type = Leaf("x"); ASSERT_OK_AND_ASSIGN(ExprNodePtr x_float, WithQTypeAnnotation(Leaf("x"), GetQType<float>())); ExprNodePtr zero_float = Literal(0.0f); ASSERT_OK_AND_ASSIGN(ExprNodePtr x_int, WithQTypeAnnotation(Leaf("x"), GetQType<int>())); ExprNodePtr zero_int = Literal(0); ASSERT_OK_AND_ASSIGN( ExprNodePtr x_opt_double, WithQTypeAnnotation(Leaf("x"), GetOptionalQType<double>())); ExprNodePtr zero_opt_double = Literal(OptionalValue<double>(0.0)); for (const auto& [a, b] : std::vector<std::pair<ExprNodePtr, ExprNodePtr>>{ {x_no_type, zero_float}, {x_opt_double, zero_float}, }) { ASSERT_OK_AND_ASSIGN(ExprNodePtr add_zero, CallOp("math.add", {a, b})); EXPECT_THAT(ApplyOptimizer(add_zero), IsOkAndHolds(EqualsExpr(add_zero))); } for (const auto& [a, zero] : std::vector<std::pair<ExprNodePtr, ExprNodePtr>>{ {x_float, zero_float}, {x_int, zero_int}, {x_opt_double, zero_opt_double}, }) { ASSERT_OK_AND_ASSIGN(ExprNodePtr add_zero, CallOp("math.add", {a, zero})); EXPECT_THAT(ApplyOptimizer(add_zero), IsOkAndHolds(EqualsExpr(a))); ASSERT_OK_AND_ASSIGN(add_zero, CallOp("math.add", {zero, a})); EXPECT_THAT(ApplyOptimizer(add_zero), IsOkAndHolds(EqualsExpr(a))); } } TEST_F(ArithmeticOptimizationsTest, MulOneRemoval) { ExprNodePtr x_no_type = Leaf("x"); ASSERT_OK_AND_ASSIGN(ExprNodePtr x_float, WithQTypeAnnotation(Leaf("x"), GetQType<float>())); ExprNodePtr one_float = Literal(1.0f); ASSERT_OK_AND_ASSIGN(ExprNodePtr x_int, WithQTypeAnnotation(Leaf("x"), GetQType<int>())); ExprNodePtr one_int = Literal(1); ASSERT_OK_AND_ASSIGN( ExprNodePtr x_opt_double, WithQTypeAnnotation(Leaf("x"), GetOptionalQType<double>())); ExprNodePtr one_opt_double = Literal(OptionalValue<double>(1.0)); for (const auto& [a, b] : std::vector<std::pair<ExprNodePtr, ExprNodePtr>>{ {x_no_type, one_float}, {x_opt_double, one_float}, }) { ASSERT_OK_AND_ASSIGN(ExprNodePtr mul_one, CallOp("math.multiply", {a, b})); EXPECT_THAT(ApplyOptimizer(mul_one), IsOkAndHolds(EqualsExpr(mul_one))); } for (const auto& [a, one] : std::vector<std::pair<ExprNodePtr, ExprNodePtr>>{ {x_float, one_float}, {x_int, one_int}, {x_opt_double, one_opt_double}, }) { ASSERT_OK_AND_ASSIGN(ExprNodePtr mul_one, CallOp("math.multiply", {a, one})); EXPECT_THAT(ApplyOptimizer(mul_one), IsOkAndHolds(EqualsExpr(a))); ASSERT_OK_AND_ASSIGN(mul_one, CallOp("math.multiply", {one, a})); EXPECT_THAT(ApplyOptimizer(mul_one), IsOkAndHolds(EqualsExpr(a))); } } } }
2,451
#ifndef AROLLA_EXPR_OPTIMIZATION_PEEPHOLE_OPTIMIZATIONS_REDUCE_H_ #define AROLLA_EXPR_OPTIMIZATION_PEEPHOLE_OPTIMIZATIONS_REDUCE_H_ #include "absl/status/statusor.h" #include "arolla/expr/optimization/peephole_optimizer.h" namespace arolla::expr { absl::StatusOr<PeepholeOptimizationPack> ReduceOptimizations(); } #endif #include "arolla/expr/optimization/peephole_optimizations/reduce.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/optimization/peephole_optimizer.h" #include "arolla/util/status_macros_backport.h" namespace arolla::expr { namespace { absl::Status AppendAdd4Optimizations(PeepholeOptimizationPack& optimizations) { ExprNodePtr a = Placeholder("a"); ExprNodePtr b = Placeholder("b"); ExprNodePtr c = Placeholder("c"); ExprNodePtr d = Placeholder("d"); auto Add = [](auto a, auto b) { return CallOpReference("math.add", {a, b}); }; ASSIGN_OR_RETURN(ExprNodePtr pattern1, Add(Add(a, b), Add(c, d))); ASSIGN_OR_RETURN(ExprNodePtr pattern2, Add(Add(Add(a, b), c), d)); ASSIGN_OR_RETURN(ExprNodePtr pattern3, Add(a, Add(b, Add(c, d)))); ASSIGN_OR_RETURN(ExprNodePtr replacement, CallOpReference("math._add4", {a, b, c, d})); ASSIGN_OR_RETURN( optimizations.emplace_back(), PeepholeOptimization::CreatePatternOptimization(pattern1, replacement)); ASSIGN_OR_RETURN( optimizations.emplace_back(), PeepholeOptimization::CreatePatternOptimization(pattern2, replacement)); ASSIGN_OR_RETURN( optimizations.emplace_back(), PeepholeOptimization::CreatePatternOptimization(pattern3, replacement)); return absl::OkStatus(); } } absl::StatusOr<PeepholeOptimizationPack> ReduceOptimizations() { PeepholeOptimizationPack optimizations; RETURN_IF_ERROR(AppendAdd4Optimizations(optimizations)); return optimizations; } }
#include "arolla/expr/optimization/peephole_optimizations/reduce.h" #include <cstddef> #include <cstdint> #include <memory> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/strings/str_format.h" #include "absl/types/span.h" #include "arolla/dense_array/qtype/types.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_visitor.h" #include "arolla/expr/optimization/peephole_optimizer.h" #include "arolla/expr/testing/testing.h" #include "arolla/qtype/base_types.h" #include "arolla/util/init_arolla.h" #include "arolla/util/testing/status_matchers_backport.h" namespace arolla::expr { namespace { using ::arolla::testing::EqualsExpr; using ::arolla::testing::IsOkAndHolds; class ReduceOptimizationsTest : public ::testing::Test { protected: void SetUp() override { ASSERT_OK(InitArolla()); ASSERT_OK_AND_ASSIGN(optimizer_, CreatePeepholeOptimizer({ReduceOptimizations})); } std::unique_ptr<PeepholeOptimizer> optimizer_; }; size_t CountNodes(const ExprNodePtr& expr) { size_t result = 0; return PostOrderTraverse( expr, [&](const ExprNodePtr& , absl::Span<const size_t* const> ) { return ++result; }); } TEST_F(ReduceOptimizationsTest, SingleSubstitution) { auto a = Leaf("l1"); auto b = Leaf("l2"); auto c = Leaf("l3"); auto d = Leaf("l4"); ASSERT_OK_AND_ASSIGN(auto ab, CallOp("math.add", {a, b})); ASSERT_OK_AND_ASSIGN(auto cd, CallOp("math.add", {c, d})); ASSERT_OK_AND_ASSIGN(auto abcd_balanced, CallOp("math.add", {ab, cd})); ASSERT_OK_AND_ASSIGN(auto abcd_linear, CallOp("math.add", {CallOp("math.add", {ab, c}), d})); ASSERT_OK_AND_ASSIGN(auto abcd_reversed, CallOp("math.add", {a, CallOp("math.add", {b, cd})})); ASSERT_OK_AND_ASSIGN(auto abcd_optimized, CallOp("math._add4", {a, b, c, d})); EXPECT_THAT(optimizer_->Apply(abcd_balanced), IsOkAndHolds(EqualsExpr(abcd_optimized))); EXPECT_THAT(optimizer_->Apply(abcd_linear), IsOkAndHolds(EqualsExpr(abcd_optimized))); EXPECT_THAT(optimizer_->Apply(abcd_reversed), IsOkAndHolds(EqualsExpr(abcd_optimized))); } TEST_F(ReduceOptimizationsTest, BalancedTree) { const int leaf_count = 128; std::vector<ExprNodePtr> nodes; nodes.reserve(leaf_count); for (int i = 0; i < leaf_count; ++i) { nodes.push_back(Leaf(absl::StrFormat("l%d", i))); } while (nodes.size() > 1) { for (int64_t i = 0; i < nodes.size() / 2; ++i) { nodes[i] = *CallOp("math.add", {nodes[i * 2], nodes[i * 2 + 1]}); } if (nodes.size() % 2 == 1) { nodes[nodes.size() / 2] = nodes.back(); } nodes.resize((nodes.size() + 1) / 2); } ExprNodePtr expr = nodes[0]; EXPECT_EQ(CountNodes(expr), leaf_count + 127); ASSERT_OK_AND_ASSIGN(auto res, optimizer_->Apply(expr)); EXPECT_EQ(CountNodes(res), leaf_count + 43); } TEST_F(ReduceOptimizationsTest, LinearTree) { const int leaf_count = 128; ExprNodePtr expr = Leaf("l0"); for (int i = 1; i < leaf_count; ++i) { expr = *CallOp("math.add", {expr, Leaf(absl::StrFormat("l%d", i))}); } EXPECT_EQ(CountNodes(expr), leaf_count + 127); ASSERT_OK_AND_ASSIGN(auto res, optimizer_->Apply(expr)); EXPECT_EQ(CountNodes(res), leaf_count + 43); } TEST_F(ReduceOptimizationsTest, ReversedLinearTree) { const int leaf_count = 128; ExprNodePtr expr = Leaf("l0"); for (int i = 1; i < leaf_count; ++i) { expr = *CallOp("math.add", {Leaf(absl::StrFormat("l%d", i)), expr}); } EXPECT_EQ(CountNodes(expr), leaf_count + 127); ASSERT_OK_AND_ASSIGN(auto res, optimizer_->Apply(expr)); EXPECT_EQ(CountNodes(res), leaf_count + 43); } } }
2,452
#ifndef AROLLA_EXPR_OPTIMIZATION_PEEPHOLE_OPTIMIZATIONS_SHORT_CIRCUIT_WHERE_H_ #define AROLLA_EXPR_OPTIMIZATION_PEEPHOLE_OPTIMIZATIONS_SHORT_CIRCUIT_WHERE_H_ #include "absl/status/statusor.h" #include "arolla/expr/optimization/peephole_optimizer.h" namespace arolla::expr { absl::StatusOr<PeepholeOptimizationPack> ShortCircuitWhereOptimizations(); } #endif #include "arolla/expr/optimization/peephole_optimizations/short_circuit_where.h" #include <functional> #include <memory> #include <utility> #include <vector> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/operators/type_meta_eval_strategies.h" #include "arolla/expr/optimization/peephole_optimizer.h" #include "arolla/memory/optional_value.h" #include "arolla/util/status_macros_backport.h" namespace arolla::expr { namespace { using ::arolla::expr_operators::type_meta::Is; std::function<bool(const ExprNodePtr&)> TypeMatches( expr_operators::type_meta::Strategy strategy) { return [strategy = std::move(strategy)](const ExprNodePtr& node) { return node->qtype() != nullptr && strategy({node->qtype()}).ok(); }; } absl::Status AddCoreWhereOptimizations( PeepholeOptimizationPack& optimizations) { ExprNodePtr cond = Placeholder("cond"); ExprNodePtr x = Placeholder("x"); ExprNodePtr y = Placeholder("y"); { ASSIGN_OR_RETURN(ExprNodePtr from, CallOpReference("core.where", {cond, x, y})); ASSIGN_OR_RETURN( ExprNodePtr to, CallOpReference("core._short_circuit_where", {cond, x, y})); ASSIGN_OR_RETURN(optimizations.emplace_back(), PeepholeOptimization::CreatePatternOptimization( from, to, {{"cond", TypeMatches(Is<OptionalUnit>)}})); } { ExprNodePtr shape = Placeholder("shape"); ASSIGN_OR_RETURN( ExprNodePtr from, CallOpReference("core.where", {CallOpReference("core.const_with_shape._array_shape", {shape, cond}), x, y})); ASSIGN_OR_RETURN( ExprNodePtr to, CallOpReference("core._short_circuit_where", {cond, x, y})); ASSIGN_OR_RETURN(optimizations.emplace_back(), PeepholeOptimization::CreatePatternOptimization( from, to, {{"cond", TypeMatches(Is<OptionalUnit>)}})); } return absl::OkStatus(); } absl::StatusOr<std::unique_ptr<PeepholeOptimization>> AlwaysTrueConditionOptimization() { ASSIGN_OR_RETURN( ExprNodePtr short_circuit_where, CallOpReference("core._short_circuit_where", {Literal(kPresent), Placeholder("x"), Placeholder("y")})); ExprNodePtr x = Placeholder("x"); return PeepholeOptimization::CreatePatternOptimization(short_circuit_where, x); } absl::StatusOr<std::unique_ptr<PeepholeOptimization>> AlwaysFalseConditionOptimization() { ASSIGN_OR_RETURN( ExprNodePtr short_circuit_where, CallOpReference("core._short_circuit_where", {Literal(kMissing), Placeholder("x"), Placeholder("y")})); ExprNodePtr y = Placeholder("y"); return PeepholeOptimization::CreatePatternOptimization(short_circuit_where, y); } } absl::StatusOr<PeepholeOptimizationPack> ShortCircuitWhereOptimizations() { std::vector<std::unique_ptr<PeepholeOptimization>> optimizations; RETURN_IF_ERROR(AddCoreWhereOptimizations(optimizations)); ASSIGN_OR_RETURN(optimizations.emplace_back(), AlwaysTrueConditionOptimization()); ASSIGN_OR_RETURN(optimizations.emplace_back(), AlwaysFalseConditionOptimization()); return optimizations; } }
#include "arolla/expr/optimization/peephole_optimizations/short_circuit_where.h" #include <cstdint> #include <memory> #include <utility> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/statusor.h" #include "arolla/dense_array/dense_array.h" #include "arolla/dense_array/qtype/types.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_visitor.h" #include "arolla/expr/optimization/peephole_optimizations/bool.h" #include "arolla/expr/optimization/peephole_optimizations/const_with_shape.h" #include "arolla/expr/optimization/peephole_optimizer.h" #include "arolla/expr/testing/testing.h" #include "arolla/memory/optional_value.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/util/init_arolla.h" #include "arolla/util/testing/status_matchers_backport.h" #include "arolla/util/unit.h" #include "arolla/util/status_macros_backport.h" namespace arolla::expr { namespace { using ::arolla::testing::EqualsExpr; using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::WithQTypeAnnotation; class ShortCircuitWhereOptimizationsTest : public ::testing::Test { protected: void SetUp() override { ASSERT_OK(InitArolla()); ASSERT_OK_AND_ASSIGN( optimizer_, CreatePeepholeOptimizer({ShortCircuitWhereOptimizations})); } absl::StatusOr<ExprNodePtr> ApplyOptimizer( absl::StatusOr<ExprNodePtr> status_or_expr) const { ASSIGN_OR_RETURN(auto expr, ToLowest(status_or_expr)); return ToLowest(optimizer_->ApplyToNode(expr)); } absl::StatusOr<ExprNodePtr> ToLowest( const absl::StatusOr<ExprNodePtr>& status_or_expr) const { if (!status_or_expr.ok()) { return std::move(status_or_expr).status(); } return ::arolla::expr::ToLowest(*status_or_expr); } std::unique_ptr<PeepholeOptimizer> optimizer_; }; TEST_F(ShortCircuitWhereOptimizationsTest, ScalarCondition) { ASSERT_OK_AND_ASSIGN( auto shape, WithQTypeAnnotation(Leaf("shape"), GetQType<DenseArrayShape>())); ASSERT_OK_AND_ASSIGN(auto x, WithQTypeAnnotation(Leaf("x"), GetQType<float>())); ASSERT_OK_AND_ASSIGN(auto y, WithQTypeAnnotation(Leaf("y"), GetQType<float>())); ASSERT_OK_AND_ASSIGN(auto x_plus_y, CallOp("math.add", {x, y})); ASSERT_OK_AND_ASSIGN(auto x_mul_y, CallOp("math.multiply", {x, y})); ASSERT_OK_AND_ASSIGN( auto scalar_cond, WithQTypeAnnotation(Leaf("cond"), GetQType<OptionalUnit>())); { ASSERT_OK_AND_ASSIGN( auto actual_expr, ApplyOptimizer(CallOp("core.where", {scalar_cond, x_plus_y, x_mul_y}))); ASSERT_OK_AND_ASSIGN(auto expected_expr, ToLowest(CallOp("core._short_circuit_where", {scalar_cond, x_plus_y, x_mul_y}))); EXPECT_THAT(actual_expr, EqualsExpr(expected_expr)); } { ASSERT_OK_AND_ASSIGN( auto actual_expr, ApplyOptimizer(CallOp("core.where", {CallOp("core.const_with_shape", {shape, scalar_cond}), x_plus_y, x_mul_y}))); ASSERT_OK_AND_ASSIGN(auto expected_expr, ToLowest(CallOp("core._short_circuit_where", {scalar_cond, x_plus_y, x_mul_y}))); EXPECT_THAT(actual_expr, EqualsExpr(expected_expr)); } } TEST_F(ShortCircuitWhereOptimizationsTest, ArrayCondition) { ASSERT_OK_AND_ASSIGN(auto x, WithQTypeAnnotation(Leaf("x"), GetQType<float>())); ASSERT_OK_AND_ASSIGN(auto y, WithQTypeAnnotation(Leaf("y"), GetQType<float>())); ASSERT_OK_AND_ASSIGN(auto x_plus_y, CallOp("math.add", {x, y})); ASSERT_OK_AND_ASSIGN(auto x_mul_y, CallOp("math.multiply", {x, y})); ASSERT_OK_AND_ASSIGN( auto array_cond, WithQTypeAnnotation(Leaf("cond"), GetDenseArrayQType<Unit>())); ASSERT_OK_AND_ASSIGN(auto expr, CallOp("core.where", {array_cond, x_plus_y, x_mul_y})); ASSERT_OK_AND_ASSIGN(auto actual_expr, ApplyOptimizer(expr)); ASSERT_OK_AND_ASSIGN(auto expected_expr, ToLowest(expr)); EXPECT_THAT(actual_expr, EqualsExpr(expected_expr)); } TEST_F(ShortCircuitWhereOptimizationsTest, UntypedCondition) { ASSERT_OK_AND_ASSIGN(auto x, WithQTypeAnnotation(Leaf("x"), GetQType<float>())); ASSERT_OK_AND_ASSIGN(auto y, WithQTypeAnnotation(Leaf("y"), GetQType<float>())); ASSERT_OK_AND_ASSIGN(auto x_plus_y, CallOp("math.add", {x, y})); ASSERT_OK_AND_ASSIGN(auto x_mul_y, CallOp("math.multiply", {x, y})); auto untyped_cond = Leaf("cond"); ASSERT_OK_AND_ASSIGN(auto expr, CallOp("core.where", {untyped_cond, x_plus_y, x_mul_y})); ASSERT_OK_AND_ASSIGN(auto actual_expr, ApplyOptimizer(expr)); ASSERT_OK_AND_ASSIGN(auto expected_expr, ToLowest(expr)); EXPECT_THAT(actual_expr, EqualsExpr(expected_expr)); } TEST_F(ShortCircuitWhereOptimizationsTest, ConstScalarCondition) { ASSERT_OK_AND_ASSIGN(auto x, WithQTypeAnnotation(Leaf("x"), GetQType<float>())); ASSERT_OK_AND_ASSIGN(auto y, WithQTypeAnnotation(Leaf("y"), GetQType<float>())); ASSERT_OK_AND_ASSIGN(auto x_plus_y, CallOp("math.add", {x, y})); ASSERT_OK_AND_ASSIGN(auto x_mul_y, CallOp("math.multiply", {x, y})); { ASSERT_OK_AND_ASSIGN( auto actual_expr, ApplyOptimizer(CallOp("core._short_circuit_where", {Literal(kPresent), x_plus_y, x_mul_y}))); ASSERT_OK_AND_ASSIGN(auto expected_expr, ToLowest(x_plus_y)); EXPECT_THAT(actual_expr, EqualsExpr(expected_expr)); } { ASSERT_OK_AND_ASSIGN( auto actual_expr, ApplyOptimizer(CallOp("core._short_circuit_where", {Literal(kMissing), x_plus_y, x_mul_y}))); ASSERT_OK_AND_ASSIGN(auto expected_expr, ToLowest(x_mul_y)); EXPECT_THAT(actual_expr, EqualsExpr(expected_expr)); } } TEST_F(ShortCircuitWhereOptimizationsTest, EndToEndWithBroadcastedCondition) { ASSERT_OK_AND_ASSIGN(auto peephole_optimizer, CreatePeepholeOptimizer({ShortCircuitWhereOptimizations, BoolOptimizations, ConstWithShapeOptimizations})); auto optimize = [&](const ExprNodePtr& node) -> absl::StatusOr<ExprNodePtr> { ASSIGN_OR_RETURN(auto new_node, ToLowerNode(node)); if (new_node->fingerprint() != node->fingerprint()) { return new_node; } return peephole_optimizer->ApplyToNode(node); }; ASSERT_OK_AND_ASSIGN(auto x, WithQTypeAnnotation(Leaf("x"), GetQType<int32_t>())); ASSERT_OK_AND_ASSIGN(auto y, WithQTypeAnnotation(Leaf("y"), GetQType<int32_t>())); auto true_case = WithQTypeAnnotation(Leaf("true_case"), GetQType<float>()); auto false_or_missing_case = WithQTypeAnnotation(Leaf("false_or_missing_case"), GetQType<float>()); ASSERT_OK_AND_ASSIGN(auto x_plus_y, CallOp("math.add", {x, y})); ASSERT_OK_AND_ASSIGN(auto x_mul_y, CallOp("math.multiply", {x, y})); ASSERT_OK_AND_ASSIGN( auto shape, CallOp("core.shape_of", {CallOp("core.has", {true_case})})); ASSERT_OK_AND_ASSIGN( auto relative_shape, CallOp("core.shape_of", {CallOp("core.has", {CallOp("core.const_with_shape", {shape, true_case})})})); ASSERT_OK_AND_ASSIGN( auto broadcasted_condition, CallOp( "bool.logical_or", {CallOp( "bool.equal", {CallOp("core.const_with_shape", {relative_shape, x_plus_y}), CallOp("core.const_with_shape", {relative_shape, Literal(1)})}), CallOp("bool.equal", {CallOp("core.const_with_shape", {relative_shape, x_mul_y}), CallOp("core.const_with_shape", {relative_shape, Literal(1)})})})); ASSERT_OK_AND_ASSIGN(auto expr, CallOp("bool.logical_if", {broadcasted_condition, true_case, false_or_missing_case, false_or_missing_case})); ASSERT_OK_AND_ASSIGN( auto unbroadcasted_condition, CallOp("bool.logical_or", {CallOp("bool.equal", {x_plus_y, Literal(1)}), CallOp("bool.equal", {x_mul_y, Literal(1)})})); EXPECT_THAT(DeepTransform(relative_shape, optimize), IsOkAndHolds(EqualsExpr(ToLowest(shape)))); EXPECT_THAT( DeepTransform(broadcasted_condition, optimize), IsOkAndHolds(EqualsExpr(ToLowest( CallOp("core.const_with_shape", {shape, unbroadcasted_condition}))))); auto optimize_and_broadcast = [&](ExprNodePtr node) -> absl::StatusOr<ExprNodePtr> { ASSIGN_OR_RETURN(node, optimize(std::move(node))); auto true_literal = Literal(true); if (node->is_op() && node->op()->display_name() == "core.equal" && node->node_deps()[1]->fingerprint() == true_literal->fingerprint()) { return CallOp("core.equal", {node->node_deps()[0], CallOp("core.const_with_shape", {shape, true_literal})}); } return node; }; EXPECT_THAT(DeepTransform(expr, optimize_and_broadcast), IsOkAndHolds(EqualsExpr(ToLowest( CallOp("core._short_circuit_where", {CallOp("core.presence_or", {CallOp("core.equal", {x_plus_y, Literal(1)}), CallOp("core.equal", {x_mul_y, Literal(1)})}), true_case, false_or_missing_case}))))); } } }
2,453
#ifndef AROLLA_EXPR_OPTIMIZATION_PEEPHOLE_OPTIMIZATIONS_CONST_WITH_SHAPE_H_ #define AROLLA_EXPR_OPTIMIZATION_PEEPHOLE_OPTIMIZATIONS_CONST_WITH_SHAPE_H_ #include "absl/status/statusor.h" #include "arolla/expr/optimization/peephole_optimizer.h" namespace arolla::expr { absl::StatusOr<PeepholeOptimizationPack> ConstWithShapeOptimizations(); } #endif #include "arolla/expr/optimization/peephole_optimizations/const_with_shape.h" #include <initializer_list> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/optimization/peephole_optimizer.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/optional_qtype.h" #include "arolla/util/status_macros_backport.h" namespace arolla::expr { namespace { struct OpRecord { const char* const from_op; const char* const to_op; }; constexpr std::initializer_list<OpRecord> kUnaryPointwiseOps = { {"bool.logical_not", "bool.logical_not"}, {"core.has._array", "core.has"}, {"core.has._optional", "core.has"}, {"core.presence_not._builtin", "core.presence_not"}, {"core.to_bool", "core.to_bool"}, {"core.to_float32", "core.to_float32"}, {"core.to_float64", "core.to_float64"}, {"core.to_int32", "core.to_int32"}, {"core.to_int64", "core.to_int64"}, {"core.to_optional._scalar", "core.to_optional"}, {"core.to_uint64", "core.to_uint64"}, {"math.abs", "math.abs"}, {"math.ceil", "math.ceil"}, {"math.exp", "math.exp"}, {"math.expm1", "math.expm1"}, {"math.floor", "math.floor"}, {"math.is_finite", "math.is_finite"}, {"math.is_inf", "math.is_inf"}, {"math.is_nan", "math.is_nan"}, {"math.log", "math.log"}, {"math.log10", "math.log10"}, {"math.log1p", "math.log1p"}, {"math.log2", "math.log2"}, {"math.logit", "math.logit"}, {"math.neg", "math.neg"}, {"math.pos", "math.pos"}, {"math.round", "math.round"}, {"math.sigmoid", "math.sigmoid"}, {"math.sign", "math.sign"}, }; constexpr std::initializer_list<OpRecord> kBinaryPointwiseOps = { {"bool.equal", "bool.equal"}, {"bool.less", "bool.less"}, {"bool.less_equal", "bool.less_equal"}, {"bool.logical_and", "bool.logical_and"}, {"bool.logical_or", "bool.logical_or"}, {"bool.not_equal", "bool.not_equal"}, {"core.equal", "core.equal"}, {"core.less", "core.less"}, {"core.less_equal", "core.less_equal"}, {"core.not_equal", "core.not_equal"}, {"core.presence_and", "core.presence_and"}, {"core.presence_or", "core.presence_or"}, {"math._pow", "math.pow"}, {"math.add", "math.add"}, {"math.divide", "math.divide"}, {"math.floordiv", "math.floordiv"}, {"math.fmod", "math.fmod"}, {"math.max", "math.max"}, {"math.min", "math.min"}, {"math.mod", "math.mod"}, {"math.multiply", "math.multiply"}, {"math.subtract", "math.subtract"}, }; absl::Status AddUnaryPointwiseOpOptimizations( PeepholeOptimizationPack& optimizations) { ExprNodePtr value = Placeholder("value"); ExprNodePtr shape = Placeholder("shape"); for (const auto& [from_op, to_op] : kUnaryPointwiseOps) { ASSIGN_OR_RETURN( ExprNodePtr from, CallOpReference(from_op, {CallOpReference("core.const_with_shape._array_shape", {shape, value})})); ASSIGN_OR_RETURN(ExprNodePtr to, CallOpReference("core.const_with_shape", {shape, CallOpReference(to_op, {value})})); ASSIGN_OR_RETURN(optimizations.emplace_back(), PeepholeOptimization::CreatePatternOptimization(from, to)); } return absl::OkStatus(); } bool IsBaseQType(const ExprNodePtr& node) { return IsScalarQType(DecayOptionalQType(node->qtype())); } absl::Status AddBinaryPointwiseOpOptimizations( PeepholeOptimizationPack& optimizations) { ExprNodePtr a = Placeholder("a"); ExprNodePtr b = Placeholder("b"); ExprNodePtr shape = Placeholder("shape"); for (const auto& [from_op, to_op] : kBinaryPointwiseOps) { ASSIGN_OR_RETURN(ExprNodePtr to, CallOpReference("core.const_with_shape", {shape, CallOpReference(to_op, {a, b})})); ASSIGN_OR_RETURN( ExprNodePtr expanded_a, CallOpReference("core.const_with_shape._array_shape", {shape, a})); ASSIGN_OR_RETURN( ExprNodePtr expanded_b, CallOpReference("core.const_with_shape._array_shape", {shape, b})); { ASSIGN_OR_RETURN(ExprNodePtr from, CallOpReference(from_op, {expanded_a, expanded_b})); ASSIGN_OR_RETURN( optimizations.emplace_back(), PeepholeOptimization::CreatePatternOptimization(from, to)); } { ASSIGN_OR_RETURN(ExprNodePtr from, CallOpReference(from_op, {expanded_a, b})); ASSIGN_OR_RETURN(optimizations.emplace_back(), PeepholeOptimization::CreatePatternOptimization( from, to, {{"b", IsBaseQType}})); } { ASSIGN_OR_RETURN(ExprNodePtr from, CallOpReference(from_op, {a, expanded_b})); ASSIGN_OR_RETURN(optimizations.emplace_back(), PeepholeOptimization::CreatePatternOptimization( from, to, {{"a", IsBaseQType}})); } } return absl::OkStatus(); } absl::Status AddArrayShapeOfOptimizations( PeepholeOptimizationPack& optimizations) { ExprNodePtr a = Placeholder("a"); ExprNodePtr shape = Placeholder("shape"); { ASSIGN_OR_RETURN( ExprNodePtr from, CallOpReference( "core._array_shape_of", {CallOpReference( "core.has._array", {CallOpReference("core.const_with_shape._array_shape", {shape, a})})})); ASSIGN_OR_RETURN( optimizations.emplace_back(), PeepholeOptimization::CreatePatternOptimization(from, shape)); } { ASSIGN_OR_RETURN( ExprNodePtr from, CallOpReference("core._array_shape_of", {CallOpReference("core.const_with_shape._array_shape", {shape, a})})); ASSIGN_OR_RETURN( optimizations.emplace_back(), PeepholeOptimization::CreatePatternOptimization(from, shape)); } return absl::OkStatus(); } } absl::StatusOr<PeepholeOptimizationPack> ConstWithShapeOptimizations() { PeepholeOptimizationPack optimizations; RETURN_IF_ERROR(AddArrayShapeOfOptimizations(optimizations)); RETURN_IF_ERROR(AddUnaryPointwiseOpOptimizations(optimizations)); RETURN_IF_ERROR(AddBinaryPointwiseOpOptimizations(optimizations)); return optimizations; } }
#include "arolla/expr/optimization/peephole_optimizations/const_with_shape.h" #include <memory> #include <optional> #include <utility> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/statusor.h" #include "arolla/dense_array/dense_array.h" #include "arolla/dense_array/qtype/types.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/optimization/peephole_optimizer.h" #include "arolla/expr/testing/testing.h" #include "arolla/memory/optional_value.h" #include "arolla/qtype/optional_qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/util/init_arolla.h" #include "arolla/util/unit.h" #include "arolla/util/status_macros_backport.h" namespace arolla::expr { namespace { using ::arolla::testing::EqualsExpr; using ::arolla::testing::WithQTypeAnnotation; class ConstWithShapeOptimizationsTest : public ::testing::Test { protected: void SetUp() override { ASSERT_OK(InitArolla()); ASSERT_OK_AND_ASSIGN( optimizer_, CreatePeepholeOptimizer({ConstWithShapeOptimizations})); GetDenseArrayQType<float>(); GetDenseArrayQType<Unit>(); } absl::StatusOr<ExprNodePtr> ApplyOptimizer( absl::StatusOr<ExprNodePtr> status_or_expr) const { ASSIGN_OR_RETURN(auto expr, ToLowest(status_or_expr)); return ToLowest(optimizer_->ApplyToNode(expr)); } absl::StatusOr<ExprNodePtr> ToLowest( const absl::StatusOr<ExprNodePtr>& status_or_expr) const { if (!status_or_expr.ok()) { return std::move(status_or_expr).status(); } return ::arolla::expr::ToLowest(*status_or_expr); } std::unique_ptr<PeepholeOptimizer> optimizer_; }; TEST_F(ConstWithShapeOptimizationsTest, UnaryPointwiseOpOptimizations) { ASSERT_OK_AND_ASSIGN( auto shape, WithQTypeAnnotation(Leaf("shape"), GetQType<DenseArrayShape>())); ASSERT_OK_AND_ASSIGN(auto x, WithQTypeAnnotation(Leaf("x"), GetQType<float>())); ASSERT_OK_AND_ASSIGN(auto y, WithQTypeAnnotation(Leaf("y"), GetQType<float>())); ASSERT_OK_AND_ASSIGN(auto x_plus_y, CallOp("math.add", {x, y})); { ASSERT_OK_AND_ASSIGN( auto actual_expr, ApplyOptimizer(CallOp( "math.exp", {CallOp("core.const_with_shape", {shape, x_plus_y})}))); ASSERT_OK_AND_ASSIGN( auto expected_expr, ToLowest(CallOp("core.const_with_shape", {shape, CallOp("math.exp", {x_plus_y})}))); EXPECT_THAT(actual_expr, EqualsExpr(expected_expr)); } { ASSERT_OK_AND_ASSIGN( auto actual_expr, ApplyOptimizer(CallOp( "core.has", {CallOp("core.const_with_shape", {shape, x_plus_y})}))); ASSERT_OK_AND_ASSIGN( auto expected_expr, ToLowest(CallOp("core.const_with_shape", {shape, Literal(Unit{})}))); EXPECT_THAT(actual_expr, EqualsExpr(expected_expr)); } } TEST_F(ConstWithShapeOptimizationsTest, BinaryPointwiseOpOptimizations) { ASSERT_OK_AND_ASSIGN( auto shape, WithQTypeAnnotation(Leaf("shape"), GetQType<DenseArrayShape>())); ASSERT_OK_AND_ASSIGN(auto x, WithQTypeAnnotation(Leaf("x"), GetQType<float>())); ASSERT_OK_AND_ASSIGN(auto y, WithQTypeAnnotation(Leaf("y"), GetQType<float>())); ASSERT_OK_AND_ASSIGN(auto x_plus_y, CallOp("math.add", {x, y})); ASSERT_OK_AND_ASSIGN(auto x_minus_y, CallOp("math.subtract", {x, y})); ASSERT_OK_AND_ASSIGN( auto actual_expr, ApplyOptimizer( CallOp("core.equal", {CallOp("core.const_with_shape", {shape, x_plus_y}), CallOp("core.const_with_shape", {shape, x_minus_y})}))); ASSERT_OK_AND_ASSIGN( auto expected_expr, ToLowest(CallOp("core.const_with_shape", {shape, CallOp("core.equal", {x_plus_y, x_minus_y})}))); EXPECT_THAT(actual_expr, EqualsExpr(expected_expr)); } TEST_F(ConstWithShapeOptimizationsTest, BinaryOpWithConstantOptimizations) { ASSERT_OK_AND_ASSIGN( auto shape, WithQTypeAnnotation(Leaf("shape"), GetQType<DenseArrayShape>())); ASSERT_OK_AND_ASSIGN( auto x, WithQTypeAnnotation(Leaf("x"), GetOptionalQType<float>())); ASSERT_OK_AND_ASSIGN( auto y, WithQTypeAnnotation(Leaf("y"), GetOptionalQType<float>())); ASSERT_OK_AND_ASSIGN(auto x_plus_y, CallOp("math.add", {x, y})); ASSERT_OK_AND_ASSIGN(auto x_minus_y, CallOp("math.subtract", {x, y})); ASSERT_OK_AND_ASSIGN( auto expected_expr, ToLowest( CallOp("core.const_with_shape", {shape, CallOp("core.presence_or", {x_plus_y, x_minus_y})}))); { SCOPED_TRACE("left expanded, right is not expanded"); ASSERT_OK_AND_ASSIGN( auto actual_expr, ApplyOptimizer(CallOp( "core.presence_or", {CallOp("core.const_with_shape", {shape, x_plus_y}), x_minus_y}))); EXPECT_THAT(actual_expr, EqualsExpr(expected_expr)); } { SCOPED_TRACE("left is not expanded, right is expanded"); ASSERT_OK_AND_ASSIGN( auto actual_expr, ApplyOptimizer(CallOp( "core.presence_or", {x_plus_y, CallOp("core.const_with_shape", {shape, x_minus_y})}))); EXPECT_THAT(actual_expr, EqualsExpr(expected_expr)); } } TEST_F(ConstWithShapeOptimizationsTest, ArrayShapeOptimizations) { ASSERT_OK_AND_ASSIGN( auto shape, WithQTypeAnnotation(Leaf("shape"), GetQType<DenseArrayShape>())); ASSERT_OK_AND_ASSIGN(auto x, WithQTypeAnnotation(Leaf("x"), GetQType<float>())); ASSERT_OK_AND_ASSIGN(auto y, WithQTypeAnnotation(Leaf("y"), GetQType<float>())); ASSERT_OK_AND_ASSIGN(auto x_plus_y, CallOp("math.add", {x, y})); ASSERT_OK_AND_ASSIGN( auto actual_expr, ApplyOptimizer(CallOp( "core.shape_of", {CallOp("core.has", {CallOp("core.const_with_shape", {shape, x_plus_y})})}))); EXPECT_THAT(actual_expr, EqualsExpr(shape)); } TEST_F(ConstWithShapeOptimizationsTest, ArrayShapeOptimizationsForPresence) { ASSERT_OK_AND_ASSIGN( auto shape, WithQTypeAnnotation(Leaf("shape"), GetQType<DenseArrayShape>())); ASSERT_OK_AND_ASSIGN( auto actual_expr, ApplyOptimizer( CallOp("core.shape_of", {CallOp("core.const_with_shape", {shape, Literal<OptionalUnit>(std::nullopt)})}))); EXPECT_THAT(actual_expr, EqualsExpr(shape)); } } }
2,454
#ifndef AROLLA_EXPR_OPTIMIZATION_PEEPHOLE_OPTIMIZATIONS_PRESENCE_H_ #define AROLLA_EXPR_OPTIMIZATION_PEEPHOLE_OPTIMIZATIONS_PRESENCE_H_ #include "absl/status/statusor.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/optimization/peephole_optimizer.h" namespace arolla::expr { namespace presence_impl { bool IsPresenceType(const ExprNodePtr& expr); bool IsAlwaysPresent(const ExprNodePtr& expr); } absl::StatusOr<PeepholeOptimizationPack> PresenceOptimizations(); absl::StatusOr<PeepholeOptimizationPack> CodegenPresenceOptimizations(); } #endif #include "arolla/expr/optimization/peephole_optimizations/presence.h" #include <string> #include <utility> #include <vector> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/optimization/peephole_optimizer.h" #include "arolla/memory/optional_value.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/optional_qtype.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/standard_type_properties/properties.h" #include "arolla/qtype/typed_value.h" #include "arolla/util/status_macros_backport.h" namespace arolla::expr { namespace presence_impl { bool IsPresenceType(const ExprNodePtr& expr) { QTypePtr qtype = expr->qtype(); return qtype != nullptr && qtype == GetPresenceQType(qtype).value_or(nullptr); } bool IsAlwaysPresentType(const ExprNodePtr& expr) { return IsScalarQType(expr->qtype()); } bool IsAlwaysPresentOptionalValue(const ExprNodePtr& expr) { const auto& optional_qvalue = expr->qvalue(); return optional_qvalue.has_value() && IsOptionalQType(optional_qvalue->GetType()) && UnsafeIsPresent(optional_qvalue->AsRef()); } bool IsAlwaysPresent(const ExprNodePtr& expr) { return IsAlwaysPresentType(expr) || IsAlwaysPresentOptionalValue(expr); } bool IsAlwaysAbsentOptionalValue(const ExprNodePtr& expr) { const auto& optional_qvalue = expr->qvalue(); return optional_qvalue.has_value() && IsOptionalQType(optional_qvalue->GetType()) && !UnsafeIsPresent(optional_qvalue->AsRef()); } } namespace { using ::arolla::expr::presence_impl::IsAlwaysAbsentOptionalValue; using ::arolla::expr::presence_impl::IsAlwaysPresent; using ::arolla::expr::presence_impl::IsAlwaysPresentOptionalValue; using ::arolla::expr::presence_impl::IsAlwaysPresentType; using ::arolla::expr::presence_impl::IsPresenceType; bool IsLiteral(const ExprNodePtr& node) { return node->is_literal(); } bool IsOptionalLikeNode(const ExprNodePtr& node) { QTypePtr qtype = node->qtype(); return qtype != nullptr && IsOptionalLikeQType(qtype); } bool IsBaseQType(const ExprNodePtr& node) { return IsScalarQType(DecayOptionalQType(node->qtype())); } absl::Status HasRemovalOptimizations(PeepholeOptimizationPack& optimizations) { { ASSIGN_OR_RETURN(ExprNodePtr from, CallOpReference("core.has._optional", {Placeholder("a")})); ExprNodePtr to = Literal(kPresent); ASSIGN_OR_RETURN(optimizations.emplace_back(), PeepholeOptimization::CreatePatternOptimization( from, to, {{"a", IsAlwaysPresentOptionalValue}})); } { ASSIGN_OR_RETURN(ExprNodePtr from, CallOpReference("core.presence_not._builtin", {CallOpReference("core.has._optional", {Placeholder("a")})})); ASSIGN_OR_RETURN(ExprNodePtr to, CallOpReference("core.presence_not", {Placeholder("a")})); ASSIGN_OR_RETURN(optimizations.emplace_back(), PeepholeOptimization::CreatePatternOptimization(from, to)); } { ASSIGN_OR_RETURN(ExprNodePtr from, CallOpReference("core.presence_not._builtin", {CallOpReference("core.has._array", {Placeholder("a")})})); ASSIGN_OR_RETURN(ExprNodePtr to, CallOpReference("core.presence_not", {Placeholder("a")})); ASSIGN_OR_RETURN(optimizations.emplace_back(), PeepholeOptimization::CreatePatternOptimization(from, to)); } { ASSIGN_OR_RETURN( ExprNodePtr from, CallOpReference( "core.has._optional", {CallOpReference("core.to_optional._scalar", {Placeholder("a")})})); ExprNodePtr to = Literal(kPresent); ASSIGN_OR_RETURN(optimizations.emplace_back(), PeepholeOptimization::CreatePatternOptimization( from, to, {{"a", IsAlwaysPresentType}})); } return absl::OkStatus(); } absl::Status PresenceAndRemovalOptimizations( PeepholeOptimizationPack& optimizations) { ExprNodePtr a = Placeholder("a"); ExprNodePtr b = Placeholder("b"); { ASSIGN_OR_RETURN(ExprNodePtr from, CallOpReference("core.presence_and", {a, b})); ASSIGN_OR_RETURN(optimizations.emplace_back(), PeepholeOptimization::CreatePatternOptimization( from, a, {{"b", IsAlwaysPresentType}})); } { ASSIGN_OR_RETURN( ExprNodePtr from, CallOpReference("core.presence_not._builtin", {CallOpReference("core.presence_and", {a, b})})); ASSIGN_OR_RETURN(ExprNodePtr to, CallOpReference("core.presence_not", {b})); ASSIGN_OR_RETURN(optimizations.emplace_back(), PeepholeOptimization::CreatePatternOptimization( from, to, {{"a", IsAlwaysPresent}})); } { ASSIGN_OR_RETURN(ExprNodePtr from, CallOpReference("core.presence_and", {a, b})); ASSIGN_OR_RETURN(ExprNodePtr to, CallOpReference("core.to_optional", {a})); ASSIGN_OR_RETURN(optimizations.emplace_back(), PeepholeOptimization::CreatePatternOptimization( from, to, {{"b", IsAlwaysPresentOptionalValue}})); } { ASSIGN_OR_RETURN(ExprNodePtr from, CallOpReference("core.presence_and", {a, b})); ASSIGN_OR_RETURN(optimizations.emplace_back(), PeepholeOptimization::CreatePatternOptimization( from, b, {{"a", [](const ExprNodePtr& expr) { return IsAlwaysPresent(expr) && IsPresenceType(expr); }}})); } return absl::OkStatus(); } absl::Status PresenceOrRemovalOptimizations( PeepholeOptimizationPack& optimizations) { ExprNodePtr a = Placeholder("a"); ExprNodePtr b = Placeholder("b"); ASSIGN_OR_RETURN(ExprNodePtr from, CallOpReference("core.presence_or", {a, b})); ASSIGN_OR_RETURN(optimizations.emplace_back(), PeepholeOptimization::CreatePatternOptimization( from, a, {{"a", IsAlwaysPresentType}})); return absl::OkStatus(); } absl::Status HasPropagationOptimizations( PeepholeOptimizationPack& optimizations) { ExprNodePtr a = Placeholder("a"); ExprNodePtr b = Placeholder("b"); ExprNodePtr c = Placeholder("c"); auto is_literal_or_presence = [](const ExprNodePtr& expr) { return IsLiteral(expr) || IsPresenceType(expr); }; for (const char* op_has : {"core.has._optional", "core.has._array"}) { for (const auto& op : {"core.presence_or", "core.presence_and"}) { ASSIGN_OR_RETURN(ExprNodePtr from, CallOpReference(op_has, {CallOpReference(op, {a, b})})); ASSIGN_OR_RETURN(ExprNodePtr to, CallOpReference(op, {CallOpReference("core.has", {a}), CallOpReference("core.has", {b})})); ASSIGN_OR_RETURN(optimizations.emplace_back(), PeepholeOptimization::CreatePatternOptimization( from, to, {{"a", is_literal_or_presence}})); ASSIGN_OR_RETURN(optimizations.emplace_back(), PeepholeOptimization::CreatePatternOptimization( from, to, {{"b", is_literal_or_presence}})); } { ASSIGN_OR_RETURN( ExprNodePtr from, CallOpReference( op_has, {CallOpReference("core._presence_and_or", {a, c, b})})); ASSIGN_OR_RETURN(ExprNodePtr to, CallOpReference("core._presence_and_or", {CallOpReference("core.has", {a}), c, CallOpReference("core.has", {b})})); ASSIGN_OR_RETURN(optimizations.emplace_back(), PeepholeOptimization::CreatePatternOptimization( from, to, {{"a", is_literal_or_presence}})); ASSIGN_OR_RETURN(optimizations.emplace_back(), PeepholeOptimization::CreatePatternOptimization( from, to, {{"b", is_literal_or_presence}})); } } return absl::OkStatus(); } absl::Status ToOptionalPropagationOptimizations( PeepholeOptimizationPack& optimizations) { ExprNodePtr a = Placeholder("a"); ExprNodePtr b = Placeholder("b"); ExprNodePtr c = Placeholder("c"); { ASSIGN_OR_RETURN( ExprNodePtr from, CallOpReference("core.to_optional._scalar", {CallOpReference("core.presence_or", {a, b})})); ASSIGN_OR_RETURN( ExprNodePtr to, CallOpReference("core.presence_or", {a, CallOpReference("core.to_optional", {b})})); ASSIGN_OR_RETURN( optimizations.emplace_back(), PeepholeOptimization::CreatePatternOptimization( from, to, {{"a", IsOptionalLikeNode}, {"b", IsLiteral}})); } { ASSIGN_OR_RETURN( ExprNodePtr from, CallOpReference("core.to_optional._scalar", {CallOpReference("core._presence_and_or", {a, c, b})})); ASSIGN_OR_RETURN( ExprNodePtr to, CallOpReference("core._presence_and_or", {CallOpReference("core.to_optional", {a}), c, CallOpReference("core.to_optional", {b})})); ASSIGN_OR_RETURN(optimizations.emplace_back(), PeepholeOptimization::CreatePatternOptimization( from, to, {{"a", IsLiteral}})); ASSIGN_OR_RETURN(optimizations.emplace_back(), PeepholeOptimization::CreatePatternOptimization( from, to, {{"b", IsLiteral}})); } return absl::OkStatus(); } absl::Status PresenceAndOptionalOptimizations( PeepholeOptimizationPack& optimizations) { ExprNodePtr a = Placeholder("a"); ExprNodePtr c = Placeholder("c"); { ASSIGN_OR_RETURN( ExprNodePtr from, CallOpReference("core.presence_and", {CallOpReference("core.to_optional._scalar", {a}), c})); ASSIGN_OR_RETURN(ExprNodePtr to, CallOpReference("core.presence_and", {a, c})); ASSIGN_OR_RETURN(optimizations.emplace_back(), PeepholeOptimization::CreatePatternOptimization(from, to)); } return absl::OkStatus(); } absl::Status PresenceAndOrCombinationOptimizations( PeepholeOptimizationPack& optimizations) { ExprNodePtr a = Placeholder("a"); ExprNodePtr b = Placeholder("b"); ExprNodePtr c = Placeholder("c"); ExprNodePtr d = Placeholder("d"); { ASSIGN_OR_RETURN( ExprNodePtr from1, CallOpReference("core.presence_or", {CallOpReference("core.presence_and", {c, a}), CallOpReference("core.presence_and", {c, b})})); ASSIGN_OR_RETURN( ExprNodePtr from2, CallOpReference("core._presence_and_or", {c, a, CallOpReference("core.presence_and", {c, b})})); ASSIGN_OR_RETURN( ExprNodePtr to, CallOpReference("core.presence_and", {c, CallOpReference("core.presence_or", {a, b})})); for (const auto& from : {from1, from2}) { ASSIGN_OR_RETURN( optimizations.emplace_back(), PeepholeOptimization::CreatePatternOptimization(from, to)); } } { ASSIGN_OR_RETURN( ExprNodePtr from, CallOpReference( "core.presence_or", {CallOpReference("core.presence_or", { d, CallOpReference("core.presence_and", {c, a}), }), CallOpReference("core.presence_and", {c, b})})); ASSIGN_OR_RETURN( ExprNodePtr to, CallOpReference( "core.presence_or", {d, CallOpReference( "core.presence_and", {c, CallOpReference("core.presence_or", {a, b})})})); ASSIGN_OR_RETURN(optimizations.emplace_back(), PeepholeOptimization::CreatePatternOptimization(from, to)); } return absl::OkStatus(); } absl::Status WhereOptimizations(PeepholeOptimizationPack& optimizations) { ExprNodePtr a = Placeholder("a"); ExprNodePtr b = Placeholder("b"); ExprNodePtr c = Placeholder("c"); { ASSIGN_OR_RETURN( ExprNodePtr from, CallOpReference( "core.presence_or", {CallOpReference("core.presence_and", {a, c}), CallOpReference( "core.presence_and", {b, CallOpReference("core.presence_not._builtin", {c})})})); ASSIGN_OR_RETURN(ExprNodePtr to, CallOpReference("core.to_optional", { CallOpReference("core.where", {c, a, b})})); ASSIGN_OR_RETURN(optimizations.emplace_back(), PeepholeOptimization::CreatePatternOptimization( from, to, {{"c", IsOptionalLikeNode}})); } { ASSIGN_OR_RETURN( ExprNodePtr from, CallOpReference( "core._presence_and_or", {a, c, CallOpReference( "core.presence_and", {b, CallOpReference("core.presence_not._builtin", {c})})})); ASSIGN_OR_RETURN(ExprNodePtr to, CallOpReference("core.where", {c, a, b})); ASSIGN_OR_RETURN(optimizations.emplace_back(), PeepholeOptimization::CreatePatternOptimization(from, to)); } { ASSIGN_OR_RETURN( ExprNodePtr from, CallOpReference("core.presence_or", {CallOpReference("core.presence_and", {a, c}), b})); ASSIGN_OR_RETURN(ExprNodePtr to, CallOpReference("core._presence_and_or", {a, c, b})); ASSIGN_OR_RETURN( optimizations.emplace_back(), PeepholeOptimization::CreatePatternOptimization( from, to, {{"a", IsBaseQType}, {"b", IsBaseQType}, {"c", IsBaseQType}})); } { ASSIGN_OR_RETURN(ExprNodePtr from, CallOpReference("core.where", {c, a, b})); ASSIGN_OR_RETURN(optimizations.emplace_back(), PeepholeOptimization::CreatePatternOptimization( from, a, {{"c", IsAlwaysPresent}, {"a", IsAlwaysPresentType}, {"b", IsAlwaysPresentType}})); } return absl::OkStatus(); } absl::Status WhereToPresenceAndOptimizations( PeepholeOptimizationPack& optimizations) { ExprNodePtr a = Placeholder("a"); ExprNodePtr b = Placeholder("b"); ExprNodePtr c = Placeholder("c"); { ASSIGN_OR_RETURN(ExprNodePtr from, CallOpReference("core.where", {c, a, b})); ASSIGN_OR_RETURN(ExprNodePtr to, CallOpReference("core.presence_and", {a, c})); ASSIGN_OR_RETURN(optimizations.emplace_back(), PeepholeOptimization::CreatePatternOptimization( from, to, {{"b", IsAlwaysAbsentOptionalValue}})); } return absl::OkStatus(); } absl::Status PresenceAndOrOptimizations( PeepholeOptimizationPack& optimizations) { ExprNodePtr a = Placeholder("a"); ExprNodePtr b = Placeholder("b"); ExprNodePtr c = Placeholder("c"); { ASSIGN_OR_RETURN(ExprNodePtr from, CallOpReference("core._presence_and_or", {a, b, c})); ASSIGN_OR_RETURN(ExprNodePtr to, CallOpReference("core.presence_or", {a, c})); ASSIGN_OR_RETURN(optimizations.emplace_back(), PeepholeOptimization::CreatePatternOptimization( from, to, {{"b", IsAlwaysPresent}})); } { ASSIGN_OR_RETURN(ExprNodePtr from, CallOpReference("core._presence_and_or", {a, b, c})); ASSIGN_OR_RETURN(ExprNodePtr to, CallOpReference("core.presence_or", {b, c})); ASSIGN_OR_RETURN(optimizations.emplace_back(), PeepholeOptimization::CreatePatternOptimization( from, to, {{"a", [](const ExprNodePtr& expr) { return IsAlwaysPresent(expr) && IsPresenceType(expr); }}})); } return absl::OkStatus(); } absl::Status InsideWherePropagationOptimizations( PeepholeOptimizationPack& optimizations) { ExprNodePtr a = Placeholder("a"); ExprNodePtr b = Placeholder("b"); ExprNodePtr c = Placeholder("c"); for (const auto& [op_from, op_to] : std::vector<std::pair<std::string, std::string>>{ {"core.to_optional._scalar", "core.to_optional"}, {"core.has._optional", "core.has"}, {"core.has._array", "core.has"}, }) { ASSIGN_OR_RETURN( ExprNodePtr from, CallOpReference(op_from, {CallOpReference("core.where", {c, a, b})})); ASSIGN_OR_RETURN( ExprNodePtr to, CallOpReference("core.where", {c, CallOpReference(op_to, {a}), CallOpReference(op_to, {b})})); ASSIGN_OR_RETURN(optimizations.emplace_back(), PeepholeOptimization::CreatePatternOptimization( from, to, {{"a", IsLiteral}})); ASSIGN_OR_RETURN(optimizations.emplace_back(), PeepholeOptimization::CreatePatternOptimization( from, to, {{"b", IsLiteral}})); } return absl::OkStatus(); } } absl::StatusOr<PeepholeOptimizationPack> PresenceOptimizations() { PeepholeOptimizationPack optimizations; RETURN_IF_ERROR(HasRemovalOptimizations(optimizations)); RETURN_IF_ERROR(PresenceAndRemovalOptimizations(optimizations)); RETURN_IF_ERROR(PresenceOrRemovalOptimizations(optimizations)); RETURN_IF_ERROR(HasPropagationOptimizations(optimizations)); RETURN_IF_ERROR(ToOptionalPropagationOptimizations(optimizations)); RETURN_IF_ERROR(PresenceAndOptionalOptimizations(optimizations)); RETURN_IF_ERROR(PresenceAndOrCombinationOptimizations(optimizations)); RETURN_IF_ERROR(WhereOptimizations(optimizations)); RETURN_IF_ERROR(InsideWherePropagationOptimizations(optimizations)); RETURN_IF_ERROR(PresenceAndOrOptimizations(optimizations)); return optimizations; } absl::StatusOr<PeepholeOptimizationPack> CodegenPresenceOptimizations() { PeepholeOptimizationPack optimizations; RETURN_IF_ERROR(WhereToPresenceAndOptimizations(optimizations)); return optimizations; } }
#include "arolla/expr/optimization/peephole_optimizations/presence.h" #include <cstdint> #include <memory> #include <utility> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/statusor.h" #include "arolla/dense_array/qtype/types.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/optimization/peephole_optimizer.h" #include "arolla/expr/testing/testing.h" #include "arolla/memory/optional_value.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/optional_qtype.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/util/init_arolla.h" #include "arolla/util/unit.h" #include "arolla/util/status_macros_backport.h" namespace arolla::expr { namespace { using ::arolla::expr::presence_impl::IsAlwaysPresent; using ::arolla::expr::presence_impl::IsPresenceType; using ::arolla::testing::EqualsExpr; using ::arolla::testing::WithQTypeAnnotation; class PresenceOptimizationsTest : public ::testing::Test { protected: void SetUp() override { ASSERT_OK(InitArolla()); ASSERT_OK_AND_ASSIGN(optimizer_, CreatePeepholeOptimizer({PresenceOptimizations})); ASSERT_OK_AND_ASSIGN( codegen_optimizer_, CreatePeepholeOptimizer( {PresenceOptimizations, CodegenPresenceOptimizations})); } absl::StatusOr<ExprNodePtr> ApplyOptimizer( absl::StatusOr<ExprNodePtr> status_or_expr) const { ASSIGN_OR_RETURN(auto expr, ToLowest(status_or_expr)); return ToLowest(optimizer_->ApplyToNode(expr)); } absl::StatusOr<ExprNodePtr> ApplyCodegenOptimizer( absl::StatusOr<ExprNodePtr> status_or_expr) const { ASSIGN_OR_RETURN(auto expr, ToLowest(status_or_expr)); return ToLowest(codegen_optimizer_->ApplyToNode(expr)); } absl::StatusOr<ExprNodePtr> ToLowest( const absl::StatusOr<ExprNodePtr>& status_or_expr) const { if (!status_or_expr.ok()) { return std::move(status_or_expr).status(); } return ::arolla::expr::ToLowest(*status_or_expr); } std::unique_ptr<PeepholeOptimizer> optimizer_; std::unique_ptr<PeepholeOptimizer> codegen_optimizer_; }; TEST_F(PresenceOptimizationsTest, IsPresenceType) { for (QTypePtr tpe : {GetQType<int>(), GetOptionalQType<int>(), GetDenseArrayQType<int>()}) { ASSERT_OK_AND_ASSIGN(auto x, WithQTypeAnnotation(Leaf("x"), tpe)); EXPECT_FALSE(IsPresenceType(x)) << tpe->name(); } for (QTypePtr tpe : {GetQType<Unit>(), GetOptionalQType<Unit>(), GetDenseArrayQType<Unit>()}) { ASSERT_OK_AND_ASSIGN(auto x, WithQTypeAnnotation(Leaf("x"), tpe)); EXPECT_TRUE(IsPresenceType(x)) << tpe->name(); } } TEST_F(PresenceOptimizationsTest, IsAlwaysPresent) { for (QTypePtr tpe : {GetQType<int>(), GetQType<Unit>()}) { ASSERT_OK_AND_ASSIGN(auto x, WithQTypeAnnotation(Leaf("x"), tpe)); EXPECT_TRUE(IsAlwaysPresent(x)) << tpe->name(); } for (QTypePtr tpe : {GetOptionalQType<int>(), GetDenseArrayQType<Unit>()}) { ASSERT_OK_AND_ASSIGN(auto x, WithQTypeAnnotation(Leaf("x"), tpe)); EXPECT_FALSE(IsAlwaysPresent(x)) << tpe->name(); } for (auto x : {Literal(1.), Literal(MakeOptionalValue(1.)), Literal(kPresent)}) { EXPECT_TRUE(IsAlwaysPresent(x)) << x->qvalue()->Repr(); } for (auto x : {Literal(OptionalValue<int>()), Literal(kMissing)}) { EXPECT_FALSE(IsAlwaysPresent(x)) << x->qvalue()->Repr(); } } TEST_F(PresenceOptimizationsTest, HasRemoval) { ASSERT_OK_AND_ASSIGN(auto x, WithQTypeAnnotation(Leaf("x"), GetQType<int>())); ASSERT_OK_AND_ASSIGN(auto y, WithQTypeAnnotation(Leaf("y"), GetQType<Unit>())); ASSERT_OK_AND_ASSIGN(auto x_opt, WithQTypeAnnotation(Leaf("x"), GetOptionalQType<int>())); ASSERT_OK_AND_ASSIGN( auto y_opt, WithQTypeAnnotation(Leaf("y"), GetOptionalQType<Unit>())); auto unit = Literal(Unit{}); auto present = Literal(kPresent); auto present_float32 = Literal(MakeOptionalValue(1.0f)); for (const auto& arg : {x, y}) { ASSERT_OK_AND_ASSIGN(auto actual_expr, ApplyOptimizer(CallOp("core.has", {arg}))); EXPECT_THAT(actual_expr, EqualsExpr(unit)); } for (const auto& arg : {present, present_float32}) { ASSERT_OK_AND_ASSIGN(auto actual_expr, ApplyOptimizer(CallOp("core.has", {arg}))); EXPECT_THAT(actual_expr, EqualsExpr(present)); } { ASSERT_OK_AND_ASSIGN(auto actual_expr, ApplyOptimizer(CallOp("core.has", {x_opt}))); ASSERT_OK_AND_ASSIGN(auto expected_expr, ToLowest(CallOp("core.has", {x_opt}))); EXPECT_THAT(actual_expr, EqualsExpr(expected_expr)); } { ASSERT_OK_AND_ASSIGN(auto actual_expr, ApplyOptimizer(CallOp("core.has", {y_opt}))); EXPECT_THAT(actual_expr, EqualsExpr(y_opt)); } { ASSERT_OK_AND_ASSIGN( auto actual_expr, ApplyOptimizer( CallOp("core.has", {CallOp("core.presence_not", {x_opt})}))); ASSERT_OK_AND_ASSIGN(auto expected_expr, ToLowest(CallOp("core.presence_not", {x_opt}))); EXPECT_THAT(actual_expr, EqualsExpr(expected_expr)); } { ASSERT_OK_AND_ASSIGN(auto actual_expr, ApplyOptimizer(CallOp("core.presence_not", {CallOp("core.has", {x_opt})}))); ASSERT_OK_AND_ASSIGN(auto expected_expr, ToLowest(CallOp("core.presence_not", {x_opt}))); EXPECT_THAT(actual_expr, EqualsExpr(expected_expr)); } { ASSERT_OK_AND_ASSIGN( auto actual_expr, ApplyOptimizer(CallOp("core.has", {CallOp("core.to_optional", {x})}))); EXPECT_THAT(actual_expr, EqualsExpr(present)); } } TEST_F(PresenceOptimizationsTest, AndRemoval) { ASSERT_OK_AND_ASSIGN(auto x, WithQTypeAnnotation(Leaf("x"), GetQType<int>())); ASSERT_OK_AND_ASSIGN(auto y, WithQTypeAnnotation(Leaf("y"), GetQType<Unit>())); ASSERT_OK_AND_ASSIGN(auto x_opt, WithQTypeAnnotation(Leaf("x"), GetOptionalQType<int>())); ASSERT_OK_AND_ASSIGN( auto y_opt, WithQTypeAnnotation(Leaf("y"), GetOptionalQType<Unit>())); auto present = Literal(kPresent); auto present_int32 = Literal(MakeOptionalValue(1)); { ASSERT_OK_AND_ASSIGN( auto actual_expr, ApplyOptimizer(CallOp("core.presence_and", {x_opt, present}))); ASSERT_OK_AND_ASSIGN(auto expected_expr, ToLowest(CallOp("core.to_optional", {x_opt}))); EXPECT_THAT(actual_expr, EqualsExpr(expected_expr)); } { ASSERT_OK_AND_ASSIGN( auto actual_expr, ApplyOptimizer(CallOp("core.presence_and", {present, y_opt}))); EXPECT_THAT(actual_expr, EqualsExpr(y_opt)); } { ASSERT_OK_AND_ASSIGN( auto actual_expr, ApplyOptimizer(CallOp("core.presence_and", {present_int32, y_opt}))); ASSERT_OK_AND_ASSIGN( auto expected_expr, ToLowest(CallOp("core.presence_and", {present_int32, y_opt}))); EXPECT_THAT(actual_expr, EqualsExpr(expected_expr)); } { ASSERT_OK_AND_ASSIGN( auto actual_expr, ApplyOptimizer(CallOp("core.presence_and", {x_opt, y_opt}))); ASSERT_OK_AND_ASSIGN(auto expected_expr, ToLowest(CallOp("core.presence_and", {x_opt, y_opt}))); EXPECT_THAT(actual_expr, EqualsExpr(expected_expr)); } } TEST_F(PresenceOptimizationsTest, OrRemoval) { ASSERT_OK_AND_ASSIGN(ExprNodePtr x, WithQTypeAnnotation(Leaf("x"), GetQType<int>())); ASSERT_OK_AND_ASSIGN(ExprNodePtr y, WithQTypeAnnotation(Leaf("y"), GetQType<Unit>())); ASSERT_OK_AND_ASSIGN(ExprNodePtr x_opt, WithQTypeAnnotation(Leaf("x"), GetOptionalQType<int>())); ASSERT_OK_AND_ASSIGN( ExprNodePtr y_opt, WithQTypeAnnotation(Leaf("y"), GetOptionalQType<Unit>())); ExprNodePtr present = Literal(kUnit); ExprNodePtr present_int32 = Literal(1); for (const auto& arg : {x, present_int32}) { ASSERT_OK_AND_ASSIGN( auto actual_expr, ApplyOptimizer(CallOp("core.presence_or", {arg, x_opt}))); EXPECT_THAT(actual_expr, EqualsExpr(arg)); } for (const auto& arg : {y, present}) { ASSERT_OK_AND_ASSIGN( auto actual_expr, ApplyOptimizer(CallOp("core.presence_or", {arg, y_opt}))); EXPECT_THAT(actual_expr, EqualsExpr(arg)); } { ASSERT_OK_AND_ASSIGN( auto actual_expr, ApplyOptimizer(CallOp("core.presence_or", {y_opt, y_opt}))); ASSERT_OK_AND_ASSIGN(auto expected_expr, ToLowest(CallOp("core.presence_or", {y_opt, y_opt}))); EXPECT_THAT(actual_expr, EqualsExpr(expected_expr)); } { ASSERT_OK_AND_ASSIGN( auto actual_expr, ApplyOptimizer(CallOp("core.presence_or", {y_opt, present}))); ASSERT_OK_AND_ASSIGN( auto expected_expr, ToLowest(CallOp("core.presence_or", {y_opt, present}))); EXPECT_THAT(actual_expr, EqualsExpr(expected_expr)); } } TEST_F(PresenceOptimizationsTest, HasPropagation) { ASSERT_OK_AND_ASSIGN(auto x, WithQTypeAnnotation(Leaf("x"), GetQType<int>())); ASSERT_OK_AND_ASSIGN(auto y, WithQTypeAnnotation(Leaf("y"), GetQType<Unit>())); ASSERT_OK_AND_ASSIGN(auto x_opt, WithQTypeAnnotation(Leaf("x"), GetOptionalQType<int>())); ASSERT_OK_AND_ASSIGN( auto y_opt, WithQTypeAnnotation(Leaf("y"), GetOptionalQType<Unit>())); ASSERT_OK_AND_ASSIGN( auto z_opt, WithQTypeAnnotation(Leaf("z"), GetOptionalQType<Unit>())); auto present = Literal(kPresent); auto present_int = Literal(MakeOptionalValue(1)); { ASSERT_OK_AND_ASSIGN( auto actual_expr, ApplyOptimizer( CallOp("core.has", {CallOp("core.presence_or", {x_opt, x_opt})}))); ASSERT_OK_AND_ASSIGN( auto expected_expr, ToLowest( CallOp("core.has", {CallOp("core.presence_or", {x_opt, x_opt})}))); EXPECT_THAT(actual_expr, EqualsExpr(expected_expr)); } { ASSERT_OK_AND_ASSIGN( auto actual_expr, ApplyOptimizer( CallOp("core.has", {CallOp("core.presence_and", {x_opt, y_opt})}))); ASSERT_OK_AND_ASSIGN( auto expected_expr, ToLowest(CallOp("core.presence_and", {CallOp("core.has", {x_opt}), CallOp("core.has", {y_opt})}))); EXPECT_THAT(actual_expr, EqualsExpr(expected_expr)); } { ASSERT_OK_AND_ASSIGN( auto actual_expr, ApplyOptimizer(CallOp( "core.has", {CallOp("core.presence_or", {x_opt, present_int})}))); ASSERT_OK_AND_ASSIGN(auto expected_expr, ToLowest(CallOp("core.presence_or", {CallOp("core.has", {x_opt}), CallOp("core.has", {present_int})}))); EXPECT_THAT(actual_expr, EqualsExpr(expected_expr)); } { ASSERT_OK_AND_ASSIGN( auto actual_expr, ApplyOptimizer( CallOp("core.has", {CallOp("core.presence_or", {y_opt, z_opt})}))); ASSERT_OK_AND_ASSIGN(auto expected_expr, ToLowest(CallOp("core.presence_or", {y_opt, z_opt}))); EXPECT_THAT(actual_expr, EqualsExpr(expected_expr)); } { ASSERT_OK_AND_ASSIGN( auto actual_expr, ApplyOptimizer(CallOp( "core.has", {CallOp("core._presence_and_or", {present_int, y_opt, x_opt})}))); ASSERT_OK_AND_ASSIGN( auto expected_expr, ToLowest(CallOp("core._presence_and_or", {CallOp("core.has", {present_int}), y_opt, CallOp("core.has", {x_opt})}))); EXPECT_THAT(actual_expr, EqualsExpr(expected_expr)); } { ASSERT_OK_AND_ASSIGN( auto actual_expr, ApplyOptimizer(CallOp( "core.has", {CallOp("core._presence_and_or", {x_opt, y_opt, present_int})}))); ASSERT_OK_AND_ASSIGN(auto expected_expr, ToLowest(CallOp("core._presence_and_or", {CallOp("core.has", {x_opt}), y_opt, CallOp("core.has", {present_int})}))); EXPECT_THAT(actual_expr, EqualsExpr(expected_expr)); } } TEST_F(PresenceOptimizationsTest, ToOptionalPropagation) { ASSERT_OK_AND_ASSIGN( auto x, WithQTypeAnnotation(Leaf("x"), GetOptionalQType<int32_t>())); ASSERT_OK_AND_ASSIGN( auto y, WithQTypeAnnotation(Leaf("y"), GetOptionalQType<int32_t>())); ASSERT_OK_AND_ASSIGN(auto z, WithQTypeAnnotation(Leaf("z"), GetQType<int32_t>())); ASSERT_OK_AND_ASSIGN( auto w, WithQTypeAnnotation(Leaf("w"), GetOptionalQType<Unit>())); auto present = Literal(kPresent); auto present_scalar_int = Literal(1); auto present_int = Literal(MakeOptionalValue(1)); { ASSERT_OK_AND_ASSIGN( auto actual_expr, ApplyOptimizer( CallOp("core.to_optional", {CallOp("core.presence_or", {x, y})}))); ASSERT_OK_AND_ASSIGN( auto expected_expr, ToLowest( CallOp("core.to_optional", {CallOp("core.presence_or", {x, y})}))); EXPECT_THAT(actual_expr, EqualsExpr(expected_expr)); } { ASSERT_OK_AND_ASSIGN( auto actual_expr, ApplyOptimizer( CallOp("core.to_optional", {CallOp("core.presence_or", {z, y})}))); ASSERT_OK_AND_ASSIGN( auto expected_expr, ToLowest( CallOp("core.to_optional", {CallOp("core.presence_or", {z, y})}))); EXPECT_THAT(actual_expr, EqualsExpr(expected_expr)); } { ASSERT_OK_AND_ASSIGN( auto actual_expr, ApplyOptimizer(CallOp("core.to_optional", {CallOp("core.presence_or", {y, present_int})}))); ASSERT_OK_AND_ASSIGN( auto expected_expr, ToLowest(CallOp("core.to_optional", {CallOp("core.presence_or", {y, present_int})}))); EXPECT_THAT(actual_expr, EqualsExpr(expected_expr)); } { ASSERT_OK_AND_ASSIGN( auto actual_expr, ApplyOptimizer( CallOp("core.to_optional", {CallOp("core.presence_or", {x, present_scalar_int})}))); ASSERT_OK_AND_ASSIGN(auto expected_expr, ToLowest(CallOp("core.presence_or", {x, CallOp("core.to_optional", {present_scalar_int})}))); EXPECT_THAT(actual_expr, EqualsExpr(expected_expr)); } { ASSERT_OK_AND_ASSIGN( auto actual_expr, ApplyOptimizer(CallOp( "core.to_optional", {CallOp("core._presence_and_or", {present_scalar_int, w, z})}))); ASSERT_OK_AND_ASSIGN( auto expected_expr, ToLowest(CallOp("core._presence_and_or", {CallOp("core.to_optional", {present_scalar_int}), w, CallOp("core.to_optional", {z})}))); EXPECT_THAT(actual_expr, EqualsExpr(expected_expr)); } { ASSERT_OK_AND_ASSIGN( auto actual_expr, ApplyOptimizer(CallOp( "core.to_optional", {CallOp("core._presence_and_or", {z, w, present_scalar_int})}))); ASSERT_OK_AND_ASSIGN( auto expected_expr, ToLowest(CallOp("core._presence_and_or", {CallOp("core.to_optional", {z}), w, CallOp("core.to_optional", {present_scalar_int})}))); EXPECT_THAT(actual_expr, EqualsExpr(expected_expr)); } } TEST_F(PresenceOptimizationsTest, InsideWherePropagationOptimizations) { ASSERT_OK_AND_ASSIGN( auto x, WithQTypeAnnotation(Leaf("x"), GetOptionalQType<int32_t>())); ASSERT_OK_AND_ASSIGN( auto y, WithQTypeAnnotation(Leaf("y"), GetOptionalQType<int32_t>())); ASSERT_OK_AND_ASSIGN( auto z, WithQTypeAnnotation(Leaf("z"), GetOptionalQType<Unit>())); auto present = Literal(kPresent); auto present_int = Literal(MakeOptionalValue(1)); { ASSERT_OK_AND_ASSIGN( auto actual_expr, ApplyOptimizer(CallOp("core.has", {CallOp("core.where", {z, x, y})}))); ASSERT_OK_AND_ASSIGN( auto expected_expr, ToLowest(CallOp("core.has", {CallOp("core.where", {z, x, y})}))); EXPECT_THAT(actual_expr, EqualsExpr(expected_expr)); } { ASSERT_OK_AND_ASSIGN( auto actual_expr, ApplyOptimizer(CallOp("core.to_optional", {CallOp("core.where", {z, present_int, x})}))); ASSERT_OK_AND_ASSIGN( auto expected_expr, ToLowest( CallOp("core.where", {z, CallOp("core.to_optional", {present_int}), CallOp("core.to_optional", {x})}))); EXPECT_THAT(actual_expr, EqualsExpr(expected_expr)); } { ASSERT_OK_AND_ASSIGN( auto actual_expr, ApplyOptimizer( CallOp("core.has", {CallOp("core.where", {z, x, present_int})}))); ASSERT_OK_AND_ASSIGN( auto expected_expr, ToLowest(CallOp("core.where", {z, CallOp("core.has", {x}), CallOp("core.has", {present_int})}))); EXPECT_THAT(actual_expr, EqualsExpr(expected_expr)); } } TEST_F(PresenceOptimizationsTest, WhereOptimization) { ASSERT_OK_AND_ASSIGN( auto cond, WithQTypeAnnotation(Leaf("cond"), GetOptionalQType<Unit>())); ASSERT_OK_AND_ASSIGN( auto x, WithQTypeAnnotation(Leaf("x"), GetOptionalQType<float>())); ASSERT_OK_AND_ASSIGN( auto y, WithQTypeAnnotation(Leaf("y"), GetOptionalQType<float>())); ASSERT_OK_AND_ASSIGN(auto x_full, WithQTypeAnnotation(Leaf("x"), GetQType<float>())); ASSERT_OK_AND_ASSIGN(auto y_full, WithQTypeAnnotation(Leaf("y"), GetQType<float>())); { ASSERT_OK_AND_ASSIGN( auto actual_expr, ApplyOptimizer( CallOp("core.where", {Literal(kPresent), x_full, y_full}))); EXPECT_THAT(actual_expr, EqualsExpr(x_full)); } { ASSERT_OK_AND_ASSIGN( auto actual_expr, ApplyOptimizer(CallOp("core.where", {Literal(kPresent), x_full, y}))); ASSERT_OK_AND_ASSIGN( auto expected_expr, ToLowest(CallOp("core.where", {Literal(kPresent), x_full, y}))); EXPECT_THAT(actual_expr, EqualsExpr(expected_expr)); } { ASSERT_OK_AND_ASSIGN( auto actual_expr, ApplyOptimizer( CallOp("core.presence_or", {CallOp("core.presence_and", {x, cond}), CallOp("core.presence_and", {y, CallOp("core.presence_not", {cond})})}))); ASSERT_OK_AND_ASSIGN(auto expected_expr, ToLowest(CallOp("core.where", {cond, x, y}))); EXPECT_THAT(actual_expr, EqualsExpr(expected_expr)); } { ASSERT_OK_AND_ASSIGN( auto scalar_x, WithQTypeAnnotation(Leaf("x"), GetQType<float>())); ASSERT_OK_AND_ASSIGN( auto scalar_y, WithQTypeAnnotation(Leaf("y"), GetQType<float>())); ASSERT_OK_AND_ASSIGN( auto actual_expr, ApplyOptimizer( CallOp("core.presence_or", {CallOp("core.presence_and", {scalar_x, cond}), CallOp("core.presence_and", {scalar_y, CallOp("core.presence_not", {cond})})}))); ASSERT_OK_AND_ASSIGN(auto expected_expr, ToLowest(CallOp("core.to_optional", {CallOp( "core.where", {cond, scalar_x, scalar_y})}))); EXPECT_THAT(actual_expr, EqualsExpr(expected_expr)); } { ASSERT_OK_AND_ASSIGN( auto actual_expr, ApplyOptimizer( CallOp("core._presence_and_or", {x, cond, CallOp("core.presence_and", {y, CallOp("core.presence_not", {cond})})}))); ASSERT_OK_AND_ASSIGN(auto expected_expr, ToLowest(CallOp("core.where", {cond, x, y}))); EXPECT_THAT(actual_expr, EqualsExpr(expected_expr)); } { ASSERT_OK_AND_ASSIGN( auto actual_expr, ApplyOptimizer( CallOp("core.presence_or", {CallOp("core.presence_and", {x, CallOp("core.presence_not", {cond})}), CallOp("core.presence_and", {y, CallOp("core.presence_not", {cond})})}))); ASSERT_OK_AND_ASSIGN( auto expected_expr, ToLowest(CallOp("core._presence_and_or", {x, CallOp("core.presence_not", {cond}), CallOp("core.presence_and", {y, CallOp("core.presence_not", {cond})})}))); EXPECT_THAT(actual_expr, EqualsExpr(expected_expr)); } { ASSERT_OK_AND_ASSIGN(auto y_present, WithQTypeAnnotation(Leaf("y"), GetQType<float>())); ASSERT_OK_AND_ASSIGN( auto actual_expr, ApplyOptimizer( CallOp("core.presence_or", {CallOp("core.presence_and", {x, cond}), y_present}))); ASSERT_OK_AND_ASSIGN( auto expected_expr, ToLowest(CallOp("core._presence_and_or", {x, cond, y_present}))); EXPECT_THAT(actual_expr, EqualsExpr(expected_expr)); } { ASSERT_OK_AND_ASSIGN( auto cond_da, WithQTypeAnnotation(Leaf("cond"), GetDenseArrayQType<Unit>())); ASSERT_OK_AND_ASSIGN( auto x_da, WithQTypeAnnotation(Leaf("x"), GetDenseArrayQType<float>())); ASSERT_OK_AND_ASSIGN( auto y_da, WithQTypeAnnotation(Leaf("y"), GetDenseArrayQType<float>())); ASSERT_OK_AND_ASSIGN( auto expr, CallOp("core.presence_or", {CallOp("core.presence_and", {x_da, CallOp("core.presence_not", {cond_da})}), CallOp("core.presence_and", {y_da, CallOp("core.presence_not", {cond_da})})})); ASSERT_OK_AND_ASSIGN(auto actual_expr, ApplyOptimizer(expr)); ASSERT_OK_AND_ASSIGN(auto expected_expr, ToLowest(expr)); EXPECT_THAT(actual_expr, EqualsExpr(expected_expr)); } } TEST_F(PresenceOptimizationsTest, CodegenWhereOptimization) { ASSERT_OK_AND_ASSIGN( auto cond, WithQTypeAnnotation(Leaf("cond"), GetOptionalQType<Unit>())); ASSERT_OK_AND_ASSIGN( auto x, WithQTypeAnnotation(Leaf("x"), GetOptionalQType<float>())); { ASSERT_OK_AND_ASSIGN( auto actual_expr, ApplyCodegenOptimizer( CallOp("core.where", {cond, x, Literal(OptionalValue<float>())}))); ASSERT_OK_AND_ASSIGN(auto expected_expr, ToLowest(CallOp("core.presence_and", {x, cond}))); EXPECT_THAT(actual_expr, EqualsExpr(expected_expr)); } } TEST_F(PresenceOptimizationsTest, PresenceAndOrSimplifications) { ASSERT_OK_AND_ASSIGN( auto cond, WithQTypeAnnotation(Leaf("cond"), GetOptionalQType<Unit>())); auto x = Leaf("x"); auto y = Leaf("y"); { ASSERT_OK_AND_ASSIGN(auto actual_expr, ApplyOptimizer(CallOp("core._presence_and_or", {x, Literal(kPresent), y}))); ASSERT_OK_AND_ASSIGN(auto expected_expr, ToLowest(CallOp("core.presence_or", {x, y}))); EXPECT_THAT(actual_expr, EqualsExpr(expected_expr)); } { ASSERT_OK_AND_ASSIGN(auto actual_expr, ApplyOptimizer(CallOp("core._presence_and_or", {Literal(kPresent), cond, y}))); ASSERT_OK_AND_ASSIGN(auto expected_expr, ToLowest(CallOp("core.presence_or", {cond, y}))); EXPECT_THAT(actual_expr, EqualsExpr(expected_expr)); } } TEST_F(PresenceOptimizationsTest, PresenceAndOptionalOptimizations) { ASSERT_OK_AND_ASSIGN(auto a, WithQTypeAnnotation(Leaf("a"), GetQType<int>())); auto c = Leaf("c"); { ASSERT_OK_AND_ASSIGN( auto actual_expr, ApplyOptimizer(CallOp("core.presence_and", {CallOp("core.to_optional._scalar", {a}), c}))); ASSERT_OK_AND_ASSIGN(auto expected_expr, ToLowest(CallOp("core.presence_and", {a, c}))); EXPECT_THAT(actual_expr, EqualsExpr(expected_expr)); } } TEST_F(PresenceOptimizationsTest, PresenceNotWithAndOptimizations) { ASSERT_OK_AND_ASSIGN( auto c, WithQTypeAnnotation(Leaf("c"), GetOptionalQType<Unit>())); { ASSERT_OK_AND_ASSIGN( auto actual_expr, ApplyOptimizer(CallOp("core.presence_not", {Literal(3.)}))); auto expected_expr = Literal(kMissing); EXPECT_THAT(actual_expr, EqualsExpr(expected_expr)); } { ASSERT_OK_AND_ASSIGN(auto actual_expr, ApplyOptimizer(CallOp( "core.presence_not", {CallOp("core.presence_and", {Literal(3.), c})}))); ASSERT_OK_AND_ASSIGN(auto expected_expr, ToLowest(CallOp("core.presence_not", {c}))); EXPECT_THAT(actual_expr, EqualsExpr(expected_expr)); } { ASSERT_OK_AND_ASSIGN( auto actual_expr, ApplyOptimizer( CallOp("core.presence_not", {CallOp("core.presence_and", {Literal(OptionalValue<float>(3.)), c})}))); ASSERT_OK_AND_ASSIGN(auto expected_expr, ToLowest(CallOp("core.presence_not", {c}))); EXPECT_THAT(actual_expr, EqualsExpr(expected_expr)); } } TEST_F(PresenceOptimizationsTest, PresenceAndOrCombinationSimplifications) { auto a = Leaf("a"); auto b = Leaf("b"); auto c = Leaf("c"); auto d = Leaf("d"); { ASSERT_OK_AND_ASSIGN( auto actual_expr1, ApplyOptimizer(CallOp("core._presence_and_or", {c, a, CallOp("core.presence_and", {c, b})}))); ASSERT_OK_AND_ASSIGN( auto actual_expr2, ApplyOptimizer( CallOp("core.presence_or", {CallOp("core.presence_and", {c, a}), CallOp("core.presence_and", {c, b})}))); ASSERT_OK_AND_ASSIGN( auto expected_expr, ToLowest(CallOp("core.presence_and", {c, CallOp("core.presence_or", {a, b})}))); EXPECT_THAT(actual_expr1, EqualsExpr(expected_expr)); EXPECT_THAT(actual_expr2, EqualsExpr(expected_expr)); } { ASSERT_OK_AND_ASSIGN( auto actual_expr, ApplyOptimizer(CallOp("core.presence_or", {CallOp("core.presence_or", {d, CallOp("core.presence_and", {c, a})}), CallOp("core.presence_and", {c, b})}))); ASSERT_OK_AND_ASSIGN( auto expected_expr, ToLowest(CallOp("core.presence_or", {d, CallOp("core.presence_and", {c, CallOp("core.presence_or", {a, b})})}))); EXPECT_THAT(actual_expr, EqualsExpr(expected_expr)); } } } }
2,455
#ifndef AROLLA_EXPR_OPTIMIZATION_PEEPHOLE_OPTIMIZATIONS_TUPLE_H_ #define AROLLA_EXPR_OPTIMIZATION_PEEPHOLE_OPTIMIZATIONS_TUPLE_H_ #include "absl/status/statusor.h" #include "arolla/expr/optimization/peephole_optimizer.h" namespace arolla::expr { absl::StatusOr<PeepholeOptimizationPack> TupleOptimizations(); } #endif #include "arolla/expr/optimization/peephole_optimizations/tuple.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/optimization/peephole_optimizer.h" #include "arolla/expr/registered_expr_operator.h" #include "arolla/expr/tuple_expr_operator.h" #include "arolla/util/fast_dynamic_downcast_final.h" #include "arolla/util/fingerprint.h" #include "arolla/util/status_macros_backport.h" namespace arolla::expr { namespace { absl::StatusOr<ExprNodePtr> OptimizeTupleGet(ExprNodePtr expr) { static Fingerprint make_tuple_fingerprint = MakeTupleOperator().fingerprint(); if (!expr->is_op()) { return expr; } auto get_nth_operator = fast_dynamic_downcast_final<const GetNthOperator*>(expr->op().get()); if (get_nth_operator == nullptr) { return expr; } if (expr->node_deps().size() != 1) { return expr; } auto tuple_expr = expr->node_deps()[0]; if (!tuple_expr->is_op()) { return expr; } ASSIGN_OR_RETURN(auto tuple_op, DecayRegisteredOperator(tuple_expr->op())); if (tuple_op->fingerprint() != make_tuple_fingerprint || tuple_expr->node_deps().size() <= get_nth_operator->index()) { return expr; } return tuple_expr->node_deps()[get_nth_operator->index()]; } absl::Status AppendGetNOptimizations(PeepholeOptimizationPack& optimizations) { ASSIGN_OR_RETURN( optimizations.emplace_back(), PeepholeOptimization::CreateTransformOptimization(OptimizeTupleGet)); return absl::OkStatus(); } } absl::StatusOr<PeepholeOptimizationPack> TupleOptimizations() { PeepholeOptimizationPack optimizations; RETURN_IF_ERROR(AppendGetNOptimizations(optimizations)); return optimizations; } }
#include "arolla/expr/optimization/peephole_optimizations/tuple.h" #include <cstdint> #include <memory> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "arolla/dense_array/qtype/types.h" #include "arolla/expr/expr.h" #include "arolla/expr/optimization/peephole_optimizer.h" #include "arolla/expr/testing/testing.h" #include "arolla/expr/tuple_expr_operator.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/util/init_arolla.h" #include "arolla/util/testing/status_matchers_backport.h" namespace arolla::expr { namespace { using ::arolla::testing::EqualsExpr; using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::WithQTypeAnnotation; class TupleOptimizationsTest : public ::testing::Test { protected: void SetUp() override { ASSERT_OK(InitArolla()); ASSERT_OK_AND_ASSIGN(optimizer_, CreatePeepholeOptimizer({TupleOptimizations})); } std::unique_ptr<PeepholeOptimizer> optimizer_; }; TEST_F(TupleOptimizationsTest, SingleSubstitution) { auto a = Leaf("l1"); auto b = Leaf("l2"); auto c = Leaf("l3"); auto d = Leaf("l4"); ASSERT_OK_AND_ASSIGN(auto tuple, CallOp("core.make_tuple", {a, b, c, d})); { ASSERT_OK_AND_ASSIGN(auto get0, CallOp(GetNthOperator::Make(0), {tuple})); EXPECT_THAT(optimizer_->Apply(get0), IsOkAndHolds(EqualsExpr(a))); } { ASSERT_OK_AND_ASSIGN(auto get1, CallOp(GetNthOperator::Make(1), {tuple})); EXPECT_THAT(optimizer_->Apply(get1), IsOkAndHolds(EqualsExpr(b))); } { ASSERT_OK_AND_ASSIGN(auto get2, CallOp(GetNthOperator::Make(2), {tuple})); EXPECT_THAT(optimizer_->Apply(get2), IsOkAndHolds(EqualsExpr(c))); } { ASSERT_OK_AND_ASSIGN(auto get3, CallOp(GetNthOperator::Make(3), {tuple})); EXPECT_THAT(optimizer_->Apply(get3), IsOkAndHolds(EqualsExpr(d))); } { ASSERT_OK_AND_ASSIGN(auto expr, CallOp(GetNthOperator::Make(0), {a})); EXPECT_THAT(optimizer_->Apply(expr), IsOkAndHolds(EqualsExpr(expr))); } } TEST_F(TupleOptimizationsTest, WorksWithConcatTuples) { ASSERT_OK_AND_ASSIGN(auto a, WithQTypeAnnotation(Leaf("a"), GetQType<int32_t>())); ASSERT_OK_AND_ASSIGN(auto b, WithQTypeAnnotation(Leaf("b"), GetQType<int64_t>())); ASSERT_OK_AND_ASSIGN( auto concat_tuples, CallOp("core.concat_tuples", {CallOp("core.make_tuple", {a, b}), CallOp("core.make_tuple", {b}), CallOp("core.make_tuple", {a})})); ASSERT_OK_AND_ASSIGN(auto lowest_concat_tuples, ToLowest(concat_tuples)); EXPECT_THAT( optimizer_->Apply(lowest_concat_tuples), IsOkAndHolds(EqualsExpr(CallOp("core.make_tuple", {a, b, b, a})))); ASSERT_OK_AND_ASSIGN(auto get_2, CallOp(GetNthOperator::Make(2), {concat_tuples})); } } }
2,456
#ifndef AROLLA_EXPR_OPTIMIZATION_PEEPHOLE_OPTIMIZATIONS_BOOL_H_ #define AROLLA_EXPR_OPTIMIZATION_PEEPHOLE_OPTIMIZATIONS_BOOL_H_ #include "absl/status/statusor.h" #include "arolla/expr/optimization/peephole_optimizer.h" namespace arolla::expr { absl::StatusOr<PeepholeOptimizationPack> BoolOptimizations(); } #endif #include "arolla/expr/optimization/peephole_optimizations/bool.h" #include <array> #include <functional> #include <string> #include <utility> #include <vector> #include "absl/container/flat_hash_set.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/optimization/peephole_optimizer.h" #include "arolla/expr/registered_expr_operator.h" #include "arolla/memory/optional_value.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/util/fingerprint.h" #include "arolla/util/status_macros_backport.h" namespace arolla::expr { namespace { auto Matches(const std::vector<ExprNodePtr>& patterns) { absl::flat_hash_set<Fingerprint> pattern_prints; pattern_prints.reserve(patterns.size()); for (const auto& p : patterns) { pattern_prints.insert(p->fingerprint()); } return [pattern_prints(std::move(pattern_prints))](const ExprNodePtr& node) { return pattern_prints.contains(node->fingerprint()); }; } std::vector<ExprNodePtr> BoolLiterals(bool value) { return {Literal(value), Literal(MakeOptionalValue(value))}; } constexpr std::array kComparisonOppositeOps = { std::pair{"bool.equal", "bool.not_equal"}, std::pair{"bool.not_equal", "bool.equal"}, std::pair{"bool.less", "bool.greater_equal"}, std::pair{"bool.less_equal", "bool.greater"}}; absl::Status LogicalNotComparisonOptimizations( PeepholeOptimizationPack& optimizations) { ExprNodePtr a = Placeholder("a"); ExprNodePtr b = Placeholder("b"); { ASSIGN_OR_RETURN( ExprNodePtr from, CallOpReference("bool.logical_not", {CallOpReference("bool.logical_not", {a})})); ASSIGN_OR_RETURN(optimizations.emplace_back(), PeepholeOptimization::CreatePatternOptimization(from, a)); } for (auto [cmp1, cmp2] : kComparisonOppositeOps) { ASSIGN_OR_RETURN( ExprNodePtr from, CallOpReference("bool.logical_not", {CallOpReference(cmp1, {a, b})})); ASSIGN_OR_RETURN(ExprNodePtr to, CallOpReference(cmp2, {a, b})); ASSIGN_OR_RETURN(optimizations.emplace_back(), PeepholeOptimization::CreatePatternOptimization(from, to)); } return absl::OkStatus(); } constexpr std::array kComparisonOps = {"equal", "not_equal", "less", "less_equal"}; constexpr std::array kLogicalOps = {"and", "or"}; absl::Status CoreBoolComparisonOptimizations( PeepholeOptimizationPack& optimizations) { ExprNodePtr a = Placeholder("a"); ExprNodePtr b = Placeholder("b"); ExprNodePtr c = Placeholder("c"); ExprNodePtr d = Placeholder("d"); ExprNodePtr true_ = Placeholder("true"); std::vector<ExprNodePtr> true_literals = BoolLiterals(true); auto is_true = Matches(true_literals); { ASSIGN_OR_RETURN(ExprNodePtr from, CallOpReference("core.equal", {true_, a})); ASSIGN_OR_RETURN(ExprNodePtr to, CallOpReference("core.equal", {a, true_})); ASSIGN_OR_RETURN( optimizations.emplace_back(), PeepholeOptimization::CreatePatternOptimization( from, to, {{"true", is_true}, {"a", std::not_fn(is_true)}})); } for (absl::string_view comparison_op : kComparisonOps) { ASSIGN_OR_RETURN( ExprNodePtr bool_cmp, CallOpReference(absl::StrCat("bool.", comparison_op), {a, b})); ASSIGN_OR_RETURN( ExprNodePtr core_cmp, CallOpReference(absl::StrCat("core.", comparison_op), {a, b})); { ASSIGN_OR_RETURN(ExprNodePtr from, CallOpReference("core.equal", {bool_cmp, true_})); ASSIGN_OR_RETURN(optimizations.emplace_back(), PeepholeOptimization::CreatePatternOptimization( from, core_cmp, {{"true", is_true}})); } { ASSIGN_OR_RETURN( ExprNodePtr from, CallOpReference( "core.equal", {CallOpReference("core.to_optional._scalar", {bool_cmp}), true_})); ASSIGN_OR_RETURN(optimizations.emplace_back(), PeepholeOptimization::CreatePatternOptimization( from, core_cmp, {{"true", is_true}})); } } absl::flat_hash_set<std::string> bool_comparison_ops; for (absl::string_view comparison_op : kComparisonOps) { bool_comparison_ops.insert(absl::StrCat("bool.", comparison_op)); } auto eq_true_will_be_optimized_further = [bool_comparison_ops](const ExprNodePtr& node) { if (node->is_literal()) return true; if (!node->is_op()) return false; return IsRegisteredOperator(node->op()) && bool_comparison_ops.contains(node->op()->display_name()); }; for (absl::string_view logical_op : kLogicalOps) { ASSIGN_OR_RETURN( ExprNodePtr bool_logic, CallOpReference(absl::StrCat("bool.logical_", logical_op), {a, b})); ASSIGN_OR_RETURN( ExprNodePtr core_logic, CallOpReference(absl::StrCat("core.presence_", logical_op), {CallOpReference("core.equal", {a, true_}), CallOpReference("core.equal", {b, true_})})); { ASSIGN_OR_RETURN(ExprNodePtr from, CallOpReference("core.equal", {bool_logic, true_})); ASSIGN_OR_RETURN( optimizations.emplace_back(), PeepholeOptimization::CreatePatternOptimization( from, core_logic, {{"true", is_true}, {"a", eq_true_will_be_optimized_further}})); ASSIGN_OR_RETURN( optimizations.emplace_back(), PeepholeOptimization::CreatePatternOptimization( from, core_logic, {{"true", is_true}, {"b", eq_true_will_be_optimized_further}})); } } return absl::OkStatus(); } absl::Status LogicalIfOptimizations(PeepholeOptimizationPack& optimizations) { ExprNodePtr condition = Placeholder("condition"); ExprNodePtr a = Placeholder("a"); ExprNodePtr b = Placeholder("b"); ExprNodePtr c = Placeholder("c"); auto is_scalar_bool = [](const ExprNodePtr& expr) { return expr->qtype() == GetQType<bool>(); }; ExprNodePtr true_ = Placeholder("true"); std::vector<ExprNodePtr> true_literals = BoolLiterals(true); auto is_true = Matches(true_literals); ExprNodePtr false_ = Placeholder("false"); std::vector<ExprNodePtr> false_literals = BoolLiterals(false); auto is_false = Matches(false_literals); { ASSIGN_OR_RETURN( ExprNodePtr from1, CallOpReference( "bool.logical_if", {CallOpReference("core.to_optional._scalar", {condition}), a, b, c})); ASSIGN_OR_RETURN( ExprNodePtr to, CallOpReference( "core.where", {CallOpReference("core.equal", {condition, Literal(true)}), a, b})); ASSIGN_OR_RETURN(optimizations.emplace_back(), PeepholeOptimization::CreatePatternOptimization( from1, to, {{"condition", is_scalar_bool}})); ASSIGN_OR_RETURN(ExprNodePtr from2, CallOpReference("bool.logical_if", {CallOpReference("core.presence_or", {condition, false_}), a, b, c})); ASSIGN_OR_RETURN(optimizations.emplace_back(), PeepholeOptimization::CreatePatternOptimization( from2, to, {{"false", is_false}})); } { ASSIGN_OR_RETURN(ExprNodePtr from, CallOpReference("bool.logical_if", {condition, a, b, b})); ASSIGN_OR_RETURN( ExprNodePtr to, CallOpReference( "core.where", {CallOpReference("core.equal", {condition, Literal(true)}), a, b})); ASSIGN_OR_RETURN(optimizations.emplace_back(), PeepholeOptimization::CreatePatternOptimization(from, to)); } { ASSIGN_OR_RETURN( ExprNodePtr from, CallOpReference("bool.logical_if", {CallOpReference("core.presence_or", {condition, true_}), a, b, c})); ASSIGN_OR_RETURN( ExprNodePtr to, CallOpReference( "core.where", {CallOpReference("core.equal", {condition, Literal(false)}), b, a})); ASSIGN_OR_RETURN(optimizations.emplace_back(), PeepholeOptimization::CreatePatternOptimization( from, to, {{"true", is_true}})); } { ASSIGN_OR_RETURN( ExprNodePtr from, CallOpReference("bool.logical_if", {condition, true_, false_, a})); ASSIGN_OR_RETURN(ExprNodePtr to, CallOpReference("core.presence_or", {condition, a})); ASSIGN_OR_RETURN(optimizations.emplace_back(), PeepholeOptimization::CreatePatternOptimization( from, to, {{"true", is_true}, {"false", is_false}})); } return absl::OkStatus(); } } absl::StatusOr<PeepholeOptimizationPack> BoolOptimizations() { PeepholeOptimizationPack optimizations; RETURN_IF_ERROR(LogicalNotComparisonOptimizations(optimizations)); RETURN_IF_ERROR(CoreBoolComparisonOptimizations(optimizations)); RETURN_IF_ERROR(LogicalIfOptimizations(optimizations)); return optimizations; } }
#include "arolla/expr/optimization/peephole_optimizations/bool.h" #include <memory> #include <utility> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/statusor.h" #include "arolla/dense_array/qtype/types.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/optimization/peephole_optimizer.h" #include "arolla/expr/testing/testing.h" #include "arolla/memory/optional_value.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/optional_qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/util/init_arolla.h" #include "arolla/util/testing/status_matchers_backport.h" #include "arolla/util/status_macros_backport.h" namespace arolla::expr { namespace { using ::arolla::testing::EqualsExpr; using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::WithQTypeAnnotation; class BoolOptimizationsTest : public ::testing::Test { protected: void SetUp() override { ASSERT_OK(InitArolla()); ASSERT_OK_AND_ASSIGN(optimizer_, CreatePeepholeOptimizer({BoolOptimizations})); } absl::StatusOr<ExprNodePtr> ApplyOptimizer( absl::StatusOr<ExprNodePtr> status_or_expr) const { ASSIGN_OR_RETURN(auto expr, ToLowest(status_or_expr)); return ToLowest(optimizer_->ApplyToNode(expr)); } absl::StatusOr<ExprNodePtr> ToLowest( const absl::StatusOr<ExprNodePtr>& status_or_expr) const { if (!status_or_expr.ok()) { return std::move(status_or_expr).status(); } return ::arolla::expr::ToLowest(*status_or_expr); } std::unique_ptr<PeepholeOptimizer> optimizer_; }; TEST_F(BoolOptimizationsTest, LogicalNotRemoval) { ExprNodePtr x = Leaf("x"); ExprNodePtr y = Leaf("y"); { ASSERT_OK_AND_ASSIGN( auto actual_expr, ApplyOptimizer( CallOp("bool.logical_not", {CallOp("bool.logical_not", {x})}))); EXPECT_THAT(actual_expr, EqualsExpr(x)); } { ASSERT_OK_AND_ASSIGN(ExprNodePtr bool_eq, CallOp("bool.equal", {x, y})); ASSERT_OK_AND_ASSIGN(ExprNodePtr bool_not_eq, CallOp("bool.not_equal", {x, y})); { ASSERT_OK_AND_ASSIGN( auto actual_expr, ApplyOptimizer(CallOp("bool.logical_not", {bool_eq}))); ASSERT_OK_AND_ASSIGN(auto expected_expr, ToLowest(bool_not_eq)); EXPECT_THAT(actual_expr, EqualsExpr(expected_expr)); } { ASSERT_OK_AND_ASSIGN( auto actual_expr, ApplyOptimizer(CallOp("bool.logical_not", {bool_not_eq}))); ASSERT_OK_AND_ASSIGN(auto expected_expr, ToLowest(bool_eq)); EXPECT_THAT(actual_expr, EqualsExpr(expected_expr)); } } { ASSERT_OK_AND_ASSIGN(auto actual_expr, ApplyOptimizer(CallOp("bool.logical_not", {CallOp("bool.less", {x, y})}))); ASSERT_OK_AND_ASSIGN(auto expected_expr, ToLowest(CallOp("bool.greater_equal", {x, y}))); EXPECT_THAT(actual_expr, EqualsExpr(expected_expr)); } { ASSERT_OK_AND_ASSIGN( auto actual_expr, ApplyOptimizer( CallOp("bool.logical_not", {CallOp("bool.less_equal", {x, y})}))); ASSERT_OK_AND_ASSIGN(auto expected_expr, ToLowest(CallOp("bool.greater", {x, y}))); EXPECT_THAT(actual_expr, EqualsExpr(expected_expr)); } } TEST_F(BoolOptimizationsTest, BoolToCore) { ASSERT_OK_AND_ASSIGN(auto x, WithQTypeAnnotation(Leaf("x"), GetQType<int>())); ASSERT_OK_AND_ASSIGN(auto y, WithQTypeAnnotation(Leaf("y"), GetQType<int>())); ExprNodePtr w = Leaf("w"); ExprNodePtr q = Leaf("q"); ExprNodePtr true_opt = Literal(MakeOptionalValue(true)); { ASSERT_OK_AND_ASSIGN(ExprNodePtr bool_cmp, CallOp("bool.equal", {x, y})); ASSERT_OK_AND_ASSIGN(ExprNodePtr core_cmp, CallOp("core.equal", {x, y})); { ASSERT_OK_AND_ASSIGN( auto actual_expr, ApplyOptimizer(CallOp("core.equal", {bool_cmp, true_opt}))); ASSERT_OK_AND_ASSIGN(auto expected_expr, ToLowest(core_cmp)); EXPECT_THAT(actual_expr, EqualsExpr(expected_expr)); } { ASSERT_OK_AND_ASSIGN( auto actual_expr, ApplyOptimizer(CallOp("core.equal", {true_opt, bool_cmp}))); ASSERT_OK_AND_ASSIGN(auto expected_expr, ToLowest(core_cmp)); EXPECT_THAT(actual_expr, EqualsExpr(expected_expr)); } } { ASSERT_OK_AND_ASSIGN(auto core_cmp, CallOp("core.equal", {Literal(true), true_opt})); ASSERT_OK_AND_ASSIGN(auto actual_expr, ApplyOptimizer(core_cmp)); ASSERT_OK_AND_ASSIGN(auto expected_expr, ToLowest(core_cmp)); EXPECT_THAT(actual_expr, EqualsExpr(expected_expr)); } { ASSERT_OK_AND_ASSIGN(ExprNodePtr bool_cmp, CallOp("bool.less", {x, y})); ASSERT_OK_AND_ASSIGN(ExprNodePtr core_cmp, CallOp("core.less", {x, y})); { ASSERT_OK_AND_ASSIGN( auto actual_expr, ApplyOptimizer(CallOp("core.equal", {bool_cmp, true_opt}))); ASSERT_OK_AND_ASSIGN(auto expected_expr, ToLowest(core_cmp)); EXPECT_THAT(actual_expr, EqualsExpr(expected_expr)); } { ASSERT_OK_AND_ASSIGN( auto actual_expr, ApplyOptimizer(CallOp("core.equal", {true_opt, bool_cmp}))); ASSERT_OK_AND_ASSIGN(auto expected_expr, ToLowest(core_cmp)); EXPECT_THAT(actual_expr, EqualsExpr(expected_expr)); } } { ASSERT_OK_AND_ASSIGN(ExprNodePtr bool_cmp, CallOp("bool.less", {x, y})); ASSERT_OK_AND_ASSIGN(ExprNodePtr core_cmp, CallOp("core.less", {x, y})); { ASSERT_OK_AND_ASSIGN( auto actual_expr, ApplyOptimizer( CallOp("core.equal", {CallOp("core.to_optional", {bool_cmp}), true_opt}))); ASSERT_OK_AND_ASSIGN(auto expected_expr, ToLowest(core_cmp)); EXPECT_THAT(actual_expr, EqualsExpr(expected_expr)); } { ASSERT_OK_AND_ASSIGN( auto actual_expr, ApplyOptimizer(CallOp("core.equal", {true_opt, bool_cmp}))); ASSERT_OK_AND_ASSIGN(auto expected_expr, ToLowest(core_cmp)); EXPECT_THAT(actual_expr, EqualsExpr(expected_expr)); } } { ASSERT_OK_AND_ASSIGN(ExprNodePtr bool_cmp1, CallOp("bool.less", {x, y})); ASSERT_OK_AND_ASSIGN(ExprNodePtr bool_cmp2, CallOp("bool.less_equal", {w, q})); ASSERT_OK_AND_ASSIGN(ExprNodePtr bool_and, CallOp("bool.logical_and", {bool_cmp1, bool_cmp2})); ASSERT_OK_AND_ASSIGN(ExprNodePtr core_cmp1, CallOp("core.less", {x, y})); ASSERT_OK_AND_ASSIGN(ExprNodePtr core_cmp2, CallOp("core.less_equal", {w, q})); ASSERT_OK_AND_ASSIGN(ExprNodePtr core_and, CallOp("core.presence_and", {core_cmp1, core_cmp2})); { ASSERT_OK_AND_ASSIGN( auto actual_expr, ToLowest(CallOp("core.equal", {bool_and, true_opt}))); ASSERT_OK_AND_ASSIGN(actual_expr, ToLowest(optimizer_->Apply(actual_expr))); ASSERT_OK_AND_ASSIGN(actual_expr, ToLowest(optimizer_->Apply(actual_expr))); ASSERT_OK_AND_ASSIGN(auto expected_expr, ToLowest(core_and)); EXPECT_THAT(actual_expr, EqualsExpr(expected_expr)); } { ASSERT_OK_AND_ASSIGN( auto actual_expr, ToLowest(CallOp("core.equal", {true_opt, bool_and}))); ASSERT_OK_AND_ASSIGN(actual_expr, ToLowest(optimizer_->Apply(actual_expr))); ASSERT_OK_AND_ASSIGN(actual_expr, ToLowest(optimizer_->Apply(actual_expr))); ASSERT_OK_AND_ASSIGN(auto expected_expr, ToLowest(core_and)); EXPECT_THAT(actual_expr, EqualsExpr(expected_expr)); } } { ASSERT_OK_AND_ASSIGN(ExprNodePtr bool_cmp1, CallOp("bool.less", {x, y})); ASSERT_OK_AND_ASSIGN(ExprNodePtr bool_cmp2, CallOp("bool.less_equal", {w, q})); ASSERT_OK_AND_ASSIGN(ExprNodePtr bool_or, CallOp("bool.logical_or", {bool_cmp1, bool_cmp2})); ASSERT_OK_AND_ASSIGN(ExprNodePtr core_cmp1, CallOp("core.less", {x, y})); ASSERT_OK_AND_ASSIGN(ExprNodePtr core_cmp2, CallOp("core.less_equal", {w, q})); ASSERT_OK_AND_ASSIGN(ExprNodePtr core_or, CallOp("core.presence_or", {core_cmp1, core_cmp2})); { ASSERT_OK_AND_ASSIGN(auto actual_expr, ToLowest(CallOp("core.equal", {bool_or, true_opt}))); ASSERT_OK_AND_ASSIGN(actual_expr, ToLowest(optimizer_->Apply(actual_expr))); ASSERT_OK_AND_ASSIGN(actual_expr, ToLowest(optimizer_->Apply(actual_expr))); ASSERT_OK_AND_ASSIGN(auto expected_expr, ToLowest(core_or)); EXPECT_THAT(actual_expr, EqualsExpr(expected_expr)); } { ASSERT_OK_AND_ASSIGN(auto actual_expr, ToLowest(CallOp("core.equal", {true_opt, bool_or}))); ASSERT_OK_AND_ASSIGN(actual_expr, ToLowest(optimizer_->Apply(actual_expr))); ASSERT_OK_AND_ASSIGN(actual_expr, ToLowest(optimizer_->Apply(actual_expr))); ASSERT_OK_AND_ASSIGN(auto expected_expr, ToLowest(core_or)); EXPECT_THAT(actual_expr, EqualsExpr(expected_expr)); } } { ASSERT_OK_AND_ASSIGN(ExprNodePtr bool_cmp1, CallOp("bool.less", {x, y})); ASSERT_OK_AND_ASSIGN(ExprNodePtr bool_or, CallOp("bool.logical_or", {bool_cmp1, q})); ASSERT_OK_AND_ASSIGN(ExprNodePtr core_cmp1, CallOp("core.less", {x, y})); ASSERT_OK_AND_ASSIGN( ExprNodePtr core_or, CallOp("core.presence_or", {core_cmp1, CallOp("core.equal", {q, true_opt})})); { ASSERT_OK_AND_ASSIGN(auto actual_expr, ToLowest(CallOp("core.equal", {bool_or, true_opt}))); ASSERT_OK_AND_ASSIGN(actual_expr, ToLowest(optimizer_->Apply(actual_expr))); ASSERT_OK_AND_ASSIGN(actual_expr, ToLowest(optimizer_->Apply(actual_expr))); ASSERT_OK_AND_ASSIGN(auto expected_expr, ToLowest(core_or)); EXPECT_THAT(actual_expr, EqualsExpr(expected_expr)); } { ASSERT_OK_AND_ASSIGN(auto actual_expr, ToLowest(CallOp("core.equal", {true_opt, bool_or}))); ASSERT_OK_AND_ASSIGN(actual_expr, ToLowest(optimizer_->Apply(actual_expr))); ASSERT_OK_AND_ASSIGN(actual_expr, ToLowest(optimizer_->Apply(actual_expr))); ASSERT_OK_AND_ASSIGN(auto expected_expr, ToLowest(core_or)); EXPECT_THAT(actual_expr, EqualsExpr(expected_expr)); } } { ASSERT_OK_AND_ASSIGN(ExprNodePtr bool_or, CallOp("bool.logical_or", {true_opt, q})); ASSERT_OK_AND_ASSIGN( ExprNodePtr core_or, CallOp("core.presence_or", {CallOp("core.equal", {true_opt, true_opt}), CallOp("core.equal", {q, true_opt})})); { ASSERT_OK_AND_ASSIGN(auto actual_expr, ToLowest(CallOp("core.equal", {bool_or, true_opt}))); ASSERT_OK_AND_ASSIGN(actual_expr, ToLowest(optimizer_->Apply(actual_expr))); ASSERT_OK_AND_ASSIGN(actual_expr, ToLowest(optimizer_->Apply(actual_expr))); ASSERT_OK_AND_ASSIGN(auto expected_expr, ToLowest(core_or)); EXPECT_THAT(actual_expr, EqualsExpr(expected_expr)); } { ASSERT_OK_AND_ASSIGN(auto actual_expr, ToLowest(CallOp("core.equal", {true_opt, bool_or}))); ASSERT_OK_AND_ASSIGN(actual_expr, ToLowest(optimizer_->Apply(actual_expr))); ASSERT_OK_AND_ASSIGN(actual_expr, ToLowest(optimizer_->Apply(actual_expr))); ASSERT_OK_AND_ASSIGN(auto expected_expr, ToLowest(core_or)); EXPECT_THAT(actual_expr, EqualsExpr(expected_expr)); } } { ASSERT_OK_AND_ASSIGN(ExprNodePtr bool_or, CallOp("bool.logical_or", {w, q})); ASSERT_OK_AND_ASSIGN(auto expr, CallOp("core.equal", {bool_or, true_opt})); ASSERT_OK_AND_ASSIGN(auto actual_expr, ApplyOptimizer(expr)); ASSERT_OK_AND_ASSIGN(auto expected_expr, ToLowest(expr)); EXPECT_THAT(ApplyOptimizer(expr), IsOkAndHolds(EqualsExpr(expr))); } } TEST_F(BoolOptimizationsTest, LogicalIf) { ExprNodePtr a = Leaf("a"); ExprNodePtr b = Leaf("b"); ExprNodePtr c = Leaf("c"); ExprNodePtr d = Leaf("d"); ASSERT_OK_AND_ASSIGN(ExprNodePtr cond_full, WithQTypeAnnotation(Leaf("cond"), GetQType<bool>())); ASSERT_OK_AND_ASSIGN( ExprNodePtr cond_optional, WithQTypeAnnotation(Leaf("cond"), GetOptionalQType<bool>())); ExprNodePtr cond_unknown = Leaf("cond"); { for (const auto& [cond, do_optimize] : {std::pair{cond_full, true}, std::pair{cond_unknown, false}}) { ASSERT_OK_AND_ASSIGN( ExprNodePtr from, CallOp("bool.logical_if", {CallOp("core.to_optional", {cond}), a, b, c})); ASSERT_OK_AND_ASSIGN( ExprNodePtr to, CallOp("core.where", {CallOp("core.equal", {cond, Literal(true)}), a, b})); auto result = do_optimize ? to : from; EXPECT_THAT(ApplyOptimizer(from), IsOkAndHolds(EqualsExpr(ToLowest(result)))); } { ASSERT_OK_AND_ASSIGN( ExprNodePtr from1, CallOp("bool.logical_if", {CallOp("core.presence_or", {cond_unknown, Literal(false)}), a, b, c})); ASSERT_OK_AND_ASSIGN( ExprNodePtr from2, CallOp("bool.logical_if", {CallOp("core.presence_or", {cond_unknown, Literal(MakeOptionalValue(false))}), a, b, c})); ASSERT_OK_AND_ASSIGN( ExprNodePtr to, CallOp("core.where", {CallOp("core.equal", {cond_unknown, Literal(true)}), a, b})); EXPECT_THAT(ApplyOptimizer(from1), IsOkAndHolds(EqualsExpr(ToLowest(to)))); EXPECT_THAT(ApplyOptimizer(from2), IsOkAndHolds(EqualsExpr(ToLowest(to)))); ASSERT_OK_AND_ASSIGN( ExprNodePtr no_optimization, CallOp("bool.logical_if", {CallOp("core.presence_or", {cond_unknown, d}), a, b, c})); EXPECT_THAT(ApplyOptimizer(no_optimization), IsOkAndHolds(EqualsExpr(ToLowest(no_optimization)))); } } { ASSERT_OK_AND_ASSIGN( auto actual_expr, ToLowest(CallOp("bool.logical_if", {CallOp("bool.equal", {a, Literal(1)}), b, c, c}))); ASSERT_OK_AND_ASSIGN(actual_expr, ToLowest(optimizer_->Apply(actual_expr))); ASSERT_OK_AND_ASSIGN(actual_expr, ToLowest(optimizer_->Apply(actual_expr))); ASSERT_OK_AND_ASSIGN( auto expected_expr, ToLowest(CallOp("core.where", {CallOp("core.equal", {a, Literal(1)}), b, c}))); EXPECT_THAT(actual_expr, EqualsExpr(expected_expr)); } { ASSERT_OK_AND_ASSIGN( ExprNodePtr from, CallOp("bool.logical_if", {a, Literal(true), Literal(false), b})); ASSERT_OK_AND_ASSIGN(ExprNodePtr to, CallOp("core.presence_or", {a, b})); EXPECT_THAT(ApplyOptimizer(from), IsOkAndHolds(EqualsExpr(to))); } { ASSERT_OK_AND_ASSIGN( auto actual_expr1, ApplyOptimizer( CallOp("bool.logical_if", {CallOp("core.presence_or", {cond_unknown, Literal(true)}), a, b, c}))); ASSERT_OK_AND_ASSIGN( auto actual_expr2, ApplyOptimizer( CallOp("bool.logical_if", {CallOp("core.presence_or", {cond_unknown, Literal(MakeOptionalValue(true))}), a, b, c}))); ASSERT_OK_AND_ASSIGN( auto expected_expr, ToLowest(CallOp( "core.where", {CallOp("core.equal", {cond_unknown, Literal(false)}), b, a}))); EXPECT_THAT(actual_expr1, EqualsExpr(expected_expr)); EXPECT_THAT(actual_expr2, EqualsExpr(expected_expr)); } { ASSERT_OK_AND_ASSIGN( ExprNodePtr no_optimization, CallOp("bool.logical_if", {CallOp("core.presence_or", {Literal(false), cond_unknown}), a, b, c})); EXPECT_THAT(ApplyOptimizer(no_optimization), IsOkAndHolds(EqualsExpr(no_optimization))); } } } }
2,457
#ifndef AROLLA_EXPR_OPTIMIZATION_PEEPHOLE_OPTIMIZATIONS_DICT_H_ #define AROLLA_EXPR_OPTIMIZATION_PEEPHOLE_OPTIMIZATIONS_DICT_H_ #include "absl/status/statusor.h" #include "arolla/expr/optimization/peephole_optimizer.h" namespace arolla::expr { absl::StatusOr<PeepholeOptimizationPack> DictOptimizations(); } #endif #include "arolla/expr/optimization/peephole_optimizations/dict.h" #include <memory> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/optimization/peephole_optimizer.h" #include "arolla/qtype/dict/dict_types.h" #include "arolla/util/status_macros_backport.h" namespace arolla::expr { namespace { absl::StatusOr<std::unique_ptr<PeepholeOptimization>> BoolDictOptimization() { ExprNodePtr dict = Placeholder("dict"); ASSIGN_OR_RETURN( ExprNodePtr pattern, CallOpReference("array.at", {Placeholder("values"), CallOpReference("dict._get_row", {dict, Placeholder("p")})})); ASSIGN_OR_RETURN( ExprNodePtr true_value, CallOpReference("array.at", {Placeholder("values"), CallOpReference("dict._get_row", {dict, Literal(true)})})); ASSIGN_OR_RETURN( ExprNodePtr false_value, CallOpReference("array.at", {Placeholder("values"), CallOpReference("dict._get_row", {dict, Literal(false)})})); ASSIGN_OR_RETURN(ExprNodePtr missing_value, CallOpReference("core.empty_like", {true_value})); ASSIGN_OR_RETURN( ExprNodePtr replacement, CallOpReference("bool.logical_if", {Placeholder("p"), true_value, false_value, missing_value})); auto is_bool_literal = [](const ExprNodePtr& node) { return node->qvalue().has_value() && node->qtype() == GetKeyToRowDictQType<bool>(); }; auto is_not_literal = [](const ExprNodePtr& node) { return !node->qvalue().has_value(); }; return PeepholeOptimization::CreatePatternOptimization( pattern, replacement, {{"dict", is_bool_literal}, {"p", is_not_literal}}); } absl::Status AddDictContainsOptimizations( PeepholeOptimizationPack& optimizations) { ASSIGN_OR_RETURN(ExprNodePtr replacement, CallOpReference("dict._contains", {Placeholder("dict"), Placeholder("x")})); for (const char* op_has : {"core.has._optional", "core.has._array"}) { { ASSIGN_OR_RETURN( ExprNodePtr pattern, CallOpReference( "core.presence_and", {CallOpReference(op_has, {Placeholder("x")}), CallOpReference("dict._contains", {Placeholder("dict"), Placeholder("x")})})); ASSIGN_OR_RETURN(optimizations.emplace_back(), PeepholeOptimization::CreatePatternOptimization( pattern, replacement)); } { ASSIGN_OR_RETURN( ExprNodePtr pattern, CallOpReference( "core.presence_and", {CallOpReference("dict._contains", {Placeholder("dict"), Placeholder("x")}), CallOpReference(op_has, {Placeholder("x")})})); ASSIGN_OR_RETURN(optimizations.emplace_back(), PeepholeOptimization::CreatePatternOptimization( pattern, replacement)); } } return absl::OkStatus(); } } absl::StatusOr<PeepholeOptimizationPack> DictOptimizations() { PeepholeOptimizationPack optimizations; ASSIGN_OR_RETURN(optimizations.emplace_back(), BoolDictOptimization()); RETURN_IF_ERROR(AddDictContainsOptimizations(optimizations)); return optimizations; } }
#include "arolla/expr/optimization/peephole_optimizations/dict.h" #include <cstdint> #include <memory> #include <utility> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/statusor.h" #include "arolla/dense_array/dense_array.h" #include "arolla/dense_array/qtype/types.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/optimization/peephole_optimizer.h" #include "arolla/expr/testing/testing.h" #include "arolla/expr/visitors/substitution.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/dict/dict_types.h" #include "arolla/util/init_arolla.h" #include "arolla/util/unit.h" #include "arolla/util/status_macros_backport.h" namespace arolla::expr { namespace { using ::arolla::testing::EqualsExpr; using ::arolla::testing::WithQTypeAnnotation; class DictOptimizationsTest : public ::testing::Test { protected: void SetUp() override { ASSERT_OK(InitArolla()); ASSERT_OK_AND_ASSIGN(optimizer_, CreatePeepholeOptimizer({DictOptimizations})); GetDenseArrayQType<int>(); GetDenseArrayQType<Unit>(); } absl::StatusOr<ExprNodePtr> ApplyOptimizer( absl::StatusOr<ExprNodePtr> status_or_expr) const { ASSIGN_OR_RETURN(auto expr, ToLowest(status_or_expr)); return ToLowest(optimizer_->ApplyToNode(expr)); } absl::StatusOr<ExprNodePtr> ToLowest( const absl::StatusOr<ExprNodePtr>& status_or_expr) const { if (!status_or_expr.ok()) { return std::move(status_or_expr).status(); } return ::arolla::expr::ToLowest(*status_or_expr); } std::unique_ptr<PeepholeOptimizer> optimizer_; }; TEST_F(DictOptimizationsTest, Bool) { auto values = CreateDenseArray<float>({57.0, 1543.0}); auto p = Leaf("cond"); auto dict = Leaf("dict"); ASSERT_OK_AND_ASSIGN( ExprNodePtr expr, CallOp("array.at", {Literal(values), CallOp("dict._get_row", {dict, p})})); { ASSERT_OK_AND_ASSIGN(auto actual_expr, ApplyOptimizer(expr)); ASSERT_OK_AND_ASSIGN(auto expected_expr, ToLowest(expr)); EXPECT_THAT(actual_expr, EqualsExpr(expected_expr)); } { ASSERT_OK_AND_ASSIGN( ExprNodePtr expr_with_literal_int_dict, SubstituteByFingerprint( expr, {{dict->fingerprint(), Literal(KeyToRowDict<int64_t>{{1, 1}, {0, 0}})}})); ASSERT_OK_AND_ASSIGN(auto actual_expr, ApplyOptimizer(expr_with_literal_int_dict)); ASSERT_OK_AND_ASSIGN(auto expected_expr, ToLowest(expr_with_literal_int_dict)); EXPECT_THAT(actual_expr, EqualsExpr(expected_expr)); } { ASSERT_OK_AND_ASSIGN( ExprNodePtr expr_with_literal_bool_dict, SubstituteByFingerprint( expr, {{dict->fingerprint(), Literal(KeyToRowDict<bool>{{false, 1}, {true, 0}})}})); ASSERT_OK_AND_ASSIGN( ExprNodePtr expected_true_value, SubstituteByFingerprint(expr_with_literal_bool_dict, {{p->fingerprint(), Literal(true)}})); ASSERT_OK_AND_ASSIGN( ExprNodePtr expected_false_value, SubstituteByFingerprint(expr_with_literal_bool_dict, {{p->fingerprint(), Literal(false)}})); ASSERT_OK_AND_ASSIGN(auto actual_expr, ApplyOptimizer(expr_with_literal_bool_dict)); ASSERT_OK_AND_ASSIGN( auto expected_expr, ToLowest(CallOp("bool.logical_if", {p, expected_true_value, expected_false_value, CallOp("core.empty_like", {expected_true_value})}))); EXPECT_THAT(actual_expr, EqualsExpr(expected_expr)); } } TEST_F(DictOptimizationsTest, Contains) { auto key = WithQTypeAnnotation(Leaf("key"), GetDenseArrayQType<int>()); auto dict = Leaf("dict"); ASSERT_OK_AND_ASSIGN(auto key_exists, CallOp("core.has", {key})); ASSERT_OK_AND_ASSIGN(auto dict_contains_key, CallOp("dict._contains", {dict, key})); { ASSERT_OK_AND_ASSIGN( auto actual_expr, ApplyOptimizer( CallOp("core.presence_and", {key_exists, dict_contains_key}))); ASSERT_OK_AND_ASSIGN(auto expected_expr, ToLowest(dict_contains_key)); EXPECT_THAT(actual_expr, EqualsExpr(expected_expr)); } { ASSERT_OK_AND_ASSIGN( auto actual_expr, ApplyOptimizer( CallOp("core.presence_and", {dict_contains_key, key_exists}))); ASSERT_OK_AND_ASSIGN(auto expected_expr, ToLowest(dict_contains_key)); EXPECT_THAT(actual_expr, EqualsExpr(expected_expr)); } } } }
2,458
#ifndef AROLLA_EXPR_OPERATOR_LOADER_BACKEND_OPERATOR_H_ #define AROLLA_EXPR_OPERATOR_LOADER_BACKEND_OPERATOR_H_ #include <vector> #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "arolla/expr/basic_expr_operator.h" #include "arolla/expr/expr_attributes.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/expr/operator_loader/qtype_constraint.h" #include "arolla/expr/operator_loader/qtype_inference.h" #include "arolla/util/fingerprint.h" namespace arolla::operator_loader { class BackendOperator final : public expr::BackendExprOperatorTag, public expr::ExprOperatorWithFixedSignature { struct PrivateConstructorTag {}; public: static absl::StatusOr<expr::ExprOperatorPtr> Make( absl::string_view name, expr::ExprOperatorSignature signature, absl::string_view doc, std::vector<QTypeConstraint> qtype_constraints, expr::ExprNodePtr qtype_inference_expr); BackendOperator(PrivateConstructorTag, absl::string_view name, expr::ExprOperatorSignature signature, absl::string_view doc, Fingerprint fingerprint, std::vector<QTypeConstraint> qtype_constraints, expr::ExprNodePtr qtype_inference_expr, QTypeInferenceFn qtype_inference_fn); absl::StatusOr<expr::ExprAttributes> InferAttributes( absl::Span<const expr::ExprAttributes> inputs) const override; const std::vector<QTypeConstraint>& qtype_constraints() const { return qtype_constraints_; } const expr::ExprNodePtr& qtype_inference_expr() const { return qtype_inference_expr_; } absl::string_view py_qvalue_specialization_key() const override; private: std::vector<QTypeConstraint> qtype_constraints_; expr::ExprNodePtr qtype_inference_expr_; QTypeInferenceFn qtype_inference_fn_; }; } #endif #include "arolla/expr/operator_loader/backend_operator.h" #include <memory> #include <set> #include <string> #include <utility> #include <vector> #include "absl/container/flat_hash_set.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_join.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "arolla/expr/basic_expr_operator.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_attributes.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/expr/operator_loader/parameter_qtypes.h" #include "arolla/expr/operator_loader/qtype_constraint.h" #include "arolla/expr/operator_loader/qtype_inference.h" #include "arolla/expr/qtype_utils.h" #include "arolla/util/fingerprint.h" #include "arolla/util/status_macros_backport.h" namespace arolla::operator_loader { using ::arolla::expr::ExprAttributes; using ::arolla::expr::ExprNodePtr; using ::arolla::expr::ExprOperatorPtr; using ::arolla::expr::ExprOperatorSignature; using ::arolla::expr::GetPlaceholderKeys; absl::StatusOr<ExprOperatorPtr> BackendOperator::Make( absl::string_view name, ExprOperatorSignature signature, absl::string_view doc, std::vector<QTypeConstraint> qtype_constraints, ExprNodePtr qtype_inference_expr) { RETURN_IF_ERROR(ValidateSignature(signature)); absl::flat_hash_set<absl::string_view> parameter_names; for (const auto& param : signature.parameters) { parameter_names.insert(param.name); } std::set<std::string> undefined_parameter_names; for (const auto& qtype_constraint : qtype_constraints) { for (auto&& placeholder_key : GetPlaceholderKeys(qtype_constraint.predicate_expr)) { if (!parameter_names.contains(placeholder_key)) { undefined_parameter_names.insert(std::move(placeholder_key)); } } } for (auto&& placeholder_key : GetPlaceholderKeys(qtype_inference_expr)) { if (!parameter_names.contains(placeholder_key)) { undefined_parameter_names.insert(std::move(placeholder_key)); } } if (!undefined_parameter_names.empty()) { return absl::InvalidArgumentError( "unexpected parameters: P." + absl::StrJoin(undefined_parameter_names, ", P.")); } ASSIGN_OR_RETURN( auto qtype_inference_fn, MakeQTypeInferenceFn(qtype_constraints, qtype_inference_expr)); FingerprintHasher hasher("::arolla::operator_loader::BackendOperator"); hasher.Combine(name, signature, doc, qtype_inference_expr->fingerprint(), qtype_constraints.size()); for (const auto& qtype_constraint : qtype_constraints) { hasher.Combine(qtype_constraint.predicate_expr->fingerprint(), qtype_constraint.error_message); } return std::make_shared<BackendOperator>( PrivateConstructorTag{}, name, std::move(signature), doc, std::move(hasher).Finish(), std::move(qtype_constraints), std::move(qtype_inference_expr), std::move(qtype_inference_fn)); } BackendOperator::BackendOperator(PrivateConstructorTag, absl::string_view name, ExprOperatorSignature signature, absl::string_view doc, Fingerprint fingerprint, std::vector<QTypeConstraint> qtype_constraints, ExprNodePtr qtype_inference_expr, QTypeInferenceFn qtype_inference_fn) : ExprOperatorWithFixedSignature(name, std::move(signature), doc, fingerprint), qtype_constraints_(std::move(qtype_constraints)), qtype_inference_expr_(std::move(qtype_inference_expr)), qtype_inference_fn_(std::move(qtype_inference_fn)) {} absl::StatusOr<ExprAttributes> BackendOperator::InferAttributes( absl::Span<const ExprAttributes> inputs) const { RETURN_IF_ERROR(ValidateOpInputsCount(inputs)); if (!HasAllAttrQTypes(inputs)) { return ExprAttributes{}; } ASSIGN_OR_RETURN( auto* output_qtype, qtype_inference_fn_(ExtractParameterQTypes(signature(), inputs))); return ExprAttributes(output_qtype); } absl::string_view BackendOperator::py_qvalue_specialization_key() const { return "::arolla::operator_loader::BackendOperator"; } }
#include "arolla/expr/operator_loader/backend_operator.h" #include <memory> #include <optional> #include <utility> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "arolla/array/array.h" #include "arolla/array/qtype/types.h" #include "arolla/dense_array/dense_array.h" #include "arolla/dense_array/qtype/types.h" #include "arolla/expr/eval/invoke.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/expr/operator_loader/qtype_constraint.h" #include "arolla/memory/optional_value.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/tuple_qtype.h" #include "arolla/util/init_arolla.h" #include "arolla/util/testing/status_matchers_backport.h" #include "arolla/util/unit.h" #include "arolla/util/status_macros_backport.h" namespace arolla::operator_loader { namespace { using ::arolla::expr::CallOp; using ::arolla::expr::ExprOperatorPtr; using ::arolla::expr::ExprOperatorSignature; using ::arolla::expr::Literal; using ::arolla::expr::Placeholder; using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::StatusIs; using ::testing::HasSubstr; class BackendOperatorTest : public ::testing::Test { protected: void SetUp() override { ASSERT_OK(InitArolla()); } absl::StatusOr<std::shared_ptr<const BackendOperator>> MakeOp() { ASSIGN_OR_RETURN(auto qtype_constraint_predicate_expr_1, CallOp("core.not_equal", {CallOp("qtype.get_scalar_qtype", {Placeholder("x")}), Literal(GetNothingQType())})); ASSIGN_OR_RETURN(auto qtype_constraint_predicate_expr_2, CallOp("core.not_equal", {CallOp("qtype.get_scalar_qtype", {Placeholder("y")}), Literal(GetNothingQType())})); ASSIGN_OR_RETURN( auto qtype_constraint_predicate_expr_3, CallOp("core.not_equal", {CallOp("qtype.broadcast_qtype_like", {Placeholder("y"), Placeholder("x")}), Literal(GetNothingQType())})); std::vector<QTypeConstraint> qtype_constraints = { {qtype_constraint_predicate_expr_1, "expected `x` to be a scalar based type, got {x}"}, {qtype_constraint_predicate_expr_2, "expected `y` to be a UNIT based type, got {y}"}, {qtype_constraint_predicate_expr_3, "incompatible types x:{x} and y:{y}"}, }; ASSIGN_OR_RETURN(auto qtype_inference_expr, CallOp("qtype.broadcast_qtype_like", {Placeholder("y"), Placeholder("x")})); ASSIGN_OR_RETURN( auto op, BackendOperator::Make( "core.presence_and", ExprOperatorSignature{{"x"}, {"y"}}, "presence-and-doc-string", std::move(qtype_constraints), std::move(qtype_inference_expr))); return std::dynamic_pointer_cast<const BackendOperator>(op); } }; TEST_F(BackendOperatorTest, GetDoc) { ASSERT_OK_AND_ASSIGN(auto op, MakeOp()); ASSERT_THAT(op.get()->doc(), "presence-and-doc-string"); ASSERT_THAT(op->GetDoc(), IsOkAndHolds("presence-and-doc-string")); } TEST_F(BackendOperatorTest, QTypeInference) { { ASSERT_OK_AND_ASSIGN(auto expr, CallOp(MakeOp(), {Literal(1.5f), Literal(kUnit)})); EXPECT_EQ(expr->qtype(), GetQType<float>()); } { ASSERT_OK_AND_ASSIGN( auto expr, CallOp(MakeOp(), {Literal(1.5f), Literal(OptionalValue<Unit>())})); EXPECT_EQ(expr->qtype(), GetQType<OptionalValue<float>>()); } } TEST_F(BackendOperatorTest, QTypeConstraint) { EXPECT_THAT( CallOp(MakeOp(), {Literal(MakeTupleFromFields()), Literal(kUnit)}), StatusIs( absl::StatusCode::kInvalidArgument, HasSubstr("expected `x` to be a scalar based type, got tuple<>"))); EXPECT_THAT( CallOp(MakeOp(), {Literal(1.5f), Literal(MakeTupleFromFields())}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("expected `y` to be a UNIT based type, got tuple<>"))); EXPECT_THAT( CallOp(MakeOp(), {Literal(Array<float>()), Literal(DenseArray<Unit>())}), StatusIs( absl::StatusCode::kInvalidArgument, HasSubstr( "incompatible types x:ARRAY_FLOAT32 and y:DENSE_ARRAY_UNIT"))); } TEST_F(BackendOperatorTest, Eval) { ASSERT_OK_AND_ASSIGN( auto expr, CallOp(MakeOp(), {Literal(1.5f), Literal(OptionalValue<Unit>())})); ASSERT_OK_AND_ASSIGN(auto result_tv, Invoke(expr, {})); ASSERT_OK_AND_ASSIGN(auto result, result_tv.As<OptionalValue<float>>()); EXPECT_EQ(result.get(), std::nullopt); } TEST_F(BackendOperatorTest, UnexpectedParameters) { ASSERT_OK_AND_ASSIGN(auto op, MakeOp()); auto& backend_op = dynamic_cast<const BackendOperator&>(*op); EXPECT_THAT(BackendOperator::Make("core.presence_and", ExprOperatorSignature{{"a"}, {"b"}}, "docstring", backend_op.qtype_constraints(), backend_op.qtype_inference_expr()), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("unexpected parameters: P.x, P.y"))); } } }
2,459
#ifndef AROLLA_EXPR_OPERATOR_LOADER_GENERIC_OPERATOR_H_ #define AROLLA_EXPR_OPERATOR_LOADER_GENERIC_OPERATOR_H_ #include <cstdint> #include <memory> #include <string> #include <vector> #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "arolla/expr/basic_expr_operator.h" #include "arolla/expr/expr_attributes.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/expr/operator_loader/generic_operator_overload_condition.h" #include "arolla/expr/registered_expr_operator.h" #include "arolla/util/thread_safe_shared_ptr.h" namespace arolla::operator_loader { constexpr absl::string_view kGenericOperatorPreparedOverloadConditionLeafKey = "input_tuple_qtype"; class GenericOperator final : public ::arolla::expr::ExprOperatorWithFixedSignature { struct PrivateConstructorTag {}; public: static absl::StatusOr<std::shared_ptr<GenericOperator>> Make( absl::string_view name, ::arolla::expr::ExprOperatorSignature signature, absl::string_view doc); GenericOperator(PrivateConstructorTag, absl::string_view name, ::arolla::expr::ExprOperatorSignature signature, absl::string_view doc); absl::string_view namespace_for_overloads() const { return display_name(); } absl::StatusOr<::arolla::expr::ExprAttributes> InferAttributes( absl::Span<const ::arolla::expr::ExprAttributes> inputs) const final; absl::StatusOr<::arolla::expr::ExprNodePtr> ToLowerLevel( const ::arolla::expr::ExprNodePtr& node) const final; absl::string_view py_qvalue_specialization_key() const final; private: struct SnapshotOfOverloads { int64_t revision_id; std::vector<::arolla::expr::RegisteredOperatorPtr> overloads; GenericOperatorOverloadConditionFn overload_condition_fn; }; using SnapshotOfOverloadsPtr = std::shared_ptr<SnapshotOfOverloads>; absl::StatusOr<SnapshotOfOverloadsPtr> BuildSnapshot() const; absl::StatusOr<SnapshotOfOverloadsPtr> GetSnapshot() const; absl::StatusOr<::arolla::expr::ExprOperatorPtr > GetOverload( absl::Span<const ::arolla::expr::ExprAttributes> inputs) const; ::arolla::expr::ExprOperatorRegistry::RevisionIdFn revision_id_fn_; mutable ThreadSafeSharedPtr<SnapshotOfOverloads> snapshot_of_overloads_; }; class GenericOperatorOverload final : public ::arolla::expr::ExprOperator { struct PrivateConstructorTag {}; public: static absl::StatusOr<std::shared_ptr<GenericOperatorOverload>> Make( ::arolla::expr::ExprOperatorPtr base_operator, ::arolla::expr::ExprNodePtr prepared_overload_condition_expr); GenericOperatorOverload( PrivateConstructorTag, ::arolla::expr::ExprOperatorPtr base_operator, ::arolla::expr::ExprNodePtr prepared_overload_condition_expr); const ::arolla::expr::ExprNodePtr& prepared_overload_condition_expr() const { return prepared_overload_condition_expr_; } const ::arolla::expr::ExprOperatorPtr& base_operator() const { return base_operator_; } absl::StatusOr<::arolla::expr::ExprOperatorSignature> GetSignature() const final { return base_operator_->GetSignature(); } absl::StatusOr<std::string> GetDoc() const final { return base_operator_->GetDoc(); } absl::StatusOr<::arolla::expr::ExprAttributes> InferAttributes( absl::Span<const ::arolla::expr::ExprAttributes> inputs) const final { return base_operator_->InferAttributes(inputs); } absl::StatusOr<::arolla::expr::ExprNodePtr> ToLowerLevel( const ::arolla::expr::ExprNodePtr& node) const final; absl::string_view py_qvalue_specialization_key() const final; private: ::arolla::expr::ExprOperatorPtr base_operator_; ::arolla::expr::ExprNodePtr prepared_overload_condition_expr_; }; } #endif #include "arolla/expr/operator_loader/generic_operator.h" #include <algorithm> #include <cstddef> #include <memory> #include <set> #include <string> #include <utility> #include <vector> #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/escaping.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" #include "absl/strings/str_join.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "arolla/expr/basic_expr_operator.h" #include "arolla/expr/expr_attributes.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/expr/expr_visitor.h" #include "arolla/expr/operator_loader/generic_operator_overload_condition.h" #include "arolla/expr/qtype_utils.h" #include "arolla/expr/registered_expr_operator.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/tuple_qtype.h" #include "arolla/util/demangle.h" #include "arolla/util/fast_dynamic_downcast_final.h" #include "arolla/util/fingerprint.h" #include "arolla/util/string.h" #include "arolla/util/status_macros_backport.h" namespace arolla::operator_loader { namespace { using ::arolla::expr::ExprAttributes; using ::arolla::expr::ExprNode; using ::arolla::expr::ExprNodePtr; using ::arolla::expr::ExprOperatorPtr; using ::arolla::expr::ExprOperatorRegistry; using ::arolla::expr::ExprOperatorSignature; using ::arolla::expr::GetExprAttrs; using ::arolla::expr::PostOrder; using ::arolla::expr::RegisteredOperator; using ::arolla::expr::RegisteredOperatorPtr; using Param = ExprOperatorSignature::Parameter; std::string FormatSignatureQTypes( const ExprOperatorSignature& signature, absl::Span<QType const* const > input_qtypes) { std::string result; bool skip_first_comma = true; size_t i = 0; for (const auto& param : signature.parameters) { switch (param.kind) { case Param::Kind::kPositionalOrKeyword: DCHECK_LT(i, input_qtypes.size()); if (auto* input_qtype = input_qtypes[i++]) { absl::StrAppend(&result, NonFirstComma(skip_first_comma), param.name, ": ", input_qtype->name()); } else { absl::StrAppend(&result, NonFirstComma(skip_first_comma), param.name); } break; case Param::Kind::kVariadicPositional: absl::StrAppend(&result, NonFirstComma(skip_first_comma), "*", param.name, ": ("); for (bool first = true; i < input_qtypes.size(); ++i) { absl::StrAppend(&result, NonFirstComma(first), input_qtypes[i] ? input_qtypes[i]->name() : "-"); } absl::StrAppend(&result, ")"); break; } } return result; } } absl::StatusOr<std::shared_ptr<GenericOperator>> GenericOperator::Make( absl::string_view name, ExprOperatorSignature signature, absl::string_view doc) { if (!IsQualifiedIdentifier(name)) { return absl::InvalidArgumentError(absl::StrFormat( "expected a operator name to be a valid namespace name, got '%s'", absl::CEscape(name))); } RETURN_IF_ERROR(ValidateSignature(signature)); for (const auto& param : signature.parameters) { if (param.kind != Param::Kind::kPositionalOrKeyword && param.kind != Param::Kind::kVariadicPositional) { return absl::InvalidArgumentError( absl::StrCat("unsupported parameter kind '", param.name, "', ", static_cast<int>(param.kind))); } } return std::make_shared<GenericOperator>(PrivateConstructorTag{}, name, std::move(signature), doc); } GenericOperator::GenericOperator( PrivateConstructorTag, absl::string_view name, ::arolla::expr::ExprOperatorSignature signature, absl::string_view doc) : ExprOperatorWithFixedSignature( name, signature, doc, FingerprintHasher("::arolla::operator_loader::GenericOperator") .Combine(name, signature, doc) .Finish()), revision_id_fn_( ExprOperatorRegistry::GetInstance()->AcquireRevisionIdFn(name)) {} absl::StatusOr<ExprAttributes> GenericOperator::InferAttributes( absl::Span<const ExprAttributes> inputs) const { RETURN_IF_ERROR(ValidateOpInputsCount(inputs)); ASSIGN_OR_RETURN(auto overload, GetOverload(inputs)); if (overload == nullptr) { return ExprAttributes{}; } return overload->InferAttributes(inputs); } absl::StatusOr<::arolla::expr::ExprNodePtr> GenericOperator::ToLowerLevel( const ::arolla::expr::ExprNodePtr& node) const { RETURN_IF_ERROR(ValidateNodeDepsCount(*node)); ASSIGN_OR_RETURN(auto overload, GetOverload(GetExprAttrs(node->node_deps()))); if (overload == nullptr) { return node; } return ExprNode::UnsafeMakeOperatorNode(std::move(overload), std::vector(node->node_deps()), ExprAttributes(node->attr())); } absl::StatusOr<GenericOperator::SnapshotOfOverloadsPtr> GenericOperator::BuildSnapshot() const { const auto& ns = namespace_for_overloads(); const auto& registry = *ExprOperatorRegistry::GetInstance(); const auto revision_id = revision_id_fn_(); std::vector<RegisteredOperatorPtr> overloads; std::vector<ExprNodePtr> condition_exprs; for (const auto& operator_name : registry.ListRegisteredOperators()) { if (!(ns.size() < operator_name.size() && std::equal(ns.begin(), ns.end(), operator_name.begin()) && operator_name[ns.size()] == '.')) { continue; } auto registered_overload = registry.LookupOperatorOrNull(operator_name); if (registered_overload == nullptr) { continue; } auto overload = DecayRegisteredOperator(registered_overload) .value_or(ExprOperatorPtr{}); if (overload == nullptr) { continue; } auto* typed_overload = fast_dynamic_downcast_final<const GenericOperatorOverload*>( overload.get()); if (typed_overload == nullptr) { return absl::FailedPreconditionError( absl::StrFormat("expected a GenericOperatorOverload, got %s: %s", TypeName(typeid(*overload)), operator_name)); } overloads.push_back(registered_overload); condition_exprs.push_back( typed_overload->prepared_overload_condition_expr()); } ASSIGN_OR_RETURN( auto condition_fn, MakeGenericOperatorOverloadConditionFn(condition_exprs), _ << "failed to compile overload conditions of generic operator " << display_name()); auto result = std::make_shared<SnapshotOfOverloads>(); result->overloads = std::move(overloads); result->overload_condition_fn = std::move(condition_fn); result->revision_id = revision_id; return result; } absl::StatusOr<GenericOperator::SnapshotOfOverloadsPtr> GenericOperator::GetSnapshot() const { auto result = snapshot_of_overloads_.load(); if (result != nullptr && result->revision_id == revision_id_fn_()) { return result; } ASSIGN_OR_RETURN(result, BuildSnapshot()); snapshot_of_overloads_.store(result); return result; } absl::StatusOr<ExprOperatorPtr > GenericOperator::GetOverload( absl::Span<const ::arolla::expr::ExprAttributes> inputs) const { ASSIGN_OR_RETURN(auto snapshot, GetSnapshot()); auto input_qtypes = GetAttrQTypes(inputs); for (auto& input_qtype : input_qtypes) { if (input_qtype == nullptr) { input_qtype = GetNothingQType(); } } ASSIGN_OR_RETURN(auto overload_conditions, snapshot->overload_condition_fn( MakeTupleQType(input_qtypes))); const auto& overloads = snapshot->overloads; DCHECK_EQ(overload_conditions.size(), overloads.size()); auto it = std::find(overload_conditions.begin(), overload_conditions.end(), true); if (it == overload_conditions.end()) { if (HasAllAttrQTypes(inputs)) { return absl::InvalidArgumentError(absl::StrCat( "no matching overload [", FormatSignatureQTypes(signature(), GetAttrQTypes(inputs)), "]")); } return nullptr; } auto jt = std::find(it + 1, overload_conditions.end(), true); if (jt == overload_conditions.end()) { return overloads[it - overload_conditions.begin()]; } std::set<absl::string_view> ambiguous_overload_names = { overloads[it - overload_conditions.begin()]->display_name(), overloads[jt - overload_conditions.begin()]->display_name(), }; for (;;) { jt = std::find(jt + 1, overload_conditions.end(), true); if (jt == overload_conditions.end()) { break; } ambiguous_overload_names.insert( overloads[jt - overload_conditions.begin()]->display_name()); } return absl::InvalidArgumentError(absl::StrCat( "ambiguous overloads: ", absl::StrJoin(ambiguous_overload_names, ", "), " [", FormatSignatureQTypes(signature(), GetAttrQTypes(inputs)), "]")); } absl::string_view GenericOperator::py_qvalue_specialization_key() const { return "::arolla::operator_loader::GenericOperator"; } absl::StatusOr<std::shared_ptr<GenericOperatorOverload>> GenericOperatorOverload::Make(ExprOperatorPtr base_operator, ExprNodePtr prepared_overload_condition_expr) { if (base_operator == nullptr) { return absl::InvalidArgumentError("base_operator==nullptr"); } if (prepared_overload_condition_expr == nullptr) { return absl::InvalidArgumentError( "prepared_overload_condition_expr==nullptr"); } std::set<absl::string_view> leaf_keys; std::set<absl::string_view> placeholder_keys; PostOrder post_order(prepared_overload_condition_expr); for (const auto& node : post_order.nodes()) { if (node->is_leaf()) { leaf_keys.insert(node->leaf_key()); } else if (node->is_placeholder()) { placeholder_keys.insert(node->placeholder_key()); } } leaf_keys.erase(kGenericOperatorPreparedOverloadConditionLeafKey); if (!placeholder_keys.empty()) { return absl::InvalidArgumentError(absl::StrCat( "prepared overload condition contains unexpected placeholders: P.", absl::StrJoin(placeholder_keys, ", P."))); } if (!leaf_keys.empty()) { return absl::InvalidArgumentError(absl::StrCat( "prepared overload condition contains unexpected leaves: L.", absl::StrJoin(leaf_keys, ", L."))); } return std::make_shared<GenericOperatorOverload>( PrivateConstructorTag{}, std::move(base_operator), std::move(prepared_overload_condition_expr)); } GenericOperatorOverload::GenericOperatorOverload( PrivateConstructorTag, ExprOperatorPtr base_operator, ExprNodePtr prepared_overload_condition_expr) : ExprOperator(base_operator->display_name(), FingerprintHasher( "::arolla::operator_loader::GenericOperatorOverload") .Combine(base_operator->fingerprint(), prepared_overload_condition_expr->fingerprint()) .Finish()), base_operator_(std::move(base_operator)), prepared_overload_condition_expr_( std::move(prepared_overload_condition_expr)) {} absl::StatusOr<::arolla::expr::ExprNodePtr> GenericOperatorOverload::ToLowerLevel( const ::arolla::expr::ExprNodePtr& node) const { auto new_node = ExprNode::UnsafeMakeOperatorNode( ExprOperatorPtr(base_operator_), std::vector(node->node_deps()), ExprAttributes(node->attr())); return base_operator_->ToLowerLevel(new_node); } absl::string_view GenericOperatorOverload::py_qvalue_specialization_key() const { return "::arolla::operator_loader::GenericOperatorOverload"; } }
#include "arolla/expr/operator_loader/generic_operator.h" #include <memory> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_attributes.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/expr/lambda_expr_operator.h" #include "arolla/expr/registered_expr_operator.h" #include "arolla/expr/testing/test_operators.h" #include "arolla/expr/testing/testing.h" #include "arolla/memory/optional_value.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/testing/qtype.h" #include "arolla/util/init_arolla.h" #include "arolla/util/testing/status_matchers_backport.h" #include "arolla/util/unit.h" namespace arolla::operator_loader { namespace { using ::arolla::expr::CallOp; using ::arolla::expr::ExprAttributes; using ::arolla::expr::ExprNode; using ::arolla::expr::ExprOperatorPtr; using ::arolla::expr::ExprOperatorSignature; using ::arolla::expr::Leaf; using ::arolla::expr::Literal; using ::arolla::expr::MakeLambdaOperator; using ::arolla::expr::Placeholder; using ::arolla::expr::SuppressUnusedWarning; using ::arolla::expr::ToLowest; using ::arolla::expr::testing::DummyOp; using ::arolla::testing::EqualsExpr; using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::StatusIs; using ::arolla::testing::TypedValueWith; using ::testing::HasSubstr; using ::testing::Optional; using ::testing::Truly; auto EqualsAttr(const ExprAttributes& expected_attr) { return Truly([expected_attr](const ExprAttributes& actual_attr) { return actual_attr.IsIdenticalTo(expected_attr); }); } class GenericOperatorOverloadTest : public ::testing::Test { protected: void SetUp() override { ASSERT_OK(InitArolla()); } static absl::StatusOr<ExprOperatorPtr> GetFirstOperator() { return MakeLambdaOperator( "get_left", ExprOperatorSignature{{"left"}, {"right"}}, SuppressUnusedWarning("right", Placeholder("left")), "doc-string-for-get-left"); } }; TEST_F(GenericOperatorOverloadTest, Make) { ASSERT_OK_AND_ASSIGN(auto base_operator, GetFirstOperator()); ASSERT_OK_AND_ASSIGN( auto prepared_overload_condition_expr, CallOp("core.not_equal", {CallOp("core.get_nth", {Leaf("input_tuple_qtype"), Literal(0)}), Literal(GetNothingQType())})); ASSERT_OK_AND_ASSIGN( auto op, GenericOperatorOverload::Make(base_operator, prepared_overload_condition_expr)); EXPECT_EQ(op->base_operator(), base_operator); EXPECT_EQ(op->prepared_overload_condition_expr().get(), prepared_overload_condition_expr.get()); EXPECT_EQ(op->display_name(), "get_left"); EXPECT_THAT(op->GetDoc(), IsOkAndHolds("doc-string-for-get-left")); EXPECT_THAT(op->InferAttributes({ExprAttributes{}, ExprAttributes{}}), IsOkAndHolds(EqualsAttr(ExprAttributes{}))); ASSERT_OK_AND_ASSIGN(auto expr, CallOp(op, {Leaf("x"), Leaf("y")})); EXPECT_THAT(ToLowest(expr), IsOkAndHolds(EqualsExpr(Leaf("x")))); } TEST_F(GenericOperatorOverloadTest, Make_ErrorUnexpectedPlaceholder) { ASSERT_OK_AND_ASSIGN(auto base_operator, GetFirstOperator()); ASSERT_OK_AND_ASSIGN( auto prepared_overload_condition_expr, CallOp("core.not_equal", {Placeholder("left"), Placeholder("right")})); EXPECT_THAT(GenericOperatorOverload::Make(base_operator, prepared_overload_condition_expr), StatusIs(absl::StatusCode::kInvalidArgument, "prepared overload condition contains unexpected " "placeholders: P.left, P.right")); } TEST_F(GenericOperatorOverloadTest, Make_ErrorUnexpectedLeaves) { ASSERT_OK_AND_ASSIGN(auto base_operator, GetFirstOperator()); ASSERT_OK_AND_ASSIGN( auto prepared_overload_condition_expr, CallOp("core.make_tuple", {Leaf("input_tuple_qtype"), Leaf("left"), Leaf("right")})); EXPECT_THAT(GenericOperatorOverload::Make(base_operator, prepared_overload_condition_expr), StatusIs(absl::StatusCode::kInvalidArgument, "prepared overload condition contains unexpected " "leaves: L.left, L.right")); } TEST_F(GenericOperatorOverloadTest, ToLowerLevelOptimization) { auto base_operator = std::make_shared<DummyOp>("base_op", ExprOperatorSignature{{"x"}, {"y"}}); ASSERT_OK_AND_ASSIGN( auto prepared_overload_condition_expr, CallOp("core.not_equal", {CallOp("core.get_nth", {Leaf("input_tuple_qtype"), Literal(0)}), Literal(GetNothingQType())})); ASSERT_OK_AND_ASSIGN( auto op, GenericOperatorOverload::Make(base_operator, prepared_overload_condition_expr)); auto expr = ExprNode::UnsafeMakeOperatorNode( op, {Leaf("x"), Leaf("y")}, ExprAttributes(GetQType<float>())); auto expected_expr = ExprNode::UnsafeMakeOperatorNode( base_operator, {Leaf("x"), Leaf("y")}, ExprAttributes(GetQType<float>())); EXPECT_THAT(ToLowest(expr), IsOkAndHolds(EqualsExpr(expected_expr))); } TEST_F(GenericOperatorOverloadTest, BadBaseOperatorNullptr) { EXPECT_THAT( GenericOperatorOverload::Make(nullptr, Literal(OptionalUnit(false))), StatusIs(absl::StatusCode::kInvalidArgument)); } TEST_F(GenericOperatorOverloadTest, BadConditionExprNullptr) { ASSERT_OK_AND_ASSIGN(auto op, MakeLambdaOperator(Placeholder("x"))); EXPECT_THAT(GenericOperatorOverload::Make(op, nullptr), StatusIs(absl::StatusCode::kInvalidArgument)); } class GenericOperatorTest : public ::testing::Test { protected: void SetUp() override { ASSERT_OK(InitArolla()); } }; TEST_F(GenericOperatorTest, CommonCase) { ASSERT_OK_AND_ASSIGN( auto base_op_1, MakeLambdaOperator("generic_operator_test.common_case.is_unit._.negative", ExprOperatorSignature{{"_x"}}, Literal(OptionalUnit(false)))); ASSERT_OK_AND_ASSIGN( auto prepared_condition_1, CallOp("core.presence_and", {CallOp("core.not_equal", {CallOp("qtype.get_field_qtype", {Leaf("input_tuple_qtype"), Literal(0)}), Literal(GetNothingQType())}), CallOp("core.not_equal", {CallOp("qtype.get_field_qtype", {Leaf("input_tuple_qtype"), Literal(0)}), Literal(GetQType<Unit>())})})); ASSERT_OK_AND_ASSIGN(auto op_1, GenericOperatorOverload::Make( base_op_1, prepared_condition_1)); ASSERT_OK_AND_ASSIGN( auto base_op_2, MakeLambdaOperator("generic_operator_test.common_case.is_unit._.positive", ExprOperatorSignature{{"_x"}}, Literal(OptionalUnit(true)))); ASSERT_OK_AND_ASSIGN( auto prepared_condition_2, CallOp("core.equal", {CallOp("qtype.get_field_qtype", {Leaf("input_tuple_qtype"), Literal(0)}), Literal(GetQType<Unit>())})); ASSERT_OK_AND_ASSIGN(auto op_2, GenericOperatorOverload::Make( base_op_2, prepared_condition_2)); ASSERT_OK(RegisterOperator( "generic_operator_test.common_case.is_unit._.negative", op_1)); ASSERT_OK(RegisterOperator( "generic_operator_test.common_case.is_unit._.positive", op_2)); ASSERT_OK_AND_ASSIGN(auto op, GenericOperator::Make( "generic_operator_test.common_case.is_unit", ExprOperatorSignature{{"x"}}, "doc-string")); EXPECT_EQ(op->display_name(), "generic_operator_test.common_case.is_unit"); EXPECT_EQ(op->namespace_for_overloads(), "generic_operator_test.common_case.is_unit"); EXPECT_EQ(op->doc(), "doc-string"); { ASSERT_OK_AND_ASSIGN(auto expr, CallOp(op, {Leaf("x")})); EXPECT_EQ(expr->qtype(), nullptr); EXPECT_THAT(ToLowerNode(expr), IsOkAndHolds(EqualsExpr(expr))); } { ASSERT_OK_AND_ASSIGN(auto expr, CallOp(op, {Literal(Unit())})); ASSERT_OK_AND_ASSIGN( auto expected_lower_node, CallOp("generic_operator_test.common_case.is_unit._.positive", {Literal(Unit())})); EXPECT_THAT(expr->qvalue(), Optional(TypedValueWith<OptionalUnit>(OptionalUnit(true)))); EXPECT_THAT(ToLowerNode(expr), IsOkAndHolds(EqualsExpr(expected_lower_node))); } { ASSERT_OK_AND_ASSIGN(auto expr, CallOp(op, {Literal(1)})); ASSERT_OK_AND_ASSIGN( auto expected_lower_node, CallOp("generic_operator_test.common_case.is_unit._.negative", {Literal(1)})); EXPECT_THAT(expr->qvalue(), Optional(TypedValueWith<OptionalUnit>(OptionalUnit(false)))); EXPECT_THAT(ToLowerNode(expr), IsOkAndHolds(EqualsExpr(expected_lower_node))); } } TEST_F(GenericOperatorTest, BadSignature) { ExprOperatorSignature sig{{"x"}, {"x"}}; EXPECT_THAT(GenericOperator::Make("foo", sig, ""), StatusIs(absl::StatusCode::kInvalidArgument)); } TEST_F(GenericOperatorTest, BadNamespace) { ExprOperatorSignature sig{{"x"}}; EXPECT_THAT(GenericOperator::Make(" StatusIs(absl::StatusCode::kInvalidArgument)); } TEST_F(GenericOperatorTest, FailOverloadMatch) { ASSERT_OK_AND_ASSIGN( auto base_op, MakeLambdaOperator("generic_operator_test.fail_overload_match.op._n", Placeholder("x"))); ASSERT_OK_AND_ASSIGN( auto prepared_condition, CallOp("core.presence_and", {CallOp("core.not_equal", {CallOp("qtype.get_field_qtype", {Leaf("input_tuple_qtype"), Literal(0)}), Literal(GetNothingQType())}), CallOp("core.not_equal", {CallOp("qtype.get_field_qtype", {Leaf("input_tuple_qtype"), Literal(0)}), Literal(GetQType<Unit>())})})); ASSERT_OK_AND_ASSIGN( auto op_n, GenericOperatorOverload::Make(base_op, prepared_condition)); ASSERT_OK(RegisterOperator("generic_operator_test.fail_overload_match.op._1", op_n)); ASSERT_OK(RegisterOperator("generic_operator_test.fail_overload_match.op._2", op_n)); ASSERT_OK(RegisterOperator("generic_operator_test.fail_overload_match.op._3", op_n)); ASSERT_OK_AND_ASSIGN( auto op, GenericOperator::Make("generic_operator_test.fail_overload_match.op", ExprOperatorSignature{{"x"}}, "")); { ASSERT_OK_AND_ASSIGN(auto expr, CallOp(op, {Leaf("x")})); EXPECT_EQ(expr->qtype(), nullptr); EXPECT_THAT(ToLowerNode(expr), IsOkAndHolds(EqualsExpr(expr))); } { EXPECT_THAT(CallOp(op, {Literal(Unit())}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("no matching overload [x: UNIT]"))); } { EXPECT_THAT( CallOp(op, {Literal(1)}), StatusIs( absl::StatusCode::kInvalidArgument, HasSubstr( "ambiguous overloads: " "generic_operator_test.fail_overload_match.op._1, " "generic_operator_test.fail_overload_match.op._2, " "generic_operator_test.fail_overload_match.op._3 [x: INT32]"))); } } TEST_F(GenericOperatorTest, BadOverloadOperator) { ASSERT_OK_AND_ASSIGN( auto op_n, MakeLambdaOperator("generic_operator_test.bad_overload.op._n", Placeholder("x"))); ASSERT_OK(RegisterOperator("generic_operator_test.bad_overload.op._n", op_n)); ASSERT_OK_AND_ASSIGN( auto op, GenericOperator::Make("generic_operator_test.bad_overload.op", ExprOperatorSignature{{"x"}}, "")); { EXPECT_THAT( CallOp(op, {Literal(Unit())}), StatusIs(absl::StatusCode::kFailedPrecondition, HasSubstr("expected a GenericOperatorOverload, got " "arolla::expr::LambdaOperator: " "generic_operator_test.bad_overload.op._n"))); } } TEST_F(GenericOperatorTest, FormatSignatureQTypes) { ASSERT_OK_AND_ASSIGN(auto sig, ExprOperatorSignature::Make("x, y, *z")); ASSERT_OK_AND_ASSIGN( auto op, GenericOperator::Make("generic_operator_test.format_sig_qtypes", sig, "")); EXPECT_OK(CallOp(op, {Leaf("x"), Leaf("x")})); EXPECT_THAT( CallOp(op, {Literal(Unit()), Literal(1)}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("no matching overload [x: UNIT, y: INT32, *z: ()]"))); EXPECT_THAT( CallOp(op, {Literal(Unit()), Literal(1), Literal(1.5f)}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr( "no matching overload [x: UNIT, y: INT32, *z: (FLOAT32)]"))); EXPECT_THAT( CallOp(op, {Literal(Unit()), Literal(1), Literal(1.5f)}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr( "no matching overload [x: UNIT, y: INT32, *z: (FLOAT32)]"))); EXPECT_THAT( CallOp(op, {Literal(Unit()), Literal(1), Literal(1.5f), Literal(2.5)}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("no matching overload [x: UNIT, y: INT32, *z: " "(FLOAT32, FLOAT64)]"))); } } }
2,460
#ifndef AROLLA_EXPR_OPERATOR_LOADER_QTYPE_CONSTRAINT_H_ #define AROLLA_EXPR_OPERATOR_LOADER_QTYPE_CONSTRAINT_H_ #include <functional> #include <string> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/types/span.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/operator_loader/parameter_qtypes.h" namespace arolla::operator_loader { struct QTypeConstraint { expr::ExprNodePtr predicate_expr; std::string error_message; }; using QTypeConstraintFn = std::function<absl::Status(const ParameterQTypes& qtypes)>; absl::StatusOr<QTypeConstraintFn> MakeQTypeConstraintFn( absl::Span<const QTypeConstraint> constraints); } #endif #include "arolla/expr/operator_loader/qtype_constraint.h" #include <cstddef> #include <functional> #include <string> #include <utility> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "absl/strings/str_join.h" #include "absl/strings/str_replace.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "arolla/expr/eval/thread_safe_model_executor.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_debug_string.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/operator_loader/helper.h" #include "arolla/expr/operator_loader/parameter_qtypes.h" #include "arolla/expr/qtype_utils.h" #include "arolla/expr/tuple_expr_operator.h" #include "arolla/memory/optional_value.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/tuple_qtype.h" #include "arolla/qtype/typed_value.h" #include "arolla/util/status_macros_backport.h" namespace arolla::operator_loader { namespace { using ::arolla::expr::BindOp; using ::arolla::expr::ExprNodePtr; using ::arolla::expr::GetLeafKeys; using ::arolla::expr::MakeTupleOperator; using ::arolla::expr::PopulateQTypes; using ::arolla::expr::ToDebugString; using QTypeConstraintPredicateFn = std::function<absl::StatusOr<OptionalUnit>(const ParameterQTypes& qtypes)>; absl::StatusOr<ExprNodePtr> NormalizeQTypeConstraintPredicateExpr( ExprNodePtr expr) { ASSIGN_OR_RETURN(auto result, ReplacePlaceholdersWithLeaves(expr)); absl::flat_hash_map<std::string, QTypePtr> leaf_qtypes; for (const auto& leaf_key : GetLeafKeys(result)) { leaf_qtypes[leaf_key] = GetQTypeQType(); } const QType* output_qtype = nullptr; if (auto annotated_expr = PopulateQTypes(result, leaf_qtypes); annotated_expr.ok()) { output_qtype = (*annotated_expr)->qtype(); } if (output_qtype == GetQType<OptionalUnit>()) { return result; } if (output_qtype == nullptr) { return absl::InvalidArgumentError( "Error while computing output QType of a QType constraint predicate: " + ToDebugString(expr)); } return absl::InvalidArgumentError(absl::StrFormat( "expected a constraint predicate to return %s, got %s: %s", GetQType<OptionalUnit>()->name(), output_qtype->name(), ToDebugString(expr))); } std::string FormatQTypeNames(absl::string_view message, const ParameterQTypes& parameter_qtypes) { absl::flat_hash_map<std::string, std::string> replacements; replacements.reserve(parameter_qtypes.size()); for (const auto& [param_name, param_qtype] : parameter_qtypes) { replacements[absl::StrFormat("{%s}", param_name)] = std::string(param_qtype->name()); if (IsTupleQType(param_qtype)) { replacements[absl::StrFormat("{*%s}", param_name)] = "(" + absl::StrJoin(param_qtype->type_fields(), ", ", [](std::string* out, const auto& field_slot) { const absl::string_view name = field_slot.GetType()->name(); out->append(name.data(), name.size()); }) + ")"; } } return absl::StrReplaceAll(message, replacements); } } absl::StatusOr<QTypeConstraintFn> MakeQTypeConstraintFn( absl::Span<const QTypeConstraint> constraints) { if (constraints.empty()) { return [](const ParameterQTypes&) { return absl::OkStatus(); }; } std::vector<ExprNodePtr> predicate_exprs; std::vector<std::string> error_messages; predicate_exprs.reserve(constraints.size()); error_messages.reserve(constraints.size()); for (const auto& constraint : constraints) { ASSIGN_OR_RETURN(auto predicate_expr, NormalizeQTypeConstraintPredicateExpr( constraint.predicate_expr)); predicate_exprs.emplace_back(std::move(predicate_expr)); error_messages.emplace_back(constraint.error_message); } ASSIGN_OR_RETURN(auto expr, BindOp(MakeTupleOperator::Make(), predicate_exprs, {})); ASSIGN_OR_RETURN(auto executor, MakeParameterQTypeModelExecutor(expr)); return [executor = std::move(executor), error_messages = std::move(error_messages)]( const ParameterQTypes& parameter_qtypes) -> absl::Status { ASSIGN_OR_RETURN(auto values, executor(parameter_qtypes)); DCHECK(IsTupleQType(values.GetType())); DCHECK(values.GetFieldCount() == error_messages.size()); for (size_t i = 0; i < error_messages.size(); ++i) { ASSIGN_OR_RETURN(OptionalUnit value, values.GetField(i).As<OptionalUnit>()); if (!value) { return absl::InvalidArgumentError( FormatQTypeNames(error_messages[i], parameter_qtypes)); } } return absl::OkStatus(); }; } }
#include "arolla/expr/operator_loader/qtype_constraint.h" #include <cstdint> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "arolla/expr/expr.h" #include "arolla/memory/optional_value.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/shape_qtype.h" #include "arolla/qtype/tuple_qtype.h" #include "arolla/util/bytes.h" #include "arolla/util/init_arolla.h" #include "arolla/util/testing/status_matchers_backport.h" #include "arolla/util/status_macros_backport.h" namespace arolla::operator_loader { namespace { using ::arolla::expr::CallOp; using ::arolla::expr::Literal; using ::arolla::expr::Placeholder; using ::arolla::testing::IsOk; using ::arolla::testing::StatusIs; using ::testing::HasSubstr; class QTypeConstraintTest : public ::testing::Test { protected: void SetUp() override { ASSERT_OK(InitArolla()); } static absl::StatusOr<QTypeConstraintFn> SampleConstraintFn() { ASSIGN_OR_RETURN(auto x_is_scalar_qtype_expr, CallOp("qtype.is_scalar_qtype", {Placeholder("x")})); ASSIGN_OR_RETURN(auto y_is_scalar_qtype_expr, CallOp("qtype.is_scalar_qtype", {Placeholder("y")})); ASSIGN_OR_RETURN( auto x_y_has_common_qtype_expr, CallOp("core.not_equal", {CallOp("qtype.common_qtype", {Placeholder("x"), Placeholder("y")}), Literal(GetNothingQType())})); return MakeQTypeConstraintFn({ {x_is_scalar_qtype_expr, "expected `x` to be scalar, got {x}"}, {y_is_scalar_qtype_expr, "expected `y` to be scalar, got {y}"}, {x_y_has_common_qtype_expr, "no common qtype for x:{x} and y:{y}"}, }); } static absl::StatusOr<QTypeConstraintFn> SampleConstraintWithVariadicFn() { auto false_expr = Literal(OptionalUnit{}); return MakeQTypeConstraintFn({ {false_expr, "*x: {*x}"}, }); } }; TEST_F(QTypeConstraintTest, Trivial) { ASSERT_OK_AND_ASSIGN(auto fn, MakeQTypeConstraintFn({})); EXPECT_THAT(fn({}), IsOk()); } TEST_F(QTypeConstraintTest, Ok) { ASSERT_OK_AND_ASSIGN(auto fn, SampleConstraintFn()); EXPECT_THAT(fn({ {"x", GetQType<int64_t>()}, {"y", GetQType<int32_t>()}, }), IsOk()); } TEST_F(QTypeConstraintTest, ErrorMessage) { ASSERT_OK_AND_ASSIGN(auto fn, SampleConstraintFn()); EXPECT_THAT( fn({ {"x", GetQType<int64_t>()}, {"y", GetQType<ScalarShape>()}, }), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("expected `y` to be scalar, got SCALAR_SHAPE"))); EXPECT_THAT(fn({ {"x", GetQType<int32_t>()}, {"y", GetQType<Bytes>()}, }), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("no common qtype for x:INT32 and y:BYTES"))); } TEST_F(QTypeConstraintTest, NoOutputQType) { ASSERT_OK_AND_ASSIGN( auto expr, CallOp("core.get_nth", {Placeholder("x"), Placeholder("y")})); EXPECT_THAT( MakeQTypeConstraintFn({{expr, ""}}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("Error while computing output QType of a QType " "constraint predicate: " "M.core.get_nth(P.x, P.y)"))); } TEST_F(QTypeConstraintTest, BadOutputQType) { auto x = Placeholder("x"); EXPECT_THAT(MakeQTypeConstraintFn({{x, ""}}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("expected a constraint predicate to return " "OPTIONAL_UNIT, got QTYPE: P.x"))); } TEST_F(QTypeConstraintTest, VariadicConstraint) { ASSERT_OK_AND_ASSIGN(auto fn, SampleConstraintWithVariadicFn()); EXPECT_THAT( fn({{"x", MakeTupleQType({})}}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("*x: ()"))); EXPECT_THAT(fn({ {"x", MakeTupleQType({GetQType<int32_t>(), GetQType<float>(), GetQType<bool>()})}, }), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("*x: (INT32, FLOAT32, BOOLEAN)"))); EXPECT_THAT( fn({ {"x", GetQType<int64_t>()}, }), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("*x: {*x}"))); } } }
2,461
#ifndef AROLLA_EXPR_OPERATOR_LOADER_GENERIC_OPERATOR_OVERLOAD_CONDITION_H_ #define AROLLA_EXPR_OPERATOR_LOADER_GENERIC_OPERATOR_OVERLOAD_CONDITION_H_ #include <vector> #include "absl/functional/any_invocable.h" #include "absl/status/statusor.h" #include "absl/types/span.h" #include "arolla/expr/expr_node.h" #include "arolla/qtype/qtype.h" namespace arolla::operator_loader { using GenericOperatorOverloadConditionFn = absl::AnyInvocable<absl::StatusOr<std::vector<bool>>( QTypePtr input_tuple_qtype) const>; absl::StatusOr<GenericOperatorOverloadConditionFn> MakeGenericOperatorOverloadConditionFn( absl::Span<const ::arolla::expr::ExprNodePtr> prepared_condition_exprs); } #endif #include "arolla/expr/operator_loader/generic_operator_overload_condition.h" #include <cstdint> #include <utility> #include <vector> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "arolla/expr/eval/model_executor.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/tuple_expr_operator.h" #include "arolla/io/wildcard_input_loader.h" #include "arolla/memory/optional_value.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/tuple_qtype.h" #include "arolla/qtype/typed_value.h" #include "arolla/util/status_macros_backport.h" namespace arolla::operator_loader { using ::arolla::expr::BindOp; using ::arolla::expr::CompileModelExecutor; using ::arolla::expr::ExprNodePtr; using ::arolla::expr::MakeTupleOperator; using ::arolla::expr::ModelEvaluationOptions; absl::StatusOr<GenericOperatorOverloadConditionFn> MakeGenericOperatorOverloadConditionFn( absl::Span<const ExprNodePtr> prepared_condition_exprs) { ASSIGN_OR_RETURN(auto expr, BindOp(MakeTupleOperator::Make(), prepared_condition_exprs, {})); auto accessor = [](QTypePtr input_tuple_qtype, absl::string_view) { return input_tuple_qtype; }; ASSIGN_OR_RETURN(auto input_loader, WildcardInputLoader<QTypePtr>::Build(accessor)); ASSIGN_OR_RETURN(auto model_executor, CompileModelExecutor<TypedValue>( std::move(expr), *input_loader)); const auto test_input_qtype = MakeTupleQType({}); const auto expected_output_qtype = MakeTupleQType( std::vector(prepared_condition_exprs.size(), GetQType<OptionalUnit>())); ASSIGN_OR_RETURN( auto actual_output, model_executor.ExecuteOnHeap(ModelEvaluationOptions{}, test_input_qtype)); if (actual_output.GetType() != expected_output_qtype) { return absl::FailedPreconditionError(absl::StrFormat( "unexpected return qtype: expected %s, got %s", expected_output_qtype->name(), actual_output.GetType()->name())); } return [model_executor = std::move(model_executor)]( QTypePtr input_tuple_qtype) -> absl::StatusOr<std::vector<bool>> { ASSIGN_OR_RETURN(auto qvalue, model_executor.ExecuteOnHeap(ModelEvaluationOptions{}, input_tuple_qtype)); const int64_t n = qvalue.GetFieldCount(); std::vector<bool> result(n); for (int64_t i = 0; i < n; ++i) { result[i] = qvalue.GetField(i).UnsafeAs<OptionalUnit>().present; } return result; }; } }
#include "arolla/expr/operator_loader/generic_operator_overload_condition.h" #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_node.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/tuple_qtype.h" #include "arolla/util/init_arolla.h" #include "arolla/util/testing/status_matchers_backport.h" #include "arolla/util/unit.h" namespace arolla::operator_loader { namespace { using ::arolla::expr::CallOp; using ::arolla::expr::ExprNodePtr; using ::arolla::expr::Leaf; using ::arolla::expr::Literal; using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::StatusIs; class GenericOperatorOverloadConditionTest : public ::testing::Test { protected: void SetUp() override { ASSERT_OK(InitArolla()); } static absl::StatusOr<ExprNodePtr> Arg(int n) { return CallOp("qtype.get_field_qtype", {Leaf("input_tuple_qtype"), Literal(n)}); } static absl::StatusOr<ExprNodePtr> Equal(absl::StatusOr<ExprNodePtr> lhs, absl::StatusOr<ExprNodePtr> rhs) { return CallOp("core.equal", {lhs, rhs}); } static absl::StatusOr<ExprNodePtr> NotEqual(absl::StatusOr<ExprNodePtr> lhs, absl::StatusOr<ExprNodePtr> rhs) { return CallOp("core.not_equal", {lhs, rhs}); } static absl::StatusOr<ExprNodePtr> And(absl::StatusOr<ExprNodePtr> lhs, absl::StatusOr<ExprNodePtr> rhs) { return CallOp("core.presence_and", {lhs, rhs}); } }; TEST_F(GenericOperatorOverloadConditionTest, Empty) { ASSERT_OK_AND_ASSIGN(auto condition_fn, MakeGenericOperatorOverloadConditionFn({})); EXPECT_THAT(condition_fn(MakeTupleQType({})), IsOkAndHolds(std::vector<bool>())); } TEST_F(GenericOperatorOverloadConditionTest, SingleCondition) { ASSERT_OK_AND_ASSIGN(auto condition_expr, NotEqual(Arg(0), Literal(GetNothingQType()))); ASSERT_OK_AND_ASSIGN( auto condition_fn, MakeGenericOperatorOverloadConditionFn({condition_expr})); EXPECT_THAT(condition_fn(MakeTupleQType({})), IsOkAndHolds(std::vector({false}))); EXPECT_THAT(condition_fn(MakeTupleQType({GetNothingQType()})), IsOkAndHolds(std::vector({false}))); EXPECT_THAT(condition_fn(MakeTupleQType({GetQType<Unit>()})), IsOkAndHolds(std::vector({true}))); } TEST_F(GenericOperatorOverloadConditionTest, MultipleConditions) { ASSERT_OK_AND_ASSIGN(auto condition_expr_1, And(And(NotEqual(Arg(0), Literal(GetNothingQType())), NotEqual(Arg(1), Literal(GetNothingQType()))), NotEqual(Arg(0), Arg(1)))); ASSERT_OK_AND_ASSIGN(auto condition_expr_2, And(And(NotEqual(Arg(0), Literal(GetNothingQType())), NotEqual(Arg(1), Literal(GetNothingQType()))), Equal(Arg(0), Arg(1)))); ASSERT_OK_AND_ASSIGN(auto condition_fn, MakeGenericOperatorOverloadConditionFn( {condition_expr_1, condition_expr_2})); EXPECT_THAT(condition_fn(MakeTupleQType({})), IsOkAndHolds(std::vector({false, false}))); EXPECT_THAT(condition_fn(MakeTupleQType({GetNothingQType()})), IsOkAndHolds(std::vector({false, false}))); EXPECT_THAT( condition_fn(MakeTupleQType({GetQType<Unit>(), GetQType<Unit>()})), IsOkAndHolds(std::vector({false, true}))); EXPECT_THAT(condition_fn(MakeTupleQType({GetQType<Unit>(), GetQType<int>()})), IsOkAndHolds(std::vector({true, false}))); } TEST_F(GenericOperatorOverloadConditionTest, UnexpectedReturnQType) { ASSERT_OK_AND_ASSIGN(auto condition_expr_1, NotEqual(Arg(0), Literal(GetNothingQType()))); ASSERT_OK_AND_ASSIGN(auto condition_expr_2, Arg(1)); EXPECT_THAT(MakeGenericOperatorOverloadConditionFn( {condition_expr_1, condition_expr_2}), StatusIs(absl::StatusCode::kFailedPrecondition, "unexpected return qtype: expected " "tuple<OPTIONAL_UNIT,OPTIONAL_UNIT>, got " "tuple<OPTIONAL_UNIT,QTYPE>")); } } }
2,462
#ifndef AROLLA_EXPR_OPERATOR_LOADER_QTYPE_INFERENCE_H_ #define AROLLA_EXPR_OPERATOR_LOADER_QTYPE_INFERENCE_H_ #include <functional> #include "absl/status/statusor.h" #include "absl/types/span.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/operator_loader/parameter_qtypes.h" #include "arolla/expr/operator_loader/qtype_constraint.h" #include "arolla/qtype/qtype.h" namespace arolla::operator_loader { using QTypeInferenceFn = std::function<absl::StatusOr<QTypePtr>( const ParameterQTypes& parameter_qtypes)>; absl::StatusOr<QTypeInferenceFn> MakeQTypeInferenceFn( absl::Span<const QTypeConstraint> qtype_constraints, expr::ExprNodePtr qtype_inference_expr); } #endif #include "arolla/expr/operator_loader/qtype_inference.h" #include <string> #include <utility> #include "absl/container/flat_hash_map.h" #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "absl/types/span.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_debug_string.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/operator_loader/helper.h" #include "arolla/expr/operator_loader/parameter_qtypes.h" #include "arolla/expr/operator_loader/qtype_constraint.h" #include "arolla/expr/qtype_utils.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/util/status_macros_backport.h" namespace arolla::operator_loader { namespace { using expr::ExprNodePtr; using expr::GetLeafKeys; using expr::PopulateQTypes; using expr::ToDebugString; absl::StatusOr<ExprNodePtr> NormalizeQTypeInferenceExpr(ExprNodePtr expr) { ASSIGN_OR_RETURN(auto result, ReplacePlaceholdersWithLeaves(expr)); absl::flat_hash_map<std::string, QTypePtr> leaf_qtypes; for (const auto& leaf_key : GetLeafKeys(result)) { leaf_qtypes[leaf_key] = GetQTypeQType(); } const QType* output_qtype = nullptr; if (const auto annotated_expr = PopulateQTypes(result, leaf_qtypes); annotated_expr.ok()) { output_qtype = (*annotated_expr)->qtype(); } if (output_qtype == GetQType<QTypePtr>()) { return result; } if (output_qtype == nullptr) { return absl::InvalidArgumentError( "Error while computing output QType of a QType inference expression: " + ToDebugString(expr)); } return absl::InvalidArgumentError(absl::StrFormat( "expected a qtype inference expression to return %s, got %s: %s", GetQTypeQType()->name(), output_qtype->name(), ToDebugString(expr))); } } absl::StatusOr<QTypeInferenceFn> MakeQTypeInferenceFn( absl::Span<const QTypeConstraint> qtype_constraints, ExprNodePtr qtype_inference_expr) { ASSIGN_OR_RETURN(auto normalized_qtype_inference_expr, NormalizeQTypeInferenceExpr(qtype_inference_expr)); ASSIGN_OR_RETURN(auto qtype_constraint_fn, MakeQTypeConstraintFn(qtype_constraints)); ASSIGN_OR_RETURN(auto executor, MakeParameterQTypeModelExecutor(std::move( normalized_qtype_inference_expr))); return [qtype_constraint_fn = std::move(qtype_constraint_fn), executor = std::move(executor), qtype_inference_expr = std::move(qtype_inference_expr)]( const ParameterQTypes& parameter_qtypes) -> absl::StatusOr<QTypePtr> { RETURN_IF_ERROR(qtype_constraint_fn(parameter_qtypes)); ASSIGN_OR_RETURN(auto qtype_typed_value, executor(parameter_qtypes)); DCHECK_EQ( qtype_typed_value.GetType(), GetQTypeQType()); auto* qtype = qtype_typed_value.UnsafeAs<QTypePtr>(); if (qtype == nullptr || qtype == GetNothingQType()) { return absl::InvalidArgumentError(absl::StrFormat( "qtype inference expression produced no qtype: %s, %s", ToDebugString(qtype_inference_expr), FormatParameterQTypes(parameter_qtypes))); } return qtype; }; } }
#include "arolla/expr/operator_loader/qtype_inference.h" #include <cstdint> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "arolla/expr/expr.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/shape_qtype.h" #include "arolla/util/bytes.h" #include "arolla/util/init_arolla.h" #include "arolla/util/testing/status_matchers_backport.h" #include "arolla/util/status_macros_backport.h" namespace arolla::operator_loader { namespace { using expr::CallOp; using expr::Literal; using expr::Placeholder; using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::StatusIs; using ::testing::HasSubstr; class QTypeInferenceTest : public ::testing::Test { protected: void SetUp() override { ASSERT_OK(InitArolla()); } static absl::StatusOr<QTypeInferenceFn> SampleInferenceFn() { ASSIGN_OR_RETURN(auto x_is_scalar_qtype_expr, CallOp("qtype.is_scalar_qtype", {Placeholder("x")})); ASSIGN_OR_RETURN(auto y_is_scalar_qtype_expr, CallOp("qtype.is_scalar_qtype", {Placeholder("y")})); ASSIGN_OR_RETURN( auto x_y_common_qtype_expr, CallOp("qtype.common_qtype", {Placeholder("x"), Placeholder("y")})); return MakeQTypeInferenceFn( { {x_is_scalar_qtype_expr, "expected `x` to be scalar, got {x}"}, {y_is_scalar_qtype_expr, "expected `y` to be scalar, got {y}"}, }, x_y_common_qtype_expr); } }; TEST_F(QTypeInferenceTest, Ok) { ASSERT_OK_AND_ASSIGN(auto fn, SampleInferenceFn()); EXPECT_THAT(fn({ {"x", GetQType<int64_t>()}, {"y", GetQType<int32_t>()}, }), IsOkAndHolds(GetQType<int64_t>())); } TEST_F(QTypeInferenceTest, ErrorMessage) { ASSERT_OK_AND_ASSIGN(auto fn, SampleInferenceFn()); EXPECT_THAT( fn({ {"x", GetQType<int32_t>()}, {"y", GetQType<ScalarShape>()}, }), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("expected `y` to be scalar, got SCALAR_SHAPE"))); EXPECT_THAT( fn({ {"x", GetQType<int32_t>()}, {"y", GetQType<Bytes>()}, }), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr( "qtype inference expression produced no " "qtype: M.qtype.common_qtype(P.x, P.y), x:INT32, y:BYTES"))); } TEST_F(QTypeInferenceTest, NoOutputQType) { ASSERT_OK_AND_ASSIGN( auto expr, CallOp("core.get_nth", {Placeholder("x"), Placeholder("y")})); EXPECT_THAT( MakeQTypeInferenceFn({}, expr), StatusIs( absl::StatusCode::kInvalidArgument, HasSubstr("Error while computing output QType of a QType inference " "expression: M.core.get_nth(P.x, P.y)"))); } TEST_F(QTypeInferenceTest, BadOutputQType) { auto x = Literal(1.f); EXPECT_THAT(MakeQTypeInferenceFn({}, x), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("expected a qtype inference expression to " "return QTYPE, got FLOAT32: 1."))); } } }
2,463
#ifndef AROLLA_EXPR_OPERATOR_LOADER_PARAMETER_QTYPES_H_ #define AROLLA_EXPR_OPERATOR_LOADER_PARAMETER_QTYPES_H_ #include <string> #include "absl/container/flat_hash_map.h" #include "absl/status/statusor.h" #include "absl/types/span.h" #include "arolla/expr/eval/thread_safe_model_executor.h" #include "arolla/expr/expr_attributes.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/typed_value.h" namespace arolla::operator_loader { struct ParameterQTypes : absl::flat_hash_map<std::string, QTypePtr> { using absl::flat_hash_map<std::string, QTypePtr>::flat_hash_map; }; ParameterQTypes ExtractParameterQTypes( const expr::ExprOperatorSignature& signature, absl::Span<const expr::ExprAttributes> bound_arg_attrs); absl::StatusOr<expr::ThreadSafeModelExecutor<ParameterQTypes, TypedValue>> MakeParameterQTypeModelExecutor(expr::ExprNodePtr expr); std::string FormatParameterQTypes(const ParameterQTypes& parameter_qtypes); } #endif #include "arolla/expr/operator_loader/parameter_qtypes.h" #include <algorithm> #include <string> #include <utility> #include <vector> #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_join.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "arolla/expr/eval/model_executor.h" #include "arolla/expr/eval/thread_safe_model_executor.h" #include "arolla/expr/expr_attributes.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/expr/qtype_utils.h" #include "arolla/io/wildcard_input_loader.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/tuple_qtype.h" #include "arolla/qtype/typed_value.h" #include "arolla/util/status_macros_backport.h" namespace arolla::operator_loader { using expr::CompileModelExecutor; using expr::ExprAttributes; using expr::ExprNodePtr; using expr::ExprOperatorSignature; using expr::ThreadSafeModelExecutor; using Param = ExprOperatorSignature::Parameter; ParameterQTypes ExtractParameterQTypes( const ExprOperatorSignature& signature, absl::Span<const ExprAttributes> bound_arg_attrs) { ParameterQTypes result; result.reserve(signature.parameters.size()); for (const auto& param : signature.parameters) { const QType* param_qtype = nullptr; switch (param.kind) { case Param::Kind::kPositionalOrKeyword: if (bound_arg_attrs.empty()) { return result; } param_qtype = bound_arg_attrs.front().qtype(); bound_arg_attrs.remove_prefix(1); break; case Param::Kind::kVariadicPositional: if (HasAllAttrQTypes(bound_arg_attrs)) { std::vector<QTypePtr> vararg_qtypes; vararg_qtypes.reserve(bound_arg_attrs.size()); for (auto& attr : bound_arg_attrs) { vararg_qtypes.push_back(attr.qtype()); } param_qtype = MakeTupleQType(vararg_qtypes); } bound_arg_attrs = {}; break; } if (param_qtype != nullptr) { result[param.name] = param_qtype; } } return result; } absl::StatusOr<ThreadSafeModelExecutor<ParameterQTypes, TypedValue>> MakeParameterQTypeModelExecutor(ExprNodePtr expr) { auto accessor = [](const ParameterQTypes& parameter_qtypes, absl::string_view parameter_name) -> QTypePtr { if (auto it = parameter_qtypes.find(parameter_name); it != parameter_qtypes.end()) { return it->second; } return GetNothingQType(); }; ASSIGN_OR_RETURN(auto input_loader, WildcardInputLoader<ParameterQTypes>::Build(accessor)); ASSIGN_OR_RETURN(auto model_executor, CompileModelExecutor<TypedValue>( std::move(expr), *input_loader)); return ThreadSafeModelExecutor<ParameterQTypes, TypedValue>( std::move(model_executor)); } std::string FormatParameterQTypes(const ParameterQTypes& parameter_qtypes) { std::vector<std::pair<absl::string_view, absl::string_view>> items; items.reserve(parameter_qtypes.size()); for (const auto& [name, qtype] : parameter_qtypes) { items.emplace_back(name, qtype->name()); } std::sort(items.begin(), items.end()); return absl::StrJoin(items, ", ", [](std::string* out, const auto& item) { absl::StrAppend(out, item.first, ":", item.second); }); } }
#include "arolla/expr/operator_loader/parameter_qtypes.h" #include <cstdint> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_attributes.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/tuple_qtype.h" #include "arolla/util/bytes.h" #include "arolla/util/init_arolla.h" #include "arolla/util/text.h" #include "arolla/util/unit.h" namespace arolla::operator_loader { namespace { using ::arolla::expr::CallOp; using ::arolla::expr::ExprOperatorSignature; using ::arolla::expr::Leaf; using ::testing::IsEmpty; using ::testing::Pair; using ::testing::UnorderedElementsAre; using Attr = ::arolla::expr::ExprAttributes; class ParameterQTypesTest : public ::testing::Test { protected: void SetUp() override { ASSERT_OK(InitArolla()); } }; TEST_F(ParameterQTypesTest, ExtractParameterQTypes) { ASSERT_OK_AND_ASSIGN( auto sig, ExprOperatorSignature::Make("first, second=, *args", kUnit)); EXPECT_THAT(ExtractParameterQTypes(sig, {}), IsEmpty()); EXPECT_THAT(ExtractParameterQTypes(sig, {Attr{GetQType<int32_t>()}}), UnorderedElementsAre(Pair("first", GetQType<int32_t>()))); EXPECT_THAT(ExtractParameterQTypes( sig, {Attr{GetQType<int32_t>()}, Attr{GetQType<float>()}}), UnorderedElementsAre(Pair("first", GetQType<int32_t>()), Pair("second", GetQType<float>()), Pair("args", MakeTupleQType({})))); EXPECT_THAT( ExtractParameterQTypes( sig, {Attr{GetQType<int32_t>()}, Attr{GetQType<float>()}, Attr{GetQType<Bytes>()}}), UnorderedElementsAre(Pair("first", GetQType<int32_t>()), Pair("second", GetQType<float>()), Pair("args", MakeTupleQType({GetQType<Bytes>()})))); EXPECT_THAT( ExtractParameterQTypes( sig, {Attr{GetQType<int32_t>()}, Attr{GetQType<float>()}, Attr{GetQType<Bytes>()}, Attr{GetQType<Text>()}}), UnorderedElementsAre( Pair("first", GetQType<int32_t>()), Pair("second", GetQType<float>()), Pair("args", MakeTupleQType({GetQType<Bytes>(), GetQType<Text>()})))); EXPECT_THAT(ExtractParameterQTypes(sig, {Attr{}, Attr{}, Attr{}, Attr{}}), IsEmpty()); } TEST_F(ParameterQTypesTest, MakeParameterQTypeModelExecutor) { ASSERT_OK_AND_ASSIGN( auto expr, CallOp("core.make_tuple", {Leaf("first"), Leaf("second"), Leaf("args")})); ASSERT_OK_AND_ASSIGN(auto executor, MakeParameterQTypeModelExecutor(expr)); { ASSERT_OK_AND_ASSIGN(auto result, executor({})); EXPECT_THAT(result.GetFingerprint(), MakeTupleFromFields(GetNothingQType(), GetNothingQType(), GetNothingQType()) .GetFingerprint()); } { ASSERT_OK_AND_ASSIGN(auto result, executor({ {"first", GetQType<int32_t>()}, {"second", GetQType<float>()}, {"args", MakeTupleQType({GetQType<Bytes>()})}, })); EXPECT_THAT(result.GetFingerprint(), MakeTupleFromFields(GetQType<int32_t>(), GetQType<float>(), MakeTupleQType({GetQType<Bytes>()})) .GetFingerprint()); } } TEST_F(ParameterQTypesTest, FormatParameterQTypes) { EXPECT_EQ(FormatParameterQTypes({ {"i32", GetQType<int32_t>()}, {"i64", GetQType<int64_t>()}, {"f32", GetQType<float>()}, {"f64", GetQType<double>()}, {"unit", GetQType<Unit>()}, {"qtype", GetQType<QTypePtr>()}, }), ("f32:FLOAT32, f64:FLOAT64, " "i32:INT32, i64:INT64, " "qtype:QTYPE, unit:UNIT")); } } }
2,464
#ifndef AROLLA_EXPR_OPERATOR_LOADER_RESTRICTED_LAMBDA_OPERATOR_H_ #define AROLLA_EXPR_OPERATOR_LOADER_RESTRICTED_LAMBDA_OPERATOR_H_ #include <memory> #include <string> #include <vector> #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "arolla/expr/expr_attributes.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/expr/lambda_expr_operator.h" #include "arolla/expr/operator_loader/qtype_constraint.h" #include "arolla/util/fingerprint.h" namespace arolla::operator_loader { class RestrictedLambdaOperator final : public expr::ExprOperator { struct PrivateConstructorTag {}; public: static absl::StatusOr<expr::ExprOperatorPtr> Make( std::shared_ptr<const expr::LambdaOperator> base_lambda_operator, std::vector<QTypeConstraint> qtype_constraints); RestrictedLambdaOperator( PrivateConstructorTag, std::shared_ptr<const expr::LambdaOperator> base_lambda_operator, Fingerprint fingerprint, std::vector<std::string> required_parameters, QTypeConstraintFn qtype_constraint_fn, std::vector<QTypeConstraint> qtype_constraints); absl::StatusOr<expr::ExprOperatorSignature> GetSignature() const final { return base_lambda_operator_->GetSignature(); } absl::StatusOr<std::string> GetDoc() const final { return base_lambda_operator_->GetDoc(); } const expr::ExprOperatorSignature& signature() const { return base_lambda_operator_->signature(); } const std::string doc() const { return base_lambda_operator_->doc(); } const std::vector<QTypeConstraint>& qtype_constraints() const { return qtype_constraints_; } const std::shared_ptr<const expr::LambdaOperator>& base_lambda_operator() const { return base_lambda_operator_; } absl::StatusOr<expr::ExprAttributes> InferAttributes( absl::Span<const expr::ExprAttributes> inputs) const final; absl::StatusOr<expr::ExprNodePtr> ToLowerLevel( const expr::ExprNodePtr& node) const final; absl::string_view py_qvalue_specialization_key() const override; private: std::shared_ptr<const expr::LambdaOperator> base_lambda_operator_; std::vector<std::string> required_parameters_; QTypeConstraintFn qtype_constraint_fn_; std::vector<QTypeConstraint> qtype_constraints_; }; } #endif #include "arolla/expr/operator_loader/restricted_lambda_operator.h" #include <algorithm> #include <memory> #include <string> #include <utility> #include <vector> #include "absl/container/flat_hash_set.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_join.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_attributes.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/expr/lambda_expr_operator.h" #include "arolla/expr/operator_loader/parameter_qtypes.h" #include "arolla/expr/operator_loader/qtype_constraint.h" #include "arolla/util/fingerprint.h" #include "arolla/util/status_macros_backport.h" namespace arolla::operator_loader { using ::arolla::expr::ExprAttributes; using ::arolla::expr::ExprNodePtr; using ::arolla::expr::ExprOperatorPtr; using ::arolla::expr::GetPlaceholderKeys; using ::arolla::expr::LambdaOperator; using ::arolla::expr::ValidateDepsCount; absl::StatusOr<ExprOperatorPtr> RestrictedLambdaOperator::Make( std::shared_ptr<const LambdaOperator> base_lambda_operator, std::vector<QTypeConstraint> qtype_constraints) { absl::flat_hash_set<std::string> qtype_constraint_parameters; for (const auto& qtype_constraint : qtype_constraints) { const auto& placeholder_keys = GetPlaceholderKeys(qtype_constraint.predicate_expr); qtype_constraint_parameters.insert(placeholder_keys.begin(), placeholder_keys.end()); } auto undefined_parameters = qtype_constraint_parameters; for (const auto& param : base_lambda_operator->signature().parameters) { undefined_parameters.erase(param.name); } if (!undefined_parameters.empty()) { std::vector<std::string> undefined_parameters_sorted( undefined_parameters.begin(), undefined_parameters.end()); std::sort(undefined_parameters_sorted.begin(), undefined_parameters_sorted.end()); return absl::InvalidArgumentError( "unexpected parameters: P." + absl::StrJoin(undefined_parameters_sorted, ", P.")); } std::vector<std::string> required_parameters( qtype_constraint_parameters.begin(), qtype_constraint_parameters.end()); std::sort(required_parameters.begin(), required_parameters.end()); ASSIGN_OR_RETURN(auto qtype_constraint_fn, MakeQTypeConstraintFn(qtype_constraints)); FingerprintHasher hasher( "::arolla::operator_loader::RestrictedLambdaOperator"); hasher.Combine(base_lambda_operator->fingerprint(), qtype_constraints.size()); for (const auto& qtype_constraint : qtype_constraints) { hasher.Combine(qtype_constraint.predicate_expr->fingerprint(), qtype_constraint.error_message); } return std::make_shared<RestrictedLambdaOperator>( PrivateConstructorTag{}, std::move(base_lambda_operator), std::move(hasher).Finish(), std::move(required_parameters), std::move(qtype_constraint_fn), std::move(qtype_constraints)); } RestrictedLambdaOperator::RestrictedLambdaOperator( PrivateConstructorTag, std::shared_ptr<const LambdaOperator> base_lambda_operator, Fingerprint fingerprint, std::vector<std::string> required_parameters, QTypeConstraintFn qtype_constraint_fn, std::vector<QTypeConstraint> qtype_constraints) : ExprOperator(base_lambda_operator->display_name(), fingerprint), base_lambda_operator_(std::move(base_lambda_operator)), required_parameters_(std::move(required_parameters)), qtype_constraint_fn_(std::move(qtype_constraint_fn)), qtype_constraints_(std::move(qtype_constraints)) {} absl::StatusOr<ExprAttributes> RestrictedLambdaOperator::InferAttributes( absl::Span<const ExprAttributes> inputs) const { RETURN_IF_ERROR(ValidateDepsCount(signature(), inputs.size(), absl::StatusCode::kInvalidArgument)); const auto parameter_qtypes = ExtractParameterQTypes(signature(), inputs); for (const auto& name : required_parameters_) { if (!parameter_qtypes.contains(name)) { return ExprAttributes{}; } } RETURN_IF_ERROR(qtype_constraint_fn_(parameter_qtypes)); return base_lambda_operator_->InferAttributes(inputs); } absl::StatusOr<ExprNodePtr> RestrictedLambdaOperator::ToLowerLevel( const ExprNodePtr& node) const { if (!node->qtype()) { return node; } return base_lambda_operator_->ToLowerLevel(node); } absl::string_view RestrictedLambdaOperator::py_qvalue_specialization_key() const { return "::arolla::operator_loader::RestrictedLambdaOperator"; } }
#include "arolla/expr/operator_loader/restricted_lambda_operator.h" #include <memory> #include <utility> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_attributes.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/expr/lambda_expr_operator.h" #include "arolla/expr/operator_loader/qtype_constraint.h" #include "arolla/expr/testing/testing.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/typed_ref.h" #include "arolla/util/bytes.h" #include "arolla/util/init_arolla.h" #include "arolla/util/testing/status_matchers_backport.h" #include "arolla/util/text.h" #include "arolla/util/unit.h" #include "arolla/util/status_macros_backport.h" namespace arolla::operator_loader { namespace { using ::arolla::expr::CallOp; using ::arolla::expr::ExprOperatorSignature; using ::arolla::expr::LambdaOperator; using ::arolla::expr::Leaf; using ::arolla::expr::Literal; using ::arolla::expr::Placeholder; using ::arolla::expr::SuppressUnusedWarning; using ::arolla::testing::EqualsAttr; using ::arolla::testing::EqualsExpr; using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::StatusIs; using ::arolla::testing::WithQTypeAnnotation; using Attr = ::arolla::expr::ExprAttributes; class RestrictedLambdaOperatorTest : public ::testing::Test { protected: void SetUp() override { ASSERT_OK(InitArolla()); } static absl::StatusOr<std::shared_ptr<LambdaOperator>> MakeBaseLambdaOp() { return expr::MakeLambdaOperator( "with_name", ExprOperatorSignature{{"x"}, {"name"}}, SuppressUnusedWarning("name", Placeholder("x")), "doc-string-for-lambda"); } static absl::StatusOr<QTypeConstraint> MakeQTypeConstraint() { ASSIGN_OR_RETURN( auto predicate_expr, CallOp("core.equal", {Placeholder("name"), Literal(GetQType<Text>())})); return QTypeConstraint{predicate_expr, "expected name to be TEXT, got {name}"}; } static absl::StatusOr<std::shared_ptr<const RestrictedLambdaOperator>> MakeOp() { ASSIGN_OR_RETURN(auto lambda_op, MakeBaseLambdaOp()); ASSIGN_OR_RETURN(auto qtype_constraint, MakeQTypeConstraint()); ASSIGN_OR_RETURN(auto restricted_lambda_op, RestrictedLambdaOperator::Make( std::move(lambda_op), {std::move(qtype_constraint)})); return std::dynamic_pointer_cast<const RestrictedLambdaOperator>( restricted_lambda_op); } }; } TEST_F(RestrictedLambdaOperatorTest, PublicProperties) { ASSERT_OK_AND_ASSIGN(auto base_lambda_op, MakeBaseLambdaOp()); ASSERT_OK_AND_ASSIGN(auto qtype_constraint, MakeQTypeConstraint()); ASSERT_OK_AND_ASSIGN(auto op, MakeOp()); EXPECT_EQ(op->display_name(), "with_name"); EXPECT_EQ(op->doc(), "doc-string-for-lambda"); EXPECT_EQ(op->base_lambda_operator()->fingerprint(), base_lambda_op->fingerprint()); EXPECT_EQ(op->qtype_constraints().size(), 1); EXPECT_EQ(op->qtype_constraints()[0].error_message, qtype_constraint.error_message); EXPECT_THAT(op->qtype_constraints()[0].predicate_expr, EqualsExpr(qtype_constraint.predicate_expr)); } TEST_F(RestrictedLambdaOperatorTest, UnexpectedParameter) { ASSERT_OK_AND_ASSIGN(auto base_lambda_op, MakeBaseLambdaOp()); ASSERT_OK_AND_ASSIGN(auto qtype_constraint0, MakeQTypeConstraint()); auto new_parameter = Placeholder("new_parameter"); QTypeConstraint qtype_constraint1 = {new_parameter, "new_message"}; EXPECT_THAT( RestrictedLambdaOperator::Make(std::move(base_lambda_op), {qtype_constraint0, qtype_constraint1}), StatusIs(absl::StatusCode::kInvalidArgument, "unexpected parameters: P.new_parameter")); } TEST_F(RestrictedLambdaOperatorTest, InferAttributes) { ASSERT_OK_AND_ASSIGN(auto op, MakeOp()); EXPECT_THAT(op->InferAttributes({Attr{}, Attr{}}), IsOkAndHolds(EqualsAttr(nullptr))); EXPECT_THAT(op->InferAttributes({Attr{}, Attr(GetQType<Text>())}), IsOkAndHolds(EqualsAttr(nullptr))); EXPECT_THAT( op->InferAttributes({Attr(GetQType<Unit>()), Attr(GetQType<Text>())}), IsOkAndHolds(EqualsAttr(GetQType<Unit>()))); EXPECT_THAT(op->InferAttributes({Attr{}, Attr(GetQType<Bytes>())}), StatusIs(absl::StatusCode::kInvalidArgument, "expected name to be TEXT, got BYTES")); } TEST_F(RestrictedLambdaOperatorTest, ToLowerLevel) { auto leaf = Leaf("leaf"); ASSERT_OK_AND_ASSIGN(auto leaf_with_qtype, WithQTypeAnnotation(Leaf("leaf"), GetQType<float>())); auto name_literal = Literal(Text("name")); auto name_placeholder = Placeholder("name"); { ASSERT_OK_AND_ASSIGN(auto expr, CallOp(MakeOp(), {leaf, name_placeholder})); EXPECT_EQ(expr->qtype(), nullptr); EXPECT_THAT(ToLowest(expr), IsOkAndHolds(EqualsExpr(expr))); } { ASSERT_OK_AND_ASSIGN(auto expr, CallOp(MakeOp(), {leaf, name_literal})); EXPECT_EQ(expr->qtype(), nullptr); EXPECT_THAT(ToLowest(expr), IsOkAndHolds(EqualsExpr(expr))); } { ASSERT_OK_AND_ASSIGN(auto expr, CallOp(MakeOp(), {leaf_with_qtype, name_placeholder})); EXPECT_EQ(expr->qtype(), nullptr); EXPECT_THAT(ToLowest(expr), IsOkAndHolds(EqualsExpr(expr))); } { ASSERT_OK_AND_ASSIGN(auto expr, CallOp(MakeOp(), {leaf_with_qtype, name_literal})); EXPECT_EQ(expr->qtype(), GetQType<float>()); EXPECT_THAT(ToLowest(expr), IsOkAndHolds(EqualsExpr(leaf_with_qtype))); } } TEST_F(RestrictedLambdaOperatorTest, QValuePropagation) { ASSERT_OK_AND_ASSIGN(const auto expr, CallOp(MakeOp(), {Literal(1), Literal(Text("abc"))})); EXPECT_THAT(expr->attr(), EqualsAttr(TypedRef::FromValue(1))); } }
2,465
#ifndef AROLLA_EXPR_OPERATOR_LOADER_DUMMY_OPERATOR_H_ #define AROLLA_EXPR_OPERATOR_LOADER_DUMMY_OPERATOR_H_ #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "arolla/expr/basic_expr_operator.h" #include "arolla/expr/expr_attributes.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/qtype/qtype.h" namespace arolla::operator_loader { class DummyOperator final : public expr::ExprOperatorWithFixedSignature { public: DummyOperator(absl::string_view name, expr::ExprOperatorSignature signature, absl::string_view doc, QTypePtr result_qtype); QTypePtr GetOutputQType() const { return result_qtype_; } absl::string_view py_qvalue_specialization_key() const override; absl::StatusOr<expr::ExprAttributes> InferAttributes( absl::Span<const expr::ExprAttributes> inputs) const final; private: QTypePtr result_qtype_; }; } #endif #include "arolla/expr/operator_loader/dummy_operator.h" #include <utility> #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "arolla/expr/basic_expr_operator.h" #include "arolla/expr/expr_attributes.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/qtype/qtype.h" #include "arolla/util/fingerprint.h" #include "arolla/util/status_macros_backport.h" namespace arolla::operator_loader { using ::arolla::expr::ExprAttributes; using ::arolla::expr::ExprOperatorPtr; using ::arolla::expr::ExprOperatorSignature; DummyOperator::DummyOperator(absl::string_view name, ExprOperatorSignature signature, absl::string_view doc, QTypePtr result_qtype) : ExprOperatorWithFixedSignature( name, signature, doc, FingerprintHasher("::arolla::operator_loader::DummyOperator") .Combine(name, signature, doc, result_qtype) .Finish()), result_qtype_(std::move(result_qtype)) {} absl::string_view DummyOperator::py_qvalue_specialization_key() const { return "::arolla::operator_loader::DummyOperator"; } absl::StatusOr<ExprAttributes> DummyOperator::InferAttributes( absl::Span<const ExprAttributes> inputs) const { RETURN_IF_ERROR(ValidateOpInputsCount(inputs)); return ExprAttributes(result_qtype_); } }
#include "arolla/expr/operator_loader/dummy_operator.h" #include <cstdint> #include <memory> #include <utility> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "arolla/array/qtype/types.h" #include "arolla/expr/eval/invoke.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/memory/optional_value.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/util/init_arolla.h" #include "arolla/util/testing/status_matchers_backport.h" #include "arolla/util/unit.h" namespace arolla::operator_loader { namespace { using ::arolla::expr::CallOp; using ::arolla::expr::ExprOperatorPtr; using ::arolla::expr::ExprOperatorSignature; using ::arolla::expr::Leaf; using ::arolla::expr::Literal; using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::StatusIs; using ::testing::AllOf; using ::testing::HasSubstr; class DummyOperatorTest : public ::testing::Test { protected: void SetUp() override { ASSERT_OK(InitArolla()); } }; TEST_F(DummyOperatorTest, GetName) { DummyOperator op("my_dummy_op", ExprOperatorSignature{{"x"}, {"y"}}, "dummy op docstring", std::move(GetArrayQType<int32_t>())); ASSERT_THAT(op.display_name(), "my_dummy_op"); } TEST_F(DummyOperatorTest, GetDoc) { DummyOperator op("my_dummy_op", ExprOperatorSignature{{"x"}, {"y"}}, "dummy op docstring", std::move(GetArrayQType<int32_t>())); ASSERT_THAT(op.doc(), "dummy op docstring"); ASSERT_THAT(op.GetDoc(), IsOkAndHolds("dummy op docstring")); } TEST_F(DummyOperatorTest, GetOutputQType) { { DummyOperator op("my_dummy_op", ExprOperatorSignature{{"x"}, {"y"}}, "dummy op docstring", std::move(GetArrayQType<int32_t>())); EXPECT_EQ(op.GetOutputQType(), GetArrayQType<int32_t>()); } { DummyOperator op("my_dummy_op", ExprOperatorSignature{{"x"}, {"y"}}, "dummy op docstring", std::move(GetQType<OptionalValue<float>>())); EXPECT_EQ(op.GetOutputQType(), GetQType<OptionalValue<float>>()); } } TEST_F(DummyOperatorTest, QTypeInference) { { auto op = std::make_shared<DummyOperator>( "my_dummy_op", ExprOperatorSignature{{"x"}, {"y"}}, "dummy op docstring", std::move(GetArrayQType<int32_t>())); ASSERT_OK_AND_ASSIGN(auto expr, CallOp(op, {Literal(1.5f), Literal(kUnit)})); EXPECT_EQ(expr->qtype(), GetArrayQType<int32_t>()); } { auto op = std::make_shared<DummyOperator>( "my_dummy_op", ExprOperatorSignature{{"x"}, {"y"}}, "dummy op docstring", std::move(GetArrayQType<int32_t>())); ASSERT_OK_AND_ASSIGN(auto expr, CallOp(op, {Leaf("x"), Leaf("y")})); EXPECT_EQ(expr->qtype(), GetArrayQType<int32_t>()); } } TEST_F(DummyOperatorTest, InferAttributesIncorrectArity) { DummyOperator op("my_dummy_op", ExprOperatorSignature{{"x"}, {"y"}}, "dummy op docstring", std::move(GetArrayQType<int32_t>())); EXPECT_THAT(op.InferAttributes({}), StatusIs(absl::StatusCode::kInvalidArgument, AllOf(HasSubstr("incorrect number of dependencies"), HasSubstr("expected 2 but got 0")))); } TEST_F(DummyOperatorTest, Eval) { auto op = std::make_shared<DummyOperator>( "my_dummy_op", ExprOperatorSignature{{"x"}, {"y"}}, "dummy op docstring", std::move(GetArrayQType<int32_t>())); ASSERT_OK_AND_ASSIGN( auto expr, CallOp(op, {Literal(1.5f), Literal(OptionalValue<Unit>())})); EXPECT_THAT( Invoke(expr, {}), StatusIs( absl::StatusCode::kInvalidArgument, HasSubstr("my_dummy_op is not a builtin or backend ExprOperator"))); } TEST_F(DummyOperatorTest, Fingerprint) { DummyOperator op1("my_dummy_op", ExprOperatorSignature{{"x"}, {"y"}}, "dummy op docstring", std::move(GetQType<float>())); { DummyOperator op2("my_dummy_op", ExprOperatorSignature{{"x"}, {"y"}}, "dummy op docstring", std::move(GetQType<float>())); EXPECT_EQ(op1.fingerprint(), op2.fingerprint()); } { DummyOperator op2("another_name", ExprOperatorSignature{{"x"}, {"y"}}, "dummy op docstring", std::move(GetQType<float>())); EXPECT_NE(op1.fingerprint(), op2.fingerprint()); } { DummyOperator op2("my_dummy_op", ExprOperatorSignature{{"x"}}, "dummy op docstring", std::move(GetQType<float>())); EXPECT_NE(op1.fingerprint(), op2.fingerprint()); } { DummyOperator op2("my_dummy_op", ExprOperatorSignature{{"x"}, {"y"}}, "another docstring", std::move(GetQType<float>())); EXPECT_NE(op1.fingerprint(), op2.fingerprint()); } { DummyOperator op2("my_dummy_op", ExprOperatorSignature{{"x"}, {"y"}}, "dummy op docstring", std::move(GetQType<int32_t>())); EXPECT_NE(op1.fingerprint(), op2.fingerprint()); } } } }
2,466
#ifndef AROLLA_EXPR_OPERATOR_LOADER_DISPATCH_OPERATOR_H_ #define AROLLA_EXPR_OPERATOR_LOADER_DISPATCH_OPERATOR_H_ #include <vector> #include "absl/base/nullability.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "arolla/expr/basic_expr_operator.h" #include "arolla/expr/expr_attributes.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/expr/operator_loader/generic_operator_overload_condition.h" #include "arolla/util/fingerprint.h" #include "arolla/util/repr.h" namespace arolla::operator_loader { class DispatchOperator final : public expr::ExprOperatorWithFixedSignature { struct PrivateConstructorTag {}; public: struct Overload { std::string name; expr::ExprOperatorPtr op; expr::ExprNodePtr condition; }; static absl::StatusOr<expr::ExprOperatorPtr> Make( absl::string_view name, expr::ExprOperatorSignature signature, std::vector<Overload> overloads, expr::ExprNodePtr dispatch_readiness_condition); DispatchOperator(PrivateConstructorTag, absl::string_view name, expr::ExprOperatorSignature signature, std::vector<Overload> overloads, GenericOperatorOverloadConditionFn overloads_condition_fn, expr::ExprNodePtr dispatch_readiness_condition, Fingerprint fingerprint); absl::StatusOr<expr::ExprAttributes> InferAttributes( absl::Span<const expr::ExprAttributes> inputs) const final; absl::StatusOr<expr::ExprNodePtr> ToLowerLevel( const expr::ExprNodePtr& node) const final; absl::string_view py_qvalue_specialization_key() const override; const expr::ExprNodePtr& dispatch_readiness_condition() const { return dispatch_readiness_condition_; } const std::vector<Overload>& overloads() const { return overloads_; } ReprToken GenReprToken() const final; private: absl::StatusOr<absl::Nullable<const Overload*>> LookupImpl( absl::Span<const expr::ExprAttributes> inputs) const; std::vector<Overload> overloads_; GenericOperatorOverloadConditionFn overloads_condition_fn_; expr::ExprNodePtr dispatch_readiness_condition_; }; } #endif #include "arolla/expr/operator_loader/dispatch_operator.h" #include <cstddef> #include <memory> #include <optional> #include <string> #include <utility> #include <vector> #include "absl/base/nullability.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/escaping.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" #include "absl/strings/str_join.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "arolla/expr/basic_expr_operator.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_attributes.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/expr/operator_loader/generic_operator_overload_condition.h" #include "arolla/expr/qtype_utils.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/tuple_qtype.h" #include "arolla/util/fingerprint.h" #include "arolla/util/repr.h" #include "arolla/util/status_macros_backport.h" namespace arolla::operator_loader { using ::arolla::expr::ExprAttributes; using ::arolla::expr::ExprNode; using ::arolla::expr::ExprNodePtr; using ::arolla::expr::ExprOperatorPtr; using ::arolla::expr::GetPlaceholderKeys; using ::arolla::expr::ValidateDepsCount; absl::StatusOr<ExprOperatorPtr> DispatchOperator::Make( absl::string_view name, expr::ExprOperatorSignature signature, std::vector<Overload> overloads, expr::ExprNodePtr dispatch_readiness_condition) { RETURN_IF_ERROR(ValidateSignature(signature)); for (const auto& overload : overloads) { const auto& placeholder_keys = GetPlaceholderKeys(overload.condition); if (!placeholder_keys.empty()) { return absl::InvalidArgumentError( "placeholders are not supported " "in dispatch operator overload conditions"); } } for (const auto& param : signature.parameters) { if (param.default_value.has_value()) { return absl::InvalidArgumentError( "signatures with the default values are not supported " "in dispatch operator; " "got signature: " + GetExprOperatorSignatureSpec(signature)); } } std::vector<ExprNodePtr> overload_conditions; overload_conditions.reserve(overloads.size() + 1); for (const auto& overload : overloads) { overload_conditions.push_back(overload.condition); } overload_conditions.push_back(dispatch_readiness_condition); ASSIGN_OR_RETURN(auto overloads_condition_fn, MakeGenericOperatorOverloadConditionFn(overload_conditions)); FingerprintHasher hasher("::arolla::operator_loader::DispatchOperator"); hasher.Combine(name, signature, dispatch_readiness_condition->fingerprint(), overloads.size()); for (const auto& overload : overloads) { hasher.Combine(overload.name, overload.op->fingerprint(), overload.condition->fingerprint()); } return std::make_shared<DispatchOperator>( PrivateConstructorTag{}, name, std::move(signature), std::move(overloads), std::move(overloads_condition_fn), std::move(dispatch_readiness_condition), std::move(hasher).Finish()); } DispatchOperator::DispatchOperator( PrivateConstructorTag, absl::string_view name, expr::ExprOperatorSignature signature, std::vector<Overload> overloads, GenericOperatorOverloadConditionFn overloads_condition_fn, expr::ExprNodePtr dispatch_readiness_condition, Fingerprint fingerprint) : ExprOperatorWithFixedSignature(name, signature, "", fingerprint), overloads_(std::move(overloads)), overloads_condition_fn_(std::move(overloads_condition_fn)), dispatch_readiness_condition_(std::move(dispatch_readiness_condition)) {} absl::StatusOr<expr::ExprAttributes> DispatchOperator::InferAttributes( absl::Span<const expr::ExprAttributes> inputs) const { ASSIGN_OR_RETURN(const auto* overload, LookupImpl(inputs)); if (overload == nullptr) { return ExprAttributes{}; } ASSIGN_OR_RETURN(expr::ExprAttributes attr, overload->op->InferAttributes(inputs), _ << "in " << absl::Utf8SafeCHexEscape(overload->name) << " overload of DispatchOperator"); return attr; } absl::StatusOr<expr::ExprNodePtr> DispatchOperator::ToLowerLevel( const expr::ExprNodePtr& node) const { ASSIGN_OR_RETURN(const auto* overload, LookupImpl(GetExprAttrs(node->node_deps()))); if (overload == nullptr) { return node; } auto expr = ExprNode::UnsafeMakeOperatorNode(ExprOperatorPtr(overload->op), std::vector(node->node_deps()), ExprAttributes(node->attr())); ASSIGN_OR_RETURN(expr::ExprNodePtr lowered, expr->op()->ToLowerLevel(expr), _ << "in " << absl::Utf8SafeCHexEscape(overload->name) << " overload of DispatchOperator"); return lowered; } absl::StatusOr<absl::Nullable<const DispatchOperator::Overload*>> DispatchOperator::LookupImpl(absl::Span<const ExprAttributes> inputs) const { RETURN_IF_ERROR(ValidateDepsCount(signature(), inputs.size(), absl::StatusCode::kInvalidArgument)); auto input_qtypes = GetAttrQTypes(inputs); for (auto& input_qtype : input_qtypes) { if (input_qtype == nullptr) { input_qtype = GetNothingQType(); } } ASSIGN_OR_RETURN(auto is_condition_passed, overloads_condition_fn_(MakeTupleQType(input_qtypes))); if (is_condition_passed.size() != overloads_.size() + 1) { return absl::InternalError("the state of DispatchOperator is invalid"); } bool ready_to_dispatch = is_condition_passed.back(); if (!ready_to_dispatch) { if (HasAllAttrQTypes(inputs)) { return absl::FailedPreconditionError( absl::StrFormat("the operator is broken for argument types %s", FormatTypeVector(input_qtypes))); } return nullptr; } std::vector<size_t> matching_ids; for (size_t i = 0; i < overloads_.size(); ++i) { if (is_condition_passed[i]) { matching_ids.push_back(i); } } if (matching_ids.size() > 1) { return absl::FailedPreconditionError(absl::StrFormat( "constraints of the multiple overloads (%s) passed for argument " "types %s", absl::StrJoin(matching_ids, ", ", [&](std::string* out, size_t id) { absl::StrAppend( out, absl::Utf8SafeCHexEscape(overloads_[id].name)); }), FormatTypeVector(input_qtypes))); } if (matching_ids.empty()) { return absl::InvalidArgumentError( absl::StrFormat("no suitable overload for argument types %s", FormatTypeVector(input_qtypes))); } return &overloads_[matching_ids[0]]; } ReprToken DispatchOperator::GenReprToken() const { return {absl::StrFormat( "<DispatchOperator: name='%s', signature='%s', cases=['%s']>", absl::Utf8SafeCHexEscape(display_name()), GetExprOperatorSignatureSpec(signature()), absl::StrJoin( overloads_, "', '", [](std::string* out, const auto& overload) { absl::StrAppend(out, absl::Utf8SafeCHexEscape(overload.name)); }))}; } absl::string_view DispatchOperator::py_qvalue_specialization_key() const { return "::arolla::operator_loader::DispatchOperator"; } }
#include "arolla/expr/operator_loader/dispatch_operator.h" #include <cstdint> #include <memory> #include <utility> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_attributes.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/expr/lambda_expr_operator.h" #include "arolla/expr/operator_loader/qtype_constraint.h" #include "arolla/expr/operator_loader/restricted_lambda_operator.h" #include "arolla/expr/testing/testing.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/typed_value.h" #include "arolla/util/bytes.h" #include "arolla/util/init_arolla.h" #include "arolla/util/testing/repr_token_eq.h" #include "arolla/util/testing/status_matchers_backport.h" #include "arolla/util/status_macros_backport.h" namespace arolla::operator_loader { namespace { using ::arolla::GetNothingQType; using ::arolla::expr::CallOp; using ::arolla::expr::ExprOperatorSignature; using ::arolla::expr::LambdaOperator; using ::arolla::expr::Leaf; using ::arolla::expr::Literal; using ::arolla::expr::Placeholder; using ::arolla::testing::EqualsAttr; using ::arolla::testing::EqualsExpr; using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::ReprTokenEq; using ::arolla::testing::StatusIs; using ::arolla::testing::WithQTypeAnnotation; using ::testing::HasSubstr; using Attr = ::arolla::expr::ExprAttributes; class DispatchOperatorTest : public ::testing::Test { protected: void SetUp() override { ASSERT_OK(InitArolla()); } static absl::StatusOr<expr::ExprNodePtr> arg_first() { return CallOp("core.get_nth", {Leaf("input_tuple_qtype"), Literal(0)}); } static absl::StatusOr<expr::ExprNodePtr> arg_second() { return CallOp("core.get_nth", {Leaf("input_tuple_qtype"), Literal(1)}); } static absl::StatusOr<expr::ExprNodePtr> arg_first_qtype() { return CallOp("qtype.get_field_qtype", {Leaf("input_tuple_qtype"), Literal(0)}); } static absl::StatusOr<expr::ExprNodePtr> args_from_second_qtype() { return CallOp("qtype.slice_tuple_qtype", {Leaf("input_tuple_qtype"), Literal(1), Literal(-1)}); } static absl::StatusOr<std::shared_ptr<const LambdaOperator>> MakeBaseBinaryOp() { return expr::MakeLambdaOperator( "with_name", ExprOperatorSignature{{"x"}, {"name"}}, SuppressUnusedWarning("name", Placeholder("x")), "doc-string-for-lambda"); } static absl::StatusOr<QTypeConstraint> MakeBaseBinaryQTypeConstraint() { ASSIGN_OR_RETURN(auto predicate_expr, CallOp("core.equal", {Placeholder("name"), Literal(GetQType<Bytes>())})); return QTypeConstraint{predicate_expr, "expected name to be bytes, got {name}"}; } static absl::StatusOr<std::shared_ptr<const RestrictedLambdaOperator>> MakeBinaryOp() { ASSIGN_OR_RETURN(auto lambda_op, MakeBaseBinaryOp()); ASSIGN_OR_RETURN(auto qtype_constraint, MakeBaseBinaryQTypeConstraint()); ASSIGN_OR_RETURN(auto restricted_lambda_op, RestrictedLambdaOperator::Make( std::move(lambda_op), {std::move(qtype_constraint)})); return std::dynamic_pointer_cast<const RestrictedLambdaOperator>( restricted_lambda_op); } static absl::StatusOr<std::shared_ptr<const LambdaOperator>> MakeBaseUnaryOp() { return expr::MakeLambdaOperator("noop", ExprOperatorSignature{{"x"}}, Placeholder("x"), "doc-string-for-unary-case"); } static absl::StatusOr<QTypeConstraint> MakeBaseUnaryQTypeConstraint() { ASSIGN_OR_RETURN(auto predicate_expr, CallOp("qtype.is_numeric_qtype", {Placeholder("x")})); return QTypeConstraint{predicate_expr, "expected x to be numeric, got {x}"}; } static absl::StatusOr<std::shared_ptr<const RestrictedLambdaOperator>> MakeUnaryOp() { ASSIGN_OR_RETURN(auto lambda_op, MakeBaseUnaryOp()); ASSIGN_OR_RETURN(auto qtype_constraint, MakeBaseUnaryQTypeConstraint()); ASSIGN_OR_RETURN(auto restricted_lambda_op, RestrictedLambdaOperator::Make( std::move(lambda_op), {std::move(qtype_constraint)})); return std::dynamic_pointer_cast<const RestrictedLambdaOperator>( restricted_lambda_op); } static absl::StatusOr<expr::ExprNodePtr> MakeUnaryCondition() { auto one_argument = CallOp("core.equal", {CallOp("qtype.get_field_count", {args_from_second_qtype()}), Literal(0)}); auto is_numeric = CallOp("qtype.is_scalar_qtype", {arg_first_qtype()}); return CallOp("core.presence_and", {one_argument, is_numeric}); } static absl::StatusOr<expr::ExprNodePtr> MakeDispatchReadinessCondition( const std::vector<int64_t> ids) { auto expr = CallOp("core.not_equal", {Leaf("input_tuple_qtype"), Literal(GetNothingQType())}); for (auto id : ids) { auto additional_expr = CallOp( "core.not_equal", {CallOp("qtype.get_field_qtype", {Leaf("input_tuple_qtype"), Literal(id)}), Literal(GetNothingQType())}); expr = CallOp("core.presence_and", {expr, additional_expr}); } return expr; } static absl::StatusOr<std::shared_ptr<const DispatchOperator>> MakeOp() { ASSIGN_OR_RETURN(auto binary_op, MakeBinaryOp()); ASSIGN_OR_RETURN(auto unary_op, MakeUnaryOp()); ASSIGN_OR_RETURN(auto unary_condition, MakeUnaryCondition()); ASSIGN_OR_RETURN(auto not_unary_condition, CallOp("core.presence_not", {unary_condition})); ASSIGN_OR_RETURN(auto readiness_condition, MakeDispatchReadinessCondition({0})); ASSIGN_OR_RETURN( auto dispatch_op, DispatchOperator::Make("op.name", expr::ExprOperatorSignature{ {"x"}, {.name = "args", .kind = ExprOperatorSignature::Parameter:: Kind::kVariadicPositional}}, {{.name = "unary\tcase", .op = std::move(unary_op), .condition = std::move(unary_condition)}, {.name = "default", .op = std::move(binary_op), .condition = std::move(not_unary_condition)}}, readiness_condition)); return std::dynamic_pointer_cast<const DispatchOperator>(dispatch_op); } static absl::StatusOr<std::shared_ptr<const DispatchOperator>> MakeOpNoDefault() { ASSIGN_OR_RETURN(auto no_op, MakeBaseUnaryOp()); ASSIGN_OR_RETURN(auto unary_op, MakeUnaryOp()); ASSIGN_OR_RETURN(auto unary_condition, MakeUnaryCondition()); ASSIGN_OR_RETURN(auto readiness_condition, MakeDispatchReadinessCondition({0})); ASSIGN_OR_RETURN( auto dispatch_op, DispatchOperator::Make("op.name", expr::ExprOperatorSignature{ {"x"}, {.name = "args", .kind = ExprOperatorSignature::Parameter:: Kind::kVariadicPositional}}, {{.name = "unary\tcase", .op = std::move(unary_op), .condition = std::move(unary_condition)}}, readiness_condition)); return std::dynamic_pointer_cast<const DispatchOperator>(dispatch_op); } static absl::StatusOr<std::shared_ptr<const DispatchOperator>> MakeDuplicatedOp() { ASSIGN_OR_RETURN(auto binary_op, MakeBinaryOp()); ASSIGN_OR_RETURN(auto unary_op_a, MakeUnaryOp()); ASSIGN_OR_RETURN(auto unary_op_b, MakeUnaryOp()); ASSIGN_OR_RETURN(auto unary_condition_a, MakeUnaryCondition()); ASSIGN_OR_RETURN(auto unary_condition_b, MakeUnaryCondition()); ASSIGN_OR_RETURN(auto not_unary_condition, CallOp("core.presence_not", {unary_condition_a})); ASSIGN_OR_RETURN(auto readiness_condition, MakeDispatchReadinessCondition({0})); ASSIGN_OR_RETURN( auto dispatch_op, DispatchOperator::Make("op.name", expr::ExprOperatorSignature{ {"x"}, {.name = "args", .kind = ExprOperatorSignature::Parameter:: Kind::kVariadicPositional}}, {{.name = "unary_case_a", .op = std::move(unary_op_a), .condition = std::move(unary_condition_a)}, {.name = "unary_case_b", .op = std::move(unary_op_b), .condition = std::move(unary_condition_b)}, {.name = "binary_case", .op = std::move(binary_op), .condition = std::move(not_unary_condition)}}, readiness_condition)); return std::dynamic_pointer_cast<const DispatchOperator>(dispatch_op); } }; } TEST_F(DispatchOperatorTest, PublicProperties) { ASSERT_OK_AND_ASSIGN(auto op, MakeOp()); EXPECT_EQ(op->display_name(), "op.name"); EXPECT_EQ(op->doc(), ""); } TEST_F(DispatchOperatorTest, InferAttributes) { ASSERT_OK_AND_ASSIGN(auto op, MakeOp()); EXPECT_THAT(op->InferAttributes({Attr{}}), IsOkAndHolds(EqualsAttr(nullptr))); EXPECT_THAT(op->InferAttributes({Attr{}, Attr{}}), IsOkAndHolds(EqualsAttr(nullptr))); EXPECT_THAT(op->InferAttributes({Attr{}, Attr{}, Attr{}}), IsOkAndHolds(EqualsAttr(nullptr))); EXPECT_THAT(op->InferAttributes({Attr(GetQType<int>()), Attr{}, Attr{}}), StatusIs(absl::StatusCode::kInvalidArgument, "incorrect number of dependencies passed to an " "operator node: expected 2 but got 3; in default " "overload of DispatchOperator")); EXPECT_THAT(op->InferAttributes({}), StatusIs(absl::StatusCode::kInvalidArgument, "incorrect number of dependencies passed to an " "operator node: expected 1 but got 0")); EXPECT_THAT(op->InferAttributes({Attr(GetQType<Bytes>())}), StatusIs(absl::StatusCode::kInvalidArgument, "expected x to be numeric, got BYTES; in unary\\tcase " "overload of DispatchOperator")); EXPECT_THAT(op->InferAttributes({Attr(GetQType<int>())}), IsOkAndHolds(EqualsAttr(GetQType<int>()))); EXPECT_THAT(op->InferAttributes({Attr(GetQType<int>()), Attr{}}), IsOkAndHolds(EqualsAttr(nullptr))); EXPECT_THAT( op->InferAttributes({Attr(GetQType<int>()), Attr(GetQType<Bytes>())}), IsOkAndHolds(EqualsAttr(GetQType<int>()))); } TEST_F(DispatchOperatorTest, InferAttributesNoDefault) { ASSERT_OK_AND_ASSIGN(auto op, MakeOpNoDefault()); EXPECT_THAT(op->InferAttributes({Attr{}}), IsOkAndHolds(EqualsAttr(nullptr))); EXPECT_THAT(op->InferAttributes({Attr{}, Attr{}}), IsOkAndHolds(EqualsAttr(nullptr))); EXPECT_THAT( op->InferAttributes({Attr(GetQType<int>()), Attr{}}), StatusIs(absl::StatusCode::kInvalidArgument, "no suitable overload for argument types (INT32,NOTHING)")); EXPECT_THAT(op->InferAttributes({}), StatusIs(absl::StatusCode::kInvalidArgument, "incorrect number of dependencies passed to an " "operator node: expected 1 but got 0")); EXPECT_THAT(op->InferAttributes({Attr(GetQType<Bytes>())}), StatusIs(absl::StatusCode::kInvalidArgument, "expected x to be numeric, got BYTES; in unary\\tcase " "overload of DispatchOperator")); EXPECT_THAT(op->InferAttributes({Attr(GetQType<int>())}), IsOkAndHolds(EqualsAttr(GetQType<int>()))); } TEST_F(DispatchOperatorTest, SignatureWithDefaultValues) { ASSERT_OK_AND_ASSIGN(auto binary_op, MakeBinaryOp()); ASSERT_OK_AND_ASSIGN(auto unary_op, MakeUnaryOp()); ASSERT_OK_AND_ASSIGN(auto readiness_condition, MakeDispatchReadinessCondition({})); ASSERT_OK_AND_ASSIGN(auto predicate_expr_xx, CallOp("core.equal", {arg_first(), arg_first()})); EXPECT_THAT( DispatchOperator::Make("op", expr::ExprOperatorSignature{ {.name = "x", .default_value = TypedValue::FromValue(false), .kind = ExprOperatorSignature::Parameter:: Kind::kPositionalOrKeyword}}, {{.name = "foo", .op = std::move(binary_op), .condition = std::move(predicate_expr_xx)}}, readiness_condition), StatusIs(absl::StatusCode::kInvalidArgument, "signatures with the default values are not supported in " "dispatch operator; got signature: x=")); } TEST_F(DispatchOperatorTest, ToLowerLevel) { auto leaf = Leaf("leaf"); ASSERT_OK_AND_ASSIGN(auto leaf_with_qtype, WithQTypeAnnotation(Leaf("leaf"), GetQType<float>())); ASSERT_OK_AND_ASSIGN(auto leaf_with_nothing_qtype, WithQTypeAnnotation(Leaf("leaf"), GetNothingQType())); auto name_literal = Literal(Bytes("name")); auto name_placeholder = Placeholder("name"); { ASSERT_OK_AND_ASSIGN(auto expr, CallOp(MakeOp(), {leaf})); ASSERT_OK_AND_ASSIGN(auto noop_leaf, CallOp(MakeUnaryOp(), {leaf})); EXPECT_EQ(expr->qtype(), nullptr); EXPECT_THAT(ToLowest(expr), IsOkAndHolds(EqualsExpr(expr))); } { ASSERT_OK_AND_ASSIGN(auto expr, CallOp(MakeOp(), {leaf, name_placeholder})); ASSERT_OK_AND_ASSIGN(auto binary_op, CallOp(MakeBinaryOp(), {leaf, name_placeholder})); EXPECT_EQ(expr->qtype(), nullptr); EXPECT_THAT(ToLowest(expr), IsOkAndHolds(EqualsExpr(expr))); } { ASSERT_OK_AND_ASSIGN(auto expr, CallOp(MakeOp(), {leaf, name_literal})); ASSERT_OK_AND_ASSIGN(auto binary_op, CallOp(MakeBinaryOp(), {leaf, name_literal})); EXPECT_EQ(expr->qtype(), nullptr); EXPECT_THAT(ToLowest(expr), IsOkAndHolds(EqualsExpr(expr))); } { ASSERT_OK_AND_ASSIGN(auto expr, CallOp(MakeOp(), {leaf_with_qtype})); EXPECT_EQ(expr->qtype(), GetQType<float>()); EXPECT_THAT(ToLowest(expr), IsOkAndHolds(EqualsExpr(leaf_with_qtype))); } { ASSERT_OK_AND_ASSIGN(auto expr, CallOp(MakeOp(), {leaf_with_qtype, name_placeholder})); ASSERT_OK_AND_ASSIGN( auto binary_op, CallOp(MakeBinaryOp(), {leaf_with_qtype, name_placeholder})); EXPECT_EQ(expr->qtype(), nullptr); EXPECT_THAT(ToLowest(expr), IsOkAndHolds(EqualsExpr(binary_op))); } { ASSERT_OK_AND_ASSIGN(auto expr, CallOp(MakeOp(), {leaf_with_qtype, name_literal})); EXPECT_EQ(expr->qtype(), GetQType<float>()); EXPECT_THAT(ToLowest(expr), IsOkAndHolds(EqualsExpr(leaf_with_qtype))); } { ASSERT_OK_AND_ASSIGN( auto expr, CallOp(MakeDuplicatedOp(), {leaf_with_qtype, name_literal})); EXPECT_EQ(expr->qtype(), GetQType<float>()); EXPECT_THAT(ToLowest(expr), IsOkAndHolds(EqualsExpr(leaf_with_qtype))); } { EXPECT_THAT( CallOp(MakeDuplicatedOp(), {leaf_with_qtype}), StatusIs( absl::StatusCode::kFailedPrecondition, HasSubstr("constraints of the multiple overloads (unary_case_a, " "unary_case_b) passed for argument types (FLOAT32)"))); } { EXPECT_THAT(CallOp(MakeOp(), {}), StatusIs(absl::StatusCode::kInvalidArgument, "missing 1 required argument: 'x'; while binding " "operator 'op.name'")); } { EXPECT_THAT( CallOp(MakeOp(), {leaf_with_nothing_qtype}), StatusIs( absl::StatusCode::kFailedPrecondition, HasSubstr("the operator is broken for argument types (NOTHING)"))); } { ASSERT_OK_AND_ASSIGN(auto expr, CallOp(MakeOp(), {leaf_with_nothing_qtype, leaf})); ASSERT_OK_AND_ASSIGN(auto binary_op, CallOp(MakeBinaryOp(), {leaf, name_literal})); EXPECT_EQ(expr->qtype(), nullptr); EXPECT_THAT(ToLowest(expr), IsOkAndHolds(EqualsExpr(expr))); } { EXPECT_THAT(CallOp(MakeOp(), {leaf_with_nothing_qtype, leaf_with_qtype}), StatusIs(absl::StatusCode::kFailedPrecondition, HasSubstr("the operator is broken for argument types " "(NOTHING,FLOAT32)"))); } } TEST_F(DispatchOperatorTest, Repr) { ASSERT_OK_AND_ASSIGN(auto op, MakeOp()); EXPECT_THAT(op->GenReprToken(), ReprTokenEq("<DispatchOperator: name='op.name', signature='x, " "*args', cases=['unary\\tcase', 'default']>")); } }
2,467
#ifndef AROLLA_EXPR_VISITORS_SUBSTITUTION_H_ #define AROLLA_EXPR_VISITORS_SUBSTITUTION_H_ #include <string> #include "absl/container/flat_hash_map.h" #include "absl/status/statusor.h" #include "arolla/expr/expr_node.h" #include "arolla/util/fingerprint.h" namespace arolla::expr { absl::StatusOr<ExprNodePtr> SubstituteByName( ExprNodePtr expr, const absl::flat_hash_map<std::string, ExprNodePtr>& subs); absl::StatusOr<ExprNodePtr> SubstituteLeaves( ExprNodePtr expr, const absl::flat_hash_map<std::string, ExprNodePtr>& subs); absl::StatusOr<ExprNodePtr> SubstitutePlaceholders( ExprNodePtr expr, const absl::flat_hash_map<std::string, ExprNodePtr>& subs, bool must_substitute_all = false); absl::StatusOr<ExprNodePtr> SubstituteByFingerprint( ExprNodePtr expr, const absl::flat_hash_map<Fingerprint, ExprNodePtr>& subs); } #endif #include "arolla/expr/visitors/substitution.h" #include <optional> #include <string> #include "absl/container/flat_hash_map.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "absl/types/span.h" #include "arolla/expr/annotation_utils.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_visitor.h" #include "arolla/util/fingerprint.h" namespace arolla::expr { namespace { template <class Key, class KeyFn> absl::StatusOr<ExprNodePtr> Substitute( ExprNodePtr expr, const absl::flat_hash_map<Key, ExprNodePtr>& subs, KeyFn key_fn) { return PostOrderTraverse( expr, [&](const ExprNodePtr& node, absl::Span<const ExprNodePtr* const> visits) -> absl::StatusOr<ExprNodePtr> { if (auto key = key_fn(node); key.has_value()) { if (auto it = subs.find(*key); it != subs.end()) { return it->second; } } return WithNewDependencies(node, DereferenceVisitPointers(visits)); }); } } absl::StatusOr<ExprNodePtr> SubstituteByName( ExprNodePtr expr, const absl::flat_hash_map<std::string, ExprNodePtr>& subs) { return Substitute(expr, subs, [](const auto& expr) -> std::optional<std::string> { if (IsNameAnnotation(expr)) { return std::string(ReadNameAnnotation(expr)); } return std::nullopt; }); } absl::StatusOr<ExprNodePtr> SubstituteLeaves( ExprNodePtr expr, const absl::flat_hash_map<std::string, ExprNodePtr>& subs) { return Substitute(expr, subs, [](const auto& expr) -> std::optional<std::string> { if (expr->is_leaf()) return expr->leaf_key(); return std::nullopt; }); } absl::StatusOr<ExprNodePtr> SubstitutePlaceholders( ExprNodePtr expr, const absl::flat_hash_map<std::string, ExprNodePtr>& subs, bool must_substitute_all) { return PostOrderTraverse( expr, [&](const ExprNodePtr& node, absl::Span<const ExprNodePtr* const> visits) -> absl::StatusOr<ExprNodePtr> { if (node->is_placeholder()) { if (subs.contains(node->placeholder_key())) { return subs.at(node->placeholder_key()); } else if (must_substitute_all) { return absl::InvalidArgumentError(absl::StrFormat( "No value was provided for P.%s, but substitution of all " "placeholders was requested.", node->placeholder_key())); } } return WithNewDependencies(node, DereferenceVisitPointers(visits)); }); } absl::StatusOr<ExprNodePtr> SubstituteByFingerprint( ExprNodePtr expr, const absl::flat_hash_map<Fingerprint, ExprNodePtr>& subs) { return Substitute(expr, subs, [](const auto& expr) -> std::optional<Fingerprint> { return expr->fingerprint(); }); } }
#include "arolla/expr/visitors/substitution.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/container/flat_hash_map.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/testing/testing.h" #include "arolla/util/fingerprint.h" #include "arolla/util/init_arolla.h" #include "arolla/util/testing/status_matchers_backport.h" namespace arolla::expr { namespace { using ::arolla::testing::EqualsExpr; using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::WithNameAnnotation; class SubstitutionTest : public ::testing::Test { void SetUp() override { ASSERT_OK(InitArolla()); } }; TEST_F(SubstitutionTest, SubsByName) { ASSERT_OK_AND_ASSIGN(auto x, WithNameAnnotation(Leaf("x"), "lx")); ASSERT_OK_AND_ASSIGN(auto y, WithNameAnnotation(Leaf("y"), "ly")); ASSERT_OK_AND_ASSIGN(auto z, WithNameAnnotation(Leaf("z"), "lz")); ASSERT_OK_AND_ASSIGN(ExprNodePtr expr, CallOp("math.add", {x, y})); ASSERT_OK_AND_ASSIGN(ExprNodePtr expected_expr, CallOp("math.add", {x, z})); EXPECT_THAT(SubstituteByName(expr, {{"ly", z}}), IsOkAndHolds(EqualsExpr(expected_expr))); } TEST_F(SubstitutionTest, SubstituteLeavesByName) { ASSERT_OK_AND_ASSIGN(auto x, WithNameAnnotation(Leaf("x"), "lx")); ASSERT_OK_AND_ASSIGN(auto y, WithNameAnnotation(Leaf("y"), "ly")); EXPECT_THAT(SubstituteByName(x, {{"lx", y}}), IsOkAndHolds(EqualsExpr(y))); } TEST_F(SubstitutionTest, SubstitutePlaceholdersByName) { ASSERT_OK_AND_ASSIGN(auto x, WithNameAnnotation(Placeholder("x"), "px")); ASSERT_OK_AND_ASSIGN(auto y, WithNameAnnotation(Placeholder("y"), "py")); EXPECT_THAT(SubstituteByName(x, {{"px", y}}), IsOkAndHolds(EqualsExpr(y))); EXPECT_THAT(SubstituteByName(x, {{"x", y}}), IsOkAndHolds(EqualsExpr(x))); } TEST_F(SubstitutionTest, SubstitutePlaceholders) { auto px = Placeholder("x"); auto py = Placeholder("y"); ASSERT_OK_AND_ASSIGN(auto x, WithNameAnnotation(px, "name")); ASSERT_OK_AND_ASSIGN(auto y, WithNameAnnotation(py, "name")); EXPECT_THAT(SubstitutePlaceholders(x, {{"x", py}}), IsOkAndHolds(EqualsExpr(y))); EXPECT_THAT(SubstitutePlaceholders(x, {{"name", py}}), IsOkAndHolds(EqualsExpr(x))); } TEST_F(SubstitutionTest, SubstituteLeaves) { auto lx = Leaf("x"); auto ly = Leaf("y"); ASSERT_OK_AND_ASSIGN(auto x, WithNameAnnotation(lx, "name")); ASSERT_OK_AND_ASSIGN(auto y, WithNameAnnotation(ly, "name")); EXPECT_THAT(SubstituteLeaves(x, {{"x", ly}}), IsOkAndHolds(EqualsExpr(y))); EXPECT_THAT(SubstituteLeaves(x, {{"name", ly}}), IsOkAndHolds(EqualsExpr(x))); } TEST_F(SubstitutionTest, SubsByFingerprint) { ASSERT_OK_AND_ASSIGN(auto x, WithNameAnnotation(Leaf("x"), "lx")); ASSERT_OK_AND_ASSIGN(auto y, WithNameAnnotation(Leaf("y"), "lx")); ASSERT_OK_AND_ASSIGN(auto z, WithNameAnnotation(Leaf("z"), "lz")); ASSERT_OK_AND_ASSIGN(auto x_add_expr, CallOp("math.add", {x, x})); ASSERT_OK_AND_ASSIGN(auto expr, CallOp("math.add", {x_add_expr, y})); absl::flat_hash_map<Fingerprint, ExprNodePtr> subs = { {x->fingerprint(), y}, {x_add_expr->fingerprint(), z}, {y->fingerprint(), x}}; ASSERT_OK_AND_ASSIGN(ExprNodePtr expected_expr, CallOp("math.add", {z, x})); EXPECT_THAT(SubstituteByFingerprint(expr, subs), IsOkAndHolds(EqualsExpr(expected_expr))); } } }
2,468
#ifndef AROLLA_EXPR_EVAL_COMPILE_WHILE_OPERATOR_H_ #define AROLLA_EXPR_EVAL_COMPILE_WHILE_OPERATOR_H_ #include "absl/status/status.h" #include "absl/types/span.h" #include "arolla/expr/eval/eval.h" #include "arolla/expr/eval/executable_builder.h" #include "arolla/expr/operators/while_loop/while_loop.h" #include "arolla/qtype/qtype.h" namespace arolla::expr::eval_internal { absl::Status CompileWhileOperator( const DynamicEvaluationEngineOptions& options, const expr_operators::WhileLoopOperator& while_op, absl::Span<const TypedSlot> input_slots, TypedSlot output_slot, ExecutableBuilder& executable_builder); } #endif #include "arolla/expr/eval/compile_while_operator.h" #include <memory> #include <optional> #include <string> #include <utility> #include <vector> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "absl/types/span.h" #include "arolla/expr/eval/eval.h" #include "arolla/expr/eval/evaluator_operators.h" #include "arolla/expr/eval/executable_builder.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/operators/while_loop/while_loop.h" #include "arolla/memory/frame.h" #include "arolla/memory/optional_value.h" #include "arolla/qexpr/eval_context.h" #include "arolla/qexpr/evaluation_engine.h" #include "arolla/qexpr/operators.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/typed_slot.h" #include "arolla/util/status_macros_backport.h" namespace arolla::expr::eval_internal { namespace { struct BoundLoopOperators { std::shared_ptr<const BoundExpr> condition; std::shared_ptr<const BoundExpr> body; }; class WhileLoopBoundOperator : public BoundOperator { public: WhileLoopBoundOperator(BoundLoopOperators operators_on_out, BoundLoopOperators operators_on_tmp, FrameLayout::Slot<OptionalUnit> condition_slot, TypedSlot initial_state_slot, TypedSlot tmp_state_slot, TypedSlot output_state_slot) : operators_on_out_(std::move(operators_on_out)), operators_on_tmp_(std::move(operators_on_tmp)), condition_slot_(condition_slot), initial_state_slot_(initial_state_slot), tmp_state_slot_(tmp_state_slot), output_state_slot_(output_state_slot) {} void Run(EvaluationContext* ctx, FramePtr frame) const override { initial_state_slot_.CopyTo(frame, output_state_slot_, frame); for (;;) { operators_on_out_.condition->Execute(ctx, frame); if (!ctx->status().ok() || !frame.Get(condition_slot_)) { break; } operators_on_out_.body->Execute(ctx, frame); if (!ctx->status().ok()) { break; } operators_on_tmp_.condition->Execute(ctx, frame); if (!ctx->status().ok() || !frame.Get(condition_slot_)) { tmp_state_slot_.CopyTo(frame, output_state_slot_, frame); break; } operators_on_tmp_.body->Execute(ctx, frame); if (!ctx->status().ok()) { break; } } } private: BoundLoopOperators operators_on_out_; BoundLoopOperators operators_on_tmp_; FrameLayout::Slot<OptionalUnit> condition_slot_; TypedSlot initial_state_slot_; TypedSlot tmp_state_slot_; TypedSlot output_state_slot_; }; absl::StatusOr<std::shared_ptr<BoundExpr>> CompileAndBindExprOperator( const DynamicEvaluationEngineOptions& options, const ExprOperatorPtr& op, absl::Span<const TypedSlot> input_slots, std::optional<TypedSlot> output_slot, ExecutableBuilder& executable_builder) { ASSIGN_OR_RETURN( auto evaluator, CompileAndBindExprOperator(options, executable_builder.layout_builder(), op, input_slots, output_slot), _ << "in loop condition"); executable_builder.AddInitOp( std::make_unique<InitializeAstLiteralsBoundOperator>(evaluator), "internal.while_loop:initialize_literals()"); return evaluator; } absl::StatusOr<BoundLoopOperators> BindLoopOperators( const DynamicEvaluationEngineOptions& options, const expr_operators::WhileLoopOperator& while_op, absl::Span<const TypedSlot> constant_slots, TypedSlot current_state_slot, TypedSlot next_state_slot, FrameLayout::Slot<OptionalUnit> condition_slot, ExecutableBuilder& executable_builder) { std::vector<TypedSlot> input_slots; input_slots.reserve(1 + constant_slots.size()); input_slots.push_back(current_state_slot); input_slots.insert(input_slots.end(), constant_slots.begin(), constant_slots.end()); ASSIGN_OR_RETURN(auto condition_on_out_op, CompileAndBindExprOperator( options, while_op.condition(), input_slots, TypedSlot::FromSlot(condition_slot), executable_builder), _ << "in loop condition"); ASSIGN_OR_RETURN( auto body_out_to_tmp_op, CompileAndBindExprOperator(options, while_op.body(), input_slots, next_state_slot, executable_builder), _ << "in loop body"); return BoundLoopOperators{std::move(condition_on_out_op), std::move(body_out_to_tmp_op)}; } } absl::Status CompileWhileOperator( const DynamicEvaluationEngineOptions& options, const expr_operators::WhileLoopOperator& while_op, absl::Span<const TypedSlot> input_slots, TypedSlot output_slot, ExecutableBuilder& executable_builder) { if (input_slots.empty()) { return absl::InvalidArgumentError( "unexpected number of input slots: expected at least 1 slot, got 0"); } TypedSlot initial_state_slot = input_slots[0]; if (output_slot.GetType() != initial_state_slot.GetType()) { return absl::InvalidArgumentError(absl::StrFormat( "unexpected type of output slot: expected %s slot, got %s", initial_state_slot.GetType()->name(), output_slot.GetType()->name())); } FrameLayout::Slot<OptionalUnit> condition_slot = executable_builder.layout_builder()->AddSlot<OptionalUnit>(); TypedSlot tmp_state_slot = AddSlot(output_slot.GetType(), executable_builder.layout_builder()); DynamicEvaluationEngineOptions subexpression_options(options); subexpression_options.enabled_preparation_stages = DynamicEvaluationEngineOptions::PreparationStage::kAll; ASSIGN_OR_RETURN(auto operators_on_out, BindLoopOperators(subexpression_options, while_op, input_slots.subspan(1), output_slot, tmp_state_slot, condition_slot, executable_builder)); ASSIGN_OR_RETURN(auto operators_on_tmp, BindLoopOperators(subexpression_options, while_op, input_slots.subspan(1), tmp_state_slot, output_slot, condition_slot, executable_builder)); std::vector<TypedSlot> used_slots(input_slots.begin(), input_slots.end()); used_slots.push_back(tmp_state_slot); used_slots.push_back(TypedSlot::FromSlot(condition_slot)); executable_builder.AddEvalOp( std::make_unique<WhileLoopBoundOperator>( std::move(operators_on_out), std::move(operators_on_tmp), condition_slot, initial_state_slot, tmp_state_slot, output_slot), eval_internal::FormatOperatorCall("internal.while_loop", input_slots, {output_slot}), "internal.while_loop"); return absl::OkStatus(); } }
#include <cstddef> #include <cstdint> #include <utility> #include "benchmark/benchmark.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/log/check.h" #include "absl/status/statusor.h" #include "arolla/dense_array/dense_array.h" #include "arolla/dense_array/qtype/types.h" #include "arolla/expr/eval/eval.h" #include "arolla/expr/eval/invoke.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/operators/while_loop/while_loop.h" #include "arolla/expr/visitors/substitution.h" #include "arolla/memory/frame.h" #include "arolla/qexpr/eval_context.h" #include "arolla/qtype/testing/qtype.h" #include "arolla/qtype/typed_slot.h" #include "arolla/qtype/typed_value.h" #include "arolla/util/init_arolla.h" #include "arolla/util/testing/status_matchers_backport.h" #include "arolla/util/text.h" #include "arolla/util/status_macros_backport.h" namespace arolla::expr::eval_internal { namespace { using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::TypedValueWith; using ::testing::ElementsAre; using ::testing::Eq; class WhileOperatorTest : public ::testing::TestWithParam<DynamicEvaluationEngineOptions> { protected: void SetUp() override { ASSERT_OK(InitArolla()); } DynamicEvaluationEngineOptions GetOptions() const { return GetParam(); } }; INSTANTIATE_TEST_SUITE_P( GarbageCollection, WhileOperatorTest, ::testing::Values( DynamicEvaluationEngineOptions{.allow_overriding_input_slots = false}, DynamicEvaluationEngineOptions{.allow_overriding_input_slots = true})); TEST_P(WhileOperatorTest, SimpleWhile) { auto init_x = Leaf("x"); auto init_y = Leaf("y"); ASSERT_OK_AND_ASSIGN( auto loop_condition, CallOp("core.not_equal", {Placeholder("y"), Literal<int64_t>(0)})); auto new_x = Placeholder("y"); ASSERT_OK_AND_ASSIGN( auto new_y, CallOp("math.mod", {Placeholder("x"), Placeholder("y")})); ASSERT_OK_AND_ASSIGN(ExprNodePtr while_loop, expr_operators::MakeWhileLoop( {{"x", init_x}, {"y", init_y}}, loop_condition, {{"x", new_x}, {"y", new_y}})); ASSERT_OK_AND_ASSIGN( ExprNodePtr gcd, CallOp("namedtuple.get_field", {while_loop, Literal(Text("x"))})); EXPECT_THAT(Invoke(gcd, {{"x", TypedValue::FromValue<int64_t>(57)}, {"y", TypedValue::FromValue<int64_t>(58)}}, GetOptions()), IsOkAndHolds(TypedValueWith<int64_t>(Eq(1)))); EXPECT_THAT(Invoke(gcd, {{"x", TypedValue::FromValue<int64_t>(171)}, {"y", TypedValue::FromValue<int64_t>(285)}}, GetOptions()), IsOkAndHolds(TypedValueWith<int64_t>(Eq(57)))); } absl::StatusOr<ExprNodePtr> SumOfXs(int64_t number_of_xs) { auto init_n = Literal<int64_t>(1); auto init_x = Leaf("x"); auto init_accumulator = Leaf("x"); ASSIGN_OR_RETURN(auto loop_condition, CallOp("core.not_equal", {Placeholder("n"), Literal<int64_t>(number_of_xs)})); ASSIGN_OR_RETURN(auto new_n, CallOp("math.add", {Placeholder("n"), Literal<int64_t>(1)})); ASSIGN_OR_RETURN( auto new_accumulator, CallOp("math.add", {Placeholder("accumulator"), Placeholder("x")})); return CallOp( "namedtuple.get_field", {expr_operators::MakeWhileLoop( {{"n", init_n}, {"x", init_x}, {"accumulator", init_accumulator}}, loop_condition, {{"n", new_n}, {"accumulator", new_accumulator}}), Literal(Text("accumulator"))}); } TEST_P(WhileOperatorTest, LoopWithDifferentNumberOfIterations) { for (int64_t iterations = 0; iterations < 10; ++iterations) { ASSERT_OK_AND_ASSIGN(ExprNodePtr sum, SumOfXs(iterations + 1)); EXPECT_THAT( Invoke(sum, {{"x", TypedValue::FromValue<int64_t>(57)}}, GetOptions()), IsOkAndHolds(TypedValueWith<int64_t>(57 * (iterations + 1)))); } } TEST_P(WhileOperatorTest, LoopWithDenseArray) { ASSERT_OK_AND_ASSIGN(ExprNodePtr sum_of_1000, SumOfXs(1000)); EXPECT_THAT(Invoke(sum_of_1000, {{"x", TypedValue::FromValue<int64_t>(1)}}, GetOptions()), IsOkAndHolds(TypedValueWith<int64_t>(1000))); EXPECT_THAT( Invoke( sum_of_1000, {{"x", TypedValue::FromValue(CreateDenseArray<int64_t>({0, 1, 2}))}}, GetOptions()), IsOkAndHolds( TypedValueWith<DenseArray<int64_t>>(ElementsAre(0, 1000, 2000)))); auto init_x = Leaf("x"); ASSERT_OK_AND_ASSIGN( ExprNodePtr sum_of_1000_1000, SubstituteByFingerprint(sum_of_1000, {{init_x->fingerprint(), sum_of_1000}})); EXPECT_THAT( Invoke( sum_of_1000_1000, {{"x", TypedValue::FromValue(CreateDenseArray<int64_t>({0, 1, 2}))}}, GetOptions()), IsOkAndHolds(TypedValueWith<DenseArray<int64_t>>( ElementsAre(0, 1000000, 2000000)))); } template <typename T> void BM_WhileOperator(benchmark::State& state, T initial_value) { CHECK_OK(InitArolla()); auto sum_of_1000_x = SumOfXs(1000).value(); FrameLayout::Builder builder; auto x_slot = builder.AddSlot<T>(); auto sum_of_1000_x_expr = CompileAndBindForDynamicEvaluation(DynamicEvaluationEngineOptions(), &builder, sum_of_1000_x, {{"x", TypedSlot::FromSlot(x_slot)}}) .value(); FrameLayout layout = std::move(builder).Build(); RootEvaluationContext ctx(&layout); CHECK_OK(sum_of_1000_x_expr->InitializeLiterals(&ctx)); for (auto _ : state) { CHECK_OK(sum_of_1000_x_expr->Execute(&ctx)); } } void BM_WhileOperator_Scalar(benchmark::State& state) { BM_WhileOperator(state, int64_t{57}); } BENCHMARK(BM_WhileOperator_Scalar); void BM_WhileOperator_DenseArray(benchmark::State& state) { constexpr size_t kArraySize = 100; BM_WhileOperator(state, CreateConstDenseArray<int64_t>(kArraySize, 57)); } BENCHMARK(BM_WhileOperator_DenseArray); } }
2,469
#ifndef AROLLA_EXPR_EVAL_EXPR_UTILS_H_ #define AROLLA_EXPR_EVAL_EXPR_UTILS_H_ #include <functional> #include "absl/status/statusor.h" #include "arolla/expr/expr_node.h" namespace arolla::expr::eval_internal { absl::StatusOr<ExprNodePtr> ExtractLambda( const ExprNodePtr& expr, std::function<absl::StatusOr<bool>(const ExprNodePtr&)> is_in_lambda); } #endif #include "arolla/expr/eval/expr_utils.h" #include <functional> #include <stack> #include <utility> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/container/flat_hash_set.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/expr/lambda_expr_operator.h" #include "arolla/util/fingerprint.h" #include "arolla/util/status_macros_backport.h" namespace arolla::expr::eval_internal { absl::StatusOr<ExprNodePtr> ExtractLambda( const ExprNodePtr& expr, std::function<absl::StatusOr<bool>(const ExprNodePtr&)> is_in_lambda) { struct Task { enum class Stage { kPreorder, kPostorder }; ExprNodePtr node; Stage stage; }; std::vector<ExprNodePtr> lambda_args; ExprOperatorSignature lambda_signature; absl::flat_hash_set<Fingerprint> previsited; absl::flat_hash_map<Fingerprint, ExprNodePtr> new_nodes; std::stack<Task> tasks; tasks.push(Task{.node = expr, .stage = Task::Stage::kPreorder}); int next_placeholder = 0; while (!tasks.empty()) { auto [node, stage] = std::move(tasks.top()); tasks.pop(); if (stage == Task::Stage::kPreorder) { if (!previsited.insert(node->fingerprint()).second) { continue; } ASSIGN_OR_RETURN(bool in_lambda, is_in_lambda(node)); if (in_lambda) { tasks.push(Task{.node = node, .stage = Task::Stage::kPostorder}); for (auto dep = node->node_deps().rbegin(); dep != node->node_deps().rend(); ++dep) { tasks.push(Task{.node = *dep, .stage = Task::Stage::kPreorder}); } } else { auto [it, inserted] = new_nodes.insert({node->fingerprint(), nullptr}); if (inserted) { it->second = Placeholder(absl::StrCat("_", next_placeholder++)); lambda_args.emplace_back(node); lambda_signature.parameters.push_back( ExprOperatorSignature::Parameter{ .name = it->second->placeholder_key()}); } } } else { std::vector<ExprNodePtr> new_deps; new_deps.reserve(node->node_deps().size()); for (const auto& dep : node->node_deps()) { new_deps.push_back(new_nodes.at(dep->fingerprint())); } ASSIGN_OR_RETURN(new_nodes[node->fingerprint()], WithNewDependencies(node, new_deps)); } } ASSIGN_OR_RETURN( ExprOperatorPtr lambda, MakeLambdaOperator(lambda_signature, new_nodes.at(expr->fingerprint()))); return MakeOpNode(lambda, lambda_args); } }
#include "arolla/expr/eval/expr_utils.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/lambda_expr_operator.h" #include "arolla/expr/testing/testing.h" #include "arolla/util/init_arolla.h" #include "arolla/util/testing/status_matchers_backport.h" namespace arolla::expr::eval_internal { namespace { using ::arolla::testing::EqualsExpr; using ::arolla::testing::StatusIs; using ::testing::ElementsAre; using ::testing::Pointee; using ::testing::Property; using ::testing::WhenDynamicCastTo; class ExptUtilsTest : public ::testing::Test { protected: void SetUp() override { ASSERT_OK(InitArolla()); } }; TEST_F(ExptUtilsTest, ExtractLambda) { ASSERT_OK_AND_ASSIGN( auto expr, CallOp("math.add", {CallOp("math.add", {Leaf("x"), Leaf("y")}), Literal(1.0)})); auto is_op = [](const ExprNodePtr& node) -> absl::StatusOr<bool> { return node->is_op(); }; ASSERT_OK_AND_ASSIGN(auto expr_as_lambda, ExtractLambda(expr, is_op)); EXPECT_THAT(expr_as_lambda->node_deps(), ElementsAre(EqualsExpr(Leaf("x")), EqualsExpr(Leaf("y")), EqualsExpr(Literal(1.0)))); EXPECT_THAT( expr_as_lambda->op().get(), WhenDynamicCastTo<const LambdaOperator*>(Pointee(Property( &LambdaOperator::lambda_body, EqualsExpr(CallOp( "math.add", {CallOp("math.add", {Placeholder("_0"), Placeholder("_1")}), Placeholder("_2")})))))); } TEST_F(ExptUtilsTest, ExtractLambda_WithSameSubnodes) { ASSERT_OK_AND_ASSIGN( auto to_keep_out, CallOp("math.add", {CallOp("math.add", {Leaf("x"), Leaf("y")}), Literal(1.0)})); ASSERT_OK_AND_ASSIGN(auto to_keep_in, CallOp("math.add", {Literal(2.0), Literal(1.0)})); ASSERT_OK_AND_ASSIGN( auto expr, CallOp("math.add", {CallOp("math.add", {to_keep_out, to_keep_in}), to_keep_out})); auto keep_in = [=](const ExprNodePtr& node) -> absl::StatusOr<bool> { return node->fingerprint() != to_keep_out->fingerprint(); }; ASSERT_OK_AND_ASSIGN(auto expr_as_lambda, ExtractLambda(expr, keep_in)); EXPECT_THAT(expr_as_lambda->node_deps(), ElementsAre(EqualsExpr(to_keep_out))); EXPECT_THAT( expr_as_lambda->op().get(), WhenDynamicCastTo<const LambdaOperator*>(Pointee(Property( &LambdaOperator::lambda_body, EqualsExpr(CallOp( "math.add", {CallOp("math.add", {Placeholder("_0"), to_keep_in}), Placeholder("_0")})))))); } TEST_F(ExptUtilsTest, ExtractLambda_AllFalse) { ASSERT_OK_AND_ASSIGN( auto expr, CallOp("math.add", {CallOp("math.add", {Leaf("x"), Leaf("y")}), Literal(1.0)})); auto all_false = [](const ExprNodePtr& node) -> absl::StatusOr<bool> { return false; }; ASSERT_OK_AND_ASSIGN(auto expr_as_lambda, ExtractLambda(expr, all_false)); EXPECT_THAT(expr_as_lambda->node_deps(), ElementsAre(EqualsExpr(expr))); EXPECT_THAT( expr_as_lambda->op().get(), WhenDynamicCastTo<const LambdaOperator*>(Pointee(Property( &LambdaOperator::lambda_body, EqualsExpr(Placeholder("_0")))))); } TEST_F(ExptUtilsTest, ExtractLambda_FilterFails) { ASSERT_OK_AND_ASSIGN( auto expr, CallOp("math.add", {CallOp("math.subtract", {Leaf("x"), Leaf("y")}), Literal(1.0)})); auto returns_error = [](const ExprNodePtr& node) -> absl::StatusOr<bool> { if (node->is_op() && node->op()->display_name() == "math.subtract") { return absl::InvalidArgumentError("foo"); } return true; }; EXPECT_THAT(ExtractLambda(expr, returns_error), StatusIs(absl::StatusCode::kInvalidArgument, "foo")); } } }
2,470
#ifndef AROLLA_EXPR_EVAL_DYNAMIC_COMPILED_EXPR_H_ #define AROLLA_EXPR_EVAL_DYNAMIC_COMPILED_EXPR_H_ #include <memory> #include <optional> #include <string> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/types/span.h" #include "arolla/expr/eval/eval.h" #include "arolla/expr/eval/executable_builder.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_stack_trace.h" #include "arolla/memory/frame.h" #include "arolla/qexpr/evaluation_engine.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/typed_slot.h" #include "arolla/util/fingerprint.h" namespace arolla::expr::eval_internal { class DynamicBoundExpr : public BoundExpr { public: using BoundExpr::BoundExpr; virtual absl::Span<const std::string> init_op_descriptions() const = 0; virtual absl::Span<const std::string> eval_op_descriptions() const = 0; }; class DynamicCompiledExpr : public CompiledExpr { public: DynamicCompiledExpr( DynamicEvaluationEngineOptions options, absl::flat_hash_map<std::string, QTypePtr> input_types, QTypePtr output_type, absl::flat_hash_map<std::string, QTypePtr> named_output_types, ExprNodePtr prepared_expr, std::vector<std::string> side_output_names, absl::flat_hash_map<Fingerprint, QTypePtr> types, std::shared_ptr<const ExprStackTrace> stack_trace = nullptr); absl::StatusOr<std::unique_ptr<BoundExpr>> Bind( FrameLayout::Builder* layout_builder, const absl::flat_hash_map<std::string, TypedSlot>& input_slots, std::optional<TypedSlot> output_slot) const final; absl::Status BindToExecutableBuilder( ExecutableBuilder& executable_builder, const absl::flat_hash_map<std::string, TypedSlot>& input_slots, TypedSlot output_slot) const; private: DynamicEvaluationEngineOptions options_; ExprNodePtr prepared_expr_; std::vector<std::string> side_output_names_; absl::flat_hash_map<Fingerprint, QTypePtr> types_; std::shared_ptr<const ExprStackTrace> stack_trace_; }; } #endif #include "arolla/expr/eval/dynamic_compiled_expr.h" #include <cstddef> #include <cstdint> #include <functional> #include <memory> #include <optional> #include <string> #include <utility> #include <vector> #include "absl/base/nullability.h" #include "absl/container/flat_hash_map.h" #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "arolla/expr/derived_qtype_cast_operator.h" #include "arolla/expr/eval/compile_std_function_operator.h" #include "arolla/expr/eval/compile_where_operator.h" #include "arolla/expr/eval/compile_while_operator.h" #include "arolla/expr/eval/eval.h" #include "arolla/expr/eval/executable_builder.h" #include "arolla/expr/eval/extensions.h" #include "arolla/expr/eval/prepare_expression.h" #include "arolla/expr/eval/slot_allocator.h" #include "arolla/expr/expr_attributes.h" #include "arolla/expr/expr_debug_string.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/expr_stack_trace.h" #include "arolla/expr/expr_visitor.h" #include "arolla/expr/operators/std_function_operator.h" #include "arolla/expr/operators/while_loop/while_loop.h" #include "arolla/expr/registered_expr_operator.h" #include "arolla/expr/tuple_expr_operator.h" #include "arolla/memory/frame.h" #include "arolla/memory/optional_value.h" #include "arolla/qexpr/evaluation_engine.h" #include "arolla/qexpr/operators.h" #include "arolla/qexpr/operators/core/utility_operators.h" #include "arolla/qtype/optional_qtype.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/typed_slot.h" #include "arolla/util/demangle.h" #include "arolla/util/fast_dynamic_downcast_final.h" #include "arolla/util/fingerprint.h" #include "arolla/util/status_macros_backport.h" namespace arolla::expr::eval_internal { namespace { const OperatorDirectory& GetOperatorDirectory( const DynamicEvaluationEngineOptions& options) { return options.operator_directory != nullptr ? *options.operator_directory : *OperatorRegistry::GetInstance(); } struct OutputInfo { ExprNodePtr expr; TypedSlot forced_output_slot; }; absl::Status VerifySlotsCount(absl::string_view op_name, absl::Span<const TypedSlot> input_slots, int64_t expected_count) { if (input_slots.size() != expected_count) { return absl::InvalidArgumentError( absl::StrFormat("%s operator expects %d argument(s), got %d", op_name, expected_count, input_slots.size())); } return absl::OkStatus(); } class EvalVisitor { public: EvalVisitor(DynamicEvaluationEngineOptions options, const absl::flat_hash_map<std::string, TypedSlot>& input_slots, OutputInfo output_info, ExecutableBuilder* executable_builder, const std::vector<std::string>& side_output_names, absl::flat_hash_map<Fingerprint, QTypePtr> node_types, eval_internal::SlotAllocator& slot_allocator) : options_(std::move(options)), expr_input_slots_(input_slots), output_info_(std::move(output_info)), executable_builder_(executable_builder), side_output_names_(side_output_names), node_types_(std::move(node_types)), slot_allocator_(slot_allocator), compiler_extensions_(CompilerExtensionRegistry::GetInstance() .GetCompilerExtensionSet()) {} absl::StatusOr<TypedSlot> operator()( const ExprNodePtr& node, absl::Span<const TypedSlot* const> visits) { auto inputs = DereferenceVisitPointers(visits); ASSIGN_OR_RETURN(QTypePtr output_type, LookupQType(node, node_types_)); if (output_type == nullptr) { return absl::FailedPreconditionError( absl::StrFormat("unable to deduce output type of the node %s", GetDebugSnippet(node))); } ASSIGN_OR_RETURN( TypedSlot output_slot, ConstructOutputSlot(node, inputs, output_type), _ << "while compiling node " << GetDebugSnippet(node) << "; the expression is likely not fully compiled and is using " "derived operators that are not supported in the backend"); if (output_slot.GetType() != output_type) { return absl::FailedPreconditionError(absl::StrFormat( "unexpected output type of the node %s: MetaEval: %s, " "backend: %s; operator signatures " "are inconsistent on argument types %s", GetDebugSnippet(node), output_type->name(), output_slot.GetType()->name(), FormatTypeVector(SlotsToTypes(inputs)))); } if (node->op() != eval_internal::InternalRootOperator()) { RETURN_IF_ERROR(slot_allocator_.ReleaseSlotsNotNeededAfter(node)); } return output_slot; } private: using AddSlotFn = std::function<TypedSlot(bool allow_recycled)>; using CopySlotFn = std::function<absl::StatusOr<TypedSlot>( TypedSlot slot, const ExprNodePtr& slot_origin)>; absl::StatusOr<TypedSlot> ConstructOutputSlot( const ExprNodePtr& node, absl::Span<const TypedSlot> input_slots, QTypePtr output_type) { std::optional<TypedSlot> forced_output_slot; if (node.get() == output_info_.expr.get()) { forced_output_slot = output_info_.forced_output_slot; } AddSlotFn maybe_add_output_slot = [this, output_type, &node, forced_output_slot](bool allow_recycled) { if (forced_output_slot.has_value()) { return *forced_output_slot; } auto slot = slot_allocator_.AddSlotForNode(node, output_type, allow_recycled); return slot; }; CopySlotFn maybe_copy_slot = [this, &node, forced_output_slot]( TypedSlot slot, const ExprNodePtr& slot_origin) -> absl::StatusOr<TypedSlot> { if (forced_output_slot.has_value()) { RETURN_IF_ERROR(this->executable_builder_ ->BindEvalOp(*MakeCopyOp(slot.GetType()), {slot}, *forced_output_slot) .status()); slot = *forced_output_slot; } else { RETURN_IF_ERROR(slot_allocator_.ExtendSlotLifetime(slot_origin, node)); } return slot; }; switch (node->type()) { case ExprNodeType::kPlaceholder: return absl::InternalError( absl::StrFormat("placeholder should be substituted before " "evaluation: P.%s", node->placeholder_key())); case ExprNodeType::kLeaf: { if (!expr_input_slots_.contains(node->leaf_key())) { return absl::InvalidArgumentError( absl::StrCat("unbound leaf: ", node->leaf_key())); } return maybe_copy_slot({expr_input_slots_.at(node->leaf_key())}, node); } case ExprNodeType::kLiteral: { TypedSlot output_slot = slot_allocator_.AddSlotForNode(node, output_type, false); RETURN_IF_ERROR(executable_builder_->AddLiteralInitialization( *node->qvalue(), output_slot)); return maybe_copy_slot(output_slot, node); } case ExprNodeType::kOperator: { ASSIGN_OR_RETURN(auto op, DecayRegisteredOperator(node->op())); if (!HasBuiltinExprOperatorTag(op) && !HasBackendExprOperatorTag(op)) { return absl::InvalidArgumentError( absl::StrCat(node->op()->display_name(), " is not a builtin or backend ExprOperator")); } const auto& op_typeid = typeid(*op); if (HasBackendExprOperatorTag(op)) { if (op->display_name() == "core.has._optional") { return HandleHas(node->node_deps(), input_slots, maybe_copy_slot, maybe_add_output_slot); } return CompileBackendOperator( op->display_name(), input_slots, maybe_add_output_slot(true), node); } else if (HasAnnotationExprOperatorTag(op)) { return maybe_copy_slot(input_slots[0], node->node_deps()[0]); } else if (op == eval_internal::InternalRootOperator()) { return HandleInternalRoot(input_slots); } else if (op_typeid == typeid(GetNthOperator)) { return HandleGetNth(op, node->node_deps(), input_slots, maybe_copy_slot); } else if (auto* where_op = fast_dynamic_downcast_final<const PackedWhereOp*>( op.get())) { DynamicEvaluationEngineOptions options(options_); options.allow_overriding_input_slots = false; return CompileWhereOperator( options, *where_op, input_slots, maybe_add_output_slot(true), executable_builder_); } else if (auto* while_op = fast_dynamic_downcast_final< const expr_operators::WhileLoopOperator*>(op.get())) { DynamicEvaluationEngineOptions options(options_); options.allow_overriding_input_slots = false; auto output_slot = maybe_add_output_slot(true); RETURN_IF_ERROR(eval_internal::CompileWhileOperator( options, *while_op, input_slots, output_slot, *executable_builder_)); return output_slot; } else if (op_typeid == typeid(DerivedQTypeUpcastOperator) || op_typeid == typeid(DerivedQTypeDowncastOperator)) { return HandleDerivedQTypeCast(*op, node->node_deps(), input_slots, maybe_copy_slot); } else if (auto* std_function_op = dynamic_cast<const expr_operators::StdFunctionOperator*>( op.get())) { auto output_slot = maybe_add_output_slot(true); RETURN_IF_ERROR(eval_internal::CompileStdFunctionOperator( *std_function_op, input_slots, output_slot, *executable_builder_, node)); return output_slot; } auto output_slot = maybe_add_output_slot(true); if (auto result = compiler_extensions_.compile_operator_fn(CompileOperatorFnArgs{ .options = options_, .op = op, .input_slots = input_slots, .output_slot = output_slot, .executable_builder = executable_builder_}); result.has_value()) { RETURN_IF_ERROR(*result); return output_slot; } return absl::InvalidArgumentError(absl::StrCat( "unsupported builtin ExprOperator: name=", node->op()->display_name(), ", CxxType=", TypeName(op_typeid))); } } return absl::InternalError(absl::StrFormat("unexpected ExprNodeType: %d", static_cast<int>(node->type()))); } absl::StatusOr<TypedSlot> HandleInternalRoot( absl::Span<const TypedSlot> input_slots) const { if (input_slots.size() != 1 + side_output_names_.size()) { return absl::InternalError( absl::StrFormat("InternalRootOperator bound with %d " "arguments, %d expected", input_slots.size(), 1 + side_output_names_.size())); } if (input_slots[0] != output_info_.forced_output_slot) { return absl::InternalError( "InternalRootOperator first slot was handled incorrectly"); } for (size_t i = 0; i < side_output_names_.size(); ++i) { RETURN_IF_ERROR(executable_builder_->AddNamedOutput(side_output_names_[i], input_slots[i + 1])); } return input_slots[0]; } absl::StatusOr<TypedSlot> HandleHas(absl::Span<const ExprNodePtr> node_deps, absl::Span<const TypedSlot> input_slots, CopySlotFn copy_slot_fn, AddSlotFn add_slot_fn) { RETURN_IF_ERROR(VerifySlotsCount("core.has._optional", input_slots, 1)); if (!IsOptionalQType(input_slots[0].GetType())) { return CompileBackendOperator("core.has._optional", input_slots, add_slot_fn(true)); } static_assert(sizeof(OptionalUnit) == sizeof(bool)); static_assert(alignof(OptionalUnit) == alignof(bool)); auto mask_slot = FrameLayout::Slot<OptionalUnit>::UnsafeSlotFromOffset( input_slots[0].byte_offset()); RETURN_IF_ERROR(executable_builder_->layout_builder()->RegisterUnsafeSlot( mask_slot, true)); DCHECK_EQ(node_deps.size(), 1); return copy_slot_fn(TypedSlot::FromSlot(mask_slot), node_deps[0]); } absl::StatusOr<TypedSlot> HandleGetNth( const ExprOperatorPtr& op, absl::Span<const ExprNodePtr> node_deps, absl::Span<const TypedSlot> input_slots, CopySlotFn copy_slot_fn) const { RETURN_IF_ERROR(VerifySlotsCount(op->display_name(), input_slots, 1)); const GetNthOperator& get_nth = *static_cast<const GetNthOperator*>(op.get()); if (get_nth.index() < 0 || get_nth.index() >= input_slots[0].SubSlotCount()) { return absl::InternalError( absl::StrFormat("input type %s is not compatible with %s, index %d " "is out of range", input_slots[0].GetType()->name(), get_nth.display_name(), get_nth.index())); } DCHECK_EQ(node_deps.size(), 1); return copy_slot_fn(input_slots[0].SubSlot(get_nth.index()), node_deps[0]); } absl::StatusOr<TypedSlot> HandleDerivedQTypeCast( const ExprOperator& op, absl::Span<const ExprNodePtr> node_deps, absl::Span<const TypedSlot> input_slots, CopySlotFn copy_slot_fn) const { RETURN_IF_ERROR(VerifySlotsCount(op.display_name(), input_slots, 1)); DCHECK(typeid(op) == typeid(DerivedQTypeUpcastOperator) || typeid(op) == typeid(DerivedQTypeDowncastOperator)); ASSIGN_OR_RETURN( auto output_attr, op.InferAttributes({ExprAttributes(input_slots[0].GetType())})); DCHECK_EQ(node_deps.size(), 1); DCHECK(output_attr.qtype()); return copy_slot_fn(TypedSlot::UnsafeFromOffset( output_attr.qtype(), input_slots[0].byte_offset()), node_deps[0]); } absl::StatusOr<TypedSlot> CompileBackendOperator( absl::string_view name, absl::Span<const TypedSlot> input_slots, TypedSlot output_slot, absl::Nullable<ExprNodePtr> node = nullptr) { ASSIGN_OR_RETURN( auto op, GetOperatorDirectory(options_).LookupOperator( name, SlotsToTypes(input_slots), output_slot.GetType())); ASSIGN_OR_RETURN(auto ip, executable_builder_->BindEvalOp(*op, input_slots, output_slot)); if (node != nullptr) { executable_builder_->RegisterStacktrace(ip, node); } return output_slot; } DynamicEvaluationEngineOptions options_; const absl::flat_hash_map<std::string, TypedSlot>& expr_input_slots_; OutputInfo output_info_; ExecutableBuilder* executable_builder_; const std::vector<std::string>& side_output_names_; absl::flat_hash_map<Fingerprint, QTypePtr> node_types_; eval_internal::SlotAllocator& slot_allocator_; CompilerExtensionSet compiler_extensions_; }; } DynamicCompiledExpr::DynamicCompiledExpr( DynamicEvaluationEngineOptions options, absl::flat_hash_map<std::string, QTypePtr> input_types, QTypePtr output_type, absl::flat_hash_map<std::string, QTypePtr> named_output_types, ExprNodePtr prepared_expr, std::vector<std::string> side_output_names, absl::flat_hash_map<Fingerprint, QTypePtr> types, std::shared_ptr<const ExprStackTrace> stack_trace) : CompiledExpr(std::move(input_types), output_type, std::move(named_output_types)), options_(std::move(options)), prepared_expr_(std::move(prepared_expr)), side_output_names_(std::move(side_output_names)), types_(std::move(types)), stack_trace_(std::move(stack_trace)) {} absl::StatusOr<std::unique_ptr<BoundExpr>> DynamicCompiledExpr::Bind( FrameLayout::Builder* layout_builder, const absl::flat_hash_map<std::string, TypedSlot>& input_slots, std::optional<TypedSlot> output_slot) const { ExecutableBuilder executable_builder( layout_builder, options_.collect_op_descriptions, stack_trace_); if (!output_slot.has_value()) { output_slot = AddSlot(output_type(), layout_builder); } RETURN_IF_ERROR( BindToExecutableBuilder(executable_builder, input_slots, *output_slot)); return std::move(executable_builder).Build(input_slots, *output_slot); } absl::Status DynamicCompiledExpr::BindToExecutableBuilder( ExecutableBuilder& executable_builder, const absl::flat_hash_map<std::string, TypedSlot>& input_slots, TypedSlot output_slot) const { RETURN_IF_ERROR(VerifySlotTypes(input_types(), input_slots, false, true)); ExprNodePtr output_expr = prepared_expr_; if (output_expr->op() == eval_internal::InternalRootOperator()) { if (output_expr->node_deps().empty()) { return absl::InternalError("InternalRootOperator bound with 0 arguments"); } output_expr = output_expr->node_deps()[0]; } eval_internal::SlotAllocator slot_allocator( prepared_expr_, *executable_builder.layout_builder(), input_slots, options_.allow_overriding_input_slots); EvalVisitor visitor(options_, input_slots, {output_expr, output_slot}, &executable_builder, side_output_names_, types_, slot_allocator); ASSIGN_OR_RETURN(TypedSlot new_output_slot, PostOrderTraverse(prepared_expr_, std::ref(visitor))); if (output_slot != new_output_slot) { return absl::InternalError( absl::StrFormat("expression %s bound to a wrong output slot", GetDebugSnippet(prepared_expr_))); } return absl::OkStatus(); } }
#include "arolla/expr/eval/dynamic_compiled_expr.h" #include <cstdint> #include <memory> #include <string> #include <utility> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/container/flat_hash_map.h" #include "arolla/expr/eval/eval.h" #include "arolla/expr/eval/executable_builder.h" #include "arolla/expr/eval/prepare_expression.h" #include "arolla/expr/eval/test_utils.h" #include "arolla/expr/expr.h" #include "arolla/memory/frame.h" #include "arolla/memory/memory_allocation.h" #include "arolla/qexpr/eval_context.h" #include "arolla/qexpr/evaluation_engine.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/typed_slot.h" #include "arolla/util/fingerprint.h" #include "arolla/util/init_arolla.h" namespace arolla::expr::eval_internal { namespace { class DynamicCompiledExprTest : public ::testing::Test { protected: void SetUp() override { ASSERT_OK(InitArolla()); } }; TEST_F(DynamicCompiledExprTest, BindToExecutableBuilder) { ASSERT_OK_AND_ASSIGN(auto expr, CallOp("math.add", {Leaf("x"), Literal<int32_t>(1)})); absl::flat_hash_map<std::string, QTypePtr> input_types = { {"x", GetQType<int32_t>()}}; ASSERT_OK_AND_ASSIGN( expr, PrepareExpression(expr, input_types, DynamicEvaluationEngineOptions{})); absl::flat_hash_map<Fingerprint, QTypePtr> node_types; ASSERT_OK_AND_ASSIGN(expr, ExtractQTypesForCompilation(expr, &node_types)); DynamicCompiledExpr compiled_expr( DynamicEvaluationEngineOptions{}, input_types, GetQType<int32_t>(), {}, expr, {}, node_types); FrameLayout::Builder layout_builder; ExecutableBuilder executable_builder(&layout_builder, true); auto x1_slot = layout_builder.AddSlot<int32_t>(); auto x2_slot = layout_builder.AddSlot<int32_t>(); auto result_slot = layout_builder.AddSlot<int32_t>(); auto other_result_slot = layout_builder.AddSlot<int32_t>(); ASSERT_OK(compiled_expr.BindToExecutableBuilder( executable_builder, {{"x", TypedSlot::FromSlot(x1_slot)}}, TypedSlot::FromSlot(result_slot))); ASSERT_OK(compiled_expr.BindToExecutableBuilder( executable_builder, {{"x", TypedSlot::FromSlot(x1_slot)}}, TypedSlot::FromSlot(other_result_slot))); ASSERT_OK(compiled_expr.BindToExecutableBuilder( executable_builder, {{"x", TypedSlot::FromSlot(x2_slot)}}, TypedSlot::FromSlot(other_result_slot))); std::unique_ptr<BoundExpr> executable_expr = std::move(executable_builder) .Build({{"x1", TypedSlot::FromSlot(x1_slot)}, {"x2", TypedSlot::FromSlot(x2_slot)}}, TypedSlot::FromSlot(result_slot)); EXPECT_THAT( executable_expr, AllOf(InitOperationsAre( "INT32 [0x10] = 1\n" "INT32 [0x14] = 1\n" "INT32 [0x18] = 1"), EvalOperationsAre( "INT32 [0x08] = math.add(INT32 [0x00], INT32 [0x10])", "INT32 [0x0C] = math.add(INT32 [0x00], INT32 [0x14])", "INT32 [0x0C] = math.add(INT32 [0x04], INT32 [0x18])"))); auto layout = std::move(layout_builder).Build(); MemoryAllocation alloc(&layout); alloc.frame().Set(x1_slot, 56); alloc.frame().Set(x2_slot, 1); EvaluationContext ctx; executable_expr->InitializeLiterals(&ctx, alloc.frame()); executable_expr->Execute(&ctx, alloc.frame()); EXPECT_OK(ctx.status()); EXPECT_EQ(alloc.frame().Get(result_slot), 57); EXPECT_EQ(alloc.frame().Get(other_result_slot), 2); } } }
2,471
#ifndef AROLLA_EXPR_EVAL_EXTENSIONS_H_ #define AROLLA_EXPR_EVAL_EXTENSIONS_H_ #include <functional> #include <optional> #include <vector> #include "absl/base/thread_annotations.h" #include "absl/status/status.h" #include "absl/synchronization/mutex.h" #include "absl/types/span.h" #include "arolla/expr/eval/eval.h" #include "arolla/expr/eval/executable_builder.h" #include "arolla/expr/eval/prepare_expression.h" #include "arolla/expr/expr_operator.h" #include "arolla/qtype/typed_slot.h" namespace arolla::expr::eval_internal { struct CompileOperatorFnArgs { const DynamicEvaluationEngineOptions& options; const ExprOperatorPtr& op; absl::Span<const TypedSlot> input_slots; TypedSlot output_slot; ExecutableBuilder* executable_builder; }; using CompileOperatorFn = std::function<std::optional<absl::Status>( const CompileOperatorFnArgs& args)>; struct CompilerExtensionSet { NodeTransformationFn node_transformation_fn; CompileOperatorFn compile_operator_fn; }; class CompilerExtensionRegistry { public: CompilerExtensionRegistry() = default; static CompilerExtensionRegistry& GetInstance(); CompilerExtensionSet GetCompilerExtensionSet() const; void RegisterNodeTransformationFn(NodeTransformationFn fn); void RegisterCompileOperatorFn(CompileOperatorFn fn); private: mutable absl::Mutex mutex_; std::vector<NodeTransformationFn> node_transformation_fns_ ABSL_GUARDED_BY(mutex_); std::vector<CompileOperatorFn> compile_operator_fns_ ABSL_GUARDED_BY(mutex_); }; } #endif #include "arolla/expr/eval/extensions.h" #include <optional> #include <utility> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/synchronization/mutex.h" #include "arolla/expr/eval/eval.h" #include "arolla/expr/eval/prepare_expression.h" #include "arolla/expr/expr_node.h" #include "arolla/util/indestructible.h" #include "arolla/util/status_macros_backport.h" namespace arolla::expr::eval_internal { CompilerExtensionRegistry& CompilerExtensionRegistry::GetInstance() { static Indestructible<CompilerExtensionRegistry> instance( [](void* self) { new (self) CompilerExtensionRegistry; }); return *instance; } CompilerExtensionSet CompilerExtensionRegistry::GetCompilerExtensionSet() const { absl::ReaderMutexLock lock(&mutex_); return CompilerExtensionSet{ .node_transformation_fn = [node_transformation_fns = node_transformation_fns_]( const DynamicEvaluationEngineOptions& options, ExprNodePtr node) -> absl::StatusOr<ExprNodePtr> { for (const auto& fn : node_transformation_fns) { ASSIGN_OR_RETURN(auto new_node, fn(options, node)); if (new_node->fingerprint() != node->fingerprint()) { return new_node; } node = std::move(new_node); } return node; }, .compile_operator_fn = [compile_operator_fns = compile_operator_fns_]( const CompileOperatorFnArgs& args) -> std::optional<absl::Status> { for (const auto& fn : compile_operator_fns) { std::optional<absl::Status> result = fn(args); if (result.has_value()) { return result; } } return std::nullopt; }}; } void CompilerExtensionRegistry::RegisterNodeTransformationFn( NodeTransformationFn fn) { absl::MutexLock lock(&mutex_); node_transformation_fns_.push_back(fn); } void CompilerExtensionRegistry::RegisterCompileOperatorFn( CompileOperatorFn fn) { absl::MutexLock lock(&mutex_); compile_operator_fns_.push_back(fn); } }
#include "arolla/expr/eval/extensions.h" #include <memory> #include <optional> #include <utility> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/types/span.h" #include "arolla/expr/basic_expr_operator.h" #include "arolla/expr/eval/eval.h" #include "arolla/expr/eval/executable_builder.h" #include "arolla/expr/eval/prepare_expression.h" #include "arolla/expr/eval/test_utils.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/expr/testing/testing.h" #include "arolla/memory/frame.h" #include "arolla/qexpr/bound_operators.h" #include "arolla/qexpr/eval_context.h" #include "arolla/qexpr/evaluation_engine.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/typed_slot.h" #include "arolla/util/fast_dynamic_downcast_final.h" #include "arolla/util/fingerprint.h" #include "arolla/util/init_arolla.h" #include "arolla/util/status_macros_backport.h" namespace arolla::expr::eval_internal { namespace { using ::arolla::testing::EqualsExpr; using ::testing::Eq; class ExtensionsTest : public ::testing::Test { protected: void SetUp() override { ASSERT_OK(InitArolla()); } }; TEST_F(ExtensionsTest, RegisterNodeTransformationFn) { CompilerExtensionRegistry registry; NodeTransformationFn replace_add_with_sub = [](const DynamicEvaluationEngineOptions&, ExprNodePtr node) -> absl::StatusOr<ExprNodePtr> { if (node->is_op() && node->op()->display_name() == "math.add") { return BindOp("math.subtract", node->node_deps(), {}); } return node; }; registry.RegisterNodeTransformationFn(replace_add_with_sub); NodeTransformationFn replace_sub_with_mul = [](const DynamicEvaluationEngineOptions&, ExprNodePtr node) -> absl::StatusOr<ExprNodePtr> { if (node->is_op() && node->op()->display_name() == "math.subtract") { return BindOp("math.multiply", node->node_deps(), {}); } return node; }; registry.RegisterNodeTransformationFn(replace_sub_with_mul); ASSERT_OK_AND_ASSIGN(ExprNodePtr expr, CallOp("math.add", {Leaf("x"), Literal(57)})); CompilerExtensionSet extensions = registry.GetCompilerExtensionSet(); DynamicEvaluationEngineOptions options; ASSERT_OK_AND_ASSIGN(auto transformed_expr, extensions.node_transformation_fn(options, expr)); EXPECT_THAT(transformed_expr, EqualsExpr(CallOp("math.subtract", {Leaf("x"), Literal(57)}))); ASSERT_OK_AND_ASSIGN( auto transforemed_transformed_expr, extensions.node_transformation_fn(options, transformed_expr)); EXPECT_THAT(transforemed_transformed_expr, EqualsExpr(CallOp("math.multiply", {Leaf("x"), Literal(57)}))); } class TestOperator final : public UnnamedExprOperator, public BuiltinExprOperatorTag { public: TestOperator() : UnnamedExprOperator( ExprOperatorSignature::MakeArgsN(1), FingerprintHasher("arolla::expr::eval_internal::TestOperator") .Finish()) {} absl::StatusOr<QTypePtr> GetOutputQType( absl::Span<const QTypePtr> input_qtypes) const final { return GetQType<float>(); } }; class OtherOperator final : public UnnamedExprOperator, public BuiltinExprOperatorTag { public: OtherOperator() : UnnamedExprOperator( ExprOperatorSignature::MakeArgsN(1), FingerprintHasher("arolla::expr::eval_internal::OtherOperator") .Finish()) {} absl::StatusOr<QTypePtr> GetOutputQType( absl::Span<const QTypePtr> input_qtypes) const final { return GetQType<float>(); } }; TEST_F(ExtensionsTest, RegisterCompileOperatorFn) { CompilerExtensionRegistry registry; CompileOperatorFn dummy_compile_op = [](CompileOperatorFnArgs args) -> std::optional<absl::Status> { return std::nullopt; }; registry.RegisterCompileOperatorFn(dummy_compile_op); CompileOperatorFn compile_test_op = [](CompileOperatorFnArgs args) -> std::optional<absl::Status> { if (fast_dynamic_downcast_final<const TestOperator*>(args.op.get()) == nullptr) { return std::nullopt; } ASSIGN_OR_RETURN(auto output_slot, args.output_slot.ToSlot<float>()); args.executable_builder->AddEvalOp( MakeBoundOperator( [output_slot](EvaluationContext* ctx, FramePtr frame) { frame.Set(output_slot, 57); }), "eval test operator", "eval test operator"); return absl::OkStatus(); }; registry.RegisterCompileOperatorFn(compile_test_op); CompilerExtensionSet extensions = registry.GetCompilerExtensionSet(); FrameLayout::Builder layout_builder; ExecutableBuilder executable_builder(&layout_builder, true); auto out_slot = layout_builder.AddSlot<float>(); ExprOperatorPtr other_op = std::make_shared<OtherOperator>(); EXPECT_THAT(extensions.compile_operator_fn(CompileOperatorFnArgs{ .options = DynamicEvaluationEngineOptions{}, .op = other_op, .input_slots = {}, .output_slot = TypedSlot::FromSlot(out_slot), .executable_builder = &executable_builder}), Eq(std::nullopt)); ExprOperatorPtr test_op = std::make_shared<TestOperator>(); EXPECT_THAT(extensions.compile_operator_fn(CompileOperatorFnArgs{ .options = DynamicEvaluationEngineOptions{}, .op = test_op, .input_slots = {}, .output_slot = TypedSlot::FromSlot(out_slot), .executable_builder = &executable_builder}), Eq(absl::OkStatus())); std::unique_ptr<BoundExpr> bound_expr = std::move(executable_builder) .Build({}, TypedSlot::FromSlot(out_slot)); EXPECT_THAT(bound_expr, EvalOperationsAre("eval test operator")); } } }
2,472
#ifndef AROLLA_EXPR_EVAL_EVAL_H_ #define AROLLA_EXPR_EVAL_EVAL_H_ #include <cstdint> #include <memory> #include <optional> #include <string> #include "absl/container/flat_hash_map.h" #include "absl/status/statusor.h" #include "absl/types/span.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/optimization/optimizer.h" #include "arolla/memory/frame.h" #include "arolla/qexpr/evaluation_engine.h" #include "arolla/qexpr/operators.h" #include "arolla/qtype/qtype.h" namespace arolla::expr { struct DynamicEvaluationEngineOptions { struct PreparationStage { static constexpr uint64_t kAll = ~uint64_t{0}; static constexpr uint64_t kPopulateQTypes = 1 << 0; static constexpr uint64_t kToLower = 1 << 1; static constexpr uint64_t kLiteralFolding = 1 << 2; static constexpr uint64_t kStripAnnotations = 1 << 3; static constexpr uint64_t kBackendCompatibilityCasting = 1 << 4; static constexpr uint64_t kOptimization = 1 << 5; static constexpr uint64_t kExtensions = 1 << 6; static constexpr uint64_t kWhereOperatorsTransformation = 1 << 7; }; uint64_t enabled_preparation_stages = PreparationStage::kAll; bool collect_op_descriptions = false; std::optional<Optimizer> optimizer = std::nullopt; bool allow_overriding_input_slots = false; const OperatorDirectory* operator_directory = nullptr; bool enable_expr_stack_trace = true; }; absl::StatusOr<std::unique_ptr<CompiledExpr>> CompileForDynamicEvaluation( const DynamicEvaluationEngineOptions& options, const ExprNodePtr& expr, const absl::flat_hash_map<std::string, QTypePtr>& input_types = {}, const absl::flat_hash_map<std::string, ExprNodePtr>& side_outputs = {}); absl::StatusOr<std::unique_ptr<BoundExpr>> CompileAndBindForDynamicEvaluation( const DynamicEvaluationEngineOptions& options, FrameLayout::Builder* layout_builder, const ExprNodePtr& expr, const absl::flat_hash_map<std::string, TypedSlot>& input_slots, std::optional<TypedSlot> output_slot = {}, const absl::flat_hash_map<std::string, ExprNodePtr>& side_outputs = {}); absl::StatusOr<std::shared_ptr<BoundExpr>> CompileAndBindExprOperator( const DynamicEvaluationEngineOptions& options, FrameLayout::Builder* layout_builder, const ExprOperatorPtr& op, absl::Span<const TypedSlot> input_slots, std::optional<TypedSlot> output_slot = {}); } #endif #include "arolla/expr/eval/eval.h" #include <algorithm> #include <cstddef> #include <memory> #include <optional> #include <string> #include <utility> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "absl/strings/str_join.h" #include "absl/types/span.h" #include "arolla/expr/eval/dynamic_compiled_expr.h" #include "arolla/expr/eval/prepare_expression.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_debug_string.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/expr_stack_trace.h" #include "arolla/memory/frame.h" #include "arolla/qexpr/evaluation_engine.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/typed_slot.h" #include "arolla/util/fingerprint.h" #include "arolla/util/status_macros_backport.h" namespace arolla::expr { absl::StatusOr<std::unique_ptr<CompiledExpr>> CompileForDynamicEvaluation( const DynamicEvaluationEngineOptions& options, const ExprNodePtr& expr, const absl::flat_hash_map<std::string, QTypePtr>& input_types, const absl::flat_hash_map<std::string, ExprNodePtr>& side_outputs) { auto expr_with_side_outputs = expr; std::vector<std::string> side_output_names; if (!side_outputs.empty()) { side_output_names.reserve(side_outputs.size()); for (const auto& [name, _] : side_outputs) { side_output_names.push_back(name); } std::sort(side_output_names.begin(), side_output_names.end()); std::vector<ExprNodePtr> exprs = {expr_with_side_outputs}; exprs.reserve(side_outputs.size() + 1); for (const auto& name : side_output_names) { exprs.push_back(side_outputs.at(name)); } ASSIGN_OR_RETURN( expr_with_side_outputs, BindOp(eval_internal::InternalRootOperator(), std::move(exprs), {})); } std::shared_ptr<LightweightExprStackTrace> stack_trace = nullptr; if (options.enable_expr_stack_trace) { stack_trace = std::make_shared<LightweightExprStackTrace>(); } ASSIGN_OR_RETURN( ExprNodePtr prepared_expr, eval_internal::PrepareExpression(expr_with_side_outputs, input_types, options, stack_trace)); auto placeholder_keys = GetPlaceholderKeys(prepared_expr); if (!placeholder_keys.empty()) { return absl::FailedPreconditionError(absl::StrFormat( "placeholders should be substituted before " "evaluation: %s, got %s", absl::StrJoin(placeholder_keys, ","), ToDebugString(prepared_expr))); } absl::flat_hash_map<Fingerprint, QTypePtr> node_types; ASSIGN_OR_RETURN(prepared_expr, eval_internal::ExtractQTypesForCompilation( prepared_expr, &node_types, stack_trace)); if (stack_trace != nullptr) { stack_trace->AddRepresentations(expr_with_side_outputs, prepared_expr); } ASSIGN_OR_RETURN(auto used_input_types, eval_internal::LookupLeafQTypes(prepared_expr, node_types)); ASSIGN_OR_RETURN(auto named_output_types, eval_internal::LookupNamedOutputTypes( prepared_expr, side_output_names, node_types)); for (const auto& [key, qtype] : used_input_types) { if (qtype == nullptr) { return absl::FailedPreconditionError(absl::StrFormat( "unable to deduce input type for L.%s in the expression %s", key, GetDebugSnippet(prepared_expr))); } } ASSIGN_OR_RETURN(QTypePtr output_type, eval_internal::LookupQType(prepared_expr, node_types)); if (output_type == nullptr) { return absl::FailedPreconditionError( absl::StrFormat("unable to deduce output type in the expression %s", GetDebugSnippet(prepared_expr))); } return std::unique_ptr<CompiledExpr>(new eval_internal::DynamicCompiledExpr( options, std::move(used_input_types), output_type, std::move(named_output_types), std::move(prepared_expr), std::move(side_output_names), std::move(node_types), std::move(stack_trace))); } absl::StatusOr<std::unique_ptr<BoundExpr>> CompileAndBindForDynamicEvaluation( const DynamicEvaluationEngineOptions& options, FrameLayout::Builder* layout_builder, const ExprNodePtr& expr, const absl::flat_hash_map<std::string, TypedSlot>& input_slots, std::optional<TypedSlot> output_slot, const absl::flat_hash_map<std::string, ExprNodePtr>& side_outputs) { ASSIGN_OR_RETURN(auto compiled_expr, CompileForDynamicEvaluation( options, expr, SlotsToTypes(input_slots), side_outputs)); ASSIGN_OR_RETURN( auto executable_expr, compiled_expr->Bind(layout_builder, input_slots, output_slot)); if (output_slot.has_value() && executable_expr->output_slot() != *output_slot) { return absl::InternalError("expression bound to a wrong output slot"); } return executable_expr; } absl::StatusOr<std::shared_ptr<BoundExpr>> CompileAndBindExprOperator( const DynamicEvaluationEngineOptions& options, FrameLayout::Builder* layout_builder, const ExprOperatorPtr& op, absl::Span<const TypedSlot> input_slots, std::optional<TypedSlot> output_slot) { std::vector<absl::StatusOr<ExprNodePtr>> inputs; inputs.reserve(input_slots.size()); absl::flat_hash_map<std::string, TypedSlot> input_slots_map; input_slots_map.reserve(input_slots.size()); for (size_t i = 0; i < input_slots.size(); ++i) { std::string name = absl::StrFormat("input_%d", i); inputs.push_back(Leaf(name)); input_slots_map.emplace(name, input_slots[i]); } ASSIGN_OR_RETURN(auto expr, CallOp(op, inputs)); ASSIGN_OR_RETURN(auto evaluator, CompileAndBindForDynamicEvaluation( options, layout_builder, expr, input_slots_map, output_slot)); return std::shared_ptr<BoundExpr>(std::move(evaluator)); } }
#include "arolla/expr/eval/eval.h" #include <cstdint> #include <memory> #include <optional> #include <string> #include <utility> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/container/flat_hash_map.h" #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "arolla/dense_array/dense_array.h" #include "arolla/dense_array/qtype/types.h" #include "arolla/expr/basic_expr_operator.h" #include "arolla/expr/eval/executable_builder.h" #include "arolla/expr/eval/extensions.h" #include "arolla/expr/eval/invoke.h" #include "arolla/expr/eval/prepare_expression.h" #include "arolla/expr/eval/side_output.h" #include "arolla/expr/eval/test_utils.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_attributes.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/expr/lambda_expr_operator.h" #include "arolla/expr/optimization/default/default_optimizer.h" #include "arolla/expr/testing/test_operators.h" #include "arolla/expr/testing/testing.h" #include "arolla/expr/tuple_expr_operator.h" #include "arolla/io/accessors_input_loader.h" #include "arolla/io/input_loader.h" #include "arolla/memory/frame.h" #include "arolla/memory/memory_allocation.h" #include "arolla/memory/optional_value.h" #include "arolla/qexpr/bound_operators.h" #include "arolla/qexpr/eval_context.h" #include "arolla/qexpr/evaluation_engine.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/testing/qtype.h" #include "arolla/qtype/typed_slot.h" #include "arolla/qtype/typed_value.h" #include "arolla/util/fast_dynamic_downcast_final.h" #include "arolla/util/fingerprint.h" #include "arolla/util/init_arolla.h" #include "arolla/util/testing/status_matchers_backport.h" #include "arolla/util/text.h" #include "arolla/util/status_macros_backport.h" namespace arolla::expr { namespace { using ::arolla::testing::InvokeExprOperator; using ::arolla::testing::IsOk; using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::StatusIs; using ::arolla::testing::TypedValueWith; using ::arolla::testing::WithExportAnnotation; using ::arolla::testing::WithNameAnnotation; using ::arolla::testing::WithQTypeAnnotation; using ::testing::_; using ::testing::ElementsAre; using ::testing::Eq; using ::testing::FloatEq; using ::testing::HasSubstr; using ::testing::IsEmpty; using ::testing::Pair; using ::testing::Property; using ::testing::UnorderedElementsAre; struct TestParams { bool use_default_optimizer = false; }; class EvalVisitorParameterizedTest : public ::testing::TestWithParam<TestParams> { protected: EvalVisitorParameterizedTest() { CHECK_OK(InitArolla()); if (GetParam().use_default_optimizer) { auto optimizer_or = DefaultOptimizer(); CHECK_OK(optimizer_or.status()); options_.optimizer = optimizer_or.value(); } options_.collect_op_descriptions = true; } DynamicEvaluationEngineOptions options_; }; INSTANTIATE_TEST_SUITE_P( Optimizer, EvalVisitorParameterizedTest, ::testing::Values(TestParams{.use_default_optimizer = false}, TestParams{.use_default_optimizer = true})); TEST_P(EvalVisitorParameterizedTest, SmokeTest) { ASSERT_OK_AND_ASSIGN( auto expr, CallOp("math.add", {CallOp("math.add", {Leaf("x"), Leaf("y")}), Leaf("z")})); FrameLayout::Builder layout_builder; auto x_slot = layout_builder.AddSlot<float>(); auto y_slot = layout_builder.AddSlot<float>(); auto z_slot = layout_builder.AddSlot<float>(); ASSERT_OK_AND_ASSIGN( auto executable_expr, CompileAndBindForDynamicEvaluation(options_, &layout_builder, expr, {{"x", TypedSlot::FromSlot(x_slot)}, {"y", TypedSlot::FromSlot(y_slot)}, {"z", TypedSlot::FromSlot(z_slot)}})); EXPECT_THAT( executable_expr, AllOf(InitOperationsAre(), EvalOperationsAre( "FLOAT32 [0x10] = math.add(FLOAT32 [0x00], FLOAT32 [0x04])", "FLOAT32 [0x0C] = math.add(FLOAT32 [0x10], FLOAT32 [0x08])"))); FrameLayout layout = std::move(layout_builder).Build(); RootEvaluationContext ctx(&layout); EXPECT_OK(executable_expr->InitializeLiterals(&ctx)); ctx.Set(x_slot, 1.0f); ctx.Set(y_slot, 10.0f); ctx.Set(z_slot, 100.0f); EXPECT_THAT(executable_expr->Execute(&ctx), IsOk()); EXPECT_THAT(executable_expr->named_output_slots(), IsEmpty()); ASSERT_OK_AND_ASSIGN(auto output_slot, executable_expr->output_slot().ToSlot<float>()); EXPECT_EQ(ctx.Get(output_slot), 111.0f); EXPECT_EQ(ctx.Get(x_slot), 1.0f); EXPECT_EQ(ctx.Get(y_slot), 10.0f); EXPECT_EQ(ctx.Get(z_slot), 100.0f); } TEST_P(EvalVisitorParameterizedTest, ReusingInputSlots) { ASSERT_OK_AND_ASSIGN( auto expr, CallOp("math.add", {CallOp("math.add", {CallOp("math.add", {Leaf("x1"), Leaf("x2")}), Leaf("x3")}), Leaf("x4")})); DynamicEvaluationEngineOptions options{.collect_op_descriptions = true}; auto create_input_slots = [](FrameLayout::Builder& layout_builder) { return absl::flat_hash_map<std::string, TypedSlot>{ {"x1", TypedSlot::FromSlot(layout_builder.AddSlot<float>())}, {"x2", TypedSlot::FromSlot(layout_builder.AddSlot<float>())}, {"x3", TypedSlot::FromSlot(layout_builder.AddSlot<float>())}, {"x4", TypedSlot::FromSlot(layout_builder.AddSlot<float>())}}; }; { FrameLayout::Builder layout_builder; auto input_slots = create_input_slots(layout_builder); EXPECT_THAT( CompileAndBindForDynamicEvaluation(options, &layout_builder, expr, input_slots), IsOkAndHolds(AllOf( InitOperationsAre(), EvalOperationsAre( "FLOAT32 [0x14] = math.add(FLOAT32 [0x00], FLOAT32 [0x04])", "FLOAT32 [0x18] = math.add(FLOAT32 [0x14], FLOAT32 [0x08])", "FLOAT32 [0x10] = math.add(FLOAT32 [0x18], FLOAT32 [0x0C])")))); } { options.allow_overriding_input_slots = true; FrameLayout::Builder layout_builder; auto input_slots = create_input_slots(layout_builder); EXPECT_THAT( CompileAndBindForDynamicEvaluation(options, &layout_builder, expr, input_slots), IsOkAndHolds(AllOf( InitOperationsAre(), EvalOperationsAre( "FLOAT32 [0x14] = math.add(FLOAT32 [0x00], FLOAT32 [0x04])", "FLOAT32 [0x04] = math.add(FLOAT32 [0x14], FLOAT32 [0x08])", "FLOAT32 [0x10] = math.add(FLOAT32 [0x04], FLOAT32 [0x0C])")))); } } TEST_P(EvalVisitorParameterizedTest, NamedNodesTest) { constexpr int kIters = 10; ASSERT_OK_AND_ASSIGN(auto xpy, CallOp("math.add", {Leaf("x"), Leaf("y")})); auto expr = xpy; for (int i = 0; i < kIters; ++i) { ASSERT_OK_AND_ASSIGN( expr, CallOp("math.maximum", {expr, WithNameAnnotation(expr, std::to_string(i))})); } FrameLayout::Builder layout_builder; auto x_slot = layout_builder.AddSlot<float>(); auto y_slot = layout_builder.AddSlot<float>(); ASSERT_OK_AND_ASSIGN( auto executable_expr, CompileAndBindForDynamicEvaluation(options_, &layout_builder, expr, {{"x", TypedSlot::FromSlot(x_slot)}, {"y", TypedSlot::FromSlot(y_slot)}})); EXPECT_THAT( executable_expr, AllOf(InitOperationsAre(), EvalOperationsAre( "FLOAT32 [0x0C] = math.add(FLOAT32 [0x00], FLOAT32 [0x04])", "FLOAT32 [0x10] = math.maximum(FLOAT32 [0x0C], FLOAT32 [0x0C])", "FLOAT32 [0x0C] = math.maximum(FLOAT32 [0x10], FLOAT32 [0x10])", "FLOAT32 [0x10] = math.maximum(FLOAT32 [0x0C], FLOAT32 [0x0C])", "FLOAT32 [0x0C] = math.maximum(FLOAT32 [0x10], FLOAT32 [0x10])", "FLOAT32 [0x10] = math.maximum(FLOAT32 [0x0C], FLOAT32 [0x0C])", "FLOAT32 [0x0C] = math.maximum(FLOAT32 [0x10], FLOAT32 [0x10])", "FLOAT32 [0x10] = math.maximum(FLOAT32 [0x0C], FLOAT32 [0x0C])", "FLOAT32 [0x0C] = math.maximum(FLOAT32 [0x10], FLOAT32 [0x10])", "FLOAT32 [0x10] = math.maximum(FLOAT32 [0x0C], FLOAT32 [0x0C])", "FLOAT32 [0x08] = math.maximum(FLOAT32 [0x10], FLOAT32 " "[0x10])"))); FrameLayout layout = std::move(layout_builder).Build(); EXPECT_EQ(layout.AllocSize(), sizeof(float) * 5); RootEvaluationContext ctx(&layout); EXPECT_OK(executable_expr->InitializeLiterals(&ctx)); ctx.Set(x_slot, 1.0f); ctx.Set(y_slot, 10.0f); EXPECT_THAT(executable_expr->Execute(&ctx), IsOk()); EXPECT_THAT(executable_expr->named_output_slots(), IsEmpty()); ASSERT_OK_AND_ASSIGN(auto output_slot, executable_expr->output_slot().ToSlot<float>()); EXPECT_EQ(ctx.Get(output_slot), 11); } TEST_P(EvalVisitorParameterizedTest, WithUsedSubSlotOfInput) { ASSERT_OK_AND_ASSIGN(auto expr, CallOp("core.has", {Leaf("x")})); FrameLayout::Builder layout_builder; auto x_slot = layout_builder.AddSlot<OptionalValue<float>>(); ASSERT_OK_AND_ASSIGN( auto executable_expr, CompileAndBindForDynamicEvaluation(options_, &layout_builder, expr, {{"x", TypedSlot::FromSlot(x_slot)}})); EXPECT_THAT( executable_expr, AllOf(InitOperationsAre(), EvalOperationsAre( "OPTIONAL_UNIT [0x08] = core._copy(OPTIONAL_UNIT [0x00])"))); FrameLayout layout = std::move(layout_builder).Build(); RootEvaluationContext ctx(&layout); EXPECT_OK(executable_expr->InitializeLiterals(&ctx)); ctx.Set(x_slot, 1.0f); EXPECT_THAT(executable_expr->Execute(&ctx), IsOk()); EXPECT_THAT(executable_expr->named_output_slots(), IsEmpty()); ASSERT_OK_AND_ASSIGN(auto output_slot, executable_expr->output_slot().ToSlot<OptionalUnit>()); EXPECT_EQ(ctx.Get(output_slot), kPresent); EXPECT_EQ(ctx.Get(x_slot), 1.0f); } TEST_P(EvalVisitorParameterizedTest, WithUsedSubSlotOfIntermediate) { ASSERT_OK_AND_ASSIGN( auto expr, CallOp("core.has", {CallOp("math.add", {Leaf("x"), Leaf("y")})})); FrameLayout::Builder layout_builder; auto x_slot = layout_builder.AddSlot<OptionalValue<float>>(); auto y_slot = layout_builder.AddSlot<OptionalValue<float>>(); ASSERT_OK_AND_ASSIGN( auto executable_expr, CompileAndBindForDynamicEvaluation(options_, &layout_builder, expr, {{"x", TypedSlot::FromSlot(x_slot)}, {"y", TypedSlot::FromSlot(y_slot)}})); EXPECT_THAT( executable_expr, AllOf(InitOperationsAre(), EvalOperationsAre( "OPTIONAL_FLOAT32 [0x14] = math.add(OPTIONAL_FLOAT32 [0x00], " "OPTIONAL_FLOAT32 [0x08])", "OPTIONAL_UNIT [0x10] = core._copy(OPTIONAL_UNIT [0x14])"))); FrameLayout layout = std::move(layout_builder).Build(); RootEvaluationContext ctx(&layout); EXPECT_OK(executable_expr->InitializeLiterals(&ctx)); ctx.Set(x_slot, 1.0f); ctx.Set(y_slot, 10.0f); EXPECT_THAT(executable_expr->Execute(&ctx), IsOk()); EXPECT_THAT(executable_expr->named_output_slots(), IsEmpty()); ASSERT_OK_AND_ASSIGN(auto output_slot, executable_expr->output_slot().ToSlot<OptionalUnit>()); EXPECT_EQ(ctx.Get(output_slot), kPresent); EXPECT_EQ(ctx.Get(x_slot), 1.0f); EXPECT_EQ(ctx.Get(y_slot), 10.0f); } TEST_P(EvalVisitorParameterizedTest, EvalWithNamedOutput) { DynamicEvaluationEngineOptions options; options.collect_op_descriptions = true; ASSERT_OK_AND_ASSIGN( auto expr, CallOp("math.add", {WithExportAnnotation( CallOp("math.add", {Leaf("x"), Leaf("y")}), "x+y"), Leaf("z")})); ASSERT_OK_AND_ASSIGN((auto [stripped_expr, side_outputs]), ExtractSideOutputs(expr)); FrameLayout::Builder layout_builder; auto x_slot = layout_builder.AddSlot<float>(); auto y_slot = layout_builder.AddSlot<float>(); auto z_slot = layout_builder.AddSlot<float>(); const QTypePtr f32 = GetQType<float>(); ASSERT_OK_AND_ASSIGN(auto compiled_expr, CompileForDynamicEvaluation( options, stripped_expr, {{"x", f32}, {"y", f32}, {"z", f32}}, side_outputs)); EXPECT_EQ(compiled_expr->output_type(), f32); EXPECT_THAT(compiled_expr->named_output_types(), UnorderedElementsAre(Pair("x+y", f32))); auto typed_output_slot = AddSlot(compiled_expr->output_type(), &layout_builder); ASSERT_OK_AND_ASSIGN(auto executable_expr, compiled_expr->Bind(&layout_builder, {{"x", TypedSlot::FromSlot(x_slot)}, {"y", TypedSlot::FromSlot(y_slot)}, {"z", TypedSlot::FromSlot(z_slot)}}, typed_output_slot)); EXPECT_THAT( executable_expr, AllOf(InitOperationsAre(), EvalOperationsAre( "FLOAT32 [0x10] = math.add(FLOAT32 [0x00], FLOAT32 [0x04])", "FLOAT32 [0x0C] = math.add(FLOAT32 [0x10], FLOAT32 [0x08])"))); FrameLayout layout = std::move(layout_builder).Build(); EXPECT_EQ(layout.AllocSize(), sizeof(float) * 5) << "Side outputs shouldn't create any extra overhead"; RootEvaluationContext ctx(&layout); EXPECT_OK(executable_expr->InitializeLiterals(&ctx)); ctx.Set(x_slot, 1.0f); ctx.Set(y_slot, 10.0f); ctx.Set(z_slot, 100.0f); EXPECT_THAT(executable_expr->Execute(&ctx), IsOk()); ASSERT_OK_AND_ASSIGN(auto output_slot, typed_output_slot.ToSlot<float>()); ASSERT_THAT(executable_expr->named_output_slots(), UnorderedElementsAre(Pair("x+y", _))); ASSERT_OK_AND_ASSIGN( auto xpy_slot, executable_expr->named_output_slots().at("x+y").ToSlot<float>()); EXPECT_EQ(ctx.Get(output_slot), 111.0f); EXPECT_EQ(ctx.Get(xpy_slot), 11.0f); } TEST_P(EvalVisitorParameterizedTest, EvalWithSideOutput) { DynamicEvaluationEngineOptions options; options.collect_op_descriptions = true; ASSERT_OK_AND_ASSIGN(auto expr, CallOp("math.add", {Leaf("x"), Leaf("y")})); ASSERT_OK_AND_ASSIGN(auto side_output_expr, CallOp("math.multiply", {Leaf("y"), Leaf("z")})); FrameLayout::Builder layout_builder; auto x_slot = layout_builder.AddSlot<float>(); auto y_slot = layout_builder.AddSlot<float>(); auto z_slot = layout_builder.AddSlot<float>(); ASSERT_OK_AND_ASSIGN(auto executable_expr, CompileAndBindForDynamicEvaluation( options, &layout_builder, expr, {{"x", TypedSlot::FromSlot(x_slot)}, {"y", TypedSlot::FromSlot(y_slot)}, {"z", TypedSlot::FromSlot(z_slot)}}, std::nullopt, {{"y*z", side_output_expr}})); EXPECT_THAT( executable_expr, AllOf(InitOperationsAre(), EvalOperationsAre( "FLOAT32 [0x0C] = math.add(FLOAT32 [0x00], FLOAT32 [0x04])", "FLOAT32 [0x10] = math.multiply(FLOAT32 [0x04], FLOAT32 " "[0x08])"))); FrameLayout layout = std::move(layout_builder).Build(); RootEvaluationContext ctx(&layout); EXPECT_OK(executable_expr->InitializeLiterals(&ctx)); ctx.Set(x_slot, 1.0f); ctx.Set(y_slot, 10.0f); ctx.Set(z_slot, 100.0f); EXPECT_THAT(executable_expr->Execute(&ctx), IsOk()); ASSERT_OK_AND_ASSIGN(auto output_slot, executable_expr->output_slot().ToSlot<float>()); ASSERT_THAT(executable_expr->named_output_slots(), UnorderedElementsAre(Pair("y*z", _))); ASSERT_OK_AND_ASSIGN( auto side_output_slot, executable_expr->named_output_slots().at("y*z").ToSlot<float>()); EXPECT_EQ(ctx.Get(output_slot), 11.0f); EXPECT_EQ(ctx.Get(side_output_slot), 1000.0f); } TEST_P(EvalVisitorParameterizedTest, EvalWithShortCircuit) { ASSERT_OK_AND_ASSIGN( auto expr, CallOp("core.where", {Leaf("do_divide"), CallOp("math.multiply", {Leaf("x"), Leaf("y")}), CallOp("math.floordiv", {Leaf("x"), Leaf("y")})})); FrameLayout::Builder layout_builder; auto x_slot = layout_builder.AddSlot<OptionalValue<int>>(); auto y_slot = layout_builder.AddSlot<int>(); auto do_divide_slot = layout_builder.AddSlot<OptionalUnit>(); ASSERT_OK_AND_ASSIGN( auto executable_expr, CompileAndBindForDynamicEvaluation( options_, &layout_builder, expr, {{"x", TypedSlot::FromSlot(x_slot)}, {"y", TypedSlot::FromSlot(y_slot)}, {"do_divide", TypedSlot::FromSlot(do_divide_slot)}})); if (GetParam().use_default_optimizer) { EXPECT_THAT( executable_expr, AllOf(InitOperationsAre(), EvalOperationsAre( "OPTIONAL_INT32 [0x18] = core.to_optional._scalar(INT32 " "[0x08])", "jump_if_not<+2>(OPTIONAL_UNIT [0x0C])", "OPTIONAL_INT32 [0x10] = math.multiply(OPTIONAL_INT32 " "[0x00], OPTIONAL_INT32 [0x18])", "jump<+1>()", "OPTIONAL_INT32 [0x10] = math.floordiv(OPTIONAL_INT32 " "[0x00], OPTIONAL_INT32 [0x18])"))); } else { EXPECT_THAT( executable_expr, AllOf(InitOperationsAre(), EvalOperationsAre( "OPTIONAL_INT32 [0x18] = core.to_optional._scalar(INT32 " "[0x08])", "OPTIONAL_INT32 [0x20] = math.multiply(OPTIONAL_INT32 " "[0x00], OPTIONAL_INT32 [0x18])", "OPTIONAL_INT32 [0x28] = math.floordiv(OPTIONAL_INT32 " "[0x00], OPTIONAL_INT32 [0x18])", "OPTIONAL_INT32 [0x10] = core.where(OPTIONAL_UNIT [0x0C], " "OPTIONAL_INT32 [0x20], OPTIONAL_INT32 [0x28])"))); } FrameLayout layout = std::move(layout_builder).Build(); RootEvaluationContext ctx(&layout); EXPECT_OK(executable_expr->InitializeLiterals(&ctx)); ctx.Set(x_slot, 1); ctx.Set(y_slot, 0); ctx.Set(do_divide_slot, kPresent); if (GetParam().use_default_optimizer) { EXPECT_THAT(executable_expr->Execute(&ctx), IsOk()); ASSERT_OK_AND_ASSIGN( auto output_slot, executable_expr->output_slot().ToSlot<OptionalValue<int>>()); EXPECT_EQ(ctx.Get(output_slot), 0); } else { EXPECT_THAT(executable_expr->Execute(&ctx), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("division by zero; during evaluation of " "operator math.floordiv"))); } } TEST_P(EvalVisitorParameterizedTest, EvalWithNamedOutputUnusedButExported) { DynamicEvaluationEngineOptions options; options.collect_op_descriptions = true; ASSERT_OK_AND_ASSIGN( auto first_op, MakeLambdaOperator(ExprOperatorSignature::Make("p0, _px, _py"), Placeholder("p0"))); ASSERT_OK_AND_ASSIGN( auto expr, CallOp(first_op, {CallOp("math.add", {Leaf("x"), Leaf("z")}), WithExportAnnotation(CallOp("math.add", {Leaf("x"), Leaf("y")}), "x+y"), WithExportAnnotation( CallOp("math.multiply", {Leaf("y"), Leaf("z")}), "y*z")})); ASSERT_OK_AND_ASSIGN((auto [stripped_expr, side_outputs]), ExtractSideOutputs(expr)); FrameLayout::Builder layout_builder; auto x_slot = layout_builder.AddSlot<float>(); auto y_slot = layout_builder.AddSlot<float>(); auto z_slot = layout_builder.AddSlot<float>(); ASSERT_OK_AND_ASSIGN(auto executable_expr, CompileAndBindForDynamicEvaluation( options, &layout_builder, stripped_expr, {{"x", TypedSlot::FromSlot(x_slot)}, {"y", TypedSlot::FromSlot(y_slot)}, {"z", TypedSlot::FromSlot(z_slot)}}, std::nullopt, side_outputs)); EXPECT_THAT( executable_expr, AllOf(InitOperationsAre(), EvalOperationsAre( "FLOAT32 [0x0C] = math.add(FLOAT32 [0x00], FLOAT32 [0x08])", "FLOAT32 [0x10] = math.add(FLOAT32 [0x00], FLOAT32 [0x04])", "FLOAT32 [0x14] = math.multiply(FLOAT32 [0x04], FLOAT32 " "[0x08])"))); FrameLayout layout = std::move(layout_builder).Build(); EXPECT_EQ(layout.AllocSize(), sizeof(float) * 6) << "Side outputs used outside of main expression require " "extra slots"; RootEvaluationContext ctx(&layout); EXPECT_OK(executable_expr->InitializeLiterals(&ctx)); ctx.Set(x_slot, 1.0f); ctx.Set(y_slot, 10.0f); ctx.Set(z_slot, 100.0f); EXPECT_THAT(executable_expr->Execute(&ctx), IsOk()); ASSERT_OK_AND_ASSIGN(auto output_slot, executable_expr->output_slot().ToSlot<float>()); EXPECT_EQ(ctx.Get(output_slot), 101.0f); ASSERT_THAT(executable_expr->named_output_slots(), UnorderedElementsAre(Pair("x+y", _), Pair("y*z", _))); ASSERT_OK_AND_ASSIGN( auto xpy_slot, executable_expr->named_output_slots().at("x+y").ToSlot<float>()); EXPECT_EQ(ctx.Get(xpy_slot), 11.0f); ASSERT_OK_AND_ASSIGN( auto xtz_slot, executable_expr->named_output_slots().at("y*z").ToSlot<float>()); EXPECT_EQ(ctx.Get(xtz_slot), 1000.0f); } TEST_P(EvalVisitorParameterizedTest, EvalWithExportAnnotation) { DynamicEvaluationEngineOptions options; options.collect_op_descriptions = true; ASSERT_OK_AND_ASSIGN( auto expr, CallOp("math.add", {WithExportAnnotation( CallOp("math.add", {Leaf("x"), Leaf("y")}), "x+y"), Leaf("z")})); ASSERT_OK_AND_ASSIGN((auto [stripped_expr, side_outputs]), ExtractSideOutputs(expr)); FrameLayout::Builder layout_builder; auto x_slot = layout_builder.AddSlot<float>(); auto y_slot = layout_builder.AddSlot<float>(); auto z_slot = layout_builder.AddSlot<float>(); ASSERT_OK_AND_ASSIGN(auto executable_expr, CompileAndBindForDynamicEvaluation( options, &layout_builder, stripped_expr, {{"x", TypedSlot::FromSlot(x_slot)}, {"y", TypedSlot::FromSlot(y_slot)}, {"z", TypedSlot::FromSlot(z_slot)}}, std::nullopt, side_outputs)); EXPECT_THAT( executable_expr, AllOf(InitOperationsAre(), EvalOperationsAre( "FLOAT32 [0x10] = math.add(FLOAT32 [0x00], FLOAT32 [0x04])", "FLOAT32 [0x0C] = math.add(FLOAT32 [0x10], FLOAT32 [0x08])"))); FrameLayout layout = std::move(layout_builder).Build(); RootEvaluationContext ctx(&layout); EXPECT_OK(executable_expr->InitializeLiterals(&ctx)); ctx.Set(x_slot, 1.0f); ctx.Set(y_slot, 10.0f); ctx.Set(z_slot, 100.0f); EXPECT_THAT(executable_expr->Execute(&ctx), IsOk()); ASSERT_OK_AND_ASSIGN(auto output_slot, executable_expr->output_slot().ToSlot<float>()); ASSERT_THAT(executable_expr->named_output_slots(), UnorderedElementsAre(Pair("x+y", _))); ASSERT_OK_AND_ASSIGN( auto xpy_slot, executable_expr->named_output_slots().at("x+y").ToSlot<float>()); EXPECT_EQ(ctx.Get(output_slot), 111.0f); EXPECT_EQ(ctx.Get(xpy_slot), 11.0f); } TEST_P(EvalVisitorParameterizedTest, EvalWithExportAnnotation_AllLiterals) { DynamicEvaluationEngineOptions options; options.collect_op_descriptions = true; ASSERT_OK_AND_ASSIGN( auto expr, CallOp("math.add", {Literal(1.f), WithExportAnnotation(Literal(10.f), "out_y")})); ASSERT_OK_AND_ASSIGN((auto [stripped_expr, side_outputs]), ExtractSideOutputs(expr)); FrameLayout::Builder layout_builder; ASSERT_OK_AND_ASSIGN(auto executable_expr, CompileAndBindForDynamicEvaluation( options, &layout_builder, stripped_expr, {}, std::nullopt, side_outputs)); EXPECT_THAT( executable_expr, AllOf(InitOperationsAre("FLOAT32 [0x04] = 11.\n" "FLOAT32 [0x08] = 10."), EvalOperationsAre("FLOAT32 [0x00] = core._copy(FLOAT32 [0x04])"))); FrameLayout layout = std::move(layout_builder).Build(); RootEvaluationContext ctx(&layout); EXPECT_OK(executable_expr->InitializeLiterals(&ctx)); EXPECT_THAT(executable_expr->Execute(&ctx), IsOk()); ASSERT_OK_AND_ASSIGN(auto output_slot, executable_expr->output_slot().ToSlot<float>()); ASSERT_THAT(executable_expr->named_output_slots(), UnorderedElementsAre(Pair("out_y", _))); ASSERT_OK_AND_ASSIGN( auto out_y_slot, executable_expr->named_output_slots().at("out_y").ToSlot<float>()); EXPECT_EQ(ctx.Get(output_slot), 11.0f); EXPECT_EQ(ctx.Get(out_y_slot), 10.0f); } TEST_P(EvalVisitorParameterizedTest, EvalWithLiteral) { ASSERT_OK_AND_ASSIGN(auto expr, CallOp("math.add", {Leaf("x"), Literal(1.f)})); FrameLayout::Builder layout_builder; auto x_slot = layout_builder.AddSlot<float>(); ASSERT_OK_AND_ASSIGN( auto executable_expr, CompileAndBindForDynamicEvaluation(options_, &layout_builder, expr, {{"x", TypedSlot::FromSlot(x_slot)}})); EXPECT_THAT( executable_expr, AllOf(InitOperationsAre("FLOAT32 [0x08] = 1."), EvalOperationsAre( "FLOAT32 [0x04] = math.add(FLOAT32 [0x00], FLOAT32 [0x08])"))); FrameLayout layout = std::move(layout_builder).Build(); RootEvaluationContext ctx(&layout); EXPECT_OK(executable_expr->InitializeLiterals(&ctx)); ctx.Set(x_slot, 2.0f); EXPECT_THAT(executable_expr->Execute(&ctx), IsOk()); ASSERT_OK_AND_ASSIGN(auto output_slot, executable_expr->output_slot().ToSlot<float>()); EXPECT_THAT(ctx.Get(output_slot), Eq(3.0f)); } TEST_P(EvalVisitorParameterizedTest, EvalSingleLeaf) { auto expr = Leaf("x"); FrameLayout::Builder layout_builder; auto x_slot = layout_builder.AddSlot<float>(); auto output_slot = layout_builder.AddSlot<float>(); ASSERT_OK_AND_ASSIGN( auto executable_expr, CompileAndBindForDynamicEvaluation(options_, &layout_builder, expr, {{"x", TypedSlot::FromSlot(x_slot)}}, TypedSlot::FromSlot(output_slot))); EXPECT_THAT( executable_expr, AllOf(InitOperationsAre(), EvalOperationsAre("FLOAT32 [0x04] = core._copy(FLOAT32 [0x00])"))); FrameLayout layout = std::move(layout_builder).Build(); RootEvaluationContext ctx(&layout); EXPECT_OK(executable_expr->InitializeLiterals(&ctx)); ctx.Set(x_slot, 2.0f); EXPECT_THAT(executable_expr->Execute(&ctx), IsOk()); EXPECT_THAT(ctx.Get(output_slot), Eq(2.0f)); } TEST_P(EvalVisitorParameterizedTest, EvalOnlyLiterals) { auto x = Literal(2.f); auto y = Literal(1.f); ASSERT_OK_AND_ASSIGN(auto expr, CallOp("math.add", {x, y})); FrameLayout::Builder layout_builder; ASSERT_OK_AND_ASSIGN( auto executable_expr, CompileAndBindForDynamicEvaluation(options_, &layout_builder, expr, {})); EXPECT_THAT( executable_expr, AllOf(InitOperationsAre("FLOAT32 [0x04] = 3."), EvalOperationsAre("FLOAT32 [0x00] = core._copy(FLOAT32 [0x04])"))); FrameLayout layout = std::move(layout_builder).Build(); RootEvaluationContext ctx(&layout); ASSERT_OK_AND_ASSIGN(auto output_slot, executable_expr->output_slot().ToSlot<float>()); ctx.Set(output_slot, 57.0f); EXPECT_OK(executable_expr->InitializeLiterals(&ctx)); EXPECT_THAT(ctx.Get(output_slot), Eq(57.0f)); EXPECT_THAT(executable_expr->Execute(&ctx), IsOk()); EXPECT_THAT(ctx.Get(output_slot), Eq(3.0f)); } TEST_P(EvalVisitorParameterizedTest, EvalUnboundLeafError) { ASSERT_OK_AND_ASSIGN(auto expr, CallOp("math.add", {Leaf("x"), Leaf("y")})); EXPECT_THAT( CompileForDynamicEvaluation(options_, expr, {{"y", GetQType<float>()}}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("missing QType information for inputs {x}"))); EXPECT_THAT( CompileForDynamicEvaluation(options_, expr, {}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("missing QType information for inputs {x, y}"))); ASSERT_OK_AND_ASSIGN(auto compiled_model, CompileForDynamicEvaluation(options_, expr, {{"x", GetQType<float>()}, {"y", GetQType<float>()}})); FrameLayout::Builder layout_builder; EXPECT_THAT(compiled_model->Bind( &layout_builder, {{"y", TypedSlot::FromSlot(layout_builder.AddSlot<float>())}}, TypedSlot::FromSlot(layout_builder.AddSlot<float>())), StatusIs(absl::StatusCode::kFailedPrecondition, HasSubstr("missed slots: x"))); EXPECT_THAT(compiled_model->Bind( &layout_builder, {}, TypedSlot::FromSlot(layout_builder.AddSlot<float>())), StatusIs(absl::StatusCode::kFailedPrecondition, HasSubstr("missed slots: x,y"))); } TEST_P(EvalVisitorParameterizedTest, EvalPlaceholderError) { auto x = Literal(2.f); ASSERT_OK_AND_ASSIGN( auto y, WithQTypeAnnotation(Placeholder("y"), GetQType<float>())); ASSERT_OK_AND_ASSIGN(auto expr, CallOp("math.add", {x, y})); EXPECT_THAT( CompileForDynamicEvaluation(options_, expr, {{"y", GetQType<float>()}}), StatusIs(absl::StatusCode::kFailedPrecondition, HasSubstr( "placeholders should be substituted before evaluation: y"))); } TEST_P(EvalVisitorParameterizedTest, EvalOperatorTakingSameNodeTwice) { auto x = Leaf("x"); ASSERT_OK_AND_ASSIGN(auto expr, CallOp("math.add", {x, x})); FrameLayout::Builder layout_builder; auto x_slot = layout_builder.AddSlot<float>(); ASSERT_OK_AND_ASSIGN( auto executable_expr, CompileAndBindForDynamicEvaluation(options_, &layout_builder, expr,
2,473
#ifndef AROLLA_EXPR_EVAL_PREPARE_EXPRESSION_H_ #define AROLLA_EXPR_EVAL_PREPARE_EXPRESSION_H_ #include <functional> #include <memory> #include <string> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/status/statusor.h" #include "arolla/expr/eval/eval.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/expr_stack_trace.h" #include "arolla/qtype/qtype.h" #include "arolla/util/fingerprint.h" namespace arolla::expr::eval_internal { using NodeTransformationFn = std::function<absl::StatusOr<ExprNodePtr>( const DynamicEvaluationEngineOptions&, ExprNodePtr)>; absl::StatusOr<ExprNodePtr> PrepareExpression( const ExprNodePtr& expr, const absl::flat_hash_map<std::string, QTypePtr>& input_types, const DynamicEvaluationEngineOptions& options, std::shared_ptr<ExprStackTrace> stack_trace = nullptr); ExprOperatorPtr InternalRootOperator(); absl::StatusOr<ExprNodePtr> ExtractQTypesForCompilation( const ExprNodePtr& expr, absl::flat_hash_map<Fingerprint, QTypePtr>* resulting_types, std::shared_ptr<ExprStackTrace> stack_trace = nullptr); absl::StatusOr<absl::flat_hash_map<std::string, QTypePtr>> LookupNamedOutputTypes( const ExprNodePtr& prepared_expr, const std::vector<std::string>& side_output_names, const absl::flat_hash_map<Fingerprint, QTypePtr>& node_types); absl::StatusOr<QTypePtr> LookupQType( const ExprNodePtr node, const absl::flat_hash_map<Fingerprint, QTypePtr>& types); absl::StatusOr<absl::flat_hash_map<std::string, QTypePtr>> LookupLeafQTypes( const ExprNodePtr& expr, const absl::flat_hash_map<Fingerprint, QTypePtr>& types); } #endif #include "arolla/expr/eval/prepare_expression.h" #include <cstddef> #include <memory> #include <optional> #include <set> #include <string> #include <utility> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/container/flat_hash_set.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "absl/strings/str_join.h" #include "absl/types/span.h" #include "arolla/expr/annotation_expr_operators.h" #include "arolla/expr/annotation_utils.h" #include "arolla/expr/basic_expr_operator.h" #include "arolla/expr/eval/casting.h" #include "arolla/expr/eval/compile_where_operator.h" #include "arolla/expr/eval/eval.h" #include "arolla/expr/eval/extensions.h" #include "arolla/expr/eval/invoke.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_attributes.h" #include "arolla/expr/expr_debug_string.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/expr/expr_stack_trace.h" #include "arolla/expr/expr_visitor.h" #include "arolla/qtype/qtype.h" #include "arolla/util/fingerprint.h" #include "arolla/util/indestructible.h" #include "arolla/util/string.h" #include "arolla/util/status_macros_backport.h" namespace arolla::expr::eval_internal { namespace { using Stage = DynamicEvaluationEngineOptions::PreparationStage; class InternalRootOperatorImpl final : public BuiltinExprOperatorTag, public ExprOperatorWithFixedSignature { public: InternalRootOperatorImpl() : ExprOperatorWithFixedSignature( "_internal_root_operator_", ExprOperatorSignature{{.name = "arg0"}, {.name = "args", .kind = ExprOperatorSignature::Parameter:: Kind::kVariadicPositional}}, "", FingerprintHasher("::arolla::expr::InternalRootOperator") .Finish()) {} absl::StatusOr<ExprAttributes> InferAttributes( absl::Span<const ExprAttributes> inputs) const final { RETURN_IF_ERROR(ValidateOpInputsCount(inputs)); return inputs[0]; } }; bool AllDepsAreLiterals(const ExprNodePtr& node) { for (const auto& d : node->node_deps()) { if (!d->qvalue()) { return false; } } return true; } absl::Status MissingInputTypesError( const absl::flat_hash_map<std::string, QTypePtr>& input_types, const ExprNodePtr& root) { std::set<std::string> missing_types; for (const auto& node : VisitorOrder(root)) { if (!node->is_op() || IsQTypeAnnotation(node)) { continue; } for (const auto& d : node->node_deps()) { if (d->is_leaf() && !input_types.contains(d->leaf_key())) { missing_types.insert(d->leaf_key()); } } } if (root->is_leaf() && !input_types.contains(root->leaf_key())) { missing_types.insert(root->leaf_key()); } return absl::InvalidArgumentError( absl::StrFormat("missing QType information for inputs {%s}", Truncate(absl::StrJoin(missing_types, ", "), 200))); } absl::StatusOr<ExprNodePtr> AnnotateLeafWithQType( ExprNodePtr leaf, const absl::flat_hash_map<std::string, QTypePtr>& input_types, const ExprNodePtr& root) { auto it = input_types.find(leaf->leaf_key()); if (it == input_types.end()) { return MissingInputTypesError(input_types, root); } return CallOp(QTypeAnnotation::Make(), {std::move(leaf), Literal(it->second)}); } NodeTransformationFn PopulateQTypesTransformation( const absl::flat_hash_map<std::string, QTypePtr>& input_types, const ExprNodePtr& root) { return [&input_types, &root](const DynamicEvaluationEngineOptions&, ExprNodePtr node) -> absl::StatusOr<ExprNodePtr> { if (!node->is_op()) { return node; } if (const QType* annotated_qtype = ReadQTypeAnnotation(node); annotated_qtype != nullptr) { if (node->node_deps()[0]->is_leaf()) { auto it = input_types.find(node->node_deps()[0]->leaf_key()); if (it != input_types.end() && it->second != annotated_qtype) { return absl::FailedPreconditionError(absl::StrFormat( "inconsistent qtype annotation and input qtype: %s", JoinTypeNames({annotated_qtype, it->second}))); } return node; } else if (node->node_deps()[0]->qtype() != nullptr) { return node->node_deps()[0]; } } bool has_leaf_dep = false; for (const auto& d : node->node_deps()) { if (d->is_leaf()) { has_leaf_dep = true; } } if (!has_leaf_dep) { return node; } std::vector<ExprNodePtr> new_deps = node->node_deps(); for (auto& d : new_deps) { if (d->is_leaf()) { ASSIGN_OR_RETURN( d, AnnotateLeafWithQType(std::move(d), input_types, root)); } } return WithNewDependencies(node, std::move(new_deps)); }; } absl::StatusOr<ExprNodePtr> LiteralFoldingTransformation( const DynamicEvaluationEngineOptions& options, ExprNodePtr node) { if (!node->is_op() || !AllDepsAreLiterals(node) || node->op() == InternalRootOperator()) { return node; } if (node->qvalue()) { return Literal(*node->qvalue()); } DynamicEvaluationEngineOptions invoke_options = options; invoke_options.enabled_preparation_stages &= ~(Stage::kLiteralFolding | Stage::kPopulateQTypes | Stage::kOptimization | Stage::kWhereOperatorsTransformation); ASSIGN_OR_RETURN(auto result, Invoke(node, {}, invoke_options), _ << "while doing literal folding"); return Literal(result); } absl::StatusOr<ExprNodePtr> ToLowerTransformation( const DynamicEvaluationEngineOptions&, ExprNodePtr expr) { return ToLowerNode(expr); } absl::StatusOr<ExprNodePtr> StripAnnotationsTransformation( const DynamicEvaluationEngineOptions&, const ExprNodePtr& node) { ASSIGN_OR_RETURN(bool is_annotation, IsAnnotation(node)); if (is_annotation && node->node_deps().empty()) { return absl::FailedPreconditionError(absl::StrFormat( "invalid annotation %s: expected at least 1 argument, got 0", GetDebugSnippet(node))); } return (is_annotation && !IsQTypeAnnotation(node) ) ? node->node_deps()[0] : node; } absl::Status CheckForTypeMismatchAndSetType( absl::flat_hash_map<Fingerprint, QTypePtr>* resulting_types, const ExprNodePtr& expr, QTypePtr qtype) { auto it = resulting_types->find(expr->fingerprint()); if (it != resulting_types->end() && it->second != nullptr) { if (it->second != qtype) { return absl::FailedPreconditionError(absl::StrFormat( "different QTypes found for the same Expr %s: %s vs %s", GetDebugSnippet(expr), it->second->name(), qtype->name())); } } else { (*resulting_types)[expr->fingerprint()] = qtype; } return absl::OkStatus(); } absl::StatusOr<ExprNodePtr> ApplyNodeTransformations( const DynamicEvaluationEngineOptions& options, ExprNodePtr expr, absl::Span<const std::pair<TransformationType, NodeTransformationFn>> transformations, std::shared_ptr<ExprStackTrace> stack_trace) { return DeepTransform( expr, [&options, &transformations, &stack_trace](ExprNodePtr node) -> absl::StatusOr<ExprNodePtr> { for (const auto& t : transformations) { ASSIGN_OR_RETURN(auto result, t.second(options, node)); if (result->fingerprint() == node->fingerprint()) { continue; } if (!node->attr().IsSubsetOf(result->attr())) { return absl::FailedPreconditionError(absl::StrFormat( "expression %s attributes changed from %s to %s during " "compilation", GetDebugSnippet(node), absl::FormatStreamed(node->attr()), absl::FormatStreamed(result->attr()))); } if (stack_trace != nullptr) { stack_trace->AddTrace(result, node, t.first); } return result; } return node; }, [&stack_trace](ExprNodePtr node, ExprNodePtr prev_node, DeepTransformStage stage) { if (stack_trace != nullptr) { if (stage == DeepTransformStage::kWithNewDeps) { stack_trace->AddTrace(node, prev_node, TransformationType::kChildTransform); } else if (stage == DeepTransformStage::kNewChildAfterTransformation) { stack_trace->AddTrace( node, prev_node, TransformationType::kCausedByAncestorTransform); } } }); } absl::StatusOr<ExprNodePtr> PrepareSingleLeafExpression( const ExprNodePtr& expr, const absl::flat_hash_map<std::string, QTypePtr>& input_types, const DynamicEvaluationEngineOptions& options) { if (options.enabled_preparation_stages & Stage::kPopulateQTypes) { return AnnotateLeafWithQType(expr, input_types, expr); } else { return expr; } } } absl::StatusOr<ExprNodePtr> PrepareExpression( const ExprNodePtr& expr, const absl::flat_hash_map<std::string, QTypePtr>& input_types, const DynamicEvaluationEngineOptions& options, std::shared_ptr<ExprStackTrace> stack_trace) { if (expr->is_leaf()) { return PrepareSingleLeafExpression(expr, input_types, options); } ExprNodePtr current_expr = expr; std::vector<std::pair<TransformationType, NodeTransformationFn>> transformations; if (options.enabled_preparation_stages & Stage::kPopulateQTypes) { transformations.push_back( {TransformationType::kUntraced, PopulateQTypesTransformation(input_types, expr)}); } if (options.enabled_preparation_stages & Stage::kLiteralFolding) { transformations.push_back( {TransformationType::kUntraced, LiteralFoldingTransformation}); } if (options.enabled_preparation_stages & Stage::kToLower) { transformations.push_back( {TransformationType::kLowering, ToLowerTransformation}); } if (options.enabled_preparation_stages & Stage::kStripAnnotations) { transformations.push_back( {TransformationType::kUntraced, StripAnnotationsTransformation}); } if (options.enabled_preparation_stages & Stage::kBackendCompatibilityCasting) { transformations.push_back( {TransformationType::kUntraced, CastingTransformation}); } if (options.enabled_preparation_stages & Stage::kOptimization && options.optimizer.has_value()) { transformations.push_back( {TransformationType::kOptimization, [](const DynamicEvaluationEngineOptions& options, ExprNodePtr expr) { return (*options.optimizer)(std::move(expr)); }}); } if (options.enabled_preparation_stages & Stage::kExtensions) { transformations.push_back( {TransformationType::kUntraced, CompilerExtensionRegistry::GetInstance() .GetCompilerExtensionSet() .node_transformation_fn}); } ASSIGN_OR_RETURN(current_expr, ApplyNodeTransformations(options, current_expr, transformations, stack_trace)); if (options.enabled_preparation_stages & Stage::kWhereOperatorsTransformation) { ASSIGN_OR_RETURN(current_expr, WhereOperatorGlobalTransformation(options, current_expr)); } return current_expr; } ExprOperatorPtr InternalRootOperator() { static Indestructible<ExprOperatorPtr> first_op( std::make_shared<InternalRootOperatorImpl>()); return (*first_op); } absl::StatusOr<absl::flat_hash_map<std::string, QTypePtr>> LookupNamedOutputTypes( const ExprNodePtr& prepared_expr, const std::vector<std::string>& side_output_names, const absl::flat_hash_map<Fingerprint, QTypePtr>& node_types) { absl::flat_hash_map<std::string, QTypePtr> named_output_types; if (!side_output_names.empty()) { const auto& root_deps = prepared_expr->node_deps(); if (root_deps.size() != side_output_names.size() + 1) { return absl::InternalError("inconsistent side_output_names size"); } named_output_types.reserve(side_output_names.size()); for (size_t i = 0; i != side_output_names.size(); ++i) { const auto& name = side_output_names[i]; if (auto it = node_types.find(root_deps[i + 1]->fingerprint()); it != node_types.end()) { named_output_types.emplace(name, it->second); } else { return absl::FailedPreconditionError( absl::StrFormat("unable to deduce named output type for %s in " "the expression %s.", name, GetDebugSnippet(prepared_expr))); } } } return named_output_types; } absl::StatusOr<ExprNodePtr> ExtractQTypesForCompilation( const ExprNodePtr& expr, absl::flat_hash_map<Fingerprint, QTypePtr>* resulting_types, std::shared_ptr<ExprStackTrace> stack_trace) { return PostOrderTraverse( expr, [&resulting_types, &stack_trace]( const ExprNodePtr& node, absl::Span<const ExprNodePtr* const> visits) -> absl::StatusOr<ExprNodePtr> { if (IsQTypeAnnotation(node) && !visits.empty()) { QTypePtr qtype = node->qtype(); ExprNodePtr wrapped_node = *(visits[0]); RETURN_IF_ERROR(CheckForTypeMismatchAndSetType(resulting_types, wrapped_node, qtype)); ASSIGN_OR_RETURN(bool is_annotation, IsAnnotation(wrapped_node)); while (is_annotation && !wrapped_node->node_deps().empty()) { wrapped_node = wrapped_node->node_deps()[0]; RETURN_IF_ERROR(CheckForTypeMismatchAndSetType( resulting_types, wrapped_node, qtype)); ASSIGN_OR_RETURN(is_annotation, IsAnnotation(wrapped_node)); } if (stack_trace != nullptr) { stack_trace->AddTrace(*(visits[0]), node, TransformationType::kUntraced); } return *(visits[0]); } std::vector<expr::ExprNodePtr> node_deps = DereferenceVisitPointers(visits); ASSIGN_OR_RETURN(auto new_node, WithNewDependencies(node, std::move(node_deps))); RETURN_IF_ERROR(CheckForTypeMismatchAndSetType( resulting_types, new_node, node->qtype())); if (stack_trace != nullptr) { stack_trace->AddTrace(new_node, node, TransformationType::kUntraced); } return new_node; }); } absl::StatusOr<QTypePtr> LookupQType( const ExprNodePtr node, const absl::flat_hash_map<Fingerprint, QTypePtr>& types) { if (auto it = types.find(node->fingerprint()); it != types.end()) { return it->second; } return absl::InternalError( absl::StrFormat("unknown QType for node %s", GetDebugSnippet(node))); } absl::StatusOr<absl::flat_hash_map<std::string, QTypePtr>> LookupLeafQTypes( const ExprNodePtr& expr, const absl::flat_hash_map<Fingerprint, QTypePtr>& types) { absl::flat_hash_map<std::string, QTypePtr> result; for (const auto& node : VisitorOrder(expr)) { if (node->is_leaf()) { ASSIGN_OR_RETURN(result[node->leaf_key()], LookupQType(node, types)); } } return result; } }
#include "arolla/expr/eval/prepare_expression.h" #include <cstdint> #include <memory> #include <string> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/container/flat_hash_map.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/types/span.h" #include "arolla/dense_array/qtype/types.h" #include "arolla/expr/annotation_expr_operators.h" #include "arolla/expr/basic_expr_operator.h" #include "arolla/expr/eval/eval.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_attributes.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/expr/expr_stack_trace.h" #include "arolla/expr/lambda_expr_operator.h" #include "arolla/expr/optimization/optimizer.h" #include "arolla/expr/testing/test_operators.h" #include "arolla/expr/testing/testing.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/util/bytes.h" #include "arolla/util/fingerprint.h" #include "arolla/util/init_arolla.h" #include "arolla/util/testing/status_matchers_backport.h" #include "arolla/util/text.h" namespace arolla::expr::eval_internal { namespace { using ::arolla::expr::testing::DummyOp; using ::arolla::testing::EqualsExpr; using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::StatusIs; using ::arolla::testing::WithQTypeAnnotation; using ::testing::Eq; using ::testing::HasSubstr; class IdentityAnnotation final : public AnnotationExprOperatorTag, public ExprOperatorWithFixedSignature { public: IdentityAnnotation() : ExprOperatorWithFixedSignature( "id", ExprOperatorSignature::MakeArgsN(1), "", FingerprintHasher("arolla::expr::IdentityAnnotation").Finish()) {} absl::StatusOr<ExprAttributes> InferAttributes( absl::Span<const ExprAttributes> inputs) const final { return inputs[0]; } }; class OperatorWithBadGetOutputQType : public ExprOperatorWithFixedSignature { public: OperatorWithBadGetOutputQType() : ExprOperatorWithFixedSignature( "bad_op", ExprOperatorSignature::MakeArgsN(1), "", FingerprintHasher("arolla::expr::OperatorWithBadGetOutputQType") .Finish()) {} absl::StatusOr<ExprAttributes> InferAttributes( absl::Span<const ExprAttributes> inputs) const final { return ExprAttributes(GetQType<int64_t>()); } absl::StatusOr<ExprNodePtr> ToLowerLevel( const ExprNodePtr& node) const final { return node->node_deps()[0]; } }; class OperatorWithNoInferAttributes final : public ExprOperatorWithFixedSignature { public: OperatorWithNoInferAttributes() : ExprOperatorWithFixedSignature( "no_infer_attr", ExprOperatorSignature::MakeArgsN(1), "", FingerprintHasher("arolla::expr::OperatorWithNoInferAttributes") .Finish()) {} absl::StatusOr<ExprAttributes> InferAttributes( absl::Span<const ExprAttributes> inputs) const final { return ExprAttributes{}; } }; class PrepareExpressionTest : public ::testing::Test { protected: void SetUp() override { ASSERT_OK(InitArolla()); } }; TEST_F(PrepareExpressionTest, ExtractQTypeForCompilation) { const auto id_annotation = std::make_shared<IdentityAnnotation>(); auto x = Leaf("x"); ASSERT_OK_AND_ASSIGN(auto id_expr, CallOp(id_annotation, {x})); ASSERT_OK_AND_ASSIGN(auto expr, WithQTypeAnnotation(id_expr, GetQType<float>())); absl::flat_hash_map<Fingerprint, QTypePtr> types; ASSERT_OK_AND_ASSIGN(auto stripped_expr, ExtractQTypesForCompilation(expr, &types)); EXPECT_THAT(stripped_expr, EqualsExpr(id_expr)); EXPECT_EQ(types[x->fingerprint()], GetQType<float>()); EXPECT_EQ(types[id_expr->fingerprint()], GetQType<float>()); } TEST_F(PrepareExpressionTest, Optimizations) { auto pattern_op = std::make_shared<DummyOp>( "pattern_op", ExprOperatorSignature::MakeArgsN(2)); auto pattern_x = Literal(2); Optimizer literals_optimizer = [pattern_op, pattern_x](ExprNodePtr node) { if (node->op() == pattern_op && node->node_deps()[0]->fingerprint() == pattern_x->fingerprint()) { return Literal(57); } return node; }; const absl::flat_hash_map<std::string, QTypePtr> input_qtypes = { {"u", GetQType<Text>()}, {"v", GetQType<Bytes>()}}; DynamicEvaluationEngineOptions options{.optimizer = literals_optimizer}; { ASSERT_OK_AND_ASSIGN( auto expr, CallOp("math.add", {CallOp(pattern_op, {pattern_x, Leaf("u")}), CallOp(pattern_op, {pattern_x, Leaf("v")})})); EXPECT_THAT(PrepareExpression(expr, input_qtypes, options), IsOkAndHolds(EqualsExpr(Literal(114)))); } { ASSERT_OK_AND_ASSIGN( auto expr, CallOp(pattern_op, {CallOp("math.add", {Literal(1), Literal(1)}), Leaf("u")})); EXPECT_THAT(PrepareExpression(expr, input_qtypes, options), IsOkAndHolds(EqualsExpr(Literal(57)))); } ASSERT_OK_AND_ASSIGN( auto add_1_lambda, MakeLambdaOperator(ExprOperatorSignature{{"x"}}, CallOp("math.add", {Placeholder("x"), Literal(1)}))); { ASSERT_OK_AND_ASSIGN( auto expr, CallOp(add_1_lambda, {CallOp(pattern_op, {pattern_x, Leaf("u")})})); EXPECT_THAT(PrepareExpression(expr, input_qtypes, options), IsOkAndHolds(EqualsExpr(Literal(58)))); } { ASSERT_OK_AND_ASSIGN( auto expr, CallOp(pattern_op, {CallOp(add_1_lambda, {Literal(1)}), Leaf("u")})); EXPECT_THAT(PrepareExpression(expr, input_qtypes, options), IsOkAndHolds(EqualsExpr(Literal(57)))); } } TEST_F(PrepareExpressionTest, DetailedStackTraceBuilding) { ASSERT_OK_AND_ASSIGN( auto add_2_lambda, MakeLambdaOperator("add_2_lambda", ExprOperatorSignature{{"x"}}, CallOp("math.add", {Placeholder("x"), Literal(2)}))); auto pattern_op = std::make_shared<DummyOp>( "pattern_op", ExprOperatorSignature::MakeArgsN(2)); Optimizer dummy_optimizer = [pattern_op, add_2_lambda](ExprNodePtr node) -> absl::StatusOr<ExprNodePtr> { if (node->op() == pattern_op && node->node_deps()[0]->fingerprint() == Literal(2)->fingerprint()) { return CallOp(add_2_lambda, {node->node_deps()[1]}); } return node; }; DynamicEvaluationEngineOptions options{.optimizer = dummy_optimizer}; auto stack_trace = std::make_shared<DetailedExprStackTrace>(); ASSERT_OK_AND_ASSIGN( auto expr, CallOp(pattern_op, {CallOp("math.add", {Literal(1), Literal(1)}), Leaf("u")})); ASSERT_OK_AND_ASSIGN( auto prepared_expr, PrepareExpression(expr, {{"u", GetQType<int>()}}, options, stack_trace)); EXPECT_EQ(stack_trace->FullTrace(prepared_expr->fingerprint()), "ORIGINAL NODE: pattern_op(M.math.add(..., ...):INT32, L.u)\n" "COMPILED NODE: M.math.add(annotation.qtype(..., ...), 2):INT32\n" "DETAILED STACK TRACE:\n" "pattern_op(M.math.add(..., ...):INT32, L.u)\n" " had transformations applied to its children\n" "pattern_op(2, L.u)\n" " was optimized to\n" "add_2_lambda(annotation.qtype(..., ...)):INT32\n" " was lowered to\n" "M.math.add(annotation.qtype(..., ...), 2):INT32"); } TEST_F(PrepareExpressionTest, LightweightStackTraceBuilding) { ASSERT_OK_AND_ASSIGN( auto add_2_lambda, MakeLambdaOperator("add_2_lambda", ExprOperatorSignature{{"x"}}, CallOp("math.add", {Placeholder("x"), Literal(2)}))); auto pattern_op = std::make_shared<DummyOp>( "pattern_op", ExprOperatorSignature::MakeArgsN(2)); Optimizer dummy_optimizer = [pattern_op, add_2_lambda](ExprNodePtr node) -> absl::StatusOr<ExprNodePtr> { if (node->op() == pattern_op && node->node_deps()[0]->fingerprint() == Literal(2)->fingerprint()) { return CallOp(add_2_lambda, {node->node_deps()[1]}); } return node; }; DynamicEvaluationEngineOptions options{.optimizer = dummy_optimizer}; auto stack_trace = std::make_shared<LightweightExprStackTrace>(); ASSERT_OK_AND_ASSIGN( auto expr, CallOp(pattern_op, {CallOp("math.add", {Literal(1), Literal(1)}), Leaf("u")})); ASSERT_OK_AND_ASSIGN( auto prepared_expr, PrepareExpression(expr, {{"u", GetQType<int>()}}, options, stack_trace)); stack_trace->AddRepresentations(prepared_expr, expr); EXPECT_EQ(stack_trace->FullTrace(prepared_expr->fingerprint()), "ORIGINAL NODE: pattern_op(M.math.add(..., ...):INT32, L.u)\n" "COMPILED NODE: M.math.add(annotation.qtype(..., ...), 2):INT32"); } TEST_F(PrepareExpressionTest, StackTraceWithErrorNestedUnderLambda) { ASSERT_OK_AND_ASSIGN( auto lambda_with_nested_error, MakeLambdaOperator( "lambda_with_nested_error", ExprOperatorSignature{{"x"}, {"y"}}, CallOp("math.add", {Literal(2.0), CallOp("math.divide", {Placeholder("x"), Placeholder("y")})}))); auto stack_trace = std::make_shared<DetailedExprStackTrace>(); ASSERT_OK_AND_ASSIGN( auto expr, CallOp(lambda_with_nested_error, {Leaf("x"), Leaf("y")})); ASSERT_OK_AND_ASSIGN( auto prepared_expr, PrepareExpression(expr, {{"x", GetQType<float>()}, {"y", GetQType<float>()}}, DynamicEvaluationEngineOptions{}, stack_trace)); ASSERT_OK_AND_ASSIGN(auto faulty_node, CallOp("math.divide", {Leaf("x"), Leaf("y")})); ASSERT_OK_AND_ASSIGN( faulty_node, PrepareExpression(faulty_node, {{"x", GetQType<float>()}, {"y", GetQType<float>()}}, DynamicEvaluationEngineOptions{})); EXPECT_THAT( stack_trace->FullTrace(faulty_node->fingerprint()), Eq("ORIGINAL NODE: lambda_with_nested_error(L.x, L.y)\n" "COMPILED NODE: M.math.divide(annotation.qtype(..., ...), " "annotation.qtype(..., ...)):FLOAT32\n" "DETAILED STACK TRACE:\n" "lambda_with_nested_error(L.x, L.y)\n" " was lowered to\n" "M.math.add(float64{2}, M.math.divide(..., ...):FLOAT32):FLOAT64\n" " which contains\n" "M.math.divide(annotation.qtype(..., ...)," " annotation.qtype(..., ...)):FLOAT32")); } TEST_F(PrepareExpressionTest, StackTraceBuildingNoTransformations) { ASSERT_OK_AND_ASSIGN( auto expr, CallOp("edge.from_sizes", {CallOp("annotation.qtype", {Leaf("x"), Literal(GetDenseArrayQType<int64_t>())})})); auto stack_trace = std::make_shared<DetailedExprStackTrace>(); ASSERT_OK_AND_ASSIGN( auto prepared_expr, PrepareExpression(expr, {{"x", GetDenseArrayQType<int64_t>()}}, DynamicEvaluationEngineOptions{}, stack_trace)); BoundExprStackTraceBuilder stack_trace_builder(stack_trace); stack_trace_builder.RegisterIp(0, prepared_expr); auto bound_stack_trace = stack_trace_builder.Build(10); EXPECT_EQ(bound_stack_trace[0], ""); } TEST_F(PrepareExpressionTest, StackTraceAnnotationCycle) { ASSERT_OK_AND_ASSIGN( auto expr, CallOp("edge.from_sizes", {Leaf("x")})); auto stack_trace = std::make_shared<DetailedExprStackTrace>(); ASSERT_OK_AND_ASSIGN( auto prepared_expr, PrepareExpression(expr, {{"x", GetDenseArrayQType<int64_t>()}}, DynamicEvaluationEngineOptions{}, stack_trace)); absl::flat_hash_map<Fingerprint, QTypePtr> node_types; ASSERT_OK_AND_ASSIGN(prepared_expr, eval_internal::ExtractQTypesForCompilation( prepared_expr, &node_types, stack_trace)); BoundExprStackTraceBuilder stack_trace_builder(stack_trace); stack_trace_builder.RegisterIp(0, prepared_expr); auto bound_stack_trace = stack_trace_builder.Build(10); EXPECT_EQ(bound_stack_trace[0], ""); } TEST_F(PrepareExpressionTest, OperatorWithBadGetOutputQType) { ASSERT_OK_AND_ASSIGN(auto expr, CallOp(std::make_shared<OperatorWithBadGetOutputQType>(), {Literal(2.0)})); EXPECT_THAT( PrepareExpression(expr, {}, DynamicEvaluationEngineOptions{}), StatusIs(absl::StatusCode::kFailedPrecondition, "expression bad_op(float64{2}):INT64 attributes changed in " "ToLower from Attr(qtype=INT64) to Attr(qvalue=float64{2}); " "this indicates incorrect InferAttributes() or GetOutputType() " "of the operator bad_op; while transforming " "bad_op(float64{2}):INT64; while doing literal folding; while " "transforming bad_op(float64{2}):INT64")); } TEST_F(PrepareExpressionTest, StripAnnotations) { const auto id_annotation = std::make_shared<IdentityAnnotation>(); ASSERT_OK_AND_ASSIGN(auto x, WithQTypeAnnotation(Leaf("x"), GetQType<float>())); ASSERT_OK_AND_ASSIGN( auto expr, CallOp(id_annotation, {CallOp("math.neg", {CallOp(id_annotation, {x})})})); EXPECT_THAT(PrepareExpression(expr, {}, DynamicEvaluationEngineOptions{}), IsOkAndHolds(EqualsExpr(CallOp("math.neg", {x})))); } TEST_F(PrepareExpressionTest, SingleLeafExpression) { auto expr = Leaf("x"); EXPECT_THAT( PrepareExpression(expr, {{"x", GetQType<float>()}}, DynamicEvaluationEngineOptions{}), IsOkAndHolds(EqualsExpr(CallOp( QTypeAnnotation::Make(), {Leaf("x"), Literal(GetQType<float>())})))); EXPECT_THAT(PrepareExpression(expr, {}, DynamicEvaluationEngineOptions{}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("missing QType information for inputs {x}"))); } TEST_F(PrepareExpressionTest, QTypeAnnotations) { ASSERT_OK_AND_ASSIGN( auto expr, CallOp("math.neg", {WithQTypeAnnotation(Leaf("x"), GetQType<float>())})); EXPECT_THAT(PrepareExpression(expr, {}, DynamicEvaluationEngineOptions{}), IsOkAndHolds(EqualsExpr(expr))); EXPECT_THAT(PrepareExpression(expr, {{"x", GetQType<float>()}}, DynamicEvaluationEngineOptions{}), IsOkAndHolds(EqualsExpr(expr))); EXPECT_THAT(PrepareExpression(expr, {{"x", GetQType<double>()}}, DynamicEvaluationEngineOptions{}), StatusIs(absl::StatusCode::kFailedPrecondition, HasSubstr("inconsistent qtype annotation and input " "qtype: FLOAT32,FLOAT64"))); EXPECT_THAT(PrepareExpression(expr, {{"x", nullptr}}, DynamicEvaluationEngineOptions{}), StatusIs(absl::StatusCode::kFailedPrecondition, HasSubstr("inconsistent qtype annotation and input " "qtype: FLOAT32,NULL"))); } TEST_F(PrepareExpressionTest, QTypeAnnotations_WithPartiallyAnnotatedLeaves) { auto x = Leaf("x"); ASSERT_OK_AND_ASSIGN(auto typed_x, CallOp(QTypeAnnotation::Make(), {x, Literal(GetQType<float>())})); ASSERT_OK_AND_ASSIGN(auto expr, CallOp("core.make_tuple", {typed_x, x})); EXPECT_THAT(PrepareExpression(expr, {}, DynamicEvaluationEngineOptions{}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("missing QType information for inputs {x}"))); EXPECT_THAT( PrepareExpression(expr, {{"x", GetQType<float>()}}, DynamicEvaluationEngineOptions{}), IsOkAndHolds(EqualsExpr(CallOp("core.make_tuple", {typed_x, typed_x})))); } TEST_F(PrepareExpressionTest, StripExtraQTypeAnnotations) { ASSERT_OK_AND_ASSIGN(auto typed_x, WithQTypeAnnotation(Leaf("x"), GetQType<float>())); ASSERT_OK_AND_ASSIGN(auto typed_typed_x, WithQTypeAnnotation(typed_x, GetQType<float>())); EXPECT_THAT( PrepareExpression(typed_typed_x, {}, DynamicEvaluationEngineOptions{}), IsOkAndHolds(EqualsExpr(typed_x))); ASSERT_OK_AND_ASSIGN( auto expr_with_non_deducible_type_annotation, WithQTypeAnnotation( CallOp(std::make_shared<OperatorWithNoInferAttributes>(), {typed_x}), GetQType<float>())); EXPECT_THAT( PrepareExpression(expr_with_non_deducible_type_annotation, {}, DynamicEvaluationEngineOptions{}), IsOkAndHolds(EqualsExpr(expr_with_non_deducible_type_annotation))); ASSERT_OK_AND_ASSIGN( auto expr_with_double_type_annotation, WithQTypeAnnotation(expr_with_non_deducible_type_annotation, GetQType<float>())); EXPECT_THAT( PrepareExpression(expr_with_double_type_annotation, {}, DynamicEvaluationEngineOptions{}), IsOkAndHolds(EqualsExpr(expr_with_non_deducible_type_annotation))); } } }
2,474
#ifndef AROLLA_EXPR_EVAL_COMPILE_WHERE_OPERATOR_H_ #define AROLLA_EXPR_EVAL_COMPILE_WHERE_OPERATOR_H_ #include "absl/status/statusor.h" #include "absl/types/span.h" #include "arolla/expr/basic_expr_operator.h" #include "arolla/expr/eval/dynamic_compiled_operator.h" #include "arolla/expr/eval/eval.h" #include "arolla/expr/eval/executable_builder.h" #include "arolla/expr/expr_attributes.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_operator.h" #include "arolla/qtype/typed_slot.h" namespace arolla::expr::eval_internal { class PackedWhereOp final : public BuiltinExprOperatorTag, public ExprOperatorWithFixedSignature { struct PrivateConstructorTag {}; public: static absl::StatusOr<ExprOperatorPtr> Create( DynamicCompiledOperator true_op, DynamicCompiledOperator false_op); PackedWhereOp(PrivateConstructorTag, DynamicCompiledOperator true_op, DynamicCompiledOperator false_op); const DynamicCompiledOperator& true_op() const { return true_op_; } const DynamicCompiledOperator& false_op() const { return false_op_; } absl::StatusOr<ExprAttributes> InferAttributes( absl::Span<const ExprAttributes> inputs) const final; private: DynamicCompiledOperator true_op_; DynamicCompiledOperator false_op_; }; absl::StatusOr<ExprNodePtr> WhereOperatorGlobalTransformation( const DynamicEvaluationEngineOptions& options, ExprNodePtr node); absl::StatusOr<TypedSlot> CompileWhereOperator( const DynamicEvaluationEngineOptions& options, const PackedWhereOp& where_op, absl::Span<const TypedSlot> input_slots, TypedSlot output_slot, eval_internal::ExecutableBuilder* executable_builder); } #endif #include "arolla/expr/eval/compile_where_operator.h" #include <algorithm> #include <cstddef> #include <cstdint> #include <functional> #include <memory> #include <string> #include <utility> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "absl/types/span.h" #include "arolla/algorithm/control_flow_graph.h" #include "arolla/expr/annotation_utils.h" #include "arolla/expr/basic_expr_operator.h" #include "arolla/expr/eval/dynamic_compiled_operator.h" #include "arolla/expr/eval/eval.h" #include "arolla/expr/eval/executable_builder.h" #include "arolla/expr/eval/expr_utils.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_attributes.h" #include "arolla/expr/expr_debug_string.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/expr/expr_visitor.h" #include "arolla/expr/qtype_utils.h" #include "arolla/expr/registered_expr_operator.h" #include "arolla/memory/optional_value.h" #include "arolla/qexpr/bound_operators.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/typed_slot.h" #include "arolla/util/fingerprint.h" #include "arolla/util/status_macros_backport.h" namespace arolla::expr::eval_internal { namespace { using Stage = DynamicEvaluationEngineOptions::PreparationStage; class ExprDominatorTree { public: static absl::StatusOr<ExprDominatorTree> Build(const ExprNodePtr& root) { auto node_order = expr::VisitorOrder(root); std::reverse(node_order.begin(), node_order.end()); absl::flat_hash_map<Fingerprint, AcyclicCFG::NodeId> node_ids; node_ids.reserve(node_order.size()); for (size_t i = 0; i < node_order.size(); ++i) { node_ids[node_order[i]->fingerprint()] = i; } std::vector<std::vector<AcyclicCFG::NodeId>> deps; deps.reserve(node_order.size()); for (const auto& node : node_order) { deps.emplace_back(); deps.back().reserve(node->node_deps().size()); for (const auto& dep : node->node_deps()) { deps.back().push_back(node_ids.at(dep->fingerprint())); } } ASSIGN_OR_RETURN(auto graph, AcyclicCFG::Create(std::move(deps))); DominatorTree tree(*graph); return ExprDominatorTree(std::move(graph), std::move(tree), std::move(node_ids)); } bool StrictlyDominates(const ExprNodePtr& descendant, const ExprNodePtr& ancestor) const { int64_t descendant_id = GetNodeId(descendant); int64_t ancestor_id = GetNodeId(ancestor); return tree_.depth(descendant_id) > tree_.depth(ancestor_id); } bool HasSingleParentInExprDag(const ExprNodePtr& node) const { int64_t id = GetNodeId(node); return graph_->reverse_deps(id).size() == 1; } void AddNodeAlias(const ExprNodePtr& new_node, const ExprNodePtr& old_node) { node_ids_.emplace(new_node->fingerprint(), GetNodeId(old_node)); } private: AcyclicCFG::NodeId GetNodeId(const ExprNodePtr& node) const { DCHECK(node_ids_.contains(node->fingerprint())) << "No node id registered for node " << GetDebugSnippet(node); return node_ids_.at(node->fingerprint()); } ExprDominatorTree( std::unique_ptr<AcyclicCFG> graph, DominatorTree tree, absl::flat_hash_map<Fingerprint, AcyclicCFG::NodeId> node_ids) : graph_(std::move(graph)), tree_(std::move(tree)), node_ids_(std::move(node_ids)) {} std::unique_ptr<AcyclicCFG> graph_; DominatorTree tree_; absl::flat_hash_map<Fingerprint, AcyclicCFG::NodeId> node_ids_; }; absl::Status VerifyArgQTypes(const QType* cond_qtype, const QType* true_qtype, const QType* false_qtype) { if (cond_qtype == nullptr || true_qtype == nullptr || false_qtype == nullptr) { return absl::InternalError( "all types must be known before core._short_circuit_where " "transformation"); } if (cond_qtype != GetQType<OptionalUnit>()) { return absl::InternalError( absl::StrFormat("core._short_circuit_where operator supports only " "OPTIONAL_UNIT conditions, got %s", cond_qtype->name())); } if (true_qtype != false_qtype) { return absl::InternalError( absl::StrFormat("true and false branches of core._short_circuit_where " "must have the same QType; got %s and %s", true_qtype->name(), false_qtype->name())); } return absl::OkStatus(); } absl::Status CheckTypesUnchangedOrStripped( absl::Span<const QTypePtr> expected, absl::Span<const ExprAttributes> given) { if (expected.size() != given.size()) { return absl::InternalError( "number of args for internal.packed_where operator changed during " "compilation"); } for (size_t i = 0; i < expected.size(); ++i) { if (given[i].qtype() != nullptr && given[i].qtype() != expected[i]) { return absl::InternalError( "input types for internal.packed_where operator changed during " "compilation"); } } return absl::OkStatus(); } } absl::StatusOr<ExprOperatorPtr> PackedWhereOp::Create( DynamicCompiledOperator true_op, DynamicCompiledOperator false_op) { if (true_op.output_qtype() != false_op.output_qtype()) { return absl::InternalError( "inconsistent output types for internal.packed_where operator " "branches"); } return std::make_shared<PackedWhereOp>( PrivateConstructorTag{}, std::move(true_op), std::move(false_op)); } PackedWhereOp::PackedWhereOp(PrivateConstructorTag, DynamicCompiledOperator true_op, DynamicCompiledOperator false_op) : ExprOperatorWithFixedSignature( "internal.packed_where", ExprOperatorSignature{{.name = "condition"}, {.name = "_leaves", .kind = ExprOperatorSignature::Parameter:: Kind::kVariadicPositional}}, "(Internal) Stateful short circuit where operator.", FingerprintHasher("arolla::expr::PackedWhereOp") .Combine(true_op.fingerprint(), false_op.fingerprint()) .Finish()), true_op_(std::move(true_op)), false_op_(std::move(false_op)) {} absl::StatusOr<ExprAttributes> PackedWhereOp::InferAttributes( absl::Span<const ExprAttributes> inputs) const { size_t expected_arg_count = 1 + true_op_.input_qtypes().size() + false_op_.input_qtypes().size(); if (expected_arg_count != inputs.size()) { return absl::InternalError( "number of args for internal.packed_where operator changed during " "compilation"); } auto true_inputs = inputs.subspan(1, true_op_.input_qtypes().size()); RETURN_IF_ERROR( CheckTypesUnchangedOrStripped(true_op_.input_qtypes(), true_inputs)); auto false_inputs = inputs.subspan(1 + true_op_.input_qtypes().size()); RETURN_IF_ERROR( CheckTypesUnchangedOrStripped(false_op_.input_qtypes(), false_inputs)); return ExprAttributes(true_op_.output_qtype()); } absl::StatusOr<ExprNodePtr> WhereOperatorTransformationImpl( const DynamicEvaluationEngineOptions& options, ExprNodePtr node, const ExprDominatorTree& dominator_tree) { ASSIGN_OR_RETURN(auto op, DecayRegisteredOperator(node->op())); if (!IsBackendOperator(op, "core._short_circuit_where")) { return node; } const auto& deps = node->node_deps(); if (deps.size() != 3) { return absl::InternalError(absl::StrFormat( "incorrect number of dependencies passed to an " "core._short_circuit_where operator node: expected 3 but got %d.", deps.size())); } const ExprNodePtr& condition_branch = deps[0]; const ExprNodePtr& true_branch = deps[1]; const ExprNodePtr& false_branch = deps[2]; RETURN_IF_ERROR(VerifyArgQTypes(condition_branch->qtype(), true_branch->qtype(), false_branch->qtype())); auto must_be_short_circuited = [&](ExprNodePtr branch_root) { return [branch_root = std::move(branch_root), &dominator_tree](const ExprNodePtr& n) -> absl::StatusOr<bool> { ASSIGN_OR_RETURN(auto annotationless_n, StripTopmostAnnotations(n)); if (annotationless_n->is_leaf()) { return false; } if (annotationless_n.get() != n.get()) { return absl::InternalError( absl::StrFormat("WhereOperatorGlobalTransformation does not " "support annotations except for leaves, got %s", GetDebugSnippet(n))); } if (n->is_literal()) { return false; } if (n.get() == branch_root.get()) { return dominator_tree.HasSingleParentInExprDag(n); } return dominator_tree.StrictlyDominates(annotationless_n, branch_root); }; }; ASSIGN_OR_RETURN(bool true_branch_must_be_short_circuited, must_be_short_circuited(true_branch)(true_branch)); ASSIGN_OR_RETURN(bool false_branch_must_be_short_circuited, must_be_short_circuited(false_branch)(false_branch)); if (!true_branch_must_be_short_circuited && !false_branch_must_be_short_circuited) { ASSIGN_OR_RETURN(ExprOperatorPtr core_where_op, LookupOperator("core.where")); ASSIGN_OR_RETURN(core_where_op, DecayRegisteredOperator(core_where_op)); if (dynamic_cast<const BackendExprOperatorTag*>(core_where_op.get()) == nullptr) { return absl::InternalError( "core.where operator must be a backend operator"); } return MakeOpNode(core_where_op, {condition_branch, true_branch, false_branch}); } DynamicEvaluationEngineOptions subexpression_options(options); subexpression_options.enabled_preparation_stages = Stage::kPopulateQTypes | Stage::kToLower; subexpression_options.allow_overriding_input_slots = false; ASSIGN_OR_RETURN( ExprNodePtr true_lambda_expr, ExtractLambda(true_branch, must_be_short_circuited(true_branch))); ASSIGN_OR_RETURN(auto precompiled_true, DynamicCompiledOperator::Build( subexpression_options, true_lambda_expr->op(), GetExprQTypes(true_lambda_expr->node_deps()))); ASSIGN_OR_RETURN( ExprNodePtr false_lambda_expr, ExtractLambda(false_branch, must_be_short_circuited(false_branch))); ASSIGN_OR_RETURN(auto precompiled_false, DynamicCompiledOperator::Build( subexpression_options, false_lambda_expr->op(), GetExprQTypes(false_lambda_expr->node_deps()))); ASSIGN_OR_RETURN(ExprOperatorPtr packed_op, PackedWhereOp::Create(std::move(precompiled_true), std::move(precompiled_false))); std::vector<ExprNodePtr> args = {condition_branch}; args.insert(args.end(), true_lambda_expr->node_deps().begin(), true_lambda_expr->node_deps().end()); args.insert(args.end(), false_lambda_expr->node_deps().begin(), false_lambda_expr->node_deps().end()); return MakeOpNode(std::move(packed_op), std::move(args)); } absl::StatusOr<ExprNodePtr> WhereOperatorGlobalTransformation( const DynamicEvaluationEngineOptions& options, ExprNodePtr node) { ASSIGN_OR_RETURN(auto dominator_tree, ExprDominatorTree::Build(node)); return PostOrderTraverse( node, [&](const ExprNodePtr& node, absl::Span<const ExprNodePtr* const> arg_visits) -> absl::StatusOr<ExprNodePtr> { ASSIGN_OR_RETURN( auto transformed_node, WithNewDependencies(node, DereferenceVisitPointers(arg_visits))); ASSIGN_OR_RETURN( transformed_node, WhereOperatorTransformationImpl( options, std::move(transformed_node), dominator_tree)); dominator_tree.AddNodeAlias(transformed_node, node); return transformed_node; }); } absl::StatusOr<TypedSlot> CompileWhereOperator( const DynamicEvaluationEngineOptions& options, const PackedWhereOp& where_op, absl::Span<const TypedSlot> input_slots, TypedSlot output_slot, eval_internal::ExecutableBuilder* executable_builder) { size_t expected_arg_count = 1 + where_op.true_op().input_qtypes().size() + where_op.false_op().input_qtypes().size(); if (expected_arg_count != input_slots.size()) { return absl::InternalError( "incorrect number of input slots passed to internal.packed_where " "operator"); } auto true_input_slots = input_slots.subspan(1, where_op.true_op().input_qtypes().size()); auto before_true_branch = executable_builder->SkipEvalOp(); RETURN_IF_ERROR(where_op.true_op().BindTo(*executable_builder, true_input_slots, output_slot)); auto false_input_slots = input_slots.subspan(1 + where_op.true_op().input_qtypes().size()); auto before_false_branch = executable_builder->SkipEvalOp(); RETURN_IF_ERROR(where_op.false_op().BindTo(*executable_builder, false_input_slots, output_slot)); if (input_slots[0].GetType() != GetQType<OptionalUnit>()) { return absl::InternalError( "unexpected condition slot type for internal.packed_where operator"); } ASSIGN_OR_RETURN(auto cond_slot, input_slots[0].SubSlot(0).ToSlot<bool>()); int64_t jump_to_false_branch = before_false_branch - before_true_branch; auto before_true_branch_op_name = absl::StrFormat("jump_if_not<%+d>", jump_to_false_branch); if (jump_to_false_branch == 0) { return absl::InternalError( "true branch of internal.packed_where compiled into no operators"); } RETURN_IF_ERROR(executable_builder->SetEvalOp( before_true_branch, JumpIfNotBoundOperator(cond_slot, jump_to_false_branch), eval_internal::FormatOperatorCall(before_true_branch_op_name, {input_slots[0]}, {}), before_true_branch_op_name)); int64_t jump_after_false_branch = executable_builder->current_eval_ops_size() - before_false_branch - 1; auto before_false_branch_op_name = absl::StrFormat("jump<%+d>", jump_after_false_branch); if (jump_after_false_branch == 0) { return absl::InternalError( "false branch of internal.packed_where compiled into no operators"); } RETURN_IF_ERROR(executable_builder->SetEvalOp( before_false_branch, JumpBoundOperator(jump_after_false_branch), eval_internal::FormatOperatorCall(before_false_branch_op_name, {}, {}), before_false_branch_op_name)); return output_slot; } }
#include "arolla/expr/eval/compile_where_operator.h" #include <algorithm> #include <cstdint> #include <memory> #include <string> #include <utility> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/container/flat_hash_map.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "arolla/array/qtype/types.h" #include "arolla/dense_array/qtype/types.h" #include "arolla/expr/eval/dynamic_compiled_operator.h" #include "arolla/expr/eval/eval.h" #include "arolla/expr/eval/invoke.h" #include "arolla/expr/eval/prepare_expression.h" #include "arolla/expr/eval/test_utils.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_attributes.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/optimization/optimizer.h" #include "arolla/expr/optimization/peephole_optimizations/short_circuit_where.h" #include "arolla/expr/optimization/peephole_optimizer.h" #include "arolla/expr/qtype_utils.h" #include "arolla/expr/registered_expr_operator.h" #include "arolla/expr/testing/testing.h" #include "arolla/expr/visitors/substitution.h" #include "arolla/memory/frame.h" #include "arolla/memory/optional_value.h" #include "arolla/qexpr/evaluation_engine.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/optional_qtype.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/testing/qtype.h" #include "arolla/qtype/typed_slot.h" #include "arolla/qtype/typed_value.h" #include "arolla/util/bytes.h" #include "arolla/util/init_arolla.h" #include "arolla/util/testing/status_matchers_backport.h" #include "arolla/util/unit.h" namespace arolla::expr::eval_internal { namespace { using ::arolla::testing::EqualsExpr; using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::StatusIs; using ::arolla::testing::TypedValueWith; using ::arolla::testing::WithNameAnnotation; using ::arolla::testing::WithQTypeAnnotation; using ::testing::AllOf; using ::testing::ElementsAre; using ::testing::Eq; using ::testing::HasSubstr; using ::testing::NotNull; absl::StatusOr<std::unique_ptr<BoundExpr>> CompileExprWithTypes( DynamicEvaluationEngineOptions options, ExprNodePtr expr, absl::flat_hash_map<std::string, QTypePtr> leaf_qtypes) { std::vector<std::string> leaves_in_order; for (const auto& [leaf, _] : leaf_qtypes) { leaves_in_order.push_back(leaf); } std::sort(leaves_in_order.begin(), leaves_in_order.end()); absl::flat_hash_map<std::string, TypedSlot> input_slots; FrameLayout::Builder layout_builder; for (const auto& leaf : leaves_in_order) { input_slots.emplace(leaf, AddSlot(leaf_qtypes.at(leaf), &layout_builder)); } return CompileAndBindForDynamicEvaluation(options, &layout_builder, expr, input_slots); } class WhereOperatorTest : public ::testing::TestWithParam<DynamicEvaluationEngineOptions> { protected: void SetUp() override { ASSERT_OK(InitArolla()); } DynamicEvaluationEngineOptions GetOptions() const { return GetParam(); } }; INSTANTIATE_TEST_SUITE_P( GarbageCollection, WhereOperatorTest, ::testing::Values( DynamicEvaluationEngineOptions{.collect_op_descriptions = true, .allow_overriding_input_slots = false}, DynamicEvaluationEngineOptions{.collect_op_descriptions = true, .allow_overriding_input_slots = true})); TEST_P(WhereOperatorTest, WhereOperatorGlobalTransformation_AnnotationHandling) { ASSERT_OK_AND_ASSIGN( auto cond, WithQTypeAnnotation(Leaf("cond"), GetOptionalQType<Unit>())); ASSERT_OK_AND_ASSIGN(auto x, WithQTypeAnnotation(Leaf("x"), GetQType<float>())); ASSERT_OK_AND_ASSIGN(auto y, WithQTypeAnnotation(Leaf("y"), GetQType<float>())); ASSERT_OK_AND_ASSIGN(auto x_plus_y, CallOp("math.add", {x, y})); ASSERT_OK_AND_ASSIGN(auto named_x_plus_y, WithNameAnnotation(x_plus_y, "name_for_x_plus_y")); ASSERT_OK_AND_ASSIGN( auto expr, CallOp( "core._short_circuit_where", { cond, WithQTypeAnnotation(CallOp("math.multiply", {named_x_plus_y, y}), GetQType<float>()), CallOp("math.multiply", {x_plus_y, CallOp("math.add", {y, Literal<float>(1.)})}), })); EXPECT_THAT(WhereOperatorGlobalTransformation(GetOptions(), expr), StatusIs(absl::StatusCode::kInternal, HasSubstr("WhereOperatorGlobalTransformation does not " "support annotations except for leaves"))); ASSERT_OK_AND_ASSIGN(auto prepared_expr, PrepareExpression(expr, {}, GetOptions())); const auto* packed_where = dynamic_cast<const PackedWhereOp*>(prepared_expr->op().get()); ASSERT_THAT(packed_where, NotNull()); ASSERT_THAT(prepared_expr->node_deps(), ElementsAre(EqualsExpr(cond), EqualsExpr(x_plus_y), EqualsExpr(y), EqualsExpr(x_plus_y), EqualsExpr(y), EqualsExpr(Literal<float>(1)))); } TEST_P(WhereOperatorTest, SimpleWhere) { ASSERT_OK_AND_ASSIGN( auto expr, CallOp("core._short_circuit_where", {Leaf("cond"), CallOp("math.add", {Leaf("x"), Leaf("y")}), CallOp("math.subtract", {Leaf("x"), Leaf("y")})})); EXPECT_THAT( CompileExprWithTypes(GetOptions(), expr, {{"cond", GetQType<OptionalUnit>()}, {"x", GetQType<int32_t>()}, {"y", GetQType<int32_t>()}}), IsOkAndHolds(AllOf( InitOperationsAre(), EvalOperationsAre( "jump_if_not<+2>(OPTIONAL_UNIT [0x00])", "INT32 [0x0C] = math.add(INT32 [0x04], INT32 [0x08])", "jump<+1>()", "INT32 [0x0C] = math.subtract(INT32 [0x04], INT32 [0x08])")))); EXPECT_THAT(Invoke(expr, {{"cond", TypedValue::FromValue(kPresent)}, {"x", TypedValue::FromValue(1)}, {"y", TypedValue::FromValue(2)}}, GetOptions()), IsOkAndHolds(TypedValueWith<int32_t>(Eq(3)))); EXPECT_THAT(Invoke(expr, {{"cond", TypedValue::FromValue(kMissing)}, {"x", TypedValue::FromValue(1)}, {"y", TypedValue::FromValue(2)}}, GetOptions()), IsOkAndHolds(TypedValueWith<int32_t>(Eq(-1)))); } TEST_P(WhereOperatorTest, PackedWhereOpComputeOutputQType) { ASSERT_OK_AND_ASSIGN(ExprOperatorPtr math_add, LookupOperator("math.add")); ASSERT_OK_AND_ASSIGN( auto add_float_double, DynamicCompiledOperator::Build(GetOptions(), math_add, {GetQType<float>(), GetQType<double>()})); ASSERT_OK_AND_ASSIGN( auto add_doubles, DynamicCompiledOperator::Build(GetOptions(), math_add, {GetQType<double>(), GetQType<double>()})); ASSERT_OK_AND_ASSIGN(ExprOperatorPtr packed_where, PackedWhereOp::Create(std::move(add_float_double), std::move(add_doubles))); EXPECT_THAT(packed_where->InferAttributes({}), StatusIs(absl::StatusCode::kInternal, "number of args for internal.packed_where operator " "changed during compilation")); auto b = ExprAttributes(GetQType<bool>()); auto f = ExprAttributes(GetQType<float>()); auto d = ExprAttributes(GetQType<double>()); EXPECT_THAT(packed_where->InferAttributes({b, f, f, d, d}), StatusIs(absl::StatusCode::kInternal, "input types for internal.packed_where operator changed " "during compilation")); { ASSERT_OK_AND_ASSIGN(auto attr, packed_where->InferAttributes({b, f, d, d, d})); EXPECT_THAT(attr.qtype(), Eq(GetQType<double>())); } { ASSERT_OK_AND_ASSIGN( auto attr, packed_where->InferAttributes( {ExprAttributes{}, ExprAttributes{}, ExprAttributes{}, ExprAttributes{}, ExprAttributes{}})); EXPECT_THAT(attr.qtype(), Eq(GetQType<double>())); } } TEST_P(WhereOperatorTest, WhereWithTypeCasting) { ASSERT_OK_AND_ASSIGN(auto expr, CallOp("core._short_circuit_where", {Leaf("cond"), Leaf("x"), Leaf("y")})); EXPECT_THAT( CompileExprWithTypes(GetOptions(), expr, {{"cond", GetQType<OptionalUnit>()}, {"x", GetQType<int32_t>()}, {"y", GetOptionalQType<int32_t>()}}), IsOkAndHolds(AllOf( InitOperationsAre(), EvalOperationsAre( "jump_if_not<+2>(OPTIONAL_UNIT [0x00])", "OPTIONAL_INT32 [0x10] = core.to_optional._scalar(INT32 [0x04])", "jump<+1>()", "OPTIONAL_INT32 [0x10] = core._copy(OPTIONAL_INT32 [0x08])")))); EXPECT_THAT(Invoke(expr, {{"cond", TypedValue::FromValue(kPresent)}, {"x", TypedValue::FromValue(1)}, {"y", TypedValue::FromValue(OptionalValue(0))}}, GetOptions()), IsOkAndHolds(TypedValueWith<OptionalValue<int32_t>>(Eq(1)))); } TEST_P(WhereOperatorTest, WhereWithEqualBranches) { ASSERT_OK_AND_ASSIGN(auto x_plus_y, CallOp("math.add", {Leaf("x"), Leaf("y")})); ASSERT_OK_AND_ASSIGN(auto expr, CallOp("core._short_circuit_where", {Leaf("cond"), x_plus_y, x_plus_y})); EXPECT_THAT(CompileExprWithTypes(GetOptions(), expr, {{"cond", GetQType<OptionalUnit>()}, {"x", GetQType<int32_t>()}, {"y", GetQType<int32_t>()}}), IsOkAndHolds(AllOf( InitOperationsAre(), EvalOperationsAre( "INT32 [0x10] = math.add(INT32 [0x04], INT32 [0x08])", "INT32 [0x0C] = core.where(OPTIONAL_UNIT [0x00], INT32 " "[0x10], INT32 [0x10])")))); EXPECT_THAT(Invoke(expr, {{"cond", TypedValue::FromValue(kPresent)}, {"x", TypedValue::FromValue(1)}, {"y", TypedValue::FromValue(2)}}, GetOptions()), IsOkAndHolds(TypedValueWith<int32_t>(Eq(3)))); } TEST_P(WhereOperatorTest, NothingToShortCircuit) { auto x_plus_y = CallOp("math.add", {Leaf("x"), Leaf("y")}); auto cond = Leaf("cond"); ASSERT_OK_AND_ASSIGN( auto expr, CallOp("math.add", {CallOp("core._short_circuit_where", {Leaf("cond"), x_plus_y, Leaf("y")}), x_plus_y})); DynamicEvaluationEngineOptions options = GetOptions(); options.allow_overriding_input_slots = true; EXPECT_THAT(CompileExprWithTypes(options, expr, {{"cond", GetQType<OptionalUnit>()}, {"x", GetQType<int32_t>()}, {"y", GetQType<int32_t>()}}), IsOkAndHolds(AllOf( InitOperationsAre(), EvalOperationsAre( "INT32 [0x10] = math.add(INT32 [0x04], INT32 [0x08])", "INT32 [0x04] = core.where(OPTIONAL_UNIT [0x00], INT32 " "[0x10], INT32 [0x08])", "INT32 [0x0C] = math.add(INT32 [0x04], INT32 [0x10])")))); EXPECT_THAT( CompileExprWithTypes(options, expr, {{"cond", GetQType<OptionalUnit>()}, {"x", GetDenseArrayQType<int32_t>()}, {"y", GetDenseArrayQType<int32_t>()}}), IsOkAndHolds(AllOf( InitOperationsAre(), EvalOperationsAre( "DENSE_ARRAY_INT32 [0xE0] = math.add(DENSE_ARRAY_INT32 [0x08], " "DENSE_ARRAY_INT32 [0x50])", "DENSE_ARRAY_INT32 [0x08] = core.where(OPTIONAL_UNIT [0x00], " "DENSE_ARRAY_INT32 [0xE0], DENSE_ARRAY_INT32 [0x50])", "DENSE_ARRAY_INT32 [0x98] = math.add(DENSE_ARRAY_INT32 [0x08], " "DENSE_ARRAY_INT32 [0xE0])")))); EXPECT_THAT( CompileExprWithTypes(options, expr, {{"cond", GetQType<OptionalUnit>()}, {"x", GetArrayQType<int32_t>()}, {"y", GetArrayQType<int32_t>()}}), IsOkAndHolds(AllOf( InitOperationsAre(), EvalOperationsAre("ARRAY_INT32 [0x1A0] = math.add(ARRAY_INT32 " "[0x08], ARRAY_INT32 [0x90])", "ARRAY_INT32 [0x08] = core.where(OPTIONAL_UNIT " "[0x00], ARRAY_INT32 [0x1A0], ARRAY_INT32 [0x90])", "ARRAY_INT32 [0x118] = math.add(ARRAY_INT32 " "[0x08], ARRAY_INT32 [0x1A0])")))); } TEST_P(WhereOperatorTest, WhereWithIndependentBranches) { ASSERT_OK_AND_ASSIGN( auto expr, CallOp("core._short_circuit_where", {Leaf("cond"), CallOp("math.add", {Literal(1), Literal(2)}), CallOp("math.add", {Literal(2), Literal(3)})})); auto options = GetOptions(); options.enabled_preparation_stages &= ~DynamicEvaluationEngineOptions::PreparationStage::kLiteralFolding; EXPECT_THAT( CompileExprWithTypes(options, expr, {{"cond", GetQType<OptionalUnit>()}}), IsOkAndHolds( AllOf(InitOperationsAre("INT32 [0x08] = 1\n" "INT32 [0x0C] = 2\n" "INT32 [0x10] = 3"), EvalOperationsAre( "jump_if_not<+2>(OPTIONAL_UNIT [0x00])", "INT32 [0x04] = math.add(INT32 [0x08], INT32 [0x0C])", "jump<+1>()", "INT32 [0x04] = math.add(INT32 [0x0C], INT32 [0x10])")))); EXPECT_THAT( Invoke(expr, {{"cond", TypedValue::FromValue(kPresent)}}, options), IsOkAndHolds(TypedValueWith<int32_t>(Eq(3)))); EXPECT_THAT( Invoke(expr, {{"cond", TypedValue::FromValue(kMissing)}}, options), IsOkAndHolds(TypedValueWith<int32_t>(Eq(5)))); } TEST_P(WhereOperatorTest, WhereWithIncompatibleTypes) { ASSERT_OK_AND_ASSIGN(auto expr, CallOp("core._short_circuit_where", {Leaf("cond"), Leaf("x"), Leaf("y")})); EXPECT_THAT(CompileExprWithTypes(GetOptions(), expr, {{"cond", GetQType<OptionalUnit>()}, {"x", GetQType<int32_t>()}, {"y", GetQType<Bytes>()}}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("no common QType for (INT32,BYTES)"))); } TEST_P(WhereOperatorTest, WhereWithExpressions) { auto cond = Leaf("cond"); auto x = Leaf("x"); auto y = Leaf("y"); ASSERT_OK_AND_ASSIGN(auto x_mul_y, CallOp("math.multiply", {x, y})); ASSERT_OK_AND_ASSIGN(auto x_plus_y, CallOp("math.add", {x, y})); ASSERT_OK_AND_ASSIGN(ExprNodePtr expr, CallOp("core._short_circuit_where", {cond, x_mul_y, x_plus_y})); EXPECT_THAT( CompileExprWithTypes(GetOptions(), expr, {{"cond", GetQType<OptionalUnit>()}, {"x", GetQType<int32_t>()}, {"y", GetQType<int32_t>()}}), IsOkAndHolds( AllOf(InitOperationsAre(), EvalOperationsAre( "jump_if_not<+2>(OPTIONAL_UNIT [0x00])", "INT32 [0x0C] = math.multiply(INT32 [0x04], INT32 [0x08])", "jump<+1>()", "INT32 [0x0C] = math.add(INT32 [0x04], INT32 [0x08])")))); EXPECT_THAT(Invoke(expr, {{"cond", TypedValue::FromValue(kPresent)}, {"x", TypedValue::FromValue(3)}, {"y", TypedValue::FromValue(19)}}, GetOptions()), IsOkAndHolds(TypedValueWith<int32_t>(Eq(57)))); EXPECT_THAT(Invoke(expr, {{"cond", TypedValue::FromValue(kMissing)}, {"x", TypedValue::FromValue(50)}, {"y", TypedValue::FromValue(7)}}, GetOptions()), IsOkAndHolds(TypedValueWith<int32_t>(Eq(57)))); } TEST_P(WhereOperatorTest, WhereWithInputSlotsOverwriting) { auto cond = Leaf("cond"); auto x = Leaf("x"); ASSERT_OK_AND_ASSIGN(auto mult, CallOp("math.multiply", {x, x})); ASSERT_OK_AND_ASSIGN(mult, CallOp("math.multiply", {mult, mult})); ASSERT_OK_AND_ASSIGN(mult, CallOp("math.multiply", {mult, mult})); ASSERT_OK_AND_ASSIGN(auto sum, CallOp("math.add", {mult, mult})); ASSERT_OK_AND_ASSIGN(sum, CallOp("math.add", {sum, sum})); ASSERT_OK_AND_ASSIGN(sum, CallOp("math.add", {sum, sum})); ASSERT_OK_AND_ASSIGN(auto sub, CallOp("math.subtract", {mult, mult})); ASSERT_OK_AND_ASSIGN(sub, CallOp("math.subtract", {sub, sub})); ASSERT_OK_AND_ASSIGN(sub, CallOp("math.subtract", {sub, sub})); ASSERT_OK_AND_ASSIGN(ExprNodePtr expr, CallOp("core._short_circuit_where", {cond, sum, sub})); if (GetOptions().allow_overriding_input_slots) { EXPECT_THAT( CompileExprWithTypes( GetOptions(), expr, {{"cond", GetQType<OptionalUnit>()}, {"x", GetQType<int32_t>()}}), IsOkAndHolds(AllOf( InitOperationsAre(), EvalOperationsAre( "INT32 [0x0C] = math.multiply(INT32 [0x04], INT32 [0x04])", "INT32 [0x04] = math.multiply(INT32 [0x0C], INT32 [0x0C])", "INT32 [0x0C] = math.multiply(INT32 [0x04], INT32 [0x04])", "jump_if_not<+4>(OPTIONAL_UNIT [0x00])", "INT32 [0x10] = math.add(INT32 [0x0C], INT32 [0x0C])", "INT32 [0x14] = math.add(INT32 [0x10], INT32 [0x10])", "INT32 [0x08] = math.add(INT32 [0x14], INT32 [0x14])", "jump<+3>()", "INT32 [0x18] = math.subtract(INT32 [0x0C], INT32 [0x0C])", "INT32 [0x1C] = math.subtract(INT32 [0x18], INT32 [0x18])", "INT32 [0x08] = math.subtract(INT32 [0x1C], INT32 [0x1C])")))); } else { EXPECT_THAT( CompileExprWithTypes( GetOptions(), expr, {{"cond", GetQType<OptionalUnit>()}, {"x", GetQType<int32_t>()}}), IsOkAndHolds(AllOf( InitOperationsAre(), EvalOperationsAre( "INT32 [0x0C] = math.multiply(INT32 [0x04], INT32 [0x04])", "INT32 [0x10] = math.multiply(INT32 [0x0C], INT32 [0x0C])", "INT32 [0x0C] = math.multiply(INT32 [0x10], INT32 [0x10])", "jump_if_not<+4>(OPTIONAL_UNIT [0x00])", "INT32 [0x14] = math.add(INT32 [0x0C], INT32 [0x0C])", "INT32 [0x18] = math.add(INT32 [0x14], INT32 [0x14])", "INT32 [0x08] = math.add(INT32 [0x18], INT32 [0x18])", "jump<+3>()", "INT32 [0x1C] = math.subtract(INT32 [0x0C], INT32 [0x0C])", "INT32 [0x20] = math.subtract(INT32 [0x1C], INT32 [0x1C])", "INT32 [0x08] = math.subtract(INT32 [0x20], INT32 [0x20])")))); } EXPECT_THAT(Invoke(expr, {{"cond", TypedValue::FromValue(kPresent)}, {"x", TypedValue::FromValue(2)}}, GetOptions()), IsOkAndHolds(TypedValueWith<int32_t>(Eq(2048)))); EXPECT_THAT(Invoke(expr, {{"cond", TypedValue::FromValue(kMissing)}, {"x", TypedValue::FromValue(2)}}, GetOptions()), IsOkAndHolds(TypedValueWith<int32_t>(Eq(0)))); } TEST_P(WhereOperatorTest, ShortCircuit) { ASSERT_OK_AND_ASSIGN(ExprNodePtr x_plus_1, CallOp("math.add", {Leaf("x"), Literal(1)})); ASSERT_OK_AND_ASSIGN(ExprNodePtr x_div_0, CallOp("math.floordiv", {Leaf("x"), Literal(0)})); ASSERT_OK_AND_ASSIGN( ExprNodePtr expr, CallOp("core._short_circuit_where", {Leaf("cond"), x_plus_1, x_div_0})); EXPECT_THAT(Invoke(expr, {{"cond", TypedValue::FromValue(kPresent)}, {"x", TypedValue::FromValue(56)}}, GetOptions()), IsOkAndHolds(TypedValueWith<int32_t>(Eq(57)))); EXPECT_THAT(Invoke(expr, {{"cond", TypedValue::FromValue(kMissing)}, {"x", TypedValue::FromValue(56)}}, GetOptions()), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("division by zero"))); } TEST_P(WhereOperatorTest, WhereWithLiteral) { ASSERT_OK_AND_ASSIGN( ExprNodePtr expr, CallOp("core._short_circuit_where", {Leaf("cond"), CallOp("math.add", {Leaf("x"), Literal(27)}), CallOp("math.subtract", {Leaf("x"), Literal(27)})})); EXPECT_THAT( CompileExprWithTypes(GetOptions(), expr, {{"cond", GetQType<OptionalUnit>()}, {"x", GetQType<int32_t>()}, {"y", GetQType<int32_t>()}}), IsOkAndHolds(AllOf( InitOperationsAre("INT32 [0x10] = 27"), EvalOperationsAre( "jump_if_not<+2>(OPTIONAL_UNIT [0x00])", "INT32 [0x0C] = math.add(INT32 [0x04], INT32 [0x10])", "jump<+1>()", "INT32 [0x0C] = math.subtract(INT32 [0x04], INT32 [0x10])")))); EXPECT_THAT(Invoke(expr, {{"cond", TypedValue::FromValue(kPresent)}, {"x", TypedValue::FromValue(30)}}, GetOptions()), IsOkAndHolds(TypedValueWith<int32_t>(Eq(57)))); EXPECT_THAT(Invoke(expr, {{"cond", TypedValue::FromValue(kMissing)}, {"x", TypedValue::FromValue(30)}}, GetOptions()), IsOkAndHolds(TypedValueWith<int32_t>(Eq(3)))); } TEST_P(WhereOperatorTest, WhereWithCommonBranches) { ASSERT_OK_AND_ASSIGN(ExprNodePtr x_plus_y, CallOp("math.add", {Leaf("x"), Leaf("y")})); ASSERT_OK_AND_ASSIGN(ExprNodePtr x_plus_y_plus_1, CallOp("math.add", {x_plus_y, Literal(1)})); ASSERT_OK_AND_ASSIGN(ExprNodePtr expr, CallOp("core._short_circuit_where", {Leaf("cond"), x_plus_y, x_plus_y_plus_1})); EXPECT_THAT(CompileExprWithTypes(GetOptions(), expr, {{"cond", GetQType<OptionalUnit>()}, {"x", GetQType<int32_t>()}, {"y", GetQType<int32_t>()}}), IsOkAndHolds(AllOf( InitOperationsAre("INT32 [0x14] = 1"), EvalOperationsAre( "INT32 [0x10] = math.add(INT32 [0x04], INT32 [0x08])", "jump_if_not<+2>(OPTIONAL_UNIT [0x00])", "INT32 [0x0C] = core._copy(INT32 [0x10])", "jump<+1>()", "INT32 [0x0C] = math.add(INT32 [0x10], INT32 [0x14])")))); EXPECT_THAT(Invoke(expr, {{"cond", TypedValue::FromValue(kPresent)}, {"x", TypedValue::FromValue(50)}, {"y", TypedValue::FromValue(7)}}, GetOptions()), IsOkAndHolds(TypedValueWith<int32_t>(Eq(57)))); EXPECT_THAT(Invoke(expr, {{"cond", TypedValue::FromValue(kMissing)}, {"x", TypedValue::FromValue(50)}, {"y", TypedValue::FromValue(7)}}, GetOptions()), IsOkAndHolds(TypedValueWith<int32_t>(Eq(58)))); } TEST_P(WhereOperatorTest, NestedWhere) { auto cond1 = Leaf("cond1"); auto cond2 = Leaf("cond2"); auto x = Leaf("x"); auto y = Leaf("y"); ASSERT_OK_AND_ASSIGN(auto true_case_where, CallOp("core._short_circuit_where", {cond2, CallOp("math.add", {x, y}), y})); ASSERT_OK_AND_ASSIGN(auto false_case_where, CallOp("core._short_circuit_where", {cond2, CallOp("math.subtract", {x, y}), x})); ASSERT_OK_AND_ASSIGN(ExprNodePtr expr, CallOp("core._short_circuit_where", {cond1, true_case_where, false_case_where})); EXPECT_THAT( CompileExprWithTypes(GetOptions(), expr, {{"cond1", GetQType<OptionalUnit>()}, {"cond2", GetQType<OptionalUnit>()}, {"x", GetQType<int32_t>()}, {"y", GetQType<int32_t>()}}), IsOkAndHolds( AllOf(InitOperationsAre(), EvalOperationsAre( "jump_if_not<+5>(OPTIONAL_UNIT [0x00])", "jump_if_not<+2>(OPTIONAL_UNIT [0x01])", "INT32 [0x0C] = math.add(INT32 [0x04], INT32 [0x08])", "jump<+1>()", "INT32 [0x0C] = core._copy(INT32 [0x08])", "jump<+4>()", "jump_if_not<+2>(OPTIONAL_UNIT [0x01])", "INT32 [0x0C] = math.subtract(INT32 [0x04], INT32 [0x08])", "jump<+1>()", "INT32 [0x0C] = core._copy(INT32 [0x04])")))); EXPECT_THAT(Invoke(expr, {{"cond1", TypedValue::FromValue(kPresent)}, {"cond2", TypedValue::FromValue(kPresent)}, {"x", TypedValue::FromValue(50)}, {"y", TypedValue::FromValue(7)}}, GetOptions()), IsOkAndHolds(TypedValueWith<int32_t>(Eq(57)))); EXPECT_THAT(Invoke(expr, {{"cond1", TypedValue::FromValue(kPresent)}, {"cond2", TypedValue::FromValue(kMissing)}, {"x", TypedValue::FromValue(50)}, {"y", TypedValue::FromValue(7)}}, GetOptions()), IsOkAndHolds(TypedValueWith<int32_t>(Eq(7)))); EXPECT_THAT(Invoke(expr, {{"cond1", TypedValue::FromValue(kMissing)}, {"cond2", TypedValue::FromValue(kPresent)}, {"x", TypedValue::FromValue(50)}, {"y", TypedValue::FromValue(7)}}, GetOptions()), IsOkAndHolds(TypedValueWith<int32_t>(Eq(43)))); EXPECT_THAT(Invoke(expr, {{"cond1", TypedValue::FromValue(kMissing)}, {"cond2", TypedValue::FromValue(kMissing)}, {"x", TypedValue::FromValue(50)}, {"y", TypedValue::FromValue(7)}}, GetOptions()), IsOkAndHolds(TypedValueWith<int32_t>(Eq(50)))); } TEST_P(WhereOperatorTest, Optimizations) { auto cond = Placeholder("cond"); auto x = Leaf("x"); auto y = Leaf("y"); ASSERT_OK_AND_ASSIGN(auto x_plus_y, CallOp("math.add", {x, y})); ASSERT_OK_AND_ASSIGN(auto x_mul_y, CallOp("math.multiply", {x, y})); ASSERT_OK_AND_ASSIGN(ExprNodePtr where, CallOp("core.where", {cond, x_plus_y, x_mul_y})); ASSERT_OK_AND_ASSIGN(auto true_condition, CallOp("core.equal", {Literal(5), Literal(5)})); ASSERT_OK_AND_ASSIGN(auto false_condition, CallOp("core.equal", {Literal(5), Literal(7)})); ASSERT_OK_AND_ASSIGN( auto true_nested_condition, CallOp("core.where", {false_condition, false_condition, true_condition})); absl::flat_hash_map<std::string, QTypePtr> input_types = { {"x", GetQType<int64_t>()}, {"y", GetQType<int64_t>()}}; ASSERT_OK_AND_ASSIGN(auto lower_x_plus_y, PopulateQTypes(x_plus_y, input_types)); ASSERT_OK_AND_ASSIGN(lower_x_plus_y, ToLowest(lower_x_plus_y)); ASSERT_OK_AND_ASSIGN(auto lower_x_mul_y, PopulateQTypes(x_mul_y, input_types)); ASSERT_OK_AND_ASSIGN(lower_x_mul_y, ToLowest(lower_x_mul_y)); auto options = GetOptions(); ASSERT_OK_AND_ASSIGN( auto peephole_optimizer, CreatePeepholeOptimizer({ShortCircuitWhereOptimizations})); options.optimizer = MakeOptimizer(std::move(peephole_optimizer)); { ASSERT_OK_AND_ASSIGN( auto expr, SubstitutePlaceholders(where, {{"cond", true_condition}})); EXPECT_THAT(PrepareExpression(expr, input_types, options), IsOkAndHolds(EqualsExpr(lower_x_plus_y))); } { ASSERT_OK_AND_ASSIGN( auto expr, SubstitutePlaceholders(where, {{"cond", false_condition}})); EXPECT_THAT(PrepareExpression(expr, input_types, options), IsOkAndHolds(EqualsExpr(lower_x_mul_y))); } { ASSERT_OK_AND_ASSIGN( auto expr, SubstitutePlaceholders(where, {{"cond", true_nested_condition}})); EXPECT_THAT(PrepareExpression(expr, input_types, options), IsOkAndHolds(EqualsExpr(lower_x_plus_y))); } } } }
2,475
#ifndef AROLLA_EXPR_EVAL_SIDE_OUTPUT_H_ #define AROLLA_EXPR_EVAL_SIDE_OUTPUT_H_ #include <string> #include "absl/container/flat_hash_map.h" #include "absl/status/statusor.h" #include "arolla/expr/expr_node.h" #include "arolla/io/slot_listener.h" namespace arolla::expr { struct ExprWithSideOutputs { ExprNodePtr expr; absl::flat_hash_map<std::string, ExprNodePtr> side_outputs; }; absl::StatusOr<ExprWithSideOutputs> ExtractSideOutputs(ExprNodePtr expr); absl::StatusOr<absl::flat_hash_map<std::string, ExprNodePtr>> PrepareSideOutputsForListener( const absl::flat_hash_map<std::string, ExprNodePtr>& side_outputs, const SlotListenerBase& slot_listener); } #endif #include "arolla/expr/eval/side_output.h" #include <string> #include <utility> #include "absl/container/flat_hash_map.h" #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "arolla/expr/annotation_utils.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_debug_string.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_visitor.h" #include "arolla/expr/operators/bootstrap_operators.h" #include "arolla/io/slot_listener.h" #include "arolla/util/status_macros_backport.h" namespace arolla::expr { absl::StatusOr<ExprWithSideOutputs> ExtractSideOutputs(ExprNodePtr expr) { ExprWithSideOutputs result; ASSIGN_OR_RETURN( result.expr, Transform(expr, [&](ExprNodePtr node) -> absl::StatusOr<ExprNodePtr> { if (!IsExportAnnotation(node)) { return node; } DCHECK_GE(node->node_deps().size(), 2); auto unwrapped_node = node->node_deps()[0]; auto tag = ReadExportAnnotationTag(node); auto value_expr = ReadExportAnnotationValue(node); DCHECK_NE(unwrapped_node, nullptr); DCHECK_NE(value_expr, nullptr); if (auto [it, inserted] = result.side_outputs.emplace(tag, value_expr); !inserted) { return absl::FailedPreconditionError(absl::StrCat( "duplicated export name ", tag, ": ", GetDebugSnippet(value_expr), " vs ", GetDebugSnippet(it->second))); } return unwrapped_node; })); return result; } absl::StatusOr<absl::flat_hash_map<std::string, ExprNodePtr>> PrepareSideOutputsForListener( const absl::flat_hash_map<std::string, ExprNodePtr>& side_outputs, const SlotListenerBase& slot_listener) { absl::flat_hash_map<std::string, ExprNodePtr> result; for (auto [name, expr] : side_outputs) { if (auto qtype = slot_listener.GetQTypeOf(name); qtype != nullptr) { ASSIGN_OR_RETURN(expr, expr_operators::CoreCast(expr, Literal(qtype))); } result.emplace(name, std::move(expr)); } return result; } }
#include "arolla/expr/eval/side_output.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "arolla/expr/expr.h" #include "arolla/expr/testing/testing.h" #include "arolla/util/init_arolla.h" #include "arolla/util/testing/status_matchers_backport.h" namespace arolla::expr { namespace { using ::arolla::testing::EqualsExpr; using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::WithExportAnnotation; using ::arolla::testing::WithExportValueAnnotation; using ::testing::Field; using ::testing::MatchesRegex; using ::testing::Pair; using ::testing::UnorderedElementsAre; class SideOutputTest : public ::testing::Test { protected: void SetUp() override { ASSERT_OK(InitArolla()); } }; TEST_F(SideOutputTest, ExtractSideOutputs) { ASSERT_OK_AND_ASSIGN( auto expr, CallOp("math.add", {WithExportAnnotation( CallOp("math.add", {WithExportValueAnnotation( Leaf("x"), "out_z", Leaf("z")), Leaf("y")}), "out_xpy"), Leaf("y")})); ASSERT_OK_AND_ASSIGN( auto expected_expr, CallOp("math.add", {CallOp("math.add", {Leaf("x"), Leaf("y")}), Leaf("y")})); auto expected_out_z = Leaf("z"); ASSERT_OK_AND_ASSIGN(auto expected_out_xpy, CallOp("math.add", {Leaf("x"), Leaf("y")})); EXPECT_THAT(ExtractSideOutputs(expr), IsOkAndHolds(AllOf( Field(&ExprWithSideOutputs::expr, EqualsExpr(expected_expr)), Field(&ExprWithSideOutputs::side_outputs, UnorderedElementsAre( Pair("out_z", EqualsExpr(expected_out_z)), Pair("out_xpy", EqualsExpr(expected_out_xpy))))))); } TEST_F(SideOutputTest, ExtractSideOutputsExportValueDuplicateNamesError) { ASSERT_OK_AND_ASSIGN( auto expr, CallOp("math.add", {WithExportValueAnnotation(Leaf("x"), "out_z", Leaf("z")), WithExportValueAnnotation(Leaf("y"), "out_z", Leaf("x"))})); EXPECT_THAT( ExtractSideOutputs(expr), testing::StatusIs(absl::StatusCode::kFailedPrecondition, MatchesRegex("duplicated export name.*out_z.*"))); } TEST_F(SideOutputTest, ExtractSideOutputsExportDuplicateNamesError) { ASSERT_OK_AND_ASSIGN( auto expr, CallOp("math.add", {WithExportAnnotation(Leaf("x"), "out_z"), WithExportAnnotation(Leaf("y"), "out_z")})); EXPECT_THAT( ExtractSideOutputs(expr), testing::StatusIs(absl::StatusCode::kFailedPrecondition, MatchesRegex("duplicated export name.*out_z.*"))); } TEST_F(SideOutputTest, ExtractSideOutputsExportVsExportValueDuplicateNamesError) { ASSERT_OK_AND_ASSIGN( auto expr, CallOp("math.add", {WithExportValueAnnotation(Leaf("x"), "out_z", Leaf("z")), WithExportAnnotation(Leaf("y"), "out_z")})); EXPECT_THAT( ExtractSideOutputs(expr), testing::StatusIs(absl::StatusCode::kFailedPrecondition, MatchesRegex("duplicated export name.*out_z.*"))); } TEST_F(SideOutputTest, ExtractSideOutputsExportVsExportValueDuplicateNamesSameExprError) { ASSERT_OK_AND_ASSIGN( auto expr, CallOp("math.add", {WithExportValueAnnotation(Leaf("x"), "out_z", Leaf("z")), WithExportAnnotation(Leaf("z"), "out_z")})); ASSERT_OK_AND_ASSIGN(auto expected_expr, CallOp("math.add", {Leaf("x"), Leaf("z")})); EXPECT_THAT( ExtractSideOutputs(expr), testing::StatusIs(absl::StatusCode::kFailedPrecondition, MatchesRegex("duplicated export name.*out_z.*"))); } } }
2,476
#ifndef AROLLA_EXPR_EVAL_EXECUTABLE_BUILDER_H_ #define AROLLA_EXPR_EVAL_EXECUTABLE_BUILDER_H_ #include <cstdint> #include <memory> #include <optional> #include <string> #include <utility> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_stack_trace.h" #include "arolla/memory/frame.h" #include "arolla/qexpr/evaluation_engine.h" #include "arolla/qexpr/operators.h" #include "arolla/qtype/typed_slot.h" #include "arolla/qtype/typed_value.h" namespace arolla::expr::eval_internal { std::string FormatSlot(TypedSlot slot); std::string FormatOperatorCall(absl::string_view op_name, absl::Span<const TypedSlot> input_slots, absl::Span<const TypedSlot> output_slots); class ExecutableBuilder { public: explicit ExecutableBuilder( FrameLayout::Builder* layout_builder, bool collect_op_descriptions = false, std::shared_ptr<const ExprStackTrace> stack_trace = nullptr); FrameLayout::Builder* layout_builder() const { return layout_builder_; } absl::Status AddLiteralInitialization(const TypedValue& literal_value, TypedSlot output_slot); absl::StatusOr<int64_t> BindEvalOp(const QExprOperator& op, absl::Span<const TypedSlot> input_slots, TypedSlot output_slot); int64_t AddInitOp(std::unique_ptr<BoundOperator> op, std::string description); int64_t AddEvalOp(std::unique_ptr<BoundOperator> op, std::string description, std::string display_name); int64_t SkipEvalOp(); absl::Status SetEvalOp(int64_t offset, std::unique_ptr<BoundOperator> op, std::string description, std::string display_name); int64_t current_eval_ops_size() { return eval_ops_.size(); } absl::Status AddNamedOutput(absl::string_view name, TypedSlot slot); std::unique_ptr<BoundExpr> Build( const absl::flat_hash_map<std::string, TypedSlot>& input_slots, TypedSlot output_slot) &&; void RegisterStacktrace(int64_t ip, const ExprNodePtr& node); private: FrameLayout::Builder* layout_builder_; std::vector<std::unique_ptr<BoundOperator>> init_ops_; std::vector<std::unique_ptr<BoundOperator>> eval_ops_; absl::flat_hash_map<std::string, TypedSlot> named_outputs_; bool collect_op_descriptions_; std::vector<std::string> init_op_descriptions_; std::vector<std::string> eval_op_descriptions_; std::vector<std::string> op_display_names_; std::vector<std::pair<TypedValue, TypedSlot>> literal_values_and_slots_; std::string init_literals_description_; std::optional<BoundExprStackTraceBuilder> stack_trace_builder_; }; } #endif #include "arolla/expr/eval/executable_builder.h" #include <cstddef> #include <cstdint> #include <memory> #include <optional> #include <string> #include <utility> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" #include "absl/strings/str_join.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "arolla/dense_array/dense_array.h" #include "arolla/expr/eval/dynamic_compiled_expr.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_stack_trace.h" #include "arolla/memory/frame.h" #include "arolla/qexpr/bound_operators.h" #include "arolla/qexpr/eval_context.h" #include "arolla/qexpr/evaluation_engine.h" #include "arolla/qexpr/operators.h" #include "arolla/qtype/typed_slot.h" #include "arolla/qtype/typed_value.h" #include "arolla/util/text.h" #include "arolla/util/status_macros_backport.h" namespace arolla::expr::eval_internal { namespace { std::string FormatSlots(absl::Span<const TypedSlot> slots) { return absl::StrJoin(slots, ", ", [](std::string* out, TypedSlot s) { absl::StrAppend(out, FormatSlot(s)); }); } class DynamicBoundExprImpl : public DynamicBoundExpr { public: DynamicBoundExprImpl( absl::flat_hash_map<std::string, TypedSlot> input_slots, TypedSlot output_slot, std::vector<std::unique_ptr<BoundOperator>> init_ops, std::vector<std::unique_ptr<BoundOperator>> eval_ops, absl::flat_hash_map<std::string, TypedSlot> named_output_slots, std::vector<std::string> init_op_descriptions, std::vector<std::string> eval_op_descriptions, DenseArray<Text> op_display_names, DenseArray<Text> op_stack_traces) : DynamicBoundExpr(std::move(input_slots), output_slot, std::move(named_output_slots)), init_ops_(std::move(init_ops)), eval_ops_(std::move(eval_ops)), init_op_descriptions_(std::move(init_op_descriptions)), eval_op_descriptions_(std::move(eval_op_descriptions)), op_display_names_(std::move(op_display_names)), op_stack_traces_(std::move(op_stack_traces)) {} void InitializeLiterals(EvaluationContext* ctx, FramePtr frame) const final { RunBoundOperators(init_ops_, ctx, frame); } void Execute(EvaluationContext* ctx, FramePtr frame) const final { int64_t last_ip = RunBoundOperators(eval_ops_, ctx, frame); if (!ctx->status().ok()) { RETURN_IF_ERROR(std::move(*ctx).status()).With([&](auto status_builder) { DCHECK_LT(last_ip, op_display_names_.size()); status_builder << "during evaluation of operator " << op_display_names_[last_ip].AsOptional().value_or(""); if (!op_stack_traces_.empty()) { status_builder << "\n" << op_stack_traces_[last_ip].AsOptional().value_or(""); } ctx->set_status(absl::Status(status_builder)); }); } } absl::Span<const std::string> init_op_descriptions() const final { return init_op_descriptions_; } absl::Span<const std::string> eval_op_descriptions() const final { return eval_op_descriptions_; } private: std::vector<std::unique_ptr<BoundOperator>> init_ops_; std::vector<std::unique_ptr<BoundOperator>> eval_ops_; std::vector<std::string> init_op_descriptions_; std::vector<std::string> eval_op_descriptions_; DenseArray<Text> op_display_names_; DenseArray<Text> op_stack_traces_; }; absl::Status VerifyNoNulls( absl::Span<const std::unique_ptr<BoundOperator>> ops) { for (size_t i = 0; i < ops.size(); ++i) { if (ops[i] == nullptr) { return absl::InternalError( absl::StrFormat("missing operator at position %d", i)); } } return absl::OkStatus(); } } std::string FormatSlot(TypedSlot slot) { return absl::StrFormat("%s [0x%02X]", slot.GetType()->name(), slot.byte_offset()); } std::string FormatOperatorCall(absl::string_view op_name, absl::Span<const TypedSlot> input_slots, absl::Span<const TypedSlot> output_slots) { if (output_slots.empty()) { return absl::StrFormat("%s(%s)", op_name, FormatSlots(input_slots)); } else { return absl::StrFormat("%s = %s(%s)", FormatSlots(output_slots), op_name, FormatSlots(input_slots)); } } ExecutableBuilder::ExecutableBuilder( FrameLayout::Builder* layout_builder, bool collect_op_descriptions, std::shared_ptr<const ExprStackTrace> stack_trace) : layout_builder_(layout_builder), collect_op_descriptions_(collect_op_descriptions) { if (stack_trace != nullptr) { stack_trace_builder_ = BoundExprStackTraceBuilder(stack_trace); } } absl::Status ExecutableBuilder::AddLiteralInitialization( const TypedValue& literal_value, TypedSlot output_slot) { if (literal_value.GetType() != output_slot.GetType()) { return absl::InternalError(absl::StrFormat( "incompatible types for literal and its slot: %s vs %s", literal_value.GetType()->name(), output_slot.GetType()->name())); } if (collect_op_descriptions_) { absl::StrAppendFormat(&init_literals_description_, "%s = %s\n", FormatSlots({output_slot}), literal_value.Repr()); } literal_values_and_slots_.push_back({literal_value, output_slot}); return absl::OkStatus(); } absl::StatusOr<int64_t> ExecutableBuilder::BindEvalOp( const QExprOperator& op, absl::Span<const TypedSlot> input_slots, TypedSlot output_slot) { ASSIGN_OR_RETURN(auto bound_op, op.Bind(input_slots, output_slot)); std::string description; if (collect_op_descriptions_) { description = FormatOperatorCall(op.name(), input_slots, {output_slot}); } return AddEvalOp(std::move(bound_op), std::move(description), std::string(op.name())); } int64_t ExecutableBuilder::AddInitOp(std::unique_ptr<BoundOperator> op, std::string description) { if (collect_op_descriptions_) { init_op_descriptions_.push_back(std::move(description)); } init_ops_.push_back(std::move(op)); return init_ops_.size() - 1; } int64_t ExecutableBuilder::AddEvalOp(std::unique_ptr<BoundOperator> op, std::string description, std::string display_name) { if (collect_op_descriptions_) { eval_op_descriptions_.push_back(std::move(description)); } eval_ops_.push_back(std::move(op)); op_display_names_.push_back(std::move(display_name)); return eval_ops_.size() - 1; } int64_t ExecutableBuilder::SkipEvalOp() { return AddEvalOp(nullptr, "", ""); } absl::Status ExecutableBuilder::SetEvalOp(int64_t offset, std::unique_ptr<BoundOperator> op, std::string description, std::string display_name) { if (offset < 0 || offset >= eval_ops_.size()) { return absl::InternalError(absl::StrFormat( "illegal operator offset: must be in range [0, %d), got %d", eval_ops_.size(), offset)); } if (eval_ops_[offset] != nullptr) { return absl::InternalError(absl::StrFormat( "attempt to override existing operator at position %d", offset)); } if (collect_op_descriptions_) { DCHECK_EQ(eval_ops_.size(), eval_op_descriptions_.size()); eval_op_descriptions_[offset] = std::move(description); } eval_ops_[offset] = std::move(op); op_display_names_[offset] = std::move(display_name); return absl::OkStatus(); } absl::Status ExecutableBuilder::AddNamedOutput(absl::string_view name, TypedSlot slot) { if (!named_outputs_.emplace(name, slot).second) { return absl::FailedPreconditionError( absl::StrCat("duplicated output slot name: ", name)); } return absl::OkStatus(); } void ExecutableBuilder::RegisterStacktrace(int64_t ip, const ExprNodePtr& node) { if (stack_trace_builder_.has_value()) { stack_trace_builder_->RegisterIp(ip, node); } } std::unique_ptr<BoundExpr> ExecutableBuilder::Build( const absl::flat_hash_map<std::string, TypedSlot>& input_slots, TypedSlot output_slot) && { if (!literal_values_and_slots_.empty()) { if (!init_literals_description_.empty()) { init_literals_description_.pop_back(); } AddInitOp(MakeBoundOperator( [values_and_slots = std::move(literal_values_and_slots_)]( EvaluationContext* ctx, FramePtr frame) { for (const auto& [value, slot] : values_and_slots) { auto ref = value.AsRef(); ref.GetType()->UnsafeCopy( ref.GetRawPointer(), frame.GetRawPointer(slot.byte_offset())); } }), std::move(init_literals_description_)); } DCHECK_OK(VerifyNoNulls(init_ops_)); DCHECK_OK(VerifyNoNulls(eval_ops_)); DenseArray<Text> stack_trace; if (stack_trace_builder_.has_value()) { stack_trace = stack_trace_builder_->Build(eval_ops_.size()); } return std::make_unique<DynamicBoundExprImpl>( input_slots, output_slot, std::move(init_ops_), std::move(eval_ops_), std::move(named_outputs_), std::move(init_op_descriptions_), std::move(eval_op_descriptions_), CreateFullDenseArray<Text>(op_display_names_.begin(), op_display_names_.end()), std::move(stack_trace)); } }
#include "arolla/expr/eval/executable_builder.h" #include <cstdint> #include <memory> #include <utility> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "arolla/expr/eval/test_utils.h" #include "arolla/memory/frame.h" #include "arolla/memory/memory_allocation.h" #include "arolla/memory/optional_value.h" #include "arolla/qexpr/bound_operators.h" #include "arolla/qexpr/eval_context.h" #include "arolla/qexpr/operators.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/typed_slot.h" #include "arolla/qtype/typed_value.h" #include "arolla/util/init_arolla.h" #include "arolla/util/testing/status_matchers_backport.h" namespace arolla::expr::eval_internal { namespace { using ::arolla::testing::IsOk; using ::arolla::testing::StatusIs; using ::testing::Eq; using ::testing::HasSubstr; class ExecutableBuilderTest : public ::testing::Test { protected: void SetUp() override { ASSERT_OK(InitArolla()); } }; std::unique_ptr<BoundOperator> Noop() { return MakeBoundOperator([](EvaluationContext* ctx, FramePtr frame) {}); } TEST_F(ExecutableBuilderTest, SetEvalOp) { FrameLayout::Builder layout_builder; auto output_slot = layout_builder.AddSlot<float>(); ExecutableBuilder builder(&layout_builder, true); EXPECT_THAT(builder.SetEvalOp(0, Noop(), "noop", "noop"), StatusIs(absl::StatusCode::kInternal, HasSubstr("illegal operator offset"))); builder.SkipEvalOp(); ASSERT_THAT(builder.SetEvalOp(0, Noop(), "noop", "noop"), IsOk()); EXPECT_THAT( builder.SetEvalOp(0, Noop(), "noop", "noop"), StatusIs( absl::StatusCode::kInternal, HasSubstr("attempt to override existing operator at position 0"))); EXPECT_THAT(std::move(builder).Build({}, TypedSlot::FromSlot(output_slot)), AllOf(InitOperationsAre(), EvalOperationsAre("noop"))); } TEST_F(ExecutableBuilderTest, BindInitializeLiteralOp) { FrameLayout::Builder layout_builder; auto float_slot = layout_builder.AddSlot<float>(); auto optional_int_slot = layout_builder.AddSlot<OptionalValue<int32_t>>(); ExecutableBuilder builder(&layout_builder, true); EXPECT_THAT( builder.AddLiteralInitialization(TypedValue::FromValue(float{57.}), TypedSlot::FromSlot(float_slot)), IsOk()); EXPECT_THAT( builder.AddLiteralInitialization(TypedValue::FromValue(int32_t{57}), TypedSlot::FromSlot(optional_int_slot)), StatusIs(absl::StatusCode::kInternal, "incompatible types for literal and its slot: INT32 vs " "OPTIONAL_INT32")); EXPECT_THAT(builder.AddLiteralInitialization( TypedValue::FromValue(OptionalValue<int32_t>(57)), TypedSlot::FromSlot(optional_int_slot)), IsOk()); auto bound_expr = std::move(builder).Build({}, TypedSlot::FromSlot(float_slot)); EXPECT_THAT( bound_expr, AllOf(InitOperationsAre("FLOAT32 [0x00] = 57.\n" "OPTIONAL_INT32 [0x04] = optional_int32{57}"), EvalOperationsAre())); auto layout = std::move(layout_builder).Build(); MemoryAllocation alloc(&layout); EvaluationContext ctx; bound_expr->InitializeLiterals(&ctx, alloc.frame()); EXPECT_THAT(alloc.frame().Get(float_slot), Eq(57.)); EXPECT_THAT(alloc.frame().Get(optional_int_slot), Eq(57)); } TEST_F(ExecutableBuilderTest, ExecuteOk) { FrameLayout::Builder layout_builder; FrameLayout::Slot<int32_t> x_slot = layout_builder.AddSlot<int32_t>(); auto make_increment_operator = [x_slot](int32_t increment) { return MakeBoundOperator( [x_slot, increment](EvaluationContext* ctx, FramePtr frame) { frame.Set(x_slot, frame.Get(x_slot) + increment); }); }; ExecutableBuilder builder(&layout_builder, true); builder.AddEvalOp(make_increment_operator(1), "inc(1)", "inc(1)"); builder.AddEvalOp(make_increment_operator(10), "inc(10)", "inc(10)"); builder.AddEvalOp(make_increment_operator(100), "inc(100)", "inc(100)"); builder.AddEvalOp(make_increment_operator(1000), "inc(1000)", "inc(1000)"); auto dynamic_bound_expr = std::move(builder).Build({}, TypedSlot::FromSlot(x_slot)); FrameLayout layout = std::move(layout_builder).Build(); MemoryAllocation alloc(&layout); EvaluationContext ctx; dynamic_bound_expr->Execute(&ctx, alloc.frame()); EXPECT_OK(ctx.status()); EXPECT_THAT(alloc.frame().Get(x_slot), Eq(1111)); } TEST_F(ExecutableBuilderTest, ExecuteWithError) { FrameLayout::Builder layout_builder; FrameLayout::Slot<int32_t> x_slot = layout_builder.AddSlot<int32_t>(); auto make_increment_operator = [x_slot](int32_t increment) { return MakeBoundOperator( [x_slot, increment](EvaluationContext* ctx, FramePtr frame) { frame.Set(x_slot, frame.Get(x_slot) + increment); }); }; ExecutableBuilder builder(&layout_builder, true); builder.AddEvalOp(make_increment_operator(1), "inc(1)", "inc(1)"); builder.AddEvalOp(make_increment_operator(10), "inc(10)", "inc(10)"); builder.AddEvalOp(make_increment_operator(100), "inc(100)", "inc(100)"); builder.AddEvalOp( MakeBoundOperator([](EvaluationContext* ctx, FramePtr frame) { ctx->set_status(absl::InvalidArgumentError("foo")); }), "error_operator", "error_operator"); builder.AddEvalOp(make_increment_operator(1000), "inc(1000)", "inc(1000)"); auto dynamic_bound_expr = std::move(builder).Build({}, TypedSlot::FromSlot(x_slot)); FrameLayout layout = std::move(layout_builder).Build(); MemoryAllocation alloc(&layout); EvaluationContext ctx; dynamic_bound_expr->Execute(&ctx, alloc.frame()); EXPECT_THAT( ctx.status(), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("foo; during evaluation of operator error_operator"))); } } }
2,477
#ifndef AROLLA_EXPR_EVAL_DYNAMIC_COMPILED_OPERATOR_H_ #define AROLLA_EXPR_EVAL_DYNAMIC_COMPILED_OPERATOR_H_ #include <memory> #include <string> #include <vector> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "arolla/expr/eval/dynamic_compiled_expr.h" #include "arolla/expr/eval/eval.h" #include "arolla/expr/eval/executable_builder.h" #include "arolla/expr/expr_operator.h" #include "arolla/qtype/qtype.h" #include "arolla/util/fingerprint.h" namespace arolla::expr::eval_internal { class DynamicCompiledOperator { public: static absl::StatusOr<DynamicCompiledOperator> Build( const DynamicEvaluationEngineOptions& options, const ExprOperatorPtr& op, std::vector<QTypePtr> input_qtypes); absl::Status BindTo(ExecutableBuilder& executable_builder, absl::Span<const TypedSlot> input_slots, TypedSlot output_slot) const; absl::string_view display_name() const { return display_name_; } absl::Span<const QTypePtr> input_qtypes() const { return input_qtypes_; } QTypePtr output_qtype() const { return compiled_expr_->output_type(); } Fingerprint fingerprint() const { return fingerprint_; } private: DynamicCompiledOperator( std::string display_name, std::vector<QTypePtr> input_qtypes, std::unique_ptr<const DynamicCompiledExpr> compiled_expr, std::vector<std::string> input_arg_names, Fingerprint fingerprint); std::string display_name_; std::vector<QTypePtr> input_qtypes_; std::unique_ptr<const DynamicCompiledExpr> compiled_expr_; std::vector<std::string> input_arg_names_; Fingerprint fingerprint_; }; } #endif #include "arolla/expr/eval/dynamic_compiled_operator.h" #include <cstddef> #include <memory> #include <string> #include <utility> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "absl/types/span.h" #include "arolla/expr/eval/dynamic_compiled_expr.h" #include "arolla/expr/eval/eval.h" #include "arolla/expr/eval/executable_builder.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_operator.h" #include "arolla/qtype/qtype.h" #include "arolla/util/fingerprint.h" #include "arolla/util/status_macros_backport.h" namespace arolla::expr::eval_internal { template <typename T, typename U> std::unique_ptr<T> dynamic_unique_ptr_cast(std::unique_ptr<U> unique) { T* casted = dynamic_cast<T*>(unique.get()); if (casted != nullptr) { unique.release(); } return std::unique_ptr<T>(casted); } absl::StatusOr<DynamicCompiledOperator> DynamicCompiledOperator::Build( const DynamicEvaluationEngineOptions& options, const ExprOperatorPtr& op, std::vector<QTypePtr> input_qtypes) { std::vector<absl::StatusOr<ExprNodePtr>> inputs; std::vector<std::string> input_arg_names; absl::flat_hash_map<std::string, QTypePtr> input_qtypes_map; inputs.reserve(input_qtypes.size()); input_qtypes_map.reserve(input_qtypes.size()); input_arg_names.reserve(input_qtypes.size()); for (size_t i = 0; i < input_qtypes.size(); ++i) { std::string name = absl::StrFormat("_%d", i); inputs.push_back(Leaf(name)); input_qtypes_map.emplace(name, input_qtypes[i]); input_arg_names.emplace_back(std::move(name)); } ASSIGN_OR_RETURN(auto expr, CallOp(op, inputs)); ASSIGN_OR_RETURN(auto compiled_expr, CompileForDynamicEvaluation( options, expr, input_qtypes_map)); std::unique_ptr<const DynamicCompiledExpr> dynamic_compiled_expr = dynamic_unique_ptr_cast<const DynamicCompiledExpr>( std::move(compiled_expr)); DCHECK(dynamic_compiled_expr); return DynamicCompiledOperator( std::string(op->display_name()), std::move(input_qtypes), std::move(dynamic_compiled_expr), std::move(input_arg_names), FingerprintHasher("arolla::expr::eval_internal::DynamicCompiledOperator") .Combine(op->fingerprint()) .CombineSpan(input_qtypes) .Finish()); } absl::Status DynamicCompiledOperator::BindTo( ExecutableBuilder& executable_builder, absl::Span<const TypedSlot> input_slots, TypedSlot output_slot) const { if (input_slots.size() != input_arg_names_.size()) { return absl::InternalError(absl::StrFormat( "input count mismatch in DynamicCompiledOperator: expected %d, got %d", input_arg_names_.size(), input_slots.size())); } absl::flat_hash_map<std::string, TypedSlot> input_slots_map; input_slots_map.reserve(input_slots.size()); for (size_t i = 0; i < input_slots.size(); ++i) { input_slots_map.emplace(input_arg_names_[i], input_slots[i]); } return compiled_expr_->BindToExecutableBuilder(executable_builder, input_slots_map, output_slot); } DynamicCompiledOperator::DynamicCompiledOperator( std::string display_name, std::vector<QTypePtr> input_qtypes, std::unique_ptr<const DynamicCompiledExpr> compiled_expr, std::vector<std::string> input_arg_names, Fingerprint fingerprint) : display_name_(std::move(display_name)), input_qtypes_(input_qtypes.begin(), input_qtypes.end()), compiled_expr_(std::move(compiled_expr)), input_arg_names_(std::move(input_arg_names)), fingerprint_(fingerprint) { DCHECK_EQ(input_qtypes_.size(), input_arg_names_.size()); } }
#include "arolla/expr/eval/dynamic_compiled_operator.h" #include <memory> #include <utility> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "arolla/expr/eval/eval.h" #include "arolla/expr/eval/executable_builder.h" #include "arolla/expr/eval/test_utils.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/expr/lambda_expr_operator.h" #include "arolla/memory/frame.h" #include "arolla/qexpr/evaluation_engine.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/typed_slot.h" #include "arolla/util/init_arolla.h" #include "arolla/util/testing/status_matchers_backport.h" namespace arolla::expr::eval_internal { namespace { using ::arolla::testing::StatusIs; using ::testing::HasSubstr; class DynamicCompiledOperatorTest : public ::testing::Test { protected: void SetUp() override { ASSERT_OK(InitArolla()); } }; TEST_F(DynamicCompiledOperatorTest, DynamicCompiledOperator) { ASSERT_OK_AND_ASSIGN( auto lambda, MakeLambdaOperator( ExprOperatorSignature::Make("x, y"), CallOp("math.add", {CallOp("math.add", {Placeholder("x"), Placeholder("y")}), Literal(1.)}))); ASSERT_OK_AND_ASSIGN( DynamicCompiledOperator op, DynamicCompiledOperator::Build(DynamicEvaluationEngineOptions{}, lambda, {GetQType<float>(), GetQType<double>()})); FrameLayout::Builder layout_builder; auto x_slot = layout_builder.AddSlot<float>(); auto y_slot = layout_builder.AddSlot<double>(); auto output_slot = layout_builder.AddSlot<double>(); ExecutableBuilder executable_builder(&layout_builder, true); EXPECT_THAT(op.BindTo(executable_builder, {TypedSlot::FromSlot(x_slot)}, TypedSlot::FromSlot(output_slot)), StatusIs(absl::StatusCode::kInternal, "input count mismatch in DynamicCompiledOperator: " "expected 2, got 1")); EXPECT_THAT( op.BindTo(executable_builder, {TypedSlot::FromSlot(x_slot), TypedSlot::FromSlot(x_slot)}, TypedSlot::FromSlot(output_slot)), StatusIs(absl::StatusCode::kFailedPrecondition, HasSubstr("slot types mismatch"))); ASSERT_OK( op.BindTo(executable_builder, {TypedSlot::FromSlot(x_slot), TypedSlot::FromSlot(y_slot)}, TypedSlot::FromSlot(output_slot))); std::unique_ptr<BoundExpr> executable_expr = std::move(executable_builder) .Build({{"x", TypedSlot::FromSlot(x_slot)}, {"y", TypedSlot::FromSlot(y_slot)}}, TypedSlot::FromSlot(output_slot)); EXPECT_THAT( executable_expr, AllOf(InitOperationsAre("FLOAT64 [0x28] = float64{1}"), EvalOperationsAre( "FLOAT64 [0x18] = core.to_float64(FLOAT32 [0x00])", "FLOAT64 [0x20] = math.add(FLOAT64 [0x18], FLOAT64 [0x08])", "FLOAT64 [0x10] = math.add(FLOAT64 [0x20], FLOAT64 [0x28])"))); } TEST_F(DynamicCompiledOperatorTest, DynamicCompiledOperator_Literal) { ASSERT_OK_AND_ASSIGN( auto lambda, MakeLambdaOperator(ExprOperatorSignature{}, Literal(1.))); ASSERT_OK_AND_ASSIGN(DynamicCompiledOperator op, DynamicCompiledOperator::Build( DynamicEvaluationEngineOptions{}, lambda, {})); FrameLayout::Builder layout_builder; auto output_slot = layout_builder.AddSlot<double>(); ExecutableBuilder executable_builder(&layout_builder, true); ASSERT_OK( op.BindTo(executable_builder, {}, TypedSlot::FromSlot(output_slot))); std::unique_ptr<BoundExpr> executable_expr = std::move(executable_builder).Build({}, TypedSlot::FromSlot(output_slot)); EXPECT_THAT( executable_expr, AllOf(InitOperationsAre("FLOAT64 [0x08] = float64{1}"), EvalOperationsAre("FLOAT64 [0x00] = core._copy(FLOAT64 [0x08])"))); } } }
2,478
#ifndef AROLLA_EXPR_EVAL_SLOT_USAGE_TRACKER_H_ #define AROLLA_EXPR_EVAL_SLOT_USAGE_TRACKER_H_ #include <cstdint> #include <string> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/status/status.h" #include "arolla/expr/expr_node.h" #include "arolla/memory/frame.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/typed_slot.h" #include "arolla/util/fingerprint.h" namespace arolla::expr::eval_internal { class SlotAllocator { public: SlotAllocator(const ExprNodePtr& root, FrameLayout::Builder& layout_builder, const absl::flat_hash_map<std::string, TypedSlot>& input_slots, bool allow_reusing_leaves); TypedSlot AddSlotForNode(const ExprNodePtr& node, QTypePtr type, bool allow_recycled); absl::Status ExtendSlotLifetime(const ExprNodePtr& of, const ExprNodePtr& to); absl::Status ReleaseSlotsNotNeededAfter(const ExprNodePtr& node); std::vector<TypedSlot> ReusableSlots() const; private: struct SlotUsage { Fingerprint node_fingerprint; int64_t node_number; }; FrameLayout::Builder* layout_builder_; absl::flat_hash_map<QTypePtr, std::vector<TypedSlot>> reusable_slots_; absl::flat_hash_map<Fingerprint, SlotUsage> last_usages_; absl::flat_hash_map<Fingerprint, TypedSlot> node_result_slot_; absl::flat_hash_map<Fingerprint, ExprNodePtr> node_origin_; bool allow_reusing_leaves_; }; } #endif #include "arolla/expr/eval/slot_allocator.h" #include <cstdint> #include <optional> #include <string> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/container/flat_hash_set.h" #include "absl/status/status.h" #include "absl/strings/str_format.h" #include "arolla/expr/expr_debug_string.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_visitor.h" #include "arolla/memory/frame.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/typed_slot.h" #include "arolla/util/fingerprint.h" namespace arolla::expr::eval_internal { SlotAllocator::SlotAllocator( const ExprNodePtr& root, FrameLayout::Builder& layout_builder, const absl::flat_hash_map<std::string, TypedSlot>& input_slots, bool allow_reusing_leaves) : layout_builder_(&layout_builder), allow_reusing_leaves_(allow_reusing_leaves) { auto node_order = VisitorOrder(root); last_usages_.reserve(node_order.size()); for (int64_t i = 0; i < node_order.size(); ++i) { const auto& node = node_order[i]; for (const auto& d : node->node_deps()) { last_usages_[d->fingerprint()] = SlotUsage{node->fingerprint(), i}; } last_usages_[node->fingerprint()] = SlotUsage{node->fingerprint(), i}; if (allow_reusing_leaves_ && node->is_leaf()) { node_result_slot_.emplace(node->fingerprint(), input_slots.at(node->leaf_key())); } } } TypedSlot SlotAllocator::AddSlotForNode(const ExprNodePtr& node, QTypePtr type, bool allow_recycled) { auto& reusable_slots = reusable_slots_[type]; std::optional<TypedSlot> slot; if (!allow_recycled || reusable_slots.empty()) { slot = ::arolla::AddSlot(type, layout_builder_); } else { slot = reusable_slots.back(); reusable_slots.pop_back(); } node_result_slot_.emplace(node->fingerprint(), *slot); return *slot; } absl::Status SlotAllocator::ExtendSlotLifetime(const ExprNodePtr& of, const ExprNodePtr& to) { if (to->fingerprint() == of->fingerprint()) { return absl::OkStatus(); } ExprNodePtr of_origin = of; if (node_origin_.contains(of->fingerprint())) { of_origin = node_origin_.at(of->fingerprint()); last_usages_.erase(of->fingerprint()); } node_origin_[to->fingerprint()] = of_origin; if (!last_usages_.contains(to->fingerprint())) { return absl::InternalError( absl::StrFormat("missing last usage for node %s", GetDebugSnippet(to))); } if (!last_usages_.contains(of_origin->fingerprint())) { return absl::InternalError(absl::StrFormat("missing last usage for node %s", GetDebugSnippet(of_origin))); } if (last_usages_.at(to->fingerprint()).node_number > last_usages_.at(of_origin->fingerprint()).node_number) { last_usages_[of_origin->fingerprint()] = last_usages_.at(to->fingerprint()); } return absl::OkStatus(); } absl::Status SlotAllocator::ReleaseSlotsNotNeededAfter( const ExprNodePtr& node) { absl::flat_hash_set<Fingerprint> processed_deps; for (ExprNodePtr dep : node->node_deps()) { if (node_origin_.contains(dep->fingerprint())) { dep = node_origin_.at(dep->fingerprint()); } const auto& [_, inserted] = processed_deps.insert(dep->fingerprint()); if (!inserted) { continue; } auto last_usage_it = last_usages_.find(dep->fingerprint()); if (last_usage_it == last_usages_.end()) { return absl::InternalError(absl::StrFormat( "missing last usage for node %s", GetDebugSnippet(dep))); } if ((dep->is_op() || (dep->is_leaf() && allow_reusing_leaves_)) && last_usage_it->second.node_fingerprint == node->fingerprint()) { auto slot_it = node_result_slot_.find(dep->fingerprint()); if (slot_it == node_result_slot_.end()) { return absl::InternalError(absl::StrFormat( "missing slot information for node %s", GetDebugSnippet(dep))); } reusable_slots_[slot_it->second.GetType()].push_back(slot_it->second); node_result_slot_.erase(slot_it); last_usages_.erase(last_usage_it); } } return absl::OkStatus(); } std::vector<TypedSlot> SlotAllocator::ReusableSlots() const { std::vector<TypedSlot> result; for (const auto& [_, slots] : reusable_slots_) { result.insert(result.end(), slots.begin(), slots.end()); } return result; } }
#include "arolla/expr/eval/slot_allocator.h" #include <string> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/container/flat_hash_map.h" #include "absl/status/status.h" #include "arolla/expr/expr.h" #include "arolla/memory/frame.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/typed_slot.h" #include "arolla/util/init_arolla.h" #include "arolla/util/testing/status_matchers_backport.h" namespace arolla::expr::eval_internal { namespace { using ::arolla::testing::IsOk; using ::arolla::testing::StatusIs; using ::testing::AllOf; using ::testing::ElementsAre; using ::testing::Eq; using ::testing::HasSubstr; using ::testing::IsEmpty; using ::testing::Ne; class SlotAllocatorTest : public ::testing::Test { protected: void SetUp() override { ASSERT_OK(InitArolla()); } }; TEST_F(SlotAllocatorTest, CompilerWorkflow) { auto zero = Literal(0.0f); ASSERT_OK_AND_ASSIGN(auto x1, CallOp("math.add", {zero, Leaf("x1")})); ASSERT_OK_AND_ASSIGN(auto x1_x1, CallOp("math.add", {x1, Leaf("x1")})); ASSERT_OK_AND_ASSIGN(auto x1_x1_x2, CallOp("math.add", {x1_x1, Leaf("x2")})); ASSERT_OK_AND_ASSIGN(auto x1_x1_x2_x3, CallOp("math.add", {x1_x1_x2, Leaf("x3")})); FrameLayout::Builder layout_builder; absl::flat_hash_map<std::string, TypedSlot> input_slots{ {"x1", TypedSlot::FromSlot(layout_builder.AddSlot<float>())}, {"x2", TypedSlot::FromSlot(layout_builder.AddSlot<float>())}, {"x3", TypedSlot::FromSlot(layout_builder.AddSlot<float>())}, }; SlotAllocator allocator(x1_x1_x2_x3, layout_builder, input_slots, false); TypedSlot zero_slot = allocator.AddSlotForNode(zero, GetQType<float>(), false); EXPECT_THAT(allocator.ReleaseSlotsNotNeededAfter(zero), IsOk()); TypedSlot x1_slot = allocator.AddSlotForNode(x1, GetQType<float>(), true); EXPECT_THAT(x1_slot, Ne(zero_slot)); EXPECT_THAT(allocator.ReleaseSlotsNotNeededAfter(x1), IsOk()); EXPECT_THAT(allocator.ReusableSlots(), IsEmpty()); TypedSlot x1_x1_slot = allocator.AddSlotForNode(x1_x1, GetQType<float>(), true); EXPECT_THAT(x1_x1_slot, AllOf(Ne(zero_slot), Ne(x1_slot))); EXPECT_THAT(allocator.ReleaseSlotsNotNeededAfter(x1_x1), IsOk()); EXPECT_THAT(allocator.ReusableSlots(), ElementsAre(x1_slot)); EXPECT_THAT(allocator.ExtendSlotLifetime(x1_x1, x1_x1_x2), IsOk()); EXPECT_THAT(allocator.ReleaseSlotsNotNeededAfter(x1_x1_x2), IsOk()); EXPECT_THAT(allocator.ReusableSlots(), ElementsAre(x1_slot)); TypedSlot x1_x1_x2_x3_slot = allocator.AddSlotForNode( x1_x1_x2_x3, GetQType<float>(), true); EXPECT_THAT(x1_x1_x2_x3_slot, Eq(x1_slot)); EXPECT_THAT(allocator.ReleaseSlotsNotNeededAfter(x1_x1_x2_x3), IsOk()); EXPECT_THAT(allocator.ReusableSlots(), ElementsAre(x1_x1_slot)); EXPECT_THAT(allocator.ExtendSlotLifetime(x1, x1_x1_x2), StatusIs(absl::StatusCode::kInternal, HasSubstr("missing last usage for node"))); EXPECT_THAT(allocator.ReleaseSlotsNotNeededAfter(x1_x1), StatusIs(absl::StatusCode::kInternal, HasSubstr("missing last usage for node"))); } TEST_F(SlotAllocatorTest, CompilerWorkflowWithReusedLeaves) { auto zero = Literal(0.0f); ASSERT_OK_AND_ASSIGN(auto x1, CallOp("math.add", {zero, Leaf("x1")})); ASSERT_OK_AND_ASSIGN(auto x1_x1, CallOp("math.add", {x1, Leaf("x1")})); ASSERT_OK_AND_ASSIGN(auto x1_x1_x2, CallOp("math.add", {x1_x1, Leaf("x2")})); ASSERT_OK_AND_ASSIGN(auto x1_x1_x2_x3, CallOp("math.add", {x1_x1_x2, Leaf("x3")})); FrameLayout::Builder layout_builder; absl::flat_hash_map<std::string, TypedSlot> input_slots{ {"x1", TypedSlot::FromSlot(layout_builder.AddSlot<float>())}, {"x2", TypedSlot::FromSlot(layout_builder.AddSlot<float>())}, {"x3", TypedSlot::FromSlot(layout_builder.AddSlot<float>())}, }; SlotAllocator allocator(x1_x1_x2_x3, layout_builder, input_slots, true); TypedSlot zero_slot = allocator.AddSlotForNode(zero, GetQType<float>(), false); EXPECT_THAT(allocator.ReleaseSlotsNotNeededAfter(zero), IsOk()); TypedSlot x1_slot = allocator.AddSlotForNode(x1, GetQType<float>(), true); EXPECT_THAT(x1_slot, Ne(zero_slot)); EXPECT_THAT(allocator.ReleaseSlotsNotNeededAfter(x1), IsOk()); EXPECT_THAT(allocator.ReusableSlots(), IsEmpty()); TypedSlot x1_x1_slot = allocator.AddSlotForNode(x1_x1, GetQType<float>(), true); EXPECT_THAT(x1_x1_slot, AllOf(Ne(zero_slot), Ne(x1_slot))); EXPECT_THAT(allocator.ReleaseSlotsNotNeededAfter(x1_x1), IsOk()); EXPECT_THAT(allocator.ReusableSlots(), ElementsAre(x1_slot, input_slots.at("x1"))); EXPECT_THAT(allocator.ExtendSlotLifetime(x1_x1, x1_x1_x2), IsOk()); EXPECT_THAT(allocator.ReleaseSlotsNotNeededAfter(x1_x1_x2), IsOk()); EXPECT_THAT(allocator.ReusableSlots(), ElementsAre(x1_slot, input_slots.at("x1"), input_slots.at("x2"))); TypedSlot x1_x1_x2_x3_slot = allocator.AddSlotForNode( x1_x1_x2_x3, GetQType<float>(), true); EXPECT_THAT(x1_x1_x2_x3_slot, Eq(input_slots.at("x2"))); EXPECT_THAT(allocator.ReleaseSlotsNotNeededAfter(x1_x1_x2_x3), IsOk()); EXPECT_THAT(allocator.ReusableSlots(), ElementsAre(x1_slot, input_slots.at("x1"), x1_x1_slot, input_slots.at("x3"))); EXPECT_THAT(allocator.ExtendSlotLifetime(x1, x1_x1_x2), StatusIs(absl::StatusCode::kInternal, HasSubstr("missing last usage for node"))); EXPECT_THAT(allocator.ReleaseSlotsNotNeededAfter(x1_x1), StatusIs(absl::StatusCode::kInternal, HasSubstr("missing last usage for node"))); } } }
2,479
#ifndef AROLLA_EXPR_EVAL_COMPILE_STD_FUNCTION_OPERATOR_H_ #define AROLLA_EXPR_EVAL_COMPILE_STD_FUNCTION_OPERATOR_H_ #include "absl/status/status.h" #include "absl/types/span.h" #include "arolla/expr/eval/executable_builder.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/operators/std_function_operator.h" #include "arolla/qtype/typed_slot.h" namespace arolla::expr::eval_internal { absl::Status CompileStdFunctionOperator( const expr_operators::StdFunctionOperator& std_function_op, absl::Span<const TypedSlot> input_slots, TypedSlot output_slot, ExecutableBuilder& executable_builder, ExprNodePtr node); } #endif #include "arolla/expr/eval/compile_std_function_operator.h" #include <cstdint> #include <string> #include <utility> #include <vector> #include "absl/status/status.h" #include "absl/strings/str_format.h" #include "absl/types/span.h" #include "arolla/expr/eval/executable_builder.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/expr/operators/std_function_operator.h" #include "arolla/memory/frame.h" #include "arolla/qexpr/bound_operators.h" #include "arolla/qexpr/eval_context.h" #include "arolla/qtype/typed_ref.h" #include "arolla/qtype/typed_slot.h" #include "arolla/util/status_macros_backport.h" namespace arolla::expr::eval_internal { absl::Status CompileStdFunctionOperator( const expr_operators::StdFunctionOperator& std_function_op, absl::Span<const TypedSlot> input_slots, TypedSlot output_slot, ExecutableBuilder& executable_builder, ExprNodePtr node) { RETURN_IF_ERROR(ValidateDepsCount(std_function_op.signature(), input_slots.size(), absl::StatusCode::kFailedPrecondition)); auto fn = std_function_op.GetEvalFn(); int64_t ip = executable_builder.AddEvalOp( MakeBoundOperator([fn, output_slot, input_slots = std::vector(input_slots.begin(), input_slots.end())]( EvaluationContext* ctx, FramePtr frame) { std::vector<TypedRef> inputs; inputs.reserve(input_slots.size()); for (const auto input_slot : input_slots) { inputs.push_back(TypedRef::FromSlot(input_slot, frame)); } ASSIGN_OR_RETURN(auto res, fn(inputs), ctx->set_status(std::move(_))); if (res.GetType() != output_slot.GetType()) { ctx->set_status(absl::InvalidArgumentError(absl::StrFormat( "expected the result to have qtype %s, got %s", output_slot.GetType()->name(), res.GetType()->name()))); return; } ctx->set_status(res.CopyToSlot(output_slot, frame)); }), FormatOperatorCall(std_function_op.display_name(), input_slots, {output_slot}), std::string(std_function_op.display_name())); executable_builder.RegisterStacktrace(ip, node); return absl::OkStatus(); } }
#include <cstdint> #include <memory> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/container/flat_hash_map.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/types/span.h" #include "arolla/expr/eval/eval.h" #include "arolla/expr/eval/invoke.h" #include "arolla/expr/eval/test_utils.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/expr/lambda_expr_operator.h" #include "arolla/expr/operators/std_function_operator.h" #include "arolla/memory/frame.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/testing/qtype.h" #include "arolla/qtype/typed_ref.h" #include "arolla/qtype/typed_value.h" #include "arolla/util/init_arolla.h" #include "arolla/util/testing/status_matchers_backport.h" #include "arolla/util/status_macros_backport.h" namespace arolla::expr::eval_internal { namespace { using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::StatusIs; using ::arolla::testing::TypedValueWith; using ::testing::AllOf; using ::testing::Eq; class StdFunctionOperatorTest : public ::testing::TestWithParam<DynamicEvaluationEngineOptions> { protected: void SetUp() override { ASSERT_OK(InitArolla()); } DynamicEvaluationEngineOptions GetOptions() const { return GetParam(); } }; absl::StatusOr<TypedValue> Add(absl::Span<const TypedRef> inputs) { ASSIGN_OR_RETURN(int32_t x, inputs[0].As<int32_t>()); ASSIGN_OR_RETURN(int64_t y, inputs[1].As<int64_t>()); double z = 3.0; return TypedValue::FromValue(x + y + z); } INSTANTIATE_TEST_SUITE_P( GarbageCollection, StdFunctionOperatorTest, ::testing::Values( DynamicEvaluationEngineOptions{.collect_op_descriptions = true, .allow_overriding_input_slots = false}, DynamicEvaluationEngineOptions{.collect_op_descriptions = true, .allow_overriding_input_slots = true})); TEST_P(StdFunctionOperatorTest, SimpleFn) { auto op = std::make_shared<expr_operators::StdFunctionOperator>( "add", ExprOperatorSignature{{"x"}, {"y"}}, "dummy op docstring", [](absl::Span<const QTypePtr> input_qtypes) { return GetQType<double>(); }, Add); ASSERT_OK_AND_ASSIGN(auto expr, CallOp(op, {Leaf("x"), Leaf("y")})); FrameLayout::Builder layout_builder; expr::DynamicEvaluationEngineOptions options; options.collect_op_descriptions = true; auto x_slot = layout_builder.AddSlot<int32_t>(); auto y_slot = layout_builder.AddSlot<int64_t>(); EXPECT_THAT(expr::CompileAndBindForDynamicEvaluation( options, &layout_builder, expr, {{"x", TypedSlot::FromSlot(x_slot)}, {"y", TypedSlot::FromSlot(y_slot)}}), IsOkAndHolds(AllOf( InitOperationsAre(), EvalOperationsAre( "FLOAT64 [0x10] = add(INT32 [0x00], INT64 [0x08])")))); EXPECT_THAT(Invoke(expr, {{"x", TypedValue::FromValue(1)}, {"y", TypedValue::FromValue(int64_t{2})}}, GetOptions()), IsOkAndHolds(TypedValueWith<double>(Eq(6.0)))); } TEST_F(StdFunctionOperatorTest, StackTraceTest) { auto error_op = std::make_shared<expr_operators::StdFunctionOperator>( "error_op", ExprOperatorSignature{}, "dummy op docstring", [](absl::Span<const QTypePtr> input_qtypes) { return GetQType<double>(); }, [](absl::Span<const TypedRef> refs) -> absl::StatusOr<TypedValue> { return absl::InternalError("Error from StdFunctionOperator"); }); ASSERT_OK_AND_ASSIGN( auto error_lambda, MakeLambdaOperator("error_lambda", ExprOperatorSignature{}, CallOp(error_op, {}))); ASSERT_OK_AND_ASSIGN(auto expr, CallOp(error_lambda, {})); FrameLayout::Builder layout_builder; expr::DynamicEvaluationEngineOptions options{.enable_expr_stack_trace = true}; EXPECT_THAT(expr::CompileAndBindForDynamicEvaluation(options, &layout_builder, expr, {}), StatusIs(absl::StatusCode::kInternal, "Error from StdFunctionOperator; " "during evaluation of operator error_op\n" "ORIGINAL NODE: error_lambda():FLOAT64\n" "COMPILED NODE: error_op():FLOAT64; while doing literal" " folding; while transforming error_lambda():FLOAT64")); } } }
2,480
#ifndef AROLLA_EXPR_EVAL_MODEL_EXECUTOR_H_ #define AROLLA_EXPR_EVAL_MODEL_EXECUTOR_H_ #include <cstddef> #include <cstdint> #include <memory> #include <optional> #include <string> #include <type_traits> #include <utility> #include <vector> #include "absl/base/attributes.h" #include "absl/base/nullability.h" #include "absl/cleanup/cleanup.h" #include "absl/container/flat_hash_map.h" #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "arolla/dense_array/dense_array.h" #include "arolla/dense_array/qtype/types.h" #include "arolla/expr/eval/eval.h" #include "arolla/expr/eval/side_output.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_node.h" #include "arolla/io/input_loader.h" #include "arolla/io/slot_listener.h" #include "arolla/memory/frame.h" #include "arolla/memory/memory_allocation.h" #include "arolla/memory/optional_value.h" #include "arolla/memory/raw_buffer_factory.h" #include "arolla/qexpr/eval_context.h" #include "arolla/qexpr/evaluation_engine.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/typed_slot.h" #include "arolla/qtype/typed_value.h" #include "arolla/util/demangle.h" #include "arolla/util/view_types.h" #include "arolla/util/status_macros_backport.h" namespace arolla::expr { struct ModelExecutorOptions { DynamicEvaluationEngineOptions eval_options; bool force_non_optional_output = false; bool allow_output_casting = false; bool allow_side_outputs_casting = false; int64_t arena_page_size = 0; bool ignore_not_listened_named_outputs = false; }; struct ModelEvaluationOptions { RawBufferFactory* buffer_factory = GetHeapBufferFactory(); }; namespace model_executor_impl { std::unique_ptr<CompiledExpr> CastOutputsIfNeeded( const CompiledExpr& expr, QTypePtr desired_output_type, absl::Nullable<const SlotListenerBase*> slot_listener, const ModelExecutorOptions& options); template <typename T> struct OutputTraits; absl::Status VerifyAllInputsAreAvailable( const ExprNodePtr& expr, const absl::flat_hash_map<std::string, QTypePtr>& input_types); absl::Status VerifyAllNamedOutputsAreListened( const absl::flat_hash_map<std::string, QTypePtr>& available_named_output_types, const SlotListenerBase& slot_listener); } template <typename I, typename O, typename S = void> class ModelExecutor { using OutputTraits = model_executor_impl::OutputTraits<O>; public: using Input = I; using Output = O; using SideOutput = S; template <class Loader> static absl::StatusOr<ModelExecutor> Compile( ExprNodePtr expr, const Loader& input_loader, const SlotListener<SideOutput>* slot_listener = nullptr, const ModelExecutorOptions& options = {}) { auto leaf_keys = GetLeafKeys(expr); ASSIGN_OR_RETURN(auto input_types, GetInputLoaderQTypes(input_loader, leaf_keys)); ASSIGN_OR_RETURN((auto [stripped_expr, side_outputs]), ExtractSideOutputs(expr), _ << "while extracting side outputs"); DynamicEvaluationEngineOptions eval_options = options.eval_options; eval_options.allow_overriding_input_slots = true; ASSIGN_OR_RETURN( auto compiled_expr, CompileForDynamicEvaluation(eval_options, stripped_expr, input_types, {}), _ << "while compiling the expression"); std::unique_ptr<CompiledExpr> compiled_expr_with_side_output; if (slot_listener != nullptr) { ASSIGN_OR_RETURN( side_outputs, PrepareSideOutputsForListener(side_outputs, *slot_listener), _ << "while preparing side outputs"); ASSIGN_OR_RETURN(compiled_expr_with_side_output, CompileForDynamicEvaluation(eval_options, stripped_expr, input_types, side_outputs), _ << "while compiling the expression with side outputs"); } return ModelExecutor::Bind(*compiled_expr, input_loader, compiled_expr_with_side_output.get(), slot_listener, options); } static absl::StatusOr<ModelExecutor> Bind( const CompiledExpr& compiled_expr, const InputLoader<Input>& input_loader, const CompiledExpr* compiled_expr_with_side_output = nullptr, const SlotListener<SideOutput>* slot_listener = nullptr, const ModelExecutorOptions& options = {}) { FrameLayout::Builder layout_builder; auto input_slots = AddSlotsMap((compiled_expr_with_side_output != nullptr ? compiled_expr_with_side_output : &compiled_expr) ->input_types(), &layout_builder); ASSIGN_OR_RETURN(auto bound_loader, input_loader.Bind(input_slots), _ << "while binding the input loader"); return ModelExecutor::BindToSlots( &layout_builder, compiled_expr, compiled_expr_with_side_output, std ::move(input_slots), std::move(bound_loader), slot_listener, options); } absl::StatusOr<Output> Execute(const ModelEvaluationOptions& options, const Input& input, SideOutput* side_output = nullptr) { DCHECK(IsValid()); if (arena_ != nullptr) { EvaluationContext ctx(arena_.get()); absl::StatusOr<Output> res = ExecuteOnFrame<false>( ctx, alloc_.frame(), input, side_output); arena_->Reset(); return res; } else { EvaluationContext ctx(options.buffer_factory); return ExecuteOnFrame<false>(ctx, alloc_.frame(), input, side_output); } } absl::StatusOr<Output> Execute(const Input& input, SideOutput* side_output = nullptr) { return Execute({}, input, side_output); } absl::StatusOr<Output> ExecuteOnHeap( const ModelEvaluationOptions& options, const Input& input, SideOutput* side_output = nullptr) const { if (arena_ != nullptr) { UnsafeArenaBufferFactory arena(shared_data_->arena_page_size); EvaluationContext ctx(&arena); return ExecuteOnHeapWithContext(ctx, input, side_output); } else { EvaluationContext ctx(options.buffer_factory); return ExecuteOnHeapWithContext(ctx, input, side_output); } } bool CanExecuteOnStack(size_t stack_size) const { const FrameLayout& layout = shared_data_->layout; return layout.AllocAlignment().value <= alignof(size_t) && layout.AllocSize() <= stack_size; } template <size_t kStackSize> absl::StatusOr<Output> ExecuteOnStack( const ModelEvaluationOptions& options, const Input& input, SideOutput* side_output = nullptr) const { DCHECK(CanExecuteOnStack(kStackSize)) << "Unable to execute on stack. " << "Possible reasons: not enough memory required=" << shared_data_->layout.AllocSize() << " provided:" << kStackSize << " non standard alignment required <=" << alignof(size_t) << " actual:" << shared_data_->layout.AllocAlignment().value; if (arena_ != nullptr) { UnsafeArenaBufferFactory arena(shared_data_->arena_page_size); EvaluationContext ctx(&arena); return ExecuteOnStackWithContext<kStackSize>(ctx, input, side_output); } else { EvaluationContext ctx(options.buffer_factory); return ExecuteOnStackWithContext<kStackSize>(ctx, input, side_output); } } absl::StatusOr<ModelExecutor> Clone() const { return Create(shared_data_); } bool IsValid() const { return alloc_.IsValid() && shared_data_ != nullptr; } private: struct SharedData { FrameLayout layout; BoundInputLoader<Input> bound_loader; std::unique_ptr<BoundExpr> evaluator; std::unique_ptr<BoundExpr> evaluator_with_side_output = nullptr; typename OutputTraits::OutputSlot output_slot; BoundSlotListener<SideOutput> bound_listener = nullptr; int64_t arena_page_size; }; explicit ModelExecutor(std::shared_ptr<const SharedData> shared_data, std::unique_ptr<UnsafeArenaBufferFactory> arena, MemoryAllocation alloc) : shared_data_(std::move(shared_data)), arena_(std::move(arena)), alloc_(std::move(alloc)) {} absl::StatusOr<Output> ExecuteOnHeapWithContext( EvaluationContext& ctx, const Input& input, SideOutput* side_output) const { MemoryAllocation alloc(&shared_data_->layout); return ExecuteOnFrame<true>(ctx, alloc.frame(), input, side_output); } template <size_t kStackSize> absl::StatusOr<Output> ExecuteOnStackWithContext( EvaluationContext& ctx, const Input& input, SideOutput* side_output) const { DCHECK_LE(shared_data_->layout.AllocSize(), kStackSize); DCHECK_LE(shared_data_->layout.AllocAlignment().value, alignof(size_t)); alignas(size_t) std::byte memory[kStackSize]; shared_data_->layout.InitializeAlignedAlloc(memory); absl::Cleanup destroy_alloc = [&] { shared_data_->layout.DestroyAlloc(&memory); }; return ExecuteOnFrame<true>( ctx, FramePtr(&memory, &shared_data_->layout), input, side_output); } template <bool kInitLiterals> absl::StatusOr<Output> ExecuteOnFrame( EvaluationContext& ctx, FramePtr frame, const Input& input, ABSL_ATTRIBUTE_UNUSED SideOutput* side_output) const { if constexpr (std::is_same_v<SideOutput, void>) { return ExecuteOnFrameWithoutSideOutput<kInitLiterals>(ctx, frame, input); } else { if (side_output == nullptr) { return ExecuteOnFrameWithoutSideOutput<kInitLiterals>(ctx, frame, input); } else { return ExecuteOnFrameWithSideOutput<kInitLiterals>(ctx, frame, input, side_output); } } } template <bool kInitLiterals> absl::StatusOr<Output> ExecuteOnFrameWithSideOutput( EvaluationContext& ctx, FramePtr frame, const Input& input, SideOutput* side_output) const { DCHECK(side_output != nullptr); ctx.set_status( shared_data_->bound_loader(input, frame, &ctx.buffer_factory())); if (shared_data_->evaluator_with_side_output != nullptr) { if constexpr (kInitLiterals) { if (ctx.status().ok()) { shared_data_->evaluator_with_side_output->InitializeLiterals(&ctx, frame); } } if (ctx.status().ok()) { shared_data_->evaluator_with_side_output->Execute(&ctx, frame); } } else { if constexpr (kInitLiterals) { if (ctx.status().ok()) { shared_data_->evaluator->InitializeLiterals(&ctx, frame); } } if (ctx.status().ok()) { shared_data_->evaluator->Execute(&ctx, frame); } } if (ctx.status().ok()) { if (shared_data_->bound_listener) { ctx.set_status(shared_data_->bound_listener(frame, side_output)); } else { ctx.set_status(absl::InvalidArgumentError( "Unable to collect side output, since slot listener was not " "provided at construction")); } } if (ctx.status().ok()) { return OutputTraits::ExtractOutput(shared_data_->output_slot, frame); } return ctx.status(); } template <bool kInitLiterals> absl::StatusOr<Output> ExecuteOnFrameWithoutSideOutput( EvaluationContext& ctx, FramePtr frame, const Input& input) const { ctx.set_status( shared_data_->bound_loader(input, frame, &ctx.buffer_factory())); if constexpr (kInitLiterals) { if (ctx.status().ok()) { shared_data_->evaluator->InitializeLiterals(&ctx, frame); } } if (ctx.status().ok()) { shared_data_->evaluator->Execute(&ctx, frame); } if (ctx.status().ok()) { return OutputTraits::ExtractOutput(shared_data_->output_slot, frame); } return ctx.status(); } static absl::StatusOr<ModelExecutor> Create( std::shared_ptr<const SharedData> shared_data) { std::unique_ptr<UnsafeArenaBufferFactory> arena; if (auto page_size = shared_data->arena_page_size; page_size != 0) { if constexpr (!OutputTraits::kSupportsArena) { return absl::InvalidArgumentError(absl::StrFormat( "Arena can not be used with ModelExecutor returning %s", TypeName<Output>())); } arena = std::make_unique<UnsafeArenaBufferFactory>(page_size); } EvaluationContext ctx; MemoryAllocation alloc(&shared_data->layout); shared_data->evaluator->InitializeLiterals(&ctx, alloc.frame()); RETURN_IF_ERROR(ctx.status()); if (shared_data->evaluator_with_side_output != nullptr) { shared_data->evaluator_with_side_output->InitializeLiterals( &ctx, alloc.frame()); RETURN_IF_ERROR(ctx.status()); } return ModelExecutor(std::move(shared_data), std::move(arena), std::move(alloc)); } static absl::StatusOr<ModelExecutor> BindToSlots( FrameLayout::Builder* layout_builder, const CompiledExpr& compiled_expr, const CompiledExpr* compiled_expr_with_side_output, absl::flat_hash_map<std::string, TypedSlot> input_slots, BoundInputLoader<Input> bound_loader, const SlotListener<SideOutput>* slot_listener, const ModelExecutorOptions& options) { RETURN_IF_ERROR(OutputTraits::VerifyForceNonOptionalCompatibility( options.force_non_optional_output)); QTypePtr output_qtype = OutputTraits::OutputQType(compiled_expr.output_type()); if (slot_listener != nullptr && !options.ignore_not_listened_named_outputs) { RETURN_IF_ERROR(model_executor_impl::VerifyAllNamedOutputsAreListened( (compiled_expr_with_side_output != nullptr ? compiled_expr_with_side_output : &compiled_expr) ->named_output_types(), *slot_listener)); } auto compiled_expr_with_casts = model_executor_impl::CastOutputsIfNeeded( compiled_expr, output_qtype, slot_listener, options); ASSIGN_OR_RETURN( auto executable_expr, compiled_expr_with_casts->Bind(layout_builder, input_slots, std::nullopt), _ << "while binding the compiled expression"); std::unique_ptr<BoundExpr> executable_expr_with_side_output; if (compiled_expr_with_side_output != nullptr) { auto compiled_expr_with_side_output_with_casts = model_executor_impl::CastOutputsIfNeeded( *compiled_expr_with_side_output, output_qtype, slot_listener, options); ASSIGN_OR_RETURN( executable_expr_with_side_output, compiled_expr_with_side_output_with_casts->Bind( layout_builder, input_slots, executable_expr->output_slot()), _ << "while binding the compiled expression"); } ASSIGN_OR_RETURN( typename OutputTraits::OutputSlot output_slot, OutputTraits::ToOutputSlot(executable_expr->output_slot()), _ << "requested output type does not correspond to the expression"); BoundSlotListener<SideOutput> bound_listener = nullptr; if (slot_listener != nullptr) { ASSIGN_OR_RETURN(auto maybe_bound_listener, slot_listener->PartialBind( (executable_expr_with_side_output != nullptr ? executable_expr_with_side_output : executable_expr) ->named_output_slots()), _ << "while binding the slot listener"); bound_listener = maybe_bound_listener.has_value() ? std::move(*maybe_bound_listener) : [](ConstFramePtr, SideOutput*) { return absl::OkStatus(); }; } auto shared_data = std::make_shared<SharedData>( SharedData{.layout = std::move(*layout_builder).Build(), .bound_loader = std::move(bound_loader), .evaluator = std::move(executable_expr), .evaluator_with_side_output = std::move(executable_expr_with_side_output), .output_slot = output_slot, .bound_listener = std::move(bound_listener), .arena_page_size = options.arena_page_size}); return Create(shared_data); } std::shared_ptr<const SharedData> shared_data_; std::unique_ptr<UnsafeArenaBufferFactory> arena_; MemoryAllocation alloc_; RawBufferFactory* buffer_factory_ = nullptr; }; template <class Output, class Input, class SideOutput = void> auto CompileModelExecutor(const ExprNodePtr& expr, const InputLoader<Input>& input_loader, const ModelExecutorOptions& options = {}) { return ModelExecutor<Input, Output, SideOutput>::Compile( expr, input_loader, nullptr, options); } template <class Output, class Input, class SideOutput = void> auto CompileModelExecutor(const ExprNodePtr& expr, const InputLoader<Input>& input_loader, const SlotListener<SideOutput>& slot_listener, const ModelExecutorOptions& options = {}) { return ModelExecutor<Input, Output, SideOutput>::Compile( expr, input_loader, &slot_listener, options); } template <class Output, class Input, class SideOutput = void> auto CompileModelExecutor(const ExprNodePtr& expr, const InputLoaderPtr<Input>& input_loader, const ModelExecutorOptions& options = {}) { return ModelExecutor<Input, Output, SideOutput>::Compile( expr, *input_loader, nullptr, options); } template <class Output, class Input, class SideOutput = void> auto CompileModelExecutor( const ExprNodePtr& expr, const InputLoaderPtr<Input>& input_loader, const std::unique_ptr<SlotListener<SideOutput>>& slot_listener, const ModelExecutorOptions& options = {}) { return ModelExecutor<Input, Output, SideOutput>::Compile( expr, *input_loader, slot_listener.get(), options); } template <class Output, class Input, class SideOutput = void> auto BindModelExecutor(const CompiledExpr& compiled_expr, const InputLoader<Input>& input_loader, const ModelExecutorOptions& options = {}) { return ModelExecutor<Input, Output, SideOutput>::Bind( compiled_expr, input_loader, nullptr, nullptr, options); } template <class Output, class Input, class SideOutput = void> auto BindModelExecutor(const CompiledExpr& compiled_expr, const InputLoader<Input>& input_loader, const SlotListener<SideOutput>& slot_listener, const ModelExecutorOptions& options = {}) { return ModelExecutor<Input, Output, SideOutput>::Bind( compiled_expr, input_loader, nullptr, &slot_listener, options); } template <class Output, class Input, class SideOutput = void> auto BindModelExecutor(const CompiledExpr& compiled_expr, const InputLoaderPtr<Input>& input_loader, const ModelExecutorOptions& options = {}) { return ModelExecutor<Input, Output, SideOutput>::Bind( compiled_expr, *input_loader, nullptr, nullptr, options); } template <class Output, class Input, class SideOutput = void> auto BindModelExecutor( const CompiledExpr& compiled_expr, const InputLoaderPtr<Input>& input_loader, const std::unique_ptr<SlotListener<SideOutput>>& slot_listener, const ModelExecutorOptions& options = {}) { return ModelExecutor<Input, Output, SideOutput>::Bind( compiled_expr, *input_loader, nullptr, slot_listener.get(), options); } namespace model_executor_impl { template <typename T> struct OutputTraits { using OutputSlot = FrameLayout::Slot<T>; static constexpr bool kSupportsArena = true; static absl::StatusOr<OutputSlot> ToOutputSlot(TypedSlot slot) { return slot.template ToSlot<T>(); } static T ExtractOutput(OutputSlot slot, FramePtr frame) { return ArenaTraits<T>::MakeOwned(std::move(*frame.GetMutable(slot)), GetHeapBufferFactory()); } static QTypePtr OutputQType(QTypePtr expr_output_qtype) { return GetQType<T>(); } static absl::Status VerifyForceNonOptionalCompatibility( bool force_non_optional_output) { if (force_non_optional_output) { if (!IsScalarQType(GetQType<T>())) { return absl::UnimplementedError( "ForceNonOptionalOutput() is only supported for non-optional " "output types"); } } return absl::OkStatus(); } }; template <> struct OutputTraits<TypedValue> { using OutputSlot = TypedSlot; static constexpr bool kSupportsArena = false; static absl::StatusOr<OutputSlot> ToOutputSlot(TypedSlot slot) { return slot; } static TypedValue ExtractOutput(OutputSlot slot, FramePtr frame) { return TypedValue::FromSlot(slot, frame); } static QTypePtr OutputQType(QTypePtr expr_output_qtype) { return expr_output_qtype; } static absl::Status VerifyForceNonOptionalCompatibility( bool force_non_optional_output) { if (force_non_optional_output) { return absl::UnimplementedError( "ForceNonOptionalOutput() is not supported for TypedValue outputs"); } return absl::OkStatus(); } }; template <typename T> struct OutputTraits<std::optional<T>> : public OutputTraits<OptionalValue<T>> { using Base = OutputTraits<OptionalValue<T>>; static std::optional<T> ExtractOutput(typename Base::OutputSlot slot, FramePtr frame) { return ArenaTraits<OptionalValue<T>>::MakeOwned( std::move(*frame.GetMutable(slot)), GetHeapBufferFactory()) .AsOptional(); } }; template <typename T> struct OutputTraits<std::vector<std::optional<T>>> : public OutputTraits<DenseArray<T>> { using Base = OutputTraits<DenseArray<T>>; static std::vector<std::optional<T>> ExtractOutput( typename Base::OutputSlot slot, FramePtr frame) { const DenseArray<T>& array = frame.Get(slot); std::vector<std::optional<T>> result(array.size()); array.ForEach([&](int64_t id, bool presence, view_type_t<T> value) { if (presence) { result[id] = T(value); } }); return result; } }; template <typename T> struct OutputTraits<std::vector<T>> : public OutputTraits<DenseArray<T>> { using Base = OutputTraits<DenseArray<T>>; static absl::StatusOr<std::vector<T>> ExtractOutput( typename Base::OutputSlot slot, FramePtr frame) { const DenseArray<T>& array = frame.Get(slot); std::vector<T> result(array.size()); absl::Status status; array.ForEach([&](int64_t id, bool presence, view_type_t<T> value) { if (presence) { result[id] = T(value); } else if (status.ok()) { status = absl::FailedPreconditionError( absl::StrFormat("non-full model output (element %d is missing) " "while full std::vector output is requested", id)); } }); RETURN_IF_ERROR(status); return result; } static absl::Status VerifyForceNonOptionalCompatibility( bool force_non_optional_output) { if (!force_non_optional_output) { return absl::FailedPreconditionError( "non-optional std::vector model output is supported only with " "ForceNonOptionalOutput() setting"); } return absl::OkStatus(); } }; } } #endif #include "arolla/expr/eval/model_executor.h" #include <algorithm> #include <map> #include <memory> #include <optional> #include <set> #include <string> #include <utility> #include <vector> #include "absl/base/nullability.h" #include "absl/container/flat_hash_map.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" #include "absl/strings/str_join.h" #include "absl/strings/string_view.h" #include "arolla/expr/eval/eval.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/operators/bootstrap_operators.h" #include "arolla/io/slot_listener.h" #include "arolla/memory/frame.h" #include "arolla/qexpr/eval_context.h" #include "arolla/qexpr/evaluation_engine.h" #include "arolla/qexpr/simple_executable.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/optional_qtype.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/typed_slot.h" #include "arolla/util/string.h" #include "arolla/util/unit.h" #include "arolla/util/status_macros_backport.h" namespace arolla::expr::model_executor_impl { namespace { struct CompiledOutputCastings { std::unique_ptr<BoundExpr> casting_executable_expr; absl::flat_hash_map<std::string, TypedSlot> named_output_slots; };
#include "arolla/expr/eval/model_executor.h" #include <sys/types.h> #include <algorithm> #include <cstdint> #include <optional> #include <string> #include <utility> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/base/nullability.h" #include "absl/container/flat_hash_map.h" #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "arolla/dense_array/dense_array.h" #include "arolla/dense_array/qtype/types.h" #include "arolla/expr/eval/eval.h" #include "arolla/expr/eval/side_output.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/expr/operators/type_meta_eval_strategies.h" #include "arolla/expr/testing/testing.h" #include "arolla/io/accessors_input_loader.h" #include "arolla/io/input_loader.h" #include "arolla/io/slot_listener.h" #include "arolla/memory/frame.h" #include "arolla/memory/optional_value.h" #include "arolla/memory/raw_buffer_factory.h" #include "arolla/qexpr/eval_context.h" #include "arolla/qexpr/operator_factory.h" #include "arolla/qexpr/operators.h" #include "arolla/qtype/optional_qtype.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/testing/qtype.h" #include "arolla/qtype/typed_value.h" #include "arolla/qtype/unspecified_qtype.h" #include "arolla/util/bytes.h" #include "arolla/util/init_arolla.h" #include "arolla/util/testing/status_matchers_backport.h" #include "arolla/util/status_macros_backport.h" namespace arolla::expr { namespace { using ::arolla::testing::IsOk; using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::StatusIs; using ::arolla::testing::TypedValueWith; using ::arolla::testing::WithExportAnnotation; using ::testing::_; using ::testing::AllOf; using ::testing::AnyNumber; using ::testing::AtLeast; using ::testing::ElementsAre; using ::testing::Eq; using ::testing::HasSubstr; using ::testing::IsFalse; using ::testing::IsTrue; struct TestInputs { int64_t x; int64_t y; std::optional<int64_t> optional_z; }; absl::StatusOr<std::unique_ptr<InputLoader<TestInputs>>> CreateTestInputLoader() { return CreateAccessorsInputLoader<TestInputs>( "x", [](const TestInputs& in) { return in.x; }, "y", [](const TestInputs& in) { return in.y; }); } absl::StatusOr<std::unique_ptr<InputLoader<TestInputs>>> CreateTestInt32InputLoader() { return CreateAccessorsInputLoader<TestInputs>( "x", [](const TestInputs& in) -> int32_t { return in.x; }, "y", [](const TestInputs& in) -> int32_t { return in.y; }); } class ModelExecutorTest : public ::testing::Test { protected: void SetUp() override { ASSERT_OK(InitArolla()); } }; TEST_F(ModelExecutorTest, Move) { ASSERT_OK_AND_ASSIGN(auto x_plus_y, CallOp("math.add", {Leaf("x"), Leaf("y")})); ASSERT_OK_AND_ASSIGN(auto input_loader, CreateTestInputLoader()); ASSERT_OK_AND_ASSIGN( auto executor, (ModelExecutor<TestInputs, int64_t>::Compile(x_plus_y, *input_loader))); ASSERT_THAT(executor.IsValid(), IsTrue()); EXPECT_THAT(executor.Execute(TestInputs{50, 7}), IsOkAndHolds(57)); ModelExecutor<TestInputs, int64_t> other_executor{std::move(executor)}; ASSERT_THAT(other_executor.IsValid(), IsTrue()); EXPECT_THAT(other_executor.Execute(TestInputs{50, 7}), IsOkAndHolds(57)); ASSERT_THAT(executor.IsValid(), IsFalse()); executor = std::move(other_executor); ASSERT_THAT(executor.IsValid(), IsTrue()); EXPECT_THAT(executor.Execute(TestInputs{50, 7}), IsOkAndHolds(57)); ASSERT_THAT(other_executor.IsValid(), IsFalse()); } TEST_F(ModelExecutorTest, MissingInputs) { ASSERT_OK_AND_ASSIGN(auto x_plus_y, CallOp("math.add", {Leaf("unknown_x"), Leaf("unknown_y")})); ASSERT_OK_AND_ASSIGN(auto input_loader, CreateTestInputLoader()); EXPECT_THAT( (ModelExecutor<TestInputs, int64_t>::Compile(x_plus_y, *input_loader)), StatusIs(absl::StatusCode::kInvalidArgument, "unknown inputs: unknown_x, unknown_y (available: x, y)")); } TEST_F(ModelExecutorTest, SimpleExpr) { ASSERT_OK_AND_ASSIGN(auto x_plus_y, CallOp("math.add", {Leaf("x"), Leaf("y")})); ASSERT_OK_AND_ASSIGN(auto input_loader, CreateTestInputLoader()); ModelExecutorOptions options; options.allow_output_casting = true; EXPECT_THAT( (ModelExecutor<TestInputs, Bytes>::Compile(x_plus_y, *input_loader, nullptr, options)), StatusIs( absl::StatusCode::kInvalidArgument, AllOf(HasSubstr("casting from INT64 to BYTES is not allowed"), HasSubstr( "while casting model outputs due to `AllowOutputCasting()` " "or `AllowSideOutputsCasting()` options")))); { ASSERT_OK_AND_ASSIGN( auto executor, (ModelExecutor<TestInputs, int64_t>::Compile(x_plus_y, *input_loader))); EXPECT_THAT(executor.Execute(TestInputs{5, 7}), IsOkAndHolds(12)); } { ASSERT_OK_AND_ASSIGN( auto executor, (ModelExecutor<TestInputs, int64_t>::Compile(x_plus_y, *input_loader))); EXPECT_THAT(executor.ExecuteOnHeap({}, TestInputs{5, 7}), IsOkAndHolds(12)); } { ASSERT_OK_AND_ASSIGN( auto executor, (ModelExecutor<TestInputs, int64_t>::Compile(x_plus_y, *input_loader))); EXPECT_FALSE(executor.CanExecuteOnStack(8)); EXPECT_TRUE(executor.CanExecuteOnStack(24)); EXPECT_THAT(executor.ExecuteOnStack<24>({}, TestInputs{5, 7}), IsOkAndHolds(12)); } { ASSERT_OK_AND_ASSIGN(auto executor, (CompileModelExecutor<int64_t>( x_plus_y, *input_loader))); EXPECT_THAT(executor.Execute(TestInputs{5, 7}), IsOkAndHolds(12)); } { ASSERT_OK_AND_ASSIGN(auto executor, (ModelExecutor<TestInputs, TypedValue>::Compile( x_plus_y, *input_loader))); EXPECT_THAT(executor.Execute(TestInputs{5, 7}), IsOkAndHolds(TypedValueWith<int64_t>(12))); } { ModelExecutorOptions options; options.allow_output_casting = true; ASSERT_OK_AND_ASSIGN( auto executor, (ModelExecutor<TestInputs, OptionalValue<int64_t>>::Compile( x_plus_y, *input_loader, nullptr, options))); EXPECT_THAT(executor.Execute(TestInputs{5, 7}), IsOkAndHolds(OptionalValue<int64_t>(12))); } { ModelExecutorOptions options; EXPECT_THAT( (ModelExecutor<TestInputs, OptionalValue<int64_t>>::Compile( x_plus_y, *input_loader, nullptr, options)), StatusIs( absl::StatusCode::kInvalidArgument, HasSubstr("output casting is not allowed: INT64 -> OPTIONAL_INT64; " "to fix add explicit `AllowOutputCasting()` in model " "compiler"))); } } TEST_F(ModelExecutorTest, ReturnsStdOptional) { ASSERT_OK_AND_ASSIGN(auto input_loader, CreateTestInputLoader()); { ASSERT_OK_AND_ASSIGN(auto optional_x, CallOp("core.to_optional", {Leaf("x")})); ASSERT_OK_AND_ASSIGN( (ModelExecutor<TestInputs, std::optional<int64_t>> executor), CompileModelExecutor<std::optional<int64_t>>(optional_x, *input_loader)); EXPECT_THAT(executor.Execute(TestInputs{5, 7}), IsOkAndHolds(Eq(5))); } { ASSERT_OK_AND_ASSIGN(auto empty_like_x, CallOp("core.empty_like", {Leaf("x")})); ASSERT_OK_AND_ASSIGN( (ModelExecutor<TestInputs, std::optional<int64_t>> executor), CompileModelExecutor<std::optional<int64_t>>(empty_like_x, *input_loader)); EXPECT_THAT(executor.Execute(TestInputs{5, 7}), IsOkAndHolds(Eq(std::nullopt))); } } TEST_F(ModelExecutorTest, ReturnsStdVectorOfOptional) { ASSERT_OK_AND_ASSIGN( auto input_loader, CreateAccessorsInputLoader<TestInputs>( "x", [](const TestInputs& in) { return CreateDenseArray<int64_t>({0, in.x, std::nullopt}); }, "y", [](const TestInputs& in) { return CreateDenseArray<int64_t>({0, in.y, std::nullopt}); })); ASSERT_OK_AND_ASSIGN(auto x_mul_y, CallOp("math.multiply", {Leaf("x"), Leaf("y")})); ASSERT_OK_AND_ASSIGN( (ModelExecutor<TestInputs, std::vector<std::optional<int64_t>>> executor), CompileModelExecutor<std::vector<std::optional<int64_t>>>(x_mul_y, *input_loader)); EXPECT_THAT(executor.Execute(TestInputs{3, 19}), IsOkAndHolds(ElementsAre(0, 57, std::nullopt))); } TEST_F(ModelExecutorTest, ReturnsStdVector) { ASSERT_OK_AND_ASSIGN( auto input_loader, CreateAccessorsInputLoader<TestInputs>("x", [](const TestInputs& in) { return CreateDenseArray<int64_t>({in.x, in.y, in.optional_z}); })); ASSERT_OK_AND_ASSIGN(auto x_mul_x, CallOp("math.multiply", {Leaf("x"), Leaf("x")})); EXPECT_THAT( (CompileModelExecutor<std::vector<int64_t>>(x_mul_x, *input_loader)), StatusIs(absl::StatusCode::kFailedPrecondition, HasSubstr("non-optional std::vector model output is supported " "only with ForceNonOptionalOutput() setting"))); ModelExecutorOptions options; options.force_non_optional_output = true; ASSERT_OK_AND_ASSIGN( (ModelExecutor<TestInputs, std::vector<int64_t>> executor), CompileModelExecutor<std::vector<int64_t>>(x_mul_x, *input_loader, options)); EXPECT_THAT(executor.Execute(TestInputs{1, 0, std::nullopt}), StatusIs(absl::StatusCode::kFailedPrecondition, "non-full model output (element 2 is missing) while " "full std::vector output is requested")); EXPECT_THAT(executor.Execute(TestInputs{1, 0, 16}), IsOkAndHolds(ElementsAre(1, 0, 256))); } class MockOperatorDirectory : public OperatorDirectory { public: MockOperatorDirectory() { ON_CALL(*this, DoLookupOperator) .WillByDefault([](absl::string_view name, absl::Span<const QTypePtr> input_types, QTypePtr output_type) { return OperatorRegistry::GetInstance()->LookupOperator( name, input_types, output_type); }); } MOCK_METHOD(absl::StatusOr<OperatorPtr>, DoLookupOperator, (absl::string_view name, absl::Span<const QTypePtr> input_types, QTypePtr output_type), (const, override)); }; TEST_F(ModelExecutorTest, OptionsPropagatedToCasting) { ASSERT_OK_AND_ASSIGN(auto x_plus_y, CallOp("math.add", {Leaf("x"), Leaf("y")})); ASSERT_OK_AND_ASSIGN(auto input_loader, CreateTestInputLoader()); MockOperatorDirectory operator_directory; ModelExecutorOptions options; options.allow_output_casting = true; options.eval_options.operator_directory = &operator_directory; EXPECT_CALL(operator_directory, DoLookupOperator(_, _, _)).Times(AnyNumber()); EXPECT_CALL(operator_directory, DoLookupOperator("core.to_optional._scalar", _, _)) .Times(AtLeast(1)); ASSERT_OK_AND_ASSIGN( auto executor, (ModelExecutor<TestInputs, OptionalValue<int64_t>>::Compile( x_plus_y, *input_loader, nullptr, options))); EXPECT_THAT(executor.Execute(TestInputs{5, 7}), IsOkAndHolds(OptionalValue<int64_t>(12))); } TEST_F(ModelExecutorTest, ExternalBufferFactory) { ASSERT_OK_AND_ASSIGN( auto expr, CallOp("array.as_dense_array", {CallOp("core.make_tuple", {Leaf("x"), Leaf("y")})})); ASSERT_OK_AND_ASSIGN(auto input_loader, CreateTestInputLoader()); ASSERT_OK_AND_ASSIGN(auto executor, (ModelExecutor<TestInputs, DenseArray<int64_t>>::Compile( expr, *input_loader))); UnsafeArenaBufferFactory arena(64 << 10); auto [buf1, data1] = arena.CreateRawBuffer(8); auto [buf2, data2] = arena.CreateRawBuffer(8); ASSERT_OK_AND_ASSIGN( DenseArray<int64_t> res, executor.Execute({.buffer_factory = &arena}, TestInputs{5, 7})); auto [buf3, data3] = arena.CreateRawBuffer(8); EXPECT_NE(reinterpret_cast<char*>(data2) - reinterpret_cast<char*>(data1), reinterpret_cast<char*>(data3) - reinterpret_cast<char*>(data2)); EXPECT_TRUE(res.is_owned()); } TEST_F(ModelExecutorTest, ReturnsNonOptional) { ASSERT_OK_AND_ASSIGN( auto input_loader, CreateAccessorsInputLoader<TestInputs>( "y", [](const TestInputs& in) { return OptionalValue<int64_t>(in.y); }, "z", [](const TestInputs& in) { return OptionalValue<int64_t>(in.optional_z); })); ASSERT_OK_AND_ASSIGN(auto y_mul_z, CallOp("math.multiply", {Leaf("y"), Leaf("z")})); EXPECT_THAT((CompileModelExecutor<int64_t>(y_mul_z, *input_loader)), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("model output is deduced to optional, while " "non-optional is requested"))); ModelExecutorOptions options; options.force_non_optional_output = true; ASSERT_OK_AND_ASSIGN( (ModelExecutor<TestInputs, int64_t> executor), CompileModelExecutor<int64_t>(y_mul_z, *input_loader, options)); EXPECT_THAT(executor.Execute(TestInputs{1, 0, std::nullopt}), StatusIs(absl::StatusCode::kFailedPrecondition, "expects a present value, got missing")); EXPECT_THAT(executor.Execute(TestInputs{1, 2, 3}), IsOkAndHolds(6)); EXPECT_THAT( (CompileModelExecutor<TypedValue>(y_mul_z, *input_loader, options)), StatusIs(absl::StatusCode::kUnimplemented, HasSubstr("ForceNonOptionalOutput() is not supported for " "TypedValue outputs"))); } TEST_F(ModelExecutorTest, ReturnsStdVectorBytes) { ASSERT_OK_AND_ASSIGN( auto input_loader, CreateAccessorsInputLoader<TestInputs>( "x", [](const TestInputs& in) { return CreateDenseArray<Bytes>( {Bytes{"foo"}, Bytes{absl::StrCat(in.x)}, std::nullopt}); }, "y", [](const TestInputs& in) { return CreateDenseArray<Bytes>( {Bytes{"bar"}, Bytes{absl::StrCat(in.y)}, std::nullopt}); })); ASSERT_OK_AND_ASSIGN(auto x_plus_y, CallOp("strings.join", {Leaf("x"), Leaf("y")})); ASSERT_OK_AND_ASSIGN( (ModelExecutor<TestInputs, std::vector<std::optional<Bytes>>> executor), CompileModelExecutor<std::vector<std::optional<Bytes>>>(x_plus_y, *input_loader)); EXPECT_THAT( executor.Execute(TestInputs{5, 7}), IsOkAndHolds(ElementsAre(Bytes{"foobar"}, Bytes{"57"}, std::nullopt))); EXPECT_THAT( executor.ExecuteOnHeap({}, TestInputs{5, 7}), IsOkAndHolds(ElementsAre(Bytes{"foobar"}, Bytes{"57"}, std::nullopt))); EXPECT_TRUE(executor.CanExecuteOnStack(1024)); EXPECT_THAT( executor.ExecuteOnStack<1024>({}, TestInputs{5, 7}), IsOkAndHolds(ElementsAre(Bytes{"foobar"}, Bytes{"57"}, std::nullopt))); } TEST_F(ModelExecutorTest, SimpleExprBind) { ASSERT_OK_AND_ASSIGN(auto x_plus_y, CallOp("math.add", {Leaf("x"), Leaf("y")})); ASSERT_OK_AND_ASSIGN(auto input_loader, CreateTestInputLoader()); ASSERT_OK_AND_ASSIGN( auto output_types, GetInputLoaderQTypes(*input_loader, GetLeafKeys(x_plus_y))); ASSERT_OK_AND_ASSIGN(auto compiled_expr, CompileForDynamicEvaluation( DynamicEvaluationEngineOptions(), x_plus_y, output_types)); { ASSERT_OK_AND_ASSIGN(auto executor, (ModelExecutor<TestInputs, int64_t>::Bind( *compiled_expr, *input_loader))); EXPECT_THAT(executor.Execute(TestInputs{5, 7}), IsOkAndHolds(12)); } { ASSERT_OK_AND_ASSIGN(auto executor, BindModelExecutor<int64_t>( *compiled_expr, *input_loader)); EXPECT_THAT(executor.Execute(TestInputs{5, 7}), IsOkAndHolds(12)); } { ASSERT_OK_AND_ASSIGN(auto executor, BindModelExecutor<int64_t>( *compiled_expr, *input_loader)); EXPECT_THAT(executor.Execute(TestInputs{5, 7}), IsOkAndHolds(12)); } { ModelExecutorOptions options; options.allow_output_casting = true; ASSERT_OK_AND_ASSIGN(auto executor, BindModelExecutor<OptionalValue<int64_t>>( *compiled_expr, *input_loader, options)); EXPECT_THAT(executor.Execute(TestInputs{5, 7}), IsOkAndHolds(12)); } } struct SideOutput { OptionalValue<int64_t> out_x; OptionalValue<int64_t> out_xpy; }; template <class OutXT, class OutYT> struct TestSlotListener : public SlotListener<SideOutput> { TestSlotListener() = default; explicit TestSlotListener( absl::flat_hash_map<std::string, QTypePtr> input_types) : input_types(std::move(input_types)) {} absl::Nullable<const QType*> GetQTypeOf( absl::string_view name, const QType* desired_qtype) const final { auto it = input_types.find(name); if (it == input_types.end()) { return nullptr; } return it->second == GetUnspecifiedQType() ? desired_qtype : it->second; } std::vector<std::string> SuggestAvailableNames() const final { std::vector<std::string> names; names.reserve(input_types.size()); for (const auto& [name, _] : input_types) { names.emplace_back(name); } std::sort(names.begin(), names.end()); return names; } absl::StatusOr<BoundSlotListener<SideOutput>> BindImpl( const absl::flat_hash_map<std::string, TypedSlot>& input_slots) const final { return [input_slots](::arolla::ConstFramePtr frame, SideOutput* output) -> absl::Status { if (input_slots.contains("out_x")) { ASSIGN_OR_RETURN(auto slot, input_slots.at("out_x").ToSlot<OutXT>()); output->out_x = frame.Get(slot); } if (input_slots.contains("out_xpy")) { ASSIGN_OR_RETURN(auto slot, input_slots.at("out_xpy").ToSlot<OutYT>()); output->out_xpy = frame.Get(slot); } return absl::OkStatus(); }; } absl::flat_hash_map<std::string, QTypePtr> input_types = { {"out_x", GetQType<OutXT>()}, {"out_xpy", GetQType<OutYT>()}}; }; TEST_F(ModelExecutorTest, SimpleExprWithSlotListener) { ASSERT_OK_AND_ASSIGN(auto x, WithExportAnnotation(Leaf("x"), "out_x")); auto y = Leaf("y"); ASSERT_OK_AND_ASSIGN( auto x_plus_y, WithExportAnnotation(CallOp("math.add", {x, y}), "out_xpy")); ASSERT_OK_AND_ASSIGN(auto expr, CallOp("math.add", {x_plus_y, y})); ASSERT_OK_AND_ASSIGN(auto input_loader, CreateTestInputLoader()); TestSlotListener<int64_t, int64_t> slot_listener; { SideOutput side_output; ASSERT_OK_AND_ASSIGN( auto executor, (ModelExecutor<TestInputs, int64_t, SideOutput>::Compile( expr, *input_loader))); EXPECT_THAT(executor.Execute(TestInputs{5, 7}, &side_output), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("slot listener was not provided"))); } { TestSlotListener<int64_t, int64_t> wrong_slot_listener{ {{"out_x", GetQType<int64_t>()}, {"out_xpy", GetQType<::arolla::Bytes>()}}}; EXPECT_THAT( CompileModelExecutor<int64_t>(expr, *input_loader, wrong_slot_listener), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("casting from INT64 to BYTES is not allowed"))); } { SideOutput side_output; ASSERT_OK_AND_ASSIGN( auto executor, (ModelExecutor<TestInputs, int64_t, SideOutput>::Compile( expr, *input_loader, &slot_listener))); EXPECT_THAT(executor.Execute(TestInputs{5, 7}, &side_output), IsOkAndHolds(19)); EXPECT_EQ(side_output.out_x.value, 5); EXPECT_EQ(side_output.out_xpy.value, 12); EXPECT_THAT(executor.Execute(TestInputs{5, 7}, nullptr), IsOkAndHolds(19)); } { SideOutput side_output; ASSERT_OK_AND_ASSIGN( auto executor, (ModelExecutor<TestInputs, int64_t, SideOutput>::Compile( expr, *input_loader, &slot_listener))); EXPECT_THAT(executor.ExecuteOnHeap({}, TestInputs{5, 7}, &side_output), IsOkAndHolds(19)); EXPECT_EQ(side_output.out_x.value, 5); EXPECT_EQ(side_output.out_xpy.value, 12); EXPECT_THAT(executor.ExecuteOnHeap({}, TestInputs{5, 7}, nullptr), IsOkAndHolds(19)); } { SideOutput side_output; ASSERT_OK_AND_ASSIGN( auto executor, (ModelExecutor<TestInputs, int64_t, SideOutput>::Compile( expr, *input_loader, &slot_listener))); EXPECT_FALSE(executor.CanExecuteOnStack(8)); EXPECT_TRUE(executor.CanExecuteOnStack(64)); EXPECT_THAT(executor.ExecuteOnStack<64>({}, TestInputs{5, 7}, &side_output), IsOkAndHolds(19)); EXPECT_EQ(side_output.out_x.value, 5); EXPECT_EQ(side_output.out_xpy.value, 12); EXPECT_THAT(executor.ExecuteOnStack<64>({}, TestInputs{5, 7}, nullptr), IsOkAndHolds(19)); } { SideOutput side_output; ASSERT_OK_AND_ASSIGN( auto executor, (CompileModelExecutor<int64_t>(expr, *input_loader, slot_listener))); EXPECT_THAT(executor.Execute(TestInputs{5, 7}, &side_output), IsOkAndHolds(19)); EXPECT_EQ(side_output.out_x.value, 5); EXPECT_EQ(side_output.out_xpy.value, 12); } { TestSlotListener<OptionalValue<int64_t>, OptionalValue<int64_t>> optional_slot_listener; SideOutput side_output; ASSERT_OK_AND_ASSIGN( auto executor, (CompileModelExecutor<int64_t>(expr, *input_loader, optional_slot_listener))); EXPECT_THAT(executor.Execute(TestInputs{5, 7}, &side_output), IsOkAndHolds(19)); EXPECT_EQ(side_output.out_x.value, 5); EXPECT_EQ(side_output.out_xpy.value, 12); } { TestSlotListener<int64_t, int64_t> slot_listener{ {{"out_x", GetQType<int64_t>()}, {"out_xpy", GetUnspecifiedQType()}}}; SideOutput side_output; ASSERT_OK_AND_ASSIGN( auto executor, (CompileModelExecutor<int64_t>(expr, *input_loader, slot_listener))); EXPECT_THAT(executor.Execute(TestInputs{5, 7}, &side_output), IsOkAndHolds(19)); EXPECT_EQ(side_output.out_x.value, 5); EXPECT_EQ(side_output.out_xpy.value, 12); } { TestSlotListener<OptionalValue<int64_t>, OptionalValue<int64_t>> optional_slot_listener; ASSERT_OK_AND_ASSIGN(auto int32_loader, CreateTestInt32InputLoader()); SideOutput side_output; ASSERT_OK_AND_ASSIGN(auto executor, (CompileModelExecutor<int>(expr, *int32_loader, optional_slot_listener))); EXPECT_THAT(executor.Execute(TestInputs{5, 7}, &side_output), IsOkAndHolds(19)); EXPECT_EQ(side_output.out_x.value, 5); EXPECT_EQ(side_output.out_xpy.value, 12); } { TestSlotListener<int64_t, int64_t> limited_slot_listener{ {{"out_xpy", GetQType<int64_t>()}}}; SideOutput side_output; ModelExecutorOptions options; options.ignore_not_listened_named_outputs = true; ASSERT_OK_AND_ASSIGN(auto executor, (CompileModelExecutor<int64_t>( expr, *input_loader, limited_slot_listener, options))); EXPECT_THAT(executor.Execute(TestInputs{5, 7}, &side_output), IsOkAndHolds(19)); EXPECT_EQ(side_output.out_x, std::nullopt); EXPECT_EQ(side_output.out_xpy.value, 12); } } TEST_F(ModelExecutorTest, SimpleExprBindWithSlotListener) { ASSERT_OK_AND_ASSIGN(auto x, WithExportAnnotation(Leaf("x"), "out_x")); auto y = Leaf("y"); ASSERT_OK_AND_ASSIGN( auto x_plus_y, WithExportAnnotation(CallOp("math.add", {x, y}), "out_xpy")); ASSERT_OK_AND_ASSIGN(auto expr, CallOp("math.add", {x_plus_y, y})); ASSERT_OK_AND_ASSIGN(auto input_loader, CreateTestInputLoader()); TestSlotListener<int64_t, int64_t> slot_listener; ASSERT_OK_AND_ASSIGN((auto [stripped_expr, side_outputs]), ExtractSideOutputs(expr)); ASSERT_OK_AND_ASSIGN( auto output_types, GetInputLoaderQTypes(*input_loader, GetLeafKeys(x_plus_y))); ASSERT_OK_AND_ASSIGN(auto compiled_expr, CompileForDynamicEvaluation( DynamicEvaluationEngineOptions(), stripped_expr, output_types, {})); ASSERT_OK_AND_ASSIGN( auto compiled_expr_with_side_output, CompileForDynamicEvaluation(DynamicEvaluationEngineOptions(), stripped_expr, output_types, side_outputs)); { SideOutput side_output; ASSERT_OK_AND_ASSIGN( auto executor, (ModelExecutor<TestInputs, int64_t, SideOutput>::Bind( *compiled_expr, *input_loader, nullptr, &slot_listener))); EXPECT_THAT(executor.Execute(TestInputs{5, 7}, &side_output), IsOkAndHolds(19)); EXPECT_FALSE(side_output.out_x.present); EXPECT_FALSE(side_output.out_xpy.present); } { SideOutput side_output; ASSERT_OK_AND_ASSIGN( auto executor, (ModelExecutor<TestInputs, int64_t, SideOutput>::Bind( *compiled_expr_with_side_output, *input_loader, nullptr, &slot_listener))); EXPECT_THAT(executor.Execute(TestInputs{5, 7}, &side_output), IsOkAndHolds(19)); EXPECT_EQ(side_output.out_x.value, 5); EXPECT_EQ(side_output.out_xpy.value, 12); } { SideOutput side_output; ASSERT_OK_AND_ASSIGN( auto executor, (ModelExecutor<TestInputs, int64_t, SideOutput>::Bind( *compiled_expr, *input_loader, compiled_expr_with_side_output.get(), &slot_listener))); EXPECT_THAT(executor.Execute(TestInputs{5, 7}, &side_output), IsOkAndHolds(19)); EXPECT_EQ(side_output.out_x.value, 5); EXPECT_EQ(side_output.out_xpy.value, 12); } { SideOutput side_output; ASSERT_OK_AND_ASSIGN(auto executor, BindModelExecutor<int64_t>( *compiled_expr_with_side_output, *input_loader, slot_listener)); EXPECT_THAT(executor.Execute(TestInputs{5, 7}, &side_output), IsOkAndHolds(19)); EXPECT_EQ(side_output.out_x, int64_t{5}); EXPECT_EQ(side_output.out_xpy, int64_t{12}); } { TestSlotListener<OptionalValue<int64_t>, OptionalValue<int64_t>> optional_slot_listener; SideOutput side_output; ModelExecutorOptions options; options.allow_side_outputs_casting = true; ASSERT_OK_AND_ASSIGN(auto executor, (BindModelExecutor<int64_t>( *compiled_expr_with_side_output, *input_loader, optional_slot_listener, options))); EXPECT_THAT(executor.Execute(TestInputs{5, 7}, &side_output), IsOkAndHolds(19)); EXPECT_EQ(side_output.out_x, int64_t{5}); EXPECT_EQ(side_output.out_xpy, int64_t{12}); } { TestSlotListener<OptionalValue<int64_t>, OptionalValue<int64_t>> irrelevant_slot_listener( {{"foo", GetOptionalQType<int64_t>()}, {"bar", GetOptionalQType<int64_t>()}}); ModelExecutorOptions options; options.ignore_not_listened_named_outputs = false; EXPECT_THAT( (ModelExecutor<TestInputs, int64_t, SideOutput>::Bind( *compiled_expr_with_side_output, *input_loader, nullptr, &irrelevant_slot_listener, options)), StatusIs(absl::StatusCode::kFailedPrecondition, HasSubstr( "slot listener does not listen for named outputs {out_x, " "out_xpy} (it listens to {bar, foo});"))); EXPECT_THAT( (ModelExecutor<TestInputs, int64_t, SideOutput>::Bind( *compiled_expr, *input_loader, compiled_expr_with_side_output.get(), &irrelevant_slot_listener, options)), StatusIs(absl::StatusCode::kFailedPrecondition, HasSubstr( "slot listener does not listen for named outputs {out_x, " "out_xpy} (it listens to {bar, foo});"))); options.ignore_not_listened_named_outputs = true; EXPECT_THAT( (ModelExecutor<TestInputs, int64_t, SideOutput>::Bind( *compiled_expr_with_side_output, *input_loader, nullptr, &irrelevant_slot_listener, options)), IsOk()); EXPECT_THAT((ModelExecutor<TestInputs, int64_t, SideOutput>::Bind( *compiled_expr, *input_loader, compiled_expr_with_side_output.get(), &irrelevant_slot_listener, options)), IsOk()); } { TestSlotListener<OptionalValue<int64_t>, OptionalValue<int64_t>> optional_slot_listener; EXPECT_THAT( (BindModelExecutor<int64_t>(*compiled_expr_with_side_output, *input_loader, optional_slot_listener)), StatusIs( absl::StatusCode::kInvalidArgument,
2,481
#ifndef AROLLA_SERIALIZATION_CONTAINER_PROTO_H_ #define AROLLA_SERIALIZATION_CONTAINER_PROTO_H_ #include <cstdint> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "arolla/serialization_base/base.pb.h" #include "arolla/serialization_base/container.h" namespace arolla::serialization_base { class ContainerProtoBuilder final : public ContainerBuilder { public: static constexpr int kContainerProtoVersion = 1; absl::StatusOr<uint64_t> Add(DecodingStepProto&& decoding_step_proto) final; ContainerProto Finish() &&; private: ContainerProto result_; }; absl::Status ProcessContainerProto(const ContainerProto& container_proto, ContainerProcessor& container_processor); } #endif #include "arolla/serialization_base/container_proto.h" #include <cstdint> #include <utility> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "arolla/serialization_base/base.pb.h" #include "arolla/serialization_base/container.h" #include "arolla/util/status_macros_backport.h" namespace arolla::serialization_base { absl::StatusOr<uint64_t> ContainerProtoBuilder::Add( DecodingStepProto&& decoding_step_proto) { switch (decoding_step_proto.type_case()) { case DecodingStepProto::kCodec: *result_.add_codecs() = std::move(*decoding_step_proto.mutable_codec()); return result_.codecs_size() - 1; case DecodingStepProto::kOutputValueIndex: result_.add_output_value_indices( decoding_step_proto.output_value_index()); return result_.output_value_indices_size() - 1; case DecodingStepProto::kOutputExprIndex: result_.add_output_expr_indices(decoding_step_proto.output_expr_index()); return result_.output_expr_indices_size() - 1; default: *result_.add_decoding_steps() = std::move(decoding_step_proto); return result_.decoding_steps_size() - 1; } } ContainerProto ContainerProtoBuilder::Finish() && { result_.set_version(kContainerProtoVersion); return std::move(result_); } absl::Status ProcessContainerProto(const ContainerProto& container_proto, ContainerProcessor& container_processor) { constexpr int kContainerProtoOldVersion = 1; constexpr int kContainerProtoNewVersion = 2; if (!container_proto.has_version()) { return absl::InvalidArgumentError("missing container.version"); } if (container_proto.version() != kContainerProtoOldVersion && container_proto.version() != kContainerProtoNewVersion) { return absl::InvalidArgumentError( absl::StrFormat("expected container.version to be %d or %d, got %d", kContainerProtoOldVersion, kContainerProtoNewVersion, container_proto.version())); } DecodingStepProto decoding_step; for (int codec_index = 0; codec_index < container_proto.codecs_size(); ++codec_index) { *decoding_step.mutable_codec() = container_proto.codecs(codec_index); RETURN_IF_ERROR( container_processor.OnDecodingStep(codec_index, decoding_step)) << "while handling codecs[" << codec_index << "]"; } for (int decoding_step_index = 0; decoding_step_index < container_proto.decoding_steps_size(); ++decoding_step_index) { RETURN_IF_ERROR(container_processor.OnDecodingStep( decoding_step_index, container_proto.decoding_steps(decoding_step_index))) << "while handling decoding_steps[" << decoding_step_index << "]"; } for (int i = 0; i < container_proto.output_value_indices_size(); ++i) { decoding_step.set_output_value_index( container_proto.output_value_indices(i)); RETURN_IF_ERROR(container_processor.OnDecodingStep(0, decoding_step)) << "while handling output_value_indices[" << i << "]"; } for (int i = 0; i < container_proto.output_expr_indices_size(); ++i) { decoding_step.set_output_expr_index(container_proto.output_expr_indices(i)); RETURN_IF_ERROR(container_processor.OnDecodingStep(0, decoding_step)) << "while handling output_expr_indices[" << i << "]"; } return absl::OkStatus(); } }
#include "arolla/serialization_base/container_proto.h" #include <cstdint> #include <utility> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "arolla/serialization_base/base.pb.h" #include "arolla/serialization_base/container.h" #include "arolla/util/testing/equals_proto.h" #include "arolla/util/testing/status_matchers_backport.h" namespace arolla::serialization_base { namespace { using ::arolla::testing::EqualsProto; using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::StatusIs; using ::testing::HasSubstr; using ::testing::InSequence; using ::testing::Return; TEST(ContainerProtoBuilderTest, TrivialBehaviour) { ContainerProtoBuilder container_builder; { DecodingStepProto decoding_step_proto; decoding_step_proto.mutable_codec()->set_name("codec1"); ASSERT_THAT(container_builder.Add(std::move(decoding_step_proto)), IsOkAndHolds(0)); } { DecodingStepProto decoding_step_proto; decoding_step_proto.mutable_leaf_node()->set_leaf_key("key1"); ASSERT_THAT(container_builder.Add(std::move(decoding_step_proto)), IsOkAndHolds(0)); } { DecodingStepProto decoding_step_proto; decoding_step_proto.set_output_expr_index(0); ASSERT_THAT(container_builder.Add(std::move(decoding_step_proto)), IsOkAndHolds(0)); } { DecodingStepProto decoding_step_proto; decoding_step_proto.mutable_codec()->set_name("codec2"); ASSERT_THAT(container_builder.Add(std::move(decoding_step_proto)), IsOkAndHolds(1)); } { DecodingStepProto decoding_step_proto; decoding_step_proto.mutable_placeholder_node()->set_placeholder_key("key2"); ASSERT_THAT(container_builder.Add(std::move(decoding_step_proto)), IsOkAndHolds(1)); } { DecodingStepProto decoding_step_proto; decoding_step_proto.mutable_value(); ASSERT_THAT(container_builder.Add(std::move(decoding_step_proto)), IsOkAndHolds(2)); } { DecodingStepProto decoding_step_proto; decoding_step_proto.set_output_expr_index(1); ASSERT_THAT(container_builder.Add(std::move(decoding_step_proto)), IsOkAndHolds(1)); } { DecodingStepProto decoding_step_proto; decoding_step_proto.set_output_value_index(2); ASSERT_THAT(container_builder.Add(std::move(decoding_step_proto)), IsOkAndHolds(0)); } EXPECT_TRUE(EqualsProto( std::move(container_builder).Finish(), R"pb( version: 1 codecs { name: "codec1" } codecs { name: "codec2" } decoding_steps { leaf_node { leaf_key: "key1" } } decoding_steps { placeholder_node { placeholder_key: "key2" } } decoding_steps { value {} } output_value_indices: [ 2 ] output_expr_indices: [ 0, 1 ] )pb")); } class MockContainerProcessor : public ContainerProcessor { public: MOCK_METHOD(absl::Status, OnDecodingStep, (uint64_t, const DecodingStepProto& decoding_step_proto), (override)); }; TEST(ProcessContainerProto, TrivialBehaviour) { ContainerProto container_proto; container_proto.set_version(1); container_proto.add_codecs()->set_name("codec1"); container_proto.add_codecs()->set_name("codec2"); container_proto.add_decoding_steps()->mutable_leaf_node()->set_leaf_key( "key1"); container_proto.add_decoding_steps() ->mutable_placeholder_node() ->set_placeholder_key("key2"); container_proto.add_decoding_steps()->mutable_value(); container_proto.add_output_value_indices(2); container_proto.add_output_expr_indices(0); container_proto.add_output_expr_indices(1); MockContainerProcessor mock_container_processor; { InSequence seq; EXPECT_CALL( mock_container_processor, OnDecodingStep(0, EqualsProto(R"pb(codec: { name: "codec1" })pb"))); EXPECT_CALL( mock_container_processor, OnDecodingStep(1, EqualsProto(R"pb(codec: { name: "codec2" })pb"))); EXPECT_CALL(mock_container_processor, OnDecodingStep( 0, EqualsProto(R"pb(leaf_node: { leaf_key: "key1" })pb"))); EXPECT_CALL(mock_container_processor, OnDecodingStep(1, EqualsProto(R"pb(placeholder_node: { placeholder_key: "key2" })pb"))); EXPECT_CALL(mock_container_processor, OnDecodingStep(2, EqualsProto(R"pb(value: {})pb"))); EXPECT_CALL(mock_container_processor, OnDecodingStep(0, EqualsProto(R"pb(output_value_index: 2)pb"))); EXPECT_CALL(mock_container_processor, OnDecodingStep(0, EqualsProto(R"pb(output_expr_index: 0)pb"))); EXPECT_CALL(mock_container_processor, OnDecodingStep(0, EqualsProto(R"pb(output_expr_index: 1)pb"))); } EXPECT_OK(ProcessContainerProto(container_proto, mock_container_processor)); } TEST(ProcessContainerProto, MissingContainerVersion) { ContainerProto container_proto; MockContainerProcessor mock_container_processor; EXPECT_THAT(ProcessContainerProto(container_proto, mock_container_processor), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("missing container.version"))); } TEST(ProcessContainerProto, WrongContainerVersion) { ContainerProto container_proto; container_proto.set_version(100); MockContainerProcessor mock_container_processor; EXPECT_THAT( ProcessContainerProto(container_proto, mock_container_processor), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("expected container.version to be 1 or 2, got 100"))); } TEST(ProcessContainerProto, ProcessorFailureOnCodec) { ContainerProto container_proto; container_proto.set_version(1); container_proto.add_codecs()->set_name("codec1"); container_proto.add_codecs()->set_name("codec2"); MockContainerProcessor mock_container_processor; { InSequence seq; EXPECT_CALL( mock_container_processor, OnDecodingStep(0, EqualsProto(R"pb(codec: { name: "codec1" })pb"))); EXPECT_CALL( mock_container_processor, OnDecodingStep(1, EqualsProto(R"pb(codec: { name: "codec2" })pb"))) .WillOnce(Return(absl::FailedPreconditionError("stop"))); } EXPECT_THAT(ProcessContainerProto(container_proto, mock_container_processor), StatusIs(absl::StatusCode::kFailedPrecondition, HasSubstr("stop; while handling codecs[1]"))); } TEST(ProcessContainerProto, ProcessorFailureOnDecodingStep) { ContainerProto container_proto; container_proto.set_version(1); container_proto.add_decoding_steps()->mutable_leaf_node()->set_leaf_key( "key1"); container_proto.add_decoding_steps()->mutable_value(); MockContainerProcessor mock_container_processor; { InSequence seq; EXPECT_CALL(mock_container_processor, OnDecodingStep( 0, EqualsProto(R"pb(leaf_node: { leaf_key: "key1" })pb"))); EXPECT_CALL(mock_container_processor, OnDecodingStep(1, EqualsProto(R"pb(value {})pb"))) .WillOnce(Return(absl::FailedPreconditionError("stop"))); } EXPECT_THAT(ProcessContainerProto(container_proto, mock_container_processor), StatusIs(absl::StatusCode::kFailedPrecondition, HasSubstr("stop; while handling decoding_steps[1]"))); } TEST(ProcessContainerProto, ProcessorFailureOnOutputValueIndex) { ContainerProto container_proto; container_proto.set_version(1); container_proto.add_output_value_indices(1); MockContainerProcessor mock_container_processor; EXPECT_CALL(mock_container_processor, OnDecodingStep(0, EqualsProto(R"pb(output_value_index: 1)pb"))) .WillOnce(Return(absl::FailedPreconditionError("stop"))); EXPECT_THAT( ProcessContainerProto(container_proto, mock_container_processor), StatusIs(absl::StatusCode::kFailedPrecondition, HasSubstr("stop; while handling output_value_indices[0]"))); } TEST(ProcessContainerProto, ProcessorFailureOnOutputExprIndex) { ContainerProto container_proto; container_proto.set_version(1); container_proto.add_output_expr_indices(2); MockContainerProcessor mock_container_processor; EXPECT_CALL(mock_container_processor, OnDecodingStep(0, EqualsProto(R"pb(output_expr_index: 2)pb"))) .WillOnce(Return(absl::FailedPreconditionError("stop"))); EXPECT_THAT( ProcessContainerProto(container_proto, mock_container_processor), StatusIs(absl::StatusCode::kFailedPrecondition, HasSubstr("stop; while handling output_expr_indices[0]"))); } } }
2,482
#ifndef AROLLA_UTIL_UNIT_H_ #define AROLLA_UTIL_UNIT_H_ #include <variant> #include "arolla/util/fingerprint.h" #include "arolla/util/repr.h" namespace arolla { using Unit = std::monostate; constexpr Unit kUnit = Unit(); AROLLA_DECLARE_REPR(Unit); AROLLA_DECLARE_FINGERPRINT_HASHER_TRAITS(Unit); } #endif #include "arolla/util/unit.h" #include "absl/strings/string_view.h" #include "arolla/util/fingerprint.h" #include "arolla/util/repr.h" namespace arolla { ReprToken ReprTraits<Unit>::operator()(const Unit&) const { return ReprToken{"unit"}; } void FingerprintHasherTraits<Unit>::operator()(FingerprintHasher* hasher, const Unit& value) const { hasher->Combine(absl::string_view("unit")); } }
#include "arolla/util/unit.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "arolla/util/repr.h" #include "arolla/util/testing/repr_token_eq.h" namespace arolla { namespace { using ::arolla::testing::ReprTokenEq; TEST(UnitTest, Repr) { EXPECT_THAT(GenReprToken(kUnit), ReprTokenEq("unit")); } } }
2,483
#ifndef AROLLA_UTIL_BITS_H_ #define AROLLA_UTIL_BITS_H_ #include <bitset> #include <climits> #include <cstddef> #include "absl/log/check.h" namespace arolla { template <typename T> constexpr int CountLeadingZeros(T n); template <> constexpr int CountLeadingZeros(unsigned int n) { return __builtin_clz(n); } template <> constexpr int CountLeadingZeros(unsigned long n) { return __builtin_clzl(n); } template <> constexpr int CountLeadingZeros(unsigned long long n) { return __builtin_clzll(n); } template <typename T> constexpr int BitScanReverse(T n) { return 8 * sizeof(n) - 1 - CountLeadingZeros<T>(n); } template <typename Word> inline int FindLSBSetNonZero(Word n); template <> inline int FindLSBSetNonZero(unsigned int n) { return __builtin_ctz(n); } template <> inline int FindLSBSetNonZero(unsigned long n) { return __builtin_ctzl(n); } template <> inline int FindLSBSetNonZero(unsigned long long n) { return __builtin_ctzll(n); } template <typename Word> class Bits { public: static constexpr unsigned Log2(unsigned n, unsigned p = 0) { return (n <= 1) ? p : Log2(n / 2, p + 1); } static constexpr size_t kIntBits = CHAR_BIT * sizeof(Word); static constexpr int kLogIntBits = Log2(kIntBits, 0); static bool GetBit(const Word* map, size_t index) { return std::bitset<kIntBits>(map[index / kIntBits])[index & (kIntBits - 1)]; } static void SetBit(Word* map, size_t index) { map[index / kIntBits] |= (Word{1} << (index & (kIntBits - 1))); } static void SetBitsInRange(Word* bitmap, size_t start, size_t end) { DCHECK_LE(start, end); if (start == end) { return; } size_t start_word = start / kIntBits; size_t end_word = (end - 1) / kIntBits; Word* p = bitmap + start_word; Word ones = ~Word{0}; Word start_mask = ones << (start & (kIntBits - 1)); Word end_mask = ones >> ((end_word + 1) * kIntBits - end); if (end_word == start_word) { *p = *p | (start_mask & end_mask); } else { *p = *p | start_mask; for (++p; p < bitmap + end_word; ++p) { *p = ones; } *p = *p | end_mask; } } static size_t CountOnes(Word word) { return std::bitset<kIntBits>(word).count(); } static size_t GetOnesCountInRange(const Word* bitmap, size_t start, size_t end) { DCHECK_LE(start, end); if (start == end) { return 0; } size_t start_word = start / kIntBits; size_t end_word = (end - 1) / kIntBits; const Word* p = bitmap + start_word; Word c = (*p & (~Word{0} << (start & (kIntBits - 1)))); Word endmask = (~Word{0} >> ((end_word + 1) * kIntBits - end)); if (end_word == start_word) { return CountOnes(c & endmask); } size_t sum = CountOnes(c); for (++p; p < bitmap + end_word; ++p) { sum += CountOnes(*p); } return sum + CountOnes(*p & endmask); } static size_t FindNextSetBitInVector(const Word* words, size_t bit_index, size_t limit) { if (bit_index >= limit) return limit; size_t int_index = bit_index >> kLogIntBits; Word one_word = words[int_index]; const size_t first_bit_offset = bit_index & (kIntBits - 1); if (one_word & (Word{1} << first_bit_offset)) return bit_index; one_word &= (~Word{0} << first_bit_offset); const size_t last_int_index = (limit - 1) >> kLogIntBits; while (int_index < last_int_index) { if (one_word != Word{0}) { return (int_index << kLogIntBits) + FindLSBSetNonZero(one_word); } one_word = words[++int_index]; } one_word &= ~((~Word{0} - 1) << ((limit - 1) & (kIntBits - 1))); if (one_word != 0) { return (int_index << kLogIntBits) + FindLSBSetNonZero(one_word); } return limit; } }; template <typename Word> inline bool GetBit(const Word* map, size_t index) { return Bits<Word>::GetBit(map, index); } template <typename Word> inline void SetBit(Word* map, size_t index) { Bits<Word>::SetBit(map, index); } template <typename Word> inline void SetBitsInRange(Word* bitmap, size_t start, size_t end) { Bits<Word>::SetBitsInRange(bitmap, start, end); } template <typename Word> inline size_t CountOnes(Word word) { return Bits<Word>::CountOnes(word); } template <typename Word> inline size_t GetOnesCountInRange(const Word* bitmap, size_t start, size_t end) { return Bits<Word>::GetOnesCountInRange(bitmap, start, end); } template <typename Word> inline size_t FindNextSetBitInVector(const Word* words, size_t bit_index, size_t bit_limit) { return Bits<Word>::FindNextSetBitInVector(words, bit_index, bit_limit); } } #endif
#include "arolla/util/bits.h" #include <array> #include <cstdint> #include "gmock/gmock.h" #include "gtest/gtest.h" namespace arolla { namespace { using ::testing::Eq; TEST(Bits, CountLeadingZeros_UInt32) { EXPECT_EQ(31, CountLeadingZeros(static_cast<uint32_t>(1))); EXPECT_EQ(15, CountLeadingZeros(static_cast<uint32_t>(1) << 16)); EXPECT_EQ(0, CountLeadingZeros(static_cast<uint32_t>(1) << 31)); } TEST(Bits, CountLeadingZeros_UInt64) { EXPECT_EQ(63, CountLeadingZeros(static_cast<uint64_t>(1))); EXPECT_EQ(31, CountLeadingZeros(static_cast<uint64_t>(1) << 32)); EXPECT_EQ(0, CountLeadingZeros(static_cast<uint64_t>(1) << 63)); } TEST(Bits, BitScanReverse) { EXPECT_EQ(BitScanReverse(1U), 0); EXPECT_EQ(BitScanReverse(2U), 1); EXPECT_EQ(BitScanReverse(3141U), 11); } TEST(Bits, FindLSBSetNonZero) { EXPECT_THAT(FindLSBSetNonZero<uint32_t>(0x80000000), Eq(31)); EXPECT_THAT(FindLSBSetNonZero<uint32_t>(0x80000001), Eq(0)); } TEST(Bits, GetBit) { std::array<uint32_t, 3> bitmap = {0x00000001, 0x0000ffff, 0x55555555}; EXPECT_TRUE(GetBit(bitmap.data(), 0)); EXPECT_TRUE(GetBit(bitmap.data(), 32)); EXPECT_TRUE(GetBit(bitmap.data(), 64)); EXPECT_FALSE(GetBit(bitmap.data(), 31)); EXPECT_FALSE(GetBit(bitmap.data(), 63)); EXPECT_FALSE(GetBit(bitmap.data(), 95)); } TEST(Bits, SetBit) { std::array<uint32_t, 3> bitmap = {0x00000001, 0x0000ffff, 0x55555555}; SetBit(bitmap.data(), 31); EXPECT_THAT(bitmap[0], Eq(0x80000001)); SetBit(bitmap.data(), 63); EXPECT_THAT(bitmap[1], Eq(0x8000ffff)); SetBit(bitmap.data(), 95); EXPECT_THAT(bitmap[2], Eq(0xd5555555)); } TEST(Bits, SetBitsInRange) { std::array<uint32_t, 5> bitmap = {0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000}; SetBitsInRange(bitmap.data(), 0, 1); SetBitsInRange(bitmap.data(), 8, 16); SetBitsInRange(bitmap.data(), 31, 32); SetBitsInRange(bitmap.data(), 32, 32); SetBitsInRange(bitmap.data(), 48, 80); SetBitsInRange(bitmap.data(), 96, 128); EXPECT_EQ(bitmap[0], 0x8000ff01); EXPECT_EQ(bitmap[1], 0xffff0000); EXPECT_EQ(bitmap[2], 0x0000ffff); EXPECT_EQ(bitmap[3], 0xffffffff); EXPECT_EQ(bitmap[4], 0x00000000); } TEST(Bits, CountOnesInRange) { std::array<uint32_t, 4> bitmap = {0x55555555, 0x55555555, 0x55555555, 0x55555555}; EXPECT_THAT(GetOnesCountInRange(bitmap.data(), 0, 128), Eq(64)); EXPECT_THAT(GetOnesCountInRange(bitmap.data(), 40, 80), Eq(20)); } TEST(Bits, FindNextSetBitInVector) { std::array<uint32_t, 3> bitmap = { 0x00000000, 0x00ff00ff, 0x55550001}; EXPECT_THAT(FindNextSetBitInVector(bitmap.data(), 0, 80), Eq(32)); EXPECT_THAT(FindNextSetBitInVector(bitmap.data(), 32, 80), Eq(32)); EXPECT_THAT(FindNextSetBitInVector(bitmap.data(), 40, 80), Eq(48)); EXPECT_THAT(FindNextSetBitInVector(bitmap.data(), 56, 80), Eq(64)); EXPECT_THAT(FindNextSetBitInVector(bitmap.data(), 65, 80), Eq(80)); } } }
2,484
#ifndef AROLLA_UTIL_STRING_H_ #define AROLLA_UTIL_STRING_H_ #include <cstddef> #include <string> #include "absl/strings/escaping.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" namespace arolla { constexpr bool IsAlpha(char c) { return ('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z'); } constexpr bool IsDigit(char c) { return '0' <= c && c <= '9'; } constexpr bool IsAlnum(char c) { return IsAlpha(c) || IsDigit(c); } constexpr bool IsIdentifier(absl::string_view str) { if (str.empty()) { return false; } if (str[0] != '_' && !IsAlpha(str[0])) { return false; } for (size_t i = 1; i < str.size(); ++i) { if (str[i] != '_' && !IsAlnum(str[i])) { return false; } } return true; } constexpr bool IsQualifiedIdentifier(absl::string_view str) { bool fail_flag = false; bool ends_with_token_flag = false; for (char ch : str) { if (ends_with_token_flag) { if (ch == '.') { ends_with_token_flag = false; } else if (ch != '_' && !IsAlnum(ch)) { fail_flag = true; } } else { if (ch != '_' && !IsAlpha(ch)) { fail_flag = true; } ends_with_token_flag = true; } } return !fail_flag && ends_with_token_flag; } constexpr absl::string_view NonFirstComma(bool& is_first_call, absl::string_view delimiter = ", ") { return (is_first_call ? (is_first_call = false, "") : delimiter); } std::string Truncate(std::string str, size_t max_length); inline std::string ContainerAccessString(absl::string_view key) { if (IsIdentifier(key)) { return absl::StrCat(".", key); } else { return absl::StrCat("['", absl::Utf8SafeCHexEscape(key), "']"); } } } #endif #include "arolla/util/string.h" #include <cstddef> #include <string> #include "absl/log/check.h" namespace arolla { std::string Truncate(std::string str, size_t max_length) { DCHECK_GT(max_length, 3); if (str.size() > max_length) { str.resize(max_length); str.replace(max_length - 3, 3, "..."); } return str; } }
#include "arolla/util/string.h" #include "gmock/gmock.h" #include "gtest/gtest.h" namespace arolla { namespace { using ::testing::Eq; TEST(StringTest, Truncate) { EXPECT_THAT(Truncate("", 7), Eq("")); EXPECT_THAT(Truncate("fifty seven", 7), Eq("fift...")); EXPECT_THAT(Truncate("fifty seven", 10), Eq("fifty s...")); EXPECT_THAT(Truncate("fifty seven", 11), Eq("fifty seven")); EXPECT_THAT(Truncate("fifty seven", 20), Eq("fifty seven")); } TEST(StringTest, IsQualifiedIdentifier) { static_assert(IsQualifiedIdentifier("foo")); static_assert(!IsQualifiedIdentifier(".bar")); static_assert(!IsQualifiedIdentifier("0.bar")); static_assert(!IsQualifiedIdentifier("9.bar")); static_assert(!IsQualifiedIdentifier("-.bar")); static_assert(IsQualifiedIdentifier("_.bar")); static_assert(IsQualifiedIdentifier("A.bar")); static_assert(IsQualifiedIdentifier("Z.bar")); static_assert(IsQualifiedIdentifier("a.bar")); static_assert(IsQualifiedIdentifier("z.bar")); static_assert(IsQualifiedIdentifier("_0.bar")); static_assert(IsQualifiedIdentifier("_9.bar")); static_assert(!IsQualifiedIdentifier("_-.bar")); static_assert(IsQualifiedIdentifier("__.bar")); static_assert(IsQualifiedIdentifier("_A.bar")); static_assert(IsQualifiedIdentifier("_Z.bar")); static_assert(IsQualifiedIdentifier("_a.bar")); static_assert(IsQualifiedIdentifier("_z.bar")); static_assert(!IsQualifiedIdentifier("foo..bar")); static_assert(!IsQualifiedIdentifier("foo.0.bar")); static_assert(!IsQualifiedIdentifier("foo.9.bar")); static_assert(!IsQualifiedIdentifier("foo.-.bar")); static_assert(IsQualifiedIdentifier("foo._.bar")); static_assert(IsQualifiedIdentifier("foo.A.bar")); static_assert(IsQualifiedIdentifier("foo.Z.bar")); static_assert(IsQualifiedIdentifier("foo.a.bar")); static_assert(IsQualifiedIdentifier("foo.z.bar")); static_assert(IsQualifiedIdentifier("foo._0.bar")); static_assert(IsQualifiedIdentifier("foo._9.bar")); static_assert(!IsQualifiedIdentifier("foo._-.bar")); static_assert(IsQualifiedIdentifier("foo.__.bar")); static_assert(IsQualifiedIdentifier("foo._A.bar")); static_assert(IsQualifiedIdentifier("foo._Z.bar")); static_assert(IsQualifiedIdentifier("foo._a.bar")); static_assert(IsQualifiedIdentifier("foo._z.bar")); static_assert(!IsQualifiedIdentifier("foo.bar.")); static_assert(IsQualifiedIdentifier("test.add")); static_assert(IsQualifiedIdentifier("test.subtest.add")); } TEST(StringTest, NonFirstComma) { bool first_call = true; EXPECT_EQ(NonFirstComma(first_call), ""); EXPECT_FALSE(first_call); EXPECT_EQ(NonFirstComma(first_call), ", "); EXPECT_FALSE(first_call); } TEST(StringTest, ContainerAccessString) { EXPECT_EQ(ContainerAccessString("bar"), ".bar"); EXPECT_EQ(ContainerAccessString("bar.baz"), "['bar.baz']"); EXPECT_EQ(ContainerAccessString(""), "['']"); } } }
2,485
#ifndef AROLLA_UTIL_DEMANGLE_H_ #define AROLLA_UTIL_DEMANGLE_H_ #include <string> #include <typeinfo> namespace arolla { std::string TypeName(const std::type_info& ti); template <class T> std::string TypeName() { return TypeName(typeid(T)); } } #undef AROLLA_HAS_CXA_DEMANGLE #endif #include "arolla/util/demangle.h" #include <cstdlib> #include <string> #include <typeinfo> #include "arolla/util/bytes.h" #if defined(__GXX_RTTI) #define AROLLA_HAS_CXA_DEMANGLE #endif #ifdef AROLLA_HAS_CXA_DEMANGLE #include <cxxabi.h> #endif namespace arolla { std::string TypeName(const std::type_info& ti) { if (ti == typeid(arolla::Bytes)) { return "arolla::Bytes"; } int status = 0; char* demangled = nullptr; #ifdef AROLLA_HAS_CXA_DEMANGLE demangled = abi::__cxa_demangle(ti.name(), nullptr, nullptr, &status); #endif if (status == 0 && demangled != nullptr) { std::string out = demangled; free(demangled); return out; } else { return ti.name(); } } }
#include "arolla/util/demangle.h" #include <cstdint> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" namespace arolla { namespace { using ::testing::Eq; using ::testing::MatchesRegex; TEST(DemangleTest, TypeName) { EXPECT_THAT(TypeName<int>(), Eq("int")); EXPECT_THAT(TypeName<int32_t>(), Eq("int")); EXPECT_THAT(TypeName<std::vector<int>>(), MatchesRegex("std::.*vector.*")); } } }
2,486