Repo
stringclasses 14
values | Code
stringlengths 131
31.4k
| Unit Test - (Ground Truth)
stringlengths 40
32.1k
|
|---|---|---|
arolla
|
#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));
}
}
}
|
arolla
|
#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>()})));
}
}
}
}
|
arolla
|
#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());
}
}
}
}
|
arolla
|
#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;
}
}
}
}
|
arolla
|
#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{}}));
}
}
}
|
arolla
|
#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")));
}
}
}
|
arolla
|
#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);
}
}
}
|
arolla
|
#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));
}
}
}
|
arolla
|
#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")));
}
}
}
|
arolla
|
#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";
}
}
}
}
}
}
|
arolla
|
#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)"));
}
}
}
|
arolla
|
#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
}
}
|
arolla
|
#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);
}
}
}
|
arolla
|
#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);
}
}
}
|
arolla
|
#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", ""));
}
}
}
|
arolla
|
#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"));
}
}
}
|
arolla
|
#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));
}
}
}
|
arolla
|
#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);
}
}
}
|
arolla
|
#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());
}
}
}
|
arolla
|
#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);
}
}
|
arolla
|
#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\\')')"));
}
}
}
|
arolla
|
#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>())));
}
}
}
|
arolla
|
#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);
}
}
}
|
arolla
|
#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)));
}
}
}
|
arolla
|
#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));
}
}
}
|
arolla
|
#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)));
}
}
}
}
|
arolla
|
#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));
}
}
}
|
arolla
|
#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)));
}
}
}
}
|
arolla
|
#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)}))));
}
}
}
|
arolla
|
#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));
}
}
}
|
arolla
|
#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(""));
}
}
}
|
arolla
|
#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}), "");
}
}
}
|
arolla
|
#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
|
arolla
|
#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));
}
}
}
|
arolla
|
#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));
}
}
}
}
}
}
|
arolla
|
#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}};
}()));
}
}
|
arolla
|
#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)")));
}
}
}
|
arolla
|
#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));
}
}
}
|
arolla
|
#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")));
}
}
}
|
arolla
|
#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")));
}
}
}
}
|
arolla
|
#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));
}
}
}
|
arolla
|
#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)}))));
}
}
}
|
arolla
|
#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))));
}
}
}
}
|
arolla
|
#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());
}
}
}
}
|
arolla
|
#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));
}
}
}
|
arolla
|
#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());
}
}
}
|
arolla
|
#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)));
}
}
}
|
arolla
|
#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`")));
}
}
}
|
arolla
|
#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")})))))));
}
}
}
}
|
arolla
|
#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)));
}
}
}
|
arolla
|
#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"));
}
}
}
|
arolla
|
#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)));
}
}
}
}
|
arolla
|
#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);
}
}
}
|
arolla
|
#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})))));
}
}
}
|
arolla
|
#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));
}
}
}
|
arolla
|
#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));
}
}
}
}
|
arolla
|
#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}));
}
}
}
|
arolla
|
#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)));
}
}
}
}
|
arolla
|
#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));
}
}
}
}
|
arolla
|
#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")));
}
}
}
|
arolla
|
#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)]")));
}
}
}
|
arolla
|
#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}")));
}
}
}
|
arolla
|
#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>"));
}
}
}
|
arolla
|
#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.")));
}
}
}
|
arolla
|
#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"));
}
}
}
|
arolla
|
#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)));
}
}
|
arolla
|
#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());
}
}
}
}
|
arolla
|
#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']>"));
}
}
|
arolla
|
#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)));
}
}
}
|
arolla
|
#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);
}
}
|
arolla
|
#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"));
}
}
}
|
arolla
|
#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);
}
}
}
|
arolla
|
#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"));
}
}
}
|
arolla
|
#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,
|
arolla
|
#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)));
}
}
}
|
arolla
|
#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)));
}
}
}
}
|
arolla
|
#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.*")));
}
}
}
|
arolla
|
#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")));
}
}
}
|
arolla
|
#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])")));
}
}
}
|
arolla
|
#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")));
}
}
}
|
arolla
|
#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"));
}
}
}
|
arolla
|
#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,
|
arolla
|
#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]")));
}
}
}
|
arolla
|
#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")); }
}
}
|
arolla
|
#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));
}
}
}
|
arolla
|
#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(""), "['']");
}
}
}
|
arolla
|
#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.*"));
}
}
}
|
arolla
|
#ifndef AROLLA_UTIL_TEXT_H_
#define AROLLA_UTIL_TEXT_H_
#include <ostream>
#include <string>
#include <utility>
#include "absl/strings/cord.h"
#include "absl/strings/string_view.h"
#include "arolla/util/fingerprint.h"
#include "arolla/util/repr.h"
namespace arolla {
class Text {
public:
Text() = default;
explicit Text(const char* s) : data_(s) {}
explicit Text(absl::string_view view) : data_(view) {}
explicit Text(const std::string& s) : data_(s) {}
explicit Text(std::string&& s) : data_(std::move(s)) {}
explicit Text(const absl::Cord& cord) : data_(std::move(cord)) {}
Text& operator=(const char* s) {
data_ = s;
return *this;
}
Text& operator=(absl::string_view s) {
data_.assign(s.data(), s.size());
return *this;
}
Text& operator=(const std::string& s) {
data_ = s;
return *this;
}
Text& operator=(std::string&& s) {
data_ = std::move(s);
return *this;
}
Text& operator=(const absl::Cord& cord) {
data_ = std::string(cord);
return *this;
}
absl::string_view view() const { return data_; }
operator absl::string_view() const {
return data_;
}
friend bool operator==(const Text& lhs, const Text& rhs) {
return lhs.data_ == rhs.data_;
}
friend bool operator==(const char* lhs, const Text& rhs) {
return lhs == rhs.data_;
}
friend bool operator==(const Text& lhs, const char* rhs) {
return lhs.data_ == rhs;
}
friend bool operator!=(const Text& lhs, const Text& rhs) {
return !(lhs == rhs);
}
friend bool operator<(const Text& lhs, const Text& rhs) {
return lhs.data_ < rhs.data_;
}
friend bool operator<=(const Text& lhs, const Text& rhs) {
return lhs.data_ <= rhs.data_;
}
friend bool operator>(const Text& lhs, const Text& rhs) {
return lhs.data_ > rhs.data_;
}
friend bool operator>=(const Text& lhs, const Text& rhs) {
return lhs.data_ >= rhs.data_;
}
private:
std::string data_;
};
inline std::ostream& operator<<(std::ostream& stream, const Text& value) {
return stream << "Text{" << value.view() << "}";
}
AROLLA_DECLARE_REPR(Text);
AROLLA_DECLARE_FINGERPRINT_HASHER_TRAITS(Text);
}
#endif
#include "arolla/util/text.h"
#include <cstddef>
#include <string>
#include "absl/strings/escaping.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
#include "arolla/util/fingerprint.h"
#include "arolla/util/repr.h"
namespace arolla {
namespace {
absl::string_view Utf8CopyFirstNCodePoints(size_t n, absl::string_view data) {
size_t offset = 0;
for (; n > 0 && offset < data.size(); --n) {
const auto byte = data[offset];
if ((byte & 0x80) == 0) {
offset += 1;
} else if ((byte & 0xe0) == 0xc0) {
offset += 2;
} else if ((byte & 0xf0) == 0xe0) {
offset += 3;
} else if ((byte & 0xf8) == 0xf0) {
offset += 4;
} else {
offset += 1;
}
}
return data.substr(0, offset);
}
}
ReprToken ReprTraits<Text>::operator()(const Text& value) const {
constexpr size_t kTextAbbrevLimit = 120;
ReprToken result;
auto text = value.view();
auto prefix = Utf8CopyFirstNCodePoints(kTextAbbrevLimit, text);
if (prefix.size() == text.size()) {
result.str = absl::StrCat("'", absl::Utf8SafeCHexEscape(text), "'");
} else {
result.str = absl::StrCat("'", absl::Utf8SafeCHexEscape(prefix),
"... (TEXT of ", text.size(), " bytes total)'");
}
return result;
}
void FingerprintHasherTraits<Text>::operator()(FingerprintHasher* hasher,
const Text& value) const {
hasher->Combine(value.view());
}
}
|
#include "arolla/util/text.h"
#include <string>
#include <type_traits>
#include <utility>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/strings/cord.h"
#include "absl/strings/string_view.h"
#include "arolla/util/repr.h"
#include "arolla/util/testing/repr_token_eq.h"
namespace arolla {
namespace {
using ::arolla::testing::ReprTokenEq;
using ::testing::Eq;
using ::testing::MatchesRegex;
TEST(TextTest, Constructor) {
EXPECT_THAT(Text("Hello").view(), Eq("Hello"));
std::string hello = "Hello";
EXPECT_THAT(Text(hello).view(), Eq("Hello"));
absl::string_view hello_view = hello;
EXPECT_THAT(Text(hello_view).view(), Eq("Hello"));
absl::Cord hello_cord(hello);
EXPECT_THAT(Text(hello_cord).view(), Eq("Hello"));
}
TEST(TextTest, CopyAndMoveConstructors) {
static_assert(std::is_nothrow_move_constructible<Text>::value);
Text src("Google");
Text copied(src);
EXPECT_THAT(copied, Eq(src));
Text moved(std::move(src));
EXPECT_THAT(moved, Eq(copied));
}
TEST(TextTest, CopyAndMoveAssignment) {
static_assert(std::is_nothrow_move_assignable<Text>::value);
Text src("Google");
Text copied = src;
EXPECT_THAT(copied, Eq(src));
Text moved = std::move(src);
EXPECT_THAT(moved, Eq(copied));
}
TEST(TextTest, AssignmentFromString) {
std::string google = "Google";
{
Text val("x");
val = "Google";
EXPECT_THAT(val.view(), Eq(google));
}
{
Text val("x");
val = google;
EXPECT_THAT(val.view(), Eq(google));
}
{
absl::string_view google_view = google;
Text val("x");
val = google_view;
EXPECT_THAT(val.view(), Eq("Google"));
}
{
absl::Cord google_cord(google);
Text val("x");
val = google_cord;
EXPECT_THAT(val.view(), Eq("Google"));
}
{
Text val("x");
val = std::move(google);
EXPECT_THAT(val.view(), Eq("Google"));
}
}
TEST(TextTest, Repr) {
EXPECT_THAT(
GenReprToken(
Text("\"\xe8\xb0\xb7\xe6\xad\x8c\" is Google\'s Chinese name\n")),
ReprTokenEq(
"'\\\"\xe8\xb0\xb7\xe6\xad\x8c\\\" is Google\\'s Chinese name\\n'"));
const std::string pattern =
"A"
"\xc3\x86"
"\xe0\xa0\x80"
"\xf0\x90\x80\x80";
std::string data = pattern;
for (int i = 0; i < 8; ++i) {
data += data;
}
EXPECT_THAT(Repr(Text(data)),
MatchesRegex("'(" + pattern +
"){30}[.]{3} \\(TEXT of 2560 bytes total\\)'"));
}
}
}
|
arolla
|
#ifndef AROLLA_UTIL_PREALLOCATED_BUFFERS_H_
#define AROLLA_UTIL_PREALLOCATED_BUFFERS_H_
#include <cstddef>
namespace arolla {
constexpr size_t kZeroInitializedBufferAlignment = 32;
constexpr size_t kZeroInitializedBufferSize = 16 * 1024;
const void* GetZeroInitializedBuffer();
}
#endif
#include "arolla/util/preallocated_buffers.h"
#include <cstring>
#include "arolla/util/memory.h"
namespace arolla {
namespace {
const void* CreateBuffer() {
auto alloc = AlignedAlloc(Alignment{kZeroInitializedBufferAlignment},
kZeroInitializedBufferSize);
std::memset(alloc.get(), 0, kZeroInitializedBufferSize);
return alloc.release();
}
}
const void* GetZeroInitializedBuffer() {
static const void* const kBuffer = CreateBuffer();
return kBuffer;
}
}
|
#include "arolla/util/preallocated_buffers.h"
#include <cstddef>
#include <cstdint>
#include "gtest/gtest.h"
#include "absl/types/span.h"
namespace arolla {
namespace {
template <typename T>
class ZeroInitializedBufferTest : public ::testing::Test {
public:
typedef T value_type;
};
using Types = testing::Types<char, int, float, int64_t, double, uint64_t>;
TYPED_TEST_SUITE(ZeroInitializedBufferTest, Types);
TYPED_TEST(ZeroInitializedBufferTest, TestAccess) {
using T = typename TestFixture::value_type;
static_assert(alignof(T) <= kZeroInitializedBufferAlignment);
size_t size = kZeroInitializedBufferSize / sizeof(T);
absl::Span<const T> data(static_cast<const T*>(GetZeroInitializedBuffer()),
size);
for (const T& v : data) {
ASSERT_EQ(v, 0);
}
}
}
}
|
arolla
|
#ifndef AROLLA_UTIL_BINARY_SEARCH_H_
#define AROLLA_UTIL_BINARY_SEARCH_H_
#include <cstddef>
#include <cstdint>
#include <optional>
#include "absl/base/attributes.h"
#include "absl/types/span.h"
namespace arolla {
size_t LowerBound(float value, absl::Span<const float> array);
size_t LowerBound(double value, absl::Span<const double> array);
size_t LowerBound(int32_t value, absl::Span<const int32_t> array);
size_t LowerBound(int64_t value, absl::Span<const int64_t> array);
size_t UpperBound(float value, absl::Span<const float> array);
size_t UpperBound(double value, absl::Span<const double> array);
size_t UpperBound(int32_t value, absl::Span<const int32_t> array);
size_t UpperBound(int64_t value, absl::Span<const int64_t> array);
template <typename T, typename Iter>
Iter GallopingLowerBound(Iter begin, Iter end, const T& value);
}
namespace arolla::binary_search_details {
constexpr size_t kSupremacySizeThreshold = 1'000'000;
template <typename T>
size_t LowerBound(T value, absl::Span<const T> array);
template <typename T>
size_t UpperBound(T value, absl::Span<const T> array);
template <typename T, typename Predicate>
inline ABSL_ATTRIBUTE_ALWAYS_INLINE std::optional<size_t> SmallLinearSearch(
absl::Span<const T> array, Predicate predicate) {
if (array.size() <= 2) {
if (array.empty() || predicate(array[0])) {
return 0;
} else if (array.size() == 1 || predicate(array[1])) {
return 1;
}
return 2;
}
return std::nullopt;
}
size_t UpperBoundImpl(float value, absl::Span<const float> array);
size_t UpperBoundImpl(double value, absl::Span<const double> array);
size_t UpperBoundImpl(int32_t value, absl::Span<const int32_t> array);
size_t UpperBoundImpl(int64_t value, absl::Span<const int64_t> array);
size_t LowerBoundImpl(float value, absl::Span<const float> array);
size_t LowerBoundImpl(double value, absl::Span<const double> array);
size_t LowerBoundImpl(int32_t value, absl::Span<const int32_t> array);
size_t LowerBoundImpl(int64_t value, absl::Span<const int64_t> array);
template <typename T>
inline ABSL_ATTRIBUTE_ALWAYS_INLINE size_t
LowerBound(T value, absl::Span<const T> array) {
if (auto result =
SmallLinearSearch(array, [value](T arg) { return !(arg < value); })) {
return *result;
}
return LowerBoundImpl(value, array);
}
template <typename T>
inline ABSL_ATTRIBUTE_ALWAYS_INLINE size_t
UpperBound(T value, absl::Span<const T> array) {
if (auto result =
SmallLinearSearch(array, [value](T arg) { return value < arg; })) {
return *result;
}
return UpperBoundImpl(value, array);
}
}
namespace arolla {
inline size_t LowerBound(float value, absl::Span<const float> array) {
return binary_search_details::LowerBound<float>(value, array);
}
inline size_t LowerBound(double value, absl::Span<const double> array) {
return binary_search_details::LowerBound<double>(value, array);
}
inline size_t LowerBound(int32_t value, absl::Span<const int32_t> array) {
return binary_search_details::LowerBound<int32_t>(value, array);
}
inline size_t LowerBound(int64_t value, absl::Span<const int64_t> array) {
return binary_search_details::LowerBound<int64_t>(value, array);
}
inline size_t UpperBound(float value, absl::Span<const float> array) {
return binary_search_details::UpperBound<float>(value, array);
}
inline size_t UpperBound(double value, absl::Span<const double> array) {
return binary_search_details::UpperBound<double>(value, array);
}
inline size_t UpperBound(int32_t value, absl::Span<const int32_t> array) {
return binary_search_details::UpperBound<int32_t>(value, array);
}
inline size_t UpperBound(int64_t value, absl::Span<const int64_t> array) {
return binary_search_details::UpperBound<int64_t>(value, array);
}
template <typename T, typename Iter>
Iter GallopingLowerBound(Iter begin, Iter end, const T& value) {
size_t i = 0;
size_t size = end - begin;
if (begin >= end || !(*begin < value)) {
return std::min<Iter>(begin, end);
}
size_t d = 1;
while (i + d < size && begin[i + d] < value) {
i += d;
d <<= 1;
}
while (d > 1) {
d >>= 1;
if (i + d < size && begin[i + d] < value) {
i += d;
}
}
return begin + i + 1;
}
}
#endif
#include "arolla/util/binary_search.h"
#include <cassert>
#include <cmath>
#include <cstddef>
#include <cstdint>
#include "absl/types/span.h"
#include "arolla/util/bits.h"
#include "arolla/util/switch_index.h"
namespace arolla::binary_search_details {
namespace {
template <size_t kArraySize, typename T, class Predicate>
size_t FastBinarySearchT(const T* const array, Predicate predicate) {
static_assert((kArraySize & (kArraySize + 1)) == 0);
size_t offset = 0;
for (size_t k = kArraySize; k > 0;) {
k >>= 1;
offset = (!predicate(array[offset + k]) ? offset + k + 1 : offset);
}
return offset;
}
template <typename T, typename Predicate>
size_t BinarySearchT(absl::Span<const T> array, Predicate predicate) {
assert(!array.empty());
const int log2_size = BitScanReverse(array.size());
return switch_index<8 * sizeof(size_t)>(
log2_size, [array, predicate](auto constexpr_log2_size) {
constexpr size_t size =
(1ULL << static_cast<int>(constexpr_log2_size)) - 1;
size_t offset = 0;
#if !defined(__clang__) && defined(__GNUC__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Warray-bounds"
#endif
offset = (!predicate(array[size]) ? array.size() - size : offset);
#if !defined(__clang__) && defined(__GNUC__)
#pragma GCC diagnostic pop
#endif
return offset +
FastBinarySearchT<size>(array.begin() + offset, predicate);
});
}
}
size_t LowerBoundImpl(float value, absl::Span<const float> array) {
return BinarySearchT(array, [value](auto arg) { return !(arg < value); });
}
size_t LowerBoundImpl(double value, absl::Span<const double> array) {
return BinarySearchT(array, [value](auto arg) { return !(arg < value); });
}
size_t LowerBoundImpl(int32_t value, absl::Span<const int32_t> array) {
return BinarySearchT(array, [value](auto arg) { return arg >= value; });
}
size_t LowerBoundImpl(int64_t value, absl::Span<const int64_t> array) {
return BinarySearchT(array, [value](auto arg) { return arg >= value; });
}
size_t UpperBoundImpl(float value, absl::Span<const float> array) {
if (std::isnan(value)) {
return array.size();
}
return BinarySearchT(array, [value](auto arg) { return !(arg <= value); });
}
size_t UpperBoundImpl(double value, absl::Span<const double> array) {
if (std::isnan(value)) {
return array.size();
}
return BinarySearchT(array, [value](auto arg) { return !(arg <= value); });
}
size_t UpperBoundImpl(int32_t value, absl::Span<const int32_t> array) {
return BinarySearchT(array, [value](auto arg) { return arg > value; });
}
size_t UpperBoundImpl(int64_t value, absl::Span<const int64_t> array) {
return BinarySearchT(array, [value](auto arg) { return arg > value; });
}
}
|
#include "arolla/util/binary_search.h"
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <limits>
#include <random>
#include <vector>
#include "gtest/gtest.h"
#include "absl/types/span.h"
namespace arolla {
namespace {
size_t StdLowerBound(float value, absl::Span<const float> array) {
return std::lower_bound(array.begin(), array.end(), value) - array.begin();
}
size_t StdLowerBound(double value, absl::Span<const double> array) {
return std::lower_bound(array.begin(), array.end(), value) - array.begin();
}
size_t StdLowerBound(int32_t value, absl::Span<const int32_t> array) {
return std::lower_bound(array.begin(), array.end(), value) - array.begin();
}
size_t StdLowerBound(int64_t value, absl::Span<const int64_t> array) {
return std::lower_bound(array.begin(), array.end(), value) - array.begin();
}
size_t RlGallopingLowerBound(float value, absl::Span<const float> array) {
return GallopingLowerBound(array.begin(), array.end(), value) - array.begin();
}
TEST(Algorithms, LowerBound_General) {
for (int n : {0, 1, 5, 7, 100, 1000}) {
std::vector<float> thresholds(n);
for (int i = 0; i < n; ++i) {
thresholds[i] = 2 * i + 1;
}
for (int i = 0; i < static_cast<int>(2 * thresholds.size()); ++i) {
size_t expected = StdLowerBound(i, thresholds);
ASSERT_EQ(LowerBound(i, thresholds), expected);
ASSERT_EQ(RlGallopingLowerBound(i, thresholds), expected);
}
ASSERT_EQ(LowerBound(-10 * n, thresholds),
StdLowerBound(-10 * n, thresholds));
ASSERT_EQ(LowerBound(10 * n, thresholds),
StdLowerBound(10 * n, thresholds));
}
}
TEST(Algorithms, LowerBound_Duplicates) {
for (int n : {2, 140}) {
std::vector<float> thresholds(n, 0.);
ASSERT_EQ(LowerBound(-1, thresholds), 0);
ASSERT_EQ(LowerBound(0., thresholds), 0);
ASSERT_EQ(LowerBound(1., thresholds), n);
ASSERT_EQ(RlGallopingLowerBound(-1, thresholds), 0);
ASSERT_EQ(RlGallopingLowerBound(0., thresholds), 0);
ASSERT_EQ(RlGallopingLowerBound(1., thresholds), n);
}
}
TEST(Algorithms, LowerBound_Infs) {
const auto kInf = std::numeric_limits<float>::infinity();
for (int n : {2, 140}) {
std::vector<float> thresholds(n);
for (int i = 0; i < n; ++i) {
thresholds.push_back(i);
}
thresholds.front() = -kInf;
thresholds.back() = kInf;
ASSERT_EQ(LowerBound(-kInf, thresholds), StdLowerBound(-kInf, thresholds));
ASSERT_EQ(LowerBound(kInf, thresholds), StdLowerBound(kInf, thresholds));
ASSERT_EQ(RlGallopingLowerBound(kInf, thresholds),
StdLowerBound(kInf, thresholds));
}
}
TEST(Algorithms, LowerBound_Nan) {
const auto kNan = std::numeric_limits<float>::quiet_NaN();
const auto kInf = std::numeric_limits<float>::infinity();
for (int n : {2, 140}) {
std::vector<float> thresholds;
for (int i = 0; i < n; ++i) {
thresholds.push_back(i);
}
thresholds.front() = -kInf;
thresholds.back() = kInf;
ASSERT_EQ(LowerBound(kNan, thresholds), StdLowerBound(kNan, thresholds));
ASSERT_EQ(RlGallopingLowerBound(kNan, thresholds),
StdLowerBound(kNan, thresholds));
}
}
size_t StdUpperBound(float value, absl::Span<const float> array) {
return std::upper_bound(array.begin(), array.end(), value) - array.begin();
}
size_t StdUpperBound(double value, absl::Span<const double> array) {
return std::upper_bound(array.begin(), array.end(), value) - array.begin();
}
size_t StdUpperBound(int32_t value, absl::Span<const int32_t> array) {
return std::upper_bound(array.begin(), array.end(), value) - array.begin();
}
size_t StdUpperBound(int64_t value, absl::Span<const int64_t> array) {
return std::upper_bound(array.begin(), array.end(), value) - array.begin();
}
TEST(Algorithms, UpperBound_General) {
for (int n : {0, 1, 5, 7, 100, 1000}) {
std::vector<float> thresholds(n);
for (int i = 0; i < n; ++i) {
thresholds[i] = 2 * i + 1;
}
for (int i = 0; i < static_cast<int>(2 * thresholds.size()); ++i) {
ASSERT_EQ(UpperBound(i, thresholds), StdUpperBound(i, thresholds));
}
ASSERT_EQ(UpperBound(-10 * n, thresholds),
StdUpperBound(-10 * n, thresholds));
ASSERT_EQ(UpperBound(10 * n, thresholds),
StdUpperBound(10 * n, thresholds));
}
}
TEST(Algorithms, UpperBound_Duplicates) {
for (int n : {2, 140}) {
std::vector<float> thresholds(n, 0.);
ASSERT_EQ(UpperBound(-1, thresholds), StdUpperBound(-1., thresholds));
ASSERT_EQ(UpperBound(0., thresholds), StdUpperBound(0., thresholds));
}
}
TEST(Algorithms, UpperBound_Infs) {
const auto kInf = std::numeric_limits<float>::infinity();
for (int n : {2, 140}) {
std::vector<float> thresholds(n);
for (int i = 0; i < n; ++i) {
thresholds.push_back(i);
}
thresholds.front() = -kInf;
thresholds.back() = kInf;
ASSERT_EQ(UpperBound(-kInf, thresholds), StdUpperBound(-kInf, thresholds));
ASSERT_EQ(UpperBound(kInf, thresholds), StdUpperBound(kInf, thresholds));
}
}
TEST(Algorithms, UpperBound_Nan) {
const auto kNan = std::numeric_limits<float>::quiet_NaN();
const auto kInf = std::numeric_limits<float>::infinity();
for (int n : {2, 140}) {
std::vector<float> thresholds;
for (int i = 0; i < n; ++i) {
thresholds.push_back(i);
}
thresholds.front() = -kInf;
thresholds.back() = kInf;
ASSERT_EQ(UpperBound(kNan, thresholds), StdUpperBound(kNan, thresholds));
}
}
template <typename T>
std::vector<T> RandomVector(size_t seed, size_t size) {
std::mt19937 gen(seed);
std::vector<T> result(size);
if constexpr (std::is_integral_v<T>) {
std::uniform_int_distribution<T> uniform(0, 1 << 30);
for (auto& x : result) {
x = uniform(gen);
}
} else {
std::uniform_real_distribution<T> uniform01;
for (auto& x : result) {
x = uniform01(gen);
}
}
return result;
}
template <typename T>
std::vector<T> Sorted(std::vector<T> vec) {
std::sort(vec.begin(), vec.end());
return vec;
}
template <typename T>
using AlgoFn = std::function<size_t(T, const std::vector<T>&)>;
template <typename T>
void BinarySearchStressTest(size_t size, AlgoFn<T> algoFn,
AlgoFn<T> referenceAlgoFn) {
const auto seed = 34 + size;
const auto array = Sorted(RandomVector<T>(seed, size));
for (auto value : RandomVector<T>(seed, 2 * size)) {
const auto actual_value = algoFn(value, array);
const auto expected_value = referenceAlgoFn(value, array);
if (actual_value != expected_value) {
ADD_FAILURE() << "Actual value: " << actual_value << '\n'
<< "Expected value: " << expected_value << '\n'
<< "size: " << size;
return;
}
}
}
TEST(Algorithms, LowerBound_Stress) {
for (int size : {10, 100, 1000, 100000}) {
BinarySearchStressTest<float>(
size,
[](float value, absl::Span<const float> array) {
return LowerBound(value, array);
},
[](float value, absl::Span<const float> array) {
return StdLowerBound(value, array);
});
BinarySearchStressTest<float>(
size,
[](float value, absl::Span<const float> array) {
return RlGallopingLowerBound(value, array);
},
[](float value, absl::Span<const float> array) {
return StdLowerBound(value, array);
});
BinarySearchStressTest<double>(
size,
[](double value, absl::Span<const double> array) {
return LowerBound(value, array);
},
[](double value, absl::Span<const double> array) {
return StdLowerBound(value, array);
});
BinarySearchStressTest<int32_t>(
size,
[](int32_t value, absl::Span<const int32_t> array) {
return LowerBound(value, array);
},
[](int32_t value, absl::Span<const int32_t> array) {
return StdLowerBound(value, array);
});
BinarySearchStressTest<int64_t>(
size,
[](int64_t value, absl::Span<const int64_t> array) {
return LowerBound(value, array);
},
[](int64_t value, absl::Span<const int64_t> array) {
return StdLowerBound(value, array);
});
}
}
TEST(Algorithms, UpperBound_Stress) {
for (int size : {10, 100, 1000, 100000}) {
BinarySearchStressTest<float>(
size,
[](float value, absl::Span<const float> array) {
return UpperBound(value, array);
},
[](float value, absl::Span<const float> array) {
return StdUpperBound(value, array);
});
BinarySearchStressTest<double>(
size,
[](double value, absl::Span<const double> array) {
return UpperBound(value, array);
},
[](double value, absl::Span<const double> array) {
return StdUpperBound(value, array);
});
BinarySearchStressTest<int32_t>(
size,
[](int32_t value, absl::Span<const int32_t> array) {
return UpperBound(value, array);
},
[](int32_t value, absl::Span<const int32_t> array) {
return StdUpperBound(value, array);
});
BinarySearchStressTest<int64_t>(
size,
[](int64_t value, absl::Span<const int64_t> array) {
return UpperBound(value, array);
},
[](int64_t value, absl::Span<const int64_t> array) {
return StdUpperBound(value, array);
});
}
}
}
}
|
arolla
|
#ifndef AROLLA_UTIL_ALGORITHMS_H_
#define AROLLA_UTIL_ALGORITHMS_H_
#include <algorithm>
#include <cstddef>
#include <iterator>
#include <limits>
#include <type_traits>
#include "absl/log/check.h"
namespace arolla {
template <class FwdIter, class T, class Compare>
inline FwdIter exp_lower_bound(FwdIter first, FwdIter last, const T& val,
Compare comp) {
typename std::iterator_traits<FwdIter>::difference_type count, step;
count = std::distance(first, last);
step = 1;
FwdIter it = first;
while (step < count) {
if (comp(*it, val)) {
first = ++it;
count -= step;
std::advance(it, step);
step *= 2;
} else {
last = it;
break;
}
}
return std::lower_bound(first, last, val, comp);
}
template <class FwdIter, class T>
inline FwdIter exp_lower_bound(FwdIter first, FwdIter last, const T& val) {
using T1 = typename std::iterator_traits<FwdIter>::value_type;
return exp_lower_bound(first, last, val,
[](const T1& a, const T& b) { return a < b; });
}
template <typename Word>
inline void LogicalAnd(const Word* src1, const Word* src2, Word* result,
size_t word_count) {
const size_t e = (word_count / 8) * 8;
for (size_t i = 0; i < e; i += 8) {
result[i] = src1[i] & src2[i];
result[i + 1] = src1[i + 1] & src2[i + 1];
result[i + 2] = src1[i + 2] & src2[i + 2];
result[i + 3] = src1[i + 3] & src2[i + 3];
result[i + 4] = src1[i + 4] & src2[i + 4];
result[i + 5] = src1[i + 5] & src2[i + 5];
result[i + 6] = src1[i + 6] & src2[i + 6];
result[i + 7] = src1[i + 7] & src2[i + 7];
}
switch (word_count - e) {
case 7:
result[e + 6] = src1[e + 6] & src2[e + 6];
[[fallthrough]];
case 6:
result[e + 5] = src1[e + 5] & src2[e + 5];
[[fallthrough]];
case 5:
result[e + 4] = src1[e + 4] & src2[e + 4];
[[fallthrough]];
case 4:
result[e + 3] = src1[e + 3] & src2[e + 3];
[[fallthrough]];
case 3:
result[e + 2] = src1[e + 2] & src2[e + 2];
[[fallthrough]];
case 2:
result[e + 1] = src1[e + 1] & src2[e + 1];
[[fallthrough]];
case 1:
result[e] = src1[e] & src2[e];
}
}
template <typename Word>
inline void InPlaceLogicalAnd(const Word* src, Word* dest, size_t word_count) {
const size_t e = (word_count / 8) * 8;
for (size_t i = 0; i < e; i += 8) {
dest[i] &= src[i];
dest[i + 1] &= src[i + 1];
dest[i + 2] &= src[i + 2];
dest[i + 3] &= src[i + 3];
dest[i + 4] &= src[i + 4];
dest[i + 5] &= src[i + 5];
dest[i + 6] &= src[i + 6];
dest[i + 7] &= src[i + 7];
}
switch (word_count - e) {
case 7:
dest[e + 6] &= src[e + 6];
[[fallthrough]];
case 6:
dest[e + 5] &= src[e + 5];
[[fallthrough]];
case 5:
dest[e + 4] &= src[e + 4];
[[fallthrough]];
case 4:
dest[e + 3] &= src[e + 3];
[[fallthrough]];
case 3:
dest[e + 2] &= src[e + 2];
[[fallthrough]];
case 2:
dest[e + 1] &= src[e + 1];
[[fallthrough]];
case 1:
dest[e] &= src[e];
}
}
template <typename Word>
void InplaceLogicalAndWithOffsets(
size_t bitmaps_size,
const Word* rhs,
int rhs_skip,
Word* lhs,
int lhs_skip)
{
static_assert(std::is_unsigned<Word>::value);
static constexpr int bits_per_word = std::numeric_limits<Word>::digits;
DCHECK_LT(lhs_skip, bits_per_word);
DCHECK_GE(lhs_skip, 0);
DCHECK_LT(rhs_skip, bits_per_word);
DCHECK_GE(rhs_skip, 0);
size_t rhs_words =
(bitmaps_size + rhs_skip + bits_per_word - 1) / bits_per_word;
size_t lhs_words =
(bitmaps_size + lhs_skip + bits_per_word - 1) / bits_per_word;
if (lhs_skip == rhs_skip) {
InPlaceLogicalAnd(rhs, lhs, rhs_words);
} else if (lhs_skip < rhs_skip) {
int a = rhs_skip - lhs_skip;
int b = bits_per_word - a;
size_t i = 0;
for (; i < rhs_words - 1; ++i) {
lhs[i] &= (rhs[i] >> a) | (rhs[i + 1] << b);
}
if (i < lhs_words) {
lhs[i] &= (rhs[i] >> a);
}
} else {
int a = lhs_skip - rhs_skip;
int b = bits_per_word - a;
lhs[0] &= rhs[0] << a;
size_t i;
for (i = 1; i < rhs_words; ++i) {
lhs[i] &= (rhs[i - 1] >> b) | (rhs[i] << a);
}
if (i < lhs_words) {
lhs[i] &= rhs[i - 1] >> b;
}
}
}
template <typename Word>
void CopyBits(size_t bitmaps_size, const Word* rhs, int rhs_skip, Word* lhs,
int lhs_skip) {
static_assert(std::is_unsigned<Word>::value);
static constexpr int bits_per_word = std::numeric_limits<Word>::digits;
DCHECK_LT(lhs_skip, bits_per_word);
DCHECK_GE(lhs_skip, 0);
DCHECK_LT(rhs_skip, bits_per_word);
DCHECK_GE(rhs_skip, 0);
if (bitmaps_size == 0) {
return;
}
size_t rhs_words =
(bitmaps_size + rhs_skip + bits_per_word - 1) / bits_per_word;
size_t lhs_words =
(bitmaps_size + lhs_skip + bits_per_word - 1) / bits_per_word;
int lhs_tail = lhs_words * bits_per_word - (bitmaps_size + lhs_skip);
DCHECK_LT(lhs_tail, bits_per_word);
if (lhs_skip != 0) {
Word rhs_val;
if (lhs_skip == rhs_skip) {
rhs_val = *rhs;
} else if (lhs_skip < rhs_skip) {
int a = rhs_skip - lhs_skip;
rhs_val = rhs[0] >> a;
if (rhs_words > 1) {
rhs_val |= rhs[1] << (bits_per_word - a);
}
} else {
rhs_val = rhs[0] << (lhs_skip - rhs_skip);
}
if (lhs_words == 1) {
Word output_mask = (~Word{0} << lhs_skip) & (~Word{0} >> lhs_tail);
*lhs = (*lhs & ~output_mask) | (rhs_val & output_mask);
return;
} else {
Word output_mask = (~Word{0} << lhs_skip);
*lhs = (*lhs & ~output_mask) | (rhs_val & output_mask);
if (lhs_skip > rhs_skip) {
rhs_skip += bits_per_word - lhs_skip;
} else {
++rhs;
--rhs_words;
rhs_skip -= lhs_skip;
}
lhs_skip = 0;
++lhs;
--lhs_words;
}
}
DCHECK_EQ(lhs_skip, 0);
size_t full_lhs_words = (lhs_tail == 0) ? lhs_words : lhs_words - 1;
if (full_lhs_words > 0) {
if (rhs_skip == 0) {
for (size_t i = 0; i < full_lhs_words; ++i) {
lhs[i] = rhs[i];
}
} else {
size_t i = 0;
for (; i < std::min(rhs_words - 1, full_lhs_words); ++i) {
lhs[i] =
(rhs[i] >> rhs_skip) | (rhs[i + 1] << (bits_per_word - rhs_skip));
}
if (i < full_lhs_words) {
lhs[i] = (rhs[i] >> rhs_skip);
}
}
lhs += full_lhs_words;
lhs_words -= full_lhs_words;
rhs += full_lhs_words;
rhs_words -= full_lhs_words;
}
if (lhs_tail) {
Word rhs_val = rhs[0] >> rhs_skip;
if (rhs_words == 2) {
rhs_val |= rhs[1] << (bits_per_word - rhs_skip);
}
Word output_mask = (~Word{0} >> lhs_tail);
*lhs = (*lhs & ~output_mask) | (rhs_val & output_mask);
}
}
template <typename Integer>
Integer RoundUp(Integer value, Integer divisor) {
return (value + divisor - 1) / divisor * divisor;
}
}
#endif
|
#include "arolla/util/algorithms.h"
#include <array>
#include <cstdint>
#include <vector>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
namespace arolla {
namespace {
using ::testing::ElementsAre;
using ::testing::Eq;
TEST(Algorithms, ExponentialLowerBound) {
std::vector<int> v{2, 4, 5, 6};
auto i1 = exp_lower_bound(v.begin(), v.end(), 4);
EXPECT_THAT(i1, Eq(v.begin() + 1));
}
TEST(Algorithms, InplaceLogicalAndWithOffsets) {
const std::array<uint32_t, 3> a = {0xf0ff0000, 0xff0fffff, 0x0000fff0};
int a_bit_offset = 16;
const std::array<uint32_t, 2> b = {0x87654321, 0x0fedcba9};
int b_bit_offset = 0;
const std::array<uint32_t, 3> c = {0x43210000, 0xcba98765, 0x00000fed};
int c_bit_offset = 16;
auto a_copy = a;
InplaceLogicalAndWithOffsets(64, b.data(), b_bit_offset, a_copy.data(),
a_bit_offset);
EXPECT_THAT(a_copy, ElementsAre(0x40210000, 0xcb098765, 0x00000fe0));
auto b_copy = b;
InplaceLogicalAndWithOffsets(64, a.data(), a_bit_offset, b_copy.data(),
b_bit_offset);
EXPECT_THAT(b_copy, ElementsAre(0x87654021, 0x0fe0cb09));
auto c_copy = c;
InplaceLogicalAndWithOffsets(64, a.data(), a_bit_offset, c_copy.data(),
c_bit_offset);
EXPECT_THAT(a_copy, ElementsAre(0x40210000, 0xcb098765, 0x00000fe0));
}
TEST(Algorithms, CopyBits) {
const std::array<uint32_t, 3> src = {0x3210dead, 0xba987654, 0xbeeffedc};
const std::array<uint32_t, 3> empty = {0x5a5a5a5a, 0x5a5a5a5a, 0x5a5a5a5a};
auto dest1 = empty;
CopyBits(64, src.data(), 16, dest1.data(), 16);
EXPECT_THAT(dest1, ElementsAre(0x32105a5a, 0xba987654, 0x5a5afedc));
auto dest2 = empty;
CopyBits(64, src.data(), 16, dest2.data(), 8);
EXPECT_THAT(dest2, ElementsAre(0x5432105a, 0xdcba9876, 0x5a5a5afe));
auto dest3 = empty;
CopyBits(64, src.data(), 16, dest3.data(), 24);
EXPECT_THAT(dest3, ElementsAre(0x105a5a5a, 0x98765432, 0x5afedcba));
uint32_t dest4 = 0xffffffff;
CopyBits(16, src.data(), 16, &dest4, 8);
EXPECT_THAT(dest4, Eq(0xff3210ff));
uint32_t src5 = 0xdcba;
std::array<uint32_t, 2> dest5 = {0xffffffff, 0xffffffff};
CopyBits(16, &src5, 0, dest5.data(), 24);
EXPECT_THAT(dest5, ElementsAre(0xbaffffff, 0xffffffdc));
}
}
}
|
arolla
|
#ifndef AROLLA_UTIL_INIT_AROLLA_H_
#define AROLLA_UTIL_INIT_AROLLA_H_
#include "absl/status/status.h"
namespace arolla {
absl::Status InitArolla();
enum class ArollaInitializerPriority {
kHighest = 0,
kRegisterQExprOperators,
kRegisterIndividualQExprOperators,
kRegisterSerializationCodecs,
kRegisterExprOperatorsBootstrap,
kRegisterExprOperatorsStandard,
kRegisterExprOperatorsStandardCpp,
kRegisterExprOperatorsExtraLazy,
kRegisterExprOperatorsExtraJagged,
kRegisterExprOperatorsLowest,
kLowest,
};
static_assert(static_cast<int>(ArollaInitializerPriority::kLowest) < 32,
"Re-evaluate design when exceeding the threshold.");
#define AROLLA_REGISTER_INITIALIZER(priority, name, ...) \
extern "C" { \
static ::arolla::init_arolla_internal::ArollaInitializer \
AROLLA_REGISTER_INITIALIZER_IMPL_CONCAT(arolla_initializer_, \
__COUNTER__)( \
(::arolla::ArollaInitializerPriority::priority), (#name), \
(__VA_ARGS__)); \
}
#define AROLLA_REGISTER_ANONYMOUS_INITIALIZER(priority, ...) \
extern "C" { \
static ::arolla::init_arolla_internal::ArollaInitializer \
AROLLA_REGISTER_INITIALIZER_IMPL_CONCAT(arolla_initializer_, \
__COUNTER__)( \
(::arolla::ArollaInitializerPriority::priority), nullptr, \
(__VA_ARGS__)); \
}
#define AROLLA_REGISTER_INITIALIZER_IMPL_CONCAT_INNER(x, y) x##y
#define AROLLA_REGISTER_INITIALIZER_IMPL_CONCAT(x, y) \
AROLLA_REGISTER_INITIALIZER_IMPL_CONCAT_INNER(x, y)
namespace init_arolla_internal {
class ArollaInitializer {
public:
using VoidInitFn = void (*)();
using StatusInitFn = absl::Status (*)();
static absl::Status ExecuteAll();
ArollaInitializer(ArollaInitializerPriority priority, const char* name,
VoidInitFn init_fn);
ArollaInitializer(ArollaInitializerPriority priority, const char* name,
StatusInitFn init_fn);
private:
static bool execution_flag_;
static const ArollaInitializer* head_;
const ArollaInitializer* const next_;
const ArollaInitializerPriority priority_;
const char* const name_;
const VoidInitFn void_init_fn_ = nullptr;
const StatusInitFn status_init_fn_ = nullptr;
};
}
}
#endif
#include "arolla/util/init_arolla.h"
#include <algorithm>
#include <cstddef>
#include <cstring>
#include <utility>
#include <vector>
#include "absl/log/log.h"
#include "absl/status/status.h"
#include "absl/strings/str_cat.h"
#include "arolla/util/indestructible.h"
namespace arolla {
absl::Status InitArolla() {
return init_arolla_internal::ArollaInitializer::ExecuteAll();
}
namespace init_arolla_internal {
bool ArollaInitializer::execution_flag_ = false;
const ArollaInitializer* ArollaInitializer::head_ = nullptr;
absl::Status ArollaInitializer::ExecuteAll() {
static const Indestructible<absl::Status> result([]() -> absl::Status {
execution_flag_ = true;
std::vector<const ArollaInitializer*> list;
for (auto* it = head_; it != nullptr; it = it->next_) {
list.push_back(it);
}
std::stable_sort(list.begin(), list.end(), [](auto* it, auto* jt) {
return (it->name_ != nullptr &&
(jt->name_ == nullptr || std::strcmp(it->name_, jt->name_) < 0));
});
for (size_t i = 1; i < list.size() && list[i]->name_ != nullptr; ++i) {
if (std::strcmp(list[i - 1]->name_, list[i]->name_) == 0) {
return absl::InternalError(absl::StrCat(
"name collision in arolla initializers: ", list[i]->name_));
}
}
std::stable_sort(list.begin(), list.end(), [](auto* it, auto* jt) {
return it->priority_ < jt->priority_;
});
for (auto* it : list) {
if (it->void_init_fn_ != nullptr) {
it->void_init_fn_();
} else if (auto status = it->status_init_fn_(); !status.ok()) {
return status;
}
}
return absl::OkStatus();
}());
return *result;
}
ArollaInitializer::ArollaInitializer(ArollaInitializerPriority priority,
const char* name, VoidInitFn init_fn)
: next_(std::exchange(head_, this)),
priority_(priority),
name_(name),
void_init_fn_(init_fn) {
if (init_fn == nullptr) {
LOG(FATAL) << "init_fn == nullptr";
}
if (execution_flag_) {
LOG(FATAL) << "A new initializer has been registered after calling "
"::arolla::InitArolla()";
}
}
ArollaInitializer::ArollaInitializer(ArollaInitializerPriority priority,
const char* name, StatusInitFn init_fn)
: next_(std::exchange(head_, this)),
priority_(priority),
name_(name),
status_init_fn_(init_fn) {
if (init_fn == nullptr) {
LOG(FATAL) << "init_fn == nullptr";
}
if (execution_flag_) {
LOG(FATAL) << "A new initializer has been registered after calling "
"::arolla::InitArolla()";
}
}
}
}
|
#include "arolla/util/init_arolla.h"
#include <string>
#include <tuple>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/status/status.h"
#include "arolla/util/indestructible.h"
#include "arolla/util/testing/status_matchers_backport.h"
namespace arolla {
namespace {
using ::arolla::testing::IsOk;
std::string& GetBuffer() {
static Indestructible<std::string> result;
return *result;
}
AROLLA_REGISTER_INITIALIZER(kHighest, Foo, [] { GetBuffer() += "Hello"; })
AROLLA_REGISTER_INITIALIZER(kLowest, Bar, []() -> absl::Status {
GetBuffer() += "World";
return absl::OkStatus();
})
AROLLA_REGISTER_ANONYMOUS_INITIALIZER(kLowest, [] { GetBuffer() += "!"; })
AROLLA_REGISTER_INITIALIZER(kLowest, Baz, []() -> absl::Status {
std::tuple<int, int>();
return absl::OkStatus();
})
TEST(InitArollaTest, Complex) {
{
EXPECT_EQ(GetBuffer(), "");
}
{
ASSERT_THAT(InitArolla(), IsOk());
EXPECT_EQ(GetBuffer(), "HelloWorld!");
}
{
ASSERT_THAT(InitArolla(), IsOk());
EXPECT_EQ(GetBuffer(), "HelloWorld!");
}
}
}
}
|
arolla
|
#ifndef AROLLA_UTIL_FINGERPRINT_H_
#define AROLLA_UTIL_FINGERPRINT_H_
#include <cstddef>
#include <cstdint>
#include <iosfwd>
#include <memory>
#include <string>
#include <type_traits>
#include <utility>
#include "absl/numeric/int128.h"
#include "absl/strings/string_view.h"
#include "absl/types/span.h"
#include "arolla/util/meta.h"
#include "arolla/util/struct_field.h"
#include "arolla/util/types.h"
namespace arolla {
struct Fingerprint {
absl::uint128 value;
std::string AsString() const;
signed_size_t PythonHash() const;
};
Fingerprint RandomFingerprint();
class FingerprintHasher {
public:
explicit FingerprintHasher(absl::string_view salt);
Fingerprint Finish() &&;
template <typename... Args>
FingerprintHasher& Combine(const Args&... args) &;
template <typename... Args>
FingerprintHasher&& Combine(const Args&... args) &&;
template <typename SpanT>
FingerprintHasher& CombineSpan(SpanT&& values) &;
template <typename SpanT>
FingerprintHasher&& CombineSpan(SpanT&& values) &&;
void CombineRawBytes(const void* data, size_t size);
private:
std::pair<uint64_t, uint64_t> state_;
};
namespace fingerprint_impl {
template <typename T, class = void>
struct HasArollaFingerprintMethod : std::false_type {};
template <class T>
struct HasArollaFingerprintMethod<
T, std::void_t<decltype(static_cast<void (T::*)(FingerprintHasher*) const>(
&T::ArollaFingerprint))>> : std::true_type {};
}
template <typename T>
struct FingerprintHasherTraits {
FingerprintHasherTraits() = delete;
};
inline bool operator==(const Fingerprint& lhs, const Fingerprint& rhs) {
return lhs.value == rhs.value;
}
inline bool operator!=(const Fingerprint& lhs, const Fingerprint& rhs) {
return !(lhs == rhs);
}
inline bool operator<(const Fingerprint& lhs, const Fingerprint& rhs) {
return lhs.value < rhs.value;
}
std::ostream& operator<<(std::ostream& ostream, const Fingerprint& fingerprint);
template <typename H>
H AbslHashValue(H state, const Fingerprint& fingerprint) {
return H::combine(std::move(state), fingerprint.value);
}
template <typename... Args>
FingerprintHasher& FingerprintHasher::Combine(const Args&... args) & {
auto combine = [this](const auto& arg) {
using Arg = std::decay_t<decltype(arg)>;
if constexpr (fingerprint_impl::HasArollaFingerprintMethod<Arg>::value) {
arg.ArollaFingerprint(this);
} else if constexpr (std::is_default_constructible_v<
FingerprintHasherTraits<Arg>>) {
FingerprintHasherTraits<Arg>()(this, arg);
} else if constexpr (std::is_arithmetic_v<Arg> || std::is_enum_v<Arg>) {
CombineRawBytes(&arg, sizeof(arg));
} else {
static_assert(sizeof(Arg) == 0,
"Please, define `void "
"T::ArollaFingerprint(FingerprintHasher* hasher) const` "
"or specialise FingerprintHasherTraits for your type.");
}
};
(combine(args), ...);
return *this;
}
template <typename... Args>
FingerprintHasher&& FingerprintHasher::Combine(const Args&... args) && {
Combine(args...);
return std::move(*this);
}
template <typename SpanT>
FingerprintHasher& FingerprintHasher::CombineSpan(SpanT&& values) & {
const auto span = absl::MakeConstSpan(values);
using T = typename decltype(span)::value_type;
Combine(values.size());
if constexpr (std::is_default_constructible_v<FingerprintHasherTraits<T>>) {
constexpr FingerprintHasherTraits<T> traits;
for (const auto& x : values) {
traits(this, x);
}
} else if constexpr (std::is_arithmetic_v<T> || std::is_enum_v<T>) {
CombineRawBytes(values.data(), values.size() * sizeof(values[0]));
} else {
static_assert(sizeof(T) == 0,
"Please specialise FingerprintHasherTraits for your type.");
}
return *this;
}
template <typename SpanT>
FingerprintHasher&& FingerprintHasher::CombineSpan(SpanT&& values) && {
CombineSpan(std::forward<SpanT>(values));
return std::move(*this);
}
template <>
struct FingerprintHasherTraits<Fingerprint> {
void operator()(FingerprintHasher* hasher, const Fingerprint& value) const {
hasher->CombineRawBytes(&value.value, sizeof(value.value));
}
};
template <>
struct FingerprintHasherTraits<std::string> {
void operator()(FingerprintHasher* hasher, const std::string& value) const {
hasher->Combine(value.size()).CombineRawBytes(value.data(), value.size());
}
};
template <>
struct FingerprintHasherTraits<absl::string_view> {
void operator()(FingerprintHasher* hasher, absl::string_view value) const {
hasher->Combine(value.size()).CombineRawBytes(value.data(), value.size());
}
};
template <class Struct>
void CombineStructFields(FingerprintHasher* hasher, const Struct& value) {
static_assert(HasStructFields<Struct>(), "no struct fields found");
meta::foreach_tuple_element(
GetStructFields<Struct>(), [&](const auto& struct_field) {
hasher->Combine(*UnsafeGetStructFieldPtr(struct_field, &value));
});
}
template <typename T>
struct FingerprintHasherTraits<T*> {
static_assert(sizeof(T*) == 0,
"Pointer values are runtime specific and not fingerprintable.");
};
template <typename T>
struct FingerprintHasherTraits<std::unique_ptr<T>> {
static_assert(
sizeof(std::unique_ptr<T>) == 0,
"Unique pointer values are runtime specific and not fingerprintable.");
};
template <typename T>
struct FingerprintHasherTraits<std::shared_ptr<T>> {
static_assert(
sizeof(std::shared_ptr<T>) == 0,
"Shared pointer values are runtime specific and not fingerprintable.");
};
#define AROLLA_DECLARE_FINGERPRINT_HASHER_TRAITS(CPP_TYPE) \
template <> \
struct FingerprintHasherTraits<CPP_TYPE> { \
void operator()(FingerprintHasher* hasher, const CPP_TYPE& value) const; \
}
}
#endif
#include "arolla/util/fingerprint.h"
#include <cstddef>
#include <cstdint>
#include <ostream>
#include <string>
#include "absl/hash/hash.h"
#include "absl/numeric/int128.h"
#include "absl/random/random.h"
#include "absl/strings/str_format.h"
#include "absl/strings/string_view.h"
#include "cityhash/city.h"
#include "arolla/util/types.h"
namespace arolla {
namespace {
uint32_t RuntimeSeed() {
static uint32_t result = absl::Hash<int>{}(501816262);
return result;
}
}
std::string Fingerprint::AsString() const {
return absl::StrFormat("%032x", value);
}
signed_size_t Fingerprint::PythonHash() const {
return absl::Hash<Fingerprint>()(*this);
}
std::ostream& operator<<(std::ostream& ostream,
const Fingerprint& fingerprint) {
return ostream << absl::StreamFormat("%032x", fingerprint.value);
}
Fingerprint RandomFingerprint() {
absl::BitGen bitgen;
return Fingerprint{absl::MakeUint128(absl::Uniform<uint64_t>(bitgen),
absl::Uniform<uint64_t>(bitgen))};
}
FingerprintHasher::FingerprintHasher(absl::string_view salt)
: state_{3102879407, 2758948377}
{
Combine(RuntimeSeed(), salt);
}
Fingerprint FingerprintHasher::Finish() && {
return Fingerprint{absl::MakeUint128(state_.second, state_.first)};
}
void FingerprintHasher::CombineRawBytes(const void* data, size_t size) {
state_ = cityhash::CityHash128WithSeed(
static_cast<const char*>(data), size, state_);
}
}
|
#include "arolla/util/fingerprint.h"
#include <limits>
#include <string>
#include <tuple>
#include <type_traits>
#include <utility>
#include "gtest/gtest.h"
#include "absl/container/flat_hash_set.h"
#include "arolla/util/struct_field.h"
namespace arolla {
namespace {
static_assert(
std::is_trivially_constructible_v<Fingerprint>,
"Make sure that fingerprint is trivially constructed, so that adding it to "
"a struct does not slow down the struct's initialization time.");
struct A {};
static_assert(!std::is_default_constructible_v<FingerprintHasherTraits<A>>);
struct AWithFingerPrintMethod {
void ArollaFingerprint(FingerprintHasher* hasher) const {
hasher->Combine(19);
}
};
struct AWithStructFields {
int a;
double b;
constexpr static auto ArollaStructFields() {
using CppType = AWithStructFields;
return std::tuple{
AROLLA_DECLARE_STRUCT_FIELD(a),
AROLLA_DECLARE_STRUCT_FIELD(b),
};
}
void ArollaFingerprint(FingerprintHasher* hasher) const {
CombineStructFields(hasher, *this);
}
};
template <typename... Ts>
Fingerprint MakeDummyFingerprint(const Ts&... values) {
return FingerprintHasher("dummy-salt").Combine(values...).Finish();
}
TEST(FingerprintTest, Empty) {
Fingerprint fgpt{};
EXPECT_EQ(fgpt.AsString(), "00000000000000000000000000000000");
}
TEST(FingerprintTest, RandomFingerprint) {
constexpr int N = 1024;
absl::flat_hash_set<Fingerprint> set;
set.reserve(N);
for (int i = 0; i < N; ++i) {
set.insert(RandomFingerprint());
}
EXPECT_EQ(set.size(), N);
}
TEST(FingerprintTest, AWithFingerPrintMethod) {
EXPECT_EQ(MakeDummyFingerprint(AWithFingerPrintMethod()),
MakeDummyFingerprint(19));
}
TEST(FingerprintTest, AWithStructFields) {
EXPECT_EQ(MakeDummyFingerprint(AWithStructFields{.a = 5, .b = 7.}),
MakeDummyFingerprint(5, 7.));
}
TEST(FingerprintTest, TestPrimitives) {
EXPECT_NE(MakeDummyFingerprint(5), MakeDummyFingerprint(6));
EXPECT_NE(MakeDummyFingerprint<std::string>("5"),
MakeDummyFingerprint<std::string>("6"));
}
TEST(FingerprintTest, FloatingPointZero) {
EXPECT_NE(MakeDummyFingerprint(0.0).PythonHash(),
MakeDummyFingerprint(-0.0).PythonHash());
EXPECT_NE(MakeDummyFingerprint(0.f).PythonHash(),
MakeDummyFingerprint(-0.f).PythonHash());
}
TEST(FingerprintTest, FloatingPointNAN) {
EXPECT_NE(MakeDummyFingerprint(std::numeric_limits<float>::quiet_NaN())
.PythonHash(),
MakeDummyFingerprint(-std::numeric_limits<float>::quiet_NaN())
.PythonHash());
EXPECT_NE(MakeDummyFingerprint(std::numeric_limits<double>::quiet_NaN())
.PythonHash(),
MakeDummyFingerprint(-std::numeric_limits<double>::quiet_NaN())
.PythonHash());
}
TEST(FingerprintTest, PythonHash) {
EXPECT_EQ(MakeDummyFingerprint(4).PythonHash(),
MakeDummyFingerprint(4).PythonHash());
EXPECT_NE(MakeDummyFingerprint(5).PythonHash(),
MakeDummyFingerprint(6).PythonHash());
}
TEST(FingerprintTest, Less) {
EXPECT_LT(Fingerprint{27}, Fingerprint{37});
EXPECT_FALSE(Fingerprint{27} < Fingerprint{27});
}
TEST(FingerprintTest, CombineRawBytes) {
{
FingerprintHasher h1("dummy-salt");
FingerprintHasher h2("dummy-salt");
h1.CombineRawBytes("foobar", 6);
h2.CombineRawBytes("foobar", 6);
EXPECT_EQ(std::move(h1).Finish(), std::move(h2).Finish());
}
{
FingerprintHasher h1("dummy-salt");
FingerprintHasher h2("dummy-salt");
h1.CombineRawBytes("foobar", 6);
h2.CombineRawBytes("barfoo", 6);
EXPECT_NE(std::move(h1).Finish(), std::move(h2).Finish());
}
}
class Circle {
public:
Circle(int x, int y, int r) : center_(x, y), radius_(r) {
FingerprintHasher hasher("arolla::TestCircle");
hasher.Combine(center_.first, center_.second, radius_);
fingerprint_ = std::move(hasher).Finish();
}
const Fingerprint& fingerprint() { return fingerprint_; }
private:
std::pair<int, int> center_;
int radius_;
Fingerprint fingerprint_;
};
TEST(FingerprintTest, UserDefined) {
EXPECT_NE(Circle(0, 0, 1).fingerprint(), Circle(0, 0, 2).fingerprint());
EXPECT_NE(Circle(1, 1, 1).fingerprint(), Circle(0, 0, 1).fingerprint());
}
TEST(FingerprintTest, HasArollaFingerprintMethodRegression) {
struct OverloadedType {
int ArollaFingerprint() const { return 0; }
void ArollaFingerprint(FingerprintHasher*) const {}
};
EXPECT_TRUE(
fingerprint_impl::HasArollaFingerprintMethod<OverloadedType>::value);
struct WrongType {
int ArollaFingerprint() const { return 0; }
};
EXPECT_FALSE(fingerprint_impl::HasArollaFingerprintMethod<WrongType>::value);
}
}
}
|
arolla
|
#ifndef AROLLA_UTIL_BYTES_H_
#define AROLLA_UTIL_BYTES_H_
#include <string>
#include "arolla/util/repr.h"
namespace arolla {
using Bytes = std::string;
AROLLA_DECLARE_REPR(Bytes);
}
#endif
#include "arolla/util/bytes.h"
#include <cstddef>
#include <string>
#include "absl/strings/escaping.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
#include "arolla/util/repr.h"
namespace arolla {
ReprToken ReprTraits<Bytes>::operator()(const Bytes& value) const {
constexpr size_t kBytesAbbrevLimit = 120;
ReprToken result;
absl::string_view bytes = value;
if (bytes.size() <= kBytesAbbrevLimit) {
result.str = absl::StrCat("b'", absl::CHexEscape(bytes), "'");
} else {
result.str =
absl::StrCat("b'", absl::CHexEscape(bytes.substr(0, kBytesAbbrevLimit)),
"... (", bytes.size(), " bytes total)'");
}
return result;
}
}
|
#include "arolla/util/bytes.h"
#include <string>
#include <type_traits>
#include <utility>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/strings/string_view.h"
#include "arolla/util/repr.h"
#include "arolla/util/testing/repr_token_eq.h"
namespace arolla {
namespace {
using ::arolla::testing::ReprTokenEq;
using ::testing::Eq;
using ::testing::MatchesRegex;
TEST(BytesTest, Constructor) {
EXPECT_THAT(Bytes("Hello"), Eq("Hello"));
std::string hello = "Hello";
EXPECT_THAT(Bytes(hello), Eq("Hello"));
absl::string_view hello_view = hello;
EXPECT_THAT(Bytes(hello_view), Eq("Hello"));
}
TEST(BytesTest, CopyAndMoveConstructors) {
static_assert(std::is_nothrow_move_constructible<Bytes>::value);
Bytes src("Google");
Bytes copied(src);
EXPECT_THAT(copied, Eq(src));
Bytes moved(std::move(src));
EXPECT_THAT(moved, Eq(copied));
}
TEST(BytesTest, CopyAndMoveAssignment) {
static_assert(std::is_nothrow_move_assignable<Bytes>::value);
Bytes src("Google");
Bytes copied = src;
EXPECT_THAT(copied, Eq(src));
Bytes moved = std::move(src);
EXPECT_THAT(moved, Eq(copied));
}
TEST(BytesTest, AssignmentFromString) {
std::string google = "Google";
{
Bytes val("x");
val = "Google";
EXPECT_THAT(val, Eq(google));
}
{
Bytes val("x");
val = google;
EXPECT_THAT(val, Eq(google));
}
{
absl::string_view google_view = google;
Bytes val("x");
val = google_view;
EXPECT_THAT(val, Eq("Google"));
}
{
Bytes val("x");
val = std::move(google);
EXPECT_THAT(val, Eq("Google"));
}
}
TEST(BytesTest, Repr) {
EXPECT_THAT(GenReprToken(Bytes("G'\"\t\xff")),
ReprTokenEq(R"(b'G\'\"\t\xff')"));
EXPECT_THAT(Repr(Bytes(std::string(1024, 'x'))),
MatchesRegex(R"(b'x{120}[.]{3} \(1024 bytes total\)')"));
}
}
}
|
arolla
|
#ifndef AROLLA_UTIL_STATUS_H_
#define AROLLA_UTIL_STATUS_H_
#include <array>
#include <cstdint>
#include <initializer_list>
#include <tuple>
#include <type_traits>
#include <utility>
#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/util/meta.h"
#include "arolla/util/status_macros_backport.h"
namespace arolla {
absl::Status SizeMismatchError(std::initializer_list<int64_t> sizes);
template <class T>
absl::Status GetStatusOrOk(const T&) {
return absl::OkStatus();
}
template <class T>
absl::Status GetStatusOrOk(const absl::StatusOr<T>& v_or) {
return v_or.status();
}
inline absl::Status GetStatusOrOk(const absl::Status& status) { return status; }
template <class T>
bool IsOkStatus(const T&) {
return true;
}
template <class T>
bool IsOkStatus(const absl::StatusOr<T>& v_or) {
return v_or.ok();
}
inline bool IsOkStatus(const absl::Status& status) { return status.ok(); }
template <class... Ts>
absl::Status CheckInputStatus(const Ts&... status_or_ts) {
if ((IsOkStatus(status_or_ts) && ...)) {
return absl::OkStatus();
}
for (auto& status : std::array<absl::Status, sizeof...(Ts)>{
GetStatusOrOk(status_or_ts)...}) {
RETURN_IF_ERROR(std::move(status));
}
return absl::OkStatus();
}
template <typename T>
struct IsStatusOrT : std::false_type {};
template <typename T>
struct IsStatusOrT<absl::StatusOr<T>> : std::true_type {};
template <typename T>
using strip_statusor_t = meta::strip_template_t<absl::StatusOr, T>;
template <class T>
decltype(auto) UnStatus(T&& t) {
if constexpr (IsStatusOrT<std::decay_t<T>>()) {
return *std::forward<T>(t);
} else {
return std::forward<T>(t);
}
}
template <class Fn>
struct UnStatusCaller {
template <class... Ts>
auto operator()(const Ts&... status_or_ts) const
-> absl::StatusOr<strip_statusor_t<
decltype(std::declval<Fn>()(UnStatus(status_or_ts)...))>> {
if ((IsOkStatus(status_or_ts) && ...)) {
return fn(UnStatus(status_or_ts)...);
}
return CheckInputStatus(status_or_ts...);
}
Fn fn;
};
template <class Fn>
UnStatusCaller<Fn> MakeUnStatusCaller(Fn&& fn) {
return UnStatusCaller<Fn>{std::forward<Fn>(fn)};
}
template <class... Ts>
static absl::StatusOr<std::tuple<Ts...>> LiftStatusUp(
absl::StatusOr<Ts>... status_or_ts) {
RETURN_IF_ERROR(CheckInputStatus(status_or_ts...));
return std::make_tuple(*std::move(status_or_ts)...);
}
template <class T>
absl::StatusOr<std::vector<T>> LiftStatusUp(
std::vector<absl::StatusOr<T>>&& status_or_ts) {
std::vector<T> result;
result.reserve(status_or_ts.size());
for (auto& status_or_t : status_or_ts) {
if (!status_or_t.ok()) {
return std::move(status_or_t).status();
}
result.push_back(*std::move(status_or_t));
}
return result;
}
template <class T>
absl::StatusOr<std::vector<T>> LiftStatusUp(
absl::Span<const absl::StatusOr<T>> status_or_ts) {
std::vector<T> result;
result.reserve(status_or_ts.size());
for (const auto& status_or_t : status_or_ts) {
if (!status_or_t.ok()) {
return status_or_t.status();
}
result.push_back(*status_or_t);
}
return result;
}
template <class K, class V>
absl::StatusOr<absl::flat_hash_map<K, V>> LiftStatusUp(
absl::flat_hash_map<K, absl::StatusOr<V>> status_or_kvs) {
absl::flat_hash_map<K, V> result;
result.reserve(status_or_kvs.size());
for (const auto& [key, status_or_v] : status_or_kvs) {
if (!status_or_v.ok()) {
return status_or_v.status();
}
result.emplace(key, *status_or_v);
}
return result;
}
template <class K, class V>
absl::StatusOr<absl::flat_hash_map<K, V>> LiftStatusUp(
std::initializer_list<std::pair<K, absl::StatusOr<V>>> status_or_kvs) {
return LiftStatusUp(absl::flat_hash_map<K, absl::StatusOr<V>>{status_or_kvs});
}
template <class K, class V>
absl::StatusOr<absl::flat_hash_map<K, V>> LiftStatusUp(
std::initializer_list<std::pair<absl::StatusOr<K>, absl::StatusOr<V>>>
status_or_kvs) {
absl::flat_hash_map<K, V> result;
result.reserve(status_or_kvs.size());
for (const auto& [status_or_k, status_or_v] : status_or_kvs) {
if (!status_or_k.ok()) {
return status_or_k.status();
}
if (!status_or_v.ok()) {
return status_or_v.status();
}
result.emplace(*status_or_k, *status_or_v);
}
return result;
}
inline absl::Status FirstErrorStatus(
std::initializer_list<absl::Status> statuses) {
for (const absl::Status& status : statuses) {
RETURN_IF_ERROR(status);
}
return absl::OkStatus();
}
}
#endif
#include "absl/status/status.h"
#include <cstdint>
#include <initializer_list>
#include "absl/strings/str_cat.h"
#include "absl/strings/str_join.h"
namespace arolla {
absl::Status SizeMismatchError(std::initializer_list<int64_t> sizes) {
return absl::InvalidArgumentError(absl::StrCat(
"argument sizes mismatch: (", absl::StrJoin(sizes, ", "), ")"));
}
}
|
#include "arolla/util/status.h"
#include <initializer_list>
#include <memory>
#include <string>
#include <tuple>
#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 "absl/types/span.h"
#include "arolla/util/testing/status_matchers_backport.h"
namespace arolla {
namespace {
using ::arolla::testing::IsOkAndHolds;
using ::testing::AnyOf;
using ::testing::Eq;
using ::testing::Test;
TEST(StatusTest, CheckInputStatus) {
EXPECT_OK(CheckInputStatus());
EXPECT_OK(CheckInputStatus(13));
EXPECT_OK(CheckInputStatus(13, "a"));
EXPECT_OK(CheckInputStatus(absl::StatusOr<int>(13), "a"));
EXPECT_OK(CheckInputStatus(13, absl::StatusOr<std::string>("a")));
EXPECT_OK(CheckInputStatus(absl::StatusOr<int>(13),
absl::StatusOr<std::string>("a")));
absl::Status bad_status1{absl::StatusCode::kInvalidArgument, "bad 1"};
absl::Status bad_status2{absl::StatusCode::kDataLoss, "bad 2"};
EXPECT_EQ(CheckInputStatus(absl::StatusOr<int>(bad_status1)), bad_status1);
EXPECT_EQ(CheckInputStatus(13, absl::StatusOr<int>(bad_status1)),
bad_status1);
EXPECT_EQ(CheckInputStatus(absl::StatusOr<int>(13),
absl::StatusOr<int>(bad_status1)),
bad_status1);
EXPECT_EQ(CheckInputStatus(absl::StatusOr<int>(bad_status1),
absl::StatusOr<int>(bad_status2)),
bad_status1);
}
TEST(StatusTest, LiftStatusUpSuccess) {
std::tuple<> empty = LiftStatusUp().value();
EXPECT_THAT(empty, Eq(std::make_tuple()));
std::tuple<int> one = LiftStatusUp(absl::StatusOr<int>(1)).value();
EXPECT_THAT(one, Eq(std::make_tuple(1)));
std::tuple<std::string, int> two =
LiftStatusUp(absl::StatusOr<std::string>("one"), absl::StatusOr<int>(2))
.value();
EXPECT_THAT(two, Eq(std::make_tuple(std::string("one"), 2)));
ASSERT_OK_AND_ASSIGN(
std::vector<int> vec,
LiftStatusUp(absl::Span<const absl::StatusOr<int>>{1, 2}));
EXPECT_THAT(vec, ::testing::ElementsAre(1, 2));
absl::flat_hash_map<int, int> fhm =
LiftStatusUp(std::initializer_list<std::pair<int, absl::StatusOr<int>>>{
{1, 2}, {3, 4}})
.value();
EXPECT_THAT(fhm, Eq(absl::flat_hash_map<int, int>{{1, 2}, {3, 4}}));
absl::flat_hash_map<int, int> fhm1 =
LiftStatusUp(std::initializer_list<
std::pair<absl::StatusOr<int>, absl::StatusOr<int>>>{
{1, 2}, {3, 4}})
.value();
EXPECT_THAT(fhm, Eq(absl::flat_hash_map<int, int>{{1, 2}, {3, 4}}));
}
TEST(StatusTest, LiftStatusUpErrors) {
absl::Status bad_status1{absl::StatusCode::kInvalidArgument, "bad 1"};
absl::Status bad_status2{absl::StatusCode::kDataLoss, "bad 2"};
EXPECT_EQ(LiftStatusUp(absl::StatusOr<int>(bad_status1)).status(),
bad_status1);
EXPECT_EQ(LiftStatusUp(absl::StatusOr<std::string>("one"),
absl::StatusOr<int>(bad_status2))
.status(),
bad_status2);
EXPECT_EQ(LiftStatusUp(absl::StatusOr<std::string>("one"),
absl::StatusOr<int>(bad_status1),
absl::StatusOr<float>(bad_status2))
.status(),
bad_status1);
EXPECT_EQ(LiftStatusUp(absl::StatusOr<float>(bad_status2),
absl::StatusOr<std::string>("one"),
absl::StatusOr<int>(bad_status1))
.status(),
bad_status2);
EXPECT_THAT(LiftStatusUp(absl::Span<const absl::StatusOr<int>>{bad_status1,
bad_status2})
.status(),
bad_status1);
EXPECT_THAT(
LiftStatusUp(std::initializer_list<std::pair<int, absl::StatusOr<int>>>{
{1, bad_status1}, {2, 3}, {4, bad_status2}})
.status(),
AnyOf(bad_status1, bad_status2));
EXPECT_THAT(
LiftStatusUp(std::initializer_list<
std::pair<absl::StatusOr<int>, absl::StatusOr<int>>>{
{bad_status1, 1}, {2, 3}, {4, bad_status2}})
.status(),
AnyOf(bad_status1, bad_status2));
EXPECT_THAT(
LiftStatusUp(std::initializer_list<
std::pair<absl::StatusOr<int>, absl::StatusOr<int>>>{
{1, bad_status1}, {2, 3}, {4, bad_status2}})
.status(),
AnyOf(bad_status1, bad_status2));
}
TEST(StatusTest, UnStatus) {
using T = std::unique_ptr<int>;
using StatusOrT = absl::StatusOr<T>;
{
StatusOrT status_or_t = std::make_unique<int>(1);
const T& value = UnStatus(status_or_t);
EXPECT_EQ(*value, 1);
EXPECT_EQ(value.get(), status_or_t.value().get());
}
{
StatusOrT status_or_t = std::make_unique<int>(1);
T value = UnStatus(std::move(status_or_t));
EXPECT_EQ(*value, 1);
}
{
T original_value = std::make_unique<int>(1);
const T& value = UnStatus(original_value);
EXPECT_EQ(*value, 1);
EXPECT_EQ(value.get(), original_value.get());
}
{
T original_value = std::make_unique<int>(1);
T value = UnStatus(std::move(original_value));
EXPECT_EQ(*value, 1);
}
}
TEST(StatusTest, FirstErrorStatus) {
absl::Status ok_status = absl::OkStatus();
absl::Status failed_precondition = absl::FailedPreconditionError("msg1");
absl::Status internal_error = absl::InternalError("msg2");
EXPECT_OK(FirstErrorStatus({}));
EXPECT_OK(FirstErrorStatus({ok_status, ok_status}));
EXPECT_EQ(FirstErrorStatus({failed_precondition}), failed_precondition);
EXPECT_EQ(FirstErrorStatus({ok_status, failed_precondition}),
failed_precondition);
EXPECT_EQ(FirstErrorStatus({failed_precondition, ok_status}),
failed_precondition);
EXPECT_EQ(FirstErrorStatus({failed_precondition, internal_error}),
failed_precondition);
EXPECT_EQ(FirstErrorStatus({internal_error, failed_precondition}),
internal_error);
}
TEST(StatusTest, GetStatusOrOk) {
absl::Status ok_status = absl::OkStatus();
EXPECT_OK(GetStatusOrOk(5));
EXPECT_OK(GetStatusOrOk(ok_status));
EXPECT_OK(GetStatusOrOk(absl::StatusOr<int>(5)));
absl::Status failed_precondition = absl::FailedPreconditionError("msg1");
EXPECT_EQ(GetStatusOrOk(failed_precondition), failed_precondition);
EXPECT_EQ(GetStatusOrOk(absl::StatusOr<int>(failed_precondition)),
failed_precondition);
}
TEST(StatusTest, IsOkStatus) {
absl::Status ok_status = absl::OkStatus();
EXPECT_TRUE(IsOkStatus(5));
EXPECT_TRUE(IsOkStatus(ok_status));
EXPECT_TRUE(IsOkStatus(absl::StatusOr<int>(5)));
absl::Status failed_precondition = absl::FailedPreconditionError("msg1");
EXPECT_FALSE(IsOkStatus(failed_precondition));
EXPECT_FALSE(IsOkStatus(absl::StatusOr<int>(failed_precondition)));
}
TEST(StatusTest, UnStatusCaller) {
absl::Status failed_precondition = absl::FailedPreconditionError("msg1");
absl::Status failed_precondition2 = absl::FailedPreconditionError("msg2");
auto add_op = [](int a, int b) { return a + b; };
UnStatusCaller<decltype(add_op)> add_op_wrap{add_op};
auto add_op_with_status = [](int a, int b) -> absl::StatusOr<int> {
return a + b;
};
auto add_op_with_status_wrap = MakeUnStatusCaller(add_op_with_status);
auto add_op_always_error = [&](int a, int b) -> absl::StatusOr<int> {
return failed_precondition;
};
auto add_op_always_error_wrap = MakeUnStatusCaller(add_op_always_error);
EXPECT_THAT(add_op_wrap(5, 7), IsOkAndHolds(12));
EXPECT_THAT(add_op_with_status_wrap(5, 7), IsOkAndHolds(12));
EXPECT_EQ(add_op_always_error_wrap(5, 7).status(), failed_precondition);
EXPECT_EQ(add_op_wrap(5, absl::StatusOr<int>(failed_precondition)).status(),
failed_precondition);
EXPECT_EQ(add_op_wrap(absl::StatusOr<int>(failed_precondition),
absl::StatusOr<int>(failed_precondition2))
.status(),
failed_precondition);
EXPECT_EQ(
add_op_always_error_wrap(5, absl::StatusOr<int>(failed_precondition2))
.status(),
failed_precondition2);
}
}
}
|
arolla
|
#ifndef AROLLA_MEMORY_STRINGS_BUFFER_H_
#define AROLLA_MEMORY_STRINGS_BUFFER_H_
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <string>
#include <tuple>
#include <utility>
#include "absl/log/check.h"
#include "absl/strings/cord.h"
#include "absl/strings/string_view.h"
#include "absl/types/span.h"
#include "arolla/memory/optional_value.h"
#include "arolla/memory/raw_buffer_factory.h"
#include "arolla/memory/simple_buffer.h"
#include "arolla/util/fingerprint.h"
#include "arolla/util/iterator.h"
#include "arolla/util/preallocated_buffers.h"
namespace arolla {
class StringsBuffer {
public:
using value_type = absl::string_view;
using size_type = int64_t;
using difference_type = int64_t;
using const_iterator = ConstArrayIterator<StringsBuffer>;
using offset_type = int64_t;
struct Offsets {
offset_type start;
offset_type end;
};
StringsBuffer() = default;
StringsBuffer(SimpleBuffer<Offsets> offsets, SimpleBuffer<char> characters,
offset_type base_offset = 0);
class Builder;
class Inserter {
public:
void Add(absl::string_view v) { builder_->Set(offset_++, v); }
void Add(const absl::Cord& v) { builder_->Set(offset_++, std::string(v)); }
void SkipN(int64_t count) {
offset_ += count;
DCHECK_LE(offset_, builder_->offsets_.size());
}
private:
friend class Builder;
explicit Inserter(Builder* builder, int64_t offset)
: builder_(builder), offset_(offset) {}
Builder* builder_;
int64_t offset_;
};
class Builder {
public:
Builder() = default;
Builder(Builder&&) = default;
Builder& operator=(Builder&&) = default;
explicit Builder(int64_t max_size,
RawBufferFactory* factory = GetHeapBufferFactory());
Inserter GetInserter(int64_t offset = 0) { return Inserter(this, offset); }
void Set(int64_t offset, absl::string_view v) {
DCHECK_GE(offset, 0);
DCHECK_LT(offset, offsets_.size());
if (v.size() + num_chars_ > characters_.size()) {
size_t new_size = characters_.size() * 2;
while (v.size() + num_chars_ > new_size) {
new_size *= 2;
}
ResizeCharacters(new_size);
}
std::copy(v.begin(), v.end(), characters_.data() + num_chars_);
offsets_[offset].start = num_chars_;
num_chars_ += v.size();
offsets_[offset].end = num_chars_;
}
void Set(int64_t offset, const absl::Cord& v) {
Set(offset, std::string(v));
}
void Copy(int64_t offset_from, int64_t offset_to) {
offsets_[offset_to] = offsets_[offset_from];
}
template <typename NextValueFn>
void SetN(int64_t first_offset, int64_t count, NextValueFn fn) {
for (int64_t i = first_offset; i < first_offset + count; ++i) {
Set(i, fn());
}
}
void SetNConst(int64_t first_offset, int64_t count, absl::string_view v) {
DCHECK_GE(count, 0);
DCHECK_GE(first_offset, 0);
DCHECK_LE(first_offset + count, offsets_.size());
if (count <= 0) return;
Set(first_offset, v);
auto d = offsets_[first_offset];
std::fill(offsets_.data() + first_offset + 1,
offsets_.data() + first_offset + count, d);
}
StringsBuffer Build(Inserter ins) && {
if (!ins.builder_) return StringsBuffer();
DCHECK_EQ(ins.builder_, this);
return std::move(*this).Build(ins.offset_);
}
StringsBuffer Build(int64_t size) &&;
StringsBuffer Build() && { return std::move(*this).Build(offsets_.size()); }
private:
friend class Inserter;
void ResizeCharacters(size_t new_size);
void InitDataPointers(std::tuple<RawBufferPtr, void*>&& buf,
int64_t offsets_count, int64_t characters_size);
RawBufferFactory* factory_;
RawBufferPtr buf_;
absl::Span<Offsets> offsets_;
absl::Span<char> characters_;
offset_type num_chars_ = 0;
};
class ReshuffleBuilder {
public:
explicit ReshuffleBuilder(
int64_t max_size, const StringsBuffer& buffer,
const OptionalValue<absl::string_view>& default_value,
RawBufferFactory* buf_factory = GetHeapBufferFactory());
void CopyValue(int64_t new_index, int64_t old_index) {
offsets_bldr_.Set(new_index, old_offsets_[old_index]);
}
void CopyValueToRange(int64_t new_index_from, int64_t new_index_to,
int64_t old_index) {
auto* new_offsets = offsets_bldr_.GetMutableSpan().begin();
std::fill(new_offsets + new_index_from, new_offsets + new_index_to,
old_offsets_[old_index]);
}
StringsBuffer Build(int64_t size) && {
return StringsBuffer(std::move(offsets_bldr_).Build(size),
std::move(characters_), base_offset_);
}
StringsBuffer Build() && {
return StringsBuffer(std::move(offsets_bldr_).Build(),
std::move(characters_), base_offset_);
}
private:
SimpleBuffer<Offsets>::Builder offsets_bldr_;
SimpleBuffer<Offsets> old_offsets_;
SimpleBuffer<char> characters_;
offset_type base_offset_;
};
static StringsBuffer CreateUninitialized(
size_t size, RawBufferFactory* factory = GetHeapBufferFactory()) {
if (size <= kZeroInitializedBufferSize / sizeof(Offsets)) {
return StringsBuffer(
SimpleBuffer<Offsets>(nullptr, absl::Span<const Offsets>(
static_cast<const Offsets*>(
GetZeroInitializedBuffer()),
size)),
SimpleBuffer<char>{nullptr, absl::Span<const char>()});
}
SimpleBuffer<Offsets>::Builder builder(size, factory);
std::memset(builder.GetMutableSpan().data(), 0, size * sizeof(Offsets));
return StringsBuffer(std::move(builder).Build(),
SimpleBuffer<char>{nullptr, absl::Span<const char>()});
}
template <class InputIt>
static StringsBuffer Create(
InputIt begin, InputIt end,
RawBufferFactory* factory = GetHeapBufferFactory()) {
auto size = std::distance(begin, end);
if (size > 0) {
Builder builder(size, factory);
for (int64_t offset = 0; offset < size; begin++, offset++) {
builder.Set(offset, *begin);
}
return std::move(builder).Build(size);
} else {
return StringsBuffer();
}
}
bool empty() const { return offsets_.empty(); }
bool is_owner() const {
return offsets_.is_owner() && characters_.is_owner();
}
size_type size() const { return offsets_.size(); }
size_t memory_usage() const {
return offsets().memory_usage() + characters().memory_usage();
}
absl::string_view operator[](size_type i) const {
DCHECK_LE(0, i);
DCHECK_LT(i, size());
auto start = offsets_[i].start;
auto end = offsets_[i].end;
return absl::string_view(characters_.begin() + start - base_offset_,
end - start);
}
bool operator==(const StringsBuffer& other) const;
bool operator!=(const StringsBuffer& other) const {
return !(*this == other);
}
StringsBuffer ShallowCopy() const;
StringsBuffer DeepCopy(RawBufferFactory* = GetHeapBufferFactory()) const;
const_iterator begin() const { return const_iterator{this, 0}; }
const_iterator end() const { return const_iterator{this, size()}; }
absl::string_view front() const { return (*this)[0]; }
absl::string_view back() const { return (*this)[size() - 1]; }
StringsBuffer Slice(size_type offset) const& {
return Slice(offset, size() - offset);
}
StringsBuffer Slice(size_type offset, size_type count) const&;
StringsBuffer Slice(size_type offset) && {
return std::move(*this).Slice(offset, size() - offset);
}
StringsBuffer Slice(size_type offset, size_type count) &&;
const SimpleBuffer<Offsets>& offsets() const { return offsets_; }
const SimpleBuffer<char>& characters() const { return characters_; }
offset_type base_offset() const { return base_offset_; }
template <typename H>
friend H AbslHashValue(H h, const StringsBuffer& buffer) {
h = H::combine(std::move(h), buffer.size());
if (!buffer.empty()) {
auto* start = reinterpret_cast<const char*>(&*buffer.offsets().begin());
const size_t size = buffer.size() * sizeof(Offsets);
h = H::combine_contiguous(std::move(h), start, size);
h = H::combine(std::move(h), buffer.characters());
}
return h;
}
private:
SimpleBuffer<Offsets> offsets_;
SimpleBuffer<char> characters_;
offset_type base_offset_ = 0;
};
template <>
struct ArenaTraits<StringsBuffer> {
static StringsBuffer MakeOwned(StringsBuffer&& v,
RawBufferFactory* buf_factory) {
return v.DeepCopy(buf_factory);
}
};
AROLLA_DECLARE_FINGERPRINT_HASHER_TRAITS(StringsBuffer);
}
#endif
#include "arolla/memory/strings_buffer.h"
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <limits>
#include <tuple>
#include <utility>
#include "absl/log/check.h"
#include "absl/strings/string_view.h"
#include "absl/types/span.h"
#include "arolla/memory/optional_value.h"
#include "arolla/memory/raw_buffer_factory.h"
#include "arolla/memory/simple_buffer.h"
#include "arolla/util/fingerprint.h"
namespace arolla {
StringsBuffer::Builder::Builder(int64_t max_size, RawBufferFactory* factory)
: factory_(factory) {
size_t initial_char_buffer_size = max_size * 16;
DCHECK_LT(initial_char_buffer_size, std::numeric_limits<offset_type>::max());
size_t offsets_size = max_size * sizeof(Offsets);
InitDataPointers(
factory->CreateRawBuffer(offsets_size + initial_char_buffer_size),
max_size, initial_char_buffer_size);
std::memset(offsets_.data(), 0, offsets_size);
}
StringsBuffer::ReshuffleBuilder::ReshuffleBuilder(
int64_t max_size, const StringsBuffer& buffer,
const OptionalValue<absl::string_view>& default_value,
RawBufferFactory* buf_factory)
: offsets_bldr_(max_size, buf_factory),
old_offsets_(buffer.offsets()),
characters_(buffer.characters()),
base_offset_(buffer.base_offset()) {
if (default_value.present && !default_value.value.empty()) {
int64_t def_value_size = default_value.value.size();
offsets_bldr_.SetNConst(
0, max_size, {characters_.size(), def_value_size + characters_.size()});
SimpleBuffer<char>::Builder chars_bldr(characters_.size() + def_value_size,
buf_factory);
char* data = chars_bldr.GetMutableSpan().data();
std::memcpy(data, characters_.begin(), characters_.size());
std::memcpy(data + characters_.size(), default_value.value.begin(),
def_value_size);
characters_ = std::move(chars_bldr).Build();
} else {
std::memset(offsets_bldr_.GetMutableSpan().begin(), 0,
max_size * sizeof(Offsets));
}
}
StringsBuffer StringsBuffer::Builder::Build(int64_t size) && {
DCHECK_LE(size, offsets_.size());
if (num_chars_ != characters_.size()) {
ResizeCharacters(num_chars_);
}
SimpleBuffer<Offsets> offsets(buf_, offsets_.subspan(0, size));
SimpleBuffer<char> characters(std::move(buf_),
characters_.subspan(0, num_chars_));
return StringsBuffer(std::move(offsets), std::move(characters));
}
void StringsBuffer::Builder::ResizeCharacters(size_t new_size) {
DCHECK_LT(new_size, std::numeric_limits<offset_type>::max());
size_t offsets_size = offsets_.size() * sizeof(Offsets);
InitDataPointers(factory_->ReallocRawBuffer(std::move(buf_), offsets_.begin(),
offsets_size + characters_.size(),
offsets_size + new_size),
offsets_.size(), new_size);
}
void StringsBuffer::Builder::InitDataPointers(
std::tuple<RawBufferPtr, void*>&& buf, int64_t offsets_count,
int64_t characters_size) {
buf_ = std::move(std::get<0>(buf));
void* data = std::get<1>(buf);
offsets_ =
absl::Span<Offsets>(reinterpret_cast<Offsets*>(data), offsets_count);
characters_ = absl::Span<char>(
reinterpret_cast<char*>(data) + offsets_count * sizeof(Offsets),
characters_size);
}
StringsBuffer::StringsBuffer(SimpleBuffer<StringsBuffer::Offsets> offsets,
SimpleBuffer<char> characters,
offset_type base_offset)
: offsets_(std::move(offsets)),
characters_(std::move(characters)),
base_offset_(base_offset) {
for (int64_t i = 0; i < offsets_.size(); ++i) {
DCHECK_LE(base_offset_, offsets_[i].start);
DCHECK_LE(offsets_[i].start, offsets_[i].end);
DCHECK_LE(offsets_[i].end, base_offset_ + characters_.size());
}
}
bool StringsBuffer::operator==(const StringsBuffer& other) const {
if (this == &other) {
return true;
}
if (size() != other.size()) {
return false;
}
return std::equal(begin(), end(), other.begin());
}
StringsBuffer StringsBuffer::Slice(int64_t offset, int64_t count) const& {
if (count == 0) {
return StringsBuffer{};
}
return StringsBuffer{offsets_.Slice(offset, count), characters_,
base_offset_};
}
StringsBuffer StringsBuffer::Slice(int64_t offset, int64_t count) && {
if (count == 0) {
return StringsBuffer{};
}
return StringsBuffer{std::move(offsets_).Slice(offset, count),
std::move(characters_), base_offset_};
}
StringsBuffer StringsBuffer::ShallowCopy() const {
return StringsBuffer(offsets_.ShallowCopy(), characters_.ShallowCopy(),
base_offset_);
}
StringsBuffer StringsBuffer::DeepCopy(RawBufferFactory* buffer_factory) const {
if (size() == 0) {
return StringsBuffer{};
}
offset_type min_offset = offsets_[0].start;
offset_type max_offset = offsets_[0].end;
for (int64_t i = 1; i < size(); ++i) {
min_offset = std::min(min_offset, offsets_[i].start);
max_offset = std::max(max_offset, offsets_[i].end);
}
auto characters_slice =
characters_.Slice(min_offset - base_offset_, max_offset - min_offset);
return StringsBuffer(offsets_.DeepCopy(buffer_factory),
characters_slice.DeepCopy(buffer_factory), min_offset);
}
void FingerprintHasherTraits<StringsBuffer>::operator()(
FingerprintHasher* hasher, const StringsBuffer& value) const {
hasher->Combine(value.size());
if (!value.empty()) {
auto offsets_span = value.offsets().span();
hasher->CombineRawBytes(offsets_span.data(),
offsets_span.size() * sizeof(offsets_span[0]));
hasher->CombineSpan(value.characters().span());
}
}
}
|
#include <array>
#include <cstddef>
#include <initializer_list>
#include <optional>
#include <string>
#include <utility>
#include <vector>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/hash/hash_testing.h"
#include "absl/strings/str_format.h"
#include "absl/strings/string_view.h"
#include "arolla/memory/buffer.h"
#include "arolla/util/fingerprint.h"
namespace arolla {
namespace {
using ::testing::ElementsAre;
using ::testing::ElementsAreArray;
using ::testing::IsEmpty;
using ::testing::Not;
class StringsBufferTest : public ::testing::Test {
public:
Buffer<std::string> CreateTestBuffer(int num_rows) {
std::vector<std::string> values(num_rows);
for (int i = 0; i < num_rows; i++) {
values[i] = absl::StrFormat("str%d", i);
}
return Buffer<std::string>::Create(values.begin(), values.end());
}
template <typename T>
Buffer<std::string> CreateTestBuffer(std::initializer_list<T> values) {
return Buffer<std::string>::Create(values.begin(), values.end());
}
};
TEST_F(StringsBufferTest, Simple) {
Buffer<std::string> buffer = CreateTestBuffer(4);
EXPECT_TRUE(buffer.is_owner());
EXPECT_THAT(buffer, ElementsAre("str0", "str1", "str2", "str3"));
EXPECT_EQ(buffer[0], "str0");
EXPECT_EQ(buffer[3], "str3");
}
TEST_F(StringsBufferTest, Empty) {
Buffer<std::string> buffer1 = CreateTestBuffer(0);
EXPECT_THAT(buffer1, IsEmpty());
Buffer<std::string> buffer2 = buffer1.DeepCopy();
EXPECT_THAT(buffer2, IsEmpty());
Buffer<std::string> buffer3;
EXPECT_THAT(buffer3, IsEmpty());
}
TEST_F(StringsBufferTest, Move) {
size_t num_rows = 4;
Buffer<std::string> buffer = CreateTestBuffer(num_rows);
EXPECT_TRUE(buffer.is_owner());
Buffer<std::string> buffer2 = std::move(buffer);
EXPECT_TRUE(buffer2.is_owner());
EXPECT_FALSE(buffer.is_owner());
EXPECT_THAT(buffer2, ElementsAre("str0", "str1", "str2", "str3"));
Buffer<std::string> buffer3;
EXPECT_TRUE(buffer3.is_owner());
buffer3 = std::move(buffer2);
EXPECT_TRUE(buffer3.is_owner());
EXPECT_FALSE(buffer2.is_owner());
EXPECT_THAT(buffer3, ElementsAre("str0", "str1", "str2", "str3"));
}
TEST_F(StringsBufferTest, MemoryUsage) {
EXPECT_EQ(sizeof(Buffer<StringsBuffer::Offsets>), 4 * sizeof(void*));
EXPECT_EQ(sizeof(Buffer<char>), 4 * sizeof(void*));
EXPECT_EQ(sizeof(Buffer<std::string>),
sizeof(Buffer<StringsBuffer::Offsets>) + sizeof(Buffer<char>) + 8);
for (size_t sz = 0; sz < 10; sz += 1) {
const size_t chars = sz * 4;
const size_t offsets = sz * sizeof(StringsBuffer::Offsets);
Buffer<std::string> buffer = CreateTestBuffer(sz);
EXPECT_EQ(chars + offsets, buffer.memory_usage());
}
}
TEST_F(StringsBufferTest, MoveSlice) {
size_t num_rows = 10;
Buffer<std::string> buffer = CreateTestBuffer(num_rows);
EXPECT_TRUE(buffer.is_owner());
buffer = std::move(buffer).Slice(0, 5);
EXPECT_TRUE(buffer.is_owner());
EXPECT_THAT(buffer, ElementsAre("str0", "str1", "str2", "str3", "str4"));
Buffer<std::string> buffer2 = std::move(buffer).Slice(2, 3);
EXPECT_TRUE(buffer2.is_owner());
EXPECT_FALSE(buffer.is_owner());
EXPECT_THAT(buffer2, ElementsAre("str2", "str3", "str4"));
}
TEST_F(StringsBufferTest, ShallowCopy) {
size_t num_rows = 10;
Buffer<std::string> buffer = CreateTestBuffer(num_rows);
Buffer<std::string> buffer_copy1 = buffer.ShallowCopy();
EXPECT_FALSE(buffer_copy1.is_owner());
EXPECT_EQ(buffer.begin(), buffer_copy1.begin());
EXPECT_EQ(buffer.end(), buffer_copy1.end());
EXPECT_THAT(buffer, ElementsAreArray(buffer_copy1));
Buffer<std::string> buffer_copy2 = buffer.Slice(5, 5);
EXPECT_THAT(buffer, Not(ElementsAreArray(buffer_copy2)));
EXPECT_TRUE(buffer_copy2.is_owner());
EXPECT_EQ(buffer[5], buffer_copy2[0]);
}
TEST_F(StringsBufferTest, DeepCopy) {
size_t num_rows = 5;
Buffer<std::string> buffer = CreateTestBuffer(num_rows);
Buffer<std::string> buffer_copy = buffer.DeepCopy();
Buffer<std::string> buffer_slice_copy = buffer.Slice(1, 3).DeepCopy();
buffer = Buffer<std::string>();
EXPECT_TRUE(buffer_copy.is_owner());
EXPECT_THAT(buffer_copy, ElementsAre("str0", "str1", "str2", "str3", "str4"));
EXPECT_TRUE(buffer_slice_copy.is_owner());
EXPECT_THAT(buffer_slice_copy, ElementsAre("str1", "str2", "str3"));
buffer_copy = buffer.DeepCopy();
EXPECT_THAT(buffer_copy, IsEmpty());
}
TEST_F(StringsBufferTest, EmptySlice) {
size_t num_rows = 10;
Buffer<std::string> buffer = CreateTestBuffer(num_rows);
Buffer<std::string> copy = buffer.Slice(3, 0);
EXPECT_THAT(copy, IsEmpty());
buffer = std::move(buffer).Slice(3, 0);
EXPECT_THAT(buffer, IsEmpty());
copy = buffer.Slice(0, 0);
EXPECT_THAT(copy, IsEmpty());
}
TEST_F(StringsBufferTest, HugeString) {
StringsBuffer::Builder builder(2);
builder.Set(0, "small string");
std::string huge_string;
for (int i = 0; i < 1000; ++i) huge_string.append("huge string; ");
builder.Set(1, huge_string);
StringsBuffer buffer = std::move(builder).Build(2);
EXPECT_EQ(buffer.size(), 2);
EXPECT_EQ(buffer[0], "small string");
EXPECT_EQ(buffer[1], huge_string);
}
TEST_F(StringsBufferTest, SupportsAbslHash) {
StringsBuffer empty;
std::array<absl::string_view, 5> values = {"one", "two", "three", "four",
"five"};
StringsBuffer test1 = StringsBuffer::Create(values.begin(), values.end());
StringsBuffer test2 = StringsBuffer::Create(values.rbegin(), values.rend());
EXPECT_TRUE(
absl::VerifyTypeImplementsAbslHashCorrectly({empty, test1, test2}));
}
TEST_F(StringsBufferTest, Fingerprint) {
std::array<absl::string_view, 5> values = {"one", "two", "three", "four",
"five"};
StringsBuffer test1 = StringsBuffer::Create(values.begin(), values.end());
StringsBuffer test2 = StringsBuffer::Create(values.begin(), values.end());
StringsBuffer test3 = StringsBuffer::Create(values.rbegin(), values.rend());
Fingerprint f1 = FingerprintHasher("salt").Combine(test1).Finish();
Fingerprint f2 = FingerprintHasher("salt").Combine(test2).Finish();
Fingerprint f3 = FingerprintHasher("salt").Combine(test3).Finish();
EXPECT_EQ(f1, f2);
EXPECT_NE(f1, f3);
}
TEST(StringsBufferBuilder, Inserter) {
Buffer<std::string>::Builder builder(10);
auto inserter = builder.GetInserter(1);
for (int i = 0; i < 4; ++i) inserter.Add(absl::StrFormat("str%d", i));
builder.Set(0, "aba");
auto buffer = std::move(builder).Build(inserter);
EXPECT_THAT(buffer, ElementsAre("aba", "str0", "str1", "str2", "str3"));
}
TEST(StringsBufferBuilder, InserterCord) {
Buffer<std::string>::Builder builder(10);
auto inserter = builder.GetInserter(1);
for (int i = 0; i < 4; ++i) {
inserter.Add(absl::Cord(absl::StrFormat("str%d", i)));
}
builder.Set(0, "aba");
auto buffer = std::move(builder).Build(inserter);
EXPECT_THAT(buffer, ElementsAre("aba", "str0", "str1", "str2", "str3"));
}
TEST(StringsBufferBuilder, Generator) {
Buffer<std::string>::Builder builder(10);
builder.SetNConst(0, 10, "default");
int i = 0;
builder.SetN(2, 3, [&]() { return absl::StrFormat("str%d", ++i); });
auto buffer = std::move(builder).Build(6);
EXPECT_THAT(buffer, ElementsAre("default", "default", "str1", "str2", "str3",
"default"));
}
TEST(StringsBufferBuilder, RandomAccess) {
Buffer<std::string>::Builder builder(10);
builder.Set(4, "s1");
builder.Set(2, "s2");
builder.Set(1, "s3");
builder.Set(0, "s4");
builder.Set(3, "s5");
builder.Set(1, "s6");
auto buffer = std::move(builder).Build(5);
EXPECT_THAT(buffer, ElementsAre("s4", "s6", "s2", "s5", "s1"));
}
TEST(StringsBufferBuilder, RandomAccessCord) {
Buffer<std::string>::Builder builder(10);
builder.Set(4, absl::Cord("s1"));
builder.Set(2, absl::Cord("s2"));
builder.Set(1, absl::Cord("s3"));
builder.Set(0, absl::Cord("s4"));
builder.Set(3, absl::Cord("s5"));
builder.Set(1, absl::Cord("s6"));
auto buffer = std::move(builder).Build(5);
EXPECT_THAT(buffer, ElementsAre("s4", "s6", "s2", "s5", "s1"));
}
TEST(StringsBufferBuilder, ReshuffleBuilder) {
auto buf = CreateBuffer<std::string>({"5v", "4ab", "3", "2", "1"});
{
Buffer<std::string>::ReshuffleBuilder bldr(7, buf, std::nullopt);
bldr.CopyValue(3, 1);
bldr.CopyValue(1, 2);
bldr.CopyValue(2, 0);
bldr.CopyValueToRange(4, 7, 0);
auto res = std::move(bldr).Build();
EXPECT_THAT(res, ElementsAre("", "3", "5v", "4ab", "5v", "5v", "5v"));
EXPECT_EQ(res.characters().begin(), buf.characters().begin());
}
{
Buffer<std::string>::ReshuffleBuilder bldr(4, buf, {true, ""});
bldr.CopyValue(3, 1);
bldr.CopyValue(1, 2);
bldr.CopyValue(2, 0);
auto res = std::move(bldr).Build();
EXPECT_THAT(res, ElementsAre("", "3", "5v", "4ab"));
EXPECT_EQ(res.characters().begin(), buf.characters().begin());
}
{
Buffer<std::string>::ReshuffleBuilder bldr(4, buf, {true, "0abc"});
bldr.CopyValue(3, 1);
bldr.CopyValue(1, 2);
bldr.CopyValue(2, 0);
auto res = std::move(bldr).Build();
EXPECT_THAT(res, ElementsAre("0abc", "3", "5v", "4ab"));
}
}
}
}
|
arolla
|
#ifndef AROLLA_MEMORY_FRAME_H_
#define AROLLA_MEMORY_FRAME_H_
#include <algorithm>
#include <cstddef>
#include <cstdlib>
#include <cstring>
#include <initializer_list>
#include <ostream>
#include <tuple>
#include <type_traits>
#include <typeindex>
#include <typeinfo>
#include <utility>
#include <vector>
#include "absl/base/attributes.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/types/span.h"
#include "arolla/memory/frame.h"
#include "arolla/util/algorithms.h"
#include "arolla/util/demangle.h"
#include "arolla/util/is_bzero_constructible.h"
#include "arolla/util/memory.h"
#include "arolla/util/struct_field.h"
namespace arolla {
class FrameLayout {
public:
class Builder;
template <typename T>
class Slot;
FrameLayout() = default;
size_t AllocSize() const { return alloc_size_; }
Alignment AllocAlignment() const { return alloc_alignment_; }
void InitializeAlignedAlloc(void* alloc) const;
void DestroyAlloc(void* alloc) const;
void InitializeAlignedAllocN(void* alloc, size_t n) const;
void DestroyAllocN(void* alloc, size_t n) const;
bool HasField(size_t offset, const std::type_info& type) const;
private:
explicit FrameLayout(Builder&& builder);
class FieldFactory;
struct FieldInitializers {
void AddOffsetToFactory(size_t offset, FieldFactory empty_factory);
void AddDerived(size_t extra_offset,
const FieldInitializers& derived_initializers);
template <class T>
void Add(size_t offset);
std::vector<FieldFactory> factories;
absl::flat_hash_map<std::type_index, size_t> type2factory;
};
#ifndef NDEBUG
absl::flat_hash_set<std::pair<size_t, std::type_index>> registered_fields_;
#endif
FieldInitializers initializers_;
size_t alloc_size_{0};
Alignment alloc_alignment_{1};
};
template <typename T>
struct TypesToSlotTypes;
template <typename... Ts>
struct TypesToSlotTypes<std::tuple<Ts...>> {
using type = std::tuple<FrameLayout::Slot<Ts>...>;
};
template <typename T>
class FrameLayout::Slot {
static constexpr size_t kNumSubslots = StructFieldCount<T>();
static_assert(std::is_standard_layout<T>::value || (kNumSubslots == 0),
"Only standard layout classes support access to subfields.");
public:
using value_type = T;
Slot(const Slot& other) = default;
size_t byte_offset() const { return byte_offset_; }
static Slot<T> UnsafeSlotFromOffset(size_t byte_offset) {
return Slot(byte_offset);
}
static constexpr size_t kUninitializedOffset = ~static_cast<size_t>(0);
static Slot<T> UnsafeUninitializedSlot() {
return Slot(kUninitializedOffset);
}
friend std::ostream& operator<<(std::ostream& stream,
const FrameLayout::Slot<T>& slot) {
return stream << "Slot<" << TypeName<T>() << ">(" << slot.byte_offset()
<< ")";
}
static constexpr size_t NumSubslots() { return kNumSubslots; }
template <size_t I>
auto GetSubslot() {
static_assert(I < kNumSubslots, "Subslot Index out of range.");
const auto& struct_field = std::get<I>(GetStructFields<T>());
return FrameLayout::Slot<
typename std::decay_t<decltype(struct_field)>::field_type>::
UnsafeSlotFromOffset(byte_offset_ + struct_field.field_offset);
}
private:
friend class Builder;
friend class FramePtr;
friend class ConstFramePtr;
explicit Slot(size_t byte_offset) : byte_offset_(byte_offset) {}
decltype(auto) UnsafeGet(const void* alloc) const {
DCHECK_NE(byte_offset_, kUninitializedOffset);
return *reinterpret_cast<const T*>(static_cast<const char*>(alloc) +
byte_offset_);
}
T* UnsafeGetMutable(void* alloc) const {
DCHECK_NE(byte_offset_, kUninitializedOffset);
return reinterpret_cast<T*>(static_cast<char*>(alloc) + byte_offset_);
}
size_t byte_offset_;
};
class FrameLayout::FieldFactory {
public:
template <typename T>
static FieldFactory Create() {
static_assert(!is_bzero_constructible<T>() ||
!std::is_trivially_destructible<T>());
FactoryFn construct;
FactoryNFn construct_n;
if constexpr (is_bzero_constructible<T>()) {
construct = [](void*, absl::Span<const size_t>) {};
construct_n = [](void*, absl::Span<const size_t>, size_t, size_t) {};
} else {
construct = [](void* ptr, absl::Span<const size_t> offsets) {
for (size_t offset : offsets) {
void* shifted_ptr = static_cast<char*>(ptr) + offset;
new (shifted_ptr) T;
}
};
construct_n = [](void* ptr, absl::Span<const size_t> offsets,
size_t block_size, size_t n) {
for (size_t i = 0; i < n; ++i) {
for (size_t offset : offsets) {
void* shifted_ptr =
static_cast<char*>(ptr) + offset + i * block_size;
new (shifted_ptr) T;
}
}
};
}
FactoryFn destruct;
FactoryNFn destruct_n;
if constexpr (std::is_trivially_destructible<T>()) {
destruct = [](void*, absl::Span<const size_t>) {};
destruct_n = [](void*, absl::Span<const size_t>, size_t, size_t) {};
} else {
destruct = [](void* ptr, absl::Span<const size_t> offsets) {
for (size_t offset : offsets) {
void* shifted_ptr = static_cast<char*>(ptr) + offset;
static_cast<T*>(shifted_ptr)->~T();
}
};
destruct_n = [](void* ptr, absl::Span<const size_t> offsets,
size_t block_size, size_t n) {
for (size_t i = 0; i < n; ++i) {
for (size_t offset : offsets) {
void* shifted_ptr =
static_cast<char*>(ptr) + offset + i * block_size;
static_cast<T*>(shifted_ptr)->~T();
}
}
};
}
return FieldFactory(std::type_index(typeid(T)), construct, destruct,
construct_n, destruct_n);
}
std::type_index type_index() const;
void Add(size_t offset);
void AddDerived(const FieldFactory& derived_factory);
FieldFactory Derive(size_t offset) const;
void Construct(void* ptr) const { construct_(ptr, offsets_); }
void Destroy(void* ptr) const { destruct_(ptr, offsets_); }
void ConstructN(void* ptr, size_t block_size, size_t n) const {
construct_n_(ptr, offsets_, block_size, n);
}
void DestroyN(void* ptr, size_t block_size, size_t n) const {
destruct_n_(ptr, offsets_, block_size, n);
}
private:
using FactoryFn = void (*)(void*, absl::Span<const size_t>);
using FactoryNFn = void (*)(void*, absl::Span<const size_t>, size_t, size_t);
FieldFactory(std::type_index tpe, FactoryFn construct, FactoryFn destruct,
FactoryNFn construct_n, FactoryNFn destruct_n)
: type_(tpe),
construct_(construct),
destruct_(destruct),
construct_n_(construct_n),
destruct_n_(destruct_n) {}
std::type_index type_;
FactoryFn construct_;
FactoryFn destruct_;
std::vector<size_t> offsets_;
FactoryNFn construct_n_;
FactoryNFn destruct_n_;
};
template <class T>
void FrameLayout::FieldInitializers::Add(size_t offset) {
AddOffsetToFactory(offset, FieldFactory::Create<T>());
}
inline void FrameLayout::InitializeAlignedAlloc(void* alloc) const {
DCHECK(IsAlignedPtr(alloc_alignment_, alloc)) << "invalid alloc alignment";
memset(alloc, 0, alloc_size_);
for (const auto& factory : initializers_.factories) {
factory.Construct(alloc);
}
}
inline void FrameLayout::DestroyAlloc(void* alloc) const {
for (const auto& factory : initializers_.factories) {
factory.Destroy(alloc);
}
}
inline void FrameLayout::InitializeAlignedAllocN(void* alloc, size_t n) const {
DCHECK(IsAlignedPtr(alloc_alignment_, alloc)) << "invalid alloc alignment";
memset(alloc, 0, alloc_size_ * n);
for (const auto& factory : initializers_.factories) {
factory.ConstructN(alloc, alloc_size_, n);
}
}
inline void FrameLayout::DestroyAllocN(void* alloc, size_t n) const {
for (const auto& factory : initializers_.factories) {
factory.DestroyN(alloc, alloc_size_, n);
}
}
class FrameLayout::Builder {
public:
template <typename T>
ABSL_ATTRIBUTE_ALWAYS_INLINE Slot<T> AddSlot() {
static_assert(alignof(T) <= 16,
"Types with strong alignments are not supported.");
alloc_size_ = RoundUp(alloc_size_, alignof(T));
size_t offset = alloc_size_;
Slot<T> slot(offset);
alloc_size_ += sizeof(T);
alloc_alignment_ = std::max(alloc_alignment_, alignof(T));
if constexpr (!is_bzero_constructible<T>() ||
!std::is_trivially_destructible<T>()) {
initializers_.Add<T>(offset);
}
auto status = RegisterSlot(slot.byte_offset(), sizeof(T), typeid(T));
DCHECK(status.ok()) << status.message()
<< "Internal error during RegisterSlot.";
status =
RegisterSubslots(slot, std::make_index_sequence<slot.NumSubslots()>());
DCHECK(status.ok()) << status.message()
<< "Internal error during RegisterSubslots.";
return slot;
}
Slot<void> AddSubFrame(const FrameLayout& subframe);
absl::Status RegisterUnsafeSlot(size_t byte_offset, size_t byte_size,
const std::type_info& type);
template <typename T>
absl::Status RegisterUnsafeSlot(const Slot<T>& slot,
bool allow_duplicates = false) {
return RegisterSlot(slot.byte_offset(), sizeof(T), typeid(T),
allow_duplicates);
}
FrameLayout Build() && {
alloc_size_ = RoundUp(alloc_size_, alloc_alignment_);
return FrameLayout(std::move(*this));
}
private:
friend class FrameLayout;
template <typename T, size_t... Is>
absl::Status RegisterSubslots(
Slot<T> slot ABSL_ATTRIBUTE_UNUSED,
std::index_sequence<Is...>) {
ABSL_ATTRIBUTE_UNUSED auto register_slot_recursively =
[&](auto subslot) -> absl::Status {
absl::Status status = RegisterUnsafeSlot(subslot);
if constexpr (decltype(subslot)::NumSubslots() != 0) {
if (status.ok()) {
status = RegisterSubslots(
subslot,
std::make_index_sequence<decltype(subslot)::NumSubslots()>());
}
}
return status;
};
for (absl::Status status : std::initializer_list<absl::Status>{
register_slot_recursively(slot.template GetSubslot<Is>())...}) {
if (!status.ok()) return status;
}
return absl::OkStatus();
}
absl::Status RegisterSlot(size_t byte_offset, size_t byte_size,
const std::type_info& type,
bool allow_duplicates = false);
#ifndef NDEBUG
absl::flat_hash_set<std::pair<size_t, std::type_index>> registered_fields_;
#endif
FieldInitializers initializers_;
size_t alloc_size_{0};
size_t alloc_alignment_{1};
};
template <typename T>
FrameLayout MakeTypeLayout() {
FrameLayout::Builder builder;
auto slot = builder.AddSlot<T>();
DCHECK_EQ(slot.byte_offset(), size_t{0});
return std::move(builder).Build();
}
class FramePtr {
public:
FramePtr(void* base_ptr, const FrameLayout* layout);
template <typename T>
T* GetMutable(FrameLayout::Slot<T> slot) const {
DCheckFieldType(slot.byte_offset(), typeid(T));
return slot.UnsafeGetMutable(base_ptr_);
}
template <typename T, typename S = T>
void Set(FrameLayout::Slot<T> slot, S&& value) const {
DCheckFieldType(slot.byte_offset(), typeid(T));
*GetMutable(slot) = std::forward<S>(value);
}
template <typename T>
const T& Get(FrameLayout::Slot<T> slot) const {
DCheckFieldType(slot.byte_offset(), typeid(T));
return slot.UnsafeGet(base_ptr_);
}
void* GetRawPointer(size_t byte_offset) const {
return static_cast<char*>(base_ptr_) + byte_offset;
}
void DCheckFieldType(size_t offset, const std::type_info& type) const;
private:
friend class ConstFramePtr;
void* base_ptr_;
#ifndef NDEBUG
const FrameLayout* layout_;
#endif
};
class ConstFramePtr {
public:
ConstFramePtr(const void* base_ptr, const FrameLayout* layout);
ConstFramePtr(FramePtr frame_ptr);
template <typename T>
const T& Get(FrameLayout::Slot<T> slot) const {
DCheckFieldType(slot.byte_offset(), typeid(T));
return slot.UnsafeGet(base_ptr_);
}
const void* GetRawPointer(size_t byte_offset) const {
return static_cast<const char*>(base_ptr_) + byte_offset;
}
void DCheckFieldType(size_t offset, const std::type_info& type) const;
private:
const void* base_ptr_;
#ifndef NDEBUG
const FrameLayout* layout_;
#endif
};
#ifndef NDEBUG
inline bool FrameLayout::HasField(size_t offset,
const std::type_info& type) const {
return registered_fields_.contains({offset, std::type_index(type)});
}
inline FrameLayout::FrameLayout(Builder&& builder)
: registered_fields_(std::move(builder.registered_fields_)),
initializers_(std::move(builder.initializers_)),
alloc_size_(builder.alloc_size_),
alloc_alignment_{builder.alloc_alignment_} {}
inline FramePtr::FramePtr(void* base_ptr, const FrameLayout* layout)
: base_ptr_(base_ptr), layout_(layout) {}
inline void FramePtr::DCheckFieldType(size_t offset,
const std::type_info& type) const {
DCHECK(layout_->HasField(offset, type))
<< "Field with given offset and type not found: Slot<" << type.name()
<< ">(" << offset << ")";
}
inline ConstFramePtr::ConstFramePtr(const void* base_ptr,
const FrameLayout* layout)
: base_ptr_(base_ptr), layout_(layout) {}
inline ConstFramePtr::ConstFramePtr(FramePtr frame_ptr)
: base_ptr_(frame_ptr.base_ptr_), layout_(frame_ptr.layout_) {}
inline void ConstFramePtr::DCheckFieldType(size_t offset,
const std::type_info& type) const {
DCHECK(layout_->HasField(offset, type))
<< "Field with given offset and type not found: Slot<" << type.name()
<< ">(" << offset << ")";
}
#else
inline bool FrameLayout::HasField(size_t, const std::type_info&) const {
return true;
}
inline FrameLayout::FrameLayout(Builder&& builder)
: initializers_(std::move(builder.initializers_)),
alloc_size_(builder.alloc_size_),
alloc_alignment_{builder.alloc_alignment_} {}
inline FramePtr::FramePtr(void* base_ptr, const FrameLayout* )
: base_ptr_(base_ptr) {}
inline void FramePtr::DCheckFieldType(size_t ,
const std::type_info& ) const {}
inline ConstFramePtr::ConstFramePtr(const void* base_ptr,
const FrameLayout* )
: base_ptr_(base_ptr) {}
inline ConstFramePtr::ConstFramePtr(FramePtr frame_ptr)
: base_ptr_(frame_ptr.base_ptr_) {}
inline void ConstFramePtr::DCheckFieldType(
size_t , const std::type_info& ) const {}
#endif
}
#endif
#include "arolla/memory/frame.h"
#include <algorithm>
#include <cstddef>
#include <cstring>
#include <tuple>
#include <typeindex>
#include <typeinfo>
#include <utility>
#include "absl/log/check.h"
#include "absl/status/status.h"
#include "absl/strings/str_cat.h"
#include "arolla/util/algorithms.h"
#include "arolla/util/memory.h"
namespace arolla {
std::type_index FrameLayout::FieldFactory::type_index() const { return type_; }
void FrameLayout::FieldFactory::Add(size_t offset) {
offsets_.push_back(offset);
}
void FrameLayout::FieldFactory::AddDerived(
const FieldFactory& derived_factory) {
DCHECK(type_index() == derived_factory.type_index());
for (size_t cur_offset : derived_factory.offsets_) {
offsets_.push_back(cur_offset);
}
}
FrameLayout::FieldFactory FrameLayout::FieldFactory::Derive(
size_t offset) const {
FieldFactory res = *this;
for (size_t& cur_offset : res.offsets_) {
cur_offset += offset;
}
return res;
}
void FrameLayout::FieldInitializers::AddOffsetToFactory(
size_t offset, FieldFactory empty_factory) {
auto it = type2factory.find(empty_factory.type_index());
if (it == type2factory.end()) {
bool inserted;
std::tie(it, inserted) =
type2factory.emplace(empty_factory.type_index(), factories.size());
factories.push_back(std::move(empty_factory));
}
DCHECK_LT(it->second, factories.size());
if (it->second < factories.size()) {
factories[it->second].Add(offset);
}
}
void FrameLayout::FieldInitializers::AddDerived(
size_t offset, const FieldInitializers& derived_initializers) {
for (const auto& [derived_tpe, derived_id] :
derived_initializers.type2factory) {
const auto& derived_factory = derived_initializers.factories[derived_id];
if (auto it = type2factory.find(derived_tpe); it != type2factory.end()) {
factories[it->second].AddDerived(derived_factory.Derive(offset));
} else {
type2factory.emplace(derived_tpe, factories.size());
factories.push_back(derived_factory.Derive(offset));
}
}
}
FrameLayout::Slot<void> FrameLayout::Builder::AddSubFrame(
const FrameLayout& subframe) {
alloc_size_ = RoundUp(alloc_size_, subframe.AllocAlignment().value);
size_t offset = alloc_size_;
alloc_size_ += subframe.AllocSize();
alloc_alignment_ =
std::max(alloc_alignment_, subframe.AllocAlignment().value);
initializers_.AddDerived(offset, subframe.initializers_);
#ifndef NDEBUG
for (const auto& [field_offset, field_type] : subframe.registered_fields_) {
registered_fields_.emplace(offset + field_offset, field_type);
}
#endif
return FrameLayout::Slot<void>(offset);
}
absl::Status FrameLayout::Builder::RegisterUnsafeSlot(
size_t byte_offset, size_t byte_size, const std::type_info& type) {
return RegisterSlot(byte_offset, byte_size, type);
}
absl::Status FrameLayout::Builder::RegisterSlot(size_t byte_offset,
size_t byte_size,
const std::type_info& type,
bool allow_duplicates) {
if (byte_offset == FrameLayout::Slot<float>::kUninitializedOffset) {
return absl::FailedPreconditionError(
"unable to register uninitialized slot");
}
if (byte_offset > alloc_size_ || byte_size > alloc_size_ - byte_offset) {
return absl::FailedPreconditionError(absl::StrCat(
"unable to register slot after the end of alloc, offset: ", byte_offset,
", size: ", byte_size, ", alloc size: ", alloc_size_));
}
#ifndef NDEBUG
if (!registered_fields_.emplace(byte_offset, std::type_index(type)).second &&
!allow_duplicates) {
return absl::FailedPreconditionError(absl::StrCat(
"slot is already registered ", byte_offset, " ", type.name()));
}
#endif
return absl::OkStatus();
}
}
|
#include "arolla/memory/frame.h"
#include <array>
#include <cstddef>
#include <cstdint>
#include <memory>
#include <sstream>
#include <string>
#include <type_traits>
#include <utility>
#include <variant>
#include <vector>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/base/dynamic_annotations.h"
#include "absl/status/status.h"
#include "arolla/memory/memory_allocation.h"
#include "arolla/util/demangle.h"
#include "arolla/util/is_bzero_constructible.h"
#include "arolla/util/memory.h"
#include "arolla/util/testing/status_matchers_backport.h"
namespace arolla::testing {
namespace {
using ::arolla::testing::IsOk;
using ::arolla::testing::StatusIs;
using ::testing::ElementsAre;
using ::testing::Eq;
using ::testing::HasSubstr;
using ::testing::IsEmpty;
struct SimpleStruct {
int a;
float b;
};
struct InitializedStruct {
int a = 1;
float b = 2.0;
};
TEST(FrameLayoutTest, SlotOutput) {
FrameLayout::Builder builder;
auto slot = builder.AddSlot<int>();
std::ostringstream ss;
ss << slot;
EXPECT_EQ(ss.str(), std::string("Slot<") + TypeName<int>() + ">(0)");
}
TEST(FrameLayoutTest, SimpleFields) {
FrameLayout::Builder builder;
auto slot1 = builder.AddSlot<int>();
auto slot2 = builder.AddSlot<float>();
auto slot3 = builder.AddSlot<double>();
auto layout = std::move(builder).Build();
MemoryAllocation alloc(&layout);
FramePtr frame = alloc.frame();
EXPECT_THAT(frame.Get(slot1), Eq(0));
EXPECT_THAT(frame.Get(slot2), Eq(0.0f));
EXPECT_THAT(frame.Get(slot3), Eq(0.0));
frame.Set(slot1, 1);
frame.Set(slot2, 2.0f);
frame.Set(slot3, M_PI);
EXPECT_THAT(frame.Get(slot1), Eq(1));
EXPECT_THAT(frame.Get(slot2), Eq(2.0f));
EXPECT_THAT(frame.Get(slot3), Eq(M_PI));
}
TEST(FrameLayoutTest, SimpleArrays) {
FrameLayout::Builder builder;
auto slot1 = builder.AddSlot<std::array<int, 4>>();
auto slot2 = builder.AddSlot<std::array<float, 4>>();
auto slot3 = builder.AddSlot<std::array<char, 4>>();
auto layout = std::move(builder).Build();
MemoryAllocation alloc(&layout);
FramePtr frame = alloc.frame();
EXPECT_THAT(frame.Get(slot1), ElementsAre(0, 0, 0, 0));
EXPECT_THAT(frame.Get(slot2), ElementsAre(0.0f, 0.0f, 0.0f, 0.0f));
EXPECT_THAT(frame.Get(slot3), ElementsAre(0, 0, 0, 0));
frame.Set(slot1, std::array<int, 4>{1, 2, 3, 4});
frame.Set(slot2, std::array<float, 4>{1.0f, 2.0f, 3.0f, 4.0f});
frame.Set(slot3, std::array<char, 4>{'a', 'b', 'c', 'd'});
EXPECT_THAT(frame.Get(slot1), ElementsAre(1, 2, 3, 4));
EXPECT_THAT(frame.Get(slot2), ElementsAre(1.0f, 2.0f, 3.0f, 4.0f));
EXPECT_THAT(frame.Get(slot3), ElementsAre('a', 'b', 'c', 'd'));
}
TEST(FrameLayoutTest, SimplePointers) {
FrameLayout::Builder builder;
auto slot1 = builder.AddSlot<int*>();
auto slot2 = builder.AddSlot<char*>();
auto layout = std::move(builder).Build();
MemoryAllocation alloc(&layout);
FramePtr frame = alloc.frame();
EXPECT_THAT(frame.Get(slot1), Eq(nullptr));
EXPECT_THAT(frame.Get(slot2), Eq(nullptr));
int int_values[] = {1, 2, 3, 4};
char text[] = "It was a dark and stormy night.";
frame.Set(slot1, int_values);
frame.Set(slot2, text);
EXPECT_THAT(frame.Get(slot1), Eq(int_values));
EXPECT_THAT(frame.Get(slot2), Eq(text));
}
TEST(FrameLayoutTest, SmartPointers) {
FrameLayout::Builder builder;
auto slot1 = builder.AddSlot<std::unique_ptr<int>>();
auto slot2 = builder.AddSlot<std::unique_ptr<std::string>>();
auto layout = std::move(builder).Build();
MemoryAllocation alloc(&layout);
FramePtr frame = alloc.frame();
EXPECT_THAT(frame.Get(slot1), Eq(nullptr));
EXPECT_THAT(frame.Get(slot2), Eq(nullptr));
frame.Set(slot1, std::make_unique<int>(12));
frame.Set(slot2,
std::make_unique<std::string>("It was a dark and stormy night."));
EXPECT_THAT(*frame.Get(slot1), Eq(12));
EXPECT_THAT(*frame.Get(slot2), Eq("It was a dark and stormy night."));
}
TEST(FrameLayoutTest, Vector) {
FrameLayout::Builder builder;
auto slot1 = builder.AddSlot<std::vector<int>>();
auto slot2 = builder.AddSlot<std::vector<std::string>>();
auto layout = std::move(builder).Build();
MemoryAllocation alloc(&layout);
FramePtr frame = alloc.frame();
EXPECT_THAT(frame.Get(slot1), IsEmpty());
EXPECT_THAT(frame.Get(slot2), IsEmpty());
auto* int_vector = frame.GetMutable(slot1);
int_vector->push_back(1);
int_vector->push_back(2);
int_vector->push_back(3);
auto* string_vector = frame.GetMutable(slot2);
string_vector->push_back("How");
string_vector->push_back("now");
string_vector->push_back("brown");
string_vector->push_back("cow?");
EXPECT_THAT(frame.Get(slot1), ElementsAre(1, 2, 3));
EXPECT_THAT(frame.Get(slot2), ElementsAre("How", "now", "brown", "cow?"));
}
TEST(FrameLayoutTest, Structs) {
FrameLayout::Builder builder;
auto slot1 = builder.AddSlot<SimpleStruct>();
auto slot2 = builder.AddSlot<InitializedStruct>();
auto layout = std::move(builder).Build();
MemoryAllocation alloc(&layout);
FramePtr frame = alloc.frame();
const SimpleStruct& s1 = frame.Get(slot1);
EXPECT_THAT(s1.a, Eq(0));
EXPECT_THAT(s1.b, Eq(0.0f));
const InitializedStruct& s2 = frame.Get(slot2);
EXPECT_THAT(s2.a, Eq(1));
EXPECT_THAT(s2.b, Eq(2.0f));
}
TEST(FrameLayoutTest, AFewDifferentTypesWellInitialized) {
FrameLayout::Builder builder;
auto slot1 = builder.AddSlot<std::vector<int>>();
auto slot2 = builder.AddSlot<std::vector<std::string>>();
auto slot3 = builder.AddSlot<std::vector<int>>();
auto slot4 = builder.AddSlot<SimpleStruct>();
auto slot5 = builder.AddSlot<InitializedStruct>();
auto slot6 = builder.AddSlot<std::vector<int>>();
auto slot7 = builder.AddSlot<std::vector<std::string>>();
auto slot8 = builder.AddSlot<std::vector<double>>();
auto slot9 = builder.AddSlot<InitializedStruct>();
auto layout = std::move(builder).Build();
MemoryAllocation alloc(&layout);
FramePtr frame = alloc.frame();
EXPECT_THAT(frame.Get(slot1), IsEmpty());
EXPECT_THAT(frame.Get(slot2), IsEmpty());
EXPECT_THAT(frame.Get(slot3), IsEmpty());
EXPECT_THAT(frame.Get(slot6), IsEmpty());
EXPECT_THAT(frame.Get(slot7), IsEmpty());
EXPECT_THAT(frame.Get(slot8), IsEmpty());
const SimpleStruct& simple = frame.Get(slot4);
EXPECT_THAT(simple.a, Eq(0));
EXPECT_THAT(simple.b, Eq(0.0f));
for (const InitializedStruct& init : {frame.Get(slot5), frame.Get(slot9)}) {
EXPECT_THAT(init.a, Eq(1));
EXPECT_THAT(init.b, Eq(2.0f));
}
}
TEST(FrameLayoutTest, HasField) {
FrameLayout::Builder builder;
auto slot1 = builder.AddSlot<int>();
auto slot2 = builder.AddSlot<std::vector<int>>();
auto slot3 = builder.AddSlot<SimpleStruct>();
auto slot4 = builder.AddSlot<std::array<SimpleStruct, 4>>();
auto slot5 = builder.AddSlot<InitializedStruct>();
auto slot6 = builder.AddSlot<std::array<InitializedStruct, 4>>();
auto layout = std::move(builder).Build();
EXPECT_TRUE(layout.HasField(slot1.byte_offset(), typeid(int)));
EXPECT_TRUE(layout.HasField(slot2.byte_offset(), typeid(std::vector<int>)));
EXPECT_TRUE(layout.HasField(slot3.byte_offset(), typeid(SimpleStruct)));
EXPECT_TRUE(layout.HasField(slot4.byte_offset(),
typeid(std::array<SimpleStruct, 4>)));
EXPECT_TRUE(layout.HasField(slot5.byte_offset(), typeid(InitializedStruct)));
EXPECT_TRUE(layout.HasField(slot6.byte_offset(),
typeid(std::array<InitializedStruct, 4>)));
}
TEST(FrameLayoutTest, RegisterUnsafeSlotWithEmptyField) {
FrameLayout::Builder builder;
ASSERT_TRUE(builder.RegisterUnsafeSlot(0, 0, typeid(std::monostate())).ok());
auto layout = std::move(builder).Build();
EXPECT_TRUE(layout.HasField(0, typeid(std::monostate())));
}
TEST(FrameLayoutTest, FieldDescriptorsRegisterUnsafe) {
FrameLayout::Builder builder;
auto slot = builder.AddSlot<int32_t>();
auto slot_1part =
FrameLayout::Slot<int16_t>::UnsafeSlotFromOffset(slot.byte_offset());
auto slot_2part =
FrameLayout::Slot<int16_t>::UnsafeSlotFromOffset(slot.byte_offset() + 2);
ASSERT_THAT(builder.RegisterUnsafeSlot(slot_1part), IsOk());
ASSERT_THAT(builder.RegisterUnsafeSlot(slot_2part), IsOk());
ASSERT_THAT(builder.RegisterUnsafeSlot(slot.byte_offset() + 2, sizeof(int8_t),
typeid(int8_t)),
IsOk());
#ifndef NDEBUG
EXPECT_THAT(builder.RegisterUnsafeSlot(slot_2part),
StatusIs(absl::StatusCode::kFailedPrecondition,
HasSubstr("slot is already registered")));
EXPECT_THAT(builder.RegisterUnsafeSlot(slot_2part, true),
IsOk());
#endif
auto layout = std::move(builder).Build();
EXPECT_TRUE(layout.HasField(slot.byte_offset(), typeid(int32_t)));
EXPECT_TRUE(layout.HasField(slot.byte_offset(), typeid(int16_t)));
EXPECT_TRUE(layout.HasField(slot.byte_offset() + 2, typeid(int16_t)));
EXPECT_TRUE(layout.HasField(slot.byte_offset() + 2, typeid(int8_t)));
#ifndef NDEBUG
EXPECT_FALSE(layout.HasField(slot.byte_offset() + 2, typeid(float)));
EXPECT_FALSE(layout.HasField(slot.byte_offset() + 1, typeid(int8_t)));
#endif
}
TEST(FrameLayoutTest, FieldDescriptorsRegisterUnsafeErrors) {
FrameLayout::Builder builder;
auto slot = builder.AddSlot<int32_t>();
auto slot_1part =
FrameLayout::Slot<int16_t>::UnsafeSlotFromOffset(slot.byte_offset());
auto slot_after_end =
FrameLayout::Slot<int16_t>::UnsafeSlotFromOffset(slot.byte_offset() + 4);
auto uninitialized_slot =
FrameLayout::Slot<int16_t>::UnsafeUninitializedSlot();
auto status = builder.RegisterUnsafeSlot(slot_1part);
ASSERT_OK(status);
#ifndef NDEBUG
status = builder.RegisterUnsafeSlot(slot);
ASSERT_FALSE(status.ok());
ASSERT_EQ(status.code(), absl::StatusCode::kFailedPrecondition);
EXPECT_THAT(status.message(), HasSubstr("slot is already registered"));
status = builder.RegisterUnsafeSlot(slot_1part);
ASSERT_FALSE(status.ok());
ASSERT_EQ(status.code(), absl::StatusCode::kFailedPrecondition);
EXPECT_THAT(status.message(), HasSubstr("slot is already registered"));
#endif
status = builder.RegisterUnsafeSlot(slot_after_end);
ASSERT_FALSE(status.ok());
ASSERT_EQ(status.code(), absl::StatusCode::kFailedPrecondition);
EXPECT_THAT(status.message(),
HasSubstr("unable to register slot after the end of alloc"));
status = builder.RegisterUnsafeSlot(100, sizeof(int), typeid(int));
ASSERT_FALSE(status.ok());
ASSERT_EQ(status.code(), absl::StatusCode::kFailedPrecondition);
EXPECT_THAT(status.message(),
HasSubstr("unable to register slot after the end of alloc, "
"offset: 100, size: 4, alloc size: 4"));
status = builder.RegisterUnsafeSlot(uninitialized_slot);
ASSERT_FALSE(status.ok());
ASSERT_EQ(status.code(), absl::StatusCode::kFailedPrecondition);
EXPECT_THAT(status.message(),
HasSubstr("unable to register uninitialized slot"));
}
struct SelfReference {
const SelfReference* self;
SelfReference() : self(this) {}
SelfReference(const SelfReference&) = delete;
SelfReference& operator=(const SelfReference&) = delete;
~SelfReference() { self = nullptr; }
};
TEST(FrameLayoutTest, AddSubFrame) {
FrameLayout subframe_layout;
std::vector<FrameLayout::Slot<SelfReference>> field_slots;
{
FrameLayout::Builder builder;
for (int i = 0; i < 2; ++i) {
field_slots.push_back(builder.AddSlot<SelfReference>());
}
subframe_layout = std::move(builder).Build();
}
FrameLayout frame_layout;
std::vector<FrameLayout::Slot<void>> subframe_slots;
{
FrameLayout::Builder builder;
builder.AddSlot<float>();
for (int j = 0; j < 3; ++j) {
subframe_slots.push_back(builder.AddSubFrame(subframe_layout));
builder.AddSlot<double>();
}
frame_layout = std::move(builder).Build();
}
for (const auto& subframe_slot : subframe_slots) {
for (const auto& field_slot : field_slots) {
EXPECT_TRUE(frame_layout.HasField(
subframe_slot.byte_offset() + field_slot.byte_offset(),
typeid(SelfReference)));
}
}
const auto alloc =
AlignedAlloc(frame_layout.AllocAlignment(), frame_layout.AllocSize());
frame_layout.InitializeAlignedAlloc(alloc.get());
FramePtr frame(alloc.get(), &frame_layout);
for (const auto& subframe_slot : subframe_slots) {
for (const auto& field_slot : field_slots) {
const void* subframe_ptr =
frame.GetRawPointer(subframe_slot.byte_offset());
ConstFramePtr subframe(subframe_ptr, &subframe_layout);
const SelfReference& field = subframe.Get(field_slot);
EXPECT_TRUE(field.self == &field);
}
}
frame_layout.DestroyAlloc(alloc.get());
ABSL_ANNOTATE_MEMORY_IS_INITIALIZED(alloc.get(), frame_layout.AllocSize());
for (const auto& subframe_slot : subframe_slots) {
for (const auto& field_slot : field_slots) {
const void* subframe_ptr =
frame.GetRawPointer(subframe_slot.byte_offset());
ConstFramePtr subframe(subframe_ptr, &subframe_layout);
const SelfReference& field = subframe.Get(field_slot);
EXPECT_TRUE(field.self == nullptr);
}
}
}
TEST(FrameLayoutTest, AddSubFrameAllocAlignment) {
FrameLayout::Builder builder;
builder.AddSubFrame(MakeTypeLayout<std::aligned_storage_t<16, 16>>());
builder.AddSubFrame(MakeTypeLayout<std::aligned_storage_t<16, 16>>());
auto frame_layout = std::move(builder).Build();
EXPECT_EQ(frame_layout.AllocSize(), 32);
EXPECT_EQ(frame_layout.AllocAlignment().value, 16);
}
TEST(FrameLayoutTest, ArrayCompatibility) {
FrameLayout::Builder builder;
builder.AddSlot<std::aligned_storage_t<16, 16>>();
builder.AddSlot<std::aligned_storage_t<1, 1>>();
auto frame_layout = std::move(builder).Build();
EXPECT_EQ(frame_layout.AllocSize(), 32);
EXPECT_EQ(frame_layout.AllocAlignment().value, 16);
}
TEST(FrameLayoutTest, InitDestroyAllocN) {
static int instance_counter = 0;
struct InstanceCounted {
InstanceCounted() { ++instance_counter; }
~InstanceCounted() { --instance_counter; }
};
struct SelfReferenced {
SelfReferenced() : self(this) {}
SelfReferenced* self;
};
FrameLayout::Builder builder;
auto int_slot = builder.AddSlot<int>();
auto self_ref_slot = builder.AddSlot<SelfReferenced>();
builder.AddSlot<InstanceCounted>();
auto layout = std::move(builder).Build();
const int n = 10;
const auto alloc =
AlignedAlloc(layout.AllocAlignment(), layout.AllocSize() * n);
layout.InitializeAlignedAllocN(alloc.get(), n);
EXPECT_EQ(instance_counter, n);
for (int i = 0; i < n; ++i) {
ConstFramePtr ith_frame(
static_cast<const std::byte*>(alloc.get()) + i * layout.AllocSize(),
&layout);
EXPECT_EQ(ith_frame.Get(int_slot), 0);
EXPECT_EQ(ith_frame.Get(self_ref_slot).self, &ith_frame.Get(self_ref_slot));
}
layout.DestroyAllocN(alloc.get(), n);
EXPECT_EQ(instance_counter, 0);
}
struct IsBZeroConstructible {
static bool ctor_called;
static bool dtor_called;
IsBZeroConstructible() { ctor_called = true; }
~IsBZeroConstructible() { dtor_called = true; }
};
bool IsBZeroConstructible::ctor_called;
bool IsBZeroConstructible::dtor_called;
}
}
namespace arolla {
template <>
struct is_bzero_constructible<::arolla::testing::IsBZeroConstructible>
: std::true_type {};
}
namespace arolla::testing {
namespace {
TEST(FrameLayoutTest, IsBZeroConstructibleHandling) {
ASSERT_FALSE(IsBZeroConstructible::ctor_called);
ASSERT_FALSE(IsBZeroConstructible::dtor_called);
{
auto layout = MakeTypeLayout<IsBZeroConstructible>();
MemoryAllocation alloc(&layout);
}
EXPECT_FALSE(IsBZeroConstructible::ctor_called);
EXPECT_TRUE(IsBZeroConstructible::dtor_called);
}
}
}
|
arolla
|
#ifndef AROLLA_MEMORY_RAW_BUFFER_FACTORY_H_
#define AROLLA_MEMORY_RAW_BUFFER_FACTORY_H_
#include <cstddef>
#include <cstdint>
#include <memory>
#include <tuple>
#include "absl/container/inlined_vector.h"
#include "google/protobuf/arena.h"
#include "arolla/util/indestructible.h"
namespace arolla {
using RawBufferPtr = std::shared_ptr<const void>;
class RawBufferFactory {
public:
virtual ~RawBufferFactory() = default;
virtual std::tuple<RawBufferPtr, void*> CreateRawBuffer(size_t nbytes) = 0;
virtual std::tuple<RawBufferPtr, void*> ReallocRawBuffer(
RawBufferPtr&& old_buffer, void* data, size_t old_size,
size_t new_size) = 0;
};
class HeapBufferFactory : public RawBufferFactory {
public:
std::tuple<RawBufferPtr, void*> CreateRawBuffer(size_t nbytes) final;
std::tuple<RawBufferPtr, void*> ReallocRawBuffer(RawBufferPtr&& old_buffer,
void* old_data,
size_t old_size,
size_t new_size) final;
};
inline RawBufferFactory* GetHeapBufferFactory() {
static Indestructible<HeapBufferFactory> factory;
return factory.get();
}
class ProtobufArenaBufferFactory final : public RawBufferFactory {
public:
explicit ProtobufArenaBufferFactory(google::protobuf::Arena& arena) : arena_(arena) {}
std::tuple<RawBufferPtr, void*> CreateRawBuffer(size_t nbytes) override;
std::tuple<RawBufferPtr, void*> ReallocRawBuffer(RawBufferPtr&& old_buffer,
void* data, size_t old_size,
size_t new_size) override;
private:
google::protobuf::Arena& arena_;
};
class UnsafeArenaBufferFactory : public RawBufferFactory {
public:
UnsafeArenaBufferFactory(const UnsafeArenaBufferFactory&) = delete;
UnsafeArenaBufferFactory& operator=(const UnsafeArenaBufferFactory&) = delete;
UnsafeArenaBufferFactory(UnsafeArenaBufferFactory&&) = delete;
UnsafeArenaBufferFactory& operator=(UnsafeArenaBufferFactory&&) = delete;
explicit UnsafeArenaBufferFactory(
int64_t page_size,
RawBufferFactory& base_factory = *GetHeapBufferFactory())
: page_size_(page_size), base_factory_(base_factory) {}
std::tuple<RawBufferPtr, void*> CreateRawBuffer(size_t nbytes) override;
std::tuple<RawBufferPtr, void*> ReallocRawBuffer(RawBufferPtr&& old_buffer,
void* data, size_t old_size,
size_t new_size) override;
void Reset();
private:
using Alloc = std::tuple<RawBufferPtr, void*>;
void NextPage();
void* SlowAlloc(size_t nbytes);
int64_t page_id_ = -1;
char* current_ = reinterpret_cast<char*>(0x8);
char* end_ = reinterpret_cast<char*>(0x8);
int64_t page_size_;
RawBufferFactory& base_factory_;
absl::InlinedVector<Alloc, 16> pages_;
absl::InlinedVector<Alloc, 16> big_allocs_;
};
template <typename T>
struct ArenaTraits {
static T MakeOwned(T&& v, RawBufferFactory*) { return std::move(v); }
};
}
#endif
#include "arolla/memory/raw_buffer_factory.h"
#include <algorithm>
#include <cstddef>
#include <cstdlib>
#include <cstring>
#include <memory>
#include <tuple>
#include <utility>
#include "absl/base/attributes.h"
#include "absl/base/dynamic_annotations.h"
#include "absl/base/optimization.h"
#include "absl/log/check.h"
namespace arolla {
namespace {
void noop_free(void*) noexcept {}
void AnnotateMemoryIsInitialized(void* data, size_t size) {
ABSL_ANNOTATE_MEMORY_IS_INITIALIZED(data, size);
}
}
std::tuple<RawBufferPtr, void*> HeapBufferFactory::CreateRawBuffer(
size_t nbytes) {
if (ABSL_PREDICT_FALSE(nbytes == 0)) return {nullptr, nullptr};
void* data = malloc(nbytes);
AnnotateMemoryIsInitialized(data, nbytes);
return {std::shared_ptr<void>(data, free), data};
}
std::tuple<RawBufferPtr, void*> HeapBufferFactory::ReallocRawBuffer(
RawBufferPtr&& old_buffer, void* old_data, size_t old_size,
size_t new_size) {
if (new_size == 0) return {nullptr, nullptr};
if (old_size == 0) return CreateRawBuffer(new_size);
DCHECK_EQ(old_buffer.use_count(), 1);
void* new_data = realloc(old_data, new_size);
if (new_size > old_size) {
AnnotateMemoryIsInitialized(static_cast<char*>(new_data) + old_size,
new_size - old_size);
}
*std::get_deleter<decltype(&free)>(old_buffer) = &noop_free;
old_buffer.reset(new_data, free);
return {std::move(old_buffer), new_data};
}
std::tuple<RawBufferPtr, void*> ProtobufArenaBufferFactory::CreateRawBuffer(
size_t nbytes) {
char* data = arena_.CreateArray<char>(&arena_, nbytes);
AnnotateMemoryIsInitialized(data, nbytes);
return {nullptr, data};
}
std::tuple<RawBufferPtr, void*> ProtobufArenaBufferFactory::ReallocRawBuffer(
RawBufferPtr&& old_buffer, void* data, size_t old_size, size_t new_size) {
if (old_size >= new_size) return {nullptr, data};
char* new_data = arena_.CreateArray<char>(&arena_, new_size);
memcpy(new_data, data, std::min(old_size, new_size));
AnnotateMemoryIsInitialized(new_data + old_size, new_size - old_size);
return {nullptr, new_data};
}
std::tuple<RawBufferPtr, void*> UnsafeArenaBufferFactory::CreateRawBuffer(
size_t nbytes) {
auto last_alloc =
reinterpret_cast<char*>(reinterpret_cast<size_t>(current_ + 7) & ~7ull);
if (ABSL_PREDICT_FALSE(last_alloc + nbytes > end_)) {
return {nullptr, SlowAlloc(nbytes)};
}
current_ = last_alloc + nbytes;
return {nullptr, last_alloc};
}
std::tuple<RawBufferPtr, void*> UnsafeArenaBufferFactory::ReallocRawBuffer(
RawBufferPtr&& old_buffer, void* data, size_t old_size, size_t new_size) {
char* last_alloc = current_ - old_size;
if ((data != last_alloc) || last_alloc + new_size > end_) {
if (old_size >= new_size) return {nullptr, data};
if (data == last_alloc) current_ = last_alloc;
void* new_data = SlowAlloc(new_size);
memcpy(new_data, data, std::min(old_size, new_size));
AnnotateMemoryIsInitialized(data, old_size);
return {nullptr, new_data};
}
current_ = last_alloc + new_size;
if (new_size < old_size) {
AnnotateMemoryIsInitialized(current_, old_size - new_size);
}
return {nullptr, last_alloc};
}
void UnsafeArenaBufferFactory::Reset() {
if (page_id_ >= 0) {
page_id_ = 0;
current_ = reinterpret_cast<char*>(std::get<1>(pages_[0]));
AnnotateMemoryIsInitialized(current_, page_size_);
end_ = current_ + page_size_;
}
big_allocs_.clear();
}
ABSL_ATTRIBUTE_NOINLINE void* UnsafeArenaBufferFactory::SlowAlloc(
size_t nbytes) {
if (ABSL_PREDICT_FALSE(nbytes > page_size_ ||
end_ - current_ >= page_size_ / 2)) {
auto [holder, memory] = base_factory_.CreateRawBuffer(nbytes);
AnnotateMemoryIsInitialized(memory, nbytes);
big_allocs_.emplace_back(std::move(holder), memory);
return memory;
}
NextPage();
auto last_alloc = current_;
current_ += nbytes;
return last_alloc;
}
void UnsafeArenaBufferFactory::NextPage() {
++page_id_;
if (ABSL_PREDICT_FALSE(page_id_ == pages_.size())) {
auto [holder, page] = base_factory_.CreateRawBuffer(page_size_);
current_ = reinterpret_cast<char*>(page);
pages_.emplace_back(std::move(holder), page);
} else {
current_ = reinterpret_cast<char*>(std::get<1>(pages_[page_id_]));
}
AnnotateMemoryIsInitialized(current_, page_size_);
end_ = current_ + page_size_;
}
}
|
#include "arolla/memory/raw_buffer_factory.h"
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <utility>
#include <vector>
#include "benchmark/benchmark.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "google/protobuf/arena.h"
namespace arolla {
namespace {
using ::testing::AnyOf;
using ::testing::Eq;
using ::testing::Ge;
using ::testing::Le;
void VerifyCanReadUninitialized(const void* ptr, size_t size) {
const char* char_ptr = static_cast<const char*>(ptr);
for (size_t i = 0; i != size; ++i) {
char c = *(char_ptr + i);
benchmark::DoNotOptimize(c);
}
}
TEST(HeapBufferFactory, CreateEmptyBuffer) {
auto [buf, data] = GetHeapBufferFactory()->CreateRawBuffer(0);
EXPECT_EQ(buf, nullptr);
EXPECT_EQ(data, nullptr);
}
TEST(HeapBufferFactory, CreateRawBuffer) {
const size_t size = 13;
auto [buf, data] = GetHeapBufferFactory()->CreateRawBuffer(size);
EXPECT_NE(buf, nullptr);
VerifyCanReadUninitialized(data, size);
EXPECT_EQ(reinterpret_cast<size_t>(data) & 7, 0);
memset(data, 0, size);
}
TEST(HeapBufferFactory, ReallocRawBuffer) {
size_t size = 13;
RawBufferPtr buf;
char* data;
{
auto res = GetHeapBufferFactory()->CreateRawBuffer(size);
buf = std::get<0>(res);
data = reinterpret_cast<char*>(std::get<1>(res));
VerifyCanReadUninitialized(data, size);
}
auto resize_fn = [&](size_t new_size) {
auto res = GetHeapBufferFactory()->ReallocRawBuffer(std::move(buf), data,
size, new_size);
buf = std::get<0>(res);
data = reinterpret_cast<char*>(std::get<1>(res));
size = new_size;
};
data[0] = 5;
resize_fn(4);
EXPECT_EQ(data[0], 5);
VerifyCanReadUninitialized(data + 1, size - 1);
resize_fn(145);
EXPECT_EQ(data[0], 5);
VerifyCanReadUninitialized(data + 1, 144);
}
TEST(ProtobufArenaBufferFactory, CreateAndResize) {
google::protobuf::Arena arena;
ProtobufArenaBufferFactory buf_factory(arena);
auto [buf1, data1] = buf_factory.CreateRawBuffer(2);
VerifyCanReadUninitialized(data1, 2);
char* d = reinterpret_cast<char*>(data1);
d[0] = 'A';
d[1] = 'B';
auto [buf2, data2] =
buf_factory.ReallocRawBuffer(std::move(buf1), data1, 2, 1);
EXPECT_EQ(data1, data2);
auto [buf3, data3] =
buf_factory.ReallocRawBuffer(std::move(buf2), data2, 1, 3);
EXPECT_NE(data2, data3);
d = reinterpret_cast<char*>(data3);
EXPECT_EQ(d[0], 'A');
VerifyCanReadUninitialized(d + 1, 2);
}
TEST(UnsafeArenaBufferFactory, CreateEmptyBuffer) {
UnsafeArenaBufferFactory arena(25);
auto [buf1, data1] = arena.CreateRawBuffer(0);
auto [buf2, data2] = arena.CreateRawBuffer(0);
auto [buf3, data3] = arena.CreateRawBuffer(1);
VerifyCanReadUninitialized(data3, 1);
auto [buf4, data4] = arena.CreateRawBuffer(0);
auto [buf5, data5] = arena.CreateRawBuffer(0);
EXPECT_EQ(data1, data2);
EXPECT_NE(data3, nullptr);
EXPECT_NE(data2, data4);
EXPECT_NE(data3, data4);
EXPECT_EQ(data4, data5);
}
TEST(UnsafeArenaBufferFactory, CreateRawBuffer) {
std::vector<int64_t> sizes = {17, 1, 15, 1, 10};
std::vector<RawBufferPtr> bufs;
std::vector<char*> ptrs;
bufs.reserve(sizes.size());
ptrs.reserve(sizes.size());
UnsafeArenaBufferFactory arena1(25);
google::protobuf::Arena proto_arena;
ProtobufArenaBufferFactory proto_buf_factory(proto_arena);
UnsafeArenaBufferFactory arena2(25, proto_buf_factory);
for (UnsafeArenaBufferFactory* arena_ptr : {&arena1, &arena2}) {
UnsafeArenaBufferFactory& arena = *arena_ptr;
for (size_t i = 0; i < sizes.size(); ++i) {
auto [buf, data] = arena.CreateRawBuffer(sizes[i]);
VerifyCanReadUninitialized(data, sizes[i]);
EXPECT_EQ(reinterpret_cast<size_t>(data) & 7, 0);
memset(data, i, sizes[i]);
bufs.push_back(buf);
ptrs.push_back(reinterpret_cast<char*>(data));
}
EXPECT_EQ(ptrs[0] + 24, ptrs[1]);
EXPECT_EQ(ptrs[2] + 16, ptrs[3]);
for (size_t i = 0; i < sizes.size(); ++i) {
for (int64_t j = 0; j < sizes[i]; ++j) {
EXPECT_EQ(ptrs[i][j], i);
}
}
}
}
TEST(UnsafeArenaBufferFactory, ReallocRawBuffer) {
UnsafeArenaBufferFactory arena1(25);
google::protobuf::Arena proto_arena;
ProtobufArenaBufferFactory proto_buf_factory(proto_arena);
UnsafeArenaBufferFactory arena2(25, proto_buf_factory);
for (UnsafeArenaBufferFactory* arena_ptr : {&arena1, &arena2}) {
UnsafeArenaBufferFactory& arena = *arena_ptr;
auto [buf1, data1] = arena.CreateRawBuffer(10);
VerifyCanReadUninitialized(data1, 10);
EXPECT_EQ(buf1, nullptr);
reinterpret_cast<char*>(data1)[0] = 7;
auto [buf2, data2] = arena.ReallocRawBuffer(std::move(buf1), data1, 10, 25);
reinterpret_cast<char*>(data1)[24] = -1;
EXPECT_EQ(reinterpret_cast<char*>(data2)[0], 7);
EXPECT_EQ(data1, data2);
auto [buf3, data3] = arena.ReallocRawBuffer(std::move(buf2), data2, 25, 26);
VerifyCanReadUninitialized(data2, 25);
EXPECT_NE(data1, data3);
EXPECT_EQ(reinterpret_cast<char*>(data3)[0], 7);
auto [buf4, data4] = arena.ReallocRawBuffer(std::move(buf3), data3, 26, 10);
EXPECT_NE(data1, data4);
EXPECT_EQ(reinterpret_cast<char*>(data4)[0], 7);
auto [buf5, data5] = arena.CreateRawBuffer(20);
VerifyCanReadUninitialized(data5, 20);
auto [buf6, data6] = arena.ReallocRawBuffer(std::move(buf5), data5, 20, 15);
VerifyCanReadUninitialized(static_cast<const char*>(data6) + 15, 5);
EXPECT_EQ(data1, data5);
EXPECT_EQ(data1, data6);
auto [buf7, data7] = arena.CreateRawBuffer(8);
VerifyCanReadUninitialized(data7, 8);
EXPECT_EQ(reinterpret_cast<char*>(data1) + 16,
reinterpret_cast<char*>(data7));
reinterpret_cast<char*>(data7)[0] = 3;
auto [buf8, data8] = arena.ReallocRawBuffer(std::move(buf7), data7, 8, 20);
EXPECT_EQ(reinterpret_cast<char*>(data8)[0], 3);
auto [buf9, data9] = arena.CreateRawBuffer(1);
VerifyCanReadUninitialized(data9, 1);
EXPECT_EQ(reinterpret_cast<char*>(data8) + 24,
reinterpret_cast<char*>(data9));
}
}
TEST(UnsafeArenaBufferFactory, BigAlloc) {
UnsafeArenaBufferFactory arena1(32);
google::protobuf::Arena proto_arena;
ProtobufArenaBufferFactory proto_buf_factory(proto_arena);
UnsafeArenaBufferFactory arena2(32, proto_buf_factory);
for (UnsafeArenaBufferFactory* arena_ptr : {&arena1, &arena2}) {
UnsafeArenaBufferFactory& arena = *arena_ptr;
auto [buf1, data1] = arena.CreateRawBuffer(16);
VerifyCanReadUninitialized(data1, 16);
auto [buf2, data2] = arena.CreateRawBuffer(64);
VerifyCanReadUninitialized(data2, 64);
auto [buf3, data3] = arena.CreateRawBuffer(16);
VerifyCanReadUninitialized(data3, 16);
EXPECT_THAT(reinterpret_cast<char*>(data3),
Eq(reinterpret_cast<char*>(data1) + 16));
EXPECT_THAT(reinterpret_cast<char*>(data2) - reinterpret_cast<char*>(data1),
AnyOf(Le(-64), Ge(32)));
memset(data2, 0, 64);
EXPECT_THAT(reinterpret_cast<int64_t*>(data2)[0], Eq(0));
}
}
TEST(UnsafeArenaBufferFactory, Reset) {
UnsafeArenaBufferFactory arena1(32);
google::protobuf::Arena proto_arena;
ProtobufArenaBufferFactory proto_buf_factory(proto_arena);
UnsafeArenaBufferFactory arena2(32, proto_buf_factory);
for (UnsafeArenaBufferFactory* arena_ptr : {&arena1, &arena2}) {
UnsafeArenaBufferFactory& arena = *arena_ptr;
arena.Reset();
auto [buf1, data1] = arena.CreateRawBuffer(16);
VerifyCanReadUninitialized(data1, 16);
auto [buf2, data2] = arena.CreateRawBuffer(16);
VerifyCanReadUninitialized(data2, 16);
auto [buf3, data3] = arena.CreateRawBuffer(16);
VerifyCanReadUninitialized(data3, 16);
std::memset(data1, 255, 16);
std::memset(data2, 255, 16);
std::memset(data3, 255, 16);
arena.Reset();
auto [buf4, data4] = arena.CreateRawBuffer(8);
VerifyCanReadUninitialized(data4, 16);
auto [buf5, data5] = arena.CreateRawBuffer(16);
VerifyCanReadUninitialized(data5, 16);
auto [buf6, data6] = arena.CreateRawBuffer(24);
VerifyCanReadUninitialized(data6, 16);
EXPECT_EQ(data1, data4);
EXPECT_EQ(reinterpret_cast<char*>(data2),
reinterpret_cast<char*>(data5) + 8);
EXPECT_EQ(data3, data6);
}
}
TEST(UnsafeArenaBufferFactory, BaseFactory) {
UnsafeArenaBufferFactory arena1(1024);
auto [buf_before, ptr_before] = arena1.CreateRawBuffer(1);
UnsafeArenaBufferFactory arena2(32, arena1);
auto [buf_small, ptr_small] = arena2.CreateRawBuffer(8);
auto [buf_big, ptr_big] = arena2.CreateRawBuffer(128);
auto [buf_after, ptr_after] = arena1.CreateRawBuffer(1);
EXPECT_LT(ptr_before, ptr_small);
EXPECT_LT(ptr_before, ptr_big);
EXPECT_GT(ptr_after, ptr_small);
EXPECT_GT(ptr_after, ptr_big);
}
}
}
|
arolla
|
#ifndef AROLLA_MEMORY_OPTIONAL_VALUE_H_
#define AROLLA_MEMORY_OPTIONAL_VALUE_H_
#include <cstdint>
#include <optional>
#include <ostream>
#include <tuple>
#include <type_traits>
#include "absl/base/attributes.h"
#include "absl/status/statusor.h"
#include "absl/strings/string_view.h"
#include "arolla/util/bytes.h"
#include "arolla/util/fingerprint.h"
#include "arolla/util/is_bzero_constructible.h"
#include "arolla/util/meta.h"
#include "arolla/util/repr.h"
#include "arolla/util/status.h"
#include "arolla/util/struct_field.h"
#include "arolla/util/text.h"
#include "arolla/util/unit.h"
#include "arolla/util/view_types.h"
#include "arolla/util/status_macros_backport.h"
namespace arolla {
template <typename T>
struct OptionalValue {
static_assert(std::is_default_constructible<T>(),
"OptionalValue<T> T must be default constructible.");
static_assert(std::is_standard_layout<T>(),
"OptionalValue<T> T must have standard layout.");
using value_type = T;
constexpr OptionalValue() : present(false), value() {}
constexpr OptionalValue(T v) : present(true), value(std::move(v)) {}
constexpr OptionalValue(std::nullopt_t) : present(false), value() {}
constexpr OptionalValue(bool present, T value)
: present(present), value(std::move(value)) {}
template <typename X = T,
typename = std::enable_if_t<
std::is_same_v<X, T> && !std::is_same_v<X, view_type_t<X>>, X>>
explicit OptionalValue(view_type_t<X> value) : present(true), value(value) {}
template <typename X = T,
typename = std::enable_if_t<
std::is_same_v<X, T> && !std::is_same_v<X, view_type_t<X>>, X>>
explicit OptionalValue(OptionalValue<view_type_t<X>> v) : present(v.present) {
if (v.present) value = T(v.value);
}
template <typename X = T,
typename = std::enable_if_t<std::is_same_v<X, T>>>
constexpr OptionalValue(std::optional<X> opt)
: present(opt.has_value()), value(std::move(opt).value_or(T{})) {}
operator OptionalValue<view_type_t<T>>() const {
return {present, value};
}
OptionalValue<T>& operator=(const OptionalValue<T>&) & = default;
OptionalValue<T>& operator=(const OptionalValue<T>&) && = delete;
OptionalValue<T>& operator=(T value) & {
this->present = true;
this->value = std::move(value);
return *this;
}
OptionalValue<T>& operator=(T) && = delete;
explicit operator bool() const { return present; }
constexpr std::optional<T> AsOptional() const& {
if (present) {
return value;
}
return {};
}
constexpr std::optional<T> AsOptional() && {
if (present) {
return std::move(value);
}
return {};
}
bool present;
value_type value = {};
void ArollaFingerprint(FingerprintHasher* hasher) const {
if (present) {
hasher->Combine(true, value);
} else {
hasher->Combine(false);
}
}
constexpr static auto ArollaStructFields() {
using CppType = OptionalValue;
return std::tuple{
AROLLA_DECLARE_STRUCT_FIELD(present),
AROLLA_DECLARE_STRUCT_FIELD(value),
};
}
};
template <typename T>
using strip_optional_t = meta::strip_template_t<OptionalValue, T>;
template <typename T>
using wrap_with_optional_t = OptionalValue<strip_optional_t<T>>;
template <typename T>
constexpr bool is_optional_v = meta::is_wrapped_with_v<OptionalValue, T>;
template <typename T>
struct view_type<OptionalValue<T>> {
using type = OptionalValue<view_type_t<T>>;
};
template <>
struct OptionalValue<Unit> {
using value_type = Unit;
constexpr OptionalValue() : present(false) {}
constexpr OptionalValue(Unit v)
: present(true) {}
constexpr OptionalValue(
std::nullopt_t)
: present(false) {}
constexpr OptionalValue(bool present, Unit value) : present(present) {}
constexpr explicit OptionalValue(bool present) : present(present) {}
constexpr OptionalValue(
std::optional<Unit> opt)
: present(opt.has_value()) {}
OptionalValue<Unit>& operator=(const OptionalValue<Unit>&) & = default;
OptionalValue<Unit>& operator=(const OptionalValue<Unit>&) && = delete;
explicit operator bool() const { return present; }
constexpr std::optional<Unit> AsOptional() const {
if (present) {
return Unit{};
}
return {};
}
template <typename H>
friend H AbslHashValue(H h, const OptionalValue& v) {
return H::combine(std::move(h), v.present);
}
bool present;
static constexpr Unit value = {};
constexpr static auto ArollaStructFields() {
using CppType = OptionalValue;
return std::tuple{
AROLLA_DECLARE_STRUCT_FIELD(present),
};
}
void ArollaFingerprint(FingerprintHasher* hasher) const {
CombineStructFields(hasher, *this);
}
};
using OptionalUnit = OptionalValue<Unit>;
constexpr OptionalUnit kPresent{Unit{}};
constexpr OptionalUnit kMissing{};
template <class T>
constexpr OptionalValue<T> MakeOptionalValue(T v) {
return {std::move(v)};
}
template <class T>
absl::StatusOr<OptionalValue<T>> MakeStatusOrOptionalValue(
absl::StatusOr<T> v) {
using ResultT = absl::StatusOr<OptionalValue<T>>;
return v.ok() ? ResultT{OptionalValue<T>{*std::move(v)}}
: ResultT{v.status()};
}
AROLLA_DECLARE_REPR(OptionalValue<bool>);
AROLLA_DECLARE_REPR(OptionalValue<int32_t>);
AROLLA_DECLARE_REPR(OptionalValue<int64_t>);
AROLLA_DECLARE_REPR(OptionalValue<uint64_t>);
AROLLA_DECLARE_REPR(OptionalValue<float>);
AROLLA_DECLARE_REPR(OptionalValue<double>);
AROLLA_DECLARE_REPR(OptionalValue<Bytes>);
AROLLA_DECLARE_REPR(OptionalValue<Text>);
AROLLA_DECLARE_REPR(OptionalUnit);
template <class T, typename = std::enable_if_t<
std::is_invocable_v<ReprTraits<OptionalValue<T>>, T>>>
std::ostream& operator<<(std::ostream& stream, const OptionalValue<T>& value) {
return stream << Repr(value);
}
template <typename T>
struct is_bzero_constructible<OptionalValue<T>> : is_bzero_constructible<T> {};
template <typename T>
constexpr bool operator==(const OptionalValue<T>& a,
const OptionalValue<T>& b) {
if (a.present && b.present) {
return a.value == b.value;
}
return (a.present == b.present);
}
template <typename T>
constexpr bool operator==(const OptionalValue<T>& a, const T& b) {
return a.present && a.value == b;
}
template <typename T>
constexpr bool operator==(const T& a, const OptionalValue<T>& b) {
return b.present && a == b.value;
}
template <typename T>
constexpr bool operator==(const OptionalValue<T>& a, std::nullopt_t) {
return !a.present;
}
template <typename T>
constexpr bool operator==(std::nullopt_t, const OptionalValue<T>& a) {
return !a.present;
}
template <typename T>
constexpr bool operator!=(const OptionalValue<T>& a,
const OptionalValue<T>& b) {
return !(a == b);
}
template <typename T>
constexpr bool operator!=(const OptionalValue<T>& a, const T& b) {
return !(a == b);
}
template <typename T>
constexpr bool operator!=(const T& a, const OptionalValue<T>& b) {
return !(a == b);
}
template <typename T>
constexpr bool operator!=(const OptionalValue<T>& a, std::nullopt_t) {
return a.present;
}
template <typename T>
constexpr bool operator!=(std::nullopt_t, const OptionalValue<T>& a) {
return a.present;
}
constexpr bool operator==(const OptionalUnit& a, const OptionalUnit& b) {
return a.present == b.present;
}
constexpr bool operator==(const OptionalUnit& a, const Unit& b) {
return a.present;
}
constexpr bool operator==(const Unit& a, const OptionalUnit& b) {
return b.present;
}
constexpr bool operator==(const OptionalValue<absl::string_view>& a,
absl::string_view b) {
return a.present && a.value == b;
}
template <typename T>
OptionalValue(T value) -> OptionalValue<T>;
namespace optional_value_impl {
template <class Fn, class ArgList>
class OptionalFn;
template <class To, class From>
ABSL_ATTRIBUTE_ALWAYS_INLINE inline bool is_available(const From& v) {
if constexpr (!is_optional_v<To>) {
return v.present;
} else {
return true;
}
}
template <class To, class From>
ABSL_ATTRIBUTE_ALWAYS_INLINE inline const To& value(const From& v) {
if constexpr (!is_optional_v<To>) {
return v.value;
} else {
return v;
}
}
template <class Fn, class... Args>
class OptionalFn<Fn, meta::type_list<Args...>> {
private:
using FnResT = std::decay_t<typename meta::function_traits<Fn>::return_type>;
static constexpr bool kHasStatus = IsStatusOrT<FnResT>::value;
using OptResT = wrap_with_optional_t<strip_statusor_t<FnResT>>;
using ResT = std::conditional_t<kHasStatus, absl::StatusOr<OptResT>, OptResT>;
public:
explicit constexpr OptionalFn(Fn fn) : fn_(std::move(fn)) {}
ResT operator()(
const wrap_with_optional_t<std::decay_t<Args>>&... args) const {
if ((is_available<std::decay_t<Args>>(args) && ...)) {
if constexpr (kHasStatus && !std::is_same_v<FnResT, ResT>) {
ASSIGN_OR_RETURN(auto res, fn_(value<std::decay_t<Args>>(args)...));
return OptResT(res);
} else {
return fn_(value<std::decay_t<Args>>(args)...);
}
} else {
return OptResT(std::nullopt);
}
}
private:
Fn fn_;
};
}
template <class Fn>
constexpr auto WrapFnToAcceptOptionalArgs(Fn fn) {
return optional_value_impl::OptionalFn<
Fn, typename meta::function_traits<Fn>::arg_types>(fn);
}
}
#endif
#include "arolla/memory/optional_value.h"
#include <cstdint>
#include "absl/strings/str_cat.h"
#include "arolla/util/bytes.h"
#include "arolla/util/repr.h"
#include "arolla/util/text.h"
namespace arolla {
ReprToken ReprTraits<OptionalValue<bool>>::operator()(
const OptionalValue<bool>& value) const {
return ReprToken{
value.present ? absl::StrCat("optional_boolean{", Repr(value.value), "}")
: "optional_boolean{NA}"};
}
ReprToken ReprTraits<OptionalValue<int32_t>>::operator()(
const OptionalValue<int32_t>& value) const {
return ReprToken{value.present
? absl::StrCat("optional_int32{", Repr(value.value), "}")
: "optional_int32{NA}"};
}
ReprToken ReprTraits<OptionalValue<int64_t>>::operator()(
const OptionalValue<int64_t>& value) const {
return ReprToken{value.present ? absl::StrCat("optional_", Repr(value.value))
: "optional_int64{NA}"};
}
ReprToken ReprTraits<OptionalValue<uint64_t>>::operator()(
const OptionalValue<uint64_t>& value) const {
return ReprToken{value.present ? absl::StrCat("optional_", Repr(value.value))
: "optional_uint64{NA}"};
}
ReprToken ReprTraits<OptionalValue<float>>::operator()(
const OptionalValue<float>& value) const {
return ReprToken{
value.present ? absl::StrCat("optional_float32{", Repr(value.value), "}")
: "optional_float32{NA}"};
}
ReprToken ReprTraits<OptionalValue<double>>::operator()(
const OptionalValue<double>& value) const {
return ReprToken{value.present ? absl::StrCat("optional_", Repr(value.value))
: "optional_float64{NA}"};
}
ReprToken ReprTraits<OptionalValue<Bytes>>::operator()(
const OptionalValue<Bytes>& value) const {
return ReprToken{value.present
? absl::StrCat("optional_bytes{", Repr(value.value), "}")
: "optional_bytes{NA}"};
}
ReprToken ReprTraits<OptionalValue<Text>>::operator()(
const OptionalValue<Text>& value) const {
return ReprToken{value.present
? absl::StrCat("optional_text{", Repr(value.value), "}")
: "optional_text{NA}"};
}
ReprToken ReprTraits<OptionalUnit>::operator()(
const OptionalUnit& value) const {
return ReprToken{value.present ? "present" : "missing"};
}
}
|
#include "arolla/memory/optional_value.h"
#include <cstdint>
#include <cstring>
#include <memory>
#include <new>
#include <optional>
#include <sstream>
#include <string>
#include <type_traits>
#include <utility>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/string_view.h"
#include "arolla/memory/frame.h"
#include "arolla/memory/memory_allocation.h"
#include "arolla/util/bytes.h"
#include "arolla/util/repr.h"
#include "arolla/util/testing/status_matchers_backport.h"
#include "arolla/util/text.h"
#include "arolla/util/view_types.h"
namespace arolla {
namespace testing {
namespace {
using ::testing::HasSubstr;
using ::testing::Test;
TEST(OptionalValueTest, TestEmptyValues) {
OptionalValue<float> v1;
EXPECT_FALSE(v1.present);
OptionalValue<float> v2(std::optional<float>{});
EXPECT_FALSE(v2.present);
OptionalValue<float> v3(std::nullopt);
EXPECT_FALSE(v3.present);
EXPECT_EQ(v1, v2);
EXPECT_EQ(v1, v3);
v1.value = 1.0f;
v2.value = 2.0f;
EXPECT_EQ(v1, v2);
auto absl_v = v2.AsOptional();
EXPECT_FALSE(absl_v.has_value());
}
TEST(OptionalValueTest, TestConstExpr) {
static_assert(!OptionalValue<int>().present);
static_assert(OptionalValue<int>(5).present);
static_assert(OptionalValue<int>(5).value == 5);
static_assert(MakeOptionalValue(5).present);
static_assert(MakeOptionalValue(5).value == 5);
}
TEST(OptionalValueTest, TestPresentValues) {
OptionalValue<float> v1(1.0f);
EXPECT_TRUE(v1.present);
EXPECT_EQ(1.0f, v1.value);
EXPECT_EQ(Repr(v1), "optional_float32{1.}");
auto v_auto = MakeOptionalValue(1.0f);
EXPECT_TRUE(v_auto.present);
EXPECT_EQ(1.0f, v_auto.value);
EXPECT_EQ(Repr(v_auto), "optional_float32{1.}");
OptionalValue<float> v2(std::optional<float>{2.0f});
EXPECT_TRUE(v2.present);
EXPECT_EQ(2.0f, v2.value);
EXPECT_EQ(Repr(v2), "optional_float32{2.}");
EXPECT_NE(v1, v2);
v1.value = 2.0f;
EXPECT_EQ(v1, v2);
}
TEST(OptionalValueTest, TestAssignment) {
OptionalValue<float> v1;
v1 = 1.0f;
EXPECT_TRUE(v1.present);
EXPECT_EQ(v1.value, 1.0f);
v1 = std::nullopt;
EXPECT_FALSE(v1.present);
}
TEST(OptionalValueTest, MakeStatusOrOptionalValue) {
absl::StatusOr<OptionalValue<float>> v =
MakeStatusOrOptionalValue(absl::StatusOr<float>(1.0f));
ASSERT_OK(v.status());
EXPECT_TRUE(v.value().present);
EXPECT_EQ(v.value().value, 1.0f);
absl::StatusOr<OptionalValue<float>> v_error = MakeStatusOrOptionalValue(
absl::StatusOr<float>(absl::InternalError("fake")));
EXPECT_THAT(v_error.status(),
StatusIs(absl::StatusCode::kInternal, HasSubstr("fake")));
}
TEST(OptionalValueTest, OptionalUnit) {
EXPECT_EQ(OptionalUnit(), kMissing);
EXPECT_EQ(OptionalUnit(false), kMissing);
EXPECT_FALSE(kMissing);
EXPECT_FALSE(kMissing.present);
EXPECT_EQ(Repr(kMissing), "missing");
EXPECT_EQ(OptionalUnit(true), kPresent);
EXPECT_TRUE(kPresent);
EXPECT_TRUE(kPresent.present);
EXPECT_EQ(Repr(kPresent), "present");
}
TEST(OptionalValueTest, Comparison) {
OptionalValue<float> v0;
v0.value = 1.0f;
OptionalValue<float> v1(1.0f);
OptionalValue<float> v2(2.0f);
{
EXPECT_TRUE(v1 == v1);
EXPECT_TRUE(v0 == v0);
EXPECT_FALSE(v1 == v2);
EXPECT_FALSE(v1 == v0);
EXPECT_FALSE(v1 != v1);
EXPECT_FALSE(v0 != v0);
EXPECT_TRUE(v1 != v2);
EXPECT_TRUE(v1 != v0);
OptionalValue<float> v0_2;
v0_2.value = 2.0f;
EXPECT_TRUE(v0 == v0_2);
EXPECT_FALSE(v0 != v0_2);
}
{
EXPECT_TRUE(v1 == 1.0f);
EXPECT_TRUE(1.0f == v1);
EXPECT_FALSE(v1 != 1.0f);
EXPECT_FALSE(1.0f != v1);
EXPECT_FALSE(v1 == 2.0f);
EXPECT_FALSE(2.0f == v1);
EXPECT_TRUE(v1 != 2.0f);
EXPECT_TRUE(2.0f != v1);
}
{
EXPECT_FALSE(v1 == std::nullopt);
EXPECT_FALSE(std::nullopt == v1);
EXPECT_TRUE(v0 == std::nullopt);
EXPECT_TRUE(std::nullopt == v0);
EXPECT_TRUE(v1 != std::nullopt);
EXPECT_TRUE(std::nullopt != v1);
EXPECT_FALSE(v0 != std::nullopt);
EXPECT_FALSE(std::nullopt != v0);
}
}
TEST(OptionalValueTest, TestImplicitConstructors) {
OptionalValue<float> v = {};
EXPECT_EQ(v, OptionalValue<float>());
v = 3.5;
EXPECT_EQ(v, OptionalValue<float>(3.5));
v = std::optional<float>(2.5);
EXPECT_EQ(v, OptionalValue<float>(2.5));
}
TEST(OptionalValueTest, TestMoves) {
auto ptr = std::make_unique<std::string>("Hello!");
OptionalValue<std::unique_ptr<std::string>> v1(std::move(ptr));
EXPECT_TRUE(v1.present);
EXPECT_EQ("Hello!", *(v1.value));
std::optional<std::unique_ptr<std::string>> v2(std::move(v1).AsOptional());
EXPECT_TRUE(v2.has_value());
EXPECT_EQ("Hello!", **v2);
}
template <typename T>
using Slot = FrameLayout::Slot<T>;
TEST(OptionalValueTest, TestFrameLayout) {
FrameLayout::Builder builder;
builder.AddSlot<double>();
builder.AddSlot<int32_t>();
auto optional_slot = builder.AddSlot<OptionalValue<float>>();
Slot<bool> presence_slot = optional_slot.GetSubslot<0>();
Slot<float> value_slot = optional_slot.GetSubslot<1>();
FrameLayout layout = std::move(builder).Build();
MemoryAllocation alloc(&layout);
FramePtr frame = alloc.frame();
frame.Set(optional_slot, OptionalValue<float>{1.0f});
EXPECT_EQ(true, frame.Get(presence_slot));
EXPECT_EQ(1.0f, frame.Get(value_slot));
frame.Set(value_slot, 2.0f);
EXPECT_EQ(2.0, frame.Get(optional_slot).value);
}
TEST(OptionalValue, IsBZeroConstructible) {
EXPECT_TRUE(is_bzero_constructible<OptionalValue<float>>());
EXPECT_TRUE(is_bzero_constructible<OptionalValue<int>>());
EXPECT_FALSE(is_bzero_constructible<OptionalValue<std::string>>());
}
TEST(OptionalValue, BZeroStateIsEmptyValue) {
using T = OptionalValue<float>;
std::aligned_storage_t<sizeof(T), alignof(T)> storage;
memset(&storage, 0, sizeof(storage));
EXPECT_FALSE(std::launder(reinterpret_cast<const T*>(&storage))->present);
}
TEST(OptionalValue, StructuredBindings) {
{
OptionalValue<float> f;
auto [present, value] = f;
EXPECT_FALSE(present);
}
{
OptionalValue<float> f = 17.0;
auto [present, value] = f;
EXPECT_TRUE(present);
EXPECT_EQ(value, 17.0);
}
}
TEST(OptionalValue, ViewType) {
static_assert(std::is_same_v<view_type_t<OptionalValue<int64_t>>,
OptionalValue<int64_t>>);
static_assert(std::is_same_v<view_type_t<OptionalValue<Bytes>>,
OptionalValue<absl::string_view>>);
auto fn = [](OptionalValue<absl::string_view> v) -> char {
return (v.present && !v.value.empty()) ? v.value[0] : 'X';
};
EXPECT_EQ(fn(OptionalValue<Text>(Text("Hello"))), 'H');
EXPECT_EQ(fn(std::nullopt), 'X');
}
TEST(OptionalValue, WrapFnToAcceptOptionalArgs) {
{
auto fn = [](int a, OptionalValue<int64_t> b, int64_t c) -> int {
return a + c + (b.present ? b.value : 10);
};
auto opt_fn = WrapFnToAcceptOptionalArgs(fn);
EXPECT_EQ(opt_fn(1, 2, 3), OptionalValue<int>(6));
EXPECT_EQ(opt_fn(std::nullopt, 2, 3), OptionalValue<int>());
EXPECT_EQ(opt_fn(1, std::nullopt, 3), OptionalValue<int>(14));
EXPECT_EQ(opt_fn(1, 2, std::nullopt), OptionalValue<int>());
}
{
auto fn = [](const Bytes& v) -> const Bytes& { return v; };
auto opt_fn = WrapFnToAcceptOptionalArgs(fn);
EXPECT_EQ(opt_fn(Bytes("123")), OptionalValue<Bytes>("123"));
}
{
auto fn = [](absl::string_view v) { return v; };
auto opt_fn = WrapFnToAcceptOptionalArgs(fn);
EXPECT_EQ(opt_fn(MakeOptionalValue(Bytes("123"))),
MakeOptionalValue(absl::string_view("123")));
}
{
auto fn = [](int a, OptionalValue<int64_t> b,
int64_t c) -> absl::StatusOr<int> {
if (c < 0) {
return absl::InvalidArgumentError("c < 0");
} else {
return a + c + (b.present ? b.value : 10);
}
};
auto opt_fn = WrapFnToAcceptOptionalArgs(fn);
EXPECT_THAT(opt_fn(1, 2, 3), IsOkAndHolds(OptionalValue<int>(6)));
EXPECT_THAT(opt_fn(1, 2, -3),
StatusIs(absl::StatusCode::kInvalidArgument, "c < 0"));
EXPECT_THAT(opt_fn(std::nullopt, 2, -3),
IsOkAndHolds(OptionalValue<int>()));
}
}
TEST(OptionalValueReprTest, bool) {
EXPECT_EQ(Repr(OptionalValue<bool>(true)), "optional_boolean{true}");
EXPECT_EQ(Repr(OptionalValue<bool>()), "optional_boolean{NA}");
}
TEST(OptionalValueReprTest, int32_t) {
EXPECT_EQ(Repr(OptionalValue<int32_t>(1)), "optional_int32{1}");
EXPECT_EQ(Repr(OptionalValue<int32_t>()), "optional_int32{NA}");
}
TEST(OptionalValueReprTest, int64_t) {
EXPECT_EQ(Repr(OptionalValue<int64_t>(1)), "optional_int64{1}");
EXPECT_EQ(Repr(OptionalValue<int64_t>()), "optional_int64{NA}");
}
TEST(OptionalValueReprTest, uint64_t) {
EXPECT_EQ(Repr(OptionalValue<uint64_t>(1)), "optional_uint64{1}");
EXPECT_EQ(Repr(OptionalValue<uint64_t>()), "optional_uint64{NA}");
}
TEST(OptionalValueReprTest, float) {
EXPECT_EQ(Repr(OptionalValue<float>(1.5)), "optional_float32{1.5}");
EXPECT_EQ(Repr(OptionalValue<float>()), "optional_float32{NA}");
}
TEST(OptionalValueReprTest, double) {
EXPECT_EQ(Repr(OptionalValue<double>(1.5)), "optional_float64{1.5}");
EXPECT_EQ(Repr(OptionalValue<double>()), "optional_float64{NA}");
}
TEST(OptionalValueReprTest, Bytes) {
EXPECT_EQ(Repr(OptionalValue<Bytes>("abc")), "optional_bytes{b'abc'}");
EXPECT_EQ(Repr(OptionalValue<Bytes>()), "optional_bytes{NA}");
}
TEST(OptionalValueReprTest, Text) {
EXPECT_EQ(Repr(OptionalValue<Text>("abc")), "optional_text{'abc'}");
EXPECT_EQ(Repr(OptionalValue<Text>()), "optional_text{NA}");
}
TEST(OptionalValueReprTest, StreamOp) {
{
std::ostringstream oss;
oss << OptionalValue<float>(1.5);
EXPECT_EQ(oss.str(), "optional_float32{1.5}");
}
{
std::ostringstream oss;
oss << OptionalValue<float>();
EXPECT_EQ(oss.str(), "optional_float32{NA}");
}
}
}
}
}
|
arolla
|
#ifndef AROLLA_OPTOOLS_OPTOOLS_H_
#define AROLLA_OPTOOLS_OPTOOLS_H_
#include <cstddef>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/string_view.h"
#include "arolla/expr/expr_operator_signature.h"
#include "arolla/qexpr/operator_factory.h"
#include "arolla/qexpr/operators.h"
#include "arolla/util/status_macros_backport.h"
namespace arolla::optools {
namespace optools_impl {
absl::Status RegisterFunctionAsOperatorImpl(
std::vector<OperatorPtr> qexpr_ops, expr::ExprOperatorSignature signature,
absl::string_view description);
template <typename Fn>
struct MakeQExprOps {
absl::StatusOr<std::vector<OperatorPtr>> operator()(absl::string_view name,
Fn fn) {
ASSIGN_OR_RETURN(OperatorPtr op, OperatorFactory()
.WithName(std::string(name))
.BuildFromFunction(std::move(fn)));
return std::vector<OperatorPtr>{op};
}
};
template <typename... FNs>
struct MakeQExprOps<std::tuple<FNs...>> {
absl::StatusOr<std::vector<OperatorPtr>> operator()(absl::string_view name,
std::tuple<FNs...> fns) {
return impl(name, std::move(fns), std::index_sequence_for<FNs...>{});
}
template <size_t... Is>
absl::StatusOr<std::vector<OperatorPtr>> impl(absl::string_view name,
std::tuple<FNs...> fns,
std::index_sequence<Is...>) {
std::vector<OperatorPtr> res;
res.reserve(sizeof...(FNs));
auto factory = OperatorFactory().WithName(std::string(name));
for (auto status_or_op :
{factory.BuildFromFunction(std::move(std::get<Is>(fns)))...}) {
RETURN_IF_ERROR(status_or_op.status());
res.push_back(*status_or_op);
}
return res;
}
};
}
template <typename Fn>
absl::Status RegisterFunctionAsOperator(
Fn&& fns, absl::string_view name,
absl::StatusOr<expr::ExprOperatorSignature> signature =
expr::ExprOperatorSignature(),
absl::string_view doc = "") {
RETURN_IF_ERROR(signature.status());
ASSIGN_OR_RETURN(std::vector<OperatorPtr> ops,
optools_impl::MakeQExprOps<Fn>()(name, fns));
return optools_impl::RegisterFunctionAsOperatorImpl(
std::move(ops), *std::move(signature), doc);
}
}
#endif
#include "arolla/optools/optools.h"
#include <cstddef>
#include <string>
#include <utility>
#include <vector>
#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/expr/basic_expr_operator.h"
#include "arolla/expr/expr_operator.h"
#include "arolla/expr/expr_operator_signature.h"
#include "arolla/expr/registered_expr_operator.h"
#include "arolla/qexpr/operators.h"
#include "arolla/qtype/qtype.h"
#include "arolla/util/fingerprint.h"
#include "arolla/util/string.h"
#include "arolla/util/status_macros_backport.h"
namespace arolla::optools::optools_impl {
namespace {
class QExprWrappingOperator final : public expr::BackendExprOperatorTag,
public expr::BasicExprOperator {
public:
QExprWrappingOperator(absl::string_view name,
std::vector<OperatorPtr> qexpr_ops,
expr::ExprOperatorSignature signature,
absl::string_view description)
: expr::BasicExprOperator(
name, signature, description,
FingerprintHasher("arolla::optools_impl::QExprWrappingOperator")
.Combine(name, signature)
.Finish()),
qexpr_ops_(std::move(qexpr_ops)) {}
absl::StatusOr<QTypePtr> GetOutputQType(
absl::Span<const QTypePtr> input_qtypes) const override {
for (const OperatorPtr& op : qexpr_ops_) {
absl::Span<const QTypePtr> required_qtypes =
op->signature()->input_types();
bool match = true;
for (size_t i = 0; i < input_qtypes.size(); ++i) {
if (input_qtypes[i] != required_qtypes[i]) {
match = false;
break;
}
}
if (match) {
return op->signature()->output_type();
}
}
std::string msg = "no such overload; available signatures: ";
bool is_first = true;
for (const auto& op : qexpr_ops_) {
absl::StrAppend(&msg, op->signature(), NonFirstComma(is_first, ", "));
}
return absl::InvalidArgumentError(msg);
}
private:
std::vector<OperatorPtr> qexpr_ops_;
};
}
absl::Status RegisterFunctionAsOperatorImpl(
std::vector<OperatorPtr> qexpr_ops, expr::ExprOperatorSignature signature,
absl::string_view description) {
RETURN_IF_ERROR(expr::ValidateSignature(signature));
if (expr::HasVariadicParameter(signature)) {
return absl::InvalidArgumentError(
"incorrect operator signature: RegisterFunctionAsOperator doesn't "
"support variadic args");
}
if (qexpr_ops.empty()) {
return absl::InvalidArgumentError(
"at least one qexpr operator is required");
}
size_t arg_count = qexpr_ops[0]->signature()->input_types().size();
absl::string_view name = qexpr_ops[0]->name();
for (const OperatorPtr& op : qexpr_ops) {
if (op->signature()->input_types().size() != arg_count) {
return absl::InvalidArgumentError(
"arg count must be the same for all overloads");
}
if (op->name() != name) {
return absl::InvalidArgumentError(
"all overloads must have the same name");
}
RETURN_IF_ERROR(
::arolla::OperatorRegistry::GetInstance()->RegisterOperator(op));
}
if (signature.parameters.empty()) {
signature = expr::ExprOperatorSignature::MakeArgsN(arg_count);
} else if (signature.parameters.size() != arg_count) {
return absl::InvalidArgumentError(
"operator signature doesn't match the function");
}
return expr::RegisterOperator<QExprWrappingOperator>(
name, name, std::move(qexpr_ops), signature, description)
.status();
}
}
|
#include "arolla/optools/optools.h"
#include <tuple>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/status/status.h"
#include "arolla/expr/expr_operator_signature.h"
#include "arolla/expr/testing/testing.h"
#include "arolla/qtype/typed_value.h"
#include "arolla/util/testing/status_matchers_backport.h"
namespace arolla::testing {
namespace {
using ::testing::HasSubstr;
int Add(int a, int b) { return a + b; }
template <typename T>
T Mul(T a, T b) {
return a * b;
}
TEST(OpTools, RegisterFunctionAsOperator) {
ASSERT_OK(optools::RegisterFunctionAsOperator(Add, "optools_test.add"));
ASSERT_OK(optools::RegisterFunctionAsOperator(
std::make_tuple(Mul<float>, Mul<int>), "optools_test.mul"));
{
ASSERT_OK_AND_ASSIGN(TypedValue res,
InvokeExprOperator("optools_test.add",
{TypedValue::FromValue<int>(3),
TypedValue::FromValue<int>(4)}));
ASSERT_OK_AND_ASSIGN(int r, res.As<int>());
EXPECT_EQ(r, 7);
}
{
ASSERT_OK_AND_ASSIGN(TypedValue res,
InvokeExprOperator("optools_test.mul",
{TypedValue::FromValue<int>(3),
TypedValue::FromValue<int>(4)}));
ASSERT_OK_AND_ASSIGN(int r, res.As<int>());
EXPECT_EQ(r, 12);
}
{
ASSERT_OK_AND_ASSIGN(TypedValue res,
InvokeExprOperator("optools_test.mul",
{TypedValue::FromValue<float>(3),
TypedValue::FromValue<float>(2)}));
ASSERT_OK_AND_ASSIGN(float r, res.As<float>());
EXPECT_FLOAT_EQ(r, 6.0);
}
EXPECT_THAT(
InvokeExprOperator("optools_test.add", {TypedValue::FromValue<float>(3),
TypedValue::FromValue<int>(4)}),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("no such overload")));
EXPECT_THAT(
InvokeExprOperator("optools_test.mul", {TypedValue::FromValue<float>(3),
TypedValue::FromValue<int>(4)}),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("no such overload")));
EXPECT_OK(optools::RegisterFunctionAsOperator(
Add, "optools_test.add_with_description",
expr::ExprOperatorSignature::Make("a, b"), "Sum A and B"));
EXPECT_THAT(optools::RegisterFunctionAsOperator(
Add, "optools_test.add_with_wrong_signature",
expr::ExprOperatorSignature::Make("a, b, c"), "Sum A and B"),
StatusIs(absl::StatusCode::kInvalidArgument,
"operator signature doesn't match the function"));
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.