ID
stringlengths
36
36
Language
stringclasses
1 value
Repository Name
stringclasses
13 values
File Name
stringlengths
2
48
File Path in Repository
stringlengths
11
111
File Path for Unit Test
stringlengths
13
116
Code
stringlengths
0
278k
Unit Test - (Ground Truth)
stringlengths
78
663k
Code Url
stringlengths
91
198
Test Code Url
stringlengths
93
203
Commit Hash
stringclasses
13 values
020f23af-2962-414a-80bf-392dce42a8cc
cpp
google/arolla
lazy_qtype
arolla/lazy/lazy_qtype.cc
arolla/lazy/lazy_qtype_test.cc
#include "arolla/lazy/lazy_qtype.h" #include <memory> #include <string> #include <utility> #include "absl/base/no_destructor.h" #include "absl/base/thread_annotations.h" #include "absl/container/flat_hash_map.h" #include "absl/log/check.h" #include "absl/status/statusor.h" #include "absl/synchronization/mutex.h" #include "arolla/lazy/lazy.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/simple_qtype.h" #include "arolla/qtype/typed_value.h" #include "arolla/util/fast_dynamic_downcast_final.h" #include "arolla/util/meta.h" namespace arolla { namespace { class LazyQType final : public SimpleQType { public: explicit LazyQType(QTypePtr value_qtype) : SimpleQType(meta::type<LazyPtr>(), "LAZY[" + std::string(value_qtype->name()) + "]", value_qtype, "::arolla::LazyQType") {} }; class LazyQTypeRegistry { public: QTypePtr GetLazyQType(QTypePtr value_qtype) { absl::WriterMutexLock l(&lock_); auto& result = registry_[value_qtype]; if (!result) { result = std::make_unique<LazyQType>(value_qtype); } return result.get(); } private: absl::Mutex lock_; absl::flat_hash_map<QTypePtr, std::unique_ptr<LazyQType>> registry_ ABSL_GUARDED_BY(lock_); }; } bool IsLazyQType(const QType* qtype) { return fast_dynamic_downcast_final<const LazyQType*>(qtype) != nullptr; } QTypePtr GetLazyQType(QTypePtr value_qtype) { static absl::NoDestructor<LazyQTypeRegistry> registry; return registry->GetLazyQType(value_qtype); } TypedValue MakeLazyQValue(LazyPtr lazy) { DCHECK_NE(lazy, nullptr); auto result = TypedValue::FromValueWithQType( std::move(lazy), GetLazyQType(lazy->value_qtype())); DCHECK_OK(result.status()); return *std::move(result); } }
#include "arolla/lazy/lazy_qtype.h" #include <cstdint> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status_matchers.h" #include "arolla/lazy/lazy.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_value.h" #include "arolla/util/testing/repr_token_eq.h" namespace arolla { namespace { using ::absl_testing::IsOkAndHolds; using ::arolla::testing::ReprTokenEq; using ::arolla::testing::TypedValueWith; TEST(LazyQTypeTest, Basics) { auto qtype = GetLazyQType<QTypePtr>(); EXPECT_EQ(qtype, GetLazyQType<QTypePtr>()); EXPECT_EQ(qtype->name(), "LAZY[QTYPE]"); EXPECT_EQ(qtype->type_info(), typeid(LazyPtr)); EXPECT_EQ(qtype->type_layout().AllocSize(), sizeof(LazyPtr)); EXPECT_EQ(qtype->type_layout().AllocAlignment().value, alignof(LazyPtr)); EXPECT_TRUE(qtype->type_fields().empty()); EXPECT_EQ(qtype->value_qtype(), GetQTypeQType()); EXPECT_EQ(qtype->qtype_specialization_key(), "::arolla::LazyQType"); } TEST(LazyQTypeTest, IsLazyQType) { EXPECT_TRUE(IsLazyQType(GetLazyQType<QTypePtr>())); EXPECT_TRUE(IsLazyQType(GetLazyQType<int32_t>())); EXPECT_TRUE(IsLazyQType(GetLazyQType<float>())); EXPECT_FALSE(IsLazyQType(GetQTypeQType())); EXPECT_FALSE(IsLazyQType(GetQType<int32_t>())); EXPECT_FALSE(IsLazyQType(GetQType<float>())); } TEST(LazyQTypeTest, MakeLazyQValue) { auto qvalue = MakeLazyQValue(MakeLazyFromQValue(TypedValue::FromValue(1))); EXPECT_THAT(qvalue.GenReprToken(), ReprTokenEq("lazy[INT32]")); ASSERT_EQ(qvalue.GetType(), GetLazyQType<int>()); EXPECT_THAT(qvalue.UnsafeAs<LazyPtr>()->Get(), IsOkAndHolds(TypedValueWith<int>(1))); EXPECT_EQ(qvalue.GetFingerprint(), MakeLazyQValue(MakeLazyFromQValue(TypedValue::FromValue(1))) .GetFingerprint()); EXPECT_NE(qvalue.GetFingerprint(), MakeLazyQValue(MakeLazyFromQValue(TypedValue::FromValue(2))) .GetFingerprint()); } } }
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/lazy/lazy_qtype.cc
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/lazy/lazy_qtype_test.cc
1ca990dbeca224035efdabffecc7f3738df6b52c
846b0ef6-bee7-4e12-ac28-585dca10c72c
cpp
google/arolla
operators
arolla/qexpr/operators.cc
arolla/qexpr/operators_test.cc
#include "arolla/qexpr/operators.h" #include <algorithm> #include <bitset> #include <cstddef> #include <memory> #include <string> #include <utility> #include <vector> #include "absl/base/no_destructor.h" #include "absl/container/flat_hash_map.h" #include "absl/log/check.h" #include "absl/log/log.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 "absl/types/span.h" #include "arolla/memory/frame.h" #include "arolla/qexpr/casting.h" #include "arolla/qexpr/eval_context.h" #include "arolla/qexpr/operator_errors.h" #include "arolla/qexpr/qexpr_operator_signature.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/typed_slot.h" #include "arolla/qtype/typed_value.h" #include "arolla/util/operator_name.h" #include "arolla/util/status_macros_backport.h" namespace arolla { namespace { class CombinedOperatorFamily final : public OperatorFamily { public: explicit CombinedOperatorFamily(std::string name) : name_(std::move(name)) {} absl::StatusOr<OperatorPtr> DoGetOperator( absl::Span<const QTypePtr> input_types, QTypePtr output_type) const final { auto it = operators_.find(input_types); if (it != operators_.end() && it->second.op->signature()->output_type() == output_type) { return it->second.op; } ASSIGN_OR_RETURN(const QExprOperatorSignature* matching_signature, FindMatchingSignature(input_types, output_type, supported_signatures_, name_)); return operators_.at(matching_signature->input_types()).op; } absl::Status Insert(OperatorPtr op, size_t overwrite_priority) { DCHECK_NE(op, nullptr); auto* signature = op->signature(); auto& record = operators_[signature->input_types()]; if (overwrite_priority >= record.overwrite_priority_mask.size()) { return absl::InvalidArgumentError( absl::StrFormat("unable to register QExpr operator %s%s:" " overwrite_priority=%d is out of range", name_, FormatTypeVector(signature->input_types()), overwrite_priority)); } if (record.overwrite_priority_mask.test(overwrite_priority)) { return absl::AlreadyExistsError( absl::StrFormat("trying to register QExpr operator %s%s twice", name_, FormatTypeVector(signature->input_types()))); } record.overwrite_priority_mask.set(overwrite_priority); if ((record.overwrite_priority_mask >> (overwrite_priority + 1)).any()) { return absl::OkStatus(); } if (record.op != nullptr) { auto it = std::find(supported_signatures_.begin(), supported_signatures_.end(), record.op->signature()); DCHECK(it != supported_signatures_.end()); *it = signature; } else { supported_signatures_.push_back(signature); } record.op = std::move(op); return absl::OkStatus(); } private: struct Record { OperatorPtr op; std::bitset<2> overwrite_priority_mask; }; std::string name_; absl::flat_hash_map<absl::Span<const QTypePtr>, Record> operators_; std::vector<const QExprOperatorSignature*> supported_signatures_; }; } absl::Status OperatorRegistry::RegisterOperatorFamily( absl::string_view name, std::unique_ptr<OperatorFamily> operation) { absl::WriterMutexLock lock(&mutex_); if (!IsOperatorName(name)) { return absl::InvalidArgumentError( absl::StrFormat("incorrect operator name \"%s\"", name)); } auto inserted = families_.emplace(name, std::move(operation)); if (!inserted.second) { return absl::Status( absl::StatusCode::kAlreadyExists, absl::StrFormat( "trying to register non-static QExpr operator family %s twice", name)); } return absl::OkStatus(); } absl::Status OperatorRegistry::RegisterOperator(absl::string_view name, OperatorPtr op, size_t overwrite_priority) { if (!IsOperatorName(name)) { return absl::InvalidArgumentError( absl::StrFormat("incorrect operator name \"%s\"", name)); } absl::WriterMutexLock lock(&mutex_); auto& family = families_[name]; if (family == nullptr) { family = std::make_unique<CombinedOperatorFamily>(std::string(name)); } auto* combined_family = dynamic_cast<CombinedOperatorFamily*>(family.get()); if (combined_family == nullptr) { return absl::AlreadyExistsError( absl::StrFormat("trying to register a single QExpr operator and an " "operator family under the same name %s", name)); } return combined_family->Insert(std::move(op), overwrite_priority); } std::vector<std::string> OperatorRegistry::ListRegisteredOperators() { absl::ReaderMutexLock lock(&mutex_); std::vector<std::string> names; names.reserve(families_.size()); for (const auto& [name, family] : families_) { names.push_back(name); } return names; } absl::StatusOr<const OperatorFamily*> OperatorRegistry::LookupOperatorFamily( absl::string_view name) const { absl::ReaderMutexLock lock(&mutex_); auto iter = families_.find(name); if (iter == families_.end()) { return absl::Status(absl::StatusCode::kNotFound, absl::StrFormat("QExpr operator %s not found; %s", name, SuggestMissingDependency())); } return iter->second.get(); } absl::StatusOr<OperatorPtr> OperatorRegistry::DoLookupOperator( absl::string_view name, absl::Span<const QTypePtr> input_types, QTypePtr output_type) const { ASSIGN_OR_RETURN(auto family, LookupOperatorFamily(name)); return family->GetOperator(input_types, output_type); } OperatorRegistry* OperatorRegistry::GetInstance() { static absl::NoDestructor<OperatorRegistry> instance; return instance.get(); } namespace { struct BoundOperatorState { std::unique_ptr<BoundOperator> op; std::vector<TypedSlot> input_slots; TypedSlot output_slot; FrameLayout layout; }; absl::StatusOr<BoundOperatorState> BindToNewLayout(const QExprOperator& op) { FrameLayout::Builder layout_builder; auto input_slots = AddSlots(op.signature()->input_types(), &layout_builder); auto output_slot = AddSlot(op.signature()->output_type(), &layout_builder); ASSIGN_OR_RETURN(auto bound_op, op.Bind(input_slots, output_slot)); return BoundOperatorState{std::move(bound_op), input_slots, output_slot, std::move(layout_builder).Build()}; } absl::Status VerifyOperatorSlots(const QExprOperator& op, absl::Span<const TypedSlot> input_slots, TypedSlot output_slot) { auto signature = op.signature(); RETURN_IF_ERROR(VerifyInputSlotTypes(input_slots, signature->input_types())); return VerifyOutputSlotType(output_slot, signature->output_type()); } } absl::StatusOr<OperatorPtr> EnsureOutputQTypeMatches( absl::StatusOr<OperatorPtr> op_or, absl::Span<const QTypePtr> input_types, QTypePtr output_type) { ASSIGN_OR_RETURN(auto op, op_or); if (op->signature()->output_type() != output_type) { return absl::Status( absl::StatusCode::kNotFound, absl::StrFormat("unexpected output type for arguments %s: requested " "%s, available %s", FormatTypeVector(input_types), output_type->name(), op->signature()->output_type()->name())); } return op; } absl::StatusOr<TypedValue> InvokeOperator(const QExprOperator& op, absl::Span<const TypedValue> args) { RETURN_IF_ERROR(VerifyInputValueTypes(args, op.signature()->input_types())); ASSIGN_OR_RETURN(auto bound, BindToNewLayout(op)); RootEvaluationContext root_ctx(&bound.layout); for (size_t i = 0; i < args.size(); ++i) { RETURN_IF_ERROR(args[i].CopyToSlot(bound.input_slots[i], root_ctx.frame())); } EvaluationContext ctx(root_ctx); bound.op->Run(&ctx, root_ctx.frame()); if (!ctx.status().ok()) { return std::move(ctx).status(); } return TypedValue::FromSlot(bound.output_slot, root_ctx.frame()); } absl::StatusOr<TypedValue> InvokeOperator(absl::string_view op_name, absl::Span<const TypedValue> args, QTypePtr output_qtype) { std::vector<QTypePtr> arg_types; arg_types.reserve(args.size()); for (const auto& arg : args) { arg_types.push_back(arg.GetType()); } ASSIGN_OR_RETURN(auto op, OperatorRegistry::GetInstance()->LookupOperator( op_name, arg_types, output_qtype)); return InvokeOperator(*op, args); } absl::StatusOr<std::unique_ptr<BoundOperator>> QExprOperator::Bind( absl::Span<const TypedSlot> input_slots, TypedSlot output_slot) const { RETURN_IF_ERROR(VerifyOperatorSlots(*this, input_slots, output_slot)); return DoBind(input_slots, output_slot); } }
#include "arolla/qexpr/operators.h" #include <algorithm> #include <cstdint> #include <memory> #include <string> #include <utility> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "absl/status/status_matchers.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "absl/types/span.h" #include "arolla/codegen/qexpr/testing/test_operators.h" #include "arolla/memory/frame.h" #include "arolla/qexpr/eval_context.h" #include "arolla/qexpr/qexpr_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/qtype/typed_slot.h" #include "arolla/qtype/typed_value.h" namespace arolla { namespace { using ::absl_testing::IsOkAndHolds; using ::absl_testing::StatusIs; using ::testing::ContainsRegex; using ::testing::ElementsAre; using ::testing::Eq; using ::testing::HasSubstr; using ::testing::Property; TEST(OperatorsTest, LookupTestOperator) { QTypePtr f32_type = GetQType<float>(); auto op = OperatorRegistry::GetInstance() ->LookupOperator("test.add", {f32_type, f32_type}, f32_type) .value(); EXPECT_EQ(op->signature(), QExprOperatorSignature::Get({f32_type, f32_type}, f32_type)); FrameLayout::Builder layout_builder; auto arg1_slot = layout_builder.AddSlot<float>(); auto arg2_slot = layout_builder.AddSlot<float>(); auto result_slot = layout_builder.AddSlot<float>(); auto bound_op = op->Bind(ToTypedSlots(arg1_slot, arg2_slot), TypedSlot::FromSlot(result_slot)) .value(); FrameLayout memory_layout = std::move(layout_builder).Build(); RootEvaluationContext root_ctx(&memory_layout); EvaluationContext ctx(root_ctx); root_ctx.Set(arg1_slot, 2.0f); root_ctx.Set(arg2_slot, 3.0f); bound_op->Run(&ctx, root_ctx.frame()); EXPECT_OK(ctx.status()); float result = root_ctx.Get(result_slot); EXPECT_THAT(result, Eq(5.0f)); } TEST(OperatorsTest, LookupOperator_WithOutputType) { QTypePtr f32_type = GetQType<float>(); auto op_float = OperatorRegistry::GetInstance() ->LookupOperator("test.add", {f32_type, f32_type}, f32_type) .value(); EXPECT_EQ(op_float->signature(), QExprOperatorSignature::Get({f32_type, f32_type}, f32_type)); QTypePtr f64_type = GetQType<float>(); auto op_double = OperatorRegistry::GetInstance() ->LookupOperator("test.add", {f32_type, f32_type}, f64_type) .value(); EXPECT_EQ(op_double->signature(), QExprOperatorSignature::Get({f64_type, f64_type}, f64_type)); EXPECT_THAT( OperatorRegistry::GetInstance()->LookupOperator( "test.add", {f32_type, f32_type}, GetQType<int32_t>()), StatusIs( absl::StatusCode::kNotFound, HasSubstr( "QExpr operator test.add(FLOAT32,FLOAT32)->INT32 not found"))); } TEST(OperatorsTest, Bind) { QTypePtr float_type = GetQType<float>(); auto op = OperatorRegistry::GetInstance() ->LookupOperator("test.add", {float_type, float_type}, float_type) .value(); EXPECT_EQ(op->signature(), QExprOperatorSignature::Get({float_type, float_type}, float_type)); FrameLayout::Builder layout_builder; auto arg1_slot = layout_builder.AddSlot<float>(); auto arg2_slot = layout_builder.AddSlot<float>(); auto double_slot = layout_builder.AddSlot<double>(); auto result_slot = layout_builder.AddSlot<float>(); auto bound_op = op->Bind(ToTypedSlots(arg1_slot, arg2_slot), TypedSlot::FromSlot(result_slot)) .value(); EXPECT_THAT( op->Bind(ToTypedSlots(arg1_slot), TypedSlot::FromSlot(result_slot)), StatusIs( absl::StatusCode::kFailedPrecondition, "incorrect input types: expected (FLOAT32,FLOAT32), got (FLOAT32)")); EXPECT_THAT(op->Bind(ToTypedSlots(arg1_slot, double_slot), TypedSlot::FromSlot(result_slot)), StatusIs(absl::StatusCode::kFailedPrecondition, "incorrect input types: expected (FLOAT32,FLOAT32), got " "(FLOAT32,FLOAT64)")); EXPECT_THAT( op->Bind(ToTypedSlots(arg1_slot, arg2_slot), TypedSlot::FromSlot(double_slot)), StatusIs(absl::StatusCode::kFailedPrecondition, "incorrect output types: expected (FLOAT32), got (FLOAT64)")); FrameLayout memory_layout = std::move(layout_builder).Build(); RootEvaluationContext root_ctx(&memory_layout); EvaluationContext ctx(root_ctx); root_ctx.Set(arg1_slot, 2.0f); root_ctx.Set(arg2_slot, 3.0f); bound_op->Run(&ctx, root_ctx.frame()); EXPECT_OK(ctx.status()); float result = root_ctx.Get(result_slot); EXPECT_THAT(result, Eq(5.0f)); } TEST(OperatorsTest, TestUserDefinedDataType) { QTypePtr f64_type = GetQType<double>(); QTypePtr v3_type = GetQType<testing::Vector3<double>>(); auto op1 = OperatorRegistry::GetInstance() ->LookupOperator("test.vector3", {f64_type, f64_type, f64_type}, v3_type) .value(); EXPECT_EQ(op1->signature(), QExprOperatorSignature::Get( {f64_type, f64_type, f64_type}, v3_type)); auto op2 = OperatorRegistry::GetInstance() ->LookupOperator("test.dot_prod", {v3_type, v3_type}, f64_type) .value(); EXPECT_EQ(op2->signature(), QExprOperatorSignature::Get({v3_type, v3_type}, f64_type)); FrameLayout::Builder layout_builder; auto x_slot = layout_builder.AddSlot<double>(); auto y_slot = layout_builder.AddSlot<double>(); auto z_slot = layout_builder.AddSlot<double>(); auto v_slot = layout_builder.AddSlot<testing::Vector3<double>>(); auto v_typed_slot = TypedSlot::FromSlot(v_slot, v3_type); auto result_slot = layout_builder.AddSlot<double>(); auto bound_op1 = op1->Bind(ToTypedSlots(x_slot, y_slot, z_slot), v_typed_slot).value(); auto bound_op2 = op2->Bind({v_typed_slot, v_typed_slot}, TypedSlot::FromSlot(result_slot)) .value(); FrameLayout memory_layout = std::move(layout_builder).Build(); RootEvaluationContext root_ctx(&memory_layout); EvaluationContext ctx(root_ctx); root_ctx.Set(x_slot, 3.0); root_ctx.Set(y_slot, 4.0); root_ctx.Set(z_slot, 5.0); bound_op1->Run(&ctx, root_ctx.frame()); EXPECT_OK(ctx.status()); bound_op2->Run(&ctx, root_ctx.frame()); EXPECT_OK(ctx.status()); double result = root_ctx.Get(result_slot); EXPECT_THAT(result, Eq(50.0)); } TEST(OperatorsTest, OperatorNotFound) { auto error = OperatorRegistry::GetInstance()->LookupOperator( "test.halts", {}, GetQType<int64_t>()); EXPECT_THAT(error, StatusIs(absl::StatusCode::kNotFound, ContainsRegex( "QExpr operator test.halts not found; adding " "\".*\" build dependency may help"))); } TEST(OperatorsTest, OperatorOverloadNotFound) { QTypePtr bool_type = GetQType<bool>(); QTypePtr float_type = GetQType<float>(); EXPECT_THAT( OperatorRegistry::GetInstance()->LookupOperator( "test.add", {bool_type, float_type}, float_type), StatusIs( absl::StatusCode::kNotFound, ContainsRegex("QExpr operator test.add\\(BOOLEAN,FLOAT32\\)->FLOAT32 " "not found; adding \".*\" build dependency may help"))); } TEST(OperatorsTest, InvokeOperator) { ASSERT_OK_AND_ASSIGN( auto mul_op, OperatorRegistry::GetInstance()->LookupOperator( "test.mul", {GetQType<int64_t>(), GetQType<int64_t>()}, GetQType<int64_t>())); EXPECT_THAT( InvokeOperator(*mul_op, {TypedValue::FromValue(int64_t{3}), TypedValue::FromValue(int64_t{19})}), IsOkAndHolds(Property(&TypedValue::As<int64_t>, IsOkAndHolds(Eq(57))))); EXPECT_THAT(InvokeOperator(*mul_op, {TypedValue::FromValue(3.0), TypedValue::FromValue(int64_t{19})}), StatusIs(absl::StatusCode::kFailedPrecondition, "incorrect input types: expected (INT64,INT64), got " "(FLOAT64,INT64)")); EXPECT_THAT(InvokeOperator<int64_t>(*mul_op, int64_t{3}, int64_t{19}), IsOkAndHolds(Eq(57))); EXPECT_THAT(InvokeOperator<int32_t>(*mul_op, int64_t{3}, int64_t{19}), StatusIs(absl::StatusCode::kFailedPrecondition, HasSubstr("type mismatch"))); } TEST(OperatorsTest, InvokeOperatorWithLookup) { EXPECT_THAT( InvokeOperator("test.mul", {TypedValue::FromValue(int64_t{3}), TypedValue::FromValue(int64_t{19})}, GetQType<int64_t>()), IsOkAndHolds(Property(&TypedValue::As<int64_t>, IsOkAndHolds(Eq(57))))); EXPECT_THAT( InvokeOperator( "test.mul", {TypedValue::FromValue(3.0), TypedValue::FromValue(int64_t{19})}, GetQType<int64_t>()), StatusIs(absl::StatusCode::kNotFound, HasSubstr( "QExpr operator test.mul(FLOAT64,INT64)->INT64 not found"))); EXPECT_THAT(InvokeOperator<int64_t>("test.mul", int64_t{3}, int64_t{19}), IsOkAndHolds(Eq(57))); } TEST(OperatorsTest, QExprOperatorSignatureTypeAndName) { auto i32 = GetQType<int32_t>(); auto f64 = GetQType<double>(); auto fn = QExprOperatorSignature::Get({i32}, f64); EXPECT_EQ(absl::StrCat(fn), "(INT32)->FLOAT64"); } TEST(OperatorsTest, GetQExprOperatorSignature) { auto i32 = GetQType<int32_t>(); auto f64 = GetQType<double>(); const QExprOperatorSignature* fn = QExprOperatorSignature::Get({i32}, f64); EXPECT_THAT(fn->input_types(), ElementsAre(i32)); EXPECT_THAT(fn->output_type(), Eq(f64)); } TEST(OperatorsTest, QExprOperatorSignatureInputsAreStored) { auto i32 = GetQType<int32_t>(); std::vector<QTypePtr> types(100, i32); auto fn_type = QExprOperatorSignature::Get(types, i32); auto f64 = GetQType<double>(); std::fill(types.begin(), types.end(), f64); std::vector<QTypePtr> types2(100, i32); auto fn2_type = QExprOperatorSignature::Get(types2, i32); ASSERT_EQ(fn_type, fn2_type); } TEST(OperatorsTest, QExprOperatorSignatureSingleton) { auto i32 = GetQType<int32_t>(); auto f64 = GetQType<double>(); EXPECT_TRUE(QExprOperatorSignature::Get({f64}, i32) == QExprOperatorSignature::Get({f64}, i32)); auto get_complex_fn = [&]() { return QExprOperatorSignature::Get({f64, i32, MakeTupleQType({f64, i32})}, MakeTupleQType({f64, i32, f64})); }; EXPECT_TRUE(get_complex_fn() == get_complex_fn()); } class DummyQExprOperator final : public QExprOperator { public: using QExprOperator::QExprOperator; private: absl::StatusOr<std::unique_ptr<BoundOperator>> DoBind( absl::Span<const TypedSlot> input_slots, TypedSlot output_slot) const final { return absl::UnimplementedError("unimplemented"); } }; TEST(OperatorsTest, RegisterOperatorWithHigherPriority) { const std::string op_name = "test_register_operator_with_higher_priority.op"; const auto f32 = GetQType<float>(); const auto f64 = GetQType<double>(); auto op1 = std::make_shared<DummyQExprOperator>( QExprOperatorSignature::Get({}, f32)); auto op2 = std::make_shared<DummyQExprOperator>( QExprOperatorSignature::Get({}, f64)); auto& registry = *OperatorRegistry::GetInstance(); ASSERT_OK(registry.RegisterOperator(op_name, op1, 0)); ASSERT_THAT(registry.LookupOperator(op_name, {}, f32), IsOkAndHolds(op1)); ASSERT_THAT(registry.LookupOperator(op_name, {}, f64), StatusIs(absl::StatusCode::kNotFound)); ASSERT_OK(registry.RegisterOperator(op_name, op2, 1)); ASSERT_THAT(registry.LookupOperator(op_name, {}, f32), StatusIs(absl::StatusCode::kNotFound)); ASSERT_THAT(registry.LookupOperator(op_name, {}, f64), IsOkAndHolds(op2)); } TEST(OperatorsTest, RegisterOperatorWithLowerPriority) { const std::string op_name = "test_register_operator_with_lower_priority.op"; const auto f32 = GetQType<float>(); const auto f64 = GetQType<double>(); auto op1 = std::make_shared<DummyQExprOperator>( QExprOperatorSignature::Get({}, f32)); auto op2 = std::make_shared<DummyQExprOperator>( QExprOperatorSignature::Get({}, f64)); auto& registry = *OperatorRegistry::GetInstance(); ASSERT_OK(registry.RegisterOperator(op_name, op1, 1)); ASSERT_THAT(registry.LookupOperator(op_name, {}, f32), IsOkAndHolds(op1)); ASSERT_THAT(registry.LookupOperator(op_name, {}, f64), StatusIs(absl::StatusCode::kNotFound)); ASSERT_OK(registry.RegisterOperator(op_name, op2, 0)); ASSERT_THAT(registry.LookupOperator(op_name, {}, f32), IsOkAndHolds(op1)); ASSERT_THAT(registry.LookupOperator(op_name, {}, f64), StatusIs(absl::StatusCode::kNotFound)); } TEST(OperatorsTest, RegisterOperatorAlreadyExists) { const std::string op_name = "test_register_operator_already_exisits.op"; const auto f32 = GetQType<float>(); auto op = std::make_shared<DummyQExprOperator>( QExprOperatorSignature::Get({}, f32)); auto& registry = *OperatorRegistry::GetInstance(); ASSERT_OK(registry.RegisterOperator(op_name, op, 1)); ASSERT_THAT(registry.RegisterOperator(op_name, op, 1), StatusIs(absl::StatusCode::kAlreadyExists)); ASSERT_OK(registry.RegisterOperator(op_name, op, 0)); ASSERT_THAT(registry.RegisterOperator(op_name, op, 0), StatusIs(absl::StatusCode::kAlreadyExists)); } TEST(OperatorsTest, RegisterOperatorBadName) { const std::string op_name = "123name"; const auto f32 = GetQType<float>(); auto op = std::make_shared<DummyQExprOperator>( QExprOperatorSignature::Get({}, f32)); auto& registry = *OperatorRegistry::GetInstance(); EXPECT_THAT(registry.RegisterOperator(op_name, op, 0), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("incorrect operator name"))); } TEST(OperatorsTest, RegisterOperatorPriorityOutOfRange) { const std::string op_name = "test_register_operator_priority_out_or_range.op"; const auto f32 = GetQType<float>(); auto op = std::make_shared<DummyQExprOperator>( QExprOperatorSignature::Get({}, f32)); auto& registry = *OperatorRegistry::GetInstance(); ASSERT_THAT(registry.RegisterOperator(op_name, op, 2), StatusIs(absl::StatusCode::kInvalidArgument)); } } }
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/qexpr/operators.cc
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/qexpr/operators_test.cc
1ca990dbeca224035efdabffecc7f3738df6b52c
16f9733f-766f-40e0-9dc0-7359dc774407
cpp
google/arolla
operator_metadata
arolla/qexpr/operator_metadata.cc
arolla/qexpr/operator_metadata_test.cc
#include "arolla/qexpr/operator_metadata.h" #include <set> #include <string> #include <utility> #include <vector> #include "absl/base/no_destructor.h" #include "absl/container/flat_hash_map.h" #include "absl/log/log.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/synchronization/mutex.h" #include "absl/types/span.h" #include "arolla/qtype/qtype.h" namespace arolla { absl::Status QExprOperatorMetadataRegistry::AddOperatorFamilyMetadata( QExprOperatorFamilyMetadata metadata) { absl::WriterMutexLock lock(&mutex_); if (family_metadatas_.contains(metadata.name) || operator_metadatas_.contains(metadata.name)) { return absl::Status( absl::StatusCode::kAlreadyExists, absl::StrFormat("trying to register individual operator or operator " "family metadata twice under the same name %s", metadata.name)); } family_metadatas_.emplace(metadata.name, std::move(metadata)); return absl::OkStatus(); } absl::Status QExprOperatorMetadataRegistry::AddOperatorMetadata( QExprOperatorMetadata metadata) { absl::WriterMutexLock lock(&mutex_); if (family_metadatas_.contains(metadata.name)) { return absl::Status( absl::StatusCode::kAlreadyExists, absl::StrFormat("trying to register individual operator or operator " "family metadata twice under the same name %s", metadata.name)); } auto [iter, inserted] = operator_metadatas_.emplace(metadata.name, TypeToMetadata{}); if (iter->second.contains(metadata.input_qtypes)) { return absl::Status( absl::StatusCode::kAlreadyExists, absl::StrFormat("trying to register operator metadata twice " "for operator %s with input types %s", metadata.name, FormatTypeVector(metadata.input_qtypes))); } iter->second.emplace(metadata.input_qtypes, std::move(metadata)); return absl::OkStatus(); } absl::StatusOr<QExprOperatorMetadata> QExprOperatorMetadataRegistry::LookupOperatorMetadata( absl::string_view op_name, absl::Span<const QTypePtr> input_qtypes) const { absl::ReaderMutexLock lock(&mutex_); std::vector<QTypePtr> input_qtypes_vector(input_qtypes.begin(), input_qtypes.end()); if (auto m = family_metadatas_.find(op_name); m != family_metadatas_.end()) { return QExprOperatorMetadata{ .name = std::string(m->second.name), .input_qtypes = std::move(input_qtypes_vector), .build_details = m->second.family_build_details}; } if (auto oms = operator_metadatas_.find(op_name); oms != operator_metadatas_.end()) { if (auto m = oms->second.find(input_qtypes_vector); m != oms->second.end()) { return m->second; } } return absl::Status( absl::StatusCode::kNotFound, absl::StrFormat( "no metadata is available for operator %s with input types %s", op_name, FormatTypeVector(input_qtypes))); } QExprOperatorMetadataRegistry& QExprOperatorMetadataRegistry::GetInstance() { static absl::NoDestructor<QExprOperatorMetadataRegistry> instance; return *instance; } absl::flat_hash_map<std::string, std::set<std::string>> QExprOperatorMetadataRegistry::OperatorBuildDependencies() const { absl::flat_hash_map<std::string, std::set<std::string>> result; absl::ReaderMutexLock lock(&mutex_); for (const auto& [_, metadata] : family_metadatas_) { result[absl::StrCat(metadata.name, "(...)")].insert( metadata.family_build_details.build_target); } for (const auto& [name, type_to_meta] : operator_metadatas_) { for (const auto& [types, metadata] : type_to_meta) { std::string name_with_types = absl::StrCat(name, ::arolla::FormatTypeVector(types)); result[name_with_types].insert(metadata.build_details.build_target); } } return result; } int RegisterOperatorFamilyMetadataOrDie(QExprOperatorFamilyMetadata metadata) { auto status = QExprOperatorMetadataRegistry::GetInstance().AddOperatorFamilyMetadata( std::move(metadata)); if (!status.ok()) { LOG(FATAL) << status; } return 57; } int RegisterOperatorMetadataOrDie(QExprOperatorMetadata metadata) { auto status = QExprOperatorMetadataRegistry::GetInstance().AddOperatorMetadata( std::move(metadata)); if (!status.ok()) { LOG(FATAL) << status; } return 57; } }
#include "arolla/qexpr/operator_metadata.h" #include <cstdint> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "absl/status/status_matchers.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/util/operator_name.h" namespace arolla { namespace { using ::absl_testing::IsOkAndHolds; using ::absl_testing::StatusIs; using ::testing::Eq; using ::testing::Field; using ::testing::MatchesRegex; TEST(OperatorMetadataTest, OperatorMetadata) { auto i32 = GetQType<int32_t>(); auto f32 = GetQType<float>(); QExprOperatorMetadata add_ints_meta; add_ints_meta.name = AROLLA_OPERATOR_NAME("test.add"); add_ints_meta.input_qtypes = {i32, i32}; add_ints_meta.build_details.op_class = "Add<int>"; QExprOperatorMetadata add_floats_meta; add_floats_meta.name = AROLLA_OPERATOR_NAME("test.add"); add_floats_meta.input_qtypes = {f32, f32}; add_floats_meta.build_details.op_class = "Add<float>"; QExprOperatorMetadataRegistry registry; ASSERT_OK(registry.AddOperatorMetadata(add_ints_meta)); ASSERT_OK(registry.AddOperatorMetadata(add_floats_meta)); EXPECT_THAT( registry.AddOperatorMetadata(add_ints_meta), StatusIs(absl::StatusCode::kAlreadyExists, MatchesRegex("trying to register operator metadata twice for " "operator test.add with input types .*"))); EXPECT_THAT( registry.AddOperatorFamilyMetadata(QExprOperatorFamilyMetadata{ .name = add_ints_meta.name, .family_build_details = {}}), StatusIs(absl::StatusCode::kAlreadyExists, Eq("trying to register individual operator or operator family " "metadata twice under the same name test.add"))); EXPECT_THAT(registry.LookupOperatorMetadata(add_ints_meta.name, {i32, i32}), IsOkAndHolds(Field(&QExprOperatorMetadata::build_details, Field(&BuildDetails::op_class, "Add<int>")))); } TEST(OperatorMetadataTest, OperatorFamilyMetadata) { auto i32 = GetQType<int32_t>(); ::arolla::BuildDetails family_build_details; family_build_details.op_family_class = "AddFamily"; QExprOperatorFamilyMetadata add_meta{ .name = "test.add", .family_build_details = family_build_details}; QExprOperatorMetadataRegistry registry; ASSERT_OK(registry.AddOperatorFamilyMetadata(add_meta)); EXPECT_THAT( registry.AddOperatorMetadata(QExprOperatorMetadata{ .name = "test.add", .input_qtypes = {i32, i32}}), StatusIs(absl::StatusCode::kAlreadyExists, Eq("trying to register individual operator or operator family " "metadata twice under the same name test.add"))); EXPECT_THAT( registry.AddOperatorFamilyMetadata(add_meta), StatusIs(absl::StatusCode::kAlreadyExists, Eq("trying to register individual operator or operator family " "metadata twice under the same name test.add"))); EXPECT_THAT( registry.LookupOperatorMetadata(add_meta.name, {i32, i32}), IsOkAndHolds(Field(&QExprOperatorMetadata::build_details, Field(&BuildDetails::op_family_class, "AddFamily")))); } } }
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/qexpr/operator_metadata.cc
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/qexpr/operator_metadata_test.cc
1ca990dbeca224035efdabffecc7f3738df6b52c
2bfcf878-eab8-4d00-8e2a-4463f10332fb
cpp
google/arolla
simple_executable
arolla/qexpr/simple_executable.cc
arolla/qexpr/simple_executable_test.cc
#include "arolla/qexpr/simple_executable.h" #include <memory> #include "absl/status/status.h" #include "arolla/memory/frame.h" #include "arolla/qexpr/bound_operators.h" #include "arolla/qexpr/eval_context.h" #include "arolla/qexpr/evaluation_engine.h" namespace arolla { void SimpleBoundExpr::InitializeLiterals(EvaluationContext* ctx, FramePtr frame) const { RunBoundOperators(init_ops_, ctx, frame); } void SimpleBoundExpr::Execute(EvaluationContext* ctx, FramePtr frame) const { RunBoundOperators(eval_ops_, ctx, frame); } void CombinedBoundExpr::InitializeLiterals(EvaluationContext* ctx, FramePtr frame) const { for (const auto& e : subexprs_) { if (e->InitializeLiterals(ctx, frame); !ctx->status().ok()) { break; } } } void CombinedBoundExpr::Execute(EvaluationContext* ctx, FramePtr frame) const { for (const auto& e : subexprs_) { if (e->Execute(ctx, frame); !ctx->status().ok()) { break; } } } }
#include "arolla/qexpr/simple_executable.h" #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_matchers.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/base_types.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/typed_slot.h" #include "arolla/util/unit.h" namespace arolla { namespace { using ::absl_testing::IsOk; using ::testing::Eq; std::unique_ptr<BoundExpr> CreateCountingBoundExpr( FrameLayout::Slot<int> init_counter, FrameLayout::Slot<int> exec_counter) { std::vector<std::unique_ptr<BoundOperator>> init_ops; init_ops.push_back(MakeBoundOperator([=](EvaluationContext*, FramePtr frame) { ++(*frame.GetMutable(init_counter)); })); std::vector<std::unique_ptr<BoundOperator>> exec_ops; exec_ops.push_back(MakeBoundOperator([=](EvaluationContext*, FramePtr frame) { ++(*frame.GetMutable(exec_counter)); })); return std::make_unique<SimpleBoundExpr>( absl::flat_hash_map<std::string, TypedSlot>{}, TypedSlot::UnsafeFromOffset(GetQType<Unit>(), 0), std::move(init_ops), std::move(exec_ops)); } TEST(SimpleExecutableTest, CombinedBoundExpr) { FrameLayout::Builder builder; std::vector<std::unique_ptr<BoundExpr>> subexprs; auto init_1_called = builder.AddSlot<int>(); auto exec_1_called = builder.AddSlot<int>(); subexprs.push_back(CreateCountingBoundExpr(init_1_called, exec_1_called)); auto init_2_called = builder.AddSlot<int>(); auto exec_2_called = builder.AddSlot<int>(); subexprs.push_back(CreateCountingBoundExpr(init_2_called, exec_2_called)); std::unique_ptr<BoundExpr> combined_expr = std::make_unique<CombinedBoundExpr>( absl::flat_hash_map<std::string, TypedSlot>{}, TypedSlot::UnsafeFromOffset(GetQType<Unit>(), 0), absl::flat_hash_map<std::string, TypedSlot>{}, std::move(subexprs)); FrameLayout layout = std::move(builder).Build(); RootEvaluationContext ctx(&layout); ctx.Set(init_1_called, 0); ctx.Set(init_2_called, 0); ctx.Set(exec_1_called, 0); ctx.Set(exec_2_called, 0); ASSERT_THAT(combined_expr->InitializeLiterals(&ctx), IsOk()); EXPECT_THAT(ctx.Get(init_1_called), Eq(1)); EXPECT_THAT(ctx.Get(init_2_called), Eq(1)); EXPECT_THAT(ctx.Get(exec_1_called), Eq(0)); EXPECT_THAT(ctx.Get(exec_2_called), Eq(0)); ASSERT_THAT(combined_expr->Execute(&ctx), IsOk()); EXPECT_THAT(ctx.Get(init_1_called), Eq(1)); EXPECT_THAT(ctx.Get(init_2_called), Eq(1)); EXPECT_THAT(ctx.Get(exec_1_called), Eq(1)); EXPECT_THAT(ctx.Get(exec_2_called), Eq(1)); } } }
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/qexpr/simple_executable.cc
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/qexpr/simple_executable_test.cc
1ca990dbeca224035efdabffecc7f3738df6b52c
f4a51649-07d8-4120-9f41-31d475ba8b57
cpp
google/arolla
operator_errors
arolla/qexpr/operator_errors.cc
arolla/qexpr/operator_errors_test.cc
#include "arolla/qexpr/operator_errors.h" #include <cstddef> #include <initializer_list> #include <string> #include <vector> #include "absl/status/status.h" #include "absl/strings/ascii.h" #include "absl/strings/str_cat.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/qexpr/qexpr_operator_signature.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/typed_ref.h" #include "arolla/qtype/typed_value.h" namespace arolla { namespace { absl::Status SlotTypesMismatchError(absl::string_view slots_kind, absl::Span<const QTypePtr> expected_types, absl::Span<const QTypePtr> got_types) { return absl::FailedPreconditionError(absl::StrFormat( "incorrect %s types: expected %s, got %s", slots_kind, FormatTypeVector(expected_types), FormatTypeVector(got_types))); } template <typename T> std::vector<QTypePtr> GetQTypes(absl::Span<const T> objects) { std::vector<QTypePtr> types; types.reserve(objects.size()); for (const auto& o : objects) { types.push_back(o.GetType()); } return types; } template <typename T> absl::Status VerifyTypes(absl::Span<const T> objects, absl::Span<const QTypePtr> expected_types, absl::string_view slots_kind) { if (objects.size() != expected_types.size()) { return SlotTypesMismatchError(slots_kind, expected_types, GetQTypes(objects)); } for (size_t i = 0; i < objects.size(); ++i) { if (objects[i].GetType() != expected_types[i]) { return SlotTypesMismatchError(slots_kind, expected_types, GetQTypes(objects)); } } return absl::OkStatus(); } } absl::Status OperatorNotDefinedError(absl::string_view operator_name, absl::Span<const QTypePtr> input_types, absl::string_view extra_message) { return absl::NotFoundError(absl::StrCat( "operator ", operator_name, " is not defined for argument types ", FormatTypeVector(input_types), extra_message.empty() ? "" : ": ", extra_message)); } absl::Status VerifyInputSlotTypes(absl::Span<const TypedSlot> slots, absl::Span<const QTypePtr> expected_types) { return VerifyTypes(slots, expected_types, "input"); } absl::Status VerifyOutputSlotType(TypedSlot slot, QTypePtr expected_type) { return VerifyTypes<TypedSlot>({slot}, {expected_type}, "output"); } absl::Status VerifyInputValueTypes(absl::Span<const TypedValue> values, absl::Span<const QTypePtr> expected_types) { return VerifyTypes(values, expected_types, "input"); } absl::Status VerifyInputValueTypes(absl::Span<const TypedRef> values, absl::Span<const QTypePtr> expected_types) { return VerifyTypes(values, expected_types, "input"); } absl::Status VerifyOutputValueType(const TypedValue& value, QTypePtr expected_type) { return VerifyTypes<TypedValue>({value}, {expected_type}, "output"); } std::string GuessLibraryName(absl::string_view operator_name) { std::string path = absl::StrReplaceAll( operator_name.substr(0, operator_name.rfind('.')), {{".", "/"}}); return absl::StrCat(" } std::string GuessOperatorLibraryName(absl::string_view operator_name) { return absl::StrFormat("%s:operator_%s", GuessLibraryName(operator_name), absl::AsciiStrToLower(operator_name.substr( operator_name.rfind('.') + 1))); } std::string SuggestMissingDependency() { return "adding \"@arolla: "build dependency may help"; } std::string SuggestAvailableOverloads( absl::string_view operator_name, absl::Span<const QExprOperatorSignature* const> supported_qtypes) { std::vector<std::string> available_overloads; for (const auto type : supported_qtypes) { available_overloads.push_back(absl::StrFormat( "%s(%s) -> %s", operator_name, JoinTypeNames(type->input_types()), type->output_type()->name())); } return absl::StrFormat("available overloads:\n %s", absl::StrJoin(available_overloads, ",\n ")); } }
#include "arolla/qexpr/operator_errors.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "absl/status/status_matchers.h" #include "absl/strings/string_view.h" #include "arolla/dense_array/qtype/types.h" #include "arolla/memory/frame.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/typed_slot.h" #include "arolla/qtype/typed_value.h" namespace arolla { namespace { using ::absl_testing::IsOk; using ::absl_testing::StatusIs; using ::testing::Eq; TEST(OperatorErrorsTest, OperatorNotDefinedError) { absl::string_view op_name = "test.Not"; EXPECT_THAT( OperatorNotDefinedError(op_name, {GetQType<int>(), GetQType<float>()}), StatusIs(absl::StatusCode::kNotFound, "operator test.Not is not defined for argument types " "(INT32,FLOAT32)")); EXPECT_THAT(OperatorNotDefinedError(op_name, {GetQType<int>()}, "Oops"), StatusIs(absl::StatusCode::kNotFound, "operator test.Not is not defined for argument types " "(INT32): Oops")); } TEST(OperatorErrorsTest, VerifySlotTypes) { FrameLayout::Builder builder; auto int_slot = builder.AddSlot<int>(); auto double_slot = builder.AddSlot<double>(); EXPECT_THAT(VerifyInputSlotTypes(ToTypedSlots(int_slot, double_slot), {GetQType<int>(), GetQType<double>()}), IsOk()); EXPECT_THAT(VerifyInputSlotTypes(ToTypedSlots(int_slot, double_slot), {GetQType<int>(), GetQType<float>()}), StatusIs(absl::StatusCode::kFailedPrecondition, "incorrect input types: expected (INT32,FLOAT32), got " "(INT32,FLOAT64)")); } TEST(OperatorErrorsTest, VerifyValueTypes) { auto int_value = TypedValue::FromValue(57); auto double_value = TypedValue::FromValue(5.7); EXPECT_THAT(VerifyInputValueTypes({int_value, double_value}, {GetQType<int>(), GetQType<double>()}), IsOk()); EXPECT_THAT(VerifyInputValueTypes({int_value, double_value}, {GetQType<int>(), GetQType<float>()}), StatusIs(absl::StatusCode::kFailedPrecondition, "incorrect input types: expected (INT32,FLOAT32), got " "(INT32,FLOAT64)")); } TEST(OperatorErrorsTest, GuessLibraryName) { EXPECT_THAT(GuessLibraryName("math.add"), Eq(" EXPECT_THAT(GuessLibraryName("math.complex.add"), Eq(" } TEST(OperatorErrorsTest, GuessOperatorLibraryName) { EXPECT_THAT(GuessOperatorLibraryName("math.add"), Eq(" EXPECT_THAT( GuessOperatorLibraryName("math.complex.add"), Eq(" } } }
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/qexpr/operator_errors.cc
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/qexpr/operator_errors_test.cc
1ca990dbeca224035efdabffecc7f3738df6b52c
8d045eae-f78b-47ac-9a3d-4ba595aa190d
cpp
google/arolla
strings
arolla/qexpr/operators/strings/strings.cc
arolla/qexpr/operators/strings/strings_test.cc
#include "arolla/qexpr/operators/strings/strings.h" #include <cstddef> #include <cstdint> #include <limits> #include <memory> #include <optional> #include <string> #include <utility> #include "absl/base/no_destructor.h" #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/string_view.h" #include "icu4c/source/common/unicode/bytestream.h" #include "icu4c/source/common/unicode/casemap.h" #include "icu4c/source/common/unicode/errorcode.h" #include "icu4c/source/common/unicode/stringoptions.h" #include "icu4c/source/common/unicode/umachine.h" #include "icu4c/source/common/unicode/utf8.h" #include "double-conversion/double-to-string.h" #include "double-conversion/utils.h" #include "arolla/memory/optional_value.h" #include "arolla/qtype/strings/regex.h" #include "arolla/util/bytes.h" #include "arolla/util/text.h" #include "arolla/util/unit.h" #include "arolla/util/status_macros_backport.h" namespace arolla { namespace { absl::Status ValidateUtf8(absl::string_view bytes) { if (bytes.size() > size_t{std::numeric_limits<int32_t>::max()}) { return absl::UnimplementedError("string is too long to convert to UTF-8"); } int32_t offset = 0; while (offset < bytes.size()) { UChar32 character; int32_t previous_offset = offset; U8_NEXT(bytes.data(), offset, bytes.size(), character); if (character < 0) { return absl::InvalidArgumentError(absl::StrFormat( "invalid UTF-8 sequence at position %d", previous_offset)); } } return absl::OkStatus(); } } absl::StatusOr<Text> LowerOp::operator()( absl::string_view in, std::optional<absl::string_view> locale) const { std::string result; icu::StringByteSink<std::string> sink(&result); icu::ErrorCode error_code; const char* locale_ptr = locale.has_value() ? locale->data() : nullptr; icu::CaseMap::utf8ToLower(locale_ptr, U_FOLD_CASE_DEFAULT, absl::string_view(in), sink, nullptr, error_code); if (error_code.isFailure()) { return absl::InvalidArgumentError(absl::StrFormat( "utf8ToLower failed with error: %s", error_code.errorName())); } return Text(std::move(result)); } absl::StatusOr<Text> UpperOp::operator()( absl::string_view in, std::optional<absl::string_view> locale) const { std::string result; icu::StringByteSink<std::string> sink(&result); icu::ErrorCode error_code; const char* locale_ptr = locale.has_value() ? locale->data() : nullptr; icu::CaseMap::utf8ToUpper(locale_ptr, U_FOLD_CASE_DEFAULT, absl::string_view(in), sink, nullptr, error_code); if (error_code.isFailure()) { return absl::InvalidArgumentError(absl::StrFormat( "utf8ToUpper failed with error: %s", error_code.errorName())); } return Text(std::move(result)); } absl::StatusOr<Text> DecodeOp::operator()(absl::string_view s) const { RETURN_IF_ERROR(ValidateUtf8(s)); return Text(s); } absl::StatusOr<std::string> ReplaceOp::operator()( absl::string_view s, absl::string_view old_sub, absl::string_view new_sub, OptionalValue<int32_t> max_subs) const { size_t count = std::numeric_limits<size_t>::max(); if (max_subs.present) { if (max_subs.value == 0) { return std::string(s); } count = max_subs.value; } std::string res; size_t offset = 0; if (old_sub.empty()) { absl::StrAppend(&res, new_sub); while ((--count > 0) && (offset < s.length())) { absl::StrAppend(&res, s.substr(offset, 1), new_sub); ++offset; } } else { while (count-- > 0) { const size_t start = s.find(old_sub, offset); if (start == std::string::npos) break; absl::StrAppend(&res, s.substr(offset, start - offset), new_sub); offset = start + old_sub.size(); } } res.append(s.begin() + offset, s.end()); return res; } absl::StatusOr<absl::Nonnull<RegexPtr>> CompileRegexOp::operator()( absl::string_view pattern) const { return CompileRegex(pattern); } OptionalUnit ContainsRegexOp::operator()(absl::string_view text, const RegexPtr& regex) const { return OptionalUnit(regex != nullptr && regex->PartialMatch(text)); } OptionalUnit ContainsRegexOp::operator()(OptionalValue<absl::string_view> text, const RegexPtr& regex) const { return OptionalUnit(text.present && regex != nullptr && regex->PartialMatch(text.value)); } absl::StatusOr<OptionalValue<Text>> ExtractRegexOp::operator()( const Text& text, const RegexPtr& regex) const { if (regex == nullptr) { return std::nullopt; } if (regex->NumberOfCapturingGroups() != 1) { return absl::InvalidArgumentError( absl::StrFormat("ExtractRegexOp expected regular expression with " "exactly one capturing group; got `%s` which " "contains %d capturing groups", regex->pattern(), regex->NumberOfCapturingGroups())); } std::string match; if (regex->PartialMatch(text.view(), &match)) { return Text(std::move(match)); } return std::nullopt; } absl::StatusOr<OptionalValue<Text>> ExtractRegexOp::operator()( const OptionalValue<Text>& text, const RegexPtr& regex) const { if (text.present) { return (*this)(text.value, regex); } return std::nullopt; } namespace { template <class T> Text SignedIntegerToText(T x) { return Text(absl::StrFormat("%d", x)); } } Text AsTextOp::operator()(absl::string_view s) const { return Text(absl::StrFormat("b'%s'", absl::Utf8SafeCHexEscape(s))); } Text AsTextOp::operator()(const Bytes& x) const { return operator()(absl::string_view(x)); } Text AsTextOp::operator()(Unit) const { return Text("present"); } Text AsTextOp::operator()(int32_t x) const { return SignedIntegerToText(x); } Text AsTextOp::operator()(int64_t x) const { return SignedIntegerToText(x); } Text AsTextOp::operator()(uint64_t x) const { return Text(absl::StrFormat("%d", x)); } Text AsTextOp::operator()(bool x) const { return x ? Text("true") : Text("false"); } Text AsTextOp::operator()(float x) const { static const absl::NoDestructor<double_conversion::DoubleToStringConverter> converter(double_conversion::DoubleToStringConverter::NO_FLAGS, "inf", "nan", 'e', -6, 21, 6, 0); char buf[128]; double_conversion::StringBuilder builder(buf, sizeof(buf)); converter->ToShortestSingle(x, &builder); return Text(builder.Finalize()); } Text AsTextOp::operator()(double x) const { static const absl::NoDestructor<double_conversion::DoubleToStringConverter> converter(double_conversion::DoubleToStringConverter::NO_FLAGS, "inf", "nan", 'e', -6, 21, 6, 0); char buf[128]; double_conversion::StringBuilder builder(buf, sizeof(buf)); converter->ToShortest(x, &builder); return Text(builder.Finalize()); } Text TextAsTextOp::operator()(absl::string_view s) const { return Text(s); } Text TextAsTextOp::operator()(const Text& s) const { return s; } }
#include <cstdint> #include <string> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "absl/status/status_matchers.h" #include "arolla/dense_array/dense_array.h" #include "arolla/dense_array/qtype/types.h" #include "arolla/memory/optional_value.h" #include "arolla/qexpr/operators.h" #include "arolla/qtype/base_types.h" #include "arolla/util/bytes.h" #include "arolla/util/text.h" #include "arolla/util/unit.h" namespace arolla { namespace { using ::absl_testing::IsOkAndHolds; using ::absl_testing::StatusIs; using ::testing::ElementsAre; using ::testing::HasSubstr; TEST(StringsTest, AsText) { EXPECT_THAT(InvokeOperator<Text>("strings.as_text", kUnit), IsOkAndHolds(Text("present"))); EXPECT_THAT(InvokeOperator<Text>("strings.as_text", Text("text")), IsOkAndHolds(Text("text"))); EXPECT_THAT(InvokeOperator<Text>("strings.as_text", Bytes(std::string({0, 'b', '\'', 'e', 1}))), IsOkAndHolds(Text("b'\\x00\\x62\\'e\\x01'"))); EXPECT_THAT(InvokeOperator<Text>("strings.as_text", false), IsOkAndHolds(Text("false"))); EXPECT_THAT(InvokeOperator<Text>("strings.as_text", int32_t{1}), IsOkAndHolds(Text("1"))); EXPECT_THAT(InvokeOperator<Text>("strings.as_text", int64_t{1}), IsOkAndHolds(Text("1"))); EXPECT_THAT(InvokeOperator<Text>("strings.as_text", 2.3f), IsOkAndHolds(Text("2.3"))); EXPECT_THAT(InvokeOperator<Text>("strings.as_text", 2.3), IsOkAndHolds(Text("2.3"))); EXPECT_THAT(InvokeOperator<Text>("strings.as_text", 14.137167f), IsOkAndHolds(Text("14.137167"))); EXPECT_THAT(InvokeOperator<Text>("strings.as_text", 14.137167), IsOkAndHolds(Text("14.137167"))); EXPECT_THAT( InvokeOperator<DenseArray<Text>>( "strings.as_text", CreateDenseArray<Bytes>( {Bytes(std::string({0, 'b', '\'', 'e', 1}))})), IsOkAndHolds(ElementsAre(Text("b'\\x00\\x62\\'e\\x01'")))); } TEST(StringsTest, Decode) { EXPECT_THAT(InvokeOperator<Text>("strings.decode", Bytes("text")), IsOkAndHolds(Text("text"))); EXPECT_THAT(InvokeOperator<Text>("strings.decode", Bytes("te\0xt")), IsOkAndHolds(Text("te\0xt"))); EXPECT_THAT(InvokeOperator<Text>("strings.decode", Bytes("\xEF\xBF\xBD")), IsOkAndHolds(Text("\xEF\xBF\xBD"))); EXPECT_THAT(InvokeOperator<Text>("strings.decode", Bytes("\xA0text")), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("invalid UTF-8 sequence at position 0"))); EXPECT_THAT(InvokeOperator<Text>("strings.decode", Bytes("te\xC0\0xt")), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("invalid UTF-8 sequence at position 2"))); EXPECT_THAT(InvokeOperator<Text>("strings.decode", Bytes("text\x80")), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("invalid UTF-8 sequence at position 4"))); } TEST(StringsTest, Lower) { Text input("Hello World."); Text expected_output("hello world."); EXPECT_THAT(InvokeOperator<Text>("strings.lower", input), IsOkAndHolds(expected_output)); } TEST(StringsTest, LowerOptional) { OptionalValue<Text> input(Text("Hello World.")); OptionalValue<Text> expected_output(Text("hello world.")); EXPECT_THAT(InvokeOperator<OptionalValue<Text>>("strings.lower", input), IsOkAndHolds(expected_output)); } TEST(StringsTest, LowerWithLocale) { Text input("TITLE"); Text locale("TR_tr"); EXPECT_THAT(InvokeOperator<Text>("strings.lower", input, locale), IsOkAndHolds(Text("tıtle"))); } TEST(StringsTest, Upper) { Text input("Hello World."); EXPECT_THAT(InvokeOperator<Text>("strings.upper", input), IsOkAndHolds(Text("HELLO WORLD."))); } TEST(StringsTest, UpperWithLocale) { Text input("istanbul"); Text locale("TR_tr"); EXPECT_THAT(InvokeOperator<Text>("strings.upper", input, locale), IsOkAndHolds(Text("İSTANBUL"))); } TEST(StringsTest, BytesLength) { EXPECT_THAT(InvokeOperator<int32_t>("strings.length", Bytes("古池や蛙飛び込む水の音")), IsOkAndHolds(33)); } TEST(StringsTest, TextLength) { EXPECT_THAT( InvokeOperator<int32_t>("strings.length", Text("古池や蛙飛び込む水の音")), IsOkAndHolds(11)); } TEST(StringsTest, Replace) { Text input("Hello ello foo."); Text old_sub("ell"); Text new_sub("XX"); EXPECT_THAT(InvokeOperator<Text>("strings.replace", input, old_sub, new_sub, OptionalValue<int32_t>(-1)), IsOkAndHolds(Text("HXXo XXo foo."))); EXPECT_THAT(InvokeOperator<Text>("strings.replace", input, old_sub, new_sub, OptionalValue<int32_t>(0)), IsOkAndHolds(Text("Hello ello foo."))); EXPECT_THAT(InvokeOperator<Text>("strings.replace", input, old_sub, new_sub, OptionalValue<int32_t>(1)), IsOkAndHolds(Text("HXXo ello foo."))); EXPECT_THAT(InvokeOperator<Text>("strings.replace", input, old_sub, new_sub, OptionalValue<int32_t>(2)), IsOkAndHolds(Text("HXXo XXo foo."))); EXPECT_THAT(InvokeOperator<Text>("strings.replace", input, old_sub, new_sub, OptionalValue<int32_t>()), IsOkAndHolds(Text("HXXo XXo foo."))); EXPECT_THAT( InvokeOperator<Text>("strings.replace", input, Text(), new_sub, OptionalValue<int32_t>(-1)), IsOkAndHolds(Text("XXHXXeXXlXXlXXoXX XXeXXlXXlXXoXX XXfXXoXXoXX.XX"))); EXPECT_THAT( InvokeOperator<Text>("strings.replace", input, Text(), new_sub, OptionalValue<int32_t>()), IsOkAndHolds(Text("XXHXXeXXlXXlXXoXX XXeXXlXXlXXoXX XXfXXoXXoXX.XX"))); EXPECT_THAT(InvokeOperator<Text>("strings.replace", input, Text(), new_sub, OptionalValue<int32_t>(3)), IsOkAndHolds(Text("XXHXXeXXllo ello foo."))); EXPECT_THAT(InvokeOperator<Text>("strings.replace", Text(), Text(), new_sub, OptionalValue<int32_t>()), IsOkAndHolds(Text("XX"))); } } }
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/qexpr/operators/strings/strings.cc
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/qexpr/operators/strings/strings_test.cc
1ca990dbeca224035efdabffecc7f3738df6b52c
3dd9df2f-2903-48be-af03-c6f0f5984a68
cpp
google/arolla
join
arolla/qexpr/operators/strings/join.cc
arolla/qexpr/operators/strings/join_test.cc
#include "arolla/qexpr/operators/strings/join.h" #include <memory> #include <string> #include <vector> #include "absl/container/inlined_vector.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/memory/frame.h" #include "arolla/memory/optional_value.h" #include "arolla/qexpr/bound_operators.h" #include "arolla/qexpr/eval_context.h" #include "arolla/qexpr/operator_errors.h" #include "arolla/qexpr/operators.h" #include "arolla/qexpr/qexpr_operator_signature.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/bytes.h" #include "arolla/util/text.h" #include "arolla/util/status_macros_backport.h" namespace arolla { namespace { using std::unique_ptr; template <typename T> using Slot = FrameLayout::Slot<T>; template <class StringType> class JoinBoundOperator : public BoundOperator { public: JoinBoundOperator(Slot<StringType> delimiter_slot, std::vector<Slot<StringType>> part_slots, Slot<StringType> output_slot) : delimiter_slot_(delimiter_slot), part_slots_(std::move(part_slots)), output_slot_(output_slot) {} void Run(EvaluationContext* ctx, FramePtr frame) const override { absl::InlinedVector<absl::string_view, 10> parts; parts.reserve(part_slots_.size()); for (auto& s : part_slots_) { parts.push_back(frame.Get(s)); } frame.Set(output_slot_, StringType(absl::StrJoin(parts.begin(), parts.end(), frame.Get(delimiter_slot_)))); } private: Slot<StringType> delimiter_slot_; std::vector<Slot<StringType>> part_slots_; Slot<StringType> output_slot_; }; template <class StringType> class JoinOperator : public QExprOperator { public: explicit JoinOperator(const QExprOperatorSignature* type) : QExprOperator(type) {} private: absl::StatusOr<std::unique_ptr<BoundOperator>> DoBind( absl::Span<const TypedSlot> typed_input_slots, TypedSlot typed_output_slot) const final { ASSIGN_OR_RETURN(Slot<StringType> delimiter_slot, typed_input_slots[0].ToSlot<StringType>()); std::vector<Slot<StringType>> part_slots; part_slots.reserve(typed_input_slots.size() - 1); std::vector<Slot<bool>> presence_slots; presence_slots.reserve(typed_input_slots.size() - 1); for (const auto& s : typed_input_slots.subspan(1)) { if (IsOptionalQType(s.GetType())) { ASSIGN_OR_RETURN(auto input_slot, s.ToSlot<OptionalValue<StringType>>()); presence_slots.push_back(GetPresenceSubslotFromOptional(input_slot)); part_slots.push_back(GetValueSubslotFromOptional(input_slot)); } else { ASSIGN_OR_RETURN(Slot<StringType> part_slot, s.ToSlot<StringType>()); part_slots.push_back(part_slot); } } if (presence_slots.empty()) { ASSIGN_OR_RETURN(Slot<StringType> output_slot, typed_output_slot.ToSlot<StringType>()); return {std::make_unique<JoinBoundOperator<StringType>>( delimiter_slot, std::move(part_slots), output_slot)}; } else { ASSIGN_OR_RETURN(auto output_slot, typed_output_slot.ToSlot<OptionalValue<StringType>>()); auto join_op = JoinBoundOperator<StringType>( delimiter_slot, std::move(part_slots), GetValueSubslotFromOptional(output_slot)); return {unique_ptr<BoundOperator>(new WhereAllBoundOperator( presence_slots, GetPresenceSubslotFromOptional(output_slot), std::move(join_op)))}; } } }; } template <class StringType> absl::StatusOr<OperatorPtr> GetJoinOperator( absl::Span<const QTypePtr> input_types) { bool has_optional = std::any_of(input_types.begin(), input_types.end(), [](QTypePtr qtype) { return IsOptionalQType(qtype); }); const QTypePtr part_type = DecayOptionalQType(input_types[1]); QTypePtr output_type = part_type; if (has_optional) { ASSIGN_OR_RETURN(output_type, ToOptionalQType(output_type)); } auto operator_qtype = QExprOperatorSignature::Get(input_types, output_type); auto scalar_qtype = GetQType<StringType>(); if (part_type == scalar_qtype) { return OperatorPtr( std::make_unique<JoinOperator<StringType>>(operator_qtype)); } else { return OperatorNotDefinedError( kJoinOperatorName, input_types, absl::StrFormat("with a separator of type %s, joined parts must be %s", scalar_qtype->name(), scalar_qtype->name())); } } absl::StatusOr<OperatorPtr> JoinOperatorFamily::DoGetOperator( absl::Span<const QTypePtr> input_types, QTypePtr output_type) const { if (input_types.size() < 2) { return OperatorNotDefinedError(kJoinOperatorName, input_types, "expected at least 2 arguments."); } if (input_types[0] != GetQType<Text>() && input_types[0] != GetQType<Bytes>()) { return OperatorNotDefinedError( kJoinOperatorName, input_types, absl::StrFormat("first argument must be TEXT or BYTES but was %s.", input_types[0]->name())); } const QTypePtr part_type = DecayOptionalQType(input_types[1]); for (const QTypePtr t : input_types.subspan(2)) { if (DecayOptionalQType(t) != part_type) { return OperatorNotDefinedError(kJoinOperatorName, input_types, "joined parts must have same type."); } } if (input_types[0] == GetQType<Text>()) { return EnsureOutputQTypeMatches(GetJoinOperator<Text>(input_types), input_types, output_type); } else { return EnsureOutputQTypeMatches(GetJoinOperator<Bytes>(input_types), input_types, output_type); } } }
#include "arolla/qexpr/operators/strings/join.h" #include <tuple> #include <type_traits> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "absl/status/status_matchers.h" #include "absl/status/statusor.h" #include "arolla/memory/optional_value.h" #include "arolla/qexpr/operators.h" #include "arolla/qtype/base_types.h" #include "arolla/util/bytes.h" #include "arolla/util/text.h" using ::testing::HasSubstr; namespace arolla { using ::absl_testing::IsOkAndHolds; using ::absl_testing::StatusIs; namespace { template <typename TypeParam> class JoinStringsTest : public ::testing::Test { public: using StringType = std::tuple_element_t<0, TypeParam>; using EvalAsFunctor = std::tuple_element_t<1, TypeParam>; template <typename... Args> absl::StatusOr<StringType> InvokeOperator(const Args&... args) { if constexpr (EvalAsFunctor::value) { auto result = JoinOperatorFamily{}(args...); static_assert(std::is_same_v<decltype(result), StringType>); return result; } else { return ::arolla::InvokeOperator<StringType>( "strings._join_with_separator", args...); } } template <typename... Args> absl::StatusOr<OptionalValue<StringType>> InvokeOperatorOptional( const Args&... args) { if constexpr (EvalAsFunctor::value) { auto result = JoinOperatorFamily{}(args...); static_assert( std::is_same_v<decltype(result), OptionalValue<StringType>>); return result; } else { return ::arolla::InvokeOperator<OptionalValue<StringType>>( "strings._join_with_separator", args...); } } }; TYPED_TEST_SUITE_P(JoinStringsTest); TYPED_TEST_P(JoinStringsTest, JoinScalars) { using StringType = typename JoinStringsTest<TypeParam>::StringType; StringType first_part("first"); StringType second_part("second"); StringType third_part("third"); StringType delimiter("/"); EXPECT_THAT(this->InvokeOperator(delimiter, first_part), IsOkAndHolds(StringType("first"))); EXPECT_THAT( this->InvokeOperator(delimiter, first_part, second_part, third_part), IsOkAndHolds(StringType("first/second/third"))); EXPECT_THAT( this->InvokeOperator(delimiter, first_part, second_part, third_part), IsOkAndHolds(StringType("first/second/third"))); } TYPED_TEST_P(JoinStringsTest, JoinScalarsErrors) { if constexpr (!JoinStringsTest<TypeParam>::EvalAsFunctor::value) { using StringType = typename JoinStringsTest<TypeParam>::StringType; using OtherType = std::conditional_t<std::is_same_v<StringType, Text>, Bytes, Text>; StringType first_part("first"); StringType second_part("second"); StringType delimiter("/"); EXPECT_THAT(this->InvokeOperator(delimiter), StatusIs(absl::StatusCode::kNotFound, HasSubstr("expected at least 2 arguments."))); EXPECT_THAT(this->InvokeOperator(delimiter, first_part, second_part, OtherType("third")), StatusIs(absl::StatusCode::kNotFound, HasSubstr("joined parts must have same type."))); EXPECT_THAT(this->InvokeOperator(0, 1, 2), StatusIs(absl::StatusCode::kNotFound, HasSubstr("first argument must be"))); } } TYPED_TEST_P(JoinStringsTest, JoinOptionalScalars) { using StringType = typename JoinStringsTest<TypeParam>::StringType; OptionalValue<StringType> first_part(StringType("first")); OptionalValue<StringType> second_part(StringType("second")); StringType third_part("third"); StringType delimiter("/"); OptionalValue<StringType> expected1(StringType("first/second/third")); EXPECT_THAT(this->InvokeOperatorOptional(delimiter, first_part, second_part, third_part), IsOkAndHolds(expected1)); OptionalValue<StringType> expected2; EXPECT_THAT( this->InvokeOperatorOptional(delimiter, first_part, OptionalValue<StringType>{}, third_part), IsOkAndHolds(expected2)); } REGISTER_TYPED_TEST_SUITE_P(JoinStringsTest, JoinScalars, JoinOptionalScalars, JoinScalarsErrors); using BytesEvalNormally = std::tuple<Bytes, std::bool_constant<false>>; INSTANTIATE_TYPED_TEST_SUITE_P(Bytes, JoinStringsTest, BytesEvalNormally); using TextEvalNormally = std::tuple<Bytes, std::bool_constant<false>>; INSTANTIATE_TYPED_TEST_SUITE_P(Text, JoinStringsTest, TextEvalNormally); using BytesEvalFunctor = std::tuple<Bytes, std::bool_constant<true>>; INSTANTIATE_TYPED_TEST_SUITE_P(BytesFunctor, JoinStringsTest, BytesEvalFunctor); using TextEvalFunctor = std::tuple<Bytes, std::bool_constant<true>>; INSTANTIATE_TYPED_TEST_SUITE_P(TextFunctor, JoinStringsTest, TextEvalFunctor); } }
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/qexpr/operators/strings/join.cc
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/qexpr/operators/strings/join_test.cc
1ca990dbeca224035efdabffecc7f3738df6b52c
d9f38920-8985-4b8e-9c10-4265dbe5c665
cpp
google/arolla
format
arolla/qexpr/operators/strings/format.cc
arolla/qexpr/operators/strings/format_test.cc
#include "arolla/qexpr/operators/strings/format.h" #include <cstddef> #include <cstdint> #include <deque> #include <memory> #include <string> #include <utility> #include <vector> #include "absl/base/no_destructor.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/ascii.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 "arolla/memory/frame.h" #include "arolla/memory/optional_value.h" #include "arolla/qexpr/bound_operators.h" #include "arolla/qexpr/eval_context.h" #include "arolla/qexpr/operator_errors.h" #include "arolla/qexpr/operators.h" #include "arolla/qexpr/qexpr_operator_signature.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_ref.h" #include "arolla/qtype/typed_slot.h" #include "arolla/qtype/weak_qtype.h" #include "arolla/util/bytes.h" #include "arolla/util/string.h" #include "arolla/util/text.h" #include "arolla/util/status_macros_backport.h" namespace arolla { namespace { constexpr absl::string_view kPrintfOperatorName = "strings.printf"; constexpr absl::string_view kFormatOperatorName = "strings.format"; template <typename T> using Slot = FrameLayout::Slot<T>; class ValueHolder { public: const absl::string_view& AddValue(absl::string_view value) { return values_.emplace_back(value); } private: std::deque<absl::string_view> values_; }; template <typename T> absl::FormatArg WrapValueImpl(const void* source, ValueHolder*) { const T& value_ref = *(reinterpret_cast<const T*>(source)); return absl::FormatArg(value_ref); } template <> absl::FormatArg WrapValueImpl<Bytes>(const void* source, ValueHolder* value_holder) { const Bytes& value_ref = *(reinterpret_cast<const Bytes*>(source)); return absl::FormatArg(value_holder->AddValue(value_ref)); } using WrapValueFn = absl::FormatArg (*)(const void*, ValueHolder*); absl::StatusOr<WrapValueFn> GetWrapValueFn(QTypePtr qtype) { static const absl::NoDestructor<absl::flat_hash_map<QTypePtr, WrapValueFn>> converter_map({{GetQType<int32_t>(), &WrapValueImpl<int32_t>}, {GetQType<int64_t>(), &WrapValueImpl<int64_t>}, {GetQType<float>(), &WrapValueImpl<float>}, {GetQType<double>(), &WrapValueImpl<double>}, {GetWeakFloatQType(), &WrapValueImpl<double>}, {GetQType<Bytes>(), &WrapValueImpl<Bytes>}, {GetQType<bool>(), &WrapValueImpl<bool>}}); auto iter = converter_map->find(qtype); if (iter == converter_map->end()) { return absl::InvalidArgumentError(absl::StrFormat( "%s is not a supported format argument type", qtype->name())); } return iter->second; } class SlotFormatter { public: static absl::StatusOr<SlotFormatter> Create(TypedSlot slot) { ASSIGN_OR_RETURN(auto wrap_value_fn, GetWrapValueFn(slot.GetType())); return SlotFormatter(slot, wrap_value_fn); } absl::FormatArg Format(FramePtr frame, ValueHolder* value_holder) const { TypedRef ref = TypedRef::FromSlot(slot_, frame); return wrap_value_fn_(ref.GetRawPointer(), value_holder); } private: SlotFormatter(TypedSlot slot, WrapValueFn wrap_value_fn) : slot_(slot), wrap_value_fn_(wrap_value_fn) {} TypedSlot slot_; WrapValueFn wrap_value_fn_; }; absl::StatusOr<Slot<Bytes>> ReadFormatSpecSlot( const TypedSlot& slot, std::vector<Slot<bool>>& presence_slots) { if (IsOptionalQType(slot.GetType())) { DCHECK_EQ(slot.SubSlotCount(), 2); ASSIGN_OR_RETURN(auto presence_slot, slot.SubSlot(0).ToSlot<bool>()); presence_slots.push_back(presence_slot); return slot.SubSlot(1).ToSlot<Bytes>(); } else { return slot.ToSlot<Bytes>(); } } absl::StatusOr<std::vector<TypedSlot>> ReadValueArgSlots( absl::Span<const TypedSlot> arg_slots, std::vector<Slot<bool>>& presence_slots) { std::vector<TypedSlot> value_arg_slots; value_arg_slots.reserve(arg_slots.size()); for (auto arg_slot : arg_slots) { TypedSlot value_slot = arg_slot; if (IsOptionalQType(arg_slot.GetType())) { ASSIGN_OR_RETURN(Slot<bool> presence_slot, GetPresenceSubslotFromOptional(arg_slot)); presence_slots.push_back(presence_slot); ASSIGN_OR_RETURN(value_slot, GetValueSubslotFromOptional(arg_slot)); } value_arg_slots.push_back(value_slot); } return value_arg_slots; } class PrintfBoundOperator : public BoundOperator { public: PrintfBoundOperator(Slot<Bytes> format_spec_slot, std::vector<SlotFormatter> slot_formatters, Slot<Bytes> output_slot) : format_spec_slot_(format_spec_slot), slot_formatters_(std::move(slot_formatters)), output_slot_(output_slot) {} void Run(EvaluationContext* ctx, FramePtr frame) const override { absl::string_view fmt_spec = frame.Get(format_spec_slot_); absl::UntypedFormatSpec fmt(fmt_spec); ValueHolder value_holder; std::vector<absl::FormatArg> fmt_args; fmt_args.reserve(slot_formatters_.size()); for (const auto& slot_formatter : slot_formatters_) { fmt_args.push_back(slot_formatter.Format(frame, &value_holder)); } std::string out; if (absl::FormatUntyped(&out, fmt, fmt_args)) { frame.Set(output_slot_, Bytes(std::move(out))); } else { ctx->set_status(absl::InvalidArgumentError(absl::StrFormat( "format specification '%s' doesn't match format arguments", fmt_spec))); } } private: Slot<Bytes> format_spec_slot_; std::vector<SlotFormatter> slot_formatters_; Slot<Bytes> output_slot_; }; class PrintfOperator : public QExprOperator { public: explicit PrintfOperator(const QExprOperatorSignature* type) : QExprOperator(type) {} private: absl::StatusOr<std::unique_ptr<BoundOperator>> DoBind( absl::Span<const TypedSlot> typed_input_slots, TypedSlot typed_output_slot) const override { std::vector<Slot<bool>> presence_slots; ASSIGN_OR_RETURN(Slot<Bytes> format_spec_slot, ReadFormatSpecSlot(typed_input_slots[0], presence_slots)); ASSIGN_OR_RETURN( auto arg_value_slots, ReadValueArgSlots(typed_input_slots.subspan(1), presence_slots)); std::vector<SlotFormatter> slot_formatters; slot_formatters.reserve(arg_value_slots.size()); for (auto value_slot : arg_value_slots) { ASSIGN_OR_RETURN(auto slot_formatter, SlotFormatter::Create(value_slot)); slot_formatters.push_back(slot_formatter); } if (presence_slots.empty()) { ASSIGN_OR_RETURN(Slot<Bytes> output_slot, typed_output_slot.ToSlot<Bytes>()); return std::make_unique<PrintfBoundOperator>( format_spec_slot, std::move(slot_formatters), output_slot); } else { ASSIGN_OR_RETURN(Slot<OptionalValue<Bytes>> output_slot, typed_output_slot.ToSlot<OptionalValue<Bytes>>()); PrintfBoundOperator printf_op(format_spec_slot, std::move(slot_formatters), GetValueSubslotFromOptional(output_slot)); return std::unique_ptr<BoundOperator>(new WhereAllBoundOperator( presence_slots, GetPresenceSubslotFromOptional(output_slot), std::move(printf_op))); } } }; class PyFormatParser { public: static absl::StatusOr<PyFormatParser> Parse(absl::string_view fmt_spec) { const auto incorrect_spec = [&] { return absl::InvalidArgumentError( absl::StrFormat("incorrect format specification '%s'", fmt_spec)); }; const auto incorrect_arg = [&](absl::string_view arg) { return absl::InvalidArgumentError(absl::StrFormat( "incorrect arg '%s' in format specification '%s'", arg, fmt_spec)); }; std::vector<std::string> regular_texts = {""}; std::vector<absl::string_view> args; for (absl::string_view spec = fmt_spec; !spec.empty();) { if (absl::ConsumePrefix(&spec, "{{")) { regular_texts.back().push_back('{'); } else if (absl::ConsumePrefix(&spec, "{")) { size_t n = spec.find('}'); if (n == absl::string_view::npos) { return incorrect_spec(); } args.emplace_back(spec.substr(0, n)); spec.remove_prefix(n + 1); regular_texts.emplace_back(); } else if (absl::ConsumePrefix(&spec, "}}")) { regular_texts.back().push_back('}'); } else if (absl::ConsumePrefix(&spec, "}")) { return incorrect_spec(); } else { regular_texts.back().push_back(spec[0]); spec.remove_prefix(1); } } std::vector<std::string> arg_names; std::vector<std::string> arg_formats; arg_names.reserve(args.size()); arg_formats.reserve(args.size()); for (absl::string_view arg : args) { auto name = arg.substr(0, arg.find(':')); arg.remove_prefix(name.size()); if (!arolla::IsIdentifier(name)) { return incorrect_arg(arg); } arg_names.emplace_back(name); if (arg.empty()) { arg_formats.emplace_back(); } else { arg_formats.emplace_back(arg.begin() + 1, arg.end()); } } return PyFormatParser(std::move(regular_texts), std::move(arg_names), std::move(arg_formats)); } absl::StatusOr<std::string> Process( const absl::flat_hash_map<absl::string_view, int64_t>& arg_names_index, absl::Span<const TypedSlot> arg_value_slots, FramePtr frame) const { DCHECK_EQ(arg_names_.size() + 1, regular_texts_.size()); std::string result = regular_texts_[0]; for (size_t i = 0; i < arg_names_.size(); ++i) { int64_t index = -1; if (auto it = arg_names_index.find(arg_names_[i]); it != arg_names_index.end()) { index = it->second; } else { return absl::InvalidArgumentError( absl::StrFormat("argument name '%s' is not found", arg_names_[i])); } TypedRef arg_value_ref = TypedRef::FromSlot(arg_value_slots[index], frame); ASSIGN_OR_RETURN(std::string txt, FormatTypeReference(arg_value_ref, arg_formats_[i])); absl::StrAppend(&result, txt, regular_texts_[i + 1]); } return result; } private: PyFormatParser(std::vector<std::string> regular_texts, std::vector<std::string> arg_names, std::vector<std::string> arg_formats) : regular_texts_(std::move(regular_texts)), arg_names_(std::move(arg_names)), arg_formats_(std::move(arg_formats)) {} absl::StatusOr<std::string> FormatTypeReference( TypedRef arg_value_ref, absl::string_view arg_format) const { if (arg_format.empty() || arg_format == "v") { return FormatTypeReferenceNoFormat(arg_value_ref); } QTypePtr arg_type = arg_value_ref.GetType(); std::string result; bool success = false; auto try_format = [&](absl::string_view spec, const auto& value) { success = absl::FormatUntyped(&result, absl::UntypedFormatSpec(spec), {absl::FormatArg(value)}); }; auto get_result = [&]() -> absl::StatusOr<std::string> { if (!success) { return absl::InvalidArgumentError(absl::StrFormat( "failed to format value of type %s with format '%s'", arg_type->name(), arg_format)); } return result; }; bool format_has_suffix = absl::ascii_isalpha(arg_format.back()); if (arg_type == GetQType<float>() || arg_type == GetQType<double>() || arg_type == GetWeakFloatQType()) { std::string float_format = absl::StrCat("%", arg_format, format_has_suffix ? "" : "f"); if (arg_type == GetQType<float>()) { try_format(float_format, arg_value_ref.UnsafeAs<float>()); } else { try_format(float_format, arg_value_ref.UnsafeAs<double>()); } return get_result(); } if (arg_type == GetQType<int32_t>() || arg_type == GetQType<int64_t>()) { std::string integer_format = absl::StrCat("%", arg_format, format_has_suffix ? "" : "d"); if (arg_type == GetQType<int32_t>()) { try_format(integer_format, arg_value_ref.UnsafeAs<int32_t>()); } else { try_format(integer_format, arg_value_ref.UnsafeAs<int64_t>()); } return get_result(); } return absl::FailedPreconditionError(absl::StrCat( "unsupported format ", arg_format, " for type: ", arg_type->name())); } absl::StatusOr<std::string> FormatTypeReferenceNoFormat( TypedRef arg_value_ref) const { if (arg_value_ref.GetType() == GetQType<Bytes>()) { return arg_value_ref.UnsafeAs<Bytes>(); } if (arg_value_ref.GetType() == GetQType<int32_t>() || arg_value_ref.GetType() == GetQType<float>() || arg_value_ref.GetType() == GetQType<bool>()) { return arg_value_ref.Repr(); } if (arg_value_ref.GetType() == GetQType<int64_t>()) { return absl::StrCat(arg_value_ref.UnsafeAs<int64_t>()); } if (arg_value_ref.GetType() == GetQType<double>()) { return absl::StrCat(arg_value_ref.UnsafeAs<double>()); } if (arg_value_ref.GetType() == GetWeakFloatQType()) { return absl::StrCat(arg_value_ref.UnsafeAs<double>()); } return absl::FailedPreconditionError( absl::StrCat("Unknown type: ", arg_value_ref.GetType()->name())); } std::vector<std::string> regular_texts_; std::vector<std::string> arg_names_; std::vector<std::string> arg_formats_; }; class FormatBoundOperator : public BoundOperator { public: FormatBoundOperator(Slot<Bytes> format_spec_slot, Slot<Text> arg_names_slot, std::vector<TypedSlot> arg_value_slots, Slot<Bytes> output_slot) : format_spec_slot_(format_spec_slot), arg_names_slot_(arg_names_slot), arg_value_slots_(std::move(arg_value_slots)), output_slot_(output_slot) {} void Run(EvaluationContext* ctx, FramePtr frame) const override { absl::string_view fmt_spec = frame.Get(format_spec_slot_); absl::string_view arg_names = frame.Get(arg_names_slot_); absl::flat_hash_map<absl::string_view, int64_t> arg_names_index; int64_t arg_name_count = 0; if (!arg_names.empty()) { for (auto name : absl::StrSplit(arg_names, ',')) { if (bool inserted = arg_names_index.emplace(name, arg_name_count++).second; !inserted) { ctx->set_status(absl::InvalidArgumentError( absl::StrFormat("arg names specification '%s' contains duplicate " "names", arg_names))); return; } } } if (arg_name_count != arg_value_slots_.size()) { ctx->set_status(absl::InvalidArgumentError( absl::StrFormat("arg names specification doesn't match number of " "arguments: %s (expected #%d)", arg_names, arg_value_slots_.size()))); return; } absl::StatusOr<PyFormatParser> parser = PyFormatParser::Parse(fmt_spec); RETURN_IF_ERROR(parser.status()).With(ctx->set_status()); absl::StatusOr<std::string> result = parser->Process(arg_names_index, arg_value_slots_, frame); RETURN_IF_ERROR(result.status()).With(ctx->set_status()); frame.Set(output_slot_, Bytes(std::move(*result))); } private: Slot<Bytes> format_spec_slot_; Slot<Text> arg_names_slot_; std::vector<TypedSlot> arg_value_slots_; Slot<Bytes> output_slot_; }; class FormatOperator : public QExprOperator { public: explicit FormatOperator(const QExprOperatorSignature* type) : QExprOperator(type) {} private: absl::StatusOr<std::unique_ptr<BoundOperator>> DoBind( absl::Span<const TypedSlot> typed_input_slots, TypedSlot typed_output_slot) const override { std::vector<Slot<bool>> presence_slots; ASSIGN_OR_RETURN(auto format_spec_slot, ReadFormatSpecSlot(typed_input_slots[0], presence_slots)); ASSIGN_OR_RETURN(auto arg_names_slot, typed_input_slots[1].ToSlot<Text>()); ASSIGN_OR_RETURN( auto arg_value_slots, ReadValueArgSlots(typed_input_slots.subspan(2), presence_slots)); if (presence_slots.empty()) { ASSIGN_OR_RETURN(Slot<Bytes> output_slot, typed_output_slot.ToSlot<Bytes>()); return std::make_unique<FormatBoundOperator>( format_spec_slot, arg_names_slot, std::move(arg_value_slots), output_slot); } else { ASSIGN_OR_RETURN(Slot<OptionalValue<Bytes>> output_slot, typed_output_slot.ToSlot<OptionalValue<Bytes>>()); FormatBoundOperator format_op(format_spec_slot, arg_names_slot, std::move(arg_value_slots), GetValueSubslotFromOptional(output_slot)); return std::unique_ptr<BoundOperator>(new WhereAllBoundOperator( presence_slots, GetPresenceSubslotFromOptional(output_slot), std::move(format_op))); } } }; } absl::StatusOr<OperatorPtr> PrintfOperatorFamily::DoGetOperator( absl::Span<const QTypePtr> input_types, QTypePtr output_type) const { if (input_types.empty()) { return OperatorNotDefinedError(kPrintfOperatorName, input_types, "expected at least 1 argument"); } if (DecayOptionalQType(input_types[0]) != GetQType<Bytes>()) { return OperatorNotDefinedError(kPrintfOperatorName, input_types, "format_spec must have BYTES QType"); } bool has_optional_arg = IsOptionalQType(input_types[0]); for (size_t i = 1; i < input_types.size(); ++i) { QTypePtr value_type = input_types[i]; if (IsOptionalQType(value_type)) { has_optional_arg = true; value_type = DecayOptionalQType(value_type); } RETURN_IF_ERROR(GetWrapValueFn(value_type).status()); } QTypePtr result_type = has_optional_arg ? GetQType<OptionalValue<Bytes>>() : GetQType<Bytes>(); return EnsureOutputQTypeMatches( OperatorPtr(std::make_unique<PrintfOperator>( QExprOperatorSignature::Get(input_types, result_type))), input_types, output_type); } absl::StatusOr<OperatorPtr> FormatOperatorFamily::DoGetOperator( absl::Span<const QTypePtr> input_types, QTypePtr output_type) const { if (input_types.size() <= 1) { return OperatorNotDefinedError(kFormatOperatorName, input_types, "expected at least 2 argument"); } if (DecayOptionalQType(input_types[0]) != GetQType<Bytes>()) { return OperatorNotDefinedError(kFormatOperatorName, input_types, "format_spec must have BYTES QType"); } if (input_types[1] != GetQType<Text>()) { return OperatorNotDefinedError(kFormatOperatorName, input_types, "arg_names must have TEXT QType"); } bool has_optional_arg = IsOptionalQType(input_types[0]); for (size_t i = 2; i < input_types.size(); ++i) { QTypePtr value_type = input_types[i]; if (IsOptionalQType(value_type)) { has_optional_arg = true; value_type = DecayOptionalQType(value_type); } RETURN_IF_ERROR(GetWrapValueFn(value_type).status()); } QTypePtr result_type = has_optional_arg ? GetQType<OptionalValue<Bytes>>() : GetQType<Bytes>(); return EnsureOutputQTypeMatches( OperatorPtr(std::make_unique<FormatOperator>( QExprOperatorSignature::Get(input_types, result_type))), input_types, output_type); } }
#include "arolla/qexpr/operators/strings/format.h" #include <cstdint> #include <string> #include <type_traits> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "absl/status/status_matchers.h" #include "absl/status/statusor.h" #include "arolla/memory/optional_value.h" #include "arolla/qexpr/operators.h" #include "arolla/qtype/base_types.h" #include "arolla/util/bytes.h" #include "arolla/util/text.h" namespace arolla { using ::absl_testing::IsOkAndHolds; using ::absl_testing::StatusIs; using ::testing::HasSubstr; namespace { template <typename EvalAsFunctor> class PrintfTest : public ::testing::Test { public: template <typename... Args> absl::StatusOr<Bytes> InvokeOperator(const Args&... args) { if constexpr (EvalAsFunctor::value) { auto result = PrintfOperatorFamily{}(args...); static_assert(std::is_same_v<decltype(result), absl::StatusOr<Bytes>>); return result; } else { return ::arolla::InvokeOperator<Bytes>("strings._printf_bytes", args...); } } template <typename... Args> absl::StatusOr<OptionalValue<Bytes>> InvokeOperatorOptional( const Args&... args) { if constexpr (EvalAsFunctor::value) { auto result = PrintfOperatorFamily{}(args...); static_assert(std::is_same_v<decltype(result), absl::StatusOr<OptionalValue<Bytes>>>); return result; } else { return ::arolla::InvokeOperator<OptionalValue<Bytes>>( "strings._printf_bytes", args...); } } }; TYPED_TEST_SUITE_P(PrintfTest); TYPED_TEST_P(PrintfTest, FormatFloats) { Bytes format_spec("a=%0.2f b=%0.3f"); float a = 20.5f; double b = 3.75; EXPECT_THAT(this->InvokeOperator(format_spec, a, b), IsOkAndHolds(Bytes("a=20.50 b=3.750"))); } TYPED_TEST_P(PrintfTest, FormatIntegers) { Bytes format_spec("c=%02d, d=%d"); int32_t c = 3; int64_t d = 4; EXPECT_THAT(this->InvokeOperator(format_spec, c, d), IsOkAndHolds(Bytes("c=03, d=4"))); } TYPED_TEST_P(PrintfTest, FormatText) { Bytes format_spec("%s is %d years older than %s."); EXPECT_THAT( this->InvokeOperator(format_spec, Bytes("Sophie"), 2, Bytes("Katie")), IsOkAndHolds(Bytes("Sophie is 2 years older than Katie."))); } TYPED_TEST_P(PrintfTest, FormatOptional) { Bytes format_spec("The atomic weight of %s is %0.3f"); EXPECT_THAT( this->InvokeOperatorOptional(format_spec, OptionalValue<Bytes>("Iron"), OptionalValue<float>(55.845)), IsOkAndHolds( OptionalValue<Bytes>("The atomic weight of Iron is 55.845"))); EXPECT_THAT(this->InvokeOperatorOptional(OptionalValue<Bytes>(format_spec), OptionalValue<Bytes>("Iron"), OptionalValue<float>(55.845)), IsOkAndHolds( OptionalValue<Bytes>("The atomic weight of Iron is 55.845"))); EXPECT_THAT(this->InvokeOperatorOptional(format_spec, OptionalValue<Bytes>("Unobtainium"), OptionalValue<float>{}), IsOkAndHolds(OptionalValue<Bytes>{})); EXPECT_THAT(this->InvokeOperatorOptional(OptionalValue<Bytes>(), OptionalValue<Bytes>("Unobtainium"), OptionalValue<float>{0}), IsOkAndHolds(OptionalValue<Bytes>{})); } TYPED_TEST_P(PrintfTest, FormatMismatchedTypes) { Bytes format_spec("%s's atomic weight is %f"); EXPECT_THAT(this->InvokeOperator(format_spec, 1.0079, Bytes("Hydrogen")), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("doesn't match format arguments"))); } TYPED_TEST_P(PrintfTest, FormatUnsupportedType) { Bytes format_spec("Payload is %s."); EXPECT_THAT( this->InvokeOperator(format_spec, Text("abc")), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("TEXT is not a supported format argument type"))); } REGISTER_TYPED_TEST_SUITE_P(PrintfTest, FormatFloats, FormatIntegers, FormatText, FormatOptional, FormatMismatchedTypes, FormatUnsupportedType); INSTANTIATE_TYPED_TEST_SUITE_P(Operator, PrintfTest, std::bool_constant<false>); INSTANTIATE_TYPED_TEST_SUITE_P(Functor, PrintfTest, std::bool_constant<true>); class FormatTest : public ::testing::Test { public: template <typename... Args> absl::StatusOr<Bytes> InvokeOperator(const Args&... args) { return ::arolla::InvokeOperator<Bytes>("strings._format_bytes", args...); } template <typename... Args> absl::StatusOr<OptionalValue<Bytes>> InvokeOperatorOptional( const Args&... args) { return ::arolla::InvokeOperator<OptionalValue<Bytes>>( "strings._format_bytes", args...); } }; TEST_F(FormatTest, FormatNumeric) { Bytes format_spec("a={a} b={b}"); float a = 20.5f; int b = 37; EXPECT_THAT(this->InvokeOperator(format_spec, Text("a,b"), a, b), IsOkAndHolds(Bytes("a=20.5 b=37"))); } TEST_F(FormatTest, FormatBytes) { Bytes format_spec("a={a0} b={_b}"); Bytes a = "AAA"; Bytes b = "BBB"; EXPECT_THAT(this->InvokeOperator(format_spec, Text("a0,_b"), a, b), IsOkAndHolds(Bytes("a=AAA b=BBB"))); } TEST_F(FormatTest, NoEscape) { Bytes format_spec("a\\\\={a}"); float a = 20.5f; EXPECT_THAT(this->InvokeOperator(format_spec, Text("a"), a), IsOkAndHolds(Bytes("a\\\\=20.5"))); } TEST_F(FormatTest, Escape) { Bytes format_spec("a={{a}}"); float a = 20.5f; EXPECT_THAT(this->InvokeOperator(format_spec, Text("a"), a), IsOkAndHolds(Bytes("a={a}"))); } TEST_F(FormatTest, IncorrectSpec) { for (auto format_spec : {"{x{a}y}", "}{a}"}) { float a = 20.5f; EXPECT_THAT(this->InvokeOperator(Bytes(format_spec), Text("a"), a), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("incorrect format specification"))) << format_spec; } } TEST_F(FormatTest, InvalidArgName) { for (std::string arg_name : {"0a", "0_a", "7b", "a+a", "\\{a", "^", "a{"}) { float a = 20.5f; EXPECT_THAT( this->InvokeOperator(Bytes("{" + arg_name + "}"), Text(arg_name), a), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("incorrect arg"))) << arg_name; } } } }
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/qexpr/operators/strings/format.cc
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/qexpr/operators/strings/format_test.cc
1ca990dbeca224035efdabffecc7f3738df6b52c
74dff902-ed21-4c41-9e79-1b623a9d17d4
cpp
google/arolla
utility_operators
arolla/qexpr/operators/core/utility_operators.cc
arolla/qexpr/operators/core/utility_operators_test.cc
#include "arolla/qexpr/operators/core/utility_operators.h" #include <memory> #include "absl/status/statusor.h" #include "absl/types/span.h" #include "arolla/memory/frame.h" #include "arolla/qexpr/bound_operators.h" #include "arolla/qexpr/eval_context.h" #include "arolla/qexpr/operators.h" #include "arolla/qexpr/qexpr_operator_signature.h" #include "arolla/qtype/qtype.h" namespace arolla { namespace { class CopyOperator : public QExprOperator { public: explicit CopyOperator(QTypePtr type) : QExprOperator(QExprOperatorSignature::Get({type}, type)) {} private: absl::StatusOr<std::unique_ptr<BoundOperator>> DoBind( absl::Span<const TypedSlot> input_slots, TypedSlot output_slot) const final { return MakeBoundOperator( [input_slot = input_slots[0], output_slot = output_slot]( EvaluationContext*, FramePtr frame) { input_slot.CopyTo(frame, output_slot, frame); }); } }; } OperatorPtr MakeCopyOp(QTypePtr type) { return OperatorPtr(std::make_unique<CopyOperator>(type)); } }
#include "arolla/qexpr/operators/core/utility_operators.h" #include <utility> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "arolla/memory/frame.h" #include "arolla/qexpr/eval_context.h" #include "arolla/qexpr/operators.h" #include "arolla/qexpr/qexpr_operator_signature.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/tuple_qtype.h" #include "arolla/qtype/typed_slot.h" namespace arolla { namespace { using ::testing::Eq; TEST(UtilityOperatorsTest, Identity) { auto i32 = GetQType<int>(); auto copy_op = MakeCopyOp(i32); ASSERT_EQ(copy_op->signature(), QExprOperatorSignature::Get({i32}, i32)); FrameLayout::Builder layout_builder; auto i0_slot = layout_builder.AddSlot<int>(); auto i1_slot = layout_builder.AddSlot<int>(); ASSERT_OK_AND_ASSIGN( auto copy_bound_op0, copy_op->Bind(ToTypedSlots(i0_slot), TypedSlot::FromSlot(i1_slot))); auto memory_layout = std::move(layout_builder).Build(); RootEvaluationContext root_ctx(&memory_layout); EvaluationContext ctx(root_ctx); root_ctx.Set(i0_slot, 7); copy_bound_op0->Run(&ctx, root_ctx.frame()); EXPECT_OK(ctx.status()); EXPECT_THAT(root_ctx.Get(i1_slot), Eq(7)); } TEST(UtilityOperatorsTest, MakeTuple) { auto i32 = GetQType<int>(); auto f64 = GetQType<double>(); auto tuple_qtype = MakeTupleQType({i32, f64}); ASSERT_OK_AND_ASSIGN(auto copy_op, OperatorRegistry::GetInstance()->LookupOperator( "core.make_tuple", {i32, f64}, tuple_qtype)); ASSERT_EQ(copy_op->signature(), QExprOperatorSignature::Get({i32, f64}, tuple_qtype)); FrameLayout::Builder layout_builder; auto tuple0_slot = AddSlot(tuple_qtype, &layout_builder); ASSERT_EQ(tuple0_slot.SubSlotCount(), 2); ASSERT_OK_AND_ASSIGN(auto i0_slot, tuple0_slot.SubSlot(0).ToSlot<int>()); ASSERT_OK_AND_ASSIGN(auto d0_slot, tuple0_slot.SubSlot(1).ToSlot<double>()); auto tuple1_slot = AddSlot(tuple_qtype, &layout_builder); ASSERT_EQ(tuple1_slot.SubSlotCount(), 2); ASSERT_OK_AND_ASSIGN(auto i1_slot, tuple1_slot.SubSlot(0).ToSlot<int>()); ASSERT_OK_AND_ASSIGN(auto d1_slot, tuple1_slot.SubSlot(1).ToSlot<double>()); ASSERT_OK_AND_ASSIGN( auto copy_bound_op, copy_op->Bind(ToTypedSlots(i0_slot, d0_slot), {tuple1_slot})); auto memory_layout = std::move(layout_builder).Build(); RootEvaluationContext root_ctx(&memory_layout); EvaluationContext ctx(root_ctx); root_ctx.Set(i0_slot, 7); root_ctx.Set(d0_slot, 4.5); copy_bound_op->Run(&ctx, root_ctx.frame()); EXPECT_OK(ctx.status()); EXPECT_THAT(root_ctx.Get(i1_slot), Eq(7)); EXPECT_THAT(root_ctx.Get(d1_slot), Eq(4.5)); } } }
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/qexpr/operators/core/utility_operators.cc
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/qexpr/operators/core/utility_operators_test.cc
1ca990dbeca224035efdabffecc7f3738df6b52c
825121b8-ad78-435b-ad35-38ea20ebd23c
cpp
google/arolla
array_ops
arolla/qexpr/operators/dense_array/array_ops.cc
arolla/qexpr/operators/dense_array/array_ops_test.cc
#include "arolla/qexpr/operators/dense_array/array_ops.h" #include <cstdint> #include "absl/status/status.h" #include "absl/strings/str_format.h" #include "arolla/dense_array/dense_array.h" #include "arolla/qexpr/eval_context.h" namespace arolla { void DenseArrayAtOp::ReportIndexOutOfRangeError(EvaluationContext* ctx, int64_t index, int64_t size) { if (ctx->status().ok()) { ctx->set_status(absl::InvalidArgumentError( absl::StrFormat("array index %d out of range [0, %d)", index, size))); } } bool DenseArrayFromIndicesAndValues::ValidateInputs( EvaluationContext* ctx, const DenseArray<int64_t>& indices, int64_t values_size, int64_t size) { if (indices.size() != values_size) { ctx->set_status(absl::InvalidArgumentError( absl::StrFormat("expected arrays of the same sizes, got " "indices.size=%d, values.size=%d", indices.size(), values_size))); return false; } if (size < 0) { ctx->set_status(absl::InvalidArgumentError( absl::StrFormat("expected a non-negative integer, got size=%d", size))); return false; } if (!indices.IsFull()) { ctx->set_status( absl::InvalidArgumentError("missing indices are not supported")); return false; } int64_t last_index = -1; for (int64_t index : indices.values) { if (index <= last_index) { if (index < 0) { ctx->set_status(absl::InvalidArgumentError(absl::StrFormat( "expected non-negative indices, got index=%d", index))); return false; } else { ctx->set_status(absl::InvalidArgumentError( absl::StrFormat("expected a strictly increasing sequence of " "indices, got [..., %d, %d, ...]", last_index, index))); return false; } } else if (index >= size) { ctx->set_status(absl::InvalidArgumentError(absl::StrFormat( "index is out of range, index=%d >= size=%d", index, size))); return false; } last_index = index; } return true; } }
#include <cstdint> #include <optional> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "absl/status/status_matchers.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/qexpr/operators.h" namespace arolla::testing { namespace { using ::absl_testing::IsOkAndHolds; using ::absl_testing::StatusIs; using ::testing::ElementsAre; TEST(ArrayOpsTest, DenseArrayAtOp) { using OF = OptionalValue<float>; using OI = OptionalValue<int64_t>; auto arr = CreateDenseArray<float>({1, 2, 3, std::nullopt}); EXPECT_THAT(InvokeOperator<OF>("array.at", arr, int64_t{1}), IsOkAndHolds(OF(2))); EXPECT_THAT(InvokeOperator<OF>("array.at", arr, OI(2)), IsOkAndHolds(OF(3))); EXPECT_THAT(InvokeOperator<OF>("array.at", arr, OI(3)), IsOkAndHolds(OF())); EXPECT_THAT(InvokeOperator<OF>("array.at", arr, OI(4)), StatusIs(absl::StatusCode::kInvalidArgument, "array index 4 out of range [0, 4)")); EXPECT_THAT(InvokeOperator<OF>("array.at", arr, OI(-1)), StatusIs(absl::StatusCode::kInvalidArgument, "array index -1 out of range [0, 4)")); EXPECT_THAT(InvokeOperator<OF>("array.at", arr, OI()), IsOkAndHolds(OF())); EXPECT_THAT( InvokeOperator<DenseArray<float>>( "array.at", arr, CreateDenseArray<int64_t>({2, 3, std::nullopt, 0})), IsOkAndHolds(ElementsAre(3.f, std::nullopt, std::nullopt, 1.f))); EXPECT_THAT( InvokeOperator<DenseArray<float>>( "array.at", arr, CreateDenseArray<int64_t>({2, 3, std::nullopt, 4})), StatusIs(absl::StatusCode::kInvalidArgument, "array index 4 out of range [0, 4)")); } TEST(ArrayOpsTest, TestArrayTakeOver) { auto x = CreateDenseArray<int>({1, 2, 3, std::nullopt, 5, 6, 7, 8}); auto offsets = CreateDenseArray<int64_t>({0, 3, 2, 1, 4, 5, 6, std::nullopt}); auto splits = CreateDenseArray<int64_t>({0, 8}); ASSERT_OK_AND_ASSIGN(auto edge, DenseArrayEdge::FromSplitPoints(splits)); EXPECT_THAT( InvokeOperator<DenseArray<int>>("array._take_over", x, offsets, edge), IsOkAndHolds(ElementsAre(1, std::nullopt, 3, 2, 5, 6, 7, std::nullopt))); } TEST(ArrayOpsTest, TestArrayTakeOverSplitPoints) { auto x = CreateDenseArray<int>({1, 2, 3, std::nullopt, 5, 6, 7, 8}); auto offsets = CreateDenseArray<int64_t>({0, 2, 1, 0, 1, 1, 0, std::nullopt}); auto splits = CreateDenseArray<int64_t>({0, 3, 3, 5, 7, 8}); ASSERT_OK_AND_ASSIGN(auto edge, DenseArrayEdge::FromSplitPoints(splits)); EXPECT_THAT( InvokeOperator<DenseArray<int>>("array._take_over", x, offsets, edge), IsOkAndHolds(ElementsAre(1, 3, 2, std::nullopt, 5, 7, 6, std::nullopt))); } TEST(ArrayOpsTest, TestArrayTakeMapping) { auto x = CreateDenseArray<int>({1, 2, 3, std::nullopt, 5, 6, 7, 8}); auto offsets = CreateDenseArray<int64_t>({0, 2, 1, 0, 1, 1, 0, std::nullopt}); auto mapping = CreateDenseArray<int64_t>({0, 1, 1, 1, 1, 0, std::nullopt, 0}); ASSERT_OK_AND_ASSIGN(auto edge, DenseArrayEdge::FromMapping(mapping, 3)); EXPECT_THAT( InvokeOperator<DenseArray<int>>("array._take_over", x, offsets, edge), IsOkAndHolds(ElementsAre(1, std::nullopt, 3, 2, 3, 6, std::nullopt, std::nullopt))); } TEST(ArrayOpsTest, TestArrayTakeOverErrors) { auto x = CreateDenseArray<int>({1, 2, 3, std::nullopt, 5, 6, 7, 8}); auto offsets = CreateDenseArray<int64_t>({0, 2, 1, 0, 1, 1, 0, std::nullopt}); auto splits = CreateDenseArray<int64_t>({0, 1}); ASSERT_OK_AND_ASSIGN(auto edge, DenseArrayEdge::FromSplitPoints(splits)); EXPECT_THAT( InvokeOperator<DenseArray<int>>("array._take_over", x, offsets, edge), StatusIs(absl::StatusCode::kInvalidArgument, ::testing::HasSubstr("argument sizes mismatch"))); x = CreateDenseArray<int>({1}); EXPECT_THAT( InvokeOperator<DenseArray<int>>("array._take_over", x, offsets, edge), StatusIs(absl::StatusCode::kInvalidArgument, ::testing::HasSubstr("argument sizes mismatch"))); } TEST(ArrayOpsTest, TestArrayTakeOverOver) { auto x = CreateDenseArray<int>({1, 2, 3, std::nullopt, 5, 6, 7, 8}); auto offsets = CreateDenseArray<int64_t>({0, 3, 1, 3, 1, std::nullopt}); auto x_splits = CreateDenseArray<int64_t>({0, 4, 8}); ASSERT_OK_AND_ASSIGN(auto x_edge, DenseArrayEdge::FromSplitPoints(x_splits)); auto offsets_splits = CreateDenseArray<int64_t>({0, 3, 6}); ASSERT_OK_AND_ASSIGN(auto offsets_edge, DenseArrayEdge::FromSplitPoints(offsets_splits)); EXPECT_THAT( InvokeOperator<DenseArray<int>>("array._take_over_over", x, offsets, x_edge, offsets_edge), IsOkAndHolds(ElementsAre(1, std::nullopt, 2, 8, 6, std::nullopt))); EXPECT_THAT( InvokeOperator<DenseArray<int>>("array._take_over_over", x, offsets, x_edge, x_edge), StatusIs(absl::StatusCode::kInvalidArgument, ::testing::HasSubstr("argument sizes mismatch: (8, 6)"))); } TEST(ArrayOpsTest, Slice) { auto x = CreateDenseArray<int>({1, 2, 3, std::nullopt, 5, 6, 7, 8}); ASSERT_OK_AND_ASSIGN(DenseArray<int> sliced, InvokeOperator<DenseArray<int>>("array.slice", x, int64_t{3}, int64_t{4})); EXPECT_THAT(sliced, ElementsAre(std::nullopt, 5, 6, 7)); EXPECT_EQ(sliced.bitmap_bit_offset, 0); EXPECT_THAT(InvokeOperator<DenseArray<int>>("array.slice", x, int64_t{5}, int64_t{-1}), IsOkAndHolds(ElementsAre(6, 7, 8))); EXPECT_THAT(InvokeOperator<DenseArray<int>>("array.slice", x, int64_t{-3}, int64_t{4}), StatusIs(absl::StatusCode::kInvalidArgument, ::testing::HasSubstr( "expected `offset` in [0, 8], but got -3"))); EXPECT_THAT( InvokeOperator<DenseArray<int>>("array.slice", x, int64_t{3}, int64_t{8}), StatusIs(absl::StatusCode::kInvalidArgument, ::testing::HasSubstr("expected `size` in [0, 5], but got 8"))); } TEST(ArrayOpsTest, Concat) { auto x = CreateDenseArray<int>({1, 2, 3}); auto y = CreateDenseArray<int>({std::nullopt, 4}); auto z = CreateDenseArray<int>({}); EXPECT_THAT(InvokeOperator<DenseArray<int>>("array.concat", x, x), IsOkAndHolds(ElementsAre(1, 2, 3, 1, 2, 3))); EXPECT_THAT(InvokeOperator<DenseArray<int>>("array.concat", x, y), IsOkAndHolds(ElementsAre(1, 2, 3, std::nullopt, 4))); EXPECT_THAT(InvokeOperator<DenseArray<int>>("array.concat", y, y), IsOkAndHolds(ElementsAre(std::nullopt, 4, std::nullopt, 4))); EXPECT_THAT(InvokeOperator<DenseArray<int>>("array.concat", x, z), IsOkAndHolds(ElementsAre(1, 2, 3))); EXPECT_THAT(InvokeOperator<DenseArray<int>>("array.concat", z, y), IsOkAndHolds(ElementsAre(std::nullopt, 4))); } } }
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/qexpr/operators/dense_array/array_ops.cc
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/qexpr/operators/dense_array/array_ops_test.cc
1ca990dbeca224035efdabffecc7f3738df6b52c
80d3466f-ab27-4cba-9f89-e18caad37262
cpp
google/arolla
factory_ops
arolla/qexpr/operators/dense_array/factory_ops.cc
arolla/qexpr/operators/dense_array/factory_ops_test.cc
#include "arolla/qexpr/operators/dense_array/factory_ops.h" #include <cstddef> #include <cstdint> #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/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/qexpr/bound_operators.h" #include "arolla/qexpr/eval_context.h" #include "arolla/qexpr/operators.h" #include "arolla/qexpr/qexpr_operator_signature.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/text.h" #include "arolla/util/unit.h" #include "arolla/util/status_macros_backport.h" namespace arolla { namespace { template <typename T> class MakeDenseArrayOperator : public QExprOperator { public: explicit MakeDenseArrayOperator(size_t tuple_size) : QExprOperator(QExprOperatorSignature::Get( std::vector<QTypePtr>(tuple_size, ::arolla::GetQType<T>()), GetDenseArrayQType<strip_optional_t<T>>())) {} private: absl::StatusOr<std::unique_ptr<BoundOperator>> DoBind( absl::Span<const TypedSlot> input_slots, TypedSlot output_slot) const final { return MakeBoundOperator( [input_slots = std::vector<TypedSlot>(input_slots.begin(), input_slots.end()), output_slot](EvaluationContext* ctx, FramePtr frame) { DenseArrayBuilder<strip_optional_t<T>> builder( input_slots.size(), &ctx->buffer_factory()); for (size_t i = 0; i < input_slots.size(); ++i) { const T& value = frame.Get(input_slots[i].UnsafeToSlot<T>()); if constexpr (is_optional_v<T>) { if (value.present) { builder.Add(i, value.value); } } else { builder.Add(i, value); } } frame.Set(output_slot.UnsafeToSlot<DenseArray<strip_optional_t<T>>>(), std::move(builder).Build()); }); } }; absl::StatusOr<OperatorPtr> ConstructMakeDenseArrayOperator(QTypePtr value_type, size_t size) { #define CONSTRUCT_OPERATOR_IF(t) \ if (value_type == GetQType<t>()) { \ return OperatorPtr(std::make_shared<MakeDenseArrayOperator<t>>(size)); \ } CONSTRUCT_OPERATOR_IF(OptionalValue<Unit>); CONSTRUCT_OPERATOR_IF(OptionalValue<bool>); CONSTRUCT_OPERATOR_IF(OptionalValue<int32_t>); CONSTRUCT_OPERATOR_IF(OptionalValue<int64_t>); CONSTRUCT_OPERATOR_IF(OptionalValue<uint64_t>); CONSTRUCT_OPERATOR_IF(OptionalValue<float>); CONSTRUCT_OPERATOR_IF(OptionalValue<double>); CONSTRUCT_OPERATOR_IF(OptionalValue<Bytes>); CONSTRUCT_OPERATOR_IF(OptionalValue<Text>); #undef CONSTRUCT_OPERATOR_IF return absl::UnimplementedError( absl::StrFormat("array.make_dense_array operator is not implemented " "for %s arguments", value_type->name())); } } absl::StatusOr<OperatorPtr> MakeDenseArrayOperatorFamily::DoGetOperator( absl::Span<const QTypePtr> input_types, QTypePtr output_type) const { QTypePtr value_qtype = DecayDerivedQType(output_type)->value_qtype(); if (value_qtype == nullptr) { return absl::InvalidArgumentError(absl::StrFormat( "unexpected return type for array.make_dense_array operator: %s", output_type->name())); } ASSIGN_OR_RETURN(auto arg_type, ToOptionalQType(value_qtype)); return ConstructMakeDenseArrayOperator(arg_type, input_types.size()); } }
#include <cstdint> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "absl/status/status_matchers.h" #include "arolla/dense_array/dense_array.h" #include "arolla/dense_array/qtype/types.h" #include "arolla/memory/buffer.h" #include "arolla/qexpr/operators.h" #include "arolla/util/unit.h" namespace arolla { namespace { using ::absl_testing::IsOkAndHolds; using ::absl_testing::StatusIs; using ::testing::ElementsAre; using ::testing::Eq; TEST(FactoryOpsTest, DenseArrayShapeOfOp) { EXPECT_THAT(InvokeOperator<DenseArrayShape>("core._array_shape_of", DenseArray<Unit>{VoidBuffer(3)}), IsOkAndHolds(DenseArrayShape{3})); } TEST(FactoryOpsTest, DenseArrayConstWithShapeOp) { ASSERT_OK_AND_ASSIGN(auto res, InvokeOperator<DenseArray<int>>( "core.const_with_shape._array_shape", DenseArrayShape{3}, 57)); EXPECT_THAT(res, ElementsAre(57, 57, 57)); } TEST(FactoryOpsTest, ArrayShapeSize_DenseArray) { EXPECT_THAT( InvokeOperator<int64_t>("array.array_shape_size", DenseArrayShape{3}), IsOkAndHolds(Eq(3))); } TEST(FactoryOpsTest, ResizeArrayShape_DenseArray) { EXPECT_THAT(InvokeOperator<DenseArrayShape>("array.resize_array_shape", DenseArrayShape{3}, int64_t{5}), IsOkAndHolds(DenseArrayShape{5})); EXPECT_THAT(InvokeOperator<DenseArrayShape>("array.resize_array_shape", DenseArrayShape{3}, int64_t{-1}), StatusIs(absl::StatusCode::kInvalidArgument, "bad size: -1")); } } }
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/qexpr/operators/dense_array/factory_ops.cc
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/qexpr/operators/dense_array/factory_ops_test.cc
1ca990dbeca224035efdabffecc7f3738df6b52c
4cd0009a-37ed-49dc-a958-326dbdc4603e
cpp
google/arolla
seq_map_operator
arolla/qexpr/eval_extensions/seq_map_operator.cc
arolla/qexpr/eval_extensions/seq_map_operator_test.cc
#include "arolla/qexpr/eval_extensions/seq_map_operator.h" #include <cstddef> #include <memory> #include <optional> #include <string> #include <utility> #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/strings/str_join.h" #include "absl/types/span.h" #include "arolla/expr/basic_expr_operator.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/eval/extensions.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/registered_expr_operator.h" #include "arolla/expr/seq_map_expr_operator.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/qtype/typed_value.h" #include "arolla/sequence/mutable_sequence.h" #include "arolla/sequence/sequence.h" #include "arolla/sequence/sequence_qtype.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 { absl::StatusOr<ExprNodePtr> SeqMapOperatorTransformation( const DynamicEvaluationEngineOptions&, ExprNodePtr node) { ASSIGN_OR_RETURN(auto seq_map_op, DecayRegisteredOperator(node->op())); if (seq_map_op == nullptr || typeid(*seq_map_op) != typeid(SeqMapOperator)) { return node; } const auto& node_deps = node->node_deps(); if (node_deps.size() < 2) { return absl::FailedPreconditionError(absl::StrFormat( "unexpected number of arguments: expected at least two, got %d", node_deps.size())); } const auto& op_node = node_deps[0]; if (op_node->qtype() == nullptr) { return absl::FailedPreconditionError("missing node_deps[0].qtype"); } if (op_node->qtype() != GetQType<ExprOperatorPtr>()) { return absl::FailedPreconditionError(absl::StrFormat( "unexpected node_deps[0].qtype: expected %s, got %s", GetQType<ExprOperatorPtr>()->name(), op_node->qtype()->name())); } const auto& op_qvalue = op_node->qvalue(); if (!op_qvalue.has_value()) { return absl::FailedPreconditionError("missing node_deps[0].literal_value"); } DCHECK(op_qvalue->GetType() == GetQType<ExprOperatorPtr>()); const auto& op = op_qvalue->UnsafeAs<ExprOperatorPtr>(); return MakeOpNode( std::make_shared<PackedSeqMapOperator>(op), std::vector<ExprNodePtr>(node_deps.begin() + 1, node_deps.end())); } std::optional<absl::Status> CompilePackedSeqMapOperator( const CompileOperatorFnArgs& args) { const auto* map_op = dynamic_cast<const PackedSeqMapOperator*>(args.op.get()); if (map_op == nullptr) { return std::nullopt; } if (args.input_slots.empty()) { return absl::FailedPreconditionError( absl::StrFormat("expected at least one input slot, got none")); } if (!IsSequenceQType(args.output_slot.GetType())) { return absl::FailedPreconditionError( absl::StrFormat("expected a sequence type, got output_qtype = %s", args.output_slot.GetType()->name())); } std::vector<QTypePtr> value_qtypes; value_qtypes.reserve(args.input_slots.size()); for (size_t i = 0; i < args.input_slots.size(); ++i) { value_qtypes.push_back(args.input_slots[i].GetType()->value_qtype()); DCHECK(value_qtypes.back() != nullptr); } std::vector<TypedSlot> mapper_arg_slots; mapper_arg_slots.reserve(args.input_slots.size()); for (size_t i = 0; i < args.input_slots.size(); ++i) { mapper_arg_slots.push_back( AddSlot(value_qtypes[i], args.executable_builder->layout_builder())); } auto mapper_output_slot = AddSlot(args.output_slot.GetType()->value_qtype(), args.executable_builder->layout_builder()); DynamicEvaluationEngineOptions subexpression_options(args.options); subexpression_options.enabled_preparation_stages = DynamicEvaluationEngineOptions::PreparationStage::kAll; ASSIGN_OR_RETURN( std::shared_ptr<BoundExpr> mapper_bound_expr, CompileAndBindExprOperator( subexpression_options, args.executable_builder->layout_builder(), map_op->op(), mapper_arg_slots, mapper_output_slot)); std::string init_op_description; std::string eval_op_description; if (args.options.collect_op_descriptions) { auto dynamic_bound_expr = dynamic_cast<const DynamicBoundExpr*>(mapper_bound_expr.get()); if (dynamic_bound_expr == nullptr) { return absl::InternalError("expected DynamicBoundExpr"); } auto init_op_name = absl::StrFormat( "%s:init{%s}", map_op->display_name(), absl::StrJoin(dynamic_bound_expr->init_op_descriptions(), "; ")); init_op_description = FormatOperatorCall(init_op_name, {}, {}); auto eval_op_name = absl::StrFormat( "%s:eval{%s}", map_op->display_name(), absl::StrJoin(dynamic_bound_expr->eval_op_descriptions(), "; ")); eval_op_description = FormatOperatorCall(eval_op_name, args.input_slots, {args.output_slot}); } args.executable_builder->AddInitOp( MakeBoundOperator( [mapper_bound_expr](EvaluationContext* ctx, FramePtr frame) { mapper_bound_expr->InitializeLiterals(ctx, frame); }), init_op_description); args.executable_builder->AddEvalOp( MakeBoundOperator([input_slots = std::vector(args.input_slots.begin(), args.input_slots.end()), output_slot = args.output_slot, mapper_bound_expr, mapper_arg_slots, mapper_output_slot]( EvaluationContext* ctx, FramePtr frame) { std::optional<size_t> seq_size = std::nullopt; for (size_t i = 0; i < input_slots.size(); ++i) { const auto& cur_slot = input_slots[i]; const auto& seq = frame.Get(cur_slot.UnsafeToSlot<Sequence>()); if (seq_size.has_value() && *seq_size != seq.size()) { ctx->set_status(absl::InvalidArgumentError(absl::StrFormat( "expected all sequences to have the same length, got %d and %d", *seq_size, seq.size()))); return; } seq_size = seq.size(); } const size_t output_value_size = mapper_output_slot.GetType()->type_layout().AllocSize(); ASSIGN_OR_RETURN( auto mutable_sequence, MutableSequence::Make(mapper_output_slot.GetType(), *seq_size), ctx->set_status(std::move(_))); for (size_t i = 0; i < seq_size && ctx->status().ok(); ++i) { for (size_t arg_id = 0; arg_id < input_slots.size(); ++arg_id) { const auto& cur_slot = input_slots[arg_id]; const auto& seq = frame.Get(cur_slot.UnsafeToSlot<Sequence>()); seq.GetRef(i) .CopyToSlot(mapper_arg_slots[arg_id], frame) .IgnoreError(); } mapper_bound_expr->Execute(ctx, frame); mapper_output_slot.GetType()->UnsafeCopy( frame.GetRawPointer(mapper_output_slot.byte_offset()), mutable_sequence.RawAt(i, output_value_size)); } frame.Set(output_slot.UnsafeToSlot<Sequence>(), std::move(mutable_sequence).Finish()); }), eval_op_description, "seq.map"); return absl::OkStatus(); } } PackedSeqMapOperator::PackedSeqMapOperator(ExprOperatorPtr op) : ExprOperatorWithFixedSignature( absl::StrFormat("packed_seq_map[%s]", op->display_name()), ExprOperatorSignature::MakeVariadicArgs(), "(internal operator) packed seq.map", FingerprintHasher("arolla::expr::eval_internal::PackedSeqMapOperator") .Combine(op->fingerprint()) .Finish()), op_(std::move(op)) {} absl::StatusOr<ExprAttributes> PackedSeqMapOperator::InferAttributes( absl::Span<const ExprAttributes> inputs) const { std::vector<ExprAttributes> new_inputs; new_inputs.reserve(inputs.size() + 1); new_inputs.emplace_back(GetQType<ExprOperatorPtr>(), TypedValue::FromValue(op_)); new_inputs.insert(new_inputs.end(), inputs.begin(), inputs.end()); return SeqMapOperator::Make()->InferAttributes(new_inputs); } AROLLA_INITIALIZER( .reverse_deps = { ::arolla::initializer_dep::kOperators, ::arolla::initializer_dep::kQExprOperators, }, .init_fn = [] { CompilerExtensionRegistry::GetInstance().RegisterNodeTransformationFn( SeqMapOperatorTransformation); CompilerExtensionRegistry::GetInstance().RegisterCompileOperatorFn( CompilePackedSeqMapOperator); }) }
#include "arolla/qexpr/eval_extensions/seq_map_operator.h" #include <cstdint> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status_matchers.h" #include "arolla/expr/annotation_expr_operators.h" #include "arolla/expr/eval/eval.h" #include "arolla/expr/eval/prepare_expression.h" #include "arolla/expr/eval/test_utils.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/registered_expr_operator.h" #include "arolla/expr/testing/testing.h" #include "arolla/memory/frame.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/typed_slot.h" #include "arolla/sequence/sequence_qtype.h" namespace arolla::expr::eval_internal { namespace { using ::absl_testing::IsOkAndHolds; using ::arolla::testing::EqualsExpr; using ::testing::ElementsAre; using ::testing::Eq; using ::testing::NotNull; TEST(SeqMapOperatorTest, SeqMapOperatorTransformation) { ASSERT_OK_AND_ASSIGN(ExprOperatorPtr add_operator, LookupOperator("math.add")); ASSERT_OK_AND_ASSIGN(auto expr, CallOp("seq.map", {Literal(add_operator), Leaf("xs"), Leaf("ys")})); EXPECT_THAT(expr->qtype(), Eq(nullptr)); QTypePtr seq_i32 = GetSequenceQType(GetQType<int32_t>()); ASSERT_OK_AND_ASSIGN( auto prepared_expr, PrepareExpression(expr, {{"xs", seq_i32}, {"ys", seq_i32}}, DynamicEvaluationEngineOptions{})); EXPECT_THAT(prepared_expr->qtype(), Eq(seq_i32)); auto packed_op = dynamic_cast<const PackedSeqMapOperator*>(prepared_expr->op().get()); ASSERT_THAT(packed_op, NotNull()); EXPECT_THAT(packed_op->op()->display_name(), Eq("math.add")); EXPECT_THAT(packed_op->display_name(), Eq("packed_seq_map[math.add]")); EXPECT_THAT(prepared_expr->node_deps(), ElementsAre( EqualsExpr(CallOp(QTypeAnnotation::Make(), {Leaf("xs"), Literal(seq_i32)})), EqualsExpr(CallOp(QTypeAnnotation::Make(), {Leaf("ys"), Literal(seq_i32)})))); } TEST(SeqMapOperatorTest, CompilePackedSeqMapOperator) { ASSERT_OK_AND_ASSIGN( ExprOperatorPtr x_plus_y_mul_2, MakeLambdaOperator( "x_plus_y_mul_2", ExprOperatorSignature::Make("x, y"), CallOp("math.multiply", {CallOp("math.add", {Placeholder("x"), Placeholder("y")}), Literal(int32_t{2})}))); ASSERT_OK_AND_ASSIGN(auto expr, CallOp("seq.map", {Literal(x_plus_y_mul_2), Leaf("xs"), Leaf("ys")})); QTypePtr seq_i32 = GetSequenceQType(GetQType<int32_t>()); FrameLayout::Builder layout_builder; auto xs_slot = AddSlot(seq_i32, &layout_builder); auto ys_slot = AddSlot(seq_i32, &layout_builder); DynamicEvaluationEngineOptions options{.collect_op_descriptions = true}; EXPECT_THAT( CompileAndBindForDynamicEvaluation(options, &layout_builder, expr, {{"xs", xs_slot}, {"ys", ys_slot}}), IsOkAndHolds(AllOf( InitOperationsAre("packed_seq_map[x_plus_y_mul_2]:init{" "INT32 [0x70] = 2" "}()"), EvalOperationsAre( "SEQUENCE[INT32] [0x40] = packed_seq_map[x_plus_y_mul_2]:eval{" "INT32 [0x6C] = math.add(INT32 [0x60], INT32 [0x64]); " "INT32 [0x68] = math.multiply(INT32 [0x6C], INT32 [0x70])" "}(SEQUENCE[INT32] [0x00], SEQUENCE[INT32] [0x20])")))); } } }
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/qexpr/eval_extensions/seq_map_operator.cc
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/qexpr/eval_extensions/seq_map_operator_test.cc
1ca990dbeca224035efdabffecc7f3738df6b52c
7a064a2f-a830-495c-aa86-9ae1e2bd2120
cpp
google/arolla
seq_reduce_operator
arolla/qexpr/eval_extensions/seq_reduce_operator.cc
arolla/qexpr/eval_extensions/seq_reduce_operator_test.cc
#include "arolla/qexpr/eval_extensions/seq_reduce_operator.h" #include <cstddef> #include <memory> #include <optional> #include <string> #include <utility> #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/strings/str_join.h" #include "absl/types/span.h" #include "arolla/expr/basic_expr_operator.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/eval/extensions.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/registered_expr_operator.h" #include "arolla/expr/seq_reduce_expr_operator.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_traits.h" #include "arolla/qtype/typed_slot.h" #include "arolla/qtype/typed_value.h" #include "arolla/sequence/sequence.h" #include "arolla/sequence/sequence_qtype.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 { absl::StatusOr<ExprNodePtr> SeqReduceOperatorTransformation( const DynamicEvaluationEngineOptions&, ExprNodePtr node) { ASSIGN_OR_RETURN(auto seq_reduce_op, DecayRegisteredOperator(node->op())); if (seq_reduce_op == nullptr || typeid(*seq_reduce_op) != typeid(SeqReduceOperator)) { return node; } const auto& node_deps = node->node_deps(); if (node_deps.size() != 3) { return absl::FailedPreconditionError( absl::StrFormat("unexpected number of arguments: expected 3, got %d", node_deps.size())); } const auto& op_node = node_deps[0]; if (op_node->qtype() == nullptr) { return absl::FailedPreconditionError("missing node_deps[0].qtype"); } if (op_node->qtype() != GetQType<ExprOperatorPtr>()) { return absl::FailedPreconditionError(absl::StrFormat( "unexpected node_deps[0].qtype: expected %s, got %s", GetQType<ExprOperatorPtr>()->name(), op_node->qtype()->name())); } const auto& op_qvalue = op_node->qvalue(); if (!op_qvalue.has_value()) { return absl::FailedPreconditionError("missing node_deps[0].literal_value"); } DCHECK(op_qvalue->GetType() == GetQType<ExprOperatorPtr>()); const auto& op = op_qvalue->UnsafeAs<ExprOperatorPtr>(); return MakeOpNode( std::make_shared<PackedSeqReduceOperator>(op), std::vector<ExprNodePtr>(node_deps.begin() + 1, node_deps.end())); } std::optional<absl::Status> CompilePackedSeqReduceOperator( const CompileOperatorFnArgs& args) { const auto* reduce_op = dynamic_cast<const PackedSeqReduceOperator*>(args.op.get()); if (reduce_op == nullptr) { return std::nullopt; } if (args.input_slots.size() != 2) { return absl::FailedPreconditionError( absl::StrFormat("unexpected number of input slots: expected 2, got %d", args.input_slots.size())); } const auto& seq_slot = args.input_slots[0]; const auto& initial_slot = args.input_slots[1]; if (!IsSequenceQType(seq_slot.GetType())) { return absl::FailedPreconditionError( absl::StrFormat("expected a sequence type, got seq_qtype = %s", seq_slot.GetType()->name())); } const auto value_qtype = seq_slot.GetType()->value_qtype(); DCHECK(value_qtype != nullptr); const auto output_qtype = args.output_slot.GetType(); if (initial_slot.GetType() != output_qtype) { return absl::FailedPreconditionError( absl::StrFormat("expected initial_qtype == output_qtype: %s != %s", initial_slot.GetType()->name(), output_qtype->name())); } auto reducer_arg_1_slot = AddSlot(output_qtype, args.executable_builder->layout_builder()); auto reducer_arg_2_slot = AddSlot(value_qtype, args.executable_builder->layout_builder()); DynamicEvaluationEngineOptions subexpression_options(args.options); subexpression_options.enabled_preparation_stages = DynamicEvaluationEngineOptions::PreparationStage::kAll; ASSIGN_OR_RETURN( std::shared_ptr<BoundExpr> reducer_bound_expr, CompileAndBindExprOperator( subexpression_options, args.executable_builder->layout_builder(), reduce_op->op(), {reducer_arg_1_slot, reducer_arg_2_slot}, args.output_slot)); std::string init_op_description; std::string eval_op_description; if (args.options.collect_op_descriptions) { auto dynamic_bound_expr = dynamic_cast<const DynamicBoundExpr*>(reducer_bound_expr.get()); if (dynamic_bound_expr == nullptr) { return absl::InternalError("expected DynamicBoundExpr"); } auto init_op_name = absl::StrFormat( "%s:init{%s}", reduce_op->display_name(), absl::StrJoin(dynamic_bound_expr->init_op_descriptions(), "; ")); init_op_description = FormatOperatorCall(init_op_name, {}, {}); auto eval_op_name = absl::StrFormat( "%s:eval{%s}", reduce_op->display_name(), absl::StrJoin(dynamic_bound_expr->eval_op_descriptions(), "; ")); eval_op_description = FormatOperatorCall(eval_op_name, args.input_slots, {args.output_slot}); } args.executable_builder->AddInitOp( MakeBoundOperator( [reducer_bound_expr](EvaluationContext* ctx, FramePtr frame) { reducer_bound_expr->InitializeLiterals(ctx, frame); }), init_op_description); args.executable_builder->AddEvalOp( MakeBoundOperator( [reducer_bound_expr, initial_slot, seq_slot, output_slot = args.output_slot, reducer_arg_1_slot, reducer_arg_2_slot](EvaluationContext* ctx, FramePtr frame) { const auto& seq = frame.Get(seq_slot.UnsafeToSlot<Sequence>()); const auto* value_qtype = seq.value_qtype(); const size_t seq_size = seq.size(); const size_t value_size = value_qtype->type_layout().AllocSize(); initial_slot.CopyTo(frame, output_slot, frame); for (size_t i = 0; i < seq_size && ctx->status().ok(); ++i) { output_slot.CopyTo(frame, reducer_arg_1_slot, frame); value_qtype->UnsafeCopy( seq.RawAt(i, value_size), frame.GetRawPointer(reducer_arg_2_slot.byte_offset())); reducer_bound_expr->Execute(ctx, frame); } }), eval_op_description, "seq.reduce"); return absl::OkStatus(); } } PackedSeqReduceOperator::PackedSeqReduceOperator(ExprOperatorPtr op) : ExprOperatorWithFixedSignature( absl::StrFormat("packed_seq_reduce[%s]", op->display_name()), ExprOperatorSignature{{"seq"}, {"initial"}}, "(internal operator) packed seq.reduce", FingerprintHasher( "arolla::expr::eval_internal::PackedSeqReduceOperator") .Combine(op->fingerprint()) .Finish()), op_(std::move(op)) {} absl::StatusOr<ExprAttributes> PackedSeqReduceOperator::InferAttributes( absl::Span<const ExprAttributes> inputs) const { std::vector<ExprAttributes> new_inputs; new_inputs.reserve(inputs.size() + 1); new_inputs.emplace_back(GetQType<ExprOperatorPtr>(), TypedValue::FromValue(op_)); new_inputs.insert(new_inputs.end(), inputs.begin(), inputs.end()); return SeqReduceOperator::Make()->InferAttributes(new_inputs); } AROLLA_INITIALIZER( .reverse_deps = { ::arolla::initializer_dep::kOperators, ::arolla::initializer_dep::kQExprOperators, }, .init_fn = [] { CompilerExtensionRegistry::GetInstance().RegisterNodeTransformationFn( SeqReduceOperatorTransformation); CompilerExtensionRegistry::GetInstance().RegisterCompileOperatorFn( CompilePackedSeqReduceOperator); }) }
#include "arolla/qexpr/eval_extensions/seq_reduce_operator.h" #include <cstdint> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status_matchers.h" #include "arolla/expr/annotation_expr_operators.h" #include "arolla/expr/eval/eval.h" #include "arolla/expr/eval/prepare_expression.h" #include "arolla/expr/eval/test_utils.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/registered_expr_operator.h" #include "arolla/expr/testing/testing.h" #include "arolla/memory/frame.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/typed_slot.h" #include "arolla/sequence/sequence_qtype.h" namespace arolla::expr::eval_internal { namespace { using ::absl_testing::IsOkAndHolds; using ::arolla::testing::EqualsExpr; using ::testing::ElementsAre; using ::testing::Eq; using ::testing::NotNull; TEST(SeqReduceOperatorTest, SeqMapOperatorTransformation) { ASSERT_OK_AND_ASSIGN(ExprOperatorPtr add_operator, LookupOperator("math.add")); ASSERT_OK_AND_ASSIGN(auto expr, CallOp("seq.reduce", {Literal(add_operator), Leaf("xs"), Literal(int32_t{0})})); EXPECT_THAT(expr->qtype(), Eq(GetQType<int32_t>())); QTypePtr seq_i32 = GetSequenceQType(GetQType<int32_t>()); ASSERT_OK_AND_ASSIGN(auto prepared_expr, PrepareExpression(expr, {{"xs", seq_i32}}, DynamicEvaluationEngineOptions{})); EXPECT_THAT(prepared_expr->qtype(), Eq(GetQType<int32_t>())); auto packed_op = dynamic_cast<const PackedSeqReduceOperator*>(prepared_expr->op().get()); ASSERT_THAT(packed_op, NotNull()); EXPECT_THAT(packed_op->op()->display_name(), Eq("math.add")); EXPECT_THAT(packed_op->display_name(), Eq("packed_seq_reduce[math.add]")); EXPECT_THAT(prepared_expr->node_deps(), ElementsAre( EqualsExpr(CallOp(QTypeAnnotation::Make(), {Leaf("xs"), Literal(seq_i32)})), EqualsExpr(Literal(int32_t{0})))); } TEST(SeqReduceOperatorTest, CompilePackedSeqReduceOperator) { ASSERT_OK_AND_ASSIGN( ExprOperatorPtr x_plus_y_mul_2, MakeLambdaOperator( "x_plus_y_mul_2", ExprOperatorSignature::Make("x, y"), CallOp("math.multiply", {CallOp("math.add", {Placeholder("x"), Placeholder("y")}), Literal(int32_t{2})}))); ASSERT_OK_AND_ASSIGN( auto expr, CallOp("seq.reduce", {Literal(x_plus_y_mul_2), Leaf("xs"), Literal(int32_t{0})})); QTypePtr seq_i32 = GetSequenceQType(GetQType<int32_t>()); FrameLayout::Builder layout_builder; auto xs_slot = AddSlot(seq_i32, &layout_builder); DynamicEvaluationEngineOptions options{.collect_op_descriptions = true}; EXPECT_THAT( CompileAndBindForDynamicEvaluation(options, &layout_builder, expr, {{"xs", xs_slot}}), IsOkAndHolds(AllOf( InitOperationsAre("packed_seq_reduce[x_plus_y_mul_2]:init{" "INT32 [0x34] = 2" "}()", "INT32 [0x24] = 0"), EvalOperationsAre( "INT32 [0x20] = packed_seq_reduce[x_plus_y_mul_2]:eval{" "INT32 [0x30] = math.add(INT32 [0x28], INT32 [0x2C]); " "INT32 [0x20] = math.multiply(INT32 [0x30], INT32 [0x34])" "}(SEQUENCE[INT32] [0x00], INT32 [0x24])")))); } } }
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/qexpr/eval_extensions/seq_reduce_operator.cc
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/qexpr/eval_extensions/seq_reduce_operator_test.cc
1ca990dbeca224035efdabffecc7f3738df6b52c
9c218c4f-2718-42f5-b1c0-20cd2d9d0113
cpp
google/arolla
mutable_sequence
arolla/sequence/mutable_sequence.cc
arolla/sequence/mutable_sequence_test.cc
#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 = 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" namespace arolla { namespace { TEST(MutableSequenceTest, DefaultConstructor) { MutableSequence seq; EXPECT_EQ(seq.value_qtype(), GetNothingQType()); EXPECT_EQ(seq.size(), 0); EXPECT_EQ(seq.RawData(), nullptr); } TEST(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(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(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(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(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(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(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(MutableSequenceTest, ConstructorDestructor) { { ASSERT_OK_AND_ASSIGN(auto seq, MutableSequence::Make(GetQType<CountedType>(), 100)); EXPECT_EQ(CountedType::counter, 100); } EXPECT_EQ(CountedType::counter, 0); } TEST(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 TEST(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(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(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(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(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(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 } }
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/sequence/mutable_sequence.cc
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/sequence/mutable_sequence_test.cc
1ca990dbeca224035efdabffecc7f3738df6b52c
5e3d8d4e-de5e-4935-8149-136d49c03c8a
cpp
google/arolla
sequence
arolla/sequence/sequence.cc
arolla/sequence/sequence_test.cc
#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/repr.h" #include "arolla/util/testing/repr_token_eq.h" #include "arolla/util/unit.h" namespace arolla { namespace { using ::arolla::testing::ReprTokenEq; TEST(SequenceTest, DefaultConstructor) { Sequence seq; EXPECT_EQ(seq.value_qtype(), GetNothingQType()); EXPECT_EQ(seq.size(), 0); EXPECT_EQ(seq.RawData(), nullptr); } TEST(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(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(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(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(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 TEST(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(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(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(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(SequenceTest, ReprEmpty) { EXPECT_THAT(GenReprToken(Sequence()), ReprTokenEq("sequence(value_qtype=NOTHING)")); } TEST(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(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(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"; } } } } } }
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/sequence/sequence.cc
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/sequence/sequence_test.cc
1ca990dbeca224035efdabffecc7f3738df6b52c
6c343a4e-4b19-467e-921b-27a1d42e21d4
cpp
google/arolla
sequence_qtype
arolla/sequence/sequence_qtype.cc
arolla/sequence/sequence_qtype_test.cc
#include "arolla/sequence/sequence_qtype.h" #include <memory> #include <string> #include "absl/base/no_destructor.h" #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/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 absl::NoDestructor<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/testing/repr_token_eq.h" namespace arolla { namespace { using ::arolla::testing::ReprTokenEq; TEST(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(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(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)")); } } }
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/sequence/sequence_qtype.cc
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/sequence/sequence_qtype_test.cc
1ca990dbeca224035efdabffecc7f3738df6b52c
96433603-bbb8-48f6-b6cb-ac5eef4b8ec9
cpp
google/arolla
jagged_shape
arolla/jagged_shape/dense_array/jagged_shape.cc
arolla/jagged_shape/jagged_shape_test.cc
#include "arolla/jagged_shape/dense_array/jagged_shape.h" #include <sstream> #include <utility> #include "arolla/jagged_shape/util/repr.h" #include "arolla/util/repr.h" #include "arolla/util/string.h" namespace arolla { ReprToken ReprTraits<JaggedDenseArrayShape>::operator()( const JaggedDenseArrayShape& value) const { std::ostringstream result; result << "JaggedShape("; bool first = true; for (const auto& edge : value.edges()) { result << NonFirstComma(first) << CompactSplitPointsAsSizesRepr(edge.edge_values().values.span(), 3); } result << ")"; return ReprToken{std::move(result).str()}; } }
#include "arolla/jagged_shape/jagged_shape.h" #include <algorithm> #include <cmath> #include <cstdint> #include <optional> #include <string> #include <type_traits> #include <utility> #include <vector> #include "benchmark/benchmark.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "absl/status/status_matchers.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/array/array.h" #include "arolla/array/edge.h" #include "arolla/dense_array/dense_array.h" #include "arolla/dense_array/edge.h" #include "arolla/jagged_shape/array/jagged_shape.h" #include "arolla/jagged_shape/dense_array/jagged_shape.h" #include "arolla/memory/buffer.h" #include "arolla/memory/optional_value.h" #include "arolla/memory/raw_buffer_factory.h" #include "arolla/util/fingerprint.h" #include "arolla/util/repr.h" #include "arolla/util/testing/repr_token_eq.h" using ::absl_testing::StatusIs; using ::arolla::testing::ReprTokenEq; using ::testing::ElementsAre; namespace arolla { namespace { class JaggedArrayShapeHelper { public: using Shape = JaggedArrayShape; using Edge = Shape::Edge; static absl::string_view ReprName() { return "JaggedArrayShape"; } static absl::StatusOr<ArrayEdge> EdgeFromSplitPoints( absl::Span<const OptionalValue<int64_t>> split_points) { return ArrayEdge::FromSplitPoints(CreateArray<int64_t>(split_points)); } static absl::StatusOr<ArrayEdge> EdgeFromMapping( absl::Span<const OptionalValue<int64_t>> mapping, int64_t parent_size) { return ArrayEdge::FromMapping(CreateArray<int64_t>(mapping), parent_size); } static const Buffer<int64_t>& GetSplitPoints(const ArrayEdge& edge) { return edge.edge_values().dense_data().values; } }; class JaggedDenseArrayShapeHelper { public: using Shape = JaggedDenseArrayShape; using Edge = Shape::Edge; static absl::string_view ReprName() { return "JaggedShape"; } static absl::StatusOr<DenseArrayEdge> EdgeFromSplitPoints( absl::Span<const OptionalValue<int64_t>> split_points) { return DenseArrayEdge::FromSplitPoints( CreateDenseArray<int64_t>(split_points)); } static absl::StatusOr<DenseArrayEdge> EdgeFromMapping( absl::Span<const OptionalValue<int64_t>> mapping, int64_t parent_size) { return DenseArrayEdge::FromMapping(CreateDenseArray<int64_t>(mapping), parent_size); } static const Buffer<int64_t>& GetSplitPoints(const DenseArrayEdge& edge) { return edge.edge_values().values; } }; template <typename JaggedShapeHelper> class JaggedShapeTest : public ::testing::Test { public: using Helper = JaggedShapeHelper; using Shape = typename JaggedShapeHelper::Shape; }; using JaggedShapeTestTypes = ::testing::Types<JaggedArrayShapeHelper, JaggedDenseArrayShapeHelper>; TYPED_TEST_SUITE(JaggedShapeTest, JaggedShapeTestTypes); TYPED_TEST(JaggedShapeTest, Empty) { auto shape = TestFixture::Shape::Empty(); EXPECT_EQ(shape.rank(), 0); EXPECT_EQ(shape.size(), 1); EXPECT_TRUE(shape.edges().empty()); } TYPED_TEST(JaggedShapeTest, FromEdges) { using Shape = typename TestFixture::Shape; using Helper = typename TestFixture::Helper; { ASSERT_OK_AND_ASSIGN(auto shape, Shape::FromEdges({})); EXPECT_EQ(shape.rank(), 0); EXPECT_EQ(shape.size(), 1); EXPECT_TRUE(shape.edges().empty()); } { ASSERT_OK_AND_ASSIGN(auto edge, Helper::EdgeFromSplitPoints({0, 2})); ASSERT_OK_AND_ASSIGN(auto shape, Shape::FromEdges({std::move(edge)})); EXPECT_EQ(shape.rank(), 1); EXPECT_EQ(shape.size(), 2); auto edges = shape.edges(); EXPECT_EQ(edges.size(), 1); EXPECT_THAT(Helper::GetSplitPoints(edges[0]), ElementsAre(0, 2)); } { ASSERT_OK_AND_ASSIGN(auto edge1, Helper::EdgeFromSplitPoints({0, 2})); ASSERT_OK_AND_ASSIGN(auto edge2, Helper::EdgeFromSplitPoints({0, 1, 3})); ASSERT_OK_AND_ASSIGN(auto edge3, Helper::EdgeFromSplitPoints({0, 1, 2, 4})); ASSERT_OK_AND_ASSIGN(auto shape, Shape::FromEdges({std::move(edge1), std::move(edge2), std::move(edge3)})); EXPECT_EQ(shape.rank(), 3); EXPECT_EQ(shape.size(), 4); auto edges = shape.edges(); EXPECT_EQ(edges.size(), 3); EXPECT_THAT(Helper::GetSplitPoints(edges[0]), ElementsAre(0, 2)); EXPECT_THAT(Helper::GetSplitPoints(edges[1]), ElementsAre(0, 1, 3)); EXPECT_THAT(Helper::GetSplitPoints(edges[2]), ElementsAre(0, 1, 2, 4)); } { ASSERT_OK_AND_ASSIGN(auto edge1, Helper::EdgeFromSplitPoints({0, 8})); ASSERT_OK_AND_ASSIGN(auto edge2, Helper::EdgeFromMapping({0, 0, 1, 1, 3, 5}, 8)); ASSERT_OK_AND_ASSIGN( auto shape, Shape::FromEdges({std::move(edge1), std::move(edge2)})); EXPECT_EQ(shape.rank(), 2); EXPECT_EQ(shape.size(), 6); auto edges = shape.edges(); EXPECT_EQ(edges.size(), 2); EXPECT_THAT(Helper::GetSplitPoints(edges[0]), ElementsAre(0, 8)); EXPECT_THAT(Helper::GetSplitPoints(edges[1]), ElementsAre(0, 2, 4, 4, 5, 5, 6, 6, 6)); } } TYPED_TEST(JaggedShapeTest, FromEdgesErrors) { using Shape = typename TestFixture::Shape; using Helper = typename TestFixture::Helper; { ASSERT_OK_AND_ASSIGN(auto edge, Helper::EdgeFromSplitPoints({0, 2, 3})); EXPECT_THAT(Shape::FromEdges({std::move(edge)}), StatusIs(absl::StatusCode::kInvalidArgument, "incompatible dimensions - edges[0].parent_size " "!= 1 (prior edge's child_size)")); } { ASSERT_OK_AND_ASSIGN(auto edge1, Helper::EdgeFromSplitPoints({0, 2})); ASSERT_OK_AND_ASSIGN(auto edge2, Helper::EdgeFromSplitPoints({0, 1, 3})); ASSERT_OK_AND_ASSIGN(auto edge3, Helper::EdgeFromSplitPoints({0, 1, 4})); EXPECT_THAT(Shape::FromEdges( {std::move(edge1), std::move(edge2), std::move(edge3)}), StatusIs(absl::StatusCode::kInvalidArgument, "incompatible dimensions - edges[2].parent_size " "!= 3 (prior edge's child_size)")); } { ASSERT_OK_AND_ASSIGN(auto edge1, Helper::EdgeFromSplitPoints({0, 1})); ASSERT_OK_AND_ASSIGN(auto edge2, Helper::EdgeFromMapping({0, std::nullopt}, 1)); EXPECT_THAT(Shape::FromEdges({std::move(edge1), std::move(edge2)}), StatusIs(absl::StatusCode::kInvalidArgument, "expected a full mapping")); } { ASSERT_OK_AND_ASSIGN(auto edge1, Helper::EdgeFromSplitPoints({0, 2})); ASSERT_OK_AND_ASSIGN(auto edge2, Helper::EdgeFromMapping({1, 0}, 2)); EXPECT_THAT(Shape::FromEdges({std::move(edge1), std::move(edge2)}), StatusIs(absl::StatusCode::kInvalidArgument, "expected a sorted mapping")); } } TYPED_TEST(JaggedShapeTest, FromEdges_BufferFactory) { using Shape = typename TestFixture::Shape; using Helper = typename TestFixture::Helper; { ASSERT_OK_AND_ASSIGN(auto edge, Helper::EdgeFromMapping({0, 0}, 1)); ASSERT_OK_AND_ASSIGN(auto shape, Shape::FromEdges({std::move(edge)})); EXPECT_TRUE(Helper::GetSplitPoints(shape.edges()[0]).is_owner()); } { ASSERT_OK_AND_ASSIGN(auto edge, Helper::EdgeFromMapping({0, 0}, 1)); UnsafeArenaBufferFactory arena{128}; ASSERT_OK_AND_ASSIGN(auto shape, Shape::FromEdges({std::move(edge)}, arena)); EXPECT_FALSE(Helper::GetSplitPoints(shape.edges()[0]).is_owner()); } } TYPED_TEST(JaggedShapeTest, FlatFromSize) { using Shape = typename TestFixture::Shape; using Helper = typename TestFixture::Helper; { auto shape = Shape::FlatFromSize(3); EXPECT_EQ(shape.rank(), 1); EXPECT_EQ(shape.size(), 3); auto edges = shape.edges(); EXPECT_EQ(edges.size(), 1); EXPECT_THAT(Helper::GetSplitPoints(edges[0]), ElementsAre(0, 3)); } { auto shape = Shape::FlatFromSize(3); EXPECT_TRUE(Helper::GetSplitPoints(shape.edges()[0]).is_owner()); } { UnsafeArenaBufferFactory arena{128}; auto shape = Shape::FlatFromSize(3, arena); EXPECT_FALSE(Helper::GetSplitPoints(shape.edges()[0]).is_owner()); } } TYPED_TEST(JaggedShapeTest, AddDims) { using Shape = typename TestFixture::Shape; using Helper = typename TestFixture::Helper; { ASSERT_OK_AND_ASSIGN(auto edge, Helper::EdgeFromSplitPoints({0, 2})); ASSERT_OK_AND_ASSIGN(auto shape, Shape::FromEdges({std::move(edge)})); ASSERT_OK_AND_ASSIGN(shape, shape.AddDims({})); EXPECT_EQ(shape.rank(), 1); EXPECT_EQ(shape.size(), 2); EXPECT_THAT(Helper::GetSplitPoints(shape.edges()[0]), ElementsAre(0, 2)); } { ASSERT_OK_AND_ASSIGN(auto edge, Helper::EdgeFromSplitPoints({0, 2})); ASSERT_OK_AND_ASSIGN(auto shape, Shape::FromEdges({std::move(edge)})); ASSERT_OK_AND_ASSIGN(auto edge2, Helper::EdgeFromSplitPoints({0, 1, 3})); ASSERT_OK_AND_ASSIGN(auto edge3, Helper::EdgeFromMapping({0, 1, 2, 2}, 3)); ASSERT_OK_AND_ASSIGN(shape, shape.AddDims({edge2, edge3})); EXPECT_EQ(shape.rank(), 3); EXPECT_EQ(shape.size(), 4); auto edges = shape.edges(); EXPECT_THAT(Helper::GetSplitPoints(edges[0]), ElementsAre(0, 2)); EXPECT_THAT(Helper::GetSplitPoints(edges[1]), ElementsAre(0, 1, 3)); EXPECT_THAT(Helper::GetSplitPoints(edges[2]), ElementsAre(0, 1, 2, 4)); } { ASSERT_OK_AND_ASSIGN(auto shape, Shape::FromEdges({})); ASSERT_OK_AND_ASSIGN(auto edge, Helper::EdgeFromMapping({0, 0}, 1)); ASSERT_OK_AND_ASSIGN(shape, shape.AddDims({edge})); EXPECT_TRUE(Helper::GetSplitPoints(shape.edges()[0]).is_owner()); } { ASSERT_OK_AND_ASSIGN(auto shape, Shape::FromEdges({})); ASSERT_OK_AND_ASSIGN(auto edge, Helper::EdgeFromMapping({0, 0}, 1)); UnsafeArenaBufferFactory arena{128}; ASSERT_OK_AND_ASSIGN(shape, shape.AddDims({edge}, arena)); EXPECT_FALSE(Helper::GetSplitPoints(shape.edges()[0]).is_owner()); } { ASSERT_OK_AND_ASSIGN(auto edge, Helper::EdgeFromSplitPoints({0, 2})); ASSERT_OK_AND_ASSIGN(auto shape, Shape::FromEdges({edge})); EXPECT_THAT(shape.AddDims({edge}), StatusIs(absl::StatusCode::kInvalidArgument, "incompatible dimensions - edges[1].parent_size " "!= 2 (prior edge's child_size)")); } } TYPED_TEST(JaggedShapeTest, RemoveDims) { using Shape = typename TestFixture::Shape; using Helper = typename TestFixture::Helper; { ASSERT_OK_AND_ASSIGN(auto shape, Shape::FromEdges({})); shape = shape.RemoveDims(0); EXPECT_EQ(shape.rank(), 0); } { ASSERT_OK_AND_ASSIGN(auto edge, Helper::EdgeFromSplitPoints({0, 2})); ASSERT_OK_AND_ASSIGN(auto shape, Shape::FromEdges({edge})); shape = shape.RemoveDims(1); EXPECT_EQ(shape.rank(), 1); EXPECT_THAT(Helper::GetSplitPoints(shape.edges()[0]), ElementsAre(0, 2)); } { ASSERT_OK_AND_ASSIGN(auto edge, Helper::EdgeFromSplitPoints({0, 2})); ASSERT_OK_AND_ASSIGN(auto edge2, Helper::EdgeFromSplitPoints({0, 1, 2})); ASSERT_OK_AND_ASSIGN(auto shape, Shape::FromEdges({edge, edge2})); shape = shape.RemoveDims(0); EXPECT_EQ(shape.rank(), 0); } { ASSERT_OK_AND_ASSIGN(auto edge, Helper::EdgeFromSplitPoints({0, 2})); ASSERT_OK_AND_ASSIGN(auto edge2, Helper::EdgeFromSplitPoints({0, 1, 3})); ASSERT_OK_AND_ASSIGN(auto edge3, Helper::EdgeFromSplitPoints({0, 1, 2, 4})); ASSERT_OK_AND_ASSIGN(auto shape, Shape::FromEdges({edge, edge2, edge3})); shape = shape.RemoveDims(1); EXPECT_EQ(shape.rank(), 1); EXPECT_THAT(Helper::GetSplitPoints(shape.edges()[0]), ElementsAre(0, 2)); } } TYPED_TEST(JaggedShapeTest, FlattenDims_RankDecrease) { using Shape = typename TestFixture::Shape; using Helper = typename TestFixture::Helper; ASSERT_OK_AND_ASSIGN(auto edge1, Helper::EdgeFromSplitPoints({0, 2})); ASSERT_OK_AND_ASSIGN(auto edge2, Helper::EdgeFromSplitPoints({0, 1, 3})); ASSERT_OK_AND_ASSIGN(auto edge3, Helper::EdgeFromSplitPoints({0, 1, 2, 4})); ASSERT_OK_AND_ASSIGN(auto edge4, Helper::EdgeFromSplitPoints({0, 3, 4, 11, 12})); ASSERT_OK_AND_ASSIGN(auto shape, Shape::FromEdges({edge1, edge2, edge3, edge4})); { auto new_shape = shape.FlattenDims(0, 1); EXPECT_EQ(new_shape.rank(), 4); auto edges = new_shape.edges(); EXPECT_THAT(Helper::GetSplitPoints(edges[0]), ElementsAre(0, 2)); EXPECT_THAT(Helper::GetSplitPoints(edges[1]), ElementsAre(0, 1, 3)); EXPECT_THAT(Helper::GetSplitPoints(edges[2]), ElementsAre(0, 1, 2, 4)); EXPECT_THAT(Helper::GetSplitPoints(edges[3]), ElementsAre(0, 3, 4, 11, 12)); } { auto new_shape = shape.FlattenDims(0, 4); EXPECT_EQ(new_shape.rank(), 1); auto edges = new_shape.edges(); EXPECT_THAT(Helper::GetSplitPoints(edges[0]), ElementsAre(0, 12)); } { auto new_shape = shape.FlattenDims(1, 3); EXPECT_EQ(new_shape.rank(), 3); auto edges = new_shape.edges(); EXPECT_THAT(Helper::GetSplitPoints(edges[0]), ElementsAre(0, 2)); EXPECT_THAT(Helper::GetSplitPoints(edges[1]), ElementsAre(0, 1, 4)); EXPECT_THAT(Helper::GetSplitPoints(edges[2]), ElementsAre(0, 3, 4, 11, 12)); } { auto new_shape = shape.FlattenDims(0, 4); EXPECT_TRUE(Helper::GetSplitPoints(new_shape.edges()[0]).is_owner()); } { UnsafeArenaBufferFactory arena{128}; auto new_shape = shape.FlattenDims(0, 4, arena); EXPECT_FALSE(Helper::GetSplitPoints(new_shape.edges()[0]).is_owner()); } } TYPED_TEST(JaggedShapeTest, FlattenDims_RankIncrease) { using Shape = typename TestFixture::Shape; using Helper = typename TestFixture::Helper; ASSERT_OK_AND_ASSIGN(auto edge1, Helper::EdgeFromSplitPoints({0, 2})); ASSERT_OK_AND_ASSIGN(auto edge2, Helper::EdgeFromSplitPoints({0, 1, 3})); ASSERT_OK_AND_ASSIGN(auto edge3, Helper::EdgeFromSplitPoints({0, 1, 2, 4})); ASSERT_OK_AND_ASSIGN(auto edge4, Helper::EdgeFromSplitPoints({0, 3, 4, 11, 12})); ASSERT_OK_AND_ASSIGN(auto shape, Shape::FromEdges({edge1, edge2, edge3, edge4})); { auto new_shape = shape.FlattenDims(0, 0); EXPECT_EQ(new_shape.rank(), 5); auto edges = new_shape.edges(); EXPECT_THAT(Helper::GetSplitPoints(edges[0]), ElementsAre(0, 1)); EXPECT_THAT(Helper::GetSplitPoints(edges[1]), ElementsAre(0, 2)); EXPECT_THAT(Helper::GetSplitPoints(edges[2]), ElementsAre(0, 1, 3)); EXPECT_THAT(Helper::GetSplitPoints(edges[3]), ElementsAre(0, 1, 2, 4)); EXPECT_THAT(Helper::GetSplitPoints(edges[4]), ElementsAre(0, 3, 4, 11, 12)); } { auto new_shape = shape.FlattenDims(2, 2); EXPECT_EQ(new_shape.rank(), 5); auto edges = new_shape.edges(); EXPECT_THAT(Helper::GetSplitPoints(edges[0]), ElementsAre(0, 2)); EXPECT_THAT(Helper::GetSplitPoints(edges[1]), ElementsAre(0, 1, 3)); EXPECT_THAT(Helper::GetSplitPoints(edges[2]), ElementsAre(0, 1, 2, 3)); EXPECT_THAT(Helper::GetSplitPoints(edges[3]), ElementsAre(0, 1, 2, 4)); EXPECT_THAT(Helper::GetSplitPoints(edges[4]), ElementsAre(0, 3, 4, 11, 12)); } { auto new_shape = shape.FlattenDims(4, 4); EXPECT_EQ(new_shape.rank(), 5); auto edges = new_shape.edges(); EXPECT_THAT(Helper::GetSplitPoints(edges[0]), ElementsAre(0, 2)); EXPECT_THAT(Helper::GetSplitPoints(edges[1]), ElementsAre(0, 1, 3)); EXPECT_THAT(Helper::GetSplitPoints(edges[2]), ElementsAre(0, 1, 2, 4)); EXPECT_THAT(Helper::GetSplitPoints(edges[3]), ElementsAre(0, 3, 4, 11, 12)); EXPECT_THAT(Helper::GetSplitPoints(edges[4]), ElementsAre(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)); } { auto empty_shape = Shape::Empty(); auto new_shape = empty_shape.FlattenDims(0, 0); EXPECT_EQ(new_shape.rank(), 1); auto edges = new_shape.edges(); EXPECT_THAT(Helper::GetSplitPoints(edges[0]), ElementsAre(0, 1)); } { auto new_shape = shape.FlattenDims(0, 0); EXPECT_TRUE(Helper::GetSplitPoints(new_shape.edges()[0]).is_owner()); } { UnsafeArenaBufferFactory arena{128}; auto new_shape = shape.FlattenDims(0, 0, arena); EXPECT_FALSE(Helper::GetSplitPoints(new_shape.edges()[0]).is_owner()); } } TYPED_TEST(JaggedShapeTest, MovableAndCopyableClass) { using Shape = typename TestFixture::Shape; using Helper = typename TestFixture::Helper; static_assert(std::is_copy_constructible_v<Shape> && std::is_copy_assignable_v<Shape>); static_assert(std::is_move_constructible_v<Shape> && std::is_move_assignable_v<Shape>); { ASSERT_OK_AND_ASSIGN(auto edge, Helper::EdgeFromSplitPoints({0, 2})); ASSERT_OK_AND_ASSIGN(auto shape, Shape::FromEdges({std::move(edge)})); auto shape_cpy = shape; EXPECT_EQ(shape_cpy.rank(), 1); EXPECT_EQ(shape_cpy.size(), 2); auto edges = shape_cpy.edges(); EXPECT_EQ(edges.size(), 1); EXPECT_THAT(Helper::GetSplitPoints(edges[0]), ElementsAre(0, 2)); } { ASSERT_OK_AND_ASSIGN(auto edge, Helper::EdgeFromSplitPoints({0, 2})); ASSERT_OK_AND_ASSIGN(auto shape, Shape::FromEdges({std::move(edge)})); auto shape_move = std::move(shape); EXPECT_EQ(shape_move.rank(), 1); EXPECT_EQ(shape_move.size(), 2); auto edges = shape_move.edges(); EXPECT_EQ(edges.size(), 1); EXPECT_THAT(Helper::GetSplitPoints(edges[0]), ElementsAre(0, 2)); } } TYPED_TEST(JaggedShapeTest, Fingerprint) { using Shape = typename TestFixture::Shape; using Helper = typename TestFixture::Helper; ASSERT_OK_AND_ASSIGN(auto edge1, Helper::EdgeFromSplitPoints({0, 2})); ASSERT_OK_AND_ASSIGN(auto edge2, Helper::EdgeFromSplitPoints({0, 1, 2})); ASSERT_OK_AND_ASSIGN(auto shape1, Shape::FromEdges({edge1, edge2})); ASSERT_OK_AND_ASSIGN(auto shape2, Shape::FromEdges({edge1, edge2})); EXPECT_EQ(FingerprintHasher("salt").Combine(shape1).Finish(), FingerprintHasher("salt").Combine(shape2).Finish()); ASSERT_OK_AND_ASSIGN(auto edge3, Helper::EdgeFromSplitPoints({0, 2, 4})); ASSERT_OK_AND_ASSIGN(auto shape3, Shape::FromEdges({edge1, edge3})); EXPECT_NE(FingerprintHasher("salt").Combine(shape1).Finish(), FingerprintHasher("salt").Combine(shape3).Finish()); ASSERT_OK_AND_ASSIGN(auto shape4, Shape::FromEdges({edge1, edge2, edge3})); EXPECT_NE(FingerprintHasher("salt").Combine(shape1).Finish(), FingerprintHasher("salt").Combine(shape4).Finish()); } TYPED_TEST(JaggedShapeTest, FastEquivalenceCheck) { using Shape = typename TestFixture::Shape; using Helper = typename TestFixture::Helper; JaggedShapeFastEquivalenceResult kEqSizes( JaggedShapeFastEquivalenceResult::kSizesEq); JaggedShapeFastEquivalenceResult kNotEq( JaggedShapeFastEquivalenceResult::kNotEq); JaggedShapeFastEquivalenceResult kEq(JaggedShapeFastEquivalenceResult::kEq); { SCOPED_TRACE("Empty is fully equal."); auto shape = Shape::Empty(); EXPECT_EQ(shape.FastEquivalenceCheck(shape), kEq); } { SCOPED_TRACE("Rank 1 is fully equal."); ASSERT_OK_AND_ASSIGN(auto edge1, Helper::EdgeFromSplitPoints({0, 2})); ASSERT_OK_AND_ASSIGN(auto shape, Shape::FromEdges({edge1})); EXPECT_EQ(shape.FastEquivalenceCheck(shape), kEq); ASSERT_OK_AND_ASSIGN(auto shape2, Shape::FromEdges({edge1})); EXPECT_EQ(shape.FastEquivalenceCheck(shape2), kEq); EXPECT_EQ(shape2.FastEquivalenceCheck(shape), kEq); ASSERT_OK_AND_ASSIGN(auto edge1_new, Helper::EdgeFromSplitPoints({0, 2})); ASSERT_OK_AND_ASSIGN(auto shape2_new, Shape::FromEdges({edge1_new})); EXPECT_EQ(shape.FastEquivalenceCheck(shape2_new), kEq); EXPECT_EQ(shape2_new.FastEquivalenceCheck(shape), kEq); } { SCOPED_TRACE("Equal shapes."); ASSERT_OK_AND_ASSIGN(auto edge1, Helper::EdgeFromSplitPoints({0, 2})); ASSERT_OK_AND_ASSIGN(auto edge2, Helper::EdgeFromSplitPoints({0, 1, 3})); ASSERT_OK_AND_ASSIGN(auto edge3, Helper::EdgeFromSplitPoints({0, 1, 2, 4})); ASSERT_OK_AND_ASSIGN(auto shape1, Shape::FromEdges({edge1, edge2, edge3})); ASSERT_OK_AND_ASSIGN(auto shape2, Shape::FromEdges({edge1, edge2, edge3})); EXPECT_EQ(shape1.FastEquivalenceCheck(shape1), kEq) << "the same pointer must be exact equal"; EXPECT_EQ(shape1.FastEquivalenceCheck(shape2), kEqSizes); EXPECT_EQ(shape2.FastEquivalenceCheck(shape1), kEqSizes); } { SCOPED_TRACE("Different shapes."); ASSERT_OK_AND_ASSIGN(auto edge1, Helper::EdgeFromSplitPoints({0, 2})); ASSERT_OK_AND_ASSIGN(auto shape1, Shape::FromEdges({edge1})); ASSERT_OK_AND_ASSIGN(auto edge2, Helper::EdgeFromSplitPoints({0, 3})); ASSERT_OK_AND_ASSIGN(auto shape2, Shape::FromEdges({edge2})); EXPECT_EQ(shape1.FastEquivalenceCheck(shape2), kNotEq); EXPECT_EQ(shape2.FastEquivalenceCheck(shape1), kNotEq); } { SCOPED_TRACE("Different ranks."); ASSERT_OK_AND_ASSIGN(auto edge1, Helper::EdgeFromSplitPoints({0, 2})); ASSERT_OK_AND_ASSIGN(auto edge2, Helper::EdgeFromSplitPoints({0, 1, 3})); ASSERT_OK_AND_ASSIGN(auto shape1, Shape::FromEdges({edge1, edge2})); ASSERT_OK_AND_ASSIGN(auto shape2, Shape::FromEdges({edge1})); EXPECT_EQ(shape1.FastEquivalenceCheck(shape2), kNotEq); EXPECT_EQ(shape2.FastEquivalenceCheck(shape1), kNotEq); } { SCOPED_TRACE("False negative."); ASSERT_OK_AND_ASSIGN(auto edge1, Helper::EdgeFromSplitPoints({0, 2})); ASSERT_OK_AND_ASSIGN(auto edge2, Helper::EdgeFromSplitPoints({0, 1, 3})); ASSERT_OK_AND_ASSIGN(auto shape1, Shape::FromEdges({edge1, edge2})); ASSERT_OK_AND_ASSIGN(auto edge3, Helper::EdgeFromSplitPoints({0, 2})); ASSERT_OK_AND_ASSIGN(auto edge4, Helper::EdgeFromSplitPoints({0, 2, 3})); ASSERT_OK_AND_ASSIGN(auto shape2, Shape::FromEdges({edge3, edge4})); EXPECT_EQ(shape1.FastEquivalenceCheck(shape2), kEqSizes); EXPECT_EQ(shape2.FastEquivalenceCheck(shape1), kEqSizes); } } TYPED_TEST(JaggedShapeTest, EqOp) { using Shape = typename TestFixture::Shape; using Helper = typename TestFixture::Helper; { ASSERT_OK_AND_ASSIGN(auto edge1, Helper::EdgeFromSplitPoints({0, 2})); ASSERT_OK_AND_ASSIGN(auto edge2, Helper::EdgeFromSplitPoints({0, 1, 3})); ASSERT_OK_AND_ASSIGN(auto edge3, Helper::EdgeFromSplitPoints({0, 1, 2, 4})); ASSERT_OK_AND_ASSIGN(auto shape1, Shape::FromEdges({edge1, edge2, edge3})); ASSERT_OK_AND_ASSIGN(auto shape2, Shape::FromEdges({edge1, edge2, edge3})); EXPECT_TRUE(shape1.IsEquivalentTo(shape2)); EXPECT_TRUE(shape2.IsEquivalentTo(shape1)); EXPECT_TRUE(shape1.IsEquivalentTo(shape1)); } { ASSERT_OK_AND_ASSIGN(auto edge1, Helper::EdgeFromSplitPoints({0, 2})); ASSERT_OK_AND_ASSIGN(auto shape1, Shape::FromEdges({edge1})); ASSERT_OK_AND_ASSIGN(auto edge2, Helper::EdgeFromSplitPoints({0, 3})); ASSERT_OK_AND_ASSIGN(auto shape2, Shape::FromEdges({edge2})); EXPECT_FALSE(shape1.IsEquivalentTo(shape2)); EXPECT_FALSE(shape2.IsEquivalentTo(shape1)); } { ASSERT_OK_AND_ASSIGN(auto edge1, Helper::EdgeFromSplitPoints({0, 2})); ASSERT_OK_AND_ASSIGN(auto edge2, Helper::EdgeFromSplitPoints({0, 1, 3})); ASSERT_OK_AND_ASSIGN(auto shape1, Shape::FromEdges({edge1, edge2})); ASSERT_OK_AND_ASSIGN(auto shape2, Shape::FromEdges({edge1})); EXPECT_FALSE(shape1.IsEquivalentTo(shape2)); EXPECT_FALSE(shape2.IsEquivalentTo(shape1)); } { ASSERT_OK_AND_ASSIGN(auto edge1, Helper::EdgeFromSplitPoints({0, 2})); ASSERT_OK_AND_ASSIGN(auto edge2, Helper::EdgeFromSplitPoints({0, 1, 3})); ASSERT_OK_AND_ASSIGN(auto shape1, Shape::FromEdges({edge1, edge2})); ASSERT_OK_AND_ASSIGN(auto edge3, Helper::EdgeFromSplitPoints({0, 2})); ASSERT_OK_AND_ASSIGN(auto edge4, Helper::EdgeFromSplitPoints({0, 2, 3})); ASSERT_OK_AND_ASSIGN(auto shape2, Shape::FromEdges({edge3, edge4})); EXPECT_FALSE(shape1.IsEquivalentTo(shape2)); EXPECT_FALSE(shape2.IsEquivalentTo(shape1)); } } TYPED_TEST(JaggedShapeTest, IsBroadcastableTo) { using Shape = typename TestFixture::Shape; using Helper = typename TestFixture::Helper; { ASSERT_OK_AND_ASSIGN(auto edge1, Helper::EdgeFromSplitPoints({0, 2})); ASSERT_OK_AND_ASSIGN(auto edge2, Helper::EdgeFromSplitPoints({0, 1, 3})); ASSERT_OK_AND_ASSIGN(auto edge3, Helper::EdgeFromSplitPoints({0, 1, 2, 4})); ASSERT_OK_AND_ASSIGN(auto shape1, Shape::FromEdges({edge1, edge2, edge3})); ASSERT_OK_AND_ASSIGN(auto shape2, Shape::FromEdges({edge1, edge2, edge3})); EXPECT_TRUE(shape1.IsBroadcastableTo(shape2)); EXPECT_TRUE(shape2.IsBroadcastableTo(shape1)); EXPECT_TRUE(shape1.IsBroadcastableTo(shape1)); } { ASSERT_OK_AND_ASSIGN(auto edge1, Helper::EdgeFromSplitPoints({0, 2})); ASSERT_OK_AND_ASSIGN(auto shape1, Shape::FromEdges({edge1})); ASSERT_OK_AND_ASSIGN(auto edge2, Helper::EdgeFromSplitPoints({0, 3})); ASSERT_OK_AND_ASSIGN(auto shape2, Shape::FromEdges({edge2})); EXPECT_FALSE(shape1.IsBroadcastableTo(shape2)); EXPECT_FALSE(shape2.IsBroadcastableTo(shape1)); } { ASSERT_OK_AND_ASSIGN(auto edge1, Helper::EdgeFromSplitPoints({0, 2})); ASSERT_OK_AND_ASSIGN(auto edge2, Helper::EdgeFromSplitPoints({0, 2, 3})); ASSERT_OK_AND_ASSIGN(auto edge3, Helper::EdgeFromSplitPoints({0, 2, 4, 6})); ASSERT_OK_AND_ASSIGN(auto shape1, Shape::FromEdges({edge1, edge2})); ASSERT_OK_AND_ASSIGN(auto shape2, Shape::FromEdges({edge1, edge2, edge3})); EXPECT_TRUE(shape1.IsBroadcastableTo(shape2)); EXPECT_FALSE(shape2.IsBroadcastableTo(shape1)); } { ASSERT_OK_AND_ASSIGN(auto edge1, Helper::EdgeFromSplitPoints({0, 2})); ASSERT_OK_AND_ASSIGN(auto edge2_1, Helper::EdgeFromSplitPoints({0, 2, 3})); ASSERT_OK_AND_ASSIGN(auto edge2_2, Helper::EdgeFromSplitPoints({0, 1, 3})); ASSERT_OK_AND_ASSIGN(auto edge3, Helper::EdgeFromSplitPoints({0, 2, 4, 6})); ASSERT_OK_AND_ASSIGN(auto shape1, Shape::FromEdges({edge1, edge2_1})); ASSERT_OK_AND_ASSIGN(auto shape2, Shape::FromEdges({edge1, edge2_2, edge3})); EXPECT_FALSE(shape1.IsBroadcastableTo(shape2)); EXPECT_FALSE(shape2.IsBroadcastableTo(shape1)); } } TYPED_TEST(JaggedShapeTest, GetBroadcastEdge) { using Shape = typename TestFixture::Shape; using Helper = typename TestFixture::Helper; { ASSERT_OK_AND_ASSIGN(auto edge1, Helper::EdgeFromSplitPoints({0, 2})); ASSERT_OK_AND_ASSIGN(auto edge2, Helper::EdgeFromSplitPoints({0, 1, 3})); ASSERT_OK_AND_ASSIGN(auto edge3, Helper::EdgeFromSplitPoints({0, 1, 2, 4})); ASSERT_OK_AND_ASSIGN(auto shape1, Shape::FromEdges({edge1})); ASSERT_OK_AND_ASSIGN(auto shape2, Shape::FromEdges({edge1, edge2, edge3})); auto edge = shape1.GetBroadcastEdge(shape2); EXPECT_TRUE(edge.IsEquivalentTo(*Helper::EdgeFromSplitPoints({0, 1, 4}))); } { ASSERT_OK_AND_ASSIGN(auto edge1, Helper::EdgeFromSplitPoints({0, 2})); ASSERT_OK_AND_ASSIGN(auto edge2, Helper::EdgeFromSplitPoints({0, 1, 3})); ASSERT_OK_AND_ASSIGN(auto edge3, Helper::EdgeFromSplitPoints({0, 1, 2, 4})); ASSERT_OK_AND_ASSIGN(auto shape1, Shape::FromEdges({edge1, edge2, edge3})); ASSERT_OK_AND_ASSIGN(auto shape2, Shape::FromEdges({edge1, edge2, edge3})); auto edge = shape1.GetBroadcastEdge(shape2); EXPECT_TRUE( edge.IsEquivalentTo(*Helper::EdgeFromSplitPoints({0, 1, 2, 3, 4}))); } { ASSERT_OK_AND_ASSIGN(auto edge1, Helper::EdgeFromSplitPoints({0, 2})); ASSERT_OK_AND_ASSIGN(auto edge2, Helper::EdgeFromSplitPoints({0, 1, 3})); ASSERT_OK_AND_ASSIGN(auto edge3, Helper::EdgeFromSplitPoints({0, 1, 2, 4})); ASSERT_OK_AND_ASSIGN(auto shape1, Shape::FromEdges({edge1})); ASSERT_OK_AND_ASSIGN(auto shape2, Shape::FromEdges({edge1, edge2, edge3})); auto edge = shape1.GetBroadcastEdge(shape2); EXPECT_TRUE(Helper::GetSplitPoints(edge).is_owner()); } { ASSERT_OK_AND_ASSIGN(auto edge1, Helper::EdgeFromSplitPoints({0, 2})); ASSERT_OK_AND_ASSIGN(auto edge2, Helper::EdgeFromSplitPoints({0, 1, 3})); ASSERT_OK_AND_ASSIGN(auto edge3, Helper::EdgeFromSplitPoints({0, 1, 2, 4})); ASSERT_OK_AND_ASSIGN(auto shape1, Shape::FromEdges({edge1})); ASSERT_OK_AND_ASSIGN(auto shape2, Shape::FromEdges({edge1, edge2, edge3})); UnsafeArenaBufferFactory arena{128}; auto edge = shape1.GetBroadcastEdge(shape2, arena); EXPECT_FALSE(Helper::GetSplitPoints(edge).is_owner()); } { ASSERT_OK_AND_ASSIGN(auto edge1, Helper::EdgeFromSplitPoints({0, 2})); ASSERT_OK_AND_ASSIGN(auto edge2, Helper::EdgeFromSplitPoints({0, 1, 3})); ASSERT_OK_AND_ASSIGN(auto edge3, Helper::EdgeFromSplitPoints({0, 1, 2, 4})); ASSERT_OK_AND_ASSIGN(auto shape1, Shape::FromEdges({edge1, edge2, edge3})); ASSERT_OK_AND_ASSIGN(auto shape2, Shape::FromEdges({edge1, edge2, edge3})); auto edge = shape1.GetBroadcastEdge(shape2); EXPECT_TRUE(Helper::GetSplitPoints(edge).is_owner()); } { ASSERT_OK_AND_ASSIGN(auto edge1, Helper::EdgeFromSplitPoints({0, 2})); ASSERT_OK_AND_ASSIGN(auto edge2, Helper::EdgeFromSplitPoints({0, 1, 3})); ASSERT_OK_AND_ASSIGN(auto edge3, Helper::EdgeFromSplitPoints({0, 1, 2, 4})); ASSERT_OK_AND_ASSIGN(auto shape1, Shape::FromEdges({edge1, edge2, edge3})); ASSERT_OK_AND_ASSIGN(auto shape2, Shape::FromEdges({edge1, edge2, edge3})); UnsafeArenaBufferFactory arena{128}; auto edge = shape1.GetBroadcastEdge(shape2, arena); EXPECT_FALSE(Helper::GetSplitPoints(edge).is_owner()); } } TYPED_TEST(JaggedShapeTest, EdgeT) { using Edge = typename TestFixture::Shape::Edge; using TestEdge = typename TestFixture::Helper::Edge; static_assert(std::is_same_v<Edge, TestEdge>); } TYPED_TEST(JaggedShapeTest, Repr) { using Shape = typename TestFixture::Shape; using Helper = typename TestFixture::Helper; ASSERT_OK_AND_ASSIGN(auto edge1, Helper::EdgeFromSplitPoints({0, 2})); ASSERT_OK_AND_ASSIGN(auto edge2, Helper::EdgeFromSplitPoints({0, 2, 7})); ASSERT_OK_AND_ASSIGN(auto edge3, Helper::EdgeFromSplitPoints({0, 1, 2, 3, 4, 5, 6, 7})); ASSERT_OK_AND_ASSIGN(auto edge4, Helper::EdgeFromSplitPoints({0, 2, 3, 4, 5, 6, 7, 8})); ASSERT_OK_AND_ASSIGN(auto shape, Shape::FromEdges({edge1, edge2, edge3, edge4})); std::string expected_repr = absl::StrCat( Helper::ReprName(), "(2, [2, 5], 1, [2, 1, 1, ..., 1, 1, 1])"); EXPECT_THAT(GenReprToken(shape), ReprTokenEq(expected_repr)); } template <typename ShapeHelper> typename ShapeHelper::Shape ShapeFromEdgesBM( const typename ShapeHelper::Shape::EdgeVec& edges, benchmark::State& state) { state.PauseTiming(); auto edges_cpy = edges; state.ResumeTiming(); return ShapeHelper::Shape::FromEdges(std::move(edges_cpy)).value(); } template <typename ShapeHelper> typename ShapeHelper::Edge GetSplitPointsEdge(int64_t parent_size, int64_t children) { std::vector<OptionalValue<int64_t>> split_points; split_points.reserve(parent_size + 1); for (int64_t i = 0; i <= parent_size; ++i) { split_points.push_back(i * children); } return ShapeHelper::EdgeFromSplitPoints(std::move(split_points)).value(); } template <typename ShapeHelper> typename ShapeHelper::Edge GetMappingEdge(int64_t parent_size, int64_t children) { std::vector<OptionalValue<int64_t>> mapping; mapping.reserve(parent_size * children); for (int64_t i = 0; i < parent_size; ++i) { for (int64_t j = 0; j < children; ++j) { mapping.push_back(i); } } return ShapeHelper::EdgeFromMapping(std::move(mapping), parent_size).value(); } template <typename ShapeHelper> typename ShapeHelper::Shape GetShape(int64_t rank, int64_t num_children) { typename ShapeHelper::Shape::EdgeVec edges; edges.reserve(rank); for (int i = 0; i < rank; ++i) { edges.push_back(GetSplitPointsEdge<ShapeHelper>(std::pow(num_children, i), num_children)); } return ShapeHelper::Shape::FromEdges(std::move(edges)).value(); } template <typename ShapeHelper> void BM_JaggedShape_EmptyCreation(benchmark::State& state) { for (auto _ : state) { auto shape = ShapeHelper::Shape::Empty(); benchmark::DoNotOptimize(shape); } } BENCHMARK(BM_JaggedShape_EmptyCreation<JaggedArrayShapeHelper>); BENCHMARK(BM_JaggedShape_EmptyCreation<JaggedDenseArrayShapeHelper>); template <typename ShapeHelper> void BM_JaggedShape_FromSplitPointEdges(benchmark::State& state) { const int rank = state.range(0); const int num_children = state.range(1); typename ShapeHelper::Shape::EdgeVec edges; edges.reserve(rank); for (int i = 0; i < rank; ++i) { edges.push_back(GetSplitPointsEdge<ShapeHelper>(std::pow(num_children, i), num_children)); } for (auto _ : state) { benchmark::DoNotOptimize(edges); auto shape = ShapeFromEdgesBM<ShapeHelper>(edges, state); benchmark::DoNotOptimize(shape); } } BENCHMARK(BM_JaggedShape_FromSplitPointEdges<JaggedArrayShapeHelper>) ->ArgPair(1, 1) ->ArgPair(100, 1) ->ArgPair(1, 100) ->ArgPair(4, 100); BENCHMARK(BM_JaggedShape_FromSplitPointEdges<JaggedDenseArrayShapeHelper>) ->ArgPair(1, 1) ->ArgPair(100, 1) ->ArgPair(1, 100) ->ArgPair(4, 100); template <typename ShapeHelper> void BM_JaggedShape_FromMappingEdges(benchmark::State& state) { const int rank = state.range(0); const int num_children = state.range(1); typename ShapeHelper::Shape::EdgeVec edges; edges.reserve(rank); for (int i = 0; i < rank; ++i) { edges.push_back( GetMappingEdge<ShapeHelper>(std::pow(num_children, i), num_children)); } for (auto _ : state) { benchmark::DoNotOptimize(edges); auto shape = ShapeFromEdgesBM<ShapeHelper>(edges, state); benchmark::DoNotOptimize(shape); } } BENCHMARK(BM_JaggedShape_FromMappingEdges<JaggedArrayShapeHelper>) ->ArgPair(1, 1) ->ArgPair(100, 1) ->ArgPair(1, 100) ->ArgPair(4, 100); BENCHMARK(BM_JaggedShape_FromMappingEdges<JaggedDenseArrayShapeHelper>) ->ArgPair(1, 1) ->ArgPair(100, 1) ->ArgPair(1, 100) ->ArgPair(4, 100); template <typename ShapeHelper> void BM_JaggedShape_FastEquivalenceCheck(benchmark::State& state) { const int rank = state.range(0); const int num_children = state.range(1); auto shape1 = GetShape<ShapeHelper>(rank, num_children); auto shape2 = GetShape<ShapeHelper>(rank, num_children); for (auto _ : state) { benchmark::DoNotOptimize(shape1); benchmark::DoNotOptimize(shape2); auto eq = shape1.FastEquivalenceCheck(shape2); benchmark::DoNotOptimize(eq); } } BENCHMARK(BM_JaggedShape_FastEquivalenceCheck<JaggedArrayShapeHelper>) ->ArgPair(1, 1) ->ArgPair(100, 1) ->ArgPair(1, 100) ->ArgPair(4, 100); BENCHMARK(BM_JaggedShape_FastEquivalenceCheck<JaggedDenseArrayShapeHelper>) ->ArgPair(1, 1) ->ArgPair(100, 1) ->ArgPair(1, 100) ->ArgPair(4, 100); template <typename ShapeHelper> void BM_JaggedShape_IsEquivalentTo(benchmark::State& state) { const int rank = state.range(0); const int num_children = state.range(1); auto shape1 = GetShape<ShapeHelper>(rank, num_children); auto shape2 = GetShape<ShapeHelper>(rank, num_children); for (auto _ : state) { benchmark::DoNotOptimize(shape1); benchmark::DoNotOptimize(shape2); auto eq = shape1.IsEquivalentTo(shape2); benchmark::DoNotOptimize(eq); } } BENCHMARK(BM_JaggedShape_IsEquivalentTo<JaggedArrayShapeHelper>) ->ArgPair(1, 1) ->ArgPair(100, 1) ->ArgPair(1, 100) ->ArgPair(4, 100); BENCHMARK(BM_JaggedShape_IsEquivalentTo<JaggedDenseArrayShapeHelper>) ->ArgPair(1, 1) ->ArgPair(100, 1) ->ArgPair(1, 100) ->ArgPair(4, 100); template <typename ShapeHelper> void BM_JaggedShape_IsEquivalentTo_SameObj(benchmark::State& state) { const int rank = state.range(0); const int num_children = state.range(1); auto shape1 = GetShape<ShapeHelper>(rank, num_children); auto shape2 = shape1; for (auto _ : state) { benchmark::DoNotOptimize(shape1); benchmark::DoNotOptimize(shape2); auto eq = shape1.IsEquivalentTo(shape2); benchmark::DoNotOptimize(eq); } } BENCHMARK(BM_JaggedShape_IsEquivalentTo_SameObj<JaggedArrayShapeHelper>) ->ArgPair(1, 1) ->ArgPair(4, 100); BENCHMARK(BM_JaggedShape_IsEquivalentTo_SameObj<JaggedDenseArrayShapeHelper>) ->ArgPair(1, 1) ->ArgPair(4, 100); template <typename ShapeHelper> void BM_JaggedShape_FlattenDims(benchmark::State& state) { const int rank = state.range(0); const int num_children = state.range(1); auto shape = GetShape<ShapeHelper>(rank, num_children); int from = state.range(2); int to = state.range(3); for (auto _ : state) { benchmark::DoNotOptimize(shape); benchmark::DoNotOptimize(from); benchmark::DoNotOptimize(to); auto flattened_shape = shape.FlattenDims(from, to); benchmark::DoNotOptimize(flattened_shape); } } BENCHMARK(BM_JaggedShape_FlattenDims<JaggedArrayShapeHelper>) ->Args({6, 10, 0, 6}) ->Args({6, 10, 0, 2}) ->Args({6, 10, 2, 4}) ->Args({6, 10, 4, 6}) ->Args({6, 10, 5, 6}) ->Args({6, 10, 0, 0}) ->Args({6, 10, 2, 2}) ->Args({6, 10, 4, 4}) ->Args({6, 10, 6, 6}); BENCHMARK(BM_JaggedShape_FlattenDims<JaggedDenseArrayShapeHelper>) ->Args({6, 10, 0, 6}) ->Args({6, 10, 0, 2}) ->Args({6, 10, 2, 4}) ->Args({6, 10, 4, 6}) ->Args({6, 10, 5, 6}) ->Args({6, 10, 0, 0}) ->Args({6, 10, 2, 2}) ->Args({6, 10, 4, 4}) ->Args({6, 10, 6, 6}); template <typename ShapeHelper> void BM_JaggedShape_IsBroadcastableTo(benchmark::State& state) { const int rank_1 = state.range(0); const int rank_2 = state.range(1); const int num_children = state.range(2); auto shape1 = GetShape<ShapeHelper>(rank_1, num_children); auto shape2 = GetShape<ShapeHelper>(rank_2, num_children); for (auto _ : state) { benchmark::DoNotOptimize(shape1); benchmark::DoNotOptimize(shape2); auto is_broadcastable = shape1.IsBroadcastableTo(shape2); benchmark::DoNotOptimize(is_broadcastable); } } BENCHMARK(BM_JaggedShape_IsBroadcastableTo<JaggedArrayShapeHelper>) ->Args({1, 1, 1}) ->Args({1, 5, 5}) ->Args({4, 5, 5}); BENCHMARK(BM_JaggedShape_IsBroadcastableTo<JaggedDenseArrayShapeHelper>) ->Args({1, 1, 1}) ->Args({1, 5, 5}) ->Args({4, 5, 5}); template <typename ShapeHelper> void BM_JaggedShape_IsBroadcastableTo_SameObj(benchmark::State& state) { const int rank_1 = state.range(0); const int num_children = state.range(1); auto shape1 = GetShape<ShapeHelper>(rank_1, num_children); auto shape2 = shape1; for (auto _ : state) { benchmark::DoNotOptimize(shape1); benchmark::DoNotOptimize(shape2); auto is_broadcastable = shape1.IsBroadcastableTo(shape2); benchmark::DoNotOptimize(is_broadcastable); } } BENCHMARK(BM_JaggedShape_IsBroadcastableTo_SameObj<JaggedArrayShapeHelper>) ->Args({1, 1}) ->Args({1, 5}) ->Args({4, 5}); BENCHMARK(BM_JaggedShape_IsBroadcastableTo_SameObj<JaggedDenseArrayShapeHelper>) ->Args({1, 1}) ->Args({1, 5}) ->Args({4, 5}); template <typename ShapeHelper> void BM_JaggedShape_Copying(benchmark::State& state) { const int rank = state.range(0); const int num_children = state.range(1); auto shape = GetShape<ShapeHelper>(rank, num_children); for (auto _ : state) { benchmark::DoNotOptimize(shape); auto shape_copy = shape; benchmark::DoNotOptimize(shape_copy); } } BENCHMARK(BM_JaggedShape_Copying<JaggedArrayShapeHelper>) ->ArgPair(1, 1) ->ArgPair(100, 1) ->ArgPair(1, 100) ->ArgPair(4, 100); BENCHMARK(BM_JaggedShape_Copying<JaggedDenseArrayShapeHelper>) ->ArgPair(1, 1) ->ArgPair(100, 1) ->ArgPair(1, 100) ->ArgPair(4, 100); template <typename ShapeHelper> void BM_JaggedShape_Repr(benchmark::State& state) { const int rank = state.range(0); const int num_children = state.range(1); auto shape = GetShape<ShapeHelper>(rank, num_children); for (auto _ : state) { benchmark::DoNotOptimize(shape); auto repr = Repr(shape); benchmark::DoNotOptimize(repr); } } BENCHMARK(BM_JaggedShape_Repr<JaggedArrayShapeHelper>) ->ArgPair(1, 1) ->ArgPair(100, 1) ->ArgPair(1, 100) ->ArgPair(4, 100); BENCHMARK(BM_JaggedShape_Repr<JaggedDenseArrayShapeHelper>) ->ArgPair(1, 1) ->ArgPair(100, 1) ->ArgPair(1, 100) ->ArgPair(4, 100); } }
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/jagged_shape/dense_array/jagged_shape.cc
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/jagged_shape/jagged_shape_test.cc
1ca990dbeca224035efdabffecc7f3738df6b52c
d40b2be0-2eb0-494d-85af-f92c0a002de8
cpp
google/arolla
encoder
arolla/serialization_base/encoder.cc
arolla/serialization_base/encoder_test.cc
#include "arolla/serialization_base/encoder.h" #include <cstdint> #include <utility> #include "absl/cleanup/cleanup.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/expr/expr_node.h" #include "arolla/expr/expr_visitor.h" #include "arolla/qtype/typed_value.h" #include "arolla/serialization_base/base.pb.h" #include "arolla/serialization_base/container.h" #include "arolla/util/fingerprint.h" #include "arolla/util/status_macros_backport.h" namespace arolla::serialization_base { using ::arolla::expr::ExprNode; using ::arolla::expr::ExprNodePtr; using ::arolla::expr::ExprNodeType; using ::arolla::expr::VisitorOrder; Encoder::Encoder(ValueEncoder value_encoder, ContainerBuilder& container_builder) : value_encoder_(std::move(value_encoder)), container_builder_(container_builder) {} absl::StatusOr<uint64_t> Encoder::EncodeValue(const TypedValue& value) { uint64_t value_index; const auto fingerprint = value.GetFingerprint(); if (auto it = known_values_.find(fingerprint); it != known_values_.end()) { value_index = it->second; } else { nesting_ += 1; absl::Cleanup guard = [&] { nesting_ -= 1; }; DecodingStepProto decoding_step_proto; ASSIGN_OR_RETURN(*decoding_step_proto.mutable_value(), value_encoder_(value.AsRef(), *this)); ASSIGN_OR_RETURN(value_index, container_builder_.Add(std::move(decoding_step_proto))); known_values_[fingerprint] = value_index; } if (nesting_ == 0) { DecodingStepProto decoding_step_proto; decoding_step_proto.set_output_value_index(value_index); RETURN_IF_ERROR( container_builder_.Add(std::move(decoding_step_proto)).status()); } return value_index; } absl::StatusOr<uint64_t> Encoder::EncodeCodec(absl::string_view codec) { if (auto it = known_codecs_.find(codec); it != known_codecs_.end()) { return it->second; } DecodingStepProto decoding_step_proto; decoding_step_proto.mutable_codec()->set_name(codec.data(), codec.size()); ASSIGN_OR_RETURN(auto codec_index, container_builder_.Add(std::move(decoding_step_proto))); known_codecs_[codec] = codec_index; return codec_index; } absl::StatusOr<uint64_t> Encoder::EncodeExpr(const ExprNodePtr& expr) { if (expr == nullptr) { return absl::InvalidArgumentError("expr is nullptr"); } uint64_t expr_index; const auto fingerprint = expr->fingerprint(); if (auto it = known_exprs_.find(fingerprint); it != known_exprs_.end()) { expr_index = it->second; } else { nesting_ += 1; absl::Cleanup guard = [&] { nesting_ -= 1; }; for (const auto& expr_node : VisitorOrder(expr)) { RETURN_IF_ERROR(EncodeExprNode(*expr_node)); } expr_index = known_exprs_.at(fingerprint); } if (nesting_ == 0) { DecodingStepProto decoding_step_proto; decoding_step_proto.set_output_expr_index(expr_index); RETURN_IF_ERROR( container_builder_.Add(std::move(decoding_step_proto)).status()); } return expr_index; } absl::Status Encoder::EncodeExprNode(const ExprNode& expr_node) { if (known_exprs_.contains(expr_node.fingerprint())) { return absl::OkStatus(); } switch (expr_node.type()) { case ExprNodeType::kLiteral: return EncodeLiteralNode(expr_node); case ExprNodeType::kLeaf: return EncodeLeafNode(expr_node); case ExprNodeType::kPlaceholder: return EncodePlaceholderNode(expr_node); case ExprNodeType::kOperator: return EncodeOperatorNode(expr_node); } return absl::FailedPreconditionError(absl::StrFormat( "unexpected ExprNodeType(%d)", static_cast<int>(expr_node.type()))); } absl::Status Encoder::EncodeLiteralNode(const ExprNode& expr_node) { ASSIGN_OR_RETURN(auto value_index, EncodeValue(*expr_node.qvalue())); DecodingStepProto decoding_step_proto; decoding_step_proto.mutable_literal_node()->set_literal_value_index( value_index); ASSIGN_OR_RETURN(known_exprs_[expr_node.fingerprint()], container_builder_.Add(std::move(decoding_step_proto))); return absl::OkStatus(); } absl::Status Encoder::EncodeLeafNode(const ExprNode& expr_node) { DecodingStepProto decoding_step_proto; decoding_step_proto.mutable_leaf_node()->set_leaf_key(expr_node.leaf_key()); ASSIGN_OR_RETURN(known_exprs_[expr_node.fingerprint()], container_builder_.Add(std::move(decoding_step_proto))); return absl::OkStatus(); } absl::Status Encoder::EncodePlaceholderNode(const ExprNode& expr_node) { DecodingStepProto decoding_step_proto; decoding_step_proto.mutable_placeholder_node()->set_placeholder_key( expr_node.placeholder_key()); ASSIGN_OR_RETURN(known_exprs_[expr_node.fingerprint()], container_builder_.Add(std::move(decoding_step_proto))); return absl::OkStatus(); } absl::Status Encoder::EncodeOperatorNode(const ExprNode& expr_node) { DecodingStepProto decoding_step_proto; auto* operator_node_proto = decoding_step_proto.mutable_operator_node(); ASSIGN_OR_RETURN(auto operator_value_index, EncodeValue(TypedValue::FromValue(expr_node.op()))); operator_node_proto->set_operator_value_index(operator_value_index); for (const auto& node_dep : expr_node.node_deps()) { auto it = known_exprs_.find(node_dep->fingerprint()); if (it == known_exprs_.end()) { return absl::FailedPreconditionError( "node dependencies must to be pre-serialized"); } operator_node_proto->add_input_expr_indices(it->second); } ASSIGN_OR_RETURN(known_exprs_[expr_node.fingerprint()], container_builder_.Add(std::move(decoding_step_proto))); return absl::OkStatus(); } }
#include "arolla/serialization_base/encoder.h" #include <cstdint> #include <memory> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "absl/status/status_matchers.h" #include "absl/status/statusor.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/qtype/base_types.h" #include "arolla/qtype/typed_ref.h" #include "arolla/qtype/typed_value.h" #include "arolla/serialization_base/base.pb.h" #include "arolla/serialization_base/container.h" #include "arolla/util/testing/equals_proto.h" namespace arolla::serialization_base { namespace { using ::absl_testing::IsOkAndHolds; using ::absl_testing::StatusIs; using ::arolla::expr::ExprOperatorPtr; using ::arolla::expr::ExprOperatorSignature; using ::arolla::expr::Leaf; using ::arolla::expr::Literal; using ::arolla::expr::Placeholder; using ::arolla::expr::testing::DummyOp; using ::arolla::testing::EqualsProto; using ::testing::InSequence; using ::testing::MockFunction; using ::testing::Ref; using ::testing::Return; using ::testing::Truly; auto EqualsTypedRef(TypedRef expected_value) { return Truly([expected_value](TypedRef actual_value) { return expected_value.GetRawPointer() == actual_value.GetRawPointer() && expected_value.GetType() == actual_value.GetType(); }); } template <typename T> auto EqualsTypedRefAsT(const T& expected_value) { return Truly([expected_value](TypedRef actual_value) { auto status_or_value = actual_value.As<T>(); return status_or_value.ok() && status_or_value.value().get() == expected_value; }); } class MockContainerBuilder : public ContainerBuilder { public: MOCK_METHOD(absl::StatusOr<uint64_t>, Add, (DecodingStepProto && decoding_step_proto), (override)); }; class EncoderTest : public ::testing::Test { protected: MockContainerBuilder mock_container_builder_; MockFunction<absl::StatusOr<ValueProto>(TypedRef value, Encoder& encoder)> mock_value_encoder_; Encoder encoder_{mock_value_encoder_.AsStdFunction(), mock_container_builder_}; }; TEST_F(EncoderTest, EncodeExpr_nullptr) { EXPECT_THAT(encoder_.EncodeExpr(nullptr), StatusIs(absl::StatusCode::kInvalidArgument)); } TEST_F(EncoderTest, Codecs) { { EXPECT_CALL(mock_container_builder_, Add(EqualsProto(R"pb(codec: { name: "a" })pb"))) .WillOnce(Return(0)); EXPECT_THAT(encoder_.EncodeCodec("a"), IsOkAndHolds(0)); EXPECT_THAT(encoder_.EncodeCodec("a"), IsOkAndHolds(0)); } { EXPECT_CALL(mock_container_builder_, Add(EqualsProto(R"pb(codec: { name: "b" })pb"))) .WillOnce(Return(1)); EXPECT_THAT(encoder_.EncodeCodec("b"), IsOkAndHolds(1)); EXPECT_THAT(encoder_.EncodeCodec("a"), IsOkAndHolds(0)); } } TEST_F(EncoderTest, EncodeExpr_LiteralNode) { auto literal = Literal(1.0f); InSequence seq; EXPECT_CALL(mock_value_encoder_, Call(EqualsTypedRef(literal->qvalue()->AsRef()), Ref(encoder_))) .WillOnce(Return(ValueProto())); EXPECT_CALL(mock_container_builder_, Add(EqualsProto(R"pb(value: {})pb"))) .WillOnce(Return(0)); EXPECT_CALL( mock_container_builder_, Add(EqualsProto(R"pb(literal_node: { literal_value_index: 0 })pb"))) .WillOnce(Return(1)); EXPECT_CALL(mock_container_builder_, Add(EqualsProto(R"pb(output_expr_index: 1)pb"))) .WillOnce(Return(2)); EXPECT_THAT(encoder_.EncodeExpr(literal), IsOkAndHolds(1)); } TEST_F(EncoderTest, EncodeExpr_LeafNode) { auto leaf = Leaf("key"); InSequence seq; EXPECT_CALL(mock_container_builder_, Add(EqualsProto(R"pb(leaf_node: { leaf_key: "key" })pb"))) .WillOnce(Return(0)); EXPECT_CALL(mock_container_builder_, Add(EqualsProto(R"pb(output_expr_index: 0)pb"))) .WillOnce(Return(1)); EXPECT_THAT(encoder_.EncodeExpr(leaf), IsOkAndHolds(0)); } TEST_F(EncoderTest, EncodeExpr_PlaceholderNode) { auto placeholder = Placeholder("key"); InSequence seq; EXPECT_CALL( mock_container_builder_, Add(EqualsProto(R"pb(placeholder_node: { placeholder_key: "key" })pb"))) .WillOnce(Return(0)); EXPECT_CALL(mock_container_builder_, Add(EqualsProto(R"pb(output_expr_index: 0)pb"))) .WillOnce(Return(1)); EXPECT_THAT(encoder_.EncodeExpr(placeholder), IsOkAndHolds(0)); } TEST_F(EncoderTest, EncodeExpr_OperatorNode) { ExprOperatorPtr dummy_op = std::make_shared<DummyOp>( "dummy_op", ExprOperatorSignature::MakeVariadicArgs()); auto leaf = Leaf("leaf"); auto literal = Literal(1.0f); ASSERT_OK_AND_ASSIGN(auto expr, BindOp(dummy_op, {leaf, literal, leaf, literal}, {})); InSequence seq; EXPECT_CALL(mock_container_builder_, Add(EqualsProto(R"pb(leaf_node: { leaf_key: "leaf" })pb"))) .WillOnce(Return(0)); EXPECT_CALL(mock_value_encoder_, Call(EqualsTypedRef(literal->qvalue()->AsRef()), Ref(encoder_))) .WillOnce(Return(ValueProto())); EXPECT_CALL(mock_container_builder_, Add(EqualsProto(R"pb(value: {})pb"))) .WillOnce(Return(1)); EXPECT_CALL( mock_container_builder_, Add(EqualsProto(R"pb(literal_node: { literal_value_index: 1 })pb"))) .WillOnce(Return(2)); EXPECT_CALL(mock_value_encoder_, Call(EqualsTypedRefAsT(dummy_op), Ref(encoder_))) .WillOnce(Return(ValueProto())); EXPECT_CALL(mock_container_builder_, Add(EqualsProto(R"pb(value: {})pb"))) .WillOnce(Return(3)); EXPECT_CALL(mock_container_builder_, Add(EqualsProto(R"pb(operator_node: { operator_value_index: 3 input_expr_indices: [ 0, 2, 0, 2 ] })pb"))) .WillOnce(Return(4)); EXPECT_CALL(mock_container_builder_, Add(EqualsProto(R"pb(output_expr_index: 4)pb"))) .WillOnce(Return(5)); EXPECT_THAT(encoder_.EncodeExpr(expr), IsOkAndHolds(4)); } TEST_F(EncoderTest, EncodeExpr_SubExprDeduplication) { ExprOperatorPtr dummy_op = std::make_shared<DummyOp>( "dummy_op", ExprOperatorSignature::MakeVariadicArgs()); auto leaf = Leaf("leaf"); ASSERT_OK_AND_ASSIGN(auto expr, BindOp(dummy_op, {leaf}, {})); InSequence seq; EXPECT_CALL(mock_container_builder_, Add(EqualsProto(R"pb(leaf_node { leaf_key: "leaf" })pb"))) .WillOnce(Return(0)); EXPECT_CALL(mock_value_encoder_, Call(EqualsTypedRefAsT(dummy_op), Ref(encoder_))) .WillOnce(Return(ValueProto())); EXPECT_CALL(mock_container_builder_, Add(EqualsProto(R"pb(value {})pb"))) .WillOnce(Return(1)); EXPECT_CALL(mock_container_builder_, Add(EqualsProto(R"pb(operator_node { operator_value_index: 1 input_expr_indices: [ 0 ] })pb"))) .WillOnce(Return(2)); EXPECT_CALL(mock_container_builder_, Add(EqualsProto(R"pb(output_expr_index: 2)pb"))) .WillOnce(Return(3)); EXPECT_CALL(mock_container_builder_, Add(EqualsProto(R"pb(output_expr_index: 0)pb"))) .WillOnce(Return(4)); EXPECT_THAT(encoder_.EncodeExpr(expr), IsOkAndHolds(2)); EXPECT_THAT(encoder_.EncodeExpr(leaf), IsOkAndHolds(0)); } TEST_F(EncoderTest, EncodeValue) { auto value = TypedValue::FromValue(1.0f); auto value_proto = ValueProto(); value_proto.add_input_value_indices(1); value_proto.add_input_value_indices(2); value_proto.add_input_expr_indices(3); value_proto.add_input_expr_indices(4); value_proto.add_input_expr_indices(5); value_proto.set_codec_index(123); InSequence seq; EXPECT_CALL(mock_value_encoder_, Call(EqualsTypedRef(value.AsRef()), Ref(encoder_))) .WillOnce(Return(value_proto)); EXPECT_CALL(mock_container_builder_, Add(EqualsProto(R"pb(value { input_value_indices: [ 1, 2 ] input_expr_indices: [ 3, 4, 5 ] codec_index: 123 })pb"))) .WillOnce(Return(0)); EXPECT_CALL(mock_container_builder_, Add(EqualsProto(R"pb(output_value_index: 0)pb"))) .WillOnce(Return(1)); EXPECT_THAT(encoder_.EncodeValue(value), IsOkAndHolds(0)); EXPECT_CALL( mock_container_builder_, Add(EqualsProto(R"pb(literal_node: { literal_value_index: 0 })pb"))) .WillOnce(Return(2)); EXPECT_CALL(mock_container_builder_, Add(EqualsProto(R"pb(output_expr_index: 2)pb"))) .WillOnce(Return(3)); EXPECT_THAT(encoder_.EncodeExpr(Literal(value)), IsOkAndHolds(2)); } } }
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/serialization_base/encoder.cc
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/serialization_base/encoder_test.cc
1ca990dbeca224035efdabffecc7f3738df6b52c
4ee00360-ce82-4f19-ad17-4a0c4333c44b
cpp
google/arolla
decoder
arolla/serialization_base/decoder.cc
arolla/serialization_base/decoder_test.cc
#include "arolla/serialization_base/decoder.h" #include <cstddef> #include <cstdint> #include <utility> #include <variant> #include <vector> #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.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/qtype/qtype_traits.h" #include "arolla/qtype/typed_value.h" #include "arolla/serialization_base/base.pb.h" #include "arolla/util/status_macros_backport.h" namespace arolla::serialization_base { using ::arolla::expr::ExprNode; using ::arolla::expr::ExprNodePtr; using ::arolla::expr::ExprOperatorPtr; using ::arolla::expr::Leaf; using ::arolla::expr::Literal; using ::arolla::expr::MakeOpNode; using ::arolla::expr::Placeholder; Decoder::Decoder(ValueDecoderProvider value_decoder_provider, const Options& options) : value_decoder_provider_(std::move(value_decoder_provider)), options_(options) {} absl::Status Decoder::OnDecodingStep( uint64_t decoding_step_index, const DecodingStepProto& decoding_step_proto) { if (decoding_step_index > decoding_step_results_.size()) { return absl::InvalidArgumentError( absl::StrFormat("encountered unexpected decoding_step_index=%d, " "indicating missing step %d", decoding_step_index, decoding_step_results_.size())); } if (decoding_step_index == decoding_step_results_.size()) { decoding_step_results_.emplace_back(); } switch (decoding_step_proto.type_case()) { case DecodingStepProto::kLiteralNode: { ASSIGN_OR_RETURN(auto expr, DecodeLiteralNode(decoding_step_proto.literal_node()), _ << "decoding_step.type=LITERAL_NODE"); return StoreDecodedExpr(decoding_step_index, std::move(expr)); } case DecodingStepProto::kLeafNode: { ASSIGN_OR_RETURN(auto expr, DecodeLeafNode(decoding_step_proto.leaf_node()), _ << "decoding_step.type=LEAF_NODE"); return StoreDecodedExpr(decoding_step_index, std::move(expr)); } case DecodingStepProto::kPlaceholderNode: { ASSIGN_OR_RETURN( auto expr, DecodePlaceholderNode(decoding_step_proto.placeholder_node()), _ << "decoding_step.type=PLACEHOLDER_NODE"); return StoreDecodedExpr(decoding_step_index, std::move(expr)); } case DecodingStepProto::kOperatorNode: { ASSIGN_OR_RETURN(auto expr, DecodeOperatorNode(decoding_step_proto.operator_node()), _ << "decoding_step.type=OPERATOR_NODE"); return StoreDecodedExpr(decoding_step_index, std::move(expr)); } case DecodingStepProto::kValue: { ASSIGN_OR_RETURN(auto value, DecodeValue(decoding_step_proto.value()), _ << "decoding_step.type=VALUE"); return StoreDecodedValue(decoding_step_index, std::move(value)); } case DecodingStepProto::kCodec: { ASSIGN_OR_RETURN(auto codec, DecodeCodec(decoding_step_proto.codec()), _ << "decoding_step.type=CODEC"); return StoreDecodedCodec(decoding_step_index, std::move(codec)); } case DecodingStepProto::kOutputValueIndex: { ASSIGN_OR_RETURN( auto value, LoadDecodedValue(decoding_step_proto.output_value_index()), _ << "decoding_step.type=OUTPUT_VALUE_INDEX"); result_.values.push_back(std::move(value)); return absl::OkStatus(); } case DecodingStepProto::kOutputExprIndex: { ASSIGN_OR_RETURN(auto expr, LoadDecodedExpr(decoding_step_proto.output_expr_index()), _ << "decoding_step.type=OUTPUT_EXPR_INDEX"); result_.exprs.push_back(std::move(expr)); return absl::OkStatus(); } case DecodingStepProto::TYPE_NOT_SET: return absl::InvalidArgumentError("missing decoding_step.type"); } return absl::InvalidArgumentError( absl::StrFormat("unexpected decoding_step.type=%d", static_cast<int>(decoding_step_proto.type_case()))); } Decoder::Result Decoder::Finish() && { return std::move(result_); } absl::StatusOr<ExprNodePtr> Decoder::DecodeLiteralNode( const LiteralNodeProto& literal_node_proto) const { if (!literal_node_proto.has_literal_value_index()) { return absl::InvalidArgumentError( "missing literal_node.literal_value_index"); } ASSIGN_OR_RETURN(auto value, LoadDecodedValue(literal_node_proto.literal_value_index())); return Literal(std::move(value)); } absl::StatusOr<ExprNodePtr> Decoder::DecodeLeafNode( const LeafNodeProto& leaf_node_proto) const { if (!leaf_node_proto.has_leaf_key()) { return absl::InvalidArgumentError("missing leaf_node.leaf_key"); } return Leaf(leaf_node_proto.leaf_key()); } absl::StatusOr<ExprNodePtr> Decoder::DecodePlaceholderNode( const PlaceholderNodeProto& placeholder_node_proto) const { if (!placeholder_node_proto.has_placeholder_key()) { return absl::InvalidArgumentError( "missing placeholder_node.placeholder_key"); } return Placeholder(placeholder_node_proto.placeholder_key()); } absl::StatusOr<ExprNodePtr> Decoder::DecodeOperatorNode( const OperatorNodeProto& operator_node_proto) const { if (!operator_node_proto.has_operator_value_index()) { return absl::InvalidArgumentError( "missing operator_node.operator_value_index"); } ASSIGN_OR_RETURN( auto value, LoadDecodedValue(operator_node_proto.operator_value_index())); if (value.GetType() != GetQType<ExprOperatorPtr>()) { return absl::InvalidArgumentError(absl::StrFormat( "expected an operator in decoding_step_results[%d], got %s", operator_node_proto.operator_value_index(), value.GetType()->name())); } const auto& op = value.UnsafeAs<ExprOperatorPtr>(); std::vector<ExprNodePtr> exprs(operator_node_proto.input_expr_indices_size()); for (size_t i = 0; i < exprs.size(); ++i) { ASSIGN_OR_RETURN( exprs[i], LoadDecodedExpr(operator_node_proto.input_expr_indices(i))); } if (options_.infer_attributes_for_operator_nodes) { return MakeOpNode(op, std::move(exprs)); } else { return ExprNode::UnsafeMakeOperatorNode(ExprOperatorPtr(op), std::move(exprs), {}); } } absl::StatusOr<TypedValue> Decoder::DecodeValue( const ValueProto& value_proto) const { std::vector<TypedValue> input_values; input_values.reserve(value_proto.input_value_indices_size()); for (auto value_index : value_proto.input_value_indices()) { ASSIGN_OR_RETURN(auto value, LoadDecodedValue(value_index)); input_values.push_back(std::move(value)); } std::vector<ExprNodePtr> input_exprs(value_proto.input_expr_indices_size()); for (size_t i = 0; i < input_exprs.size(); ++i) { ASSIGN_OR_RETURN(input_exprs[i], LoadDecodedExpr(value_proto.input_expr_indices(i))); } if (value_proto.has_codec_index()) { return DecodeValueWithKnownCodec(value_proto, value_proto.codec_index(), input_values, input_exprs); } return DecodeValueWithUnknownCodec(value_proto, input_values, input_exprs); } absl::StatusOr<TypedValue> Decoder::DecodeValueWithKnownCodec( const ValueProto& value_proto, uint64_t codec_index, absl::Span<const TypedValue> input_values, absl::Span<const ExprNodePtr> input_exprs) const { if (static_cast<size_t>(codec_index) >= decoding_step_results_.size()) { return absl::InvalidArgumentError( absl::StrFormat("codec_index is out of range: %d", codec_index)); } auto* codec = decoding_step_results_[codec_index].codec; if (codec == nullptr) { return absl::InvalidArgumentError(absl::StrFormat( "found no codec in decoding_step_results[%d]", codec_index)); } ASSIGN_OR_RETURN(auto value_decoder_result, codec->value_decoder(value_proto, input_values, input_exprs), _ << "codecs[" << codec_index << "]=" << codec->codec_name); if (auto* value = std::get_if<TypedValue>(&value_decoder_result)) { return std::move(*value); } return absl::NotFoundError(absl::StrFormat( "no extension found; codecs[%d]=%s", codec_index, codec->codec_name)); } absl::StatusOr<TypedValue> Decoder::DecodeValueWithUnknownCodec( const ValueProto& value_proto, absl::Span<const TypedValue> input_values, absl::Span<const ExprNodePtr> input_exprs) const { for (const auto& codec : know_codecs_) { ASSIGN_OR_RETURN( auto value_decoder_result, codec.value_decoder(value_proto, input_values, input_exprs), _ << "detected_codec=" << codec.codec_name); if (auto* value = std::get_if<TypedValue>(&value_decoder_result)) { return *value; } } return absl::InvalidArgumentError("unable to detect codec"); } absl::StatusOr<Decoder::Codec> Decoder::DecodeCodec( const CodecProto& codec_proto) const { ASSIGN_OR_RETURN(auto value_decoder, value_decoder_provider_(codec_proto.name())); DCHECK(value_decoder != nullptr); return Codec{codec_proto.name(), std::move(value_decoder)}; } absl::Status Decoder::StoreDecodedValue(uint64_t value_index, TypedValue&& value) { DCHECK_LT(value_index, decoding_step_results_.size()); if (decoding_step_results_[value_index].value != nullptr) { return absl::InvalidArgumentError("value_index collision"); } decoding_step_results_[value_index].value = &know_values_.emplace_back(std::move(value)); return absl::OkStatus(); } absl::Status Decoder::StoreDecodedExpr(uint64_t expr_index, ExprNodePtr&& expr) { DCHECK_LT(expr_index, decoding_step_results_.size()); if (decoding_step_results_[expr_index].expr != nullptr) { return absl::InvalidArgumentError("expr_index collision"); } decoding_step_results_[expr_index].expr = know_exprs_.emplace_back(std::move(expr)).get(); return absl::OkStatus(); } absl::Status Decoder::StoreDecodedCodec(uint64_t codec_index, Codec&& codec) { DCHECK_LT(codec_index, decoding_step_results_.size()); if (decoding_step_results_[codec_index].codec != nullptr) { return absl::InvalidArgumentError("codec_index collision"); } decoding_step_results_[codec_index].codec = &know_codecs_.emplace_back(std::move(codec)); return absl::OkStatus(); } absl::StatusOr<TypedValue> Decoder::LoadDecodedValue( uint64_t value_index) const { if (static_cast<size_t>(value_index) >= decoding_step_results_.size()) { return absl::InvalidArgumentError( absl::StrFormat("value_index is out of range: %d", value_index)); } if (decoding_step_results_[value_index].value == nullptr) { return absl::InvalidArgumentError(absl::StrFormat( "found no value in decoding_step_results[%d]", value_index)); } return *decoding_step_results_[value_index].value; } absl::StatusOr<ExprNodePtr> Decoder::LoadDecodedExpr( uint64_t expr_index) const { if (static_cast<size_t>(expr_index) >= decoding_step_results_.size()) { return absl::InvalidArgumentError( absl::StrFormat("expr_index is out of range: %d", expr_index)); } if (decoding_step_results_[expr_index].expr == nullptr) { return absl::InvalidArgumentError(absl::StrFormat( "found no expression in decoding_step_results[%d]", expr_index)); } return ExprNodePtr::NewRef(decoding_step_results_[expr_index].expr); } }
#include "arolla/serialization_base/decoder.h" #include <memory> #include <string> #include <utility> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "absl/status/status_matchers.h" #include "absl/status/statusor.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/lambda_expr_operator.h" #include "arolla/expr/testing/testing.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/testing/qtype.h" #include "arolla/qtype/typed_value.h" #include "arolla/serialization_base/base.pb.h" namespace arolla::serialization_base { namespace { using ::absl_testing::StatusIs; using ::arolla::expr::ExprAttributes; using ::arolla::expr::ExprNode; using ::arolla::expr::ExprNodePtr; using ::arolla::expr::ExprOperatorPtr; using ::arolla::expr::LambdaOperator; using ::arolla::expr::Leaf; using ::arolla::expr::Literal; using ::arolla::expr::Placeholder; using ::arolla::testing::EqualsExpr; using ::arolla::testing::TypedValueWith; using ::testing::ElementsAre; using ::testing::InSequence; using ::testing::IsEmpty; using ::testing::MockFunction; using ::testing::Ref; using ::testing::Return; using MockValueDecoderProvider = MockFunction<absl::StatusOr<ValueDecoder>(absl::string_view codec_name)>; using MockValueDecoder = MockFunction<absl::StatusOr<ValueDecoderResult>( const ValueProto& value_proto, absl::Span<const TypedValue> input_values, absl::Span<const ExprNodePtr> input_exprs)>; TEST(DecodeTest, EmptyMessage) { MockValueDecoderProvider mock_value_decoder_provider; Decoder decoder(mock_value_decoder_provider.AsStdFunction(), {}); auto output = std::move(decoder).Finish(); EXPECT_THAT(output.values, IsEmpty()); EXPECT_THAT(output.exprs, IsEmpty()); } TEST(DecodeTest, LiteralNode) { MockValueDecoderProvider mock_value_decoder_provider; MockValueDecoder mock_value_decoder; Decoder decoder(mock_value_decoder_provider.AsStdFunction(), {}); DecodingStepProto decoding_step_proto; { decoding_step_proto.mutable_codec()->set_name("mock_codec"); EXPECT_CALL(mock_value_decoder_provider, Call("mock_codec")) .WillOnce(Return(mock_value_decoder.AsStdFunction())); EXPECT_OK(decoder.OnDecodingStep(0, decoding_step_proto)); } { decoding_step_proto.mutable_value(); EXPECT_CALL(mock_value_decoder, Call(Ref(decoding_step_proto.value()), IsEmpty(), IsEmpty())) .WillOnce(Return(TypedValue::FromValue(1.0f))); EXPECT_OK(decoder.OnDecodingStep(1, decoding_step_proto)); } { decoding_step_proto.mutable_literal_node()->set_literal_value_index(1); EXPECT_OK(decoder.OnDecodingStep(2, decoding_step_proto)); } { decoding_step_proto.set_output_expr_index(2); EXPECT_OK(decoder.OnDecodingStep(3, decoding_step_proto)); } auto output = std::move(decoder).Finish(); EXPECT_THAT(output.values, IsEmpty()); EXPECT_THAT(output.exprs, ElementsAre(EqualsExpr(Literal(1.0f)))); } TEST(DecodeTest, LeafNode) { MockValueDecoderProvider mock_value_decoder_provider; Decoder decoder(mock_value_decoder_provider.AsStdFunction(), {}); DecodingStepProto decoding_step_proto; { decoding_step_proto.mutable_leaf_node()->set_leaf_key("leaf_key"); EXPECT_OK(decoder.OnDecodingStep(0, decoding_step_proto)); } { decoding_step_proto.set_output_expr_index(0); EXPECT_OK(decoder.OnDecodingStep(1, decoding_step_proto)); } auto output = std::move(decoder).Finish(); EXPECT_THAT(output.values, IsEmpty()); EXPECT_THAT(output.exprs, ElementsAre(EqualsExpr(Leaf("leaf_key")))); } TEST(DecodeTest, PlaceholderNode) { MockValueDecoderProvider mock_value_decoder_provider; Decoder decoder(mock_value_decoder_provider.AsStdFunction(), {}); DecodingStepProto decoding_step_proto; { decoding_step_proto.mutable_placeholder_node()->set_placeholder_key( "placeholder_key"); EXPECT_OK(decoder.OnDecodingStep(0, decoding_step_proto)); } { decoding_step_proto.set_output_expr_index(0); EXPECT_OK(decoder.OnDecodingStep(1, decoding_step_proto)); } auto output = std::move(decoder).Finish(); EXPECT_THAT(output.values, IsEmpty()); EXPECT_THAT(output.exprs, ElementsAre(EqualsExpr(Placeholder("placeholder_key")))); } TEST(DecodeTest, OperatorNode) { MockValueDecoderProvider mock_value_decoder_provider; MockValueDecoder mock_value_decoder; Decoder decoder(mock_value_decoder_provider.AsStdFunction(), {}); DecodingStepProto decoding_step_proto; ASSERT_OK_AND_ASSIGN(ExprOperatorPtr dummy_op, LambdaOperator::Make("dummy_op", Placeholder("x"))); { decoding_step_proto.mutable_codec()->set_name("mock_codec"); EXPECT_CALL(mock_value_decoder_provider, Call("mock_codec")) .WillOnce(Return(mock_value_decoder.AsStdFunction())); EXPECT_OK(decoder.OnDecodingStep(0, decoding_step_proto)); } { decoding_step_proto.mutable_value()->set_codec_index(0); EXPECT_CALL(mock_value_decoder, Call(Ref(decoding_step_proto.value()), IsEmpty(), IsEmpty())) .WillOnce(Return(TypedValue::FromValue(dummy_op))); EXPECT_OK(decoder.OnDecodingStep(1, decoding_step_proto)); } { decoding_step_proto.mutable_value()->set_codec_index(0); EXPECT_CALL(mock_value_decoder, Call(Ref(decoding_step_proto.value()), IsEmpty(), IsEmpty())) .WillOnce(Return(TypedValue::FromValue(1.0f))); EXPECT_OK(decoder.OnDecodingStep(2, decoding_step_proto)); } { decoding_step_proto.mutable_literal_node()->set_literal_value_index(2); EXPECT_OK(decoder.OnDecodingStep(3, decoding_step_proto)); } { auto* operator_node_proto = decoding_step_proto.mutable_operator_node(); operator_node_proto->set_operator_value_index(1); operator_node_proto->add_input_expr_indices(3); EXPECT_OK(decoder.OnDecodingStep(4, decoding_step_proto)); } { decoding_step_proto.set_output_expr_index(4); EXPECT_OK(decoder.OnDecodingStep(5, decoding_step_proto)); } auto output = std::move(decoder).Finish(); EXPECT_THAT(output.values, IsEmpty()); EXPECT_THAT(output.exprs, ElementsAre(EqualsExpr(ExprNode::UnsafeMakeOperatorNode( ExprOperatorPtr(dummy_op), {Literal(1.0f)}, ExprAttributes{TypedValue::FromValue(1.0f)})))); } TEST(DecodeTest, OperatorNode_NoMetadata) { MockValueDecoderProvider mock_value_decoder_provider; MockValueDecoder mock_value_decoder; Decoder decoder(mock_value_decoder_provider.AsStdFunction(), {.infer_attributes_for_operator_nodes = false}); DecodingStepProto decoding_step_proto; ASSERT_OK_AND_ASSIGN(ExprOperatorPtr dummy_op, LambdaOperator::Make("dummy_op", Placeholder("x"))); { decoding_step_proto.mutable_codec()->set_name("mock_codec"); EXPECT_CALL(mock_value_decoder_provider, Call("mock_codec")) .WillOnce(Return(mock_value_decoder.AsStdFunction())); EXPECT_OK(decoder.OnDecodingStep(0, decoding_step_proto)); } { decoding_step_proto.mutable_value()->set_codec_index(0); EXPECT_CALL(mock_value_decoder, Call(Ref(decoding_step_proto.value()), IsEmpty(), IsEmpty())) .WillOnce(Return(TypedValue::FromValue(dummy_op))); EXPECT_OK(decoder.OnDecodingStep(1, decoding_step_proto)); } { decoding_step_proto.mutable_value()->set_codec_index(0); EXPECT_CALL(mock_value_decoder, Call(Ref(decoding_step_proto.value()), IsEmpty(), IsEmpty())) .WillOnce(Return(TypedValue::FromValue(1.0f))); EXPECT_OK(decoder.OnDecodingStep(2, decoding_step_proto)); } { decoding_step_proto.mutable_literal_node()->set_literal_value_index(2); EXPECT_OK(decoder.OnDecodingStep(3, decoding_step_proto)); } { auto* operator_node_proto = decoding_step_proto.mutable_operator_node(); operator_node_proto->set_operator_value_index(1); operator_node_proto->add_input_expr_indices(3); EXPECT_OK(decoder.OnDecodingStep(4, decoding_step_proto)); } { decoding_step_proto.set_output_expr_index(4); EXPECT_OK(decoder.OnDecodingStep(5, decoding_step_proto)); } auto output = std::move(decoder).Finish(); EXPECT_THAT(output.values, IsEmpty()); EXPECT_THAT( output.exprs, ElementsAre(EqualsExpr(ExprNode::UnsafeMakeOperatorNode( ExprOperatorPtr(dummy_op), {Literal(1.0f)}, ExprAttributes{})))); } TEST(DecodeTest, Value) { MockValueDecoderProvider mock_value_decoder_provider; MockValueDecoder mock_value_decoder_1; MockValueDecoder mock_value_decoder_2; Decoder decoder(mock_value_decoder_provider.AsStdFunction(), {}); DecodingStepProto decoding_step_proto; { decoding_step_proto.mutable_codec()->set_name("mock_codec_1"); EXPECT_CALL(mock_value_decoder_provider, Call("mock_codec_1")) .WillOnce(Return(mock_value_decoder_1.AsStdFunction())); EXPECT_OK(decoder.OnDecodingStep(0, decoding_step_proto)); } { decoding_step_proto.mutable_codec()->set_name("mock_codec_2"); EXPECT_CALL(mock_value_decoder_provider, Call("mock_codec_2")) .WillOnce(Return(mock_value_decoder_2.AsStdFunction())); EXPECT_OK(decoder.OnDecodingStep(1, decoding_step_proto)); } { decoding_step_proto.mutable_value()->set_codec_index(0); EXPECT_CALL(mock_value_decoder_1, Call(Ref(decoding_step_proto.value()), IsEmpty(), IsEmpty())) .WillOnce(Return(TypedValue::FromValue(1.0f))); EXPECT_OK(decoder.OnDecodingStep(2, decoding_step_proto)); } { decoding_step_proto.mutable_value()->set_codec_index(0); EXPECT_CALL(mock_value_decoder_1, Call(Ref(decoding_step_proto.value()), IsEmpty(), IsEmpty())) .WillOnce(Return(TypedValue::FromValue(2.0f))); EXPECT_OK(decoder.OnDecodingStep(3, decoding_step_proto)); } { decoding_step_proto.mutable_leaf_node()->set_leaf_key("leaf_key"); EXPECT_OK(decoder.OnDecodingStep(4, decoding_step_proto)); } { decoding_step_proto.mutable_placeholder_node()->set_placeholder_key( "placeholder_key"); EXPECT_OK(decoder.OnDecodingStep(5, decoding_step_proto)); } { decoding_step_proto.mutable_value()->add_input_value_indices(2); decoding_step_proto.mutable_value()->add_input_value_indices(3); decoding_step_proto.mutable_value()->add_input_value_indices(2); decoding_step_proto.mutable_value()->add_input_expr_indices(5); decoding_step_proto.mutable_value()->add_input_expr_indices(4); decoding_step_proto.mutable_value()->add_input_expr_indices(5); decoding_step_proto.mutable_value()->add_input_expr_indices(4); decoding_step_proto.mutable_value()->set_codec_index(1); EXPECT_CALL(mock_value_decoder_2, Call(Ref(decoding_step_proto.value()), ElementsAre(TypedValueWith<float>(1.0f), TypedValueWith<float>(2.0f), TypedValueWith<float>(1.0f)), ElementsAre(EqualsExpr(Placeholder("placeholder_key")), EqualsExpr(Leaf("leaf_key")), EqualsExpr(Placeholder("placeholder_key")), EqualsExpr(Leaf("leaf_key"))))) .WillOnce(Return(TypedValue::FromValue(3.0f))); EXPECT_OK(decoder.OnDecodingStep(6, decoding_step_proto)); } { decoding_step_proto.set_output_value_index(6); EXPECT_OK(decoder.OnDecodingStep(7, decoding_step_proto)); } auto output = std::move(decoder).Finish(); EXPECT_THAT(output.values, ElementsAre(TypedValueWith<float>(3.0f))); EXPECT_THAT(output.exprs, IsEmpty()); } TEST(DecodeTest, ValueWithUnknownCodec) { MockValueDecoderProvider mock_value_decoder_provider; MockValueDecoder mock_value_decoder_1; MockValueDecoder mock_value_decoder_2; Decoder decoder(mock_value_decoder_provider.AsStdFunction(), {}); DecodingStepProto decoding_step_proto; { decoding_step_proto.mutable_codec()->set_name("mock_codec_1"); EXPECT_CALL(mock_value_decoder_provider, Call("mock_codec_1")) .WillOnce(Return(mock_value_decoder_1.AsStdFunction())); EXPECT_OK(decoder.OnDecodingStep(0, decoding_step_proto)); } { decoding_step_proto.mutable_codec()->set_name("mock_codec_2"); EXPECT_CALL(mock_value_decoder_provider, Call("mock_codec_2")) .WillOnce(Return(mock_value_decoder_2.AsStdFunction())); EXPECT_OK(decoder.OnDecodingStep(1, decoding_step_proto)); } { InSequence seq; decoding_step_proto.mutable_value(); EXPECT_CALL(mock_value_decoder_1, Call(Ref(decoding_step_proto.value()), IsEmpty(), IsEmpty())) .WillOnce(Return(NoExtensionFound{})); EXPECT_CALL(mock_value_decoder_2, Call(Ref(decoding_step_proto.value()), IsEmpty(), IsEmpty())) .WillOnce(Return(TypedValue::FromValue(1.0f))); EXPECT_OK(decoder.OnDecodingStep(2, decoding_step_proto)); } { decoding_step_proto.set_output_value_index(2); EXPECT_OK(decoder.OnDecodingStep(3, decoding_step_proto)); } auto output = std::move(decoder).Finish(); EXPECT_THAT(output.values, ElementsAre(TypedValueWith<float>(1.0f))); EXPECT_THAT(output.exprs, IsEmpty()); } TEST(DecodeTest, Error_UnexpectedDecodingStepIndex) { MockValueDecoderProvider mock_value_decoder_provider; Decoder decoder(mock_value_decoder_provider.AsStdFunction(), {}); EXPECT_THAT(decoder.OnDecodingStep(2, DecodingStepProto()), StatusIs(absl::StatusCode::kInvalidArgument, "encountered unexpected decoding_step_index=2, " "indicating missing step 0")); } TEST(DecodeTest, Error_EmptyDecodingStep) { MockValueDecoderProvider mock_value_decoder_provider; Decoder decoder(mock_value_decoder_provider.AsStdFunction(), {}); EXPECT_THAT(decoder.OnDecodingStep(0, DecodingStepProto()), StatusIs(absl::StatusCode::kInvalidArgument, "missing decoding_step.type")); } TEST(DecodeTest, Error_Codec_CodecNotFound) { MockValueDecoderProvider mock_value_decoder_provider; MockValueDecoder mock_value_decoder; Decoder decoder(mock_value_decoder_provider.AsStdFunction(), {}); DecodingStepProto decoding_step_proto; { decoding_step_proto.mutable_codec()->set_name("foo"); EXPECT_CALL(mock_value_decoder_provider, Call("foo")) .WillOnce(Return(mock_value_decoder.AsStdFunction())); EXPECT_OK(decoder.OnDecodingStep(0, decoding_step_proto)); } { decoding_step_proto.mutable_codec()->set_name("foo"); EXPECT_CALL(mock_value_decoder_provider, Call("foo")) .WillOnce(Return(absl::InvalidArgumentError("unknown codec: bar"))); EXPECT_THAT(decoder.OnDecodingStep(1, decoding_step_proto), StatusIs(absl::StatusCode::kInvalidArgument, "unknown codec: bar; decoding_step.type=CODEC")); } } TEST(DecodeTest, Error_CodecIndexCollision) { MockValueDecoderProvider mock_value_decoder_provider; MockValueDecoder mock_value_decoder; Decoder decoder(mock_value_decoder_provider.AsStdFunction(), {}); DecodingStepProto decoding_step_proto; { decoding_step_proto.mutable_codec()->set_name("foo"); EXPECT_CALL(mock_value_decoder_provider, Call("foo")) .WillOnce(Return(mock_value_decoder.AsStdFunction())); EXPECT_OK(decoder.OnDecodingStep(0, decoding_step_proto)); } { decoding_step_proto.mutable_codec()->set_name("bar"); EXPECT_CALL(mock_value_decoder_provider, Call("bar")) .WillOnce(Return(mock_value_decoder.AsStdFunction())); EXPECT_THAT( decoder.OnDecodingStep(0, decoding_step_proto), StatusIs(absl::StatusCode::kInvalidArgument, "codec_index collision")); } } TEST(DecodeTest, Error_ExprIndexCollision) { MockValueDecoderProvider mock_value_decoder_provider; Decoder decoder(mock_value_decoder_provider.AsStdFunction(), {}); DecodingStepProto decoding_step_proto; { decoding_step_proto.mutable_leaf_node()->set_leaf_key("leaf_key"); EXPECT_OK(decoder.OnDecodingStep(0, decoding_step_proto)); } { decoding_step_proto.mutable_leaf_node()->set_leaf_key("leaf_key"); EXPECT_THAT( decoder.OnDecodingStep(0, decoding_step_proto), StatusIs(absl::StatusCode::kInvalidArgument, "expr_index collision")); } } TEST(DecodeTest, Error_ValueIndexCollision) { MockValueDecoderProvider mock_value_decoder_provider; MockValueDecoder mock_value_decoder; Decoder decoder(mock_value_decoder_provider.AsStdFunction(), {}); DecodingStepProto decoding_step_proto; { decoding_step_proto.mutable_codec()->set_name("mock_codec"); EXPECT_CALL(mock_value_decoder_provider, Call("mock_codec")) .WillOnce(Return(mock_value_decoder.AsStdFunction())); EXPECT_OK(decoder.OnDecodingStep(0, decoding_step_proto)); } { decoding_step_proto.mutable_value(); EXPECT_CALL(mock_value_decoder, Call(Ref(decoding_step_proto.value()), IsEmpty(), IsEmpty())) .WillOnce(Return(TypedValue::FromValue(1.0f))); EXPECT_OK(decoder.OnDecodingStep(1, decoding_step_proto)); } { decoding_step_proto.mutable_value(); EXPECT_CALL(mock_value_decoder, Call(Ref(decoding_step_proto.value()), IsEmpty(), IsEmpty())) .WillOnce(Return(TypedValue::FromValue(1.0f))); EXPECT_THAT( decoder.OnDecodingStep(1, decoding_step_proto), StatusIs(absl::StatusCode::kInvalidArgument, "value_index collision")); } } TEST(DecodeTest, Error_LiteralNode_MissingLiteralValueIndex) { MockValueDecoderProvider mock_value_decoder_provider; Decoder decoder(mock_value_decoder_provider.AsStdFunction(), {}); DecodingStepProto decoding_step_proto; decoding_step_proto.mutable_literal_node(); EXPECT_THAT(decoder.OnDecodingStep(0, decoding_step_proto), StatusIs(absl::StatusCode::kInvalidArgument, "missing literal_node.literal_value_index; " "decoding_step.type=LITERAL_NODE")); } TEST(DecodeTest, Error_LiteralNode_IllegalLiteralValueIndex) { MockValueDecoderProvider mock_value_decoder_provider; Decoder decoder(mock_value_decoder_provider.AsStdFunction(), {}); DecodingStepProto decoding_step_proto; decoding_step_proto.mutable_literal_node()->set_literal_value_index(100); EXPECT_THAT(decoder.OnDecodingStep(0, decoding_step_proto), StatusIs(absl::StatusCode::kInvalidArgument, "value_index is out of range: 100; " "decoding_step.type=LITERAL_NODE")); } TEST(DecodeTest, Error_LiteralNode_LiteralValueIndexPointsToExpr) { MockValueDecoderProvider mock_value_decoder_provider; Decoder decoder(mock_value_decoder_provider.AsStdFunction(), {}); DecodingStepProto decoding_step_proto; { decoding_step_proto.mutable_leaf_node()->set_leaf_key("leaf_key"); EXPECT_OK(decoder.OnDecodingStep(0, decoding_step_proto)); } { decoding_step_proto.mutable_literal_node()->set_literal_value_index(1); EXPECT_THAT(decoder.OnDecodingStep(1, decoding_step_proto), StatusIs(absl::StatusCode::kInvalidArgument, "found no value in decoding_step_results[1]; " "decoding_step.type=LITERAL_NODE")); } } TEST(DecodeTest, Error_LeafNode_MissingLeafKey) { MockValueDecoderProvider mock_value_decoder_provider; Decoder decoder(mock_value_decoder_provider.AsStdFunction(), {}); DecodingStepProto decoding_step_proto; decoding_step_proto.mutable_leaf_node(); EXPECT_THAT(decoder.OnDecodingStep(0, decoding_step_proto), StatusIs(absl::StatusCode::kInvalidArgument, "missing leaf_node.leaf_key; " "decoding_step.type=LEAF_NODE")); } TEST(DecodeTest, Error_PlaceholderNode_MissingPlaceholderKey) { MockValueDecoderProvider mock_value_decoder_provider; Decoder decoder(mock_value_decoder_provider.AsStdFunction(), {}); DecodingStepProto decoding_step_proto; decoding_step_proto.mutable_placeholder_node(); EXPECT_THAT(decoder.OnDecodingStep(0, decoding_step_proto), StatusIs(absl::StatusCode::kInvalidArgument, "missing placeholder_node.placeholder_key; " "decoding_step.type=PLACEHOLDER_NODE")); } TEST(DecodeTest, Error_OperatorNode_MissingOperatorValueIndex) { MockValueDecoderProvider mock_value_decoder_provider; Decoder decoder(mock_value_decoder_provider.AsStdFunction(), {}); DecodingStepProto decoding_step_proto; decoding_step_proto.mutable_operator_node(); EXPECT_THAT(decoder.OnDecodingStep(0, decoding_step_proto), StatusIs(absl::StatusCode::kInvalidArgument, "missing operator_node.operator_value_index; " "decoding_step.type=OPERATOR_NODE")); } TEST(DecodeTest, Error_OperatorNode_IllegalOperatorValueIndex) { MockValueDecoderProvider mock_value_decoder_provider; Decoder decoder(mock_value_decoder_provider.AsStdFunction(), {}); DecodingStepProto decoding_step_proto; decoding_step_proto.mutable_operator_node()->set_operator_value_index(100); EXPECT_THAT(decoder.OnDecodingStep(0, decoding_step_proto), StatusIs(absl::StatusCode::kInvalidArgument, "value_index is out of range: 100; " "decoding_step.type=OPERATOR_NODE")); } TEST(DecodeTest, Error_OperatorNode_OperatorValueIndexPointsToFloat32) { MockValueDecoderProvider mock_value_decoder_provider; MockValueDecoder mock_value_decoder; Decoder decoder(mock_value_decoder_provider.AsStdFunction(), {}); DecodingStepProto decoding_step_proto; { decoding_step_proto.mutable_codec()->set_name("mock_codec"); EXPECT_CALL(mock_value_decoder_provider, Call("mock_codec")) .WillOnce(Return(mock_value_decoder.AsStdFunction())); EXPECT_OK(decoder.OnDecodingStep(0, decoding_step_proto)); } { decoding_step_proto.mutable_value()->set_codec_index(0); EXPECT_CALL(mock_value_decoder, Call(Ref(decoding_step_proto.value()), IsEmpty(), IsEmpty())) .WillOnce(Return(TypedValue::FromValue(1.0f))); EXPECT_OK(decoder.OnDecodingStep(1, decoding_step_proto)); } { decoding_step_proto.mutable_operator_node()->set_operator_value_index(1); EXPECT_THAT( decoder.OnDecodingStep(2, decoding_step_proto), StatusIs( absl::StatusCode::kInvalidArgument, "expected an operator in decoding_step_results[1], got FLOAT32; " "decoding_step.type=OPERATOR_NODE")); } } TEST(DecodeTest, Error_OperatorNode_IllegalInputExprIndex) { MockValueDecoderProvider mock_value_decoder_provider; MockValueDecoder mock_value_decoder; Decoder decoder(mock_value_decoder_provider.AsStdFunction(), {}); DecodingStepProto decoding_step_proto; ASSERT_OK_AND_ASSIGN(ExprOperatorPtr dummy_op, LambdaOperator::Make("dummy_op", Placeholder("x"))); { decoding_step_proto.mutable_codec()->set_name("mock_codec"); EXPECT_CALL(mock_value_decoder_provider, Call("mock_codec")) .WillOnce(Return(mock_value_decoder.AsStdFunction())); EXPECT_OK(decoder.OnDecodingStep(0, decoding_step_proto)); } { decoding_step_proto.mutable_value()->set_codec_index(0); EXPECT_CALL(mock_value_decoder, Call(Ref(decoding_step_proto.value()), IsEmpty(), IsEmpty())) .WillOnce(Return(TypedValue::FromValue(dummy_op))); EXPECT_OK(decoder.OnDecodingStep(1, decoding_step_proto)); } { auto* operator_node_proto = decoding_step_proto.mutable_operator_node(); operator_node_proto->set_operator_value_index(1); operator_node_proto->add_input_expr_indices(100); EXPECT_THAT(decoder.OnDecodingStep(2, decoding_step_proto), StatusIs(absl::StatusCode::kInvalidArgument, "expr_index is out of range: 100; " "decoding_step.type=OPERATOR_NODE")); } } TEST(DecodeTest, Error_OperatorNode_InvalidDepCount) { MockValueDecoderProvider mock_value_decoder_provider; MockValueDecoder mock_value_decoder; Decoder decoder(mock_value_decoder_provider.AsStdFunction(), {}); DecodingStepProto decoding_step_proto; ASSERT_OK_AND_ASSIGN(ExprOperatorPtr dummy_op, LambdaOperator::Make("dummy_op", Placeholder("x"))); { decoding_step_proto.mutable_codec()->set_name("mock_codec"); EXPECT_CALL(mock_value_decoder_provider, Call("mock_codec")) .WillOnce(Return(mock_value_decoder.AsStdFunction())); EXPECT_OK(decoder.OnDecodingStep(0, decoding_step_proto)); } { decoding_step_proto.mutable_value()->set_codec_index(0); EXPECT_CALL(mock_value_decoder, Call(Ref(decoding_step_proto.value()), IsEmpty(), IsEmpty())) .WillOnce(Return(TypedValue::FromValue(dummy_op))); EXPECT_OK(decoder.OnDecodingStep(1, decoding_step_proto)); } { decoding_step_proto.mutable_leaf_node()->set_leaf_key("leaf_key"); EXPECT_OK(decoder.OnDecodingStep(2, decoding_step_proto)); } { auto* operator_node_proto = decoding_step_proto.mutable_operator_node(); operator_node_proto->set_operator_value_index(1); operator_node_proto->add_input_expr_indices(2); operator_node_proto->add_input_expr_indices(2); EXPECT_THAT( decoder.OnDecodingStep(2, decoding_step_proto), StatusIs(absl::StatusCode::kInvalidArgument, "incorrect number of dependencies passed to an " "operator node: expected 1 but got 2; " "while calling dummy_op with args {L.leaf_key, L.leaf_key}; " "decoding_step.type=OPERATOR_NODE")); } } TEST(DecodeTest, Error_Value_IllegalInputValueIndex) { MockValueDecoderProvider mock_value_decoder_provider; MockValueDecoder mock_value_decoder; Decoder decoder(mock_value_decoder_provider.AsStdFunction(), {}); DecodingStepProto decoding_step_proto; { decoding_step_proto.mutable_codec()->set_name("mock_codec"); EXPECT_CALL(mock_value_decoder_provider, Call("mock_codec")) .WillOnce(Return(mock_value_decoder.AsStdFunction())); EXPECT_OK(decoder.OnDecodingStep(0, decoding_step_proto)); } { auto* value_proto = decoding_step_proto.mutable_value(); value_proto->set_codec_index(0); value_proto->add_input_value_indices(100); EXPECT_THAT(decoder.OnDecodingStep(1, decoding_step_proto), StatusIs(absl::StatusCode::kInvalidArgument, "value_index is out of range: 100; " "decoding_step.type=VALUE")); } } TEST(DecodeTest, Error_Value_IllegalInputExprIndex) { MockValueDecoderProvider mock_value_decoder_provider; MockValueDecoder mock_value_decoder; Decoder decoder(mock_value_decoder_provider.AsStdFunction(), {}); DecodingStepProto decoding_step_proto; { decoding_step_proto.mutable_codec()->set_name("mock_codec"); EXPECT_CALL(mock_value_decoder_provider, Call("mock_codec")) .WillOnce(Return(mock_value_decoder.AsStdFunction())); EXPECT_OK(decoder.OnDecodingStep(0, decoding_step_proto)); } { auto* value_proto = decoding_step_proto.mutable_value(); value_proto->set_codec_index(0); value_proto->add_input_expr_indices(100); EXPECT_THAT(decoder.OnDecodingStep(1, decoding_step_proto), StatusIs(absl::StatusCode::kInvalidArgument, "expr_index is out of range: 100; " "decoding_step.type=VALUE")); } } TEST(DecodeTest, Error_Value_IllegalCodecIndex) { MockValueDecoderProvider mock_value_decoder_provider; Decoder decoder(mock_value_decoder_provider.AsStdFunction(), {}); DecodingStepProto decoding_step_proto; decoding_step_proto.mutable_value()->set_codec_index(100); EXPECT_THAT(decoder.OnDecodingStep(0, decoding_step_proto), StatusIs(absl::StatusCode::kInvalidArgument, "codec_index is out of range: 100; " "decoding_step.type=VALUE")); } TEST(DecodeTest, Error_Value_InvalidCodecIndex) { MockValueDecoderProvider mock_value_decoder_provider; Decoder decoder(mock_value_decoder_provider.AsStdFunction(), {}); DecodingStepProto decoding_step_proto; { decoding_step_proto.mutable_leaf_node()->set_leaf_key("leaf_key"); EXPECT_OK(decoder.OnDecodingStep(0, decoding_step_proto)); } { decoding_step_proto.mutable_value()->set_codec_index(0); EXPECT_THAT(decoder.OnDecodingStep(0, decoding_step_proto), StatusIs(absl::StatusCode::kInvalidArgument, "found no codec in decoding_step_results[0]; " "decoding_step.type=VALUE")); } } TEST(DecodeTest, Error_Value_CodecFailed) { MockValueDecoderProvider mock_value_decoder_provider; MockValueDecoder mock_value_decoder; Decoder decoder(mock_value_decoder_provider.AsStdFunction(), {}); DecodingStepProto decoding_step_proto; { decoding_step_proto.mutable_codec()->set_name("mock_codec"); EXPECT_CALL(mock_value_decoder_provider, Call("mock_codec")) .WillOnce(Return(mock_value_decoder.AsStdFunction())); EXPECT_OK(decoder.OnDecodingStep(0, decoding_step_proto)); } { decoding_step_proto.mutable_value()->set_codec_index(0); EXPECT_CALL(mock_value_decoder, Call(Ref(decoding_step_proto.value()), IsEmpty(), IsEmpty())) .WillOnce(Return(absl::UnimplementedError("codec error"))); EXPECT_THAT(decoder.OnDecodingStep(1, decoding_step_proto), StatusIs(absl::StatusCode::kUnimplemented, "codec error; codecs[0]=mock_codec; " "decoding_step.type=VALUE")); } } TEST(DecodeTest, Error_Value_NoExtensionFound) { MockValueDecoderProvider mock_value_decoder_provider; MockValueDecoder mock_value_decoder; Decoder decoder(mock_value_decoder_provider.AsStdFunction(), {}); DecodingStepProto decoding_step_proto; { decoding_step_proto.mutable_codec()->set_name("mock_codec"); EXPECT_CALL(mock_value_decoder_provider, Call("mock_codec")) .WillOnce(Return(mock_value_decoder.AsStdFunction())); EXPECT_OK(decoder.OnDecodingStep(0, decoding_step_proto)); } { decoding_step_proto.mutable_value()->set_codec_index(0); EXPECT_CALL(mock_value_decoder, Call(Ref(decoding_step_proto.value()), IsEmpty(), IsEmpty())) .WillOnce(Return(NoExtensionFound{})); EXPECT_THAT(decoder.OnDecodingStep(1, decoding_step_proto), StatusIs(absl::StatusCode::kNotFound, "no extension found; codecs[0]=mock_codec; " "decoding_step.type=VALUE")); } } TEST(DecodeTest, Error_ValueWithUnknownCodec_CodecFailed) { MockValueDecoderProvider mock_value_decoder_provider; MockValueDecoder mock_value_decoder; Decoder decoder(mock_value_decoder_provider.AsStdFunction(), {}); DecodingStepProto decoding_step_proto; { decoding_step_proto.mutable_codec()->set_name("mock_codec"); EXPECT_CALL(mock_value_decoder_provider, Call("mock_codec")) .WillOnce(Return(mock_value_decoder.AsStdFunction())); EXPECT_OK(decoder.OnDecodingStep(0, decoding_step_proto)); } { decoding_step_proto.mutable_value(); EXPECT_CALL(mock_value_decoder, Call(Ref(decoding_step_proto.value()), IsEmpty(), IsEmpty())) .WillOnce(Return(absl::UnimplementedError("codec error"))); EXPECT_THAT(decoder.OnDecodingStep(1, decoding_step_proto), StatusIs(absl::StatusCode::kUnimplemented, "codec error; detected_codec=mock_codec; " "decoding_step.type=VALUE")); } } TEST(DecodeTest, Error_ValueWithUnknownCodec_CodecUndetected) { MockValueDecoderProvider mock_value_decoder_provider; MockValueDecoder mock_value_decoder; Decoder decoder(mock_value_decoder_provider.AsStdFunction(), {}); DecodingStepProto decoding_step_proto; { decoding_step_proto.mutable_codec()->set_name("mock_codec"); EXPECT_CALL(mock_value_decoder_provider, Call("mock_codec")) .WillOnce(Return(mock_value_decoder.AsStdFunction())); EXPECT_OK(decoder.OnDecodingStep(0, decoding_step_proto)); } { decoding_step_proto.mutable_value(); EXPECT_CALL(mock_value_decoder, Call(Ref(decoding_step_proto.value()), IsEmpty(), IsEmpty())) .WillOnce(Return(NoExtensionFound{})); EXPECT_THAT(decoder.OnDecodingStep(1, decoding_step_proto), StatusIs(absl::StatusCode::kInvalidArgument, "unable to detect codec; decoding_step.type=VALUE")); } } TEST(DecodeTest, Error_Output_IllegalOutputValueIndex) { MockValueDecoderProvider mock_value_decoder_provider; Decoder decoder(mock_value_decoder_provider.AsStdFunction(), {}); DecodingStepProto decoding_step_proto; decoding_step_proto.set_output_value_index(100); EXPECT_THAT(decoder.OnDecodingStep(0, decoding_step_proto), StatusIs(absl::StatusCode::kInvalidArgument, "value_index is out of range: 100; " "decoding_step.type=OUTPUT_VALUE_INDEX")); } TEST(DecodeTest, Error_Output_InvalidOutputValueIndex) { MockValueDecoderProvider mock_value_decoder_provider; MockValueDecoder mock_value_decoder; Decoder decoder(mock_value_decoder_provider.AsStdFunction(), {}); DecodingStepProto decoding_step_proto; { decoding_step_proto.mutable_codec()->set_name("mock_codec"); EXPECT_CALL(mock_value_decoder_provider, Call("mock_codec")) .WillOnce(Return(mock_value_decoder.AsStdFunction())); EXPECT_OK(decoder.OnDecodingStep(0, decoding_step_proto)); } { decoding_step_proto.set_output_value_index(0); EXPECT_THAT(decoder.OnDecodingStep(0, decoding_step_proto), StatusIs(absl::StatusCode::kInvalidArgument, "found no value in decoding_step_results[0]; " "decoding_step.type=OUTPUT_VALUE_INDEX")); } } TEST(DecodeTest, Error_Output_IllegalOutputExprIndex) { MockValueDecoderProvider mock_value_decoder_provider; Decoder decoder(mock_value_decoder_provider.AsStdFunction(), {}); DecodingStepProto decoding_step_proto; decoding_step_proto.set_output_expr_index(100); EXPECT_THAT(decoder.OnDecodingStep(0, decoding_step_proto), StatusIs(absl::StatusCode::kInvalidArgument, "expr_index is out of range: 100; " "decoding_step.type=OUTPUT_EXPR_INDEX")); } TEST(DecodeTest, Error_Output_InvalidOutputExprIndex) { MockValueDecoderProvider mock_value_decoder_provider; MockValueDecoder mock_value_decoder; Decoder decoder(mock_value_decoder_provider.AsStdFunction(), {}); DecodingStepProto decoding_step_proto; { decoding_step_proto.mutable_codec()->set_name("mock_codec"); EXPECT_CALL(mock_value_decoder_provider, Call("mock_codec")) .WillOnce(Return(mock_value_decoder.AsStdFunction())); EXPECT_OK(decoder.OnDecodingStep(0, decoding_step_proto)); } { decoding_step_proto.set_output_expr_index(0); EXPECT_THAT(decoder.OnDecodingStep(0, decoding_step_proto), StatusIs(absl::StatusCode::kInvalidArgument, "found no expression in decoding_step_results[0]; " "decoding_step.type=OUTPUT_EXPR_INDEX")); } } } }
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/serialization_base/decoder.cc
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/serialization_base/decoder_test.cc
1ca990dbeca224035efdabffecc7f3738df6b52c
2c5c241f-6b4e-4542-923d-597b8b85217c
cpp
google/arolla
container_proto
arolla/serialization_base/container_proto.cc
arolla/serialization_base/container_proto_test.cc
#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) { *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 "absl/status/status_matchers.h" #include "arolla/serialization_base/base.pb.h" #include "arolla/serialization_base/container.h" #include "arolla/util/testing/equals_proto.h" #include "arolla/util/status_macros_backport.h" namespace arolla::serialization_base { namespace { using ::absl_testing::IsOkAndHolds; using ::absl_testing::StatusIs; using ::arolla::testing::EqualsProto; 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(1)); } { DecodingStepProto decoding_step_proto; decoding_step_proto.set_output_expr_index(1); ASSERT_THAT(container_builder.Add(std::move(decoding_step_proto)), IsOkAndHolds(2)); } { DecodingStepProto decoding_step_proto; decoding_step_proto.mutable_codec()->set_name("codec2"); ASSERT_THAT(container_builder.Add(std::move(decoding_step_proto)), IsOkAndHolds(3)); } { 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(4)); } { DecodingStepProto decoding_step_proto; decoding_step_proto.set_output_expr_index(4); ASSERT_THAT(container_builder.Add(std::move(decoding_step_proto)), IsOkAndHolds(5)); } { DecodingStepProto decoding_step_proto; decoding_step_proto.mutable_value(); ASSERT_THAT(container_builder.Add(std::move(decoding_step_proto)), IsOkAndHolds(6)); } { DecodingStepProto decoding_step_proto; decoding_step_proto.set_output_value_index(6); ASSERT_THAT(container_builder.Add(std::move(decoding_step_proto)), IsOkAndHolds(7)); } EXPECT_TRUE(EqualsProto( std::move(container_builder).Finish(), R"pb( version: 2 decoding_steps { codec { name: "codec1" } } decoding_steps { leaf_node { leaf_key: "key1" } } decoding_steps { output_expr_index: 1 } decoding_steps { codec { name: "codec2" } } decoding_steps { placeholder_node { placeholder_key: "key2" } } decoding_steps { output_expr_index: 4 } decoding_steps { value {} } decoding_steps { output_value_index: 6 } )pb")); } class MockContainerProcessor : public ContainerProcessor { public: MOCK_METHOD(absl::Status, OnDecodingStep, (uint64_t, const DecodingStepProto& decoding_step_proto), (override)); }; TEST(ProcessContainerProto, V1Behaviour) { 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, V2Behaviour) { ContainerProto container_proto; container_proto.set_version(2); container_proto.add_decoding_steps()->mutable_codec()->set_name("codec1"); container_proto.add_decoding_steps()->mutable_leaf_node()->set_leaf_key( "key1"); container_proto.add_decoding_steps()->set_output_expr_index(1); container_proto.add_decoding_steps()->mutable_codec()->set_name("codec2"); container_proto.add_decoding_steps() ->mutable_placeholder_node() ->set_placeholder_key("key2"); container_proto.add_decoding_steps()->set_output_expr_index(4); container_proto.add_decoding_steps()->mutable_value(); container_proto.add_decoding_steps()->set_output_value_index(6); 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(leaf_node: { leaf_key: "key1" })pb"))); EXPECT_CALL(mock_container_processor, OnDecodingStep(2, EqualsProto(R"pb(output_expr_index: 1)pb"))); EXPECT_CALL( mock_container_processor, OnDecodingStep(3, EqualsProto(R"pb(codec: { name: "codec2" })pb"))); EXPECT_CALL(mock_container_processor, OnDecodingStep(4, EqualsProto(R"pb(placeholder_node: { placeholder_key: "key2" })pb"))); EXPECT_CALL(mock_container_processor, OnDecodingStep(5, EqualsProto(R"pb(output_expr_index: 4)pb"))); EXPECT_CALL(mock_container_processor, OnDecodingStep(6, EqualsProto(R"pb(value: {})pb"))); EXPECT_CALL(mock_container_processor, OnDecodingStep(7, EqualsProto(R"pb(output_value_index: 6)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]"))); } } }
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/serialization_base/container_proto.cc
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/serialization_base/container_proto_test.cc
1ca990dbeca224035efdabffecc7f3738df6b52c
45ed9816-f665-43c8-84d3-daee2ca567a2
cpp
google/arolla
py_object_ptr_impl
py/arolla/py_utils/py_object_ptr_impl.h
py/arolla/py_utils/py_object_ptr_impl_test.cc
#ifndef THIRD_PARTY_PY_AROLLA_PY_UTILS_PY_OBJECT_PTR_IMPL_H_ #define THIRD_PARTY_PY_AROLLA_PY_UTILS_PY_OBJECT_PTR_IMPL_H_ #include <Python.h> #include <cstddef> #include <utility> #include "absl/base/attributes.h" namespace arolla::python::py_object_ptr_impl_internal { template <typename SelfType, typename Traits> class BasePyObjectPtr { using GILGuardType = typename Traits::GILGuardType; using PyObjectType = typename Traits::PyObjectType; ABSL_ATTRIBUTE_ALWAYS_INLINE static void inc_ref(PyObjectType* ptr) { Traits().inc_ref(ptr); } ABSL_ATTRIBUTE_ALWAYS_INLINE static void dec_ref(PyObjectType* ptr) { Traits().dec_ref(ptr); } public: [[nodiscard]] static SelfType Own(PyObjectType* ptr) { SelfType result; result.ptr_ = ptr; return result; } [[nodiscard]] static SelfType NewRef(PyObjectType* ptr) { SelfType result; if (ptr != nullptr) { GILGuardType gil_guard; result.ptr_ = ptr; inc_ref(result.ptr_); } return result; } BasePyObjectPtr() = default; ~BasePyObjectPtr() { reset(); } BasePyObjectPtr(const BasePyObjectPtr& other) { if (other.ptr_ != nullptr) { GILGuardType gil_guard; ptr_ = other.ptr_; inc_ref(ptr_); } } BasePyObjectPtr& operator=(const BasePyObjectPtr& other) { if (ptr_ != other.ptr_) { GILGuardType gil_guard; PyObjectType* old_ptr = std::exchange(ptr_, other.ptr_); if (ptr_ != nullptr) { inc_ref(ptr_); } if (old_ptr != nullptr) { dec_ref(old_ptr); } } return *this; } BasePyObjectPtr(BasePyObjectPtr&& other) : ptr_(other.release()) {} BasePyObjectPtr& operator=(BasePyObjectPtr&& other) { PyObjectType* old_ptr = std::exchange(ptr_, other.release()); if (old_ptr != nullptr) { GILGuardType gil_guard; dec_ref(old_ptr); } return *this; } [[nodiscard]] PyObjectType* get() const { return ptr_; } bool operator==(std::nullptr_t) const { return ptr_ == nullptr; } bool operator!=(std::nullptr_t) const { return ptr_ != nullptr; } [[nodiscard]] PyObjectType* release() { return std::exchange(ptr_, nullptr); } void reset() { if (PyObjectType* old_ptr = release()) { GILGuardType gil_guard; dec_ref(old_ptr); } } private: PyObjectType* ptr_ = nullptr; }; } #endif
#include "py/arolla/py_utils/py_object_ptr_impl.h" #include <Python.h> #include <utility> #include "gtest/gtest.h" namespace arolla::python::py_object_ptr_impl_internal::testing { namespace { struct DummyGILGuard { static int active; static int total; static void reset() { active = 0; total = 0; } DummyGILGuard() { ++active; ++total; } ~DummyGILGuard() { --active; } DummyGILGuard(const DummyGILGuard&) = delete; DummyGILGuard& operator=(const DummyGILGuard&) = delete; }; int DummyGILGuard::active; int DummyGILGuard::total; struct DummyPyObject { int ref_counter = {1}; }; struct DummyTraits { using GILGuardType = DummyGILGuard; using PyObjectType = DummyPyObject; void inc_ref(PyObjectType* ptr) { ++ptr->ref_counter; } void dec_ref(PyObjectType* ptr) { --ptr->ref_counter; } }; class DummyPyObjectPtr final : public BasePyObjectPtr<DummyPyObjectPtr, DummyTraits> { public: DummyPyObjectPtr() = default; DummyPyObjectPtr(const DummyPyObjectPtr&) = default; DummyPyObjectPtr& operator=(const DummyPyObjectPtr&) = default; DummyPyObjectPtr(DummyPyObjectPtr&&) = default; DummyPyObjectPtr& operator=(DummyPyObjectPtr&&) = default; }; class BasePyObjectPtrTest : public ::testing::Test { protected: void SetUp() override { DummyGILGuard::reset(); } }; TEST_F(BasePyObjectPtrTest, OwnFactoryNull) { { auto ptr = DummyPyObjectPtr::Own(nullptr); ASSERT_EQ(ptr.get(), nullptr); ASSERT_EQ(DummyGILGuard::active, 0); ASSERT_EQ(DummyGILGuard::total, 0); } ASSERT_EQ(DummyGILGuard::active, 0); ASSERT_EQ(DummyGILGuard::total, 0); } TEST_F(BasePyObjectPtrTest, OwnNullFactory) { DummyPyObject obj; { auto ptr = DummyPyObjectPtr::Own(&obj); ASSERT_EQ(ptr.get(), &obj); ASSERT_EQ(obj.ref_counter, 1); ASSERT_EQ(DummyGILGuard::active, 0); ASSERT_EQ(DummyGILGuard::total, 0); } ASSERT_EQ(obj.ref_counter, 0); ASSERT_EQ(DummyGILGuard::active, 0); ASSERT_EQ(DummyGILGuard::total, 1); } TEST_F(BasePyObjectPtrTest, NewRefNullFactory) { { auto ptr = DummyPyObjectPtr::NewRef(nullptr); ASSERT_EQ(ptr.get(), nullptr); ASSERT_EQ(DummyGILGuard::active, 0); ASSERT_EQ(DummyGILGuard::total, 0); } ASSERT_EQ(DummyGILGuard::active, 0); ASSERT_EQ(DummyGILGuard::total, 0); } TEST_F(BasePyObjectPtrTest, NewRefFactory) { DummyPyObject obj; { auto ptr = DummyPyObjectPtr::NewRef(&obj); ASSERT_EQ(ptr.get(), &obj); ASSERT_EQ(obj.ref_counter, 2); ASSERT_EQ(DummyGILGuard::active, 0); ASSERT_EQ(DummyGILGuard::total, 1); } ASSERT_EQ(obj.ref_counter, 1); ASSERT_EQ(DummyGILGuard::active, 0); ASSERT_EQ(DummyGILGuard::total, 2); } TEST_F(BasePyObjectPtrTest, DefaultCtor) { { DummyPyObjectPtr ptr; ASSERT_EQ(ptr.get(), nullptr); ASSERT_EQ(DummyGILGuard::active, 0); ASSERT_EQ(DummyGILGuard::total, 0); } ASSERT_EQ(DummyGILGuard::active, 0); ASSERT_EQ(DummyGILGuard::total, 0); } TEST_F(BasePyObjectPtrTest, CopyNullCtor) { { DummyPyObjectPtr ptr1; DummyPyObjectPtr ptr2 = ptr1; ASSERT_EQ(ptr1.get(), nullptr); ASSERT_EQ(ptr2.get(), nullptr); ASSERT_EQ(DummyGILGuard::active, 0); ASSERT_EQ(DummyGILGuard::total, 0); } ASSERT_EQ(DummyGILGuard::active, 0); ASSERT_EQ(DummyGILGuard::total, 0); } TEST_F(BasePyObjectPtrTest, CopyCtor) { DummyPyObject obj; { DummyPyObjectPtr ptr1 = DummyPyObjectPtr::Own(&obj); DummyPyObjectPtr ptr2 = ptr1; ASSERT_EQ(ptr1.get(), &obj); ASSERT_EQ(ptr2.get(), &obj); ASSERT_EQ(obj.ref_counter, 2); ASSERT_EQ(DummyGILGuard::active, 0); ASSERT_EQ(DummyGILGuard::total, 1); } ASSERT_EQ(obj.ref_counter, 0); ASSERT_EQ(DummyGILGuard::active, 0); ASSERT_EQ(DummyGILGuard::total, 3); } TEST_F(BasePyObjectPtrTest, MoveNullCtor) { { DummyPyObjectPtr ptr1; DummyPyObjectPtr ptr2 = std::move(ptr1); ASSERT_EQ(ptr1.get(), nullptr); ASSERT_EQ(ptr2.get(), nullptr); ASSERT_EQ(DummyGILGuard::active, 0); ASSERT_EQ(DummyGILGuard::total, 0); } ASSERT_EQ(DummyGILGuard::active, 0); ASSERT_EQ(DummyGILGuard::total, 0); } TEST_F(BasePyObjectPtrTest, MoveCtor) { DummyPyObject obj; { DummyPyObjectPtr ptr1 = DummyPyObjectPtr::Own(&obj); DummyPyObjectPtr ptr2 = std::move(ptr1); ASSERT_EQ(ptr1.get(), nullptr); ASSERT_EQ(ptr2.get(), &obj); ASSERT_EQ(obj.ref_counter, 1); ASSERT_EQ(DummyGILGuard::active, 0); ASSERT_EQ(DummyGILGuard::total, 0); } ASSERT_EQ(obj.ref_counter, 0); ASSERT_EQ(DummyGILGuard::active, 0); ASSERT_EQ(DummyGILGuard::total, 1); } TEST_F(BasePyObjectPtrTest, CopyOp_Null_Null) { { DummyPyObjectPtr ptr1; DummyPyObjectPtr ptr2; ptr1 = ptr2; ASSERT_EQ(ptr1.get(), nullptr); ASSERT_EQ(ptr2.get(), nullptr); ASSERT_EQ(DummyGILGuard::active, 0); ASSERT_EQ(DummyGILGuard::total, 0); } ASSERT_EQ(DummyGILGuard::active, 0); ASSERT_EQ(DummyGILGuard::total, 0); } TEST_F(BasePyObjectPtrTest, CopyOp_Null_Obj) { DummyPyObject obj; { DummyPyObjectPtr ptr1; DummyPyObjectPtr ptr2 = DummyPyObjectPtr::Own(&obj); ptr1 = ptr2; ASSERT_EQ(ptr1.get(), &obj); ASSERT_EQ(ptr2.get(), &obj); ASSERT_EQ(obj.ref_counter, 2); ASSERT_EQ(DummyGILGuard::active, 0); ASSERT_EQ(DummyGILGuard::total, 1); } ASSERT_EQ(obj.ref_counter, 0); ASSERT_EQ(DummyGILGuard::active, 0); ASSERT_EQ(DummyGILGuard::total, 3); } TEST_F(BasePyObjectPtrTest, CopyOp_Obj_Null) { DummyPyObject obj; { DummyPyObjectPtr ptr1 = DummyPyObjectPtr::Own(&obj); DummyPyObjectPtr ptr2; ptr1 = ptr2; ASSERT_EQ(ptr1.get(), nullptr); ASSERT_EQ(ptr2.get(), nullptr); ASSERT_EQ(obj.ref_counter, 0); ASSERT_EQ(DummyGILGuard::active, 0); ASSERT_EQ(DummyGILGuard::total, 1); } ASSERT_EQ(obj.ref_counter, 0); ASSERT_EQ(DummyGILGuard::active, 0); ASSERT_EQ(DummyGILGuard::total, 1); } TEST_F(BasePyObjectPtrTest, CopyOp_Obj1_Obj1) { DummyPyObject obj1; { DummyPyObjectPtr ptr1 = DummyPyObjectPtr::Own(&obj1); DummyPyObjectPtr ptr2 = DummyPyObjectPtr::NewRef( &obj1); ptr1 = ptr2; ASSERT_EQ(ptr1.get(), &obj1); ASSERT_EQ(ptr2.get(), &obj1); ASSERT_EQ(obj1.ref_counter, 2); ASSERT_EQ(DummyGILGuard::active, 0); ASSERT_EQ(DummyGILGuard::total, 1); } ASSERT_EQ(obj1.ref_counter, 0); ASSERT_EQ(DummyGILGuard::active, 0); ASSERT_EQ(DummyGILGuard::total, 3); } TEST_F(BasePyObjectPtrTest, CopyOp_Obj1_Obj2) { DummyPyObject obj1; DummyPyObject obj2; { DummyPyObjectPtr ptr1 = DummyPyObjectPtr::Own(&obj1); DummyPyObjectPtr ptr2 = DummyPyObjectPtr::Own(&obj2); ptr1 = ptr2; ASSERT_EQ(ptr1.get(), &obj2); ASSERT_EQ(ptr2.get(), &obj2); ASSERT_EQ(obj1.ref_counter, 0); ASSERT_EQ(obj2.ref_counter, 2); ASSERT_EQ(DummyGILGuard::active, 0); ASSERT_EQ(DummyGILGuard::total, 1); } ASSERT_EQ(obj1.ref_counter, 0); ASSERT_EQ(obj2.ref_counter, 0); ASSERT_EQ(DummyGILGuard::active, 0); ASSERT_EQ(DummyGILGuard::total, 3); } TEST_F(BasePyObjectPtrTest, MoveOp_Null_Null) { { DummyPyObjectPtr ptr1; DummyPyObjectPtr ptr2; ptr1 = std::move(ptr2); ASSERT_EQ(ptr1.get(), nullptr); ASSERT_EQ(ptr2.get(), nullptr); ASSERT_EQ(DummyGILGuard::active, 0); ASSERT_EQ(DummyGILGuard::total, 0); } ASSERT_EQ(DummyGILGuard::active, 0); ASSERT_EQ(DummyGILGuard::total, 0); } TEST_F(BasePyObjectPtrTest, MoveOp_Null_Obj) { DummyPyObject obj; { DummyPyObjectPtr ptr1; DummyPyObjectPtr ptr2 = DummyPyObjectPtr::Own(&obj); ptr1 = std::move(ptr2); ASSERT_EQ(ptr1.get(), &obj); ASSERT_EQ(ptr2.get(), nullptr); ASSERT_EQ(obj.ref_counter, 1); ASSERT_EQ(DummyGILGuard::active, 0); ASSERT_EQ(DummyGILGuard::total, 0); } ASSERT_EQ(obj.ref_counter, 0); ASSERT_EQ(DummyGILGuard::active, 0); ASSERT_EQ(DummyGILGuard::total, 1); } TEST_F(BasePyObjectPtrTest, MoveOp_Obj_Null) { DummyPyObject obj; { DummyPyObjectPtr ptr1 = DummyPyObjectPtr::Own(&obj); DummyPyObjectPtr ptr2; ptr1 = std::move(ptr2); ASSERT_EQ(ptr1.get(), nullptr); ASSERT_EQ(ptr2.get(), nullptr); ASSERT_EQ(obj.ref_counter, 0); ASSERT_EQ(DummyGILGuard::active, 0); ASSERT_EQ(DummyGILGuard::total, 1); } ASSERT_EQ(obj.ref_counter, 0); ASSERT_EQ(DummyGILGuard::active, 0); ASSERT_EQ(DummyGILGuard::total, 1); } TEST_F(BasePyObjectPtrTest, MoveOp_Obj1_Obj1) { DummyPyObject obj1; { DummyPyObjectPtr ptr1 = DummyPyObjectPtr::Own(&obj1); DummyPyObjectPtr ptr2 = DummyPyObjectPtr::NewRef( &obj1); ptr1 = std::move(ptr2); ASSERT_EQ(ptr1.get(), &obj1); ASSERT_EQ(ptr2.get(), nullptr); ASSERT_EQ(obj1.ref_counter, 1); ASSERT_EQ(DummyGILGuard::active, 0); ASSERT_EQ(DummyGILGuard::total, 2); } ASSERT_EQ(obj1.ref_counter, 0); ASSERT_EQ(DummyGILGuard::active, 0); ASSERT_EQ(DummyGILGuard::total, 3); } TEST_F(BasePyObjectPtrTest, MoveOp_Obj1_Obj2) { DummyPyObject obj1; DummyPyObject obj2; { DummyPyObjectPtr ptr1 = DummyPyObjectPtr::Own(&obj1); DummyPyObjectPtr ptr2 = DummyPyObjectPtr::Own(&obj2); ptr1 = std::move(ptr2); ASSERT_EQ(ptr1.get(), &obj2); ASSERT_EQ(ptr2.get(), nullptr); ASSERT_EQ(obj1.ref_counter, 0); ASSERT_EQ(obj2.ref_counter, 1); ASSERT_EQ(DummyGILGuard::active, 0); ASSERT_EQ(DummyGILGuard::total, 1); } ASSERT_EQ(obj1.ref_counter, 0); ASSERT_EQ(obj2.ref_counter, 0); ASSERT_EQ(DummyGILGuard::active, 0); ASSERT_EQ(DummyGILGuard::total, 2); } TEST_F(BasePyObjectPtrTest, Equality) { DummyPyObject obj; const DummyPyObjectPtr null_ptr; const DummyPyObjectPtr not_null_ptr = DummyPyObjectPtr::Own(&obj); ASSERT_TRUE(null_ptr == nullptr); ASSERT_FALSE(null_ptr != nullptr); ASSERT_FALSE(not_null_ptr == nullptr); ASSERT_TRUE(not_null_ptr != nullptr); ASSERT_EQ(obj.ref_counter, 1); ASSERT_EQ(DummyGILGuard::active, 0); ASSERT_EQ(DummyGILGuard::total, 0); } TEST_F(BasePyObjectPtrTest, Release) { DummyPyObject obj; { DummyPyObjectPtr ptr = DummyPyObjectPtr::Own(&obj); ASSERT_EQ(ptr.release(), &obj); ASSERT_EQ(ptr.get(), nullptr); ASSERT_EQ(obj.ref_counter, 1); ASSERT_EQ(DummyGILGuard::active, 0); ASSERT_EQ(DummyGILGuard::total, 0); } ASSERT_EQ(obj.ref_counter, 1); ASSERT_EQ(DummyGILGuard::active, 0); ASSERT_EQ(DummyGILGuard::total, 0); } TEST_F(BasePyObjectPtrTest, ResetNull) { { DummyPyObjectPtr ptr; ptr.reset(); ASSERT_EQ(ptr.get(), nullptr); ASSERT_EQ(DummyGILGuard::active, 0); ASSERT_EQ(DummyGILGuard::total, 0); } ASSERT_EQ(DummyGILGuard::active, 0); ASSERT_EQ(DummyGILGuard::total, 0); } TEST_F(BasePyObjectPtrTest, Reset) { DummyPyObject obj; { DummyPyObjectPtr ptr = DummyPyObjectPtr::Own(&obj); ptr.reset(); ASSERT_EQ(ptr.get(), nullptr); ASSERT_EQ(obj.ref_counter, 0); ASSERT_EQ(DummyGILGuard::active, 0); ASSERT_EQ(DummyGILGuard::total, 1); } ASSERT_EQ(obj.ref_counter, 0); ASSERT_EQ(DummyGILGuard::active, 0); ASSERT_EQ(DummyGILGuard::total, 1); } } }
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/py/arolla/py_utils/py_object_ptr_impl.h
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/py/arolla/py_utils/py_object_ptr_impl_test.cc
1ca990dbeca224035efdabffecc7f3738df6b52c
e3bfde0e-9a6f-443c-be03-78ee0a78278c
cpp
google/arolla
bound_split_conditions
arolla/decision_forest/pointwise_evaluation/bound_split_conditions.h
arolla/decision_forest/pointwise_evaluation/bound_split_conditions_test.cc
#ifndef AROLLA_DECISION_FOREST_POINTWISE_EVALUATION_BOUND_SPLIT_CONDITIONS_H_ #define AROLLA_DECISION_FOREST_POINTWISE_EVALUATION_BOUND_SPLIT_CONDITIONS_H_ #include <memory> #include <variant> #include "absl/container/flat_hash_set.h" #include "absl/container/inlined_vector.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/types/span.h" #include "arolla/decision_forest/split_condition.h" #include "arolla/decision_forest/split_conditions/interval_split_condition.h" #include "arolla/decision_forest/split_conditions/set_of_values_split_condition.h" #include "arolla/memory/frame.h" #include "arolla/memory/optional_value.h" #include "arolla/qtype/typed_slot.h" #include "arolla/util/status_macros_backport.h" namespace arolla { struct IntervalBoundCondition { FrameLayout::Slot<OptionalValue<float>> input_slot = FrameLayout::Slot<OptionalValue<float>>::UnsafeUninitializedSlot(); float left, right; bool operator()(const ConstFramePtr ctx) const { OptionalValue<float> v = ctx.Get(input_slot); return v.present && left <= v.value && v.value <= right; } using cond_type = IntervalSplitCondition; static absl::StatusOr<IntervalBoundCondition> Create( const std::shared_ptr<const cond_type>& cond, absl::Span<const TypedSlot> input_slots) { ASSIGN_OR_RETURN( auto input_slot, input_slots[cond->input_id()].ToSlot<OptionalValue<float>>()); return IntervalBoundCondition{input_slot, cond->left(), cond->right()}; } }; template <class T> struct SetOfValuesBoundCondition { FrameLayout::Slot<OptionalValue<T>> input_slot = FrameLayout::Slot<OptionalValue<T>>::UnsafeUninitializedSlot(); absl::flat_hash_set<T> values; bool result_if_missed; bool operator()(const ConstFramePtr ctx) const { const OptionalValue<T>& v = ctx.Get(input_slot); return (v.present && values.contains(v.value)) || (!v.present && result_if_missed); } using cond_type = SetOfValuesSplitCondition<T>; static absl::StatusOr<SetOfValuesBoundCondition> Create( const std::shared_ptr<const cond_type>& cond, absl::Span<const TypedSlot> input_slots) { ASSIGN_OR_RETURN( auto input_slot, input_slots[cond->input_id()].template ToSlot<OptionalValue<T>>()); return SetOfValuesBoundCondition{input_slot, cond->values(), cond->GetDefaultResultForMissedInput()}; } }; struct VirtualBoundCondition { std::shared_ptr<const SplitCondition> condition; absl::InlinedVector<TypedSlot, 1> inputs; bool operator()(const ConstFramePtr ctx) const { return condition->EvaluateCondition(ctx, inputs); } using cond_type = SplitCondition; static absl::StatusOr<VirtualBoundCondition> Create( const std::shared_ptr<const cond_type>& cond, absl::Span<const TypedSlot> input_slots) { VirtualBoundCondition res; res.condition = cond; res.inputs.insert(res.inputs.end(), input_slots.begin(), input_slots.end()); return res; } }; template <typename... Args> class VariantBoundCondition { public: bool operator()(const ConstFramePtr ctx) const { return std::visit(Visitor{ctx}, bound_condition_); } static absl::StatusOr<VariantBoundCondition<Args...>> Create( const std::shared_ptr<const SplitCondition>& condition, absl::Span<const TypedSlot> input_slots) { VariantBoundCondition<Args...> res; bool initialized = false; for (auto status : {res.TryInit<Args>(condition, input_slots, &initialized)...}) { if (!status.ok()) return status; } if (initialized) { return res; } else { return absl::InvalidArgumentError("unsupported SplitCondition"); } } private: template <class T> absl::Status TryInit(const std::shared_ptr<const SplitCondition>& cond, absl::Span<const TypedSlot> input_slots, bool* initialized) { if (*initialized) return absl::OkStatus(); if (auto casted_cond = std::dynamic_pointer_cast<const typename T::cond_type>(cond)) { ASSIGN_OR_RETURN(bound_condition_, T::Create(casted_cond, input_slots)); *initialized = true; } return absl::OkStatus(); } struct Visitor { const ConstFramePtr context; explicit Visitor(const ConstFramePtr ctx) : context(ctx) {} template <class T> bool operator()(const T& condition) { return condition(context); } }; std::variant<Args...> bound_condition_; }; } #endif
#include "arolla/decision_forest/pointwise_evaluation/bound_split_conditions.h" #include <cmath> #include <cstdint> #include <utility> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "arolla/decision_forest/split_conditions/interval_split_condition.h" #include "arolla/decision_forest/split_conditions/set_of_values_split_condition.h" #include "arolla/memory/frame.h" #include "arolla/memory/memory_allocation.h" #include "arolla/memory/optional_value.h" #include "arolla/qtype/typed_slot.h" #include "arolla/util/bytes.h" namespace arolla::testing { namespace { TEST(BoundConditions, IntervalSplitCondition) { auto interval_split = IntervalSplit(0, 2, 3); FrameLayout::Builder bldr; auto slot = bldr.AddSlot<OptionalValue<float>>(); auto layout = std::move(bldr).Build(); MemoryAllocation alloc(&layout); FramePtr context = alloc.frame(); using BoundCondition = VariantBoundCondition<IntervalBoundCondition, SetOfValuesBoundCondition<int64_t>>; std::vector<TypedSlot> typed_slots = {TypedSlot::FromSlot(slot)}; ASSERT_OK_AND_ASSIGN(BoundCondition bound_interval, BoundCondition::Create(interval_split, typed_slots)); context.Set(slot, 3.5); EXPECT_EQ(bound_interval(context), false); context.Set(slot, NAN); EXPECT_EQ(bound_interval(context), false); context.Set(slot, 2.5); EXPECT_EQ(bound_interval(context), true); context.Set(slot, {}); EXPECT_EQ(bound_interval(context), false); } TEST(BoundConditions, SetOfValuesSplitCondition) { auto set_of_values = SetOfValuesSplit<int64_t>(0, {2, 4, 3}, true); FrameLayout::Builder bldr; auto slot = bldr.AddSlot<OptionalValue<int64_t>>(); std::vector<TypedSlot> typed_slots = {TypedSlot::FromSlot(slot)}; auto layout = std::move(bldr).Build(); MemoryAllocation alloc(&layout); FramePtr context = alloc.frame(); using BoundCondition = VariantBoundCondition<IntervalBoundCondition, SetOfValuesBoundCondition<int64_t>>; ASSERT_OK_AND_ASSIGN(BoundCondition bound_set_of_values, BoundCondition::Create(set_of_values, typed_slots)); context.Set(slot, 3); EXPECT_EQ(bound_set_of_values(context), true); context.Set(slot, 5); EXPECT_EQ(bound_set_of_values(context), false); context.Set(slot, {}); EXPECT_EQ(bound_set_of_values(context), true); } TEST(BoundConditions, VirtualBoundCondition) { auto set_of_values = SetOfValuesSplit<Bytes>(0, {Bytes("A"), Bytes("B"), Bytes("C")}, true); FrameLayout::Builder bldr; auto slot = bldr.AddSlot<OptionalValue<Bytes>>(); std::vector<TypedSlot> typed_slots = {TypedSlot::FromSlot(slot)}; auto layout = std::move(bldr).Build(); MemoryAllocation alloc(&layout); FramePtr context = alloc.frame(); using BoundCondition = VariantBoundCondition<IntervalBoundCondition, SetOfValuesBoundCondition<int64_t>, VirtualBoundCondition>; ASSERT_OK_AND_ASSIGN(BoundCondition bound_set_of_values, BoundCondition::Create(set_of_values, typed_slots)); context.Set(slot, Bytes("B")); EXPECT_EQ(bound_set_of_values(context), true); context.Set(slot, Bytes("D")); EXPECT_EQ(bound_set_of_values(context), false); context.Set(slot, {}); EXPECT_EQ(bound_set_of_values(context), true); } } }
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/decision_forest/pointwise_evaluation/bound_split_conditions.h
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/decision_forest/pointwise_evaluation/bound_split_conditions_test.cc
1ca990dbeca224035efdabffecc7f3738df6b52c
09dfc316-45fc-4797-bba2-a7e440dd956c
cpp
google/arolla
pointwise
arolla/decision_forest/pointwise_evaluation/pointwise.h
arolla/decision_forest/qexpr_operator/pointwise_test.cc
#ifndef AROLLA_DECISION_FOREST_POINTWISE_EVALUATION_POINTWISE_H_ #define AROLLA_DECISION_FOREST_POINTWISE_EVALUATION_POINTWISE_H_ #include <array> #include <cstddef> #include <cstdint> #include <deque> #include <type_traits> #include <vector> #include "absl/base/optimization.h" #include "absl/container/inlined_vector.h" #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "arolla/util/status_macros_backport.h" namespace arolla { namespace internal { struct NodeId { static NodeId Split(int32_t split_node_id) { return {split_node_id}; } static NodeId Leaf(int32_t adjustment_id) { return {~adjustment_id}; } bool is_leaf() const { return val < 0; } int32_t split_node_id() const { DCHECK(!this->is_leaf()); return val; } int32_t adjsutment_id() const { DCHECK(this->is_leaf()); return ~val; } int32_t val; }; template <class NodeTest> struct CompactCondition { NodeTest test; std::array<NodeId, 2> next_node_ids; }; template <class OutT, class NodeTest> struct CompactDecisionTree { std::vector<CompactCondition<NodeTest>> splits; std::vector<OutT> adjustments; NodeId RootNodeId() const { return splits.empty() ? NodeId::Leaf(0) : NodeId::Split(0); } }; template <class OutT, class NodeTest> struct SingleTreeCompilationImpl { explicit SingleTreeCompilationImpl(size_t node_cnt) : nodes_(node_cnt), node_used_(node_cnt), node_used_as_child_(node_cnt) { if (node_cnt > 0) { node_used_as_child_[0] = true; } } absl::Status SetNode(size_t node_id, size_t left_id, size_t right_id, const NodeTest& test) { RETURN_IF_ERROR(TestNode(node_id, &node_used_)); RETURN_IF_ERROR(TestNode(left_id, &node_used_as_child_)); RETURN_IF_ERROR(TestNode(right_id, &node_used_as_child_)); nodes_[node_id].left_id = left_id; nodes_[node_id].right_id = right_id; nodes_[node_id].test = test; return absl::OkStatus(); } absl::Status SetLeaf(size_t node_id, OutT leaf_value) { RETURN_IF_ERROR(TestNode(node_id, &node_used_)); nodes_[node_id].leaf_id = leaf_values_.size(); leaf_values_.push_back(leaf_value); return absl::OkStatus(); } absl::StatusOr<CompactDecisionTree<OutT, NodeTest>> Compile() { if (nodes_.empty()) { return absl::Status(absl::StatusCode::kFailedPrecondition, "Empty trees are not supported."); } for (size_t i = 0; i < nodes_.size(); ++i) { if (!node_used_as_child_[i] || !node_used_[i]) { return absl::Status(absl::StatusCode::kInvalidArgument, "Id is not used"); } } CompactDecisionTree<OutT, NodeTest> tree; const size_t inner_node_count = nodes_.size() - leaf_values_.size(); leaf_values_.shrink_to_fit(); tree.adjustments = std::move(leaf_values_); std::vector<NodeId> node_mapping(nodes_.size()); int cur_new_node_id = 0; for (int id = 0; id < nodes_.size(); ++id) { const auto& node = nodes_[id]; if (node.leaf_id == -1) { node_mapping[id] = NodeId::Split(cur_new_node_id++); } else { node_mapping[id] = NodeId::Leaf(node.leaf_id); } } tree.splits.resize(inner_node_count); for (int id = 0; id < nodes_.size(); ++id) { const auto& node = nodes_[id]; if (node.leaf_id == -1) { auto& compact_node = tree.splits[node_mapping[id].split_node_id()]; compact_node.test = node.test; compact_node.next_node_ids[1] = node_mapping[node.left_id]; compact_node.next_node_ids[0] = node_mapping[node.right_id]; } } return tree; } private: absl::Status TestNode(size_t id, std::vector<bool>* used) { if (id >= used->size()) { return absl::Status(absl::StatusCode::kOutOfRange, "Id out of range"); } if ((*used)[id]) { return absl::Status(absl::StatusCode::kInvalidArgument, "Id duplicated"); } (*used)[id] = true; return absl::OkStatus(); } struct Node { size_t leaf_id = -1; size_t left_id = -1; size_t right_id = -1; NodeTest test = {}; }; std::vector<Node> nodes_; std::vector<bool> node_used_; std::vector<bool> node_used_as_child_; std::vector<OutT> leaf_values_; }; template <class OutT, class NodeTest> class DecisionTreeTraverser { public: explicit DecisionTreeTraverser( const internal::CompactDecisionTree<OutT, NodeTest>& tree) : node_id_(tree.RootNodeId()), tree_(tree) {} bool CanStep() const { return !node_id_.is_leaf(); } template <class FeatureContainer> void MakeStep(const FeatureContainer& values) { const auto& split = tree_.splits[node_id_.split_node_id()]; node_id_ = split.next_node_ids[split.test(values)]; } OutT GetValue() const { return tree_.adjustments[node_id_.adjsutment_id()]; } private: NodeId node_id_; const internal::CompactDecisionTree<OutT, NodeTest>& tree_; }; struct EmptyFilterTag {}; } template <class OutT, class NodeTest> class SinglePredictor { public: explicit SinglePredictor(internal::CompactDecisionTree<OutT, NodeTest> tree) : tree_(std::move(tree)) {} template <class FeatureContainer> OutT Predict(const FeatureContainer& values) const { internal::DecisionTreeTraverser<OutT, NodeTest> traverser(tree_); while (ABSL_PREDICT_TRUE(traverser.CanStep())) { traverser.MakeStep(values); } return traverser.GetValue(); } private: internal::CompactDecisionTree<OutT, NodeTest> tree_; }; template <class TreeOutT, class NodeTest, class BinaryOp, class FilterTag = internal::EmptyFilterTag> class BoostedPredictor { public: using OutT = std::decay_t<decltype(BinaryOp()(TreeOutT(), TreeOutT()))>; using NodeTestType = NodeTest; explicit BoostedPredictor( std::vector<internal::CompactDecisionTree<TreeOutT, NodeTest>> trees, std::vector<FilterTag> filter_tags, BinaryOp op) : trees_(std::move(trees)), filter_tags_(std::move(filter_tags)), op_(op) {} template <class FeatureContainer, class FilterFn> OutT Predict(const FeatureContainer& values, OutT start, FilterFn filter) const { constexpr int kBatchSize = 16; absl::InlinedVector<internal::DecisionTreeTraverser<TreeOutT, NodeTest>, kBatchSize> traversers; uint32_t ids[kBatchSize]; for (int first = 0; first < trees_.size(); first += kBatchSize) { int count = std::min<int>(trees_.size() - first, kBatchSize); traversers.clear(); uint32_t* ids_end = ids; for (int i = 0; i < count; ++i) { if (!filter(filter_tags_[first + i])) continue; *(ids_end++) = traversers.size(); traversers.emplace_back(trees_[first + i]); } while (ABSL_PREDICT_TRUE(ids != ids_end)) { auto out_it = ids; for (auto it = ids; it != ids_end; ++it) { auto& traverser = traversers[*it]; if (ABSL_PREDICT_TRUE(traverser.CanStep())) { traverser.MakeStep(values); *(out_it++) = *it; } else { start = op_(start, traverser.GetValue()); } } ids_end = out_it; } } return start; } template <class FeatureContainer> OutT Predict(const FeatureContainer& values, OutT start = OutT()) const { if (trees_.empty()) return start; return Predict(values, start, [](FilterTag tag) { return true; }); } private: std::vector<internal::CompactDecisionTree<TreeOutT, NodeTest>> trees_; std::vector<FilterTag> filter_tags_; BinaryOp op_; }; template <class OutT, class NodeTest> class PredictorCompiler { public: explicit PredictorCompiler(size_t node_cnt) : impl_(node_cnt) {} absl::Status SetNode(size_t node_id, size_t left_id, size_t right_id, const NodeTest& test) { return impl_.SetNode(node_id, left_id, right_id, test); } absl::Status SetLeaf(size_t node_id, OutT leaf_value) { return impl_.SetLeaf(node_id, leaf_value); } absl::StatusOr<SinglePredictor<OutT, NodeTest>> Compile() { if (compiled_) { return absl::Status(absl::StatusCode::kFailedPrecondition, "Already compiled."); } compiled_ = true; auto tree_or = impl_.Compile(); RETURN_IF_ERROR(tree_or.status()); return SinglePredictor<OutT, NodeTest>(*std::move(tree_or)); } private: bool compiled_ = false; internal::SingleTreeCompilationImpl<OutT, NodeTest> impl_; }; template <class OutT, class NodeTest> class OneTreeCompiler { public: explicit OneTreeCompiler( internal::SingleTreeCompilationImpl<OutT, NodeTest>* impl) : impl_(impl) {} absl::Status SetNode(size_t node_id, size_t left_id, size_t right_id, const NodeTest& test) { return impl_->SetNode(node_id, left_id, right_id, test); } absl::Status SetLeaf(size_t node_id, OutT leaf_value) { return impl_->SetLeaf(node_id, leaf_value); } private: internal::SingleTreeCompilationImpl<OutT, NodeTest>* impl_; }; template <class OutT, class NodeTest, class BinaryOp, class FilterTag = internal::EmptyFilterTag> class BoostedPredictorCompiler { public: BoostedPredictorCompiler() {} explicit BoostedPredictorCompiler(BinaryOp op) : op_(op) {} OneTreeCompiler<OutT, NodeTest> AddTree(size_t node_count, FilterTag tag = FilterTag()) { impls_.emplace_back(node_count); filter_tags_.push_back(tag); return OneTreeCompiler<OutT, NodeTest>(&impls_.back()); } absl::StatusOr<BoostedPredictor<OutT, NodeTest, BinaryOp, FilterTag>> Compile() { if (compiled_) { return absl::Status(absl::StatusCode::kFailedPrecondition, "Already compiled."); } compiled_ = true; std::vector<internal::CompactDecisionTree<OutT, NodeTest>> trees; trees.reserve(impls_.size()); for (auto& impl : impls_) { auto tree_or = impl.Compile(); RETURN_IF_ERROR(tree_or.status()); trees.push_back(*std::move(tree_or)); } return BoostedPredictor<OutT, NodeTest, BinaryOp, FilterTag>( std::move(trees), std::move(filter_tags_), op_); } private: bool compiled_ = false; BinaryOp op_; std::deque<internal::SingleTreeCompilationImpl<OutT, NodeTest>> impls_; std::vector<FilterTag> filter_tags_; }; } #endif
#include <cstdint> #include <limits> #include <memory> #include <utility> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "arolla/decision_forest/decision_forest.h" #include "arolla/decision_forest/qexpr_operator/pointwise_operator.h" #include "arolla/decision_forest/split_conditions/interval_split_condition.h" #include "arolla/decision_forest/split_conditions/set_of_values_split_condition.h" #include "arolla/memory/frame.h" #include "arolla/memory/optional_value.h" #include "arolla/qexpr/eval_context.h" #include "arolla/qexpr/qexpr_operator_signature.h" #include "arolla/qtype/optional_qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/tuple_qtype.h" #include "arolla/qtype/typed_slot.h" namespace arolla { namespace { using ::testing::Test; class DecisionForestPointwiseTest : public Test { protected: void SetUp() override { const float inf = std::numeric_limits<float>::infinity(); auto S = DecisionTreeNodeId::SplitNodeId; auto A = DecisionTreeNodeId::AdjustmentId; std::vector<DecisionTree> trees(2); trees[0].tag.submodel_id = 2; trees[0].adjustments = {0.5, 1.5, 2.5, 3.5}; trees[0].split_nodes = { {S(1), S(2), IntervalSplit(0, 1.5, inf)}, {A(0), A(2), SetOfValuesSplit<int64_t>(1, {1, 2}, false)}, {A(1), A(3), IntervalSplit(0, -inf, 10)}}; trees[1].tag.submodel_id = 1; trees[1].adjustments = {1.0}; ASSERT_OK_AND_ASSIGN(forest_, DecisionForest::FromTrees(std::move(trees))); } std::shared_ptr<const DecisionForest> forest_; }; TEST_F(DecisionForestPointwiseTest, Run) { auto result_type = MakeTupleQType({GetQType<float>(), GetQType<float>()}); FrameLayout::Builder bldr; auto input1_slot = bldr.AddSlot<OptionalValue<float>>(); auto input2_slot = bldr.AddSlot<OptionalValue<int64_t>>(); auto result_slot = AddSlot(result_type, &bldr); auto forest_op_type = QExprOperatorSignature::Get( {GetOptionalQType<float>(), GetOptionalQType<int64_t>()}, result_type); ASSERT_OK_AND_ASSIGN( auto forest_op, CreatePointwiseDecisionForestOperator( forest_, forest_op_type, {{.submodels = {1}}, {.submodels = {2}}})); ASSERT_OK_AND_ASSIGN(auto bound_forest_op, forest_op->Bind({TypedSlot::FromSlot(input1_slot), TypedSlot::FromSlot(input2_slot)}, {result_slot})); FrameLayout layout = std::move(bldr).Build(); RootEvaluationContext root_ctx(&layout); EvaluationContext ctx(root_ctx); root_ctx.Set(input1_slot, 1.0f); root_ctx.Set(input2_slot, 2); bound_forest_op->Run(&ctx, root_ctx.frame()); EXPECT_OK(ctx.status()); EXPECT_EQ(root_ctx.Get(result_slot.SubSlot(0).UnsafeToSlot<float>()), 1.0); EXPECT_EQ(root_ctx.Get(result_slot.SubSlot(1).UnsafeToSlot<float>()), 2.5); root_ctx.Set(input1_slot, 2.0f); root_ctx.Set(input2_slot, 1); bound_forest_op->Run(&ctx, root_ctx.frame()); EXPECT_OK(ctx.status()); EXPECT_EQ(root_ctx.Get(result_slot.SubSlot(0).UnsafeToSlot<float>()), 1.0); EXPECT_EQ(root_ctx.Get(result_slot.SubSlot(1).UnsafeToSlot<float>()), 3.5); } } }
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/decision_forest/pointwise_evaluation/pointwise.h
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/decision_forest/qexpr_operator/pointwise_test.cc
1ca990dbeca224035efdabffecc7f3738df6b52c
9f878577-68d2-4fd6-98e3-622434fd7322
cpp
google/arolla
embedded_model
arolla/serving/embedded_model.h
arolla/serving/embedded_model_test.cc
#ifndef AROLLA_SERVING_EMBEDDED_MODEL_H_ #define AROLLA_SERVING_EMBEDDED_MODEL_H_ #include <functional> #include <type_traits> #include "absl/base/no_destructor.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/util/init_arolla.h" #include "arolla/util/meta.h" #include "arolla/util/status_macros_backport.h" #define AROLLA_DEFINE_EMBEDDED_MODEL_FN(fn_name, model_or) \ namespace { \ const decltype(model_or)& _arolla_embed_model_or_status_##fn_name() { \ using ModelT = decltype(model_or); \ static const absl::NoDestructor<ModelT> model(model_or); \ return *model; \ } \ } \ \ const ::arolla::meta::strip_template_t<absl::StatusOr, decltype(model_or)>& \ fn_name() { \ const auto& model = _arolla_embed_model_or_status_##fn_name(); \ \ if (!model.ok()) { \ static ::arolla::meta::strip_template_t<absl::StatusOr, \ decltype(model_or)> \ error_fn = \ [status_(model.status())](const auto&...) { return status_; }; \ return error_fn; \ } \ return *model; \ } \ \ AROLLA_INITIALIZER( \ .deps = \ { \ "@phony/serving_compiler_optimizer", \ ::arolla::initializer_dep::kOperators, \ ::arolla::initializer_dep::kS11n, \ }, \ .init_fn = []() -> absl::Status { \ RETURN_IF_ERROR( \ _arolla_embed_model_or_status_##fn_name().status()) \ << "while initializing embedded model " << #fn_name << " at " \ << __FILE__ << ":" << __LINE__; \ return absl::OkStatus(); \ }) #define AROLLA_DEFINE_EMBEDDED_MODEL_SET_FN(fn_name, model_set_or) \ namespace { \ const decltype(model_set_or)& \ _arolla_embed_model_set_or_status_##fn_name() { \ using ModelSetT = decltype(model_set_or); \ static const absl::NoDestructor<ModelSetT> model_set(model_set_or); \ return *model_set; \ } \ } \ \ absl::StatusOr<std::reference_wrapper< \ const std::decay_t<decltype(model_set_or->at(""))>>> \ fn_name(absl::string_view model_name) { \ const auto& model_set = _arolla_embed_model_set_or_status_##fn_name(); \ RETURN_IF_ERROR(model_set.status()); \ auto it = model_set->find(model_name); \ if (it == model_set->end()) { \ return absl::NotFoundError( \ absl::StrFormat("model \"%s\" not found in " #fn_name, model_name)); \ } \ return it->second; \ } \ \ AROLLA_INITIALIZER( \ .deps = \ { \ "@phony/serving_compiler_optimizer", \ ::arolla::initializer_dep::kOperators, \ ::arolla::initializer_dep::kS11n, \ }, \ .init_fn = []() -> absl::Status { \ RETURN_IF_ERROR( \ _arolla_embed_model_set_or_status_##fn_name().status()) \ << "while initializing embedded model " << #fn_name << " at " \ << __FILE__ << ":" << __LINE__; \ return absl::OkStatus(); \ }) #endif
#include "arolla/serving/embedded_model.h" #include <functional> #include <memory> #include <optional> #include <string> #include <type_traits> #include "benchmark/benchmark.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/base/no_destructor.h" #include "absl/container/flat_hash_map.h" #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/status/status_matchers.h" #include "absl/status/statusor.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/testing/testing.h" #include "arolla/io/accessors_input_loader.h" #include "arolla/io/accessors_slot_listener.h" #include "arolla/io/input_loader.h" #include "arolla/io/slot_listener.h" #include "arolla/qexpr/evaluation_engine.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/serving/expr_compiler.h" #include "arolla/util/init_arolla.h" #include "arolla/util/status_macros_backport.h" namespace { using ::absl_testing::IsOk; using ::absl_testing::IsOkAndHolds; using ::absl_testing::StatusIs; using ::testing::Eq; struct TestInput { float x; float y; }; struct TestSideOutput { std::optional<float> subtract; }; absl::StatusOr<std::unique_ptr<arolla::InputLoader<TestInput>>> CreateInputLoader() { return ::arolla::CreateAccessorsInputLoader<TestInput>( "x", [](const auto& x) { return x.x; }, "y", [](const auto& x) { return x.y; }); } absl::StatusOr<std::unique_ptr<::arolla::SlotListener<TestSideOutput>>> CreateSlotListener() { return ::arolla::CreateAccessorsSlotListener<TestSideOutput>( "subtract", [](float x, TestSideOutput* out) { out->subtract = x; }); } absl::StatusOr<::arolla::expr::ExprNodePtr> CreateExpr() { using ::arolla::expr::CallOp; using ::arolla::expr::Leaf; using ::arolla::testing::WithExportValueAnnotation; ASSIGN_OR_RETURN(auto add_expr, CallOp("math.add", {Leaf("x"), Leaf("y")})); ASSIGN_OR_RETURN(auto subtract_expr, CallOp("math.subtract", {Leaf("x"), Leaf("y")})); return WithExportValueAnnotation(add_expr, "subtract", subtract_expr); } absl::StatusOr<std::unique_ptr<::arolla::CompiledExpr>> CreateCompiledExpr() { using ::arolla::GetQType; using ::arolla::expr::CallOp; using ::arolla::expr::Leaf; ASSIGN_OR_RETURN(auto add_expr, CallOp("math.add", {Leaf("x"), Leaf("y")})); ASSIGN_OR_RETURN(auto subtract_expr, CallOp("math.subtract", {Leaf("x"), Leaf("y")})); return ::arolla::expr::CompileForDynamicEvaluation( ::arolla::expr::DynamicEvaluationEngineOptions(), add_expr, {{"x", GetQType<float>()}, {"y", GetQType<float>()}}, {{"subtract", subtract_expr}}); } namespace test_namespace { const ::arolla::ExprCompiler<TestInput, std::optional<float>>::Function& MyDynamicEmbeddedModel(); AROLLA_DEFINE_EMBEDDED_MODEL_FN( MyDynamicEmbeddedModel, (::arolla::ExprCompiler<TestInput, std::optional<float>>() .SetInputLoader(CreateInputLoader()) .AllowOutputCasting() .Compile(CreateExpr().value()))); } TEST(ExprCompilerTest, UseDynamicEmbeddedExpr) { auto model = ::test_namespace::MyDynamicEmbeddedModel(); static_assert( std::is_same_v<std::decay_t<decltype(model)>, std::function<absl::StatusOr<std::optional<float>>( const TestInput&)>>); TestInput input{.x = 28, .y = 29}; EXPECT_THAT(model(input), IsOkAndHolds(57)); } namespace test_namespace { const ::arolla::ExprCompiler<TestInput, std::optional<float>, TestSideOutput>::Function& MyCompiledEmbeddedModel(); AROLLA_DEFINE_EMBEDDED_MODEL_FN( MyCompiledEmbeddedModel, (::arolla::ExprCompiler<TestInput, std::optional<float>, TestSideOutput>() .SetInputLoader(CreateInputLoader()) .SetSlotListener(CreateSlotListener()) .AllowOutputCasting() .Compile(*CreateCompiledExpr().value()))); } TEST(ExprCompilerTest, UseCompiledEmbeddedExprWithSideOutput) { auto model = ::test_namespace::MyCompiledEmbeddedModel(); static_assert( std::is_same_v<std::decay_t<decltype(model)>, std::function<absl::StatusOr<std::optional<float>>( const TestInput&, TestSideOutput*)>>); TestInput input{.x = 28, .y = 29}; EXPECT_THAT(model(input, nullptr), IsOkAndHolds(57)); TestSideOutput side_output; EXPECT_THAT(model(input, &side_output), IsOkAndHolds(57)); EXPECT_THAT(side_output.subtract, Eq(-1)); } namespace test_namespace { absl::flat_hash_map<std::string, absl::StatusOr<::arolla::expr::ExprNodePtr>> CreateExprSet() { return {{"first_expr", CreateExpr()}, {"second_expr", CreateExpr()}}; } absl::StatusOr<std::reference_wrapper< const ::arolla::ExprCompiler<TestInput, std::optional<float>>::Function>> MyDynamicEmbeddedExprSet(absl::string_view); AROLLA_DEFINE_EMBEDDED_MODEL_SET_FN( MyDynamicEmbeddedExprSet, ::arolla::CompileExprSet( ::arolla::ExprCompiler<TestInput, std::optional<float>>() .SetInputLoader(CreateInputLoader()) .AllowOutputCasting(), CreateExprSet())); } TEST(ExprCompilerTest, UseDynamicEmbeddedExprSet) { ASSERT_OK_AND_ASSIGN(auto model, test_namespace::MyDynamicEmbeddedExprSet("first_expr")); static_assert( std::is_same_v<decltype(model), std::reference_wrapper<const std::function<absl::StatusOr< std::optional<float>>(const TestInput&)>>>); TestInput input{.x = 28, .y = 29}; EXPECT_THAT(model(input), IsOkAndHolds(57)); EXPECT_THAT(test_namespace::MyDynamicEmbeddedExprSet("second_expr"), IsOk()); EXPECT_THAT( test_namespace::MyDynamicEmbeddedExprSet("missing_expr"), StatusIs(absl::StatusCode::kNotFound, "model \"missing_expr\" not found in MyDynamicEmbeddedExprSet")); } namespace test_namespace { absl::flat_hash_map<std::string, std::reference_wrapper<const ::arolla::CompiledExpr>> CreateCompiledExprSet() { static const absl::NoDestructor<std::unique_ptr<::arolla::CompiledExpr>> compiled_expr(CreateCompiledExpr().value()); return absl::flat_hash_map< std::string, std::reference_wrapper<const ::arolla::CompiledExpr>>{ {"first_expr", **compiled_expr}, {"second_expr", **compiled_expr}}; } absl::StatusOr<std::reference_wrapper< const ::arolla::ExprCompiler<TestInput, std::optional<float>>::Function>> MyCompiledEmbeddedExprSet(absl::string_view); AROLLA_DEFINE_EMBEDDED_MODEL_SET_FN( MyCompiledEmbeddedExprSet, ::arolla::CompileExprSet( ::arolla::ExprCompiler<TestInput, std::optional<float>>() .SetInputLoader(CreateInputLoader()) .AllowOutputCasting(), CreateCompiledExprSet())); } TEST(ExprCompilerTest, UseCompiledEmbeddedExprSet) { ASSERT_OK_AND_ASSIGN(auto model, test_namespace::MyCompiledEmbeddedExprSet("first_expr")); static_assert( std::is_same_v<decltype(model), std::reference_wrapper<const std::function<absl::StatusOr< std::optional<float>>(const TestInput&)>>>); TestInput input{.x = 28, .y = 29}; EXPECT_THAT(model(input), IsOkAndHolds(57)); EXPECT_THAT(test_namespace::MyCompiledEmbeddedExprSet("second_expr"), IsOk()); EXPECT_THAT( test_namespace::MyCompiledEmbeddedExprSet("missing_expr"), StatusIs( absl::StatusCode::kNotFound, "model \"missing_expr\" not found in MyCompiledEmbeddedExprSet")); } void BM_MyDynamicEmbeddedModel_Request(benchmark::State& state) { arolla::InitArolla(); TestInput input{.x = 28, .y = 29}; for (auto _ : state) { benchmark::DoNotOptimize(input); CHECK_EQ(**test_namespace::MyDynamicEmbeddedModel()(input), 57); } } void BM_MyDynamicEmbeddedModel_ConstructOutOfTheLoop(benchmark::State& state) { arolla::InitArolla(); TestInput input{.x = 28, .y = 29}; auto model = test_namespace::MyDynamicEmbeddedModel(); for (auto _ : state) { benchmark::DoNotOptimize(input); CHECK_EQ(*model(input).value(), 57); } } BENCHMARK(BM_MyDynamicEmbeddedModel_Request); BENCHMARK(BM_MyDynamicEmbeddedModel_ConstructOutOfTheLoop); }
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/serving/embedded_model.h
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/serving/embedded_model_test.cc
1ca990dbeca224035efdabffecc7f3738df6b52c
a7c4e7e1-4c9d-4e25-9452-ecf7b7547ffd
cpp
google/arolla
memory_allocation
arolla/memory/memory_allocation.h
arolla/memory/memory_allocation_test.cc
#ifndef AROLLA_UTIL_MEMORY_ALLOCATION_H_ #define AROLLA_UTIL_MEMORY_ALLOCATION_H_ #include <utility> #include "absl/log/check.h" #include "arolla/memory/frame.h" #include "arolla/util/memory.h" namespace arolla { class MemoryAllocation { public: MemoryAllocation() = default; explicit MemoryAllocation(const FrameLayout* layout) : layout_(layout), alloc_(AlignedAlloc(layout->AllocAlignment(), layout->AllocSize())) { layout_->InitializeAlignedAlloc(alloc_.get()); } MemoryAllocation(const MemoryAllocation&) = delete; MemoryAllocation& operator=(const MemoryAllocation&) = delete; MemoryAllocation(MemoryAllocation&&) = default; MemoryAllocation& operator=(MemoryAllocation&& other) { if (alloc_ != nullptr) { layout_->DestroyAlloc(alloc_.get()); } layout_ = other.layout_; alloc_ = std::move(other.alloc_); return *this; } ~MemoryAllocation() { if (alloc_ != nullptr) { layout_->DestroyAlloc(alloc_.get()); } } bool IsValid() const { return alloc_ != nullptr; } FramePtr frame() { DCHECK(IsValid()); return FramePtr(alloc_.get(), layout_); } ConstFramePtr frame() const { DCHECK(IsValid()); return ConstFramePtr(alloc_.get(), layout_); } private: const FrameLayout* layout_ = nullptr; MallocPtr alloc_ = nullptr; }; } #endif
#include "arolla/memory/memory_allocation.h" #include <memory> #include <utility> #include "gtest/gtest.h" #include "arolla/memory/frame.h" namespace arolla { namespace { struct DeleteCounter { ~DeleteCounter() { ++deletions; } static int deletions; }; int DeleteCounter::deletions = 0; TEST(MemoryAllocationTest, TestEmptyValues) { FrameLayout::Builder builder; auto slot = builder.AddSlot<std::unique_ptr<DeleteCounter>>(); auto layout = std::move(builder).Build(); ASSERT_EQ(DeleteCounter::deletions, 0); MemoryAllocation alloc(&layout); EXPECT_TRUE(alloc.IsValid()); auto owned_ptr = std::make_unique<DeleteCounter>(); auto ptr = owned_ptr.get(); alloc.frame().Set(slot, std::move(owned_ptr)); EXPECT_EQ(alloc.frame().Get(slot).get(), ptr); MemoryAllocation new_alloc(std::move(alloc)); EXPECT_TRUE(new_alloc.IsValid()); EXPECT_FALSE(alloc.IsValid()); EXPECT_EQ(new_alloc.frame().Get(slot).get(), ptr); EXPECT_EQ(DeleteCounter::deletions, 0); MemoryAllocation newer_alloc(&layout); EXPECT_TRUE(newer_alloc.IsValid()); newer_alloc.frame().Set(slot, std::make_unique<DeleteCounter>()); newer_alloc = std::move(new_alloc); EXPECT_TRUE(newer_alloc.IsValid()); EXPECT_FALSE(new_alloc.IsValid()); EXPECT_EQ(newer_alloc.frame().Get(slot).get(), ptr); EXPECT_EQ(DeleteCounter::deletions, 1); } } }
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/memory/memory_allocation.h
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/memory/memory_allocation_test.cc
1ca990dbeca224035efdabffecc7f3738df6b52c
6dd7503a-c154-49fa-ad75-8d6e30234b59
cpp
google/arolla
buffer
arolla/memory/buffer.h
arolla/memory/buffer_test.cc
#ifndef AROLLA_MEMORY_BUFFER_H_ #define AROLLA_MEMORY_BUFFER_H_ #include <initializer_list> #include <string> #include <variant> #include <vector> #include "absl/strings/string_view.h" #include "arolla/memory/simple_buffer.h" #include "arolla/memory/strings_buffer.h" #include "arolla/memory/void_buffer.h" #include "arolla/util/bytes.h" #include "arolla/util/text.h" namespace arolla { template <typename T> struct BufferTraits { using buffer_type = SimpleBuffer<T>; }; template <> struct BufferTraits<std::monostate> { using buffer_type = VoidBuffer; }; template <> struct BufferTraits<std::string> { using buffer_type = StringsBuffer; }; template <> struct BufferTraits<absl::string_view> { using buffer_type = StringsBuffer; }; template <> struct BufferTraits<Text> { using buffer_type = StringsBuffer; }; template <typename T> using Buffer = typename BufferTraits<T>::buffer_type; template <typename T> Buffer<T> CreateBuffer(std::initializer_list<T> values) { return Buffer<T>::Create(values.begin(), values.end()); } template <typename T> Buffer<T> CreateBuffer(const std::vector<T>& values) { return Buffer<T>::Create(values.begin(), values.end()); } } #endif
#include "arolla/memory/buffer.h" #include <algorithm> #include <array> #include <cstddef> #include <cstdint> #include <tuple> #include <utility> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/hash/hash_testing.h" #include "arolla/qtype/qtype.h" #include "arolla/util/bytes.h" #include "arolla/util/preallocated_buffers.h" #include "arolla/util/text.h" #include "arolla/util/unit.h" namespace arolla { namespace { using ::testing::ElementsAre; using ::testing::ElementsAreArray; using ::testing::Eq; using ::testing::IsEmpty; class BufferTest : public ::testing::Test { public: Buffer<float> CreateTestBuffer(int num_rows) { std::vector<float> values(num_rows); for (int i = 0; i < num_rows; i++) { values[i] = i; } return Buffer<float>::Create(values.begin(), values.end()); } }; TEST_F(BufferTest, Simple) { size_t num_rows = 5; Buffer<float> buffer = CreateTestBuffer(num_rows); EXPECT_TRUE(buffer.is_owner()); EXPECT_THAT(buffer, ElementsAre(0.0f, 1.0f, 2.0f, 3.0f, 4.0f)); EXPECT_EQ(buffer[0], 0.0f); EXPECT_EQ(buffer[4], 4.0f); } struct ComplicatedType { ComplicatedType() : ComplicatedType(0) {} explicit ComplicatedType(int x) { v = x; count++; } ComplicatedType(const ComplicatedType& c) { v = c.v; count++; } ~ComplicatedType() { count--; } bool operator==(const ComplicatedType& other) const { return v == other.v; } int v = 0; static int64_t count; }; int64_t ComplicatedType::count = 0; TEST_F(BufferTest, ComplicatedType) { ASSERT_EQ(ComplicatedType::count, 0); { Buffer<ComplicatedType>::Builder bldr(10); for (int i = 0; i < 5; ++i) { bldr.Set(i, ComplicatedType(i * i)); } Buffer<ComplicatedType> buf = std::move(bldr).Build(5); EXPECT_EQ(ComplicatedType::count, 10); EXPECT_EQ(buf[4].v, 16); } ASSERT_EQ(ComplicatedType::count, 0); { Buffer<ComplicatedType>::Builder bldr(1000); for (int i = 0; i < 5; ++i) { bldr.Set(i, ComplicatedType(-i * i)); } Buffer<ComplicatedType> buf = std::move(bldr).Build(5); EXPECT_EQ(ComplicatedType::count, 5); EXPECT_EQ(buf[4].v, -16); } ASSERT_EQ(ComplicatedType::count, 0); } template <typename T> class BufferUninitializedTest : public ::testing::Test { public: typedef T value_type; }; using BufferUninitializedTestTypes = testing::Types<char, int, float, int64_t, double, uint64_t, QTypePtr, ComplicatedType, Unit, Bytes, Text>; TYPED_TEST_SUITE(BufferUninitializedTest, BufferUninitializedTestTypes); TYPED_TEST(BufferUninitializedTest, CreateUninitializedSmall) { using T = typename TestFixture::value_type; Buffer<T> buffer = Buffer<T>::CreateUninitialized(100); bool expected_to_use_global_buffer = std::is_trivially_destructible_v<T> || std::is_same_v<T, Text> || std::is_same_v<T, Bytes>; EXPECT_EQ(buffer.is_owner(), (!expected_to_use_global_buffer || std::is_same_v<T, Unit>)); EXPECT_THAT(buffer, ElementsAreArray(std::vector<T>(100, T()))); } TYPED_TEST(BufferUninitializedTest, CreateUninitializedBig) { using T = typename TestFixture::value_type; size_t size = kZeroInitializedBufferSize / sizeof(T) + 1; if (std::is_same_v<T, Text> || std::is_same_v<T, Bytes>) { size = kZeroInitializedBufferSize / sizeof(StringsBuffer::Offsets) + 1; } Buffer<T> buffer = Buffer<T>::CreateUninitialized(size); EXPECT_TRUE(buffer.is_owner()); EXPECT_EQ(buffer.size(), size); if (!std::is_trivially_destructible_v<T>) { EXPECT_THAT(buffer, ElementsAreArray(std::vector<T>(size, T()))); } } TEST_F(BufferTest, InitializerListCreate) { Buffer<float> buffer = Buffer<float>::Create({0.0f, 2.0f}); EXPECT_TRUE(buffer.is_owner()); EXPECT_THAT(buffer, ElementsAre(0.0f, 2.0f)); EXPECT_EQ(buffer[0], 0.0f); EXPECT_EQ(buffer[1], 2.0f); } TEST_F(BufferTest, TransferOwnershipFromVector) { std::vector<int> v{1, 2, 3}; int* data = v.data(); auto buf = Buffer<int>::Create(std::move(v)); EXPECT_THAT(buf, ElementsAre(1, 2, 3)); EXPECT_EQ(buf.span().data(), data); } TEST_F(BufferTest, Empty) { Buffer<float> buffer1 = CreateTestBuffer(0); EXPECT_THAT(buffer1, IsEmpty()); Buffer<float> buffer2 = buffer1.DeepCopy(); EXPECT_THAT(buffer2, IsEmpty()); Buffer<float> buffer3; EXPECT_THAT(buffer3, IsEmpty()); } TEST_F(BufferTest, Move) { size_t num_rows = 5; Buffer<float> buffer = CreateTestBuffer(num_rows); EXPECT_TRUE(buffer.is_owner()); Buffer<float> buffer2 = std::move(buffer); EXPECT_TRUE(buffer2.is_owner()); EXPECT_FALSE(buffer.is_owner()); EXPECT_THAT(buffer2, ElementsAre(0.0f, 1.0f, 2.0f, 3.0f, 4.0f)); Buffer<float> buffer3; EXPECT_TRUE(buffer3.is_owner()); buffer3 = std::move(buffer2); EXPECT_TRUE(buffer3.is_owner()); EXPECT_FALSE(buffer2.is_owner()); EXPECT_THAT(buffer3, ElementsAre(0.0f, 1.0f, 2.0f, 3.0f, 4.0f)); } TEST_F(BufferTest, MemoryUsage) { EXPECT_EQ(sizeof(Buffer<float>), 4 * sizeof(void*)); for (size_t sz = 1; sz < 50; sz += 7) { Buffer<float> buffer = CreateTestBuffer(sz); const size_t floats = sz * sizeof(float); EXPECT_EQ(floats, buffer.memory_usage()); } } TEST_F(BufferTest, MoveSlice) { size_t num_rows = 10; Buffer<float> 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(0.0f, 1.0f, 2.0f, 3.0f, 4.0f)); Buffer<float> buffer2 = std::move(buffer).Slice(2, 3); EXPECT_TRUE(buffer2.is_owner()); EXPECT_FALSE(buffer.is_owner()); EXPECT_THAT(buffer2, ElementsAre(2.0f, 3.0f, 4.0f)); } TEST_F(BufferTest, ShallowCopy) { size_t num_rows = 10; Buffer<float> buffer = CreateTestBuffer(num_rows); Buffer<float> 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_EQ(buffer, buffer_copy1); Buffer<float> buffer_copy2 = buffer.Slice(5, 5); EXPECT_TRUE(buffer_copy2.is_owner()); EXPECT_EQ(buffer.begin() + 5, buffer_copy2.begin()); EXPECT_EQ(buffer.span().subspan(5, 5), buffer_copy2.span()); } TEST_F(BufferTest, DeepCopy) { size_t num_rows = 5; Buffer<float> buffer = CreateTestBuffer(num_rows); Buffer<float> buffer_copy = buffer.DeepCopy(); Buffer<float> buffer_slice_copy = buffer.Slice(1, 3).DeepCopy(); buffer = Buffer<float>(); EXPECT_TRUE(buffer_copy.is_owner()); EXPECT_THAT(buffer_copy, ElementsAre(0.0f, 1.0f, 2.0f, 3.0f, 4.0f)); EXPECT_TRUE(buffer_slice_copy.is_owner()); EXPECT_THAT(buffer_slice_copy, ElementsAre(1.0f, 2.0f, 3.0f)); buffer_copy = buffer.DeepCopy(); EXPECT_THAT(buffer_copy, IsEmpty()); } TEST_F(BufferTest, EmptySlice) { size_t num_rows = 10; Buffer<float> buffer = CreateTestBuffer(num_rows); Buffer<float> copy = buffer.Slice(3, 0); EXPECT_THAT(copy, IsEmpty()); EXPECT_EQ(copy.begin(), nullptr); buffer = std::move(buffer).Slice(3, 0); EXPECT_THAT(buffer, IsEmpty()); EXPECT_EQ(buffer.begin(), nullptr); copy = buffer.Slice(0, 0); EXPECT_THAT(copy, IsEmpty()); EXPECT_EQ(copy.begin(), nullptr); } TEST_F(BufferTest, UnownedBuffer) { float values[] = {1.0f, 2.0f, 3.0f, 4.0f, 5.0f}; Buffer<float> buffer(nullptr, values); EXPECT_THAT(buffer.begin(), Eq(&values[0])); EXPECT_THAT(buffer, ElementsAre(1.0f, 2.0f, 3.0f, 4.0f, 5.0f)); EXPECT_FALSE(buffer.is_owner()); auto slice = buffer.Slice(1, 3); EXPECT_THAT(slice, ElementsAre(2.0f, 3.0f, 4.0f)); EXPECT_THAT(slice.begin(), Eq(&values[1])); EXPECT_FALSE(slice.is_owner()); auto deep_copy = buffer.DeepCopy(); std::fill(values, values + 5, 0.0f); EXPECT_TRUE(deep_copy.is_owner()); EXPECT_THAT(deep_copy, ElementsAre(1.0f, 2.0f, 3.0f, 4.0f, 5.0f)); } TEST_F(BufferTest, SupportsAbslHash) { Buffer<float> empty; std::array<float, 5> values = {1, 2, 3, 4, 5}; Buffer<float> test1 = Buffer<float>::Create(values.begin(), values.end()); Buffer<float> test2 = Buffer<float>::Create(values.rbegin(), values.rend()); EXPECT_TRUE( absl::VerifyTypeImplementsAbslHashCorrectly({empty, test1, test2})); } TEST(BufferBuilder, ReshuffleBuilder) { auto b = CreateBuffer<int>({5, 4, 3, 2, 1}); Buffer<int>::ReshuffleBuilder bldr(8, b, 0); bldr.CopyValueToRange(6, 8, 3); bldr.CopyValue(3, 1); bldr.CopyValue(1, 2); bldr.CopyValue(2, 0); auto res = std::move(bldr).Build(); EXPECT_THAT(res, ElementsAre(0, 3, 5, 4, 0, 0, 2, 2)); } TEST(BufferBuilder, MutableSpan) { Buffer<float>::Builder builder(10); auto span = builder.GetMutableSpan(); for (int i = 0; i < 10; ++i) span[i] = i; auto buffer = std::move(builder).Build(5); EXPECT_THAT(buffer, ElementsAre(0.0f, 1.0f, 2.0f, 3.0f, 4.0f)); } TEST(BufferBuilder, Inserter) { Buffer<float>::Builder builder(10); auto inserter = builder.GetInserter(1); for (int i = 0; i < 4; ++i) inserter.Add(i); builder.Set(0, 5); auto buffer = std::move(builder).Build(inserter); EXPECT_THAT(buffer, ElementsAre(5.f, 0.0f, 1.0f, 2.0f, 3.0f)); } TEST(BufferBuilder, Generator) { Buffer<int>::Builder builder(10); builder.SetNConst(0, 10, -1); int i = 0; builder.SetN(2, 3, [&]() { return ++i; }); auto buffer = std::move(builder).Build(6); EXPECT_THAT(buffer, ElementsAre(-1, -1, 1, 2, 3, -1)); } TEST(BufferBuilder, RandomAccess) { Buffer<float>::Builder builder(10); builder.Set(4, 1); builder.Set(2, 2); builder.Set(1, 3); builder.Set(0, 4); builder.Set(3, 5); builder.Set(1, 6); auto buffer = std::move(builder).Build(5); EXPECT_THAT(buffer, ElementsAre(4.f, 6.f, 2.f, 5.f, 1.f)); } TEST(BufferBuilder, Tuple) { Buffer<std::tuple<int, float>>::Builder builder(10); for (int i = 0; i < 5; ++i) { builder.Set(i, {i * 2, i * 0.5}); } auto buffer = std::move(builder).Build(5); EXPECT_THAT(buffer, ElementsAre(std::tuple<int, float>{0, 0.0}, std::tuple<int, float>{2, 0.5}, std::tuple<int, float>{4, 1.0}, std::tuple<int, float>{6, 1.5}, std::tuple<int, float>{8, 2.0})); } } }
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/memory/buffer.h
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/memory/buffer_test.cc
1ca990dbeca224035efdabffecc7f3738df6b52c
5c7ae049-08bd-4f1f-ae08-81f1ad0558fe
cpp
google/arolla
void_buffer
arolla/memory/void_buffer.h
arolla/memory/void_buffer_test.cc
#ifndef AROLLA_MEMORY_VOID_BUFFER_H_ #define AROLLA_MEMORY_VOID_BUFFER_H_ #include <cstddef> #include <cstdint> #include <variant> #include "arolla/memory/optional_value.h" #include "arolla/memory/raw_buffer_factory.h" #include "arolla/util/iterator.h" #include "arolla/util/unit.h" namespace arolla { class VoidBuffer { public: using value_type = std::monostate; using size_type = int64_t; using difference_type = int64_t; using const_iterator = ConstArrayIterator<VoidBuffer>; using offset_type = int64_t; explicit VoidBuffer(int64_t size = 0) : size_(size) {} bool is_owner() const { return true; } bool empty() const { return (size_ == 0); } int64_t size() const { return size_; } value_type operator[](int64_t offset) const { return {}; } const_iterator begin() const { return const_iterator{this, 0}; } const_iterator end() const { return const_iterator{this, size()}; } value_type front() const { return {}; } value_type back() const { return {}; } bool operator==(const VoidBuffer& other) const { return size_ == other.size_; } bool operator!=(const VoidBuffer& other) const { return !(*this == other); } VoidBuffer ShallowCopy() const { return VoidBuffer(size_); } VoidBuffer DeepCopy(RawBufferFactory* = nullptr) const { return VoidBuffer(size_); } VoidBuffer Slice(int64_t offset, int64_t count) const { return VoidBuffer(count); } static VoidBuffer CreateUninitialized(size_t size, RawBufferFactory* = nullptr) { return VoidBuffer(size); } template <typename Iter> static VoidBuffer Create(Iter begin, Iter end, RawBufferFactory* = nullptr) { return VoidBuffer(std::distance(begin, end)); } struct Inserter { int64_t size = 0; void Add(value_type) { size++; } void SkipN(int64_t count) { size += count; } }; class Builder { public: Builder() = default; Builder(Builder&&) = default; Builder& operator=(Builder&&) = default; explicit Builder(int64_t max_size, RawBufferFactory* = nullptr) : max_size_(max_size) {} void Set(int64_t, value_type) {} void Copy(int64_t, int64_t) {} template <typename T> void SetN(int64_t first_offset, int64_t count, T) {} void SetNConst(int64_t first_offset, int64_t count, value_type) {} VoidBuffer Build(int64_t size) && { return VoidBuffer(size); } VoidBuffer Build() && { return VoidBuffer(max_size_); } Inserter GetInserter(int64_t offset = 0) { return Inserter(); } VoidBuffer Build(Inserter ins) && { return VoidBuffer(ins.size); } private: int64_t max_size_; }; class ReshuffleBuilder { public: explicit ReshuffleBuilder(int64_t new_size, VoidBuffer, const OptionalValue<Unit>&, RawBufferFactory* buf_factory = nullptr) : size_(new_size) {} void CopyValue(int64_t, int64_t) {} void CopyValueToRange(int64_t new_index_from, int64_t new_index_to, int64_t old_index) {} VoidBuffer Build() && { return VoidBuffer(size_); } VoidBuffer Build(int64_t size) && { return VoidBuffer(size); } private: int64_t size_; }; size_t memory_usage() const { return 0; } template <typename H> friend H AbslHashValue(H h, const VoidBuffer& buffer) { return H::combine(std::move(h), buffer.size_); } private: int64_t size_; }; } #endif
#include <variant> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/hash/hash_testing.h" #include "arolla/memory/buffer.h" namespace arolla { namespace { using ::testing::ElementsAre; using ::testing::Eq; using ::testing::IsEmpty; using ::testing::Not; using Void = std::monostate; TEST(VoidBuffer, Simple) { VoidBuffer buffer(4); EXPECT_TRUE(buffer.is_owner()); EXPECT_THAT(buffer, Not(IsEmpty())); EXPECT_THAT(buffer.size(), Eq(4)); EXPECT_THAT(buffer.front(), Eq(Void{})); EXPECT_THAT(buffer.back(), Eq(Void())); EXPECT_THAT(buffer, ElementsAre(Void(), Void(), Void(), Void())); EXPECT_EQ(buffer, VoidBuffer(4)); EXPECT_NE(buffer, VoidBuffer(5)); EXPECT_THAT(buffer.Slice(1, 2), Eq(VoidBuffer(2))); } TEST(VoidBuffer, SupportsAbslHash) { EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly( {Buffer<Void>(0), Buffer<Void>(10)})); } } }
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/memory/void_buffer.h
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/memory/void_buffer_test.cc
1ca990dbeca224035efdabffecc7f3738df6b52c
5036342e-0544-4dc5-a2c3-c2d51efedf19
cpp
google/arolla
qtype_traits
arolla/qtype/qtype_traits.h
arolla/qtype/qtype_traits_test.cc
#ifndef AROLLA_QTYPE_QTYPE_TRAITS_H_ #define AROLLA_QTYPE_QTYPE_TRAITS_H_ #include <type_traits> #include "absl/base/attributes.h" #include "absl/log/check.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/util/demangle.h" namespace arolla { template <typename T> struct QTypeTraits; template <typename T, typename = void> struct has_qtype_traits : std::false_type {}; template <typename T> struct has_qtype_traits<T, std::void_t<decltype(QTypeTraits<T>::type())>> : std::true_type {}; template <typename T> constexpr bool has_qtype_traits_v = has_qtype_traits<T>::value; template <typename T> ABSL_ATTRIBUTE_ALWAYS_INLINE inline QTypePtr GetQType() { static_assert( has_qtype_traits_v<T>, "QTypeTraits<T> specialization is not included. #include file with " "QTypeTraits<T> expliclty to fix this problem. " "E.g., #include \"arolla/qtype/base_types.h\" for standard " "Arolla scalar and OptionalValue types."); DCHECK(typeid(T) == QTypeTraits<T>::type()->type_info()) << "There is an error in the QType implementation for " << QTypeTraits<T>::type()->name(); DCHECK(sizeof(T) <= QTypeTraits<T>::type()->type_layout().AllocSize()) << "QType " << QTypeTraits<T>::type()->name() << " has too small frame layout to carry a value of C++ type " << TypeName<T>(); return QTypeTraits<T>::type(); } #define AROLLA_DECLARE_QTYPE(...) \ template <> \ struct QTypeTraits<__VA_ARGS__> { \ static QTypePtr type(); \ } template <> struct QTypeTraits<QTypePtr> { static QTypePtr type() { return GetQTypeQType(); } }; } #endif
#include "arolla/qtype/qtype_traits.h" namespace arolla { struct WithQTypeTraits {}; AROLLA_DECLARE_QTYPE(WithQTypeTraits); struct WithoutQTypeTraits {}; static_assert(has_qtype_traits_v<WithQTypeTraits>); static_assert(!has_qtype_traits_v<WithoutQTypeTraits>); }
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/qtype/qtype_traits.h
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/qtype/qtype_traits_test.cc
1ca990dbeca224035efdabffecc7f3738df6b52c
e2b61ad0-5e16-4782-b7ce-a9f1973adf27
cpp
google/arolla
struct_field
arolla/util/struct_field.h
arolla/util/struct_field_test.cc
#ifndef AROLLA_UTIL_STRUCT_FIELD_H_ #define AROLLA_UTIL_STRUCT_FIELD_H_ #include <array> #include <cstddef> #include <tuple> #include <type_traits> #include <utility> #include "absl/base/attributes.h" #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/strings/string_view.h" #include "arolla/util/demangle.h" namespace arolla { template <typename T, bool kIsSkipped = false> struct StructField { static constexpr bool kIsIncludedToArollaQType = !kIsSkipped; static_assert(!kIsIncludedToArollaQType || !std::is_array_v<T>, "array field types are not supported"); using field_type = T; size_t field_offset; absl::string_view field_name; }; template <class FieldType> const FieldType* UnsafeGetStructFieldPtr(const StructField<FieldType>& field, const void* value) { return reinterpret_cast<const FieldType*>(static_cast<const char*>(value) + field.field_offset); } namespace struct_field_impl { template <typename T, typename Enabled = void> struct StructFieldTraits { static constexpr auto ArollaStructFields() { return std::tuple(); } }; template <typename T> struct StructFieldTraits< T, std::enable_if_t<std::is_invocable_v<decltype(T::ArollaStructFields)>>> { static auto ArollaStructFields() { return T::ArollaStructFields(); } }; template <class T, class FieldTuple, size_t... Is> absl::Status VerifyArollaStructFields( ABSL_ATTRIBUTE_UNUSED const FieldTuple& fields, std::index_sequence<Is...>) { if constexpr (sizeof...(Is) != 0) { auto offsets = std::array<size_t, sizeof...(Is)>{std::get<Is>(fields).field_offset...}; auto alignments = std::array<size_t, sizeof...(Is)>{ alignof(typename std::tuple_element_t<Is, FieldTuple>::field_type)...}; auto sizes = std::array<size_t, sizeof...(Is)>{ sizeof(typename std::tuple_element_t<Is, FieldTuple>::field_type)...}; if (offsets[0] != 0) { return absl::FailedPreconditionError( "first struct field defined incorrectly"); } if (!(((Is == 0) || (offsets[Is] > offsets[Is - 1])) && ...)) { return absl::FailedPreconditionError("struct fields are out of order"); } auto align_offset = [](size_t offset, size_t alignment) constexpr { return offset + (offset % alignment == 0 ? 0 : alignment - offset % alignment); }; if (!(((Is == 0) || (offsets[Is] <= align_offset(offsets[Is - 1] + sizes[Is - 1], alignments[Is]))) && ...)) { return absl::FailedPreconditionError( "struct field is missed in the middle"); } if (align_offset(offsets.back() + sizes.back(), alignof(T)) != sizeof(T)) { return absl::FailedPreconditionError("struct field is missed at the end"); } } return absl::OkStatus(); } } template <class T> const auto& GetStructFields() { ABSL_ATTRIBUTE_UNUSED static const bool once = [] { const auto fields = struct_field_impl::StructFieldTraits<T>::ArollaStructFields(); constexpr size_t kSize = std::tuple_size_v<decltype(fields)>; CHECK_OK(struct_field_impl::VerifyArollaStructFields<T>( fields, std::make_index_sequence<kSize>())) << TypeName<T>(); return true; }(); auto filter_and_convert_to_tuple = [](auto struct_field) { using StructField = decltype(struct_field); if constexpr (StructField::kIsIncludedToArollaQType) { return std::tuple<StructField>{struct_field}; } else { return std::tuple<>(); } }; static const auto filtered_fields = std::apply( [&](auto... struct_fields) { return std::tuple_cat(filter_and_convert_to_tuple(struct_fields)...); }, struct_field_impl::StructFieldTraits<T>::ArollaStructFields()); return filtered_fields; } template <class T> constexpr size_t StructFieldCount() { return std::tuple_size_v<std::decay_t<decltype(GetStructFields<T>())>>; } template <class T> constexpr bool HasStructFields() { return StructFieldCount<T>() != 0; } #define AROLLA_DECLARE_STRUCT_FIELD(NAME) \ ::arolla::StructField<decltype(CppType::NAME)> { \ .field_offset = offsetof(CppType, NAME), .field_name = #NAME \ } #define AROLLA_SKIP_STRUCT_FIELD(NAME) \ ::arolla::StructField<decltype(CppType::NAME), true> { \ .field_offset = offsetof(CppType, NAME), .field_name = #NAME \ } } #endif
#include "arolla/util/struct_field.h" #include <cstddef> #include <cstdint> #include <string> #include <tuple> #include <type_traits> #include <utility> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "absl/status/status_matchers.h" #include "arolla/memory/frame.h" #include "arolla/memory/memory_allocation.h" #include "arolla/util/meta.h" namespace { using ::absl_testing::StatusIs; using ::testing::MatchesRegex; struct Point { int x; float y; constexpr static auto ArollaStructFields() { using CppType = Point; return std::tuple{ AROLLA_DECLARE_STRUCT_FIELD(x), AROLLA_DECLARE_STRUCT_FIELD(y), }; } }; struct Rectangle { Point upper_left; Point lower_bound; std::string name; constexpr static auto ArollaStructFields() { using CppType = Rectangle; return std::tuple{ AROLLA_DECLARE_STRUCT_FIELD(upper_left), AROLLA_DECLARE_STRUCT_FIELD(lower_bound), AROLLA_DECLARE_STRUCT_FIELD(name), }; } }; template <class A, class B, class C, bool kIsBSkipped = false> struct Tripple { A a; B b; C c; constexpr static auto ArollaStructFields() { using CppType = Tripple; if constexpr (kIsBSkipped) { return std::tuple{ AROLLA_DECLARE_STRUCT_FIELD(a), AROLLA_SKIP_STRUCT_FIELD(b), AROLLA_DECLARE_STRUCT_FIELD(c), }; } else { return std::tuple{ AROLLA_DECLARE_STRUCT_FIELD(a), AROLLA_DECLARE_STRUCT_FIELD(b), AROLLA_DECLARE_STRUCT_FIELD(c), }; } } }; struct UnsupportedSkippedFields { struct UnknownType {}; int a; void* b; float c; UnknownType d; constexpr static auto ArollaStructFields() { using CppType = UnsupportedSkippedFields; return std::tuple{ AROLLA_DECLARE_STRUCT_FIELD(a), AROLLA_SKIP_STRUCT_FIELD(b), AROLLA_DECLARE_STRUCT_FIELD(c), AROLLA_SKIP_STRUCT_FIELD(d), }; } }; TEST(DeclareMacroTest, MacroInternalTest) { using CppType = Point; Point p{5, 7.}; auto field_x = AROLLA_DECLARE_STRUCT_FIELD(x); static_assert(std::is_same_v<decltype(field_x)::field_type, int>); EXPECT_EQ(field_x.field_offset, offsetof(Point, x)); EXPECT_EQ(field_x.field_name, "x"); EXPECT_EQ(::arolla::UnsafeGetStructFieldPtr(field_x, &p), &p.x); auto field_y = AROLLA_DECLARE_STRUCT_FIELD(y); static_assert(std::is_same_v<decltype(field_y)::field_type, float>); EXPECT_EQ(field_y.field_offset, offsetof(Point, y)); EXPECT_EQ(field_y.field_name, "y"); EXPECT_EQ(::arolla::UnsafeGetStructFieldPtr(field_y, &p), &p.y); } } namespace arolla { namespace { TEST(StructFieldTest, UnsupportedSkippedFields) { auto t = arolla::GetStructFields<UnsupportedSkippedFields>(); EXPECT_EQ(std::tuple_size_v<decltype(t)>, 2); EXPECT_EQ(std::get<0>(t).field_name, "a"); EXPECT_EQ(std::get<1>(t).field_name, "c"); } TEST(StructFieldTest, PaddingVerification) { meta::foreach_type( meta::type_list<std::bool_constant<true>, std::bool_constant<false>>(), [](auto t) { constexpr bool kIsBSkipped = typename decltype(t)::type(); constexpr size_t kExpectedFieldCount = kIsBSkipped ? 2 : 3; { auto t = arolla::GetStructFields< Tripple<int, char, double, kIsBSkipped>>(); EXPECT_EQ(std::tuple_size_v<decltype(t)>, kExpectedFieldCount); EXPECT_EQ(std::get<0>(t).field_name, "a"); if constexpr (kIsBSkipped) { EXPECT_EQ(std::get<1>(t).field_name, "c"); } else { EXPECT_EQ(std::get<1>(t).field_name, "b"); EXPECT_EQ(std::get<2>(t).field_name, "c"); } } { auto t = ::arolla::GetStructFields< Tripple<char, char, double, kIsBSkipped>>(); EXPECT_EQ(std::tuple_size_v<decltype(t)>, kExpectedFieldCount); } { auto t = ::arolla::GetStructFields< Tripple<char, double, char, kIsBSkipped>>(); EXPECT_EQ(std::tuple_size_v<decltype(t)>, kExpectedFieldCount); } { auto t = ::arolla::GetStructFields< Tripple<double, char, char, kIsBSkipped>>(); EXPECT_EQ(std::tuple_size_v<decltype(t)>, kExpectedFieldCount); } { auto t = ::arolla::GetStructFields<Tripple<int, int, int, kIsBSkipped>>(); EXPECT_EQ(std::tuple_size_v<decltype(t)>, kExpectedFieldCount); } { auto t = ::arolla::GetStructFields< Tripple<int16_t, char, double, kIsBSkipped>>(); EXPECT_EQ(std::tuple_size_v<decltype(t)>, kExpectedFieldCount); } { auto t = ::arolla::GetStructFields< Tripple<int, double, int16_t, kIsBSkipped>>(); EXPECT_EQ(std::tuple_size_v<decltype(t)>, kExpectedFieldCount); } }); } TEST(LayoutTest, Point) { FrameLayout::Builder builder; auto point_slot = builder.AddSlot<Point>(); auto layout = std::move(builder).Build(); MemoryAllocation alloc(&layout); FramePtr frame = alloc.frame(); frame.Set(point_slot, {5, 7.}); FrameLayout::Slot<int> x_slot = point_slot.GetSubslot<0>(); EXPECT_EQ(frame.Get(x_slot), 5); FrameLayout::Slot<float> y_slot = point_slot.GetSubslot<1>(); EXPECT_EQ(frame.Get(y_slot), 7.); } TEST(LayoutTest, Rectangle) { FrameLayout::Builder builder; auto rectangle_slot = builder.AddSlot<Rectangle>(); auto layout = std::move(builder).Build(); MemoryAllocation alloc(&layout); FramePtr frame = alloc.frame(); frame.Set(rectangle_slot, {{-5, -7.}, {5, 7.}, "ABCD"}); FrameLayout::Slot<Point> ul_slot = rectangle_slot.GetSubslot<0>(); FrameLayout::Slot<int> ulx_slot = ul_slot.GetSubslot<0>(); FrameLayout::Slot<float> uly_slot = ul_slot.GetSubslot<1>(); EXPECT_EQ(frame.Get(ulx_slot), -5); EXPECT_EQ(frame.Get(uly_slot), -7.); FrameLayout::Slot<Point> lb_slot = rectangle_slot.GetSubslot<1>(); FrameLayout::Slot<int> lbx_slot = lb_slot.GetSubslot<0>(); FrameLayout::Slot<float> lby_slot = lb_slot.GetSubslot<1>(); EXPECT_EQ(frame.Get(lbx_slot), 5); EXPECT_EQ(frame.Get(lby_slot), 7.); FrameLayout::Slot<std::string> name_slot = rectangle_slot.GetSubslot<2>(); EXPECT_EQ(frame.Get(name_slot), "ABCD"); } TEST(VerifyArollaStructFieldsTest, MissedFirst) { struct MissedFirst { int a; int b; int c; constexpr static auto ArollaStructFields() { using CppType = MissedFirst; return std::tuple{ AROLLA_DECLARE_STRUCT_FIELD(b), AROLLA_DECLARE_STRUCT_FIELD(c), }; } }; EXPECT_THAT(struct_field_impl::VerifyArollaStructFields<MissedFirst>( MissedFirst::ArollaStructFields(), std::make_index_sequence<StructFieldCount<MissedFirst>()>()), StatusIs(absl::StatusCode::kFailedPrecondition, MatchesRegex(".*first.*incorrectly.*"))); } TEST(VerifyArollaStructFieldsTest, MissedMiddle) { struct MissedMiddle { int a; int b; int c; constexpr static auto ArollaStructFields() { using CppType = MissedMiddle; return std::tuple{ AROLLA_DECLARE_STRUCT_FIELD(a), AROLLA_DECLARE_STRUCT_FIELD(c), }; } }; EXPECT_THAT(struct_field_impl::VerifyArollaStructFields<MissedMiddle>( MissedMiddle::ArollaStructFields(), std::make_index_sequence<StructFieldCount<MissedMiddle>()>()), StatusIs(absl::StatusCode::kFailedPrecondition, MatchesRegex(".*missed.*middle.*"))); } TEST(VerifyArollaStructFieldsTest, MissedEnd) { struct MissedEnd { int a; int b; int c; constexpr static auto ArollaStructFields() { using CppType = MissedEnd; return std::tuple{ AROLLA_DECLARE_STRUCT_FIELD(a), AROLLA_DECLARE_STRUCT_FIELD(b), }; } }; EXPECT_THAT(struct_field_impl::VerifyArollaStructFields<MissedEnd>( MissedEnd::ArollaStructFields(), std::make_index_sequence<StructFieldCount<MissedEnd>()>()), StatusIs(absl::StatusCode::kFailedPrecondition, MatchesRegex(".*missed.*end.*"))); } TEST(VerifyArollaStructFieldsTest, OutOfOrder) { struct OutOfOrder { int a; int b; int c; constexpr static auto ArollaStructFields() { using CppType = OutOfOrder; return std::tuple{ AROLLA_DECLARE_STRUCT_FIELD(a), AROLLA_DECLARE_STRUCT_FIELD(c), AROLLA_DECLARE_STRUCT_FIELD(b), }; } }; EXPECT_THAT(struct_field_impl::VerifyArollaStructFields<OutOfOrder>( OutOfOrder::ArollaStructFields(), std::make_index_sequence<StructFieldCount<OutOfOrder>()>()), StatusIs(absl::StatusCode::kFailedPrecondition, MatchesRegex(".*out.*order.*"))); } } }
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/util/struct_field.h
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/util/struct_field_test.cc
1ca990dbeca224035efdabffecc7f3738df6b52c
00ceddf4-ea80-4620-be1c-41a58cd93bcb
cpp
google/arolla
refcount_ptr
arolla/util/refcount_ptr.h
arolla/util/refcount_ptr_test.cc
#ifndef AROLLA_UTIL_REFCOUNT_PTR_H_ #define AROLLA_UTIL_REFCOUNT_PTR_H_ #include <cstddef> #include <memory> #include <ostream> #include <type_traits> #include <utility> #include "absl/base/nullability.h" #include "arolla/util/refcount.h" namespace arolla { template <typename T> class RefcountPtr; class RefcountedBase { mutable Refcount refcount_; template <typename T> friend class RefcountPtr; }; template <typename T> class RefcountPtr { public: template <typename... Args> static constexpr RefcountPtr<T> Make(Args&&... args) noexcept { return RefcountPtr( std::make_unique<T>(std::forward<Args>(args)...).release()); } static constexpr RefcountPtr<T> Own(std::unique_ptr<T>&& ptr) noexcept { return RefcountPtr(ptr.release()); } static RefcountPtr<T> NewRef(T* ptr) noexcept { if (ptr != nullptr) { ptr->refcount_.increment(); } return RefcountPtr(ptr); } constexpr RefcountPtr() noexcept = default; constexpr RefcountPtr( std::nullptr_t) noexcept {} RefcountPtr(const RefcountPtr& rhs) noexcept : ptr_(rhs.ptr_) { if (ptr_ != nullptr) { ptr_->refcount_.increment(); } } RefcountPtr(RefcountPtr&& rhs) noexcept : ptr_(rhs.ptr_) { rhs.ptr_ = nullptr; } ~RefcountPtr() noexcept(noexcept(reset())) { reset(); } RefcountPtr& operator=(const RefcountPtr& rhs) noexcept(noexcept(reset())) { if (ptr_ != rhs.ptr_) { const auto tmp = std::move(*this); ptr_ = rhs.ptr_; if (ptr_ != nullptr) { ptr_->refcount_.increment(); } } return *this; } RefcountPtr& operator=(RefcountPtr&& rhs) noexcept { T* const tmp = ptr_; ptr_ = rhs.ptr_; rhs.ptr_ = tmp; return *this; } void reset() noexcept(std::is_nothrow_destructible_v<T>) { T* const tmp = ptr_; ptr_ = nullptr; if (tmp != nullptr && !tmp->refcount_.decrement()) { delete tmp; } } constexpr bool operator==(std::nullptr_t) const noexcept { return ptr_ == nullptr; } constexpr bool operator!=(std::nullptr_t) const noexcept { return ptr_ != nullptr; } bool operator==(const RefcountPtr& rhs) const noexcept { return ptr_ == rhs.ptr_; } bool operator!=(const RefcountPtr& rhs) const noexcept { return ptr_ != rhs.ptr_; } constexpr T* get() const noexcept { return ptr_; } T& operator*() const noexcept { return *ptr_; } T* operator->() const noexcept { return ptr_; } friend void swap(RefcountPtr& lhs, RefcountPtr& rhs) noexcept { T* const tmp = lhs.ptr_; lhs.ptr_ = rhs.ptr_; rhs.ptr_ = tmp; } using absl_nullability_compatible = void; private: explicit constexpr RefcountPtr(T* ptr) noexcept : ptr_(ptr) {} T* ptr_ = nullptr; }; template <typename T> std::ostream& operator<<(std::ostream& ostream, const RefcountPtr<T>& ptr) { return ostream << static_cast<T*>(ptr.get()); } template <typename T> T* GetRawPointer(const RefcountPtr<T>& ptr) { return ptr.get(); } } #endif
#include "arolla/util/refcount_ptr.h" #include <memory> #include <sstream> #include <type_traits> #include <utility> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/cleanup/cleanup.h" #include "absl/log/check.h" namespace arolla { namespace { using ::testing::IsNull; using ::testing::Pointer; struct RefcountedObject : RefcountedBase { static int instance_counter; int value = 0; RefcountedObject() { ++instance_counter; } ~RefcountedObject() { --instance_counter; } }; struct RefcountedObjectWithArgs : RefcountedBase { static int instance_counter; int x; std::unique_ptr<int> non_copyable_y; RefcountedObjectWithArgs(int x, std::unique_ptr<int> non_copyable_y) : x(x), non_copyable_y(std::move(non_copyable_y)) { ++instance_counter; } ~RefcountedObjectWithArgs() { --instance_counter; } }; int RefcountedObject::instance_counter; int RefcountedObjectWithArgs::instance_counter; using RefcountedObjectPtr = RefcountPtr<RefcountedObject>; using RefcountedObjectWithArgsPtr = RefcountPtr<RefcountedObjectWithArgs>; class RefcountPtrTest : public ::testing::Test { protected: void SetUp() override { ASSERT_EQ(RefcountedObject::instance_counter, 0); } void TearDown() override { ASSERT_EQ(RefcountedObject::instance_counter, 0); } }; static_assert(!std::is_copy_constructible_v<RefcountedBase> && !std::is_copy_assignable_v<RefcountedBase>); static_assert(!std::is_move_constructible_v<RefcountedBase> && !std::is_move_assignable_v<RefcountedBase>); TEST(RefcountPtr, Make) { auto ptr = RefcountedObjectWithArgsPtr::Make(2, std::make_unique<int>(3)); EXPECT_EQ(RefcountedObjectWithArgs::instance_counter, 1); EXPECT_EQ(ptr->x, 2); const std::unique_ptr<int>& non_copyable_y = ptr->non_copyable_y; EXPECT_EQ(*non_copyable_y, 3); } TEST(RefcountPtr, Own) { auto unique_ptr = std::make_unique<RefcountedObject>(); EXPECT_EQ(RefcountedObject::instance_counter, 1); auto* raw_ptr = unique_ptr.get(); auto ptr = RefcountedObjectPtr::Own(std::move(unique_ptr)); EXPECT_THAT(ptr, Pointer(raw_ptr)); } TEST(RefcountPtr, OwnNullptr) { auto ptr = RefcountedObjectPtr::Own(std::unique_ptr<RefcountedObject>()); EXPECT_THAT(ptr, IsNull()); } TEST(RefcountPtr, NewRef) { auto unique_ptr = std::make_unique<RefcountedObject>(); EXPECT_EQ(RefcountedObject::instance_counter, 1); auto* raw_ptr = unique_ptr.get(); auto ptr1 = RefcountedObjectPtr::Own(std::move(unique_ptr)); EXPECT_EQ(RefcountedObject::instance_counter, 1); auto ptr2 = RefcountedObjectPtr::NewRef(raw_ptr); EXPECT_THAT(ptr2.get(), Pointer(raw_ptr)); EXPECT_EQ(RefcountedObject::instance_counter, 1); ptr1.reset(); EXPECT_EQ(RefcountedObject::instance_counter, 1); ptr2.reset(); EXPECT_EQ(RefcountedObject::instance_counter, 0); } TEST(RefcountPtr, NewRefNullptr) { auto ptr = RefcountedObjectPtr::NewRef(nullptr); EXPECT_THAT(ptr, IsNull()); } TEST(RefcountPtr, DefaultConstructor) { EXPECT_THAT(RefcountedObjectPtr(), IsNull()); } TEST(RefcountPtr, NullptrConstructor) { EXPECT_THAT(RefcountedObjectPtr(nullptr), IsNull()); } TEST(RefcountPtr, CopyConstructor) { auto unique_ptr = std::make_unique<RefcountedObject>(); auto* raw_ptr = unique_ptr.get(); auto ptr1 = RefcountedObjectPtr::Own(std::move(unique_ptr)); auto ptr2 = ptr1; EXPECT_THAT(ptr2, Pointer(raw_ptr)); } TEST(RefcountPtr, CopyConstructorNullptr) { auto ptr1 = RefcountedObjectPtr{}; auto ptr2 = ptr1; EXPECT_THAT(ptr2, IsNull()); } TEST(RefcountPtr, MoveConstructor) { auto unique_ptr = std::make_unique<RefcountedObject>(); auto* raw_ptr = unique_ptr.get(); auto ptr1 = RefcountedObjectPtr::Own(std::move(unique_ptr)); auto ptr2 = std::move(ptr1); EXPECT_THAT(ptr2, Pointer(raw_ptr)); } TEST(RefcountPtr, MoveConstructorNullptr) { auto ptr1 = RefcountedObjectPtr(); auto ptr2 = std::move(ptr1); EXPECT_THAT(ptr2, IsNull()); } TEST(RefcountPtr, CopyOperator) { auto unique_ptr1 = std::make_unique<RefcountedObject>(); auto* raw_ptr1 = unique_ptr1.get(); auto ptr1 = RefcountedObjectPtr::Own(std::move(unique_ptr1)); ptr1 = ptr1; ASSERT_THAT(ptr1, Pointer(raw_ptr1)); auto ptr2 = RefcountedObjectPtr::Own(std::make_unique<RefcountedObject>()); ptr2 = ptr1; ASSERT_THAT(ptr1, Pointer(raw_ptr1)); ASSERT_THAT(ptr2, Pointer(raw_ptr1)); ptr2 = ptr1; ASSERT_THAT(ptr1, Pointer(raw_ptr1)); ASSERT_THAT(ptr2, Pointer(raw_ptr1)); } TEST(RefcountPtr, CopyOperatorNullptr) { auto ptr1 = RefcountedObjectPtr(); auto ptr2 = RefcountedObjectPtr::Own(std::make_unique<RefcountedObject>()); ptr2 = ptr1; ASSERT_THAT(ptr1, IsNull()); ASSERT_THAT(ptr2, IsNull()); ptr2 = ptr1; ASSERT_THAT(ptr1, IsNull()); ASSERT_THAT(ptr2, IsNull()); } TEST(RefcountPtr, MoveOperator) { auto unique_ptr1 = std::make_unique<RefcountedObject>(); auto* raw_ptr1 = unique_ptr1.get(); auto ptr1 = RefcountedObjectPtr::Own(std::move(unique_ptr1)); auto ptr2 = RefcountedObjectPtr::Own(std::make_unique<RefcountedObject>()); ptr2 = std::move(ptr1); ASSERT_THAT(ptr2, Pointer(raw_ptr1)); ptr1 = std::move(ptr2); ASSERT_THAT(ptr1, Pointer(raw_ptr1)); } TEST(RefcountPtr, MoveOperatorNullptr) { auto ptr1 = RefcountedObjectPtr(); auto ptr2 = RefcountedObjectPtr::Own(std::make_unique<RefcountedObject>()); ptr2 = std::move(ptr1); ASSERT_THAT(ptr2, IsNull()); ptr1 = std::move(ptr2); ASSERT_THAT(ptr1, IsNull()); } TEST(RefcountPtr, Reset) { auto ptr = RefcountedObjectPtr::Own(std::make_unique<RefcountedObject>()); ptr.reset(); ASSERT_THAT(ptr, IsNull()); ptr.reset(); ASSERT_THAT(ptr, IsNull()); } TEST(RefcountPtr, Compare) { auto ptr1 = RefcountedObjectPtr::Own(std::make_unique<RefcountedObject>()); { auto ptr2 = RefcountedObjectPtr(); ASSERT_FALSE((ptr1 == nullptr)); ASSERT_TRUE((ptr1 != nullptr)); ASSERT_TRUE((ptr2 == nullptr)); ASSERT_FALSE((ptr2 != nullptr)); } { auto ptr1_copy = ptr1; auto ptr2 = RefcountedObjectPtr::Own(std::make_unique<RefcountedObject>()); EXPECT_TRUE(ptr1 == ptr1); EXPECT_TRUE(ptr2 == ptr2); EXPECT_TRUE(ptr1 == ptr1_copy); EXPECT_FALSE(ptr1 != ptr1); EXPECT_FALSE(ptr2 != ptr2); EXPECT_FALSE(ptr1 != ptr1_copy); EXPECT_FALSE(ptr1 == ptr2); EXPECT_TRUE(ptr1 != ptr2); } } TEST(RefcountPtr, Swap) { using std::swap; auto unique_ptr1 = std::make_unique<RefcountedObject>(); auto unique_ptr2 = std::make_unique<RefcountedObject>(); auto* raw_ptr1 = unique_ptr1.get(); auto* raw_ptr2 = unique_ptr2.get(); auto ptr1 = RefcountedObjectPtr::Own(std::move(unique_ptr1)); auto ptr2 = RefcountedObjectPtr::Own(std::move(unique_ptr2)); swap(ptr1, ptr2); ASSERT_THAT(ptr1, Pointer(raw_ptr2)); ASSERT_THAT(ptr2, Pointer(raw_ptr1)); swap(ptr1, ptr1); ASSERT_THAT(ptr1, Pointer(raw_ptr2)); ASSERT_THAT(ptr2, Pointer(raw_ptr1)); } TEST(RefcountPtr, Get) { auto unique_ptr = std::make_unique<RefcountedObject>(); auto* raw_ptr = unique_ptr.get(); auto ptr = RefcountedObjectPtr::Own(std::move(unique_ptr)); ASSERT_EQ(ptr.get(), raw_ptr); } TEST(RefcountPtr, Dereference) { auto ptr = RefcountedObjectPtr::Own(std::make_unique<RefcountedObject>()); (*ptr).value = 1; ASSERT_EQ(ptr->value, 1); ptr->value = 2; ASSERT_EQ((*ptr).value, 2); } TEST(RefcountPtr, OStream) { auto ptr = RefcountedObjectPtr::Own(std::make_unique<RefcountedObject>()); std::ostringstream actual; std::ostringstream expected; actual << ptr; expected << ptr.get(); ASSERT_EQ(actual.str(), expected.str()); } TEST(RefcountPtr, Checks) { auto ptr1 = RefcountedObjectPtr::Own(std::make_unique<RefcountedObject>()); auto ptr2 = RefcountedObjectPtr(); CHECK_NE(ptr1, nullptr); CHECK_EQ(ptr2, nullptr); DCHECK_NE(ptr1, nullptr); DCHECK_EQ(ptr2, nullptr); } TEST(RefcountPtr, SelfReferencingCopyAssignment) { struct SelfReferencingObject; using SelfReferencingObjectPtr = RefcountPtr<SelfReferencingObject>; struct SelfReferencingObject : public RefcountedBase { SelfReferencingObjectPtr parent = nullptr; ~SelfReferencingObject() noexcept = default; }; auto ptr = SelfReferencingObjectPtr::Make(); ptr->parent = SelfReferencingObjectPtr::Make(); ptr = ptr->parent; } TEST(RefcountPtr, SelfReferencingChain) { struct SelfReferencingObject; using SelfReferencingObjectPtr = RefcountPtr<SelfReferencingObject>; struct SelfReferencingObject : public RefcountedBase { SelfReferencingObjectPtr parent = nullptr; ~SelfReferencingObject() noexcept { thread_local bool is_cleanup_ongoing = false; thread_local SelfReferencingObjectPtr to_destruct; to_destruct = std::move(parent); if (is_cleanup_ongoing) { return; } is_cleanup_ongoing = true; absl::Cleanup reset_flag = [&] { is_cleanup_ongoing = false; }; while (to_destruct != nullptr) { to_destruct.reset(); } } }; auto ptr1 = SelfReferencingObjectPtr::Make(); ptr1->parent = SelfReferencingObjectPtr::Make(); ptr1->parent->parent = SelfReferencingObjectPtr::Make(); } } }
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/util/refcount_ptr.h
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/util/refcount_ptr_test.cc
1ca990dbeca224035efdabffecc7f3738df6b52c
3b9c8a87-0a4d-43ad-924a-6cf494b4f7e3
cpp
google/arolla
operator_name
arolla/util/operator_name.h
arolla/util/operator_name_test.cc
#ifndef AROLLA_UTIL_OPERATOR_NAME_H_ #define AROLLA_UTIL_OPERATOR_NAME_H_ #include "absl/strings/string_view.h" #include "arolla/util/string.h" namespace arolla { constexpr bool IsOperatorName(absl::string_view name) { return IsQualifiedIdentifier(name); } #define AROLLA_OPERATOR_NAME(name) \ ( \ []() { \ static_assert(::arolla::IsOperatorName(name), \ "Invalid operator name."); \ }(), \ name) } #endif
#include "arolla/util/operator_name.h" #include <string> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/strings/string_view.h" namespace arolla { namespace { using ::testing::Eq; using ::testing::StrEq; TEST(OperatorNameTest, Macro) { const char* name1 = AROLLA_OPERATOR_NAME("foo.bar"); EXPECT_THAT(name1, StrEq("foo.bar")); absl::string_view name2 = AROLLA_OPERATOR_NAME("foo.bar"); EXPECT_THAT(name2, Eq("foo.bar")); std::string name3 = AROLLA_OPERATOR_NAME("foo.bar"); EXPECT_THAT(name1, Eq("foo.bar")); } } }
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/util/operator_name.h
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/util/operator_name_test.cc
1ca990dbeca224035efdabffecc7f3738df6b52c
e0e3962d-5ba1-46ae-a510-9b91e916ddc4
cpp
google/arolla
map
arolla/util/map.h
arolla/util/map_test.cc
#ifndef AROLLA_UTIL_MAP_H_ #define AROLLA_UTIL_MAP_H_ #include <algorithm> #include <vector> namespace arolla { template <class Map> std::vector<typename Map::key_type> SortedMapKeys(const Map& map) { std::vector<typename Map::key_type> result; result.reserve(map.size()); for (const auto& item : map) { result.push_back(item.first); } std::sort(result.begin(), result.end()); return result; } } #endif
#include "arolla/util/map.h" #include <string> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/container/flat_hash_map.h" namespace arolla { namespace { using ::testing::ElementsAre; using ::testing::TypedEq; struct V {}; TEST(SortedMapKeys, small) { EXPECT_THAT(SortedMapKeys(absl::flat_hash_map<int, V>{}), ElementsAre()); EXPECT_THAT(SortedMapKeys(absl::flat_hash_map<char, V>{{0, V{}}}), ElementsAre(TypedEq<char>(0))); EXPECT_THAT(SortedMapKeys( absl::flat_hash_map<std::string, V>{{"1", V{}}, {"0", V{}}}), ElementsAre("0", "1")); } TEST(SortedMapKeys, big) { absl::flat_hash_map<std::string, V> m; for (int i = 1000; i != 10000; ++i) { m.emplace(std::to_string(i), V{}); } std::vector<std::string> keys = SortedMapKeys(m); EXPECT_EQ(keys.size(), 9000); auto it = keys.begin(); for (int i = 1000; i != 10000; ++i, ++it) { EXPECT_EQ(*it, std::to_string(i)); } } } }
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/util/map.h
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/util/map_test.cc
1ca990dbeca224035efdabffecc7f3738df6b52c
1cc91eed-892b-4197-b92b-ad38eaf993c4
cpp
google/arolla
lru_cache
arolla/util/lru_cache.h
arolla/util/lru_cache_test.cc
#ifndef AROLLA_UTIL_LRU_CACHE_H_ #define AROLLA_UTIL_LRU_CACHE_H_ #include <cstddef> #include <functional> #include <list> #include <utility> #include "absl/base/nullability.h" #include "absl/container/flat_hash_set.h" #include "absl/hash/hash.h" #include "absl/log/check.h" namespace arolla { template <typename Key, typename Value, typename KeyHash = absl::Hash<Key>, typename KeyEq = std::equal_to<>> class LruCache { public: explicit LruCache(size_t capacity) : capacity_(capacity) { DCHECK_GT(capacity, 0); index_.reserve(capacity + 1); } LruCache(const LruCache&) = delete; LruCache& operator=(const LruCache&) = delete; template <typename K> [[nodiscard]] absl::Nullable<const Value*> LookupOrNull(K&& key) { if (auto it = index_.find(std::forward<K>(key)); it != index_.end()) { entries_.splice(entries_.begin(), entries_, it->entry); return &it->entry->second; } return nullptr; } template <typename K, typename V> [[nodiscard]] absl::Nonnull<const Value*> Put(K&& key, V&& value) { entries_.emplace_front(std::forward<K>(key), std::forward<V>(value)); const auto& [it, ok] = index_.emplace(IndexEntry{entries_.begin()}); if (!ok) { entries_.pop_front(); entries_.splice(entries_.begin(), entries_, it->entry); } else if (entries_.size() > capacity_) { index_.erase(entries_.back().first); entries_.pop_back(); } DCHECK_LE(entries_.size(), capacity_); DCHECK_EQ(entries_.size(), index_.size()); return &entries_.front().second; } void Clear() { entries_.clear(); index_.clear(); } private: using Entry = std::pair<const Key, const Value>; struct IndexEntry { typename std::list<Entry>::iterator entry; }; struct IndexRecordHash { using is_transparent = void; size_t operator()(const IndexEntry& index_record) const { return KeyHash()(index_record.entry->first); } template <typename K> size_t operator()(K&& key) const { return KeyHash()(std::forward<K>(key)); } }; struct IndexRecordEq { using is_transparent = void; bool operator()(const IndexEntry& lhs, const IndexEntry& rhs) const { return KeyEq()(lhs.entry->first, rhs.entry->first); } template <typename K> bool operator()(const IndexEntry& lhs, K&& rhs) const { return KeyEq()(lhs.entry->first, std::forward<K>(rhs)); } }; using Index = absl::flat_hash_set<IndexEntry, IndexRecordHash, IndexRecordEq>; size_t capacity_; std::list<Entry> entries_; Index index_; }; } #endif
#include "arolla/util/lru_cache.h" #include <functional> #include <string> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/hash/hash.h" #include "absl/strings/string_view.h" namespace arolla { namespace { using ::testing::IsNull; using ::testing::Pointee; TEST(LruCache, BasicBehaviuor) { LruCache<int, double, std::hash<int>, std::equal_to<int>> cache(2); ASSERT_THAT(cache.LookupOrNull(1), IsNull()); ASSERT_THAT(cache.LookupOrNull(2), IsNull()); ASSERT_THAT(cache.LookupOrNull(3), IsNull()); (void)cache.Put(1, 1.5); ASSERT_THAT(cache.LookupOrNull(1), Pointee(1.5)); ASSERT_THAT(cache.LookupOrNull(2), IsNull()); ASSERT_THAT(cache.LookupOrNull(3), IsNull()); (void)cache.Put(2, 2.5); ASSERT_THAT(cache.LookupOrNull(1), Pointee(1.5)); ASSERT_THAT(cache.LookupOrNull(2), Pointee(2.5)); ASSERT_THAT(cache.LookupOrNull(3), IsNull()); (void)cache.Put(3, 3.5); ASSERT_THAT(cache.LookupOrNull(1), IsNull()); ASSERT_THAT(cache.LookupOrNull(2), Pointee(2.5)); ASSERT_THAT(cache.LookupOrNull(3), Pointee(3.5)); } TEST(LruCache, TransparentKeyType) { LruCache<std::string, int, absl::Hash<absl::string_view>, std::equal_to<>> cache(3); (void)cache.Put("1", 1); (void)cache.Put(absl::string_view("2"), 2); (void)cache.Put(std::string("3"), 3); ASSERT_THAT(cache.LookupOrNull("1"), Pointee(1)); ASSERT_THAT(cache.LookupOrNull("2"), Pointee(2)); ASSERT_THAT(cache.LookupOrNull("3"), Pointee(3)); ASSERT_THAT(cache.LookupOrNull(absl::string_view("1")), Pointee(1)); ASSERT_THAT(cache.LookupOrNull(absl::string_view("2")), Pointee(2)); ASSERT_THAT(cache.LookupOrNull(absl::string_view("3")), Pointee(3)); ASSERT_THAT(cache.LookupOrNull(std::string("1")), Pointee(1)); ASSERT_THAT(cache.LookupOrNull(std::string("2")), Pointee(2)); ASSERT_THAT(cache.LookupOrNull(std::string("3")), Pointee(3)); } TEST(LruCache, Clear) { LruCache<int, double> cache(2); ASSERT_THAT(cache.LookupOrNull(1), IsNull()); (void)cache.Put(1, 1.5); ASSERT_THAT(cache.LookupOrNull(1), Pointee(1.5)); cache.Clear(); ASSERT_THAT(cache.LookupOrNull(1), IsNull()); } TEST(LruCache, Overwrite) { LruCache<int, double> cache(2); (void)cache.Put(1, 1.5); ASSERT_THAT(cache.LookupOrNull(1), Pointee(1.5)); (void)cache.Put(1, 2.5); ASSERT_THAT(cache.LookupOrNull(1), Pointee(1.5)); } TEST(LruCache, EvictionOrder) { { LruCache<int, double> cache(2); (void)cache.Put(1, 1.0); (void)cache.Put(2, 2.0); (void)cache.Put(3, 3.0); EXPECT_THAT(cache.LookupOrNull(1), IsNull()); EXPECT_THAT(cache.LookupOrNull(2), Pointee(2.0)); EXPECT_THAT(cache.LookupOrNull(3), Pointee(3.0)); } { LruCache<int, double> cache(2); (void)cache.Put(1, 1.0); (void)cache.Put(2, 2.0); (void)cache.LookupOrNull(1); (void)cache.Put(3, 3.0); EXPECT_THAT(cache.LookupOrNull(1), Pointee(1.0)); EXPECT_THAT(cache.LookupOrNull(2), IsNull()); EXPECT_THAT(cache.LookupOrNull(3), Pointee(3.0)); } { LruCache<int, double> cache(2); (void)cache.Put(1, 1.0); (void)cache.Put(2, 2.0); (void)cache.Put(1, 1.1); (void)cache.Put(3, 3.0); EXPECT_THAT(cache.LookupOrNull(1), Pointee(1.0)); EXPECT_THAT(cache.LookupOrNull(2), IsNull()); EXPECT_THAT(cache.LookupOrNull(3), Pointee(3.0)); } } TEST(LruCache, LookupPointerStability) { LruCache<int, double> cache(3); (void)cache.Put(1, 1.0); (void)cache.Put(2, 2.0); (void)cache.Put(3, 3.0); auto* p0 = cache.LookupOrNull(0); auto* p1 = cache.LookupOrNull(1); auto* p2 = cache.LookupOrNull(2); auto* q0 = cache.LookupOrNull(0); auto* q1 = cache.LookupOrNull(1); auto* q2 = cache.LookupOrNull(2); EXPECT_EQ(p0, q0); EXPECT_EQ(p1, q1); EXPECT_EQ(p2, q2); } } }
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/util/lru_cache.h
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/util/lru_cache_test.cc
1ca990dbeca224035efdabffecc7f3738df6b52c
c8c785cb-0a1c-4856-9184-3546aad84b13
cpp
google/arolla
switch_index
arolla/util/switch_index.h
arolla/util/switch_index_test.cc
#ifndef AROLLA_UTIL_SWITCH_INDEX_H_ #define AROLLA_UTIL_SWITCH_INDEX_H_ #include <cassert> #include <type_traits> #include <utility> #include "absl/base/attributes.h" namespace arolla { #define CASE_1(k) \ case (k): \ return std::forward<Callback>(callback)(std::integral_constant<int, (k)>()) #define CASE_4(k) \ CASE_1(k); \ CASE_1(k + 1); \ CASE_1(k + 2); \ CASE_1(k + 3) #define CASE_16(k) \ CASE_4(k); \ CASE_4(k + 4); \ CASE_4(k + 8); \ CASE_4(k + 12) template <typename Callback> auto switch_index_32(int n, Callback&& callback) { assert(0 <= n && n < 32); switch (n) { CASE_16(0); CASE_16(16); } return std::forward<Callback>(callback)(std::integral_constant<int, 31>()); } template <typename Callback> auto switch_index_64(int n, Callback&& callback) { assert(0 <= n && n < 64); switch (n) { CASE_16(0); CASE_16(16); CASE_16(32); CASE_16(48); } return std::forward<Callback>(callback)(std::integral_constant<int, 63>()); } template <int N, typename Callback> inline ABSL_ATTRIBUTE_ALWAYS_INLINE auto switch_index(int n, Callback&& callback) { static_assert(N == 32 || N == 64); if constexpr (N == 32) { return switch_index_32(n, std::forward<Callback>(callback)); } else { return switch_index_64(n, std::forward<Callback>(callback)); } } #undef CASE_16 #undef CASE_4 #undef CASE_1 } #endif
#include "arolla/util/switch_index.h" #include <string> #include "gtest/gtest.h" namespace arolla::testing { namespace { template <int N> void test_switch_index() { for (int i = 0; i < N; ++i) { EXPECT_EQ(std::to_string(i), switch_index<N>(i, [i](auto arg) { constexpr int constexpr_i = arg(); EXPECT_EQ(i, constexpr_i); return std::to_string(constexpr_i); })); } } TEST(SwitchIndex, switch_index_32) { test_switch_index<32>(); } TEST(SwitchIndex, switch_index_64) { test_switch_index<64>(); } } }
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/util/switch_index.h
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/util/switch_index_test.cc
1ca990dbeca224035efdabffecc7f3738df6b52c
a58caa09-5c30-4a02-8b26-4a5ad48596f1
cpp
google/arolla
thread_safe_shared_ptr
arolla/util/thread_safe_shared_ptr.h
arolla/util/thread_safe_shared_ptr_test.cc
#ifndef AROLLA_UTIL_THREAD_SAFE_SHARED_PTR_H_ #define AROLLA_UTIL_THREAD_SAFE_SHARED_PTR_H_ #include <cstddef> #include <memory> #include "absl/base/thread_annotations.h" #include "absl/synchronization/mutex.h" namespace arolla { template <typename T> class ThreadSafeSharedPtr { public: ThreadSafeSharedPtr() = default; explicit ThreadSafeSharedPtr(std::shared_ptr<T> ptr) : ptr_(std::move(ptr)) {} ThreadSafeSharedPtr(const ThreadSafeSharedPtr&) = delete; ThreadSafeSharedPtr& operator=(const ThreadSafeSharedPtr&) = delete; bool operator==(std::nullptr_t) const ABSL_LOCKS_EXCLUDED(mx_) { absl::MutexLock guard(&mx_); return ptr_ == nullptr; } bool operator!=(std::nullptr_t) const ABSL_LOCKS_EXCLUDED(mx_) { return !(*this == nullptr); } std::shared_ptr<T> load() const ABSL_LOCKS_EXCLUDED(mx_) { absl::MutexLock guard(&mx_); return ptr_; } void store(std::shared_ptr<T> ptr) ABSL_LOCKS_EXCLUDED(mx_) { absl::MutexLock guard(&mx_); ptr.swap(ptr_); } private: std::shared_ptr<T> ptr_ ABSL_GUARDED_BY(mx_); mutable absl::Mutex mx_; }; } #endif
#include "arolla/util/thread_safe_shared_ptr.h" #include <array> #include <memory> #include <string> #include "benchmark/benchmark.h" #include "gtest/gtest.h" #include "absl/base/no_destructor.h" namespace arolla { namespace { TEST(ThreadSafeSharedPtr, DefaultConstructor) { ThreadSafeSharedPtr<std::string> ptr; EXPECT_TRUE(ptr == nullptr); EXPECT_FALSE(ptr != nullptr); EXPECT_EQ(ptr.load(), nullptr); } TEST(ThreadSafeSharedPtr, Constructor) { auto hello = std::make_shared<std::string>("Hello"); ThreadSafeSharedPtr<std::string> ptr(hello); EXPECT_FALSE(ptr == nullptr); EXPECT_TRUE(ptr != nullptr); EXPECT_EQ(ptr.load(), hello); } TEST(ThreadSafeSharedPtr, Store) { auto hello = std::make_shared<std::string>("Hello"); auto world = std::make_shared<std::string>("World"); ThreadSafeSharedPtr<std::string> ptr; EXPECT_EQ(ptr.load(), nullptr); ptr.store(hello); EXPECT_EQ(ptr.load(), hello); ptr.store(world); EXPECT_EQ(ptr.load(), world); } void BM_ThreadSafeSharedPtr_Load(benchmark::State& state) { static absl::NoDestructor<ThreadSafeSharedPtr<std::string>> storage( std::make_shared<std::string>("Hello, World!")); for (auto _ : state) { auto tmp = storage->load(); benchmark::DoNotOptimize(tmp); } } void BM_ThreadSafeSharedPtr_Store(benchmark::State& state) { static absl::NoDestructor<ThreadSafeSharedPtr<std::string>> storage( std::make_shared<std::string>("Hello, World!")); std::array<std::shared_ptr<std::string>, 2> values = { std::make_shared<std::string>("Hello"), std::make_shared<std::string>("World")}; unsigned int idx = 0; for (auto _ : state) { storage->store(values[++idx & 1]); } } BENCHMARK(BM_ThreadSafeSharedPtr_Load)->ThreadRange(1, 8); BENCHMARK(BM_ThreadSafeSharedPtr_Store)->ThreadRange(1, 8); } }
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/util/thread_safe_shared_ptr.h
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/util/thread_safe_shared_ptr_test.cc
1ca990dbeca224035efdabffecc7f3738df6b52c
fd40ac30-586f-4884-9c6e-7edd9bbe0bf6
cpp
google/arolla
memory
arolla/util/memory.h
arolla/util/memory_test.cc
#ifndef AROLLA_UTIL_MEMORY_H_ #define AROLLA_UTIL_MEMORY_H_ #include <cstddef> #include <cstdint> #include <cstdlib> #include <memory> #include "absl/log/check.h" namespace arolla { struct FreeDeleter { void operator()(const void* ptr) const { std::free(const_cast<void*>(ptr)); } }; using MallocPtr = std::unique_ptr<void, FreeDeleter>; struct Alignment { size_t value; }; inline MallocPtr AlignedAlloc(Alignment alignment, size_t size) { DCHECK(alignment.value > 0 && !(alignment.value & (alignment.value - 1))); if (size == 0) { size = 1; } if (alignment.value <= sizeof(void*)) { return MallocPtr(std::malloc(size)); } void* result = nullptr; if (posix_memalign(&result, alignment.value, size)) { result = nullptr; } DCHECK(result) << "posix_memalign failed."; return MallocPtr(result); } inline bool IsAlignedPtr(size_t alignment, const void* ptr) { DCHECK(alignment > 0 && !(alignment & (alignment - 1))); return (reinterpret_cast<uintptr_t>(ptr) & (alignment - 1)) == 0; } inline bool IsAlignedPtr(Alignment alignment, const void* ptr) { return IsAlignedPtr(alignment.value, ptr); } } #endif
#include "arolla/util/memory.h" #include <cstdint> #include <vector> #include "gtest/gtest.h" namespace arolla { namespace { TEST(Memory, IsAlignedPtr) { std::vector<char> range(128, 0); for (auto& ref : range) { EXPECT_EQ(IsAlignedPtr(32, &ref), reinterpret_cast<uintptr_t>(&ref) % 32 == 0); } } TEST(Memory, AlignedAlloc) { std::vector<MallocPtr> ptrs; for (int i = 0; i < 100; ++i) { ptrs.push_back(AlignedAlloc(Alignment{64}, 3)); } for (const auto& ptr : ptrs) { EXPECT_TRUE(IsAlignedPtr(64, ptr.get())); } EXPECT_NE(AlignedAlloc(Alignment{1}, 0).get(), nullptr); EXPECT_NE(AlignedAlloc(Alignment{1}, 64).get(), nullptr); } } }
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/util/memory.h
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/util/memory_test.cc
1ca990dbeca224035efdabffecc7f3738df6b52c
f6761b5b-a721-4091-a0f7-e88701bb858b
cpp
google/arolla
fast_dynamic_downcast_final
arolla/util/fast_dynamic_downcast_final.h
arolla/util/fast_dynamic_downcast_final_test.cc
#ifndef AROLLA_UTIL_FAST_DYNAMIC_DOWNCAST_FINAL_H_ #define AROLLA_UTIL_FAST_DYNAMIC_DOWNCAST_FINAL_H_ #include <type_traits> #include <typeinfo> #include "absl/base/attributes.h" namespace arolla { template <typename T, typename S> ABSL_ATTRIBUTE_ALWAYS_INLINE inline T fast_dynamic_downcast_final(S* src) { static_assert(std::is_pointer_v<T>); static_assert( !std::is_const_v<S> || std::is_const_v<std::remove_pointer_t<T>>, "cannot cast 'const' to 'non-const'"); using DecayedT = std::decay_t<std::remove_pointer_t<T>>; using DecayedS = std::decay_t<S>; static_assert(!std::is_same_v<DecayedS, DecayedT>); static_assert(std::is_base_of_v<DecayedS, DecayedT>); static_assert( std::is_convertible_v<DecayedT*, DecayedS*>); static_assert(std::is_polymorphic_v<DecayedS>); static_assert(std::is_final_v<DecayedT>); if (src != nullptr && typeid(*src) == typeid(DecayedT)) { return static_cast<T>(src); } return nullptr; } } #endif
#include "arolla/util/fast_dynamic_downcast_final.h" #include <new> #include "gtest/gtest.h" namespace arolla { namespace { class A { public: virtual ~A() = default; }; class B final : public A {}; class C : public A {}; class D final : public C {}; TEST(FastDynamicDownCastFinal, Basics) { B b; D d; EXPECT_EQ(fast_dynamic_downcast_final<B*>(std::launder<A>(nullptr)), nullptr); EXPECT_EQ(fast_dynamic_downcast_final<D*>(std::launder<A>(nullptr)), nullptr); EXPECT_EQ(fast_dynamic_downcast_final<B*>(std::launder<A>(&b)), &b); EXPECT_EQ(fast_dynamic_downcast_final<B*>(std::launder<A>(&d)), nullptr); EXPECT_EQ(fast_dynamic_downcast_final<D*>(std::launder<A>(&b)), nullptr); EXPECT_EQ(fast_dynamic_downcast_final<D*>(std::launder<A>(&d)), &d); EXPECT_EQ(fast_dynamic_downcast_final<D*>(std::launder<C>(&d)), &d); EXPECT_EQ( fast_dynamic_downcast_final<const B*>(std::launder<const A>(nullptr)), nullptr); EXPECT_EQ( fast_dynamic_downcast_final<const D*>(std::launder<const A>(nullptr)), nullptr); EXPECT_EQ(fast_dynamic_downcast_final<const B*>(std::launder<const A>(&b)), &b); EXPECT_EQ(fast_dynamic_downcast_final<const B*>(std::launder<const A>(&d)), nullptr); EXPECT_EQ(fast_dynamic_downcast_final<const D*>(std::launder<const A>(&b)), nullptr); EXPECT_EQ(fast_dynamic_downcast_final<const D*>(std::launder<const A>(&d)), &d); EXPECT_EQ(fast_dynamic_downcast_final<const D*>(std::launder<const C>(&d)), &d); } class E { public: virtual ~E() = default; }; class F final : public A, public E {}; TEST(FastDynamicDownCastFinal, MultiInheritance) { F f; EXPECT_EQ(fast_dynamic_downcast_final<F*>(std::launder<A>(nullptr)), nullptr); EXPECT_EQ(fast_dynamic_downcast_final<F*>(std::launder<E>(nullptr)), nullptr); EXPECT_EQ(fast_dynamic_downcast_final<F*>(std::launder<A>(&f)), &f); EXPECT_EQ(fast_dynamic_downcast_final<F*>(std::launder<E>(&f)), &f); EXPECT_EQ(fast_dynamic_downcast_final<const F*>(std::launder<A>(nullptr)), nullptr); EXPECT_EQ(fast_dynamic_downcast_final<const F*>(std::launder<E>(nullptr)), nullptr); EXPECT_EQ(fast_dynamic_downcast_final<const F*>(std::launder<A>(&f)), &f); EXPECT_EQ(fast_dynamic_downcast_final<const F*>(std::launder<E>(&f)), &f); } } }
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/util/fast_dynamic_downcast_final.h
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/util/fast_dynamic_downcast_final_test.cc
1ca990dbeca224035efdabffecc7f3738df6b52c
6a8cc5b4-5166-4312-8960-1ad8d88de028
cpp
google/arolla
refcount
arolla/util/refcount.h
arolla/util/refcount_test.cc
#ifndef AROLLA_UTIL_REFCOUNT_H_ #define AROLLA_UTIL_REFCOUNT_H_ #include <atomic> #include <cstdint> namespace arolla { class Refcount { public: constexpr Refcount() noexcept : count_{1} {} void increment() noexcept { count_.fetch_add(1, std::memory_order_relaxed); } [[nodiscard]] bool decrement() noexcept { return count_.fetch_sub(1, std::memory_order_acq_rel) != 1; } [[nodiscard]] bool skewed_decrement() noexcept { auto refcount = count_.load(std::memory_order_acquire); return refcount != 1 && count_.fetch_sub(1, std::memory_order_acq_rel) != 1; } struct TestOnly {}; constexpr Refcount(TestOnly, int initial_count) noexcept : count_{initial_count} {} private: std::atomic<int32_t> count_; }; } #endif
#include "arolla/util/refcount.h" #include "gtest/gtest.h" namespace arolla { namespace { TEST(RefcountTest, Decrement) { { Refcount refcount; EXPECT_FALSE(refcount.decrement()); } { Refcount refcount; EXPECT_FALSE(refcount.skewed_decrement()); } } TEST(RefcountTest, IncrementDecrement) { constexpr int N = 10; { Refcount refcount; for (int i = 0; i < N; ++i) { refcount.increment(); } for (int i = 0; i < N; ++i) { ASSERT_TRUE(refcount.decrement()); } ASSERT_FALSE(refcount.decrement()); } { Refcount refcount; for (int i = 0; i < N; ++i) { refcount.increment(); } for (int i = 0; i < N; ++i) { ASSERT_TRUE(refcount.skewed_decrement()); } ASSERT_FALSE(refcount.skewed_decrement()); } } } }
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/util/refcount.h
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/util/refcount_test.cc
1ca990dbeca224035efdabffecc7f3738df6b52c
c5e4d7d2-b829-43c7-a717-d8e1a08b6a64
cpp
google/arolla
meta
arolla/util/meta.h
arolla/util/meta_test.cc
#ifndef AROLLA_UTIL_META_H_ #define AROLLA_UTIL_META_H_ #include <cstddef> #include <functional> #include <tuple> #include <type_traits> #include <utility> #include "absl/base/attributes.h" namespace arolla::meta { template <class T> struct type_ { using type = T; }; template <typename T> using type = type_<T>; template <class... TypeTraits> struct type_list { using tuple = std::tuple<TypeTraits...>; }; template <class L> struct head; template <class T, class... Ts> struct head<type_list<T, Ts...>> : type<T> {}; template <class L> using head_t = typename head<L>::type; template <class L> struct tail; template <class T, class... Ts> struct tail<type_list<T, Ts...>> { using type = type_list<Ts...>; }; template <class L> using tail_t = typename tail<L>::type; template <class L1, class L2> struct concat; template <class... Ts1, class... Ts2> struct concat<type_list<Ts1...>, type_list<Ts2...>> { using type = type_list<Ts1..., Ts2...>; }; template <class L1, class L2> using concat_t = typename concat<L1, L2>::type; template <typename Fn, typename... Ts> ABSL_ATTRIBUTE_ALWAYS_INLINE inline constexpr void foreach_type( type_list<Ts...>, Fn fn) { (fn(type<Ts>()), ...); } template <typename TypeList, typename Fn> ABSL_ATTRIBUTE_ALWAYS_INLINE inline constexpr void foreach_type(Fn fn) { foreach_type(TypeList(), fn); } template <typename TypeList, typename T> struct contains : std::false_type {}; template <typename T, typename... Ts> struct contains<type_list<Ts...>, T> : std::disjunction<std::is_same<T, Ts>...> {}; template <typename TypeList, typename T> constexpr bool contains_v = contains<TypeList, T>::value; template <typename T> struct function_traits : public function_traits<decltype(&T::operator())> {}; template <typename CLS, typename RES, typename... ARGs> struct function_traits<RES (CLS::*)(ARGs...) const> { static constexpr int arity = sizeof...(ARGs); using arg_types = type_list<ARGs...>; using return_type = RES; }; template <typename CLS, typename RES, typename... ARGs> struct function_traits<RES (CLS::*)(ARGs...)> { static constexpr int arity = sizeof...(ARGs); using arg_types = type_list<ARGs...>; using return_type = RES; }; template <typename RES, typename... ARGs> struct function_traits<RES (*)(ARGs...)> { static constexpr int arity = sizeof...(ARGs); using arg_types = type_list<ARGs...>; using return_type = RES; }; template <typename F> struct function_traits<std::reference_wrapper<F>> : function_traits<F> {}; template <template <typename> class Wrapper, class T> struct is_wrapped_with : public std::false_type {}; template <template <typename> class Wrapper, class T> struct is_wrapped_with<Wrapper, Wrapper<T>> : public std::true_type {}; template <template <typename> class Wrapper, class T> constexpr bool is_wrapped_with_v = is_wrapped_with<Wrapper, T>::value; template <template <typename> class Wrapper, class T> struct strip_template { using type = T; }; template <template <typename> class Wrapper, class T> struct strip_template<Wrapper, Wrapper<T>> { using type = T; }; template <template <typename> class Wrapper, class T> using strip_template_t = typename strip_template<Wrapper, T>::type; template <typename T, typename ArgsTypeList, class = void> struct has_create_method_impl : std::false_type {}; template <class T, class... Args> struct has_create_method_impl< T, type_list<Args...>, std::void_t<decltype(T::Create(std::declval<Args>()...))>> : std::true_type {}; template <class T, class... Args> struct has_create_method : public has_create_method_impl<T, type_list<Args...>> {}; template <class T, class... Args> constexpr bool has_create_method_v = has_create_method<T, Args...>::value; template <typename Tuple, typename Fn, size_t... Is> ABSL_ATTRIBUTE_ALWAYS_INLINE inline void foreach_tuple_element_impl( ABSL_ATTRIBUTE_UNUSED Tuple&& tuple, ABSL_ATTRIBUTE_UNUSED Fn&& fn, std::index_sequence<Is...>) { (fn(std::get<Is>(std::forward<Tuple>(tuple))), ...); } template <typename Tuple, typename Fn> ABSL_ATTRIBUTE_ALWAYS_INLINE inline void foreach_tuple_element(Tuple&& tuple, Fn&& fn) { static_assert(std::tuple_size_v<std::decay_t<Tuple>> >= 0, "expected a tuple"); foreach_tuple_element_impl( std::forward<Tuple>(tuple), std::forward<Fn>(fn), std::make_index_sequence<std::tuple_size_v<std::decay_t<Tuple>>>()); } template <typename Tuple, typename Fn, size_t... Is> void foreach_tuple_element_type_impl(ABSL_ATTRIBUTE_UNUSED Fn&& fn, std::index_sequence<Is...>) { (fn(::arolla::meta::type<std::tuple_element_t<Is, Tuple>>()), ...); } template <typename Tuple, typename Fn> void foreach_tuple_element_type(Fn fn) { static_assert(std::tuple_size_v<Tuple> >= 0, "expected a tuple"); foreach_tuple_element_type_impl<Tuple>( std::forward<Fn>(fn), std::make_index_sequence<std::tuple_size_v<Tuple>>()); } template <class, class = void> struct is_transparent : std::false_type {}; template <class T> struct is_transparent<T, std::void_t<typename T::is_transparent>> : std::true_type {}; template <typename T> constexpr bool is_transparent_v = is_transparent<T>::value; } #endif
#include "arolla/util/meta.h" #include <cstdint> #include <functional> #include <optional> #include <tuple> #include <type_traits> #include <typeindex> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/statusor.h" namespace arolla::meta { namespace { using ::testing::ElementsAre; TEST(MetaTest, TypeList) { static_assert( std::is_same_v<head_t<type_list<int64_t, int32_t, int8_t>>, int64_t>); static_assert(std::is_same_v<tail_t<type_list<int64_t, int32_t, int8_t>>, type_list<int32_t, int8_t>>); static_assert(contains_v<type_list<int64_t, int32_t, int8_t>, int32_t>); static_assert( contains_v<type_list<int64_t, int32_t, int32_t, int8_t>, int32_t>); static_assert(!contains_v<type_list<int64_t, int32_t, int8_t>, float>); static_assert(!contains_v<type_list<>, float>); } TEST(MetaTest, ForeachType) { using meta_int_list = type_list<std::integral_constant<int, 1>, std::integral_constant<int, 2>, std::integral_constant<int, 4>, std::integral_constant<int, 8>>; int value = 0; foreach_type<meta_int_list>( [&value](auto meta_type) { value ^= decltype(meta_type)::type::value; }); EXPECT_EQ(value, 15); } TEST(MetaTest, FunctionTraits) { int64_t someValue = 57; auto lambda = [&someValue](int32_t, double) { return static_cast<float>(someValue); }; using lambda_traits = function_traits<decltype(lambda)>; static_assert(lambda_traits::arity == 2); static_assert(std::is_same<typename lambda_traits::arg_types, type_list<int32_t, double>>::value); static_assert( std::is_same<typename lambda_traits::return_type, float>::value); struct ConstFunctor { float operator()(int32_t, double) const { return 57; } }; using const_functor_traits = function_traits<ConstFunctor>; static_assert(const_functor_traits::arity == 2); static_assert(std::is_same<typename const_functor_traits::arg_types, type_list<int32_t, double>>::value); static_assert( std::is_same<typename const_functor_traits::return_type, float>::value); struct NonConstFunctor { float operator()(int32_t, double) { return 57; } }; using non_const_functor_traits = function_traits<NonConstFunctor>; static_assert(non_const_functor_traits::arity == 2); static_assert(std::is_same<typename non_const_functor_traits::arg_types, type_list<int32_t, double>>::value); static_assert(std::is_same<typename non_const_functor_traits::return_type, float>::value); using ref_traits = function_traits<std::reference_wrapper<ConstFunctor>>; static_assert(std::is_same<typename ref_traits::return_type, float>::value); } TEST(MetaTest, is_wrapped_with) { static_assert(is_wrapped_with<std::optional, std::optional<float>>::value); static_assert( is_wrapped_with<::absl::StatusOr, ::absl::StatusOr<float>>::value); } TEST(MetaTest, concat) { static_assert( std::is_same_v<concat_t<type_list<>, type_list<>>, type_list<>>); static_assert( std::is_same_v<concat_t<type_list<>, type_list<void>>, type_list<void>>); static_assert( std::is_same_v<concat_t<type_list<int>, type_list<>>, type_list<int>>); static_assert(std::is_same_v<concat_t<type_list<int>, type_list<void>>, type_list<int, void>>); static_assert(std::is_same_v< concat_t<type_list<int, char, bool>, type_list<void, char>>, type_list<int, char, bool, void, char>>); } TEST(MetaTest, has_create_method) { struct A { explicit A(int v) : value(v) {} int value; }; struct B { static B Create(int v) { return B{.value = v}; } int value; }; static_assert(!has_create_method_v<A, int>); static_assert(!has_create_method_v<B>); static_assert(!has_create_method_v<B, char*>); static_assert(has_create_method_v<B, int>); static_assert(has_create_method_v<B, int16_t>); } TEST(MetaTest, foreach_tuple_element) { { auto tuple = std::tuple(); meta::foreach_tuple_element(tuple, [](auto&) { FAIL(); }); } { std::vector<const void*> result; auto tuple = std::tuple(1, 2.5, "foo"); meta::foreach_tuple_element(tuple, [&](auto& x) { result.push_back(&x); }); EXPECT_THAT(result, ElementsAre(&std::get<0>(tuple), &std::get<1>(tuple), &std::get<2>(tuple))); } } TEST(MetaTest, foreach_tuple_element_type) { { using Tuple = std::tuple<>; meta::foreach_tuple_element_type<Tuple>([](auto) { FAIL(); }); } { using Tuple = std::tuple<int, float, const char*>; std::vector<std::type_index> result; meta::foreach_tuple_element_type<Tuple>([&](auto meta_type) { result.push_back(typeid(typename decltype(meta_type)::type)); }); EXPECT_THAT(result, ElementsAre(std::type_index(typeid(int)), std::type_index(typeid(float)), std::type_index(typeid(const char*)))); } } TEST(MetaTest, is_transparent) { EXPECT_TRUE(is_transparent_v<std::equal_to<>>); EXPECT_FALSE(is_transparent_v<std::equal_to<int>>); } } }
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/util/meta.h
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/util/meta_test.cc
1ca990dbeca224035efdabffecc7f3738df6b52c
1c360f4d-582c-463d-a680-29eb0516227f
cpp
google/arolla
iterator
arolla/util/iterator.h
arolla/util/iterator_test.cc
#ifndef AROLLA_UTIL_ITERATOR_H_ #define AROLLA_UTIL_ITERATOR_H_ #include <iterator> namespace arolla { template <typename Array> class ConstArrayIterator { public: using iterator_category = std::random_access_iterator_tag; using value_type = typename Array::value_type; using pointer = const value_type*; using reference = decltype(std::declval<const Array>()[0]); using size_type = typename Array::size_type; using difference_type = typename Array::difference_type; ConstArrayIterator() : arr_(nullptr), pos_(0) {} ConstArrayIterator(const Array* arr, size_type pos) : arr_(arr), pos_(pos) {} reference operator*() const { return (*arr_)[pos_]; } pointer operator->() const { return &**this; } reference operator[](size_type n) const { return *(*this + n); } ConstArrayIterator& operator+=(difference_type n) { pos_ += n; return *this; } ConstArrayIterator& operator-=(difference_type n) { return *this += -n; } ConstArrayIterator& operator++() { return *this += 1; } ConstArrayIterator& operator--() { return *this -= 1; } ConstArrayIterator operator++(int) { ConstArrayIterator t = *this; ++*this; return t; } ConstArrayIterator operator--(int) { ConstArrayIterator t = *this; --*this; return t; } friend ConstArrayIterator operator+(ConstArrayIterator v, difference_type n) { return v += n; } friend ConstArrayIterator operator+(difference_type n, ConstArrayIterator v) { return v += n; } friend ConstArrayIterator operator-(ConstArrayIterator v, difference_type n) { return v -= n; } friend difference_type operator-(const ConstArrayIterator& a, const ConstArrayIterator& b) { return static_cast<difference_type>(a.pos_) - static_cast<difference_type>(b.pos_); } friend bool operator==(ConstArrayIterator a, ConstArrayIterator b) { return a.pos_ == b.pos_; } friend bool operator!=(ConstArrayIterator a, ConstArrayIterator b) { return !(a == b); } friend bool operator<(ConstArrayIterator a, ConstArrayIterator b) { return b - a > 0; } friend bool operator>(ConstArrayIterator a, ConstArrayIterator b) { return b < a; } friend bool operator<=(ConstArrayIterator a, ConstArrayIterator b) { return !(a > b); } friend bool operator>=(ConstArrayIterator a, ConstArrayIterator b) { return !(a < b); } private: const Array* arr_; size_type pos_; }; } #endif
#include "arolla/util/iterator.h" #include <algorithm> #include <cstdint> #include <iterator> #include <string> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" using ::testing::ElementsAre; namespace arolla { namespace { class FloatGeneratorArray { public: using value_type = float; using size_type = int64_t; using difference_type = int64_t; using const_iterator = ConstArrayIterator<FloatGeneratorArray>; explicit FloatGeneratorArray(int64_t size) : size_(size) {} float operator[](int64_t i) const { return i * 10.0f; } const_iterator begin() const { return const_iterator{this, 0}; } const_iterator end() const { return const_iterator{this, size_}; } private: int64_t size_; }; TEST(Iterator, IteratorOverFloatGeneratorArray) { FloatGeneratorArray array(10); auto iter1 = array.begin(); EXPECT_EQ(*(iter1++), 0.0f); EXPECT_EQ(*iter1, 10.0f); EXPECT_EQ(*(++iter1), 20.0f); EXPECT_EQ(*(iter1--), 20.0f); EXPECT_EQ(*(--iter1), 0.0f); EXPECT_EQ(iter1[5], 50.0f); EXPECT_EQ(iter1, array.begin()); EXPECT_NE(iter1, array.end()); EXPECT_LT(array.begin(), array.end()); EXPECT_GT(array.end(), array.begin()); EXPECT_EQ(*(iter1 += 9), 90.0f); EXPECT_EQ(*(iter1 -= 2), 70.0f); EXPECT_EQ(iter1, array.begin() + 7); EXPECT_EQ(iter1, 7 + array.begin()); EXPECT_EQ(iter1, array.end() - 3); EXPECT_EQ(iter1 - array.begin(), 7); EXPECT_LE(array.begin() + 10, array.end()); EXPECT_GE(array.end(), array.begin() + 10); EXPECT_THAT(array, ElementsAre(0.0f, 10.0f, 20.0f, 30.0f, 40.0f, 50.0f, 60.0f, 70.0f, 80.0f, 90.0f)); } TEST(Iterator, Algorithms) { FloatGeneratorArray array(5); std::vector<float> copy1(array.begin(), array.end()); EXPECT_THAT(copy1, ElementsAre(0.f, 10.f, 20.f, 30.f, 40.f)); std::vector<float> copy2; std::copy_if(array.begin(), array.end(), std::back_inserter(copy2), [](float value) { return value > 12.f; }); EXPECT_THAT(copy2, ElementsAre(20.f, 30.f, 40.f)); std::vector<float> copy3; for (float val : array) { copy3.push_back(val); } EXPECT_THAT(copy3, ElementsAre(0.f, 10.f, 20.f, 30.f, 40.f)); } TEST(Iterator, IteratorOverStdVector) { using StringContainer = std::vector<std::string>; StringContainer strings{"one", "two", "three"}; ConstArrayIterator<StringContainer> my_iter(&strings, 0); EXPECT_EQ(*my_iter, "one"); EXPECT_EQ(my_iter[2], "three"); EXPECT_EQ(my_iter->size(), 3); auto strings_copy = strings; EXPECT_TRUE(std::equal(strings_copy.begin(), strings_copy.end(), my_iter)); EXPECT_THAT(strings, ElementsAre("one", "two", "three")); } } }
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/util/iterator.h
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/util/iterator_test.cc
1ca990dbeca224035efdabffecc7f3738df6b52c
bef8cc3a-91b3-489e-bded-4866f414d7d9
cpp
google/arolla
status_macros_backport
arolla/util/status_macros_backport.h
arolla/util/status_macros_backport_test.cc
#ifndef AROLLA_UTIL_STATUS_MACROS_BACKPORT_H_ #define AROLLA_UTIL_STATUS_MACROS_BACKPORT_H_ #include <sstream> #include <string> #include <utility> #include "absl/base/optimization.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" namespace arolla { namespace status_macros_backport_internal { inline absl::string_view GetStatusMessage(const absl::Status& status) { return status.message(); } template <typename T> inline absl::string_view GetStatusMessage(const absl::StatusOr<T>& status_or) { return status_or.status().message(); } class StatusBuilder { public: explicit StatusBuilder(const ::absl::Status& status) : status_(status) {} explicit StatusBuilder(::absl::Status&& status) : status_(std::move(status)) {} operator ::absl::Status() const { const auto& stream_msg = stream_.str(); if (stream_msg.empty()) { return status_; } ::absl::Status result; if (status_.message().empty()) { result = absl::Status(status_.code(), stream_msg); } else { result = absl::Status(status_.code(), absl::StrCat(status_.message(), "; ", stream_msg)); } status_.ForEachPayload([&](auto type_url, auto payload) { result.SetPayload(std::move(type_url), std::move(payload)); }); return result; } template <typename Adaptor> auto With(Adaptor&& adaptor) { return std::forward<Adaptor>(adaptor)(std::move(*this)); } template <typename T> StatusBuilder& operator<<(const T& extra_msg) & { stream_ << extra_msg; return *this; } template <typename T> StatusBuilder&& operator<<(const T& extra_msg) && { stream_ << extra_msg; return std::move(*this); } private: ::absl::Status status_; std::ostringstream stream_; }; } #define RETURN_IF_ERROR(expr) \ RETURN_IF_ERROR_IMPL(AROLLA_STATUS_IMPL_CONCAT(status, __COUNTER__), expr) #define RETURN_IF_ERROR_IMPL(_status, expr) \ if (auto _status = (expr); _status.ok()) { \ } else \ return ::arolla::status_macros_backport_internal::StatusBuilder(_status) #define ASSIGN_OR_RETURN(...) \ AROLLA_STATUS_IMPL_GET_VARIADIC( \ (__VA_ARGS__, ASSIGN_OR_RETURN_IMPL_3, ASSIGN_OR_RETURN_IMPL_2)) \ (__VA_ARGS__) #define ASSIGN_OR_RETURN_IMPL_2(lhs, rexpr) \ ASSIGN_OR_RETURN_IMPL_3(lhs, rexpr, _) #define ASSIGN_OR_RETURN_IMPL_3(lhs, rexpr, error_expression) \ ASSIGN_OR_RETURN_IMPL(AROLLA_STATUS_IMPL_CONCAT(statusor, __COUNTER__), lhs, \ rexpr, error_expression) #define ASSIGN_OR_RETURN_IMPL(_statusor, lhs, rexpr, error_expression) \ auto _statusor = (rexpr); \ if (ABSL_PREDICT_FALSE(!_statusor.ok())) { \ ::arolla::status_macros_backport_internal::StatusBuilder _( \ std::move(_statusor).status()); \ (void)_; \ return (error_expression); \ } \ AROLLA_STATUS_IMPL_UNPARENTHESIZE_IF_PARENTHESIZED(lhs) = \ (*std::move(_statusor)) #define EXPECT_OK(value) \ EXPECT_TRUE((value).ok()) \ << ::arolla::status_macros_backport_internal::GetStatusMessage(value) #define ASSERT_OK(value) \ ASSERT_TRUE((value).ok()) \ << ::arolla::status_macros_backport_internal::GetStatusMessage(value) #define ASSERT_OK_AND_ASSIGN(lhs, rexpr) \ ASSERT_OK_AND_ASSIGN_IMPL(AROLLA_STATUS_IMPL_CONCAT(statusor, __COUNTER__), \ lhs, rexpr) #define ASSERT_OK_AND_ASSIGN_IMPL(_statusor, lhs, rexpr) \ auto _statusor = (rexpr); \ ASSERT_OK(_statusor); \ AROLLA_STATUS_IMPL_UNPARENTHESIZE_IF_PARENTHESIZED(lhs) = \ (*std::move(_statusor)); #define AROLLA_STATUS_IMPL_CONCAT_INNER(a, b) a##b #define AROLLA_STATUS_IMPL_CONCAT(a, b) AROLLA_STATUS_IMPL_CONCAT_INNER(a, b) #define AROLLA_STATUS_IMPL_GET_VARIADIC_INNER(_1, _2, _3, NAME, ...) NAME #define AROLLA_STATUS_IMPL_GET_VARIADIC(args) \ AROLLA_STATUS_IMPL_GET_VARIADIC_INNER args #define AROLLA_STATUS_IMPL_EAT(...) #define AROLLA_STATUS_IMPL_REM(...) __VA_ARGS__ #define AROLLA_STATUS_IMPL_EMPTY() #define AROLLA_STATUS_IMPL_IS_EMPTY_INNER(...) \ AROLLA_STATUS_IMPL_IS_EMPTY_INNER_HELPER((__VA_ARGS__, 0, 1)) #define AROLLA_STATUS_IMPL_IS_EMPTY_INNER_HELPER(args) \ AROLLA_STATUS_IMPL_IS_EMPTY_INNER_I args #define AROLLA_STATUS_IMPL_IS_EMPTY_INNER_I(e0, e1, is_empty, ...) is_empty #define AROLLA_STATUS_IMPL_IS_EMPTY(...) \ AROLLA_STATUS_IMPL_IS_EMPTY_I(__VA_ARGS__) #define AROLLA_STATUS_IMPL_IS_EMPTY_I(...) \ AROLLA_STATUS_IMPL_IS_EMPTY_INNER(_, ##__VA_ARGS__) #define AROLLA_STATUS_IMPL_IF_1(_Then, _Else) _Then #define AROLLA_STATUS_IMPL_IF_0(_Then, _Else) _Else #define AROLLA_STATUS_IMPL_IF(_Cond, _Then, _Else) \ AROLLA_STATUS_IMPL_CONCAT(AROLLA_STATUS_IMPL_IF_, _Cond)(_Then, _Else) #define AROLLA_STATUS_IMPL_IS_PARENTHESIZED(...) \ AROLLA_STATUS_IMPL_IS_EMPTY(AROLLA_STATUS_IMPL_EAT __VA_ARGS__) #define AROLLA_STATUS_IMPL_UNPARENTHESIZE_IF_PARENTHESIZED(...) \ AROLLA_STATUS_IMPL_IF(AROLLA_STATUS_IMPL_IS_PARENTHESIZED(__VA_ARGS__), \ AROLLA_STATUS_IMPL_REM, AROLLA_STATUS_IMPL_EMPTY()) \ __VA_ARGS__ } #endif
#include "arolla/util/status_macros_backport.h" #include <tuple> #include "gtest/gtest-spi.h" #include "gtest/gtest.h" #include "absl/log/check.h" #include "absl/log/log.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/cord.h" #include "absl/strings/string_view.h" #include "arolla/util/status_macros_backport.h" namespace { #define INTERNAL_ASSERT_EQ(lhs, rhs) \ [](auto lhs_, auto rhs_) { \ if (lhs_ != rhs_) { \ LOG(FATAL) << "assertion " #lhs " == " #rhs " failed: " << lhs_ \ << " != " << rhs_; \ } \ }(lhs, rhs) template <typename T> absl::StatusOr<T> ReturnStatusOrValue(T v) { return v; } absl::StatusOr<int> ReturnStatusOrError(absl::string_view msg) { return absl::Status(absl::StatusCode::kUnknown, msg); } absl::Status ReturnError(absl::string_view msg) { return absl::Status(absl::StatusCode::kUnknown, msg); } absl::Status ReturnOk() { return absl::Status(); } TEST(ExternalStatusTest, ReturnIfError) { auto func = []() -> absl::StatusOr<int> { RETURN_IF_ERROR(ReturnOk()) << "UNEXPECTED"; RETURN_IF_ERROR(ReturnError("EXPECTED")) << "ALSO " << "EXPECTED"; return 5; }; ASSERT_EQ(func().status().message(), "EXPECTED; ALSO EXPECTED"); } TEST(ExternalStatusTest, ReturnIfErrorAnnotateEmpty) { auto err = [] { return absl::InvalidArgumentError(""); }; auto func = [&]() -> absl::Status { RETURN_IF_ERROR(err()) << "suffix"; return absl::OkStatus(); }; ASSERT_EQ(func().message(), "suffix"); } TEST(ExternalStatusTest, ReturnIfErrorPayload) { auto err = [] { auto status = absl::InvalidArgumentError("message"); status.SetPayload("url", absl::Cord("payload")); return status; }; auto func = [&]() -> absl::Status { RETURN_IF_ERROR(err()) << "suffix"; return absl::OkStatus(); }; ASSERT_EQ(func().message(), "message; suffix"); ASSERT_EQ(func().GetPayload("url"), "payload"); } TEST(ExternalStatusTest, AssignOrReturn) { auto func = []() -> absl::StatusOr<int> { ASSIGN_OR_RETURN(int value1, ReturnStatusOrValue(1)); INTERNAL_ASSERT_EQ(1, value1); ASSIGN_OR_RETURN(const int value2, ReturnStatusOrValue(2)); INTERNAL_ASSERT_EQ(2, value2); ASSIGN_OR_RETURN(const int& value3, ReturnStatusOrValue(3)); INTERNAL_ASSERT_EQ(3, value3); ASSIGN_OR_RETURN((const auto& [tuple1, tuple2]), ReturnStatusOrValue(std::make_tuple(1, 2))); INTERNAL_ASSERT_EQ(1, tuple1); INTERNAL_ASSERT_EQ(2, tuple2); ASSIGN_OR_RETURN(int value4, ReturnStatusOrError("EXPECTED")); return value4; }; ASSERT_EQ(func().status().message(), "EXPECTED"); } TEST(ExternalStatusTest, AssignOrReturn3) { auto func1 = []() -> absl::StatusOr<int> { ASSIGN_OR_RETURN(int value1, ReturnStatusOrValue(1), _ << "NOT EXPECTED"); INTERNAL_ASSERT_EQ(1, value1); ASSIGN_OR_RETURN((const auto& [tuple1, tuple2]), ReturnStatusOrValue(std::make_tuple(1, 2)), _ << "NOT EXPECTED"); INTERNAL_ASSERT_EQ(1, tuple1); INTERNAL_ASSERT_EQ(2, tuple2); ASSIGN_OR_RETURN(int value2, ReturnStatusOrError("EXPECTED"), _ << "ALSO " << "EXPECTED"); return value2; }; ASSERT_EQ(func1().status().message(), "EXPECTED; ALSO EXPECTED"); auto func2 = []() -> void { ASSIGN_OR_RETURN(int value, absl::StatusOr<int>(5), (void)_); INTERNAL_ASSERT_EQ(value, 5); }; func2(); } TEST(ExternalStatusTest, AssignOrReturnAnnotateEmpty) { auto err = [] { return absl::StatusOr<int>(absl::InvalidArgumentError("")); }; auto func = [&]() -> absl::StatusOr<int> { ASSIGN_OR_RETURN(auto result, err(), _ << "suffix"); return result; }; ASSERT_EQ(func().status().message(), "suffix"); } TEST(ExternalStatusTest, AssignOrReturn3Payload) { auto err = [] { auto status = absl::InvalidArgumentError("message"); status.SetPayload("url", absl::Cord("payload")); return absl::StatusOr<int>(status); }; auto func = [&]() -> absl::StatusOr<int> { ASSIGN_OR_RETURN(auto result, err(), _ << "suffix"); return result; }; ASSERT_EQ(func().status().message(), "message; suffix"); ASSERT_EQ(func().status().GetPayload("url"), "payload"); } TEST(ExternalStatusTest, AssertOkAndAssign) { ASSERT_OK_AND_ASSIGN(auto value, ReturnStatusOrValue(1)); ASSERT_EQ(1, value); ASSERT_OK_AND_ASSIGN((const auto& [tuple1, tuple2]), ReturnStatusOrValue(std::make_tuple(1, 2))); ASSERT_EQ(1, tuple1); ASSERT_EQ(2, tuple2); EXPECT_FATAL_FAILURE( []() { ASSERT_OK_AND_ASSIGN(auto x, ReturnStatusOrError("Expected error")); (void)x; }(), "Expected error"); } TEST(ExternalStatusTest, AssertOk) { ASSERT_OK(ReturnOk()); ASSERT_OK(ReturnStatusOrValue(1)); EXPECT_FATAL_FAILURE(ASSERT_OK(ReturnStatusOrError("Expected error")), "Expected error"); } TEST(ExternalStatusTest, ExpectOk) { EXPECT_OK(ReturnOk()); EXPECT_OK(ReturnStatusOrValue(1)); EXPECT_NONFATAL_FAILURE(EXPECT_OK(ReturnStatusOrError("Expected error")), "Expected error"); } }
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/util/status_macros_backport.h
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/util/status_macros_backport_test.cc
1ca990dbeca224035efdabffecc7f3738df6b52c
212ea646-6de4-4c3e-ac79-06511b9ea44b
cpp
google/arolla
equals_proto
arolla/util/testing/equals_proto.h
arolla/util/testing/equals_proto_test.cc
#ifndef AROLLA_UTIL_TESTING_EQUALS_PROTO_H_ #define AROLLA_UTIL_TESTING_EQUALS_PROTO_H_ #include <string> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/strings/string_view.h" #include "google/protobuf/text_format.h" #include "google/protobuf/util/message_differencer.h" namespace arolla::testing { template <typename TypeProto> ::testing::AssertionResult EqualsProto(const TypeProto& actual_proto, absl::string_view expected_proto_text) { using ::google::protobuf::TextFormat; using ::google::protobuf::util::MessageDifferencer; TypeProto expected_proto; if (!TextFormat::ParseFromString(std::string(expected_proto_text), &expected_proto)) { return ::testing::AssertionFailure() << "could not parse proto: " << expected_proto_text; } MessageDifferencer differencer; std::string differences; differencer.ReportDifferencesToString(&differences); if (!differencer.Compare(expected_proto, actual_proto)) { return ::testing::AssertionFailure() << "the protos are different:\n" << differences; } return ::testing::AssertionSuccess(); } inline auto EqualsProto(absl::string_view expected_proto_text) { return ::testing::Truly([expected_proto_text = std::string( expected_proto_text)](const auto& actual_proto) { return EqualsProto(actual_proto, expected_proto_text); }); } } #endif
#include "arolla/util/testing/equals_proto.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "arolla/util/testing/test.pb.h" namespace arolla::testing { namespace { using ::testing::Not; TEST(EqualsProtoTest, Predicate) { { TestProto test_proto; EXPECT_TRUE(EqualsProto(test_proto, R"pb()pb")); EXPECT_FALSE(EqualsProto(test_proto, R"pb(field: 0)pb")); EXPECT_FALSE(EqualsProto(test_proto, R"pb(field: 100)pb")); } { TestProto test_proto; test_proto.set_field(0); EXPECT_FALSE(EqualsProto(test_proto, R"pb()pb")); EXPECT_TRUE(EqualsProto(test_proto, R"pb(field: 0)pb")); EXPECT_FALSE(EqualsProto(test_proto, R"pb(field: 100)pb")); } { TestProto test_proto; test_proto.set_field(100); EXPECT_FALSE(EqualsProto(test_proto, R"pb()pb")); EXPECT_FALSE(EqualsProto(test_proto, R"pb(field: 0)pb")); EXPECT_TRUE(EqualsProto(test_proto, R"pb(field: 100)pb")); } { TestProto test_proto; EXPECT_FALSE(EqualsProto(test_proto, R"pb(unknown_field: 0)pb")); } { TestProto test_proto; EXPECT_FALSE(EqualsProto(test_proto, "invalid text proto literal")); } } TEST(EqualsProtoTest, Matcher) { { TestProto test_proto; EXPECT_THAT(test_proto, EqualsProto(R"pb()pb")); EXPECT_THAT(test_proto, Not(EqualsProto(R"pb(field: 0)pb"))); EXPECT_THAT(test_proto, Not(EqualsProto(R"pb(field: 100)pb"))); } { TestProto test_proto; test_proto.set_field(0); EXPECT_THAT(test_proto, Not(EqualsProto(R"pb()pb"))); EXPECT_THAT(test_proto, EqualsProto(R"pb(field: 0)pb")); EXPECT_THAT(test_proto, Not(EqualsProto(R"pb(field: 100)pb"))); } { TestProto test_proto; test_proto.set_field(100); EXPECT_THAT(test_proto, Not(EqualsProto(R"pb()pb"))); EXPECT_THAT(test_proto, Not(EqualsProto(R"pb(field: 0)pb"))); EXPECT_THAT(test_proto, EqualsProto(R"pb(field: 100)pb")); } { TestProto test_proto; EXPECT_THAT(test_proto, Not(EqualsProto(R"pb(unknown_field: 0)pb"))); } { TestProto test_proto; EXPECT_THAT(test_proto, Not(EqualsProto("invalid text proto literal"))); } } } }
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/util/testing/equals_proto.h
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/util/testing/equals_proto_test.cc
1ca990dbeca224035efdabffecc7f3738df6b52c
38927dfd-d806-4ded-8fdd-5adb64b435d7
cpp
google/arolla
pointwise_op
arolla/array/pointwise_op.h
arolla/array/pointwise_op_test.cc
#ifndef AROLLA_ARRAY_POINTWISE_OP_H_ #define AROLLA_ARRAY_POINTWISE_OP_H_ #include <cstdint> #include <optional> #include <utility> #include "absl/status/statusor.h" #include "arolla/array/array.h" #include "arolla/array/id_filter.h" #include "arolla/dense_array/dense_array.h" #include "arolla/dense_array/ops/dense_ops.h" #include "arolla/memory/optional_value.h" #include "arolla/memory/raw_buffer_factory.h" #include "arolla/util/meta.h" #include "arolla/util/status_macros_backport.h" namespace arolla { template <class ResT, class DenseArrayOp, class PointwiseFn, class ArgList> class ArrayPointwiseOp; template <class ResT, class DenseArrayOp, class PointwiseFn, class... Args> class ArrayPointwiseOp<ResT, DenseArrayOp, PointwiseFn, meta::type_list<Args...>> { public: explicit ArrayPointwiseOp(DenseArrayOp dense_op, PointwiseFn pointwise_fn, RawBufferFactory* buf_factory) : dense_op_(std::move(dense_op)), pointwise_fn_(std::move(pointwise_fn)), buf_factory_(std::move(buf_factory)) {} template <class... As> absl::StatusOr<Array<ResT>> operator()(const As&... args) const { ASSIGN_OR_RETURN(int64_t size, GetCommonSize(args...)); if ((((!is_optional_v<Args> && args.IsAllMissingForm())) || ...)) { return Array<ResT>(size, std::nullopt); } IdFilter id_filter(IdFilter::kEmpty); DenseArray<ResT> data; if (IsSameIdFilter(args...)) { id_filter = First(args...).id_filter(); if (id_filter.type() != IdFilter::kEmpty) { ASSIGN_OR_RETURN(data, ApplyDenseOp(args...)); } } else { if ((CanBeIntersected<Args>(args) || ...)) { IdFilter full(IdFilter::kFull); id_filter = IdFilter::UpperBoundIntersect( (CanBeIntersected<Args>(args) ? args.id_filter() : full)...); } else { id_filter = IdFilter::UpperBoundMerge(size, buf_factory_, args.id_filter()...); } ASSIGN_OR_RETURN(data, ApplyDenseOp(args.WithIds( id_filter, args.missing_id_value())...)); } auto missing_id_value = pointwise_fn_(args.missing_id_value()...); RETURN_IF_ERROR(GetStatusOrOk(missing_id_value)); return Array<ResT>( size, std::move(id_filter), std::move(data), OptionalValue<ResT>(UnStatus(std::move(missing_id_value)))); } private: template <class... As> absl::StatusOr<DenseArray<ResT>> ApplyDenseOp(const As&... args) const { return dense_op_(args.dense_data()...); } template <class Arg, class A> static bool CanBeIntersected(const A& arg) { return !is_optional_v<Arg> && !arg.HasMissingIdValue(); } template <class A, class... As> static absl::StatusOr<int64_t> GetCommonSize(const A& a, const As&... as) { if (!((a.size() == as.size()) && ...)) { return SizeMismatchError({a.size(), as.size()...}); } else { return a.size(); } } template <class A, class... As> static bool IsSameIdFilter(const A& a, const As&... as) { return ((a.id_filter().IsSame(as.id_filter()) && ...)); } template <class A, class... As> static const A& First(const A& a, const As&...) { return a; } DenseArrayOp dense_op_; PointwiseFn pointwise_fn_; RawBufferFactory* buf_factory_; }; template <int flags, class Fn, class ResT = dense_ops_internal::result_base_t<Fn>> auto CreateArrayOp(Fn fn, RawBufferFactory* buf_factory = GetHeapBufferFactory()) { auto dense_op = CreateDenseOp<flags | DenseOpFlags::kNoSizeValidation, decltype(fn), ResT>(fn, buf_factory); auto optional_fn = WrapFnToAcceptOptionalArgs(fn); using Op = ArrayPointwiseOp<ResT, decltype(dense_op), decltype(optional_fn), typename meta::function_traits<Fn>::arg_types>; return Op(dense_op, optional_fn, buf_factory); } template <class Fn, class ResT = dense_ops_internal::result_base_t<Fn>> auto CreateArrayOp(Fn fn, RawBufferFactory* buf_factory = GetHeapBufferFactory()) { return CreateArrayOp<0, decltype(fn), ResT>(fn, buf_factory); } } #endif
#include "arolla/array/pointwise_op.h" #include <cstdint> #include <optional> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "arolla/array/array.h" #include "arolla/array/id_filter.h" #include "arolla/dense_array/dense_array.h" #include "arolla/memory/buffer.h" #include "arolla/memory/optional_value.h" namespace arolla { namespace { using ::testing::ElementsAre; template <typename T> struct UnionAddFn { OptionalValue<T> operator()(OptionalValue<T> a, OptionalValue<T> b) const { return {a.present || b.present, (a.present ? a.value : 0) + (b.present ? b.value : 0)}; } }; TEST(OpAddTest, WithConst) { auto op = CreateArrayOp([](int a, int b) { return a + b; }); { ASSERT_OK_AND_ASSIGN(Array<int> block, op(Array<int>(10, 2), Array<int>(10, 3))); EXPECT_TRUE(block.IsConstForm()); EXPECT_EQ(block.missing_id_value(), OptionalValue<int>(5)); } { ASSERT_OK_AND_ASSIGN(Array<int> block, op(Array<int>(10, 2), Array<int>(10, std::nullopt))); EXPECT_TRUE(block.IsAllMissingForm()); } { ASSERT_OK_AND_ASSIGN( Array<int> block, op(CreateArray<int>({1, std::nullopt, 2}), Array<int>(3, 5))); EXPECT_TRUE(block.IsDenseForm()); EXPECT_THAT(block, ElementsAre(6, std::nullopt, 7)); } { ASSERT_OK_AND_ASSIGN( Array<int> block, op(CreateArray<int>({1, std::nullopt, 2}).ToSparseForm(), Array<int>(3, 5))); EXPECT_TRUE(block.IsSparseForm()); EXPECT_THAT(block, ElementsAre(6, std::nullopt, 7)); } { ASSERT_OK_AND_ASSIGN(Array<int> block, op(CreateArray<int>({1, std::nullopt, 2}), Array<int>(3, std::nullopt))); EXPECT_TRUE(block.IsAllMissingForm()); } } TEST(OpAddTest, SameIdFilter) { auto op = CreateArrayOp([](int a, int b) { return a + b; }); IdFilter ids(10, CreateBuffer<int64_t>({1, 2, 5, 9})); Array<int> arg1(10, ids, CreateDenseArray<int>({1, 2, std::nullopt, 3}), 2); Array<int> arg2(10, ids, CreateDenseArray<int>({7, 5, 3, 0}), 3); ASSERT_OK_AND_ASSIGN(Array<int> res, op(arg1, arg2)); EXPECT_EQ(res.size(), arg1.size()); EXPECT_TRUE(res.id_filter().IsSame(arg1.id_filter())); EXPECT_EQ(res.missing_id_value(), OptionalValue<int>(5)); EXPECT_THAT(res.dense_data(), ElementsAre(8, 7, std::nullopt, 3)); } TEST(OpAddTest, DensePlusSparse) { auto op = CreateArrayOp([](int a, int b) { return a + b; }); auto arg1 = CreateArray<int>({1, 2, 3, 0, 0, 3, 2, 1}); { auto arg2 = CreateArray<int>( {4, 7, 3, std::nullopt, 3, 6, std::nullopt, std::nullopt}) .ToSparseForm(); ASSERT_OK_AND_ASSIGN(Array<int> res, op(arg1, arg2)); EXPECT_EQ(res.size(), arg1.size()); EXPECT_TRUE(res.id_filter().IsSame(arg2.id_filter())); EXPECT_FALSE(res.HasMissingIdValue()); EXPECT_THAT(res.dense_data(), ElementsAre(5, 9, 6, 3, 9)); } { auto arg2 = CreateArray<int>({4, 7, 3, 1, 3, 6, 1, 1}).ToSparseForm(1); ASSERT_OK_AND_ASSIGN(Array<int> res, op(arg1, arg2)); EXPECT_EQ(res.size(), arg1.size()); EXPECT_TRUE(res.IsDenseForm()); EXPECT_TRUE(arg2.IsSparseForm()); EXPECT_TRUE(res.dense_data().bitmap.empty()); EXPECT_THAT(res.dense_data().values, ElementsAre(5, 9, 6, 1, 3, 9, 3, 2)); } } TEST(OpAddTest, SparsePlusSparse) { auto op = CreateArrayOp([](int a, int b) { return a + b; }); auto arg1 = CreateArray<int>({3, std::nullopt, std::nullopt, std::nullopt, std::nullopt, 3, 4, 5}) .ToSparseForm(); auto arg2 = CreateArray<int>( {4, 7, 3, std::nullopt, 3, 6, std::nullopt, std::nullopt}) .ToSparseForm(); { ASSERT_OK_AND_ASSIGN(Array<int> res, op(arg1, arg2)); EXPECT_EQ(res.size(), arg1.size()); EXPECT_TRUE(res.IsSparseForm()); EXPECT_FALSE(res.HasMissingIdValue()); EXPECT_TRUE(res.id_filter().IsSame(arg1.id_filter())); EXPECT_THAT(res, ElementsAre(7, std::nullopt, std::nullopt, std::nullopt, std::nullopt, 9, std::nullopt, std::nullopt)); } { ASSERT_OK_AND_ASSIGN(Array<int> res, op(arg2, arg1)); EXPECT_EQ(res.size(), arg1.size()); EXPECT_TRUE(res.IsSparseForm()); EXPECT_FALSE(res.HasMissingIdValue()); EXPECT_TRUE(res.id_filter().IsSame(arg1.id_filter())); EXPECT_THAT(res, ElementsAre(7, std::nullopt, std::nullopt, std::nullopt, std::nullopt, 9, std::nullopt, std::nullopt)); } } TEST(OpUnionAddTest, WithConst) { auto op = CreateArrayOp(UnionAddFn<int>()); { ASSERT_OK_AND_ASSIGN(Array<int> block, op(Array<int>(10, 2), Array<int>(10, 3))); EXPECT_TRUE(block.IsConstForm()); EXPECT_EQ(block.missing_id_value(), OptionalValue<int>(5)); } { ASSERT_OK_AND_ASSIGN(Array<int> block, op(Array<int>(10, 2), Array<int>(10, std::nullopt))); EXPECT_TRUE(block.IsConstForm()); EXPECT_EQ(block.missing_id_value(), OptionalValue<int>(2)); } { ASSERT_OK_AND_ASSIGN( Array<int> block, op(CreateArray<int>({1, std::nullopt, 2}), Array<int>(3, 5))); EXPECT_TRUE(block.IsDenseForm()); EXPECT_THAT(block, ElementsAre(6, 5, 7)); } { ASSERT_OK_AND_ASSIGN( Array<int> block, op(CreateArray<int>({1, std::nullopt, 2}).ToSparseForm(), Array<int>(3, 5))); EXPECT_TRUE(block.IsSparseForm()); EXPECT_THAT(block, ElementsAre(6, 5, 7)); } { ASSERT_OK_AND_ASSIGN(Array<int> block, op(CreateArray<int>({1, std::nullopt, 2}), Array<int>(3, std::nullopt))); EXPECT_THAT(block, ElementsAre(1, std::nullopt, 2)); } } TEST(OpUnionAddTest, DensePlusSparse) { auto op = CreateArrayOp(UnionAddFn<int>()); Array<int> arg1(DenseArray<int>{CreateBuffer<int>({1, 2, 3, 0, 0, 3, 2, 1})}); { auto arg2 = CreateArray<int>( {4, 7, 3, std::nullopt, 3, 6, std::nullopt, std::nullopt}) .ToSparseForm(); ASSERT_OK_AND_ASSIGN(Array<int> res, op(arg1, arg2)); EXPECT_TRUE(res.IsFullForm()); EXPECT_THAT(res, ElementsAre(5, 9, 6, 0, 3, 9, 2, 1)); } { auto arg2 = CreateArray<int>({4, 7, 3, 1, 3, 6, 1, 1}).ToSparseForm(1); ASSERT_OK_AND_ASSIGN(Array<int> res, op(arg1, arg2)); EXPECT_TRUE(res.IsFullForm()); EXPECT_THAT(res, ElementsAre(5, 9, 6, 1, 3, 9, 3, 2)); } } TEST(OpUnionAddTest, SparsePlusSparse) { auto op = CreateArrayOp(UnionAddFn<int>()); auto arg1 = CreateArray<int>({3, std::nullopt, std::nullopt, std::nullopt, std::nullopt, 3, 4, 5}) .ToSparseForm(); auto arg2 = CreateArray<int>( {4, 7, 3, std::nullopt, 3, 6, std::nullopt, std::nullopt}) .ToSparseForm(); { ASSERT_OK_AND_ASSIGN(Array<int> res, op(arg1, arg2)); EXPECT_THAT(res, ElementsAre(7, 7, 3, std::nullopt, 3, 9, 4, 5)); } { ASSERT_OK_AND_ASSIGN(Array<int> res, op(arg2, arg1)); EXPECT_THAT(res, ElementsAre(7, 7, 3, std::nullopt, 3, 9, 4, 5)); } } } }
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/array/pointwise_op.h
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/array/pointwise_op_test.cc
1ca990dbeca224035efdabffecc7f3738df6b52c
1008aca8-d9ec-47ce-bf94-ea245a28e353
cpp
google/arolla
group_op
arolla/array/group_op.h
arolla/array/group_op_test.cc
#ifndef AROLLA_ARRAY_GROUP_OP_H_ #define AROLLA_ARRAY_GROUP_OP_H_ #include <algorithm> #include <cstddef> #include <cstdint> #include <type_traits> #include <utility> #include <vector> #include "absl/base/attributes.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/types/span.h" #include "arolla/array/array.h" #include "arolla/array/edge.h" #include "arolla/array/id_filter.h" #include "arolla/array/ops_util.h" #include "arolla/dense_array/dense_array.h" #include "arolla/dense_array/ops/dense_group_ops.h" #include "arolla/memory/buffer.h" #include "arolla/memory/optional_value.h" #include "arolla/memory/raw_buffer_factory.h" #include "arolla/util/binary_search.h" #include "arolla/util/meta.h" #include "arolla/util/view_types.h" #include "arolla/util/status_macros_backport.h" namespace arolla { namespace array_ops_internal { template <class Accumulator, class ParentTypes, class ChildTypes, bool ForwardId = false, bool UseDenseGroupOps = true> class ArrayGroupOpImpl; template <class Accumulator, class... ParentTs, class... ChildTs, bool ForwardId, bool UseDenseGroupOps> class ArrayGroupOpImpl<Accumulator, meta::type_list<ParentTs...>, meta::type_list<ChildTs...>, ForwardId, UseDenseGroupOps> { using ParentUtil = ArrayOpsUtil<true, meta::type_list<ParentTs...>>; using ChildUtil = ArrayOpsUtil<false, meta::type_list<ChildTs...>>; using MappingAndChildUtil = ArrayOpsUtil<false, meta::type_list<int64_t, ChildTs...>>; using ResT = strip_optional_t<typename Accumulator::result_type>; using DenseGroupOp = dense_ops_internal::DenseGroupOpsImpl< Accumulator, meta::type_list<ParentTs...>, meta::type_list<ChildTs...>, ForwardId>; static constexpr bool kIsAggregator = Accumulator::IsAggregator(); static constexpr bool kIsPartial = Accumulator::IsPartial(); static constexpr bool kIsFull = Accumulator::IsFull(); static constexpr double kNonEmptyGroupProbLimit = 0.25; public: explicit ArrayGroupOpImpl(RawBufferFactory* buffer_factory, Accumulator empty_accumulator = Accumulator()) : buffer_factory_(buffer_factory), empty_accumulator_(std::move(empty_accumulator)) {} absl::StatusOr<Array<ResT>> Apply(const ArrayEdge& edge, const AsArray<ParentTs>&... p_args, const AsArray<ChildTs>&... c_args) const { if constexpr (UseDenseGroupOps) { if (edge.edge_values().IsDenseForm() && (p_args.IsDenseForm() && ... && true) && (c_args.IsDenseForm() && ... && true)) { auto op = [this](const auto&... args) ABSL_ATTRIBUTE_NOINLINE { return DenseGroupOp(buffer_factory_, empty_accumulator_) .Apply(args...); }; ASSIGN_OR_RETURN(DenseArray<ResT> res, op(edge.ToDenseArrayEdge(), p_args.dense_data()..., c_args.dense_data()...)); return Array<ResT>(res); } } if (((p_args.size() != edge.parent_size()) || ... || false)) { return SizeMismatchError({edge.parent_size(), p_args.size()...}); } if (((c_args.size() != edge.child_size()) || ... || false)) { return SizeMismatchError({edge.child_size(), c_args.size()...}); } switch (edge.edge_type()) { case ArrayEdge::SPLIT_POINTS: { const Buffer<int64_t>& splits = edge.edge_values().dense_data().values; ChildUtil child_util(edge.child_size(), c_args..., buffer_factory_); if constexpr (kIsAggregator) { if constexpr (sizeof...(ParentTs) == 0) { if (child_util.PresentCountUpperEstimate() < kNonEmptyGroupProbLimit * edge.parent_size()) { return ApplyAggregatorWithSplitPointsOnVerySparseData( edge.parent_size(), child_util, splits.span()); } } ParentUtil parent_util(edge.parent_size(), p_args..., buffer_factory_); return ApplyAggregatorWithSplitPoints(parent_util, child_util, splits); } else { ParentUtil parent_util(edge.parent_size(), p_args..., buffer_factory_); if (child_util.PresentCountUpperEstimate() > edge.child_size() * IdFilter::kDenseSparsityLimit) { return ApplyDenseWithSplitPoints(parent_util, child_util, splits); } else { return ApplySparseWithSplitPoints(parent_util, child_util, splits); } } } case ArrayEdge::MAPPING: { MappingAndChildUtil mapchild_util(edge.child_size(), edge.edge_values(), c_args..., buffer_factory_); if constexpr (kIsAggregator && sizeof...(ParentTs) == 0) { if (mapchild_util.PresentCountUpperEstimate() < kNonEmptyGroupProbLimit * edge.parent_size()) { return ApplyAggregatorWithMappingOnVerySparseData( edge.parent_size(), mapchild_util); } } ParentUtil parent_util(edge.parent_size(), p_args..., buffer_factory_); return ApplyWithMapping(parent_util, mapchild_util); } default: return absl::InvalidArgumentError("unsupported edge type"); } } absl::StatusOr< std::conditional_t<Accumulator::IsAggregator(), typename Accumulator::result_type, Array<ResT>>> Apply(const ArrayGroupScalarEdge& edge, view_type_t<ParentTs>... p_args, const AsArray<ChildTs>&... c_args) const { if constexpr (UseDenseGroupOps) { if ((c_args.IsDenseForm() && ... && true)) { auto op = [this](const auto&... args) ABSL_ATTRIBUTE_NOINLINE { return DenseGroupOp(buffer_factory_, empty_accumulator_) .Apply(args...); }; ASSIGN_OR_RETURN(auto res, op(edge.ToDenseArrayGroupScalarEdge(), p_args..., c_args.dense_data()...)); if constexpr (Accumulator::IsAggregator()) { return res; } else { return Array<ResT>(res); } } } if (((c_args.size() != edge.child_size()) || ... || false)) { return SizeMismatchError({edge.child_size(), c_args.size()...}); } ChildUtil util(edge.child_size(), c_args..., buffer_factory_); Accumulator accumulator = empty_accumulator_; accumulator.Reset(p_args...); if constexpr (kIsAggregator) { AggregateSingleGroup(accumulator, util, 0, edge.child_size()); auto res = accumulator.GetResult(); RETURN_IF_ERROR(accumulator.GetStatus()); return typename Accumulator::result_type(std::move(res)); } else { const int64_t max_present_count = util.PresentCountUpperEstimate(); if (kIsPartial && max_present_count > edge.child_size() * IdFilter::kDenseSparsityLimit) { DenseArrayBuilder<ResT> builder(edge.child_size(), buffer_factory_); auto fn = [&](int64_t child_id, view_type_t<ChildTs>... args) { Add(accumulator, child_id, args...); builder.Set(child_id, accumulator.GetResult()); }; util.Iterate(0, edge.child_size(), fn); RETURN_IF_ERROR(accumulator.GetStatus()); return Array<ResT>(std::move(builder).Build()); } SparseArrayBuilder<ResT> builder(edge.child_size(), max_present_count, buffer_factory_); auto fn = [&](int64_t child_id, view_type_t<ChildTs>... args) { Add(accumulator, child_id, args...); if constexpr (kIsPartial) { builder.SetByOffset(builder.NextOffset(), accumulator.GetResult()); } builder.AddId(child_id); }; util.Iterate(0, edge.child_size(), fn); if constexpr (kIsFull) { accumulator.FinalizeFullGroup(); for (int64_t offset = 0; offset < builder.NextOffset(); ++offset) { builder.SetByOffset(offset, accumulator.GetResult()); } } RETURN_IF_ERROR(accumulator.GetStatus()); return std::move(builder).Build(); } } private: absl::StatusOr<Array<ResT>> ApplyWithMapping( ParentUtil& parent_util, MappingAndChildUtil& mapchild_util) const { std::vector<Accumulator> accumulators(parent_util.size(), empty_accumulator_); std::vector<bool> valid_parents(parent_util.size(), false); parent_util.IterateSimple( [&](int64_t parent, view_type_t<ParentTs>... args) { accumulators[parent].Reset(args...); valid_parents[parent] = true; }); const int64_t child_row_count = mapchild_util.size(); const int64_t max_present_count = mapchild_util.PresentCountUpperEstimate(); if (kIsAggregator || (kIsPartial && max_present_count > child_row_count * IdFilter::kDenseSparsityLimit)) { return ApplyAggregatorOrDensePartialWithMapping( parent_util, mapchild_util, accumulators, valid_parents); } DCHECK(kIsFull || kIsPartial); SparseArrayBuilder<ResT> builder(child_row_count, max_present_count, buffer_factory_); std::vector<int64_t> parent_ids; if constexpr (kIsFull) { parent_ids.reserve(max_present_count); } auto fn = [&](int64_t child_id, int64_t parent_id, view_type_t<ChildTs>... args) { if (!valid_parents[parent_id]) return; auto& accumulator = accumulators[parent_id]; Add(accumulator, child_id, args...); if constexpr (kIsPartial) { builder.SetByOffset(builder.NextOffset(), accumulator.GetResult()); } else { DCHECK(kIsFull); parent_ids.push_back(parent_id); } builder.AddId(child_id); }; mapchild_util.IterateSimple(fn); if constexpr (kIsFull) { int64_t parent_id = 0; for (bool valid : valid_parents) { if (valid) accumulators[parent_id].FinalizeFullGroup(); parent_id++; } for (int64_t offset = 0; offset < builder.NextOffset(); ++offset) { builder.SetByOffset(offset, accumulators[parent_ids[offset]].GetResult()); } } int64_t parent_id = 0; for (bool valid : valid_parents) { if (valid) { RETURN_IF_ERROR(accumulators[parent_id].GetStatus()); } parent_id++; } return std::move(builder).Build(); } absl::StatusOr<Array<ResT>> ApplyAggregatorWithMappingOnVerySparseData( size_t parent_size, MappingAndChildUtil& mapchild_util) const { static_assert(kIsAggregator); static_assert(sizeof...(ParentTs) == 0); absl::flat_hash_map<int64_t, Accumulator> accumulators; mapchild_util.IterateSimple( [&](int64_t child_id, int64_t parent_id, view_type_t<ChildTs>... args) { auto it = accumulators.find(parent_id); if (it == accumulators.end()) { it = accumulators.emplace(parent_id, empty_accumulator_).first; it->second.Reset(); } Add(it->second, child_id, args...); }); std::vector<std::pair< int64_t, decltype(Accumulator(empty_accumulator_).GetResult())>> results; results.reserve(accumulators.size()); for (auto& [parent_id, accumulator] : accumulators) { results.emplace_back(parent_id, accumulator.GetResult()); RETURN_IF_ERROR(accumulator.GetStatus()); } std::sort(results.begin(), results.end(), [](const auto& a, const auto& b) { return a.first < b.first; }); Buffer<int64_t>::Builder ids_bldr(accumulators.size(), buffer_factory_); DenseArrayBuilder<ResT> dense_builder(accumulators.size(), buffer_factory_); int64_t offset = 0; for (auto& [parent_id, value] : results) { ids_bldr.Set(offset, parent_id); dense_builder.Set(offset, value); offset++; } OptionalValue<ResT> missing_id_value; if (accumulators.size() < parent_size) { Accumulator acc(empty_accumulator_); acc.Reset(); missing_id_value = OptionalValue<ResT>(acc.GetResult()); RETURN_IF_ERROR(acc.GetStatus()); } IdFilter id_filter(parent_size, std::move(ids_bldr).Build()); return Array<ResT>(parent_size, std::move(id_filter), std::move(dense_builder).Build(), missing_id_value); } absl::StatusOr<Array<ResT>> ApplyAggregatorOrDensePartialWithMapping( ParentUtil& parent_util, MappingAndChildUtil& mapchild_util, std::vector<Accumulator>& accumulators, std::vector<bool>& valid_parents) const { DCHECK(kIsAggregator || kIsPartial); DenseArrayBuilder<ResT> builder( kIsAggregator ? parent_util.size() : mapchild_util.size(), buffer_factory_); auto fn = [&](int64_t child_id, int64_t parent_id, view_type_t<ChildTs>... args) { auto& accumulator = accumulators[parent_id]; if constexpr (kIsAggregator) { Add(accumulator, child_id, args...); } else { if (valid_parents[parent_id]) { Add(accumulator, child_id, args...); builder.Set(child_id, accumulator.GetResult()); } } }; mapchild_util.IterateSimple(fn); int64_t parent_id = 0; for (bool valid : valid_parents) { if (valid) { if constexpr (kIsAggregator) { builder.Set(parent_id, accumulators[parent_id].GetResult()); } RETURN_IF_ERROR(accumulators[parent_id].GetStatus()); } parent_id++; } return Array<ResT>(std::move(builder).Build()); } absl::StatusOr<Array<ResT>> ApplyAggregatorWithSplitPoints( ParentUtil& parent_util, ChildUtil& child_util, const Buffer<int64_t>& splits) const { static_assert(kIsAggregator); DCHECK_EQ(splits.size(), parent_util.size() + 1); Accumulator accumulator = empty_accumulator_; DenseArrayBuilder<ResT> builder(parent_util.size(), buffer_factory_); auto process_group = [&](int64_t parent_id, view_type_t<ParentTs>... args) { accumulator.Reset(args...); int64_t child_from = splits[parent_id]; int64_t child_to = splits[parent_id + 1]; AggregateSingleGroup(accumulator, child_util, child_from, child_to); builder.Set(parent_id, accumulator.GetResult()); }; parent_util.IterateSimple(process_group); RETURN_IF_ERROR(accumulator.GetStatus()); return Array<ResT>(std::move(builder).Build()); } void AggregateSingleGroup(Accumulator& accumulator, ChildUtil& child_util, int64_t child_from, int64_t child_to) const { static_assert(kIsAggregator); auto fn = [&](int64_t child_id, view_type_t<ChildTs>... args) { Add(accumulator, child_id, args...); }; auto repeated_fn = [&](int64_t first_child_id, int64_t count, view_type_t<ChildTs>... args) { AddN(accumulator, first_child_id, count, args...); }; child_util.Iterate(child_from, child_to, fn, empty_missing_fn, repeated_fn); } absl::StatusOr<Array<ResT>> ApplyAggregatorWithSplitPointsOnVerySparseData( int64_t parent_size, ChildUtil& child_util, absl::Span<const int64_t> splits) const { static_assert(kIsAggregator); static_assert(sizeof...(ParentTs) == 0); DCHECK_EQ(splits.size(), parent_size + 1); const int64_t max_res_dense_count = std::min(parent_size, child_util.PresentCountUpperEstimate()); Buffer<int64_t>::Builder ids_bldr(max_res_dense_count, buffer_factory_); DenseArrayBuilder<ResT> dense_builder(max_res_dense_count, buffer_factory_); int64_t res_offset = 0; int64_t next_parent_id = 0; Accumulator accumulator = empty_accumulator_; accumulator.Reset(); absl::Status status = absl::OkStatus(); auto add_previous_to_results = [&]() { if (next_parent_id > 0 && status.ok()) { ids_bldr.Set(res_offset, next_parent_id - 1); dense_builder.Set(res_offset, accumulator.GetResult()); status = accumulator.GetStatus(); accumulator.Reset(); res_offset++; } }; child_util.IterateSimple([&](int64_t child_id, view_type_t<ChildTs>... args) { if (child_id >= splits[next_parent_id]) { add_previous_to_results(); next_parent_id = GallopingLowerBound(splits.begin() + next_parent_id, splits.end(), child_id + 1) - splits.begin(); } Add(accumulator, child_id, args...); }); add_previous_to_results(); RETURN_IF_ERROR(status); OptionalValue<ResT> missing_id_value; if (res_offset < parent_size) { missing_id_value = OptionalValue<ResT>(accumulator.GetResult()); RETURN_IF_ERROR(accumulator.GetStatus()); } IdFilter id_filter(parent_size, std::move(ids_bldr).Build(res_offset)); return Array<ResT>(parent_size, std::move(id_filter), std::move(dense_builder).Build(res_offset), missing_id_value); } absl::StatusOr<Array<ResT>> ApplyDenseWithSplitPoints( ParentUtil& parent_util, ChildUtil& child_util, const Buffer<int64_t>& splits) const { static_assert(kIsPartial || kIsFull); DenseArrayBuilder<ResT> builder(child_util.size(), buffer_factory_); std::vector<int64_t> processed_rows; Accumulator accumulator = empty_accumulator_; auto fn = [&](int64_t child_id, view_type_t<ChildTs>... args) { Add(accumulator, child_id, args...); if constexpr (kIsPartial) { builder.Set(child_id, accumulator.GetResult()); } else { processed_rows.push_back(child_id); } }; auto process_group = [&](int64_t parent_id, view_type_t<ParentTs>... args) { accumulator.Reset(args...); int64_t child_from = splits[parent_id]; int64_t child_to = splits[parent_id + 1]; child_util.Iterate(child_from, child_to, fn); if constexpr (kIsFull) { accumulator.FinalizeFullGroup(); for (int64_t row_id : processed_rows) { builder.Set(row_id, accumulator.GetResult()); } processed_rows.clear(); } }; parent_util.IterateSimple(process_group); RETURN_IF_ERROR(accumulator.GetStatus()); return Array<ResT>(std::move(builder).Build()); } absl::StatusOr<Array<ResT>> ApplySparseWithSplitPoints( ParentUtil& parent_util, ChildUtil& child_util, const Buffer<int64_t>& splits) const { static_assert(kIsPartial || kIsFull); SparseArrayBuilder<ResT> builder(child_util.size(), child_util.PresentCountUpperEstimate(), buffer_factory_); Accumulator accumulator = empty_accumulator_; auto fn = [&](int64_t child_id, view_type_t<ChildTs>... args) { Add(accumulator, child_id, args...); if constexpr (kIsPartial) { builder.SetByOffset(builder.NextOffset(), accumulator.GetResult()); } builder.AddId(child_id); }; auto process_group = [&](int64_t parent_id, view_type_t<ParentTs>... args) { accumulator.Reset(args...); int64_t child_from = splits[parent_id]; int64_t child_to = splits[parent_id + 1]; int64_t offset = builder.NextOffset(); child_util.Iterate(child_from, child_to, fn); if constexpr (kIsFull) { accumulator.FinalizeFullGroup(); while (offset < builder.NextOffset()) { builder.SetByOffset(offset++, accumulator.GetResult()); } } }; parent_util.IterateSimple(process_group); RETURN_IF_ERROR(accumulator.GetStatus()); return std::move(builder).Build(); } void Add(Accumulator& accumulator, int64_t child_id, view_type_t<ChildTs>... args) const { if constexpr (ForwardId) { accumulator.Add(child_id, args...); } else { (void)child_id; accumulator.Add(args...); } } void AddN(Accumulator& accumulator, int64_t first_child_id, int64_t N, view_type_t<ChildTs>... args) const { if constexpr (ForwardId) { for (int64_t i = 0; i < N; ++i) { accumulator.Add(first_child_id + i, args...); } } else { (void)first_child_id; accumulator.AddN(N, args...); } } RawBufferFactory* buffer_factory_; const Accumulator empty_accumulator_; }; } template <class Accumulator> using ArrayGroupOp = array_ops_internal::ArrayGroupOpImpl<Accumulator, typename Accumulator::parent_types, typename Accumulator::child_types>; template <class Accumulator> using ArrayGroupOpWithId = array_ops_internal::ArrayGroupOpImpl< Accumulator, typename Accumulator::parent_types, meta::tail_t<typename Accumulator::child_types>, true>; } #endif
#include "arolla/array/group_op.h" #include <cstdint> #include <optional> #include <utility> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "absl/status/status_matchers.h" #include "absl/strings/string_view.h" #include "arolla/array/array.h" #include "arolla/array/edge.h" #include "arolla/array/id_filter.h" #include "arolla/dense_array/dense_array.h" #include "arolla/memory/buffer.h" #include "arolla/memory/raw_buffer_factory.h" #include "arolla/qexpr/operators/testing/accumulators.h" #include "arolla/util/meta.h" #include "arolla/util/text.h" namespace arolla { namespace { using ::absl_testing::IsOkAndHolds; using ::absl_testing::StatusIs; using ::testing::ElementsAre; using ::testing::HasSubstr; using ::testing::Test; template <class Accumulator> using ArrayGroupOpNoDense = array_ops_internal::ArrayGroupOpImpl< Accumulator, typename Accumulator::parent_types, typename Accumulator::child_types, false, false>; template <class Accumulator> using ArrayGroupOpWithIdNoDense = array_ops_internal::ArrayGroupOpImpl< Accumulator, typename Accumulator::parent_types, meta::tail_t<typename Accumulator::child_types>, true, false>; TEST(ArrayGroupOp, FullArrayGroupSum) { auto values = CreateArray<float>({5.0f, 8.0f, 3.0f, 6.0f}); auto detail_to_group = CreateArray<int64_t>({1, 1, 2, 3}); auto splits = CreateArray<int64_t>({0, 0, 2, 3, 4}); ArrayGroupOpNoDense<testing::AggSumAccumulator<float>> agg( GetHeapBufferFactory()); ASSERT_OK_AND_ASSIGN(ArrayEdge edge1, ArrayEdge::FromMapping( detail_to_group, 4)); EXPECT_THAT(*agg.Apply(edge1, values), ElementsAre(std::nullopt, 13.0f, 3.0f, 6.0f)); ASSERT_OK_AND_ASSIGN(ArrayEdge edge2, ArrayEdge::FromSplitPoints(splits)); EXPECT_THAT(*agg.Apply(edge2, values), ElementsAre(std::nullopt, 13.0f, 3.0f, 6.0f)); } TEST(ArrayGroupOp, DenseGroupOpShortcut) { auto values = CreateArray<float>({5.0f, 8.0f, 3.0f, 6.0f}); auto detail_to_group = CreateArray<int64_t>({1, 1, 2, 3}); auto splits = CreateArray<int64_t>({0, 0, 2, 3, 4}); ArrayGroupOp<testing::AggSumAccumulator<float>> agg(GetHeapBufferFactory()); ASSERT_OK_AND_ASSIGN(ArrayEdge edge1, ArrayEdge::FromMapping( detail_to_group, 4)); EXPECT_THAT(*agg.Apply(edge1, values), ElementsAre(std::nullopt, 13.0f, 3.0f, 6.0f)); ASSERT_OK_AND_ASSIGN(ArrayEdge edge2, ArrayEdge::FromSplitPoints(splits)); EXPECT_THAT(*agg.Apply(edge2, values), ElementsAre(std::nullopt, 13.0f, 3.0f, 6.0f)); } TEST(ArrayGroupOp, ForwardId) { auto splits = CreateArray<int64_t>({0, 0, 2, 3, 4}); ASSERT_OK_AND_ASSIGN(ArrayEdge edge, ArrayEdge::FromSplitPoints(splits)); std::vector<int64_t> ids; ArrayGroupOpWithIdNoDense<testing::CollectIdsAccumulator> op( GetHeapBufferFactory(), testing::CollectIdsAccumulator(&ids)); EXPECT_OK(op.Apply(edge).status()); EXPECT_THAT(ids, ElementsAre(0, 1, 2, 3)); } TEST(ArrayGroupOp, FullArrayAverageWithErrorStatus) { auto values = CreateArray<float>({5.0f, 8.0f, 3.0f, 6.0f}); auto detail_to_group = CreateArray<int64_t>({1, 1, 2, 3}); auto splits = CreateArray<int64_t>({0, 0, 2, 3, 4}); ArrayGroupOpNoDense<testing::AverageAccumulator> agg(GetHeapBufferFactory()); ASSERT_OK_AND_ASSIGN(ArrayEdge edge1, ArrayEdge::FromMapping( detail_to_group, 4)); EXPECT_THAT( agg.Apply(edge1, values), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("empty group"))); ASSERT_OK_AND_ASSIGN(ArrayEdge edge2, ArrayEdge::FromSplitPoints(splits)); EXPECT_THAT( agg.Apply(edge2, values), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("empty group"))); } TEST(ArrayGroupOp, AggregationOnVerySparseArray) { int parent_size = 100; int group_size = 5; int child_size = parent_size * group_size; Buffer<int64_t>::Builder splits_bldr(parent_size + 1); for (int i = 0; i < parent_size + 1; ++i) { splits_bldr.Set(i, i * group_size); } auto splits = Array<int64_t>(std::move(splits_bldr).Build()); Buffer<int64_t>::Builder mapping_bldr(child_size); for (int i = 0; i < child_size; ++i) { mapping_bldr.Set((i + child_size / 2) % child_size, i / group_size); } auto mapping = Array<int64_t>(std::move(mapping_bldr).Build()); ASSERT_OK_AND_ASSIGN(ArrayEdge splits_edge, ArrayEdge::FromSplitPoints(splits)); ASSERT_OK_AND_ASSIGN(ArrayEdge mapping_edge, ArrayEdge::FromMapping(mapping, parent_size)); { ArrayGroupOpNoDense<testing::AggSumAccumulator<float>> agg( GetHeapBufferFactory()); auto ids = CreateBuffer<int64_t>({3, 25, 438, 439}); auto values = CreateBuffer<float>({1.0f, 2.0f, 3.0f, 4.0f}); Array<float> array(child_size, IdFilter(child_size, ids), {values}); ASSERT_OK_AND_ASSIGN(Array<float> res_splits, agg.Apply(splits_edge, array)); ASSERT_TRUE(res_splits.IsSparseForm()); EXPECT_FALSE(res_splits.HasMissingIdValue()); EXPECT_THAT(res_splits.id_filter().ids(), ElementsAre(0, 5, 87)); EXPECT_THAT(res_splits.dense_data(), ElementsAre(1, 2, 7)); ASSERT_OK_AND_ASSIGN(Array<float> res_mapping, agg.Apply(mapping_edge, array)); ASSERT_TRUE(res_mapping.IsSparseForm()); EXPECT_FALSE(res_mapping.HasMissingIdValue()); EXPECT_THAT(res_mapping.id_filter().ids(), ElementsAre(37, 50, 55)); EXPECT_THAT(res_mapping.dense_data(), ElementsAre(7, 1, 2)); } { ArrayGroupOpNoDense<testing::AggSumAccumulator<float>> agg( GetHeapBufferFactory()); auto ids = CreateBuffer<int64_t>({23, 25, 438, 439}); auto values = CreateBuffer<float>({1.0f, 2.0f, 3.0f, 4.0f}); Array<float> array(child_size, IdFilter(child_size, ids), {values}); ASSERT_OK_AND_ASSIGN(Array<float> res_splits, agg.Apply(splits_edge, array)); ASSERT_TRUE(res_splits.IsSparseForm()); EXPECT_FALSE(res_splits.HasMissingIdValue()); EXPECT_THAT(res_splits.id_filter().ids(), ElementsAre(4, 5, 87)); EXPECT_THAT(res_splits.dense_data(), ElementsAre(1, 2, 7)); ASSERT_OK_AND_ASSIGN(Array<float> res_mapping, agg.Apply(mapping_edge, array)); ASSERT_TRUE(res_mapping.IsSparseForm()); EXPECT_FALSE(res_mapping.HasMissingIdValue()); EXPECT_THAT(res_mapping.id_filter().ids(), ElementsAre(37, 54, 55)); EXPECT_THAT(res_mapping.dense_data(), ElementsAre(7, 1, 2)); } { ArrayGroupOpNoDense<testing::AggCountAccumulator<float>> agg( GetHeapBufferFactory()); auto ids = CreateBuffer<int64_t>({3, 25, 438, 439}); auto values = CreateBuffer<float>({1.0f, 2.0f, 3.0f, 4.0f}); Array<float> array(child_size, IdFilter(child_size, ids), {values}); ASSERT_OK_AND_ASSIGN(Array<int64_t> res_splits, agg.Apply(splits_edge, array)); ASSERT_TRUE(res_splits.IsSparseForm()); EXPECT_TRUE(res_splits.HasMissingIdValue()); EXPECT_EQ(res_splits.missing_id_value().value, 0); EXPECT_THAT(res_splits.id_filter().ids(), ElementsAre(0, 5, 87)); EXPECT_THAT(res_splits.dense_data(), ElementsAre(1, 1, 2)); ASSERT_OK_AND_ASSIGN(Array<int64_t> res_mapping, agg.Apply(mapping_edge, array)); ASSERT_TRUE(res_mapping.IsSparseForm()); EXPECT_TRUE(res_mapping.HasMissingIdValue()); EXPECT_EQ(res_mapping.missing_id_value().value, 0); EXPECT_THAT(res_mapping.id_filter().ids(), ElementsAre(37, 50, 55)); EXPECT_THAT(res_mapping.dense_data(), ElementsAre(2, 1, 1)); } { ArrayGroupOpNoDense<testing::AverageAccumulator> agg( GetHeapBufferFactory()); auto ids = CreateBuffer<int64_t>({3, 25, 38, 39}); auto values = CreateBuffer<float>({1.0f, 2.0f, 3.0f, 4.0f}); Array<float> array(child_size, IdFilter(child_size, ids), {values}); EXPECT_THAT( agg.Apply(splits_edge, array), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("empty group"))); EXPECT_THAT( agg.Apply(mapping_edge, array), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("empty group"))); } } TEST(ArrayGroupOp, AverageToScalar) { ArrayGroupOpNoDense<testing::AverageAccumulator> agg(GetHeapBufferFactory()); EXPECT_THAT(agg.Apply(ArrayGroupScalarEdge(3), CreateArray<float>({1.0f, 3.0f, 8.0f})), IsOkAndHolds(4.0f)); EXPECT_THAT( agg.Apply(ArrayGroupScalarEdge(0), Array<float>()), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("empty group"))); } TEST(ArrayGroupOp, AggregationToScalar) { ArrayGroupOpNoDense<testing::AggSumAccumulator<float>> agg( GetHeapBufferFactory()); { auto values = CreateArray<float>({5.0f, 8.0f, 3.0f, 6.0f}); ArrayGroupScalarEdge edge(values.size()); EXPECT_EQ(*agg.Apply(edge, values), 22.0f); } { auto values = Array<float>(10, 5.0f); ArrayGroupScalarEdge edge(values.size()); EXPECT_EQ(*agg.Apply(edge, values), 50.0f); } { auto values = CreateArray<float>({5.0f, std::nullopt, std::nullopt, 6.0f}) .ToSparseForm(); ArrayGroupScalarEdge edge(values.size()); EXPECT_EQ(*agg.Apply(edge, values), 11.0f); } { auto values = CreateArray<float>({5.0f, 3.0f, 3.0f, 6.0f}).ToSparseForm(3.0f); ArrayGroupScalarEdge edge(values.size()); EXPECT_EQ(*agg.Apply(edge, values), 17.0f); } } TEST(ArrayGroupOp, RankValues) { auto values = CreateArray<float>({3.0f, 5.0f, 2.0f, 1.0f, 3.1f, 7.0f}); auto detail_to_group = CreateArray<int64_t>({0, 0, 0, 0, 1, 1}); auto splits = CreateArray<int64_t>({0, 4, 6}); ArrayGroupOpNoDense<testing::RankValuesAccumulator<float>> agg( GetHeapBufferFactory()); ASSERT_OK_AND_ASSIGN(ArrayEdge edge1, ArrayEdge::FromMapping( detail_to_group, 2)); EXPECT_THAT(*agg.Apply(edge1, values), ElementsAre(1, 0, 2, 3, 1, 0)); ASSERT_OK_AND_ASSIGN(ArrayEdge edge2, ArrayEdge::FromSplitPoints(splits)); EXPECT_THAT(*agg.Apply(edge2, values), ElementsAre(1, 0, 2, 3, 1, 0)); EXPECT_THAT(*agg.Apply(ArrayGroupScalarEdge(values.size()), values), ElementsAre(5, 1, 4, 0, 2, 3)); } TEST(ArrayGroupOp, RankValuesSparse) { auto values = CreateArray<float>(100, {0, 10, 20, 30, 40, 50}, {3.0f, 5.0f, 2.0f, 1.0f, 3.1f, 7.0f}); auto detail_to_group = CreateArray<int64_t>(100, {0, 10, 20, 30, 40, 50}, {0, 0, 0, 0, 1, 1}); auto splits = CreateArray<int64_t>({0, 40, 100}); ArrayGroupOpNoDense<testing::RankValuesAccumulator<float>> agg( GetHeapBufferFactory()); ASSERT_OK_AND_ASSIGN(ArrayEdge edge1, ArrayEdge::FromMapping( detail_to_group, 2)); { ASSERT_OK_AND_ASSIGN(auto res, agg.Apply(edge1, values)); EXPECT_TRUE(res.IsSparseForm()); EXPECT_THAT(res.id_filter().ids(), ElementsAre(0, 10, 20, 30, 40, 50)); EXPECT_THAT(res.dense_data(), ElementsAre(1, 0, 2, 3, 1, 0)); } ASSERT_OK_AND_ASSIGN(ArrayEdge edge2, ArrayEdge::FromSplitPoints(splits)); { ASSERT_OK_AND_ASSIGN(auto res, agg.Apply(edge2, values)); EXPECT_TRUE(res.IsSparseForm()); EXPECT_THAT(res.id_filter().ids(), ElementsAre(0, 10, 20, 30, 40, 50)); EXPECT_THAT(res.dense_data(), ElementsAre(1, 0, 2, 3, 1, 0)); } { ASSERT_OK_AND_ASSIGN( auto res, agg.Apply(ArrayGroupScalarEdge(values.size()), values)); EXPECT_TRUE(res.IsSparseForm()); EXPECT_THAT(res.id_filter().ids(), ElementsAre(0, 10, 20, 30, 40, 50)); EXPECT_THAT(res.dense_data(), ElementsAre(5, 1, 4, 0, 2, 3)); } } TEST(ArrayGroupOp, PartialSparseMapping) { auto a = CreateArray<float>({2.0f, 1.0f, 1.0f}); auto b = CreateArray<float>({2.0f, 2.0f, 1.0f}); auto c = CreateArray<float>({0.0f, -1.0f, -1.0f}); IdFilter ids(100, CreateBuffer<int64_t>({5, 10, 15, 20, 25, 30})); auto x = Array<float>( 100, ids, CreateDenseArray<float>({1.0, 1.0, 1.0, 1.0, 1.0, 1.0})); auto y = Array<float>( 100, ids, CreateDenseArray<float>({1.0, 2.0, 3.0, 1.0, 3.0, 2.0})); auto z = Array<float>( 100, ids, CreateDenseArray<float>({1.0, 2.0, 1.0, 2.0, 1.0, 2.0})); IdFilter edge_ids(100, CreateBuffer<int64_t>({0, 5, 10, 15, 20, 25})); auto detail_to_group = Array<int64_t>( 100, edge_ids, CreateDenseArray<int64_t>({0, 0, 1, 1, 2, 2})); ArrayGroupOpNoDense<testing::WeightedSumAccumulator> agg( GetHeapBufferFactory()); { ASSERT_OK_AND_ASSIGN(ArrayEdge edge, ArrayEdge::FromMapping(detail_to_group, 3)); ASSERT_OK_AND_ASSIGN(auto res, agg.Apply(edge, a, b, c, x, y, z)); EXPECT_TRUE(res.IsSparseForm()); EXPECT_FALSE(res.HasMissingIdValue()); EXPECT_THAT(res.id_filter().ids(), ElementsAre(5, 10, 15, 20, 25)); EXPECT_THAT(res.dense_data(), ElementsAre(4.f, 3.f, 6.f, 0.f, 3.f)); } { ASSERT_OK_AND_ASSIGN( ArrayEdge edge, ArrayEdge::FromSplitPoints(CreateArray<int64_t>({0, 10, 20, 100}))); ASSERT_OK_AND_ASSIGN(auto res, agg.Apply(edge, a, b, c, x, y, z)); EXPECT_TRUE(res.IsSparseForm()); EXPECT_FALSE(res.HasMissingIdValue()); EXPECT_THAT(res.id_filter().ids(), ElementsAre(5, 10, 15, 20, 25, 30)); EXPECT_THAT(res.dense_data(), ElementsAre(4.f, 3.f, 6.f, 0.f, 3.f, 1.0f)); } } TEST(ArrayGroupOp, PartialDenseMapping) { auto a = CreateArray<float>({2.0f, 1.0f, 1.0f}); auto b = CreateArray<float>({2.0f, 2.0f, std::nullopt}); auto c = CreateArray<float>({0.0f, -1.0f, -1.0f}); auto x = CreateArray<float>({1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f}); auto y = CreateArray<float>({1.0f, 2.0f, 3.0f, 1.0f, 3.0f, 2.0f}); auto z = CreateArray<float>({1.f, 2.f, 1.f, std::nullopt, 1.f, 2.f}); auto splits = CreateArray<int64_t>({0, 2, 5, 6}); auto detail_to_group = CreateArray<int64_t>({0, 0, 1, 1, 1, 2}); ArrayGroupOpNoDense<testing::WeightedSumAccumulator> agg( GetHeapBufferFactory()); ASSERT_OK_AND_ASSIGN(ArrayEdge edge1, ArrayEdge::FromSplitPoints(splits)); EXPECT_THAT(*agg.Apply(edge1, a, b, c, x, y, z), ElementsAre(4.f, 6.f, 6.f, std::nullopt, 6.f, std::nullopt)); ASSERT_OK_AND_ASSIGN(ArrayEdge edge2, ArrayEdge::FromMapping( detail_to_group, 3)); EXPECT_THAT(*agg.Apply(edge2, a, b, c, x, y, z), ElementsAre(4.f, 6.f, 6.f, std::nullopt, 6.f, std::nullopt)); } TEST(ArrayGroupOp, PartialGroupScalarEdge) { auto x = CreateArray<float>({1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f}); auto y = CreateArray<float>({1.0f, 2.0f, 3.0f, 1.0f, 3.0f, 2.0f}); auto z = CreateArray<float>({1.f, 2.f, 1.f, std::nullopt, 1.f, 2.f}); ArrayGroupOpNoDense<testing::WeightedSumAccumulator> agg( GetHeapBufferFactory()); EXPECT_THAT(*agg.Apply(ArrayGroupScalarEdge(6), 2.0f, 2.0f, 0.0f, x, y, z), ElementsAre(4.f, 6.f, 8.f, std::nullopt, 8.f, 6.f)); EXPECT_THAT( *agg.Apply(ArrayGroupScalarEdge(6), 2.0f, 2.0f, 0.0f, x.ToSparseForm(1.0f), y.ToSparseForm(1.0f), z.ToSparseForm()), ElementsAre(4.f, 6.f, 8.f, std::nullopt, 8.f, 6.f)); } TEST(ArrayGroupOp, OptionalText) { auto detail_to_group = CreateArray<int64_t>({1, 1, 2, 3, 3}); auto splits = CreateArray<int64_t>({0, 0, 2, 3, 5}); auto prefixes = CreateArray<Text>( {Text("empty"), Text("some:\n"), Text("prefix:\n"), std::nullopt}); auto values = CreateArray<Text>( {Text("w1"), std::nullopt, Text("w3"), Text("w4"), Text("w5")}); auto comments = CreateArray<Text>({std::nullopt, Text("it is word #2"), std::nullopt, Text("it is word #4"), std::nullopt}); ArrayGroupOpNoDense<testing::AggTextAccumulator> agg(GetHeapBufferFactory()); ASSERT_OK_AND_ASSIGN(ArrayEdge edge1, ArrayEdge::FromMapping( detail_to_group, 4)); ASSERT_OK_AND_ASSIGN(Array<Text> res1, agg.Apply(edge1, prefixes, values, comments)); ASSERT_OK_AND_ASSIGN(ArrayEdge edge2, ArrayEdge::FromSplitPoints(splits)); ASSERT_OK_AND_ASSIGN(Array<Text> res2, agg.Apply(edge2, prefixes, values, comments)); using V = absl::string_view; EXPECT_THAT(res1, ElementsAre(V("empty"), V("some:\nw1\n"), V("prefix:\nw3\n"), V("w4 (it is word #4)\nw5\n"))); EXPECT_EQ(res1.size(), res2.size()); for (int64_t i = 0; i < res1.size(); ++i) { EXPECT_EQ(res1[i], res2[i]); } } } }
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/array/group_op.h
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/array/group_op_test.cc
1ca990dbeca224035efdabffecc7f3738df6b52c
04d8e833-ef24-4c6a-94a9-6f57be904037
cpp
google/arolla
ops_util
arolla/array/ops_util.h
arolla/array/ops_util_test.cc
#ifndef AROLLA_ARRAY_OPS_UTIL_H_ #define AROLLA_ARRAY_OPS_UTIL_H_ #include <algorithm> #include <cstddef> #include <cstdint> #include <iterator> #include <tuple> #include <type_traits> #include <utility> #include "absl/log/check.h" #include "arolla/array/array.h" #include "arolla/array/id_filter.h" #include "arolla/dense_array/dense_array.h" #include "arolla/dense_array/ops/util.h" #include "arolla/memory/optional_value.h" #include "arolla/memory/raw_buffer_factory.h" #include "arolla/util/meta.h" #include "arolla/util/view_types.h" namespace arolla::array_ops_internal { inline void empty_missing_fn(int64_t, int64_t) {} template <bool ConvertToDense, class ArgList> class ArrayOpsUtil; template <bool ConvertToDense, class... Ts> class ArrayOpsUtil<ConvertToDense, meta::type_list<Ts...>> { public: explicit ArrayOpsUtil(int64_t size, const AsArray<Ts>&... args, RawBufferFactory* buf_factory = GetHeapBufferFactory()) : size_(size) { DCHECK(((size == args.size()) && ... && true)); if constexpr (ConvertToDense) { dense_ = std::make_tuple(args.ToDenseForm(buf_factory).dense_data()...); } else { default_valid_ = !(BoundsValidIds<Ts>(args) || ...); if (default_valid_) { default_values_ = std::make_tuple( MaybeUnwrapOptional<Ts>(args.missing_id_value())...); } if (IsSameIdFilter(args...)) { ids_ = First(args...).id_filter(); dense_ = std::make_tuple(args.dense_data()...); } else { if (!default_valid_) { IdFilter full(IdFilter::kFull); ids_ = IdFilter::UpperBoundIntersect( (BoundsValidIds<Ts>(args) ? args.id_filter() : full)...); } else { ids_ = IdFilter::UpperBoundMerge(First(args...).size(), buf_factory, args.id_filter()...); } dense_ = std::make_tuple( args.WithIds(ids_, args.missing_id_value(), buf_factory) .dense_data()...); } } } template <class Fn, class RepeatedFn, class MissedFn> void Iterate(int64_t from, int64_t to, Fn&& fn, MissedFn&& missing_fn, RepeatedFn&& repeated_fn) const { return Iterate(std::forward<Fn>(fn), std::forward<RepeatedFn>(repeated_fn), std::forward<MissedFn>(missing_fn), std::index_sequence_for<Ts...>{}, from, to); } template <class Fn, class MissedFn> void Iterate(int64_t from, int64_t to, Fn&& fn, MissedFn&& missing_fn) const { auto repeated_fn = [&](int64_t id, int64_t count, view_type_t<Ts>... args) { for (int64_t i = 0; i < count; ++i) fn(id + i, args...); }; return Iterate(fn, std::move(repeated_fn), std::forward<MissedFn>(missing_fn), std::index_sequence_for<Ts...>{}, from, to); } template <class Fn> void Iterate(int64_t from, int64_t to, Fn&& fn) const { Iterate(from, to, std::forward<Fn>(fn), empty_missing_fn); } template <class Fn> void IterateSimple(Fn&& fn) const { return IterateSimple(std::forward<Fn>(fn), std::index_sequence_for<Ts...>{}); } int64_t size() const { return size_; } int64_t PresentCountUpperEstimate() const { if (ids_.type() == IdFilter::kFull || default_valid_) { return size_; } else { return ids_.ids().size(); } } private: using DenseUtil = dense_ops_internal::DenseOpsUtil<meta::type_list<Ts...>>; template <class Fn, class RepeatedFn, class MissedFn, size_t... Is> void Iterate(Fn&& fn, RepeatedFn&& repeated_fn, MissedFn&& missing_fn, std::index_sequence<Is...>, uint64_t from, uint64_t to) const { DCHECK_GE(from, 0); DCHECK_GE(to, from); if (ids_.type() == IdFilter::kFull) { DenseUtil::Iterate( [&](int64_t id, bool valid, view_type_t<Ts>... args) { if (valid) { fn(id, args...); } else { missing_fn(id, 1); } }, from, to, std::get<Is>(dense_)...); return; } DCHECK(!ConvertToDense) << "If ConvertToDense=true, `ids_` must be full"; if constexpr (!ConvertToDense) { auto defaultFn = [&](int64_t id, int64_t row_count) { if (default_valid_) { repeated_fn(id, row_count, std::get<Is>(default_values_)...); } else { missing_fn(id, row_count); } }; auto ids_iter = std::lower_bound(ids_.ids().begin(), ids_.ids().end(), from + ids_.ids_offset()); int64_t offset_from = std::distance(ids_.ids().begin(), ids_iter); auto iter_to = std::lower_bound(ids_.ids().begin(), ids_.ids().end(), to + ids_.ids_offset()); int64_t offset_to = std::distance(ids_.ids().begin(), iter_to); int64_t id = from; const int64_t* ids = ids_.ids().begin(); DenseUtil::Iterate( [&](int64_t offset, bool valid, view_type_t<Ts>... args) { int64_t new_id = ids[offset] - ids_.ids_offset(); if (id < new_id) defaultFn(id, new_id - id); if (valid) { fn(new_id, args...); } else { missing_fn(new_id, 1); } id = new_id + 1; }, offset_from, offset_to, std::get<Is>(dense_)...); if (id < to) defaultFn(id, to - id); } } template <class Fn, size_t... Is> void IterateSimple(Fn&& fn, std::index_sequence<Is...>) const { if (ids_.type() == IdFilter::kFull) { DenseUtil::IterateFromZero( [&](int64_t id, bool valid, view_type_t<Ts>... args) { if (valid) fn(id, args...); }, size_, std::get<Is>(dense_)...); return; } DCHECK(!ConvertToDense) << "If ConvertToDense=true, `ids_` must be full"; if constexpr (!ConvertToDense) { int64_t id = 0; const int64_t* ids = ids_.ids().begin(); DenseUtil::IterateFromZero( [&](int64_t offset, bool valid, view_type_t<Ts>... args) { int64_t new_id = ids[offset] - ids_.ids_offset(); if (default_valid_ && id < new_id) { while (id < new_id) { fn(id++, std::get<Is>(default_values_)...); } } if (valid) fn(new_id, args...); id = new_id + 1; }, ids_.ids().size(), std::get<Is>(dense_)...); if (default_valid_) { while (id < size_) { fn(id++, std::get<Is>(default_values_)...); } } } } template <class Arg, class A> static bool BoundsValidIds(const A& arg) { return !is_optional_v<Arg> && !arg.HasMissingIdValue(); } template <class A, class... As> static bool IsSameIdFilter(const A& a, const As&... as) { return ((a.id_filter().IsSame(as.id_filter()) && ... && true)); } template <class A, class... As> static const A& First(const A& a, const As&...) { return a; } template <class To, class From> static const To& MaybeUnwrapOptional(const OptionalValue<From>& v) { if constexpr (!is_optional_v<To>) { DCHECK(v.present); return v.value; } else { return v; } } int64_t size_; IdFilter ids_{IdFilter::kFull}; std::tuple<AsDenseArray<Ts>...> dense_; bool default_valid_; std::tuple<Ts...> default_values_; }; template <bool ConvertToDense> class ArrayOpsUtil<ConvertToDense, meta::type_list<>> { public: explicit ArrayOpsUtil(int64_t size, RawBufferFactory* = nullptr) : size_(size) {} template <class Fn, class RepeatedFn, class MissedFn> void Iterate(int64_t from, int64_t to, Fn&&, MissedFn&&, RepeatedFn&& repeated_fn) const { repeated_fn(from, to - from); } template <class Fn, class MissedFn> void Iterate(int64_t from, int64_t to, Fn&& fn, MissedFn&&) const { for (int64_t i = from; i < to; ++i) fn(i); } template <class Fn> void Iterate(int64_t from, int64_t to, Fn&& fn) const { for (int64_t i = from; i < to; ++i) fn(i); } template <class Fn> void IterateSimple(Fn&& fn) const { for (int64_t i = 0; i < size_; ++i) fn(i); } int64_t size() const { return size_; } int64_t PresentCountUpperEstimate() const { return size_; } private: int64_t size_; }; template <class OptionalityList, class TypeList> struct ApplyOptionalityToTypes; template <class... Os, class... Ts> struct ApplyOptionalityToTypes<meta::type_list<Os...>, meta::type_list<Ts...>> { using types = meta::type_list<std::conditional_t<is_optional_v<Os>, ::arolla::OptionalValue<Ts>, Ts>...>; }; } namespace arolla { template <class Fn, class T, class... Ts> void ArraysIterate(Fn&& fn, const Array<T>& first_array, const Array<Ts>&... arrays) { static_assert(meta::function_traits<Fn>::arity == sizeof...(arrays) + 2); using arg_list = typename array_ops_internal::ApplyOptionalityToTypes< meta::tail_t<typename meta::function_traits<Fn>::arg_types>, meta::type_list<T, Ts...>>::types; array_ops_internal::ArrayOpsUtil<false, arg_list> util( first_array.size(), first_array, arrays...); util.IterateSimple(std::forward<Fn>(fn)); } template <class Fn, class T, class... Ts> void ArraysIterateDense(Fn&& fn, const Array<T>& first_array, const Array<Ts>&... arrays) { static_assert(meta::function_traits<Fn>::arity == sizeof...(arrays) + 2); using arg_list = typename array_ops_internal::ApplyOptionalityToTypes< meta::tail_t<typename meta::function_traits<Fn>::arg_types>, meta::type_list<T, Ts...>>::types; array_ops_internal::ArrayOpsUtil<true, arg_list> util(first_array.size(), first_array, arrays...); util.IterateSimple(std::forward<Fn>(fn)); } } #endif
#include "arolla/array/ops_util.h" #include <cstdint> #include <optional> #include <string> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/strings/str_format.h" #include "absl/strings/string_view.h" #include "arolla/array/array.h" #include "arolla/array/id_filter.h" #include "arolla/dense_array/dense_array.h" #include "arolla/memory/buffer.h" #include "arolla/memory/optional_value.h" #include "arolla/util/bytes.h" #include "arolla/util/meta.h" #include "arolla/util/text.h" using ::testing::ElementsAre; namespace arolla::array_ops_internal { TEST(ArrayOpsUtilTest, IterateConst) { ArrayOpsUtil<false, meta::type_list<int, int>> util(6, Array<int>(6, 3), Array<int>(6, 7)); { std::vector<int64_t> ids; std::vector<int> vx; std::vector<int> vy; util.Iterate(1, 4, [&](int64_t id, int x, int y) { ids.push_back(id); vx.push_back(x); vy.push_back(y); }); EXPECT_THAT(ids, ElementsAre(1, 2, 3)); EXPECT_THAT(vx, ElementsAre(3, 3, 3)); EXPECT_THAT(vy, ElementsAre(7, 7, 7)); } { int fn_count = 0; int missing_fn_count = 0; int repeated_fn_count = 0; auto fn = [&](int64_t, int, int) { fn_count++; }; auto missing_fn = [&](int64_t, int64_t) { missing_fn_count++; }; auto repeated_fn = [&](int64_t first_id, int64_t count, int x, int y) { EXPECT_EQ(first_id, 1); EXPECT_EQ(count, 3); EXPECT_EQ(x, 3); EXPECT_EQ(y, 7); repeated_fn_count++; }; util.Iterate(1, 4, fn, missing_fn, repeated_fn); EXPECT_EQ(fn_count, 0); EXPECT_EQ(missing_fn_count, 0); EXPECT_EQ(repeated_fn_count, 1); } } TEST(ArrayOpsUtilTest, IterateSparse) { auto q1 = CreateArray<int>(20, {3, 7, 8, 10}, {1, 2, 3, 4}); auto q2 = CreateArray<int>(20, {4, 8, 10, 11}, {1, 2, 3, 4}); std::vector<std::string> res; auto fn = [&](int64_t id, int x, int y) { res.push_back(absl::StrFormat("single(%d, %d, %d)", id, x, y)); }; auto missing_fn = [&](int64_t id, int64_t count) { res.push_back(absl::StrFormat("missing(%d, %d)", id, count)); }; auto repeated_fn = [&](int64_t id, int64_t count, int x, int y) { res.push_back(absl::StrFormat("repeated(%d, %d, %d, %d)", id, count, x, y)); }; ArrayOpsUtil<false, meta::type_list<int, int>> util(20, q1, q2); util.Iterate(0, 15, fn, missing_fn, repeated_fn); EXPECT_THAT( res, ElementsAre("missing(0, 4)", "missing(4, 1)", "missing(5, 3)", "single(8, 3, 2)", "missing(9, 1)", "single(10, 4, 3)", "missing(11, 1)", "missing(12, 3)")); } TEST(ArrayOpsUtilTest, IterateSparseWithMissedIdValue) { Array<int> q1(20, IdFilter(20, CreateBuffer<int64_t>({3, 7, 8, 10})), CreateDenseArray<int>({1, 2, 3, 4}), 9); auto q2 = CreateArray<int>(20, {4, 8, 10, 11}, {1, 2, 3, 4}); std::vector<std::string> res; auto fn = [&](int64_t id, int x, OptionalValue<int> y) { if (y.present) { res.push_back(absl::StrFormat("single(%d, %d, %d)", id, x, y.value)); } else { res.push_back(absl::StrFormat("single(%d, %d, NA)", id, x)); } }; auto missing_fn = [&](int64_t id, int64_t count) { res.push_back(absl::StrFormat("missing(%d, %d)", id, count)); }; auto repeated_fn = [&](int64_t id, int64_t count, int x, OptionalValue<int> y) { if (y.present) { res.push_back( absl::StrFormat("repeated(%d, %d, %d, %d)", id, count, x, y.value)); } else { res.push_back(absl::StrFormat("repeated(%d, %d, %d, NA)", id, count, x)); } }; ArrayOpsUtil<false, meta::type_list<int, OptionalValue<int>>> util(20, q1, q2); util.Iterate(0, 15, fn, missing_fn, repeated_fn); EXPECT_THAT(res, ElementsAre("repeated(0, 3, 9, NA)", "single(3, 1, NA)", "single(4, 9, 1)", "repeated(5, 2, 9, NA)", "single(7, 2, NA)", "single(8, 3, 2)", "repeated(9, 1, 9, NA)", "single(10, 4, 3)", "single(11, 9, 4)", "repeated(12, 3, 9, NA)")); } TEST(ArrayOpsUtilTest, ArraysIterate) { Array<int> array_x = CreateArray<int>({5, 4, std::nullopt, 2, 1}); Array<int> array_y = CreateArray<int>({3, std::nullopt, 3, 1, 3}).ToSparseForm(); std::vector<int64_t> ids; std::vector<OptionalValue<int>> vx; std::vector<int> vy; ArraysIterate( [&](int64_t id, OptionalValue<int> x, int y) { ids.push_back(id); vx.push_back(x); vy.push_back(y); }, array_x, array_y); EXPECT_THAT(ids, ElementsAre(0, 2, 3, 4)); EXPECT_THAT(vx, ElementsAre(5, std::nullopt, 2, 1)); EXPECT_THAT(vy, ElementsAre(3, 3, 1, 3)); } TEST(ArrayOpsUtilTest, ArraysIterateDense) { Array<int> array_x = CreateArray<int>({5, 4, std::nullopt, 2, 1}); Array<int> array_y = CreateArray<int>({3, std::nullopt, 3, 1, 3}).ToSparseForm(); std::vector<int64_t> ids; std::vector<OptionalValue<int>> vx; std::vector<int> vy; ArraysIterateDense( [&](int64_t id, OptionalValue<int> x, int y) { ids.push_back(id); vx.push_back(x); vy.push_back(y); }, array_x, array_y); EXPECT_THAT(ids, ElementsAre(0, 2, 3, 4)); EXPECT_THAT(vx, ElementsAre(5, std::nullopt, 2, 1)); EXPECT_THAT(vy, ElementsAre(3, 3, 1, 3)); } TEST(ArrayOpsUtilTest, ArraysIterateStrings) { Array<Text> array_x = CreateArray<Text>( {Text("5"), Text("4"), std::nullopt, Text("2"), Text("1")}); Array<Bytes> array_y = CreateArray<Bytes>( {Bytes("3"), std::nullopt, Bytes("3"), Bytes("1"), Bytes("3")}) .ToSparseForm(); std::vector<int64_t> ids; std::vector<OptionalValue<absl::string_view>> vx; std::vector<absl::string_view> vy; ArraysIterate( [&](int64_t id, OptionalValue<absl::string_view> x, absl::string_view y) { ids.push_back(id); vx.push_back(x); vy.push_back(y); }, array_x, array_y); EXPECT_THAT(ids, ElementsAre(0, 2, 3, 4)); EXPECT_THAT(vx, ElementsAre("5", std::nullopt, "2", "1")); EXPECT_THAT(vy, ElementsAre("3", "3", "1", "3")); } }
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/array/ops_util.h
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/array/ops_util_test.cc
1ca990dbeca224035efdabffecc7f3738df6b52c
3c8a649d-a07a-4083-bbd8-6bf737c237e3
cpp
google/arolla
multi_edge_util
arolla/dense_array/ops/multi_edge_util.h
arolla/dense_array/ops/multi_edge_util_test.cc
#ifndef AROLLA_DENSE_ARRAY_OPS_MULTI_EDGE_UTIL_H_ #define AROLLA_DENSE_ARRAY_OPS_MULTI_EDGE_UTIL_H_ #include <cstdint> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/types/span.h" #include "arolla/dense_array/dense_array.h" #include "arolla/dense_array/edge.h" #include "arolla/dense_array/ops/util.h" #include "arolla/memory/raw_buffer_factory.h" #include "arolla/util/meta.h" #include "arolla/util/status.h" #include "arolla/util/view_types.h" #include "arolla/util/status_macros_backport.h" namespace arolla { struct DenseArrayMultiEdgeUtil { template <class T> using Array = DenseArray<T>; template <class T> using AsArray = AsDenseArray<T>; using Edge = DenseArrayEdge; template <class State, class Fn, class... ParentTs> static absl::Status ApplyParentArgs(Fn fn, absl::Span<State> states, meta::type_list<ParentTs...>, const AsDenseArray<ParentTs>&... args) { using ParentUtil = dense_ops_internal::DenseOpsUtil<meta::type_list<ParentTs...>>; if (((args.size() != states.size()) || ... || false)) { return SizeMismatchError( {static_cast<int64_t>(states.size()), args.size()...}); } auto fn_with_state = [&](int64_t id, bool valid, view_type_t<ParentTs>... v) { if (valid) fn(states[id], v...); }; ParentUtil::IterateFromZero(fn_with_state, states.size(), args...); return absl::OkStatus(); } template <class State, class Fn, class... ChildTs> static absl::Status ApplyChildArgs(Fn fn, absl::Span<State> states, const DenseArrayEdge& edge, meta::type_list<ChildTs...>, const AsDenseArray<ChildTs>&... args) { if (states.size() != edge.parent_size()) { return SizeMismatchError( {static_cast<int64_t>(states.size()), edge.parent_size()}); } if (((args.size() != edge.child_size()) || ... || false)) { return SizeMismatchError({edge.child_size(), args.size()...}); } switch (edge.edge_type()) { case DenseArrayEdge::SPLIT_POINTS: { using ChildUtil = dense_ops_internal::DenseOpsUtil<meta::type_list<ChildTs...>>; absl::Span<const int64_t> splits = edge.edge_values().values.span(); for (int64_t parent_id = 0; parent_id < edge.parent_size(); ++parent_id) { State& state = states[parent_id]; auto fn_with_state = [&](int64_t child_id, bool valid, view_type_t<ChildTs>... v) { if (valid) fn(state, child_id, v...); }; ChildUtil::Iterate(fn_with_state, splits[parent_id], splits[parent_id + 1], args...); } return absl::OkStatus(); } case DenseArrayEdge::MAPPING: { auto fn_with_state = [&](int64_t child_id, bool valid, int64_t parent_id, view_type_t<ChildTs>... v) { if (valid) fn(states[parent_id], child_id, v...); }; const DenseArray<int64_t>& mapping = edge.edge_values(); using MappingAndChildUtil = dense_ops_internal::DenseOpsUtil< meta::type_list<int64_t, ChildTs...>>; MappingAndChildUtil::IterateFromZero(fn_with_state, edge.child_size(), mapping, args...); return absl::OkStatus(); } default: return absl::InvalidArgumentError("unsupported edge type"); } } template <class ResT, class State, class Fn, class... ChildTs> static absl::StatusOr<DenseArray<ResT>> ProduceResult( RawBufferFactory* buf_factory, Fn fn, absl::Span<State> states, const DenseArrayEdge& edge, meta::type_list<ChildTs...> types, const AsDenseArray<ChildTs>&... args) { DenseArrayBuilder<ResT> builder(edge.child_size(), buf_factory); auto process_result_fn = [&](State& state, int64_t child_id, view_type_t<ChildTs>... v) { builder.Set(child_id, fn(state, child_id, v...)); }; RETURN_IF_ERROR( ApplyChildArgs(process_result_fn, states, edge, types, args...)); return std::move(builder).Build(); } }; } #endif
#include "arolla/dense_array/ops/multi_edge_util.h" #include <cstdint> #include <optional> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "absl/status/status_matchers.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "arolla/dense_array/dense_array.h" #include "arolla/dense_array/edge.h" #include "arolla/memory/optional_value.h" #include "arolla/memory/raw_buffer_factory.h" #include "arolla/util/bytes.h" #include "arolla/util/meta.h" using ::absl_testing::IsOkAndHolds; using ::absl_testing::StatusIs; using ::testing::ElementsAre; using ::testing::HasSubstr; namespace arolla { namespace { TEST(MultiEdgeUtil, ApplyParentArgs) { struct State { int x = -1; OptionalValue<float> y; }; auto x = CreateDenseArray<int>({1, std::nullopt, 3}); auto y = CreateDenseArray<float>({std::nullopt, 0.5, 2.5}); auto b = CreateDenseArray<int>( {1, 2, std::nullopt, std::nullopt, std::nullopt, 6}); std::vector<State> states(3); absl::Span<State> state_span(states.data(), states.size()); EXPECT_THAT(DenseArrayMultiEdgeUtil::ApplyParentArgs( [](State&, int) {}, state_span, meta::type_list<int>{}, b), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("argument sizes mismatch"))); EXPECT_OK(DenseArrayMultiEdgeUtil::ApplyParentArgs( [](State& s, int x, OptionalValue<float> y) { s.x = x; s.y = y; }, state_span, meta::type_list<int, OptionalValue<float>>{}, x, y)); EXPECT_EQ(states[0].x, 1); EXPECT_EQ(states[1].x, -1); EXPECT_EQ(states[2].x, 3); EXPECT_EQ(states[0].y, std::nullopt); EXPECT_EQ(states[1].y, std::nullopt); EXPECT_EQ(states[2].y, 2.5f); } TEST(MultiEdgeUtil, ApplyChildArgs) { struct State { std::vector<int64_t> ids1; std::vector<Bytes> a; std::vector<OptionalValue<int>> b; std::vector<int64_t> ids2; std::vector<float> c; }; ASSERT_OK_AND_ASSIGN(auto edge1, DenseArrayEdge::FromMapping( CreateDenseArray<int64_t>({0, 0, 1, 1, 1, 2}), 3)); auto a = CreateDenseArray<Bytes>({ Bytes("ab"), std::nullopt, Bytes("cd"), Bytes("de"), std::nullopt, Bytes("gh") }); auto b = CreateDenseArray<int>({ 1, 2, std::nullopt, std::nullopt, std::nullopt, 6 }); ASSERT_OK_AND_ASSIGN( auto edge2, DenseArrayEdge::FromSplitPoints(CreateDenseArray<int64_t>({0, 3, 3, 7}))); auto c = CreateDenseArray<float>({ std::nullopt, 0.2f, 0.3f, 0.4f, 0.5f, 0.6f, std::nullopt }); std::vector<State> states(3); absl::Span<State> state_span(states.data(), states.size()); EXPECT_THAT(DenseArrayMultiEdgeUtil::ApplyChildArgs( [](State&, int64_t, float) {}, state_span, edge1, meta::type_list<float>{}, c), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("argument sizes mismatch"))); EXPECT_THAT(DenseArrayMultiEdgeUtil::ApplyChildArgs( [](State&, int64_t, float) {}, state_span.subspan(1), edge2, meta::type_list<float>{}, c), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("argument sizes mismatch"))); EXPECT_OK(DenseArrayMultiEdgeUtil::ApplyChildArgs( [](State& s, int64_t child_id, absl::string_view a, OptionalValue<int> b) { s.ids1.push_back(child_id); s.a.push_back(Bytes(a)); s.b.push_back(b); }, state_span, edge1, meta::type_list<Bytes, OptionalValue<int>>{}, a, b)); EXPECT_OK(DenseArrayMultiEdgeUtil::ApplyChildArgs( [](State& s, int64_t child_id, float c) { s.ids2.push_back(child_id); s.c.push_back(c); }, state_span, edge2, meta::type_list<float>{}, c)); EXPECT_THAT(states[0].ids1, ElementsAre(0)); EXPECT_THAT(states[0].a, ElementsAre(Bytes("ab"))); EXPECT_THAT(states[0].b, ElementsAre(1)); EXPECT_THAT(states[1].ids1, ElementsAre(2, 3)); EXPECT_THAT(states[1].a, ElementsAre(Bytes("cd"), Bytes("de"))); EXPECT_THAT(states[1].b, ElementsAre(std::nullopt, std::nullopt)); EXPECT_THAT(states[2].ids1, ElementsAre(5)); EXPECT_THAT(states[2].a, ElementsAre(Bytes("gh"))); EXPECT_THAT(states[2].b, ElementsAre(6)); EXPECT_THAT(states[0].ids2, ElementsAre(1, 2)); EXPECT_THAT(states[0].c, ElementsAre(0.2f, 0.3f)); EXPECT_THAT(states[1].ids2, ElementsAre()); EXPECT_THAT(states[1].c, ElementsAre()); EXPECT_THAT(states[2].ids2, ElementsAre(3, 4, 5)); EXPECT_THAT(states[2].c, ElementsAre(0.4f, 0.5f, 0.6f)); } TEST(MultiEdgeUtil, ProduceResult) { struct State { int parent_id; }; ASSERT_OK_AND_ASSIGN(auto edge1, DenseArrayEdge::FromMapping( CreateDenseArray<int64_t>({0, 0, 1, 1, 1, 2}), 3)); auto a = CreateDenseArray<Bytes>({ Bytes("ab"), std::nullopt, Bytes("cd"), Bytes("de"), std::nullopt, Bytes("gh") }); auto b = CreateDenseArray<int>({ 1, 2, std::nullopt, std::nullopt, std::nullopt, 6 }); ASSERT_OK_AND_ASSIGN( auto edge2, DenseArrayEdge::FromSplitPoints(CreateDenseArray<int64_t>({0, 3, 3, 7}))); auto c = CreateDenseArray<float>({ std::nullopt, 0.2f, 0.3f, 0.4f, 0.5f, 0.6f, std::nullopt }); std::vector<State> states(3); for (int i = 0; i < 3; ++i) states[i].parent_id = i; absl::Span<State> state_span(states.data(), states.size()); EXPECT_THAT( DenseArrayMultiEdgeUtil::ProduceResult<float>( GetHeapBufferFactory(), [](State&, int64_t, float) { return 0.f; }, state_span, edge1, meta::type_list<float>{}, c), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("argument sizes mismatch"))); EXPECT_THAT(DenseArrayMultiEdgeUtil::ProduceResult<int64_t>( GetHeapBufferFactory(), [](State& s, int64_t child_id, absl::string_view, OptionalValue<int> b) { return child_id + b.AsOptional().value_or(0); }, state_span, edge1, meta::type_list<Bytes, OptionalValue<int>>{}, a, b), IsOkAndHolds(ElementsAre(1, std::nullopt, 2, 3, std::nullopt, 11 ))); EXPECT_THAT( DenseArrayMultiEdgeUtil::ProduceResult<float>( GetHeapBufferFactory(), [](State& s, int64_t, float c) { return OptionalValue<float>{c < 0.55f, s.parent_id + c}; }, state_span, edge2, meta::type_list<float>{}, c), IsOkAndHolds(ElementsAre(std::nullopt, 0.2f, 0.3f, 2.4f, 2.5f, std::nullopt, std::nullopt ))); } } }
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/dense_array/ops/multi_edge_util.h
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/dense_array/ops/multi_edge_util_test.cc
1ca990dbeca224035efdabffecc7f3738df6b52c
d941cff6-036d-42a7-bcf8-7c61b2975299
cpp
google/arolla
copier
arolla/dense_array/qtype/copier.h
arolla/dense_array/qtype/copier_test.cc
#ifndef AROLLA_DENSE_ARRAY_QTYPE_COPIER_H_ #define AROLLA_DENSE_ARRAY_QTYPE_COPIER_H_ #include <cstddef> #include <cstdint> #include <optional> #include <variant> #include <vector> #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/types/span.h" #include "arolla/dense_array/bitmap.h" #include "arolla/dense_array/dense_array.h" #include "arolla/memory/buffer.h" #include "arolla/memory/frame.h" #include "arolla/memory/optional_value.h" #include "arolla/memory/raw_buffer_factory.h" #include "arolla/qtype/array_like/array_like_qtype.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/util/status_macros_backport.h" namespace arolla { template <class T> class DenseArray2FramesCopier : public BatchToFramesCopier { public: absl::Status AddMapping(TypedRef array_ptr, TypedSlot scalar_slot) final { if (IsStarted()) { return absl::FailedPreconditionError( "can't add new mappings when started"); } ASSIGN_OR_RETURN(const DenseArray<T>& array, array_ptr.As<DenseArray<T>>()); RETURN_IF_ERROR(SetRowCount(array.size())); if (scalar_slot.GetType() == GetQType<T>()) { mappings_.push_back(Mapping{array, scalar_slot.UnsafeToSlot<T>()}); } else { ASSIGN_OR_RETURN(auto slot, scalar_slot.ToSlot<OptionalValue<T>>()); mappings_.push_back(Mapping{array, slot}); } return absl::OkStatus(); } void CopyNextBatch(absl::Span<FramePtr> output_buffers) final { if (!IsStarted()) Start(); for (const auto& mapping : mappings_) { auto iter = mapping.array.values.begin() + current_row_id_; if (std::holds_alternative<FrameLayout::Slot<T>>(mapping.scalar_slot)) { auto scalar_slot = *std::get_if<FrameLayout::Slot<T>>(&mapping.scalar_slot); for (size_t i = 0; i < output_buffers.size(); ++i) { output_buffers[i].Set(scalar_slot, T(iter[i])); } } else { DCHECK(std::holds_alternative<FrameLayout::Slot<OptionalValue<T>>>( mapping.scalar_slot)); auto scalar_slot = *std::get_if<FrameLayout::Slot<OptionalValue<T>>>( &mapping.scalar_slot); if (mapping.array.bitmap.empty()) { for (FramePtr frame : output_buffers) { frame.Set(scalar_slot, {true, T(*(iter++))}); } } else { bitmap::IterateByGroups( mapping.array.bitmap.begin(), current_row_id_ + mapping.array.bitmap_bit_offset, output_buffers.size(), [&](int64_t offset) { FramePtr* frame_group = output_buffers.begin() + offset; auto values = iter + offset; return [=](int i, bool present) { frame_group[i].Set(scalar_slot, {present, T(values[i])}); }; }); iter += output_buffers.size(); } } } current_row_id_ += output_buffers.size(); } private: struct Mapping { const DenseArray<T>& array; std::variant<FrameLayout::Slot<T>, FrameLayout::Slot<OptionalValue<T>>> scalar_slot; }; std::vector<Mapping> mappings_; int64_t current_row_id_ = 0; }; template <class T> class Frames2DenseArrayCopier : public BatchFromFramesCopier { public: explicit Frames2DenseArrayCopier( RawBufferFactory* buffer_factory = GetHeapBufferFactory()) : buffer_factory_(buffer_factory) {} absl::Status AddMapping(TypedSlot scalar_slot, TypedSlot array_slot) final { if (IsStarted()) { return absl::FailedPreconditionError( "can't add new mappings when started"); } ASSIGN_OR_RETURN(auto dst_slot, array_slot.ToSlot<DenseArray<T>>()); if (IsOptionalQType(scalar_slot.GetType())) { ASSIGN_OR_RETURN(auto src_slot, scalar_slot.ToSlot<OptionalValue<T>>()); mappings_.push_back(Mapping{src_slot, dst_slot}); } else { ASSIGN_OR_RETURN(auto src_slot, scalar_slot.ToSlot<T>()); mappings_.push_back(Mapping{src_slot, dst_slot}); } return absl::OkStatus(); } absl::Status CopyNextBatch( absl::Span<const ConstFramePtr> input_buffers) final { if (!IsStarted()) { return absl::FailedPreconditionError( "start(row_count) should be called before CopyNextBatch"); } for (Mapping& mapping : mappings_) { DCHECK(mapping.values_builder.has_value()); if (std::holds_alternative<FrameLayout::Slot<T>>(mapping.scalar_slot)) { auto scalar_slot = *std::get_if<FrameLayout::Slot<T>>(&mapping.scalar_slot); const ConstFramePtr* iter = input_buffers.data(); mapping.values_builder->SetN( current_row_id_, input_buffers.size(), [&] { return (iter++)->Get(scalar_slot); }); } else { DCHECK(std::holds_alternative<FrameLayout::Slot<OptionalValue<T>>>( mapping.scalar_slot)); DCHECK(mapping.bitmap_builder.has_value()); auto scalar_slot = *std::get_if<FrameLayout::Slot<OptionalValue<T>>>( &mapping.scalar_slot); auto values_inserter = mapping.values_builder->GetInserter(current_row_id_); auto fn = [&](ConstFramePtr frame) { const OptionalValue<T>& v = frame.Get(scalar_slot); values_inserter.Add(v.value); return v.present; }; mapping.bitmap_builder->AddForEach(input_buffers, fn); } } current_row_id_ += input_buffers.size(); return absl::OkStatus(); } absl::Status Finalize(FramePtr arrays_frame) final { if (finished_) { return absl::FailedPreconditionError("finalize can be called only once"); } finished_ = true; for (Mapping& mapping : mappings_) { DCHECK(mapping.values_builder.has_value()); DenseArray<T> res; res.values = (*std::move(mapping.values_builder)).Build(); if (mapping.bitmap_builder.has_value()) { res.bitmap = (*std::move(mapping.bitmap_builder)).Build(); } arrays_frame.Set(mapping.array_slot, std::move(res)); } return absl::OkStatus(); } private: struct Mapping { std::variant<FrameLayout::Slot<T>, FrameLayout::Slot<OptionalValue<T>>> scalar_slot; FrameLayout::Slot<DenseArray<T>> array_slot; std::optional<typename Buffer<T>::Builder> values_builder; std::optional<bitmap::Builder> bitmap_builder; }; void SetArraySize(int64_t size) final { for (auto& mapping : mappings_) { mapping.values_builder.emplace(size, buffer_factory_); if (mapping.scalar_slot.index() == 1) { mapping.bitmap_builder.emplace(size, buffer_factory_); } } } std::vector<Mapping> mappings_; int64_t current_row_id_ = 0; bool finished_ = false; RawBufferFactory* buffer_factory_; }; } #endif
#include "arolla/dense_array/qtype/copier.h" #include <cstdint> #include <memory> #include <optional> #include <utility> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "absl/status/status_matchers.h" #include "arolla/dense_array/dense_array.h" #include "arolla/dense_array/qtype/types.h" #include "arolla/memory/buffer.h" #include "arolla/memory/frame.h" #include "arolla/memory/memory_allocation.h" #include "arolla/memory/optional_value.h" #include "arolla/qtype/typed_ref.h" #include "arolla/qtype/typed_slot.h" namespace arolla::testing { namespace { using ::absl_testing::StatusIs; using ::testing::ElementsAre; using ::testing::HasSubstr; TEST(DenseArray2FramesCopier, ArraySizeValidation) { DenseArray<int64_t> arr1{CreateBuffer<int64_t>({3, 4})}; DenseArray<int64_t> arr2{CreateBuffer<int64_t>({3, 4, 5})}; FrameLayout::Builder bldr; auto slot1 = bldr.AddSlot<OptionalValue<int64_t>>(); auto slot2 = bldr.AddSlot<OptionalValue<int64_t>>(); auto layout = std::move(bldr).Build(); auto copier = std::make_unique<DenseArray2FramesCopier<int64_t>>(); EXPECT_OK(copier->AddMapping(TypedRef::FromValue(arr1), TypedSlot::FromSlot(slot1))); EXPECT_THAT( copier->AddMapping(TypedRef::FromValue(arr2), TypedSlot::FromSlot(slot2)), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("array size doesn't match: 2 vs 3"))); } TEST(DenseArray2FramesCopier, TryAddMappingWhenStarted) { DenseArray<int64_t> arr1{CreateBuffer<int64_t>({3, 4})}; DenseArray<int64_t> arr2{CreateBuffer<int64_t>({4, 5})}; FrameLayout::Builder bldr; auto slot1 = bldr.AddSlot<OptionalValue<int64_t>>(); auto slot2 = bldr.AddSlot<OptionalValue<int64_t>>(); auto layout = std::move(bldr).Build(); auto copier = std::make_unique<DenseArray2FramesCopier<int64_t>>(); EXPECT_OK(copier->AddMapping(TypedRef::FromValue(arr1), TypedSlot::FromSlot(slot1))); copier->Start(); EXPECT_THAT( copier->AddMapping(TypedRef::FromValue(arr2), TypedSlot::FromSlot(slot2)), StatusIs(absl::StatusCode::kFailedPrecondition, HasSubstr("can't add new mappings when started"))); } TEST(DenseArray2FramesCopier, TypesValidation) { DenseArray<float> arr1{CreateBuffer<float>({3.0, 4.0})}; DenseArray<int64_t> arr2{CreateBuffer<int64_t>({3, 4})}; FrameLayout::Builder bldr; auto slot1 = bldr.AddSlot<OptionalValue<int64_t>>(); auto slot2 = bldr.AddSlot<OptionalValue<float>>(); auto layout = std::move(bldr).Build(); auto copier = std::make_unique<DenseArray2FramesCopier<int64_t>>(); EXPECT_THAT( copier->AddMapping(TypedRef::FromValue(arr1), TypedSlot::FromSlot(slot1)), StatusIs(absl::StatusCode::kFailedPrecondition, HasSubstr("type mismatch"))); EXPECT_THAT( copier->AddMapping(TypedRef::FromValue(arr2), TypedSlot::FromSlot(slot2)), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("slot type does not match C++ type"))); } TEST(DenseArray2FramesCopier, Iterate) { FrameLayout::Builder scalars_bldr; auto scalar_f_slot1 = scalars_bldr.AddSlot<OptionalValue<float>>(); auto scalar_f_slot2 = scalars_bldr.AddSlot<float>(); auto scalar_layout = std::move(scalars_bldr).Build(); DenseArray<float> arr_f1 = CreateDenseArray<float>({1.5, {}, 2.5, 3.5}); DenseArray<float> arr_f2 = CreateDenseArray<float>({3.2, 2.2, {false, 7.2}, 1.2}); MemoryAllocation ctx0(&scalar_layout); MemoryAllocation ctx1(&scalar_layout); MemoryAllocation ctx2(&scalar_layout); MemoryAllocation ctx3(&scalar_layout); auto float_copier = std::make_unique<DenseArray2FramesCopier<float>>(); EXPECT_OK(float_copier->AddMapping(TypedRef::FromValue(arr_f1), TypedSlot::FromSlot(scalar_f_slot1))); EXPECT_OK(float_copier->AddMapping(TypedRef::FromValue(arr_f2), TypedSlot::FromSlot(scalar_f_slot2))); float_copier->Start(); FramePtr memory_ptrs1[2] = {ctx0.frame(), ctx1.frame()}; float_copier->CopyNextBatch({memory_ptrs1, 2}); EXPECT_EQ(ctx0.frame().Get(scalar_f_slot1), OptionalValue<float>(1.5)); EXPECT_FLOAT_EQ(ctx0.frame().Get(scalar_f_slot2), 3.2); EXPECT_EQ(ctx1.frame().Get(scalar_f_slot1), OptionalValue<float>()); EXPECT_FLOAT_EQ(ctx1.frame().Get(scalar_f_slot2), 2.2); FramePtr memory_ptrs2[2] = {ctx2.frame(), ctx3.frame()}; float_copier->CopyNextBatch({memory_ptrs2, 2}); EXPECT_EQ(ctx2.frame().Get(scalar_f_slot1), OptionalValue<float>(2.5)); EXPECT_FLOAT_EQ(ctx2.frame().Get(scalar_f_slot2), 7.2); EXPECT_EQ(ctx3.frame().Get(scalar_f_slot1), OptionalValue<float>(3.5)); EXPECT_FLOAT_EQ(ctx3.frame().Get(scalar_f_slot2), 1.2); } TEST(Frames2DenseArrayCopier, TryAddMappingWhenStarted) { FrameLayout::Builder arrays_bldr; auto array_slot1 = arrays_bldr.AddSlot<DenseArray<int64_t>>(); auto array_slot2 = arrays_bldr.AddSlot<DenseArray<int64_t>>(); auto arrays_layout = std::move(arrays_bldr).Build(); FrameLayout::Builder bldr; auto slot1 = bldr.AddSlot<OptionalValue<int64_t>>(); auto slot2 = bldr.AddSlot<OptionalValue<int64_t>>(); auto layout = std::move(bldr).Build(); auto copier = std::make_unique<Frames2DenseArrayCopier<int64_t>>(); EXPECT_OK(copier->AddMapping(TypedSlot::FromSlot(slot1), TypedSlot::FromSlot(array_slot1))); copier->Start(4); EXPECT_THAT(copier->AddMapping(TypedSlot::FromSlot(slot2), TypedSlot::FromSlot(array_slot2)), StatusIs(absl::StatusCode::kFailedPrecondition, HasSubstr("can't add new mappings when started"))); } TEST(Frames2DenseArrayCopier, TypesValidation) { FrameLayout::Builder arrays_bldr; auto array_slot1 = arrays_bldr.AddSlot<DenseArray<float>>(); auto array_slot2 = arrays_bldr.AddSlot<DenseArray<int64_t>>(); auto arrays_layout = std::move(arrays_bldr).Build(); FrameLayout::Builder bldr; auto slot1 = bldr.AddSlot<OptionalValue<int64_t>>(); auto slot2 = bldr.AddSlot<OptionalValue<float>>(); auto layout = std::move(bldr).Build(); auto copier = std::make_unique<Frames2DenseArrayCopier<int64_t>>(); EXPECT_THAT(copier->AddMapping(TypedSlot::FromSlot(slot1), TypedSlot::FromSlot(array_slot1)), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("slot type does not match C++ type"))); EXPECT_THAT(copier->AddMapping(TypedSlot::FromSlot(slot2), TypedSlot::FromSlot(array_slot2)), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("slot type does not match C++ type"))); } TEST(Frames2DenseArrayCopier, Iterate) { FrameLayout::Builder arrays_bldr; auto array_slot1 = arrays_bldr.AddSlot<DenseArray<float>>(); auto array_slot2 = arrays_bldr.AddSlot<DenseArray<float>>(); auto arrays_layout = std::move(arrays_bldr).Build(); FrameLayout::Builder scalars_bldr; auto scalar_f_slot1 = scalars_bldr.AddSlot<OptionalValue<float>>(); auto scalar_f_slot2 = scalars_bldr.AddSlot<float>(); auto scalar_layout = std::move(scalars_bldr).Build(); MemoryAllocation ctx0(&scalar_layout); MemoryAllocation ctx1(&scalar_layout); MemoryAllocation ctx2(&scalar_layout); MemoryAllocation ctx3(&scalar_layout); ctx0.frame().Set(scalar_f_slot1, 1.5); ctx0.frame().Set(scalar_f_slot2, 3.2); ctx1.frame().Set(scalar_f_slot1, {}); ctx1.frame().Set(scalar_f_slot2, 2.2); ctx2.frame().Set(scalar_f_slot1, 2.5); ctx2.frame().Set(scalar_f_slot2, 0.0); ctx3.frame().Set(scalar_f_slot1, 3.5); ctx3.frame().Set(scalar_f_slot2, 1.2); auto copier = std::make_unique<Frames2DenseArrayCopier<float>>(); EXPECT_OK(copier->AddMapping(TypedSlot::FromSlot(scalar_f_slot1), TypedSlot::FromSlot(array_slot1))); EXPECT_OK(copier->AddMapping(TypedSlot::FromSlot(scalar_f_slot2), TypedSlot::FromSlot(array_slot2))); ConstFramePtr memory_ptrs1[2] = {ctx0.frame(), ctx1.frame()}; ConstFramePtr memory_ptrs2[2] = {ctx2.frame(), ctx3.frame()}; MemoryAllocation arrays_ctx(&arrays_layout); copier->Start(4); EXPECT_OK(copier->CopyNextBatch({memory_ptrs1, 2})); EXPECT_OK(copier->CopyNextBatch({memory_ptrs2, 2})); EXPECT_OK(copier->Finalize(arrays_ctx.frame())); EXPECT_THAT(copier->Finalize(arrays_ctx.frame()), StatusIs(absl::StatusCode::kFailedPrecondition, HasSubstr("finalize can be called only once"))); EXPECT_THAT(arrays_ctx.frame().Get(array_slot1), ElementsAre(1.5, std::nullopt, 2.5, 3.5)); EXPECT_THAT(arrays_ctx.frame().Get(array_slot2), ElementsAre(3.2, 2.2, 0.0, 1.2)); } } }
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/dense_array/qtype/copier.h
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/dense_array/qtype/copier_test.cc
1ca990dbeca224035efdabffecc7f3738df6b52c
ee057e94-2419-4c05-bab9-9e53964dcd58
cpp
google/arolla
util
arolla/dense_array/ops/util.h
arolla/dense_array/ops/util_test.cc
#ifndef AROLLA_DENSE_ARRAY_OPS_UTIL_H_ #define AROLLA_DENSE_ARRAY_OPS_UTIL_H_ #include <algorithm> #include <cstddef> #include <cstdint> #include <optional> #include <tuple> #include <utility> #include "absl/base/attributes.h" #include "absl/log/check.h" #include "arolla/dense_array/bitmap.h" #include "arolla/memory/buffer.h" #include "arolla/memory/optional_value.h" #include "arolla/util/meta.h" #include "arolla/util/view_types.h" namespace arolla::dense_ops_internal { template <bool AllowBitmapOffset = true, class ArrayT> bitmap::Word GetMask(const ArrayT& array, int64_t word_id) { if constexpr (AllowBitmapOffset) { return bitmap::GetWordWithOffset(array.bitmap, word_id, array.bitmap_bit_offset); } else { DCHECK_EQ(array.bitmap_bit_offset, 0); return bitmap::GetWord(array.bitmap, word_id); } } template <class T, bool AllowBitmapOffset = true, class ArrayT> bitmap::Word GetOptionalMask(const ArrayT& array, int64_t word_id ABSL_ATTRIBUTE_UNUSED) { if constexpr (meta::is_wrapped_with<OptionalValue, T>::value) { return bitmap::kFullWord; } else { return GetMask<AllowBitmapOffset>(array, word_id); } } template <class T, class ArrayT, bool AllowBitmapOffset = true> struct Getter { Getter(const ArrayT& array, int64_t word_id) { iter = array.values.begin() + word_id * bitmap::kWordBitCount; } view_type_t<T> operator()(int i) const { return *(iter + i); } typename Buffer<T>::const_iterator iter; }; template <class T, class ArrayT, bool AllowBitmapOffset> struct Getter<OptionalValue<T>, ArrayT, AllowBitmapOffset> { Getter(const ArrayT& array, int64_t word_id) { mask = GetMask<AllowBitmapOffset>(array, word_id); iter = array.values.begin() + word_id * bitmap::kWordBitCount; } OptionalValue<view_type_t<T>> operator()(int i) const { return {bitmap::GetBit(mask, i), *(iter + i)}; } bitmap::Word mask; typename Buffer<T>::const_iterator iter; }; template <class ArgList, bool AllowBitmapOffset = true> struct DenseOpsUtil {}; template <class... Ts, bool AllowBitmapOffset> struct DenseOpsUtil<meta::type_list<Ts...>, AllowBitmapOffset> { template <class... As> static bitmap::Word IntersectMasks(int64_t word_id ABSL_ATTRIBUTE_UNUSED, const As&... arrays) { return (GetOptionalMask<Ts, AllowBitmapOffset>(arrays, word_id) & ... & bitmap::kFullWord); } template <class... As> static std::tuple<Getter<Ts, As, AllowBitmapOffset>...> CreateGetters( int64_t word_id ABSL_ATTRIBUTE_UNUSED, const As&... arrays) { return {Getter<Ts, As, AllowBitmapOffset>(arrays, word_id)...}; } template <class Fn, class... As> static void Iterate(Fn&& fn, int64_t from, int64_t to, const As&... args) { DCHECK_GE(from, 0); DCHECK_GE(to, from); return Iterate(fn, std::index_sequence_for<As...>{}, from, to, args...); } template <class Fn, class... As> static void IterateFromZero(Fn&& fn, int64_t to, const As&... args) { return IterateFromZero(fn, std::index_sequence_for<As...>{}, to, args...); } private: template <class Fn, class... As, size_t... Is> static void Iterate(Fn&& fn, std::index_sequence<Is...>, uint64_t from, uint64_t to, const As&... args) { auto group_fn = [&](int64_t word_id, int local_from, int local_to) { bitmap::Word mask = IntersectMasks(word_id, args...); auto getters ABSL_ATTRIBUTE_UNUSED = CreateGetters(word_id, args...); for (int i = local_from; i < local_to; ++i) { fn(word_id * bitmap::kWordBitCount + i, bitmap::GetBit(mask, i), std::get<Is>(getters)(i)...); } }; uint64_t word_id = from / bitmap::kWordBitCount; int local_from = from & (bitmap::kWordBitCount - 1); if (local_from > 0) { int local_to = std::min<int64_t>(to - from + local_from, bitmap::kWordBitCount); group_fn(word_id, local_from, local_to); word_id++; } for (; word_id < to / bitmap::kWordBitCount; ++word_id) { group_fn(word_id, 0, bitmap::kWordBitCount); } int local_to = to - word_id * bitmap::kWordBitCount; if (local_to > 0) { group_fn(word_id, 0, local_to); } } template <class Fn, class... As, size_t... Is> static void IterateFromZero(Fn&& fn, std::index_sequence<Is...>, uint64_t to, const As&... args) { for (uint64_t offset = 0; offset < to; offset += bitmap::kWordBitCount) { int group_size = std::min<int64_t>(bitmap::kWordBitCount, to - offset); int64_t word_id = offset / bitmap::kWordBitCount; bitmap::Word mask = IntersectMasks(word_id, args...); auto getters ABSL_ATTRIBUTE_UNUSED = CreateGetters(word_id, args...); for (int i = 0; i < group_size; ++i) { fn(word_id * bitmap::kWordBitCount + i, bitmap::GetBit(mask, i), std::get<Is>(getters)(i)...); } } } }; } #endif
#include "arolla/dense_array/ops/util.h" #include <cstdint> #include <cstring> #include <optional> #include <utility> #include "gtest/gtest.h" #include "absl/strings/str_format.h" #include "absl/strings/string_view.h" #include "arolla/dense_array/bitmap.h" #include "arolla/dense_array/dense_array.h" #include "arolla/memory/buffer.h" #include "arolla/memory/optional_value.h" #include "arolla/util/bits.h" #include "arolla/util/bytes.h" #include "arolla/util/meta.h" namespace arolla { namespace { TEST(DenseOpsUtil, Getter) { using Getter = dense_ops_internal::Getter<int, DenseArray<int>, false>; DenseArrayBuilder<int> bldr(200); for (int i = 0; i < 200; ++i) bldr.Set(i, i * i); auto array = std::move(bldr).Build(); auto g = Getter(array, 0); for (int i = 0; i < 32; ++i) { EXPECT_EQ(g(i), i * i); } g = Getter(array, 2); for (int i = 0; i < 32; ++i) { EXPECT_EQ(g(i), (i + 64) * (i + 64)); } } TEST(DenseOpsUtil, OptionalGetter) { { using Getter = dense_ops_internal::Getter<OptionalValue<int>, DenseArray<int>, false>; DenseArrayBuilder<int> bldr(200); for (int i = 0; i < 200; ++i) bldr.Set(i, i * i); auto array = std::move(bldr).Build(); auto g = Getter(array, 0); for (int i = 0; i < 32; ++i) { EXPECT_EQ(g(i), i * i); } g = Getter(array, 2); for (int i = 0; i < 32; ++i) { EXPECT_EQ(g(i), (i + 64) * (i + 64)); } } { using Getter = dense_ops_internal::Getter<OptionalValue<int>, DenseArray<int>, false>; DenseArrayBuilder<int> bldr(200); for (int i = 0; i < 200; ++i) { if (i % 3 == 0) bldr.Set(i, i * i); } auto array = std::move(bldr).Build(); auto g = Getter(array, 0); for (int i = 0; i < 32; ++i) { if (i % 3 == 0) { EXPECT_EQ(g(i), i * i); } else { EXPECT_EQ(g(i), std::nullopt); } } g = Getter(array, 2); for (int i = 0; i < 32; ++i) { if ((i + 64) % 3 == 0) { EXPECT_EQ(g(i), (i + 64) * (i + 64)); } else { EXPECT_EQ(g(i), std::nullopt); } } } { using Getter = dense_ops_internal::Getter<OptionalValue<int>, DenseArray<int>, true>; Buffer<int>::Builder values_bldr(200); Buffer<bitmap::Word>::Builder bitmap_bldr(bitmap::BitmapSize(200 + 2)); auto bitmap = bitmap_bldr.GetMutableSpan(); std::memset(bitmap.begin(), 0, bitmap.size() * sizeof(bitmap::Word)); for (int i = 0; i < 200; ++i) { values_bldr.Set(i, i * i); if (i % 3 == 0) SetBit(bitmap.begin(), i + 2); } DenseArray<int> array{std::move(values_bldr).Build(), std::move(bitmap_bldr).Build(), 2}; auto g = Getter(array, 0); for (int i = 0; i < 32; ++i) { if (i % 3 == 0) { EXPECT_EQ(g(i), i * i); } else { EXPECT_EQ(g(i), std::nullopt); } } g = Getter(array, 2); for (int i = 0; i < 32; ++i) { if ((i + 64) % 3 == 0) { EXPECT_EQ(g(i), (i + 64) * (i + 64)); } else { EXPECT_EQ(g(i), std::nullopt); } } } } TEST(DenseOpsUtil, OptionalGetterBoolUninitializedMemoryRead) { using Getter = dense_ops_internal::Getter<OptionalValue<bool>, DenseArray<bool>, false>; DenseArrayBuilder<bool> bldr(200); for (int i = 0; i < 200; ++i) { if (i % 3 == 0) bldr.Set(i, i % 2 == 0); } auto array = std::move(bldr).Build(); auto g = Getter(array, 0); for (int i = 0; i < 32; ++i) { if (i % 3 == 0) { EXPECT_EQ(g(i), i % 2 == 0); } else { EXPECT_EQ(g(i), std::nullopt); } } g = Getter(array, 2); for (int i = 0; i < 32; ++i) { if ((i + 64) % 3 == 0) { EXPECT_EQ(g(i), (i + 64) % 2 == 0); } else { EXPECT_EQ(g(i), std::nullopt); } } } constexpr int MAX_SIZE = 199; template <class Fn> void StressTestRanges(Fn&& fn) { for (int from = 0; from < 64; ++from) { for (int count = 0; count < MAX_SIZE - from; ++count) { fn(from, from + count); } } } TEST(DenseOpsUtil, IterateEmpty) { using Util = dense_ops_internal::DenseOpsUtil<meta::type_list<>>; int counter; auto count_fn = [&counter](int64_t, bool valid) { EXPECT_TRUE(valid); counter++; }; StressTestRanges([&](int from, int to) { counter = 0; Util::Iterate(count_fn, from, to); EXPECT_EQ(counter, to - from); }); } TEST(DenseOpsUtil, Iterate) { using Util = dense_ops_internal::DenseOpsUtil< meta::type_list<OptionalValue<int>, Bytes, float, OptionalValue<Bytes>>>; DenseArrayBuilder<int> bldr_a(MAX_SIZE); DenseArrayBuilder<Bytes> bldr_b(MAX_SIZE); DenseArrayBuilder<float> bldr_c(MAX_SIZE); DenseArrayBuilder<Bytes> bldr_d(MAX_SIZE); for (int i = 0; i < MAX_SIZE; ++i) { if (i % 5 < 2) bldr_a.Set(i, i + 123); if (i % 7 > 2) bldr_b.Set(i, absl::StrFormat("b %d", i)); if (i % 11 < 7) bldr_c.Set(i, i + 1.5f); if (i % 13 < 4) bldr_d.Set(i, absl::StrFormat("d %d", i)); } auto a = std::move(bldr_a).Build(); auto b = std::move(bldr_b).Build(); auto c = std::move(bldr_c).Build(); auto d = std::move(bldr_d).Build(); EXPECT_EQ(Util::IntersectMasks(0, a, b, c, d), 0x0F023878); EXPECT_EQ(Util::IntersectMasks(1, a, b, c, d), 0x3881E0C6); EXPECT_EQ(Util::IntersectMasks(2, a, b, c, d), 0x470F003C); EXPECT_EQ(Util::IntersectMasks(3, a, b, c, d), 0x3C18C1E0); int index; bool error = false; auto fn = [&](int64_t id, bool valid, OptionalValue<int> va, absl::string_view vb, float vc, OptionalValue<absl::string_view> vd) { if (error) return; EXPECT_EQ(index, id); EXPECT_EQ(valid, b.present(index) && c.present(index)); error = error || (valid != b.present(index) && c.present(index)); if (valid) { EXPECT_EQ(va, a[index]); EXPECT_EQ(vb, b.values[index]); EXPECT_EQ(vc, c.values[index]); EXPECT_EQ(vd, d[index]); error = error || (va != a[index]); error = error || (vb != b.values[index]); error = error || (vc != c.values[index]); error = error || (vd != d[index]); } index++; }; StressTestRanges([&](int from, int to) { index = from; Util::Iterate(fn, from, to, a, b, c, d); if (!error) { EXPECT_EQ(index, to); } if (from == 0) { index = from; Util::IterateFromZero(fn, to, a, b, c, d); if (!error) { EXPECT_EQ(index, to); } } }); } } }
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/dense_array/ops/util.h
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/dense_array/ops/util_test.cc
1ca990dbeca224035efdabffecc7f3738df6b52c
7101ad49-0209-4740-b2c9-7c1c1361a321
cpp
google/arolla
dense_group_ops
arolla/dense_array/ops/dense_group_ops.h
arolla/dense_array/ops/dense_group_ops_test.cc
#ifndef AROLLA_DENSE_ARRAY_OPS_DENSE_GROUP_OPS_H_ #define AROLLA_DENSE_ARRAY_OPS_DENSE_GROUP_OPS_H_ #include <cstddef> #include <cstdint> #include <type_traits> #include <utility> #include <vector> #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "arolla/dense_array/dense_array.h" #include "arolla/dense_array/edge.h" #include "arolla/dense_array/ops/util.h" #include "arolla/memory/optional_value.h" #include "arolla/memory/raw_buffer_factory.h" #include "arolla/util/meta.h" #include "arolla/util/view_types.h" #include "arolla/util/status_macros_backport.h" namespace arolla { namespace dense_ops_internal { template <class Accumulator, class ParentTypes, class ChildTypes, bool ForwardId = false> class DenseGroupOpsImpl; template <class Accumulator, class... ParentTs, class... ChildTs, bool ForwardId> class DenseGroupOpsImpl<Accumulator, meta::type_list<ParentTs...>, meta::type_list<ChildTs...>, ForwardId> { using ParentUtil = DenseOpsUtil<meta::type_list<ParentTs...>>; using ChildUtil = DenseOpsUtil<meta::type_list<ChildTs...>>; using ResT = strip_optional_t<typename Accumulator::result_type>; static constexpr bool kIsAggregator = Accumulator::IsAggregator(); static constexpr bool kIsPartial = Accumulator::IsPartial(); static constexpr bool kIsFull = Accumulator::IsFull(); public: explicit DenseGroupOpsImpl(RawBufferFactory* buffer_factory, Accumulator empty_accumulator = Accumulator()) : buffer_factory_(buffer_factory), empty_accumulator_(std::move(empty_accumulator)) {} absl::StatusOr<DenseArray<ResT>> Apply( const DenseArrayEdge& edge, const AsDenseArray<ParentTs>&... p_args, const AsDenseArray<ChildTs>&... c_args) const { if (((p_args.size() != edge.parent_size()) || ... || false)) { return SizeMismatchError({edge.parent_size(), p_args.size()...}); } if (((c_args.size() != edge.child_size()) || ... || false)) { return SizeMismatchError({edge.child_size(), c_args.size()...}); } switch (edge.edge_type()) { case DenseArrayEdge::SPLIT_POINTS: { const auto& split_points = edge.edge_values(); return ApplyWithSplitPoints(edge.parent_size(), edge.child_size(), split_points, p_args..., c_args...); } case DenseArrayEdge::MAPPING: { const auto& mapping = edge.edge_values(); return ApplyWithMapping(edge.parent_size(), edge.child_size(), mapping, p_args..., c_args...); } default: return absl::InvalidArgumentError("unsupported edge type"); } } absl::StatusOr<std::conditional_t< kIsAggregator, typename Accumulator::result_type, DenseArray<ResT>>> Apply(const DenseArrayGroupScalarEdge& edge, view_type_t<ParentTs>... p_args, const AsDenseArray<ChildTs>&... c_args) const { if (((c_args.size() != edge.child_size()) || ... || false)) { return SizeMismatchError({edge.child_size(), c_args.size()...}); } Accumulator accumulator = empty_accumulator_; accumulator.Reset(p_args...); if constexpr (kIsAggregator) { auto fn = [&](int64_t child_id, bool child_row_valid, view_type_t<ChildTs>... args) { if (child_row_valid) { Add(accumulator, child_id, args...); } }; ChildUtil::Iterate(fn, 0, edge.child_size(), c_args...); auto res = accumulator.GetResult(); RETURN_IF_ERROR(accumulator.GetStatus()); return typename Accumulator::result_type(std::move(res)); } else { DenseArrayBuilder<ResT> builder(edge.child_size(), buffer_factory_); std::vector<int64_t> processed_rows; auto fn = [&](int64_t child_id, bool child_row_valid, view_type_t<ChildTs>... args) { if (child_row_valid) { Add(accumulator, child_id, args...); if constexpr (kIsPartial) { builder.Set(child_id, accumulator.GetResult()); } else if constexpr (kIsFull) { processed_rows.push_back(child_id); } } }; ChildUtil::Iterate(fn, 0, edge.child_size(), c_args...); if constexpr (kIsFull) { accumulator.FinalizeFullGroup(); for (int64_t row_id : processed_rows) { builder.Set(row_id, accumulator.GetResult()); } } RETURN_IF_ERROR(accumulator.GetStatus()); return std::move(builder).Build(); } } private: absl::StatusOr<DenseArray<ResT>> ApplyWithMapping( int64_t parent_row_count, int64_t child_row_count, const DenseArray<int64_t>& mapping, const AsDenseArray<ParentTs>&... p_values, const AsDenseArray<ChildTs>&... c_values) const { DCHECK_EQ(child_row_count, mapping.size()); using MappingAndChildUtil = DenseOpsUtil<meta::type_list<int64_t, ChildTs...>>; std::vector<Accumulator> accumulators(parent_row_count, empty_accumulator_); std::vector<bool> valid_groups(parent_row_count, false); { auto fn = [&](int64_t group, bool valid, view_type_t<ParentTs>... args) { if (valid) accumulators[group].Reset(args...); valid_groups[group] = valid; }; ParentUtil::IterateFromZero(fn, parent_row_count, p_values...); } std::vector<bool> processed_child_rows; if constexpr (kIsFull) { processed_child_rows.resize(child_row_count, false); } const int64_t result_row_count = kIsAggregator ? parent_row_count : child_row_count; DenseArrayBuilder<ResT> builder(result_row_count, buffer_factory_); auto process_child_row_fn = [&](int64_t child_id, bool valid, int64_t parent_id, view_type_t<ChildTs>... args) { if (!valid || !valid_groups[parent_id]) return; auto& accumulator = accumulators[parent_id]; Add(accumulator, child_id, args...); if constexpr (kIsFull) { processed_child_rows[child_id] = true; } if constexpr (kIsPartial) { builder.Set(child_id, accumulator.GetResult()); } }; MappingAndChildUtil::Iterate(process_child_row_fn, 0, child_row_count, mapping, c_values...); if constexpr (kIsFull) { int64_t parent_id = 0; for (bool valid : valid_groups) { if (valid) accumulators[parent_id].FinalizeFullGroup(); parent_id++; } for (int64_t child_id = 0; child_id < processed_child_rows.size(); ++child_id) { if (processed_child_rows[child_id]) { int64_t parent_id = mapping.values[child_id]; DCHECK(valid_groups[parent_id]) << "Child rows from invalid groups shouldn't be processed"; builder.Set(child_id, accumulators[parent_id].GetResult()); } } } for (int64_t parent_id = 0; parent_id < parent_row_count; ++parent_id) { if (valid_groups[parent_id]) { if constexpr (kIsAggregator) { builder.Set(parent_id, accumulators[parent_id].GetResult()); } RETURN_IF_ERROR(accumulators[parent_id].GetStatus()); } } return std::move(builder).Build(); } template <size_t... GIs> absl::StatusOr<DenseArray<ResT>> ApplyWithSplitPoints( int64_t parent_row_count, int64_t child_row_count, const DenseArray<int64_t>& splits, const AsDenseArray<ParentTs>&... p_values, const AsDenseArray<ChildTs>&... c_values) const { if (splits.size() != parent_row_count + 1) { return absl::InvalidArgumentError( "splits row count is not compatible with parent row count"); } const int64_t result_row_count = kIsAggregator ? parent_row_count : child_row_count; DenseArrayBuilder<ResT> builder(result_row_count, buffer_factory_); std::vector<int64_t> processed_rows; Accumulator accumulator = empty_accumulator_; ParentUtil::IterateFromZero( [&](int64_t parent_id, bool parent_valid, view_type_t<ParentTs>... args) { if (parent_valid) { accumulator.Reset(args...); ProcessSingleGroupWithSplitPoints(parent_id, splits, c_values..., processed_rows, accumulator, builder); } }, parent_row_count, p_values...); RETURN_IF_ERROR(accumulator.GetStatus()); return std::move(builder).Build(); } void ProcessSingleGroupWithSplitPoints( int64_t parent_id, const DenseArray<int64_t>& splits, const AsDenseArray<ChildTs>&... c_values, std::vector<int64_t>& processed_rows, Accumulator& accumulator, DenseArrayBuilder<ResT>& builder) const { DCHECK(splits.present(parent_id)); DCHECK(splits.present(parent_id + 1)); int64_t child_from = splits.values[parent_id]; int64_t child_to = splits.values[parent_id + 1]; auto fn = [&](int64_t child_id, bool child_row_valid, view_type_t<ChildTs>... args) { if (child_row_valid) { Add(accumulator, child_id, args...); if constexpr (kIsPartial) { builder.Set(child_id, accumulator.GetResult()); } else if constexpr (kIsFull) { processed_rows.push_back(child_id); } } }; ChildUtil::Iterate(fn, child_from, child_to, c_values...); if constexpr (kIsAggregator) { builder.Set(parent_id, accumulator.GetResult()); } else if constexpr (kIsFull) { accumulator.FinalizeFullGroup(); for (int64_t row_id : processed_rows) { builder.Set(row_id, accumulator.GetResult()); } processed_rows.clear(); } } void Add(Accumulator& accumulator, int64_t child_id, view_type_t<ChildTs>... args) const { if constexpr (ForwardId) { accumulator.Add(child_id, args...); } else { (void)child_id; accumulator.Add(args...); } } RawBufferFactory* buffer_factory_; const Accumulator empty_accumulator_; }; } template <class Accumulator> using DenseGroupOps = dense_ops_internal::DenseGroupOpsImpl<Accumulator, typename Accumulator::parent_types, typename Accumulator::child_types>; template <class Accumulator> using DenseGroupOpsWithId = dense_ops_internal::DenseGroupOpsImpl< Accumulator, typename Accumulator::parent_types, meta::tail_t<typename Accumulator::child_types>, true>; } #endif
#include "arolla/dense_array/ops/dense_group_ops.h" #include <cstdint> #include <optional> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "absl/status/status_matchers.h" #include "absl/strings/string_view.h" #include "arolla/dense_array/dense_array.h" #include "arolla/dense_array/edge.h" #include "arolla/dense_array/testing/util.h" #include "arolla/memory/raw_buffer_factory.h" #include "arolla/qexpr/operators/testing/accumulators.h" #include "arolla/util/text.h" namespace arolla { namespace { using ::absl_testing::IsOkAndHolds; using ::absl_testing::StatusIs; using ::arolla::testing::CreateDenseArrayFromIdValues; using ::testing::ElementsAre; using ::testing::HasSubstr; using ::testing::Test; TEST(DenseGroupOps, FullArrayGroupSum) { auto values = CreateDenseArray<float>({5.0f, 8.0f, 3.0f, 6.0f}); auto detail_to_group = CreateDenseArray<int64_t>({1, 1, 2, 3}); auto splits = CreateDenseArray<int64_t>({0, 0, 2, 3, 4}); DenseGroupOps<testing::AggSumAccumulator<float>> agg(GetHeapBufferFactory()); ASSERT_OK_AND_ASSIGN( DenseArrayEdge edge1, DenseArrayEdge::FromMapping(detail_to_group, 4)); EXPECT_THAT(*agg.Apply(edge1, values), ElementsAre(std::nullopt, 13.0f, 3.0f, 6.0f)); ASSERT_OK_AND_ASSIGN(DenseArrayEdge edge2, DenseArrayEdge::FromSplitPoints(splits)); EXPECT_THAT(*agg.Apply(edge2, values), ElementsAre(std::nullopt, 13.0f, 3.0f, 6.0f)); } TEST(DenseGroupOps, ForwardId) { auto splits = CreateDenseArray<int64_t>({0, 0, 2, 3, 4}); ASSERT_OK_AND_ASSIGN(DenseArrayEdge edge, DenseArrayEdge::FromSplitPoints(splits)); std::vector<int64_t> ids; DenseGroupOpsWithId<testing::CollectIdsAccumulator> op( GetHeapBufferFactory(), testing::CollectIdsAccumulator(&ids)); EXPECT_OK(op.Apply(edge).status()); EXPECT_THAT(ids, ElementsAre(0, 1, 2, 3)); } TEST(DenseGroupOps, FullArrayAverageWithErrorStatus) { auto values = CreateDenseArray<float>({5.0f, 8.0f, 3.0f, 6.0f}); auto detail_to_group = CreateDenseArray<int64_t>({1, 1, 2, 3}); auto splits = CreateDenseArray<int64_t>({0, 0, 2, 3, 4}); DenseGroupOps<testing::AverageAccumulator> agg(GetHeapBufferFactory()); ASSERT_OK_AND_ASSIGN( DenseArrayEdge edge1, DenseArrayEdge::FromMapping(detail_to_group, 4)); EXPECT_THAT( agg.Apply(edge1, values), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("empty group"))); ASSERT_OK_AND_ASSIGN(DenseArrayEdge edge2, DenseArrayEdge::FromSplitPoints(splits)); EXPECT_THAT( agg.Apply(edge2, values), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("empty group"))); } TEST(DenseGroupOps, AverageToScalar) { DenseGroupOps<testing::AverageAccumulator> agg(GetHeapBufferFactory()); EXPECT_THAT(agg.Apply(DenseArrayGroupScalarEdge(3), CreateDenseArray<float>({1.0f, 3.0f, 8.0f})), IsOkAndHolds(4.0f)); EXPECT_THAT( agg.Apply(DenseArrayGroupScalarEdge(0), DenseArray<float>()), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("empty group"))); } TEST(DenseGroupOps, AggregationToScalar) { auto values = CreateDenseArray<float>({5.0f, 8.0f, 3.0f, 6.0f}); DenseGroupOps<testing::AggSumAccumulator<float>> agg(GetHeapBufferFactory()); DenseArrayGroupScalarEdge edge(values.size()); EXPECT_EQ(*agg.Apply(edge, values), 22.0f); } TEST(DenseGroupOps, RankValues) { auto values = CreateDenseArray<float>({3.0f, 5.0f, 2.0f, 1.0f, 3.1f, 7.0f}); auto detail_to_group = CreateDenseArray<int64_t>({0, 0, 0, 0, 1, 1}); auto splits = CreateDenseArray<int64_t>({0, 4, 6}); DenseGroupOps<testing::RankValuesAccumulator<float>> agg( GetHeapBufferFactory()); ASSERT_OK_AND_ASSIGN( DenseArrayEdge edge1, DenseArrayEdge::FromMapping(detail_to_group, 2)); EXPECT_THAT(*agg.Apply(edge1, values), ElementsAre(1, 0, 2, 3, 1, 0)); ASSERT_OK_AND_ASSIGN(DenseArrayEdge edge2, DenseArrayEdge::FromSplitPoints(splits)); EXPECT_THAT(*agg.Apply(edge2, values), ElementsAre(1, 0, 2, 3, 1, 0)); EXPECT_THAT(*agg.Apply(DenseArrayGroupScalarEdge(values.size()), values), ElementsAre(5, 1, 4, 0, 2, 3)); } TEST(DenseGroupOps, PartialSparseMapping) { auto a = CreateDenseArray<float>({2.0f, 1.0f, 1.0f}); auto b = CreateDenseArray<float>({2.0f, 2.0f, 1.0f}); auto c = CreateDenseArray<float>({0.0f, -1.0f, -1.0f}); auto x = CreateDenseArrayFromIdValues<float>( 100, {{5, 1.0}, {10, 1.0}, {15, 1.0}, {20, 1.0}, {25, 1.0}, {30, 1.0}}); auto y = CreateDenseArrayFromIdValues<float>( 100, {{5, 1.0}, {10, 2.0}, {15, 3.0}, {20, 1.0}, {25, 3.0}, {30, 2.0}}); auto z = CreateDenseArrayFromIdValues<float>( 100, {{5, 1.0}, {10, 2.0}, {15, 1.0}, {20, 2.0}, {25, 1.0}, {30, 2.0}}); auto detail_to_group = CreateDenseArrayFromIdValues<int64_t>( 100, {{0, 0}, {5, 1}, {10, 0}, {15, 1}, {20, 0}, {25, 1}}); DenseGroupOps<testing::WeightedSumAccumulator> agg(GetHeapBufferFactory()); auto expected = CreateDenseArrayFromIdValues<float>( 100, {{5, 2.f}, {10, 6.f}, {15, 6.f}, {20, 4.f}, {25, 6.f}}); ASSERT_OK_AND_ASSIGN(DenseArrayEdge edge, DenseArrayEdge::FromMapping(detail_to_group, 3)); ASSERT_OK_AND_ASSIGN(auto res, agg.Apply(edge, a, b, c, x, y, z)); EXPECT_EQ(res.size(), expected.size()); for (int i = 0; i < res.size(); ++i) { EXPECT_EQ(expected[i], res[i]); } } TEST(DenseGroupOps, PartialDenseMapping) { auto a = CreateDenseArray<float>({2.0f, 1.0f, 1.0f}); auto b = CreateDenseArray<float>({2.0f, 2.0f, std::nullopt}); auto c = CreateDenseArray<float>({0.0f, -1.0f, -1.0f}); auto x = CreateDenseArray<float>({1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f}); auto y = CreateDenseArray<float>({1.0f, 2.0f, 3.0f, 1.0f, 3.0f, 2.0f}); auto z = CreateDenseArray<float>({1.f, 2.f, 1.f, std::nullopt, 1.f, 2.f}); auto splits = CreateDenseArray<int64_t>({0, 2, 5, 6}); auto detail_to_group = CreateDenseArray<int64_t>({0, 0, 1, 1, 1, 2}); DenseGroupOps<testing::WeightedSumAccumulator> agg(GetHeapBufferFactory()); ASSERT_OK_AND_ASSIGN(DenseArrayEdge edge1, DenseArrayEdge::FromSplitPoints(splits)); EXPECT_THAT(*agg.Apply(edge1, a, b, c, x, y, z), ElementsAre(4.f, 6.f, 6.f, std::nullopt, 6.f, std::nullopt)); ASSERT_OK_AND_ASSIGN( DenseArrayEdge edge2, DenseArrayEdge::FromMapping(detail_to_group, 3)); EXPECT_THAT(*agg.Apply(edge2, a, b, c, x, y, z), ElementsAre(4.f, 6.f, 6.f, std::nullopt, 6.f, std::nullopt)); } TEST(DenseGroupOps, PartialGroupScalarEdge) { auto x = CreateDenseArray<float>({1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f}); auto y = CreateDenseArray<float>({1.0f, 2.0f, 3.0f, 1.0f, 3.0f, 2.0f}); auto z = CreateDenseArray<float>({1.f, 2.f, 1.f, std::nullopt, 1.f, 2.f}); DenseGroupOps<testing::WeightedSumAccumulator> agg(GetHeapBufferFactory()); EXPECT_THAT( *agg.Apply(DenseArrayGroupScalarEdge(6), 2.0f, 2.0f, 0.0f, x, y, z), ElementsAre(4.f, 6.f, 8.f, std::nullopt, 8.f, 6.f)); } TEST(DenseGroupOps, OptionalText) { auto detail_to_group = CreateDenseArray<int64_t>({1, 1, 2, 3, 3}); auto splits = CreateDenseArray<int64_t>({0, 0, 2, 3, 5}); auto prefixes = CreateDenseArray<Text>( {Text("empty"), Text("some:\n"), Text("prefix:\n"), std::nullopt}); auto values = CreateDenseArray<Text>( {Text("w1"), std::nullopt, Text("w3"), Text("w4"), Text("w5")}); auto comments = CreateDenseArray<Text>({std::nullopt, Text("it is word #2"), std::nullopt, Text("it is word #4"), std::nullopt}); DenseGroupOps<testing::AggTextAccumulator> agg(GetHeapBufferFactory()); ASSERT_OK_AND_ASSIGN( DenseArrayEdge edge1, DenseArrayEdge::FromMapping(detail_to_group, 4)); ASSERT_OK_AND_ASSIGN(DenseArray<Text> res1, agg.Apply(edge1, prefixes, values, comments)); ASSERT_OK_AND_ASSIGN(DenseArrayEdge edge2, DenseArrayEdge::FromSplitPoints(splits)); ASSERT_OK_AND_ASSIGN(DenseArray<Text> res2, agg.Apply(edge2, prefixes, values, comments)); using V = absl::string_view; EXPECT_THAT(res1, ElementsAre(V("empty"), V("some:\nw1\n"), V("prefix:\nw3\n"), V("w4 (it is word #4)\nw5\n"))); EXPECT_EQ(res1.size(), res2.size()); for (int64_t i = 0; i < res1.size(); ++i) { EXPECT_EQ(res1[i], res2[i]); } } } }
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/dense_array/ops/dense_group_ops.h
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/dense_array/ops/dense_group_ops_test.cc
1ca990dbeca224035efdabffecc7f3738df6b52c
39095eb1-c166-4ed7-a88c-6c222886e4c3
cpp
google/arolla
dense_ops
arolla/dense_array/ops/dense_ops.h
arolla/dense_array/ops/dense_ops_test.cc
#ifndef AROLLA_DENSE_ARRAY_OPS_DENSE_OPS_H_ #define AROLLA_DENSE_ARRAY_OPS_DENSE_OPS_H_ #include <cstddef> #include <cstdint> #include <cstring> #include <type_traits> #include <utility> #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/bitmap.h" #include "arolla/dense_array/dense_array.h" #include "arolla/dense_array/ops/universal_dense_op.h" #include "arolla/dense_array/ops/util.h" #include "arolla/memory/buffer.h" #include "arolla/memory/optional_value.h" #include "arolla/memory/raw_buffer_factory.h" #include "arolla/util/meta.h" #include "arolla/util/unit.h" #include "arolla/util/view_types.h" namespace arolla { struct DenseOpFlags { static constexpr int kRunOnMissing = 1 << 0; static constexpr int kNoBitmapOffset = 1 << 1; static constexpr int kNoSizeValidation = 1 << 2; }; namespace dense_ops_internal { template <class Fn> struct SpanOp { Fn fn; template <class Res, class... Ts> void operator()(absl::Span<Res> res, absl::Span<const Ts>... args) const { for (size_t i = 0; i < res.size(); ++i) { res[i] = fn(args[i]...); } } }; template <class ResT, class SpanOpT> class UnaryOpImpl { public: explicit UnaryOpImpl( SpanOpT op, RawBufferFactory* buffer_factory = GetHeapBufferFactory()) : op_(op), buffer_factory_(buffer_factory) {} template <class ArgT> DenseArray<ResT> operator()(const DenseArray<ArgT>& arg) const { typename Buffer<ResT>::Builder builder(arg.size(), buffer_factory_); op_(builder.GetMutableSpan(), arg.values.span()); return {std::move(builder).Build(), arg.bitmap, arg.bitmap_bit_offset}; } private: SpanOpT op_; RawBufferFactory* buffer_factory_; }; template <class ResT, bool NoBitmapOffset, class SpanOpT> class BinaryOpImpl { public: explicit BinaryOpImpl( SpanOpT op, RawBufferFactory* buffer_factory = GetHeapBufferFactory()) : op_(op), buffer_factory_(buffer_factory) {} template <class Arg1T, class Arg2T> DenseArray<ResT> operator()(const DenseArray<Arg1T>& arg1, const DenseArray<Arg2T>& arg2) const { DCHECK_EQ(arg1.size(), arg2.size()); DCHECK(!NoBitmapOffset || (arg1.bitmap_bit_offset == 0 && arg2.bitmap_bit_offset == 0)); typename Buffer<ResT>::Builder builder(arg1.size(), buffer_factory_); op_(builder.GetMutableSpan(), arg1.values.span(), arg2.values.span()); if (arg2.bitmap.empty()) { return {std::move(builder).Build(), arg1.bitmap, arg1.bitmap_bit_offset}; } else if (arg1.bitmap.empty()) { return {std::move(builder).Build(), arg2.bitmap, arg2.bitmap_bit_offset}; } else { bitmap::RawBuilder bitmap_builder( std::min(arg1.bitmap.size(), arg2.bitmap.size()), buffer_factory_); int res_bit_offset = 0; if constexpr (NoBitmapOffset) { bitmap::Intersect(arg1.bitmap, arg2.bitmap, bitmap_builder.GetMutableSpan()); } else { res_bit_offset = std::min(arg1.bitmap_bit_offset, arg2.bitmap_bit_offset); bitmap::Intersect(arg1.bitmap, arg2.bitmap, arg1.bitmap_bit_offset, arg2.bitmap_bit_offset, bitmap_builder.GetMutableSpan()); } return {std::move(builder).Build(), std::move(bitmap_builder).Build(), res_bit_offset}; } } private: SpanOpT op_; RawBufferFactory* buffer_factory_; }; template <class ResT, class SpanOpT> class SimpleOpImpl { public: explicit SimpleOpImpl( SpanOpT op, RawBufferFactory* buffer_factory = GetHeapBufferFactory()) : op_(op), buffer_factory_(buffer_factory) {} template <class Arg1T, class... ArgsT> DenseArray<ResT> operator()(const DenseArray<Arg1T>& arg1, const DenseArray<ArgsT>&... args) const { DCHECK(((arg1.size() == args.size()) && ... && true)); DCHECK(arg1.bitmap_bit_offset == 0 && ((args.bitmap_bit_offset == 0) && ... && true)); typename Buffer<ResT>::Builder builder(arg1.size(), buffer_factory_); op_(builder.GetMutableSpan(), arg1.values.span(), args.values.span()...); if ((args.bitmap.empty() && ... && true)) { return {std::move(builder).Build(), arg1.bitmap}; } else { size_t bitmap_size = bitmap::BitmapSize(arg1.size()); bitmap::RawBuilder bitmap_builder(bitmap_size, buffer_factory_); bitmap::Word* bitmap = bitmap_builder.GetMutableSpan().begin(); bool initialized = false; auto intersect_fn = [&](const bitmap::Bitmap& b) { if (b.empty()) return; const bitmap::Word* ptr = b.begin(); if (initialized) { for (int64_t i = 0; i < bitmap_size; ++i) { bitmap[i] &= ptr[i]; } } else { std::memcpy(bitmap, ptr, bitmap_size * sizeof(bitmap::Word)); initialized = true; } }; intersect_fn(arg1.bitmap); (intersect_fn(args.bitmap), ...); return {std::move(builder).Build(), std::move(bitmap_builder).Build()}; } } private: SpanOpT op_; RawBufferFactory* buffer_factory_; }; template <class ResT, class Op> class OpWithSizeValidation { public: explicit OpWithSizeValidation(Op op) : op_(std::move(op)) {} template <class... Args> absl::StatusOr<DenseArray<ResT>> operator()(const Args&... args) const { if (!AreSizesEqual(args...)) { return SizeMismatchError({args.size()...}); } return op_(args...); } private: template <class A, class... As> static bool AreSizesEqual(const A& a, const As&... as) { return ((a.size() == as.size()) && ...); } Op op_; }; template <class TypeList> struct ArgsAnalyzer {}; template <class... Ts> struct ArgsAnalyzer<meta::type_list<Ts...>> { static constexpr bool kHasOptionalArg = (meta::is_wrapped_with<OptionalValue, Ts>::value || ...); static constexpr bool kHasStringArg = (std::is_same_v<view_type_t<Ts>, absl::string_view> || ...); static constexpr bool kHasUnitArg = (std::is_same_v<view_type_t<Ts>, Unit> || ...); }; template <class Fn, int flags> struct ImplChooser { static constexpr bool kRunOnMissing = flags & DenseOpFlags::kRunOnMissing; static constexpr bool kNoBitmapOffset = flags & DenseOpFlags::kNoBitmapOffset; static constexpr bool kNoSizeValidation = flags & DenseOpFlags::kNoSizeValidation; static constexpr int kArgCount = meta::function_traits<Fn>::arity; using args = ArgsAnalyzer<typename meta::function_traits<Fn>::arg_types>; using fn_return_t = typename meta::function_traits<Fn>::return_type; static constexpr bool kComplicatedFn = meta::is_wrapped_with<absl::StatusOr, fn_return_t>::value || meta::is_wrapped_with<OptionalValue, fn_return_t>::value || std::is_same_v<view_type_t<fn_return_t>, absl::string_view> || args::kHasOptionalArg || args::kHasStringArg || args::kHasUnitArg || !(flags & DenseOpFlags::kRunOnMissing); static constexpr bool kWithSizeValidationOp = !kNoSizeValidation && kArgCount > 1; static constexpr bool kCanUseUnaryOp = kArgCount == 1 && !kComplicatedFn; static constexpr bool kCanUseBinaryOp = kArgCount == 2 && !kComplicatedFn && !kWithSizeValidationOp; static constexpr bool kCanUseSimpleOp = kArgCount > 2 && !kComplicatedFn && kNoBitmapOffset && !kWithSizeValidationOp; }; template <class Fn, class ResT, int flags, class = void> struct ImplSwitcher { using Chooser = ImplChooser<Fn, flags>; using Impl = UniversalDenseOp<Fn, ResT, !Chooser::kRunOnMissing, Chooser::kNoBitmapOffset>; static Impl Create(Fn fn, RawBufferFactory* buffer_factory) { return Impl(fn, buffer_factory); } }; template <class Fn, class ResT, int flags> struct ImplSwitcher< Fn, ResT, flags, std::enable_if_t<ImplChooser<Fn, flags>::kCanUseUnaryOp, void>> { using Impl = UnaryOpImpl<ResT, SpanOp<Fn>>; static Impl Create(Fn fn, RawBufferFactory* buffer_factory) { return Impl({fn}, buffer_factory); } }; template <class Fn, class ResT, int flags> struct ImplSwitcher< Fn, ResT, flags, std::enable_if_t<ImplChooser<Fn, flags>::kCanUseBinaryOp, void>> { using Chooser = ImplChooser<Fn, flags>; using Impl = BinaryOpImpl<ResT, Chooser::kNoBitmapOffset, SpanOp<Fn>>; static Impl Create(Fn fn, RawBufferFactory* buffer_factory) { return Impl({fn}, buffer_factory); } }; template <class Fn, class ResT, int flags> struct ImplSwitcher< Fn, ResT, flags, std::enable_if_t<ImplChooser<Fn, flags>::kCanUseSimpleOp, void>> { using Chooser = ImplChooser<Fn, flags>; using Impl = SimpleOpImpl<ResT, SpanOp<Fn>>; static Impl Create(Fn fn, RawBufferFactory* buffer_factory) { return Impl({fn}, buffer_factory); } }; template <class Fn, class ResT, int flags> struct ImplSwitcher< Fn, ResT, flags, std::enable_if_t<ImplChooser<Fn, flags>::kWithSizeValidationOp, void>> { using BaseSwitcher = ImplSwitcher<Fn, ResT, flags | DenseOpFlags::kNoSizeValidation>; using Impl = OpWithSizeValidation<ResT, typename BaseSwitcher::Impl>; template <class... Args> static Impl Create(Args&&... args) { return Impl(BaseSwitcher::Create(args...)); } }; template <class Fn> using result_base_t = strip_optional_t<meta::strip_template_t< absl::StatusOr, typename meta::function_traits<Fn>::return_type>>; } template <class Fn, class ResT = dense_ops_internal::result_base_t<Fn>, int flags = 0> using DenseOp = typename dense_ops_internal::ImplSwitcher<Fn, ResT, flags>::Impl; template <class Fn, class ResT = dense_ops_internal::result_base_t<Fn>> DenseOp<Fn, ResT> CreateDenseOp( Fn fn, RawBufferFactory* buf_factory = GetHeapBufferFactory()) { return dense_ops_internal::ImplSwitcher<Fn, ResT, 0>::Create(fn, buf_factory); } template <int flags, class Fn, class ResT = dense_ops_internal::result_base_t<Fn>> DenseOp<Fn, ResT, flags> CreateDenseOp( Fn fn, RawBufferFactory* buf_factory = GetHeapBufferFactory()) { return dense_ops_internal::ImplSwitcher<Fn, ResT, flags>::Create(fn, buf_factory); } template <class ResT, class SpanOpT> auto CreateDenseUnaryOpFromSpanOp( SpanOpT op, RawBufferFactory* buf_factory = GetHeapBufferFactory()) { return dense_ops_internal::UnaryOpImpl<ResT, SpanOpT>(op, buf_factory); } template <class ResT, class SpanOpT> auto CreateDenseBinaryOpFromSpanOp( SpanOpT op, RawBufferFactory* buf_factory = GetHeapBufferFactory()) { using ImplBase = dense_ops_internal::BinaryOpImpl<ResT, false, SpanOpT>; using Impl = dense_ops_internal::OpWithSizeValidation<ResT, ImplBase>; return Impl(ImplBase(op, buf_factory)); } template <class ResT, int flags, class SpanOpT> auto CreateDenseBinaryOpFromSpanOp( SpanOpT op, RawBufferFactory* buf_factory = GetHeapBufferFactory()) { static constexpr bool kNoBitmapOffset = flags & DenseOpFlags::kNoBitmapOffset; static constexpr bool kNoSizeValidation = flags & DenseOpFlags::kNoSizeValidation; using ImplBase = dense_ops_internal::BinaryOpImpl<ResT, kNoBitmapOffset, SpanOpT>; if constexpr (kNoSizeValidation) { return ImplBase(op, buf_factory); } else { using Impl = dense_ops_internal::OpWithSizeValidation<ResT, ImplBase>; return Impl(ImplBase(op, buf_factory)); } } template <class Fn, class T, class... As> absl::Status DenseArraysForEach(Fn&& fn, const DenseArray<T>& arg0, const As&... args) { if (!((arg0.size() == args.size()) && ...)) { return SizeMismatchError({arg0.size(), args.size()...}); } using fn_arg_types = typename meta::function_traits<std::decay_t<Fn>>::arg_types; using value_types = meta::tail_t<meta::tail_t<fn_arg_types>>; dense_ops_internal::DenseOpsUtil<value_types>::IterateFromZero( fn, arg0.size(), arg0, args...); return absl::OkStatus(); } template <class Fn, class T, class... As> absl::Status DenseArraysForEachPresent(Fn&& fn, const DenseArray<T>& arg0, const As&... args) { if (!((arg0.size() == args.size()) && ...)) { return SizeMismatchError({arg0.size(), args.size()...}); } using fn_arg_types = typename meta::function_traits<std::decay_t<Fn>>::arg_types; using value_types = meta::tail_t<fn_arg_types>; dense_ops_internal::DenseOpsUtil<value_types>::IterateFromZero( [&fn](int64_t id, bool valid, auto&&... vals) { if (valid) { fn(id, std::forward<decltype(vals)>(vals)...); } }, arg0.size(), arg0, args...); return absl::OkStatus(); } } #endif
#include "arolla/dense_array/ops/dense_ops.h" #include <cstdint> #include <optional> #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/status_matchers.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "arolla/dense_array/bitmap.h" #include "arolla/dense_array/dense_array.h" #include "arolla/memory/buffer.h" #include "arolla/memory/optional_value.h" #include "arolla/memory/raw_buffer_factory.h" #include "arolla/qexpr/operators/math/batch_arithmetic.h" #include "arolla/util/bytes.h" #include "arolla/util/text.h" namespace arolla::testing { using ::absl_testing::IsOkAndHolds; using ::absl_testing::StatusIs; using ::arolla::dense_ops_internal::BinaryOpImpl; using ::arolla::dense_ops_internal::OpWithSizeValidation; using ::arolla::dense_ops_internal::SimpleOpImpl; using ::arolla::dense_ops_internal::SpanOp; using ::arolla::dense_ops_internal::UnaryOpImpl; using ::arolla::dense_ops_internal::UniversalDenseOp; using ::testing::ElementsAre; using ::testing::ElementsAreArray; struct BoolOrFn { bool operator()(bool a, bool b) const { return a || b; } }; struct AddFn { int operator()(int a, int b) const { return a + b; } }; struct UnionAddFn { OptionalValue<int> operator()(OptionalValue<int> a, OptionalValue<int> b) const { return {a.present || b.present, (a.present ? a.value : 0) + (b.present ? b.value : 0)}; } }; TEST(UnaryDenseOp, PlusOne) { DenseArray<int64_t> arr = CreateDenseArray<int64_t>({1, {}, 2, 3}); auto fn = [](int64_t a) -> int { return a + 1; }; UnaryOpImpl<int, SpanOp<decltype(fn)>> op = CreateDenseOp<DenseOpFlags::kRunOnMissing>(fn); DenseArray<int> res = op(arr); EXPECT_EQ(res.bitmap.span().data(), arr.bitmap.span().data()); EXPECT_THAT(op(arr), ElementsAre(2, std::nullopt, 3, 4)); } TEST(BinaryDenseOp, AddFullDense) { DenseArray<int> arr1{CreateBuffer<int>({1, 4, 2, 3})}; DenseArray<int> arr2 = CreateDenseArray<int>({3, 6, {}, 2}); BinaryOpImpl<int, false, SpanOp<AddFn>> op = CreateDenseOp<DenseOpFlags::kNoSizeValidation | DenseOpFlags::kRunOnMissing>(AddFn()); { DenseArray<int> res = op(arr1, arr2); EXPECT_EQ(res.bitmap.span().data(), arr2.bitmap.span().data()); EXPECT_THAT(res, ElementsAre(4, 10, std::nullopt, 5)); } { DenseArray<int> res = op(arr2, arr1); EXPECT_EQ(res.bitmap.span().data(), arr2.bitmap.span().data()); EXPECT_THAT(res, ElementsAre(4, 10, std::nullopt, 5)); } } TEST(BinaryDenseOp, AddDenseDense) { DenseArray<int> arr1 = CreateDenseArray<int>({1, {}, 2, 3}); DenseArray<int> arr2 = CreateDenseArray<int>({3, 6, {}, 2}); BinaryOpImpl<int, false, SpanOp<AddFn>> op = CreateDenseOp<DenseOpFlags::kNoSizeValidation | DenseOpFlags::kRunOnMissing>(AddFn()); EXPECT_THAT(op(arr1, arr2), ElementsAre(4, std::nullopt, std::nullopt, 5)); } TEST(BinaryDenseOp, BoolOrDenseDenseOnUninitializedMemory) { UnsafeArenaBufferFactory factory(1024); Buffer<bool>::Builder builder1(bitmap::kWordBitCount * 3, &factory); builder1.GetMutableSpan()[0] = true; DenseArray<bool> arr1{std::move(builder1).Build(), bitmap::Bitmap::Create({1, 0, 0})}; Buffer<bool>::Builder builder2(bitmap::kWordBitCount * 3, &factory); builder2.GetMutableSpan()[1] = true; DenseArray<bool> arr2{std::move(builder2).Build(), bitmap::Bitmap::Create({2, 0, 0})}; BinaryOpImpl<bool, false, SpanOp<BoolOrFn>> op = CreateDenseOp<DenseOpFlags::kNoSizeValidation | DenseOpFlags::kRunOnMissing>(BoolOrFn()); EXPECT_THAT(op(arr1, arr2), ElementsAreArray(std::vector<OptionalValue<bool>>( bitmap::kWordBitCount * 3, std::nullopt))); } TEST(BinaryDenseOp, EigenAdd) { DenseArray<int> arr1 = CreateDenseArray<int>({1, {}, 2, 3}); DenseArray<int> arr2 = CreateDenseArray<int>({3, 6, {}, 2}); auto op = CreateDenseBinaryOpFromSpanOp<int>(BatchAdd<int>()); EXPECT_THAT(op(arr1, arr2), IsOkAndHolds(ElementsAre(4, std::nullopt, std::nullopt, 5))); EXPECT_THAT( op(arr1, CreateDenseArray<int>({3})), StatusIs(absl::StatusCode::kInvalidArgument, ::testing::HasSubstr("argument sizes mismatch: (4, 1)"))); } TEST(BinaryDenseOp, FromSpanOpWithoutSizeValidation) { DenseArray<int> arr1 = CreateDenseArray<int>({1, {}, 2, 3}); DenseArray<int> arr2 = CreateDenseArray<int>({3, 6, {}, 2}); auto op = CreateDenseBinaryOpFromSpanOp<int, DenseOpFlags::kNoSizeValidation>( BatchAdd<int>()); EXPECT_THAT(op(arr1, arr2), ElementsAre(4, std::nullopt, std::nullopt, 5)); } TEST(BinaryDenseOp, BitOffset) { DenseArray<int> arr1 = CreateDenseArray<int>({1, {false, 2}, 3, 4}); DenseArray<int> arr2 = CreateDenseArray<int>({5, 5, {false, 5}, 5}); { BinaryOpImpl<int, true, SpanOp<AddFn>> op = CreateDenseOp<DenseOpFlags::kNoBitmapOffset | DenseOpFlags::kNoSizeValidation | DenseOpFlags::kRunOnMissing>(AddFn()); auto res = op(arr1, arr2); EXPECT_EQ(res.bitmap_bit_offset, arr1.bitmap_bit_offset); EXPECT_THAT(res, ElementsAre(6, std::nullopt, std::nullopt, 9)); } arr1.bitmap_bit_offset = 1; EXPECT_THAT(arr1, ElementsAre(std::nullopt, 2, 3, std::nullopt)); { BinaryOpImpl<int, false, SpanOp<AddFn>> op = CreateDenseOp<DenseOpFlags::kNoSizeValidation | DenseOpFlags::kRunOnMissing>(AddFn()); auto res = op(arr1, arr2); EXPECT_THAT(res, ElementsAre(std::nullopt, 7, std::nullopt, std::nullopt)); } } TEST(BinaryDenseOp, DifferentTypes) { DenseArray<int> arr1 = CreateDenseArray<int>({1, {}, 2, 3}); DenseArray<float> arr2 = CreateDenseArray<float>({3.f, 6.f, {}, 2.f}); auto fn = [](int a, float b) { return a > b; }; BinaryOpImpl<bool, false, SpanOp<decltype(fn)>> op = CreateDenseOp<DenseOpFlags::kNoSizeValidation | DenseOpFlags::kRunOnMissing>(fn); EXPECT_THAT(op(arr1, arr2), ElementsAre(false, std::nullopt, std::nullopt, true)); } TEST(BinaryDenseOp, SizeValidation) { auto fn = [](int a, float b) { return a > b; }; using ImplBase = BinaryOpImpl<bool, false, SpanOp<decltype(fn)>>; using Impl = OpWithSizeValidation<bool, ImplBase>; Impl op = CreateDenseOp<DenseOpFlags::kRunOnMissing>(fn); { DenseArray<int> arr1 = CreateDenseArray<int>({1, {}, 2, 3}); DenseArray<float> arr2 = CreateDenseArray<float>({3.f, 6.f, {}, 2.f}); EXPECT_THAT(op(arr1, arr2), IsOkAndHolds(ElementsAre(false, std::nullopt, std::nullopt, true))); } { DenseArray<int> arr1 = CreateDenseArray<int>({1, {}, 2, 3}); DenseArray<float> arr2 = CreateDenseArray<float>({3.f, 6.f, {}}); EXPECT_THAT( op(arr1, arr2), StatusIs(absl::StatusCode::kInvalidArgument, ::testing::HasSubstr("argument sizes mismatch: (4, 3)"))); } } TEST(SimpleDenseOp, Add3) { auto add3 = [](int a, int b, int c) { return a + b + c; }; DenseArray<int> arr1 = CreateDenseArray<int>({1, {}, 2, 3}); DenseArray<int> arr2 = CreateDenseArray<int>({3, 6, {}, 2}); DenseArray<int> arr3 = CreateDenseArray<int>({4, 3, 2, 1}); SimpleOpImpl<int, SpanOp<decltype(add3)>> op = CreateDenseOp<DenseOpFlags::kNoBitmapOffset | DenseOpFlags::kNoSizeValidation | DenseOpFlags::kRunOnMissing>(add3); EXPECT_THAT(op(arr1, arr2, arr3), ElementsAre(8, std::nullopt, std::nullopt, 6)); EXPECT_THAT(op(arr1, arr3, arr2), ElementsAre(8, std::nullopt, std::nullopt, 6)); EXPECT_THAT(op(arr3, arr1, arr2), ElementsAre(8, std::nullopt, std::nullopt, 6)); EXPECT_THAT(op(arr3, arr3, arr3), ElementsAre(12, 9, 6, 3)); } TEST(SimpleDenseOp, SizeValidation) { auto add3 = [](int a, int b, int c) { return a + b + c; }; DenseArray<int> arr1 = CreateDenseArray<int>({1, {}, 2, 3}); DenseArray<int> arr2 = CreateDenseArray<int>({3, 6, {}, 2}); DenseArray<int> arr3 = CreateDenseArray<int>({4, 3, 2, 1}); using BaseImpl = SimpleOpImpl<int, SpanOp<decltype(add3)>>; using Op = OpWithSizeValidation<int, BaseImpl>; Op op = CreateDenseOp<DenseOpFlags::kNoBitmapOffset | DenseOpFlags::kRunOnMissing>(add3); EXPECT_THAT(op(arr1, arr2, arr3), IsOkAndHolds(ElementsAre(8, std::nullopt, std::nullopt, 6))); EXPECT_THAT( op(arr1, CreateDenseArray<int>({1, {}}), arr3), StatusIs(absl::StatusCode::kInvalidArgument, ::testing::HasSubstr("argument sizes mismatch: (4, 2, 4)"))); } TEST(UniversalDenseOp, Add) { DenseArray<int> arr1 = CreateDenseArray<int>({1, {}, 2, 3}); DenseArray<int> arr2 = CreateDenseArray<int>({3, 6, {}, 2}); auto res = UniversalDenseOp<AddFn, int, false, false>(AddFn())(arr1, arr2); EXPECT_THAT(res, ElementsAre(4, std::nullopt, std::nullopt, 5)); } TEST(UniversalDenseOp, SkipMissed) { DenseArray<int> arr1 = CreateDenseArray<int>({1, {}, 2, 3}); DenseArray<int> arr2 = CreateDenseArray<int>({3, 6, {}, 2}); UniversalDenseOp<AddFn, int, true, false> op = CreateDenseOp<DenseOpFlags::kNoSizeValidation>(AddFn()); EXPECT_THAT(op(arr1, arr2), ElementsAre(4, std::nullopt, std::nullopt, 5)); } TEST(UniversalDenseOp, UnionAdd) { DenseArray<int> arr1 = CreateDenseArray<int>({1, {}, {}, 3}); DenseArray<int> arr2 = CreateDenseArray<int>({3, 6, {}, {}}); UniversalDenseOp<UnionAddFn, int, false, false> op = CreateDenseOp<DenseOpFlags::kNoSizeValidation | DenseOpFlags::kRunOnMissing>(UnionAddFn()); EXPECT_THAT(op(arr1, arr2), ElementsAre(4, 6, std::nullopt, 3)); auto op_with_size_validation = CreateDenseOp(UnionAddFn()); EXPECT_THAT(op_with_size_validation(arr1, arr2), IsOkAndHolds(ElementsAre(4, 6, std::nullopt, 3))); EXPECT_THAT( op_with_size_validation(CreateDenseArray<int>({3, 6}), arr2), StatusIs(absl::StatusCode::kInvalidArgument, ::testing::HasSubstr("argument sizes mismatch: (2, 4)"))); } TEST(UniversalDenseOp, BitOffset) { DenseArray<int> arr1 = CreateDenseArray<int>({1, {false, 2}, 3, 4}); DenseArray<int> arr2 = CreateDenseArray<int>({{}, 5, 5, 5}); { auto res = UniversalDenseOp<AddFn, int, false, true>(AddFn())(arr1, arr2); EXPECT_THAT(res, ElementsAre(std::nullopt, std::nullopt, 8, 9)); } arr1.bitmap_bit_offset = 1; EXPECT_THAT(arr1, ElementsAre(std::nullopt, 2, 3, std::nullopt)); { auto res = UniversalDenseOp<AddFn, int, false, false>(AddFn())(arr1, arr2); EXPECT_THAT(res, ElementsAre(std::nullopt, 7, 8, std::nullopt)); } } TEST(UniversalDenseOp, DifferentSizesAndOffsets) { for (int64_t item_count = 0; item_count < 1024; ++item_count) { int bit_offset1 = item_count % bitmap::kWordBitCount; int bit_offset2 = (4096 - item_count * 3) % bitmap::kWordBitCount; int64_t bitmap_size1 = bitmap::BitmapSize(item_count + bit_offset1); int64_t bitmap_size2 = bitmap::BitmapSize(item_count + bit_offset2); Buffer<int>::Builder values1(item_count); Buffer<int>::Builder values2(item_count); Buffer<bitmap::Word>::Builder presence1(bitmap_size1); Buffer<bitmap::Word>::Builder presence2(bitmap_size2); for (int i = 0; i < item_count; ++i) { values1.Set(i, i); values2.Set(i, 2 * i); } for (int i = 0; i < bitmap_size1; ++i) { presence1.Set(i, 0xfff0ff0f + i); } for (int i = 0; i < bitmap_size2; ++i) { presence2.Set(i, 0xfff0ff0f - i); } DenseArray<int> arr1{std::move(values1).Build(), std::move(presence1).Build(), bit_offset1}; DenseArray<int> arr2{std::move(values2).Build(), std::move(presence2).Build(), bit_offset2}; ASSERT_OK_AND_ASSIGN(auto res, CreateDenseOp(UnionAddFn())(arr1, arr2)); for (int64_t i = 0; i < item_count; ++i) { EXPECT_EQ(res[i], UnionAddFn()(arr1[i], arr2[i])); } } } TEST(UniversalDenseOp, String) { DenseArray<absl::string_view> arg_str; DenseArray<int> arg_pos; DenseArray<int> arg_len; arg_str.values = CreateBuffer<absl::string_view>( {"Hello, world!", "Some other string", "?", "abaca", "Gooooooooooooooooooooooooooooooooooooooooooogle"}); arg_pos.values = CreateBuffer<int>({3, 5, 1, 0, 0}); arg_len.values = CreateBuffer<int>({5, 4, 0, 3, 4}); auto op = CreateDenseOp([](absl::string_view str, int pos, int len) { return str.substr(pos, len); }); ASSERT_OK_AND_ASSIGN(DenseArray<absl::string_view> res, op(arg_str, arg_pos, arg_len)); EXPECT_EQ(res.values[0], "lo, w"); EXPECT_EQ(res.values[1], "othe"); EXPECT_EQ(res.values[2], ""); EXPECT_EQ(res.values[3], "aba"); EXPECT_EQ(res.values[4], "Gooo"); } TEST(UniversalDenseOp, Text) { DenseArray<Text> arg_str; DenseArray<int> arg_pos; DenseArray<int> arg_len; arg_str.values = CreateBuffer<absl::string_view>( {"Hello, world!", "Some other string", "?", "abaca", "Gooooooooooooooooooooooooooooooooooooooooooogle"}); arg_pos.values = CreateBuffer<int>({3, 5, 1, 0, 0}); arg_len.values = CreateBuffer<int>({5, 4, 0, 3, 4}); auto op = CreateDenseOp([](absl::string_view str, int pos, int len) { return str.substr(pos, len); }); ASSERT_OK_AND_ASSIGN(DenseArray<absl::string_view> res, op(arg_str, arg_pos, arg_len)); EXPECT_EQ(res.values[0], "lo, w"); EXPECT_EQ(res.values[1], "othe"); EXPECT_EQ(res.values[2], ""); EXPECT_EQ(res.values[3], "aba"); EXPECT_EQ(res.values[4], "Gooo"); } TEST(UniversalDenseOp, OutputText) { DenseArray<Text> arg_str; DenseArray<int> arg_pos; DenseArray<int> arg_len; arg_str.values = CreateBuffer<absl::string_view>( {"Hello, world!", "Some other string", "?", "abaca", "Gooooooooooooooooooooooooooooooooooooooooooogle"}); arg_pos.values = CreateBuffer<int>({3, 5, 1, 0, 0}); arg_len.values = CreateBuffer<int>({5, 4, 0, 3, 4}); auto op = CreateDenseOp<DenseOpFlags::kNoSizeValidation>( [](absl::string_view str, int pos, int len) { return Text(str.substr(pos, len)); }); DenseArray<Text> res = op(arg_str, arg_pos, arg_len); EXPECT_EQ(res.values[0], "lo, w"); EXPECT_EQ(res.values[1], "othe"); EXPECT_EQ(res.values[2], ""); EXPECT_EQ(res.values[3], "aba"); EXPECT_EQ(res.values[4], "Gooo"); } TEST(UniversalDenseOp, ForwardErrorStatus) { DenseArray<int> arr = CreateDenseArray<int>({1, {}, 2, 3}); auto status = absl::InternalError("it is an error"); auto op1 = CreateDenseOp([status](int a) -> absl::StatusOr<int> { return status; }); auto op2 = CreateDenseOp([status](int a) -> absl::StatusOr<OptionalValue<float>> { return status; }); auto op3 = CreateDenseOp<DenseOpFlags::kNoSizeValidation>( [status](int a) -> absl::StatusOr<int> { return status; }); auto op4 = CreateDenseOp([](int a) -> absl::StatusOr<int> { return a + 1; }); EXPECT_EQ(op1(arr).status(), status); EXPECT_EQ(op2(arr).status(), status); EXPECT_EQ(op3(arr).status(), status); ASSERT_OK_AND_ASSIGN(auto res, op4(arr)); EXPECT_THAT(res, ElementsAre(2, std::nullopt, 3, 4)); } TEST(DenseOps, DenseArraysForEach) { using OB = ::arolla::OptionalValue<::arolla::Bytes>; DenseArray<float> af = CreateDenseArray<float>( {std::nullopt, 3.0, std::nullopt, 2.0, std::nullopt}); DenseArray<::arolla::Bytes> as = CreateDenseArray<::arolla::Bytes>( {OB("abc"), OB(std::nullopt), OB("bca"), OB("def"), OB("cab")}); DenseArray<int> ai = CreateDenseArray<int>({std::nullopt, 10, 20, 30, std::nullopt}); struct Row { int64_t id; OptionalValue<float> f; absl::string_view s; int i; auto AsTuple() const { return std::make_tuple(id, f, s, i); } }; { std::vector<Row> rows; auto fn = [&](int64_t id, bool valid, OptionalValue<float> f, absl::string_view s, int i) { if (valid) { rows.push_back({id, f, s, i}); } }; EXPECT_THAT( DenseArraysForEach(fn, af, as, DenseArray<int>()), StatusIs(absl::StatusCode::kInvalidArgument, ::testing::HasSubstr("argument sizes mismatch: (5, 5, 0)"))); EXPECT_OK(DenseArraysForEach(fn, af, as, ai)); ASSERT_EQ(rows.size(), 2); EXPECT_EQ(rows[0].AsTuple(), (Row{2, {}, "bca", 20}).AsTuple()); EXPECT_EQ(rows[1].AsTuple(), (Row{3, 2.f, "def", 30}).AsTuple()); } { std::vector<Row> rows; auto fn = [&](int64_t id, OptionalValue<float> f, absl::string_view s, int i) { rows.push_back({id, f, s, i}); }; EXPECT_THAT( DenseArraysForEachPresent(fn, af, as, DenseArray<int>()), StatusIs(absl::StatusCode::kInvalidArgument, ::testing::HasSubstr("argument sizes mismatch: (5, 5, 0)"))); EXPECT_OK(DenseArraysForEachPresent(fn, af, as, ai)); ASSERT_EQ(rows.size(), 2); EXPECT_EQ(rows[0].AsTuple(), (Row{2, {}, "bca", 20}).AsTuple()); EXPECT_EQ(rows[1].AsTuple(), (Row{3, 2.f, "def", 30}).AsTuple()); } } }
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/dense_array/ops/dense_ops.h
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/dense_array/ops/dense_ops_test.cc
1ca990dbeca224035efdabffecc7f3738df6b52c
e3012d8c-ae17-412e-ab5b-ff9ac3d55419
cpp
google/arolla
inplace_slot_builder
arolla/io/inplace_slot_builder.h
arolla/io/inplace_slot_builder_test.cc
#ifndef AROLLA_IO_INPLACE_LOADER_H_ #define AROLLA_IO_INPLACE_LOADER_H_ #include <cstddef> #include <string> #include <type_traits> #include <utility> #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/qtype/qtype.h" #include "arolla/qtype/typed_slot.h" namespace arolla { template <class Struct> class InplaceSlotBuilder final { static_assert( std::is_standard_layout<Struct>::value, "Data must be standard layout to be used with InplaceSlotBuilder."); public: using value_type = Struct; absl::flat_hash_map<std::string, TypedSlot> OutputSlots( FrameLayout::Slot<Struct> slot) const { absl::flat_hash_map<std::string, TypedSlot> slots; slots.reserve(zero_based_slots_.size()); for (const auto& name_slot : zero_based_slots_) { slots.insert({name_slot.first, TypedSlot::UnsafeFromOffset( name_slot.second.GetType(), name_slot.second.byte_offset() + slot.byte_offset())}); } return slots; } absl::Status AddUnsafeField(const std::string& name, QTypePtr type, size_t field_offset) { if (!zero_based_slots_ .insert({name, TypedSlot::UnsafeFromOffset(type, field_offset)}) .second) { return absl::FailedPreconditionError(absl::StrCat( "InplaceLoaderBuilder: duplicated slot name: '", name, "'")); } return absl::OkStatus(); } private: absl::flat_hash_map<std::string, TypedSlot> zero_based_slots_; }; #define AROLLA_ADD_INPLACE_SLOT_FIELD(builder, field, name) \ builder.AddUnsafeField( \ name, \ ::arolla::GetQType< \ decltype(std::declval<decltype(builder)::value_type>().field)>(), \ offsetof(decltype(builder)::value_type, field)) } #endif
#include "arolla/io/inplace_slot_builder.h" #include <cstddef> #include <cstdint> #include <utility> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/container/flat_hash_map.h" #include "absl/status/status.h" #include "absl/status/status_matchers.h" #include "arolla/memory/frame.h" #include "arolla/memory/memory_allocation.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/typed_slot.h" namespace arolla { namespace { using ::absl_testing::StatusIs; using ::testing::HasSubstr; using ::testing::Pair; using ::testing::UnorderedElementsAre; struct TestStruct { int a; double b; }; TEST(ImplaceSlotTest, InplaceSlotBuilder) { auto i32 = GetQType<int32_t>(); auto f64 = GetQType<double>(); FrameLayout::Builder layout_builder; layout_builder.AddSlot<double>(); auto struct_slot = layout_builder.AddSlot<TestStruct>(); InplaceSlotBuilder<TestStruct> builder; ASSERT_OK(AROLLA_ADD_INPLACE_SLOT_FIELD(builder, a, "a")); ASSERT_OK(AROLLA_ADD_INPLACE_SLOT_FIELD(builder, b, "name_for_b")); EXPECT_THAT( builder.OutputSlots(struct_slot), UnorderedElementsAre( Pair("a", TypedSlot::UnsafeFromOffset( i32, offsetof(TestStruct, a) + struct_slot.byte_offset())), Pair("name_for_b", TypedSlot::UnsafeFromOffset( f64, offsetof(TestStruct, b) + struct_slot.byte_offset())))); } TEST(InputLoaderTest, InplaceLoaderBuilderErrors) { FrameLayout::Builder layout_builder; InplaceSlotBuilder<TestStruct> builder; ASSERT_OK(AROLLA_ADD_INPLACE_SLOT_FIELD(builder, a, "a")); ASSERT_THAT( AROLLA_ADD_INPLACE_SLOT_FIELD(builder, b, "a"), StatusIs(absl::StatusCode::kFailedPrecondition, HasSubstr("InplaceLoaderBuilder: duplicated slot name: 'a'"))); } struct TestStructWithStruct { int a; TestStruct b; }; TEST(InputLoaderTest, InplaceLoaderBuilderNestedStruct) { auto i32 = GetQType<int32_t>(); auto f64 = GetQType<double>(); FrameLayout::Builder layout_builder; layout_builder.AddSlot<double>(); auto struct_slot = layout_builder.AddSlot<TestStructWithStruct>(); InplaceSlotBuilder<TestStructWithStruct> builder; ASSERT_OK(AROLLA_ADD_INPLACE_SLOT_FIELD(builder, a, "a")); ASSERT_OK(AROLLA_ADD_INPLACE_SLOT_FIELD(builder, b.a, "b.a")); ASSERT_OK(AROLLA_ADD_INPLACE_SLOT_FIELD(builder, b.b, "b.b")); EXPECT_THAT(builder.OutputSlots(struct_slot), UnorderedElementsAre( Pair("a", TypedSlot::UnsafeFromOffset( i32, offsetof(TestStructWithStruct, a) + struct_slot.byte_offset())), Pair("b.a", TypedSlot::UnsafeFromOffset( i32, offsetof(TestStructWithStruct, b.a) + struct_slot.byte_offset())), Pair("b.b", TypedSlot::UnsafeFromOffset( f64, offsetof(TestStructWithStruct, b.b) + struct_slot.byte_offset())))); } TEST(StructReadOperatorTest, Reader) { InplaceSlotBuilder<TestStructWithStruct> builder; ASSERT_OK(AROLLA_ADD_INPLACE_SLOT_FIELD(builder, a, "a")); ASSERT_OK(AROLLA_ADD_INPLACE_SLOT_FIELD(builder, b.b, "b.b")); FrameLayout::Builder layout_builder; layout_builder.AddSlot<double>(); auto struct_slot = layout_builder.AddSlot<TestStructWithStruct>(); auto slots_map = builder.OutputSlots(struct_slot); ASSERT_OK(RegisterUnsafeSlotsMap(slots_map, &layout_builder)); ASSERT_OK_AND_ASSIGN(auto slot_a, slots_map.at("a").ToSlot<int>()); ASSERT_OK_AND_ASSIGN(auto slot_b, slots_map.at("b.b").ToSlot<double>()); FrameLayout memory_layout = std::move(layout_builder).Build(); MemoryAllocation alloc(&memory_layout); alloc.frame().Set(struct_slot, {3, {0, 5.5}}); EXPECT_EQ(alloc.frame().Get(slot_a), 3); EXPECT_EQ(alloc.frame().Get(slot_b), 5.5); TestStructWithStruct* input = alloc.frame().GetMutable(struct_slot); input->a = 4; input->b.b = 6.5; EXPECT_EQ(alloc.frame().Get(slot_a), 4); EXPECT_EQ(alloc.frame().Get(slot_b), 6.5); EXPECT_EQ(alloc.frame().GetMutable(slot_a), &input->a); EXPECT_EQ(alloc.frame().GetMutable(slot_b), &input->b.b); } } } namespace other_namespace { namespace { struct TestStruct { int a; double b; }; TEST(InputLoaderTest, InplaceLoaderMacroCompilesInOtherNamespace) { ::arolla::InplaceSlotBuilder<TestStruct> builder; ASSERT_OK(AROLLA_ADD_INPLACE_SLOT_FIELD(builder, a, "a")); } } }
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/io/inplace_slot_builder.h
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/io/inplace_slot_builder_test.cc
1ca990dbeca224035efdabffecc7f3738df6b52c
0977269c-291b-49e7-ae5b-3ecff7f99329
cpp
google/arolla
accessor_helpers
arolla/io/accessor_helpers.h
arolla/io/accessor_helpers_test.cc
#ifndef AROLLA_IO_ACCESSOR_HELPERS_H_ #define AROLLA_IO_ACCESSOR_HELPERS_H_ #include <cstddef> #include <string> #include <tuple> #include <type_traits> #include <utility> namespace arolla::accessor_helpers_impl { template <class... NameAccessors> class VariadicPackToNestedTupleImpl { private: template <size_t I> using AccessorType = std::remove_cv_t<std::remove_reference_t<typename std::tuple_element< I * 2 + 1, std::tuple<NameAccessors...>>::type>>; template <size_t I> AccessorType<I> Accessor() const { return std::get<I * 2 + 1>(name_accessors_); } template <size_t... Is> using NestedTupleType = std::tuple<std::pair<std::string, AccessorType<Is>>...>; template <size_t... Is> NestedTupleType<Is...> MakeNestedTupleImpl(std::index_sequence<Is...>) const { return std::make_tuple(std::make_pair(Name<Is>(), Accessor<Is>())...); } template <size_t I> std::string Name() const { return std::string(std::get<I * 2>(name_accessors_)); } public: static_assert( sizeof...(NameAccessors) % 2 == 0, "NameAccessors must be formed as name, accessor, name, accessor, ..."); static constexpr size_t kAccessorCount = sizeof...(NameAccessors) / 2; explicit VariadicPackToNestedTupleImpl( std::tuple<NameAccessors...> name_accessors) : name_accessors_(name_accessors) {} auto MakeNestedTuple() const -> decltype(MakeNestedTupleImpl( std::make_index_sequence< VariadicPackToNestedTupleImpl::kAccessorCount>())) { return MakeNestedTupleImpl( std::make_index_sequence< VariadicPackToNestedTupleImpl::kAccessorCount>()); } private: std::tuple<NameAccessors...> name_accessors_; }; template <class... NameAccessors> auto ConvertNameAccessorsPackToNestedTuple(NameAccessors... name_accessors) -> decltype(VariadicPackToNestedTupleImpl<NameAccessors...>( std::make_tuple(name_accessors...)) .MakeNestedTuple()) { return VariadicPackToNestedTupleImpl<NameAccessors...>( std::forward_as_tuple(name_accessors...)) .MakeNestedTuple(); } } #endif
#include "arolla/io/accessor_helpers.h" #include <string> #include <tuple> #include <utility> #include "gtest/gtest.h" namespace arolla::accessor_helpers_impl { namespace { struct TestStruct { int a; double b; }; struct GetAConstRef { const int& operator()(const TestStruct& s) const { return s.a; } }; struct GetBValue { double operator()(const TestStruct& s) const { return s.b; } }; TEST(InputLoaderTest, ConvertNameAccessorsPackToNestedTuple) { { std::tuple<std::pair<std::string, GetAConstRef>, std::pair<std::string, GetBValue>> t = ConvertNameAccessorsPackToNestedTuple("a", GetAConstRef{}, "b", GetBValue{}); EXPECT_EQ(std::get<0>(std::get<0>(t)), "a"); EXPECT_EQ(std::get<0>(std::get<1>(t)), "b"); EXPECT_EQ(std::get<1>(std::get<0>(t))(TestStruct{5, 3.5}), 5); EXPECT_EQ(std::get<1>(std::get<1>(t))(TestStruct{5, 3.5}), 3.5); } { auto t = ConvertNameAccessorsPackToNestedTuple( "a", [](const TestStruct& s) { return s.a; }, "b", [](const TestStruct& s) { return s.b; }); EXPECT_EQ(std::get<0>(std::get<0>(t)), "a"); EXPECT_EQ(std::get<0>(std::get<1>(t)), "b"); EXPECT_EQ(std::get<1>(std::get<0>(t))(TestStruct{5, 3.5}), 5); EXPECT_EQ(std::get<1>(std::get<1>(t))(TestStruct{5, 3.5}), 3.5); } { auto t = ConvertNameAccessorsPackToNestedTuple( "a", GetAConstRef{}, "b", [](const TestStruct& s) { return s.b; }); EXPECT_EQ(std::get<0>(std::get<0>(t)), "a"); EXPECT_EQ(std::get<0>(std::get<1>(t)), "b"); EXPECT_EQ(std::get<1>(std::get<0>(t))(TestStruct{5, 3.5}), 5); EXPECT_EQ(std::get<1>(std::get<1>(t))(TestStruct{5, 3.5}), 3.5); } } } }
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/io/accessor_helpers.h
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/io/accessor_helpers_test.cc
1ca990dbeca224035efdabffecc7f3738df6b52c
79cb2597-85ae-444b-a838-21b1f68986d9
cpp
google/arolla
span_input_loader
arolla/io/span_input_loader.h
arolla/io/span_input_loader_test.cc
#ifndef AROLLA_IO_SPAN_INPUT_LOADER_H_ #define AROLLA_IO_SPAN_INPUT_LOADER_H_ #include <cstddef> #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_format.h" #include "absl/types/span.h" #include "arolla/io/input_loader.h" #include "arolla/memory/frame.h" #include "arolla/memory/optional_value.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/util/status_macros_backport.h" namespace arolla { namespace span_input_loader_impl { template <typename T> struct InputTraits { using ArollaType = T; }; template <typename T> struct InputTraits<std::optional<T>> { using ArollaType = OptionalValue<T>; }; template <typename T> std::vector<std::pair<std::string, QTypePtr>> MakeQTypesList( std::vector<std::string> names_in_order) { std::vector<std::pair<std::string, QTypePtr>> qtypes; qtypes.reserve(names_in_order.size()); for (const auto& name : names_in_order) { qtypes.emplace_back(name, GetQType<T>()); } return qtypes; } } template <typename T> class SpanInputLoader : public StaticInputLoader<absl::Span<const T>> { using Input = absl::Span<const T>; using ArollaT = typename span_input_loader_impl::InputTraits<T>::ArollaType; public: static InputLoaderPtr<absl::Span<const T>> Create( std::vector<std::string> output_names_in_order) { return InputLoaderPtr<absl::Span<const T>>(static_cast<InputLoader<Input>*>( new SpanInputLoader<T>(std::move(output_names_in_order)))); } private: explicit SpanInputLoader(std::vector<std::string> output_names_in_order) : StaticInputLoader<absl::Span<const T>>( span_input_loader_impl::MakeQTypesList<ArollaT>( output_names_in_order)) {} 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<FrameLayout::Slot<ArollaT>> slots; for (size_t i = 0; i != this->types_in_order().size(); ++i) { if (auto it = output_slots.find(this->types_in_order()[i].first); it != output_slots.end()) { ASSIGN_OR_RETURN(auto slot, it->second.template ToSlot<ArollaT>()); element_ids.push_back(i); slots.push_back(slot); } } return BoundInputLoader<Input>( [slots = std::move(slots), element_ids = std::move(element_ids), expected_input_size = this->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()); frame.Set(slots[i], ArollaT(input[id])); } return absl::OkStatus(); }); } }; } #endif
#include "arolla/io/span_input_loader.h" #include <optional> #include <utility> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "absl/status/status_matchers.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/memory/optional_value.h" #include "arolla/qtype/optional_qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/typed_slot.h" namespace arolla { namespace { using ::absl_testing::IsOk; using ::absl_testing::StatusIs; using ::arolla::testing::InputLoaderSupports; using ::testing::Eq; TEST(SpanInputLoaderTest, Scalars) { std::unique_ptr<InputLoader<absl::Span<const float>>> input_loader = SpanInputLoader<float>::Create({"a", "b"}); EXPECT_THAT(input_loader, InputLoaderSupports({{"a", GetQType<float>()}, {"b", GetQType<float>()}})); FrameLayout::Builder layout_builder; auto a_slot = layout_builder.AddSlot<float>(); auto b_slot = layout_builder.AddSlot<float>(); ASSERT_OK_AND_ASSIGN( BoundInputLoader<absl::Span<const float>> 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); ASSERT_THAT(bound_input_loader({5, 7}, alloc.frame()), IsOk()); EXPECT_THAT(alloc.frame().Get(a_slot), Eq(5)); EXPECT_THAT(alloc.frame().Get(b_slot), Eq(7)); EXPECT_THAT(bound_input_loader({5, 7, 9}, alloc.frame()), StatusIs(absl::StatusCode::kInvalidArgument, "unexpected input count: expected 2, got 3")); ASSERT_OK_AND_ASSIGN( BoundInputLoader<absl::Span<const float>> bound_b_input_loader, input_loader->Bind({ {"b", TypedSlot::FromSlot(b_slot)}, })); ASSERT_THAT(bound_b_input_loader({2, 57}, alloc.frame()), IsOk()); EXPECT_THAT(alloc.frame().Get(a_slot), Eq(5)); EXPECT_THAT(alloc.frame().Get(b_slot), Eq(57)); } TEST(SpanInputLoaderTest, Optionals) { std::unique_ptr<InputLoader<absl::Span<const std::optional<float>>>> input_loader = SpanInputLoader<std::optional<float>>::Create({"a", "b"}); EXPECT_THAT(input_loader, InputLoaderSupports({{"a", GetOptionalQType<float>()}, {"b", GetOptionalQType<float>()}})); 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<absl::Span<const std::optional<float>>> 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); ASSERT_THAT(bound_input_loader({5, std::nullopt}, alloc.frame()), IsOk()); EXPECT_THAT(alloc.frame().Get(a_slot), Eq(5.f)); EXPECT_THAT(alloc.frame().Get(b_slot), Eq(std::nullopt)); } } }
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/io/span_input_loader.h
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/io/span_input_loader_test.cc
1ca990dbeca224035efdabffecc7f3738df6b52c
152c662f-daaf-4c56-854f-bb34cf535d3f
cpp
google/arolla
delegating_input_loader
arolla/io/delegating_input_loader.h
arolla/io/delegating_input_loader_test.cc
#ifndef AROLLA_IO_DELEGATING_INPUT_LOADER_H_ #define AROLLA_IO_DELEGATING_INPUT_LOADER_H_ #include <functional> #include <string> #include <type_traits> #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/string_view.h" #include "absl/strings/strip.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/typed_slot.h" #include "arolla/util/status_macros_backport.h" namespace arolla { namespace delegating_input_loader_impl { template <class Input, class DelegateInputFullType> class DelegatingInputLoader final : public InputLoader<Input> { using DelegateInput = std::decay_t<DelegateInputFullType>; public: static absl::StatusOr<InputLoaderPtr<Input>> Build( InputLoaderPtr<std::decay_t<DelegateInputFullType>> delegate_loader, std::function<DelegateInputFullType(const Input&)> accessor, std::string name_prefix) { return InputLoaderPtr<Input>( static_cast<InputLoader<Input>*>(new DelegatingInputLoader( std::move(delegate_loader), accessor, std::move(name_prefix)))); } absl::Nullable<const QType*> GetQTypeOf(absl::string_view name) const final { if (!absl::ConsumePrefix(&name, name_prefix_)) { return nullptr; } return delegate_loader_->GetQTypeOf(name); } std::vector<std::string> SuggestAvailableNames() const final { std::vector<std::string> names = delegate_loader_->SuggestAvailableNames(); for (auto& name : names) { name = absl::StrCat(name_prefix_, name); } return names; } private: DelegatingInputLoader( InputLoaderPtr<DelegateInput> delegate_loader, std::function<DelegateInputFullType(const Input&)> accessor, std::string name_prefix) : delegate_loader_(std::move(delegate_loader)), accessor_(accessor), name_prefix_(name_prefix) {} absl::StatusOr<BoundInputLoader<Input>> BindImpl( const absl::flat_hash_map<std::string, TypedSlot>& output_slots) const final { absl::flat_hash_map<std::string, TypedSlot> delegate_output_slots; for (const auto& [name, slot] : output_slots) { absl::string_view delegate_name = name; if (!absl::ConsumePrefix(&delegate_name, name_prefix_)) { return absl::InternalError( absl::StrFormat("unexpected input name %s", name)); } delegate_output_slots.emplace(delegate_name, slot); } ASSIGN_OR_RETURN(BoundInputLoader<DelegateInput> bound_delegate_loader, delegate_loader_->Bind(delegate_output_slots)); return BoundInputLoader<Input>( [bound_delegate_loader(std::move(bound_delegate_loader)), accessor(accessor_)](const Input& input, FramePtr frame, RawBufferFactory* factory) -> absl::Status { return bound_delegate_loader(accessor(input), frame, factory); }); } InputLoaderPtr<DelegateInput> delegate_loader_; std::function<DelegateInputFullType(const Input&)> accessor_; std::string name_prefix_; }; } template <class Input, class DelegateInput, class Accessor> absl::StatusOr<InputLoaderPtr<Input>> CreateDelegatingInputLoader( InputLoaderPtr<DelegateInput> delegate_loader, const Accessor& accessor, std::string name_prefix = "") { static_assert( std::is_same_v<decltype(accessor(std::declval<Input>())), const DelegateInput&>, "Accessor must have `const DelegateInput&` result type. In case of " "lambda specify output type explicitly, this would save copying. " "In case you are creating temporary object and copy is necessary or " "intended, use CreateDelegatingInputLoaderWithCopyAllowed."); return delegating_input_loader_impl::DelegatingInputLoader< Input, const DelegateInput&>::Build(std::move(delegate_loader), accessor, std::move(name_prefix)); } template <class Input, class DelegateInput, class Accessor> absl::StatusOr<InputLoaderPtr<Input>> CreateDelegatingInputLoaderWithCopyAllowed( InputLoaderPtr<DelegateInput> delegate_loader, const Accessor& accessor, std::string name_prefix = "") { static_assert( std::is_same_v<decltype(accessor(std::declval<Input>())), DelegateInput>, "Accessor must have `DelegateInput` result type for " "CreateDelegatingInputLoaderWithCopyAllowed. In case accessor returns " "`const DelegateInput&`, use CreateDelegatingInputLoader."); return delegating_input_loader_impl::DelegatingInputLoader< Input, DelegateInput>::Build(std::move(delegate_loader), accessor, std::move(name_prefix)); } } #endif
#include "arolla/io/delegating_input_loader.h" #include <cstdint> #include <memory> #include <string> #include <utility> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/log/check.h" #include "absl/status/statusor.h" #include "absl/types/span.h" #include "arolla/io/accessors_input_loader.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.h" #include "arolla/qtype/qtype_traits.h" namespace arolla { namespace { using ::arolla::testing::InputLoaderSupports; struct TestStruct { int a; double b; }; struct OuterTestStruct { TestStruct* a; int b; }; TEST(InputLoaderTest, DelegatingInputLoader) { auto i32 = GetQType<int32_t>(); auto f64 = GetQType<double>(); std::unique_ptr<InputLoader<OuterTestStruct>> input_loader; std::unique_ptr<InputLoader<OuterTestStruct>> renamed_input_loader; std::unique_ptr<InputLoader<OuterTestStruct>> input_loader_with_copy_allowed; { auto create_struct_loader = []() { return CreateAccessorsInputLoader<TestStruct>( "a", [](const TestStruct& s) { return s.a; }, "b", [](const TestStruct& s) { return s.b; }) .value(); }; auto accessor = [](const OuterTestStruct& s) -> const TestStruct& { return *s.a; }; ASSERT_OK_AND_ASSIGN(input_loader, CreateDelegatingInputLoader<OuterTestStruct>( create_struct_loader(), accessor)); ASSERT_OK_AND_ASSIGN( renamed_input_loader, CreateDelegatingInputLoader<OuterTestStruct>( create_struct_loader(), accessor, "p_")); ASSERT_OK_AND_ASSIGN( auto loader_span, CreateAccessorsInputLoader<absl::Span<const TestStruct>>( "a", [](const auto& s) { CHECK_EQ(s.size(), 1); return s[0].a; }, "b", [](const auto& s) { CHECK_EQ(s.size(), 1); return s[0].b; })); auto span_accessor = [](const OuterTestStruct& s) -> absl::Span<const TestStruct> { return absl::MakeConstSpan(s.a, 1); }; ASSERT_OK_AND_ASSIGN( input_loader_with_copy_allowed, CreateDelegatingInputLoaderWithCopyAllowed<OuterTestStruct>( std::move(loader_span), span_accessor)); } for (const auto& [prefix, input_loader] : std::vector<std::pair<std::string, const InputLoader<OuterTestStruct>*>>{ {"", input_loader.get()}, {"p_", renamed_input_loader.get()}, {"", input_loader_with_copy_allowed.get()}}) { EXPECT_THAT(*input_loader, InputLoaderSupports( {{prefix + "a", i32}, {prefix + "b", f64}})); FrameLayout::Builder layout_builder; auto a_slot = layout_builder.AddSlot<int>(); auto b_slot = layout_builder.AddSlot<double>(); ASSERT_OK_AND_ASSIGN(BoundInputLoader<OuterTestStruct> bound_input_loader, input_loader->Bind({ {prefix + "a", TypedSlot::FromSlot(a_slot)}, {prefix + "b", TypedSlot::FromSlot(b_slot)}, })); FrameLayout memory_layout = std::move(layout_builder).Build(); MemoryAllocation alloc(&memory_layout); TestStruct ts{5, 3.5}; ASSERT_OK(bound_input_loader({&ts, -1}, alloc.frame())); EXPECT_EQ(alloc.frame().Get(a_slot), 5); EXPECT_EQ(alloc.frame().Get(b_slot), 3.5); } } } }
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/io/delegating_input_loader.h
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/io/delegating_input_loader_test.cc
1ca990dbeca224035efdabffecc7f3738df6b52c
c0bbb1d9-7af7-45c5-8810-2ff63fa804c5
cpp
google/arolla
tuple_input_loader
arolla/io/tuple_input_loader.h
arolla/io/tuple_input_loader_test.cc
#ifndef AROLLA_IO_TUPLE_INPUT_LOADER_H_ #define AROLLA_IO_TUPLE_INPUT_LOADER_H_ #include <cstddef> #include <string> #include <tuple> #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_cat.h" #include "absl/strings/str_format.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/qtype_traits.h" namespace arolla { template <typename Input> class TupleInputLoader; template <typename... Ts> class TupleInputLoader<std::tuple<Ts...>> final : public StaticInputLoader<std::tuple<Ts...>> { public: using Input = std::tuple<Ts...>; static absl::StatusOr<InputLoaderPtr<Input>> Create( std::vector<std::string> arg_names) { if (arg_names.size() != sizeof...(Ts)) { return absl::InvalidArgumentError( absl::StrFormat("tuple size doesn't match arg_names size: %d vs %d", sizeof...(Ts), arg_names.size())); } return InputLoaderPtr<Input>( static_cast<InputLoader<Input>*>(new TupleInputLoader<Input>( std::move(arg_names), std::index_sequence_for<Ts...>{}))); } private: template <size_t... Is> explicit TupleInputLoader(std::vector<std::string> arg_names, std::index_sequence<Is...>) : StaticInputLoader<std::tuple<Ts...>>( {{arg_names[Is], ::arolla::GetQType<Ts>()}...}) {} absl::StatusOr<BoundInputLoader<Input>> BindImpl( const absl::flat_hash_map<std::string, TypedSlot>& output_slots) const override { std::vector<TypedSlot> slots_in_order; slots_in_order.reserve(this->types_in_order().size()); for (const auto& [name, _] : this->types_in_order()) { auto it = output_slots.find(name); if (it == output_slots.end()) { return absl::FailedPreconditionError(absl::StrCat( "TupleInputLoader doesn't support unused arguments; no slot for: ", name)); } slots_in_order.push_back(it->second); } return BoundInputLoader<Input>( [slots_in_order](const Input& input, FramePtr frame, RawBufferFactory*) -> absl::Status { LoaderImpl(input, frame, slots_in_order, std::index_sequence_for<Ts...>{}); return absl::OkStatus(); }); } template <size_t... Is> static void LoaderImpl(const Input& input, FramePtr frame, const std::vector<TypedSlot>& slots, std::index_sequence<Is...>) { (frame.Set(slots[Is].UnsafeToSlot<Ts>(), std::get<Is>(input)), ...); } }; } #endif
#include "arolla/io/tuple_input_loader.h" #include <tuple> #include <utility> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "absl/status/status_matchers.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_slot.h" namespace arolla { namespace { using ::absl_testing::IsOk; using ::absl_testing::StatusIs; using ::arolla::testing::InputLoaderSupports; using ::testing::Eq; using ::testing::HasSubstr; TEST(TupleInputLoaderTest, Scalars) { using Input = std::tuple<float, int>; ASSERT_OK_AND_ASSIGN(std::unique_ptr<InputLoader<Input>> input_loader, (TupleInputLoader<Input>::Create({"a", "b"}))); 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); ASSERT_THAT(bound_input_loader({5, 7}, alloc.frame()), IsOk()); EXPECT_THAT(alloc.frame().Get(a_slot), Eq(5)); EXPECT_THAT(alloc.frame().Get(b_slot), Eq(7)); EXPECT_THAT(input_loader->Bind({ {"b", TypedSlot::FromSlot(b_slot)}, }), StatusIs(absl::StatusCode::kFailedPrecondition, HasSubstr("TupleInputLoader doesn't support unused " "arguments; no slot for: a"))); } } }
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/io/tuple_input_loader.h
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/io/tuple_input_loader_test.cc
1ca990dbeca224035efdabffecc7f3738df6b52c
e70ccc92-ee3a-4f91-a06b-cda54f120d37
cpp
google/arolla
chain_slot_listener
arolla/io/chain_slot_listener.h
arolla/io/chain_slot_listener_test.cc
#ifndef AROLLA_IO_CHAIN_SLOT_LISTENER_H_ #define AROLLA_IO_CHAIN_SLOT_LISTENER_H_ #include <memory> #include <optional> #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/slot_listener.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 Output> class ChainSlotListener final : public SlotListener<Output> { struct PrivateConstructorTag {}; public: template <class... ListenerTs> static absl::StatusOr<std::unique_ptr<SlotListener<Output>>> Build( std::unique_ptr<ListenerTs>... listeners) { std::vector<std::unique_ptr<SlotListener<Output>>> listeners_vec; (listeners_vec.push_back(std::move(listeners)), ...); return Build(std::move(listeners_vec)); } static absl::StatusOr<std::unique_ptr<SlotListener<Output>>> Build( std::vector<std::unique_ptr<SlotListener<Output>>> listeners) { return std::make_unique<ChainSlotListener>(PrivateConstructorTag{}, std::move(listeners)); } absl::Nullable<const QType*> GetQTypeOf( absl::string_view name, absl::Nullable<const QType*> desired_qtype) const final { for (const auto& listener : listeners_) { if (auto qtype = listener->GetQTypeOf(name, desired_qtype); qtype != nullptr) { return qtype; } } return nullptr; } std::vector<std::string> SuggestAvailableNames() const final { std::vector<std::string> names; for (const auto& listener : listeners_) { auto available = listener->SuggestAvailableNames(); names.insert(names.end(), available.begin(), available.end()); } return names; } explicit ChainSlotListener( PrivateConstructorTag, std::vector<std::unique_ptr<SlotListener<Output>>> listeners) : listeners_(std::move(listeners)) {} private: absl::StatusOr<BoundSlotListener<Output>> BindImpl( const absl::flat_hash_map<std::string, TypedSlot>& slots) const final { std::vector<BoundSlotListener<Output>> bound_listeners; bound_listeners.reserve(listeners_.size()); for (const auto& listener : listeners_) { ASSIGN_OR_RETURN(std::optional<BoundSlotListener<Output>> bound_listener, listener->PartialBind(slots)); if (bound_listener.has_value()) { bound_listeners.push_back(*std::move(bound_listener)); } } if (bound_listeners.empty()) { return BoundSlotListener<Output>( [](ConstFramePtr, Output*) { return absl::OkStatus(); }); } if (bound_listeners.size() == 1) { return std::move(bound_listeners[0]); } return BoundSlotListener<Output>( [bound_listeners(std::move(bound_listeners))]( ConstFramePtr frame, Output* output) -> absl::Status { for (const auto& listener : bound_listeners) { RETURN_IF_ERROR(listener(frame, output)); } return absl::OkStatus(); }); } std::vector<std::unique_ptr<SlotListener<Output>>> listeners_; }; } #endif
#include "arolla/io/chain_slot_listener.h" #include <cstdint> #include <functional> #include <memory> #include <utility> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "absl/status/status_matchers.h" #include "absl/status/statusor.h" #include "arolla/io/accessors_slot_listener.h" #include "arolla/io/slot_listener.h" #include "arolla/memory/frame.h" #include "arolla/memory/memory_allocation.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" namespace arolla { namespace { using ::absl_testing::StatusIs; using ::testing::ElementsAre; using ::testing::Eq; using ::testing::HasSubstr; struct TestStruct { int a; double b; int c; }; TEST(SlotListenerTest, ChainSlotListenerErrors) { ASSERT_OK_AND_ASSIGN(auto loader1, CreateAccessorsSlotListener<TestStruct>( "a", [](int a, TestStruct* s) { s->a = a; }, "b", [](double b, TestStruct* s) { s->b = b; })); ASSERT_OK_AND_ASSIGN( auto loader2, CreateAccessorsSlotListener<TestStruct>( "a", [](double b, TestStruct* s) { s->b = b; })); ASSERT_OK_AND_ASSIGN(auto chain_listener, ChainSlotListener<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(); EXPECT_THAT( chain_listener->Bind({ {"a", TypedSlot::FromSlot(a_slot)}, {"b", TypedSlot::FromSlot(b_slot)}, }), StatusIs(absl::StatusCode::kFailedPrecondition, HasSubstr("slots/types match errors:slot types mismatch: " "a{expected:FLOAT64, actual:INT32}"))); } TEST(SlotListenerTest, ChainSlotListener) { auto create_listener1 = []() { return CreateAccessorsSlotListener<TestStruct>( "a", [](int a, TestStruct* s) { s->a = a; }) .value(); }; auto create_listener2 = []() { return CreateAccessorsSlotListener<TestStruct>( "b", [](double b, TestStruct* s) { s->b = b; }, "a", [](int a, TestStruct* s) { s->c = a; }) .value(); }; ASSERT_OK_AND_ASSIGN(auto chain_listener1, ChainSlotListener<TestStruct>::Build( create_listener1(), create_listener2())); std::vector<std::unique_ptr<SlotListener<TestStruct>>> listeners; listeners.push_back(create_listener1()); listeners.push_back(create_listener2()); ASSERT_OK_AND_ASSIGN( auto chain_listener2, ChainSlotListener<TestStruct>::Build(std::move(listeners))); 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(); for (auto chain_listener : {chain_listener1.get(), chain_listener2.get()}) { EXPECT_THAT(chain_listener->GetQTypeOf("a"), Eq(GetQType<int>())); EXPECT_THAT(chain_listener->GetQTypeOf("b"), Eq(GetQType<double>())); EXPECT_THAT(chain_listener->SuggestAvailableNames(), ElementsAre("a", "b", "a")); ASSERT_OK_AND_ASSIGN(BoundSlotListener<TestStruct> bound_chain_listener, chain_listener->Bind({ {"a", TypedSlot::FromSlot(a_slot)}, {"b", TypedSlot::FromSlot(b_slot)}, })); MemoryAllocation alloc(&memory_layout); alloc.frame().Set(a_slot, 5); alloc.frame().Set(b_slot, 3.5); TestStruct s; ASSERT_OK(bound_chain_listener(alloc.frame(), &s)); EXPECT_EQ(s.a, 5); EXPECT_EQ(s.b, 3.5); EXPECT_EQ(s.c, 5); } } } }
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/io/chain_slot_listener.h
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/io/chain_slot_listener_test.cc
1ca990dbeca224035efdabffecc7f3738df6b52c
8a854171-eb11-48c9-a96f-8a9df32a976f
cpp
google/arolla
accessors_slot_listener
arolla/io/accessors_slot_listener.h
arolla/io/accessors_slot_listener_test.cc
#ifndef AROLLA_IO_ACCESSORS_SLOT_LISTENER_H_ #define AROLLA_IO_ACCESSORS_SLOT_LISTENER_H_ #include <cstddef> #include <memory> #include <optional> #include <string> #include <tuple> #include <type_traits> #include <utility> #include <vector> #include "absl/base/attributes.h" #include "absl/container/flat_hash_map.h" #include "absl/memory/memory.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "arolla/io/accessor_helpers.h" #include "arolla/io/input_loader.h" #include "arolla/io/slot_listener.h" #include "arolla/memory/frame.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/typed_slot.h" #include "arolla/util/meta.h" #include "arolla/util/status_macros_backport.h" namespace arolla { namespace slot_listener_impl { template <class Accessor, class Output> using slot_listener_accessor_input_t = std::decay_t<meta::head_t< typename meta::function_traits<std::decay_t<Accessor>>::arg_types>>; template <class Output, class Accessor> class Getter { public: using InputType = slot_listener_accessor_input_t<Accessor, Output>; Getter(std::optional<FrameLayout::Slot<InputType>> slot, Accessor accessor) : slot_(slot), accessor_(std::move(accessor)) {} static absl::StatusOr<Getter> Build(std::optional<TypedSlot> slot, const Accessor& accessor) { if (slot.has_value()) { ASSIGN_OR_RETURN(auto specific_slot, slot->ToSlot<InputType>()); return {Getter({specific_slot}, accessor)}; } else { return {Getter(std::nullopt, accessor)}; } } void operator()(ConstFramePtr frame, Output* output) const { if (slot_.has_value()) { accessor_(frame.Get(*slot_), output); } } private: std::optional<FrameLayout::Slot<InputType>> slot_; Accessor accessor_; }; template <class Input, class NameAccessorsTuple> class AccessorsSlotListener; template <class Output, class... Accessors> class AccessorsSlotListener<Output, std::tuple<std::pair<std::string, Accessors>...>> final : public StaticSlotListener<Output> { using NameAccessorsTuple = std::tuple<std::pair<std::string, Accessors>...>; public: static absl::StatusOr<std::unique_ptr<SlotListener<Output>>> Build( NameAccessorsTuple accessors) { auto loader = absl::WrapUnique(new AccessorsSlotListener(std::move(accessors))); RETURN_IF_ERROR(ValidateDuplicatedNames(loader->types_in_order())); return {std::move(loader)}; } private: absl::StatusOr<BoundSlotListener<Output>> BindImpl( const absl::flat_hash_map<std::string, TypedSlot>& input_slots) const final { ASSIGN_OR_RETURN(auto slots, MaybeFindSlotsAndVerifyTypes( this->types_in_order(), input_slots)); return BindImpl( std::move(slots), std::make_index_sequence<std::tuple_size<NameAccessorsTuple>::value>{}); } explicit AccessorsSlotListener(NameAccessorsTuple accessors) : StaticSlotListener<Output>( AccessorsSlotListener::CreateOutputTypesInOrder( accessors, std::make_index_sequence< std::tuple_size<NameAccessorsTuple>::value>{})), accessors_(std::move(accessors)) {} template <size_t I> using Accessor = std::tuple_element_t<1, std::tuple_element_t<I, NameAccessorsTuple>>; template <size_t I> using SlotListenerAccessorInputType = slot_listener_impl::slot_listener_accessor_input_t<Accessor<I>, Output>; template <size_t I> const Accessor<I>& GetAccessor() const { return std::get<1>(std::get<I>(accessors_)); } template <size_t I> static QTypePtr GetOutputType() { return GetQType<SlotListenerAccessorInputType<I>>(); } template <size_t... Is> static std::vector<std::pair<std::string, QTypePtr>> CreateOutputTypesInOrder( const NameAccessorsTuple& accessors, std::index_sequence<Is...>) { return {{std::string(std::get<0>(std::get<Is>(accessors))), GetOutputType<Is>()}...}; } template <size_t... Is> absl::StatusOr<BoundSlotListener<Output>> BindImpl( std::vector<std::optional<TypedSlot>> slots, std::index_sequence<Is...>) const { auto getters_or = LiftStatusUp(slot_listener_impl::Getter<Output, Accessor<Is>>::Build( slots[Is], GetAccessor<Is>())...); ASSIGN_OR_RETURN(auto getters, getters_or); return BoundSlotListener<Output>( [getters_(std::move(getters))]( ConstFramePtr frame ABSL_ATTRIBUTE_UNUSED, Output* output ABSL_ATTRIBUTE_UNUSED) { (std::get<Is>(getters_)(frame, output), ...); return absl::OkStatus(); }); } NameAccessorsTuple accessors_; }; } template <class Input, class NameAccessorsTuple> using AccessorsSlotListener = slot_listener_impl::AccessorsSlotListener<Input, NameAccessorsTuple>; template <class Output, class... Accessors> absl::StatusOr<std::unique_ptr<SlotListener<Output>>> CreateAccessorsSlotListenerFromTuple( std::tuple<std::pair<std::string, Accessors>...> name_accessors) { return AccessorsSlotListener<Output, decltype(name_accessors)>::Build( std::move(name_accessors)); } template <class Output, class... NameAccessors> absl::StatusOr<std::unique_ptr<SlotListener<Output>>> CreateAccessorsSlotListener(NameAccessors... name_accessors) { return CreateAccessorsSlotListenerFromTuple<Output>( accessor_helpers_impl::ConvertNameAccessorsPackToNestedTuple( name_accessors...)); } } #endif
#include "arolla/io/accessors_slot_listener.h" #include <cstddef> #include <cstdint> #include <functional> #include <memory> #include <string> #include <tuple> #include <utility> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/container/flat_hash_map.h" #include "absl/status/status.h" #include "absl/status/status_matchers.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "arolla/io/slot_listener.h" #include "arolla/memory/frame.h" #include "arolla/memory/memory_allocation.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" namespace arolla { namespace { using ::absl_testing::StatusIs; using ::testing::ElementsAre; using ::testing::Eq; using ::testing::HasSubstr; struct TestStruct { int a; double b; }; TEST(AccessorsSlotListenerTest, NormalAccessors) { ASSERT_OK_AND_ASSIGN(auto slot_listener, CreateAccessorsSlotListener<TestStruct>( "a", [](int a, TestStruct* s) { s->a = a; }, "b", [](double b, TestStruct* s) { s->b = b; })); EXPECT_THAT(slot_listener->GetQTypeOf("a"), Eq(GetQType<int32_t>())); EXPECT_THAT(slot_listener->GetQTypeOf("b"), Eq(GetQType<double>())); EXPECT_THAT(slot_listener->SuggestAvailableNames(), ElementsAre("a", "b")); { FrameLayout::Builder layout_builder; layout_builder.AddSlot<double>(); auto a_slot = layout_builder.AddSlot<int>(); layout_builder.AddSlot<char>(); auto b_slot = layout_builder.AddSlot<double>(); layout_builder.AddSlot<std::string>(); ASSERT_OK_AND_ASSIGN(BoundSlotListener<TestStruct> bound_slot_listener, slot_listener->Bind({ {"a", TypedSlot::FromSlot(a_slot)}, {"b", TypedSlot::FromSlot(b_slot)}, })); FrameLayout memory_layout = std::move(layout_builder).Build(); MemoryAllocation alloc(&memory_layout); alloc.frame().Set(a_slot, 5); alloc.frame().Set(b_slot, 3.5); TestStruct side_output{0, 0}; ASSERT_OK(bound_slot_listener(alloc.frame(), &side_output)); EXPECT_THAT(side_output.a, Eq(5)); EXPECT_THAT(side_output.b, Eq(3.5)); } { FrameLayout::Builder layout_builder; layout_builder.AddSlot<double>(); auto a_slot = layout_builder.AddSlot<int>(); layout_builder.AddSlot<char>(); ASSERT_OK_AND_ASSIGN(BoundSlotListener<TestStruct> bound_slot_listener, slot_listener->Bind({ {"a", TypedSlot::FromSlot(a_slot)}, })); FrameLayout memory_layout = std::move(layout_builder).Build(); MemoryAllocation alloc(&memory_layout); alloc.frame().Set(a_slot, 5); TestStruct side_output{0, 0}; ASSERT_OK(bound_slot_listener(alloc.frame(), &side_output)); EXPECT_THAT(side_output.a, Eq(5)); EXPECT_THAT(side_output.b, Eq(0)); } { FrameLayout::Builder layout_builder; layout_builder.AddSlot<double>(); auto b_slot = layout_builder.AddSlot<double>(); layout_builder.AddSlot<std::string>(); ASSERT_OK_AND_ASSIGN(BoundSlotListener<TestStruct> bound_slot_listener, slot_listener->Bind({ {"b", TypedSlot::FromSlot(b_slot)}, })); FrameLayout memory_layout = std::move(layout_builder).Build(); MemoryAllocation alloc(&memory_layout); alloc.frame().Set(b_slot, 3.5); TestStruct side_output{0, 0}; ASSERT_OK(bound_slot_listener(alloc.frame(), &side_output)); EXPECT_THAT(side_output.a, Eq(0)); EXPECT_THAT(side_output.b, Eq(3.5)); } { FrameLayout::Builder layout_builder; layout_builder.AddSlot<double>(); auto b_slot = layout_builder.AddSlot<double>(); auto c_slot = layout_builder.AddSlot<int>(); layout_builder.AddSlot<std::string>(); ASSERT_OK_AND_ASSIGN(auto bound_slot_listener, slot_listener->PartialBind({ {"b", TypedSlot::FromSlot(b_slot)}, {"c", TypedSlot::FromSlot(c_slot)}, })); ASSERT_TRUE(bound_slot_listener.has_value()); FrameLayout memory_layout = std::move(layout_builder).Build(); MemoryAllocation alloc(&memory_layout); alloc.frame().Set(b_slot, 3.5); TestStruct side_output{0, 0}; ASSERT_OK((*bound_slot_listener)(alloc.frame(), &side_output)); EXPECT_THAT(side_output.a, Eq(0)); EXPECT_THAT(side_output.b, Eq(3.5)); } { FrameLayout::Builder layout_builder; auto c_slot = layout_builder.AddSlot<int>(); layout_builder.AddSlot<std::string>(); ASSERT_OK_AND_ASSIGN(auto bound_slot_listener, slot_listener->PartialBind({ {"c", TypedSlot::FromSlot(c_slot)}, })); EXPECT_FALSE(bound_slot_listener.has_value()); } } TEST(InputLoaderTest, NameDuplicates) { EXPECT_THAT(CreateAccessorsSlotListener<TestStruct>( "a", [](int a, TestStruct* s) { s->a = a; }, "c", [](double b, TestStruct* s) { s->b = b; }, "b", [](double b, TestStruct* s) { s->b = b; }, "c", [](double b, TestStruct* s) { s->b = b; }, "a", [](int a, TestStruct* s) { s->a = a; }), StatusIs(absl::StatusCode::kFailedPrecondition, HasSubstr("accessors have duplicated names: a, c"))); } TEST(InputLoaderTest, Errors) { ASSERT_OK_AND_ASSIGN(auto slot_listener, CreateAccessorsSlotListener<TestStruct>( "a", [](int a, TestStruct* s) { s->a = a; })); { FrameLayout::Builder layout_builder; auto dslot = layout_builder.AddSlot<double>(); EXPECT_THAT( slot_listener->Bind({ {"a", TypedSlot::FromSlot(dslot)}, }), StatusIs( absl::StatusCode::kFailedPrecondition, HasSubstr("types mismatch: a{expected:INT32, actual:FLOAT64}"))); } } using PairStringFunction = std::pair<std::string, std::function<void(int, int*)>>; template <size_t> using PairStringFunctionByInt = PairStringFunction; template <size_t... Is> absl::StatusOr<std::unique_ptr<SlotListener<int>>> CreateAccessorsSlotListenerManyInputs(std::index_sequence<Is...>) { using T = std::tuple<PairStringFunctionByInt<Is>...>; return CreateAccessorsSlotListenerFromTuple<int>(T{PairStringFunction( absl::StrCat(Is), [](int, int* out) { *out = Is; })...}); } TEST(AccessorsSlotListenerTest, CreateAccessorsSlotListenerCompilationStressTest) { constexpr size_t N = 50; ASSERT_OK_AND_ASSIGN(auto loader, CreateAccessorsSlotListenerManyInputs( std::make_index_sequence<N>())); EXPECT_THAT(loader->SuggestAvailableNames().size(), Eq(N)); } } }
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/io/accessors_slot_listener.h
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/io/accessors_slot_listener_test.cc
1ca990dbeca224035efdabffecc7f3738df6b52c
e323db2b-0e80-4d90-9be3-3874744cbaa2
cpp
google/arolla
delegating_slot_listener
arolla/io/delegating_slot_listener.h
arolla/io/delegating_slot_listener_test.cc
#ifndef AROLLA_IO_DELEGATING_SLOT_LISTENER_H_ #define AROLLA_IO_DELEGATING_SLOT_LISTENER_H_ #include <functional> #include <memory> #include <string> #include <type_traits> #include <utility> #include <vector> #include "absl/base/nullability.h" #include "absl/container/flat_hash_map.h" #include "absl/memory/memory.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "absl/strings/strip.h" #include "arolla/io/input_loader.h" #include "arolla/io/slot_listener.h" #include "arolla/memory/frame.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 { namespace delegating_output_listener_impl { template <class Output, class DelegateOutput> class DelegatingSlotListener final : public SlotListener<Output> { struct PrivateConstructorTag {}; public: template <class Accessor> static absl::StatusOr<std::unique_ptr<SlotListener<Output>>> Build( std::unique_ptr<SlotListener<DelegateOutput>> delegate_listener, const Accessor& accessor, std::string name_prefix) { static_assert(std::is_same_v<decltype(accessor(std::declval<Output*>())), DelegateOutput*>, "Accessor must have `DelegateOutput*` result type."); return absl::make_unique<DelegatingSlotListener>( PrivateConstructorTag{}, std::move(delegate_listener), accessor, std::move(name_prefix)); } absl::Nullable<const QType*> GetQTypeOf( absl::string_view name, absl::Nullable<const QType*> desired_qtype) const final { if (!absl::ConsumePrefix(&name, name_prefix_)) { return nullptr; } return delegate_listener_->GetQTypeOf(name, desired_qtype); } std::vector<std::string> SuggestAvailableNames() const final { std::vector<std::string> names = delegate_listener_->SuggestAvailableNames(); for (auto& name : names) { name = absl::StrCat(name_prefix_, name); } return names; } DelegatingSlotListener( PrivateConstructorTag, std::unique_ptr<SlotListener<DelegateOutput>> delegate_listener, std::function<DelegateOutput*(Output*)> accessor, std::string name_prefix) : delegate_listener_(std::move(delegate_listener)), accessor_(accessor), name_prefix_(name_prefix) {} private: absl::StatusOr<BoundSlotListener<Output>> BindImpl( const absl::flat_hash_map<std::string, TypedSlot>& input_slots) const final { absl::flat_hash_map<std::string, TypedSlot> delegate_input_slots; for (const auto& [name, slot] : input_slots) { absl::string_view name_view = name; if (absl::ConsumePrefix(&name_view, name_prefix_)) { delegate_input_slots.emplace(std::string(name_view), slot); } } ASSIGN_OR_RETURN(BoundSlotListener<DelegateOutput> bound_delegate_listener, delegate_listener_->Bind(delegate_input_slots)); return BoundSlotListener<Output>( [bound_delegate_listener(std::move(bound_delegate_listener)), accessor(accessor_)](ConstFramePtr frame, Output* output) -> absl::Status { return bound_delegate_listener(frame, accessor(output)); }); } std::unique_ptr<SlotListener<DelegateOutput>> delegate_listener_; std::function<DelegateOutput*(Output*)> accessor_; absl::flat_hash_map<std::string, QTypePtr> types_; std::string name_prefix_; }; } template <class Output, class DelegateOutput, class Accessor> absl::StatusOr<std::unique_ptr<SlotListener<Output>>> CreateDelegatingSlotListener( std::unique_ptr<SlotListener<DelegateOutput>> delegate_listener, const Accessor& accessor, std::string name_prefix = "") { return delegating_output_listener_impl::DelegatingSlotListener< Output, DelegateOutput>::Build(std::move(delegate_listener), accessor, std::move(name_prefix)); } } #endif
#include "arolla/io/delegating_slot_listener.h" #include <cstdint> #include <functional> #include <memory> #include <string> #include <utility> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "arolla/io/accessors_slot_listener.h" #include "arolla/io/slot_listener.h" #include "arolla/memory/frame.h" #include "arolla/memory/memory_allocation.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" namespace arolla { namespace { using ::testing::ElementsAre; using ::testing::Eq; struct TestStruct { int a; double b; }; struct OuterTestStruct { TestStruct* a; int b; }; TEST(SlotListenerTest, DelegateSlotListener) { ASSERT_OK_AND_ASSIGN(auto listener_struct, CreateAccessorsSlotListener<TestStruct>( "a", [](int a, TestStruct* s) { s->a = a; }, "b", [](double b, TestStruct* s) { s->b = b; })); auto accessor = [](OuterTestStruct* s) -> TestStruct* { return s->a; }; ASSERT_OK_AND_ASSIGN( std::unique_ptr<SlotListener<OuterTestStruct>> delegate_slot_listener, CreateDelegatingSlotListener<OuterTestStruct>( MakeNotOwningSlotListener(listener_struct.get()), accessor)); ASSERT_OK_AND_ASSIGN( std::unique_ptr<SlotListener<OuterTestStruct>> renamed_delegate_slot_listener, CreateDelegatingSlotListener<OuterTestStruct>( MakeNotOwningSlotListener(listener_struct.get()), accessor, "p_")); for (const auto& [prefix, slot_listener] : std::vector< std::pair<std::string, const SlotListener<OuterTestStruct>*>>{ {"", delegate_slot_listener.get()}, {"p_", renamed_delegate_slot_listener.get()}}) { EXPECT_THAT(slot_listener->GetQTypeOf(prefix + "a"), Eq(GetQType<int32_t>())); EXPECT_THAT(slot_listener->GetQTypeOf(prefix + "b"), Eq(GetQType<double>())); EXPECT_THAT(slot_listener->SuggestAvailableNames(), ElementsAre(prefix + "a", prefix + "b")); FrameLayout::Builder layout_builder; auto a_slot = layout_builder.AddSlot<int>(); auto b_slot = layout_builder.AddSlot<double>(); ASSERT_OK_AND_ASSIGN(BoundSlotListener<OuterTestStruct> bound_slot_listener, slot_listener->Bind({ {prefix + "a", TypedSlot::FromSlot(a_slot)}, {prefix + "b", TypedSlot::FromSlot(b_slot)}, })); FrameLayout memory_layout = std::move(layout_builder).Build(); MemoryAllocation alloc(&memory_layout); alloc.frame().Set(a_slot, 5); alloc.frame().Set(b_slot, 3.5); TestStruct ts; OuterTestStruct ots{&ts, -1}; ASSERT_OK(bound_slot_listener(alloc.frame(), &ots)); EXPECT_EQ(ts.a, 5); EXPECT_EQ(ts.b, 3.5); } } } }
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/io/delegating_slot_listener.h
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/io/delegating_slot_listener_test.cc
1ca990dbeca224035efdabffecc7f3738df6b52c
dd438dc2-0e03-4bc7-a6fb-f4729c4a30fa
cpp
google/arolla
accessors_input_loader
arolla/io/accessors_input_loader.h
arolla/io/accessors_input_loader_test.cc
#ifndef AROLLA_IO_ACCESSORS_INPUT_LOADER_H_ #define AROLLA_IO_ACCESSORS_INPUT_LOADER_H_ #include <cstddef> #include <optional> #include <string> #include <tuple> #include <type_traits> #include <utility> #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 "arolla/io/accessor_helpers.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_slot.h" #include "arolla/util/meta.h" #include "arolla/util/status_macros_backport.h" namespace arolla { template <class Accessor, class Input, class Output> ABSL_ATTRIBUTE_ALWAYS_INLINE inline void InvokeInputLoaderAccessor( const Accessor& accessor, const Input& input, RawBufferFactory* factory, Output* output) { if constexpr (std::is_invocable_v<const Accessor&, const Input&, RawBufferFactory*, Output*>) { accessor(input, factory, output); } else if constexpr (std::is_invocable_v<const Accessor&, const Input&, Output*>) { ((void)(factory)); accessor(input, output); } else if constexpr (std::is_invocable_v<const Accessor&, const Input&, RawBufferFactory*>) { *output = accessor(input, factory); } else if constexpr (std::is_invocable_v<const Accessor&, const Input&>) { ((void)(factory)); *output = accessor(input); } } namespace input_loader_impl { template <class Accessor, class Input> ABSL_ATTRIBUTE_ALWAYS_INLINE inline auto InvokeInputLoaderAccessorTypeMeta() { if constexpr (std::is_invocable_v<const Accessor&, const Input&, RawBufferFactory*>) { return std::invoke_result<const Accessor&, const Input&, RawBufferFactory*>(); } else if constexpr (std::is_invocable_v<const Accessor&, const Input&>) { return std::invoke_result<const Accessor&, const Input&>(); } else { using info = meta::function_traits<std::decay_t<Accessor>>; if constexpr (info::arity == 2) { using Output = std::remove_pointer_t< std::tuple_element_t<1, typename info::arg_types::tuple>>; static_assert(std::is_invocable_v<const Accessor&, const Input&, Output*>, "Unexpected accessor signature."); return meta::type<Output>(); } else { 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&, RawBufferFactory*, Output*>, "Unexpected accessor signature."); return meta::type<Output>(); } } } } template <class Accessor, class Input> using InputLoaderAccessorResultType = std::decay_t< typename decltype(input_loader_impl::InvokeInputLoaderAccessorTypeMeta< const Accessor&, const Input&>())::type>; namespace input_loader_impl { template <class Input, class NameAccessorsTuple> class AccessorsInputLoader; template <class Input, class Accessor> class Setter { public: using ResultType = InputLoaderAccessorResultType<Accessor, Input>; Setter(std::optional<FrameLayout::Slot<ResultType>> slot, Accessor accessor) : slot_(slot), accessor_(std::move(accessor)) {} static absl::StatusOr<Setter> Build(std::optional<TypedSlot> slot, const Accessor& accessor) { if (slot.has_value()) { ASSIGN_OR_RETURN(auto specific_slot, slot->ToSlot<ResultType>()); return {Setter({specific_slot}, accessor)}; } else { return {Setter(std::nullopt, accessor)}; } } void operator()(const Input& input, FramePtr frame, RawBufferFactory* factory) const { if (slot_.has_value()) { InvokeInputLoaderAccessor(accessor_, input, factory, frame.GetMutable(*slot_)); } } private: std::optional<FrameLayout::Slot<ResultType>> slot_; Accessor accessor_; }; template <class Input, class... Accessors> class AccessorsInputLoader<Input, std::tuple<std::pair<std::string, Accessors>...>> final : public StaticInputLoader<Input> { using NameAccessorsTuple = std::tuple<std::pair<std::string, Accessors>...>; public: static absl::StatusOr<InputLoaderPtr<Input>> Build( NameAccessorsTuple accessors) { auto output_types_in_order = CreateOutputTypesInOrder( accessors, std::make_index_sequence<std::tuple_size<NameAccessorsTuple>::value>{}); RETURN_IF_ERROR(ValidateDuplicatedNames(output_types_in_order)); return InputLoaderPtr<Input>( static_cast<InputLoader<Input>*>(new AccessorsInputLoader( std::move(accessors), std::move(output_types_in_order)))); } absl::StatusOr<BoundInputLoader<Input>> BindImpl( const absl::flat_hash_map<std::string, TypedSlot>& output_slots) const final { ASSIGN_OR_RETURN(auto slots, MaybeFindSlotsAndVerifyTypes( this->types_in_order(), output_slots)); return BindImpl( std::move(slots), std::make_index_sequence<std::tuple_size<NameAccessorsTuple>::value>{}); } private: explicit AccessorsInputLoader( NameAccessorsTuple accessors, std::vector<std::pair<std::string, QTypePtr>> output_types_in_order) : StaticInputLoader<Input>(std::move(output_types_in_order)), accessors_(std::move(accessors)) {} template <size_t I> using Accessor = std::tuple_element_t<1, std::tuple_element_t<I, NameAccessorsTuple>>; template <size_t I> using InputLoaderAccessorResultType = InputLoaderAccessorResultType<Accessor<I>, Input>; template <size_t I> const Accessor<I>& GetAccessor() const { return std::get<1>(std::get<I>(accessors_)); } template <size_t I> static QTypePtr GetOutputType() { return GetQType<InputLoaderAccessorResultType<I>>(); } template <size_t... Is> static std::vector<std::pair<std::string, QTypePtr>> CreateOutputTypesInOrder( const NameAccessorsTuple& accessors, std::index_sequence<Is...>) { return {{std::string(std::get<0>(std::get<Is>(accessors))), GetOutputType<Is>()}...}; } template <size_t... Is> absl::StatusOr<BoundInputLoader<Input>> BindImpl( std::vector<std::optional<TypedSlot>> slots, std::index_sequence<Is...>) const { auto setters_or = LiftStatusUp( Setter<Input, Accessor<Is>>::Build(slots[Is], GetAccessor<Is>())...); ASSIGN_OR_RETURN(auto setters, setters_or); return BoundInputLoader<Input>( [setters_(std::move(setters))]( const Input& input ABSL_ATTRIBUTE_UNUSED, FramePtr frame ABSL_ATTRIBUTE_UNUSED, RawBufferFactory* factory ABSL_ATTRIBUTE_UNUSED) { (std::get<Is>(setters_)(input, frame, factory), ...); return absl::OkStatus(); }); } NameAccessorsTuple accessors_; }; } template <class Input, class NameAccessorsTuple> using AccessorsInputLoader = input_loader_impl::AccessorsInputLoader<Input, NameAccessorsTuple>; template <class Input, class... Accessors> absl::StatusOr<InputLoaderPtr<Input>> CreateAccessorsInputLoaderFromTuple( std::tuple<std::pair<std::string, Accessors>...> name_accessors) { return AccessorsInputLoader<Input, decltype(name_accessors)>::Build( std::move(name_accessors)); } template <class Input, class... NameAccessors> absl::StatusOr<InputLoaderPtr<Input>> CreateAccessorsInputLoader( NameAccessors... name_accessors) { return CreateAccessorsInputLoaderFromTuple<Input>( accessor_helpers_impl::ConvertNameAccessorsPackToNestedTuple( name_accessors...)); } } #endif
#include "arolla/io/accessors_input_loader.h" #include <cstddef> #include <cstdint> #include <functional> #include <memory> #include <string> #include <tuple> #include <type_traits> #include <utility> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/container/flat_hash_map.h" #include "absl/status/status.h" #include "absl/status/status_matchers.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.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/raw_buffer_factory.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" namespace arolla { namespace { using ::absl_testing::StatusIs; using ::arolla::testing::InputLoaderSupports; using ::testing::HasSubstr; using ::testing::Pair; using ::testing::UnorderedElementsAre; struct TestStruct { int a; double b; }; struct GetAConstRef { const int& operator()(const TestStruct& s) const { return s.a; } }; struct GetBValue { double operator()(const TestStruct& s) const { return s.b; } }; struct GetBValueViaOutputArg { void operator()(const TestStruct& s, double* res) const { *res = s.b; } }; struct GetBValueViaOutputArgWithRawBufferFactory { void operator()(const TestStruct& s, RawBufferFactory*, double* res) const { *res = s.b; } }; TEST(InputLoaderTest, InputLoaderAccessorResultType) { static_assert( std::is_same_v<InputLoaderAccessorResultType<GetAConstRef, TestStruct>, int>); static_assert( std::is_same_v<InputLoaderAccessorResultType<GetBValue, TestStruct>, double>); static_assert( std::is_same_v< InputLoaderAccessorResultType<GetBValueViaOutputArg, TestStruct>, double>); static_assert( std::is_same_v<InputLoaderAccessorResultType< GetBValueViaOutputArgWithRawBufferFactory, TestStruct>, double>); } TEST(InputLoaderTest, AccessorsInputLoader) { auto i32 = GetQType<int32_t>(); auto f64 = GetQType<double>(); auto accessors_tuple = std::make_tuple( std::make_pair(std::string("a"), GetAConstRef{}), std::make_pair(std::string("b"), GetBValue{}), std::make_pair(std::string("b2"), GetBValueViaOutputArg{}), std::make_pair(std::string("b3"), GetBValueViaOutputArgWithRawBufferFactory{})); ASSERT_OK_AND_ASSIGN( auto input_loader, (AccessorsInputLoader<TestStruct, decltype(accessors_tuple)>::Build( accessors_tuple))); EXPECT_THAT( input_loader, InputLoaderSupports({{"a", i32}, {"b", f64}, {"b2", f64}, {"b3", f64}})); { FrameLayout::Builder layout_builder; layout_builder.AddSlot<double>(); auto a_slot = layout_builder.AddSlot<int>(); layout_builder.AddSlot<char>(); auto b_slot = layout_builder.AddSlot<double>(); layout_builder.AddSlot<std::string>(); auto b2_slot = layout_builder.AddSlot<double>(); layout_builder.AddSlot<int16_t>(); auto b3_slot = layout_builder.AddSlot<double>(); ASSERT_OK_AND_ASSIGN(BoundInputLoader<TestStruct> bound_input_loader, input_loader->Bind({ {"a", TypedSlot::FromSlot(a_slot)}, {"b", TypedSlot::FromSlot(b_slot)}, {"b2", TypedSlot::FromSlot(b2_slot)}, {"b3", TypedSlot::FromSlot(b3_slot)}, })); FrameLayout memory_layout = std::move(layout_builder).Build(); 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(b2_slot), 3.5); EXPECT_EQ(alloc.frame().Get(b3_slot), 3.5); } { FrameLayout::Builder layout_builder; layout_builder.AddSlot<std::string>(); auto a_slot = layout_builder.AddSlot<int>(); layout_builder.AddSlot<char>(); ASSERT_OK_AND_ASSIGN(BoundInputLoader<TestStruct> 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({5, 3.5}, alloc.frame())); EXPECT_EQ(alloc.frame().Get(a_slot), 5); } { FrameLayout::Builder layout_builder; layout_builder.AddSlot<std::string>(); auto b_slot = layout_builder.AddSlot<double>(); layout_builder.AddSlot<char>(); ASSERT_OK_AND_ASSIGN(BoundInputLoader<TestStruct> bound_input_loader, input_loader->Bind({ {"b", TypedSlot::FromSlot(b_slot)}, })); FrameLayout memory_layout = std::move(layout_builder).Build(); MemoryAllocation alloc(&memory_layout); ASSERT_OK(bound_input_loader({5, 3.5}, alloc.frame())); EXPECT_EQ(alloc.frame().Get(b_slot), 3.5); } } struct GetWithFactoryWithHelper { void operator()(const TestStruct& s, RawBufferFactory*, double* res) const { *res = 1; } double operator()(const TestStruct& s, RawBufferFactory*) const { return 3; } }; struct GetWithoutFactoryWithHelper { void operator()(const TestStruct& s, double* res) const { *res = 2; } double operator()(const TestStruct& s) const { return 4; } }; struct GetWithAllVariantsHelper { void operator()(const TestStruct& s, RawBufferFactory*, double* res) const { *res = 1; } double operator()(const TestStruct& s, RawBufferFactory*) const { return 3; } void operator()(const TestStruct& s, double* res) const { *res = 2; } double operator()(const TestStruct& s) const { return 4; } }; TEST(InputLoaderTest, AccessorsInputLoaderChooseRightSignature) { auto f64 = GetQType<double>(); auto accessors_tuple = std::make_tuple( std::make_pair(std::string("a"), GetWithFactoryWithHelper{}), std::make_pair(std::string("b"), GetWithoutFactoryWithHelper{}), std::make_pair(std::string("c"), GetWithAllVariantsHelper{})); ASSERT_OK_AND_ASSIGN( auto input_loader, (AccessorsInputLoader<TestStruct, decltype(accessors_tuple)>::Build( accessors_tuple))); EXPECT_THAT(input_loader, InputLoaderSupports({{"a", f64}, {"b", f64}, {"c", f64}})); FrameLayout::Builder layout_builder; auto a_slot = layout_builder.AddSlot<double>(); auto b_slot = layout_builder.AddSlot<double>(); auto c_slot = layout_builder.AddSlot<double>(); ASSERT_OK_AND_ASSIGN(BoundInputLoader<TestStruct> 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({0, 0}, alloc.frame())); EXPECT_EQ(alloc.frame().Get(a_slot), 1); EXPECT_EQ(alloc.frame().Get(b_slot), 2); EXPECT_EQ(alloc.frame().Get(c_slot), 1); } TEST(InputLoaderTest, AccessorsInputLoaderPartialBind) { ASSERT_OK_AND_ASSIGN(auto input_loader, CreateAccessorsInputLoader<TestStruct>( "a", GetAConstRef{}, "b", GetBValue{})); { FrameLayout::Builder layout_builder; auto ignored_slot = layout_builder.AddSlot<int>(); auto b_slot = layout_builder.AddSlot<double>(); layout_builder.AddSlot<char>(); absl::flat_hash_map<std::string, TypedSlot> slots = { {"b", TypedSlot::FromSlot(b_slot)}, {"ignored", TypedSlot::FromSlot(ignored_slot)}}; EXPECT_THAT(input_loader->Bind(slots), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("unknown inputs: ignored"))); ASSERT_OK_AND_ASSIGN(auto bound_input_loader, input_loader->PartialBind(&slots)); EXPECT_THAT(slots, UnorderedElementsAre( Pair("ignored", TypedSlot::FromSlot(ignored_slot)))); FrameLayout memory_layout = std::move(layout_builder).Build(); MemoryAllocation alloc(&memory_layout); ASSERT_OK(bound_input_loader({5, 3.5}, alloc.frame())); EXPECT_EQ(alloc.frame().Get(b_slot), 3.5); EXPECT_EQ(alloc.frame().Get(ignored_slot), 0); } { FrameLayout::Builder layout_builder; auto ignored_a_slot = layout_builder.AddSlot<int>(); auto ignored_b_slot = layout_builder.AddSlot<int>(); auto a_slot = layout_builder.AddSlot<int>(); auto b_slot = layout_builder.AddSlot<double>(); layout_builder.AddSlot<char>(); absl::flat_hash_map<std::string, TypedSlot> slots = { {"a", TypedSlot::FromSlot(a_slot)}, {"b", TypedSlot::FromSlot(b_slot)}, {"ignored_a", TypedSlot::FromSlot(ignored_a_slot)}, {"ignored_b", TypedSlot::FromSlot(ignored_b_slot)}, }; EXPECT_THAT(input_loader->Bind(slots), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("unknown inputs: ignored_a, ignored_b"))); ASSERT_OK_AND_ASSIGN(auto bound_input_loader, input_loader->PartialBind(&slots)); EXPECT_THAT(slots, UnorderedElementsAre( Pair("ignored_a", TypedSlot::FromSlot(ignored_a_slot)), Pair("ignored_b", TypedSlot::FromSlot(ignored_b_slot)))); FrameLayout memory_layout = std::move(layout_builder).Build(); 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(ignored_a_slot), 0); EXPECT_EQ(alloc.frame().Get(ignored_b_slot), 0); } } TEST(InputLoaderTest, NameDuplicates) { auto accessors_tuple = std::make_tuple(std::make_pair(std::string("a"), GetAConstRef{}), std::make_pair(std::string("c"), GetAConstRef{}), std::make_pair(std::string("a"), GetBValue{}), std::make_pair(std::string("b"), GetAConstRef{}), std::make_pair(std::string("c"), GetAConstRef{})); using Loader = AccessorsInputLoader<TestStruct, decltype(accessors_tuple)>; EXPECT_THAT(Loader::Build(accessors_tuple), StatusIs(absl::StatusCode::kFailedPrecondition, HasSubstr("accessors have duplicated names: a, c"))); } TEST(InputLoaderTest, Errors) { auto accessors_tuple = std::make_tuple(std::make_pair(std::string("a"), GetAConstRef{})); ASSERT_OK_AND_ASSIGN( auto input_loader, (AccessorsInputLoader<TestStruct, decltype(accessors_tuple)>::Build( accessors_tuple))); { FrameLayout::Builder layout_builder; auto dslot = layout_builder.AddSlot<double>(); EXPECT_THAT( input_loader ->Bind({ {"a", TypedSlot::FromSlot(dslot)}, }) .status(), StatusIs( absl::StatusCode::kFailedPrecondition, HasSubstr( "slot types mismatch: a{expected:INT32, actual:FLOAT64}"))); } } TEST(InputLoaderTest, CreateAccessorsInputLoader) { auto i32 = GetQType<int32_t>(); auto f64 = GetQType<double>(); ASSERT_OK_AND_ASSIGN(auto input_loader, CreateAccessorsInputLoader<TestStruct>( "a", [](const TestStruct& s) { return s.a; }, "b", [](const TestStruct& s) { return s.b; }, "c", [](const TestStruct& s) { return s.b * s.b; })); EXPECT_THAT(input_loader, InputLoaderSupports({{"a", i32}, {"b", f64}, {"c", f64}})); 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>(); ASSERT_OK_AND_ASSIGN(BoundInputLoader<TestStruct> 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({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, AccessorsInputLoaderBufferFactoryPropagated) { auto qbool = GetQType<bool>(); UnsafeArenaBufferFactory global_factory(1000); ASSERT_OK_AND_ASSIGN( auto input_loader, CreateAccessorsInputLoader<TestStruct>( "a", [&global_factory](const TestStruct&, RawBufferFactory* factory) { return &global_factory == factory; })); EXPECT_THAT(input_loader, InputLoaderSupports({{"a", qbool}})); FrameLayout::Builder layout_builder; auto a_slot = layout_builder.AddSlot<bool>(); ASSERT_OK_AND_ASSIGN(BoundInputLoader<TestStruct> 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({5, 3.5}, alloc.frame(), &global_factory)); EXPECT_TRUE(alloc.frame().Get(a_slot)); UnsafeArenaBufferFactory global_factory2(1000); ASSERT_OK(bound_input_loader({5, 3.5}, alloc.frame(), &global_factory2)); EXPECT_FALSE(alloc.frame().Get(a_slot)); } using PairStringFunction = std::pair<std::string, std::function<int(int)>>; template <size_t> using PairStringFunctionByInt = PairStringFunction; template <size_t... Is> absl::StatusOr<std::unique_ptr<InputLoader<int>>> CreateAccessorsInputLoaderManyInputs(std::index_sequence<Is...>) { using T = std::tuple<PairStringFunctionByInt<Is>...>; return CreateAccessorsInputLoaderFromTuple<int>( T{PairStringFunction(absl::StrCat(Is), [](int) { return Is; })...}); } TEST(InputLoaderTest, CreateAccessorsInputLoaderCompilationStressTest) { constexpr size_t N = 50; ASSERT_OK_AND_ASSIGN(auto loader, CreateAccessorsInputLoaderManyInputs( std::make_index_sequence<N>())); EXPECT_THAT(loader, InputLoaderSupports({{"1", GetQType<int>()}, {"2", GetQType<int>()}, {"49", GetQType<int>()}})); } } }
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/io/accessors_input_loader.h
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/io/accessors_input_loader_test.cc
1ca990dbeca224035efdabffecc7f3738df6b52c
cdb712dc-200b-4711-ab75-2e714a826f2e
cpp
google/arolla
matchers
arolla/jagged_shape/testing/matchers.h
arolla/jagged_shape/testing/matchers_test.cc
#ifndef AROLLA_JAGGED_SHAPE_TESTING_MATCHERS_H_ #define AROLLA_JAGGED_SHAPE_TESTING_MATCHERS_H_ #include <ostream> #include "gtest/gtest.h" #include "arolla/jagged_shape/jagged_shape.h" #include "arolla/util/repr.h" namespace arolla::testing { namespace matchers_impl { template <typename Edge> class JaggedShapeEquivalentToMatcher { public: using is_gtest_matcher = void; explicit JaggedShapeEquivalentToMatcher(JaggedShape<Edge> expected_shape) : expected_shape_(std::move(expected_shape)) {} bool MatchAndExplain(const JaggedShape<Edge>& shape, ::testing::MatchResultListener* listener) const { bool is_equivalent = shape.IsEquivalentTo(expected_shape_); *listener << Repr(shape) << (is_equivalent ? " which is equivalent" : " which is not equivalent"); return is_equivalent; } void DescribeTo(::std::ostream* os) const { *os << "is equivalent to " << Repr(expected_shape_); } void DescribeNegationTo(::std::ostream* os) const { *os << "is not equivalent to " << Repr(expected_shape_); } private: JaggedShape<Edge> expected_shape_; }; } template <typename Edge> auto IsEquivalentTo(const JaggedShape<Edge>& expected_shape) { return matchers_impl::JaggedShapeEquivalentToMatcher<Edge>(expected_shape); } } #endif
#include "arolla/jagged_shape/testing/matchers.h" #include <cstdint> #include <string> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "arolla/dense_array/dense_array.h" #include "arolla/dense_array/edge.h" #include "arolla/jagged_shape/dense_array/jagged_shape.h" namespace arolla { namespace { using ::arolla::testing::IsEquivalentTo; using ::testing::Eq; using ::testing::Not; using ::testing::StringMatchResultListener; template <typename MatcherType, typename Value> std::string Explain(const MatcherType& m, const Value& x) { StringMatchResultListener listener; ExplainMatchResult(m, x, &listener); return listener.str(); } TEST(QTypeTest, JaggedShapeIsEquivalentTo) { ASSERT_OK_AND_ASSIGN(auto edge1, DenseArrayEdge::FromSplitPoints( CreateDenseArray<int64_t>({0, 2}))); ASSERT_OK_AND_ASSIGN(auto edge2, DenseArrayEdge::FromSplitPoints( CreateDenseArray<int64_t>({0, 1, 3}))); ASSERT_OK_AND_ASSIGN(auto shape1, JaggedDenseArrayShape::FromEdges({edge1, edge2})); ASSERT_OK_AND_ASSIGN(auto edge3, DenseArrayEdge::FromSplitPoints( CreateDenseArray<int64_t>({0, 1, 4}))); ASSERT_OK_AND_ASSIGN(auto shape2, JaggedDenseArrayShape::FromEdges({edge1, edge3})); EXPECT_THAT(shape1, IsEquivalentTo(shape1)); EXPECT_THAT(shape1, Not(IsEquivalentTo(shape2))); auto m = IsEquivalentTo(shape1); EXPECT_THAT(::testing::DescribeMatcher<JaggedDenseArrayShape>(m), Eq("is equivalent to JaggedShape(2, [1, 2])")); EXPECT_THAT( ::testing::DescribeMatcher<JaggedDenseArrayShape>(m, true), Eq("is not equivalent to JaggedShape(2, [1, 2])")); EXPECT_THAT(Explain(m, shape1), Eq("JaggedShape(2, [1, 2]) which is equivalent")); EXPECT_THAT(Explain(m, shape2), Eq("JaggedShape(2, [1, 3]) which is not equivalent")); } } }
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/jagged_shape/testing/matchers.h
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/jagged_shape/testing/matchers_test.cc
1ca990dbeca224035efdabffecc7f3738df6b52c
2f8254e7-a889-490a-8574-026b6151b216
cpp
google/arolla
registration
arolla/expr/operators/registration.h
arolla/expr/operators/registration_test.cc
#ifndef AROLLA_EXPR_OPERATORS_REGISTRATION_H_ #define AROLLA_EXPR_OPERATORS_REGISTRATION_H_ #include <type_traits> #include "absl/base/no_destructor.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_operator.h" #include "arolla/util/status_macros_backport.h" namespace arolla::expr_operators { #define AROLLA_DECLARE_EXPR_OPERATOR(op_function_name) \ absl::StatusOr<::arolla::expr::ExprOperatorPtr> Get##op_function_name(); \ inline absl::Status Register##op_function_name() { \ return Get##op_function_name().status(); \ } \ template <typename... Args> \ std::enable_if_t<(std::is_convertible_v< \ Args, absl::StatusOr<::arolla::expr::ExprNodePtr>> && \ ...), \ absl::StatusOr<::arolla::expr::ExprNodePtr>> \ op_function_name(Args... args) { \ ASSIGN_OR_RETURN(auto op, Get##op_function_name()); \ return ::arolla::expr::CallOp(op, {args...}); \ } #define AROLLA_DEFINE_EXPR_OPERATOR(op_function_name, registration_call) \ absl::StatusOr<::arolla::expr::ExprOperatorPtr> Get##op_function_name() { \ static const absl::NoDestructor< \ absl::StatusOr<::arolla::expr::ExprOperatorPtr>> \ registered(registration_call); \ return *registered; \ } } #endif
#include "arolla/expr/operators/registration.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "absl/status/status_matchers.h" #include "arolla/expr/expr.h" #include "arolla/expr/lambda_expr_operator.h" #include "arolla/expr/operators/type_meta_eval_strategies.h" #include "arolla/expr/registered_expr_operator.h" namespace arolla::expr_operators { namespace { using ::absl_testing::IsOk; using ::absl_testing::StatusIs; using ::arolla::expr::CallOp; using ::arolla::expr::Literal; using ::arolla::expr::MakeLambdaOperator; using ::arolla::expr::Placeholder; using ::arolla::expr::RegisterOperator; using ::arolla::expr_operators::RegisterBackendOperator; using ::arolla::expr_operators::type_meta::Unary; using ::testing::HasSubstr; AROLLA_DECLARE_EXPR_OPERATOR(TestBackendOp); AROLLA_DEFINE_EXPR_OPERATOR(TestBackendOp, RegisterBackendOperator("test.backend_op", Unary)); AROLLA_DECLARE_EXPR_OPERATOR(TestHigherLevelOp); AROLLA_DEFINE_EXPR_OPERATOR( TestHigherLevelOp, RegisterOperator("test.higher_level_op", MakeLambdaOperator(CallOp("test.backend_op", {Placeholder("x")})))); AROLLA_DECLARE_EXPR_OPERATOR(TestBrokenOp); AROLLA_DEFINE_EXPR_OPERATOR( TestBrokenOp, RegisterOperator("test.broken_op", MakeLambdaOperator(CallOp("test.unregistered_op", {Placeholder("x")})))); TEST(RegistrationTest, RegistrationMacros) { EXPECT_THAT(CallOp("test.higher_level_op", {Literal(1.0)}), StatusIs(absl::StatusCode::kNotFound, HasSubstr("operator 'test.higher_level_op' not found"))); ASSERT_THAT(RegisterTestBackendOp(), IsOk()); ASSERT_THAT(RegisterTestHigherLevelOp(), IsOk()); EXPECT_THAT(CallOp("test.higher_level_op", {Literal(1.0)}), IsOk()); EXPECT_THAT(RegisterTestBrokenOp(), StatusIs(absl::StatusCode::kNotFound, HasSubstr("operator 'test.unregistered_op' not found"))); } } }
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/expr/operators/registration.h
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/expr/operators/registration_test.cc
1ca990dbeca224035efdabffecc7f3738df6b52c
3b869489-1ef2-4403-9e89-15493ab32680
cpp
google/arolla
thread_safe_model_executor
arolla/expr/eval/thread_safe_model_executor.h
arolla/expr/eval/thread_safe_model_executor_test.cc
#ifndef AROLLA_EXPR_EVAL_THREAD_SAFE_MODEL_EXECUTOR_H_ #define AROLLA_EXPR_EVAL_THREAD_SAFE_MODEL_EXECUTOR_H_ #include <cstddef> #include <memory> #include <optional> #include <vector> #include "absl/base/thread_annotations.h" #include "absl/log/check.h" #include "absl/status/statusor.h" #include "absl/synchronization/mutex.h" #include "arolla/expr/eval/model_executor.h" #include "arolla/util/threadlocal.h" #include "arolla/util/status_macros_backport.h" namespace arolla::expr { template <typename Input, typename Output, typename SideOutput = void> class ThreadSafeModelExecutor { using WrappedModelExecutor = ModelExecutor<Input, Output, SideOutput>; public: explicit ThreadSafeModelExecutor(WrappedModelExecutor&& prototype_executor) : prototype_executor_(std::make_shared<WrappedModelExecutor>( std::move(prototype_executor))), thread_local_executor_( std::make_shared< ThreadLocal<std::optional<WrappedModelExecutor>>>()) {} absl::StatusOr<Output> operator()(const ModelEvaluationOptions& options, const Input& input, SideOutput* side_output) const { return Execute(options, input, side_output); } absl::StatusOr<Output> operator()(const ModelEvaluationOptions& options, const Input& input) const { return Execute(options, input); } absl::StatusOr<Output> operator()(const Input& input, SideOutput* side_output) const { return Execute({}, input, side_output); } absl::StatusOr<Output> operator()(const Input& input) const { return Execute({}, input); } absl::StatusOr<Output> Execute(const ModelEvaluationOptions& options, const Input& input, SideOutput* side_output = nullptr) const { DCHECK(IsValid()); std::optional<WrappedModelExecutor>& local_executor = *thread_local_executor_->pointer(); if (!local_executor.has_value()) { ASSIGN_OR_RETURN(local_executor, prototype_executor_->Clone()); } return local_executor->Execute(options, input, side_output); } absl::StatusOr<Output> Execute(const Input& input, SideOutput* side_output = nullptr) const { return Execute({}, input, side_output); } bool IsValid() const { return thread_local_executor_ != nullptr && prototype_executor_ != nullptr && prototype_executor_->IsValid(); } private: std::shared_ptr<const WrappedModelExecutor> prototype_executor_; std::shared_ptr<ThreadLocal<std::optional<WrappedModelExecutor>>> thread_local_executor_; }; template <typename Input, typename Output, typename SideOutput = void> class ThreadSafePoolModelExecutor { using WrappedModelExecutor = ModelExecutor<Input, Output, SideOutput>; public: static constexpr size_t kDefaultMaximumCacheSize = 400; explicit ThreadSafePoolModelExecutor( WrappedModelExecutor&& prototype_executor, size_t maximum_cache_size = kDefaultMaximumCacheSize) : shared_data_(std::make_shared<SharedData>( maximum_cache_size, std::move(prototype_executor))) {} absl::StatusOr<Output> operator()(const ModelEvaluationOptions& options, const Input& input, SideOutput* side_output) const { return Execute(options, input, side_output); } absl::StatusOr<Output> operator()(const ModelEvaluationOptions& options, const Input& input) const { return Execute(options, input); } absl::StatusOr<Output> operator()(const Input& input, SideOutput* side_output) const { return Execute({}, input, side_output); } absl::StatusOr<Output> operator()(const Input& input) const { return Execute({}, input); } bool IsValid() const { return shared_data_ != nullptr && shared_data_->prototype_executor.IsValid(); } private: absl::StatusOr<Output> Execute(const ModelEvaluationOptions& options, const Input& input, SideOutput* side_output = nullptr) const { DCHECK(IsValid()); std::unique_ptr<WrappedModelExecutor> local_executor; if (shared_data_->maximum_cache_size != 0) { absl::MutexLock l(&shared_data_->mutex); if (!shared_data_->executors_pool.empty()) { local_executor = std::move(shared_data_->executors_pool.back()); shared_data_->executors_pool.pop_back(); } } if (local_executor == nullptr) { ASSIGN_OR_RETURN(auto new_executor, shared_data_->prototype_executor.Clone()); local_executor = std::make_unique<WrappedModelExecutor>(std::move(new_executor)); } auto result = local_executor->Execute(options, input, side_output); if (shared_data_->maximum_cache_size != 0) { absl::MutexLock l(&shared_data_->mutex); if (shared_data_->executors_pool.size() < shared_data_->maximum_cache_size) { shared_data_->executors_pool.emplace_back(std::move(local_executor)); } } return result; } struct SharedData { SharedData(size_t maximum_cache_size, WrappedModelExecutor prototype_executor) : maximum_cache_size(maximum_cache_size), prototype_executor(std::move(prototype_executor)) {} size_t maximum_cache_size; WrappedModelExecutor prototype_executor; absl::Mutex mutex; std::vector<std::unique_ptr<WrappedModelExecutor>> executors_pool ABSL_GUARDED_BY(mutex); }; std::shared_ptr<SharedData> shared_data_; }; template <typename Input, typename Output, typename SideOutput = void> class CopyableThreadUnsafeModelExecutor { using WrappedModelExecutor = ModelExecutor<Input, Output, SideOutput>; public: explicit CopyableThreadUnsafeModelExecutor( WrappedModelExecutor&& prototype_executor) : model_executor_(std::move(prototype_executor)) {} CopyableThreadUnsafeModelExecutor( const CopyableThreadUnsafeModelExecutor& other) : model_executor_(other.model_executor_.ok() ? other.model_executor_->Clone() : other.model_executor_.status()) {} CopyableThreadUnsafeModelExecutor& operator=( const CopyableThreadUnsafeModelExecutor& other) { model_executor_ = other.model_executor_.ok() ? other.model_executor_->Clone() : other.model_executor_.status(); return *this; } CopyableThreadUnsafeModelExecutor(CopyableThreadUnsafeModelExecutor&&) = default; CopyableThreadUnsafeModelExecutor& operator=( CopyableThreadUnsafeModelExecutor&&) = default; absl::StatusOr<Output> operator()(const ModelEvaluationOptions& options, const Input& input, SideOutput* side_output) const { return Execute(options, input, side_output); } absl::StatusOr<Output> operator()(const ModelEvaluationOptions& options, const Input& input) const { return Execute(options, input); } absl::StatusOr<Output> operator()(const Input& input, SideOutput* side_output) const { return Execute({}, input, side_output); } absl::StatusOr<Output> operator()(const Input& input) const { return Execute({}, input); } bool IsValid() const { return model_executor_.ok() && model_executor_->IsValid(); } private: absl::StatusOr<Output> Execute(const ModelEvaluationOptions& options, const Input& input, SideOutput* side_output = nullptr) const { RETURN_IF_ERROR(model_executor_.status()); return model_executor_->Execute(options, input, side_output); } mutable absl::StatusOr<WrappedModelExecutor> model_executor_; }; } #endif
#include "arolla/expr/eval/thread_safe_model_executor.h" #include <cstdint> #include <functional> #include <future> #include <numeric> #include <utility> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/container/flat_hash_set.h" #include "absl/status/status_matchers.h" #include "absl/status/statusor.h" #include "arolla/dense_array/dense_array.h" #include "arolla/dense_array/qtype/types.h" #include "arolla/expr/eval/model_executor.h" #include "arolla/expr/expr.h" #include "arolla/io/accessors_input_loader.h" #include "arolla/io/input_loader.h" namespace arolla::expr { namespace { constexpr int kNumIterations = 100; constexpr int kNumThreads = 10; using ::absl_testing::IsOkAndHolds; using ::testing::IsFalse; using ::testing::IsTrue; using ::testing::UnorderedElementsAreArray; struct TestInput { int64_t x; }; absl::StatusOr<std::unique_ptr<InputLoader<TestInput>>> CreateTestInputsLoader() { return CreateAccessorsInputLoader<TestInput>( "x", [](const TestInput& in) { return in.x; }); } absl::StatusOr<std::unique_ptr<InputLoader<TestInput>>> CreateDenseArrayTestInputsLoader() { return CreateAccessorsInputLoader<TestInput>("x", [](const TestInput& in) { return CreateDenseArray<int64_t>({in.x, in.x, in.x}); }); } std::vector<int64_t> Iota(int64_t num_elements) { std::vector<int64_t> result(num_elements); std::iota(result.begin(), result.end(), 0); return result; } template <template <typename I, typename O, typename S> typename ME, typename Input, typename Output, typename SideOutput> std::vector<absl::StatusOr<Output>> RunManyThreadFunc( int thread_nr, const ME<Input, Output, SideOutput>& executor) { std::vector<absl::StatusOr<Output>> results; for (int j = 0; j < kNumIterations; ++j) { results.emplace_back( std::move(executor(TestInput{thread_nr * kNumIterations + j}))); } return results; } template <template <typename I, typename O, typename S> typename ME, typename Input, typename Output, typename SideOutput> std::vector<absl::StatusOr<Output>> RunMany( const ME<Input, Output, SideOutput>& executor, bool copy_for_each_thread) { std::vector<std::future<std::vector<absl::StatusOr<Output>>>> futures; for (int i = 0; i < kNumThreads; ++i) { std::function<std::vector<absl::StatusOr<Output>>()> thread_func; if (copy_for_each_thread) { thread_func = [i, executor]() { return RunManyThreadFunc(i, executor); }; } else { thread_func = [i, &executor]() { return RunManyThreadFunc(i, executor); }; } futures.push_back(std::async(std::launch::async, thread_func)); } std::vector<absl::StatusOr<Output>> results; for (auto& future : futures) { auto thread_results = future.get(); results.insert(results.end(), thread_results.begin(), thread_results.end()); } return results; } TEST(ThreadSafeModelExecutorTest, Move) { auto ast = Leaf("x"); ASSERT_OK_AND_ASSIGN(auto input_loader, CreateTestInputsLoader()); ASSERT_OK_AND_ASSIGN(auto executor, (CompileModelExecutor<int64_t>(ast, *input_loader))); ThreadSafeModelExecutor<TestInput, int64_t> thread_safe_executor( std::move(executor)); ASSERT_THAT(thread_safe_executor.IsValid(), IsTrue()); EXPECT_THAT(thread_safe_executor(TestInput{57}), IsOkAndHolds(57)); ThreadSafeModelExecutor<TestInput, int64_t> other_thread_safe_executor( std::move(thread_safe_executor)); ASSERT_THAT(other_thread_safe_executor.IsValid(), IsTrue()); EXPECT_THAT(other_thread_safe_executor(TestInput{57}), IsOkAndHolds(57)); EXPECT_THAT(thread_safe_executor.IsValid(), IsFalse()); thread_safe_executor = std::move(other_thread_safe_executor); ASSERT_THAT(thread_safe_executor.IsValid(), IsTrue()); EXPECT_THAT(thread_safe_executor(TestInput{57}), IsOkAndHolds(57)); EXPECT_THAT(other_thread_safe_executor.IsValid(), IsFalse()); } TEST(ThreadSafeModelExecutorTest, Copy) { auto ast = Leaf("x"); ASSERT_OK_AND_ASSIGN(auto input_loader, CreateTestInputsLoader()); ASSERT_OK_AND_ASSIGN(auto executor, (CompileModelExecutor<int64_t>(ast, *input_loader))); ThreadSafeModelExecutor<TestInput, int64_t> thread_safe_executor( std::move(executor)); ASSERT_THAT(thread_safe_executor.IsValid(), IsTrue()); EXPECT_THAT(thread_safe_executor(TestInput{57}), IsOkAndHolds(57)); ThreadSafeModelExecutor<TestInput, int64_t> other_thread_safe_executor( thread_safe_executor); ASSERT_THAT(other_thread_safe_executor.IsValid(), IsTrue()); EXPECT_THAT(other_thread_safe_executor(TestInput{57}), IsOkAndHolds(57)); EXPECT_THAT(thread_safe_executor.IsValid(), IsTrue()); } TEST(ThreadSafeModelExecutorTest, ExecuteOnce) { auto ast = Leaf("x"); ASSERT_OK_AND_ASSIGN(auto input_loader, CreateTestInputsLoader()); ASSERT_OK_AND_ASSIGN(auto executor, (CompileModelExecutor<int64_t>(ast, *input_loader))); ThreadSafeModelExecutor<TestInput, int64_t> thread_safe_executor( std::move(executor)); EXPECT_THAT(thread_safe_executor(TestInput{57}), IsOkAndHolds(57)); } TEST(ThreadSafeModelExecutorTest, ExecuteMany) { auto ast = Leaf("x"); ASSERT_OK_AND_ASSIGN(auto input_loader, CreateTestInputsLoader()); ASSERT_OK_AND_ASSIGN(auto executor, (CompileModelExecutor<int64_t>(ast, *input_loader))); ThreadSafeModelExecutor<TestInput, int64_t> thread_safe_executor( std::move(executor)); absl::flat_hash_set<int64_t> seen_results; for (auto& result_or : RunMany(thread_safe_executor, false)) { ASSERT_OK_AND_ASSIGN(auto result, result_or); seen_results.insert(result); } EXPECT_THAT(seen_results, UnorderedElementsAreArray(Iota(kNumThreads * kNumIterations))); } TEST(ThreadSafeModelExecutorTest, ExecuteManyOnDenseArrays) { auto ast = Leaf("x"); ASSERT_OK_AND_ASSIGN(auto input_loader, CreateDenseArrayTestInputsLoader()); ASSERT_OK_AND_ASSIGN( auto executor, (CompileModelExecutor<DenseArray<int64_t>>(ast, *input_loader))); ThreadSafeModelExecutor<TestInput, DenseArray<int64_t>> thread_safe_executor( std::move(executor)); absl::flat_hash_set<int64_t> seen_results; for (auto& result_or : RunMany(thread_safe_executor, false)) { ASSERT_OK_AND_ASSIGN(auto result, result_or); seen_results.insert(result[0].value); } EXPECT_THAT(seen_results, UnorderedElementsAreArray(Iota(kNumThreads * kNumIterations))); } TEST(ThreadSafeModelExecutorTest, ExecuteManyOnDenseArraysWithArena) { auto ast = Leaf("x"); ASSERT_OK_AND_ASSIGN(auto input_loader, CreateDenseArrayTestInputsLoader()); ModelExecutorOptions options; options.arena_page_size = 64 << 10; ASSERT_OK_AND_ASSIGN( auto executor, (CompileModelExecutor<DenseArray<int64_t>>(ast, *input_loader, options))); ThreadSafePoolModelExecutor<TestInput, DenseArray<int64_t>> thread_safe_executor(std::move(executor)); absl::flat_hash_set<int64_t> seen_results; for (auto& result_or : RunMany(thread_safe_executor, false)) { ASSERT_OK_AND_ASSIGN(auto result, result_or); seen_results.insert(result[0].value); } EXPECT_THAT(seen_results, UnorderedElementsAreArray(Iota(kNumThreads * kNumIterations))); } TEST(ThreadSafePoolModelExecutorTest, Move) { auto ast = Leaf("x"); ASSERT_OK_AND_ASSIGN(auto input_loader, CreateTestInputsLoader()); ASSERT_OK_AND_ASSIGN(auto executor, (CompileModelExecutor<int64_t>(ast, *input_loader))); ThreadSafePoolModelExecutor<TestInput, int64_t> thread_safe_executor( std::move(executor)); ASSERT_THAT(thread_safe_executor.IsValid(), IsTrue()); EXPECT_THAT(thread_safe_executor(TestInput{57}), IsOkAndHolds(57)); ThreadSafePoolModelExecutor<TestInput, int64_t> other_thread_safe_executor( std::move(thread_safe_executor)); ASSERT_THAT(other_thread_safe_executor.IsValid(), IsTrue()); EXPECT_THAT(other_thread_safe_executor(TestInput{57}), IsOkAndHolds(57)); EXPECT_THAT(thread_safe_executor.IsValid(), IsFalse()); thread_safe_executor = std::move(other_thread_safe_executor); ASSERT_THAT(thread_safe_executor.IsValid(), IsTrue()); EXPECT_THAT(thread_safe_executor(TestInput{57}), IsOkAndHolds(57)); EXPECT_THAT(other_thread_safe_executor.IsValid(), IsFalse()); } TEST(ThreadSafePoolModelExecutorTest, Copy) { auto ast = Leaf("x"); ASSERT_OK_AND_ASSIGN(auto input_loader, CreateTestInputsLoader()); ASSERT_OK_AND_ASSIGN(auto executor, (CompileModelExecutor<int64_t>(ast, *input_loader))); ThreadSafePoolModelExecutor<TestInput, int64_t> thread_safe_executor( std::move(executor)); ASSERT_THAT(thread_safe_executor.IsValid(), IsTrue()); EXPECT_THAT(thread_safe_executor(TestInput{57}), IsOkAndHolds(57)); ThreadSafePoolModelExecutor<TestInput, int64_t> other_thread_safe_executor( thread_safe_executor); ASSERT_THAT(other_thread_safe_executor.IsValid(), IsTrue()); EXPECT_THAT(other_thread_safe_executor(TestInput{57}), IsOkAndHolds(57)); EXPECT_THAT(thread_safe_executor.IsValid(), IsTrue()); } TEST(ThreadSafePoolModelExecutorTest, ExecuteOnce) { auto ast = Leaf("x"); ASSERT_OK_AND_ASSIGN(auto input_loader, CreateTestInputsLoader()); ASSERT_OK_AND_ASSIGN(auto executor, (CompileModelExecutor<int64_t>(ast, *input_loader))); ThreadSafePoolModelExecutor<TestInput, int64_t> thread_safe_executor( std::move(executor)); EXPECT_THAT(thread_safe_executor(TestInput{57}), IsOkAndHolds(57)); } TEST(ThreadSafePoolModelExecutorTest, ExecuteMany) { auto ast = Leaf("x"); ASSERT_OK_AND_ASSIGN(auto input_loader, CreateTestInputsLoader()); ASSERT_OK_AND_ASSIGN(auto executor, (CompileModelExecutor<int64_t>(ast, *input_loader))); ThreadSafePoolModelExecutor<TestInput, int64_t> thread_safe_executor( std::move(executor)); absl::flat_hash_set<int64_t> seen_results; for (auto& result_or : RunMany(thread_safe_executor, false)) { ASSERT_OK_AND_ASSIGN(auto result, result_or); seen_results.insert(result); } EXPECT_THAT(seen_results, UnorderedElementsAreArray(Iota(kNumThreads * kNumIterations))); } TEST(ThreadSafePoolModelExecutorTest, ExecuteManyOnDenseArrays) { auto ast = Leaf("x"); ASSERT_OK_AND_ASSIGN(auto input_loader, CreateDenseArrayTestInputsLoader()); ASSERT_OK_AND_ASSIGN( auto executor, (CompileModelExecutor<DenseArray<int64_t>>(ast, *input_loader))); ThreadSafePoolModelExecutor<TestInput, DenseArray<int64_t>> thread_safe_executor(std::move(executor)); absl::flat_hash_set<int64_t> seen_results; for (auto& result_or : RunMany(thread_safe_executor, false)) { ASSERT_OK_AND_ASSIGN(auto result, result_or); seen_results.insert(result[0].value); } EXPECT_THAT(seen_results, UnorderedElementsAreArray(Iota(kNumThreads * kNumIterations))); } TEST(ThreadSafePoolModelExecutorTest, ExecuteManyOnDenseArraysWithArena) { auto ast = Leaf("x"); ASSERT_OK_AND_ASSIGN(auto input_loader, CreateDenseArrayTestInputsLoader()); ModelExecutorOptions options; options.arena_page_size = 64 << 10; ASSERT_OK_AND_ASSIGN( auto executor, (CompileModelExecutor<DenseArray<int64_t>>(ast, *input_loader, options))); ThreadSafePoolModelExecutor<TestInput, DenseArray<int64_t>> thread_safe_executor(std::move(executor)); absl::flat_hash_set<int64_t> seen_results; for (auto& result_or : RunMany(thread_safe_executor, false)) { ASSERT_OK_AND_ASSIGN(auto result, result_or); seen_results.insert(result[0].value); } EXPECT_THAT(seen_results, UnorderedElementsAreArray(Iota(kNumThreads * kNumIterations))); } TEST(CopyableThreadUnsafeModelExecutorTest, Move) { auto ast = Leaf("x"); ASSERT_OK_AND_ASSIGN(auto input_loader, CreateTestInputsLoader()); ASSERT_OK_AND_ASSIGN(auto executor, (CompileModelExecutor<int64_t>(ast, *input_loader))); CopyableThreadUnsafeModelExecutor<TestInput, int64_t> copyable_executor( std::move(executor)); ASSERT_THAT(copyable_executor.IsValid(), IsTrue()); EXPECT_THAT(copyable_executor(TestInput{57}), IsOkAndHolds(57)); CopyableThreadUnsafeModelExecutor<TestInput, int64_t> other_copyable_executor( std::move(copyable_executor)); ASSERT_THAT(other_copyable_executor.IsValid(), IsTrue()); EXPECT_THAT(other_copyable_executor(TestInput{57}), IsOkAndHolds(57)); EXPECT_THAT(copyable_executor.IsValid(), IsFalse()); copyable_executor = std::move(other_copyable_executor); ASSERT_THAT(copyable_executor.IsValid(), IsTrue()); EXPECT_THAT(copyable_executor(TestInput{57}), IsOkAndHolds(57)); EXPECT_THAT(other_copyable_executor.IsValid(), IsFalse()); } TEST(CopyableThreadUnsafeModelExecutorTest, Copy) { auto ast = Leaf("x"); ASSERT_OK_AND_ASSIGN(auto input_loader, CreateTestInputsLoader()); ASSERT_OK_AND_ASSIGN(auto executor, (CompileModelExecutor<int64_t>(ast, *input_loader))); CopyableThreadUnsafeModelExecutor<TestInput, int64_t> copyable_executor( std::move(executor)); ASSERT_THAT(copyable_executor.IsValid(), IsTrue()); EXPECT_THAT(copyable_executor(TestInput{57}), IsOkAndHolds(57)); CopyableThreadUnsafeModelExecutor<TestInput, int64_t> other_copyable_executor( copyable_executor); ASSERT_THAT(other_copyable_executor.IsValid(), IsTrue()); EXPECT_THAT(other_copyable_executor(TestInput{57}), IsOkAndHolds(57)); EXPECT_THAT(copyable_executor.IsValid(), IsTrue()); } TEST(CopyableThreadUnsafeModelExecutorTest, ExecuteOnce) { auto ast = Leaf("x"); ASSERT_OK_AND_ASSIGN(auto input_loader, CreateTestInputsLoader()); ASSERT_OK_AND_ASSIGN(auto executor, (CompileModelExecutor<int64_t>(ast, *input_loader))); CopyableThreadUnsafeModelExecutor<TestInput, int64_t> copyable_executor( std::move(executor)); EXPECT_THAT(copyable_executor(TestInput{57}), IsOkAndHolds(57)); } TEST(CopyableThreadUnsafeModelExecutorTest, ExecuteMany) { auto ast = Leaf("x"); ASSERT_OK_AND_ASSIGN(auto input_loader, CreateTestInputsLoader()); ASSERT_OK_AND_ASSIGN(auto executor, (CompileModelExecutor<int64_t>(ast, *input_loader))); CopyableThreadUnsafeModelExecutor<TestInput, int64_t> copyable_executor( std::move(executor)); absl::flat_hash_set<int64_t> seen_results; for (auto& result_or : RunMany(copyable_executor, true)) { ASSERT_OK_AND_ASSIGN(auto result, result_or); seen_results.insert(result); } EXPECT_THAT(seen_results, UnorderedElementsAreArray(Iota(kNumThreads * kNumIterations))); } } }
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/expr/eval/thread_safe_model_executor.h
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/expr/eval/thread_safe_model_executor_test.cc
1ca990dbeca224035efdabffecc7f3738df6b52c
4decdc63-0b55-463f-bcc4-8d92940cc475
cpp
google/arolla
lift_accumulator_to_scalar_operator
arolla/qexpr/lift_accumulator_to_scalar_operator.h
arolla/qexpr/lift_accumulator_to_scalar_operator_test.cc
#ifndef AROLLA_QEXPR_LIFT_ACCUMULATOR_TO_SCALAR_OPERATOR_H_ #define AROLLA_QEXPR_LIFT_ACCUMULATOR_TO_SCALAR_OPERATOR_H_ #include <type_traits> #include "arolla/memory/optional_value.h" #include "arolla/qexpr/aggregation_ops_interface.h" #include "arolla/qexpr/eval_context.h" #include "arolla/qtype/array_like/array_like_qtype.h" #include "arolla/util/meta.h" namespace arolla { template <typename Accumulator, typename ParentTypes, typename ChildTypes> class ScalarToScalarGroupLifter; template <typename Accumulator, typename... ParentTs, typename... ChildTs> class ScalarToScalarGroupLifter<Accumulator, meta::type_list<ParentTs...>, meta::type_list<ChildTs...>> { public: template <typename... Ts> std::conditional_t<Accumulator::IsAggregator(), typename Accumulator::result_type, wrap_with_optional_t<typename Accumulator::result_type>> operator()(EvaluationContext* ctx, const ParentTs&... p_args, const wrap_with_optional_t<ChildTs>&... c_args, const ScalarToScalarEdge&, const Ts&... init_args) const { auto accumulator_or_status = CreateAccumulator<Accumulator>(init_args...); if (!accumulator_or_status.ok()) { ctx->set_status(std::move(accumulator_or_status).status()); return typename Accumulator::result_type(); } Accumulator& accumulator = *accumulator_or_status; accumulator.Reset(p_args...); bool child_args_present = (is_present_or_not_required<ChildTs>(c_args) && ... && true); if (child_args_present) { accumulator.Add(value<ChildTs>(c_args)...); } if constexpr (Accumulator::IsFull()) { accumulator.FinalizeFullGroup(); } ctx->set_status(accumulator.GetStatus()); if (Accumulator::IsAggregator() || child_args_present) { return typename Accumulator::result_type(accumulator.GetResult()); } else { return {}; } } private: template <typename T> bool is_present_or_not_required(const wrap_with_optional_t<T>& arg) const { if constexpr (is_optional_v<T>) { return true; } else { return arg.present; } } template <typename T> T value(const wrap_with_optional_t<T>& arg) const { if constexpr (is_optional_v<T>) { return arg; } else { return arg.value; } } }; } #endif
#include <cstdint> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status_matchers.h" #include "arolla/memory/optional_value.h" #include "arolla/qexpr/operators.h" #include "arolla/qtype/array_like/array_like_qtype.h" #include "arolla/qtype/base_types.h" namespace arolla { namespace { using ::absl_testing::IsOkAndHolds; TEST(ScalarToScalarGroupLifterTest, AggSum) { EXPECT_THAT(InvokeOperator<OptionalValue<int>>( "test.agg_sum", OptionalValue<int>(5), ScalarToScalarEdge()), IsOkAndHolds(OptionalValue<int>(5))); } TEST(ScalarToScalarGroupLifterTest, Average) { EXPECT_THAT(InvokeOperator<float>("test.average", OptionalValue<float>(5.0f), ScalarToScalarEdge()), IsOkAndHolds(5.0f)); } TEST(ScalarToScalarGroupLifterTest, RankValues) { EXPECT_THAT( InvokeOperator<OptionalValue<int64_t>>( "test.rank_values", OptionalValue<int>(5), ScalarToScalarEdge()), IsOkAndHolds(OptionalValue<int64_t>(0))); } } }
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/qexpr/lift_accumulator_to_scalar_operator.h
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/qexpr/lift_accumulator_to_scalar_operator_test.cc
1ca990dbeca224035efdabffecc7f3738df6b52c
b2c41507-2889-4121-a7a6-29ab6b433e18
cpp
google/arolla
lifting
arolla/qexpr/lifting.h
arolla/qexpr/lifting_test.cc
#ifndef AROLLA_QEXPR_LIFTING_H_ #define AROLLA_QEXPR_LIFTING_H_ #include <cstdint> #include <tuple> #include <type_traits> #include "absl/base/attributes.h" #include "arolla/util/meta.h" namespace arolla { template <class T> struct DoNotLiftTag { using type = T; }; template <class T> using DecayDoNotLiftTag = meta::strip_template_t<DoNotLiftTag, T>; template <template <class> class Lifted, class T> using LiftedType = std::conditional_t<meta::is_wrapped_with_v<DoNotLiftTag, T>, DecayDoNotLiftTag<T>, Lifted<T>>; namespace lifting_internal { template <class ArgTypeList> struct CallOnLiftedArgsImpl; template <> struct CallOnLiftedArgsImpl<meta::type_list<>> { template <class Fn, class... Ts> ABSL_ATTRIBUTE_ALWAYS_INLINE auto operator()(Fn&& fn, Ts&&... args) const { return std::forward<Fn>(fn)(std::forward<Ts>(args)...); } }; template <class LeftArg, class... LeftArgs> struct CallOnLiftedArgsImpl<meta::type_list<LeftArg, LeftArgs...>> { template <class Fn, class T, class... Ts> ABSL_ATTRIBUTE_ALWAYS_INLINE auto operator()(Fn&& fn, T&& arg, Ts&&... args) const { if constexpr (meta::is_wrapped_with_v<DoNotLiftTag, LeftArg>) { return CallOnLiftedArgsImpl<meta::type_list<LeftArgs...>>{}( std::forward<Fn>(fn), std::forward<Ts>(args)...); } else { return CallOnLiftedArgsImpl<meta::type_list<LeftArgs...>>{}( std::forward<Fn>(fn), std::forward<Ts>(args)..., std::forward<T>(arg)); } } }; template <uint64_t kDontLiftMask, class ScalarArgsList, class LiftedArgsList, class MergedArgsList> struct CallShuffledArgsFn; template <class... LiftedArgs, class... MergedArgs> struct CallShuffledArgsFn<0, meta::type_list<>, meta::type_list<LiftedArgs...>, meta::type_list<MergedArgs...>> { template <class SctrictFn> ABSL_ATTRIBUTE_ALWAYS_INLINE auto operator()( const SctrictFn& fn, const LiftedArgs&... lifted_args, const MergedArgs&... merged_args) const { return fn(merged_args..., lifted_args...); } }; template <uint64_t kDontLiftMask, class... ScalarArgs, class... MergedArgs> struct CallShuffledArgsFn<kDontLiftMask, meta::type_list<ScalarArgs...>, meta::type_list<>, meta::type_list<MergedArgs...>> { static_assert(kDontLiftMask == (1ull << sizeof...(ScalarArgs)) - 1); template <class SctrictFn> ABSL_ATTRIBUTE_ALWAYS_INLINE auto operator()( const SctrictFn& fn, const ScalarArgs&... scalar_args, const MergedArgs&... merged_args) const { return fn(merged_args..., scalar_args...); } }; template <class... MergedArgs> struct CallShuffledArgsFn<0, meta::type_list<>, meta::type_list<>, meta::type_list<MergedArgs...>> { template <class SctrictFn> ABSL_ATTRIBUTE_ALWAYS_INLINE auto operator()( const SctrictFn& fn, const MergedArgs&... merged_args) const { return fn(merged_args...); } }; template <uint64_t kDontLiftMask, class ScalarArg, class... ScalarArgs, class LiftedArg, class... LiftedArgs, class... MergedArgs> struct CallShuffledArgsFn< kDontLiftMask, meta::type_list<ScalarArg, ScalarArgs...>, meta::type_list<LiftedArg, LiftedArgs...>, meta::type_list<MergedArgs...>> { template <class SctrictFn> ABSL_ATTRIBUTE_ALWAYS_INLINE auto operator()( const SctrictFn& fn, const ScalarArg& scalar_arg, const ScalarArgs&... scalar_args, const LiftedArg& lifted_arg, const LiftedArgs&... lifted_args, MergedArgs... merged_args) const { if constexpr (kDontLiftMask % 2 == 1) { return CallShuffledArgsFn<kDontLiftMask / 2, meta::type_list<ScalarArgs...>, meta::type_list<LiftedArg, LiftedArgs...>, meta::type_list<MergedArgs..., ScalarArg>>()( fn, scalar_args..., lifted_arg, lifted_args..., merged_args..., scalar_arg); } else { return CallShuffledArgsFn<kDontLiftMask / 2, meta::type_list<ScalarArg, ScalarArgs...>, meta::type_list<LiftedArgs...>, meta::type_list<MergedArgs..., LiftedArg>>()( fn, scalar_arg, scalar_args..., lifted_args..., merged_args..., lifted_arg); } } }; template <template <typename> class LiftedViewType, class ArgsToProcessList, class LiftedArgList, uint64_t kDontLiftMask> struct CaptureDontLift; template <template <typename> class LiftedViewType, uint64_t kDontLiftMask, class LeftArg, class... LeftArgs, class... LiftedArgs> struct CaptureDontLift<LiftedViewType, meta::type_list<LeftArg, LeftArgs...>, meta::type_list<LiftedArgs...>, kDontLiftMask> { template <class Fn, class T, class... Ts> ABSL_ATTRIBUTE_ALWAYS_INLINE auto operator()(const Fn& fn, const T& arg, const Ts&... args) const { if constexpr (meta::is_wrapped_with_v<DoNotLiftTag, LeftArg>) { constexpr uint64_t total_arg_count = 1 + sizeof...(Ts) + sizeof...(LiftedArgs); constexpr uint64_t arg_id = total_arg_count - (sizeof...(LeftArgs) + 1); return CaptureDontLift<LiftedViewType, meta::type_list<LeftArgs...>, meta::type_list<LiftedArgs...>, kDontLiftMask + (1ull << arg_id)>{}(fn, args..., arg); } else { return CaptureDontLift<LiftedViewType, meta::type_list<LeftArgs...>, meta::type_list<LiftedArgs..., LeftArg>, kDontLiftMask>{}(fn, args...); } } }; template <template <typename> class LiftedViewType, uint64_t kDontLiftMask, class... LiftedArgs> struct CaptureDontLift<LiftedViewType, meta::type_list<>, meta::type_list<LiftedArgs...>, kDontLiftMask> { template <class Fn, class... Ts> ABSL_ATTRIBUTE_ALWAYS_INLINE auto operator()(const Fn& fn, const Ts&... args) const { return [fn, &args...](LiftedViewType<LiftedArgs>... view_args) ABSL_ATTRIBUTE_ALWAYS_INLINE { return CallShuffledArgsFn< kDontLiftMask, meta::type_list<Ts...>, meta::type_list<LiftedViewType<LiftedArgs>...>, meta::type_list<>>()(fn, args..., view_args...); }; } }; template <class ArgList> struct LiftableArgs; template <> struct LiftableArgs<meta::type_list<>> { using type = meta::type_list<>; }; template <class T, class... Ts> struct LiftableArgs<meta::type_list<T, Ts...>> { using type = meta::concat_t<meta::type_list<T>, typename LiftableArgs<meta::type_list<Ts...>>::type>; }; template <class T, class... Ts> struct LiftableArgs<meta::type_list<DoNotLiftTag<T>, Ts...>> { using type = typename LiftableArgs<meta::type_list<Ts...>>::type; }; } template <class... Args> class LiftingTools { static_assert(sizeof...(Args) <= 64, "Arg count limit is 64"); public: using LiftableArgs = typename lifting_internal::LiftableArgs<meta::type_list<Args...>>::type; static constexpr bool kAllLiftable = std::tuple_size_v<typename LiftableArgs::tuple> == sizeof...(Args); template <template <typename> class LiftedViewType, class Fn, class... Ts> static auto CreateFnWithDontLiftCaptured(const Fn& fn, const Ts&... args) { static_assert(sizeof...(Args) == sizeof...(Ts)); if constexpr (kAllLiftable) { return [fn](LiftedViewType<Args>... largs) { return fn(largs...); }; } else { return lifting_internal::CaptureDontLift< LiftedViewType, meta::type_list<Args...>, meta::type_list<>, 0>{}( fn, args...); } } template <class Fn, class... Ts> ABSL_ATTRIBUTE_ALWAYS_INLINE static auto CallOnLiftedArgs(Fn&& fn, Ts&&... args) { static_assert(sizeof...(Args) == sizeof...(Ts)); if constexpr (kAllLiftable) { return std::forward<Fn>(fn)(std::forward<Ts>(args)...); } else { return lifting_internal::CallOnLiftedArgsImpl<meta::type_list<Args...>>{}( std::forward<Fn>(fn), std::forward<Ts>(args)...); } } }; } #endif
#include "arolla/qexpr/lifting.h" #include <cstddef> #include <memory> #include <string> #include <type_traits> #include "gtest/gtest.h" #include "arolla/memory/optional_value.h" #include "arolla/util/meta.h" namespace arolla { namespace { TEST(Lifting, DoNotLiftTag) { static_assert(std::is_same_v<int, DoNotLiftTag<int>::type>); static_assert(std::is_same_v<OptionalValue<int>, DoNotLiftTag<OptionalValue<int>>::type>); } TEST(LiftingTools, LiftableArgs) { static_assert( std::is_same_v<LiftingTools<>::LiftableArgs, meta::type_list<>>); static_assert( std::is_same_v<LiftingTools<int>::LiftableArgs, meta::type_list<int>>); static_assert(std::is_same_v<LiftingTools<DoNotLiftTag<int>>::LiftableArgs, meta::type_list<>>); static_assert( std::is_same_v<LiftingTools<int, DoNotLiftTag<float>>::LiftableArgs, meta::type_list<int>>); static_assert( std::is_same_v<LiftingTools<DoNotLiftTag<float>, int>::LiftableArgs, meta::type_list<int>>); static_assert( std::is_same_v< LiftingTools<std::string, DoNotLiftTag<float>, int>::LiftableArgs, meta::type_list<std::string, int>>); static_assert( std::is_same_v<LiftingTools<std::string, DoNotLiftTag<float>, int, DoNotLiftTag<char>, DoNotLiftTag<std::string>, double>::LiftableArgs, meta::type_list<std::string, int, double>>); } template <class T> struct MyView { using type = T; T value; }; TEST(LiftingTools, CreateFnWithDontLiftCaptured) { { using Tools = LiftingTools<int>; auto fn = Tools::CreateFnWithDontLiftCaptured<MyView>( [](MyView<int> x) { return x.value; }, nullptr); EXPECT_EQ(fn(MyView<int>{5}), 5); EXPECT_EQ(Tools::CallOnLiftedArgs(fn, MyView<int>{5}), 5); static_assert(std::is_same_v<meta::function_traits<decltype(fn)>::arg_types, meta::type_list<MyView<int>>>); static_assert( std::is_same_v<meta::function_traits<decltype(fn)>::return_type, int>); } const int& kFive = 5; { using Tools = LiftingTools<DoNotLiftTag<int>>; auto fn = Tools::CreateFnWithDontLiftCaptured<MyView>( [](int x) { return x; }, kFive); EXPECT_EQ(fn(), 5); EXPECT_EQ(Tools::CallOnLiftedArgs(fn, nullptr), 5); static_assert(std::is_same_v<meta::function_traits<decltype(fn)>::arg_types, meta::type_list<>>); static_assert( std::is_same_v<meta::function_traits<decltype(fn)>::return_type, int>); } { using Tools = LiftingTools<DoNotLiftTag<int>, float, DoNotLiftTag<std::string>>; auto lambda = [](int x, MyView<float> y, std::string z) { if (x != 5 || y.value != 2.0f || z != "a") { return 0; } return 1; }; auto fn = Tools::CreateFnWithDontLiftCaptured<MyView>(lambda, kFive, nullptr, "a"); EXPECT_EQ(fn(MyView<float>{2.0f}), 1); EXPECT_EQ( Tools::CallOnLiftedArgs(fn, nullptr, MyView<float>{2.0f}, nullptr), 1); static_assert(std::is_same_v<meta::function_traits<decltype(fn)>::arg_types, meta::type_list<MyView<float>>>); static_assert( std::is_same_v<meta::function_traits<decltype(fn)>::return_type, int>); } { using Tools = LiftingTools<char, DoNotLiftTag<int>, float, DoNotLiftTag<std::string>>; auto lambda = [](MyView<char> q, int x, MyView<float> y, std::string z) { if (q.value != 'Q' || x != 5 || y.value != 2.0f || z != "a") { return 0; } return 1; }; std::string kA = "a"; auto fn = Tools::CreateFnWithDontLiftCaptured<MyView>(lambda, nullptr, kFive, nullptr, kA); EXPECT_EQ(fn(MyView<char>{'Q'}, MyView<float>{2.0f}), 1); EXPECT_EQ(Tools::CallOnLiftedArgs(fn, MyView<char>{'Q'}, nullptr, MyView<float>{2.0f}, nullptr), 1); static_assert(std::is_same_v<meta::function_traits<decltype(fn)>::arg_types, meta::type_list<MyView<char>, MyView<float>>>); static_assert( std::is_same_v<meta::function_traits<decltype(fn)>::return_type, int>); } } TEST(LiftingTools, CallOnLiftedArgsWithADifferentFunction) { using Tools = LiftingTools<char, DoNotLiftTag<int>, float, DoNotLiftTag<std::string>>; auto fn = [](float x, std::string z) { if (x != 1.0f || z != "z") { return 0; } return 1; }; EXPECT_EQ(Tools::CallOnLiftedArgs(fn, 1.0f, nullptr, "z", nullptr), 1); } TEST(LiftingTools, CaptureNonCopiable) { using Tools = LiftingTools<DoNotLiftTag<std::unique_ptr<int>>>; const auto ptr = std::make_unique<int>(5); auto fn = Tools::CreateFnWithDontLiftCaptured<MyView>( [](const std::unique_ptr<int>& x) { return x == nullptr ? -1 : *x; }, ptr); EXPECT_EQ(fn(), 5); EXPECT_EQ(Tools::CallOnLiftedArgs(fn, MyView<int>{-7}), 5); static_assert(std::is_same_v<meta::function_traits<decltype(fn)>::arg_types, meta::type_list<>>); static_assert( std::is_same_v<meta::function_traits<decltype(fn)>::return_type, int>); } template <class T> using ConstRef = const T&; TEST(LiftingTools, CallNonCopiable) { using Tools = LiftingTools<std::unique_ptr<int>>; auto fn = Tools::CreateFnWithDontLiftCaptured<ConstRef>( [](const std::unique_ptr<int>& x) { return x == nullptr ? -1 : *x; }, MyView<int>{-13}); EXPECT_EQ(fn(std::make_unique<int>(5)), 5); EXPECT_EQ(Tools::CallOnLiftedArgs(fn, std::make_unique<int>(5)), 5); static_assert(std::is_same_v<meta::function_traits<decltype(fn)>::arg_types, meta::type_list<const std::unique_ptr<int>&>>); static_assert( std::is_same_v<meta::function_traits<decltype(fn)>::return_type, int>); } TEST(LiftingTools, CreateFnWithDontLiftCaptured64Args) { using Tools = LiftingTools< DoNotLiftTag<int>, int, int, int, DoNotLiftTag<int>, int, int, int, DoNotLiftTag<int>, DoNotLiftTag<int>, int, int, int, int, int, int, DoNotLiftTag<int>, int, int, int, DoNotLiftTag<int>, int, int, int, int, DoNotLiftTag<int>, int, int, int, int, DoNotLiftTag<int>, int, int, int, int, DoNotLiftTag<int>, int, DoNotLiftTag<int>, int, int, int, int, int, DoNotLiftTag<int>, DoNotLiftTag<int>, int, int, int, int, DoNotLiftTag<int>, DoNotLiftTag<int>, int, int, int, int, int, int, DoNotLiftTag<int>, int, int, int, int, int, DoNotLiftTag<int> >; const int x = -1; #define TEST_ARGS_8 x, x, x, x, x, x, x, x #define TEST_ARGS_32 TEST_ARGS_8, TEST_ARGS_8, TEST_ARGS_8, TEST_ARGS_8 #define TEST_ARGS_64 TEST_ARGS_32, TEST_ARGS_32 auto fn = Tools::CreateFnWithDontLiftCaptured<ConstRef>( [](auto... args) { return sizeof...(args); }, TEST_ARGS_64); EXPECT_EQ(Tools::CallOnLiftedArgs(fn, TEST_ARGS_64), 64); static_assert( std::is_same_v<meta::function_traits<decltype(fn)>::return_type, size_t>); #undef TEST_ARGS_8 #undef TEST_ARGS_32 #undef TEST_ARGS_64 } } }
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/qexpr/lifting.h
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/qexpr/lifting_test.cc
1ca990dbeca224035efdabffecc7f3738df6b52c
d33b30d0-a91b-487d-8ffe-621250906013
cpp
google/arolla
operator_factory
arolla/qexpr/operator_factory.h
arolla/qexpr/operator_factory_test.cc
#ifndef AROLLA_QEXPR_OPERATOR_FACTORY_H_ #define AROLLA_QEXPR_OPERATOR_FACTORY_H_ #include <cstddef> #include <memory> #include <string> #include <tuple> #include <type_traits> #include <utility> #include <vector> #include "absl/base/attributes.h" #include "absl/container/inlined_vector.h" #include "absl/log/check.h" #include "absl/meta/type_traits.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "absl/types/span.h" #include "arolla/memory/frame.h" #include "arolla/qexpr/bound_operators.h" #include "arolla/qexpr/eval_context.h" #include "arolla/qexpr/operators.h" #include "arolla/qexpr/qexpr_operator_signature.h" #include "arolla/qexpr/result_type_traits.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/qtype/typed_slot.h" #include "arolla/util/demangle.h" #include "arolla/util/meta.h" #include "arolla/util/status_macros_backport.h" namespace arolla { template <typename FUNC> absl::StatusOr<OperatorPtr> QExprOperatorFromFunction(FUNC func); template <typename FUNC> absl::StatusOr<OperatorPtr> QExprOperatorBuildFromFunction( FUNC func, const QExprOperatorSignature* signature); template <typename FUNC, typename... ARG_Ts> absl::StatusOr<OperatorPtr> QExprOperatorFromFunctor(); template <typename FUNC> std::unique_ptr<arolla::OperatorFamily> MakeVariadicInputOperatorFamily( FUNC eval_func); namespace operator_factory_impl { template <typename T> using Slot = FrameLayout::Slot<T>; template <typename FUNC, typename... OTHER_ARGs> struct ContextFunc : private FUNC { explicit ContextFunc(FUNC func) : FUNC(std::move(func)) {} auto operator()(EvaluationContext*, OTHER_ARGs... args) const { return static_cast<const FUNC&>(*this)(args...); } }; template <typename FUNC, typename... OTHER_ARGs> struct ContextFunc<FUNC, EvaluationContext*, OTHER_ARGs...> : FUNC { explicit ContextFunc(FUNC func) : FUNC(std::move(func)) {} }; template <typename FUNC, typename... FUNC_ARGs> auto WrapIntoContextFunc(FUNC func, meta::type_list<FUNC_ARGs...>) { if constexpr (std::is_class_v<FUNC>) { return ContextFunc<FUNC, FUNC_ARGs...>(std::move(func)); } else { auto fn = [func = std::forward<FUNC>(func)](FUNC_ARGs... args) { return func(args...); }; return ContextFunc<decltype(fn), FUNC_ARGs...>(std::move(fn)); } } template <typename... Ts> struct QTypesVerifier; template <typename T, typename... Ts> struct QTypesVerifier<T, Ts...> { static absl::Status Verify(absl::Span<const QTypePtr> qtypes) { if (qtypes.size() != sizeof...(Ts) + 1) { return absl::Status( absl::StatusCode::kInvalidArgument, absl::StrFormat( "unexpected number of types: expected %d types %s, got %d", qtypes.size(), FormatTypeVector(qtypes), sizeof...(Ts) + 1)); } DCHECK_GT(qtypes.size(), size_t{0}); if (qtypes[0]->type_info() != typeid(T)) { return absl::Status( absl::StatusCode::kInvalidArgument, absl::StrFormat( "unexpected type: expected %s with C++ type %s, got %s", qtypes[0]->name(), TypeName(qtypes[0]->type_info()), TypeName<T>())); } return QTypesVerifier<Ts...>::Verify(qtypes.subspan(1)); } }; template <> struct QTypesVerifier<> { static absl::Status Verify(absl::Span<const QTypePtr> qtypes) { if (!qtypes.empty()) { return absl::Status( absl::StatusCode::kInvalidArgument, absl::StrFormat( "unexpected number of types: expected %d types %s, got 0", qtypes.size(), FormatTypeVector(qtypes))); } return absl::OkStatus(); } }; template <typename... Ts> struct QTypesVerifier<meta::type_list<Ts...>> { static absl::Status Verify(absl::Span<const QTypePtr> qtypes) { return QTypesVerifier<Ts...>::Verify(qtypes); } }; template <typename Slots, std::size_t... Is> Slots UnsafeToSlotsTupleImpl(absl::Span<const TypedSlot> slots, std::index_sequence<Is...>) { DCHECK_EQ(slots.size(), sizeof...(Is)); return { slots[Is] .UnsafeToSlot< typename std::tuple_element<Is, Slots>::type::value_type>()...}; } template <typename Slots> Slots UnsafeToSlotsTuple(absl::Span<const TypedSlot> slots) { return UnsafeToSlotsTupleImpl<Slots>( slots, std::make_index_sequence<std::tuple_size<Slots>::value>{}); } template <typename FUNC, typename RES, typename... ARGs> const QExprOperatorSignature* DeduceOperatorSignatureImpl( meta::type_list<RES>, meta::type_list<ARGs...>) { return QExprOperatorSignature::Get( {GetQType<std::decay_t<ARGs>>()...}, qexpr_impl::ResultTypeTraits<RES>::GetOutputType()); } template <typename FUNC> const QExprOperatorSignature* DeduceOperatorSignature() { return DeduceOperatorSignatureImpl<FUNC>( meta::type_list<typename meta::function_traits<FUNC>::return_type>(), meta::tail_t<typename meta::function_traits<FUNC>::arg_types>()); } template <typename FUNC> absl::Status VerifyOperatorSignature(const QExprOperatorSignature* signature) { RETURN_IF_ERROR(QTypesVerifier<meta::tail_t<typename meta::function_traits< FUNC>::arg_types>>::Verify(signature->input_types())) << "in input types of " << signature << "."; std::vector<QTypePtr> output_types = {signature->output_type()}; if (IsTupleQType(signature->output_type())) { output_types = SlotsToTypes(signature->output_type()->type_fields()); } RETURN_IF_ERROR( QTypesVerifier<typename qexpr_impl::ResultTypeTraits< typename meta::function_traits<FUNC>::return_type>::Types>:: Verify(output_types)) << "in output types of " << signature << "."; return absl::OkStatus(); } template <typename CTX_FUNC, typename RES, typename... ARGs> class OpImpl : public QExprOperator { public: OpImpl(const QExprOperatorSignature* signature, CTX_FUNC func) : QExprOperator(signature), func_(std::move(func)) {} private: absl::StatusOr<std::unique_ptr<BoundOperator>> DoBind( absl::Span<const TypedSlot> input_slots, TypedSlot output_slot) const override { auto inputs = UnsafeToSlotsTuple<InputSlots>(input_slots); auto outputs = qexpr_impl::ResultTypeTraits<RES>::UnsafeToSlots(output_slot); return MakeBoundOperator( [data = BoundOpData(func_, std::move(inputs), std::move(outputs))]( EvaluationContext* ctx, FramePtr frame) { RunImpl(data, ctx, frame, std::index_sequence_for<ARGs...>{}); }); } private: using InputSlots = std::tuple<Slot<absl::decay_t<ARGs>>...>; using OutputSlots = typename qexpr_impl::ResultTypeTraits<RES>::Slots; struct BoundOpData : private CTX_FUNC { BoundOpData(CTX_FUNC func, InputSlots input_slots, OutputSlots output_slots) : CTX_FUNC(std::move(func)), input_slots(input_slots), output_slots(output_slots) {} const CTX_FUNC& func() const { return static_cast<const CTX_FUNC&>(*this); } const InputSlots input_slots; const OutputSlots output_slots; }; template <std::size_t... Is> static void RunImpl(const BoundOpData& data, EvaluationContext* ctx, FramePtr frame, std::index_sequence<Is...>) { qexpr_impl::ResultTypeTraits<RES>::SaveAndReturn( ctx, frame, data.output_slots, data.func()(ctx, frame.Get(std::get<Is>(data.input_slots))...)); } const CTX_FUNC func_; }; template <typename CTX_FUNC, typename... ARGs> absl::StatusOr<OperatorPtr> QExprOperatorFromFunctionImpl( CTX_FUNC func, const QExprOperatorSignature* signature, meta::type_list<ARGs...>) { return OperatorPtr( new operator_factory_impl::OpImpl< CTX_FUNC, typename meta::function_traits<CTX_FUNC>::return_type, ARGs...>(signature, std::move(func))); } template <typename T> struct VariadicInputTypeTraits { using Container = nullptr_t; using Slot = nullptr_t; static_assert(sizeof(T) == 0, "unsupported input for VariadicInputOperatorFamily"); }; template <typename T> struct VariadicInputTypeTraits<meta::type_list<absl::Span<const T* const>>> { using Container = absl::InlinedVector<const T*, 4>; using Slot = FrameLayout::Slot<T>; static QTypePtr GetInputType() ABSL_ATTRIBUTE_ALWAYS_INLINE { return GetQType<T>(); } static Container GetInputs(arolla::FramePtr frame, absl::Span<const Slot> input_slots) { Container inputs; inputs.reserve(input_slots.size()); for (const auto& input_slot : input_slots) { inputs.push_back(&frame.Get(input_slot)); } return inputs; } static Slot UnsafeToSlot(TypedSlot output_slot) ABSL_ATTRIBUTE_ALWAYS_INLINE { return output_slot.UnsafeToSlot<T>(); } }; template <typename T> struct VariadicInputTypeTraits<meta::type_list<std::vector<T>>> { using Container = std::vector<T>; using Slot = FrameLayout::Slot<T>; static QTypePtr GetInputType() ABSL_ATTRIBUTE_ALWAYS_INLINE { return GetQType<T>(); } static Container GetInputs(arolla::FramePtr frame, absl::Span<const Slot> input_slots) { Container inputs; inputs.reserve(input_slots.size()); for (const auto& input_slot : input_slots) { inputs.push_back(frame.Get(input_slot)); } return inputs; } static Slot UnsafeToSlot(TypedSlot output_slot) ABSL_ATTRIBUTE_ALWAYS_INLINE { return output_slot.UnsafeToSlot<T>(); } }; template <typename FUNC> struct VariadicInputFuncTraits { using input = VariadicInputTypeTraits<typename meta::function_traits<FUNC>::arg_types>; using result = qexpr_impl::ResultTypeTraits< typename meta::function_traits<FUNC>::return_type>; }; template <typename FUNC> class VariadicInputOperator : public arolla::QExprOperator { using input_traits = VariadicInputFuncTraits<FUNC>::input; using result_traits = VariadicInputFuncTraits<FUNC>::result; public: explicit VariadicInputOperator(FUNC eval_func, absl::Span<const arolla::QTypePtr> input_types) : arolla::QExprOperator(arolla::QExprOperatorSignature::Get( input_types, result_traits::GetOutputType())), eval_func_(std::move(eval_func)) {} private: absl::StatusOr<std::unique_ptr<arolla::BoundOperator>> DoBind( absl::Span<const arolla::TypedSlot> typed_input_slots, arolla::TypedSlot typed_output_slot) const final { std::vector<typename input_traits::Slot> input_slots; input_slots.reserve(typed_input_slots.size()); for (const auto& input_slot : typed_input_slots) { input_slots.push_back(input_traits::UnsafeToSlot(input_slot)); } return arolla::MakeBoundOperator( [input_slots = std::move(input_slots), output_slot = result_traits::UnsafeToSlots(typed_output_slot), eval_func = eval_func_](arolla::EvaluationContext* ctx, arolla::FramePtr frame) { auto inputs = input_traits::GetInputs(frame, input_slots); result_traits::SaveAndReturn(ctx, frame, output_slot, eval_func(std::move(inputs))); }); } FUNC eval_func_; }; template <typename FUNC> class VariadicInputOperatorFamily : public arolla::OperatorFamily { using input_traits = VariadicInputFuncTraits<FUNC>::input; public: explicit VariadicInputOperatorFamily(FUNC eval_func) : eval_func_(std::move(eval_func)) {} private: absl::StatusOr<arolla::OperatorPtr> DoGetOperator( absl::Span<const arolla::QTypePtr> input_types, arolla::QTypePtr output_type) const final { for (const auto& input_type : input_types) { if (input_type != input_traits::GetInputType()) { return absl::InvalidArgumentError(absl::StrFormat( "expected only %s, got %s", input_traits::GetInputType()->name(), input_type->name())); } } return arolla::EnsureOutputQTypeMatches( std::make_shared<VariadicInputOperator<FUNC>>(eval_func_, input_types), input_types, output_type); } FUNC eval_func_; }; } template <typename FUNC> absl::StatusOr<OperatorPtr> QExprOperatorFromFunction(FUNC func) { auto context_func = operator_factory_impl::WrapIntoContextFunc( std::move(func), typename meta::function_traits<FUNC>::arg_types()); using CtxFunc = decltype(context_func); const QExprOperatorSignature* signature = operator_factory_impl::DeduceOperatorSignature<CtxFunc>(); return QExprOperatorFromFunctionImpl( std::move(context_func), signature, meta::tail_t<typename meta::function_traits<CtxFunc>::arg_types>()); } template <typename FUNC> absl::StatusOr<OperatorPtr> QExprOperatorFromFunction( FUNC func, const QExprOperatorSignature* signature) { auto context_func = operator_factory_impl::WrapIntoContextFunc( std::move(func), typename meta::function_traits<FUNC>::arg_types()); using CtxFunc = decltype(context_func); RETURN_IF_ERROR( operator_factory_impl::VerifyOperatorSignature<CtxFunc>(signature)); return QExprOperatorFromFunctionImpl( std::move(context_func), signature, meta::tail_t<typename meta::function_traits<CtxFunc>::arg_types>()); } template <typename FUNC, typename... ARG_Ts> absl::StatusOr<OperatorPtr> QExprOperatorFromFunctor() { return QExprOperatorFromFunction( [](EvaluationContext* ctx, const ARG_Ts&... args) { if constexpr (std::is_invocable_v<FUNC, ARG_Ts...>) { ((void)(ctx)); return FUNC()(args...); } else { return FUNC()(ctx, args...); } }); } template <typename FUNC> std::unique_ptr<arolla::OperatorFamily> MakeVariadicInputOperatorFamily( FUNC eval_func) { return std::make_unique< operator_factory_impl::VariadicInputOperatorFamily<FUNC>>( std::move(eval_func)); } } #endif
#include "arolla/qexpr/operator_factory.h" #include <cstdint> #include <tuple> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "absl/status/status_matchers.h" #include "absl/status/statusor.h" #include "absl/types/span.h" #include "arolla/qexpr/eval_context.h" #include "arolla/qexpr/operators.h" #include "arolla/qexpr/qexpr_operator_signature.h" #include "arolla/qexpr/testing/operator_fixture.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/simple_qtype.h" #include "arolla/qtype/tuple_qtype.h" #include "arolla/util/fingerprint.h" namespace arolla { using ::absl_testing::IsOk; using ::absl_testing::IsOkAndHolds; using ::absl_testing::StatusIs; using ::testing::Eq; using ::testing::Field; using ::testing::MatchesRegex; struct CopyCounter { CopyCounter() = default; CopyCounter(const CopyCounter& other) { count = other.count + 1; } CopyCounter& operator=(const CopyCounter& other) { count = other.count + 1; return *this; } CopyCounter(CopyCounter&& other) = default; CopyCounter& operator=(CopyCounter&& other) = default; int count = 0; }; AROLLA_DECLARE_FINGERPRINT_HASHER_TRAITS(CopyCounter); void FingerprintHasherTraits<CopyCounter>::operator()( FingerprintHasher* hasher, const CopyCounter& value) const { hasher->Combine(value.count); } AROLLA_DECLARE_SIMPLE_QTYPE(COPY_COUNTER, CopyCounter); AROLLA_DEFINE_SIMPLE_QTYPE(COPY_COUNTER, CopyCounter); namespace { TEST(OperatorFactory, SimpleOperator) { ASSERT_OK_AND_ASSIGN( auto op, QExprOperatorFromFunction([](int64_t a, int64_t b) { return a * b; })); ASSERT_THAT(op->signature(), Eq(QExprOperatorSignature::Get( {GetQType<int64_t>(), GetQType<int64_t>()}, GetQType<int64_t>()))); EXPECT_THAT(InvokeOperator<int64_t>(*op, int64_t{3}, int64_t{19}), IsOkAndHolds(Eq(57))); } int64_t Multiply(int64_t a, int64_t b) { return a * b; } TEST(OperatorFactory, NotAFunctor) { ASSERT_OK_AND_ASSIGN(auto op, QExprOperatorFromFunction(Multiply)); ASSERT_THAT(op->signature(), Eq(QExprOperatorSignature::Get( {GetQType<int64_t>(), GetQType<int64_t>()}, GetQType<int64_t>()))); EXPECT_THAT(InvokeOperator<int64_t>(*op, int64_t{3}, int64_t{19}), IsOkAndHolds(Eq(57))); } TEST(OperatorFactory, ReturnsTuple) { using Pair = std::tuple<int64_t, int64_t>; ASSERT_OK_AND_ASSIGN(auto op, QExprOperatorFromFunction([](int64_t a, int64_t b) { return std::make_tuple(b, a % b); })); ASSERT_THAT(op->signature(), Eq(QExprOperatorSignature::Get( {GetQType<int64_t>(), GetQType<int64_t>()}, MakeTupleQType({GetQType<int64_t>(), GetQType<int64_t>()})))); ASSERT_OK_AND_ASSIGN(auto fixture, (OperatorFixture<Pair, Pair>::Create(*op))); EXPECT_THAT(fixture.Call(57, 20), IsOkAndHolds(Eq(std::make_tuple(20, 17)))); } TEST(OperatorFactory, ReturnsStatusOr) { ASSERT_OK_AND_ASSIGN( auto op, QExprOperatorFromFunction([]() -> absl::StatusOr<int64_t> { return absl::Status(absl::StatusCode::kFailedPrecondition, "failed"); })); ASSERT_THAT(op->signature(), Eq(QExprOperatorSignature::Get({}, GetQType<int64_t>()))); EXPECT_THAT(InvokeOperator<int64_t>(*op), StatusIs(absl::StatusCode::kFailedPrecondition)); } TEST(OperatorFactory, ReturnsStatusOrTuple) { using Pair = std::tuple<int64_t, int64_t>; auto qtype = QExprOperatorSignature::Get( {GetQType<int64_t>(), GetQType<int64_t>()}, MakeTupleQType({GetQType<int64_t>(), GetQType<int64_t>()})); ASSERT_OK_AND_ASSIGN( auto op, QExprOperatorFromFunction( [](int64_t a, int64_t b) -> absl::StatusOr<Pair> { if (b == 0) { return absl::Status(absl::StatusCode::kInvalidArgument, "b is 0"); } return std::make_tuple(b, a % b); }, qtype)); EXPECT_THAT(op->signature(), Eq(QExprOperatorSignature::Get( {GetQType<int64_t>(), GetQType<int64_t>()}, MakeTupleQType({GetQType<int64_t>(), GetQType<int64_t>()})))); ASSERT_OK_AND_ASSIGN(auto fixture, (OperatorFixture<Pair, Pair>::Create(*op))); EXPECT_THAT(fixture.Call(57, 20), IsOkAndHolds(Eq(std::tuple(20, 17)))); EXPECT_THAT(fixture.Call(57, 0), StatusIs(absl::StatusCode::kInvalidArgument)); } TEST(OperatorFactory, NumberOfCopies) { using Fixture = OperatorFixture<std::tuple<CopyCounter>, CopyCounter>; ASSERT_OK_AND_ASSIGN( auto by_ref_with_eval_context_op, QExprOperatorFromFunction( [](EvaluationContext*, const CopyCounter& c) { return c; })); ASSERT_OK_AND_ASSIGN(auto by_ref_with_eval_context_op_fixture, Fixture::Create(*by_ref_with_eval_context_op)); EXPECT_THAT(by_ref_with_eval_context_op_fixture.Call(CopyCounter()), IsOkAndHolds(Field(&CopyCounter::count, 1))); ASSERT_OK_AND_ASSIGN( auto by_ref_without_eval_context_op, QExprOperatorFromFunction([](const CopyCounter& c) { return c; })); ASSERT_OK_AND_ASSIGN(auto by_ref_without_eval_context_op_fixture, Fixture::Create(*by_ref_without_eval_context_op)); EXPECT_THAT(by_ref_without_eval_context_op_fixture.Call(CopyCounter()), IsOkAndHolds(Field(&CopyCounter::count, 1))); ASSERT_OK_AND_ASSIGN( auto by_val_with_eval_context_op, QExprOperatorFromFunction( [](EvaluationContext*, CopyCounter c) { return c; })); ASSERT_OK_AND_ASSIGN(auto by_val_with_eval_context_op_fixture, Fixture::Create(*by_val_with_eval_context_op)); EXPECT_THAT(by_val_with_eval_context_op_fixture.Call(CopyCounter()), IsOkAndHolds(Field(&CopyCounter::count, 1))); ASSERT_OK_AND_ASSIGN( auto by_val_without_eval_context_op, QExprOperatorFromFunction([](CopyCounter c) { return c; })); ASSERT_OK_AND_ASSIGN(auto by_val_without_eval_context_op_fixture, Fixture::Create(*by_val_without_eval_context_op)); EXPECT_THAT(by_val_without_eval_context_op_fixture.Call(CopyCounter()), IsOkAndHolds(Field(&CopyCounter::count, 2))); ASSERT_OK_AND_ASSIGN(auto returns_tuple_op, QExprOperatorFromFunction([](const CopyCounter& c) { return std::make_tuple(c); })); ASSERT_OK_AND_ASSIGN(auto returns_tuple_op_fixture, Fixture::Create(*returns_tuple_op)); EXPECT_THAT(returns_tuple_op_fixture.Call(CopyCounter()), IsOkAndHolds(Field(&CopyCounter::count, 1))); ASSERT_OK_AND_ASSIGN( auto returns_status_or_tuple_op, QExprOperatorFromFunction([](const CopyCounter& c) { return absl::StatusOr<std::tuple<CopyCounter>>(std::make_tuple(c)); })); ASSERT_OK_AND_ASSIGN(auto returns_status_or_tuple_op_fixture, Fixture::Create(*returns_status_or_tuple_op)); EXPECT_THAT(returns_status_or_tuple_op_fixture.Call(CopyCounter()), IsOkAndHolds(Field(&CopyCounter::count, 1))); } TEST(OperatorFactory, TakesContext) { ASSERT_OK_AND_ASSIGN( auto op, QExprOperatorFromFunction([](EvaluationContext* ctx, float x) { ctx->buffer_factory().CreateRawBuffer(0); return 1; })); EXPECT_THAT(InvokeOperator<int32_t>(*op, 5.7f), IsOkAndHolds(1)); } struct AddOp { template <typename T> T operator()(T a, T b) const { return a + b; } }; struct Int64AddOp { int64_t operator()(int64_t a, int64_t b) const { return a + b; } }; struct ContextAddOp { template <typename T> T operator()(EvaluationContext* ctx, T a, T b) const { return a + b; } }; TEST(OperatorFactory, FromFunctor) { ASSERT_OK_AND_ASSIGN(auto op, (QExprOperatorFromFunctor<AddOp, int32_t, int32_t>())); EXPECT_THAT(InvokeOperator<int32_t>(*op, 1, 2), IsOkAndHolds(Eq(3))); ASSERT_OK_AND_ASSIGN( auto non_template_op, (QExprOperatorFromFunctor<Int64AddOp, int64_t, int64_t>())); EXPECT_THAT(InvokeOperator<int64_t>(*non_template_op, int64_t{1}, int64_t{2}), IsOkAndHolds(Eq(3))); ASSERT_OK_AND_ASSIGN( auto context_op, (QExprOperatorFromFunctor<ContextAddOp, int32_t, int32_t>())); EXPECT_THAT(InvokeOperator<int32_t>(*context_op, 1, 2), IsOkAndHolds(Eq(3))); } TEST(OperatorFactory, Errors) { EXPECT_THAT( QExprOperatorFromFunction([](int64_t a, int64_t b) { return a * b; }), IsOk()); auto qtype = QExprOperatorSignature::Get( {GetQType<float>(), GetQType<int32_t>()}, GetQType<int>()); EXPECT_THAT( QExprOperatorFromFunction( [](float arg1, float arg2) -> int32_t { return 57; }, qtype), StatusIs( absl::StatusCode::kInvalidArgument, MatchesRegex("unexpected type: expected INT32 with C\\+\\+ type int, " "got float; in input types of .*->.*\\."))); } TEST(VariadicInputOperatorTest, MakeVariadicInputOperatorFamily) { { auto op_family = MakeVariadicInputOperatorFamily( [](std::vector<int32_t> args) -> int64_t { return args[0] * args[1]; }); ASSERT_OK_AND_ASSIGN(auto op, op_family->GetOperator({GetQType<int32_t>(), GetQType<int32_t>()}, GetQType<int64_t>())); EXPECT_THAT(InvokeOperator<int64_t>(*op, 3, 19), IsOkAndHolds(Eq(57))); } { auto op_family = MakeVariadicInputOperatorFamily( [](absl::Span<const int32_t* const> args) -> int64_t { return *args[0] * *args[1]; }); ASSERT_OK_AND_ASSIGN(auto op, op_family->GetOperator({GetQType<int32_t>(), GetQType<int32_t>()}, GetQType<int64_t>())); EXPECT_THAT(InvokeOperator<int64_t>(*op, 3, 19), IsOkAndHolds(Eq(57))); } { auto op_family = MakeVariadicInputOperatorFamily( [](absl::Span<const int32_t* const> args) -> absl::StatusOr<int64_t> { return *args[0] * *args[1]; }); ASSERT_OK_AND_ASSIGN(auto op, op_family->GetOperator({GetQType<int32_t>(), GetQType<int32_t>()}, GetQType<int64_t>())); EXPECT_THAT(InvokeOperator<int64_t>(*op, 3, 19), IsOkAndHolds(Eq(57))); } { auto op_family = MakeVariadicInputOperatorFamily( [](absl::Span<const int32_t* const> args) -> absl::StatusOr<int64_t> { return absl::InvalidArgumentError("failed"); }); ASSERT_OK_AND_ASSIGN(auto op, op_family->GetOperator({GetQType<int32_t>(), GetQType<int32_t>()}, GetQType<int64_t>())); EXPECT_THAT(InvokeOperator<int64_t>(*op, 3, 19), StatusIs(absl::StatusCode::kInvalidArgument, "failed")); } { auto op_family = MakeVariadicInputOperatorFamily( [](absl::Span<const int32_t* const> args) { return std::make_tuple(*args[0], *args[1]); }); ASSERT_OK_AND_ASSIGN( auto op, op_family->GetOperator( {GetQType<int32_t>(), GetQType<int32_t>()}, MakeTupleQType({GetQType<int32_t>(), GetQType<int32_t>()}))); ASSERT_OK_AND_ASSIGN( auto fixture, (OperatorFixture<std::tuple<int32_t, int32_t>, std::tuple<int32_t, int32_t>>::Create(*op))); EXPECT_THAT(fixture.Call(57, 20), IsOkAndHolds(Eq(std::make_tuple(57, 20)))); } { auto op_family = MakeVariadicInputOperatorFamily( [](absl::Span<const int32_t* const> args) -> absl::StatusOr<int64_t> { return *args[0] + *args[1]; }); EXPECT_THAT( op_family->GetOperator({GetQType<int32_t>(), GetQType<int64_t>()}, GetQType<int64_t>()), StatusIs(absl::StatusCode::kInvalidArgument, "expected only INT32, got INT64")); } { auto op_family = MakeVariadicInputOperatorFamily( [](absl::Span<const int32_t* const> args) -> absl::StatusOr<int64_t> { return *args[0] + *args[1]; }); EXPECT_THAT( op_family->GetOperator({GetQType<int32_t>(), GetQType<int32_t>()}, GetQType<int32_t>()), StatusIs(absl::StatusCode::kNotFound)); } } } }
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/qexpr/operator_factory.h
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/qexpr/operator_factory_test.cc
1ca990dbeca224035efdabffecc7f3738df6b52c
956656bf-69b4-4389-a81e-71bb39f3ec59
cpp
google/arolla
lift_to_optional_operator
arolla/qexpr/lift_to_optional_operator.h
arolla/qexpr/lift_to_optional_operator_test.cc
#ifndef AROLLA_QEXPR_LIFT_TO_OPTIONAL_OPERATOR_H_ #define AROLLA_QEXPR_LIFT_TO_OPTIONAL_OPERATOR_H_ #include <type_traits> #include "arolla/memory/optional_value.h" #include "arolla/qexpr/lifting.h" #include "arolla/util/meta.h" namespace arolla { template <typename Op, typename ArgList> class OptionalLiftedOperator; template <typename Op, typename... Args> class OptionalLiftedOperator<Op, meta::type_list<Args...>> { template <class T> using LiftedType = std::conditional_t<meta::is_wrapped_with_v<DoNotLiftTag, T>, meta::strip_template_t<DoNotLiftTag, T>, wrap_with_optional_t<T>>; template <class T> using LiftedTypeView = const T&; public: template <class... Ts> auto CreateOptionalOpWithCapturedScalars(const Ts&... args) const { using Tools = LiftingTools<Args...>; return WrapFnToAcceptOptionalArgs( Tools::template CreateFnWithDontLiftCaptured<LiftedTypeView>(Op(), args...)); } auto operator()(const LiftedType<Args>&... args) const { using Tools = LiftingTools<Args...>; return Tools::CallOnLiftedArgs(CreateOptionalOpWithCapturedScalars(args...), args...); } }; } #endif
#include "arolla/qexpr/lift_to_optional_operator.h" #include <optional> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "absl/status/status_matchers.h" #include "absl/status/statusor.h" #include "arolla/memory/optional_value.h" #include "arolla/qexpr/lifting.h" #include "arolla/util/meta.h" namespace arolla { namespace { using ::absl_testing::IsOkAndHolds; using ::absl_testing::StatusIs; using ::testing::Eq; struct IntDivOp { template <typename T> OptionalValue<T> operator()(const T& lhs, const T& rhs) const { if (rhs == 0) { return std::nullopt; } return lhs / rhs; } }; TEST(OptionalLiftedOperatorTest, ReturnOptional) { using LiftedIntDivOp = OptionalLiftedOperator<IntDivOp, meta::type_list<int, int>>; EXPECT_THAT(LiftedIntDivOp()(OptionalValue<int>(5), OptionalValue<int>(2)), Eq(OptionalValue<int>(2))); EXPECT_THAT(LiftedIntDivOp()(OptionalValue<int>(5), OptionalValue<int>(0)), Eq(OptionalValue<int>())); EXPECT_THAT(LiftedIntDivOp()(OptionalValue<int>(), OptionalValue<int>()), Eq(OptionalValue<int>())); EXPECT_THAT(LiftedIntDivOp()(OptionalValue<int>(2), OptionalValue<int>()), Eq(OptionalValue<int>())); EXPECT_THAT(LiftedIntDivOp()(OptionalValue<int>(), OptionalValue<int>(2)), Eq(OptionalValue<int>())); } TEST(OptionalLiftedOperatorTest, NonLiftableArg) { using LiftedIntDivOp = OptionalLiftedOperator<IntDivOp, meta::type_list<DoNotLiftTag<int>, int>>; EXPECT_THAT(LiftedIntDivOp()(5, OptionalValue<int>(2)), Eq(OptionalValue<int>(2))); EXPECT_THAT(LiftedIntDivOp()(5, OptionalValue<int>(0)), Eq(OptionalValue<int>())); EXPECT_THAT(LiftedIntDivOp()(2, OptionalValue<int>()), Eq(OptionalValue<int>())); } struct MyInt { int value; friend int operator+(int x, MyInt y) { return y.value + x; } }; template <typename... Ts> struct TemplatedVariadicAddFn { int operator()(Ts... vs) const { return (0 + ... + vs); } }; TEST(Lifter, NonLiftableArgs) { { auto op = OptionalLiftedOperator< TemplatedVariadicAddFn<MyInt, MyInt, int>, meta::type_list<DoNotLiftTag<MyInt>, DoNotLiftTag<MyInt>, int>>(); OptionalValue<int> res = op(MyInt{3}, MyInt{5}, OptionalValue<int>(1)); EXPECT_THAT(res, Eq(9)); } { auto op = OptionalLiftedOperator< TemplatedVariadicAddFn<MyInt, int, MyInt>, meta::type_list<DoNotLiftTag<MyInt>, int, DoNotLiftTag<MyInt>>>(); OptionalValue<int> res = op(MyInt{3}, OptionalValue<int>(1), MyInt{5}); EXPECT_THAT(res, Eq(9)); } { auto op = OptionalLiftedOperator< TemplatedVariadicAddFn<int, MyInt, MyInt>, meta::type_list<int, DoNotLiftTag<MyInt>, DoNotLiftTag<MyInt>>>(); OptionalValue<int> res = op(OptionalValue<int>(1), MyInt{3}, MyInt{5}); EXPECT_THAT(res, Eq(9)); } { auto op = OptionalLiftedOperator< TemplatedVariadicAddFn<int, MyInt, int>, meta::type_list<int, DoNotLiftTag<MyInt>, int>>(); OptionalValue<int> res = op(OptionalValue<int>(1), MyInt{3}, OptionalValue<int>(1)); EXPECT_THAT(res, Eq(5)); } { auto op = OptionalLiftedOperator< TemplatedVariadicAddFn<MyInt, int, MyInt, int>, meta::type_list<DoNotLiftTag<MyInt>, int, DoNotLiftTag<MyInt>, int>>(); OptionalValue<int> res = op(MyInt{5}, OptionalValue<int>(1), MyInt{3}, OptionalValue<int>(1)); EXPECT_THAT(res, Eq(10)); } { auto op = OptionalLiftedOperator< TemplatedVariadicAddFn<int, MyInt, int, MyInt>, meta::type_list<int, DoNotLiftTag<MyInt>, int, DoNotLiftTag<MyInt>>>(); OptionalValue<int> res = op(OptionalValue<int>(1), MyInt{3}, OptionalValue<int>(1), MyInt{5}); EXPECT_THAT(res, Eq(10)); } { auto op = OptionalLiftedOperator< TemplatedVariadicAddFn<int, MyInt, int, MyInt, MyInt>, meta::type_list<int, DoNotLiftTag<MyInt>, int, DoNotLiftTag<MyInt>, DoNotLiftTag<MyInt>>>(); OptionalValue<int> res = op(OptionalValue<int>(1), MyInt{3}, OptionalValue<int>(1), MyInt{5}, MyInt{4}); EXPECT_THAT(res, Eq(14)); } } TEST(Lifter, NonLiftableArgsMissed) { auto op = OptionalLiftedOperator< TemplatedVariadicAddFn<MyInt, MyInt, int>, meta::type_list<DoNotLiftTag<MyInt>, DoNotLiftTag<MyInt>, int>>(); OptionalValue<int> res = op(MyInt{3}, MyInt{5}, OptionalValue<int>()); EXPECT_THAT(res, Eq(std::nullopt)); } struct FailingDivOp { template <typename T> absl::StatusOr<OptionalValue<T>> operator()(const T& lhs, const T& rhs) const { if (rhs == 0) { return absl::Status(absl::StatusCode::kInvalidArgument, "division by zero"); } return lhs / rhs; } }; TEST(LiftScalarOperatorTest, ReturnStatusOr) { using LiftedOp = OptionalLiftedOperator<FailingDivOp, meta::type_list<int, int>>; EXPECT_THAT(LiftedOp()(OptionalValue<int>(5), OptionalValue<int>(2)), IsOkAndHolds(Eq(OptionalValue<int>(2)))); EXPECT_THAT(LiftedOp()(OptionalValue<int>(), OptionalValue<int>(1)), IsOkAndHolds(Eq(OptionalValue<int>()))); EXPECT_THAT(LiftedOp()(OptionalValue<int>(1), OptionalValue<int>()), IsOkAndHolds(Eq(OptionalValue<int>()))); EXPECT_THAT(LiftedOp()(OptionalValue<int>(1), OptionalValue<int>(0)), StatusIs(absl::StatusCode::kInvalidArgument, "division by zero")); } struct StrangeDivOp { template <typename T> absl::StatusOr<OptionalValue<T>> operator()(const T& lhs, const T& rhs) const { if (rhs == 0) { return absl::Status(absl::StatusCode::kInvalidArgument, "division by zero"); } if (rhs < 0) { return std::nullopt; } return lhs / rhs; } }; TEST(LiftScalarOperatorTest, ReturnStatusOrOptional) { using LiftedOp = OptionalLiftedOperator<StrangeDivOp, meta::type_list<int, int>>; EXPECT_THAT(LiftedOp()(OptionalValue<int>(5), OptionalValue<int>(2)), IsOkAndHolds(Eq(OptionalValue<int>(2)))); EXPECT_THAT(LiftedOp()(OptionalValue<int>(), OptionalValue<int>(1)), IsOkAndHolds(Eq(OptionalValue<int>()))); EXPECT_THAT(LiftedOp()(OptionalValue<int>(1), OptionalValue<int>()), IsOkAndHolds(Eq(OptionalValue<int>()))); EXPECT_THAT(LiftedOp()(OptionalValue<int>(1), OptionalValue<int>(-1)), IsOkAndHolds(Eq(OptionalValue<int>()))); EXPECT_THAT(LiftedOp()(OptionalValue<int>(1), OptionalValue<int>(0)), StatusIs(absl::StatusCode::kInvalidArgument, "division by zero")); } struct DivWithDefaultOp { template <typename T> absl::StatusOr<T> operator()(T lhs, T rhs, OptionalValue<T> default_result) const { if (rhs == 0) { if (default_result.present) { return default_result.value; } else { return absl::Status(absl::StatusCode::kInvalidArgument, "division by zero"); } } return lhs / rhs; } }; TEST(LiftScalarOperatorTest, OptionalArguments) { using LiftedOp = OptionalLiftedOperator<DivWithDefaultOp, meta::type_list<int, int, OptionalValue<int>>>; const OptionalValue<int> missing(std::nullopt); const OptionalValue<int> one = 1; const OptionalValue<int> zero = 0; EXPECT_THAT(LiftedOp()(OptionalValue<int>(5), OptionalValue<int>(2), missing), IsOkAndHolds(Eq(2))); EXPECT_THAT(LiftedOp()(missing, one, missing), IsOkAndHolds(Eq(missing))); EXPECT_THAT(LiftedOp()(one, missing, missing), IsOkAndHolds(Eq(missing))); EXPECT_THAT(LiftedOp()(one, zero, missing), StatusIs(absl::StatusCode::kInvalidArgument, "division by zero")); EXPECT_THAT(LiftedOp()(one, zero, one), IsOkAndHolds(Eq(one))); } } }
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/qexpr/lift_to_optional_operator.h
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/qexpr/lift_to_optional_operator_test.cc
1ca990dbeca224035efdabffecc7f3738df6b52c
57e29178-a658-4623-9062-0009d375758f
cpp
google/arolla
eval_context
arolla/qexpr/eval_context.h
arolla/qexpr/eval_context_test.cc
#ifndef AROLLA_QEXPR_EVAL_CONTEXT_H_ #define AROLLA_QEXPR_EVAL_CONTEXT_H_ #include <cstdint> #include <type_traits> #include <utility> #include "absl/functional/any_invocable.h" #include "absl/log/check.h" #include "absl/status/status.h" #include "arolla/memory/frame.h" #include "arolla/memory/memory_allocation.h" #include "arolla/memory/raw_buffer_factory.h" namespace arolla { class RootEvaluationContext { public: RootEvaluationContext() : buffer_factory_(GetHeapBufferFactory()) {} explicit RootEvaluationContext(const FrameLayout* layout, RawBufferFactory* buffer_factory = nullptr) : alloc_(layout), buffer_factory_(buffer_factory == nullptr ? GetHeapBufferFactory() : buffer_factory) {} RootEvaluationContext(const RootEvaluationContext&) = delete; RootEvaluationContext& operator=(const RootEvaluationContext&) = delete; RootEvaluationContext(RootEvaluationContext&&) = default; RootEvaluationContext& operator=(RootEvaluationContext&&) = default; template <typename T> T* GetMutable(FrameLayout::Slot<T> slot) { return frame().GetMutable(slot); } template <typename T, typename S = T> void Set(FrameLayout::Slot<T> slot, S&& value) { return frame().Set(slot, std::forward<S>(value)); } template <typename T> const T& Get(FrameLayout::Slot<T> slot) const { return frame().Get(slot); } FramePtr frame() { return alloc_.frame(); } ConstFramePtr frame() const { return alloc_.frame(); } RawBufferFactory& buffer_factory() const { return *buffer_factory_; } bool IsValid() const { return alloc_.IsValid(); } private: MemoryAllocation alloc_; RawBufferFactory* buffer_factory_ = nullptr; }; class EvaluationContext { public: using CheckInterruptFn = absl::AnyInvocable<absl::Status()>; EvaluationContext() = default; explicit EvaluationContext(RootEvaluationContext& root_ctx) : buffer_factory_(root_ctx.buffer_factory()) {} explicit EvaluationContext(RawBufferFactory* buffer_factory, CheckInterruptFn* check_interrupt_fn = nullptr) : buffer_factory_(*buffer_factory), check_interrupt_fn_(check_interrupt_fn) { DCHECK(buffer_factory); } EvaluationContext(const EvaluationContext&) = delete; EvaluationContext& operator=(const EvaluationContext&) = delete; EvaluationContext(EvaluationContext&&) = delete; EvaluationContext& operator=(EvaluationContext&&) = delete; const absl::Status& status() const& { return status_; } absl::Status&& status() && { return std::move(status_); } template <typename StatusLike> auto set_status(StatusLike&& status_like) -> std::enable_if_t< !std::is_lvalue_reference_v<StatusLike> && !std::is_const_v<std::remove_reference_t<StatusLike>>, std::void_t<decltype(static_cast<absl::Status>( std::forward<StatusLike>(status_like)))>> { status_ = static_cast<absl::Status>(std::forward<StatusLike>(status_like)); signal_received_ = signal_received_ || !status_.ok(); } auto set_status() { return [this](auto&& status_like) { this->set_status(std::forward<decltype(status_like)>(status_like)); }; } RawBufferFactory& buffer_factory() { return buffer_factory_; } int64_t requested_jump() const { return jump_; } void set_requested_jump(int64_t jump) { signal_received_ = true; jump_ = jump; } bool signal_received() const { return signal_received_; } void ResetSignals() { signal_received_ = false; jump_ = 0; status_ = absl::OkStatus(); } bool has_check_interrupt_fn() const { return check_interrupt_fn_ != nullptr; } void check_interrupt(int64_t ops_evaluated) { constexpr int64_t kCheckInterruptPeriod = 128; check_interrupt_counter_ += ops_evaluated; if (check_interrupt_counter_ >= kCheckInterruptPeriod && check_interrupt_fn_ && status_.ok()) { set_status((*check_interrupt_fn_)()); check_interrupt_counter_ = 0; } } private: bool signal_received_ = false; int64_t jump_ = 0; absl::Status status_; RawBufferFactory& buffer_factory_ = *GetHeapBufferFactory(); CheckInterruptFn* check_interrupt_fn_ = nullptr; int64_t check_interrupt_counter_ = 0; }; } #endif
#include "arolla/qexpr/eval_context.h" #include <cstdint> #include <memory> #include <string> #include <utility> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/functional/any_invocable.h" #include "absl/status/status.h" #include "absl/status/status_matchers.h" #include "absl/status/statusor.h" #include "arolla/memory/frame.h" #include "arolla/memory/raw_buffer_factory.h" #include "arolla/qtype/base_types.h" #include "arolla/util/status_macros_backport.h" namespace arolla { namespace { using ::absl_testing::IsOk; using ::absl_testing::StatusIs; using ::testing::Eq; using ::testing::IsFalse; using ::testing::IsTrue; using ::testing::Not; TEST(EvalContextTest, OperatorExample) { class AddOperator { public: AddOperator(FrameLayout::Slot<double> op1_slot, FrameLayout::Slot<double> op2_slot, FrameLayout::Slot<double> result_slot) : op1_slot_(op1_slot), op2_slot_(op2_slot), result_slot_(result_slot) {} void operator()(FramePtr frame) const { double op1 = frame.Get(op1_slot_); double op2 = frame.Get(op2_slot_); frame.Set(result_slot_, op1 + op2); } private: FrameLayout::Slot<double> op1_slot_; FrameLayout::Slot<double> op2_slot_; FrameLayout::Slot<double> result_slot_; }; FrameLayout::Builder bldr; auto op1_slot = bldr.AddSlot<double>(); auto op2_slot = bldr.AddSlot<double>(); auto tmp_slot = bldr.AddSlot<double>(); AddOperator add_op1(op1_slot, op2_slot, tmp_slot); auto op3_slot = bldr.AddSlot<double>(); auto result_slot = bldr.AddSlot<double>(); AddOperator add_op2(tmp_slot, op3_slot, result_slot); FrameLayout layout = std::move(bldr).Build(); RootEvaluationContext ctx(&layout); ctx.Set(op1_slot, 1.0); ctx.Set(op2_slot, 2.0); ctx.Set(op3_slot, 3.0); add_op1(ctx.frame()); add_op2(ctx.frame()); EXPECT_EQ(6.0, ctx.Get(result_slot)); } TEST(EvalContextTest, SetByRValue) { FrameLayout::Builder bldr; auto slot = bldr.AddSlot<std::unique_ptr<int>>(); FrameLayout layout = std::move(bldr).Build(); RootEvaluationContext ctx(&layout); ctx.Set(slot, std::make_unique<int>(5)); EXPECT_EQ(5, *ctx.Get(slot)); std::unique_ptr<int> ptr(new int(6)); ctx.Set(slot, std::move(ptr)); EXPECT_EQ(6, *ctx.Get(slot)); } TEST(EvalContextTest, ImplicitTypeCastingOnSet) { FrameLayout::Builder bldr; auto slot = bldr.AddSlot<int8_t>(); FrameLayout layout = std::move(bldr).Build(); RootEvaluationContext ctx(&layout); ctx.Set(slot, 5); EXPECT_EQ(5, ctx.Get(slot)); } TEST(EvalContextTest, RegisterUnsafeSlot) { FrameLayout::Builder bldr; auto slot = bldr.AddSlot<int32_t>(); auto slot_1byte = FrameLayout::Slot<int8_t>::UnsafeSlotFromOffset(slot.byte_offset()); auto slot_2bytes = FrameLayout::Slot<int16_t>::UnsafeSlotFromOffset(slot.byte_offset() + 2); ASSERT_OK(bldr.RegisterUnsafeSlot(slot_1byte)); ASSERT_OK(bldr.RegisterUnsafeSlot(slot_2bytes)); FrameLayout layout = std::move(bldr).Build(); RootEvaluationContext ctx(&layout); ctx.Set(slot_1byte, 5); EXPECT_EQ(5, ctx.Get(slot_1byte)); ctx.Set(slot_2bytes, 1024); EXPECT_EQ(1024, ctx.Get(slot_2bytes)); } TEST(EvalContextTest, SetByConstReference) { FrameLayout::Builder bldr; auto slot = bldr.AddSlot<int32_t>(); FrameLayout layout = std::move(bldr).Build(); RootEvaluationContext ctx(&layout); const int32_t value = 12; ctx.Set(slot, value); EXPECT_EQ(12, ctx.Get(slot)); } TEST(EvalContextTest, SetStatus) { EvaluationContext ctx; absl::Status error = absl::InvalidArgumentError( "error message too long for a small string optimization"); const char* message_ptr = error.message().data(); ctx.set_status(std::move(error)); EXPECT_THAT(ctx.status(), Not(IsOk())); EXPECT_THAT(ctx.status().message().data(), Eq(message_ptr)); } TEST(EvalContextTest, SetStatusInAssignOrReturn) { const char* message_ptr; auto fn = [&](EvaluationContext* ctx) { absl::Status error = absl::InvalidArgumentError( "error message too long for a small string optimization"); message_ptr = error.message().data(); absl::StatusOr<float> value_or = std::move(error); ASSIGN_OR_RETURN(float f32, std::move(value_or), ctx->set_status(std::move(_))); return void(f32); }; EvaluationContext ctx; fn(&ctx); EXPECT_THAT(ctx.status(), Not(IsOk())); EXPECT_THAT(ctx.status().message().data(), Eq(message_ptr)); } TEST(EvalContextTest, SetStatusInReturnIfError) { const char* message_ptr; auto fn = [&](EvaluationContext* ctx) { absl::Status error = absl::InvalidArgumentError( "error message too long for a small string optimization"); message_ptr = error.message().data(); RETURN_IF_ERROR(std::move(error)).With(ctx->set_status()); }; EvaluationContext ctx; fn(&ctx); EXPECT_THAT(ctx.status(), Not(IsOk())); EXPECT_THAT(ctx.status().message().data(), Eq(message_ptr)); } TEST(EvalContextTest, Status) { EvaluationContext ctx; EXPECT_THAT(ctx.status(), IsOk()); EXPECT_THAT(ctx.signal_received(), IsFalse()); ctx.set_status(absl::OkStatus()); EXPECT_THAT(ctx.signal_received(), IsFalse()); ctx.set_status(absl::InvalidArgumentError("foo")); EXPECT_THAT(ctx.signal_received(), IsTrue()); EXPECT_THAT(ctx.status(), StatusIs(absl::StatusCode::kInvalidArgument, "foo")); ctx.set_status(absl::OkStatus()); EXPECT_THAT(ctx.signal_received(), IsTrue()); EXPECT_THAT(ctx.status(), IsOk()); ctx.set_status(absl::InvalidArgumentError("foo")); ctx.ResetSignals(); EXPECT_THAT(ctx.signal_received(), IsFalse()); EXPECT_THAT(ctx.status(), IsOk()); } TEST(EvalContextTest, Jump) { EvaluationContext ctx; EXPECT_THAT(ctx.requested_jump(), Eq(0)); EXPECT_THAT(ctx.signal_received(), IsFalse()); ctx.set_requested_jump(-57); EXPECT_THAT(ctx.signal_received(), IsTrue()); EXPECT_THAT(ctx.requested_jump(), Eq(-57)); ctx.ResetSignals(); EXPECT_THAT(ctx.signal_received(), IsFalse()); EXPECT_THAT(ctx.requested_jump(), Eq(0)); } TEST(EvalContextTest, CheckInterrupt) { bool interrupt = false; absl::AnyInvocable<absl::Status()> check_fn = [&interrupt]() -> absl::Status { return interrupt ? absl::CancelledError("interrupt") : absl::OkStatus(); }; EvaluationContext ctx(GetHeapBufferFactory(), &check_fn); EXPECT_THAT(ctx.signal_received(), IsFalse()); EXPECT_TRUE(ctx.status().ok()); for (int i = 0; i < 100; ++i) ctx.check_interrupt(10); EXPECT_THAT(ctx.signal_received(), IsFalse()); EXPECT_TRUE(ctx.status().ok()); interrupt = true; for (int i = 0; i < 100; ++i) ctx.check_interrupt(10); EXPECT_THAT(ctx.signal_received(), IsTrue()); EXPECT_THAT(ctx.status(), StatusIs(absl::StatusCode::kCancelled, "interrupt")); } #ifndef NDEBUG TEST(EvalContextDeathTest, TypeMismatch) { FrameLayout::Builder builder1; auto slot1 = builder1.AddSlot<float>(); auto descriptor1 = std::move(builder1).Build(); RootEvaluationContext ctx1(&descriptor1); ctx1.Set(slot1, 1.0f); FrameLayout::Builder builder2; auto slot2 = builder2.AddSlot<std::string>(); auto descriptor2 = std::move(builder2).Build(); RootEvaluationContext ctx2(&descriptor2); ctx2.Set(slot2, "A string"); EXPECT_DEATH(ctx1.Set(slot2, "Another string"), "Field with given offset and type not found"); } TEST(EvalContextDeathTest, TypeMismatchWithRegisteredExtraSlot) { FrameLayout::Builder builder; auto slot_int = builder.AddSlot<int>(); auto slot_1byte = FrameLayout::Slot<char>::UnsafeSlotFromOffset(slot_int.byte_offset()); auto slot_2bytes = FrameLayout::Slot<int16_t>::UnsafeSlotFromOffset(slot_int.byte_offset()); ASSERT_OK(builder.RegisterUnsafeSlot(slot_1byte)); auto descriptor = std::move(builder).Build(); RootEvaluationContext ctx1(&descriptor); ctx1.Set(slot_int, 1); ctx1.Set(slot_1byte, 1); EXPECT_DEATH(ctx1.Set(slot_2bytes, 1), "Field with given offset and type not found"); } #endif } }
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/qexpr/eval_context.h
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/qexpr/eval_context_test.cc
1ca990dbeca224035efdabffecc7f3738df6b52c
ce1aac24-e987-4099-af49-172276ddf340
cpp
google/arolla
timeseries
arolla/qexpr/operators/experimental/dense_array/timeseries.h
arolla/qexpr/operators/experimental/dense_array/timeseries_test.cc
#ifndef AROLLA_QEXPR_OPERATORS_EXPERIMENTAL_DENSE_ARRAY_TIMESERIES_H_ #define AROLLA_QEXPR_OPERATORS_EXPERIMENTAL_DENSE_ARRAY_TIMESERIES_H_ #include <cstdint> #include <deque> #include <optional> #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/edge.h" #include "arolla/dense_array/ops/dense_group_ops.h" #include "arolla/dense_array/qtype/types.h" #include "arolla/memory/optional_value.h" #include "arolla/qexpr/aggregation_ops_interface.h" #include "arolla/qexpr/eval_context.h" #include "arolla/util/meta.h" #include "arolla/util/view_types.h" namespace arolla { namespace moving_average_operator_impl { template <typename ScalarT> class MovingAverageAccumulator final : public Accumulator<AccumulatorType::kPartial, OptionalValue<ScalarT>, meta::type_list<>, meta::type_list<OptionalValue<ScalarT>>> { public: explicit MovingAverageAccumulator(int window_size) : window_size_(window_size) {} void Reset() final { current_window_.clear(); window_sum_ = 0; } void Add(OptionalValue<ScalarT> tail_value) final { if (tail_value.present) { current_window_.push_front(tail_value.value); window_sum_ += tail_value.value; } else { Reset(); } } OptionalValue<ScalarT> GetResult() final { if (current_window_.size() == window_size_) { auto result = window_sum_ / window_size_; window_sum_ -= current_window_.back(); current_window_.pop_back(); return result; } else { return std::nullopt; } } private: std::deque<ScalarT> current_window_; int window_size_; double window_sum_ = 0; }; } struct AggMovingAverageOp { template <typename ScalarT> absl::StatusOr<DenseArray<ScalarT>> operator()( EvaluationContext* ctx, const DenseArray<ScalarT>& series, const int64_t window_size, const DenseArrayEdge& edge) const { using MovingAvgAcc = moving_average_operator_impl::MovingAverageAccumulator<ScalarT>; DenseGroupOps<MovingAvgAcc> agg(&ctx->buffer_factory(), MovingAvgAcc(window_size)); return agg.Apply(edge, series); } }; struct ExponentialWeightedMovingAverageOp { template <typename ScalarT> DenseArray<ScalarT> AdjustedEWMA(const DenseArray<ScalarT>& series, double alpha, bool ignore_missing = false) const { DenseArrayBuilder<ScalarT> builder(series.size()); int64_t previous_non_missing_id = -1; double previous_non_missing_value = 0; double current_ewma_numerator = 0; double current_ewma_denominator = 0; series.ForEach([&](int64_t current_row_id, bool present, view_type_t<ScalarT> tail_value) { if (!present) return; if (previous_non_missing_id >= 0) { for (int64_t i = previous_non_missing_id + 1; i < current_row_id; i++) { builder.Set(i, previous_non_missing_value); if (!ignore_missing) { current_ewma_numerator *= (1.0 - alpha); current_ewma_denominator *= (1.0 - alpha); } } } current_ewma_numerator = tail_value + (1. - alpha) * current_ewma_numerator; current_ewma_denominator = 1. + (1. - alpha) * current_ewma_denominator; previous_non_missing_value = current_ewma_numerator / current_ewma_denominator; builder.Set(current_row_id, previous_non_missing_value); previous_non_missing_id = current_row_id; }); return std::move(builder).Build(); } template <typename ScalarT> DenseArray<ScalarT> UnadjustedEWMA(const DenseArray<ScalarT>& series, double alpha, bool ignore_missing = false) const { DenseArrayBuilder<ScalarT> builder(series.size()); int64_t previous_non_missing_id = -1; double previous_non_missing_value = 0; series.ForEach([&](int64_t current_row_id, bool present, view_type_t<ScalarT> tail_value) { if (!present) return; double previous_weight = (1. - alpha); if (previous_non_missing_id >= 0) { for (int64_t i = previous_non_missing_id + 1; i < current_row_id; i++) { builder.Set(i, previous_non_missing_value); if (!ignore_missing) { previous_weight *= (1. - alpha); } } } else { previous_non_missing_value = tail_value; } previous_non_missing_value = (alpha * tail_value + previous_weight * previous_non_missing_value) / (alpha + previous_weight); builder.Set(current_row_id, previous_non_missing_value); previous_non_missing_id = current_row_id; }); return std::move(builder).Build(); } template <typename ScalarT> absl::StatusOr<DenseArray<ScalarT>> operator()( const DenseArray<ScalarT>& series, double alpha, bool adjust = true, bool ignore_missing = false) const { if (alpha <= 0 || alpha > 1) { return absl::Status( absl::StatusCode::kInvalidArgument, absl::StrFormat("alpha must be in range (0, 1], got %f", alpha)); } if (adjust) { return AdjustedEWMA(series, alpha, ignore_missing); } else { return UnadjustedEWMA(series, alpha, ignore_missing); } } }; } #endif
#include <cstdint> #include <initializer_list> #include <optional> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "absl/status/status_matchers.h" #include "absl/status/statusor.h" #include "arolla/dense_array/dense_array.h" #include "arolla/dense_array/edge.h" #include "arolla/dense_array/qtype/types.h" #include "arolla/memory/buffer.h" #include "arolla/qexpr/operators.h" namespace arolla { namespace { using ::absl_testing::IsOkAndHolds; using ::absl_testing::StatusIs; using ::testing::ElementsAre; absl::StatusOr<DenseArrayEdge> CreateEdgeFromSplitPoints( std::initializer_list<int64_t> splits) { return DenseArrayEdge::FromSplitPoints({CreateBuffer<int64_t>(splits)}); } const char kAggMovingAverage[] = "experimental.agg_moving_average"; constexpr auto NA = std::nullopt; TEST(AggMovingAverage, FullTimeSeries) { const auto series = CreateDenseArray<float>({1, 2, 3, 4, 5, 6, 7, 8}); ASSERT_OK_AND_ASSIGN(auto edge, CreateEdgeFromSplitPoints({0, 8})); EXPECT_THAT(InvokeOperator<DenseArray<float>>(kAggMovingAverage, series, int64_t{3}, edge), IsOkAndHolds(ElementsAre(NA, NA, 2, 3, 4, 5, 6, 7))); } TEST(AggMovingAverage, TimeSeriesWithMissingValue) { const auto series = CreateDenseArray<float>({1, 2, 3, NA, 5, 6, 7, 8}); ASSERT_OK_AND_ASSIGN(auto edge, CreateEdgeFromSplitPoints({0, 8})); EXPECT_THAT(InvokeOperator<DenseArray<float>>(kAggMovingAverage, series, int64_t{3}, edge), IsOkAndHolds(ElementsAre(NA, NA, 2, NA, NA, NA, 6, 7))); } TEST(AggMovingAverage, ZeroWindow) { const auto series = CreateDenseArray<float>({1, 2, 3, 4, 5, 6, 7, 8}); ASSERT_OK_AND_ASSIGN(auto edge, CreateEdgeFromSplitPoints({0, 8})); EXPECT_THAT(InvokeOperator<DenseArray<float>>(kAggMovingAverage, series, int64_t{0}, edge), IsOkAndHolds(ElementsAre(NA, NA, NA, NA, NA, NA, NA, NA))); } TEST(AggMovingAverage, WindowSizeEqualToInputArraySize) { const auto series = CreateDenseArray<float>({1, 2, 3, 4, 5, 6, 7, 8}); ASSERT_OK_AND_ASSIGN(auto edge, CreateEdgeFromSplitPoints({0, 8})); EXPECT_THAT(InvokeOperator<DenseArray<float>>(kAggMovingAverage, series, int64_t{8}, edge), IsOkAndHolds(ElementsAre(NA, NA, NA, NA, NA, NA, NA, 4.5))); } TEST(AggMovingAverage, WindowSizeLargerThanInputArraySize) { const auto series = CreateDenseArray<float>({1, 2, 3, 4, 5, 6, 7, 8}); ASSERT_OK_AND_ASSIGN(auto edge, CreateEdgeFromSplitPoints({0, 8})); EXPECT_THAT(InvokeOperator<DenseArray<float>>(kAggMovingAverage, series, int64_t{9}, edge), IsOkAndHolds(ElementsAre(NA, NA, NA, NA, NA, NA, NA, NA))); } TEST(AggMovingAverage, EmptyTimeSeries) { ASSERT_OK_AND_ASSIGN(auto edge, CreateEdgeFromSplitPoints({0})); EXPECT_THAT(InvokeOperator<DenseArray<float>>( kAggMovingAverage, DenseArray<float>(), int64_t{3}, edge), IsOkAndHolds(ElementsAre())); } TEST(AggMovingAverage, FullTimeSeriesWithTwoGroups) { const auto series = CreateDenseArray<float>({1, 2, 3, 4, 5, 6, 7, 8}); ASSERT_OK_AND_ASSIGN(auto edge, CreateEdgeFromSplitPoints({0, 4, 8})); EXPECT_THAT(InvokeOperator<DenseArray<float>>(kAggMovingAverage, series, int64_t{3}, edge), IsOkAndHolds(ElementsAre(NA, NA, 2, 3, NA, NA, 6, 7))); } TEST(ExponentialWeightedMovingAverageOpTest, MissingValue_Adjust) { const auto series = CreateDenseArray<float>({1, 2, 3, NA, 5, 6, 7, 8}); EXPECT_THAT( InvokeOperator<DenseArray<float>>("experimental.ewma", series, 0.6, true, false), IsOkAndHolds(ElementsAre(1., 1.71428571, 2.53846154, 2.53846154, 4.50832266, 5.50288031, 6.43861754, 7.39069488))); } TEST(ExponentialWeightedMovingAverageOpTest, MissingValue_Adjust_IgnoreMissing) { const auto series = CreateDenseArray<float>({1, 2, 3, NA, 5, 6, 7, 8}); EXPECT_THAT( InvokeOperator<DenseArray<float>>("experimental.ewma", series, 0.6, true, true), IsOkAndHolds(ElementsAre(1., 1.71428571, 2.53846154, 2.53846154, 4.05418719, 5.23375364, 6.29786003, 7.32082003))); } TEST(ExponentialWeightedMovingAverageOpTest, FirstMissing_Adjust) { const auto series = CreateDenseArray<float>({NA, 2, 3}); EXPECT_THAT( InvokeOperator<DenseArray<float>>("experimental.ewma", series, 0.6, true, false), IsOkAndHolds(ElementsAre(NA, 2., 2.71428571))); } TEST(ExponentialWeightedMovingAverageOpTest, FirstTwoMissing_Adjust) { const auto series = CreateDenseArray<float>({NA, NA, 3, NA, 5}); EXPECT_THAT( InvokeOperator<DenseArray<float>>("experimental.ewma", series, 0.6, true, false), IsOkAndHolds(ElementsAre(NA, NA, 3., 3., 4.72413793))); } TEST(ExponentialWeightedMovingAverageOpTest, FirstTwoMissing_Adjust_IgnoreMissing) { const auto series = CreateDenseArray<float>({NA, NA, 3, NA, 5}); EXPECT_THAT( InvokeOperator<DenseArray<float>>("experimental.ewma", series, 0.6, true, true), IsOkAndHolds(ElementsAre(NA, NA, 3., 3., 4.42857143))); } TEST(ExponentialWeightedMovingAverageOpTest, AlphaLessThanZero_Adjust) { const auto series = CreateDenseArray<float>({NA, 2, 3}); ASSERT_THAT(InvokeOperator<DenseArray<float>>("experimental.ewma", series, -1.2, true, false), StatusIs(absl::StatusCode::kInvalidArgument)); } TEST(ExponentialWeightedMovingAverageOpTest, AlphaEqualsZero_Adjust) { const auto series = CreateDenseArray<float>({NA, 2, 3}); ASSERT_THAT(InvokeOperator<DenseArray<float>>("experimental.ewma", series, 0., true, false), StatusIs(absl::StatusCode::kInvalidArgument)); } TEST(ExponentialWeightedMovingAverageOpTest, AlphaGreaterThanOne_Adjust) { const auto series = CreateDenseArray<float>({NA, 2, 3}); ASSERT_THAT( InvokeOperator<DenseArray<float>>("experimental.ewma", series, 1.2, true, false), StatusIs(absl::StatusCode::kInvalidArgument)); } TEST(ExponentialWeightedMovingAverageOpTest, AlphaEqualsOne_Adjust) { const auto series = CreateDenseArray<float>({1, 2, 3, NA, 5}); EXPECT_THAT(InvokeOperator<DenseArray<float>>("experimental.ewma", series, 1., true, false), IsOkAndHolds(ElementsAre(1, 2, 3, 3, 5))); } TEST(ExponentialWeightedMovingAverageOpTest, AlphaEqualsOne_Adjust_IgnoreMissing) { const auto series = CreateDenseArray<float>({1, 2, 3, NA, 5}); EXPECT_THAT(InvokeOperator<DenseArray<float>>("experimental.ewma", series, 1., true, true), IsOkAndHolds(ElementsAre(1, 2, 3, 3, 5))); } TEST(ExponentialWeightedMovingAverageOpTest, AlphaEqualsOne_Adjust_FirstMissing) { const auto series = CreateDenseArray<float>({NA, 2, 3, NA, 5}); EXPECT_THAT(InvokeOperator<DenseArray<float>>("experimental.ewma", series, 1., true, false), IsOkAndHolds(ElementsAre(NA, 2, 3, 3, 5))); } TEST(ExponentialWeightedMovingAverageOpTest, EmptyTimeSeries) { EXPECT_THAT(InvokeOperator<DenseArray<float>>("experimental.ewma", DenseArray<float>(), 1., false, false), IsOkAndHolds(ElementsAre())); } TEST(ExponentialWeightedMovingAverageOpTest, MissingValue) { const auto series = CreateDenseArray<float>({1, 2, 3, NA, 5, 6, 7, 8}); EXPECT_THAT( InvokeOperator<DenseArray<float>>("experimental.ewma", series, 0.6, false, false), IsOkAndHolds(ElementsAre(1., 1.6, 2.44, 2.44, 4.46105263, 5.38442105, 6.35376842, 7.34150737))); } TEST(ExponentialWeightedMovingAverageOpTest, MissingValue_IgnoreMissing) { const auto series = CreateDenseArray<float>({1, 2, 3, NA, 5, 6, 7, 8}); EXPECT_THAT( InvokeOperator<DenseArray<float>>("experimental.ewma", series, 0.6, false, true), IsOkAndHolds( ElementsAre(1., 1.6, 2.44, 2.44, 3.976, 5.1904, 6.27616, 7.310464))); } TEST(ExponentialWeightedMovingAverageOpTest, FirstMissing) { const auto series = CreateDenseArray<float>({NA, 2, 3}); EXPECT_THAT( InvokeOperator<DenseArray<float>>("experimental.ewma", series, 0.6, false, false), IsOkAndHolds(ElementsAre(NA, 2., 2.6))); } TEST(ExponentialWeightedMovingAverageOpTest, FirstTwoMissing) { const auto series = CreateDenseArray<float>({NA, NA, 3, NA, 5}); EXPECT_THAT( InvokeOperator<DenseArray<float>>("experimental.ewma", series, 0.6, false, false), IsOkAndHolds(ElementsAre(NA, NA, 3., 3., 4.57894737))); } TEST(ExponentialWeightedMovingAverageOpTest, FirstTwoMissing_IgnoreMissing) { const auto series = CreateDenseArray<float>({NA, NA, 3, NA, 5}); EXPECT_THAT( InvokeOperator<DenseArray<float>>("experimental.ewma", series, 0.6, false, true), IsOkAndHolds(ElementsAre(NA, NA, 3, 3, 4.2))); } TEST(ExponentialWeightedMovingAverageOpTest, AlphaLessThanZero) { const auto series = CreateDenseArray<float>({NA, 2, 3}); ASSERT_THAT(InvokeOperator<DenseArray<float>>("experimental.ewma", series, -1.2, false, false), StatusIs(absl::StatusCode::kInvalidArgument)); } TEST(ExponentialWeightedMovingAverageOpTest, AlphaEqualsZero) { const auto series = CreateDenseArray<float>({NA, 2, 3}); ASSERT_THAT(InvokeOperator<DenseArray<float>>("experimental.ewma", series, 0., false, false), StatusIs(absl::StatusCode::kInvalidArgument)); } TEST(ExponentialWeightedMovingAverageOpTest, AlphaGreaterThanOne) { const auto series = CreateDenseArray<float>({NA, 2, 3}); ASSERT_THAT( InvokeOperator<DenseArray<float>>("experimental.ewma", series, 1.2, false, false), StatusIs(absl::StatusCode::kInvalidArgument)); } TEST(ExponentialWeightedMovingAverageOpTest, AlphaEqualsOne) { const auto series = CreateDenseArray<float>({1, 2, 3, NA, 5}); EXPECT_THAT(InvokeOperator<DenseArray<float>>("experimental.ewma", series, 1., false, false), IsOkAndHolds(ElementsAre(1, 2, 3, 3, 5))); } TEST(ExponentialWeightedMovingAverageOpTest, AlphaEqualsOne_IgnoreMissing) { const auto series = CreateDenseArray<float>({1, 2, 3, NA, 5}); EXPECT_THAT(InvokeOperator<DenseArray<float>>("experimental.ewma", series, 1., false, true), IsOkAndHolds(ElementsAre(1, 2, 3, 3, 5))); } TEST(ExponentialWeightedMovingAverageOpTest, AlphaEqualsOne_FirstMissing) { const auto series = CreateDenseArray<float>({NA, 2, 3, NA, 5}); EXPECT_THAT(InvokeOperator<DenseArray<float>>("experimental.ewma", series, 1., false, false), IsOkAndHolds(ElementsAre(NA, 2, 3, 3, 5))); } } }
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/qexpr/operators/experimental/dense_array/timeseries.h
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/qexpr/operators/experimental/dense_array/timeseries_test.cc
1ca990dbeca224035efdabffecc7f3738df6b52c
ba7b5bf3-c665-4206-9012-cb249e157cf2
cpp
google/arolla
cast_operator
arolla/qexpr/operators/core/cast_operator.h
arolla/qexpr/operators/core/cast_operator_test.cc
#ifndef AROLLA_OPERATORS_CORE_CAST_OPERATOR_H_ #define AROLLA_OPERATORS_CORE_CAST_OPERATOR_H_ #include <cstdint> #include <limits> #include <tuple> #include <type_traits> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "arolla/memory/optional_value.h" #include "arolla/util/meta.h" #include "arolla/util/repr.h" namespace arolla { template <typename DST> struct CastOp { using run_on_missing = std::true_type; using DstTypes = meta::type_list<bool, int32_t, int64_t, uint64_t, float, double>; using SrcTypes = meta::type_list<bool, int32_t, int64_t, uint64_t, float, double>; static_assert(meta::contains_v<DstTypes, DST>); template <typename SRC> static constexpr SRC max_float_to_int_safe_value() { using dst_limits = std::numeric_limits<DST>; using src_limits = std::numeric_limits<SRC>; static_assert(dst_limits::is_integer); static_assert(std::is_floating_point_v<SRC>); SRC result = 0; int i = 0; for (; i < src_limits::digits; ++i) { result *= 2; result += 1; } for (; i < dst_limits::digits; ++i) { result *= 2; } for (; i > dst_limits::digits; --i) { result /= 2; } return result; } template <typename SRC> static constexpr SRC min_float_to_int_safe_value() { using dst_limits = std::numeric_limits<DST>; using src_limits = std::numeric_limits<SRC>; static_assert(dst_limits::is_integer); static_assert(std::is_floating_point_v<SRC>); if constexpr (!dst_limits::is_signed) { return 0.0; } else { SRC result = 1; int i = 0; for (; i < src_limits::digits; ++i) { result *= 2; } for (; i < dst_limits::digits; ++i) { result *= 2; } for (; i > dst_limits::digits; --i) { result += 1; result /= 2; } return -result; } } template <typename SRC> static constexpr auto safe_range() { static_assert(meta::contains_v<SrcTypes, SRC>); using dst_limits = std::numeric_limits<DST>; using src_limits = std::numeric_limits<SRC>; if constexpr (std::is_same_v<SRC, DST>) { return std::make_tuple(); } else if constexpr (std::is_integral_v<DST> && std::is_integral_v<SRC>) { constexpr SRC safe_min = std::max<int64_t>(dst_limits::min(), src_limits::min()); constexpr SRC safe_max = std::min<uint64_t>(dst_limits::max(), src_limits::max()); if constexpr (safe_min <= src_limits::min() && safe_max >= src_limits::max()) { return std::make_tuple(); } else { return std::tuple<SRC, SRC>(safe_min, safe_max); } } else if constexpr (std::is_integral_v<DST> && std::is_floating_point_v<SRC>) { return std::tuple<SRC, SRC>(min_float_to_int_safe_value<SRC>(), max_float_to_int_safe_value<SRC>()); } else if constexpr (std::is_floating_point_v<DST> && std::is_floating_point_v<SRC>) { constexpr bool ub_check = (src_limits::max() <= dst_limits::max() || static_cast<DST>(src_limits::max()) == dst_limits::max() || static_cast<DST>(src_limits::max()) == dst_limits::infinity()); static_assert(ub_check); return std::make_tuple(); } else { return std::make_tuple(); } } template <typename SRC> auto operator()(SRC src) const { constexpr auto src_range = safe_range<SRC>(); if constexpr (std::tuple_size_v<decltype(src_range)> == 0) { return static_cast<DST>(src); } else { using ReturnType = absl::StatusOr<DST>; const auto& [range_min, range_max] = src_range; if (range_min <= src && src <= range_max) { return ReturnType(static_cast<DST>(src)); } else { return ReturnType(absl::InvalidArgumentError(absl::StrCat( "cannot cast ", ::arolla::Repr(src), " to ", std::is_unsigned_v<DST> ? "u" : "", "int", 8 * sizeof(DST)))); } } } }; struct ToBoolOp { using run_on_missing = std::true_type; template <typename T> bool operator()(const T& x) const { return x != 0; } }; struct ToOptionalOp { using run_on_missing = std::true_type; template <typename T> OptionalValue<T> operator()(const T& x) const { return OptionalValue<T>(x); } }; struct GetOptionalValueOp { template <typename T> absl::StatusOr<T> operator()(const OptionalValue<T>& x) const { if (!x.present) { return absl::FailedPreconditionError( "core.get_optional_value expects present value, got missing"); } return x.value; } }; } #endif
#include "arolla/qexpr/operators/core/cast_operator.h" #include <cmath> #include <cstdint> #include <limits> #include <tuple> #include <type_traits> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "absl/status/status_matchers.h" #include "arolla/util/meta.h" namespace arolla { namespace { using ::absl_testing::IsOkAndHolds; using ::absl_testing::StatusIs; using ::testing::Eq; TEST(CastOperatorTest, CastToInt32UB) { constexpr auto kInt32Min = std::numeric_limits<int32_t>::min(); constexpr auto kInt32Max = std::numeric_limits<int32_t>::max(); constexpr auto kDoubleInt32Min = static_cast<double>(kInt32Min); constexpr auto kDoubleInt32Max = static_cast<double>(kInt32Max); const auto to_int32 = CastOp<int32_t>(); EXPECT_THAT(to_int32(kDoubleInt32Min), IsOkAndHolds(kInt32Min)); EXPECT_THAT(to_int32(kDoubleInt32Max), IsOkAndHolds(kInt32Max)); EXPECT_THAT(to_int32(std::nextafter(kDoubleInt32Min - 1., 0.)), IsOkAndHolds(kInt32Min)); EXPECT_THAT(to_int32(std::nextafter(kDoubleInt32Max + 1., 0.)), IsOkAndHolds(kInt32Max)); EXPECT_THAT(to_int32(kDoubleInt32Min - 1.), StatusIs(absl::StatusCode::kInvalidArgument, "cannot cast float64{-2147483649} to int32")); EXPECT_THAT(to_int32(kDoubleInt32Max + 1.), StatusIs(absl::StatusCode::kInvalidArgument, "cannot cast float64{2147483648} to int32")); } TEST(CastOperatorTest, CastFromUInt64) { EXPECT_THAT((CastOp<int32_t>()(uint64_t{1})), IsOkAndHolds(int32_t{1})); EXPECT_THAT((CastOp<float>()(uint64_t{1})), Eq(1.0f)); EXPECT_THAT((CastOp<double>()(uint64_t{1})), Eq(1.0)); EXPECT_THAT((CastOp<int64_t>()(uint64_t{1ull << 63})), StatusIs(absl::StatusCode::kInvalidArgument, "cannot cast uint64{9223372036854775808} to int64")); } TEST(CastOperatorTest, CastToUInt64) { CastOp<uint64_t> to_uint64; EXPECT_THAT(to_uint64(std::numeric_limits<int64_t>::max()), IsOkAndHolds(uint64_t{std::numeric_limits<int64_t>::max()})); EXPECT_THAT(to_uint64(double{1.0}), IsOkAndHolds(uint64_t{1})); EXPECT_THAT(to_uint64(float{1.0f}), IsOkAndHolds(uint64_t{1})); EXPECT_THAT(to_uint64(uint64_t{1}), Eq(uint64_t{1})); EXPECT_THAT(to_uint64(float{-1.0f}), StatusIs(absl::StatusCode::kInvalidArgument, "cannot cast -1. to uint64")); EXPECT_THAT(to_uint64(double{-1.0f}), StatusIs(absl::StatusCode::kInvalidArgument, "cannot cast float64{-1} to uint64")); EXPECT_THAT( to_uint64(int32_t{-1}), StatusIs(absl::StatusCode::kInvalidArgument, "cannot cast -1 to uint64")); EXPECT_THAT(to_uint64(int64_t{-1}), StatusIs(absl::StatusCode::kInvalidArgument, "cannot cast int64{-1} to uint64")); } TEST(CastOperatorTest, CastTo_SafeRange_FloatToInt) { using Srcs = meta::type_list<float, double>; using Dsts = meta::type_list<int32_t, int64_t, uint64_t>; meta::foreach_type<Srcs>([](auto src_type) { using SRC = typename decltype(src_type)::type; meta::foreach_type<Dsts>([](auto dst_type) { using DST = typename decltype(dst_type)::type; using dst_limits = std::numeric_limits<DST>; using src_limits = std::numeric_limits<SRC>; const auto [range_min, range_max] = CastOp<DST>::template safe_range<SRC>(); ASSERT_EQ(static_cast<DST>(range_min), dst_limits::min()); if (!std::is_unsigned_v<DST>) { ASSERT_NE( std::trunc(range_min), std::trunc(std::nextafter(range_min, -src_limits::infinity()))); } ASSERT_LE(static_cast<DST>(range_max), dst_limits::max()); ASSERT_GE(std::nextafter(range_max, src_limits::infinity()), std::exp2(static_cast<SRC>(dst_limits::digits))); }); }); } TEST(CastOperatorTest, CastTo_SafeRange_IntToInt) { ASSERT_EQ(CastOp<int32_t>::safe_range<uint64_t>(), (std::tuple<uint64_t, uint64_t>(0, (1ull << 31) - 1))); ASSERT_EQ(CastOp<int64_t>::safe_range<uint64_t>(), (std::tuple<uint64_t, uint64_t>(0, (1ull << 63) - 1))); ASSERT_EQ(CastOp<uint64_t>::safe_range<int32_t>(), (std::tuple<uint32_t, uint32_t>(0, (1u << 31) - 1))); ASSERT_EQ(CastOp<uint64_t>::safe_range<int64_t>(), (std::tuple<int64_t, int64_t>(0, (1ull << 63) - 1))); } TEST(CastOperatorTest, CastTo_SafeRange_Unneeded) { ASSERT_EQ(CastOp<int64_t>::safe_range<int32_t>(), std::tuple<>()); ASSERT_EQ(CastOp<int32_t>::safe_range<bool>(), std::tuple<>()); ASSERT_EQ(CastOp<float>::safe_range<double>(), std::tuple<>()); ASSERT_EQ(CastOp<double>::safe_range<float>(), std::tuple<>()); } } }
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/qexpr/operators/core/cast_operator.h
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/qexpr/operators/core/cast_operator_test.cc
1ca990dbeca224035efdabffecc7f3738df6b52c
558067bd-0e7a-47f3-aa77-bf649891f270
cpp
google/arolla
logic_operators
arolla/qexpr/operators/core/logic_operators.h
arolla/qexpr/operators/core/logic_operators_test.cc
#ifndef AROLLA_OPERATORS_CORE_LOGIC_OPERATORS_H_ #define AROLLA_OPERATORS_CORE_LOGIC_OPERATORS_H_ #include <memory> #include <type_traits> #include "absl/status/status.h" #include "absl/status/statusor.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/memory/optional_value.h" #include "arolla/qexpr/operator_errors.h" #include "arolla/qexpr/operators.h" #include "arolla/qexpr/qexpr_operator_signature.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/standard_type_properties/common_qtype.h" #include "arolla/util/status.h" #include "arolla/util/unit.h" namespace arolla { struct HasOp { using run_on_missing = std::true_type; template <typename T> std::enable_if_t<is_optional_v<T>, OptionalUnit> operator()( const T& arg) const { return OptionalUnit{arg.present}; } }; struct PresenceOrOp { using run_on_missing = std::true_type; template <typename T> T operator()(const OptionalValue<T>& lhs, const T& rhs) const { return lhs.present ? lhs.value : rhs; } template <typename T> OptionalValue<T> operator()(const OptionalValue<T>& lhs, const OptionalValue<T>& rhs) const { return lhs.present ? lhs : rhs; } template <typename T> T operator()(const T& lhs, const OptionalValue<T>& rhs) const { return lhs; } template <typename T> T operator()(const T& lhs, const T& rhs) const { return lhs; } template <typename T, class Fn> auto operator()(const OptionalValue<T>& lhs, const Fn& rhs) const { using result_t = strip_statusor_t<std::decay_t<decltype(rhs())>>; if constexpr (std::is_same_v<result_t, T>) { return lhs.present ? lhs.value : rhs(); } else { return lhs.present ? lhs : rhs(); } } template <typename T, class Fn> T operator()(const T& lhs, const Fn&) const { return lhs; } }; struct PresenceAndOp { using run_on_missing = std::true_type; template <typename T, std::enable_if_t<!std::is_invocable_v<T>, bool> = true> const T& operator()(const T& lhs, Unit) const { return lhs; } template <typename T, std::enable_if_t<!std::is_invocable_v<T>, bool> = true> OptionalValue<T> operator()(const T& lhs, OptionalUnit rhs) const { return rhs ? lhs : OptionalValue<T>{}; } template <typename T> OptionalValue<T> operator()(const OptionalValue<T>& lhs, OptionalUnit rhs) const { return rhs ? lhs : OptionalValue<T>{}; } template <typename Fn, std::enable_if_t<std::is_invocable_v<Fn>, bool> = true> auto operator()(const Fn& lhs, Unit) const { return lhs(); } template <typename Fn, std::enable_if_t<std::is_invocable_v<Fn>, bool> = true> auto operator()(const Fn& lhs, OptionalUnit rhs) const { using T = strip_optional_t<strip_statusor_t<std::decay_t<decltype(lhs())>>>; constexpr bool is_status = IsStatusOrT<std::decay_t<decltype(lhs())>>::value; constexpr bool is_optional = is_optional_v<strip_statusor_t<std::decay_t<decltype(lhs())>>>; if constexpr (is_status) { if constexpr (is_optional) { return rhs ? lhs() : OptionalValue<T>{}; } else { return rhs ? MakeStatusOrOptionalValue(lhs()) : OptionalValue<T>{}; } } else { return rhs ? lhs() : OptionalValue<T>{}; } } }; struct WhereOp { using run_on_missing = std::true_type; template <typename T, std::enable_if_t<!std::is_invocable_v<T>, bool> = true> T operator()(OptionalUnit c, const T& a, const T& b) const { return c.present ? a : b; } template < typename AFn, typename BFn, std::enable_if_t<std::is_invocable_v<AFn> && std::is_invocable_v<BFn>, bool> = true> auto operator()(OptionalUnit c, const AFn& a, const BFn& b) const { return c.present ? a() : b(); } template < typename AFn, typename T, std::enable_if_t<std::is_invocable_v<AFn> && !std::is_invocable_v<T>, bool> = true> auto operator()(OptionalUnit c, const AFn& a, const T& b) const { return c.present ? a() : b; } template < typename BFn, typename T, std::enable_if_t<!std::is_invocable_v<T> && std::is_invocable_v<BFn>, bool> = true> auto operator()(OptionalUnit c, const T& a, const BFn& b) const { return c.present ? a : b(); } }; struct PresenceAndOrOp { using run_on_missing = std::true_type; template <typename T> OptionalValue<T> operator()(const OptionalValue<T>& a, OptionalUnit b, const OptionalValue<T>& c) const { return b && a.present ? a : c; } template <typename T> T operator()(const OptionalValue<T>& a, OptionalUnit b, const T& c) const { return b && a.present ? a.value : c; } template <typename T> OptionalValue<T> operator()(const T& a, OptionalUnit b, const OptionalValue<T>& c) const { return b ? MakeOptionalValue(a) : c; } template <typename T> T operator()(const T& a, OptionalUnit b, const T& c) const { return b ? a : c; } template <typename T, class Fn> auto operator()(const OptionalValue<T>& a, OptionalUnit b, const Fn& c) const { using result_t = strip_statusor_t<std::decay_t<decltype(c())>>; if constexpr (std::is_same_v<result_t, T>) { return b && a.present ? a.value : c(); } else { return b && a.present ? a : c(); } } template <typename T, class Fn> auto operator()(const T& a, OptionalUnit b, const Fn& c) const { using result_t = strip_statusor_t<std::decay_t<decltype(c())>>; if constexpr (std::is_same_v<result_t, T>) { return b ? a : c(); } else { return b ? MakeOptionalValue(a) : c(); } } }; struct PresenceNotOp { using run_on_missing = std::true_type; template <class T> OptionalUnit operator()(const OptionalValue<T>& arg) const { return OptionalUnit{!arg.present}; } }; struct MaskEqualOp { using run_on_missing = std::true_type; template <typename T> OptionalUnit operator()(const T& lhs, const T& rhs) const { return OptionalUnit{lhs == rhs}; } }; struct MaskNotEqualOp { using run_on_missing = std::true_type; template <typename T> OptionalUnit operator()(const T& lhs, const T& rhs) const { return OptionalUnit{lhs != rhs}; } }; struct MaskLessOp { using run_on_missing = std::true_type; template <typename T> OptionalUnit operator()(const T& lhs, const T& rhs) const { return OptionalUnit{lhs < rhs}; } }; struct MaskLessEqualOp { using run_on_missing = std::true_type; template <typename T> OptionalUnit operator()(const T& lhs, const T& rhs) const { return OptionalUnit{(lhs < rhs) || (lhs == rhs)}; } }; class FakeShortCircuitWhereOperatorFamily final : public OperatorFamily { absl::StatusOr<OperatorPtr> DoGetOperator( absl::Span<const QTypePtr> input_types, QTypePtr output_type) const final { auto not_defined_error = [&](absl::string_view detail) { return OperatorNotDefinedError("core._short_circuit_where", input_types, detail); }; if (input_types.size() < 3) { return not_defined_error("expected 3 arguments"); } if (input_types[0] != GetQType<OptionalUnit>()) { return not_defined_error("first argument must be OPTIONAL_UNIT"); } QTypePtr true_type = input_types[1]; QTypePtr false_type = input_types[2]; const QType* common_type = CommonQType(true_type, false_type, false); if (common_type == nullptr) { return not_defined_error("no common type between operator branches"); } return EnsureOutputQTypeMatches( std::make_unique<FakeShortCircuitWhereOperator>( QExprOperatorSignature::Get( {GetQType<OptionalUnit>(), common_type, common_type}, common_type)), input_types, output_type); } class FakeShortCircuitWhereOperator final : public QExprOperator { public: explicit FakeShortCircuitWhereOperator( const QExprOperatorSignature* signature) : QExprOperator(signature) {} private: absl::StatusOr<std::unique_ptr<BoundOperator>> DoBind( absl::Span<const TypedSlot> input_slots, TypedSlot output_slot) const override { return absl::InternalError( "FakeShortCircuitWhereOperator is not supposed to be used"); } }; }; } #endif
#include "arolla/qexpr/operators/core/logic_operators.h" #include <cstdint> #include <string> #include <type_traits> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "absl/status/status_matchers.h" #include "absl/status/statusor.h" #include "arolla/array/qtype/types.h" #include "arolla/dense_array/dense_array.h" #include "arolla/dense_array/qtype/types.h" #include "arolla/memory/optional_value.h" #include "arolla/qexpr/operators.h" #include "arolla/qexpr/qexpr_operator_signature.h" #include "arolla/qtype/optional_qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/util/text.h" #include "arolla/util/unit.h" namespace arolla { namespace { using ::absl_testing::IsOkAndHolds; using ::absl_testing::StatusIs; using ::testing::Eq; using ::testing::HasSubstr; using ::testing::Pointee; using ::testing::Property; using Oi64 = OptionalValue<int64_t>; using DAi64 = DenseArray<int64_t>; const int64_t one = 1; const int64_t two = 2; const Oi64 optional_one = 1; const Oi64 optional_two = 2; const Oi64 missing; TEST(LogicOperatorsTest, PresenceOr) { EXPECT_THAT( InvokeOperator<OptionalUnit>("core.presence_or", kPresent, kPresent), IsOkAndHolds(kPresent)); EXPECT_THAT( InvokeOperator<OptionalUnit>("core.presence_or", kPresent, kMissing), IsOkAndHolds(kPresent)); EXPECT_THAT( InvokeOperator<OptionalUnit>("core.presence_or", kMissing, kMissing), IsOkAndHolds(kMissing)); EXPECT_THAT(InvokeOperator<int64_t>("core.presence_or", one, one), IsOkAndHolds(one)); EXPECT_THAT(InvokeOperator<int64_t>("core.presence_or", one, optional_two), IsOkAndHolds(one)); EXPECT_THAT(InvokeOperator<int64_t>("core.presence_or", missing, one), IsOkAndHolds(one)); EXPECT_THAT(InvokeOperator<int64_t>("core.presence_or", optional_two, one), IsOkAndHolds(two)); EXPECT_THAT( InvokeOperator<Oi64>("core.presence_or", optional_two, optional_one), IsOkAndHolds(optional_two)); EXPECT_THAT(InvokeOperator<Oi64>("core.presence_or", optional_two, missing), IsOkAndHolds(optional_two)); EXPECT_THAT(InvokeOperator<Oi64>("core.presence_or", missing, optional_two), IsOkAndHolds(optional_two)); EXPECT_THAT(InvokeOperator<Oi64>("core.presence_or", missing, missing), IsOkAndHolds(missing)); } TEST(LogicOperatorsTest, LazyPresenceOrFunctor) { auto as_fn = [](auto x) { return [x]() { return x; }; }; auto as_no_call_fn = [](auto x) { return [x]() { ADD_FAILURE() << "function shouldn't be called"; return x; }; }; EXPECT_EQ(PresenceOrOp{}(kPresent, as_no_call_fn(kPresent)), kPresent); EXPECT_EQ(PresenceOrOp{}(kPresent, as_no_call_fn(kMissing)), kPresent); EXPECT_EQ(PresenceOrOp{}(kMissing, as_fn(kMissing)), kMissing); EXPECT_EQ(PresenceOrOp{}(one, as_no_call_fn(one)), one); EXPECT_EQ(PresenceOrOp{}(one, as_no_call_fn(optional_two)), one); EXPECT_EQ(PresenceOrOp{}(missing, as_fn(one)), one); EXPECT_EQ(PresenceOrOp{}(optional_two, as_no_call_fn(one)), two); EXPECT_EQ(PresenceOrOp{}(optional_two, as_no_call_fn(optional_one)), optional_two); EXPECT_EQ(PresenceOrOp{}(optional_two, as_no_call_fn(missing)), optional_two); EXPECT_EQ(PresenceOrOp{}(missing, as_fn(optional_two)), optional_two); EXPECT_EQ(PresenceOrOp{}(missing, as_fn(missing)), missing); } TEST(LogicOperatorsTest, WhereOperatorFamily) { EXPECT_THAT(OperatorRegistry::GetInstance()->LookupOperator( "core.where", {GetQType<OptionalUnit>(), GetQType<int32_t>(), GetOptionalQType<int64_t>()}, GetOptionalQType<int64_t>()), IsOkAndHolds(Pointee(Property( &QExprOperator::signature, Eq(QExprOperatorSignature::Get( {GetQType<OptionalUnit>(), GetOptionalQType<int64_t>(), GetOptionalQType<int64_t>()}, GetOptionalQType<int64_t>())))))); EXPECT_THAT(OperatorRegistry::GetInstance()->LookupOperator( "core.where", {GetQType<OptionalUnit>(), GetQType<int32_t>(), GetDenseArrayQType<int64_t>()}, GetDenseArrayQType<int64_t>()), IsOkAndHolds(Pointee(Property( &QExprOperator::signature, Eq(QExprOperatorSignature::Get( {GetQType<OptionalUnit>(), GetDenseArrayQType<int64_t>(), GetDenseArrayQType<int64_t>()}, GetDenseArrayQType<int64_t>())))))); EXPECT_THAT(OperatorRegistry::GetInstance()->LookupOperator( "core.where", {GetQType<OptionalUnit>(), GetQType<int32_t>(), GetArrayQType<int64_t>()}, GetArrayQType<int64_t>()), IsOkAndHolds(Pointee(Property( &QExprOperator::signature, Eq(QExprOperatorSignature::Get( {GetQType<OptionalUnit>(), GetArrayQType<int64_t>(), GetArrayQType<int64_t>()}, GetArrayQType<int64_t>())))))); EXPECT_THAT( OperatorRegistry::GetInstance()->LookupOperator( "core.where", {GetDenseArrayQType<Unit>(), GetQType<int32_t>(), GetQType<int64_t>()}, GetDenseArrayQType<int64_t>()), IsOkAndHolds(Pointee(Property( &QExprOperator::signature, Eq(QExprOperatorSignature::Get( {GetDenseArrayQType<Unit>(), GetDenseArrayQType<int64_t>(), GetDenseArrayQType<int64_t>()}, GetDenseArrayQType<int64_t>())))))); EXPECT_THAT( OperatorRegistry::GetInstance()->LookupOperator( "core.where", {GetArrayQType<Unit>(), GetQType<int32_t>(), GetQType<int64_t>()}, GetArrayQType<int64_t>()), IsOkAndHolds( Pointee(Property(&QExprOperator::signature, Eq(QExprOperatorSignature::Get( {GetArrayQType<Unit>(), GetArrayQType<int64_t>(), GetArrayQType<int64_t>()}, GetArrayQType<int64_t>())))))); } TEST(LogicOperatorsTest, LazyWhereFunctor) { auto as_fn = [](auto x) { return [x]() { return x; }; }; auto as_no_call_fn = [](auto x) { return [x]() { ADD_FAILURE() << "function shouldn't be called"; return x; }; }; EXPECT_EQ(WhereOp{}(kPresent, as_fn(kPresent), as_no_call_fn(kPresent)), kPresent); EXPECT_EQ(WhereOp{}(kPresent, as_fn(kMissing), as_no_call_fn(kPresent)), kMissing); EXPECT_EQ(WhereOp{}(kMissing, as_no_call_fn(kPresent), as_fn(kPresent)), kPresent); EXPECT_EQ(WhereOp{}(kMissing, as_no_call_fn(kPresent), as_fn(kMissing)), kMissing); EXPECT_EQ(WhereOp{}(kPresent, kPresent, as_no_call_fn(kPresent)), kPresent); EXPECT_EQ(WhereOp{}(kPresent, kMissing, as_no_call_fn(kPresent)), kMissing); EXPECT_EQ(WhereOp{}(kMissing, as_no_call_fn(kPresent), kPresent), kPresent); EXPECT_EQ(WhereOp{}(kMissing, as_no_call_fn(kPresent), kMissing), kMissing); auto as_status_fn = [](auto x) { return [x]() { return absl::StatusOr<OptionalUnit>(x); }; }; EXPECT_THAT(WhereOp{}(kPresent, as_status_fn(kPresent), kPresent), IsOkAndHolds(kPresent)); EXPECT_THAT(WhereOp{}(kMissing, kPresent, as_status_fn(kPresent)), IsOkAndHolds(kPresent)); EXPECT_THAT( WhereOp{}(kPresent, as_status_fn(kPresent), as_no_call_fn(kPresent)), IsOkAndHolds(kPresent)); EXPECT_THAT( WhereOp{}(kMissing, as_no_call_fn(kPresent), as_status_fn(kPresent)), IsOkAndHolds(kPresent)); EXPECT_THAT( WhereOp{}(kPresent, as_status_fn(kPresent), as_status_fn(kPresent)), IsOkAndHolds(kPresent)); auto as_error_status_fn = []() { return []() { return absl::StatusOr<OptionalUnit>(absl::UnimplementedError("")); }; }; EXPECT_THAT(WhereOp{}(kPresent, as_status_fn(kPresent), as_error_status_fn()), IsOkAndHolds(kPresent)); EXPECT_THAT(WhereOp{}(kPresent, as_error_status_fn(), as_status_fn(kPresent)) .status(), StatusIs(absl::StatusCode::kUnimplemented)); EXPECT_THAT( WhereOp{}(kPresent, as_error_status_fn(), as_fn(kPresent)).status(), StatusIs(absl::StatusCode::kUnimplemented)); EXPECT_THAT(WhereOp{}(kPresent, as_error_status_fn(), kPresent).status(), StatusIs(absl::StatusCode::kUnimplemented)); } TEST(LogicOperatorsTest, LazyPresenceOrWithStatusFunctor) { auto as_fn = [](auto x) { return [x]() { return absl::StatusOr<std::decay_t<decltype(x)>>(x); }; }; EXPECT_THAT(PresenceOrOp{}(kPresent, as_fn(kPresent)), IsOkAndHolds(kPresent)); EXPECT_THAT(PresenceOrOp{}(kPresent, as_fn(kMissing)), IsOkAndHolds(kPresent)); EXPECT_THAT(PresenceOrOp{}(kMissing, as_fn(kMissing)), IsOkAndHolds(kMissing)); EXPECT_THAT(PresenceOrOp{}(one, as_fn(one)), Eq(one)); EXPECT_THAT(PresenceOrOp{}(one, as_fn(optional_two)), Eq(one)); EXPECT_THAT(PresenceOrOp{}(missing, as_fn(one)), IsOkAndHolds(one)); EXPECT_THAT(PresenceOrOp{}(optional_two, as_fn(one)), IsOkAndHolds(two)); EXPECT_THAT(PresenceOrOp{}(optional_two, as_fn(optional_one)), IsOkAndHolds(optional_two)); EXPECT_THAT(PresenceOrOp{}(optional_two, as_fn(missing)), IsOkAndHolds(optional_two)); EXPECT_THAT(PresenceOrOp{}(missing, as_fn(optional_two)), IsOkAndHolds(optional_two)); EXPECT_THAT(PresenceOrOp{}(missing, as_fn(missing)), IsOkAndHolds(missing)); auto error_fn = []() { return absl::StatusOr<OptionalUnit>(absl::InternalError("fake")); }; EXPECT_THAT(PresenceOrOp{}(kMissing, error_fn), StatusIs(absl::StatusCode::kInternal, HasSubstr("fake"))); EXPECT_THAT(PresenceOrOp{}(kPresent, error_fn), IsOkAndHolds(kPresent)); } TEST(LogicOperatorsTest, PresenceAndOr) { EXPECT_THAT( InvokeOperator<int64_t>("core._presence_and_or", one, kPresent, two), IsOkAndHolds(one)); EXPECT_THAT( InvokeOperator<int64_t>("core._presence_and_or", one, kMissing, two), IsOkAndHolds(two)); EXPECT_THAT(InvokeOperator<Oi64>("core._presence_and_or", optional_one, kPresent, optional_two), IsOkAndHolds(optional_one)); EXPECT_THAT(InvokeOperator<Oi64>("core._presence_and_or", optional_one, kMissing, optional_two), IsOkAndHolds(optional_two)); EXPECT_THAT(InvokeOperator<Oi64>("core._presence_and_or", optional_one, kPresent, missing), IsOkAndHolds(optional_one)); EXPECT_THAT(InvokeOperator<Oi64>("core._presence_and_or", missing, kMissing, optional_two), IsOkAndHolds(optional_two)); EXPECT_THAT(InvokeOperator<Oi64>("core._presence_and_or", missing, kPresent, optional_two), IsOkAndHolds(optional_two)); EXPECT_THAT( InvokeOperator<int64_t>("core._presence_and_or", missing, kPresent, two), IsOkAndHolds(two)); EXPECT_THAT(InvokeOperator<Oi64>("core._presence_and_or", optional_one, kMissing, missing), IsOkAndHolds(missing)); } TEST(LogicOperatorsTest, LazyPresenceAndOrFunctor) { auto as_fn = [](auto x) { return [x]() { return x; }; }; auto as_no_call_fn = [](auto x) { return [x]() { ADD_FAILURE() << "function shouldn't be called"; return x; }; }; EXPECT_EQ(PresenceAndOrOp{}(one, kPresent, as_no_call_fn(two)), one); EXPECT_EQ(PresenceAndOrOp{}(one, kMissing, as_fn(two)), two); EXPECT_EQ( PresenceAndOrOp{}(optional_one, kPresent, as_no_call_fn(optional_two)), optional_one); EXPECT_EQ(PresenceAndOrOp{}(optional_one, kMissing, as_fn(optional_two)), optional_two); EXPECT_EQ(PresenceAndOrOp{}(optional_one, kPresent, as_no_call_fn(missing)), optional_one); EXPECT_EQ(PresenceAndOrOp{}(missing, kMissing, as_fn(optional_two)), optional_two); EXPECT_EQ(PresenceAndOrOp{}(missing, kPresent, as_fn(optional_two)), optional_two); EXPECT_EQ(PresenceAndOrOp{}(missing, kPresent, as_fn(two)), two); EXPECT_EQ(PresenceAndOrOp{}(optional_one, kMissing, as_fn(missing)), missing); } TEST(LogicOperatorsTest, LazyPresenceAndOrWithStatusFunctor) { auto as_fn = [](auto x) { return [x]() { return absl::StatusOr<std::decay_t<decltype(x)>>(x); }; }; EXPECT_THAT(PresenceAndOrOp{}(one, kPresent, as_fn(two)), IsOkAndHolds(one)); EXPECT_THAT(PresenceAndOrOp{}(one, kMissing, as_fn(two)), IsOkAndHolds(two)); EXPECT_THAT(PresenceAndOrOp{}(optional_one, kPresent, as_fn(optional_two)), IsOkAndHolds(optional_one)); EXPECT_THAT(PresenceAndOrOp{}(optional_one, kMissing, as_fn(optional_two)), IsOkAndHolds(optional_two)); EXPECT_THAT(PresenceAndOrOp{}(optional_one, kPresent, as_fn(missing)), IsOkAndHolds(optional_one)); EXPECT_THAT(PresenceAndOrOp{}(missing, kMissing, as_fn(optional_two)), IsOkAndHolds(optional_two)); EXPECT_THAT(PresenceAndOrOp{}(missing, kPresent, as_fn(optional_two)), IsOkAndHolds(optional_two)); EXPECT_THAT(PresenceAndOrOp{}(missing, kPresent, as_fn(two)), IsOkAndHolds(two)); EXPECT_THAT(PresenceAndOrOp{}(optional_one, kMissing, as_fn(missing)), IsOkAndHolds(missing)); auto error_fn = []() { return absl::StatusOr<OptionalUnit>(absl::InternalError("fake")); }; EXPECT_THAT(PresenceAndOrOp{}(kMissing, kMissing, error_fn), StatusIs(absl::StatusCode::kInternal, HasSubstr("fake"))); EXPECT_THAT(PresenceAndOrOp{}(kPresent, kMissing, error_fn), StatusIs(absl::StatusCode::kInternal, HasSubstr("fake"))); EXPECT_THAT(PresenceAndOrOp{}(kPresent, kPresent, error_fn), IsOkAndHolds(kPresent)); } TEST(LogicOperatorsTest, PresenceAnd) { EXPECT_THAT(InvokeOperator<int64_t>("core.presence_and", one, kUnit), IsOkAndHolds(one)); EXPECT_THAT( InvokeOperator<OptionalUnit>("core.presence_and", kPresent, kPresent), IsOkAndHolds(kPresent)); EXPECT_THAT( InvokeOperator<OptionalUnit>("core.presence_and", kPresent, kMissing), IsOkAndHolds(kMissing)); EXPECT_THAT(InvokeOperator<Oi64>("core.presence_and", one, kPresent), IsOkAndHolds(optional_one)); EXPECT_THAT(InvokeOperator<Oi64>("core.presence_and", one, kMissing), IsOkAndHolds(missing)); EXPECT_THAT(InvokeOperator<Oi64>("core.presence_and", missing, kPresent), IsOkAndHolds(missing)); EXPECT_THAT(InvokeOperator<Oi64>("core.presence_and", optional_one, kPresent), IsOkAndHolds(optional_one)); EXPECT_THAT(InvokeOperator<Oi64>("core.presence_and", optional_one, kMissing), IsOkAndHolds(missing)); } TEST(LogicOperatorsTest, LazyPresenceAndFunctor) { auto as_fn = [](auto x) { return [x]() { return x; }; }; auto as_no_call_fn = [](auto x) { return [x]() { ADD_FAILURE() << "function shouldn't be called"; return x; }; }; EXPECT_EQ(PresenceAndOp{}(as_fn(one), kUnit), one); EXPECT_EQ(PresenceAndOp{}(as_fn(kPresent), kPresent), kPresent); EXPECT_EQ(PresenceAndOp{}(as_no_call_fn(kPresent), kMissing), kMissing); EXPECT_EQ(PresenceAndOp{}(as_fn(one), kPresent), optional_one); EXPECT_EQ(PresenceAndOp{}(as_no_call_fn(one), kMissing), missing); EXPECT_EQ(PresenceAndOp{}(as_fn(missing), kPresent), missing); EXPECT_EQ(PresenceAndOp{}(as_fn(optional_one), kPresent), optional_one); EXPECT_EQ(PresenceAndOp{}(as_no_call_fn(optional_one), kMissing), missing); } TEST(LogicOperatorsTest, LazyPresenceAndWithStatusFunctor) { auto as_fn = [](auto x) { return [x]() { return absl::StatusOr<std::decay_t<decltype(x)>>(x); }; }; EXPECT_THAT(PresenceAndOp{}(as_fn(one), kUnit), IsOkAndHolds(one)); EXPECT_THAT(PresenceAndOp{}(as_fn(kPresent), kPresent), IsOkAndHolds(kPresent)); EXPECT_THAT(PresenceAndOp{}(as_fn(kPresent), kMissing), IsOkAndHolds(kMissing)); EXPECT_THAT(PresenceAndOp{}(as_fn(one), kPresent), IsOkAndHolds(optional_one)); EXPECT_THAT(PresenceAndOp{}(as_fn(one), kMissing), IsOkAndHolds(missing)); EXPECT_THAT(PresenceAndOp{}(as_fn(missing), kPresent), IsOkAndHolds(missing)); EXPECT_THAT(PresenceAndOp{}(as_fn(optional_one), kPresent), IsOkAndHolds(optional_one)); EXPECT_THAT(PresenceAndOp{}(as_fn(optional_one), kMissing), IsOkAndHolds(missing)); auto error_fn = []() { return absl::StatusOr<OptionalUnit>(absl::InternalError("fake")); }; EXPECT_THAT(PresenceAndOp{}(error_fn, kPresent), StatusIs(absl::StatusCode::kInternal, HasSubstr("fake"))); EXPECT_THAT(PresenceAndOp{}(error_fn, kMissing), IsOkAndHolds(kMissing)); } TEST(LogicOperatorsTest, PresenceNot) { EXPECT_THAT( InvokeOperator<OptionalUnit>("core.presence_not._builtin", kPresent), IsOkAndHolds(kMissing)); EXPECT_THAT(InvokeOperator<OptionalUnit>("core.presence_not._builtin", OptionalValue<float>{0.0f}), IsOkAndHolds(kMissing)); EXPECT_THAT(InvokeOperator<OptionalUnit>("core.presence_not._builtin", OptionalValue<float>{}), IsOkAndHolds(kPresent)); } #define EXPECT_LOGIC_OPERATOR(op_name, lhs, rhs, result) \ EXPECT_THAT(InvokeOperator<OptionalUnit>(op_name, lhs, rhs), \ IsOkAndHolds(result)); TEST(LogicOperatorsTest, MaskEqual) { Text foo("foo"); Text bar("bar"); OptionalValue<Text> optional_foo = Text("foo"); OptionalValue<Text> optional_bar = Text("bar"); OptionalValue<Text> missing_text; const std::string op_name = "core.equal"; EXPECT_LOGIC_OPERATOR(op_name, one, one, kPresent); EXPECT_LOGIC_OPERATOR(op_name, one, two, kMissing); EXPECT_LOGIC_OPERATOR(op_name, optional_one, optional_one, kPresent); EXPECT_LOGIC_OPERATOR(op_name, optional_one, optional_two, kMissing); EXPECT_LOGIC_OPERATOR(op_name, optional_one, missing, kMissing); EXPECT_LOGIC_OPERATOR(op_name, missing, missing, kMissing); EXPECT_LOGIC_OPERATOR(op_name, foo, foo, kPresent); EXPECT_LOGIC_OPERATOR(op_name, foo, bar, kMissing); EXPECT_LOGIC_OPERATOR(op_name, optional_foo, optional_foo, kPresent); EXPECT_LOGIC_OPERATOR(op_name, optional_foo, optional_bar, kMissing); EXPECT_LOGIC_OPERATOR(op_name, optional_foo, missing_text, kMissing); } TEST(LogicOperatorsTest, MaskNotEqual) { Text foo("foo"); Text bar("bar"); OptionalValue<Text> optional_foo = Text("foo"); OptionalValue<Text> optional_bar = Text("bar"); OptionalValue<Text> missing_text; const std::string op_name = "core.not_equal"; EXPECT_LOGIC_OPERATOR(op_name, one, one, kMissing); EXPECT_LOGIC_OPERATOR(op_name, one, two, kPresent); EXPECT_LOGIC_OPERATOR(op_name, optional_one, optional_one, kMissing); EXPECT_LOGIC_OPERATOR(op_name, optional_one, optional_two, kPresent); EXPECT_LOGIC_OPERATOR(op_name, optional_one, missing, kMissing); EXPECT_LOGIC_OPERATOR(op_name, missing, missing, kMissing); EXPECT_LOGIC_OPERATOR(op_name, foo, foo, kMissing); EXPECT_LOGIC_OPERATOR(op_name, foo, bar, kPresent); EXPECT_LOGIC_OPERATOR(op_name, optional_foo, optional_foo, kMissing); EXPECT_LOGIC_OPERATOR(op_name, optional_foo, optional_bar, kPresent); EXPECT_LOGIC_OPERATOR(op_name, optional_foo, missing_text, kMissing); } TEST(LogicOperatorsTest, MaskLess) { Text foo("foo"); Text bar("bar"); OptionalValue<Text> optional_foo = Text("foo"); OptionalValue<Text> optional_bar = Text("bar"); OptionalValue<Text> missing_text; const std::string op_name = "core.less"; EXPECT_LOGIC_OPERATOR(op_name, one, one, kMissing); EXPECT_LOGIC_OPERATOR(op_name, one, two, kPresent); EXPECT_LOGIC_OPERATOR(op_name, two, one, kMissing); EXPECT_LOGIC_OPERATOR(op_name, optional_one, optional_two, kPresent); EXPECT_LOGIC_OPERATOR(op_name, optional_one, optional_one, kMissing); EXPECT_LOGIC_OPERATOR(op_name, optional_two, optional_one, kMissing); EXPECT_LOGIC_OPERATOR(op_name, optional_one, missing, kMissing); EXPECT_LOGIC_OPERATOR(op_name, missing, missing, kMissing); EXPECT_LOGIC_OPERATOR(op_name, foo, foo, kMissing); EXPECT_LOGIC_OPERATOR(op_name, foo, bar, kMissing); EXPECT_LOGIC_OPERATOR(op_name, bar, foo, kPresent); EXPECT_LOGIC_OPERATOR(op_name, optional_foo, optional_foo, kMissing); EXPECT_LOGIC_OPERATOR(op_name, optional_foo, optional_bar, kMissing); EXPECT_LOGIC_OPERATOR(op_name, optional_bar, optional_foo, kPresent); EXPECT_LOGIC_OPERATOR(op_name, optional_foo, missing_text, kMissing); } TEST(LogicOperatorsTest, MaskLessEqual) { Text foo("foo"); Text bar("bar"); OptionalValue<Text> optional_foo = Text("foo"); OptionalValue<Text> optional_bar = Text("bar"); OptionalValue<Text> missing_text; const std::string op_name = "core.less_equal"; EXPECT_LOGIC_OPERATOR(op_name, one, one, kPresent); EXPECT_LOGIC_OPERATOR(op_name, one, two, kPresent); EXPECT_LOGIC_OPERATOR(op_name, two, one, kMissing); EXPECT_LOGIC_OPERATOR(op_name, optional_one, optional_two, kPresent); EXPECT_LOGIC_OPERATOR(op_name, optional_one, optional_one, kPresent); EXPECT_LOGIC_OPERATOR(op_name, optional_two, optional_one, kMissing); EXPECT_LOGIC_OPERATOR(op_name, optional_one, missing, kMissing); EXPECT_LOGIC_OPERATOR(op_name, missing, missing, kMissing); EXPECT_LOGIC_OPERATOR(op_name, foo, foo, kPresent); EXPECT_LOGIC_OPERATOR(op_name, foo, bar, kMissing); EXPECT_LOGIC_OPERATOR(op_name, bar, foo, kPresent); EXPECT_LOGIC_OPERATOR(op_name, optional_foo, optional_foo, kPresent); EXPECT_LOGIC_OPERATOR(op_name, optional_foo, optional_bar, kMissing); EXPECT_LOGIC_OPERATOR(op_name, optional_bar, optional_foo, kPresent); EXPECT_LOGIC_OPERATOR(op_name, optional_foo, missing_text, kMissing); } } }
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/qexpr/operators/core/logic_operators.h
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/qexpr/operators/core/logic_operators_test.cc
1ca990dbeca224035efdabffecc7f3738df6b52c
015dca0e-f9cb-4031-88b3-3bdd69de74ab
cpp
google/arolla
edge_ops
arolla/qexpr/operators/array_like/edge_ops.h
arolla/qexpr/operators/dense_array/edge_ops_test.cc
#ifndef AROLLA_QEXPR_OPERATORS_ARRAY_LIKE_EDGE_OPS_H_ #define AROLLA_QEXPR_OPERATORS_ARRAY_LIKE_EDGE_OPS_H_ #include <cstddef> #include <memory> #include <string> #include <utility> #include <vector> #include "absl/status/statusor.h" #include "absl/types/span.h" #include "arolla/memory/frame.h" #include "arolla/qexpr/bound_operators.h" #include "arolla/qexpr/eval_context.h" #include "arolla/qexpr/operators.h" #include "arolla/qexpr/qexpr_operator_signature.h" #include "arolla/qtype/qtype.h" #include "arolla/util/status_macros_backport.h" namespace arolla { template <typename EdgeT> class EdgeComposeOperator : public InlineOperator { public: explicit EdgeComposeOperator(size_t size) : InlineOperator(QExprOperatorSignature::Get( std::vector<QTypePtr>(size, ::arolla::GetQType<EdgeT>()), ::arolla::GetQType<EdgeT>())) {} private: absl::StatusOr<std::unique_ptr<BoundOperator>> DoBind( absl::Span<const TypedSlot> input_slots, TypedSlot output_slot) const override { std::vector<Slot<EdgeT>> input_edge_slots; input_edge_slots.reserve(input_slots.size()); for (const auto& input_slot : input_slots) { ASSIGN_OR_RETURN(Slot<EdgeT> edge_slot, input_slot.ToSlot<EdgeT>()); input_edge_slots.push_back(std::move(edge_slot)); } ASSIGN_OR_RETURN(Slot<EdgeT> output_edge_slot, output_slot.ToSlot<EdgeT>()); return MakeBoundOperator([input_edge_slots = std::move(input_edge_slots), output_edge_slot = std::move(output_edge_slot)]( EvaluationContext* ctx, FramePtr frame) { std::vector<EdgeT> edges; edges.reserve(input_edge_slots.size()); for (const auto& edge_slot : input_edge_slots) { edges.push_back(frame.Get(edge_slot)); } ASSIGN_OR_RETURN(auto composed_edge, EdgeT::ComposeEdges(edges, ctx->buffer_factory()), ctx->set_status(std::move(_))); frame.Set(output_edge_slot, std::move(composed_edge)); }); } }; } #endif
#include <cstdint> #include <optional> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "absl/status/status_matchers.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/qexpr/operators.h" #include "arolla/qtype/shape_qtype.h" #include "arolla/util/bytes.h" #include "arolla/util/text.h" #include "arolla/util/unit.h" namespace arolla { namespace { using ::absl_testing::IsOkAndHolds; using ::absl_testing::StatusIs; using ::testing::ElementsAre; using ::testing::HasSubstr; TEST(EdgeOpsTest, EdgeFromSplitPointsOp) { auto sizes = CreateDenseArray<int64_t>({0, 2, 5, 6, 6, 8}); ASSERT_OK_AND_ASSIGN(auto edge, InvokeOperator<DenseArrayEdge>( "edge.from_split_points", sizes)); EXPECT_THAT(edge.edge_values().values, ElementsAre(0, 2, 5, 6, 6, 8)); } TEST(EdgeOpsTest, EdgeFromMappingOp) { auto mapping = CreateDenseArray<int64_t>({0, 2, 5, 6, 6, 8}); ASSERT_OK_AND_ASSIGN( auto edge, InvokeOperator<DenseArrayEdge>("edge.from_mapping", mapping, int64_t{10})); EXPECT_THAT(edge.edge_values().values, ElementsAre(0, 2, 5, 6, 6, 8)); EXPECT_THAT( InvokeOperator<DenseArrayEdge>("edge.from_mapping", mapping, int64_t{5}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("parent_size=5, but parent id 8 is used"))); } TEST(EdgeOpsTest, EdgeFromSizesOp) { auto sizes = CreateDenseArray<int64_t>({2, 3, 1, 0, 2}); ASSERT_OK_AND_ASSIGN( auto edge, InvokeOperator<DenseArrayEdge>("edge.from_sizes", sizes)); EXPECT_THAT(edge.edge_values().values, ElementsAre(0, 2, 5, 6, 6, 8)); } TEST(EdgeOpsTest, EdgeFromShapeOp) { ASSERT_OK_AND_ASSIGN(auto edge, InvokeOperator<DenseArrayGroupScalarEdge>( "edge.from_shape", DenseArrayShape{5})); EXPECT_THAT(edge.child_size(), 5); } TEST(EdgeOpsTest, MappingOp) { { const auto mapping = CreateDenseArray<int64_t>({1, 2, 3}); ASSERT_OK_AND_ASSIGN(auto edge, DenseArrayEdge::FromMapping(mapping, 4)); EXPECT_THAT(InvokeOperator<DenseArray<int64_t>>("edge.mapping", edge), IsOkAndHolds(ElementsAre(1, 2, 3))); } { const auto splits = CreateDenseArray<int64_t>({0, 2, 5}); ASSERT_OK_AND_ASSIGN(auto edge, DenseArrayEdge::FromSplitPoints(splits)); EXPECT_THAT(InvokeOperator<DenseArray<int64_t>>("edge.mapping", edge), IsOkAndHolds(ElementsAre(0, 0, 1, 1, 1))); } } TEST(EdgeOpsTest, FromKindAndShapeOp) { auto split_points = CreateDenseArray<int64_t>({0, 2, 5, 6, 6, 8}); ASSERT_OK_AND_ASSIGN(auto edge, DenseArrayEdge::FromSplitPoints(split_points)); EXPECT_THAT(InvokeOperator<DenseArrayShape>("edge.child_shape", edge), IsOkAndHolds(DenseArrayShape{8})); EXPECT_THAT(InvokeOperator<DenseArrayShape>("edge.child_shape", DenseArrayGroupScalarEdge{5}), IsOkAndHolds(DenseArrayShape{5})); } TEST(EdgeOpsTest, IntoKindAndShapeOp) { auto split_points = CreateDenseArray<int64_t>({0, 2, 5, 6, 6, 8}); ASSERT_OK_AND_ASSIGN(auto edge, DenseArrayEdge::FromSplitPoints(split_points)); EXPECT_THAT(InvokeOperator<DenseArrayShape>("edge.parent_shape", edge), IsOkAndHolds(DenseArrayShape{5})); EXPECT_THAT(InvokeOperator<OptionalScalarShape>("edge.parent_shape", DenseArrayGroupScalarEdge{5}), IsOkAndHolds(OptionalScalarShape{})); } TEST(EdgeOpsTest, ExpandOverMapping) { auto mapping = CreateDenseArray<int64_t>({0, 1, std::nullopt, 0, 1, 2, 2, 1, 0}); ASSERT_OK_AND_ASSIGN(auto edge, DenseArrayEdge::FromMapping(mapping, 3)); ASSERT_OK_AND_ASSIGN(auto bad_edge, DenseArrayEdge::FromMapping(mapping, 4)); { auto values = CreateDenseArray<float>({0, std::nullopt, 1}); ASSERT_OK_AND_ASSIGN( DenseArray<float> res, InvokeOperator<DenseArray<float>>("array._expand", values, edge)); EXPECT_THAT(res, ElementsAre(0, std::nullopt, std::nullopt, 0, std::nullopt, 1, 1, std::nullopt, 0)); EXPECT_THAT( InvokeOperator<DenseArray<float>>("array._expand", values, bad_edge), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("argument sizes mismatch"))); } { auto values = CreateDenseArray<Text>({Text("0"), std::nullopt, Text("1")}); ASSERT_OK_AND_ASSIGN( DenseArray<Text> res, InvokeOperator<DenseArray<Text>>("array._expand", values, edge)); EXPECT_THAT(res, ElementsAre(Text("0"), std::nullopt, std::nullopt, Text("0"), std::nullopt, Text("1"), Text("1"), std::nullopt, Text("0"))); EXPECT_EQ(values[0].value.begin(), res[0].value.begin()); EXPECT_EQ(values[0].value.begin(), res[3].value.begin()); EXPECT_EQ(values[0].value.begin(), res[8].value.begin()); EXPECT_EQ(values[2].value.begin(), res[5].value.begin()); EXPECT_EQ(values[2].value.begin(), res[6].value.begin()); } } TEST(EdgeOpsTest, ExpandOverSplitPoints) { auto values = CreateDenseArray<Bytes>({Bytes("first"), std::nullopt, Bytes("second")}); auto split_points = CreateDenseArray<int64_t>({0, 3, 6, 10}); ASSERT_OK_AND_ASSIGN(auto edge, DenseArrayEdge::FromSplitPoints(split_points)); ASSERT_OK_AND_ASSIGN(auto res, InvokeOperator<DenseArray<Bytes>>( "array._expand", values, edge)); EXPECT_THAT( res, ElementsAre("first", "first", "first", std::nullopt, std::nullopt, std::nullopt, "second", "second", "second", "second")); EXPECT_EQ(values[0].value.begin(), res[0].value.begin()); EXPECT_EQ(values[0].value.begin(), res[2].value.begin()); EXPECT_EQ(values[2].value.begin(), res[6].value.begin()); EXPECT_EQ(values[2].value.begin(), res[9].value.begin()); } TEST(EdgeOpsTest, ExpandOverSplitPointsNoBitmap) { auto values = CreateFullDenseArray<Bytes>({Bytes("first"), Bytes("second")}); auto split_points = CreateDenseArray<int64_t>({0, 3, 7}); ASSERT_OK_AND_ASSIGN(auto edge, DenseArrayEdge::FromSplitPoints(split_points)); ASSERT_OK_AND_ASSIGN(auto res, InvokeOperator<DenseArray<Bytes>>( "array._expand", values, edge)); EXPECT_THAT(res, ElementsAre("first", "first", "first", "second", "second", "second", "second")); EXPECT_EQ(values[0].value.begin(), res[0].value.begin()); EXPECT_EQ(values[0].value.begin(), res[2].value.begin()); EXPECT_EQ(values[1].value.begin(), res[3].value.begin()); EXPECT_EQ(values[1].value.begin(), res[6].value.begin()); } TEST(EdgeOpsTest, ExpandGroupScalarEdge) { auto edge = DenseArrayGroupScalarEdge(3); ASSERT_OK_AND_ASSIGN( auto res1, InvokeOperator<DenseArray<Bytes>>( "array._expand", MakeOptionalValue(Bytes("first")), edge)); EXPECT_THAT(res1, ElementsAre("first", "first", "first")); ASSERT_OK_AND_ASSIGN(auto res2, InvokeOperator<DenseArray<Bytes>>( "array._expand", OptionalValue<Bytes>(), edge)); EXPECT_THAT(res2, ElementsAre(std::nullopt, std::nullopt, std::nullopt)); } TEST(EdgeOpsTest, GroupByOp_Integral) { const auto series = CreateDenseArray<int64_t>({101, 102, 103, 104}); ASSERT_OK_AND_ASSIGN(auto over, DenseArrayEdge::FromSplitPoints( CreateDenseArray<int64_t>({0, 4}))); ASSERT_OK_AND_ASSIGN(auto edge, InvokeOperator<DenseArrayEdge>( "edge._group_by", series, over)); EXPECT_EQ(edge.parent_size(), 4); EXPECT_THAT(edge.edge_values(), ElementsAre(0, 1, 2, 3)); } TEST(EdgeOpsTest, GroupByOp_Float) { const auto series = CreateDenseArray<float>({5., 7., 1., 2., 4.}); ASSERT_OK_AND_ASSIGN(auto over, DenseArrayEdge::FromSplitPoints( CreateDenseArray<int64_t>({0, 5}))); ASSERT_OK_AND_ASSIGN(auto edge, InvokeOperator<DenseArrayEdge>( "edge._group_by", series, over)); EXPECT_EQ(edge.parent_size(), 5); EXPECT_THAT(edge.edge_values(), ElementsAre(0, 1, 2, 3, 4)); } TEST(EdgeOpsTest, GroupByOp_Bytes) { const auto series = CreateDenseArray<Bytes>( {Bytes("a"), Bytes("b"), Bytes("c"), Bytes("d"), Bytes("e")}); ASSERT_OK_AND_ASSIGN(auto over, DenseArrayEdge::FromSplitPoints( CreateDenseArray<int64_t>({0, 5}))); ASSERT_OK_AND_ASSIGN(auto edge, InvokeOperator<DenseArrayEdge>( "edge._group_by", series, over)); EXPECT_EQ(edge.parent_size(), 5); EXPECT_THAT(edge.edge_values(), ElementsAre(0, 1, 2, 3, 4)); } TEST(EdgeOpsTest, GroupByOp_DuplicatesInInputSeries) { const auto series = CreateDenseArray<float>({5., 7., 5., 7., 4., 8.}); ASSERT_OK_AND_ASSIGN(auto over, DenseArrayEdge::FromSplitPoints( CreateDenseArray<int64_t>({0, 6}))); ASSERT_OK_AND_ASSIGN(auto edge, InvokeOperator<DenseArrayEdge>( "edge._group_by", series, over)); EXPECT_EQ(edge.parent_size(), 4); EXPECT_THAT(edge.edge_values(), ElementsAre(0, 1, 0, 1, 2, 3)); } TEST(EdgeOpsTest, GroupByOp_DuplicatesInInputSeries_WithSplits) { const auto series = CreateDenseArray<float>({5., 7., 5., 7., 7., 8.}); ASSERT_OK_AND_ASSIGN(auto over, DenseArrayEdge::FromSplitPoints( CreateDenseArray<int64_t>({0, 3, 6}))); ASSERT_OK_AND_ASSIGN(auto edge, InvokeOperator<DenseArrayEdge>( "edge._group_by", series, over)); EXPECT_EQ(edge.parent_size(), 4); EXPECT_THAT(edge.edge_values(), ElementsAre(0, 1, 0, 2, 2, 3)); } TEST(EdgeOpsTest, GroupByOp_DuplicatesInInputSeries_WithMapping) { const auto series = CreateDenseArray<float>({5., 7., 5., 7., 7., 8.}); ASSERT_OK_AND_ASSIGN(auto over, DenseArrayEdge::FromMapping( CreateDenseArray<int64_t>({1, 1, 0, 2, 1, 0}), 3)); ASSERT_OK_AND_ASSIGN(auto edge, InvokeOperator<DenseArrayEdge>( "edge._group_by", series, over)); EXPECT_EQ(edge.parent_size(), 5); EXPECT_THAT(edge.edge_values(), ElementsAre(0, 1, 2, 3, 1, 4)); } TEST(EdgeOpsTest, GroupByOp_MissingValuesAndDuplicates) { const auto series = CreateDenseArray<int64_t>({7, 8, std::nullopt, 7, 10, 8}); ASSERT_OK_AND_ASSIGN(auto over, DenseArrayEdge::FromSplitPoints( CreateDenseArray<int64_t>({0, 6}))); ASSERT_OK_AND_ASSIGN(auto edge, InvokeOperator<DenseArrayEdge>( "edge._group_by", series, over)); EXPECT_EQ(edge.parent_size(), 3); EXPECT_THAT(edge.edge_values(), ElementsAre(0, 1, std::nullopt, 0, 2, 1)); } TEST(EdgeOpsTest, GroupByOp_MissingValuesAndDuplicates_WithSplits) { const auto series = CreateDenseArray<int64_t>({7, 6, 7, 5, 5, std::nullopt, std::nullopt, 5, 5, std::nullopt, 7, 10, 7}); ASSERT_OK_AND_ASSIGN(auto over, DenseArrayEdge::FromSplitPoints( CreateDenseArray<int64_t>({0, 3, 4, 5, 7, 9, 13}))); ASSERT_OK_AND_ASSIGN(auto edge, InvokeOperator<DenseArrayEdge>( "edge._group_by", series, over)); EXPECT_EQ(edge.parent_size(), 7); EXPECT_THAT(edge.edge_values(), ElementsAre(0, 1, 0, 2, 3, std::nullopt, std::nullopt, 4, 4, std::nullopt, 5, 6, 5)); } TEST(EdgeOpsTest, GroupByOp_EmptyDenseArray) { const auto series = CreateDenseArray<int64_t>({}); ASSERT_OK_AND_ASSIGN(auto over, DenseArrayEdge::FromSplitPoints( CreateDenseArray<int64_t>({0}))); ASSERT_OK_AND_ASSIGN(auto edge, InvokeOperator<DenseArrayEdge>( "edge._group_by", series, over)); EXPECT_EQ(edge.parent_size(), 0); EXPECT_THAT(edge.edge_values(), ElementsAre()); } TEST(EdgeOpsTest, GroupByOp_MissingValuesAndDuplicates_WithMapping) { const auto series = CreateDenseArray<int64_t>({7, 6, 6, 7, 5, 5, std::nullopt, std::nullopt, 5, 5, std::nullopt, 7, 10, 7, 5}); ASSERT_OK_AND_ASSIGN( auto over, DenseArrayEdge::FromMapping( CreateDenseArray<int64_t>({2, std::nullopt, 2, 3, 1, 2, 2, std::nullopt, 1, 2, 4, 2, 3, 3, std::nullopt}), 5)); ASSERT_OK_AND_ASSIGN(auto edge, InvokeOperator<DenseArrayEdge>( "edge._group_by", series, over)); EXPECT_EQ(edge.parent_size(), 6); EXPECT_THAT( edge.edge_values(), ElementsAre(0, std::nullopt, 1, 2, 3, 4, std::nullopt, std::nullopt, 3, 4, std::nullopt, 0, 5, 2, std::nullopt)); } TEST(EdgeOpsTest, GroupByOp_IncompatibleOverEdge) { const auto series = CreateDenseArray<int64_t>({1, 2}); ASSERT_OK_AND_ASSIGN(auto over, DenseArrayEdge::FromSplitPoints( CreateDenseArray<int64_t>({0, 3}))); EXPECT_THAT(InvokeOperator<DenseArrayEdge>("edge._group_by", series, over), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("argument sizes mismatch"))); } TEST(EdgeOpsTest, AggSizeEdgeOp_Mapping) { auto mapping = CreateDenseArray<int64_t>({0, std::nullopt, 0, std::nullopt, 2}); ASSERT_OK_AND_ASSIGN(auto edge, DenseArrayEdge::FromMapping(mapping, 3)); ASSERT_OK_AND_ASSIGN(auto dense_array, InvokeOperator<DenseArray<int64_t>>("edge.sizes", edge)); EXPECT_THAT(dense_array, ElementsAre(2, 0, 1)); } TEST(EdgeOpsTest, AggSizeEdgeOp_SplitPoints) { auto split_points = CreateDenseArray<int64_t>({0, 2, 4, 4, 8}); ASSERT_OK_AND_ASSIGN(auto edge, DenseArrayEdge::FromSplitPoints(split_points)); ASSERT_OK_AND_ASSIGN(auto dense_array, InvokeOperator<DenseArray<int64_t>>("edge.sizes", edge)); EXPECT_THAT(dense_array, ElementsAre(2, 2, 0, 4)); } TEST(EdgeOpsTest, TestAggCountScalarEdge) { auto mask = CreateDenseArray<Unit>({kUnit, std::nullopt, kUnit, std::nullopt}); auto edge = DenseArrayGroupScalarEdge(4); EXPECT_THAT(InvokeOperator<int64_t>("array._count", mask, edge), IsOkAndHolds(2)); } TEST(EdgeOpsTest, EdgeComposeOp) { { ASSERT_OK_AND_ASSIGN(auto edge1, DenseArrayEdge::FromSplitPoints( CreateDenseArray<int64_t>({0, 2, 3}))); ASSERT_OK_AND_ASSIGN(auto edge2, DenseArrayEdge::FromSplitPoints( CreateDenseArray<int64_t>({0, 1, 2, 4}))); ASSERT_OK_AND_ASSIGN(auto composed_edge, InvokeOperator<DenseArrayEdge>( "edge.compose._dense_array", edge1, edge2)); EXPECT_THAT(composed_edge.edge_values(), ElementsAre(0, 2, 4)); EXPECT_THAT(composed_edge.edge_type(), DenseArrayEdge::SPLIT_POINTS); } { ASSERT_OK_AND_ASSIGN(auto edge1, DenseArrayEdge::FromSplitPoints( CreateDenseArray<int64_t>({0, 2, 3}))); ASSERT_OK_AND_ASSIGN(auto edge2, DenseArrayEdge::FromMapping( CreateDenseArray<int64_t>({0, 1, 2, 2}), 3)); ASSERT_OK_AND_ASSIGN(auto composed_edge, InvokeOperator<DenseArrayEdge>( "edge.compose._dense_array", edge1, edge2)); EXPECT_THAT(composed_edge.edge_values(), ElementsAre(0, 0, 1, 1)); EXPECT_THAT(composed_edge.edge_type(), DenseArrayEdge::MAPPING); } } } }
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/qexpr/operators/array_like/edge_ops.h
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/qexpr/operators/dense_array/edge_ops_test.cc
1ca990dbeca224035efdabffecc7f3738df6b52c
34799c31-1af1-42ef-be2e-3fbff6036ffd
cpp
google/arolla
logic_ops
arolla/qexpr/operators/dense_array/logic_ops.h
arolla/qexpr/operators/dense_array/logic_ops_test.cc
#ifndef AROLLA_QEXPR_OPERATORS_DENSE_ARRAY_LOGIC_OPS_H_ #define AROLLA_QEXPR_OPERATORS_DENSE_ARRAY_LOGIC_OPS_H_ #include <cstdint> #include <cstring> #include <utility> #include "absl/base/optimization.h" #include "absl/status/statusor.h" #include "absl/types/span.h" #include "arolla/dense_array/bitmap.h" #include "arolla/dense_array/dense_array.h" #include "arolla/dense_array/ops/dense_ops.h" #include "arolla/dense_array/qtype/types.h" #include "arolla/memory/buffer.h" #include "arolla/memory/optional_value.h" #include "arolla/qexpr/eval_context.h" #include "arolla/util/unit.h" #include "arolla/util/view_types.h" namespace arolla { struct DenseArrayHasOp { template <typename T> DenseArray<Unit> operator()(const DenseArray<T>& arg) const { return {VoidBuffer(arg.size()), arg.bitmap, arg.bitmap_bit_offset}; } }; struct DenseArrayPresenceAndOp { template <typename T> absl::StatusOr<DenseArray<T>> operator()(EvaluationContext* ctx, const DenseArray<T>& lhs, const DenseArray<Unit>& rhs) const { if (ABSL_PREDICT_FALSE(lhs.size() != rhs.size())) { return SizeMismatchError({lhs.size(), rhs.size()}); } if (rhs.bitmap.empty()) { return lhs; } else if (lhs.bitmap.empty()) { return DenseArray<T>{lhs.values, rhs.bitmap, rhs.bitmap_bit_offset}; } else { int64_t bitmap_size = bitmap::BitmapSize(lhs.size()); bitmap::RawBuilder bldr(bitmap_size, &ctx->buffer_factory()); bitmap::Intersect(lhs.bitmap, rhs.bitmap, lhs.bitmap_bit_offset, rhs.bitmap_bit_offset, bldr.GetMutableSpan()); return DenseArray<T>{ lhs.values, std::move(bldr).Build(), std::min(lhs.bitmap_bit_offset, rhs.bitmap_bit_offset)}; } } }; struct DenseArrayPresenceNotOp { template <typename T> DenseArray<Unit> operator()(EvaluationContext* ctx, const DenseArray<T>& arg) const { if (arg.bitmap.empty()) { return CreateEmptyDenseArray<Unit>(arg.size(), &ctx->buffer_factory()); } absl::Span<const bitmap::Word> bitmap_in = arg.bitmap.span(); int64_t first_not_zero_index = 0; int64_t bitmap_size = arg.bitmap.size(); while (first_not_zero_index < bitmap_size && bitmap_in[first_not_zero_index] == 0) { first_not_zero_index++; } if (first_not_zero_index == bitmap_size) { return {VoidBuffer(arg.size())}; } bitmap::RawBuilder bldr(bitmap_size, &ctx->buffer_factory()); absl::Span<bitmap::Word> bitmap_out = bldr.GetMutableSpan(); if (first_not_zero_index > 0) { std::memset(bitmap_out.data(), 0xff, sizeof(bitmap::Word) * first_not_zero_index); } for (int64_t i = first_not_zero_index; i < bitmap_size; ++i) { bitmap_out[i] = ~bitmap_in[i]; } return {VoidBuffer(arg.size()), std::move(bldr).Build(), arg.bitmap_bit_offset}; } }; struct DenseArrayPresenceOrOp { template <typename T> absl::StatusOr<DenseArray<T>> operator()(EvaluationContext* ctx, const DenseArray<T>& lhs, const DenseArray<T>& rhs) const { if (ABSL_PREDICT_FALSE(lhs.size() != rhs.size())) { return SizeMismatchError({lhs.size(), rhs.size()}); } if (lhs.bitmap.empty()) { return lhs; } else if (bitmap::AreAllBitsUnset(lhs.bitmap.begin(), lhs.size())) { return rhs; } else { auto fn = [&](OptionalValue<view_type_t<T>> a, OptionalValue<view_type_t<T>> b) { return OptionalValue<view_type_t<T>>{a.present || b.present, a.present ? a.value : b.value}; }; return CreateDenseOp<DenseOpFlags::kRunOnMissing | DenseOpFlags::kNoBitmapOffset | DenseOpFlags::kNoSizeValidation, decltype(fn), T>(fn, &ctx->buffer_factory())(lhs, rhs); } } template <typename T> DenseArray<T> operator()(EvaluationContext* ctx, const DenseArray<T>& lhs, const OptionalValue<T>& rhs) const { if (!rhs.present || lhs.bitmap.empty()) { return lhs; } else if (bitmap::AreAllBitsUnset(lhs.bitmap.begin(), lhs.size())) { return CreateConstDenseArray<T>(lhs.size(), rhs.value, &ctx->buffer_factory()); } else { auto fn = [value = rhs.value](OptionalValue<view_type_t<T>> a) { return a.present ? a.value : value; }; return CreateDenseOp<DenseOpFlags::kRunOnMissing | DenseOpFlags::kNoBitmapOffset | DenseOpFlags::kNoSizeValidation, decltype(fn), T>(fn, &ctx->buffer_factory())(lhs); } } }; } #endif
#include <optional> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status_matchers.h" #include "arolla/dense_array/dense_array.h" #include "arolla/dense_array/qtype/types.h" #include "arolla/memory/optional_value.h" #include "arolla/qexpr/operators.h" #include "arolla/util/unit.h" namespace arolla::testing { namespace { using ::absl_testing::IsOkAndHolds; using ::testing::ElementsAre; using ::testing::ElementsAreArray; TEST(LogicOpsTest, DenseArrayPresenceAndOp) { EXPECT_THAT(InvokeOperator<DenseArray<int>>( "core.presence_and", CreateDenseArray<int>({1, 2, 3}), CreateDenseArray<Unit>({kUnit, std::nullopt, kUnit})), IsOkAndHolds(ElementsAre(1, std::nullopt, 3))); EXPECT_THAT( InvokeOperator<DenseArray<int>>( "core.presence_and", CreateDenseArray<int>({1, 2, std::nullopt}), CreateDenseArray<Unit>({kUnit, std::nullopt, kUnit})), IsOkAndHolds(ElementsAre(1, std::nullopt, std::nullopt))); EXPECT_THAT( InvokeOperator<DenseArray<int>>( "core.presence_and", CreateDenseArray<int>({1, 2, std::nullopt}), CreateDenseArray<Unit>({kUnit, kUnit, kUnit})), IsOkAndHolds(ElementsAre(1, 2, std::nullopt))); } TEST(LogicOpsTest, DenseArrayPresenceOrOp) { EXPECT_THAT(InvokeOperator<DenseArray<int>>("core.presence_or", CreateDenseArray<int>({1, 2, 3}), CreateDenseArray<int>({4, 5, 6})), IsOkAndHolds(ElementsAre(1, 2, 3))); EXPECT_THAT( InvokeOperator<DenseArray<int>>( "core.presence_or", CreateDenseArray<int>({1, 2, std::nullopt}), CreateDenseArray<int>({4, 5, 6})), IsOkAndHolds(ElementsAre(1, 2, 6))); EXPECT_THAT( InvokeOperator<DenseArray<int>>( "core.presence_or", CreateDenseArray<int>({1, 2, std::nullopt}), CreateDenseArray<int>({4, 5, std::nullopt})), IsOkAndHolds(ElementsAre(1, 2, std::nullopt))); EXPECT_THAT( InvokeOperator<DenseArray<int>>( "core.presence_or", CreateDenseArray<int>({std::nullopt, std::nullopt, std::nullopt}), CreateDenseArray<int>({4, 5, std::nullopt})), IsOkAndHolds(ElementsAre(4, 5, std::nullopt))); } TEST(LogicOpsTest, DenseArrayPresenceNotOp) { { auto full_int = CreateConstDenseArray<int>(35, 7); auto empty_unit = CreateEmptyDenseArray<Unit>(35); EXPECT_THAT(InvokeOperator<DenseArray<Unit>>("core.presence_not._builtin", full_int), IsOkAndHolds(ElementsAreArray(empty_unit))); } { auto empty_int = CreateEmptyDenseArray<int>(35); auto full_unit = CreateConstDenseArray<Unit>(35, kUnit); EXPECT_THAT(InvokeOperator<DenseArray<Unit>>("core.presence_not._builtin", empty_int), IsOkAndHolds(ElementsAreArray(full_unit))); } { std::vector<std::optional<int>> input(35, std::nullopt); input[15] = 5; input[24] = 7; std::vector<OptionalValue<Unit>> expected(input.size()); for (int i = 0; i < input.size(); ++i) { expected[i].present = !input[i].has_value(); } ASSERT_OK_AND_ASSIGN( auto res, InvokeOperator<DenseArray<Unit>>( "core.presence_not._builtin", CreateDenseArray<int>(input.begin(), input.end()))); EXPECT_EQ(std::vector(res.begin(), res.end()), expected); } } TEST(LogicOpsTest, DenseArrayPresenceOrWithOptionalOp) { EXPECT_THAT(InvokeOperator<DenseArray<int>>("core.presence_or", CreateDenseArray<int>({1, 2, 3}), OptionalValue<int>(4)), IsOkAndHolds(ElementsAre(1, 2, 3))); EXPECT_THAT( InvokeOperator<DenseArray<int>>( "core.presence_or", CreateDenseArray<int>({1, std::nullopt, 3}), OptionalValue<int>(4)), IsOkAndHolds(ElementsAre(1, 4, 3))); EXPECT_THAT(InvokeOperator<DenseArray<int>>( "core.presence_or", CreateDenseArray<int>({std::nullopt, std::nullopt}), OptionalValue<int>(4)), IsOkAndHolds(ElementsAre(4, 4))); EXPECT_THAT(InvokeOperator<DenseArray<int>>("core.presence_or", CreateDenseArray<int>({3, 2}), OptionalValue<int>()), IsOkAndHolds(ElementsAre(3, 2))); EXPECT_THAT(InvokeOperator<DenseArray<int>>( "core.presence_or", CreateDenseArray<int>({3, std::nullopt}), OptionalValue<int>()), IsOkAndHolds(ElementsAre(3, std::nullopt))); EXPECT_THAT(InvokeOperator<DenseArray<int>>( "core.presence_or", CreateDenseArray<int>({std::nullopt, std::nullopt}), OptionalValue<int>()), IsOkAndHolds(ElementsAre(std::nullopt, std::nullopt))); } TEST(LogicOpsTest, HasOp) { auto array = CreateDenseArray<float>({1.0, {}, 2.0, {}, 3.0}); ASSERT_OK_AND_ASSIGN( auto mask, InvokeOperator<DenseArray<Unit>>("core.has._array", array)); EXPECT_THAT(mask, ElementsAre(kUnit, std::nullopt, kUnit, std::nullopt, kUnit)); } } }
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/qexpr/operators/dense_array/logic_ops.h
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/qexpr/operators/dense_array/logic_ops_test.cc
1ca990dbeca224035efdabffecc7f3738df6b52c
04214a7c-da83-4558-8b92-d0c7af9fc73b
cpp
google/arolla
batch_arithmetic
arolla/qexpr/operators/math/batch_arithmetic.h
arolla/qexpr/operators/math/batch_arithmetic_test.cc
#ifndef AROLLA_QEXPR_OPERATORS_MATH_BATCH_ARITHMETIC_H_ #define AROLLA_QEXPR_OPERATORS_MATH_BATCH_ARITHMETIC_H_ #include <type_traits> #include "absl/log/check.h" #include "absl/types/span.h" #include "Eigen/Core" namespace arolla { namespace batch_arithmetic_internal { template <typename T> using DynamicEigenVector = Eigen::Array<T, 1, Eigen::Dynamic, Eigen::RowMajor>; template <typename T> using DynamicEigenVectorView = Eigen::Map<const DynamicEigenVector<T>>; template <typename T> using DynamicMutableEigenVectorView = Eigen::Map<DynamicEigenVector<T>>; template <typename T, class OP, typename InternalT = T> struct BinaryEigenOperation { void operator()(absl::Span<T> result, absl::Span<const T> a, absl::Span<const T> b) const { auto size = a.size(); DCHECK_EQ(size, b.size()); DCHECK_EQ(size, result.size()); static_assert( sizeof(T) == sizeof(InternalT) && std::is_floating_point_v<T> == std::is_floating_point_v<InternalT>, "Incorrect InternalT"); const auto* a_data = reinterpret_cast<const InternalT*>(a.data()); const auto* b_data = reinterpret_cast<const InternalT*>(b.data()); auto* result_data = reinterpret_cast<InternalT*>(result.data()); DynamicEigenVectorView<InternalT> eigen_a(a_data, size); DynamicEigenVectorView<InternalT> eigen_b(b_data, size); DynamicMutableEigenVectorView<InternalT> eigen_result(result_data, size); OP::Apply(eigen_a, eigen_b, &eigen_result); } }; struct ProdOp { template <typename T, typename RT> static void Apply(const T& a, const T& b, RT* c) { *c = a * b; } }; struct AddOp { template <typename T, typename RT> static void Apply(const T& a, const T& b, RT* c) { *c = a + b; } }; struct SubOp { template <typename T, typename RT> static void Apply(const T& a, const T& b, RT* c) { *c = a - b; } }; template <typename T> static auto MakeUnsignedIfIntegralFn() { if constexpr (std::is_integral_v<T>) { return std::make_unsigned_t<T>(); } else { return T(); } } template <typename T> using UnsignedIfIntegral = decltype(MakeUnsignedIfIntegralFn<T>()); } template <typename T> using BatchAdd = batch_arithmetic_internal::BinaryEigenOperation< T, batch_arithmetic_internal::AddOp, batch_arithmetic_internal::UnsignedIfIntegral<T>>; template <typename T> using BatchSub = batch_arithmetic_internal::BinaryEigenOperation< T, batch_arithmetic_internal::SubOp, batch_arithmetic_internal::UnsignedIfIntegral<T>>; template <typename T> using BatchProd = batch_arithmetic_internal::BinaryEigenOperation< T, batch_arithmetic_internal::ProdOp, batch_arithmetic_internal::UnsignedIfIntegral<T>>; template <typename T> T BatchAggSum(absl::Span<const T> data) { batch_arithmetic_internal::DynamicEigenVectorView<T> e_data(data.data(), data.size()); return e_data.sum(); } } #endif
#include "arolla/qexpr/operators/math/batch_arithmetic.h" #include <cstdint> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/types/span.h" namespace arolla { namespace { TEST(BatchArithmetic, BatchAdd) { std::vector<float> arg1{1., 3., 2.}; std::vector<float> arg2{3.5, 1.5, 2.}; std::vector<float> res(3); BatchAdd<float>()(absl::Span<float>(res), arg1, arg2); EXPECT_THAT(res, testing::ElementsAre(4.5, 4.5, 4.0)); } TEST(BatchArithmetic, BatchSub) { std::vector<int64_t> arg1{1, 3, 2}; std::vector<int64_t> arg2{3, 1, 2}; std::vector<int64_t> res(3); BatchSub<int64_t>()(absl::Span<int64_t>(res), arg1, arg2); EXPECT_THAT(res, testing::ElementsAre(-2, 2, 0)); } TEST(BatchArithmetic, BatchProd) { std::vector<double> arg1{1., 3., 2.}; std::vector<double> arg2{3.5, 1.5, 2.}; std::vector<double> res(3); BatchProd<double>()(absl::Span<double>(res), arg1, arg2); EXPECT_THAT(res, testing::ElementsAre(3.5, 4.5, 4.0)); } TEST(BatchArithmetic, AggSum) { std::vector<float> arg{1., 3., 2.}; EXPECT_EQ(BatchAggSum<float>(arg), 6.); } } }
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/qexpr/operators/math/batch_arithmetic.h
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/qexpr/operators/math/batch_arithmetic_test.cc
1ca990dbeca224035efdabffecc7f3738df6b52c
d854d58e-93ef-48d2-b091-d6dc7fbb5240
cpp
google/arolla
math
arolla/qexpr/operators/math/math.h
arolla/qexpr/operators/math/math_test.cc
#ifndef AROLLA_OPERATORS_MATH_MATH_H_ #define AROLLA_OPERATORS_MATH_MATH_H_ #include <cmath> namespace arolla { struct LogOp { float operator()(float x) const { return std::log(x); } double operator()(double x) const { return std::log(x); } }; struct Log2Op { template <typename T> T operator()(T x) const { return std::log2(x); } }; struct Log10Op { template <typename T> T operator()(T x) const { return std::log10(x); } }; struct Log1pOp { template <typename T> T operator()(T x) const { return std::log1p(x); } }; struct Symlog1pOp { template <typename T> T operator()(T x) const { return x >= 0 ? std::log1p(x) : -std::log1p(-x); } }; struct ExpOp { float operator()(float x) const { return std::exp(x); } double operator()(double x) const { return std::exp(x); } }; struct Expm1Op { template <typename T> T operator()(T x) const { return std::expm1(x); } }; struct PowOp { template <typename T> T operator()(T a, T b) const { return std::pow(a, b); } double operator()(double a, double b) const { return std::pow(a, b); } }; struct SigmoidOp { template <typename T> T operator()(T value, T half, T slope) const { return 1.0f / (1.0f + ExpOp()(slope * (half - value))); } }; struct LogitOp { template <typename T> T operator()(T p) const { return LogOp()(p) - std::log1p(-p); } }; struct LogSigmoidOp { template <typename T> T operator()(T x) const { if (x >= 0) { return -std::log1p(std::exp(-x)); } return x - std::log1p(std::exp(x)); } }; struct SinOp { template <typename T> T operator()(T x) const { return std::sin(x); } }; struct CosOp { template <typename T> T operator()(T x) const { return std::cos(x); } }; struct SinhOp { template <typename T> T operator()(T x) const { return std::sinh(x); } }; struct AtanOp { template <typename T> T operator()(T x) const { return std::atan(x); } }; } #endif
#include <cmath> #include <limits> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status_matchers.h" #include "arolla/qexpr/operators.h" #include "arolla/qtype/base_types.h" namespace arolla { namespace { using ::absl_testing::IsOkAndHolds; using ::testing::AllOf; using ::testing::DoubleEq; using ::testing::DoubleNear; using ::testing::Eq; using ::testing::FloatEq; using ::testing::FloatNear; using ::testing::Ge; using ::testing::Gt; using ::testing::IsNan; using ::testing::Le; using ::testing::Lt; const float kPi = 3.1415927f; TEST(ArithmeticOperatorsTest, Log) { EXPECT_THAT(InvokeOperator<float>("math.log", 1.f), IsOkAndHolds(0.f)); EXPECT_THAT(InvokeOperator<float>("math.log", 2.f), IsOkAndHolds(FloatEq(std::log(2.f)))); EXPECT_THAT(InvokeOperator<float>("math.log", 0.f), IsOkAndHolds(-std::numeric_limits<float>::infinity())); EXPECT_THAT(InvokeOperator<float>("math.log", -5.f), IsOkAndHolds(IsNan())); EXPECT_THAT(InvokeOperator<double>("math.log", 2.), IsOkAndHolds(DoubleEq(std::log(2.)))); EXPECT_THAT(InvokeOperator<double>("math.log", 1.), IsOkAndHolds(0.)); EXPECT_THAT(InvokeOperator<double>("math.log", 0.), IsOkAndHolds(-std::numeric_limits<double>::infinity())); EXPECT_THAT(InvokeOperator<double>("math.log", -4.), IsOkAndHolds(IsNan())); } TEST(ArithmeticOperatorsTest, Log2) { EXPECT_THAT(InvokeOperator<float>("math.log2", 1.f), IsOkAndHolds(0.f)); EXPECT_THAT(InvokeOperator<float>("math.log2", 2.f), IsOkAndHolds(FloatEq(std::log2(2.f)))); EXPECT_THAT(InvokeOperator<float>("math.log2", 0.f), IsOkAndHolds(-std::numeric_limits<float>::infinity())); EXPECT_THAT(InvokeOperator<float>("math.log2", -5.f), IsOkAndHolds(IsNan())); EXPECT_THAT(InvokeOperator<double>("math.log2", 1.), IsOkAndHolds(0.)); EXPECT_THAT(InvokeOperator<double>("math.log2", 2.), IsOkAndHolds(DoubleEq(std::log2(2.)))); EXPECT_THAT(InvokeOperator<double>("math.log2", 0.), IsOkAndHolds(-std::numeric_limits<double>::infinity())); EXPECT_THAT(InvokeOperator<double>("math.log2", -4.), IsOkAndHolds(IsNan())); } TEST(ArithmeticOperatorsTest, Log10) { EXPECT_THAT(InvokeOperator<float>("math.log10", 1.f), IsOkAndHolds(0.f)); EXPECT_THAT(InvokeOperator<float>("math.log10", 2.f), IsOkAndHolds(FloatEq(std::log10(2.f)))); EXPECT_THAT(InvokeOperator<float>("math.log10", 0.f), IsOkAndHolds(-std::numeric_limits<float>::infinity())); EXPECT_THAT(InvokeOperator<float>("math.log10", -5.f), IsOkAndHolds(IsNan())); EXPECT_THAT(InvokeOperator<double>("math.log10", 1.), IsOkAndHolds(0.)); EXPECT_THAT(InvokeOperator<double>("math.log10", 2.), IsOkAndHolds(DoubleEq(std::log10(2.)))); EXPECT_THAT(InvokeOperator<double>("math.log10", 0.), IsOkAndHolds(-std::numeric_limits<double>::infinity())); EXPECT_THAT(InvokeOperator<double>("math.log10", -4.), IsOkAndHolds(IsNan())); } TEST(ArithmeticOperatorsTest, Log1p) { EXPECT_THAT(InvokeOperator<float>("math.log1p", 0.f), IsOkAndHolds(0.f)); EXPECT_THAT(InvokeOperator<float>("math.log1p", 2.f), IsOkAndHolds(FloatEq(std::log1p(2.f)))); EXPECT_THAT(InvokeOperator<float>("math.log1p", -1.f), IsOkAndHolds(-std::numeric_limits<float>::infinity())); EXPECT_THAT(InvokeOperator<float>("math.log1p", -5.f), IsOkAndHolds(IsNan())); EXPECT_THAT(InvokeOperator<double>("math.log1p", 0.), IsOkAndHolds(0.)); EXPECT_THAT(InvokeOperator<double>("math.log1p", 2.), IsOkAndHolds(DoubleEq(std::log1p(2.)))); EXPECT_THAT(InvokeOperator<double>("math.log1p", -1.), IsOkAndHolds(-std::numeric_limits<double>::infinity())); EXPECT_THAT(InvokeOperator<double>("math.log1p", -4.), IsOkAndHolds(IsNan())); } TEST(ArithmeticOperatorsTest, Symlog1p) { EXPECT_THAT(InvokeOperator<float>("math.symlog1p", 0.f), IsOkAndHolds(0.)); EXPECT_THAT(InvokeOperator<float>("math.symlog1p", 2.f), IsOkAndHolds(FloatEq(std::log1p(2.)))); EXPECT_THAT(InvokeOperator<float>("math.symlog1p", -2.f), IsOkAndHolds(FloatEq(-std::log1p(2.)))); EXPECT_THAT(InvokeOperator<double>("math.symlog1p", 0.), IsOkAndHolds(0.)); EXPECT_THAT(InvokeOperator<double>("math.symlog1p", 2.), IsOkAndHolds(DoubleEq(std::log1p(2.)))); EXPECT_THAT(InvokeOperator<double>("math.symlog1p", -2.), IsOkAndHolds(DoubleEq(-std::log1p(2.)))); } TEST(MathOperatorsTest, Exp) { EXPECT_THAT(InvokeOperator<float>("math.exp", 0.f), IsOkAndHolds(1.f)); EXPECT_THAT(InvokeOperator<float>("math.exp", 2.f), IsOkAndHolds(FloatEq(std::exp(2.f)))); EXPECT_THAT(InvokeOperator<double>("math.exp", 0.), IsOkAndHolds(Eq(1.))); EXPECT_THAT(InvokeOperator<double>("math.exp", 2.), IsOkAndHolds(DoubleEq(std::exp(2.)))); } TEST(MathOperatorsTest, Expm1) { EXPECT_THAT(InvokeOperator<float>("math.expm1", 0.f), IsOkAndHolds(0.f)); EXPECT_THAT(InvokeOperator<float>("math.expm1", 2.f), IsOkAndHolds(FloatEq(std::expm1(2.f)))); EXPECT_THAT(InvokeOperator<double>("math.expm1", 0.), IsOkAndHolds(Eq(0.))); EXPECT_THAT(InvokeOperator<double>("math.expm1", 2.), IsOkAndHolds(DoubleEq(std::expm1(2.)))); } TEST(MathOperatorsTest, Sigmoid) { for (float slope = 1; slope < 5; slope++) { EXPECT_THAT(InvokeOperator<float>("math.sigmoid", 10.f, 10.f, slope), IsOkAndHolds(0.5f)) << slope; EXPECT_THAT(InvokeOperator<double>("math.sigmoid", 10., 10., double{slope}), IsOkAndHolds(0.5)) << slope; float epsilon = 0.001; EXPECT_THAT(InvokeOperator<float>("math.sigmoid", -10.f, 10.f, slope), IsOkAndHolds(AllOf(Lt(epsilon), Ge(0)))) << slope; EXPECT_THAT(InvokeOperator<float>("math.sigmoid", 20.f, 10.f, slope), IsOkAndHolds(AllOf(Gt(1. - epsilon), Le(1.)))) << slope; } EXPECT_THAT(InvokeOperator<float>("math.sigmoid", 2.f, 4.f, 5.f), IsOkAndHolds(FloatEq(1.f / (1.f + std::exp(5.f * (2.f)))))); EXPECT_THAT(InvokeOperator<double>("math.sigmoid", 2., 4., 5.), IsOkAndHolds(DoubleEq(1. / (1. + std::exp(5. * (2.)))))); } TEST(MathOperatorsTest, LogSigmoid) { EXPECT_THAT( InvokeOperator<float>("math.log_sigmoid", 5.f), IsOkAndHolds(FloatNear(std::log(1 / (1 + std::exp(-5.f))), 1e-5))); EXPECT_THAT( InvokeOperator<float>("math.log_sigmoid", 0.f), IsOkAndHolds(FloatNear(std::log(1 / (1 + std::exp(-0.f))), 1e-5))); EXPECT_THAT(InvokeOperator<float>("math.log_sigmoid", -5.f), IsOkAndHolds(FloatNear(std::log(1 / (1 + std::exp(5.f))), 1e-5))); EXPECT_THAT( InvokeOperator<double>("math.log_sigmoid", 5.), IsOkAndHolds(DoubleNear(std::log(1 / (1 + std::exp(-5.))), 1e-5))); EXPECT_THAT( InvokeOperator<double>("math.log_sigmoid", 0.), IsOkAndHolds(DoubleNear(std::log(1 / (1 + std::exp(-0.))), 1e-5))); EXPECT_THAT(InvokeOperator<double>("math.log_sigmoid", -5.), IsOkAndHolds(DoubleNear(std::log(1 / (1 + std::exp(5.))), 1e-5))); EXPECT_THAT(InvokeOperator<float>("math.log_sigmoid", -1000.f), IsOkAndHolds(FloatNear(-1000.f, 1e-05))); EXPECT_THAT(InvokeOperator<double>("math.log_sigmoid", -1000.), IsOkAndHolds(DoubleNear(-1000., 1e-05))); EXPECT_THAT(InvokeOperator<float>("math.log_sigmoid", 100.f), IsOkAndHolds(FloatNear(-std::exp(-100.f), 1e-50))); EXPECT_THAT(InvokeOperator<double>("math.log_sigmoid", 100.), IsOkAndHolds(DoubleNear(-std::exp(-100.), 1e-50))); } TEST(MathOperatorsTest, Logit) { EXPECT_THAT(InvokeOperator<float>("math.logit", 0.f), IsOkAndHolds(-std::numeric_limits<float>::infinity())); EXPECT_THAT(InvokeOperator<float>("math.logit", 1.f), IsOkAndHolds(std::numeric_limits<float>::infinity())); EXPECT_THAT(InvokeOperator<float>("math.logit", 0.5f), IsOkAndHolds(FloatNear(0.f, 1e-05))); EXPECT_THAT(InvokeOperator<float>("math.logit", -1.f), IsOkAndHolds(IsNan())); EXPECT_THAT(InvokeOperator<float>("math.logit", 2.f), IsOkAndHolds(IsNan())); EXPECT_THAT(InvokeOperator<double>("math.logit", 0.), IsOkAndHolds(-std::numeric_limits<float>::infinity())); EXPECT_THAT(InvokeOperator<double>("math.logit", 1.), IsOkAndHolds(std::numeric_limits<float>::infinity())); EXPECT_THAT(InvokeOperator<double>("math.logit", 0.5), IsOkAndHolds(DoubleNear(0., 1e-05))); EXPECT_THAT(InvokeOperator<double>("math.logit", -1.), IsOkAndHolds(IsNan())); EXPECT_THAT(InvokeOperator<double>("math.logit", 2.), IsOkAndHolds(IsNan())); } TEST(MathOperatorsTest, Sin) { EXPECT_THAT(InvokeOperator<float>("math.trig.sin", kPi), IsOkAndHolds(FloatNear(0.f, 1e-05))); EXPECT_THAT(InvokeOperator<float>("math.trig.sin", 1.f), IsOkAndHolds(FloatEq(std::sin(1.f)))); EXPECT_THAT(InvokeOperator<double>("math.trig.sin", double{kPi}), IsOkAndHolds(DoubleNear(0.f, 1e-05))); EXPECT_THAT(InvokeOperator<double>("math.trig.sin", 1.), IsOkAndHolds(DoubleEq(std::sin(1.)))); } TEST(MathOperatorsTest, Cos) { EXPECT_THAT(InvokeOperator<float>("math.trig.cos", kPi), IsOkAndHolds(FloatNear(-1.f, 1e-05))); EXPECT_THAT(InvokeOperator<float>("math.trig.cos", 1.f), IsOkAndHolds(FloatEq(std::cos(1.f)))); EXPECT_THAT(InvokeOperator<double>("math.trig.cos", double{kPi}), IsOkAndHolds(DoubleNear(-1.f, 1e-05))); EXPECT_THAT(InvokeOperator<double>("math.trig.cos", 1.), IsOkAndHolds(DoubleEq(std::cos(1.)))); } TEST(MathOperatorsTest, Sinh) { EXPECT_THAT(InvokeOperator<float>("math.trig.sinh", 0.f), IsOkAndHolds(FloatNear(0.f, 1e-05))); EXPECT_THAT(InvokeOperator<float>("math.trig.sinh", 1.f), IsOkAndHolds(FloatEq(std::sinh(1.f)))); EXPECT_THAT(InvokeOperator<double>("math.trig.sinh", 0.), IsOkAndHolds(DoubleNear(0.f, 1e-05))); EXPECT_THAT(InvokeOperator<double>("math.trig.sinh", 1.), IsOkAndHolds(DoubleEq(std::sinh(1.)))); } TEST(MathOperatorsTest, atan) { EXPECT_THAT(InvokeOperator<float>("math.trig.atan", 0.f), IsOkAndHolds(FloatNear(0.f, 1e-05))); EXPECT_THAT(InvokeOperator<float>("math.trig.atan", 1.f), IsOkAndHolds(FloatEq(std::atan(1.f)))); EXPECT_THAT(InvokeOperator<double>("math.trig.atan", 0.), IsOkAndHolds(DoubleNear(0.f, 1e-05))); EXPECT_THAT(InvokeOperator<double>("math.trig.atan", 1.), IsOkAndHolds(DoubleEq(std::atan(1.)))); } } }
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/qexpr/operators/math/math.h
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/qexpr/operators/math/math_test.cc
1ca990dbeca224035efdabffecc7f3738df6b52c
efeaf228-f0b1-48ec-ac82-7c7d4a53f59f
cpp
google/arolla
comparison
arolla/qexpr/operators/bool/comparison.h
arolla/qexpr/operators/bool/comparison_test.cc
#ifndef AROLLA_QEXPR_OPERATORS_BOOL_COMPARISON_H_ #define AROLLA_QEXPR_OPERATORS_BOOL_COMPARISON_H_ #include <type_traits> namespace arolla { struct EqualOp { using run_on_missing = std::true_type; template <typename T> bool operator()(const T& lhs, const T& rhs) const { return lhs == rhs; } }; struct NotEqualOp { using run_on_missing = std::true_type; template <typename T> bool operator()(const T& lhs, const T& rhs) const { return lhs != rhs; } }; struct LessOp { using run_on_missing = std::true_type; template <typename T> bool operator()(const T& lhs, const T& rhs) const { return lhs < rhs; } }; struct LessEqualOp { using run_on_missing = std::true_type; template <typename T> bool operator()(const T& lhs, const T& rhs) const { return lhs <= rhs; } }; } #endif
#include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status_matchers.h" #include "arolla/memory/optional_value.h" #include "arolla/qexpr/operators.h" #include "arolla/qtype/base_types.h" namespace arolla { namespace { using ::absl_testing::IsOkAndHolds; using OI = OptionalValue<int>; using OB = OptionalValue<bool>; TEST(ComparisonOperatorsTest, Equal) { EXPECT_THAT(InvokeOperator<bool>("bool.equal", 57, 57), IsOkAndHolds(true)); EXPECT_THAT(InvokeOperator<bool>("bool.equal", 57, 2), IsOkAndHolds(false)); EXPECT_THAT(InvokeOperator<OB>("bool.equal", OI{57}, OI{57}), IsOkAndHolds(OB{true})); EXPECT_THAT(InvokeOperator<OB>("bool.equal", OI{}, OI{57}), IsOkAndHolds(OB{})); EXPECT_THAT(InvokeOperator<OB>("bool.equal", OI{57}, OI{}), IsOkAndHolds(OB{})); EXPECT_THAT(InvokeOperator<OB>("bool.equal", OI{}, OI{}), IsOkAndHolds(OB{})); } TEST(ComparisonOperatorsTest, Less) { EXPECT_THAT(InvokeOperator<bool>("bool.less", 2, 57), IsOkAndHolds(true)); EXPECT_THAT(InvokeOperator<bool>("bool.less", 57, 57), IsOkAndHolds(false)); EXPECT_THAT(InvokeOperator<bool>("bool.less", 57, 2), IsOkAndHolds(false)); EXPECT_THAT(InvokeOperator<OB>("bool.less", OI{57}, OI{57}), IsOkAndHolds(OB{false})); EXPECT_THAT(InvokeOperator<OB>("bool.less", OI{}, OI{57}), IsOkAndHolds(OB{})); EXPECT_THAT(InvokeOperator<OB>("bool.less", OI{57}, OI{}), IsOkAndHolds(OB{})); EXPECT_THAT(InvokeOperator<OB>("bool.less", OI{}, OI{}), IsOkAndHolds(OB{})); } } }
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/qexpr/operators/bool/comparison.h
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/qexpr/operators/bool/comparison_test.cc
1ca990dbeca224035efdabffecc7f3738df6b52c
1fcf550c-2428-4d30-9fda-2b909f592820
cpp
google/arolla
logic
arolla/qexpr/operators/bool/logic.h
arolla/qexpr/operators/bool/logic_test.cc
#ifndef AROLLA_QEXPR_OPERATORS_BOOL_LOGIC_H_ #define AROLLA_QEXPR_OPERATORS_BOOL_LOGIC_H_ #include <type_traits> #include "arolla/dense_array/dense_array.h" #include "arolla/dense_array/ops/dense_ops.h" #include "arolla/dense_array/qtype/types.h" #include "arolla/memory/optional_value.h" #include "arolla/qexpr/eval_context.h" namespace arolla { struct LogicalAndOp { using run_on_missing = std::true_type; bool operator()(bool lhs, bool rhs) const { return lhs && rhs; } OptionalValue<bool> operator()(const OptionalValue<bool>& lhs, const OptionalValue<bool>& rhs) const { if (lhs.present) { return !lhs.value ? false : rhs; } else if (rhs.present) { return !rhs.value ? false : lhs; } else { return OptionalValue<bool>{}; } } }; struct LogicalOrOp { using run_on_missing = std::true_type; bool operator()(bool lhs, bool rhs) const { return lhs || rhs; } OptionalValue<bool> operator()(const OptionalValue<bool>& lhs, const OptionalValue<bool>& rhs) const { if (lhs.present) { return lhs.value ? true : rhs; } else if (rhs.present) { return rhs.value ? true : lhs; } else { return OptionalValue<bool>{}; } } }; struct LogicalNotOp { using run_on_missing = std::true_type; bool operator()(bool arg) const { return !arg; } }; struct LogicalIfOp { using run_on_missing = std::true_type; template <typename T, typename = std::enable_if_t<is_scalar_type_v<T>>> const T& operator()(const OptionalValue<bool>& condition, const T& true_value, const T& false_value, const T& missing_value) const { if (condition.present) { return condition.value ? true_value : false_value; } else { return missing_value; } } template <typename T> OptionalValue<T> operator()(const OptionalValue<bool>& condition, const OptionalValue<T>& true_value, const OptionalValue<T>& false_value, const OptionalValue<T>& missing_value) const { if (condition.present) { return condition.value ? true_value : false_value; } else { return missing_value; } } template <typename T> DenseArray<T> operator()(EvaluationContext* ctx, const DenseArray<bool>& condition, const OptionalValue<T>& true_value, const OptionalValue<T>& false_value, const OptionalValue<T>& missing_value) const { auto fn = [&true_value, &false_value, &missing_value]( OptionalValue<bool> condition) -> OptionalValue<T> { return LogicalIfOp()(condition, true_value, false_value, missing_value); }; auto op = CreateDenseOp<DenseOpFlags::kRunOnMissing, decltype(fn), T>( fn, &ctx->buffer_factory()); return op(condition); } template <typename TrueFn, typename FalseFn, typename MissingFn, std::enable_if_t<std::is_invocable_v<TrueFn> || std::is_invocable_v<FalseFn> || std::is_invocable_v<MissingFn>, bool> = true> auto operator()(const OptionalValue<bool>& condition, const TrueFn& true_value, const FalseFn& false_value, const MissingFn& missing_value) const { auto unwrap = [](const auto& fn) { if constexpr (std::is_invocable_v<decltype(fn)>) { return fn(); } else { return fn; } }; return condition.present ? (condition.value ? unwrap(true_value) : unwrap(false_value)) : unwrap(missing_value); } }; } #endif
#include "arolla/qexpr/operators/bool/logic.h" #include <cstdint> #include <optional> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/log/log.h" #include "absl/status/status.h" #include "absl/status/status_matchers.h" #include "absl/status/statusor.h" #include "arolla/dense_array/dense_array.h" #include "arolla/dense_array/qtype/types.h" #include "arolla/memory/optional_value.h" #include "arolla/qexpr/operators.h" #include "arolla/qtype/base_types.h" namespace arolla { namespace { using ::absl_testing::IsOkAndHolds; using ::absl_testing::StatusIs; using ::testing::ElementsAre; using ::testing::Eq; using OB = OptionalValue<bool>; using OI = OptionalValue<int64_t>; constexpr auto NA = std::nullopt; #define EXPECT_OPERATOR_RESULT_IS(op_name, lhs, rhs, result) \ do { \ EXPECT_THAT(InvokeOperator<OB>(op_name, lhs, rhs), IsOkAndHolds(result)); \ if (lhs.present && rhs.present) { \ EXPECT_THAT(InvokeOperator<bool>(op_name, lhs.value, rhs.value), \ IsOkAndHolds(result.value)); \ } \ } while (false) TEST(LogicOperatorsTest, LogicalAnd) { EXPECT_OPERATOR_RESULT_IS("bool.logical_and", OB{true}, OB{true}, OB{true}); EXPECT_OPERATOR_RESULT_IS("bool.logical_and", OB{true}, OB{false}, OB{false}); EXPECT_OPERATOR_RESULT_IS("bool.logical_and", OB{true}, OB{}, OB{}); EXPECT_OPERATOR_RESULT_IS("bool.logical_and", OB{false}, OB{true}, OB{false}); EXPECT_OPERATOR_RESULT_IS("bool.logical_and", OB{false}, OB{false}, OB{false}); EXPECT_OPERATOR_RESULT_IS("bool.logical_and", OB{false}, OB{}, OB{false}); EXPECT_OPERATOR_RESULT_IS("bool.logical_and", OB{}, OB{true}, OB{}); EXPECT_OPERATOR_RESULT_IS("bool.logical_and", OB{}, OB{false}, OB{false}); EXPECT_OPERATOR_RESULT_IS("bool.logical_and", OB{}, OB{}, OB{}); EXPECT_THAT(InvokeOperator<DenseArray<bool>>( "bool.logical_and", CreateDenseArray<bool>({true, false}), CreateDenseArray<bool>({true, NA})), IsOkAndHolds(ElementsAre(true, false))); } TEST(LogicOperatorsTest, LogicalOr) { EXPECT_OPERATOR_RESULT_IS("bool.logical_or", OB{true}, OB{true}, OB{true}); EXPECT_OPERATOR_RESULT_IS("bool.logical_or", OB{true}, OB{false}, OB{true}); EXPECT_OPERATOR_RESULT_IS("bool.logical_or", OB{true}, OB{}, OB{true}); EXPECT_OPERATOR_RESULT_IS("bool.logical_or", OB{false}, OB{true}, OB{true}); EXPECT_OPERATOR_RESULT_IS("bool.logical_or", OB{false}, OB{false}, OB{false}); EXPECT_OPERATOR_RESULT_IS("bool.logical_or", OB{false}, OB{}, OB{}); EXPECT_OPERATOR_RESULT_IS("bool.logical_or", OB{}, OB{true}, OB{true}); EXPECT_OPERATOR_RESULT_IS("bool.logical_or", OB{}, OB{false}, OB{}); EXPECT_OPERATOR_RESULT_IS("bool.logical_or", OB{}, OB{}, OB{}); EXPECT_THAT(InvokeOperator<DenseArray<bool>>( "bool.logical_or", CreateDenseArray<bool>( {true, true, true, false, false, false, NA, NA, NA}), CreateDenseArray<bool>( {true, false, NA, true, false, NA, true, false, NA})), IsOkAndHolds(ElementsAre(true, true, true, true, false, NA, true, NA, NA))); } TEST(LogicOperatorsTest, LogicalNot) { EXPECT_THAT(InvokeOperator<bool>("bool.logical_not", true), IsOkAndHolds(false)); EXPECT_THAT(InvokeOperator<bool>("bool.logical_not", false), IsOkAndHolds(true)); EXPECT_THAT(InvokeOperator<OB>("bool.logical_not", OB{}), IsOkAndHolds(OB{})); } TEST(LogicOperatorsTest, LogicalIf) { EXPECT_THAT( InvokeOperator<OI>("bool.logical_if", OB{true}, OI{1}, OI{2}, OI{3}), IsOkAndHolds(1)); EXPECT_THAT( InvokeOperator<OI>("bool.logical_if", OB{true}, OI{}, OI{2}, OI{3}), IsOkAndHolds(std::nullopt)); EXPECT_THAT( InvokeOperator<OI>("bool.logical_if", OB{false}, OI{1}, OI{2}, OI{3}), IsOkAndHolds(2)); EXPECT_THAT( InvokeOperator<OI>("bool.logical_if", OB{false}, OI{1}, OI{}, OI{3}), IsOkAndHolds(std::nullopt)); EXPECT_THAT(InvokeOperator<OI>("bool.logical_if", OB{}, OI{1}, OI{2}, OI{3}), IsOkAndHolds(3)); EXPECT_THAT(InvokeOperator<OI>("bool.logical_if", OB{}, OI{1}, OI{2}, OI{}), IsOkAndHolds(std::nullopt)); } TEST(LogicOperatorsTest, LogicalIfOnLambdas) { auto lambda = [](auto x) { return [x]() { return x; }; }; auto no_call_lambda = [](auto x) { return [x]() { LOG(FATAL) << "Lambda shouldn't be called. " << x; return x; }; }; EXPECT_THAT(LogicalIfOp()(OB{true}, OI{1}, OI{2}, OI{3}), Eq(OI{1})); EXPECT_THAT(LogicalIfOp()(OB{true}, lambda(OI{1}), OI{2}, OI{3}), Eq(OI{1})); EXPECT_THAT(LogicalIfOp()(OB{false}, no_call_lambda(OI{1}), OI{2}, OI{3}), Eq(OI{2})); EXPECT_THAT(LogicalIfOp()(OB{}, no_call_lambda(OI{1}), OI{2}, OI{3}), Eq(OI{3})); EXPECT_THAT(LogicalIfOp()(OB{true}, OI{1}, no_call_lambda(OI{2}), OI{3}), Eq(OI{1})); EXPECT_THAT(LogicalIfOp()(OB{false}, OI{1}, lambda(OI{2}), OI{3}), Eq(OI{2})); EXPECT_THAT(LogicalIfOp()(OB{}, OI{1}, no_call_lambda(OI{2}), OI{3}), Eq(OI{3})); EXPECT_THAT(LogicalIfOp()(OB{true}, OI{1}, OI{2}, no_call_lambda(OI{3})), Eq(OI{1})); EXPECT_THAT(LogicalIfOp()(OB{false}, OI{1}, OI{2}, no_call_lambda(OI{3})), Eq(OI{2})); EXPECT_THAT(LogicalIfOp()(OB{}, OI{1}, OI{2}, lambda(OI{3})), Eq(OI{3})); EXPECT_THAT( LogicalIfOp()(OB{true}, lambda(OI{1}), no_call_lambda(OI{2}), OI{3}), Eq(OI{1})); EXPECT_THAT( LogicalIfOp()(OB{false}, no_call_lambda(OI{1}), lambda(OI{2}), OI{3}), Eq(OI{2})); EXPECT_THAT( LogicalIfOp()(OB{}, no_call_lambda(OI{1}), no_call_lambda(OI{2}), OI{3}), Eq(OI{3})); EXPECT_THAT( LogicalIfOp()(OB{true}, lambda(OI{1}), OI{2}, no_call_lambda(OI{3})), Eq(OI{1})); EXPECT_THAT(LogicalIfOp()(OB{false}, no_call_lambda(OI{1}), OI{2}, no_call_lambda(OI{3})), Eq(OI{2})); EXPECT_THAT(LogicalIfOp()(OB{}, no_call_lambda(OI{1}), OI{2}, lambda(OI{3})), Eq(OI{3})); EXPECT_THAT(LogicalIfOp()(OB{true}, OI{1}, no_call_lambda(OI{2}), no_call_lambda(OI{3})), Eq(OI{1})); EXPECT_THAT( LogicalIfOp()(OB{false}, OI{1}, lambda(OI{2}), no_call_lambda(OI{3})), Eq(OI{2})); EXPECT_THAT(LogicalIfOp()(OB{}, OI{1}, no_call_lambda(OI{2}), lambda(OI{3})), Eq(OI{3})); EXPECT_THAT(LogicalIfOp()(OB{true}, lambda(OI{1}), no_call_lambda(OI{2}), no_call_lambda(OI{3})), Eq(OI{1})); EXPECT_THAT(LogicalIfOp()(OB{false}, no_call_lambda(OI{1}), lambda(OI{2}), no_call_lambda(OI{3})), Eq(OI{2})); EXPECT_THAT(LogicalIfOp()(OB{}, no_call_lambda(OI{1}), no_call_lambda(OI{2}), lambda(OI{3})), Eq(OI{3})); } TEST(LogicOperatorsTest, LogicalIfOnLambdasWithError) { auto lambda = [](auto x) { return [x]() { return x; }; }; auto lambda_ok = [](auto x) { return [x]() { return absl::StatusOr<decltype(x)>(x); }; }; auto lambda_fail = [](auto x) { return [x]() { return absl::StatusOr<decltype(x)>(absl::UnimplementedError("fake")); }; }; auto no_call_lambda = [](auto x) { return [x]() { LOG(FATAL) << "Lambda shouldn't be called. " << x; return x; }; }; auto no_call_lambda_ok = [](auto x) { return [x]() { LOG(FATAL) << "Lambda shouldn't be called. " << x; return absl::StatusOr<decltype(x)>(x); }; }; auto op = LogicalIfOp(); EXPECT_THAT(op(OB{true}, OI{1}, OI{2}, OI{3}), Eq(OI{1})); EXPECT_THAT(op(OB{true}, lambda_ok(OI{1}), OI{2}, OI{3}), IsOkAndHolds(Eq(OI{1}))); EXPECT_THAT(op(OB{false}, no_call_lambda_ok(OI{1}), OI{2}, OI{3}), IsOkAndHolds(Eq(OI{2}))); EXPECT_THAT(op(OB{}, no_call_lambda_ok(OI{1}), OI{2}, OI{3}), IsOkAndHolds(Eq(OI{3}))); EXPECT_THAT(op(OB{true}, OI{1}, no_call_lambda_ok(OI{2}), OI{3}), IsOkAndHolds(Eq(OI{1}))); EXPECT_THAT(op(OB{false}, OI{1}, lambda_ok(OI{2}), OI{3}), IsOkAndHolds(Eq(OI{2}))); EXPECT_THAT(op(OB{}, OI{1}, no_call_lambda_ok(OI{2}), OI{3}), IsOkAndHolds(Eq(OI{3}))); EXPECT_THAT(op(OB{true}, OI{1}, OI{2}, no_call_lambda_ok(OI{3})), IsOkAndHolds(Eq(OI{1}))); EXPECT_THAT(op(OB{false}, OI{1}, OI{2}, no_call_lambda_ok(OI{3})), IsOkAndHolds(Eq(OI{2}))); EXPECT_THAT(op(OB{}, OI{1}, OI{2}, lambda_ok(OI{3})), IsOkAndHolds(Eq(OI{3}))); EXPECT_THAT(op(OB{true}, lambda_ok(OI{1}), no_call_lambda(OI{2}), OI{3}), IsOkAndHolds(Eq(OI{1}))); EXPECT_THAT(op(OB{false}, no_call_lambda(OI{1}), lambda_ok(OI{2}), OI{3}), IsOkAndHolds(Eq(OI{2}))); EXPECT_THAT(op(OB{}, no_call_lambda(OI{1}), no_call_lambda_ok(OI{2}), OI{3}), IsOkAndHolds(Eq(OI{3}))); EXPECT_THAT(op(OB{true}, lambda_ok(OI{1}), OI{2}, no_call_lambda(OI{3})), IsOkAndHolds(Eq(OI{1}))); EXPECT_THAT( op(OB{false}, no_call_lambda(OI{1}), OI{2}, no_call_lambda_ok(OI{3})), IsOkAndHolds(Eq(OI{2}))); EXPECT_THAT(op(OB{}, no_call_lambda(OI{1}), OI{2}, lambda_ok(OI{3})), IsOkAndHolds(Eq(OI{3}))); EXPECT_THAT( op(OB{true}, OI{1}, no_call_lambda_ok(OI{2}), no_call_lambda(OI{3})), IsOkAndHolds(Eq(OI{1}))); EXPECT_THAT(op(OB{false}, OI{1}, lambda(OI{2}), no_call_lambda_ok(OI{3})), IsOkAndHolds(Eq(OI{2}))); EXPECT_THAT(op(OB{}, OI{1}, no_call_lambda_ok(OI{2}), lambda_ok(OI{3})), IsOkAndHolds(Eq(OI{3}))); EXPECT_THAT(op(OB{true}, lambda_ok(OI{1}), no_call_lambda(OI{2}), no_call_lambda(OI{3})), IsOkAndHolds(Eq(OI{1}))); EXPECT_THAT(op(OB{false}, no_call_lambda_ok(OI{1}), lambda(OI{2}), no_call_lambda_ok(OI{3})), IsOkAndHolds(Eq(OI{2}))); EXPECT_THAT(op(OB{}, no_call_lambda_ok(OI{1}), no_call_lambda_ok(OI{2}), lambda_ok(OI{3})), IsOkAndHolds(Eq(OI{3}))); EXPECT_THAT(op(OB{true}, lambda_fail(OI{1}), no_call_lambda(OI{2}), no_call_lambda(OI{3})), StatusIs(absl::StatusCode::kUnimplemented, "fake")); EXPECT_THAT(op(OB{false}, no_call_lambda(OI{1}), lambda_fail(OI{2}), no_call_lambda(OI{3})), StatusIs(absl::StatusCode::kUnimplemented, "fake")); EXPECT_THAT(op(OB{}, no_call_lambda_ok(OI{1}), no_call_lambda(OI{2}), lambda_fail(OI{3})), StatusIs(absl::StatusCode::kUnimplemented, "fake")); } TEST(LogicOperatorsTest, LogicalIfDenseArray) { EXPECT_THAT(InvokeOperator<DenseArray<int64_t>>( "bool.logical_if", CreateDenseArray<bool>( {true, true, false, false, std::nullopt, std::nullopt}), CreateDenseArray<int64_t>( {1, std::nullopt, 1, std::nullopt, 1, std::nullopt}), CreateDenseArray<int64_t>( {2, std::nullopt, 2, std::nullopt, 2, std::nullopt}), CreateDenseArray<int64_t>( {3, std::nullopt, 3, std::nullopt, 3, std::nullopt})), IsOkAndHolds(ElementsAre(1, std::nullopt, 2, std::nullopt, 3, std::nullopt))); } TEST(LogicOperatorsTest, LogicalIfDenseArrayWithScalars) { EXPECT_THAT(InvokeOperator<DenseArray<int64_t>>( "bool.logical_if", CreateDenseArray<bool>({true, false, std::nullopt}), OI{1}, OI{2}, OI{3}), IsOkAndHolds(ElementsAre(1, 2, 3))); } } }
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/qexpr/operators/bool/logic.h
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/qexpr/operators/bool/logic_test.cc
1ca990dbeca224035efdabffecc7f3738df6b52c
2801fa6d-a374-41d2-8d79-f378f788147e
cpp
google/arolla
bitwise
arolla/qexpr/operators/bitwise/bitwise.h
arolla/qexpr/operators/bitwise/bitwise_test.cc
#ifndef AROLLA_QEXPR_OPERATORS_BITWISE_BITWISE_H_ #define AROLLA_QEXPR_OPERATORS_BITWISE_BITWISE_H_ #include <type_traits> namespace arolla { struct BitwiseAndOp { using run_on_missing = std::true_type; template <typename T> T operator()(T lhs, T rhs) const { return lhs & rhs; } }; struct BitwiseOrOp { using run_on_missing = std::true_type; template <typename T> T operator()(T lhs, T rhs) const { return lhs | rhs; } }; struct BitwiseXorOp { using run_on_missing = std::true_type; template <typename T> T operator()(T lhs, T rhs) const { return lhs ^ rhs; } }; struct InvertOp { using run_on_missing = std::true_type; template <typename T> T operator()(T x) const { return ~x; } }; } #endif
#include <cstdint> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status_matchers.h" #include "arolla/qexpr/operators.h" #include "arolla/qtype/base_types.h" namespace arolla { namespace { using ::absl_testing::IsOkAndHolds; TEST(BitwiseOperatorsTest, BitwiseAnd) { EXPECT_THAT( InvokeOperator<int32_t>("bitwise.bitwise_and", int32_t{5}, int32_t{17}), IsOkAndHolds(1)); EXPECT_THAT( InvokeOperator<int64_t>("bitwise.bitwise_and", int64_t{5}, int64_t{17}), IsOkAndHolds(1)); EXPECT_THAT( InvokeOperator<int32_t>("bitwise.bitwise_and", int32_t{-2}, int32_t{17}), IsOkAndHolds(16)); EXPECT_THAT( InvokeOperator<int32_t>("bitwise.bitwise_and", int32_t{-2}, int32_t{-2}), IsOkAndHolds(-2)); } TEST(BitwiseOperatorsTest, BitwiseOr) { EXPECT_THAT( InvokeOperator<int32_t>("bitwise.bitwise_or", int32_t{5}, int32_t{17}), IsOkAndHolds(21)); EXPECT_THAT( InvokeOperator<int64_t>("bitwise.bitwise_or", int64_t{5}, int64_t{17}), IsOkAndHolds(21)); EXPECT_THAT( InvokeOperator<int32_t>("bitwise.bitwise_or", int32_t{-2}, int32_t{17}), IsOkAndHolds(-1)); EXPECT_THAT( InvokeOperator<int32_t>("bitwise.bitwise_or", int32_t{-2}, int32_t{-2}), IsOkAndHolds(-2)); } TEST(BitwiseOperatorsTest, BitwiseXor) { EXPECT_THAT( InvokeOperator<int32_t>("bitwise.bitwise_xor", int32_t{5}, int32_t{17}), IsOkAndHolds(20)); EXPECT_THAT( InvokeOperator<int64_t>("bitwise.bitwise_xor", int64_t{5}, int64_t{17}), IsOkAndHolds(20)); EXPECT_THAT( InvokeOperator<int32_t>("bitwise.bitwise_xor", int32_t{-2}, int32_t{17}), IsOkAndHolds(-17)); EXPECT_THAT( InvokeOperator<int32_t>("bitwise.bitwise_xor", int32_t{-2}, int32_t{-2}), IsOkAndHolds(0)); } TEST(BitwiseOperatorsTest, Invert) { EXPECT_THAT(InvokeOperator<int32_t>("bitwise.invert", int32_t{5}), IsOkAndHolds(-6)); EXPECT_THAT(InvokeOperator<int64_t>("bitwise.invert", int64_t{5}), IsOkAndHolds(-6)); EXPECT_THAT(InvokeOperator<int32_t>("bitwise.invert", int32_t{-2}), IsOkAndHolds(1)); } } }
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/qexpr/operators/bitwise/bitwise.h
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/qexpr/operators/bitwise/bitwise_test.cc
1ca990dbeca224035efdabffecc7f3738df6b52c
ecd66c0f-40bd-4fc8-95a8-367b929fe67c
cpp
google/arolla
dict_operators
arolla/qexpr/operators/dict/dict_operators.h
arolla/qexpr/operators/dict/dict_operators_test.cc
#ifndef AROLLA_OPERATORS_EXPERIMENTAL_DICT_H_ #define AROLLA_OPERATORS_EXPERIMENTAL_DICT_H_ #include <cmath> #include <cstdint> #include <optional> #include <type_traits> #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/memory/optional_value.h" #include "arolla/qexpr/eval_context.h" #include "arolla/qtype/dict/dict_types.h" #include "arolla/util/view_types.h" namespace arolla { struct MakeKeyToRowDictOp { template <typename Key> absl::StatusOr<KeyToRowDict<Key>> operator()( const DenseArray<Key>& keys) const { typename KeyToRowDict<Key>::Map dict; dict.reserve(keys.size()); absl::Status status; keys.ForEach([&](int64_t id, bool present, view_type_t<Key> key) { if (present) { if constexpr (std::is_floating_point_v<Key>) { if (std::isnan(key)) { status = absl::InvalidArgumentError("NaN dict keys are prohibited"); return; } } auto [iter, inserted] = dict.emplace(Key{key}, id); if (!inserted) { status = absl::InvalidArgumentError( absl::StrFormat("duplicated key %s in the dict", Repr(Key{key}))); } } else { } }); if (status.ok()) { return KeyToRowDict<Key>(std::move(dict)); } else { return status; } } }; class DictGetRowOp { public: template <typename Key> OptionalValue<int64_t> operator()(const KeyToRowDict<Key>& dict, view_type_t<Key> key) const { if (auto iter = dict.map().find(key); iter != dict.map().end()) { return iter->second; } else { return std::nullopt; } } }; class DictContainsOp { public: template <typename Key> OptionalUnit operator()(const KeyToRowDict<Key>& dict, view_type_t<Key> key) const { return OptionalUnit{dict.map().contains(key)}; } }; class DictKeysOp { public: template <typename Key> absl::StatusOr<DenseArray<Key>> operator()( EvaluationContext* ctx, const KeyToRowDict<Key>& dict) const { DenseArrayBuilder<Key> result_builder(dict.map().size(), &ctx->buffer_factory()); for (const auto& [key, row] : dict.map()) { if (row < 0 || row >= dict.map().size()) { return absl::InternalError( "unexpected row ids in the key-to-row mapping in the dict"); } result_builder.Set(row, key); } DenseArray<Key> result = std::move(result_builder).Build(); if (!result.IsFull()) { return absl::InternalError("incomplete key-to-row mapping in the dict"); } return result; } }; } #endif
#include <cstdint> #include <optional> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "absl/status/status_matchers.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/memory/optional_value.h" #include "arolla/qexpr/operators.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/dict/dict_types.h" #include "arolla/util/bytes.h" #include "arolla/util/unit.h" namespace arolla { namespace { using ::absl_testing::IsOkAndHolds; using ::absl_testing::StatusIs; using ::testing::ElementsAre; using ::testing::Eq; using ::testing::HasSubstr; using ::testing::Pair; using ::testing::Property; using ::testing::UnorderedElementsAre; TEST(DictOperatorsTest, MakeKeyToRowDict) { EXPECT_THAT( InvokeOperator<KeyToRowDict<int32_t>>("dict._make_key_to_row_dict", CreateDenseArray<int32_t>({2, 57})), IsOkAndHolds(Property(&KeyToRowDict<int32_t>::map, UnorderedElementsAre(Pair(2, 0), Pair(57, 1))))); EXPECT_THAT( InvokeOperator<KeyToRowDict<Bytes>>( "dict._make_key_to_row_dict", CreateDenseArray<Bytes>({Bytes("foo"), Bytes("bar")})), IsOkAndHolds(Property( &KeyToRowDict<Bytes>::map, UnorderedElementsAre(Pair(Bytes("foo"), 0), Pair(Bytes("bar"), 1))))); EXPECT_THAT(InvokeOperator<KeyToRowDict<Bytes>>( "dict._make_key_to_row_dict", CreateDenseArray<Bytes>({Bytes("foo"), Bytes("foo")})), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("duplicated key b'foo' in the dict"))); } TEST(DictOperatorsTest, GetRow) { using ORI = OptionalValue<int64_t>; using OB = OptionalValue<Bytes>; KeyToRowDict<Bytes> dict({{Bytes("foo"), 5}, {Bytes("bar"), 7}}); EXPECT_THAT(InvokeOperator<ORI>("dict._get_row", dict, Bytes("foo")), IsOkAndHolds(Eq(ORI(5)))); EXPECT_THAT(InvokeOperator<ORI>("dict._get_row", dict, Bytes("unknown")), IsOkAndHolds(Eq(ORI()))); EXPECT_THAT(InvokeOperator<ORI>("dict._get_row", dict, OB(Bytes("foo"))), IsOkAndHolds(Eq(ORI(5)))); EXPECT_THAT(InvokeOperator<ORI>("dict._get_row", dict, OB()), IsOkAndHolds(Eq(ORI()))); DenseArray<Bytes> dense_array = CreateDenseArray<Bytes>({Bytes{"foo"}, Bytes{"unknown"}, std::nullopt}); { ASSERT_OK_AND_ASSIGN(auto res, InvokeOperator<DenseArray<int64_t>>( "dict._get_row", dict, dense_array)); EXPECT_THAT(res, ElementsAre(5, std::nullopt, std::nullopt)); } { ASSERT_OK_AND_ASSIGN( auto res, InvokeOperator<Array<int64_t>>("dict._get_row", dict, Array<Bytes>(dense_array))); EXPECT_THAT(res, ElementsAre(5, std::nullopt, std::nullopt)); } } TEST(DictOperatorsTest, Contains) { KeyToRowDict<Bytes> dict({{Bytes("foo"), 5}, {Bytes("bar"), 7}}); EXPECT_THAT( InvokeOperator<OptionalUnit>("dict._contains", dict, Bytes("foo")), IsOkAndHolds(Eq(kPresent))); EXPECT_THAT( InvokeOperator<OptionalUnit>("dict._contains", dict, Bytes("unknown")), IsOkAndHolds(Eq(kMissing))); EXPECT_THAT(InvokeOperator<OptionalUnit>("dict._contains", dict, OptionalValue<Bytes>(Bytes("foo"))), IsOkAndHolds(Eq(kPresent))); EXPECT_THAT(InvokeOperator<OptionalUnit>("dict._contains", dict, OptionalValue<Bytes>()), IsOkAndHolds(Eq(kMissing))); DenseArray<Bytes> dense_array = CreateDenseArray<Bytes>({Bytes{"foo"}, Bytes{"unknown"}, std::nullopt}); { ASSERT_OK_AND_ASSIGN(auto res, InvokeOperator<DenseArray<Unit>>( "dict._contains", dict, dense_array)); EXPECT_THAT(res, ElementsAre(kPresent, kMissing, kMissing)); } { ASSERT_OK_AND_ASSIGN( auto res, InvokeOperator<Array<Unit>>("dict._contains", dict, Array<Bytes>(dense_array))); EXPECT_THAT(res, ElementsAre(kPresent, kMissing, kMissing)); } } TEST(DictOperatorsTest, Keys) { EXPECT_THAT(InvokeOperator<DenseArray<Bytes>>( "dict._keys", KeyToRowDict<Bytes>({{Bytes("foo"), 1}, {Bytes("bar"), 0}})), IsOkAndHolds(ElementsAre("bar", "foo"))); EXPECT_THAT( InvokeOperator<DenseArray<Bytes>>( "dict._keys", KeyToRowDict<Bytes>({{Bytes("foo"), 57}, {Bytes("bar"), 0}})), StatusIs( absl::StatusCode::kInternal, HasSubstr( "unexpected row ids in the key-to-row mapping in the dict"))); EXPECT_THAT( InvokeOperator<DenseArray<Bytes>>( "dict._keys", KeyToRowDict<Bytes>({{Bytes("foo"), -1}, {Bytes("bar"), 0}})), StatusIs( absl::StatusCode::kInternal, HasSubstr( "unexpected row ids in the key-to-row mapping in the dict"))); EXPECT_THAT(InvokeOperator<DenseArray<Bytes>>( "dict._keys", KeyToRowDict<Bytes>({{Bytes("foo"), 0}, {Bytes("bar"), 0}})), StatusIs(absl::StatusCode::kInternal, HasSubstr("incomplete key-to-row mapping in the dict"))); } } }
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/qexpr/operators/dict/dict_operators.h
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/qexpr/operators/dict/dict_operators_test.cc
1ca990dbeca224035efdabffecc7f3738df6b52c
cc8f58bf-dadd-4b33-9288-7382a0f4e746
cpp
google/arolla
operator_fixture
arolla/qexpr/testing/operator_fixture.h
arolla/qexpr/testing/operator_fixture_test.cc
#ifndef AROLLA_QEXPR_OPERATOR_FIXTURE_H_ #define AROLLA_QEXPR_OPERATOR_FIXTURE_H_ #include <array> #include <cstddef> #include <cstdint> #include <memory> #include <tuple> #include <typeindex> #include <utility> #include <vector> #include "absl/base/attributes.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "absl/types/span.h" #include "arolla/memory/frame.h" #include "arolla/qexpr/eval_context.h" #include "arolla/qexpr/operators.h" #include "arolla/qexpr/qexpr_operator_signature.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/tuple_qtype.h" #include "arolla/qtype/typed_slot.h" #include "arolla/util/status_macros_backport.h" namespace arolla { template <typename ARG_Ts, typename RES_Ts> class OperatorFixture; template <typename... ARG_Ts, typename... RES_Ts> class OperatorFixture<std::tuple<ARG_Ts...>, std::tuple<RES_Ts...>> { public: static absl::StatusOr<OperatorFixture> Create(const QExprOperator& op) { return CreateImpl(op, std::make_index_sequence<sizeof...(ARG_Ts)>(), std::make_index_sequence<sizeof...(RES_Ts)>()); } OperatorFixture(OperatorFixture&& other) = default; OperatorFixture& operator=(OperatorFixture&& other) = default; absl::StatusOr<std::tuple<RES_Ts...>> Call(ARG_Ts&&... args) const { return CallImpl(std::forward<ARG_Ts&&>(args)..., std::make_index_sequence<sizeof...(RES_Ts)>()); } private: OperatorFixture(std::unique_ptr<BoundOperator> bound_op, FrameLayout&& layout, std::tuple<FrameLayout::Slot<ARG_Ts>...> input_slots, std::tuple<FrameLayout::Slot<RES_Ts>...> output_slots) : bound_op_(std::move(bound_op)), layout_(std::move(layout)), input_slots_(input_slots), output_slots_(output_slots) {} template <typename... Ts> static absl::Status VerifyTypes(absl::Span<const QTypePtr> types) { if (sizeof...(Ts) != types.size()) { return absl::FailedPreconditionError( absl::StrFormat("argument count mismatch; got %d expected %d", types.size(), sizeof...(Ts))); } std::array<std::type_index, sizeof...(Ts)> expected_types = { std::type_index(typeid(Ts))...}; for (size_t i = 0; i < types.size(); ++i) { if (expected_types[i] != std::type_index(types[i]->type_info())) { return absl::FailedPreconditionError( absl::StrFormat("type mismatch at position %d", i)); } } return absl::OkStatus(); } template <typename... Ts> static absl::Status VerifyTypes(absl::Span<const TypedSlot> slots) { std::vector<QTypePtr> types; types.reserve(slots.size()); for (auto slot : slots) { types.push_back(slot.GetType()); } return VerifyTypes<Ts...>(types); } template <size_t... ARG_Is, size_t... RES_Is> static absl::StatusOr<OperatorFixture> CreateImpl( const QExprOperator& op, std::index_sequence<ARG_Is...> arg_seq, std::index_sequence<RES_Is...> res_seq) { FrameLayout::Builder layout_builder; auto input_slots = std::make_tuple(layout_builder.AddSlot<ARG_Ts>()...); const QExprOperatorSignature* op_signature = op.signature(); auto input_types = op_signature->input_types(); RETURN_IF_ERROR(VerifyTypes<ARG_Ts...>(input_types)) << "on input types"; auto output_type = op_signature->output_type(); auto output_typed_slot = AddSlot(output_type, &layout_builder); std::vector<TypedSlot> output_typed_subslots; if (IsTupleQType(output_type)) { output_typed_subslots.reserve(output_typed_slot.SubSlotCount()); for (int64_t i = 0; i < output_typed_slot.SubSlotCount(); ++i) { output_typed_subslots.push_back(output_typed_slot.SubSlot(i)); } } else { output_typed_subslots = {output_typed_slot}; } ASSIGN_OR_RETURN(auto output_slots, TypedSlot::ToSlots<RES_Ts...>(output_typed_subslots)); RETURN_IF_ERROR(VerifyTypes<RES_Ts...>(output_typed_subslots)) << "on output types"; ASSIGN_OR_RETURN(auto bound_op, op.Bind({TypedSlot::FromSlot(std::get<ARG_Is>(input_slots), input_types[ARG_Is])...}, output_typed_slot)); auto layout = std::move(layout_builder).Build(); return OperatorFixture(std::move(bound_op), std::move(layout), input_slots, output_slots); } template <size_t... ARG_Is> void SetInputs(FramePtr frame ABSL_ATTRIBUTE_UNUSED, ARG_Ts&&... args, std::index_sequence<ARG_Is...>) const { (frame.Set(std::get<ARG_Is>(input_slots_), std::move(args)), ...); } template <size_t... RES_Is> absl::StatusOr<std::tuple<RES_Ts...>> CallImpl( ARG_Ts&&... args, std::index_sequence<RES_Is...>) const { RootEvaluationContext root_ctx(&layout_); SetInputs(root_ctx.frame(), std::move(args)..., std::make_index_sequence<sizeof...(ARG_Ts)>()); EvaluationContext ctx(root_ctx); bound_op_->Run(&ctx, root_ctx.frame()); if (!ctx.status().ok()) { return std::move(ctx).status(); } return std::make_tuple( std::move(*root_ctx.GetMutable(std::get<RES_Is>(output_slots_)))...); } std::unique_ptr<BoundOperator> bound_op_; FrameLayout layout_; std::tuple<FrameLayout::Slot<ARG_Ts>...> input_slots_; std::tuple<FrameLayout::Slot<RES_Ts>...> output_slots_; }; template <template <typename...> class TYPE_LIST, typename... ARG_Ts, typename RES_T> class OperatorFixture<TYPE_LIST<ARG_Ts...>, RES_T> { public: OperatorFixture(OperatorFixture&& other) = default; OperatorFixture& operator=(OperatorFixture&& other) = default; static absl::StatusOr<OperatorFixture> Create(const QExprOperator& op) { ASSIGN_OR_RETURN(auto delegate, DelegateT::Create(op)); return OperatorFixture(std::move(delegate)); } absl::StatusOr<RES_T> Call(ARG_Ts&&... args) const { ASSIGN_OR_RETURN(auto tuple, delegate_.Call(std::forward<ARG_Ts&&>(args)...)); return std::get<0>(std::move(tuple)); } private: using DelegateT = OperatorFixture<TYPE_LIST<ARG_Ts...>, TYPE_LIST<RES_T>>; explicit OperatorFixture(DelegateT&& delegate) : delegate_(std::move(delegate)) {} DelegateT delegate_; }; } #endif
#include "arolla/qexpr/testing/operator_fixture.h" #include <cstdint> #include <tuple> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status_matchers.h" #include "arolla/codegen/qexpr/testing/test_operators.h" #include "arolla/memory/frame.h" #include "arolla/qexpr/operator_factory.h" #include "arolla/qexpr/operators.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/tuple_qtype.h" namespace arolla { namespace { using ::absl_testing::IsOkAndHolds; using ::arolla::testing::Vector3; using ::testing::Eq; template <typename T> using Slot = FrameLayout::Slot<T>; TEST(OperatorFixtureTest, TestSingleResultOperator) { auto float_type = GetQType<float>(); auto op = OperatorRegistry::GetInstance() ->LookupOperator("test.add", {float_type, float_type}, float_type) .value(); using ARG_Ts = std::tuple<float, float>; using RES_Ts = float; auto fixture = OperatorFixture<ARG_Ts, RES_Ts>::Create(*op).value(); float result = fixture.Call(10.0f, 20.0f).value(); EXPECT_THAT(result, Eq(30.0f)); } TEST(OperatorFixtureTest, TestMultipleResultOperator) { auto vector_type = GetQType<Vector3<float>>(); auto op = OperatorRegistry::GetInstance() ->LookupOperator("test.vector_components", {vector_type}, MakeTupleQType({GetQType<float>(), GetQType<float>(), GetQType<float>()})) .value(); using ARG_Ts = std::tuple<Vector3<float>>; using RES_Ts = std::tuple<float, float, float>; auto fixture = OperatorFixture<ARG_Ts, RES_Ts>::Create(*op).value(); float a, b, c; std::tie(a, b, c) = fixture.Call(Vector3<float>(10.0f, 20.0f, 30.0f)).value(); EXPECT_THAT(a, Eq(10.0f)); EXPECT_THAT(b, Eq(20.0f)); EXPECT_THAT(c, Eq(30.0f)); } TEST(OperatorFixtureTest, TestReturningTupleOperator) { ASSERT_OK_AND_ASSIGN(auto op, QExprOperatorFromFunction([]() { return std::tuple<int32_t, float>(57, 57.75f); })); using ARG_Ts = std::tuple<>; using RES_Ts = std::tuple<int32_t, float>; auto fixture = OperatorFixture<ARG_Ts, RES_Ts>::Create(*op).value(); EXPECT_THAT(fixture.Call(), IsOkAndHolds(Eq(std::tuple(57, 57.75f)))); } } }
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/qexpr/testing/operator_fixture.h
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/qexpr/testing/operator_fixture_test.cc
1ca990dbeca224035efdabffecc7f3738df6b52c
383cd2d6-6362-4b74-9646-61a16848ebcc
cpp
google/arolla
concat
arolla/jagged_shape/dense_array/util/concat.h
arolla/jagged_shape/util/concat_test.cc
#ifndef AROLLA_JAGGED_SHAPE_DENSE_ARRAY_UTIL_CONCAT_H_ #define AROLLA_JAGGED_SHAPE_DENSE_ARRAY_UTIL_CONCAT_H_ #include <cstdint> #include "absl/types/span.h" #include "arolla/dense_array/dense_array.h" #include "arolla/jagged_shape/util/concat.h" namespace arolla { namespace jagged_shape_internal { template <typename T> struct ConcatResultArrayBuilderHelper<DenseArray<T>> { DenseArrayBuilder<T> operator()( absl::Span<const DenseArray<T>> arrays) const { int64_t result_size = 0; for (const auto& array : arrays) { result_size += array.size(); } return DenseArrayBuilder<T>(result_size); } }; } } #endif
#include "arolla/jagged_shape/util/concat.h" #include <cmath> #include <cstdint> #include <utility> #include <vector> #include "benchmark/benchmark.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "absl/status/status_matchers.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "arolla/array/array.h" #include "arolla/array/edge.h" #include "arolla/dense_array/dense_array.h" #include "arolla/dense_array/edge.h" #include "arolla/jagged_shape/array/jagged_shape.h" #include "arolla/jagged_shape/array/util/concat.h" #include "arolla/jagged_shape/dense_array/jagged_shape.h" #include "arolla/jagged_shape/dense_array/util/concat.h" #include "arolla/jagged_shape/jagged_shape.h" #include "arolla/jagged_shape/testing/matchers.h" #include "arolla/memory/buffer.h" #include "arolla/memory/optional_value.h" using ::absl_testing::StatusIs; using ::arolla::testing::IsEquivalentTo; using ::testing::ElementsAre; namespace arolla { namespace { class JaggedArrayShapeHelper { public: using Shape = JaggedArrayShape; using Edge = Shape::Edge; static absl::string_view ReprName() { return "JaggedArrayShape"; } static absl::StatusOr<ArrayEdge> EdgeFromSplitPoints( absl::Span<const OptionalValue<int64_t>> split_points) { return ArrayEdge::FromSplitPoints(CreateArray<int64_t>(split_points)); } static absl::StatusOr<ArrayEdge> EdgeFromMapping( absl::Span<const OptionalValue<int64_t>> mapping, int64_t parent_size) { return ArrayEdge::FromMapping(CreateArray<int64_t>(mapping), parent_size); } static const Buffer<int64_t>& GetSplitPoints(const ArrayEdge& edge) { return edge.edge_values().dense_data().values; } template <typename T> static Array<T> MakeArray(absl::Span<const OptionalValue<T>> data) { return CreateArray<T>(data); } template <typename T> static Array<T> MakeArray(int64_t size, const T& value) { return Array<T>(CreateConstDenseArray<T>(size, value)); } }; class JaggedDenseArrayShapeHelper { public: using Shape = JaggedDenseArrayShape; using Edge = Shape::Edge; static absl::string_view ReprName() { return "JaggedShape"; } static absl::StatusOr<DenseArrayEdge> EdgeFromSplitPoints( absl::Span<const OptionalValue<int64_t>> split_points) { return DenseArrayEdge::FromSplitPoints( CreateDenseArray<int64_t>(split_points)); } static absl::StatusOr<DenseArrayEdge> EdgeFromMapping( absl::Span<const OptionalValue<int64_t>> mapping, int64_t parent_size) { return DenseArrayEdge::FromMapping(CreateDenseArray<int64_t>(mapping), parent_size); } static const Buffer<int64_t>& GetSplitPoints(const DenseArrayEdge& edge) { return edge.edge_values().values; } template <typename T> static DenseArray<T> MakeArray(absl::Span<const OptionalValue<T>> data) { return CreateDenseArray<T>(data); } template <typename T> static DenseArray<T> MakeArray(int64_t size, const T& value) { return CreateConstDenseArray<T>(size, value); } }; template <typename JaggedShapeHelper> class ConcatTest : public ::testing::Test { public: using Helper = JaggedShapeHelper; using Shape = typename JaggedShapeHelper::Shape; Shape MakeShape(absl::Span<const absl::Span<const int64_t>> shape) { std::vector<typename Helper::Edge> edges; edges.reserve(shape.size()); for (const auto& edge_sizes : shape) { std::vector<OptionalValue<int64_t>> split_points; split_points.reserve(edge_sizes.size() + 1); split_points.push_back(0); for (int64_t edge_size : edge_sizes) { split_points.push_back(split_points.back().value + edge_size); } auto edge = Helper::EdgeFromSplitPoints(split_points).value(); edges.push_back(std::move(edge)); } return Shape::FromEdges(std::move(edges)).value(); } template <typename T> auto MakeArray(absl::Span<const T> values) { std::vector<OptionalValue<T>> array_values; array_values.reserve(values.size()); for (const T& value : values) { array_values.push_back(OptionalValue<T>(value)); } return Helper::MakeArray(absl::MakeConstSpan(array_values)); } }; using ConcatTestTypes = ::testing::Types<JaggedArrayShapeHelper, JaggedDenseArrayShapeHelper>; TYPED_TEST_SUITE(ConcatTest, ConcatTestTypes); TYPED_TEST(ConcatTest, StackOrConcatJaggedShapesAlongDimension) { { ASSERT_OK_AND_ASSIGN( typename TestFixture::Shape result_shape, StackJaggedShapesAlongDimension<typename TestFixture::Shape>( { TestFixture::Shape::Empty(), }, 0)); EXPECT_THAT(result_shape, IsEquivalentTo(TestFixture::MakeShape({{1}}))); } { ASSERT_OK_AND_ASSIGN( typename TestFixture::Shape result_shape, StackJaggedShapesAlongDimension<typename TestFixture::Shape>( { TestFixture::Shape::Empty(), TestFixture::Shape::Empty(), TestFixture::Shape::Empty(), }, 0)); EXPECT_THAT(result_shape, IsEquivalentTo(TestFixture::MakeShape({{3}}))); } { ASSERT_OK_AND_ASSIGN( typename TestFixture::Shape result_shape, StackJaggedShapesAlongDimension<typename TestFixture::Shape>( { TestFixture::MakeShape({{2}, {1, 2}, {3, 4, 5}}), TestFixture::MakeShape({{3}, {1, 3, 1}, {6, 7, 8, 9, 10}}), }, 0)); EXPECT_THAT(result_shape, IsEquivalentTo(TestFixture::MakeShape({ {2}, {2, 3}, {1, 2, 1, 3, 1}, {3, 4, 5, 6, 7, 8, 9, 10}, }))); } { ASSERT_OK_AND_ASSIGN( typename TestFixture::Shape result_shape, ConcatJaggedShapesAlongDimension<typename TestFixture::Shape>( { TestFixture::MakeShape({{2}, {1, 2}, {3, 4, 5}}), TestFixture::MakeShape({{3}, {1, 3, 1}, {6, 7, 8, 9, 10}}), }, 0)); EXPECT_THAT(result_shape, IsEquivalentTo(TestFixture::MakeShape({ {5}, {1, 2, 1, 3, 1}, {3, 4, 5, 6, 7, 8, 9, 10}, }))); } { ASSERT_OK_AND_ASSIGN( typename TestFixture::Shape result_shape, StackJaggedShapesAlongDimension<typename TestFixture::Shape>( { TestFixture::MakeShape({{2}, {1, 2}, {3, 4, 5}}), TestFixture::MakeShape({{2}, {1, 3}, {6, 7, 8, 9}}), }, 1)); EXPECT_THAT(result_shape, IsEquivalentTo(TestFixture::MakeShape({ {2}, {2, 2}, {1, 1, 2, 3}, {3, 6, 4, 5, 7, 8, 9}, }))); } { ASSERT_OK_AND_ASSIGN( typename TestFixture::Shape result_shape, ConcatJaggedShapesAlongDimension<typename TestFixture::Shape>( { TestFixture::MakeShape({{2}, {1, 2}, {3, 4, 5}}), TestFixture::MakeShape({{2}, {1, 3}, {6, 7, 8, 9}}), }, 1)); EXPECT_THAT(result_shape, IsEquivalentTo(TestFixture::MakeShape({ {2}, {2, 5}, {3, 6, 4, 5, 7, 8, 9}, }))); } { ASSERT_OK_AND_ASSIGN( typename TestFixture::Shape result_shape, StackJaggedShapesAlongDimension<typename TestFixture::Shape>( { TestFixture::MakeShape({{2}, {1, 2}, {3, 4, 5}}), TestFixture::MakeShape({{2}, {1, 2}, {6, 7, 8}}), }, 2)); EXPECT_THAT(result_shape, IsEquivalentTo(TestFixture::MakeShape({ {2}, {1, 2}, {2, 2, 2}, {3, 6, 4, 7, 5, 8}, }))); } { ASSERT_OK_AND_ASSIGN( typename TestFixture::Shape result_shape, ConcatJaggedShapesAlongDimension<typename TestFixture::Shape>( { TestFixture::MakeShape({{2}, {1, 2}, {3, 4, 5}}), TestFixture::MakeShape({{2}, {1, 2}, {6, 7, 8}}), }, 2)); EXPECT_THAT(result_shape, IsEquivalentTo(TestFixture::MakeShape({ {2}, {1, 2}, {9, 11, 13}, }))); } { ASSERT_OK_AND_ASSIGN( typename TestFixture::Shape result_shape, ConcatJaggedShapesAlongDimension<typename TestFixture::Shape>( { TestFixture::MakeShape({{2}, {1, 2}, {1, 1, 2}, {1, 1, 1, 2}}), TestFixture::MakeShape({{2}, {3, 1}, {2, 3, 1, 4}, {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}}), }, 1)); EXPECT_THAT(result_shape, IsEquivalentTo(TestFixture::MakeShape( {{2}, {4, 3}, {1, 2, 3, 1, 1, 2, 4}, {1, 1, 2, 3, 4, 5, 6, 1, 1, 2, 7, 8, 9, 10}}))); } { EXPECT_THAT(StackJaggedShapesAlongDimension<typename TestFixture::Shape>( absl::Span<const typename TestFixture::Shape>{}, 0), StatusIs(absl::StatusCode::kInvalidArgument, "concat/stack requires a nonzero number of inputs")); } { EXPECT_THAT(ConcatJaggedShapesAlongDimension<typename TestFixture::Shape>( { TestFixture::Shape::Empty(), }, 0), StatusIs(absl::StatusCode::kInvalidArgument, "cannot concat shapes of rank zero")); } { EXPECT_THAT(StackJaggedShapesAlongDimension<typename TestFixture::Shape>( { TestFixture::MakeShape({{2}, {1, 2}, {3, 4, 5}}), }, -1), StatusIs(absl::StatusCode::kInvalidArgument, "invalid dim = -1 for concat/stack")); } { EXPECT_THAT(ConcatJaggedShapesAlongDimension<typename TestFixture::Shape>( { TestFixture::MakeShape({{2}, {1, 2}, {3, 4, 5}}), }, 3), StatusIs(absl::StatusCode::kInvalidArgument, "invalid dim = 3 for concat/stack")); } { EXPECT_THAT(StackJaggedShapesAlongDimension<typename TestFixture::Shape>( { TestFixture::MakeShape({{2}, {1, 2}, {3, 4, 5}}), }, 4), StatusIs(absl::StatusCode::kInvalidArgument, "invalid dim = 4 for concat/stack")); } { EXPECT_THAT(StackJaggedShapesAlongDimension<typename TestFixture::Shape>( { TestFixture::MakeShape({{2}, {1, 2}, {3, 4, 5}}), TestFixture::MakeShape({{2}, {1, 2}}), }, 0), StatusIs(absl::StatusCode::kInvalidArgument, "concat/stack requires all inputs to have the same " "rank, got 3 and 2")); } { EXPECT_THAT( StackJaggedShapesAlongDimension<typename TestFixture::Shape>( { TestFixture::MakeShape({{2}, {1, 2}, {3, 4, 5}}), TestFixture::MakeShape({{2}, {2, 1}, {3, 4, 5}}), }, 2), StatusIs( absl::StatusCode::kInvalidArgument, "concat/stack requires all inputs to have the same shape prefix " "before the concatenation dimension")); } } TYPED_TEST(ConcatTest, StackOrConcatJaggedArraysAlongDimension) { { const auto array1 = TestFixture::MakeArray(absl::Span<const int>({1, 2, 3})); const auto shape1 = TestFixture::MakeShape({{3}}); ASSERT_OK_AND_ASSIGN( (const auto& [result_array, result_shape]), StackJaggedArraysAlongDimension(absl::MakeConstSpan({array1}), absl::MakeConstSpan({shape1}), 0)); EXPECT_THAT(result_shape, IsEquivalentTo(TestFixture::MakeShape({{1}, {3}}))); EXPECT_THAT(result_array, ElementsAre(1, 2, 3)); } { const auto array1 = TestFixture::MakeArray(absl::Span<const int>({1, 2, 3})); const auto shape1 = TestFixture::MakeShape({{3}}); ASSERT_OK_AND_ASSIGN( (const auto& [result_array, result_shape]), ConcatJaggedArraysAlongDimension(absl::MakeConstSpan({array1}), absl::MakeConstSpan({shape1}), 0)); EXPECT_THAT(result_shape, IsEquivalentTo(TestFixture::MakeShape({{3}}))); EXPECT_THAT(result_array, ElementsAre(1, 2, 3)); } { const auto array1 = TestFixture::MakeArray(absl::Span<const int>({1, 2, 3})); const auto shape1 = TestFixture::MakeShape({{3}}); const auto array2 = TestFixture::MakeArray(absl::Span<const int>({4, 5})); const auto shape2 = TestFixture::MakeShape({{2}}); ASSERT_OK_AND_ASSIGN((const auto& [result_array, result_shape]), StackJaggedArraysAlongDimension( absl::MakeConstSpan({array1, array2}), absl::MakeConstSpan({shape1, shape2}), 0)); EXPECT_THAT(result_shape, IsEquivalentTo(TestFixture::MakeShape({{2}, {3, 2}}))); EXPECT_THAT(result_array, ElementsAre(1, 2, 3, 4, 5)); } { const auto array1 = TestFixture::MakeArray(absl::Span<const int>({1, 2, 3})); const auto shape1 = TestFixture::MakeShape({{{2}, {1, 2}}}); const auto array2 = TestFixture::MakeArray(absl::Span<const int>({4, 5, 6})); const auto shape2 = TestFixture::MakeShape({{{2}, {2, 1}}}); ASSERT_OK_AND_ASSIGN((const auto& [result_array, result_shape]), StackJaggedArraysAlongDimension( absl::MakeConstSpan({array1, array2}), absl::MakeConstSpan({shape1, shape2}), 0)); EXPECT_THAT( result_shape, IsEquivalentTo(TestFixture::MakeShape({{2}, {2, 2}, {1, 2, 2, 1}}))); EXPECT_THAT(result_array, ElementsAre(1, 2, 3, 4, 5, 6)); } { const auto array1 = TestFixture::MakeArray(absl::Span<const int>({1, 2, 3})); const auto shape1 = TestFixture::MakeShape({{{2}, {1, 2}}}); const auto array2 = TestFixture::MakeArray(absl::Span<const int>({4, 5, 6})); const auto shape2 = TestFixture::MakeShape({{{2}, {1, 2}}}); ASSERT_OK_AND_ASSIGN((const auto& [result_array, result_shape]), StackJaggedArraysAlongDimension( absl::MakeConstSpan({array1, array2}), absl::MakeConstSpan({shape1, shape2}), 1)); EXPECT_THAT( result_shape, IsEquivalentTo(TestFixture::MakeShape({{2}, {2, 2}, {1, 1, 2, 2}}))); EXPECT_THAT(result_array, ElementsAre(1, 4, 2, 3, 5, 6)); } { const auto array1 = TestFixture::MakeArray(absl::Span<const int>({1, 2, 3, 4})); const auto shape1 = TestFixture::MakeShape({{{2}, {2, 1}, {2, 1, 1}}}); const auto array2 = TestFixture::MakeArray(absl::Span<const int>({5, 6, 7, 8})); const auto shape2 = TestFixture::MakeShape({{{2}, {2, 1}, {2, 1, 1}}}); ASSERT_OK_AND_ASSIGN((const auto& [result_array, result_shape]), ConcatJaggedArraysAlongDimension( absl::MakeConstSpan({array1, array2}), absl::MakeConstSpan({shape1, shape2}), 0)); EXPECT_THAT(result_shape, IsEquivalentTo(TestFixture::MakeShape( {{4}, {2, 1, 2, 1}, {2, 1, 1, 2, 1, 1}}))); EXPECT_THAT(result_array, ElementsAre(1, 2, 3, 4, 5, 6, 7, 8)); } { const auto array1 = TestFixture::MakeArray(absl::Span<const int>({1, 2, 3, 4})); const auto shape1 = TestFixture::MakeShape({{{2}, {2, 1}, {2, 1, 1}}}); const auto array2 = TestFixture::MakeArray(absl::Span<const int>({5, 6, 7, 8})); const auto shape2 = TestFixture::MakeShape({{{2}, {2, 1}, {2, 1, 1}}}); ASSERT_OK_AND_ASSIGN((const auto& [result_array, result_shape]), ConcatJaggedArraysAlongDimension( absl::MakeConstSpan({array1, array2}), absl::MakeConstSpan({shape1, shape2}), 1)); EXPECT_THAT(result_shape, IsEquivalentTo(TestFixture::MakeShape( {{2}, {4, 2}, {2, 1, 2, 1, 1, 1}}))); EXPECT_THAT(result_array, ElementsAre(1, 2, 3, 5, 6, 7, 4, 8)); } { const auto array1 = TestFixture::MakeArray(absl::Span<const int>({1, 2, 3, 4})); const auto shape1 = TestFixture::MakeShape({{{2}, {2, 1}, {2, 1, 1}}}); const auto array2 = TestFixture::MakeArray(absl::Span<const int>({5, 6, 7, 8})); const auto shape2 = TestFixture::MakeShape({{{2}, {2, 1}, {2, 1, 1}}}); ASSERT_OK_AND_ASSIGN((const auto& [result_array, result_shape]), ConcatJaggedArraysAlongDimension( absl::MakeConstSpan({array1, array2}), absl::MakeConstSpan({shape1, shape2}), 2)); EXPECT_THAT( result_shape, IsEquivalentTo(TestFixture::MakeShape({{2}, {2, 1}, {4, 2, 2}}))); EXPECT_THAT(result_array, ElementsAre(1, 2, 5, 6, 3, 7, 4, 8)); } { const auto array1 = TestFixture::MakeArray(absl::Span<const int>({1, 2, 3})); const auto shape1 = TestFixture::MakeShape({{3}}); const auto array2 = TestFixture::MakeArray(absl::Span<const int>({4, 5})); const auto shape2 = TestFixture::MakeShape({{2}}); EXPECT_THAT(StackJaggedArraysAlongDimension( absl::MakeConstSpan({array1}), absl::MakeConstSpan({shape1, shape2}), 0), StatusIs(absl::StatusCode::kInvalidArgument, "concat/stack expects `arrays` and `array_shapes` to " "be 1:1, got sizes 1 and 2")); } { const auto array1 = TestFixture::MakeArray(absl::Span<const int>({1, 2, 3})); const auto shape1 = TestFixture::MakeShape({{3}}); const auto array2 = TestFixture::MakeArray(absl::Span<const int>({4, 5})); const auto shape2 = TestFixture::MakeShape({{2}}); EXPECT_THAT( StackJaggedArraysAlongDimension(absl::MakeConstSpan({array2, array2}), absl::MakeConstSpan({shape1, shape2}), 0), StatusIs(absl::StatusCode::kInvalidArgument, "concat/stack expects `arrays` and `array_shapes` to describe " "arrays with the same size, but got 2 != 3 for index 0")); } } template <typename ShapeHelper> typename ShapeHelper::Edge GetSplitPointsEdge(int64_t parent_size, int64_t children) { std::vector<OptionalValue<int64_t>> split_points; split_points.reserve(parent_size + 1); for (int64_t i = 0; i <= parent_size; ++i) { split_points.push_back(i * children); } return ShapeHelper::EdgeFromSplitPoints(std::move(split_points)).value(); } template <typename ShapeHelper> typename ShapeHelper::Shape GetShape(int64_t rank, int64_t num_children) { typename ShapeHelper::Shape::EdgeVec edges; edges.reserve(rank); for (int i = 0; i < rank; ++i) { edges.push_back(GetSplitPointsEdge<ShapeHelper>(std::pow(num_children, i), num_children)); } return ShapeHelper::Shape::FromEdges(std::move(edges)).value(); } template <typename ShapeHelper> void BM_ConcatJaggedShapesAlongDimension_StackFirst(benchmark::State& state) { const int rank = state.range(0); const int num_children = state.range(1); const int num_shapes = state.range(2); std::vector<typename ShapeHelper::Shape> shapes; shapes.reserve(num_shapes); for (int i = 0; i < num_shapes; ++i) { shapes.push_back(GetShape<ShapeHelper>(rank, num_children)); } for (auto _ : state) { benchmark::DoNotOptimize(shapes); auto result_shape_or = StackJaggedShapesAlongDimension(absl::MakeConstSpan(shapes), 0); benchmark::DoNotOptimize(result_shape_or); } } BENCHMARK( BM_ConcatJaggedShapesAlongDimension_StackFirst<JaggedArrayShapeHelper>) ->Args({1, 1, 2}) ->Args({4, 100, 2}) ->Args({4, 100, 10}); BENCHMARK( BM_ConcatJaggedShapesAlongDimension_StackFirst<JaggedDenseArrayShapeHelper>) ->Args({1, 1, 2}) ->Args({4, 100, 2}) ->Args({4, 100, 10}); template <typename ShapeHelper> void BM_StackJaggedShapesAlongDimension_StackLast(benchmark::State& state) { const int rank = state.range(0); const int num_children = state.range(1); const int num_shapes = state.range(2); std::vector<typename ShapeHelper::Shape> shapes; shapes.reserve(num_shapes); for (int i = 0; i < num_shapes; ++i) { shapes.push_back(GetShape<ShapeHelper>(rank, num_children)); } for (auto _ : state) { benchmark::DoNotOptimize(shapes); auto result_shape_or = StackJaggedShapesAlongDimension(absl::MakeConstSpan(shapes), rank); benchmark::DoNotOptimize(result_shape_or); } } BENCHMARK(BM_StackJaggedShapesAlongDimension_StackLast<JaggedArrayShapeHelper>) ->Args({1, 1, 2}) ->Args({4, 100, 2}) ->Args({4, 100, 10}); BENCHMARK( BM_StackJaggedShapesAlongDimension_StackLast<JaggedDenseArrayShapeHelper>) ->Args({1, 1, 2}) ->Args({4, 100, 2}) ->Args({4, 100, 10}); template <typename ShapeHelper> void BM_ConcatJaggedShapesAlongDimension_ConcatFirst(benchmark::State& state) { const int rank = state.range(0); const int num_children = state.range(1); const int num_shapes = state.range(2); std::vector<typename ShapeHelper::Shape> shapes; shapes.reserve(num_shapes); for (int i = 0; i < num_shapes; ++i) { shapes.push_back(GetShape<ShapeHelper>(rank, num_children)); } for (auto _ : state) { benchmark::DoNotOptimize(shapes); auto result_shape_or = ConcatJaggedShapesAlongDimension(absl::MakeConstSpan(shapes), 0); benchmark::DoNotOptimize(result_shape_or); } } BENCHMARK( BM_ConcatJaggedShapesAlongDimension_ConcatFirst<JaggedArrayShapeHelper>) ->Args({1, 1, 2}) ->Args({4, 100, 2}) ->Args({4, 100, 10}); BENCHMARK(BM_ConcatJaggedShapesAlongDimension_ConcatFirst< JaggedDenseArrayShapeHelper>) ->Args({1, 1, 2}) ->Args({4, 100, 2}) ->Args({4, 100, 10}); template <typename ShapeHelper> void BM_ConcatJaggedShapesAlongDimension_ConcatLast(benchmark::State& state) { const int rank = state.range(0); const int num_children = state.range(1); const int num_shapes = state.range(2); std::vector<typename ShapeHelper::Shape> shapes; shapes.reserve(num_shapes); for (int i = 0; i < num_shapes; ++i) { shapes.push_back(GetShape<ShapeHelper>(rank, num_children)); } for (auto _ : state) { benchmark::DoNotOptimize(shapes); auto result_shape_or = ConcatJaggedShapesAlongDimension(absl::MakeConstSpan(shapes), rank - 1); benchmark::DoNotOptimize(result_shape_or); } } BENCHMARK( BM_ConcatJaggedShapesAlongDimension_ConcatLast<JaggedArrayShapeHelper>) ->Args({1, 1, 2}) ->Args({4, 100, 2}) ->Args({4, 100, 10}); BENCHMARK( BM_ConcatJaggedShapesAlongDimension_ConcatLast<JaggedDenseArrayShapeHelper>) ->Args({1, 1, 2}) ->Args({4, 100, 2}) ->Args({4, 100, 10}); template <typename ShapeHelper> void BM_StackJaggedArraysAlongDimension_StackFirst(benchmark::State& state) { const int rank = state.range(0); const int num_children = state.range(1); const auto shape1 = GetShape<ShapeHelper>(rank, num_children); const auto shape2 = GetShape<ShapeHelper>(rank, num_children); const auto array1 = ShapeHelper::MakeArray(std::pow(num_children, rank), 1); const auto array2 = ShapeHelper::MakeArray(std::pow(num_children, rank), 2); for (auto _ : state) { auto result_shape_or = StackJaggedArraysAlongDimension( absl::MakeConstSpan({array1, array2}), absl::MakeConstSpan({shape1, shape2}), 0); benchmark::DoNotOptimize(result_shape_or); } } BENCHMARK( BM_StackJaggedArraysAlongDimension_StackFirst<JaggedArrayShapeHelper>) ->Args({1, 1}) ->Args({2, 1000}); BENCHMARK( BM_StackJaggedArraysAlongDimension_StackFirst<JaggedDenseArrayShapeHelper>) ->Args({1, 1}) ->Args({2, 1000}); template <typename ShapeHelper> void BM_StackJaggedArraysAlongDimension_StackLast(benchmark::State& state) { const int rank = state.range(0); const int num_children = state.range(1); const auto shape1 = GetShape<ShapeHelper>(rank, num_children); const auto shape2 = GetShape<ShapeHelper>(rank, num_children); const auto array1 = ShapeHelper::MakeArray(std::pow(num_children, rank), 1); const auto array2 = ShapeHelper::MakeArray(std::pow(num_children, rank), 2); for (auto _ : state) { auto result_shape_or = StackJaggedArraysAlongDimension( absl::MakeConstSpan({array1, array2}), absl::MakeConstSpan({shape1, shape2}), rank); benchmark::DoNotOptimize(result_shape_or); } } BENCHMARK(BM_StackJaggedArraysAlongDimension_StackLast<JaggedArrayShapeHelper>) ->Args({1, 1}) ->Args({2, 1000}); BENCHMARK( BM_StackJaggedArraysAlongDimension_StackLast<JaggedDenseArrayShapeHelper>) ->Args({1, 1}) ->Args({2, 1000}); } }
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/jagged_shape/dense_array/util/concat.h
https://github.com/google/arolla/blob/1ca990dbeca224035efdabffecc7f3738df6b52c/arolla/jagged_shape/util/concat_test.cc
1ca990dbeca224035efdabffecc7f3738df6b52c
fe34d6ce-f548-4ce9-b75b-ba93249e22dd
cpp
tensorflow/tensorflow
autotune_result_wrapper
third_party/xla/xla/autotune_result_wrapper.cc
third_party/xla/xla/autotune_result_wrapper_test.cc
#include "xla/autotune_result_wrapper.h" #include <vector> #include "absl/log/check.h" #include "absl/status/status.h" #include "xla/autotune_results.pb.h" #include "xla/autotuning.pb.h" #include "xla/tsl/lib/strings/proto_serialization.h" namespace xla { absl::StatusOr<AutotuneResultWrapper> AutotuneResultWrapper::FromKeyAndValue(OpaqueKey key, OpaqueValue value) { AutotuneResults key_proto; if (!key_proto.ParseFromString(key)) { return absl::Status(absl::StatusCode::kInvalidArgument, "Could not parse the provided key"); } AutotuneResults::Entry value_entry; if (!value_entry.ParseFromString(value)) { return absl::Status(absl::StatusCode::kInvalidArgument, "Could not parse the provided value"); } AutotuneResults::Entry full_entry; full_entry.set_device(key_proto.results(0).device()); full_entry.set_hlo(key_proto.results(0).hlo()); *full_entry.mutable_result() = value_entry.result(); return AutotuneResultWrapper(full_entry, key_proto.version()); } AutotuneResultWrapper::OpaqueKey AutotuneResultWrapper::Key() const { AutotuneResults key_proto; key_proto.set_version(version_); auto entry = key_proto.add_results(); entry->set_device(autotune_result_.device()); entry->set_hlo(autotune_result_.hlo()); OpaqueKey serialized; CHECK(tsl::SerializeToStringDeterministic(key_proto, &serialized)); return serialized; } AutotuneResultWrapper::OpaqueValue AutotuneResultWrapper::Value() const { AutotuneResults::Entry entry; *entry.mutable_result() = autotune_result_.result(); OpaqueValue serialized; CHECK(tsl::SerializeToStringDeterministic(entry, &serialized)); return serialized; } std::vector<AutotuneResultWrapper> AutotuneResultWrapper::AutotuneResultsToWrappers( const AutotuneResults& autotune_results) { std::vector<AutotuneResultWrapper> wrappers; wrappers.reserve(autotune_results.results_size()); for (const auto& result : autotune_results.results()) { wrappers.push_back( AutotuneResultWrapper(result, autotune_results.version())); } return wrappers; } absl::StatusOr<AutotuneResults> AutotuneResultWrapper::AutotuneResultsFromWrappers( const std::vector<AutotuneResultWrapper>& wrappers) { AutotuneResults autotune_results; for (const auto& wrapper : wrappers) { if (autotune_results.results_size() > 0 && autotune_results.version() != wrapper.version_) { return absl::Status(absl::StatusCode::kInvalidArgument, "All wrappers must have the same version number"); } *autotune_results.add_results() = wrapper.autotune_result_; autotune_results.set_version(wrapper.version_); } return autotune_results; } }
#include "xla/autotune_result_wrapper.h" #include <cstdint> #include <utility> #include <vector> #include "xla/autotune_results.pb.h" #include "xla/autotuning.pb.h" #include "xla/test.h" #include "xla/test_helpers.h" #include "tsl/platform/statusor.h" namespace xla { namespace { AutotuneResults ThreeAutotuneEntries(int32_t version) { AutotuneResults results; results.set_version(version); auto r1 = results.add_results(); r1->set_device("dev1"); r1->set_hlo("hlo1"); r1->mutable_result()->set_scratch_bytes(1); auto r2 = results.add_results(); r2->set_device("dev2"); r2->set_hlo("hlo2"); r2->mutable_result()->set_scratch_bytes(2); auto r3 = results.add_results(); r3->set_device("dev3"); r3->set_hlo("hlo3"); r3->mutable_result()->set_scratch_bytes(3); return results; } TEST(AutotuneResultWrapperTest, FullRoundTrip) { std::vector<AutotuneResultWrapper> wrappers = AutotuneResultWrapper::AutotuneResultsToWrappers( ThreeAutotuneEntries(42)); std::vector<std::pair<AutotuneResultWrapper::OpaqueKey, AutotuneResultWrapper::OpaqueValue>> key_value_pairs; for (const auto& wrapper : wrappers) { key_value_pairs.push_back(std::make_pair(wrapper.Key(), wrapper.Value())); } std::vector<AutotuneResultWrapper> new_wrappers; for (const auto& [key, value] : key_value_pairs) { TF_ASSERT_OK_AND_ASSIGN(AutotuneResultWrapper wrapper, AutotuneResultWrapper::FromKeyAndValue(key, value)); new_wrappers.push_back(std::move(wrapper)); } TF_ASSERT_OK_AND_ASSIGN( AutotuneResults round_tripped, AutotuneResultWrapper::AutotuneResultsFromWrappers(new_wrappers)); EXPECT_EQ(round_tripped.results_size(), 3); EXPECT_EQ(round_tripped.version(), 42); EXPECT_EQ(round_tripped.results(0).device(), "dev1"); EXPECT_EQ(round_tripped.results(0).hlo(), "hlo1"); EXPECT_EQ(round_tripped.results(0).result().scratch_bytes(), 1); EXPECT_EQ(round_tripped.results(1).device(), "dev2"); EXPECT_EQ(round_tripped.results(1).hlo(), "hlo2"); EXPECT_EQ(round_tripped.results(1).result().scratch_bytes(), 2); EXPECT_EQ(round_tripped.results(2).device(), "dev3"); EXPECT_EQ(round_tripped.results(2).hlo(), "hlo3"); EXPECT_EQ(round_tripped.results(2).result().scratch_bytes(), 3); } TEST(AutotuneResultWrapperTest, InconsistentVersions) { std::vector<AutotuneResultWrapper> wrappers = AutotuneResultWrapper::AutotuneResultsToWrappers( ThreeAutotuneEntries(42)); auto inconsistent_wrappers = AutotuneResultWrapper::AutotuneResultsToWrappers( ThreeAutotuneEntries(43)); wrappers.insert(wrappers.end(), inconsistent_wrappers.begin(), inconsistent_wrappers.end()); std::vector<std::pair<AutotuneResultWrapper::OpaqueKey, AutotuneResultWrapper::OpaqueValue>> key_value_pairs; for (const auto& wrapper : wrappers) { key_value_pairs.push_back(std::make_pair(wrapper.Key(), wrapper.Value())); } std::vector<AutotuneResultWrapper> decoded_wrappers; for (const auto& [key, value] : key_value_pairs) { TF_ASSERT_OK_AND_ASSIGN(AutotuneResultWrapper wrapper, AutotuneResultWrapper::FromKeyAndValue(key, value)); decoded_wrappers.push_back(std::move(wrapper)); } EXPECT_IS_NOT_OK( AutotuneResultWrapper::AutotuneResultsFromWrappers(decoded_wrappers)); } } }
https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/third_party/xla/xla/autotune_result_wrapper.cc
https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/third_party/xla/xla/autotune_result_wrapper_test.cc
4a29233a7b7c1a3a4294e4ccdd1772f9083944ea
87bfd4b9-ec7b-4c54-b090-bb8a279883ad
cpp
tensorflow/tensorflow
sort_json
third_party/xla/xla/sort_json.cc
third_party/xla/xla/sort_json_test.cc
#include "xla/sort_json.h" #include <algorithm> #include <cctype> #include <cstddef> #include <memory> #include <string> #include <utility> #include <variant> #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 "tsl/platform/errors.h" #include "tsl/platform/statusor.h" namespace { void SkipWhitespace(absl::string_view json, size_t& index) { while (index < json.size() && std::isspace(json[index])) { ++index; } } absl::Status CheckNotEndOfString(absl::string_view json, int index, absl::string_view expected) { return index < json.size() ? absl::OkStatus() : absl::InvalidArgumentError(absl::StrCat( "Prematurely reached end of JSON while looking for ", expected, ".")); } absl::Status Consume(absl::string_view json, size_t& index, char c, bool optional = false) { SkipWhitespace(json, index); TF_RETURN_IF_ERROR(CheckNotEndOfString(json, index, std::string(1, c))); if (json[index] == c) { ++index; SkipWhitespace(json, index); } else if (!optional) { return absl::InvalidArgumentError( absl::StrCat("Expected '", std::string(1, c), "', but found '", std::string(1, json[index]), "'.")); } return absl::OkStatus(); } struct JsonArray; struct JsonObject; using JsonValue = std::variant<absl::string_view, std::unique_ptr<JsonObject>, std::unique_ptr<JsonArray>>; struct JsonField { absl::string_view name; JsonValue value; }; template <typename T> struct JsonSequence { std::vector<T> elements; }; struct JsonArray : public JsonSequence<JsonValue> {}; struct JsonObject : public JsonSequence<JsonField> {}; template <typename T, char begin, char end, const char* name, typename ElemFn> absl::StatusOr<std::unique_ptr<T>> ParseSequence(absl::string_view outer_json, size_t& index, ElemFn elem_fn) { TF_RETURN_IF_ERROR(Consume(outer_json, index, begin)); TF_RETURN_IF_ERROR(CheckNotEndOfString(outer_json, index, name)); auto seq = std::make_unique<T>(); while (outer_json[index] != end) { TF_ASSIGN_OR_RETURN(auto elem, elem_fn(outer_json, index)); seq->elements.emplace_back(std::move(elem)); TF_RETURN_IF_ERROR(Consume(outer_json, index, ',', true)); TF_RETURN_IF_ERROR(CheckNotEndOfString(outer_json, index, name)); } TF_RETURN_IF_ERROR(Consume(outer_json, index, end)); return seq; } absl::Status EnsureValidLiteralStart(char c) { if (c != '"' && c != '+' && c != '-' && c != 'f' && c != 't' && c != 'n' && (c < '0' || c > '9')) { return absl::InvalidArgumentError(absl::StrCat( "Invalid first character of literal: '", std::string(1, c), "'.")); } return absl::OkStatus(); } bool HandleEscape(absl::string_view outer_json, size_t& index, bool& is_escaped) { if (is_escaped) { is_escaped = false; ++index; return true; } if (outer_json[index] == '\\') { is_escaped = true; ++index; return true; } return false; } bool LiteralIsFinished(absl::string_view outer_json, size_t& index, bool is_string_literal) { char c = outer_json[index]; if (is_string_literal) { index += (c == '"' ? 1 : 0); return c == '"'; } return std::isspace(c) || c == ',' || c == '{' || c == '}' || c == '[' || c == ']' || c == ':'; } absl::StatusOr<absl::string_view> ParseLiteral(absl::string_view outer_json, size_t& index) { SkipWhitespace(outer_json, index); TF_RETURN_IF_ERROR(CheckNotEndOfString(outer_json, index, "literal")); auto c = outer_json[index]; TF_RETURN_IF_ERROR(EnsureValidLiteralStart(c)); bool is_string_literal = c == '"'; size_t start_index = index; bool is_escaped = false; ++index; while (index < outer_json.size()) { if (HandleEscape(outer_json, index, is_escaped)) { continue; } if (LiteralIsFinished(outer_json, index, is_string_literal)) { break; } ++index; } return outer_json.substr(start_index, index - start_index); } absl::StatusOr<JsonField> ParseField(absl::string_view outer_json, size_t& index); absl::StatusOr<JsonValue> ParseValue(absl::string_view outer_json, size_t& index) { JsonValue value; SkipWhitespace(outer_json, index); TF_RETURN_IF_ERROR(CheckNotEndOfString(outer_json, index, "value")); auto c = outer_json[index]; if (c == '{') { constexpr static char kObject[] = "object"; auto seq = ParseSequence<JsonObject, '{', '}', kObject>(outer_json, index, ParseField); TF_ASSIGN_OR_RETURN(value, std::move(seq)); } else if (c == '[') { constexpr static char kArray[] = "array"; auto seq = ParseSequence<JsonArray, '[', ']', kArray>(outer_json, index, ParseValue); TF_ASSIGN_OR_RETURN(value, std::move(seq)); } else { TF_ASSIGN_OR_RETURN(value, ParseLiteral(outer_json, index)); } return value; } absl::StatusOr<JsonField> ParseField(absl::string_view outer_json, size_t& index) { JsonField field; TF_ASSIGN_OR_RETURN(field.name, ParseLiteral(outer_json, index)); TF_RETURN_IF_ERROR(Consume(outer_json, index, ':')); TF_ASSIGN_OR_RETURN(field.value, ParseValue(outer_json, index)); return field; } template <typename T> std::vector<std::string> SerializedElements(const JsonSequence<T>& seq) { std::vector<std::string> result; for (const auto& field : seq.elements) { result.push_back(""); Serialize(field, result.back()); } return result; } template <typename ElemT, char begin_brace, char end_brace> void Serialize(const JsonSequence<ElemT>& object, std::string& result) { auto elems = SerializedElements(object); if constexpr (std::is_same_v<ElemT, JsonField>) { std::sort(elems.begin(), elems.end()); } result += begin_brace; bool has_preceeding = false; for (const auto& elem : elems) { if (has_preceeding) { result += ','; } result += elem; has_preceeding = true; } result += end_brace; } void Serialize(const JsonValue& value, std::string& result) { if (auto* lit = std::get_if<absl::string_view>(&value)) { absl::StrAppend(&result, *lit); } else if (auto* object = std::get_if<std::unique_ptr<JsonObject>>(&value)) { Serialize<JsonField, '{', '}'>(**object, result); } else if (auto* array = std::get_if<std::unique_ptr<JsonArray>>(&value)) { Serialize<JsonValue, '[', ']'>(**array, result); } } void Serialize(const JsonField& field, std::string& result) { absl::StrAppend(&result, field.name, ":"); Serialize(field.value, result); } } namespace xla { absl::StatusOr<std::string> SortJson(absl::string_view json) { size_t index = 0; TF_ASSIGN_OR_RETURN(auto value, ParseValue(json, index)); SkipWhitespace(json, index); if (index < json.size()) { return absl::InvalidArgumentError("Found trailing characters in JSON."); } std::string result; Serialize(value, result); return result; } }
#include "xla/sort_json.h" #include <gmock/gmock.h> #include <gtest/gtest.h> #include "tsl/platform/status_matchers.h" #include "tsl/platform/test.h" namespace xla { namespace { using ::tsl::testing::IsOkAndHolds; TEST(SortJsonTest, SortsJson) { EXPECT_THAT(SortJson(R"({"a": 1, "c": 3,"b": 2, "b": 1,})"), IsOkAndHolds(R"({"a":1,"b":1,"b":2,"c":3})")); EXPECT_THAT(SortJson(R"({"a": 1 , "c": 1,"b": 1 })"), IsOkAndHolds(R"({"a":1,"b":1,"c":1})")); EXPECT_THAT(SortJson(R"({"a": 1,"c": 3,"b": 2,"b": [3,2,1],})"), IsOkAndHolds(R"({"a":1,"b":2,"b":[3,2,1],"c":3})")); EXPECT_THAT(SortJson(R"({"aa": 1, "a": {"c": "c", "b": "b"}})"), IsOkAndHolds(R"({"a":{"b":"b","c":"c"},"aa":1})")); EXPECT_THAT( SortJson( R"({"x": true, "x": false, "x": null, "x": 0, "x": -0.5,"x": "a"})"), IsOkAndHolds(R"({"x":"a","x":-0.5,"x":0,"x":false,"x":null,"x":true})")); EXPECT_THAT(SortJson(R"({"a": "a}", "a": "a"})"), IsOkAndHolds(R"({"a":"a","a":"a}"})")); } } }
https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/third_party/xla/xla/sort_json.cc
https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/third_party/xla/xla/sort_json_test.cc
4a29233a7b7c1a3a4294e4ccdd1772f9083944ea
e12fd44f-7d53-4a07-8e2c-1dc0ce7c5d61
cpp
tensorflow/tensorflow
status_macros
third_party/xla/xla/status_macros.cc
third_party/xla/xla/status_macros_test.cc
#include "xla/status_macros.h" #include <algorithm> #include <string> #include "absl/base/attributes.h" #include "absl/base/log_severity.h" #include "absl/base/optimization.h" #include "absl/status/status.h" #include "absl/strings/str_cat.h" #include "tsl/platform/logging.h" #include "tsl/platform/stacktrace.h" #include "tsl/platform/status.h" namespace xla { namespace status_macros { ABSL_CONST_INIT const char kPossibleAutoJitAlternative[] = "This error might be occurring with the use of xla.compile. If it is not " "necessary that every Op be compiled with XLA, an alternative is to use " "auto_jit with OptimizerOptions.global_jit_level = ON_2 or the environment " "variable TF_XLA_FLAGS=\"tf_xla_auto_jit=2\" which will attempt to use xla " "to compile as much of the graph as the compiler is able to."; static void LogError(const absl::Status& status, const char* filename, int line, absl::LogSeverity log_severity, bool should_log_stack_trace) { std::string stack_trace; if (should_log_stack_trace) { stack_trace = absl::StrCat("\n", tsl::CurrentStackTrace()); } switch (log_severity) { case absl::LogSeverity::kInfo: LOG(INFO) << status << stack_trace; break; case absl::LogSeverity::kWarning: LOG(WARNING) << status << stack_trace; break; case absl::LogSeverity::kError: LOG(ERROR) << status << stack_trace; break; case absl::LogSeverity::kFatal: LOG(FATAL) << status << stack_trace; break; default: LOG(FATAL) << "Unknown LOG severity " << log_severity; } } static absl::Status MakeError(const char* filename, int line, absl::StatusCode code, const std::string& message, bool should_log, absl::LogSeverity log_severity, bool should_log_stack_trace) { if (ABSL_PREDICT_FALSE(code == absl::StatusCode::kOk)) { LOG(ERROR) << "Cannot create error with status OK"; code = absl::StatusCode::kUnknown; } const absl::Status status = absl::Status(code, message); if (ABSL_PREDICT_TRUE(should_log)) { LogError(status, filename, line, log_severity, should_log_stack_trace); } return status; } MakeErrorStream::MakeErrorStreamWithOutput& MakeErrorStream::add_ret_check_failure(const char* condition) { return *this << "RET_CHECK failure (" << impl_->file_ << ":" << impl_->line_ << ") " << condition << " "; } void MakeErrorStream::CheckNotDone() const { impl_->CheckNotDone(); } MakeErrorStream::Impl::Impl(const char* file, int line, tsl::error::Code code, MakeErrorStream* error_stream, bool is_logged_by_default) : file_(file), line_(line), code_(static_cast<absl::StatusCode>(code)), is_done_(false), should_log_(is_logged_by_default), log_severity_(absl::LogSeverity::kError), should_log_stack_trace_(false), make_error_stream_with_output_wrapper_(error_stream) {} MakeErrorStream::Impl::Impl(const absl::Status& status, PriorMessageHandling prior_message_handling, const char* file, int line, MakeErrorStream* error_stream) : file_(file), line_(line), code_(!status.ok() ? static_cast<absl::StatusCode>(status.code()) : absl::StatusCode::kUnknown), prior_message_handling_(prior_message_handling), prior_message_(status.message()), is_done_(false), should_log_(true), log_severity_(absl::LogSeverity::kError), should_log_stack_trace_(false), make_error_stream_with_output_wrapper_(error_stream) { DCHECK(!status.ok()) << "Attempted to append/prepend error text to status OK"; } MakeErrorStream::Impl::~Impl() { if (!is_done_) { LOG(ERROR) << "MakeErrorStream destructed without getting absl::Status: " << file_ << ":" << line_ << " " << stream_.str(); } } absl::Status MakeErrorStream::Impl::GetStatus() { if (is_done_) { LOG(ERROR) << "MakeErrorStream got absl::Status more than once: " << file_ << ":" << line_ << " " << stream_.str(); } is_done_ = true; const std::string& stream_str = stream_.str(); const std::string str = prior_message_handling_ == kAppendToPriorMessage ? absl::StrCat(prior_message_, stream_str) : absl::StrCat(stream_str, prior_message_); if (ABSL_PREDICT_FALSE(str.empty())) { return MakeError( file_, line_, code_, absl::StrCat(str, "Error without message at ", file_, ":", line_), true, absl::LogSeverity::kError, should_log_stack_trace_); } else { return MakeError(file_, line_, code_, str, should_log_, log_severity_, should_log_stack_trace_); } } void MakeErrorStream::Impl::CheckNotDone() const { if (is_done_) { LOG(ERROR) << "MakeErrorStream shift called after getting absl::Status: " << file_ << ":" << line_ << " " << stream_.str(); } } } }
#include "xla/status_macros.h" #include <functional> #include <utility> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "xla/test.h" #include "xla/test_helpers.h" #include "tsl/platform/errors.h" #include "tsl/platform/statusor.h" namespace xla { absl::Status RetCheckFail() { TF_RET_CHECK(2 > 3); return absl::OkStatus(); } absl::Status RetCheckFailWithExtraMessage() { TF_RET_CHECK(2 > 3) << "extra message"; return absl::OkStatus(); } absl::Status RetCheckSuccess() { TF_RET_CHECK(3 > 2); return absl::OkStatus(); } TEST(StatusMacros, RetCheckFailing) { absl::Status status = RetCheckFail(); EXPECT_EQ(status.code(), tsl::error::INTERNAL); EXPECT_THAT(status.message(), ::testing::ContainsRegex("RET_CHECK failure.*2 > 3")); } TEST(StatusMacros, RetCheckFailingWithExtraMessage) { absl::Status status = RetCheckFailWithExtraMessage(); EXPECT_EQ(status.code(), tsl::error::INTERNAL); EXPECT_THAT(status.message(), ::testing::ContainsRegex("RET_CHECK.*2 > 3 extra message")); } TEST(StatusMacros, RetCheckSucceeding) { absl::Status status = RetCheckSuccess(); EXPECT_IS_OK(status); } absl::StatusOr<int> CreateIntSuccessfully() { return 42; } absl::StatusOr<int> CreateIntUnsuccessfully() { return tsl::errors::Internal("foobar"); } TEST(StatusMacros, AssignOrAssertOnOK) { TF_ASSERT_OK_AND_ASSIGN(int result, CreateIntSuccessfully()); EXPECT_EQ(42, result); } absl::Status ReturnStatusOK() { return absl::OkStatus(); } absl::Status ReturnStatusError() { return (tsl::errors::Internal("foobar")); } using StatusReturningFunction = std::function<absl::Status()>; absl::StatusOr<int> CallStatusReturningFunction( const StatusReturningFunction& func) { TF_RETURN_IF_ERROR(func()); return 42; } TEST(StatusMacros, ReturnIfErrorOnOK) { absl::StatusOr<int> rc = CallStatusReturningFunction(ReturnStatusOK); EXPECT_IS_OK(rc); EXPECT_EQ(42, std::move(rc).value()); } TEST(StatusMacros, ReturnIfErrorOnError) { absl::StatusOr<int> rc = CallStatusReturningFunction(ReturnStatusError); EXPECT_FALSE(rc.ok()); EXPECT_EQ(rc.status().code(), tsl::error::INTERNAL); } TEST(StatusMacros, AssignOrReturnSuccessfully) { absl::Status status = []() { TF_ASSIGN_OR_RETURN(int value, CreateIntSuccessfully()); EXPECT_EQ(value, 42); return absl::OkStatus(); }(); EXPECT_IS_OK(status); } TEST(StatusMacros, AssignOrReturnUnsuccessfully) { absl::Status status = []() { TF_ASSIGN_OR_RETURN(int value, CreateIntUnsuccessfully()); (void)value; return absl::OkStatus(); }(); EXPECT_FALSE(status.ok()); EXPECT_EQ(status.code(), tsl::error::INTERNAL); } }
https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/third_party/xla/xla/status_macros.cc
https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/third_party/xla/xla/status_macros_test.cc
4a29233a7b7c1a3a4294e4ccdd1772f9083944ea
80bcb2c4-7146-42ea-ae36-aa47df8769b3
cpp
tensorflow/tensorflow
array
tensorflow/lite/array.cc
tensorflow/lite/array_test.cc
#include "tensorflow/lite/array.h" namespace tflite { namespace array_internal { void TfLiteArrayDeleter::operator()(TfLiteIntArray* a) { if (a) { TfLiteIntArrayFree(a); } } void TfLiteArrayDeleter::operator()(TfLiteFloatArray* a) { if (a) { TfLiteFloatArrayFree(a); } } } }
#include "tensorflow/lite/array.h" #include <algorithm> #include <initializer_list> #include <type_traits> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "absl/types/span.h" #include "tensorflow/lite/core/c/common.h" using testing::ElementsAreArray; using testing::Eq; namespace tflite { namespace { absl::Span<int> GetSpan(TfLiteIntArray& array) { return {array.data, static_cast<size_t>(array.size)}; } absl::Span<float> GetSpan(TfLiteFloatArray& array) { return {array.data, static_cast<size_t>(array.size)}; } template <class T> class TfLiteArrayTest : public testing::Test { static_assert( std::is_same_v<TfLiteIntArray, TfLiteArrayUniquePtr<int>::element_type>, "TfLiteArrayUniquePtr<int>::element_type should be TfLiteIntArray"); static_assert( std::is_same_v<TfLiteFloatArray, TfLiteArrayUniquePtr<float>::element_type>, "TfLiteArrayUniquePtr<float>::element_type should be TfLiteFloatArray"); }; using ArrayTypes = testing::Types<int, float>; TYPED_TEST_SUITE(TfLiteArrayTest, ArrayTypes); TYPED_TEST(TfLiteArrayTest, BuildArrayWithSize) { constexpr int size = 3; TfLiteArrayUniquePtr<TypeParam> array = BuildTfLiteArray<TypeParam>(size); ASSERT_NE(array, nullptr); EXPECT_THAT(array->size, Eq(size)); std::fill_n(array->data, size, static_cast<TypeParam>(1)); } TYPED_TEST(TfLiteArrayTest, BuildFromDynamicArray) { constexpr int size = 4; constexpr TypeParam values[size] = {1, 2, 3, 4}; TfLiteArrayUniquePtr<TypeParam> array = BuildTfLiteArray(size, values); ASSERT_NE(array, nullptr); EXPECT_THAT(array->size, Eq(size)); EXPECT_THAT(GetSpan(*array), ElementsAreArray(values)); } TYPED_TEST(TfLiteArrayTest, BuildFromCArray) { TypeParam values[] = {1, 2, 3, 4}; TfLiteArrayUniquePtr<TypeParam> array = BuildTfLiteArray(values); ASSERT_NE(array, nullptr); EXPECT_THAT(array->size, Eq(sizeof(values) / sizeof(TypeParam))); EXPECT_THAT(GetSpan(*array), ElementsAreArray(values)); } TYPED_TEST(TfLiteArrayTest, BuildFromVector) { std::vector<TypeParam> values = {1, 2, 3, 4}; TfLiteArrayUniquePtr<TypeParam> array = BuildTfLiteArray(values); ASSERT_NE(array, nullptr); EXPECT_THAT(array->size, Eq(values.size())); EXPECT_THAT(GetSpan(*array), ElementsAreArray(values)); } TYPED_TEST(TfLiteArrayTest, BuildFromVectorForceType) { using DifferentType = std::conditional_t<std::is_same_v<TypeParam, int>, float, int>; std::vector<DifferentType> values = {1, 2, 3, 4}; TfLiteArrayUniquePtr<TypeParam> array = BuildTfLiteArray<TypeParam>(values); ASSERT_NE(array, nullptr); EXPECT_THAT(array->size, Eq(values.size())); EXPECT_THAT(GetSpan(*array), ElementsAreArray(values)); } TYPED_TEST(TfLiteArrayTest, BuildFromSpan) { std::vector<TypeParam> values = {1, 2, 3, 4}; TfLiteArrayUniquePtr<TypeParam> array = BuildTfLiteArray(absl::Span<const TypeParam>(values)); ASSERT_NE(array, nullptr); EXPECT_THAT(array->size, Eq(values.size())); EXPECT_THAT(GetSpan(*array), ElementsAreArray(values)); } TYPED_TEST(TfLiteArrayTest, BuildFromInitializerList) { std::initializer_list<TypeParam> values{1, 2, 3, 4}; TfLiteArrayUniquePtr<TypeParam> array = BuildTfLiteArray(values); ASSERT_NE(array, nullptr); EXPECT_THAT(array->size, Eq(values.size())); EXPECT_THAT(GetSpan(*array), ElementsAreArray(values)); } TYPED_TEST(TfLiteArrayTest, BuildUsingSingleElementInitializerList) { constexpr TypeParam value = 42; TfLiteArrayUniquePtr<TypeParam> array = BuildTfLiteArray({value}); ASSERT_NE(array, nullptr); EXPECT_THAT(array->size, Eq(1)); EXPECT_THAT(array->data[0], Eq(value)); } TYPED_TEST(TfLiteArrayTest, BuildFromTfLiteArray) { std::initializer_list<TypeParam> values{1, 2, 3, 4}; const auto ref = BuildTfLiteArray(values); TfLiteArrayUniquePtr<TypeParam> array = BuildTfLiteArray(*ref); ASSERT_NE(array, nullptr); EXPECT_THAT(array->size, Eq(values.size())); EXPECT_THAT(GetSpan(*array), ElementsAreArray(values)); } } }
https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/tensorflow/lite/array.cc
https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/tensorflow/lite/array_test.cc
4a29233a7b7c1a3a4294e4ccdd1772f9083944ea
df9c3ca4-5178-49e5-9e5f-3c983d3d5701
cpp
tensorflow/tensorflow
window_util
third_party/xla/xla/window_util.cc
third_party/xla/xla/window_util_test.cc
#include "xla/window_util.h" #include <functional> #include <string> #include <vector> #include "absl/algorithm/container.h" #include "absl/functional/function_ref.h" #include "absl/strings/str_cat.h" #include "xla/xla_data.pb.h" #include "tsl/platform/logging.h" namespace xla { namespace window_util { Window MakeWindow(absl::Span<const int64_t> sizes) { Window window; for (int64_t size : sizes) { auto* dimension = window.add_dimensions(); dimension->set_size(size); dimension->set_stride(1); dimension->set_base_dilation(1); dimension->set_window_dilation(1); } return window; } Window MakeWindow(absl::Span<const int64_t> sizes, absl::Span<const int64_t> strides) { Window window; CHECK_EQ(sizes.size(), strides.size()); for (auto nb = 0; nb < sizes.size(); ++nb) { auto* dimension = window.add_dimensions(); dimension->set_size(sizes[nb]); dimension->set_stride(strides[nb]); dimension->set_base_dilation(1); dimension->set_window_dilation(1); } return window; } PaddingConfig MakeSymmetricPadding(absl::Span<const int64_t> sizes) { PaddingConfig config; for (int64_t size : sizes) { auto* dimension = config.add_dimensions(); dimension->set_edge_padding_low(size); dimension->set_edge_padding_high(size); } return config; } std::string ToString(const WindowDimension& dim) { using absl::StrAppend; using absl::StrCat; std::string str = StrCat("(size=", dim.size()); if (dim.stride() != 1) { StrAppend(&str, ",stride=", dim.stride()); } if (dim.padding_low() != 0) { StrAppend(&str, ",padding_low=", dim.padding_low()); } if (dim.padding_high() != 0) { StrAppend(&str, ",padding_high=", dim.padding_high()); } if (dim.base_dilation() != 1) { StrAppend(&str, ",base_dilation=", dim.base_dilation()); } if (dim.window_dilation() != 1) { StrAppend(&str, ",window_dilation=", dim.window_dilation()); } if (dim.window_reversal()) { StrAppend(&str, ",window_reversal"); } StrAppend(&str, ")"); return str; } std::string ToString(const Window& window) { using absl::StrAppend; using absl::StrCat; std::string str; const auto add_field = [&](const char* heading, absl::FunctionRef<std::string(const WindowDimension&)> format) { StrAppend(&str, heading, "="); const char* prefix = ""; for (const auto& window_dimension : window.dimensions()) { StrAppend(&str, prefix, format(window_dimension)); prefix = "x"; } }; if (window.dimensions_size() > 0) { add_field("size", [](const WindowDimension& dim) { return StrCat(dim.size()); }); } if (HasStride(window)) { add_field(" stride", [](const WindowDimension& dim) { return StrCat(dim.stride()); }); } if (HasPadding(window)) { add_field(" pad", [](const WindowDimension& dim) { return StrCat(dim.padding_low(), "_", dim.padding_high()); }); } if (HasBaseDilation(window)) { add_field(" lhs_dilate", [](const WindowDimension& dim) { return StrCat(dim.base_dilation()); }); } if (HasWindowDilation(window)) { add_field(" rhs_dilate", [](const WindowDimension& dim) { return StrCat(dim.window_dilation()); }); } if (HasWindowReversal(window)) { add_field(" rhs_reversal", [](const WindowDimension& dim) { return StrCat(dim.window_reversal() ? 1 : 0); }); } return str; } bool HasStride(const Window& window) { for (const auto& dim : window.dimensions()) { if (dim.stride() != 1) { return true; } } return false; } bool HasPadding(const Window& window) { for (const auto& dim : window.dimensions()) { if (dim.padding_low() != 0 || dim.padding_high() != 0) { return true; } } return false; } bool HasSymmetricPadding(const Window& window) { return absl::c_all_of(window.dimensions(), [](const WindowDimension& dim) { return dim.padding_low() == dim.padding_high(); }); } bool HasSymmetricPadding(const PaddingConfig& padding_config) { return absl::c_all_of(padding_config.dimensions(), [](const PaddingConfig::PaddingConfigDimension& dim) { return dim.edge_padding_low() == dim.edge_padding_high(); }); } bool HasNegativePadding(const Window& window) { return absl::c_any_of(window.dimensions(), [](const WindowDimension& dim) { return dim.padding_low() < 0 || dim.padding_high() < 0; }); } bool HasBaseDilation(const Window& window) { for (const auto& dim : window.dimensions()) { if (dim.base_dilation() != 1) { return true; } } return false; } bool HasWindowDilation(const Window& window) { for (const auto& dim : window.dimensions()) { if (dim.window_dilation() != 1) { return true; } } return false; } bool HasWindowReversal(const Window& window) { for (const auto& dim : window.dimensions()) { if (dim.window_reversal()) { return true; } } return false; } bool AllOrNoneReversed(const Window& window) { if (window.dimensions().empty()) { return true; } bool reversed = window.dimensions()[0].window_reversal(); return absl::c_all_of(window.dimensions(), [&](const WindowDimension& dim) { return dim.window_reversal() == reversed; }); } bool HasDilation(const Window& window) { return HasBaseDilation(window) || HasWindowDilation(window); } bool IsTrivialWindowDimension(const WindowDimension& window_dimension) { return window_dimension.size() == 1 && window_dimension.stride() == 1 && window_dimension.padding_low() == 0 && window_dimension.padding_high() == 0 && window_dimension.window_dilation() == 1 && window_dimension.base_dilation() == 1; } bool HasOverlappingWindow(const Window& window) { for (const auto& dim : window.dimensions()) { if (dim.size() > dim.stride()) { return true; } } return false; } int64_t DilatedBound(int64_t bound, int64_t dilation) { CHECK_GE(bound, 0); CHECK_GE(dilation, 1); if (bound == 0) { return 0; } return (bound - 1) * dilation + 1; } int64_t StridedBound(int64_t bound, int64_t window_size, int64_t stride) { CHECK_GE(window_size, 0); CHECK_GE(bound, 0); CHECK_GE(stride, 1); if (bound == 0 || window_size > bound) { return 0; } return (bound - window_size) / stride + 1; } } }
#include "xla/window_util.h" #include "xla/test.h" namespace xla { namespace { using ::testing::ElementsAre; TEST(WindowUtilTest, HasOverlappingWindowTest) { EXPECT_FALSE( window_util::HasOverlappingWindow(window_util::MakeWindow({1, 1}))); EXPECT_TRUE( window_util::HasOverlappingWindow(window_util::MakeWindow({2, 2, 2, 2}))); } TEST(WindowUtilTest, MakeWindowStrideTest) { Window w = window_util::MakeWindow({1, 2}, {3, 4}); EXPECT_EQ(w.dimensions()[0].size(), 1); EXPECT_EQ(w.dimensions()[1].size(), 2); EXPECT_EQ(w.dimensions()[0].stride(), 3); EXPECT_EQ(w.dimensions()[1].stride(), 4); } } }
https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/third_party/xla/xla/window_util.cc
https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/third_party/xla/xla/window_util_test.cc
4a29233a7b7c1a3a4294e4ccdd1772f9083944ea
9bfa0aed-5597-42d1-a7a7-edf29201be63
cpp
tensorflow/tensorflow
text_literal_reader
third_party/xla/xla/text_literal_reader.cc
third_party/xla/xla/text_literal_reader_test.cc
#include "xla/text_literal_reader.h" #include <limits> #include <memory> #include <string> #include <utility> #include <vector> #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/ascii.h" #include "absl/strings/match.h" #include "absl/strings/numbers.h" #include "absl/strings/str_split.h" #include "absl/strings/string_view.h" #include "absl/strings/strip.h" #include "xla/literal.h" #include "xla/service/hlo_parser.h" #include "xla/shape.h" #include "xla/shape_util.h" #include "xla/tsl/lib/io/buffered_inputstream.h" #include "xla/tsl/lib/io/random_inputstream.h" #include "xla/util.h" #include "xla/xla_data.pb.h" #include "tsl/platform/env.h" #include "tsl/platform/file_system.h" #include "tsl/platform/statusor.h" namespace xla { absl::StatusOr<Literal> TextLiteralReader::ReadPath(absl::string_view path) { CHECK(!absl::EndsWith(path, ".gz")) << "TextLiteralReader no longer supports reading .gz files"; std::unique_ptr<tsl::RandomAccessFile> file; absl::Status s = tsl::Env::Default()->NewRandomAccessFile(std::string(path), &file); if (!s.ok()) { return s; } TextLiteralReader reader(file.release()); return reader.ReadAllLines(); } TextLiteralReader::TextLiteralReader(tsl::RandomAccessFile* file) : file_(file) {} absl::StatusOr<Literal> TextLiteralReader::ReadAllLines() { tsl::io::RandomAccessInputStream stream(file_.get()); tsl::io::BufferedInputStream buf(&stream, 65536); std::string shape_string; absl::Status s = buf.ReadLine(&shape_string); if (!s.ok()) { return s; } absl::StripAsciiWhitespace(&shape_string); TF_ASSIGN_OR_RETURN(Shape shape, ParseShape(shape_string)); if (shape.element_type() != F32) { return Unimplemented( "unsupported element type for text literal reading: %s", ShapeUtil::HumanString(shape)); } Literal result(shape); const float fill = std::numeric_limits<float>::quiet_NaN(); result.PopulateWithValue<float>(fill); std::vector<absl::string_view> pieces; std::vector<absl::string_view> coordinates; std::vector<int64_t> coordinate_values; std::string line; while (buf.ReadLine(&line).ok()) { pieces = absl::StrSplit(line, ':'); absl::string_view coordinates_string = absl::StripAsciiWhitespace(pieces[0]); absl::string_view value_string = absl::StripAsciiWhitespace(pieces[1]); if (!absl::ConsumePrefix(&coordinates_string, "(")) { return InvalidArgument( "expected '(' at the beginning of coordinates: \"%s\"", line); } if (!absl::ConsumeSuffix(&coordinates_string, ")")) { return InvalidArgument("expected ')' at the end of coordinates: \"%s\"", line); } float value; if (!absl::SimpleAtof(value_string, &value)) { return InvalidArgument("could not parse value as float: \"%s\"", value_string); } coordinates = absl::StrSplit(coordinates_string, ','); coordinate_values.clear(); for (absl::string_view piece : coordinates) { int64_t coordinate_value; if (!absl::SimpleAtoi(piece, &coordinate_value)) { return InvalidArgument( "could not parse coordinate member as int64_t: \"%s\"", std::string(piece)); } coordinate_values.push_back(coordinate_value); } if (coordinate_values.size() != shape.dimensions_size()) { return InvalidArgument( "line did not have expected number of coordinates; want %d got %u: " "\"%s\"", shape.dimensions_size(), coordinate_values.size(), line); } result.Set<float>(coordinate_values, value); } return std::move(result); } }
#include "xla/text_literal_reader.h" #include <string> #include "xla/literal.h" #include "xla/shape_util.h" #include "xla/test.h" #include "xla/xla_data.pb.h" #include "tsl/platform/env.h" namespace xla { namespace { TEST(TextLiteralReaderTest, ReadsR3File) { std::string contents = R"(f32[1,2,3] (0,0,0): 42.5 (0,0,1): 43.5 (0,0,2): 44.5 (0,1,0): 45.5 (0,1,1): 46.5 (0,1,2): 47.5 )"; std::string fname = tsl::testing::TmpDir() + "/ReadsR3File.data.txt"; EXPECT_TRUE( tsl::WriteStringToFile(tsl::Env::Default(), fname, contents).ok()); Literal literal = TextLiteralReader::ReadPath(fname).value(); EXPECT_TRUE( ShapeUtil::Equal(ShapeUtil::MakeShape(F32, {1, 2, 3}), literal.shape())); EXPECT_EQ(42.5, literal.Get<float>({0, 0, 0})); EXPECT_EQ(43.5, literal.Get<float>({0, 0, 1})); EXPECT_EQ(44.5, literal.Get<float>({0, 0, 2})); EXPECT_EQ(45.5, literal.Get<float>({0, 1, 0})); EXPECT_EQ(46.5, literal.Get<float>({0, 1, 1})); EXPECT_EQ(47.5, literal.Get<float>({0, 1, 2})); } } }
https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/third_party/xla/xla/text_literal_reader.cc
https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/third_party/xla/xla/text_literal_reader_test.cc
4a29233a7b7c1a3a4294e4ccdd1772f9083944ea
360c2c87-d341-492d-b99c-25d8a17c02b4
cpp
tensorflow/tensorflow
permutation_util
third_party/xla/xla/permutation_util.cc
third_party/xla/xla/permutation_util_test.cc
#include "xla/permutation_util.h" #include <vector> #include "absl/container/inlined_vector.h" namespace xla { bool IsPermutation(absl::Span<const int64_t> permutation) { absl::InlinedVector<bool, 8> seen(permutation.size(), false); for (int64_t p : permutation) { if (p < 0 || p >= permutation.size() || seen[p]) { return false; } seen[p] = true; } return true; } std::vector<int64_t> InversePermutation( absl::Span<const int64_t> input_permutation) { DCHECK(IsPermutation(input_permutation)); std::vector<int64_t> output_permutation(input_permutation.size(), -1); for (size_t i = 0; i < input_permutation.size(); ++i) { output_permutation[input_permutation[i]] = i; } return output_permutation; } std::vector<int64_t> ComposePermutations(absl::Span<const int64_t> p1, absl::Span<const int64_t> p2) { CHECK_EQ(p1.size(), p2.size()); std::vector<int64_t> output; output.reserve(p1.size()); for (size_t i = 0; i < p1.size(); ++i) { output.push_back(p1.at(p2.at(i))); } return output; } bool IsIdentityPermutation(absl::Span<const int64_t> permutation) { for (int64_t i = 0; i < permutation.size(); ++i) { if (permutation[i] != i) { return false; } } return true; } }
#include "xla/permutation_util.h" #include "xla/test.h" namespace xla { namespace { TEST(PermutationUtilTest, IsPermutation) { EXPECT_TRUE(IsPermutation({})); EXPECT_TRUE(IsPermutation({0})); EXPECT_FALSE(IsPermutation({-3})); EXPECT_TRUE(IsPermutation({0, 1})); EXPECT_FALSE(IsPermutation({1, 1})); EXPECT_TRUE(IsPermutation({1, 0})); EXPECT_TRUE(IsPermutation({3, 1, 0, 2})); EXPECT_FALSE(IsPermutation({3, 0, 2})); } } }
https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/third_party/xla/xla/permutation_util.cc
https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/third_party/xla/xla/permutation_util_test.cc
4a29233a7b7c1a3a4294e4ccdd1772f9083944ea
55be3496-37ca-4495-9404-30bbf91e9b67
cpp
tensorflow/tensorflow
comparison_util
third_party/xla/xla/comparison_util.cc
third_party/xla/xla/comparison_util_test.cc
#include "xla/comparison_util.h" #include <optional> #include <string> #include "absl/container/flat_hash_map.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "xla/primitive_util.h" #include "xla/util.h" #include "xla/xla_data.pb.h" #include "tsl/platform/logging.h" namespace xla { namespace { bool IsValidComparison(xla::PrimitiveType type, Comparison::Order order) { if (primitive_util::IsFloatingPointType(type) || primitive_util::IsComplexType(type)) { return true; } if (primitive_util::IsIntegralType(type) || type == PRED) { return order == Comparison::Order::kTotal; } LOG(FATAL) << "Unsupported type: " << PrimitiveType_Name(type); } PrimitiveType DefaultPrimitiveType(Comparison::Type type) { switch (type) { case Comparison::Type::kFloat: case Comparison::Type::kFloatTotalOrder: return PrimitiveType::F32; case Comparison::Type::kSigned: return PrimitiveType::S32; case Comparison::Type::kUnsigned: return PrimitiveType::U32; } } Comparison::Order DefaultOrdering(Comparison::Type type) { switch (type) { case Comparison::Type::kFloat: return Comparison::Order::kPartial; case Comparison::Type::kFloatTotalOrder: case Comparison::Type::kSigned: case Comparison::Type::kUnsigned: return Comparison::Order::kTotal; } } Comparison::Order DefaultOrdering(PrimitiveType type) { if (primitive_util::IsFloatingPointType(type) || primitive_util::IsComplexType(type)) { return Comparison::Order::kPartial; } if (primitive_util::IsIntegralType(type) || type == PRED) { return Comparison::Order::kTotal; } LOG(FATAL) << "Unsupported type: " << PrimitiveType_Name(type); } Comparison::Direction Converse(Comparison::Direction direction) { switch (direction) { case Comparison::Direction::kEq: return Comparison::Direction::kEq; case Comparison::Direction::kNe: return Comparison::Direction::kNe; case Comparison::Direction::kGe: return Comparison::Direction::kLe; case Comparison::Direction::kGt: return Comparison::Direction::kLt; case Comparison::Direction::kLe: return Comparison::Direction::kGe; case Comparison::Direction::kLt: return Comparison::Direction::kGt; } } Comparison::Direction Inverse(Comparison::Direction direction) { switch (direction) { case Comparison::Direction::kEq: return Comparison::Direction::kNe; case Comparison::Direction::kNe: return Comparison::Direction::kEq; case Comparison::Direction::kGe: return Comparison::Direction::kLt; case Comparison::Direction::kGt: return Comparison::Direction::kLe; case Comparison::Direction::kLe: return Comparison::Direction::kGt; case Comparison::Direction::kLt: return Comparison::Direction::kGe; } } } std::string ComparisonDirectionToString(Comparison::Direction direction) { switch (direction) { case Comparison::Direction::kEq: return "EQ"; case Comparison::Direction::kNe: return "NE"; case Comparison::Direction::kGe: return "GE"; case Comparison::Direction::kGt: return "GT"; case Comparison::Direction::kLe: return "LE"; case Comparison::Direction::kLt: return "LT"; default: LOG(FATAL) << "Attempted to print uninitialized comparison direction"; } } std::string ComparisonTypeToString(Comparison::Type type) { switch (type) { case Comparison::Type::kFloat: return "FLOAT"; case Comparison::Type::kFloatTotalOrder: return "TOTALORDER"; case Comparison::Type::kSigned: return "SIGNED"; case Comparison::Type::kUnsigned: return "UNSIGNED"; } } absl::string_view ComparisonPrimitiveTypeToString(PrimitiveType type) { return PrimitiveType_Name(type); } absl::string_view ComparisonOrderToString(Comparison::Order order) { switch (order) { case Comparison::Order::kPartial: return "PARTIALORDER"; case Comparison::Order::kTotal: return "TOTALORDER"; } } absl::StatusOr<Comparison::Direction> StringToComparisonDirection( absl::string_view direction) { static auto* map = new absl::flat_hash_map<std::string, Comparison::Direction>({ {"EQ", Comparison::Direction::kEq}, {"NE", Comparison::Direction::kNe}, {"GE", Comparison::Direction::kGe}, {"GT", Comparison::Direction::kGt}, {"LE", Comparison::Direction::kLe}, {"LT", Comparison::Direction::kLt}, }); auto it = map->find(direction); if (it == map->end()) { return InvalidArgument("Unknown comparison direction: %s", direction); } return it->second; } absl::StatusOr<Comparison::Order> StringToComparisonOrder( absl::string_view order) { static auto* map = new absl::flat_hash_map<std::string, Comparison::Order>({ {"TOTALORDER", Comparison::Order::kTotal}, {"PARTIALORDER", Comparison::Order::kPartial}, }); auto it = map->find(order); if (it == map->end()) { return InvalidArgument("Unknown comparison type: %s", order); } return it->second; } absl::StatusOr<Comparison::Type> StringToComparisonType( absl::string_view comparison) { static auto* map = new absl::flat_hash_map<std::string, Comparison::Type>({ {"FLOAT", Comparison::Type::kFloat}, {"TOTALORDER", Comparison::Type::kFloatTotalOrder}, {"SIGNED", Comparison::Type::kSigned}, {"UNSIGNED", Comparison::Type::kUnsigned}, }); auto it = map->find(comparison); if (it == map->end()) { return InvalidArgument("Unknown comparison type: %s", comparison); } return it->second; } Comparison::Type Comparison::DefaultComparisonType(PrimitiveType type) { if (primitive_util::IsFloatingPointType(type) || primitive_util::IsComplexType(type)) { return Type::kFloat; } if (primitive_util::IsSignedIntegralType(type)) { return Type::kSigned; } if (primitive_util::IsUnsignedIntegralType(type) || type == PRED) { return Type::kUnsigned; } LOG(FATAL) << "Unexpected: " << PrimitiveType_Name(type); } Comparison::Comparison(Direction dir, PrimitiveType type, Order order) : dir_(dir), primitive_type_(type), order_(order), type_(DefaultComparisonType(type)) { CHECK(IsValidComparison(primitive_type_, order_)); } Comparison::Comparison(Direction dir, PrimitiveType type) : dir_(dir), primitive_type_(type), order_(DefaultOrdering(type)), type_(DefaultComparisonType(type)) { CHECK(IsValidComparison(primitive_type_, order_)); } Comparison::Comparison(Direction dir, Type type) : dir_(dir), primitive_type_(DefaultPrimitiveType(type)), order_(DefaultOrdering(type)), type_(type) { CHECK(IsValidComparison(primitive_type_, order_)); } Comparison Comparison::Converse() const { return Comparison(xla::Converse(dir_), primitive_type_, order_); } std::optional<Comparison> Comparison::Inverse() const { if (IsPartialOrder()) { return std::nullopt; } if (primitive_util::IsArrayType(primitive_type_)) { return Comparison(xla::Inverse(dir_), primitive_type_, order_); } return std::nullopt; } bool Comparison::IsReflexive() const { switch (dir_) { case Direction::kEq: case Direction::kGe: case Direction::kLe: return IsTotalOrder(); case Direction::kNe: case Direction::kGt: case Direction::kLt: return false; } } bool Comparison::IsAntireflexive() const { switch (dir_) { case Direction::kNe: return IsTotalOrder(); case Direction::kGt: case Direction::kLt: return true; case Direction::kEq: case Direction::kGe: case Direction::kLe: return false; } } std::string Comparison::ToString(std::string prefix1, std::string prefix2, std::string prefix3) const { return absl::StrCat(prefix1, ComparisonDirectionToString(dir_), prefix2, ComparisonPrimitiveTypeToString(primitive_type_), prefix3, ComparisonOrderToString(order_)); } }
#include "xla/comparison_util.h" #include <cstdint> #include <limits> #include "xla/test.h" #include "xla/types.h" #include "xla/xla_data.pb.h" namespace xla { namespace { using ::testing::Eq; TEST(Comparison, FloatsDefaultToPartialOrder) { EXPECT_EQ( Comparison(Comparison::Direction::kGe, PrimitiveType::BF16).GetOrder(), Comparison::Order::kPartial); EXPECT_EQ( Comparison(Comparison::Direction::kGe, PrimitiveType::F32).GetOrder(), Comparison::Order::kPartial); EXPECT_EQ( Comparison(Comparison::Direction::kGe, PrimitiveType::C64).GetOrder(), Comparison::Order::kPartial); } TEST(Comparison, IntegersDefaultToTotalOrder) { EXPECT_EQ( Comparison(Comparison::Direction::kGe, PrimitiveType::S32).GetOrder(), Comparison::Order::kTotal); EXPECT_EQ( Comparison(Comparison::Direction::kGe, PrimitiveType::U8).GetOrder(), Comparison::Order::kTotal); EXPECT_EQ( Comparison(Comparison::Direction::kGe, PrimitiveType::PRED).GetOrder(), Comparison::Order::kTotal); } TEST(Comparison, LegacyConstructorDefaultsToX32) { EXPECT_EQ(Comparison(Comparison::Direction::kGe, Comparison::Type::kFloat) .GetPrimitiveType(), xla::PrimitiveType::F32); EXPECT_EQ( Comparison(Comparison::Direction::kGe, Comparison::Type::kFloatTotalOrder) .GetPrimitiveType(), xla::PrimitiveType::F32); EXPECT_EQ(Comparison(Comparison::Direction::kGe, Comparison::Type::kSigned) .GetPrimitiveType(), xla::PrimitiveType::S32); EXPECT_EQ(Comparison(Comparison::Direction::kGe, Comparison::Type::kUnsigned) .GetPrimitiveType(), xla::PrimitiveType::U32); } TEST(Comparison, PartialOrderReflexivity) { EXPECT_FALSE( Comparison(Comparison::Direction::kEq, PrimitiveType::F32).IsReflexive()); EXPECT_FALSE( Comparison(Comparison::Direction::kLe, PrimitiveType::F32).IsReflexive()); EXPECT_FALSE( Comparison(Comparison::Direction::kLt, PrimitiveType::S32).IsReflexive()); } TEST(Comparison, TotalOrderReflexivity) { EXPECT_TRUE(Comparison(Comparison::Direction::kLe, PrimitiveType::BF16, Comparison::Order::kTotal) .IsReflexive()); EXPECT_TRUE(Comparison(Comparison::Direction::kGe, PrimitiveType::F32, Comparison::Order::kTotal) .IsReflexive()); EXPECT_TRUE( Comparison(Comparison::Direction::kEq, PrimitiveType::S32).IsReflexive()); EXPECT_FALSE(Comparison(Comparison::Direction::kNe, PrimitiveType::F32, Comparison::Order::kTotal) .IsReflexive()); EXPECT_FALSE(Comparison(Comparison::Direction::kLt, PrimitiveType::F64, Comparison::Order::kTotal) .IsReflexive()); } TEST(Comparison, PartialOrderAntiReflexivity) { EXPECT_TRUE(Comparison(Comparison::Direction::kGt, PrimitiveType::F32) .IsAntireflexive()); EXPECT_TRUE(Comparison(Comparison::Direction::kLt, PrimitiveType::F32, Comparison::Order::kTotal) .IsAntireflexive()); EXPECT_FALSE(Comparison(Comparison::Direction::kEq, PrimitiveType::F32, Comparison::Order::kTotal) .IsAntireflexive()); } TEST(Comparison, TotalOrderAntiReflexivity) { EXPECT_TRUE(Comparison(Comparison::Direction::kNe, PrimitiveType::BF16, Comparison::Order::kTotal) .IsAntireflexive()); EXPECT_TRUE(Comparison(Comparison::Direction::kNe, PrimitiveType::S32) .IsAntireflexive()); EXPECT_FALSE(Comparison(Comparison::Direction::kEq, PrimitiveType::F32, Comparison::Order::kTotal) .IsAntireflexive()); EXPECT_FALSE(Comparison(Comparison::Direction::kLe, PrimitiveType::F64, Comparison::Order::kTotal) .IsAntireflexive()); EXPECT_FALSE(Comparison(Comparison::Direction::kLe, PrimitiveType::S8) .IsAntireflexive()); } TEST(Comparison, Converse) { EXPECT_THAT( Comparison(Comparison::Direction::kLe, PrimitiveType::S8).Converse(), Eq(Comparison(Comparison::Direction::kGe, PrimitiveType::S8))); EXPECT_THAT( Comparison(Comparison::Direction::kEq, PrimitiveType::U16).Converse(), Eq(Comparison(Comparison::Direction::kEq, PrimitiveType::U16))); EXPECT_THAT( Comparison(Comparison::Direction::kGt, PrimitiveType::F32).Converse(), Eq(Comparison(Comparison::Direction::kLt, PrimitiveType::F32))); } TEST(Comparison, PartialOrderFloatsShouldNotHaveInverse) { EXPECT_FALSE(Comparison(Comparison::Direction::kGt, PrimitiveType::F32) .Inverse() .has_value()); } TEST(Comparison, Inverse) { EXPECT_THAT( *Comparison(Comparison::Direction::kLe, PrimitiveType::S64).Inverse(), Eq(Comparison(Comparison::Direction::kGt, PrimitiveType::S64))); EXPECT_THAT( *Comparison(Comparison::Direction::kEq, PrimitiveType::U16).Inverse(), Eq(Comparison(Comparison::Direction::kNe, PrimitiveType::U16))); EXPECT_THAT(*Comparison(Comparison::Direction::kGt, PrimitiveType::F32, Comparison::Order::kTotal) .Inverse(), Eq(Comparison(Comparison::Direction::kLe, PrimitiveType::F32, Comparison::Order::kTotal))); } TEST(Comparison, ToString) { EXPECT_EQ( Comparison(Comparison::Direction::kLt, PrimitiveType::F32).ToString(), ".LT.F32.PARTIALORDER"); EXPECT_EQ( Comparison(Comparison::Direction::kEq, PrimitiveType::S8).ToString(), ".EQ.S8.TOTALORDER"); EXPECT_EQ(Comparison(Comparison::Direction::kGe, PrimitiveType::C128) .ToString("_1_", "_2_", "_3_"), "_1_GE_2_C128_3_PARTIALORDER"); } TEST(Comparison, TotalOrderFloatComparison) { EXPECT_TRUE(Comparison(Comparison::Direction::kEq, PrimitiveType::F32, Comparison::Order::kTotal) .Compare<float>(std::numeric_limits<float>::quiet_NaN(), std::numeric_limits<float>::quiet_NaN())); EXPECT_TRUE(Comparison(Comparison::Direction::kLt, PrimitiveType::F32, Comparison::Order::kTotal) .Compare<float>(1.0f, 2.0f)); EXPECT_FALSE(Comparison(Comparison::Direction::kLt, PrimitiveType::F32, Comparison::Order::kTotal) .Compare<float>(std::numeric_limits<float>::infinity(), -std::numeric_limits<float>::infinity())); EXPECT_TRUE(Comparison(Comparison::Direction::kLt, PrimitiveType::F32, Comparison::Order::kTotal) .Compare<float>(-0.0f, +0.0f)); EXPECT_TRUE(Comparison(Comparison::Direction::kNe, PrimitiveType::F32, Comparison::Order::kTotal) .Compare<float>(+0.0f, -0.0f)); EXPECT_FALSE(Comparison(Comparison::Direction::kGt, PrimitiveType::F32, Comparison::Order::kTotal) .Compare<float>(-0.1f, 0.1f)); } TEST(Comparison, TotalOrderBfloat16Comparison) { EXPECT_TRUE(Comparison(Comparison::Direction::kEq, PrimitiveType::BF16, Comparison::Order::kTotal) .Compare<xla::bfloat16>( std::numeric_limits<xla::bfloat16>::quiet_NaN(), std::numeric_limits<xla::bfloat16>::quiet_NaN())); EXPECT_TRUE( Comparison(Comparison::Direction::kLt, PrimitiveType::BF16, Comparison::Order::kTotal) .Compare<xla::bfloat16>(xla::bfloat16(1.0f), xla::bfloat16(2.0f))); EXPECT_FALSE(Comparison(Comparison::Direction::kLt, PrimitiveType::BF16, Comparison::Order::kTotal) .Compare<xla::bfloat16>( std::numeric_limits<xla::bfloat16>::infinity(), -std::numeric_limits<xla::bfloat16>::infinity())); EXPECT_TRUE( Comparison(Comparison::Direction::kLt, PrimitiveType::BF16, Comparison::Order::kTotal) .Compare<xla::bfloat16>(xla::bfloat16(-0.0f), xla::bfloat16(+0.0f))); EXPECT_TRUE( Comparison(Comparison::Direction::kGt, PrimitiveType::BF16, Comparison::Order::kTotal) .Compare<xla::bfloat16>(xla::bfloat16(+0.0f), xla::bfloat16(-0.0f))); EXPECT_FALSE( Comparison(Comparison::Direction::kGt, PrimitiveType::BF16, Comparison::Order::kTotal) .Compare<xla::bfloat16>(xla::bfloat16(-0.1f), xla::bfloat16(0.1f))); } TEST(Comparison, Compare) { EXPECT_TRUE(Comparison(Comparison::Direction::kLt, PrimitiveType::F32) .Compare<float>(1.0f, 2.0f)); EXPECT_TRUE( Comparison(Comparison::Direction::kGe, PrimitiveType::BF16) .Compare<xla::bfloat16>(xla::bfloat16(2.0f), xla::bfloat16(1.0f))); EXPECT_FALSE(Comparison(Comparison::Direction::kNe, PrimitiveType::S64) .Compare<int64_t>(1'000'000, 1'000'000)); EXPECT_TRUE(Comparison(Comparison::Direction::kEq, PrimitiveType::U8) .Compare<uint8_t>(63, 63)); } } }
https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/third_party/xla/xla/comparison_util.cc
https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/third_party/xla/xla/comparison_util_test.cc
4a29233a7b7c1a3a4294e4ccdd1772f9083944ea
56e50346-9b28-42eb-bd12-b78a59d61181
cpp
tensorflow/tensorflow
ef57
third_party/xla/xla/ef57.cc
third_party/xla/xla/ef57_test.cc
#include "xla/ef57.h" #include <limits> #include <tuple> #include "absl/types/span.h" #include "xla/compiler_macros.h" #include "tsl/platform/logging.h" #ifdef XLA_HAS_SSE2 #include <immintrin.h> #endif #if defined(XLA_HAS_ARM_NEON) && defined(XLA_HAS_ARM64) #include <arm_neon.h> #endif namespace xla { void ConvertF64ToEf57(absl::Span<const double> input, absl::Span<float> output) { DCHECK_EQ(input.size() * 2, output.size()); #ifdef __AVX__ constexpr int kDoublesPerAvxIteration = sizeof(__m256d) / sizeof(double); constexpr int kFloatsPerSseRegister = sizeof(__m128) / sizeof(float); while (input.size() >= kDoublesPerAvxIteration) { __m256d x = _mm256_loadu_pd(input.data()); __m128 x_hi_f32 = _mm256_cvtpd_ps(x); __m256d x_hi_f64 = _mm256_cvtps_pd(x_hi_f32); __m256d x_lo_f64 = _mm256_sub_pd(x, x_hi_f64); __m128 x_lo_f32 = _mm256_cvtpd_ps(x_lo_f64); const __m128 inf = _mm_set1_ps(std::numeric_limits<float>::infinity()); __m128 x_hi_exponent = _mm_and_ps(x_hi_f32, inf); __m128 x_is_finite = _mm_cmplt_ps(x_hi_exponent, inf); x_lo_f32 = _mm_and_ps(x_lo_f32, x_is_finite); _mm_storeu_ps(output.data(), _mm_unpacklo_ps(x_hi_f32, x_lo_f32)); output.remove_prefix(kFloatsPerSseRegister); _mm_storeu_ps(output.data(), _mm_unpackhi_ps(x_hi_f32, x_lo_f32)); output.remove_prefix(kFloatsPerSseRegister); input.remove_prefix(kDoublesPerAvxIteration); } #endif #ifdef XLA_HAS_SSE2 constexpr int kDoublesPerSseIteration = sizeof(__m128d) / sizeof(double); constexpr int kFloatsPerSseIteration = sizeof(__m128) / sizeof(float); while (input.size() >= kDoublesPerSseIteration) { __m128d x = _mm_loadu_pd(input.data()); __m128 x_hi_f32 = _mm_cvtpd_ps(x); __m128d x_hi_f64 = _mm_cvtps_pd(x_hi_f32); __m128d x_lo_f64 = _mm_sub_pd(x, x_hi_f64); __m128 x_lo_f32 = _mm_cvtpd_ps(x_lo_f64); const __m128 inf = _mm_set1_ps(std::numeric_limits<float>::infinity()); __m128 x_hi_exponent = _mm_and_ps(x_hi_f32, inf); __m128 x_is_finite = _mm_cmplt_ps(x_hi_exponent, inf); x_lo_f32 = _mm_and_ps(x_lo_f32, x_is_finite); __m128 to_store = _mm_unpacklo_ps(x_hi_f32, x_lo_f32); _mm_storeu_ps(output.data(), to_store); input.remove_prefix(kDoublesPerSseIteration); output.remove_prefix(kFloatsPerSseIteration); } #endif #if defined(XLA_HAS_ARM_NEON) && defined(XLA_HAS_ARM64) constexpr int kDoublesPerNeonIteration = sizeof(float64x2_t) / sizeof(double); constexpr int kFloatsPerNeonIteration = sizeof(float32x2x2_t) / sizeof(float); while (input.size() >= kDoublesPerNeonIteration) { float64x2_t x = vld1q_f64(input.data()); float32x2_t x_hi_f32 = vcvt_f32_f64(x); float64x2_t x_hi_f64 = vcvt_f64_f32(x_hi_f32); float64x2_t x_lo_f64 = vsubq_f64(x, x_hi_f64); float32x2_t x_lo_f32 = vcvt_f32_f64(x_lo_f64); uint32x2_t x_is_finite = vcalt_f32(x_hi_f32, vdup_n_f32(std::numeric_limits<float>::infinity())); x_lo_f32 = vreinterpret_f32_u32( vand_u32(vreinterpret_u32_f32(x_lo_f32), x_is_finite)); float32x2x2_t to_store; to_store.val[0] = x_hi_f32; to_store.val[1] = x_lo_f32; vst2_f32(output.data(), to_store); input.remove_prefix(kDoublesPerNeonIteration); output.remove_prefix(kFloatsPerNeonIteration); } #endif while (input.size() >= 1) { std::tie(output[0], output[1]) = SplitF64ToF32(input.front()); input.remove_prefix(1); output.remove_prefix(2); } } }
#include "xla/ef57.h" #include <cmath> #include <limits> #include <vector> #include "absl/algorithm/container.h" #include "absl/log/log_streamer.h" #include "absl/random/random.h" #include "absl/types/span.h" #include "xla/test.h" namespace xla { namespace { TEST(Ef57Test, DoubleMax) { auto [high, low] = SplitF64ToF32(std::numeric_limits<double>::max()); EXPECT_EQ(high, std::numeric_limits<float>::infinity()); EXPECT_EQ(low, 0.0f); } TEST(Ef57Test, Overflow) { auto [high, low] = SplitF64ToF32(0x1.ffffffp+127); EXPECT_EQ(high, std::numeric_limits<float>::infinity()); EXPECT_EQ(low, 0.0f); } TEST(Ef57Test, CheckPrecision) { auto [high, low] = SplitF64ToF32(2.0 - 0x1p-52); EXPECT_EQ(high, 2.0f); EXPECT_EQ(low, -0x1p-52f); } TEST(Ef57Test, SimpleArray) { std::vector<double> inputs(127); absl::BitGen gen; for (double& input : inputs) { input = absl::Uniform<float>(gen, 0.0f, 1.0f); } std::vector<float> outputs(inputs.size() * 2); ConvertF64ToEf57(inputs, absl::MakeSpan(outputs)); for (int i = 0; i < inputs.size(); ++i) { EXPECT_EQ(outputs[i * 2], inputs[i]); EXPECT_EQ(outputs[i * 2 + 1], 0.0f); } } TEST(Ef57Test, RelativeSplit) { const float distance = std::scalbnf(1.0f, std::numeric_limits<float>::digits); std::vector<double> inputs(127); absl::BitGen gen; for (double& input : inputs) { input = absl::Uniform<double>(gen, 0.0, 1.0); } std::vector<float> outputs(inputs.size() * 2); ConvertF64ToEf57(inputs, absl::MakeSpan(outputs)); for (int i = 0; i < outputs.size(); i += 2) { auto most_significant = outputs[i]; auto least_significant = outputs[i + 1]; auto most_significant_mag = std::fabs(most_significant); auto least_significant_mag = std::fabs(least_significant); EXPECT_FALSE(std::isnan(most_significant_mag)); if (most_significant_mag == 0.0f) { EXPECT_EQ(least_significant_mag, 0.0f); } else { EXPECT_GT(most_significant_mag, least_significant_mag * distance); } } } } }
https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/third_party/xla/xla/ef57.cc
https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/third_party/xla/xla/ef57_test.cc
4a29233a7b7c1a3a4294e4ccdd1772f9083944ea
bd4c1478-bbde-4786-a6d1-34d8a3fb48f2
cpp
tensorflow/tensorflow
text_literal_writer
third_party/xla/xla/text_literal_writer.cc
third_party/xla/xla/text_literal_writer_test.cc
#include "xla/text_literal_writer.h" #include <memory> #include <string> #include "absl/status/status.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 "xla/literal.h" #include "xla/shape_util.h" #include "tsl/platform/env.h" #include "tsl/platform/file_system.h" namespace xla { absl::Status TextLiteralWriter::WriteToPath( const Literal& literal, absl::string_view path) { std::unique_ptr<tsl::WritableFile> f; auto s = tsl::Env::Default()->NewWritableFile(std::string(path), &f); if (!s.ok()) { return s; } s = f->Append(ShapeUtil::HumanString(literal.shape()) + "\n"); if (!s.ok()) { return s; } absl::Status status; tsl::WritableFile* f_ptr = f.get(); literal.EachCellAsString([f_ptr, &status](absl::Span<const int64_t> indices, const std::string& value) { if (!status.ok()) { return; } std::string coordinates = absl::StrCat("(", absl::StrJoin(indices, ", "), ")"); status = f_ptr->Append(absl::StrCat(coordinates, ": ", value, "\n")); }); auto ignored = f->Close(); return status; } }
#include "xla/text_literal_writer.h" #include <memory> #include <string> #include "xla/literal_util.h" #include "xla/test.h" #include "xla/test_helpers.h" #include "xla/tsl/lib/core/status_test_util.h" #include "tsl/platform/env.h" namespace xla { namespace { TEST(TextLiteralWriterTest, WritesFloatLiteral) { auto literal = LiteralUtil::CreateR2<float>({ {3.14, 2.17}, {1.23, 4.56}, }); std::string path; ASSERT_TRUE(tsl::Env::Default()->LocalTempFilename(&path)); ASSERT_IS_OK(TextLiteralWriter::WriteToPath(literal, path)); std::string contents; TF_ASSERT_OK(tsl::ReadFileToString(tsl::Env::Default(), path, &contents)); const std::string expected = R"(f32[2,2] (0, 0): 3.14 (0, 1): 2.17 (1, 0): 1.23 (1, 1): 4.56 )"; EXPECT_EQ(expected, contents); } } }
https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/third_party/xla/xla/text_literal_writer.cc
https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/third_party/xla/xla/text_literal_writer_test.cc
4a29233a7b7c1a3a4294e4ccdd1772f9083944ea
2d30b848-631b-4668-8f6c-fe02c615407f
cpp
tensorflow/tensorflow
literal_comparison
third_party/xla/xla/literal_comparison.cc
third_party/xla/xla/literal_comparison_test.cc
#include "xla/literal_comparison.h" #include <complex> #ifndef _WIN32 #include <unistd.h> #endif #include <array> #include <cmath> #include <cstdint> #include <limits> #include <optional> #include <set> #include <string> #include <utility> #include <vector> #include "absl/status/status.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" #include "absl/types/span.h" #include "Eigen/Core" #include "xla/error_spec.h" #include "xla/fp_util.h" #include "xla/index_util.h" #include "xla/layout_util.h" #include "xla/literal.h" #include "xla/literal_util.h" #include "xla/primitive_util.h" #include "xla/shape.h" #include "xla/shape_util.h" #include "xla/types.h" #include "xla/util.h" #include "xla/xla_data.pb.h" #include "tsl/platform/errors.h" #include "tsl/platform/logging.h" using absl::StrAppend; using absl::StrAppendFormat; using absl::StrCat; namespace xla { namespace literal_comparison { namespace { template <typename FloatT, typename UnsignedT> bool CompareFloatsBitwiseEqual(FloatT lhs, FloatT rhs, absl::Span<const int64_t> multi_index) { auto ulhs = Eigen::numext::bit_cast<UnsignedT>(lhs); auto urhs = Eigen::numext::bit_cast<UnsignedT>(rhs); return ulhs == urhs; } template <typename NativeT> bool CompareEqual(NativeT lhs, NativeT rhs, absl::Span<const int64_t> multi_index) { if constexpr (is_specialized_floating_point_v<NativeT>) { using BitT = UnsignedIntegerTypeForSizeType<sizeof(NativeT)>; return CompareFloatsBitwiseEqual<NativeT, BitT>(lhs, rhs, multi_index); } if constexpr (is_complex_v<NativeT>) { using ComponentT = typename NativeT::value_type; return CompareEqual<ComponentT>(lhs.real(), rhs.real(), multi_index) && CompareEqual<ComponentT>(lhs.imag(), rhs.imag(), multi_index); } return lhs == rhs; } template <typename NativeT, typename UnsignedT> absl::Status MakeBitwiseErrorStatus(NativeT lhs, NativeT rhs, absl::Span<const int64_t> multi_index) { auto ulhs = Eigen::numext::bit_cast<UnsignedT>(lhs); auto urhs = Eigen::numext::bit_cast<UnsignedT>(rhs); auto lhs_double = static_cast<double>(lhs); auto rhs_double = static_cast<double>(rhs); return InvalidArgument( "floating values are not bitwise-equal; and equality testing " "was requested: %s=%s=%a vs %s=%s=%a at array index %s", StrCat(absl::Hex(ulhs)), RoundTripFpToString(lhs), lhs_double, StrCat(absl::Hex(urhs)), RoundTripFpToString(rhs), rhs_double, LiteralUtil::MultiIndexAsString(multi_index)); } template <typename NativeT> absl::Status MakeErrorStatus(NativeT lhs, NativeT rhs, absl::Span<const int64_t> multi_index) { if constexpr (is_specialized_integral_v<NativeT>) { return InvalidArgument( "first mismatch at array index %s:\n expected value: %s\n actual " "value: %s", LiteralUtil::MultiIndexAsString(multi_index), StrCat(lhs), StrCat(rhs)); } if constexpr (is_specialized_floating_point_v<NativeT>) { using BitT = UnsignedIntegerTypeForSizeType<sizeof(NativeT)>; return MakeBitwiseErrorStatus<NativeT, BitT>(lhs, rhs, multi_index); } if constexpr (is_complex_v<NativeT>) { using ComponentT = typename NativeT::value_type; if (!CompareEqual<ComponentT>(lhs.real(), rhs.real(), multi_index)) { return MakeErrorStatus(lhs.real(), rhs.real(), multi_index); } return MakeErrorStatus(lhs.imag(), rhs.imag(), multi_index); } } template <typename NativeT> absl::Status Equal(LiteralSlice expected, LiteralSlice actual, absl::Span<int64_t> multi_index, int64_t dimension, Literal* mismatched = nullptr) { if (dimension == expected.shape().dimensions_size()) { NativeT expected_value = expected.Get<NativeT>(multi_index); NativeT actual_value = actual.Get<NativeT>(multi_index); bool result = CompareEqual<NativeT>(expected_value, actual_value, multi_index); if (mismatched) { mismatched->Set<bool>(multi_index, !result); } return result ? absl::OkStatus() : MakeErrorStatus<NativeT>(expected_value, actual_value, multi_index); } absl::Status result; int64_t upper_bound = expected.shape().dimensions(dimension); if (expected.shape().is_dynamic_dimension(dimension)) { upper_bound = expected.GetDynamicSize(dimension); } for (int64_t i = 0; i < upper_bound; ++i) { multi_index[dimension] = i; if (mismatched != nullptr) { result.Update(Equal<NativeT>(expected, actual, multi_index, dimension + 1, mismatched)); } else { TF_RETURN_IF_ERROR(Equal<NativeT>(expected, actual, multi_index, dimension + 1, mismatched)); } } return result; } int64_t RecursiveElementCount(const Shape& shape) { if (shape.IsTuple()) { const int64_t tuple_elements = ShapeUtil::TupleElementCount(shape); int64_t total = 0; for (int64_t i = 0; i < tuple_elements; ++i) { total += RecursiveElementCount(ShapeUtil::GetTupleElementShape(shape, i)); } return total; } else if (shape.IsArray()) { return ShapeUtil::ElementsIn(shape); } else { return 0; } } template <typename NativeT> bool IsInf(NativeT val) { return Eigen::numext::isinf(val); } template <typename NativeT> bool IsNan(NativeT value) { return Eigen::numext::isnan(value); } template <typename NativeT> std::string FpValueToString(NativeT value) { if constexpr (is_specialized_floating_point_v<NativeT>) { constexpr int kPrecisionDigits = std::numeric_limits<NativeT>::max_digits10; const int kExponentDigts = std::ceil(std::log10(std::numeric_limits<NativeT>::max_exponent10)); constexpr int kExtraChars = 4; const int kTotalChars = kPrecisionDigits * kExponentDigts + kExtraChars; return absl::StrFormat("%*.*g", kTotalChars, kPrecisionDigits, static_cast<double>(value)); } if constexpr (is_complex_v<NativeT>) { return absl::StrCat(FpValueToString(value.real()), " + ", FpValueToString(value.imag())); } } template <typename NativeT> double FpAbsoluteValue(NativeT value) { return static_cast<double>(Eigen::numext::abs(value)); } template <typename NativeT> class NearComparator { public: static absl::Status Compare(const LiteralSlice& expected, const LiteralSlice& actual, const ShapeIndex& shape_index, ErrorSpec error, bool detailed_message, const MiscompareCallback& miscompare_callback) { NearComparator<NativeT> comparator(expected, actual, shape_index, error, detailed_message, miscompare_callback); return comparator.Run(); } private: struct Mismatch { NativeT actual; NativeT expected; double rel_error; double abs_error; int64_t linear_index; int float_distance = -1; bool operator<(const Mismatch& other) const { return rel_error < other.rel_error; } std::string ToString(const Shape& shape) const { auto s = absl::StrFormat( "actual %s, expected %s, index %s, rel error %8.3g, abs error " "%8.3g", FpValueToString(actual), FpValueToString(expected), LiteralUtil::MultiIndexAsString( IndexUtil::LinearIndexToMultidimensionalIndex(shape, linear_index)), rel_error, abs_error); if (float_distance >= 0) { StrAppendFormat(&s, ", float distance %d", float_distance); } return s; } }; NearComparator(const LiteralSlice& expected, const LiteralSlice& actual, const ShapeIndex& shape_index, ErrorSpec error, bool detailed_message, const MiscompareCallback& miscompare_callback) : expected_(expected), actual_(actual), shape_index_(shape_index), error_(error), detailed_message_(detailed_message), miscompare_callback_(miscompare_callback), abs_value_buckets_(kAbsValueBucketBounds.size() - 1, {0, 0}), abs_error_buckets_(kErrorBucketBounds.size(), 0), rel_error_buckets_(kErrorBucketBounds.size(), 0) {} absl::Status Run() { TF_RETURN_IF_ERROR(EqualShapes(expected_.shape(), actual_.shape())); if (!expected_.shape().IsArray()) { return InvalidArgument("Expected array shape; got %s.", ShapeUtil::HumanString(expected_.shape())); } mismatches_ = Literal(ShapeUtil::ChangeElementType(actual_.shape(), PRED)); mismatches_.PopulateWithValue(false); CompareLiterals(); if (num_mismatches_ == 0) { return absl::OkStatus(); } else if (!VLOG_IS_ON(1) && miscompare_callback_ != nullptr) { miscompare_callback_( expected_, actual_, mismatches_, shape_index_, ErrorBuckets(abs_error_buckets_, rel_error_buckets_)); } return InvalidArgument("%s", ErrorMessage()); } void UpdateAbsValueBucket(NativeT value, bool is_mismatch) { const double abs_value = FpAbsoluteValue(value); for (int i = 0; i < abs_value_buckets_.size(); ++i) { if (i == abs_value_buckets_.size() - 1 || (abs_value >= kAbsValueBucketBounds[i] && abs_value < kAbsValueBucketBounds[i + 1])) { abs_value_buckets_[i].first++; if (is_mismatch) { abs_value_buckets_[i].second++; } return; } } } void UpdateErrorBucket(double error, absl::Span<int64_t> error_buckets) { CHECK_EQ(error_buckets.size(), kErrorBucketBounds.size()); for (int i = 0; i < error_buckets.size(); ++i) { if (error >= kErrorBucketBounds[i]) { error_buckets[i]++; } } } template <typename T> int CalculateFloatDistance(T expected, T actual) { if (error_.low_precision_fp_error_spec.type == PrimitiveType::PRIMITIVE_TYPE_INVALID) return -1; return primitive_util::FloatingPointTypeSwitch<int>( [&](const auto kType) -> int { using NarrowNativeT = primitive_util::NativeTypeOf<kType>; if constexpr (std::is_same_v<NarrowNativeT, tsl::float8_e3m4>) { return CalculateDistanceInFloats(NarrowNativeT(half(expected)), NarrowNativeT(half(actual))); } else { return CalculateDistanceInFloats(NarrowNativeT(expected), NarrowNativeT(actual)); } }, error_.low_precision_fp_error_spec.type); } template <typename T> void CompareValues(T expected, T actual, int64_t linear_index) { double abs_error; double rel_error; int float_distance = -1; if (CompareEqual<T>(expected, actual, {linear_index})) { abs_error = 0; rel_error = 0; } else if (IsNan(expected) || IsNan(actual)) { if (error_.all_nans_are_equivalent && IsNan(expected) && IsNan(actual)) { abs_error = 0; rel_error = 0; } else if ((!error_.relaxed_nans && IsNan(expected) != IsNan(actual)) || (error_.relaxed_nans && !IsNan(expected) && IsNan(actual))) { num_nan_mismatches_++; abs_error = std::numeric_limits<double>::infinity(); rel_error = std::numeric_limits<double>::infinity(); } else { abs_error = 0; rel_error = 0; } } else if (IsInf(actual) && !IsInf(expected) && error_.fewer_infs_ok) { T actual_finite = actual > T{0} ? std::numeric_limits<T>::max() : std::numeric_limits<T>::lowest(); abs_error = FpAbsoluteValue(actual_finite - expected); if (expected != T{0}) { rel_error = abs_error / FpAbsoluteValue(expected); } else { rel_error = std::numeric_limits<double>::infinity(); } } else if (IsInf(expected) || IsInf(actual)) { CHECK(!CompareEqual(expected, actual, {linear_index})); abs_error = std::numeric_limits<double>::infinity(); rel_error = std::numeric_limits<double>::infinity(); } else { float_distance = CalculateFloatDistance<T>(expected, actual); abs_error = FpAbsoluteValue(actual - expected); if (expected != T{0}) { rel_error = abs_error / FpAbsoluteValue(expected); } else { rel_error = std::numeric_limits<double>::infinity(); } } bool is_within_n_floats = false; bool should_use_float_error_spec = error_.low_precision_fp_error_spec.type != PrimitiveType::PRIMITIVE_TYPE_INVALID; if (should_use_float_error_spec && error_.low_precision_fp_error_spec.within_n_values >= 0) { is_within_n_floats = float_distance <= error_.low_precision_fp_error_spec.within_n_values; } const bool is_abs_mismatch = (should_use_float_error_spec && is_within_n_floats) ? false : (abs_error > error_.abs); const bool is_rel_mismatch = (should_use_float_error_spec && is_within_n_floats) ? false : (rel_error > error_.rel); const bool is_mismatch = is_abs_mismatch && is_rel_mismatch; if (is_abs_mismatch) { num_abs_mismatches_++; UpdateErrorBucket(rel_error, absl::MakeSpan(rel_error_buckets_)); } if (is_rel_mismatch) { num_rel_mismatches_++; UpdateErrorBucket(abs_error, absl::MakeSpan(abs_error_buckets_)); } UpdateAbsValueBucket(actual, is_mismatch); if (!is_mismatch) { return; } num_mismatches_++; if (top_rel_mismatches_.size() < kTopRelativeErrorCount || rel_error > top_rel_mismatches_.begin()->rel_error) { Mismatch mismatch = {actual, expected, rel_error, abs_error, linear_index, float_distance}; top_rel_mismatches_.insert(mismatch); if (top_rel_mismatches_.size() > kTopRelativeErrorCount) { top_rel_mismatches_.erase(top_rel_mismatches_.begin()); } } mismatches_.data<bool>()[linear_index] = true; } template <typename T> void CompareValues(std::complex<T> expected, std::complex<T> actual, int64_t linear_index) { const auto both_parts_mismatch = num_mismatches_ + 2; CompareValues<T>(expected.real(), actual.real(), linear_index); CompareValues<T>(expected.imag(), actual.imag(), linear_index); if (num_mismatches_ == both_parts_mismatch) { num_mismatches_--; } } void CompareLiterals() { if (LayoutUtil::Equal(actual_.shape().layout(), expected_.shape().layout()) && expected_.shape().is_static() && actual_.shape().is_static()) { absl::Span<const NativeT> expected_data = expected_.data<NativeT>(); absl::Span<const NativeT> actual_data = actual_.data<NativeT>(); const int64_t len = expected_data.size(); for (int64_t i = 0; i < len; ++i) { CompareValues(expected_data[i], actual_data[i], i); } return; } std::vector<int64_t> multi_index(actual_.shape().rank(), 0); CompareLiteralsSlow(0, &multi_index); } void CompareLiteralsSlow(int64_t dimension, std::vector<int64_t>* multi_index) { if (dimension == multi_index->size()) { CompareValues(expected_.Get<NativeT>(*multi_index), actual_.Get<NativeT>(*multi_index), IndexUtil::MultidimensionalIndexToLinearIndex( actual_.shape(), *multi_index)); } else { int64_t upper_bound = expected_.shape().dimensions(dimension); if (expected_.shape().is_dynamic_dimension(dimension)) { upper_bound = expected_.GetDynamicSize(dimension); } for (int64_t i = 0; i < upper_bound; ++i) { (*multi_index)[dimension] = i; CompareLiteralsSlow(dimension + 1, multi_index); } } } std::string ErrorMessage() { std::string out; int64_t element_count = ShapeUtil::ElementsIn(actual_.shape()); auto percent_string = [](double a, double b) { double pct = b == 0.0 ? 0.0 : 100.0 * a / b; return absl::StrFormat("%0.4f%%", pct); }; StrAppendFormat( &out, "\nMismatch count %d (%s) in shape %s (%d elements), abs bound " "%g, rel bound %g\n", num_mismatches_, percent_string(num_mismatches_, element_count), ShapeUtil::HumanString(actual_.shape()), ShapeUtil::ElementsIn(actual_.shape()), error_.abs, error_.rel); if (num_nan_mismatches_ > 0) { StrAppend(&out, "nan mismatches ", num_nan_mismatches_, "\n"); } StrAppendFormat(&out, "Top relative error mismatches:\n"); for (auto it = top_rel_mismatches_.rbegin(); it != top_rel_mismatches_.rend(); ++it) { StrAppend(&out, " ", it->ToString(actual_.shape()), "\n"); } if (!detailed_message_) { return out; } StrAppend(&out, "Absolute magnitude breakdown of actual values:\n"); CHECK_EQ(abs_value_buckets_.size() + 1, kAbsValueBucketBounds.size()); for (int i = 0; i < abs_value_buckets_.size(); ++i) { const int64_t bucket_size = abs_value_buckets_[i].first; const int64_t bucket_mismatches = abs_value_buckets_[i].second; std::string mismatch_str = bucket_mismatches > 0 ? absl::StrFormat(", mismatches %d", bucket_mismatches) : ""; StrAppendFormat(&out, " %-6g <= x < %-6g : %7d (%9s)%s\n", kAbsValueBucketBounds[i], kAbsValueBucketBounds[i + 1], bucket_size, percent_string(bucket_size, element_count), mismatch_str); } auto print_accum_buckets = [&](const std::string& header, int64_t total, absl::Span<const int64_t> buckets) { StrAppend(&out, header, ":\n"); StrAppendFormat(&out, " < %-6g : %7d (%s)\n", kErrorBucketBounds[0], total - buckets[0], percent_string(total - buckets[0], total)); CHECK_EQ(buckets.size(), kErrorBucketBounds.size()); for (int i = 0; i < kErrorBucketBounds.size(); ++i) { StrAppendFormat(&out, " >= %-6g : %7d (%s)\n", kErrorBucketBounds[i], buckets[i], percent_string(buckets[i], total)); } }; StrAppendFormat(&out, "Elements exceeding abs error bound %g: %d (%s)\n", error_.abs, num_abs_mismatches_, percent_string(num_abs_mismatches_, element_count)); print_accum_buckets( "Relative error breakdown of elements exceeding abs error bound", num_abs_mismatches_, rel_error_buckets_); StrAppendFormat(&out, "Elements exceeding rel error bound %g: %d (%s)\n", error_.rel, num_rel_mismatches_, percent_string(num_rel_mismatches_, element_count)); print_accum_buckets( "Absolute error breakdown of elements exceeding rel error bound", num_rel_mismatches_, abs_error_buckets_); return out; } LiteralSlice expected_; LiteralSlice actual_; ShapeIndex shape_index_; ErrorSpec error_; bool detailed_message_; MiscompareCallback miscompare_callback_; int64_t num_mismatches_ = 0; int64_t num_nan_mismatches_ = 0; int64_t num_abs_mismatches_ = 0; int64_t num_rel_mismatches_ = 0; Literal mismatches_; static constexpr int64_t kTopRelativeErrorCount = 5; std::multiset<Mismatch> top_rel_mismatches_; static inline constexpr std::array<double, 7> kAbsValueBucketBounds = { 0.0, 0.0001, 0.001, 0.01, 0.1, 1, std::numeric_limits<double>::infinity(), }; std::vector<std::pair<int64_t, int64_t>> abs_value_buckets_; static inline constexpr std::array<double, 5> kErrorBucketBounds = { 0.0001, 0.001, 0.01, 0.1, 1}; std::vector<int64_t> abs_error_buckets_; std::vector<int64_t> rel_error_buckets_; }; absl::Status EqualHelper(const LiteralSlice& expected, const LiteralSlice& actual, const ShapeIndex& shape_index, const MiscompareCallback& miscompare_callback) { if (expected.shape().is_static() && actual.shape().is_static()) { TF_RETURN_IF_ERROR(EqualShapes(expected.shape(), actual.shape())); } else { TF_RETURN_IF_ERROR(EqualDynamicShapesAndDimensions(expected, actual)); } absl::Status result; if (expected.shape().IsTuple()) { ShapeIndex next_index = shape_index; for (int i = 0; i < ShapeUtil::TupleElementCount(expected.shape()); ++i) { next_index.push_back(i); absl::Status tuple_result = EqualHelper(LiteralSlice(expected, {i}), LiteralSlice(actual, {i}), next_index, miscompare_callback); if (miscompare_callback) { result.Update(tuple_result); } else { TF_RETURN_IF_ERROR(tuple_result); } next_index.pop_back(); } } else { std::vector<int64_t> multi_index(expected.shape().dimensions_size(), 0); auto index = absl::MakeSpan(multi_index); Shape unequal_shape = ShapeUtil::MakeShape(PrimitiveType::PRED, expected.shape().dimensions()); Literal miscompared(unequal_shape); Literal* miscompared_ptr = (miscompare_callback == nullptr ? nullptr : &miscompared); primitive_util::PrimitiveTypeSwitch<void>( [&](auto primitive_type_constant) -> void { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = primitive_util::NativeTypeOf<primitive_type_constant>; result = Equal<NativeT>(expected, actual, index, 0, miscompared_ptr); return; } if constexpr (primitive_type_constant == TOKEN) { return; } LOG(FATAL) << "Unsupported primitive type: " << PrimitiveType_Name(expected.shape().element_type()); }, expected.shape().element_type()); if (!result.ok() && miscompare_callback) { miscompare_callback(expected, actual, LiteralSlice(miscompared), shape_index, ErrorBuckets()); } } return result; } absl::Status NearHelper(const LiteralSlice& expected, const LiteralSlice& actual, const ShapeIndex& shape_index, const ErrorSpec& error, std::optional<bool> detailed_message, const MiscompareCallback& miscompare_callback) { if (expected.shape().is_static() && actual.shape().is_static()) { TF_RETURN_IF_ERROR(EqualShapes(expected.shape(), actual.shape())); } else { TF_RETURN_IF_ERROR(EqualDynamicShapesAndDimensions(expected, actual)); } if (expected.shape().IsTuple()) { absl::Status return_status; for (int64_t i = 0; i < ShapeUtil::TupleElementCount(expected.shape()); ++i) { const auto expected_element = LiteralSlice(expected, {i}); const auto actual_element = LiteralSlice(actual, {i}); ShapeIndex element_index = shape_index; element_index.push_back(i); absl::Status element_result = NearHelper(expected_element, actual_element, element_index, error, detailed_message, miscompare_callback); if (!element_result.ok()) { element_result = InvalidArgument("Array at shape index %s, %s", element_index.ToString(), element_result.message()); if (return_status.ok()) { return_status = element_result; } else { return_status = AppendStatus(return_status, element_result.message()); } } } if (!return_status.ok() && shape_index.empty()) { int64_t total_elements = RecursiveElementCount(actual.shape()); return_status = InvalidArgument("\nMismatches in shape %s (%d elements):\n%s", ShapeUtil::HumanString(actual.shape()), total_elements, return_status.message()); } return return_status; } if (ShapeUtil::ElementIsFloating(expected.shape()) || ShapeUtil::ElementIsComplex(expected.shape())) { bool use_detailed_message = detailed_message.value_or( ShapeUtil::ElementsIn(expected.shape()) >= 64); return primitive_util::PrimitiveTypeSwitch<absl::Status>( [&](auto primitive_type) -> absl::Status { if constexpr (primitive_util::IsFloatingPointType(primitive_type) || primitive_util::IsComplexType(primitive_type)) { using NativeT = primitive_util::NativeTypeOf<primitive_type>; return NearComparator<NativeT>::Compare( expected, actual, shape_index, error, use_detailed_message, miscompare_callback); } LOG(FATAL) << "Unsupported primitive type in near comparator: " << PrimitiveType_Name(expected.shape().element_type()) << ". Must be floating-point type."; }, expected.shape().element_type()); } return EqualHelper(expected, actual, shape_index, miscompare_callback); } } absl::Status EqualShapes(const Shape& expected, const Shape& actual) { if (expected.element_type() != actual.element_type()) { return InvalidArgument("element type mismatch, want: %s got %s", ShapeUtil::HumanString(expected), ShapeUtil::HumanString(actual)); } if (expected.IsTuple()) { if (ShapeUtil::TupleElementCount(expected) != ShapeUtil::TupleElementCount(actual)) { return InvalidArgument( "want tuple element count: %d got tuple element count: %d", ShapeUtil::TupleElementCount(expected), ShapeUtil::TupleElementCount(actual)); } for (int i = 0; i < expected.tuple_shapes_size(); ++i) { absl::Status result = EqualShapes(expected.tuple_shapes(i), actual.tuple_shapes(i)); if (!result.ok()) { return AppendStatus(result, StrCat("mismatch in tuple index", i)); } } } else if (expected.IsArray()) { if (expected.rank() != actual.rank()) { return InvalidArgument("want rank of %s got rank of %s", ShapeUtil::HumanString(expected), ShapeUtil::HumanString(actual)); } if (expected.element_type() != actual.element_type()) { return InvalidArgument("mismatch in primitive type %s vs %s", PrimitiveType_Name(expected.element_type()), PrimitiveType_Name(actual.element_type())); } if (expected.dimensions_size() != actual.dimensions_size()) { return InvalidArgument("want dimensions_size %d got dimensions_size %d", expected.dimensions_size(), actual.dimensions_size()); } for (int i = 0; i < expected.dimensions_size(); ++i) { if (expected.dimensions(i) != actual.dimensions(i)) { return InvalidArgument( "mismatch in dimension #%d expected: %s actual: %s", i, ShapeUtil::HumanString(expected), ShapeUtil::HumanString(actual)); } } } return absl::OkStatus(); } absl::Status EqualDynamicShapesAndDimensions(const LiteralSlice& expected, const LiteralSlice& actual) { TF_RETURN_IF_ERROR(EqualShapes(expected.shape(), actual.shape())); return ShapeUtil::ForEachSubshapeWithStatus( expected.shape(), [&expected, &actual](const Shape& expected_shape, const ShapeIndex& index) -> absl::Status { auto actual_shape = ShapeUtil::GetSubshape(actual.shape(), index); for (int i = 0; i < expected_shape.dimensions().size(); ++i) { if (!expected_shape.is_dynamic_dimension(i) && !actual_shape.is_dynamic_dimension(i)) { continue; } if (expected_shape.is_dynamic_dimension(i) && !actual_shape.is_dynamic_dimension(i)) { return InvalidArgument( "mismatch at dimension %d. the expected shape %s is dynamic " "while " "the actual shape %s is not.", i, ShapeUtil::HumanString(expected.shape()), ShapeUtil::HumanString(actual.shape())); } if (!expected_shape.is_dynamic_dimension(i) && actual_shape.is_dynamic_dimension(i)) { return InvalidArgument( "mismatch at dimension %d. the expected shape %s is not " "dynamic " "while the actual shape %s is dynamic.", i, ShapeUtil::HumanString(expected.shape()), ShapeUtil::HumanString(actual.shape())); } int64_t expected_dynamic_size = expected.GetDynamicSize(i, index); int64_t actual_dynamic_size = actual.GetDynamicSize(i, index); if (expected_dynamic_size != actual_dynamic_size) { return InvalidArgument( "mismatch at dimension %d. The expected dynamic size does not " "match " "the actual dynamic size. %d vs. %d", i, expected_dynamic_size, actual_dynamic_size); } } return absl::OkStatus(); }); } namespace { absl::Status EmitLiteralsInErrorMessage(const absl::Status& result, const LiteralSlice& expected, const LiteralSlice& actual) { if (result.ok()) { return result; } return InvalidArgument("%s\n\nExpected literal:\n%s\n\nActual literal:\n%s", result.message(), ToStringTruncated(expected), ToStringTruncated(actual)); } } absl::Status Equal(const LiteralSlice& expected, const LiteralSlice& actual) { if (VLOG_IS_ON(1)) { LOG(INFO) << "expected:"; XLA_LOG_LINES(INFO, expected.ToString()); LOG(INFO) << "actual:"; XLA_LOG_LINES(INFO, actual.ToString()); } absl::Status result = EqualHelper(expected, actual, {}, nullptr); return EmitLiteralsInErrorMessage(result, expected, actual); } absl::Status Near(const LiteralSlice& expected, const LiteralSlice& actual, const ErrorSpec& error, std::optional<bool> detailed_message, const MiscompareCallback& miscompare_callback) { if (VLOG_IS_ON(1)) { LOG(INFO) << "Expected literal:"; XLA_LOG_LINES(INFO, expected.ToString()); LOG(INFO) << "Actual literal:"; XLA_LOG_LINES(INFO, actual.ToString()); } absl::Status result = NearHelper(expected, actual, {}, error, detailed_message, miscompare_callback); return EmitLiteralsInErrorMessage(result, expected, actual); } std::string ToStringTruncated(const LiteralSlice& literal) { return RecursiveElementCount(literal.shape()) < 1000 ? literal.ToString() : "[TRUNCATED, Literal with more than 1000 values]"; } } }
#include "xla/literal_comparison.h" #include <gtest/gtest.h> #include "xla/error_spec.h" #include "xla/literal_util.h" #include "xla/test_helpers.h" #include "xla/tsl/lib/core/status_test_util.h" #include "xla/xla_data.pb.h" #include "tsl/platform/ml_dtypes.h" namespace xla { namespace { template <typename T> class LiteralComparisonTest : public ::testing::Test {}; using TestedTypes = ::testing::Types<tsl::float8_e3m4, tsl::float8_e4m3, tsl::float8_e4m3fn, tsl::float8_e4m3b11fnuz, tsl::float8_e5m2>; TYPED_TEST_SUITE(LiteralComparisonTest, TestedTypes); TYPED_TEST(LiteralComparisonTest, CompareNear_Equal) { auto actual = LiteralUtil::CreateR0<TypeParam>(TypeParam(8.0)); auto expected = LiteralUtil::CreateR0<TypeParam>(TypeParam(8.0)); TF_EXPECT_OK(literal_comparison::Near(expected, actual, ErrorSpec(0.0, 0.0), false, nullptr)); } TYPED_TEST(LiteralComparisonTest, CompareNear_NotEqual_1ulp) { PrimitiveType type = primitive_util::NativeToPrimitiveType<TypeParam>(); auto actual = LiteralUtil::CreateR0<TypeParam>(TypeParam(8.0)); float expV = 9.0; if (type == F8E5M2) expV = 10.0; else if (type == F8E3M4) expV = 8.5; auto expected = LiteralUtil::CreateR0<TypeParam>(TypeParam{expV}); auto error_spec = ErrorSpec(0.0, 0.0); EXPECT_IS_NOT_OK(literal_comparison::Near(expected, actual, error_spec, false, nullptr)); error_spec.low_precision_fp_error_spec.type = type; error_spec.low_precision_fp_error_spec.within_n_values = 1; EXPECT_IS_OK(literal_comparison::Near(expected, actual, error_spec, false, nullptr)); } TYPED_TEST(LiteralComparisonTest, CompareNear_NotEqual_4ulps) { PrimitiveType type = primitive_util::NativeToPrimitiveType<TypeParam>(); auto actual = LiteralUtil::CreateR0<TypeParam>(TypeParam(8.0)); float expV = 12.0; if (type == F8E5M2) expV = 14.0; else if (type == F8E3M4) expV = 10.0; auto expected = LiteralUtil::CreateR0<TypeParam>(TypeParam{expV}); auto error_spec = ErrorSpec(0.0, 0.0); error_spec.low_precision_fp_error_spec.type = type; error_spec.low_precision_fp_error_spec.within_n_values = 1; EXPECT_IS_NOT_OK(literal_comparison::Near(expected, actual, error_spec, false, nullptr)); error_spec.low_precision_fp_error_spec.type = type; error_spec.low_precision_fp_error_spec.within_n_values = 4; EXPECT_IS_OK(literal_comparison::Near(expected, actual, error_spec, false, nullptr)); } TYPED_TEST(LiteralComparisonTest, FloatUsingCompareNear_NotEqual_4ulps) { PrimitiveType type = primitive_util::NativeToPrimitiveType<TypeParam>(); auto actual = LiteralUtil::CreateR0<float>(8.0); float expV = 12.1; if (type == F8E5M2) expV = 13.0; else if (type == F8E3M4) expV = 10.125; auto expected = LiteralUtil::CreateR0<float>(expV); auto error_spec = ErrorSpec(0.0, 0.0); error_spec.low_precision_fp_error_spec.type = type; error_spec.low_precision_fp_error_spec.within_n_values = 1; EXPECT_IS_NOT_OK(literal_comparison::Near(expected, actual, error_spec, false, nullptr)); error_spec.low_precision_fp_error_spec.type = type; error_spec.low_precision_fp_error_spec.within_n_values = 4; EXPECT_IS_OK(literal_comparison::Near(expected, actual, error_spec, false, nullptr)); } } }
https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/third_party/xla/xla/literal_comparison.cc
https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/third_party/xla/xla/literal_comparison_test.cc
4a29233a7b7c1a3a4294e4ccdd1772f9083944ea
8796243f-8a63-44d1-9528-3f37f6782728
cpp
tensorflow/tensorflow
cpu_function_runtime
third_party/xla/xla/cpu_function_runtime.cc
tensorflow/compiler/tf2xla/cpu_function_runtime_test.cc
#include "xla/cpu_function_runtime.h" #include "absl/base/dynamic_annotations.h" namespace xla { namespace { void* aligned_malloc(size_t size, int minimum_alignment) { #if defined(__ANDROID__) || defined(OS_ANDROID) || defined(OS_CYGWIN) return memalign(minimum_alignment, size); #elif defined(_WIN32) return _aligned_malloc(size, minimum_alignment); #else void* ptr = nullptr; const int required_alignment = sizeof(void*); if (minimum_alignment < required_alignment) return malloc(size); if (posix_memalign(&ptr, minimum_alignment, size) != 0) return nullptr; else return ptr; #endif } void aligned_free(void* aligned_memory) { #if defined(_WIN32) _aligned_free(aligned_memory); #else free(aligned_memory); #endif } size_t align_to(size_t n, size_t align) { return (((n - 1) / align) + 1) * align; } } namespace cpu_function_runtime { size_t AlignedBufferBytes(const BufferInfo* buffer_infos, size_t n, bool allocate_entry_params) { size_t total = 0; for (size_t i = 0; i < n; ++i) { bool should_allocate = buffer_infos[i].is_temp_buffer() || (buffer_infos[i].is_entry_parameter() && allocate_entry_params); if (should_allocate) { total += align_to(buffer_infos[i].size(), Align()); } } return total; } void* MallocContiguousBuffers(const BufferInfo* buffer_infos, size_t n, bool allocate_entry_params, void** bufs, bool annotate_initialized) { const size_t total = AlignedBufferBytes(buffer_infos, n, allocate_entry_params); void* contiguous = nullptr; if (total > 0) { contiguous = aligned_malloc(total, Align()); if (annotate_initialized) { ABSL_ANNOTATE_MEMORY_IS_INITIALIZED(contiguous, total); } } uintptr_t pos = reinterpret_cast<uintptr_t>(contiguous); for (size_t i = 0; i < n; ++i) { bool should_allocate = buffer_infos[i].is_temp_buffer() || (buffer_infos[i].is_entry_parameter() && allocate_entry_params); if (should_allocate) { bufs[i] = reinterpret_cast<void*>(pos); pos += align_to(buffer_infos[i].size(), Align()); } else { bufs[i] = nullptr; } } return contiguous; } void FreeContiguous(void* contiguous) { if (contiguous != nullptr) { aligned_free(contiguous); } } } }
#include "xla/cpu_function_runtime.h" #include "tensorflow/core/framework/allocator.h" #include "tensorflow/core/platform/test.h" namespace tensorflow { namespace { using ::xla::cpu_function_runtime::BufferInfo; TEST(XlaCompiledCpuFunctionTest, AlignmentValue) { EXPECT_EQ(xla::cpu_function_runtime::Align(), Allocator::kAllocatorAlignment); EXPECT_LE(xla::cpu_function_runtime::MinAlign(), Allocator::kAllocatorAlignment); } std::vector<BufferInfo> SizesToBufferInfos(const intptr_t* sizes, size_t n) { std::vector<BufferInfo> buffer_infos; std::transform(sizes, sizes + n, std::back_inserter(buffer_infos), [&](intptr_t size) { if (size == -1) { int64_t on_stack_buffer_size = 4; return BufferInfo::MakeOnStackBuffer(on_stack_buffer_size); } return BufferInfo::MakeTempBuffer(size); }); return buffer_infos; } size_t AlignedBufferBytesFromSizes(const intptr_t* sizes, size_t n) { std::vector<BufferInfo> buffer_infos = SizesToBufferInfos(sizes, n); return AlignedBufferBytes(buffer_infos.data(), n, false); } void* MallocContiguousBuffersFromSizes(const intptr_t* sizes, size_t n, void** bufs, bool annotate_initialized) { std::vector<BufferInfo> buffer_infos = SizesToBufferInfos(sizes, n); return MallocContiguousBuffers(buffer_infos.data(), n, false, bufs, annotate_initialized); } TEST(XlaCompiledCpuFunctionTest, AlignedBufferBytes) { EXPECT_EQ(AlignedBufferBytesFromSizes(nullptr, 0), 0); static constexpr intptr_t sizesA[1] = {-1}; EXPECT_EQ(AlignedBufferBytesFromSizes(sizesA, 1), 0); static constexpr intptr_t sizesB[1] = {3}; EXPECT_EQ(AlignedBufferBytesFromSizes(sizesB, 1), 64); static constexpr intptr_t sizesC[1] = {32}; EXPECT_EQ(AlignedBufferBytesFromSizes(sizesC, 1), 64); static constexpr intptr_t sizesD[7] = {1, -1, 32, -1, 64, 2, 3}; EXPECT_EQ(AlignedBufferBytesFromSizes(sizesD, 7), 320); } void* add_ptr(void* base, uintptr_t delta) { return reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(base) + delta); } TEST(XlaCompiledCpuFunctionTest, MallocFreeContiguousBuffers) { void* base = MallocContiguousBuffersFromSizes(nullptr, 0, nullptr, false); EXPECT_EQ(base, nullptr); xla::cpu_function_runtime::FreeContiguous(base); static constexpr intptr_t sizesA[1] = {-1}; void* bufA[1]; base = MallocContiguousBuffersFromSizes(sizesA, 1, bufA, false); EXPECT_EQ(base, nullptr); EXPECT_EQ(bufA[0], nullptr); xla::cpu_function_runtime::FreeContiguous(base); static constexpr intptr_t sizesB[1] = {3}; void* bufB[1]; base = MallocContiguousBuffersFromSizes(sizesB, 1, bufB, false); EXPECT_NE(base, nullptr); EXPECT_EQ(bufB[0], add_ptr(base, 0)); char* bufB0_bytes = static_cast<char*>(bufB[0]); bufB0_bytes[0] = 'A'; bufB0_bytes[1] = 'B'; bufB0_bytes[2] = 'C'; xla::cpu_function_runtime::FreeContiguous(base); static constexpr intptr_t sizesC[1] = {3}; void* bufC[1]; base = MallocContiguousBuffersFromSizes(sizesC, 1, bufC, true); EXPECT_NE(base, nullptr); EXPECT_EQ(bufC[0], add_ptr(base, 0)); char* bufC0_bytes = static_cast<char*>(bufC[0]); bufC0_bytes[0] = 'A'; bufC0_bytes[1] = 'B'; bufC0_bytes[2] = 'C'; xla::cpu_function_runtime::FreeContiguous(base); static constexpr intptr_t sizesD[7] = {1, -1, 32, -1, 64, 2, 3}; void* bufD[7]; base = MallocContiguousBuffersFromSizes(sizesD, 7, bufD, false); EXPECT_NE(base, nullptr); EXPECT_EQ(bufD[0], add_ptr(base, 0)); EXPECT_EQ(bufD[1], nullptr); EXPECT_EQ(bufD[2], add_ptr(base, 64)); EXPECT_EQ(bufD[3], nullptr); EXPECT_EQ(bufD[4], add_ptr(base, 128)); EXPECT_EQ(bufD[5], add_ptr(base, 192)); EXPECT_EQ(bufD[6], add_ptr(base, 256)); for (int i = 0; i < 7; ++i) { const intptr_t size = sizesD[i]; if (size != -1) { char* bufD_bytes = static_cast<char*>(bufD[i]); for (size_t j = 0; j < size; ++j) { bufD_bytes[j] = 'A' + j; } } } xla::cpu_function_runtime::FreeContiguous(base); } void CheckRoundTripIsOk(const BufferInfo& buffer_info) { BufferInfo round_trip(buffer_info.Encode()); ASSERT_EQ(round_trip, buffer_info); } TEST(XlaCompiledCpuFunctionTest, BufferInfoTest) { CheckRoundTripIsOk(BufferInfo::MakeTempBuffer(0)); CheckRoundTripIsOk(BufferInfo::MakeTempBuffer(4)); CheckRoundTripIsOk(BufferInfo::MakeOnStackBuffer(0)); CheckRoundTripIsOk(BufferInfo::MakeOnStackBuffer(4)); CheckRoundTripIsOk(BufferInfo::MakeConstant(0)); CheckRoundTripIsOk(BufferInfo::MakeConstant(4)); CheckRoundTripIsOk( BufferInfo::MakeEntryParameter(0, 4)); CheckRoundTripIsOk( BufferInfo::MakeEntryParameter(4, 0)); } } }
https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/third_party/xla/xla/cpu_function_runtime.cc
https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/tensorflow/compiler/tf2xla/cpu_function_runtime_test.cc
4a29233a7b7c1a3a4294e4ccdd1772f9083944ea
147250cd-0c15-4f1e-8224-6ffd1c121a75
cpp
tensorflow/tensorflow
shape
tensorflow/lite/delegates/gpu/common/shape.cc
tensorflow/lite/delegates/gpu/common/shape_test.cc
#include "tensorflow/lite/delegates/gpu/common/shape.h" #include <stdint.h> #include <string> #include <vector> #include "absl/strings/str_cat.h" #include "absl/strings/str_join.h" namespace tflite { namespace gpu { namespace { struct GetAxisByIndexFunc { template <Layout T> Axis operator()() const { return GetAxis<T>(index); } int32_t index; }; struct GetIndexByAxisFunc { template <Layout T> int operator()() const { return GetAxisIndex<T>(axis); } Axis axis; }; struct NumAxisFunc { template <Layout T> int operator()() const { return Size<T>(); } }; } std::string ToString(Axis axis) { switch (axis) { case Axis::BATCH: return "batch"; case Axis::CHANNELS: return "channels"; case Axis::INPUT_CHANNELS: return "input_channels"; case Axis::OUTPUT_CHANNELS: return "output_channels"; case Axis::HEIGHT: return "height"; case Axis::WIDTH: return "width"; case Axis::VALUE: return "value"; case Axis::DEPTH: return "depth"; case Axis::UNKNOWN: return "unknown"; } return "undefined"; } std::string ToString(Layout layout) { switch (layout) { case Layout::SCALAR: return "scalar"; case Layout::LINEAR: return "linear"; case Layout::HW: return "hw"; case Layout::HWD: return "hwd"; case Layout::CHW: return "chw"; case Layout::HWC: return "hwc"; case Layout::HWDC: return "hwdc"; case Layout::OHWI: return "ohwi"; case Layout::IHWO: return "ihwo"; case Layout::OIHW: return "oihw"; case Layout::IOHW: return "iohw"; case Layout::BHWC: return "bhwc"; case Layout::BHWDC: return "bhwdc"; case Layout::OHWDI: return "ohwdi"; case Layout::HWIO: return "hwio"; case Layout::UNKNOWN: return "unknown"; } return "undefined"; } Axis GetAxis(Layout layout, int32_t index) { return DispatchByLayout(layout, GetAxisByIndexFunc{index}); } int GetAxisIndex(Layout layout, Axis axis) { return DispatchByLayout(layout, GetIndexByAxisFunc{axis}); } bool HasAxis(Layout layout, Axis axis) { return GetAxisIndex(layout, axis) >= 0; } int Size(Layout layout) { return DispatchByLayout(layout, NumAxisFunc()); } std::string ToString(const Shape& s) { return absl::StrCat("{", ToString(s.layout), ", {", absl::StrJoin(s.dimensions, ", "), "}}"); } } }
#include "tensorflow/lite/delegates/gpu/common/shape.h" #include <stdint.h> #include <vector> #include <gtest/gtest.h> namespace tflite { namespace gpu { namespace { TEST(OIHW, Smoke) { OIHW OIHW; OIHW.i = 1; ASSERT_TRUE(OIHW.set<Axis::OUTPUT_CHANNELS>(2)); ASSERT_TRUE(OIHW.set(Axis::HEIGHT, 3)); ASSERT_TRUE(OIHW.set(3, 4)); ASSERT_FALSE(OIHW.set(5, 10)); ASSERT_FALSE(OIHW.set(Axis::CHANNELS, 10)); ASSERT_FALSE(OIHW.set<Axis::CHANNELS>(10)); EXPECT_EQ(1, OIHW.get(Axis::INPUT_CHANNELS)); EXPECT_EQ(2, OIHW.o); EXPECT_EQ(3, OIHW.get(2)); EXPECT_EQ(4, OIHW.get<Axis::WIDTH>()); EXPECT_EQ(-1, OIHW.get(5)); EXPECT_EQ(-1, OIHW.get(Axis::CHANNELS)); EXPECT_EQ(-1, OIHW.get<Axis::CHANNELS>()); ASSERT_EQ(4, OIHW.size()); std::vector<Axis> expected = {Axis::OUTPUT_CHANNELS, Axis::INPUT_CHANNELS, Axis::HEIGHT, Axis::WIDTH}; for (int i = 0; i < OIHW.size(); ++i) { Axis axis = OIHW.axis(i); ASSERT_EQ(expected[i], axis); ASSERT_EQ(i, OIHW.index(axis)); } OHWI ohwi; ASSERT_TRUE(ohwi.CopyAllDefinedAxis(OIHW)); EXPECT_EQ(ohwi.o, OIHW.o); EXPECT_EQ(ohwi.i, OIHW.i); EXPECT_EQ(ohwi.h, OIHW.h); EXPECT_EQ(ohwi.w, OIHW.w); ohwi = OHWI(10, 20, 30, 40); ASSERT_TRUE(OIHW.CopyAllGivenAxis(ohwi)); EXPECT_EQ(ohwi.o, OIHW.o); EXPECT_EQ(ohwi.i, OIHW.i); EXPECT_EQ(ohwi.h, OIHW.h); EXPECT_EQ(ohwi.w, OIHW.w); EXPECT_TRUE(ohwi.has(Axis::WIDTH)); EXPECT_FALSE(ohwi.has(Axis::DEPTH)); } TEST(Layout, Smoke) { EXPECT_EQ(4, Size<Layout::OIHW>()); EXPECT_EQ(4, Size(Layout::OIHW)); std::vector<Axis> expected = {Axis::OUTPUT_CHANNELS, Axis::INPUT_CHANNELS, Axis::HEIGHT, Axis::WIDTH}; for (int i = 0; i < Size<Layout::OIHW>(); ++i) { Axis axis = GetAxis<Layout::OIHW>(i); ASSERT_EQ(expected[i], axis); ASSERT_EQ(axis, GetAxis(Layout::OIHW, i)); ASSERT_EQ(i, GetAxisIndex<Layout::OIHW>(axis)); ASSERT_EQ(i, GetAxisIndex(Layout::OIHW, axis)); } EXPECT_EQ(Axis::UNKNOWN, GetAxis(Layout::OIHW, 5)); EXPECT_EQ(-1, GetAxisIndex<Layout::OIHW>(Axis::CHANNELS)); EXPECT_EQ(-1, GetAxisIndex<Layout::OIHW>(Axis::CHANNELS)); EXPECT_TRUE(HasAxis<Layout::OHWDI>(Axis::DEPTH)); EXPECT_FALSE(HasAxis<Layout::OHWDI>(Axis::CHANNELS)); } TEST(Shape, Smoke) { Shape s(Layout::OIHW, {1, 2, 3, 4}); EXPECT_TRUE(s.set(Axis::HEIGHT, 10)); EXPECT_TRUE(s.set<Axis::WIDTH>(20)); EXPECT_FALSE(s.set(Axis::BATCH, 10)); EXPECT_FALSE(s.set<Axis::BATCH>(20)); ASSERT_EQ(10, s.get<Axis::HEIGHT>()); ASSERT_EQ(20, s.get(Axis::WIDTH)); EXPECT_EQ(20, s.dimensions[3]); EXPECT_TRUE(s.has(Axis::HEIGHT)); EXPECT_FALSE(s.has(Axis::DEPTH)); OIHW oihw(1, 2, 10, 20); Shape s2 = oihw.ToShape(); EXPECT_EQ(s2.layout, oihw.layout); EXPECT_EQ(s.layout, s2.layout); EXPECT_EQ(s.dimensions, s2.dimensions); OHWI ohwi; ASSERT_TRUE(ohwi.Adopt(s2)); EXPECT_EQ(1, ohwi.o); EXPECT_EQ(2, ohwi.i); EXPECT_EQ(10, ohwi.h); EXPECT_EQ(20, ohwi.w); } } } }
https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/tensorflow/lite/delegates/gpu/common/shape.cc
https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/tensorflow/lite/delegates/gpu/common/shape_test.cc
4a29233a7b7c1a3a4294e4ccdd1772f9083944ea
fa92c336-7a0d-4ca4-81f9-7498b458157f
cpp
tensorflow/tensorflow
layout_util
tensorflow/compiler/tf2xla/layout_util.cc
third_party/xla/xla/layout_util_test.cc
#include "tensorflow/compiler/tf2xla/layout_util.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "tensorflow/compiler/tf2xla/shape_util.h" #include "tensorflow/compiler/tf2xla/type_util.h" #include "tensorflow/compiler/tf2xla/xla_argument.h" #include "tensorflow/compiler/tf2xla/xla_helpers.h" #include "xla/hlo/builder/xla_builder.h" #include "xla/hlo/ir/hlo_sharding.h" #include "xla/shape.h" #include "xla/shape_util.h" #include "xla/xla_data.pb.h" #include "tensorflow/core/framework/tensor_shape.h" #include "tensorflow/core/framework/types.pb.h" #include "tensorflow/core/lib/core/status.h" #include "tsl/platform/errors.h" #include "tsl/platform/statusor.h" namespace tensorflow { XlaShapeLayoutHelpers::ShapeDeterminationFns::ShapeDeterminationFns() { layout_preference_fn = UseNoPreferenceLayoutFn(); shape_representation_fn = IdentityShapeRepresentationFn(); } XlaShapeLayoutHelpers::LayoutPreferenceFn UseNoPreferenceLayoutFn() { return [](const TensorShape& shape, DataType dtype, std::optional<XlaArgument::Kind>) -> XlaLayoutPreference { return XlaLayoutPreference::kNoPreference; }; } Status RewriteLayoutWithShardedShape( const std::optional<xla::HloSharding>& sharding, bool use_fast_memory, XlaShapeLayoutHelpers::ShapeDeterminationFns shape_determination_fns, xla::Shape* xla_shape) { if (sharding && !sharding->IsTileMaximal() && !sharding->IsManual()) { int64_t device = sharding->tile_assignment().first(); std::vector<int64_t> offset = sharding->TileOffsetForDevice(*xla_shape, device); std::vector<int64_t> limit = sharding->TileLimitForDevice(*xla_shape, device); std::vector<int64_t> dimensions(xla_shape->rank()); for (int64_t i = 0; i < xla_shape->rank(); ++i) { dimensions[i] = limit[i] - offset[i]; } xla::Shape per_device_xla_shape = xla::ShapeUtil::MakeShape(xla_shape->element_type(), dimensions); TensorShape per_device_tensor_shape; TF_RETURN_IF_ERROR( XLAShapeToTensorShape(per_device_xla_shape, &per_device_tensor_shape)); TF_ASSIGN_OR_RETURN(DataType dtype, EncodePrimitiveTypeAsDataType( xla_shape->element_type())); auto layout_preference = shape_determination_fns.layout_preference_fn( per_device_tensor_shape, dtype, std::nullopt); TF_ASSIGN_OR_RETURN(per_device_xla_shape, shape_determination_fns.shape_representation_fn( per_device_tensor_shape, dtype, use_fast_memory, layout_preference)); *xla_shape->mutable_layout() = per_device_xla_shape.layout(); } return absl::OkStatus(); } absl::StatusOr<xla::XlaOp> ReshapeWithCorrectRepresentationAndSharding( xla::XlaBuilder* builder, xla::XlaOp original, xla::Shape original_shape, XlaShapeLayoutHelpers::ShapeDeterminationFns shape_determination_fns, std::optional<xla::OpSharding> sharding, bool fast_mem) { if (original_shape.IsTuple()) { std::vector<xla::XlaOp> elements; for (int i = 0; i < original_shape.tuple_shapes_size(); ++i) { auto subsharding = sharding ? sharding->tuple_shardings(i) : sharding; TF_ASSIGN_OR_RETURN(auto element, ReshapeWithCorrectRepresentationAndSharding( builder, xla::GetTupleElement(original, i), original_shape.tuple_shapes(i), shape_determination_fns, subsharding, fast_mem)); elements.push_back(element); } return xla::Tuple(builder, elements); } if (!original_shape.IsArray()) return original; TensorShape shape; TF_RETURN_IF_ERROR(XLAShapeToTensorShape(original_shape, &shape)); TF_ASSIGN_OR_RETURN(DataType dtype, EncodePrimitiveTypeAsDataType( original_shape.element_type())); auto layout_preference = shape_determination_fns.layout_preference_fn(shape, dtype, std::nullopt); TF_ASSIGN_OR_RETURN(auto to_shape, shape_determination_fns.shape_representation_fn( shape, dtype, fast_mem, layout_preference)); if (sharding) { TF_ASSIGN_OR_RETURN(auto hlo_sharding, xla::HloSharding::FromProto(*sharding)); TF_RETURN_IF_ERROR(RewriteLayoutWithShardedShape( hlo_sharding, fast_mem, shape_determination_fns, &to_shape)); } if (xla::ShapeUtil::Compatible(original_shape, to_shape)) { for (int64_t i = 0; i < original_shape.rank(); ++i) { to_shape.set_dynamic_dimension(i, original_shape.is_dynamic_dimension(i)); } } return xla::Reshape(to_shape, original); } }
#include "xla/layout_util.h" #include <cstdint> #include <vector> #include "absl/types/span.h" #include "xla/layout.h" #include "xla/shape.h" #include "xla/shape_util.h" #include "xla/test.h" #include "xla/test_helpers.h" #include "xla/xla_data.pb.h" #include "tsl/platform/errors.h" #include "tsl/platform/logging.h" #include "tsl/platform/status_matchers.h" namespace xla { namespace { class LayoutUtilTest : public ::testing::Test { protected: Shape MakeShapeWithLayout( PrimitiveType element_type, absl::Span<const int64_t> dimensions, absl::Span<const int64_t> minor_to_major, absl::Span<const DimLevelType> dim_level_types = {}) { Shape shape = ShapeUtil::MakeShape(element_type, dimensions); *shape.mutable_layout() = LayoutUtil::MakeLayout(minor_to_major, dim_level_types); return shape; } }; TEST_F(LayoutUtilTest, TupleLayoutComparison) { Shape shape = ShapeUtil::MakeTupleShape({MakeShapeWithLayout(F32, {2, 3}, {0, 1})}); Shape other_shape = ShapeUtil::MakeTupleShape({MakeShapeWithLayout(F32, {2, 2}, {0, 1})}); Shape tuple0 = ShapeUtil::MakeTupleShape({}); Shape tuple1 = ShapeUtil::MakeTupleShape({shape}); Shape tuple2 = ShapeUtil::MakeTupleShape({shape, shape}); EXPECT_TRUE(LayoutUtil::LayoutsInShapesEqual(tuple0, tuple0)); EXPECT_FALSE(LayoutUtil::LayoutsInShapesEqual(tuple0, tuple1)); EXPECT_FALSE(LayoutUtil::LayoutsInShapesEqual(tuple0, tuple2)); EXPECT_FALSE(LayoutUtil::LayoutsInShapesEqual(tuple1, tuple0)); EXPECT_FALSE(LayoutUtil::LayoutsInShapesEqual(tuple2, tuple0)); EXPECT_TRUE(LayoutUtil::LayoutsInShapesEqual(tuple1, tuple1)); EXPECT_FALSE(LayoutUtil::LayoutsInShapesEqual(tuple1, tuple2)); EXPECT_FALSE(LayoutUtil::LayoutsInShapesEqual(tuple2, tuple1)); Shape other_tuple2 = ShapeUtil::MakeTupleShape({shape, other_shape}); EXPECT_TRUE(LayoutUtil::LayoutsInShapesEqual(tuple2, tuple2)); EXPECT_TRUE(LayoutUtil::LayoutsInShapesEqual(tuple2, other_tuple2)); EXPECT_TRUE(LayoutUtil::LayoutsInShapesEqual(other_tuple2, tuple2)); } TEST_F(LayoutUtilTest, CopyLayoutDenseArray) { Shape src = MakeShapeWithLayout(F32, {2, 3}, {0, 1}); Shape dst = MakeShapeWithLayout(F32, {2, 3}, {1, 0}); EXPECT_FALSE(LayoutUtil::LayoutsInShapesEqual(src, dst)); EXPECT_IS_OK(LayoutUtil::CopyLayoutBetweenShapes(src, &dst)); EXPECT_TRUE(LayoutUtil::LayoutsInShapesEqual(src, dst)); dst.clear_layout(); EXPECT_FALSE(LayoutUtil::LayoutsInShapesEqual(src, dst)); EXPECT_IS_OK(LayoutUtil::CopyLayoutBetweenShapes(src, &dst)); EXPECT_TRUE(LayoutUtil::LayoutsInShapesEqual(src, dst)); src.clear_layout(); EXPECT_FALSE(LayoutUtil::LayoutsInShapesEqual(src, dst)); EXPECT_TRUE(dst.has_layout()); EXPECT_IS_OK(LayoutUtil::CopyLayoutBetweenShapes(src, &dst)); EXPECT_TRUE(LayoutUtil::LayoutsInShapesEqual(src, dst)); EXPECT_FALSE(dst.has_layout()); } TEST_F(LayoutUtilTest, CopyLayoutCSRArray) { Shape src = MakeShapeWithLayout(F32, {2, 3}, {1, 0}, {DIM_DENSE, DIM_COMPRESSED}); Shape dst = MakeShapeWithLayout(F32, {2, 3}, {0, 1}); EXPECT_TRUE(LayoutUtil::IsSparseArray(src)); EXPECT_FALSE(LayoutUtil::IsSparseArray(dst)); EXPECT_TRUE(LayoutUtil::IsCSRArray(src)); EXPECT_FALSE(LayoutUtil::IsCSRArray(dst)); EXPECT_FALSE(LayoutUtil::LayoutsInShapesEqual(src, dst)); EXPECT_IS_OK(LayoutUtil::CopyLayoutBetweenShapes(src, &dst)); EXPECT_TRUE(LayoutUtil::LayoutsInShapesEqual(src, dst)); EXPECT_TRUE(LayoutUtil::IsCSRArray(dst)); dst.clear_layout(); EXPECT_FALSE(LayoutUtil::IsCSRArray(dst)); EXPECT_FALSE(LayoutUtil::LayoutsInShapesEqual(src, dst)); EXPECT_IS_OK(LayoutUtil::CopyLayoutBetweenShapes(src, &dst)); EXPECT_TRUE(LayoutUtil::LayoutsInShapesEqual(src, dst)); EXPECT_TRUE(LayoutUtil::IsCSRArray(dst)); *dst.mutable_layout()->mutable_minor_to_major() = {0, 1}; EXPECT_TRUE(LayoutUtil::IsCSCArray(dst)); EXPECT_FALSE(LayoutUtil::IsCSRArray(dst)); EXPECT_IS_OK(LayoutUtil::CopyLayoutBetweenShapes(src, &dst)); *src.mutable_layout()->mutable_physical_shape() = ShapeUtil::MakeTupleShape({ ShapeUtil::MakeShapeWithDenseLayout(U32, {2}, {0}, {Tile({100})}), ShapeUtil::MakeShapeWithDenseLayout(U32, {4}, {0}, {Tile({100})}), ShapeUtil::MakeShapeWithDenseLayout(F32, {4}, {0}, {Tile({100})}), }); EXPECT_FALSE(LayoutUtil::LayoutsInShapesEqual(src, dst)); dst.clear_layout(); EXPECT_IS_OK(LayoutUtil::CopyLayoutBetweenShapes(src, &dst)); EXPECT_TRUE(LayoutUtil::LayoutsInShapesEqual(src, dst)); src.clear_layout(); EXPECT_FALSE(LayoutUtil::IsCSRArray(src)); EXPECT_FALSE(LayoutUtil::LayoutsInShapesEqual(src, dst)); EXPECT_TRUE(dst.has_layout()); EXPECT_IS_OK(LayoutUtil::CopyLayoutBetweenShapes(src, &dst)); EXPECT_TRUE(LayoutUtil::LayoutsInShapesEqual(src, dst)); EXPECT_FALSE(dst.has_layout()); EXPECT_FALSE(LayoutUtil::IsCSRArray(dst)); } TEST_F(LayoutUtilTest, CopyLayoutTuple) { Shape src = ShapeUtil::MakeTupleShape( {MakeShapeWithLayout(F32, {2, 3}, {0, 1}), MakeShapeWithLayout(F32, {42, 123}, {1, 0}), ShapeUtil::MakeTupleShape( {MakeShapeWithLayout(F32, {}, {}), MakeShapeWithLayout(F32, {1, 2, 3}, {0, 2, 1})})}); Shape dst = ShapeUtil::MakeTupleShape( {MakeShapeWithLayout(F32, {2, 3}, {1, 0}), MakeShapeWithLayout(F32, {42, 123}, {1, 0}), ShapeUtil::MakeTupleShape( {MakeShapeWithLayout(F32, {}, {}), MakeShapeWithLayout(F32, {1, 2, 3}, {1, 2, 0})})}); EXPECT_FALSE(LayoutUtil::LayoutsInShapesEqual(src, dst)); EXPECT_IS_OK(LayoutUtil::CopyLayoutBetweenShapes(src, &dst)); EXPECT_TRUE(LayoutUtil::LayoutsInShapesEqual(src, dst)); } TEST_F(LayoutUtilTest, CopyLayoutNotCompatibleSameRank) { Shape src = MakeShapeWithLayout(F32, {123, 42, 7}, {2, 0, 1}); Shape dst = MakeShapeWithLayout(F32, {2, 3, 5}, {1, 0}); ASSERT_IS_OK(LayoutUtil::CopyLayoutBetweenShapes(src, &dst)); EXPECT_TRUE(LayoutUtil::LayoutsInShapesEqual(src, dst)); } TEST_F(LayoutUtilTest, CopyLayoutNotCompatibleDifferentRank) { Shape src = MakeShapeWithLayout(F32, {123, 42, 7}, {2, 0, 1}); Shape dst = MakeShapeWithLayout(F32, {2, 3}, {1, 0}); auto status = LayoutUtil::CopyLayoutBetweenShapes(src, &dst); EXPECT_FALSE(status.ok()); EXPECT_THAT(status.message(), ::testing::ContainsRegex("cannot copy layout from shape")); } TEST_F(LayoutUtilTest, CopyLayoutNotCompatibleTuple) { Shape src = ShapeUtil::MakeTupleShape({MakeShapeWithLayout(F32, {2, 3}, {0, 1}), MakeShapeWithLayout(F32, {42, 123}, {1, 0}), ShapeUtil::MakeTupleShape({MakeShapeWithLayout( F32, {1, 2, 3}, {0, 2, 1})})}); Shape dst = ShapeUtil::MakeTupleShape( {MakeShapeWithLayout(F32, {2, 3}, {1, 0}), MakeShapeWithLayout(F32, {42, 123}, {1, 0}), ShapeUtil::MakeTupleShape( {MakeShapeWithLayout(F32, {}, {}), MakeShapeWithLayout(F32, {1, 2, 3}, {1, 2, 0})})}); auto status = LayoutUtil::CopyLayoutBetweenShapes(src, &dst); EXPECT_FALSE(status.ok()); EXPECT_THAT(status.message(), ::testing::ContainsRegex("cannot copy layout from shape")); } TEST_F(LayoutUtilTest, CopyLayoutBogusLayout) { Shape src = ShapeUtil::MakeShape(F32, {2, 3}); Shape dst = ShapeUtil::MakeShape(F32, {2, 3}); *src.mutable_layout() = LayoutUtil::MakeLayout({1, 2, 3, 4}); auto status = LayoutUtil::CopyLayoutBetweenShapes(src, &dst); EXPECT_FALSE(status.ok()); EXPECT_THAT(status.message(), ::testing::ContainsRegex( "layout minor_to_major field contains .* " "elements, but shape is rank")); } TEST_F(LayoutUtilTest, CopyTokenLayout) { Shape src = ShapeUtil::MakeTokenShape(); Shape dst = ShapeUtil::MakeTokenShape(); EXPECT_TRUE(LayoutUtil::LayoutsInShapesEqual(src, dst)); EXPECT_IS_OK(LayoutUtil::CopyLayoutBetweenShapes(src, &dst)); EXPECT_TRUE(LayoutUtil::LayoutsInShapesEqual(src, dst)); } TEST_F(LayoutUtilTest, CopyOpaqueLayout) { Shape src = ShapeUtil::MakeOpaqueShape(); Shape dst = ShapeUtil::MakeOpaqueShape(); EXPECT_TRUE(LayoutUtil::LayoutsInShapesEqual(src, dst)); EXPECT_IS_OK(LayoutUtil::CopyLayoutBetweenShapes(src, &dst)); EXPECT_TRUE(LayoutUtil::LayoutsInShapesEqual(src, dst)); } TEST_F(LayoutUtilTest, CopyTupleLayoutWithTokenAndOpaque) { Shape src = ShapeUtil::MakeTupleShape( {MakeShapeWithLayout(F32, {2, 3}, {0, 1}), MakeShapeWithLayout(F32, {42, 123}, {1, 0}), ShapeUtil::MakeTokenShape(), ShapeUtil::MakeTupleShape( {ShapeUtil::MakeOpaqueShape(), MakeShapeWithLayout(F32, {}, {}), MakeShapeWithLayout(F32, {1, 2, 3}, {0, 2, 1})})}); Shape dst = ShapeUtil::MakeTupleShape( {MakeShapeWithLayout(F32, {2, 3}, {1, 0}), MakeShapeWithLayout(F32, {42, 123}, {1, 0}), ShapeUtil::MakeTokenShape(), ShapeUtil::MakeTupleShape( {ShapeUtil::MakeOpaqueShape(), MakeShapeWithLayout(F32, {}, {}), MakeShapeWithLayout(F32, {1, 2, 3}, {1, 2, 0})})}); EXPECT_FALSE(LayoutUtil::LayoutsInShapesEqual(src, dst)); EXPECT_IS_OK(LayoutUtil::CopyLayoutBetweenShapes(src, &dst)); EXPECT_TRUE(LayoutUtil::LayoutsInShapesEqual(src, dst)); } TEST_F(LayoutUtilTest, ClearLayoutTuple) { Shape shape = ShapeUtil::MakeTupleShape( {MakeShapeWithLayout(F32, {2, 3}, {1, 0}), MakeShapeWithLayout(F32, {42, 123}, {1, 0}), ShapeUtil::MakeTupleShape( {MakeShapeWithLayout(F32, {}, {}), MakeShapeWithLayout(F32, {1, 2, 3}, {1, 2, 0})})}); EXPECT_TRUE(LayoutUtil::HasLayout(shape)); EXPECT_TRUE(shape.tuple_shapes(0).has_layout()); EXPECT_TRUE(shape.tuple_shapes(2).tuple_shapes(1).has_layout()); LayoutUtil::ClearLayout(&shape); EXPECT_FALSE(LayoutUtil::HasLayout(shape)); EXPECT_FALSE(shape.tuple_shapes(0).has_layout()); EXPECT_FALSE(shape.tuple_shapes(2).tuple_shapes(1).has_layout()); } TEST_F(LayoutUtilTest, ClearLayoutOpaqueAndToken) { for (Shape shape : {ShapeUtil::MakeOpaqueShape(), ShapeUtil::MakeTokenShape()}) { EXPECT_TRUE(LayoutUtil::HasLayout(shape)); LayoutUtil::ClearLayout(&shape); EXPECT_TRUE(LayoutUtil::HasLayout(shape)); } } TEST_F(LayoutUtilTest, SetToDefaultLayoutTuple) { Shape shape = ShapeUtil::MakeTupleShape( {MakeShapeWithLayout(F32, {2, 3, 4}, {1, 0, 2}), MakeShapeWithLayout(F32, {42, 123, 7}, {1, 2, 0}), ShapeUtil::MakeTupleShape( {MakeShapeWithLayout(F32, {}, {}), MakeShapeWithLayout(F32, {1, 2, 3, 4}, {3, 1, 2, 0})})}); EXPECT_FALSE(LayoutUtil::Equal(shape.tuple_shapes(0).layout(), shape.tuple_shapes(1).layout())); LayoutUtil::SetToDefaultLayout(&shape); EXPECT_TRUE(LayoutUtil::Equal(shape.tuple_shapes(0).layout(), shape.tuple_shapes(1).layout())); EXPECT_TRUE(LayoutUtil::Equal( LayoutUtil::GetDefaultLayoutForShape(shape.tuple_shapes(0)), shape.tuple_shapes(1).layout())); } TEST_F(LayoutUtilTest, DefaultLayoutGettersMajorToMinor) { EXPECT_TRUE(LayoutUtil::Equal(LayoutUtil::MakeLayout({1, 0}), LayoutUtil::GetDefaultLayoutForR2())); EXPECT_TRUE(LayoutUtil::Equal(LayoutUtil::MakeLayout({2, 1, 0}), LayoutUtil::GetDefaultLayoutForR3())); EXPECT_TRUE(LayoutUtil::Equal(LayoutUtil::MakeLayout({3, 2, 1, 0}), LayoutUtil::GetDefaultLayoutForR4())); EXPECT_TRUE( LayoutUtil::Equal(LayoutUtil::MakeLayout({4, 3, 2, 1, 0}), LayoutUtil::GetDefaultLayoutForShape( ShapeUtil::MakeShape(F32, {10, 20, 30, 15, 25})))); } TEST_F(LayoutUtilTest, MakeDescending) { EXPECT_TRUE(LayoutUtil::Equal(LayoutUtil::MakeDescendingLayout(5), LayoutUtil::MakeLayout({4, 3, 2, 1, 0}))); EXPECT_TRUE(LayoutUtil::Equal(LayoutUtil::MakeDescendingLayout(1), LayoutUtil::MakeLayout({0}))); EXPECT_TRUE(LayoutUtil::Equal(LayoutUtil::MakeDescendingLayout(0), LayoutUtil::MakeLayout({}))); } TEST_F(LayoutUtilTest, MakeAscending) { EXPECT_TRUE(LayoutUtil::Equal(LayoutUtil::MakeAscendingLayout(5), LayoutUtil::MakeLayout({0, 1, 2, 3, 4}))); EXPECT_TRUE(LayoutUtil::Equal(LayoutUtil::MakeAscendingLayout(1), LayoutUtil::MakeLayout({0}))); EXPECT_TRUE(LayoutUtil::Equal(LayoutUtil::MakeAscendingLayout(0), LayoutUtil::MakeLayout({}))); } TEST_F(LayoutUtilTest, HumanStringWithTiling) { Shape shape = ShapeUtil::MakeShapeWithDenseLayout(F32, {2, 3, 4}, {0, 1, 2}); Tile* tile; EXPECT_EQ(ShapeUtil::HumanStringWithLayout(shape), "f32[2,3,4]{0,1,2}"); tile = shape.mutable_layout()->add_tiles(); tile->add_dimensions(512); tile->add_dimensions(1024); EXPECT_EQ(ShapeUtil::HumanStringWithLayout(shape), "f32[2,3,4]{0,1,2:T(512,1024)}"); shape.mutable_layout()->clear_tiles(); tile = shape.mutable_layout()->add_tiles(); tile->add_dimensions(512); EXPECT_EQ(ShapeUtil::HumanStringWithLayout(shape), "f32[2,3,4]{0,1,2:T(512)}"); shape = ShapeUtil::MakeShapeWithDenseLayout(BF16, {2, 3, 4}, {1, 2, 0}); tile = shape.mutable_layout()->add_tiles(); tile->add_dimensions(16); tile->add_dimensions(256); tile = shape.mutable_layout()->add_tiles(); tile->add_dimensions(2); tile->add_dimensions(1); EXPECT_EQ(ShapeUtil::HumanStringWithLayout(shape), "bf16[2,3,4]{1,2,0:T(16,256)(2,1)}"); shape = ShapeUtil::MakeShapeWithDenseLayout(PRED, {8, 8, 8}, {0, 2, 1}); tile = shape.mutable_layout()->add_tiles(); tile->add_dimensions(8); tile->add_dimensions(128); EXPECT_EQ(ShapeUtil::HumanStringWithLayout(shape), "pred[8,8,8]{0,2,1:T(8,128)}"); shape.mutable_layout()->clear_tiles(); tile = shape.mutable_layout()->add_tiles(); tile->add_dimensions(8); tile->add_dimensions(128); shape.mutable_layout()->set_element_size_in_bits(32); EXPECT_EQ(ShapeUtil::HumanStringWithLayout(shape), "pred[8,8,8]{0,2,1:T(8,128)E(32)}"); shape.mutable_layout()->clear_tiles(); shape.mutable_layout()->set_element_size_in_bits(32); EXPECT_EQ(ShapeUtil::HumanStringWithLayout(shape), "pred[8,8,8]{0,2,1:E(32)}"); shape = ShapeUtil::MakeShapeWithDenseLayout(BF16, {2, 3, 1004}, {2, 1, 0}); tile = shape.mutable_layout()->add_tiles(); tile->add_dimensions(2); tile->add_dimensions(Tile::kCombineDimension); tile->add_dimensions(128); EXPECT_EQ(ShapeUtil::HumanStringWithLayout(shape), "bf16[2,3,1004]{2,1,0:T(2,*,128)}"); shape = ShapeUtil::MakeShapeWithDenseLayout(BF16, {8, 2, 3, 1004}, {3, 2, 1, 0}); tile = shape.mutable_layout()->add_tiles(); tile->add_dimensions(2); tile->add_dimensions(Tile::kCombineDimension); tile->add_dimensions(Tile::kCombineDimension); tile->add_dimensions(128); EXPECT_EQ(ShapeUtil::HumanStringWithLayout(shape), "bf16[8,2,3,1004]{3,2,1,0:T(2,*,*,128)}"); } TEST_F(LayoutUtilTest, ValidateLayout_ValidArrayLayout) { Shape shape = ShapeUtil::MakeShapeWithDenseLayout(F32, {2, 3}, {0, 1}); auto status = LayoutUtil::ValidateLayoutInShape(shape, false); EXPECT_TRUE(status.ok()); status = LayoutUtil::ValidateLayoutInShape(shape, true); EXPECT_TRUE(status.ok()); } TEST_F(LayoutUtilTest, ValidateLayout_InvalidArrayLayout) { Shape shape = ShapeUtil::MakeShape(F32, {2, 3}); *shape.mutable_layout() = LayoutUtil::MakeLayout({0, 1, 2}); auto status = LayoutUtil::ValidateLayoutInShape(shape, false); EXPECT_FALSE(status.ok()); EXPECT_THAT(status.message(), ::testing::HasSubstr("layout minor_to_major field " "contains 3 elements, but shape is rank 2")); status = LayoutUtil::ValidateLayoutInShape(shape, true); EXPECT_FALSE(status.ok()); EXPECT_THAT(status.message(), ::testing::HasSubstr("layout minor_to_major field " "contains 3 elements, but shape is rank 2")); } TEST_F(LayoutUtilTest, ValidateLayout_InvalidDimLevelTypes) { Shape shape = ShapeUtil::MakeShape(F32, {2, 3}); *shape.mutable_layout() = LayoutUtil::MakeLayout({0, 1}); shape.mutable_layout()->add_dim_level_type(DIM_DENSE); shape.mutable_layout()->add_dim_level_type(DIM_DENSE); shape.mutable_layout()->add_dim_level_type(DIM_DENSE); auto status = LayoutUtil::ValidateLayoutInShape(shape, false); EXPECT_FALSE(status.ok()); EXPECT_THAT(status.message(), ::testing::HasSubstr("layout dim_level_types field " "contains 3 elements, but shape is rank 2")); status = LayoutUtil::ValidateLayoutInShape(shape, true); EXPECT_FALSE(status.ok()); EXPECT_THAT(status.message(), ::testing::HasSubstr("layout dim_level_types field " "contains 3 elements, but shape is rank 2")); } TEST_F(LayoutUtilTest, ValidateLayout_MissingArrayLayout) { Shape shape = ShapeUtil::MakeShape(F32, {2, 3}); LayoutUtil::ClearLayout(&shape); auto status = LayoutUtil::ValidateLayoutInShape(shape, false); EXPECT_FALSE(status.ok()); EXPECT_THAT(status.message(), ::testing::HasSubstr("shape f32[2,3] does not have a layout")); status = LayoutUtil::ValidateLayoutInShape(shape, true); EXPECT_TRUE(status.ok()); } TEST_F(LayoutUtilTest, ValidateLayout_Sparse) { Shape shape = ShapeUtil::MakeShape(F32, {2, 3}); *shape.mutable_layout() = LayoutUtil::MakeLayout( {1, 0}, {DIM_DENSE, DIM_COMPRESSED}, {}, {}, {Tile({10, 10})}); EXPECT_THAT(LayoutUtil::ValidateLayoutInShape(shape), tsl::testing::StatusIs( tsl::error::INVALID_ARGUMENT, ::testing::HasSubstr( "layout has tiles, but the shape is a sparse array"))); shape.mutable_layout()->clear_tiles(); EXPECT_THAT(LayoutUtil::ValidateLayoutInShape(shape), tsl::testing::IsOk()); *shape.mutable_layout()->mutable_physical_shape() = ShapeUtil::MakeShape(F32, {6}); EXPECT_THAT(LayoutUtil::ValidateLayoutInShape(shape), tsl::testing::IsOk()); *shape.mutable_layout() ->mutable_physical_shape() ->mutable_layout() ->mutable_physical_shape() = ShapeUtil::MakeShape(S32, {10}); EXPECT_THAT( LayoutUtil::ValidateLayoutInShape(shape), tsl::testing::StatusIs( tsl::error::INVALID_ARGUMENT, ::testing::HasSubstr( "layout has a physical_shape, but is not a sparse array"))); shape.mutable_layout()->mutable_physical_shape()->clear_layout(); shape.mutable_layout()->clear_dim_level_types(); EXPECT_THAT( LayoutUtil::ValidateLayoutInShape(shape), tsl::testing::StatusIs( tsl::error::INVALID_ARGUMENT, ::testing::HasSubstr( "layout has a physical_shape, but is not a sparse array"))); *shape.mutable_layout() = LayoutUtil::MakeLayout({1, 0}, {DIM_DENSE, DIM_DENSE}, {true, false}); EXPECT_THAT(LayoutUtil::ValidateLayoutInShape(shape), tsl::testing::StatusIs( tsl::error::INVALID_ARGUMENT, ::testing::HasSubstr("layout dimension 1 has invalid level " "encoding DIM_DENSE, non-unique"))); } TEST_F(LayoutUtilTest, ValidateLayout_TupleSubshapesWithMissingLayouts) { Shape sub_1_1_1 = ShapeUtil::MakeShape(F32, {1, 2}); Shape sub_1_1 = ShapeUtil::MakeTupleShape({sub_1_1_1}); Shape sub_1_2 = ShapeUtil::MakeShape(F32, {1, 2}); LayoutUtil::ClearLayout(&sub_1_2); Shape sub_1 = ShapeUtil::MakeTupleShape({sub_1_1, sub_1_2}); Shape sub_2_1 = ShapeUtil::MakeShape(F32, {9}); LayoutUtil::ClearLayout(&sub_2_1); Shape sub_2 = ShapeUtil::MakeTupleShape({sub_2_1}); Shape shape = ShapeUtil::MakeTupleShape({sub_1, sub_2}); auto status = LayoutUtil::ValidateLayoutInShape(shape, false); EXPECT_FALSE(status.ok()); EXPECT_THAT(status.message(), ::testing::HasSubstr("shape f32[1,2] does not have a layout")); status = LayoutUtil::ValidateLayoutInShape(shape, true); EXPECT_TRUE(status.ok()); *shape.mutable_tuple_shapes(1)->mutable_tuple_shapes(0)->mutable_layout() = LayoutUtil::MakeLayout({0, 2, 3}); status = LayoutUtil::ValidateLayoutInShape(shape, true); EXPECT_FALSE(status.ok()); EXPECT_THAT(status.message(), ::testing::HasSubstr("layout minor_to_major field " "contains 3 elements, but shape is rank 1")); } TEST_F(LayoutUtilTest, MoveDimToMajor) { const Layout layout = LayoutUtil::MakeLayout({2, 1, 0}); Layout new_layout = LayoutUtil::MoveDimToMajor(layout, 0); EXPECT_EQ(new_layout, layout); new_layout = LayoutUtil::MoveDimToMajor(layout, 1); EXPECT_EQ(new_layout, LayoutUtil::MakeLayout({2, 0, 1})); } TEST_F(LayoutUtilTest, StridesIsMajorToMinor) { std::vector<int64_t> byte_strides = {3960, 440, 44, 4}; EXPECT_TRUE(LayoutUtil::ByteStridesIsMajorToMinor( byte_strides, {8, 9, 10, 11}, PrimitiveType::F32)); } TEST_F(LayoutUtilTest, StridesNotMajorToMinorInnerMostStrideIncorrect) { std::vector<int64_t> byte_strides = {1880, 220, 22, 2}; EXPECT_FALSE(LayoutUtil::ByteStridesIsMajorToMinor( byte_strides, {8, 9, 10, 11}, PrimitiveType::F32)); } TEST_F(LayoutUtilTest, StridesNotMajorToMinor) { std::vector<int64_t> byte_strides = {1880, 440, 44, 4}; EXPECT_FALSE(LayoutUtil::ByteStridesIsMajorToMinor( byte_strides, {8, 9, 10, 11}, PrimitiveType::F32)); } TEST_F(LayoutUtilTest, HasCustomElementSizeInBits) { Shape shape = ShapeUtil::MakeShape(F32, {1, 2}); EXPECT_FALSE(LayoutUtil::HasCustomElementSizeInBits(shape)); shape = ShapeUtil::MakeShape(F32, {1, 2}); shape.mutable_layout()->set_element_size_in_bits(0); EXPECT_FALSE(LayoutUtil::HasCustomElementSizeInBits(shape)); shape = ShapeUtil::MakeShape(F32, {1, 2}); shape.mutable_layout()->set_element_size_in_bits(32); EXPECT_TRUE(LayoutUtil::HasCustomElementSizeInBits(shape)); shape = ShapeUtil::MakeTupleShape( {ShapeUtil::MakeTupleShape({ShapeUtil::MakeShape(F32, {1, 2}), ShapeUtil::MakeShape(F32, {1, 2})}), ShapeUtil::MakeShape(F32, {1, 2})}); EXPECT_FALSE(LayoutUtil::HasCustomElementSizeInBits(shape)); shape = ShapeUtil::MakeTupleShape( {ShapeUtil::MakeTupleShape({ShapeUtil::MakeShape(F32, {1, 2}), ShapeUtil::MakeShape(F32, {1, 2})}), ShapeUtil::MakeShape(F32, {1, 2})}); ShapeUtil::GetMutableSubshape(&shape, {0, 1}) ->mutable_layout() ->set_element_size_in_bits(32); EXPECT_TRUE(LayoutUtil::HasCustomElementSizeInBits(shape)); } TEST_F(LayoutUtilTest, MaxSplitSize) { Shape shape = ShapeUtil::MakeShape(F32, {150, 200, 100}); *shape.mutable_layout() = LayoutUtil::MakeLayout({0, 1, 2}) .add_split_configs(SplitConfig(0, {30})) .add_split_configs(SplitConfig(1, {40, 130})); EXPECT_EQ(LayoutUtil::MaxSplitSize(shape, 0), 150); EXPECT_EQ(LayoutUtil::MaxSplitSize(shape, 1), 90); EXPECT_EQ(LayoutUtil::MaxSplitSize(shape, 2), 70); } TEST_F(LayoutUtilTest, MaxElementsInPerSplit) { Shape shape = ShapeUtil::MakeShape(F32, {150, 200, 100}); *shape.mutable_layout() = LayoutUtil::MakeLayout({0, 1, 2}); EXPECT_EQ(LayoutUtil::MaxElementsInPerSplit(shape), 150 * 200 * 100); *shape.mutable_layout() = LayoutUtil::MakeLayout({0, 1, 2}) .add_split_configs(SplitConfig(0, {30})) .add_split_configs(SplitConfig(1, {40, 130})); EXPECT_EQ(LayoutUtil::MaxElementsInPerSplit(shape), 150 * 90 * 70); } } }
https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/tensorflow/compiler/tf2xla/layout_util.cc
https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/third_party/xla/xla/layout_util_test.cc
4a29233a7b7c1a3a4294e4ccdd1772f9083944ea
29a2a2be-c9b2-4451-bd94-deb8b9faf4a1
cpp
tensorflow/tensorflow
primitive_util
third_party/xla/xla/primitive_util.cc
third_party/xla/xla/primitive_util_test.cc
#include "xla/primitive_util.h" #include <cstdint> #include <limits> #include <string> #include "absl/base/optimization.h" #include "absl/container/flat_hash_map.h" #include "absl/strings/ascii.h" #include "absl/strings/string_view.h" #include "xla/types.h" #include "xla/util.h" #include "xla/xla_data.pb.h" #include "tsl/platform/logging.h" namespace xla { namespace primitive_util { int SignificandWidth(PrimitiveType type) { return FloatingPointTypeSwitch<int>( [&](auto constant_type) -> int { return std::numeric_limits<NativeTypeOf<constant_type>>::digits; }, type); } int ExponentWidth(PrimitiveType type) { int total_bit_width = BitWidth(type); int trailing_significand_field_width = SignificandWidth(type) - 1; int kSignBitWidth = 1; return total_bit_width - (trailing_significand_field_width + kSignBitWidth); } int UnderflowExponent(PrimitiveType type) { return FloatingPointTypeSwitch<int>( [&](auto constant_type) -> int { return std::numeric_limits<NativeTypeOf<constant_type>>::min_exponent; }, type); } int OverflowExponent(PrimitiveType type) { return FloatingPointTypeSwitch<int>( [&](auto constant_type) -> int { return std::numeric_limits<NativeTypeOf<constant_type>>::max_exponent; }, type); } int ExponentBias(PrimitiveType type) { return (1 - UnderflowExponent(type)) + 1; } bool HasInfinity(PrimitiveType type) { if (ABSL_PREDICT_TRUE(IsFloatingPointType(type))) { return FloatingPointTypeSwitch<bool>( [&](auto constant_type) -> bool { return std::numeric_limits<NativeTypeOf<constant_type>>::has_infinity; }, type); } return false; } bool HasNegativeZero(PrimitiveType type) { if (ABSL_PREDICT_TRUE(IsFloatingPointType(type))) { return FloatingPointTypeSwitch<bool>( [&](auto constant_type) -> bool { return has_negative_zero_v<NativeTypeOf<constant_type>>; }, type); } return false; } xla::PrimitiveType SignedIntegralTypeForBitWidth(int64_t src_bitwidth) { switch (src_bitwidth) { case 2: return xla::S2; case 4: return xla::S4; case 8: return xla::S8; case 16: return xla::S16; case 32: return xla::S32; case 64: return xla::S64; default: return xla::PRIMITIVE_TYPE_INVALID; } } class PrimitiveTypeNameGenerator { public: PrimitiveTypeNameGenerator() { for (int i = 0; i < PrimitiveType_ARRAYSIZE; i++) { if (i == static_cast<int>(OPAQUE_TYPE)) { lowercase_name_[i] = "opaque"; } else if (PrimitiveType_IsValid(i)) { lowercase_name_[i] = absl::AsciiStrToLower( PrimitiveType_Name(static_cast<PrimitiveType>(i))); } } } const std::string& LowercaseName(PrimitiveType t) { CHECK_LT(t, PrimitiveType_ARRAYSIZE); return lowercase_name_[static_cast<int>(t)]; } private: std::string lowercase_name_[PrimitiveType_ARRAYSIZE]; }; const std::string& LowercasePrimitiveTypeName(PrimitiveType s) { static auto* gen = new PrimitiveTypeNameGenerator(); return gen->LowercaseName(s); } namespace { const absl::flat_hash_map<std::string, PrimitiveType>& GetPrimitiveTypeStringMap() { static absl::flat_hash_map<std::string, PrimitiveType>* name_to_type = [] { static auto* map = new absl::flat_hash_map<std::string, PrimitiveType>; for (int i = 0; i < PrimitiveType_ARRAYSIZE; i++) { if (PrimitiveType_IsValid(i) && i != PRIMITIVE_TYPE_INVALID) { auto value = static_cast<PrimitiveType>(i); (*map)[LowercasePrimitiveTypeName(value)] = value; } } (*map)["opaque"] = OPAQUE_TYPE; return map; }(); return *name_to_type; } } absl::StatusOr<PrimitiveType> StringToPrimitiveType(absl::string_view name) { const auto& map = GetPrimitiveTypeStringMap(); auto found = map.find(name); if (found == map.end()) { return InvalidArgument("Invalid element type string: \"%s\".", name); } return found->second; } bool IsPrimitiveTypeName(absl::string_view name) { const auto& map = GetPrimitiveTypeStringMap(); auto found = map.find(name); return found != map.end(); } } }
#include "xla/primitive_util.h" #include <numeric> #include <string> #include "xla/test.h" #include "xla/test_helpers.h" #include "xla/xla_data.pb.h" #include "tsl/platform/statusor.h" namespace xla { namespace { TEST(PrimitiveUtilTest, StringToPrimitiveType) { auto expect_ok_and_equal = [](const std::string& str, PrimitiveType expected) { TF_ASSERT_OK_AND_ASSIGN(PrimitiveType actual, primitive_util::StringToPrimitiveType(str)); EXPECT_EQ(expected, actual); }; expect_ok_and_equal("f32", F32); expect_ok_and_equal("tuple", TUPLE); expect_ok_and_equal("pred", PRED); expect_ok_and_equal("s32", S32); EXPECT_IS_NOT_OK(primitive_util::StringToPrimitiveType("F32").status()); EXPECT_IS_NOT_OK(primitive_util::StringToPrimitiveType("Pred").status()); EXPECT_IS_NOT_OK(primitive_util::StringToPrimitiveType("preD").status()); } TEST(PrimitiveUtilTest, FloatTypes) { EXPECT_EQ(primitive_util::SignificandWidth(F32), 24); EXPECT_EQ(primitive_util::SignificandWidth(BF16), 8); EXPECT_EQ(primitive_util::ExponentWidth(F32), 8); EXPECT_EQ(primitive_util::ExponentWidth(BF16), 8); EXPECT_EQ(primitive_util::UnderflowExponent(F32), -125); EXPECT_EQ(primitive_util::UnderflowExponent(BF16), -125); EXPECT_EQ(primitive_util::OverflowExponent(F32), 128); EXPECT_EQ(primitive_util::OverflowExponent(BF16), 128); } TEST(PrimitiveUtilTest, CastPreservesValues) { bool expecteds[PrimitiveType_ARRAYSIZE][PrimitiveType_ARRAYSIZE]; expecteds[PRED][PRED] = true; expecteds[PRED][S2] = true; expecteds[PRED][S4] = true; expecteds[PRED][S8] = true; expecteds[PRED][S16] = true; expecteds[PRED][S32] = true; expecteds[PRED][S64] = true; expecteds[PRED][U2] = true; expecteds[PRED][U4] = true; expecteds[PRED][U8] = true; expecteds[PRED][U16] = true; expecteds[PRED][U32] = true; expecteds[PRED][U64] = true; expecteds[PRED][F16] = true; expecteds[PRED][F32] = true; expecteds[PRED][F64] = true; expecteds[PRED][C64] = true; expecteds[PRED][BF16] = true; expecteds[PRED][C128] = true; expecteds[PRED][F8E5M2] = true; expecteds[PRED][F8E4M3] = true; expecteds[PRED][F8E4M3FN] = true; expecteds[PRED][F8E4M3B11FNUZ] = true; expecteds[PRED][F8E5M2FNUZ] = true; expecteds[PRED][F8E4M3FNUZ] = true; expecteds[PRED][F8E3M4] = true; expecteds[S2][PRED] = false; expecteds[S2][S2] = true; expecteds[S2][S4] = true; expecteds[S2][S8] = true; expecteds[S2][S16] = true; expecteds[S2][S32] = true; expecteds[S2][S64] = true; expecteds[S2][U2] = false; expecteds[S2][U4] = false; expecteds[S2][U8] = false; expecteds[S2][U16] = false; expecteds[S2][U32] = false; expecteds[S2][U64] = false; expecteds[S2][F16] = true; expecteds[S2][F32] = true; expecteds[S2][F64] = true; expecteds[S2][C64] = true; expecteds[S2][BF16] = true; expecteds[S2][C128] = true; expecteds[S2][F8E5M2] = true; expecteds[S2][F8E4M3] = true; expecteds[S2][F8E4M3FN] = true; expecteds[S2][F8E4M3B11FNUZ] = true; expecteds[S2][F8E5M2FNUZ] = true; expecteds[S2][F8E4M3FNUZ] = true; expecteds[S2][F8E3M4] = true; expecteds[S4][PRED] = false; expecteds[S4][S2] = false; expecteds[S4][S4] = true; expecteds[S4][S8] = true; expecteds[S4][S16] = true; expecteds[S4][S32] = true; expecteds[S4][S64] = true; expecteds[S4][U2] = false; expecteds[S4][U4] = false; expecteds[S4][U8] = false; expecteds[S4][U16] = false; expecteds[S4][U32] = false; expecteds[S4][U64] = false; expecteds[S4][F16] = true; expecteds[S4][F32] = true; expecteds[S4][F64] = true; expecteds[S4][C64] = true; expecteds[S4][BF16] = true; expecteds[S4][C128] = true; expecteds[S4][F8E5M2] = true; expecteds[S4][F8E4M3] = true; expecteds[S4][F8E4M3FN] = true; expecteds[S4][F8E4M3B11FNUZ] = true; expecteds[S4][F8E5M2FNUZ] = true; expecteds[S4][F8E4M3FNUZ] = true; expecteds[S4][F8E3M4] = true; expecteds[S8][PRED] = false; expecteds[S8][S2] = false; expecteds[S8][S4] = false; expecteds[S8][S8] = true; expecteds[S8][S16] = true; expecteds[S8][S32] = true; expecteds[S8][S64] = true; expecteds[S8][U2] = false; expecteds[S8][U4] = false; expecteds[S8][U8] = false; expecteds[S8][U16] = false; expecteds[S8][U32] = false; expecteds[S8][U64] = false; expecteds[S8][F16] = true; expecteds[S8][F32] = true; expecteds[S8][F64] = true; expecteds[S8][C64] = true; expecteds[S8][BF16] = true; expecteds[S8][C128] = true; expecteds[S8][F8E5M2] = false; expecteds[S8][F8E4M3] = false; expecteds[S8][F8E4M3FN] = false; expecteds[S8][F8E4M3B11FNUZ] = false; expecteds[S8][F8E5M2FNUZ] = false; expecteds[S8][F8E4M3FNUZ] = false; expecteds[S8][F8E3M4] = false; expecteds[S16][PRED] = false; expecteds[S16][S2] = false; expecteds[S16][S4] = false; expecteds[S16][S8] = false; expecteds[S16][S16] = true; expecteds[S16][S32] = true; expecteds[S16][S64] = true; expecteds[S16][U2] = false; expecteds[S16][U4] = false; expecteds[S16][U8] = false; expecteds[S16][U16] = false; expecteds[S16][U32] = false; expecteds[S16][U64] = false; expecteds[S16][F16] = false; expecteds[S16][F32] = true; expecteds[S16][F64] = true; expecteds[S16][C64] = true; expecteds[S16][BF16] = false; expecteds[S16][C128] = true; expecteds[S16][F8E5M2] = false; expecteds[S16][F8E4M3] = false; expecteds[S16][F8E4M3FN] = false; expecteds[S16][F8E4M3B11FNUZ] = false; expecteds[S16][F8E5M2FNUZ] = false; expecteds[S16][F8E4M3FNUZ] = false; expecteds[S16][F8E3M4] = false; expecteds[S32][PRED] = false; expecteds[S32][S2] = false; expecteds[S32][S4] = false; expecteds[S32][S8] = false; expecteds[S32][S16] = false; expecteds[S32][S32] = true; expecteds[S32][S64] = true; expecteds[S32][U2] = false; expecteds[S32][U4] = false; expecteds[S32][U8] = false; expecteds[S32][U16] = false; expecteds[S32][U32] = false; expecteds[S32][U64] = false; expecteds[S32][F16] = false; expecteds[S32][F32] = false; expecteds[S32][F64] = true; expecteds[S32][C64] = false; expecteds[S32][BF16] = false; expecteds[S32][C128] = true; expecteds[S32][F8E5M2] = false; expecteds[S32][F8E4M3] = false; expecteds[S32][F8E4M3FN] = false; expecteds[S32][F8E4M3B11FNUZ] = false; expecteds[S32][F8E5M2FNUZ] = false; expecteds[S32][F8E4M3FNUZ] = false; expecteds[S32][F8E3M4] = false; expecteds[S64][PRED] = false; expecteds[S64][S2] = false; expecteds[S64][S4] = false; expecteds[S64][S8] = false; expecteds[S64][S16] = false; expecteds[S64][S32] = false; expecteds[S64][S64] = true; expecteds[S64][U2] = false; expecteds[S64][U4] = false; expecteds[S64][U8] = false; expecteds[S64][U16] = false; expecteds[S64][U32] = false; expecteds[S64][U64] = false; expecteds[S64][F16] = false; expecteds[S64][F32] = false; expecteds[S64][F64] = false; expecteds[S64][C64] = false; expecteds[S64][BF16] = false; expecteds[S64][C128] = false; expecteds[S64][F8E5M2] = false; expecteds[S64][F8E4M3] = false; expecteds[S64][F8E4M3FN] = false; expecteds[S64][F8E4M3B11FNUZ] = false; expecteds[S64][F8E5M2FNUZ] = false; expecteds[S64][F8E4M3FNUZ] = false; expecteds[S64][F8E3M4] = false; expecteds[U2][PRED] = false; expecteds[U2][S2] = false; expecteds[U2][S4] = true; expecteds[U2][S8] = true; expecteds[U2][S16] = true; expecteds[U2][S32] = true; expecteds[U2][S64] = true; expecteds[U2][U2] = true; expecteds[U2][U4] = true; expecteds[U2][U8] = true; expecteds[U2][U16] = true; expecteds[U2][U32] = true; expecteds[U2][U64] = true; expecteds[U2][F16] = true; expecteds[U2][F32] = true; expecteds[U2][F64] = true; expecteds[U2][C64] = true; expecteds[U2][BF16] = true; expecteds[U2][C128] = true; expecteds[U2][BF16] = true; expecteds[U2][C128] = true; expecteds[U2][F8E5M2] = true; expecteds[U2][F8E4M3] = true; expecteds[U2][F8E4M3FN] = true; expecteds[U2][F8E4M3B11FNUZ] = true; expecteds[U2][F8E5M2FNUZ] = true; expecteds[U2][F8E4M3FNUZ] = true; expecteds[U2][F8E3M4] = true; expecteds[U4][PRED] = false; expecteds[U4][S2] = false; expecteds[U4][S4] = false; expecteds[U4][S8] = true; expecteds[U4][S16] = true; expecteds[U4][S32] = true; expecteds[U4][S64] = true; expecteds[U4][U2] = false; expecteds[U4][U4] = true; expecteds[U4][U8] = true; expecteds[U4][U16] = true; expecteds[U4][U32] = true; expecteds[U4][U64] = true; expecteds[U4][F16] = true; expecteds[U4][F32] = true; expecteds[U4][F64] = true; expecteds[U4][C64] = true; expecteds[U4][BF16] = true; expecteds[U4][C128] = true; expecteds[U4][BF16] = true; expecteds[U4][C128] = true; expecteds[U4][F8E5M2] = false; expecteds[U4][F8E4M3] = true; expecteds[U4][F8E4M3FN] = true; expecteds[U4][F8E4M3B11FNUZ] = true; expecteds[U4][F8E5M2FNUZ] = false; expecteds[U4][F8E4M3FNUZ] = true; expecteds[U4][F8E3M4] = true; expecteds[U8][PRED] = false; expecteds[U8][S2] = false; expecteds[U8][S4] = false; expecteds[U8][S8] = false; expecteds[U8][S16] = true; expecteds[U8][S32] = true; expecteds[U8][S64] = true; expecteds[U8][U2] = false; expecteds[U8][U4] = false; expecteds[U8][U8] = true; expecteds[U8][U16] = true; expecteds[U8][U32] = true; expecteds[U8][U64] = true; expecteds[U8][F16] = true; expecteds[U8][F32] = true; expecteds[U8][F64] = true; expecteds[U8][C64] = true; expecteds[U8][BF16] = true; expecteds[U8][C128] = true; expecteds[U8][BF16] = true; expecteds[U8][C128] = true; expecteds[U8][F8E5M2] = false; expecteds[U8][F8E4M3] = false; expecteds[U8][F8E4M3FN] = false; expecteds[U8][F8E4M3B11FNUZ] = false; expecteds[U8][F8E5M2FNUZ] = false; expecteds[U8][F8E4M3FNUZ] = false; expecteds[U8][F8E3M4] = false; expecteds[U16][PRED] = false; expecteds[U16][S2] = false; expecteds[U16][S4] = false; expecteds[U16][S8] = false; expecteds[U16][S16] = false; expecteds[U16][S32] = true; expecteds[U16][S64] = true; expecteds[U16][U2] = false; expecteds[U16][U4] = false; expecteds[U16][U8] = false; expecteds[U16][U16] = true; expecteds[U16][U32] = true; expecteds[U16][U64] = true; expecteds[U16][F16] = false; expecteds[U16][F32] = true; expecteds[U16][F64] = true; expecteds[U16][C64] = true; expecteds[U16][BF16] = false; expecteds[U16][C128] = true; expecteds[U16][F8E5M2] = false; expecteds[U16][F8E4M3] = false; expecteds[U16][F8E4M3FN] = false; expecteds[U16][F8E4M3B11FNUZ] = false; expecteds[U16][F8E5M2FNUZ] = false; expecteds[U16][F8E4M3FNUZ] = false; expecteds[U16][F8E3M4] = false; expecteds[U32][PRED] = false; expecteds[U32][S2] = false; expecteds[U32][S4] = false; expecteds[U32][S8] = false; expecteds[U32][S16] = false; expecteds[U32][S32] = false; expecteds[U32][S64] = true; expecteds[U32][U2] = false; expecteds[U32][U4] = false; expecteds[U32][U8] = false; expecteds[U32][U16] = false; expecteds[U32][U32] = true; expecteds[U32][U64] = true; expecteds[U32][F16] = false; expecteds[U32][F32] = false; expecteds[U32][F64] = true; expecteds[U32][C64] = false; expecteds[U32][BF16] = false; expecteds[U32][C128] = true; expecteds[U32][F8E5M2] = false; expecteds[U32][F8E4M3] = false; expecteds[U32][F8E4M3FN] = false; expecteds[U32][F8E4M3B11FNUZ] = false; expecteds[U32][F8E5M2FNUZ] = false; expecteds[U32][F8E4M3FNUZ] = false; expecteds[U32][F8E3M4] = false; expecteds[U64][PRED] = false; expecteds[U64][S2] = false; expecteds[U64][S4] = false; expecteds[U64][S8] = false; expecteds[U64][S16] = false; expecteds[U64][S32] = false; expecteds[U64][S64] = false; expecteds[U64][U2] = false; expecteds[U64][U4] = false; expecteds[U64][U8] = false; expecteds[U64][U16] = false; expecteds[U64][U32] = false; expecteds[U64][U64] = true; expecteds[U64][F16] = false; expecteds[U64][F32] = false; expecteds[U64][F64] = false; expecteds[U64][C64] = false; expecteds[U64][BF16] = false; expecteds[U64][C128] = false; expecteds[U64][F8E5M2] = false; expecteds[U64][F8E4M3] = false; expecteds[U64][F8E4M3FN] = false; expecteds[U64][F8E4M3B11FNUZ] = false; expecteds[U64][F8E5M2FNUZ] = false; expecteds[U64][F8E4M3FNUZ] = false; expecteds[U64][F8E3M4] = false; expecteds[F16][PRED] = false; expecteds[F16][S2] = false; expecteds[F16][S4] = false; expecteds[F16][S8] = false; expecteds[F16][S16] = false; expecteds[F16][S32] = false; expecteds[F16][S64] = false; expecteds[F16][U2] = false; expecteds[F16][U4] = false; expecteds[F16][U8] = false; expecteds[F16][U16] = false; expecteds[F16][U32] = false; expecteds[F16][U64] = false; expecteds[F16][F16] = true; expecteds[F16][F32] = true; expecteds[F16][F64] = true; expecteds[F16][C64] = true; expecteds[F16][BF16] = false; expecteds[F16][C128] = true; expecteds[F16][F8E5M2] = false; expecteds[F16][F8E4M3] = false; expecteds[F16][F8E4M3FN] = false; expecteds[F16][F8E4M3B11FNUZ] = false; expecteds[F16][F8E5M2FNUZ] = false; expecteds[F16][F8E4M3FNUZ] = false; expecteds[F16][F8E3M4] = false; expecteds[F32][PRED] = false; expecteds[F32][S2] = false; expecteds[F32][S4] = false; expecteds[F32][S8] = false; expecteds[F32][S16] = false; expecteds[F32][S32] = false; expecteds[F32][S64] = false; expecteds[F32][U2] = false; expecteds[F32][U4] = false; expecteds[F32][U8] = false; expecteds[F32][U16] = false; expecteds[F32][U32] = false; expecteds[F32][U64] = false; expecteds[F32][F16] = false; expecteds[F32][F32] = true; expecteds[F32][F64] = true; expecteds[F32][C64] = true; expecteds[F32][BF16] = false; expecteds[F32][C128] = true; expecteds[F32][F8E5M2] = false; expecteds[F32][F8E4M3] = false; expecteds[F32][F8E4M3FN] = false; expecteds[F32][F8E4M3B11FNUZ] = false; expecteds[F32][F8E5M2FNUZ] = false; expecteds[F32][F8E4M3FNUZ] = false; expecteds[F32][F8E3M4] = false; expecteds[F64][PRED] = false; expecteds[F64][S2] = false; expecteds[F64][S4] = false; expecteds[F64][S8] = false; expecteds[F64][S16] = false; expecteds[F64][S32] = false; expecteds[F64][S64] = false; expecteds[F64][U2] = false; expecteds[F64][U4] = false; expecteds[F64][U8] = false; expecteds[F64][U16] = false; expecteds[F64][U32] = false; expecteds[F64][U64] = false; expecteds[F64][F16] = false; expecteds[F64][F32] = false; expecteds[F64][F64] = true; expecteds[F64][C64] = false; expecteds[F64][BF16] = false; expecteds[F64][C128] = true; expecteds[F64][F8E5M2] = false; expecteds[F64][F8E4M3] = false; expecteds[F64][F8E4M3FN] = false; expecteds[F64][F8E4M3B11FNUZ] = false; expecteds[F64][F8E5M2FNUZ] = false; expecteds[F64][F8E4M3FNUZ] = false; expecteds[F64][F8E3M4] = false; expecteds[C64][PRED] = false; expecteds[C64][S2] = false; expecteds[C64][S4] = false; expecteds[C64][S8] = false; expecteds[C64][S16] = false; expecteds[C64][S32] = false; expecteds[C64][S64] = false; expecteds[C64][U2] = false; expecteds[C64][U4] = false; expecteds[C64][U8] = false; expecteds[C64][U16] = false; expecteds[C64][U32] = false; expecteds[C64][U64] = false; expecteds[C64][F16] = false; expecteds[C64][F32] = false; expecteds[C64][F64] = false; expecteds[C64][C64] = true; expecteds[C64][BF16] = false; expecteds[C64][C128] = true; expecteds[C64][F8E5M2] = false; expecteds[C64][F8E4M3] = false; expecteds[C64][F8E4M3FN] = false; expecteds[C64][F8E4M3B11FNUZ] = false; expecteds[C64][F8E5M2FNUZ] = false; expecteds[C64][F8E4M3FNUZ] = false; expecteds[C64][F8E3M4] = false; expecteds[BF16][PRED] = false; expecteds[BF16][S2] = false; expecteds[BF16][S4] = false; expecteds[BF16][S8] = false; expecteds[BF16][S16] = false; expecteds[BF16][S32] = false; expecteds[BF16][S64] = false; expecteds[BF16][U2] = false; expecteds[BF16][U4] = false; expecteds[BF16][U8] = false; expecteds[BF16][U16] = false; expecteds[BF16][U32] = false; expecteds[BF16][U64] = false; expecteds[BF16][F16] = false; expecteds[BF16][F32] = true; expecteds[BF16][F64] = true; expecteds[BF16][C64] = true; expecteds[BF16][BF16] = true; expecteds[BF16][C128] = true; expecteds[BF16][F8E5M2] = false; expecteds[BF16][F8E4M3] = false; expecteds[BF16][F8E4M3FN] = false; expecteds[BF16][F8E4M3B11FNUZ] = false; expecteds[BF16][F8E5M2FNUZ] = false; expecteds[BF16][F8E4M3FNUZ] = false; expecteds[BF16][F8E3M4] = false; expecteds[C128][PRED] = false; expecteds[C128][S2] = false; expecteds[C128][S4] = false; expecteds[C128][S8] = false; expecteds[C128][S16] = false; expecteds[C128][S32] = false; expecteds[C128][S64] = false; expecteds[C128][U2] = false; expecteds[C128][U4] = false; expecteds[C128][U8] = false; expecteds[C128][U16] = false; expecteds[C128][U32] = false; expecteds[C128][U64] = false; expecteds[C128][F16] = false; expecteds[C128][F32] = false; expecteds[C128][F64] = false; expecteds[C128][C64] = false; expecteds[C128][BF16] = false; expecteds[C128][C128] = true; expecteds[C128][F8E5M2] = false; expecteds[C128][F8E4M3] = false; expecteds[C128][F8E4M3FN] = false; expecteds[C128][F8E4M3B11FNUZ] = false; expecteds[C128][F8E5M2FNUZ] = false; expecteds[C128][F8E4M3FNUZ] = false; expecteds[C128][F8E3M4] = false; expecteds[F8E5M2][PRED] = false; expecteds[F8E5M2][S2] = false; expecteds[F8E5M2][S4] = false; expecteds[F8E5M2][S8] = false; expecteds[F8E5M2][S16] = false; expecteds[F8E5M2][S32] = false; expecteds[F8E5M2][S64] = false; expecteds[F8E5M2][U2] = false; expecteds[F8E5M2][U4] = false; expecteds[F8E5M2][U8] = false; expecteds[F8E5M2][U16] = false; expecteds[F8E5M2][U32] = false; expecteds[F8E5M2][U64] = false; expecteds[F8E5M2][F16] = true; expecteds[F8E5M2][F32] = true; expecteds[F8E5M2][F64] = true; expecteds[F8E5M2][C64] = true; expecteds[F8E5M2][BF16] = true; expecteds[F8E5M2][C128] = true; expecteds[F8E5M2][F8E5M2] = true; expecteds[F8E5M2][F8E4M3] = false; expecteds[F8E5M2][F8E4M3FN] = false; expecteds[F8E5M2][F8E4M3B11FNUZ] = false; expecteds[F8E5M2][F8E5M2FNUZ] = false; expecteds[F8E5M2][F8E4M3FNUZ] = false; expecteds[F8E5M2][F8E3M4] = false; expecteds[F8E4M3][PRED] = false; expecteds[F8E4M3][S2] = false; expecteds[F8E4M3][S4] = false; expecteds[F8E4M3][S8] = false; expecteds[F8E4M3][S16] = false; expecteds[F8E4M3][S32] = false; expecteds[F8E4M3][S64] = false; expecteds[F8E4M3][U2] = false; expecteds[F8E4M3][U4] = false; expecteds[F8E4M3][U8] = false; expecteds[F8E4M3][U16] = false; expecteds[F8E4M3][U32] = false; expecteds[F8E4M3][U64] = false; expecteds[F8E4M3][F16] = true; expecteds[F8E4M3][F32] = true; expecteds[F8E4M3][F64] = true; expecteds[F8E4M3][C64] = true; expecteds[F8E4M3][BF16] = true; expecteds[F8E4M3][C128] = true; expecteds[F8E4M3][F8E5M2] = false; expecteds[F8E4M3][F8E5M2FNUZ] = false; expecteds[F8E4M3][F8E4M3] = true; expecteds[F8E4M3][F8E4M3FN] = false; expecteds[F8E4M3][F8E4M3FNUZ] = false; expecteds[F8E4M3][F8E4M3B11FNUZ] = false; expecteds[F8E4M3][F8E3M4] = false; expecteds[F8E4M3FN][PRED] = false; expecteds[F8E4M3FN][S2] = false; expecteds[F8E4M3FN][S4] = false; expecteds[F8E4M3FN][S8] = false; expecteds[F8E4M3FN][S16] = false; expecteds[F8E4M3FN][S32] = false; expecteds[F8E4M3FN][S64] = false; expecteds[F8E4M3FN][U2] = false; expecteds[F8E4M3FN][U4] = false; expecteds[F8E4M3FN][U8] = false; expecteds[F8E4M3FN][U16] = false; expecteds[F8E4M3FN][U32] = false; expecteds[F8E4M3FN][U64] = false; expecteds[F8E4M3FN][F16] = true; expecteds[F8E4M3FN][F32] = true; expecteds[F8E4M3FN][F64] = true; expecteds[F8E4M3FN][C64] = true; expecteds[F8E4M3FN][BF16] = true; expecteds[F8E4M3FN][C128] = true; expecteds[F8E4M3FN][F8E5M2] = false; expecteds[F8E4M3FN][F8E5M2FNUZ] = false; expecteds[F8E4M3FN][F8E4M3] = false; expecteds[F8E4M3FN][F8E4M3FN] = true; expecteds[F8E4M3FN][F8E4M3FNUZ] = false; expecteds[F8E4M3FN][F8E4M3B11FNUZ] = false; expecteds[F8E4M3FN][F8E3M4] = false; expecteds[F8E4M3B11FNUZ][PRED] = false; expecteds[F8E4M3B11FNUZ][S2] = false; expecteds[F8E4M3B11FNUZ][S4] = false; expecteds[F8E4M3B11FNUZ][S8] = false; expecteds[F8E4M3B11FNUZ][S16] = false; expecteds[F8E4M3B11FNUZ][S32] = false; expecteds[F8E4M3B11FNUZ][S64] = false; expecteds[F8E4M3B11FNUZ][U2] = false; expecteds[F8E4M3B11FNUZ][U4] = false; expecteds[F8E4M3B11FNUZ][U8] = false; expecteds[F8E4M3B11FNUZ][U16] = false; expecteds[F8E4M3B11FNUZ][U32] = false; expecteds[F8E4M3B11FNUZ][U64] = false; expecteds[F8E4M3B11FNUZ][F16] = true; expecteds[F8E4M3B11FNUZ][F32] = true; expecteds[F8E4M3B11FNUZ][F64] = true; expecteds[F8E4M3B11FNUZ][C64] = true; expecteds[F8E4M3B11FNUZ][BF16] = true; expecteds[F8E4M3B11FNUZ][C128] = true; expecteds[F8E4M3B11FNUZ][F8E5M2] = false; expecteds[F8E4M3B11FNUZ][F8E4M3] = false; expecteds[F8E4M3B11FNUZ][F8E4M3FN] = false; expecteds[F8E4M3B11FNUZ][F8E4M3B11FNUZ] = true; expecteds[F8E4M3B11FNUZ][F8E4M3FNUZ] = false; expecteds[F8E4M3B11FNUZ][F8E5M2FNUZ] = false; expecteds[F8E4M3B11FNUZ][F8E3M4] = false; expecteds[F8E5M2FNUZ][PRED] = false; expecteds[F8E5M2FNUZ][S2] = false; expecteds[F8E5M2FNUZ][S4] = false; expecteds[F8E5M2FNUZ][S8] = false; expecteds[F8E5M2FNUZ][S16] = false; expecteds[F8E5M2FNUZ][S32] = false; expecteds[F8E5M2FNUZ][S64] = false; expecteds[F8E5M2FNUZ][U2] = false; expecteds[F8E5M2FNUZ][U4] = false; expecteds[F8E5M2FNUZ][U8] = false; expecteds[F8E5M2FNUZ][U16] = false; expecteds[F8E5M2FNUZ][U32] = false; expecteds[F8E5M2FNUZ][U64] = false; expecteds[F8E5M2FNUZ][F16] = true; expecteds[F8E5M2FNUZ][F32] = true; expecteds[F8E5M2FNUZ][F64] = true; expecteds[F8E5M2FNUZ][C64] = true; expecteds[F8E5M2FNUZ][BF16] = true; expecteds[F8E5M2FNUZ][C128] = true; expecteds[F8E5M2FNUZ][F8E5M2] = false; expecteds[F8E5M2FNUZ][F8E4M3] = false; expecteds[F8E5M2FNUZ][F8E4M3FN] = false; expecteds[F8E5M2FNUZ][F8E4M3B11FNUZ] = false; expecteds[F8E5M2FNUZ][F8E5M2FNUZ] = true; expecteds[F8E5M2FNUZ][F8E4M3FNUZ] = false; expecteds[F8E5M2FNUZ][F8E3M4] = false; expecteds[F8E4M3FNUZ][PRED] = false; expecteds[F8E4M3FNUZ][S2] = false; expecteds[F8E4M3FNUZ][S4] = false; expecteds[F8E4M3FNUZ][S8] = false; expecteds[F8E4M3FNUZ][S16] = false; expecteds[F8E4M3FNUZ][S32] = false; expecteds[F8E4M3FNUZ][S64] = false; expecteds[F8E4M3FNUZ][U2] = false; expecteds[F8E4M3FNUZ][U4] = false; expecteds[F8E4M3FNUZ][U8] = false; expecteds[F8E4M3FNUZ][U16] = false; expecteds[F8E4M3FNUZ][U32] = false; expecteds[F8E4M3FNUZ][U64] = false; expecteds[F8E4M3FNUZ][F16] = true; expecteds[F8E4M3FNUZ][F32] = true; expecteds[F8E4M3FNUZ][F64] = true; expecteds[F8E4M3FNUZ][C64] = true; expecteds[F8E4M3FNUZ][BF16] = true; expecteds[F8E4M3FNUZ][C128] = true; expecteds[F8E4M3FNUZ][F8E5M2] = false; expecteds[F8E4M3FNUZ][F8E4M3] = false; expecteds[F8E4M3FNUZ][F8E4M3FN] = false; expecteds[F8E4M3FNUZ][F8E4M3B11FNUZ] = false; expecteds[F8E4M3FNUZ][F8E5M2FNUZ] = false; expecteds[F8E4M3FNUZ][F8E4M3FNUZ] = true; expecteds[F8E4M3FNUZ][F8E3M4] = false; expecteds[F8E3M4][PRED] = false; expecteds[F8E3M4][S2] = false; expecteds[F8E3M4][S4] = false; expecteds[F8E3M4][S8] = false; expecteds[F8E3M4][S16] = false; expecteds[F8E3M4][S32] = false; expecteds[F8E3M4][S64] = false; expecteds[F8E3M4][U2] = false; expecteds[F8E3M4][U4] = false; expecteds[F8E3M4][U8] = false; expecteds[F8E3M4][U16] = false; expecteds[F8E3M4][U32] = false; expecteds[F8E3M4][U64] = false; expecteds[F8E3M4][F16] = true; expecteds[F8E3M4][F32] = true; expecteds[F8E3M4][F64] = true; expecteds[F8E3M4][C64] = true; expecteds[F8E3M4][BF16] = true; expecteds[F8E3M4][C128] = true; expecteds[F8E3M4][F8E5M2] = false; expecteds[F8E3M4][F8E5M2FNUZ] = false; expecteds[F8E3M4][F8E4M3] = false; expecteds[F8E3M4][F8E4M3FN] = false; expecteds[F8E3M4][F8E4M3FNUZ] = false; expecteds[F8E3M4][F8E4M3B11FNUZ] = false; expecteds[F8E3M4][F8E3M4] = true; for (int from_type_int = PrimitiveType_MIN; from_type_int < PrimitiveType_ARRAYSIZE; ++from_type_int) { auto from_type = static_cast<PrimitiveType>(from_type_int); if (!primitive_util::IsArrayType(from_type)) { continue; } for (int to_type_int = PrimitiveType_MIN; to_type_int < PrimitiveType_ARRAYSIZE; ++to_type_int) { auto to_type = static_cast<PrimitiveType>(to_type_int); if (!primitive_util::IsArrayType(to_type)) { continue; } bool expected = expecteds[from_type][to_type]; bool actual = primitive_util::CastPreservesValues(from_type, to_type); EXPECT_EQ(expected, actual) << primitive_util::LowercasePrimitiveTypeName(from_type) << " -> " << primitive_util::LowercasePrimitiveTypeName(to_type); } } } } }
https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/third_party/xla/xla/primitive_util.cc
https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/third_party/xla/xla/primitive_util_test.cc
4a29233a7b7c1a3a4294e4ccdd1772f9083944ea
b62725b6-4c18-4f34-9de3-eb4f8b23529e
cpp
tensorflow/tensorflow
parse_flags_from_env
third_party/xla/xla/parse_flags_from_env.cc
third_party/xla/xla/parse_flags_from_env_test.cc
#include "xla/parse_flags_from_env.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <memory> #include <string> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/strings/ascii.h" #include "absl/strings/str_format.h" #include "absl/strings/str_join.h" #include "absl/types/span.h" #include "xla/tsl/util/command_line_flags.h" #include "tsl/platform/logging.h" namespace xla { static const char kWS[] = " \t\r\n"; namespace { struct FreeDeleter { void operator()(char* ptr) { free(ptr); } }; struct EnvArgv { EnvArgv() : initialized(false), argc(0) {} bool initialized; int argc; std::vector<char*> argv; std::vector<std::unique_ptr<char, FreeDeleter>> argv_save; }; } static void AppendToEnvArgv(const char* s0, size_t s0len, const char* s1, size_t s1len, EnvArgv* a) { if (s0 == nullptr) { a->argv.push_back(nullptr); a->argv_save.push_back(nullptr); } else { std::string s = std::string(s0, s0len) + std::string(s1, s1len); char* str = strdup(s.c_str()); a->argv.push_back(str); a->argv_save.emplace_back(str); a->argc++; } } static size_t FindFirstOf(const std::string& s, const char* x, size_t pos) { size_t result = s.find_first_of(x, pos); return result == std::string::npos ? s.size() : result; } static size_t FindFirstNotOf(const std::string& s, const char* x, size_t pos) { size_t result = s.find_first_not_of(x, pos); return result == std::string::npos ? s.size() : result; } static void ParseArgvFromString(const std::string& flag_str, EnvArgv* a) { size_t b = FindFirstNotOf(flag_str, kWS, 0); while (b != flag_str.size() && flag_str[b] == '-') { size_t e = b; while (e != flag_str.size() && isascii(flag_str[e]) && (strchr("-_", flag_str[e]) != nullptr || absl::ascii_isalnum(flag_str[e]))) { e++; } if (e != flag_str.size() && flag_str[e] == '=' && e + 1 != flag_str.size() && strchr("'\"", flag_str[e + 1]) != nullptr) { int c; e++; size_t eflag = e; char quote = flag_str[e]; e++; std::string value; for (; e != flag_str.size() && (c = flag_str[e]) != quote; e++) { if (quote == '"' && c == '\\' && e + 1 != flag_str.size()) { e++; c = flag_str[e]; } value += c; } if (e != flag_str.size()) { e++; } AppendToEnvArgv(flag_str.data() + b, eflag - b, value.data(), value.size(), a); } else { e = FindFirstOf(flag_str, kWS, e); AppendToEnvArgv(flag_str.data() + b, e - b, "", 0, a); } b = FindFirstNotOf(flag_str, kWS, e); } } static void SetArgvFromEnv(absl::string_view envvar, EnvArgv* a) { if (!a->initialized) { static const char kDummyArgv[] = "<argv[0]>"; AppendToEnvArgv(kDummyArgv, strlen(kDummyArgv), nullptr, 0, a); const char* env = getenv(std::string(envvar).c_str()); if (env == nullptr || env[0] == '\0') { } else if (env[strspn(env, kWS)] == '-') { ParseArgvFromString(env, a); } else { FILE* fp = fopen(env, "r"); if (fp != nullptr) { std::string str; char buf[512]; int n; while ((n = fread(buf, 1, sizeof(buf), fp)) > 0) { str.append(buf, n); } fclose(fp); ParseArgvFromString(str, a); } else { LOG(QFATAL) << "Could not open file \"" << env << "\" to read flags for environment variable \"" << envvar << "\". (We assumed \"" << env << "\" was a file name because it did not start with a \"--\".)"; } } AppendToEnvArgv(nullptr, 0, nullptr, 0, a); a->initialized = true; } } static absl::flat_hash_map<std::string, EnvArgv>& EnvArgvs() { static auto* env_argvs = new absl::flat_hash_map<std::string, EnvArgv>(); return *env_argvs; } static absl::Mutex env_argv_mu(absl::kConstInit); static void DieIfEnvHasUnknownFlagsLeft(absl::string_view envvar); void ParseFlagsFromEnvAndDieIfUnknown(absl::string_view envvar, const std::vector<tsl::Flag>& flag_list) { ParseFlagsFromEnvAndIgnoreUnknown(envvar, flag_list); DieIfEnvHasUnknownFlagsLeft(envvar); } void ParseFlagsFromEnvAndIgnoreUnknown( absl::string_view envvar, const std::vector<tsl::Flag>& flag_list) { absl::MutexLock lock(&env_argv_mu); auto* env_argv = &EnvArgvs()[envvar]; SetArgvFromEnv(envvar, env_argv); if (VLOG_IS_ON(1)) { VLOG(1) << "For env var " << envvar << " found arguments:"; for (int i = 0; i < env_argv->argc; i++) { VLOG(1) << " argv[" << i << "] = " << env_argv->argv[i]; } } QCHECK(tsl::Flags::Parse(&env_argv->argc, env_argv->argv.data(), flag_list)) << "Flag parsing failed.\n" << tsl::Flags::Usage(getenv(std::string(envvar).c_str()), flag_list); } static void DieIfEnvHasUnknownFlagsLeft(absl::string_view envvar) { absl::MutexLock lock(&env_argv_mu); auto* env_argv = &EnvArgvs()[envvar]; SetArgvFromEnv(envvar, env_argv); if (env_argv->argc != 1) { auto unknown_flags = absl::MakeSpan(env_argv->argv); unknown_flags.remove_prefix(1); LOG(QFATAL) << "Unknown flag" << (unknown_flags.size() > 1 ? "s" : "") << " in " << envvar << ": " << absl::StrJoin(unknown_flags, " "); } } void ResetFlagsFromEnvForTesting(absl::string_view envvar, int** pargc, std::vector<char*>** pargv) { absl::MutexLock lock(&env_argv_mu); EnvArgvs().erase(envvar); auto& env_argv = EnvArgvs()[envvar]; *pargc = &env_argv.argc; *pargv = &env_argv.argv; } }
#include "xla/parse_flags_from_env.h" #include <stdio.h> #include <stdlib.h> #include <string> #include <vector> #include "absl/strings/str_format.h" #include "xla/tsl/util/command_line_flags.h" #include "tsl/platform/env.h" #include "tsl/platform/logging.h" #include "tsl/platform/subprocess.h" #include "tsl/platform/test.h" namespace xla { static void TestParseFlagsFromEnv(const char* msg) { int* pargc; std::vector<char*>* pargv; ResetFlagsFromEnvForTesting("TF_XLA_FLAGS", &pargc, &pargv); bool simple = false; std::string with_value; std::string embedded_quotes; std::string single_quoted; std::string double_quoted; std::vector<tsl::Flag> flag_list = { tsl::Flag("simple", &simple, ""), tsl::Flag("with_value", &with_value, ""), tsl::Flag("embedded_quotes", &embedded_quotes, ""), tsl::Flag("single_quoted", &single_quoted, ""), tsl::Flag("double_quoted", &double_quoted, ""), }; ParseFlagsFromEnvAndDieIfUnknown("TF_XLA_FLAGS", flag_list); CHECK_EQ(*pargc, 1) << msg; const std::vector<char*>& argv_second = *pargv; CHECK_NE(argv_second[0], nullptr) << msg; CHECK_EQ(argv_second[1], nullptr) << msg; CHECK(simple) << msg; CHECK_EQ(with_value, "a_value") << msg; CHECK_EQ(embedded_quotes, "single'double\"") << msg; CHECK_EQ(single_quoted, "single quoted \\\\ \n \"") << msg; CHECK_EQ(double_quoted, "double quoted \\ \n '\"") << msg; } static const char kTestFlagString[] = "--simple " "--with_value=a_value " "--embedded_quotes=single'double\" " "--single_quoted='single quoted \\\\ \n \"' " "--double_quoted=\"double quoted \\\\ \n '\\\"\" "; TEST(ParseFlagsFromEnv, Basic) { tsl::setenv("TF_XLA_FLAGS", kTestFlagString, true ); TestParseFlagsFromEnv("(flags in environment variable)"); } TEST(ParseFlagsFromEnv, File) { static const char* kTempVars[] = {"TEST_TMPDIR", "TMP"}; static const char kTempDir[] = "/tmp"; const char* tmp_dir = nullptr; for (int i = 0; i != TF_ARRAYSIZE(kTempVars) && tmp_dir == nullptr; i++) { tmp_dir = getenv(kTempVars[i]); } if (tmp_dir == nullptr) { tmp_dir = kTempDir; } std::string tmp_file = absl::StrFormat("%s/parse_flags_from_env.%d", tmp_dir, getpid()); FILE* fp = fopen(tmp_file.c_str(), "w"); CHECK_NE(fp, nullptr) << "can't write to " << tmp_file; for (int i = 0; kTestFlagString[i] != '\0'; i++) { putc(kTestFlagString[i], fp); } fflush(fp); CHECK_EQ(ferror(fp), 0) << "writes failed to " << tmp_file; fclose(fp); tsl::setenv("TF_XLA_FLAGS", tmp_file.c_str(), true ); TestParseFlagsFromEnv("(flags in file)"); unlink(tmp_file.c_str()); } static const char* binary_name; TEST(ParseFlagsFromEnv, EnvAndFlag) { static struct { const char* env; const char* arg; const char* expected_value; } test[] = { {nullptr, nullptr, "1\n"}, {nullptr, "--int_flag=2", "2\n"}, {"--int_flag=3", nullptr, "3\n"}, {"--int_flag=3", "--int_flag=2", "2\n"}, }; for (int i = 0; i != TF_ARRAYSIZE(test); i++) { if (test[i].env == nullptr) { tsl::unsetenv("TF_XLA_FLAGS"); } else { tsl::setenv("TF_XLA_FLAGS", test[i].env, true); } tsl::SubProcess child; std::vector<std::string> argv; argv.push_back(binary_name); argv.push_back("--recursing"); if (test[i].arg != nullptr) { argv.push_back(test[i].arg); } child.SetProgram(binary_name, argv); child.SetChannelAction(tsl::CHAN_STDOUT, tsl::ACTION_PIPE); child.SetChannelAction(tsl::CHAN_STDERR, tsl::ACTION_PIPE); CHECK(child.Start()) << "test " << i; std::string stdout_str; std::string stderr_str; int child_status = child.Communicate(nullptr, &stdout_str, &stderr_str); CHECK_EQ(child_status, 0) << "test " << i << "\nstdout\n" << stdout_str << "\nstderr\n" << stderr_str; stdout_str.erase(std::remove(stdout_str.begin(), stdout_str.end(), '\r'), stdout_str.end()); CHECK_EQ(stdout_str, test[i].expected_value) << "test " << i; } } TEST(ParseFlagsFromEnv, ErrorOutOnFlagFailure) { const char* env = "--int_flag=3parsefailure"; if (env == nullptr) { tsl::unsetenv("TF_XLA_FLAGS"); } else { tsl::setenv("TF_XLA_FLAGS", env, true); } tsl::SubProcess child; std::vector<std::string> argv; argv.push_back(binary_name); argv.push_back("--recursing"); child.SetProgram(binary_name, argv); child.SetChannelAction(tsl::CHAN_STDOUT, tsl::ACTION_PIPE); child.SetChannelAction(tsl::CHAN_STDERR, tsl::ACTION_PIPE); EXPECT_TRUE(child.Start()); std::string stdout_str; std::string stderr_str; int child_status = child.Communicate(nullptr, &stdout_str, &stderr_str); EXPECT_NE(child_status, 0); } TEST(ParseFlagsFromEnv, ErrorOutOnUnknownFlag) { const char* env = "--int_flag=3 --unknown_flag=value"; if (env == nullptr) { tsl::unsetenv("TF_XLA_FLAGS"); } else { tsl::setenv("TF_XLA_FLAGS", env, true); } tsl::SubProcess child; std::vector<std::string> argv; argv.push_back(binary_name); argv.push_back("--recursing"); child.SetProgram(binary_name, argv); child.SetChannelAction(tsl::CHAN_STDOUT, tsl::ACTION_PIPE); child.SetChannelAction(tsl::CHAN_STDERR, tsl::ACTION_PIPE); EXPECT_TRUE(child.Start()); std::string stdout_str; std::string stderr_str; int child_status = child.Communicate(nullptr, &stdout_str, &stderr_str); EXPECT_NE(child_status, 0); } } int main(int argc, char* argv[]) { xla::binary_name = argv[0]; bool recursing = false; int32_t int_flag = 1; const std::vector<tsl::Flag> flag_list = { tsl::Flag("recursing", &recursing, "Whether the binary is being invoked recursively."), tsl::Flag("int_flag", &int_flag, "An integer flag to test with"), }; std::string usage = tsl::Flags::Usage(argv[0], flag_list); xla::ParseFlagsFromEnvAndDieIfUnknown("TF_XLA_FLAGS", flag_list); tsl::Flags::Parse(&argc, argv, flag_list); if (recursing) { printf("%d\n", int_flag); exit(0); } testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/third_party/xla/xla/parse_flags_from_env.cc
https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/third_party/xla/xla/parse_flags_from_env_test.cc
4a29233a7b7c1a3a4294e4ccdd1772f9083944ea
3f4125f8-8d11-42d5-b0b3-5deed021bf5a
cpp
tensorflow/tensorflow
literal_util
tensorflow/compiler/tf2xla/literal_util.cc
tensorflow/compiler/tf2xla/literal_util_test.cc
#include "tensorflow/compiler/tf2xla/literal_util.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/types/span.h" #include "tensorflow/compiler/tf2xla/shape_util.h" #include "tensorflow/compiler/tf2xla/type_util.h" #include "xla/literal.h" #include "xla/shape.h" #include "xla/shape_util.h" #include "xla/status_macros.h" #include "xla/xla_data.pb.h" #include "tensorflow/core/common_runtime/dma_helper.h" #include "tensorflow/core/framework/tensor.h" #include "tensorflow/core/framework/tensor_shape.h" #include "tensorflow/core/framework/types.h" #include "tensorflow/core/framework/types.pb.h" #include "tensorflow/core/platform/errors.h" #include "tensorflow/core/platform/status.h" #include "tsl/platform/errors.h" namespace tensorflow { Status HostTensorToBorrowingLiteral(const Tensor& host_tensor, xla::BorrowingLiteral* literal) { xla::Shape xla_shape; TF_RETURN_IF_ERROR(TensorShapeToXLAShape(host_tensor.dtype(), host_tensor.shape(), &xla_shape)); return HostTensorToBorrowingLiteral(xla_shape, host_tensor, literal); } Status HostTensorToBorrowingLiteral(const xla::Shape& xla_shape, const Tensor& host_tensor, xla::BorrowingLiteral* literal) { const auto& tshape = host_tensor.shape(); TF_RET_CHECK(tshape.IsFullyDefined() && tshape.dims() == xla_shape.dimensions_size() && tshape.dim_sizes() == xla_shape.dimensions()) << "Provided xla::Shape must have the same dims as the Tensor shape."; *literal = xla::BorrowingLiteral( static_cast<const char*>(DMAHelper::base(&host_tensor)), xla_shape); return absl::OkStatus(); } absl::StatusOr<xla::Literal> HostTensorToLiteral(const Tensor& host_tensor) { xla::BorrowingLiteral literal; TF_RETURN_IF_ERROR(HostTensorToBorrowingLiteral(host_tensor, &literal)); return literal.Clone(); } Status HostTensorToMutableBorrowingLiteral( Tensor* host_tensor, xla::MutableBorrowingLiteral* literal) { xla::Shape xla_shape; TF_RETURN_IF_ERROR(TensorShapeToXLAShape(host_tensor->dtype(), host_tensor->shape(), &xla_shape)); return HostTensorToMutableBorrowingLiteral(xla_shape, host_tensor, literal); } Status HostTensorToMutableBorrowingLiteral( const xla::Shape& xla_shape, Tensor* host_tensor, xla::MutableBorrowingLiteral* literal) { *literal = xla::MutableBorrowingLiteral( static_cast<const char*>(DMAHelper::base(host_tensor)), xla_shape); return absl::OkStatus(); } Status HostTensorsToBorrowingLiteralTuple(absl::Span<const Tensor> host_tensors, xla::BorrowingLiteral* literal) { std::vector<const char*> buf_ptrs; buf_ptrs.reserve(host_tensors.size()); std::vector<xla::Shape> tensor_shapes(host_tensors.size()); for (int i = 0, end = host_tensors.size(); i < end; i++) { const Tensor* tensor = &host_tensors[i]; buf_ptrs.emplace_back(static_cast<const char*>(DMAHelper::base(tensor))); TF_RETURN_IF_ERROR(TensorShapeToXLAShape(tensor->dtype(), tensor->shape(), &tensor_shapes[i])); } *literal = xla::BorrowingLiteral( buf_ptrs, xla::ShapeUtil::MakeTupleShape(tensor_shapes)); return absl::OkStatus(); } Status CopyLiteralToHostTensor(const xla::LiteralSlice& literal, Tensor* host_tensor) { TF_RET_CHECK(literal.shape().IsArray() && xla::ShapeUtil::ElementsIn(literal.shape()) == host_tensor->NumElements()); xla::PrimitiveType primitive_type; TF_RETURN_IF_ERROR( DataTypeToPrimitiveType(host_tensor->dtype(), &primitive_type)); if (literal.shape().element_type() != primitive_type) { return errors::InvalidArgument( "Cannot convert literal of type ", xla::PrimitiveType_Name(literal.shape().element_type()), " to tensor of type ", DataTypeString(host_tensor->dtype())); } size_t total_bytes = host_tensor->TotalBytes(); if (total_bytes > 0) { const void* src_ptr = literal.untyped_data(); void* dst_ptr = DMAHelper::base(host_tensor); memcpy(dst_ptr, src_ptr, total_bytes); } return absl::OkStatus(); } Status LiteralToHostTensor(const xla::LiteralSlice& literal, DataType target_type, Tensor* host_tensor) { TensorShape shape; TF_RETURN_IF_ERROR(XLAShapeToTensorShape(literal.shape(), &shape)); *host_tensor = Tensor(target_type, shape); return CopyLiteralToHostTensor(literal, host_tensor); } }
#include "tensorflow/compiler/tf2xla/literal_util.h" #include <gtest/gtest.h> #include "absl/types/span.h" #include "xla/literal.h" #include "xla/literal_util.h" #include "tensorflow/core/framework/numeric_types.h" #include "tensorflow/core/framework/tensor.h" #include "tensorflow/core/framework/tensor_testutil.h" #include "tensorflow/core/framework/types.h" #include "tensorflow/core/framework/types.pb.h" #include "tensorflow/core/platform/test.h" #include "tensorflow/core/platform/types.h" #include "tsl/protobuf/error_codes.pb.h" namespace tensorflow { namespace { TEST(LiteralUtil, LiteralToHostTensor) { std::vector<int64_t> int64_values = {1, 2, 3}; xla::Literal int64_values_literal = xla::LiteralUtil::CreateR1(absl::Span<const int64_t>(int64_values)); Tensor host_tensor; EXPECT_EQ("Cannot convert literal of type S64 to tensor of type int32", LiteralToHostTensor(int64_values_literal, DT_INT32, &host_tensor) .message()); EXPECT_EQ("Cannot convert literal of type S64 to tensor of type qint32", LiteralToHostTensor(int64_values_literal, DT_QINT32, &host_tensor) .message()); EXPECT_TRUE( LiteralToHostTensor(int64_values_literal, DT_INT64, &host_tensor).ok()); test::ExpectTensorEqual<int64_t>(host_tensor, test::AsTensor<int64_t>(int64_values)); } template <class T> using LiteralUtilTest = ::testing::Test; using Types = ::testing::Types<std::pair<int8, qint8>, std::pair<uint8, quint8>, std::pair<int16, qint16>, std::pair<uint16, quint16>, std::pair<int32, qint32>>; TYPED_TEST_SUITE(LiteralUtilTest, Types); TYPED_TEST(LiteralUtilTest, LiteralToQuantizedHostTensor) { using int_type = typename TypeParam::first_type; using qint_type = typename TypeParam::second_type; Tensor host_tensor; std::vector<int_type> int_values = {10, 11}; xla::Literal int_values_literal = xla::LiteralUtil::CreateR1(absl::Span<const int_type>(int_values)); EXPECT_TRUE(LiteralToHostTensor(int_values_literal, DataTypeToEnum<int_type>::value, &host_tensor) .ok()); test::ExpectTensorEqual<int_type>(host_tensor, test::AsTensor<int_type>(int_values)); EXPECT_TRUE(LiteralToHostTensor(int_values_literal, DataTypeToEnum<qint_type>::value, &host_tensor) .ok()); std::vector<qint_type> qint_values = {10, 11}; test::ExpectTensorEqual<qint_type>(host_tensor, test::AsTensor<qint_type>(qint_values)); EXPECT_EQ( error::INVALID_ARGUMENT, LiteralToHostTensor(int_values_literal, DT_INT64, &host_tensor).code()); } } }
https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/tensorflow/compiler/tf2xla/literal_util.cc
https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/tensorflow/compiler/tf2xla/literal_util_test.cc
4a29233a7b7c1a3a4294e4ccdd1772f9083944ea
a5ecc6e9-0c1c-4e01-9180-c293cbfd50be
cpp
tensorflow/tensorflow
reference_util
third_party/xla/xla/reference_util.cc
third_party/xla/xla/reference_util_test.cc
#include "xla/reference_util.h" #include <array> #include <cmath> #include <functional> #include <memory> #include <optional> #include <utility> #include <vector> #include "absl/container/flat_hash_set.h" #include "absl/functional/function_ref.h" #include "absl/types/span.h" #include "xla/array2d.h" #include "xla/array3d.h" #include "xla/array4d.h" #include "xla/client/padding.h" #include "xla/client/xla_builder.h" #include "xla/hlo/evaluator/hlo_evaluator.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/literal.h" #include "xla/literal_util.h" #include "xla/service/hlo_module_config.h" #include "xla/service/shape_inference.h" #include "xla/shape.h" #include "xla/tsl/lib/math/math_util.h" #include "xla/window_util.h" #include "xla/xla_data.pb.h" #include "tsl/platform/logging.h" namespace xla { std::unique_ptr<Array2D<double>> ReferenceUtil::Array2DF32ToF64( const Array2D<float>& input) { auto result = std::make_unique<Array2D<double>>(input.height(), input.width()); for (int64_t rowno = 0; rowno < input.height(); ++rowno) { for (int64_t colno = 0; colno < input.width(); ++colno) { (*result)(rowno, colno) = input(rowno, colno); } } return result; } std::unique_ptr<Array3D<float>> ReferenceUtil::ConvArray3D( const Array3D<float>& lhs, const Array3D<float>& rhs, int64_t kernel_stride, Padding padding) { return ConvArray3DGeneralDimensionsDilated( lhs, rhs, kernel_stride, padding, 1, 1, XlaBuilder::CreateDefaultConvDimensionNumbers(1)); } std::unique_ptr<Array3D<float>> ReferenceUtil::ConvArray3DGeneralDimensionsDilated( const Array3D<float>& lhs, const Array3D<float>& rhs, int64_t kernel_stride, Padding padding, int64_t lhs_dilation, int64_t rhs_dilation, const ConvolutionDimensionNumbers& dnums) { CHECK_EQ(dnums.input_spatial_dimensions_size(), 1); CHECK_EQ(dnums.kernel_spatial_dimensions_size(), 1); CHECK_EQ(dnums.output_spatial_dimensions_size(), 1); Array4D<float> a4dlhs(lhs.n1(), lhs.n2(), lhs.n3(), 1); a4dlhs.Each([&](absl::Span<const int64_t> indices, float* value_ptr) { CHECK_EQ(indices[3], 0); *value_ptr = lhs.operator()(indices[0], indices[1], indices[2]); }); Array4D<float> a4drhs(rhs.n1(), rhs.n2(), rhs.n3(), 1); a4drhs.Each([&](absl::Span<const int64_t> indices, float* value_ptr) { CHECK_EQ(indices[3], 0); *value_ptr = rhs.operator()(indices[0], indices[1], indices[2]); }); ConvolutionDimensionNumbers dnums2d = dnums; dnums2d.add_input_spatial_dimensions(3); dnums2d.add_kernel_spatial_dimensions(3); dnums2d.add_output_spatial_dimensions(3); std::unique_ptr<Array4D<float>> convr4 = ConvArray4DGeneralDimensionsDilated( a4dlhs, a4drhs, {kernel_stride, 1}, padding, {lhs_dilation, 1}, {rhs_dilation, 1}, dnums2d); auto convr3 = std::make_unique<Array3D<float>>( convr4->planes(), convr4->depth(), convr4->height()); convr4->Each([&](absl::Span<const int64_t> indices, float* value_ptr) { CHECK_EQ(indices[3], 0); convr3->operator()(indices[0], indices[1], indices[2]) = *value_ptr; }); return convr3; } std::unique_ptr<Array4D<float>> ReferenceUtil::ConvArray4D( const Array4D<float>& lhs, const Array4D<float>& rhs, std::pair<int64_t, int64_t> kernel_stride, Padding padding) { return ConvArray4DGeneralDimensions( lhs, rhs, kernel_stride, padding, XlaBuilder::CreateDefaultConvDimensionNumbers()); } std::unique_ptr<Array4D<float>> ReferenceUtil::SeparableConvArray4D(const Array4D<float>& input, const Array4D<float>& depthwise_weights, const Array4D<float>& pointwise_weights, std::pair<int64_t, int64_t> kernel_stride, Padding padding) { const int64_t depth_multiplier = depthwise_weights.planes(); CHECK_EQ(pointwise_weights.depth(), input.depth() * depth_multiplier); Array4D<float> weights(pointwise_weights.planes(), input.depth(), depthwise_weights.height(), depthwise_weights.width()); for (int64_t kx = 0; kx < depthwise_weights.width(); ++kx) { for (int64_t ky = 0; ky < depthwise_weights.height(); ++ky) { for (int64_t kz = 0; kz < input.depth(); ++kz) { for (int64_t out = 0; out < pointwise_weights.planes(); ++out) { float weight = 0.0; for (int64_t depth = 0; depth < depth_multiplier; ++depth) { weight += depthwise_weights(depth, kz, ky, kx) * pointwise_weights(out, depth + kz * depth_multiplier, 0, 0); } weights(out, kz, ky, kx) = weight; } } } } return ConvArray4D(input, weights, kernel_stride, padding); } int64_t ReferenceUtil::WindowCount(int64_t unpadded_width, int64_t window_len, int64_t stride, Padding padding) { if (padding == Padding::kValid) { return window_util::StridedBound(unpadded_width, window_len, stride); } return tsl::MathUtil::CeilOfRatio(unpadded_width, stride); } std::unique_ptr<std::vector<float>> ReferenceUtil::ReduceWindow1DGeneric( absl::Span<const float> operand, float init, absl::FunctionRef<float(float, float)> reduce_func, absl::Span<const int64_t> window, absl::Span<const int64_t> stride, absl::Span<const std::pair<int64_t, int64_t>> padding) { CHECK_EQ(window.size(), 1); CHECK_EQ(stride.size(), 1); CHECK_EQ(padding.size(), 1); int64_t padded_width = padding[0].first + operand.size() + padding[0].second; int64_t stride_amount = stride[0]; int64_t window_size = window[0]; int64_t result_size = window_util::StridedBound(padded_width, window_size, stride_amount); int64_t pad_low = padding[0].first; auto result = std::make_unique<std::vector<float>>(result_size); for (int64_t i0 = 0; i0 < result_size; ++i0) { int64_t i0_base = i0 * stride_amount - pad_low; float val = init; for (int64_t i0_win = 0; i0_win < window_size; ++i0_win) { if (i0_base + i0_win >= 0 && i0_base + i0_win < operand.size()) { val = reduce_func(val, operand[i0_base + i0_win]); } } (*result)[i0] = val; } return result; } std::unique_ptr<Array4D<float>> ReferenceUtil::ReduceWindow4DGeneric( const Array4D<float>& operand, float init, absl::FunctionRef<float(float, float)> reduce_func, absl::Span<const int64_t> window, absl::Span<const int64_t> stride, Padding padding) { std::vector<int64_t> dim_lengths{operand.n1(), operand.n2(), operand.n3(), operand.n4()}; return ReduceWindow4DGeneric( operand, init, reduce_func, window, stride, xla::MakePadding(dim_lengths, window, stride, padding)); } std::unique_ptr<Array4D<float>> ReferenceUtil::ReduceWindow4DGeneric( const Array4D<float>& operand, float init, absl::FunctionRef<float(float, float)> reduce_func, absl::Span<const int64_t> window, absl::Span<const int64_t> stride, absl::Span<const std::pair<int64_t, int64_t>> padding) { std::vector<int64_t> dim_lengths{operand.n1(), operand.n2(), operand.n3(), operand.n4()}; std::vector<int64_t> window_counts(window.size(), 0); std::vector<int64_t> pad_low(window.size(), 0); for (int64_t i = 0; i < window.size(); ++i) { int64_t padded_width = padding[i].first + dim_lengths[i] + padding[i].second; window_counts[i] = window_util::StridedBound(padded_width, window[i], stride[i]); pad_low[i] = padding[i].first; } auto result = std::make_unique<Array4D<float>>( window_counts[0], window_counts[1], window_counts[2], window_counts[3]); for (int64_t i0 = 0; i0 < window_counts[0]; ++i0) { for (int64_t i1 = 0; i1 < window_counts[1]; ++i1) { for (int64_t i2 = 0; i2 < window_counts[2]; ++i2) { for (int64_t i3 = 0; i3 < window_counts[3]; ++i3) { int64_t i0_base = i0 * stride[0] - pad_low[0]; int64_t i1_base = i1 * stride[1] - pad_low[1]; int64_t i2_base = i2 * stride[2] - pad_low[2]; int64_t i3_base = i3 * stride[3] - pad_low[3]; float val = init; for (int64_t i0_win = 0; i0_win < window[0]; ++i0_win) { for (int64_t i1_win = 0; i1_win < window[1]; ++i1_win) { for (int64_t i2_win = 0; i2_win < window[2]; ++i2_win) { for (int64_t i3_win = 0; i3_win < window[3]; ++i3_win) { if (i0_base + i0_win >= 0 && i1_base + i1_win >= 0 && i2_base + i2_win >= 0 && i3_base + i3_win >= 0 && i0_base + i0_win < operand.n1() && i1_base + i1_win < operand.n2() && i2_base + i2_win < operand.n3() && i3_base + i3_win < operand.n4()) { val = reduce_func( val, operand(i0_base + i0_win, i1_base + i1_win, i2_base + i2_win, i3_base + i3_win)); } } } } } (*result)(i0, i1, i2, i3) = val; } } } } return result; } std::unique_ptr<Array4D<float>> ReferenceUtil::ReduceWindow4DAdd( const Array4D<float>& operand, float init, absl::Span<const int64_t> window, absl::Span<const int64_t> stride, Padding padding) { const auto add_reduce = [](float arg1, float arg2) { return arg1 + arg2; }; return ReduceWindow4DGeneric(operand, init, add_reduce, window, stride, padding); } std::unique_ptr<Array4D<float>> ReferenceUtil::BatchNorm4D( const Array4D<float>& input, const Array4D<float>& mean, const Array4D<float>& var, const Array4D<float>& scale, const Array4D<float>& offset, float epsilon) { auto normalized = *MapArray4D(input, mean, [](float a, float b) { return a - b; }); normalized = *MapArray4D(normalized, var, [&](float a, float b) { return a / std::sqrt(b + epsilon); }); normalized = *MapArray4D(normalized, scale, [](float a, float b) { return a * b; }); return MapArray4D(normalized, offset, [](float a, float b) { return a + b; }); } std::unique_ptr<Array4D<float>> ReferenceUtil::SelectAndScatter4DGePlus(const Array4D<float>& operand, const Array4D<float>& source, float init, absl::Span<const int64_t> window, absl::Span<const int64_t> stride, bool same_padding) { Padding padding = same_padding ? Padding::kSame : Padding::kValid; auto result = std::make_unique<Array4D<float>>(operand.n1(), operand.n2(), operand.n3(), operand.n4()); std::vector<int64_t> dim_lengths{operand.n1(), operand.n2(), operand.n3(), operand.n4()}; auto padding_both = xla::MakePadding(dim_lengths, window, stride, padding); result->Fill(init); std::vector<int64_t> window_counts(window.size(), 0); std::vector<int64_t> pad_low(window.size(), 0); for (int64_t i = 0; i < window.size(); ++i) { window_counts[i] = WindowCount(dim_lengths[i], window[i], stride[i], padding); pad_low[i] = padding_both[i].first; } CHECK_EQ(window_counts[0], source.n1()); CHECK_EQ(window_counts[1], source.n2()); CHECK_EQ(window_counts[2], source.n3()); CHECK_EQ(window_counts[3], source.n4()); for (int64_t i0 = 0; i0 < window_counts[0]; ++i0) { for (int64_t i1 = 0; i1 < window_counts[1]; ++i1) { for (int64_t i2 = 0; i2 < window_counts[2]; ++i2) { for (int64_t i3 = 0; i3 < window_counts[3]; ++i3) { int64_t i0_base = i0 * stride[0] - pad_low[0]; int64_t i1_base = i1 * stride[1] - pad_low[1]; int64_t i2_base = i2 * stride[2] - pad_low[2]; int64_t i3_base = i3 * stride[3] - pad_low[3]; int64_t scatter_0 = (i0_base >= 0) ? i0_base : 0; int64_t scatter_1 = (i1_base >= 0) ? i1_base : 0; int64_t scatter_2 = (i2_base >= 0) ? i2_base : 0; int64_t scatter_3 = (i3_base >= 0) ? i3_base : 0; float val = operand(scatter_0, scatter_1, scatter_2, scatter_3); for (int64_t i0_win = 0; i0_win < window[0]; ++i0_win) { for (int64_t i1_win = 0; i1_win < window[1]; ++i1_win) { for (int64_t i2_win = 0; i2_win < window[2]; ++i2_win) { for (int64_t i3_win = 0; i3_win < window[3]; ++i3_win) { if (i0_base + i0_win >= 0 && i1_base + i1_win >= 0 && i2_base + i2_win >= 0 && i3_base + i3_win >= 0 && i0_base + i0_win < operand.n1() && i1_base + i1_win < operand.n2() && i2_base + i2_win < operand.n3() && i3_base + i3_win < operand.n4()) { float tmp = operand(i0_base + i0_win, i1_base + i1_win, i2_base + i2_win, i3_base + i3_win); if (tmp > val) { val = tmp; scatter_0 = i0_base + i0_win; scatter_1 = i1_base + i1_win; scatter_2 = i2_base + i2_win; scatter_3 = i3_base + i3_win; } } } } } } (*result)(scatter_0, scatter_1, scatter_2, scatter_3) += source(i0, i1, i2, i3); } } } } return result; } std::unique_ptr<Array4D<float>> ReferenceUtil::ConvArray4DGeneralDimensions( const Array4D<float>& lhs, const Array4D<float>& rhs, std::pair<int64_t, int64_t> kernel_stride, Padding padding, ConvolutionDimensionNumbers dimension_numbers) { return ConvArray4DGeneralDimensionsDilated(lhs, rhs, kernel_stride, padding, {1, 1}, {1, 1}, std::move(dimension_numbers)); } std::unique_ptr<Array4D<float>> ReferenceUtil::ConvArray4DGeneralDimensionsDilated( const Array4D<float>& lhs, const Array4D<float>& rhs, std::pair<int64_t, int64_t> kernel_stride, Padding padding, std::pair<int64_t, int64_t> lhs_dilation, std::pair<int64_t, int64_t> rhs_dilation, ConvolutionDimensionNumbers dnums) { HloComputation::Builder b("ConvArray4DGeneralDimensionDilated"); auto lhs_literal = LiteralUtil::CreateR4FromArray4D<float>(lhs); auto rhs_literal = LiteralUtil::CreateR4FromArray4D<float>(rhs); std::array<int64_t, 2> ordered_kernel_strides; std::array<int64_t, 2> ordered_input_dimensions; std::array<int64_t, 2> ordered_kernel_dimensions; if (dnums.kernel_spatial_dimensions(0) > dnums.kernel_spatial_dimensions(1)) { ordered_kernel_strides[0] = kernel_stride.second; ordered_kernel_strides[1] = kernel_stride.first; } else { ordered_kernel_strides[0] = kernel_stride.first; ordered_kernel_strides[1] = kernel_stride.second; } ordered_input_dimensions[0] = lhs_literal.shape().dimensions(dnums.input_spatial_dimensions(0)); ordered_input_dimensions[1] = lhs_literal.shape().dimensions(dnums.input_spatial_dimensions(1)); ordered_kernel_dimensions[0] = rhs_literal.shape().dimensions(dnums.kernel_spatial_dimensions(0)); ordered_kernel_dimensions[1] = rhs_literal.shape().dimensions(dnums.kernel_spatial_dimensions(1)); std::vector<std::pair<int64_t, int64_t>> paddings = MakePadding(ordered_input_dimensions, ordered_kernel_dimensions, ordered_kernel_strides, padding); CHECK_EQ(paddings.size(), 2); Window window; WindowDimension dim; dim.set_size( rhs_literal.shape().dimensions(dnums.kernel_spatial_dimensions(0))); dim.set_stride(kernel_stride.first); dim.set_padding_low(paddings[0].first); dim.set_padding_high(paddings[0].second); dim.set_window_dilation(rhs_dilation.first); dim.set_base_dilation(lhs_dilation.first); *window.add_dimensions() = dim; WindowDimension dim2; dim2.set_size( rhs_literal.shape().dimensions(dnums.kernel_spatial_dimensions(1))); dim2.set_stride(kernel_stride.second); dim2.set_padding_low(paddings[1].first); dim2.set_padding_high(paddings[1].second); dim2.set_window_dilation(rhs_dilation.second); dim2.set_base_dilation(lhs_dilation.second); *window.add_dimensions() = dim2; const Shape shape = ShapeInference::InferConvolveShape( lhs_literal.shape(), rhs_literal.shape(), 1, 1, window, dnums, std::nullopt) .value(); HloInstruction* lhs_instruction = b.AddInstruction(HloInstruction::CreateConstant(std::move(lhs_literal))); HloInstruction* rhs_instruction = b.AddInstruction(HloInstruction::CreateConstant(std::move(rhs_literal))); PrecisionConfig precision_config; precision_config.mutable_operand_precision()->Resize( 2, PrecisionConfig::DEFAULT); b.AddInstruction(HloInstruction::CreateConvolve( shape, lhs_instruction, rhs_instruction, 1, 1, window, dnums, precision_config)); HloModuleConfig config; HloModule module("ReferenceUtil", config); auto computation = module.AddEntryComputation(b.Build()); HloEvaluator evaluator; Literal result_literal = evaluator.Evaluate(*computation, {}).value(); CHECK_EQ(result_literal.shape().rank(), 4); auto result = std::make_unique<Array4D<float>>(result_literal.shape().dimensions(0), result_literal.shape().dimensions(1), result_literal.shape().dimensions(2), result_literal.shape().dimensions(3)); result->Each([&](absl::Span<const int64_t> indices, float* value) { *value = result_literal.Get<float>(indices); }); return result; } std::unique_ptr<std::vector<float>> ReferenceUtil::ReduceToColArray2D( const Array2D<float>& matrix, float init, absl::FunctionRef<float(float, float)> reduce_function) { int64_t rows = matrix.height(); int64_t cols = matrix.width(); auto result = std::make_unique<std::vector<float>>(); for (int64_t i = 0; i < rows; ++i) { float acc = init; for (int64_t j = 0; j < cols; ++j) { acc = reduce_function(acc, matrix(i, j)); } result->push_back(acc); } return result; } std::unique_ptr<std::vector<float>> ReferenceUtil::ReduceToRowArray2D( const Array2D<float>& matrix, float init, absl::FunctionRef<float(float, float)> reduce_function) { int64_t rows = matrix.height(); int64_t cols = matrix.width(); auto result = std::make_unique<std::vector<float>>(); for (int64_t i = 0; i < cols; ++i) { float acc = init; for (int64_t j = 0; j < rows; ++j) { acc = reduce_function(acc, matrix(j, i)); } result->push_back(acc); } return result; } std::vector<float> ReferenceUtil::Reduce4DTo1D( const Array4D<float>& array, float init, absl::Span<const int64_t> dims, absl::FunctionRef<float(float, float)> reduce_function) { std::vector<float> result; CHECK_EQ(dims.size(), 3); const absl::flat_hash_set<int64_t> dim_set(dims.begin(), dims.end()); CHECK_EQ(dim_set.size(), 3); for (int64_t a0 = 0; a0 == 0 || (!dim_set.contains(0) && a0 < array.n1()); ++a0) { for (int64_t a1 = 0; a1 == 0 || (!dim_set.contains(1) && a1 < array.n2()); ++a1) { for (int64_t a2 = 0; a2 == 0 || (!dim_set.contains(2) && a2 < array.n3()); ++a2) { for (int64_t a3 = 0; a3 == 0 || (!dim_set.contains(3) && a3 < array.n4()); ++a3) { float accumulator = init; for (int64_t i0 = 0; i0 == 0 || (dim_set.contains(0) && i0 < array.n1()); ++i0) { for (int64_t i1 = 0; i1 == 0 || (dim_set.contains(1) && i1 < array.n2()); ++i1) { for (int64_t i2 = 0; i2 == 0 || (dim_set.contains(2) && i2 < array.n3()); ++i2) { for (int64_t i3 = 0; i3 == 0 || (dim_set.contains(3) && i3 < array.n4()); ++i3) { if (array.n1() > 0 && array.n2() > 0 && array.n3() > 0 && array.n4() > 0) { accumulator = reduce_function( accumulator, array(a0 + i0, a1 + i1, a2 + i2, a3 + i3)); } } } } } result.push_back(accumulator); } } } } return result; } std::unique_ptr<Array4D<float>> ReferenceUtil::Broadcast1DTo4D( const std::vector<float>& array, const std::vector<int64_t>& bounds, int64_t broadcast_from_dim) { auto result = std::make_unique<Array4D<float>>(bounds[0], bounds[1], bounds[2], bounds[3]); for (int64_t i = 0; i < result->n1(); ++i) { for (int64_t j = 0; j < result->n2(); ++j) { for (int64_t k = 0; k < result->n3(); ++k) { for (int64_t l = 0; l < result->n4(); ++l) { switch (broadcast_from_dim) { case 0: (*result)(i, j, k, l) = array[i]; break; case 1: (*result)(i, j, k, l) = array[j]; break; case 2: (*result)(i, j, k, l) = array[k]; break; case 3: (*result)(i, j, k, l) = array[l]; break; default: break; } } } } } return result; } std::unique_ptr<Array2D<float>> ReferenceUtil::Reduce3DTo2D( const Array3D<float>& array, float init, absl::Span<const int64_t> dims, absl::FunctionRef<float(float, float)> reduce_function) { CHECK_EQ(dims.size(), 1); int64_t rows = dims[0] == 0 ? array.n2() : array.n1(); int64_t cols = dims[0] == 2 ? array.n2() : array.n3(); auto result = std::make_unique<Array2D<float>>(rows, cols); result->Fill(init); for (int i0 = 0; i0 < array.n1(); ++i0) { for (int i1 = 0; i1 < array.n2(); ++i1) { for (int i2 = 0; i2 < array.n3(); ++i2) { int64_t row = dims[0] == 0 ? i1 : i0; int64_t col = dims[0] == 2 ? i1 : i2; (*result)(row, col) = reduce_function((*result)(row, col), array(i0, i1, i2)); } } } return result; } std::unique_ptr<Array2D<float>> ReferenceUtil::MapArray2D( const Array2D<float>& matrix, absl::FunctionRef<float(float)> map_function) { int64_t rows = matrix.height(); int64_t cols = matrix.width(); auto result = std::make_unique<Array2D<float>>(rows, cols); for (int64_t i = 0; i < rows; ++i) { for (int64_t j = 0; j < cols; ++j) { (*result)(i, j) = map_function(matrix(i, j)); } } return result; } std::unique_ptr<Array2D<float>> ReferenceUtil::MapArray2D( const Array2D<float>& lhs, const Array2D<float>& rhs, absl::FunctionRef<float(float, float)> map_function) { CHECK_EQ(lhs.height(), rhs.height()); CHECK_EQ(lhs.width(), rhs.width()); int64_t rows = lhs.height(); int64_t cols = rhs.width(); auto result = std::make_unique<Array2D<float>>(rows, cols); for (int64_t i = 0; i < rows; ++i) { for (int64_t j = 0; j < cols; ++j) { (*result)(i, j) = map_function(lhs(i, j), rhs(i, j)); } } return result; } std::unique_ptr<Array3D<float>> ReferenceUtil::MapArray3D( const Array3D<float>& array, absl::FunctionRef<float(float)> map_function) { int64_t n1 = array.n1(); int64_t n2 = array.n2(); int64_t n3 = array.n3(); auto result = std::make_unique<Array3D<float>>(n1, n2, n3); for (int64_t i = 0; i < n1; ++i) { for (int64_t j = 0; j < n2; ++j) { for (int64_t k = 0; k < n3; ++k) { (*result)(i, j, k) = map_function(array(i, j, k)); } } } return result; } std::unique_ptr<Array3D<float>> ReferenceUtil::MapArray3D( const Array3D<float>& lhs, const Array3D<float>& rhs, absl::FunctionRef<float(float, float)> map_function) { CHECK_EQ(lhs.n1(), rhs.n1()); CHECK_EQ(lhs.n2(), rhs.n2()); CHECK_EQ(lhs.n3(), rhs.n3()); int64_t n1 = lhs.n1(); int64_t n2 = rhs.n2(); int64_t n3 = rhs.n3(); auto result = std::make_unique<Array3D<float>>(n1, n2, n3); for (int64_t i = 0; i < n1; ++i) { for (int64_t j = 0; j < n2; ++j) { for (int64_t k = 0; k < n3; ++k) { (*result)(i, j, k) = map_function(lhs(i, j, k), rhs(i, j, k)); } } } return result; } std::unique_ptr<Array2D<float>> ReferenceUtil::MapWithIndexArray2D( const Array2D<float>& matrix, absl::FunctionRef<float(float, int64_t, int64_t)> map_function) { int64_t rows = matrix.height(); int64_t cols = matrix.width(); auto result = std::make_unique<Array2D<float>>(rows, cols); for (int64_t i = 0; i < rows; ++i) { for (int64_t j = 0; j < cols; ++j) { (*result)(i, j) = map_function(matrix(i, j), i, j); } } return result; } }
#include "xla/reference_util.h" #include <cmath> #include <memory> #include "xla/array2d.h" #include "xla/array3d.h" #include "xla/array4d.h" #include "xla/client/padding.h" #include "xla/error_spec.h" #include "xla/literal.h" #include "xla/literal_util.h" #include "xla/test.h" #include "xla/tests/literal_test_util.h" #include "xla/xla_data.pb.h" namespace xla { namespace { class ReferenceUtilTest : public ::testing::Test { protected: ReferenceUtilTest() { matrix_ = std::make_unique<Array2D<float>>(rows_, cols_); for (int64_t i = 0; i < rows_; ++i) { for (int64_t j = 0; j < cols_; ++j) { (*matrix_)(i, j) = i * cols_ + j + 1; } } } const int64_t rows_ = 2; const int64_t cols_ = 3; std::unique_ptr<Array2D<float>> matrix_; }; TEST_F(ReferenceUtilTest, TransposeArray2D) { auto result = ReferenceUtil::TransposeArray2D(*matrix_); auto actual_literal = LiteralUtil::CreateR2FromArray2D(*result); LiteralTestUtil::ExpectR2Near<float>({{1.f, 4.f}, {2.f, 5.f}, {3.f, 6.f}}, actual_literal, ErrorSpec(0.0001)); } TEST_F(ReferenceUtilTest, MatmulArray2D) { Array2D<float> rhs({ {7.f, 8.f}, {9.f, 10.f}, {11.f, 12.f}, }); auto result = ReferenceUtil::MatmulArray2D(*matrix_, rhs); auto actual_literal = LiteralUtil::CreateR2FromArray2D(*result); LiteralTestUtil::ExpectR2Near<float>({{58.f, 64.f}, {139.f, 154.f}}, actual_literal, ErrorSpec(0.0001)); } TEST_F(ReferenceUtilTest, ReduceToColArray2D) { auto add = [](float lhs, float rhs) { return lhs + rhs; }; auto result = ReferenceUtil::ReduceToColArray2D(*matrix_, 0.0f, add); auto actual_literal = LiteralUtil::CreateR1<float>(*result); LiteralTestUtil::ExpectR1Near<float>({6.f, 15.f}, actual_literal, ErrorSpec(0.0001)); } TEST_F(ReferenceUtilTest, ReduceToRowArray2D) { auto add = [](float lhs, float rhs) { return lhs + rhs; }; auto result = ReferenceUtil::ReduceToRowArray2D(*matrix_, 0.0f, add); auto actual_literal = LiteralUtil::CreateR1<float>(*result); LiteralTestUtil::ExpectR1Near<float>({5.f, 7.f, 9.f}, actual_literal, ErrorSpec(0.0001)); } TEST_F(ReferenceUtilTest, Array2DF32ToF64Test) { auto result = ReferenceUtil::Array2DF32ToF64(*matrix_); ASSERT_EQ(result->height(), matrix_->height()); ASSERT_EQ(result->width(), matrix_->width()); for (int64_t rowno = 0; rowno < matrix_->height(); ++rowno) { for (int64_t colno = 0; colno < matrix_->width(); ++colno) { EXPECT_EQ(static_cast<double>((*matrix_)(rowno, colno)), (*result)(rowno, colno)); } } } TEST_F(ReferenceUtilTest, Reduce4Dto1DZeroSizedArray) { auto result = LiteralUtil::CreateR1<float>(ReferenceUtil::Reduce4DTo1D( Array4D<float>(1, 0, 1, 1), 0, {0, 1, 2}, [](float a, float b) { return a + b; })); LiteralTestUtil::ExpectR1Equal<float>({0}, result); } TEST_F(ReferenceUtilTest, MapArray2D) { auto identity = [](float value) { return std::log(std::exp(value)); }; auto result = ReferenceUtil::MapArray2D(*matrix_, identity); auto actual_literal = LiteralUtil::CreateR2FromArray2D(*result); LiteralTestUtil::ExpectR2NearArray2D(*matrix_, actual_literal, ErrorSpec(0.0001)); } TEST_F(ReferenceUtilTest, MapArray3D) { auto identity = [](float value) { return std::log(std::exp(value)); }; Array3D<float> input(2, 3, 4); input.FillIota(0); auto result = ReferenceUtil::MapArray3D(input, identity); auto actual_literal = LiteralUtil::CreateR3FromArray3D(*result); LiteralTestUtil::ExpectR3NearArray3D(input, actual_literal, ErrorSpec(0.0001)); } TEST_F(ReferenceUtilTest, MapWithIndexArray2D) { auto add_index = [](float value, int64_t row, int64_t col) { return value + row + col; }; auto result = ReferenceUtil::MapWithIndexArray2D(*matrix_, add_index); auto actual_literal = LiteralUtil::CreateR2FromArray2D(*result); LiteralTestUtil::ExpectR2Near<float>({{1.f, 3.f, 5.f}, {5.f, 7.f, 9.f}}, actual_literal, ErrorSpec(0.0001)); } TEST_F(ReferenceUtilTest, MapArray4D) { auto input = std::make_unique<Array4D<float>>(2, 3, 4, 5); input->FillWithMultiples(1.0f); auto multiply_by_two = [](float value) { return 2 * value; }; auto result = ReferenceUtil::MapArray4D(*input, multiply_by_two); auto actual_literal = LiteralUtil::CreateR4FromArray4D(*result); Array4D<float> expected(2, 3, 4, 5); expected.FillWithMultiples(2.0f); LiteralTestUtil::ExpectR4NearArray4D(expected, actual_literal, ErrorSpec(0.0001)); } TEST_F(ReferenceUtilTest, MapWithIndexArray4D) { auto input = std::make_unique<Array4D<float>>(2, 3, 4, 5); input->FillWithMultiples(1.0f); auto subtract_index = [](float value, int64_t plane, int64_t depth, int64_t height, int64_t width) { return value - (3 * 4 * 5 * plane + 4 * 5 * depth + 5 * height + width); }; auto result = ReferenceUtil::MapWithIndexArray4D(*input, subtract_index); auto actual_literal = LiteralUtil::CreateR4FromArray4D(*result); Array4D<float> expected(2, 3, 4, 5); expected.Fill(0.0f); LiteralTestUtil::ExpectR4NearArray4D(expected, actual_literal, ErrorSpec(0.0001)); } TEST_F(ReferenceUtilTest, SliceArray2D) { auto result = ReferenceUtil::Slice2D(*matrix_, {{0, 0}}, {{2, 2}}, {{1, 1}}); auto actual_literal = LiteralUtil::CreateR2FromArray2D(*result); LiteralTestUtil::ExpectR2Near<float>({{1.f, 2.f}, {4.f, 5.f}}, actual_literal, ErrorSpec(0.0001)); } TEST_F(ReferenceUtilTest, SliceStridedArray2D) { auto result = ReferenceUtil::Slice2D(*matrix_, {{0, 0}}, {{2, 3}}, {{1, 2}}); auto actual_literal = LiteralUtil::CreateR2FromArray2D(*result); LiteralTestUtil::ExpectR2Near<float>({{1.f, 3.f}, {4.f, 6.f}}, actual_literal, ErrorSpec(0.0001)); } TEST_F(ReferenceUtilTest, SliceArray3D) { Array3D<float> input(2, 3, 4); input.FillIota(0); auto result = ReferenceUtil::Slice3D(input, {{0, 0, 0}}, {{2, 2, 2}}, {{1, 1, 1}}); auto actual_literal = LiteralUtil::CreateR3FromArray3D(*result); LiteralTestUtil::ExpectR3Near<float>( {{{0.f, 1.f}, {4.f, 5.f}}, {{12.f, 13.f}, {16.f, 17.f}}}, actual_literal, ErrorSpec(0.0001)); } TEST_F(ReferenceUtilTest, SliceStridedArray3D) { Array3D<float> input(2, 3, 4); input.FillIota(0); auto result = ReferenceUtil::Slice3D(input, {{0, 0, 0}}, {{2, 3, 4}}, {{1, 2, 2}}); auto actual_literal = LiteralUtil::CreateR3FromArray3D(*result); LiteralTestUtil::ExpectR3Near<float>( {{{0.f, 2.f}, {8.f, 10.f}}, {{12.f, 14.f}, {20.f, 22.f}}}, actual_literal, ErrorSpec(0.0001)); } TEST_F(ReferenceUtilTest, SliceArray4D) { Array4D<float> input(2, 3, 4, 5); input.FillIota(0); auto result = ReferenceUtil::Slice4D(input, {{1, 0, 0, 0}}, {{2, 2, 2, 2}}, {{1, 1, 1, 1}}); auto actual_literal = LiteralUtil::CreateR4FromArray4D(*result); LiteralTestUtil::ExpectR4Near<float>( {{{{60.f, 61.f}, {65.f, 66.f}}, {{80.f, 81.f}, {85.f, 86.f}}}}, actual_literal, ErrorSpec(0.0001)); } TEST_F(ReferenceUtilTest, SliceStridedArray4D) { Array4D<float> input(2, 3, 4, 5); input.FillIota(0); auto result = ReferenceUtil::Slice4D(input, {{1, 0, 0, 0}}, {{2, 3, 4, 5}}, {{1, 2, 2, 2}}); auto actual_literal = LiteralUtil::CreateR4FromArray4D(*result); LiteralTestUtil::ExpectR4Near<float>( {{{{60.f, 62.f, 64.f}, {70.f, 72.f, 74.f}}, {{100.f, 102.f, 104.f}, {110.f, 112.f, 114.f}}}}, actual_literal, ErrorSpec(0.0001)); } TEST_F(ReferenceUtilTest, ConvArray3DWithSamePadding) { Array3D<float> input = {{{1, 2, 3, 4}}}; Array3D<float> weights = {{{5, 6}}}; std::unique_ptr<Array3D<float>> actual = ReferenceUtil::ConvArray3D(input, weights, 1, Padding::kSame); Array3D<float> expected = {{{17, 28, 39, 20}}}; auto actual_literal = LiteralUtil::CreateR3FromArray3D(*actual); LiteralTestUtil::ExpectR3NearArray3D<float>(expected, actual_literal, ErrorSpec(0.0001)); } TEST_F(ReferenceUtilTest, ConvArray3DWithValidPadding) { Array3D<float> input = {{{1, 2, 3, 4}}}; Array3D<float> weights = {{{5, 6}}}; std::unique_ptr<Array3D<float>> actual = ReferenceUtil::ConvArray3D(input, weights, 1, Padding::kValid); Array3D<float> expected = {{{17, 28, 39}}}; auto actual_literal = LiteralUtil::CreateR3FromArray3D(*actual); LiteralTestUtil::ExpectR3NearArray3D<float>(expected, actual_literal, ErrorSpec(0.0001)); } TEST_F(ReferenceUtilTest, ConvWithSamePadding) { Array4D<float> input(1, 1, 4, 4); input.FillWithYX(Array2D<float>({ {1, 2, 3, 4 }, {5, 6, 7, 8 }, {9, 10, 11, 12}, {13, 14, 15, 16}, })); Array4D<float> weights(1, 1, 2, 2); weights.FillWithYX(Array2D<float>({ {5, 6}, {7, 8}, })); std::unique_ptr<Array4D<float>> actual = ReferenceUtil::ConvArray4D(input, weights, {1, 1}, Padding::kSame); Array4D<float> expected(1, 1, 4, 4); expected.FillWithYX(Array2D<float>({ {100, 126, 152, 76}, {204, 230, 256, 124}, {308, 334, 360, 172}, {149, 160, 171, 80}, })); auto actual_literal = LiteralUtil::CreateR4FromArray4D(*actual); LiteralTestUtil::ExpectR4NearArray4D<float>(expected, actual_literal, ErrorSpec(0.0001)); } TEST_F(ReferenceUtilTest, ConvWithValidPadding) { Array4D<float> input(1, 1, 4, 4); input.FillWithYX(Array2D<float>({ {1, 2, 3, 4 }, {5, 6, 7, 8 }, {9, 10, 11, 12}, {13, 14, 15, 16}, })); Array4D<float> weights(1, 1, 2, 2); weights.FillWithYX(Array2D<float>({ {5, 6}, {7, 8}, })); std::unique_ptr<Array4D<float>> actual = ReferenceUtil::ConvArray4D(input, weights, {1, 1}, Padding::kValid); Array4D<float> expected(1, 1, 3, 3); expected.FillWithYX(Array2D<float>({ {1*5+2*6+5*7+6*8, 126, 152}, {204, 230, 256}, {308, 334, 11*5+12*6+15*7+16*8}, })); auto actual_literal = LiteralUtil::CreateR4FromArray4D(*actual); LiteralTestUtil::ExpectR4NearArray4D<float>(expected, actual_literal, ErrorSpec(0.0001)); } TEST_F(ReferenceUtilTest, ConvGeneralDimensionsWithSamePadding) { Array4D<float> input({ {{{1, 2, 3, 4}}, {{5, 6, 7, 8}}, {{9, 10, 11, 12}}}, {{{13, 14, 15, 16}}, {{17, 18, 19, 20}}, {{21, 22, 23, 24}}} }); Array4D<float> weight({{ {{1, 2, 3}, {4, 5, 6}}, {{7, 8, 9}, {10, 11, 12}}, {{13, 14, 15}, {16, 17, 18}} }}); ConvolutionDimensionNumbers dimension_numbers; dimension_numbers.set_input_batch_dimension(2); dimension_numbers.set_input_feature_dimension(0); dimension_numbers.set_output_batch_dimension(2); dimension_numbers.set_output_feature_dimension(0); dimension_numbers.add_input_spatial_dimensions(1); dimension_numbers.add_output_spatial_dimensions(1); dimension_numbers.add_input_spatial_dimensions(3); dimension_numbers.add_output_spatial_dimensions(3); dimension_numbers.set_kernel_output_feature_dimension(0); dimension_numbers.set_kernel_input_feature_dimension(2); dimension_numbers.add_kernel_spatial_dimensions(1); dimension_numbers.add_kernel_spatial_dimensions(3); std::unique_ptr<Array4D<float>> actual = ReferenceUtil::ConvArray4DGeneralDimensions( input, weight, {1, 1}, Padding::kSame, dimension_numbers); Array4D<float> expected({{ {{1110, 1688, 1838, 1226}}, {{1683, 2514, 2685, 1761}}, {{878, 1280, 1358, 866}} }}); auto actual_literal = LiteralUtil::CreateR4FromArray4D(*actual); LiteralTestUtil::ExpectR4NearArray4D<float>(expected, actual_literal, ErrorSpec(0.0001)); } TEST_F(ReferenceUtilTest, ConvGeneralDimensionsWithValidPadding) { Array4D<float> input({ {{{1, 2, 3, 4}}, {{5, 6, 7, 8}}, {{9, 10, 11, 12}}}, {{{13, 14, 15, 16}}, {{17, 18, 19, 20}}, {{21, 22, 23, 24}}} }); Array4D<float> weight({{ {{1, 7, 13}, {4, 10, 16}}, {{2, 8, 14}, {5, 11, 17}}, {{3, 9, 15}, {6, 12, 18}} }}); ConvolutionDimensionNumbers dimension_numbers; dimension_numbers.set_input_batch_dimension(2); dimension_numbers.set_input_feature_dimension(0); dimension_numbers.set_output_batch_dimension(2); dimension_numbers.set_output_feature_dimension(0); dimension_numbers.add_input_spatial_dimensions(1); dimension_numbers.add_output_spatial_dimensions(1); dimension_numbers.add_input_spatial_dimensions(3); dimension_numbers.add_output_spatial_dimensions(3); dimension_numbers.set_kernel_output_feature_dimension(0); dimension_numbers.set_kernel_input_feature_dimension(2); dimension_numbers.add_kernel_spatial_dimensions(3); dimension_numbers.add_kernel_spatial_dimensions(1); std::unique_ptr<Array4D<float>> actual = ReferenceUtil::ConvArray4DGeneralDimensions( input, weight, {1, 1}, Padding::kValid, dimension_numbers); Array4D<float> expected({{{{2514, 2685}}}}); auto actual_literal = LiteralUtil::CreateR4FromArray4D(*actual); LiteralTestUtil::ExpectR4NearArray4D<float>(expected, actual_literal, ErrorSpec(0.0001)); } TEST_F(ReferenceUtilTest, ApplyElementwise2D) { Array2D<float> a({{1, 2}, {3, 4}}); Array2D<float> b({{10, 20}, {30, 40}}); Array2D<float> c({{100, 200}, {300, 400}}); auto actual = ReferenceUtil::ApplyElementwise2D( [](float x, float y, float z) { return 100 * x + 10 * y + z; }, a, b, c); auto actual_literal = LiteralUtil::CreateR2FromArray2D(*actual); LiteralTestUtil::ExpectR2Near({{300.f, 600.f}, {900.f, 1200.f}}, actual_literal, ErrorSpec(0.0001)); } } }
https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/third_party/xla/xla/reference_util.cc
https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/third_party/xla/xla/reference_util_test.cc
4a29233a7b7c1a3a4294e4ccdd1772f9083944ea
a1f2d497-f959-4a6e-86b8-c65f9c20ebd5
cpp
tensorflow/tensorflow
util
tensorflow/compiler/mlir/tfrt/transforms/mlrt/util.cc
tensorflow/cc/saved_model/util_test.cc
#include "tensorflow/compiler/mlir/tfrt/transforms/mlrt/util.h" #include "llvm/Support/Casting.h" #include "mlir/IR/Operation.h" #include "tensorflow/compiler/mlir/tensorflow/ir/host_runtime/tfrt_ops.h.inc" #include "tensorflow/compiler/mlir/tensorflow/ir/tf_dialect.h" #include "tensorflow/compiler/mlir/tensorflow/ir/tf_ops.h" #include "tensorflow/compiler/mlir/tensorflow/ir/tf_ops_a_m.h.inc" #include "tensorflow/compiler/mlir/tensorflow/ir/tf_ops_n_z.h.inc" namespace tensorflow { namespace mlrt_compiler { bool UseFallback(mlir::Operation *op) { if (!llvm::isa<mlir::TF::TensorFlowDialect>(op->getDialect())) return false; return !llvm::isa< mlir::TF::_TfrtSetResourceOp, mlir::TF::_TfrtGetResourceOp, mlir::TF::BatchFunctionOp, mlir::TF::CaseOp, mlir::TF::IfrtRestoreVariableOp, mlir::TF::StatefulPartitionedCallOp, mlir::TF::PartitionedCallOp, mlir::TF::LegacyCallOp, mlir::TF::IfOp, mlir::TF::WhileOp, mlir::TF::TPUCompileMlirAndExecuteOp>(op); } } }
#include "tensorflow/cc/saved_model/util.h" #include <map> #include <string> #include <utility> #include <vector> #include "tensorflow/cc/saved_model/test_utils.h" #include "tensorflow/core/framework/tensor_shape.pb.h" #include "tensorflow/core/framework/tensor_testutil.h" #include "tensorflow/core/lib/core/status_test_util.h" #include "tensorflow/core/lib/io/path.h" #include "tensorflow/core/platform/env.h" #include "tensorflow/core/platform/test.h" #include "tensorflow/core/protobuf/meta_graph.pb.h" #include "tensorflow/core/protobuf/saved_object_graph.pb.h" #include "tsl/platform/status_matchers.h" namespace tensorflow { namespace saved_model { namespace { using tsl::testing::StatusIs; TEST(UtilTest, TestGetWriteVersionV2) { SavedModel saved_model_proto; MetaGraphDef* meta_graphdef = saved_model_proto.add_meta_graphs(); auto* object_graph_def = meta_graphdef->mutable_object_graph_def(); object_graph_def->add_nodes(); EXPECT_EQ(GetWriteVersion(saved_model_proto), "2"); } TEST(UtilTest, TestGetWriteVersionV1) { SavedModel saved_model_proto; saved_model_proto.add_meta_graphs(); EXPECT_EQ(GetWriteVersion(saved_model_proto), "1"); saved_model_proto.add_meta_graphs(); EXPECT_EQ(GetWriteVersion(saved_model_proto), "1"); } class GetInputValuesTest : public ::testing::Test { public: GetInputValuesTest() { (*sig_.mutable_inputs())["x"].set_name("feed_x"); (*sig_.mutable_inputs())["y"].set_name("feed_y"); (*sig_.mutable_defaults())["x"] = CreateTensorProto(1); (*sig_.mutable_defaults())["y"] = CreateTensorProto("A"); request_["x"] = CreateTensorProto(2); request_["y"] = CreateTensorProto("B"); unaliased_request_["feed_x"] = CreateTensorProto(2); unaliased_request_["feed_y"] = CreateTensorProto("B"); input_x_ = CreateTensorProto(2); input_y_ = CreateTensorProto("B"); default_x_ = CreateTensorProto(1); default_y_ = CreateTensorProto("A"); } template <class T> TensorProto CreateTensorProto(const T& val) { Tensor tensor(val); TensorProto tensor_proto; tensor.AsProtoTensorContent(&tensor_proto); return tensor_proto; } void ConvertOutputTensorToProto( std::vector<std::pair<string, Tensor>>& inputs, std::vector<std::pair<string, TensorProto>>& protos) { for (const auto& input : inputs) { TensorProto tensor_proto; input.second.AsProtoTensorContent(&tensor_proto); protos.push_back({input.first, std::move(tensor_proto)}); } } SignatureDef sig_; google::protobuf::Map<std::string, TensorProto> request_; std::map<std::string, TensorProto> unaliased_request_; TensorProto input_x_, input_y_, default_x_, default_y_; }; TEST_F(GetInputValuesTest, RequestContainsInvalidInputs) { google::protobuf::Map<std::string, TensorProto> local_request = request_; local_request["xx"] = CreateTensorProto(2); std::vector<std::pair<string, Tensor>> inputs; EXPECT_THAT(GetInputValues(sig_, local_request, inputs), StatusIs(absl::StatusCode::kInvalidArgument)); } TEST_F(GetInputValuesTest, RequestContainsAllTheInputs) { std::vector<std::pair<string, Tensor>> inputs; TF_EXPECT_OK(GetInputValues(sig_, request_, inputs)); std::vector<std::pair<string, TensorProto>> exp_inputs; ConvertOutputTensorToProto(inputs, exp_inputs); EXPECT_THAT(exp_inputs, UnorderedElementsAre(Pair("feed_x", EqualsProto(input_x_)), Pair("feed_y", EqualsProto(input_y_)))); } TEST_F(GetInputValuesTest, RequestContainsNoInputs) { google::protobuf::Map<std::string, TensorProto> local_request = request_; local_request.erase("x"); local_request.erase("y"); std::vector<std::pair<string, Tensor>> inputs; TF_EXPECT_OK(GetInputValues(sig_, local_request, inputs)); std::vector<std::pair<string, TensorProto>> exp_inputs; ConvertOutputTensorToProto(inputs, exp_inputs); EXPECT_THAT(exp_inputs, UnorderedElementsAre(Pair("feed_x", EqualsProto(default_x_)), Pair("feed_y", EqualsProto(default_y_)))); } TEST_F(GetInputValuesTest, RequestContainsPartialInputs) { google::protobuf::Map<std::string, TensorProto> local_request = request_; local_request.erase("y"); std::vector<std::pair<string, Tensor>> inputs; TF_EXPECT_OK(GetInputValues(sig_, local_request, inputs)); std::vector<std::pair<string, TensorProto>> exp_inputs; ConvertOutputTensorToProto(inputs, exp_inputs); EXPECT_THAT(exp_inputs, UnorderedElementsAre(Pair("feed_x", EqualsProto(input_x_)), Pair("feed_y", EqualsProto(default_y_)))); } } } }
https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/tensorflow/compiler/mlir/tfrt/transforms/mlrt/util.cc
https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/tensorflow/cc/saved_model/util_test.cc
4a29233a7b7c1a3a4294e4ccdd1772f9083944ea
81f07eaa-6daf-4636-87c4-9733b688408d
cpp
tensorflow/tensorflow
layout
third_party/xla/xla/layout.cc
third_party/xla/xla/layout_test.cc
#include "xla/layout.h" #include <cstdint> #include <memory> #include <ostream> #include <string> #include <utility> #include "absl/strings/str_cat.h" #include "absl/strings/str_join.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "xla/layout_util.h" #include "xla/primitive_util.h" #include "xla/printer.h" #include "xla/shape.h" #include "xla/xla_data.pb.h" #include "tsl/platform/logging.h" namespace xla { TileProto Tile::ToProto() const { TileProto tile_proto; SetProto(tile_proto); return tile_proto; } void Tile::SetProto(TileProto& tile_proto) const { tile_proto.Clear(); for (int64_t i : dimensions()) { tile_proto.add_dimensions(i); } } void Tile::Print(Printer* printer) const { printer->Append("("); AppendJoin(printer, dimensions(), ",", [&](Printer* printer, int64_t dim) { if (dim >= 0) { printer->Append(dim); } else { if (dim == kCombineDimension) { printer->Append("*"); } else { printer->Append("Invalid value "); printer->Append(dim); } } }); printer->Append(")"); } std::string Tile::ToString() const { StringPrinter printer; Print(&printer); return std::move(printer).ToString(); } Layout::Layout() : index_primitive_type_(PRIMITIVE_TYPE_INVALID), pointer_primitive_type_(PRIMITIVE_TYPE_INVALID) {} SplitConfigProto SplitConfig::ToProto() const { SplitConfigProto split_config_proto; split_config_proto.set_dimension(dimension_); for (int64_t i : split_indices_) { split_config_proto.add_split_indices(i); } return split_config_proto; } void SplitConfig::SetProto(SplitConfigProto& split_config_proto) const { split_config_proto.Clear(); split_config_proto.set_dimension(dimension_); for (int64_t i : split_indices_) { split_config_proto.add_split_indices(i); } } std::string SplitConfig::ToString() const { return absl::StrCat("(", dimension_, ":", absl::StrJoin(split_indices_, ","), ")"); } Layout::Layout(absl::Span<const int64_t> minor_to_major) : index_primitive_type_(PRIMITIVE_TYPE_INVALID), pointer_primitive_type_(PRIMITIVE_TYPE_INVALID), minor_to_major_(minor_to_major.begin(), minor_to_major.end()) {} Layout::Layout(absl::Span<const int64_t> minor_to_major, absl::Span<const Tile> tiles, int64_t element_size_in_bits) : index_primitive_type_(PRIMITIVE_TYPE_INVALID), pointer_primitive_type_(PRIMITIVE_TYPE_INVALID), element_size_in_bits_(element_size_in_bits), minor_to_major_(minor_to_major.begin(), minor_to_major.end()), tiles_(tiles.begin(), tiles.end()) {} Layout::Layout(absl::Span<const int64_t> minor_to_major, absl::Span<const DimLevelType> dim_level_types, absl::Span<const bool> dim_unique, absl::Span<const bool> dim_ordered, absl::Span<const Tile> tiles, int64_t tail_padding_alignment_in_elements, PrimitiveType index_primitive_type, PrimitiveType element_primitive_type, int64_t element_size_in_bits, int64_t memory_space, absl::Span<const SplitConfig> split_configs, std::unique_ptr<Shape> physical_shape, int64_t dynamic_shape_metadata_prefix_bytes) : index_primitive_type_(index_primitive_type), pointer_primitive_type_(element_primitive_type), memory_space_(memory_space), element_size_in_bits_(element_size_in_bits), minor_to_major_(minor_to_major.begin(), minor_to_major.end()), tiles_(tiles.begin(), tiles.end()), split_configs_(split_configs.begin(), split_configs.end()), tail_padding_alignment_in_elements_(tail_padding_alignment_in_elements), physical_shape_(std::move(physical_shape)), dynamic_shape_metadata_prefix_bytes_( dynamic_shape_metadata_prefix_bytes) { n_dim_level_types_ = dim_level_types.size(); n_dim_unique_ = dim_unique.size(); n_dim_ordered_ = dim_ordered.size(); const int n_attributes = std::max<int>( n_dim_level_types_, std::max<int>(n_dim_unique_, n_dim_ordered_)); dim_attributes_.resize(n_attributes); for (int i = 0; i < n_attributes; i++) { if (i < n_dim_level_types_) dim_attributes_[i].dim_level_type = dim_level_types[i]; if (i < n_dim_unique_) dim_attributes_[i].dim_unique = dim_unique[i]; if (i < n_dim_ordered_) dim_attributes_[i].dim_ordered = dim_ordered[i]; } } Layout::Layout(const Layout& other) : dim_attributes_(other.dim_attributes_), n_dim_level_types_(other.n_dim_level_types_), n_dim_unique_(other.n_dim_unique_), n_dim_ordered_(other.n_dim_ordered_), index_primitive_type_(other.index_primitive_type_), pointer_primitive_type_(other.pointer_primitive_type_), memory_space_(other.memory_space_), element_size_in_bits_(other.element_size_in_bits_), minor_to_major_(other.minor_to_major_), tiles_(other.tiles_), split_configs_(other.split_configs_), tail_padding_alignment_in_elements_( other.tail_padding_alignment_in_elements_), physical_shape_(other.physical_shape_ != nullptr ? std::make_unique<Shape>(*other.physical_shape_) : nullptr), dynamic_shape_metadata_prefix_bytes_( other.dynamic_shape_metadata_prefix_bytes_) {} Layout::Layout(Layout&& other) = default; Layout::~Layout() = default; Layout& Layout::operator=(const Layout& other) { if (this != &other) { dim_attributes_ = other.dim_attributes_; n_dim_level_types_ = other.n_dim_level_types_; n_dim_unique_ = other.n_dim_unique_; n_dim_ordered_ = other.n_dim_ordered_; minor_to_major_ = other.minor_to_major_; tiles_ = other.tiles_; tail_padding_alignment_in_elements_ = other.tail_padding_alignment_in_elements_; index_primitive_type_ = other.index_primitive_type_; pointer_primitive_type_ = other.pointer_primitive_type_; element_size_in_bits_ = other.element_size_in_bits_; memory_space_ = other.memory_space_; split_configs_ = other.split_configs_; if (other.physical_shape_ != nullptr) { physical_shape_ = std::make_unique<Shape>(*other.physical_shape_); } else { physical_shape_ = nullptr; } dynamic_shape_metadata_prefix_bytes_ = other.dynamic_shape_metadata_prefix_bytes_; } return *this; } Layout& Layout::operator=(Layout&& other) = default; Layout Layout::CreateFromProto(const LayoutProto& proto) { Layout layout; for (int dim_level_type : proto.dim_level_types()) { layout.add_dim_level_type(static_cast<DimLevelType>(dim_level_type)); } for (bool dim_unique : proto.dim_unique()) { layout.add_dim_unique(dim_unique); } for (bool dim_ordered : proto.dim_ordered()) { layout.add_dim_ordered(dim_ordered); } layout.minor_to_major_.reserve(proto.minor_to_major_size()); for (const int64_t dimension : proto.minor_to_major()) { layout.add_minor_to_major(dimension); } for (const TileProto& tile_proto : proto.tiles()) { *layout.add_tiles() = Tile::CreateFromProto(tile_proto); } if (proto.tail_padding_alignment_in_elements() != 0) { layout.set_tail_padding_alignment_in_elements( proto.tail_padding_alignment_in_elements()); } else { layout.set_tail_padding_alignment_in_elements(1); } layout.set_index_primitive_type(proto.index_primitive_type()); layout.set_pointer_primitive_type(proto.pointer_primitive_type()); layout.set_element_size_in_bits(proto.element_size_in_bits()); layout.set_memory_space(proto.memory_space()); for (const SplitConfigProto& split_config_proto : proto.split_configs()) { layout.add_split_configs(SplitConfig::CreateFromProto(split_config_proto)); } if (proto.has_physical_shape()) { *layout.mutable_physical_shape() = Shape(proto.physical_shape()); } layout.set_dynamic_shape_metadata_prefix_bytes( proto.dynamic_shape_metadata_prefix_bytes()); return layout; } LayoutProto Layout::ToProto() const { LayoutProto proto; SetProto(proto); return proto; } void Layout::SetProto(LayoutProto& proto) const { proto.Clear(); for (int i = 0; i < n_dim_level_types_; i++) { proto.add_dim_level_types(dim_level_type(i)); } for (int i = 0; i < n_dim_unique_; i++) { proto.add_dim_unique(dim_unique(i)); } for (int i = 0; i < n_dim_ordered_; i++) { proto.add_dim_ordered(dim_ordered(i)); } proto.mutable_minor_to_major()->Reserve(minor_to_major_size()); for (const int64_t dimension : minor_to_major()) { proto.add_minor_to_major(dimension); } for (const Tile& tile : tiles()) { tile.SetProto(*proto.add_tiles()); } proto.set_tail_padding_alignment_in_elements( tail_padding_alignment_in_elements()); proto.set_index_primitive_type(index_primitive_type()); proto.set_pointer_primitive_type(pointer_primitive_type()); proto.set_element_size_in_bits(element_size_in_bits_); proto.set_memory_space(memory_space_); for (const SplitConfig& split_config : split_configs()) { split_config.SetProto(*proto.add_split_configs()); } if (has_physical_shape()) { *proto.mutable_physical_shape() = physical_shape_->ToProto(); } proto.set_dynamic_shape_metadata_prefix_bytes( dynamic_shape_metadata_prefix_bytes_); } namespace { absl::string_view DimLevelTypeAbbrev(DimLevelType dim_level_type) { switch (dim_level_type) { case DIM_DENSE: return "D"; case DIM_COMPRESSED: return "C"; case DIM_SINGLETON: return "S"; case xla::DIM_LOOSE_COMPRESSED: return "H"; default: LOG(FATAL) << "Invalid DimLevelType value: " << dim_level_type; } } } void Layout::Print(Printer* printer) const { printer->Append("{"); AppendJoin(printer, minor_to_major(), ","); bool colon_printed = false; auto print_colon = [&]() { if (colon_printed) return; printer->Append(":"); colon_printed = true; }; if (n_dim_level_types_ > 0) { auto print_one = [&](int i) { printer->Append(DimLevelTypeAbbrev(dim_level_type(i))); if (n_dim_unique_ > 0 && !dim_unique(i)) { printer->Append("+"); } if (n_dim_ordered_ > 0 && !dim_ordered(i)) { printer->Append("~"); } }; print_colon(); printer->Append("D("); print_one(0); for (int i = 1; i < n_dim_level_types_; ++i) { printer->Append(","); print_one(i); } printer->Append(")"); } if (!tiles().empty()) { print_colon(); printer->Append("T"); for (const Tile& tile : tiles()) { tile.Print(printer); } } if (tail_padding_alignment_in_elements() != 1) { print_colon(); printer->Append("L("); printer->Append(tail_padding_alignment_in_elements()); printer->Append(")"); } if (index_primitive_type() != PRIMITIVE_TYPE_INVALID) { print_colon(); if (primitive_util::IsIntegralType(index_primitive_type())) { printer->Append("#("); printer->Append( primitive_util::LowercasePrimitiveTypeName(index_primitive_type())); printer->Append(")"); } else { printer->Append("#(invalid)"); } } if (pointer_primitive_type() != PRIMITIVE_TYPE_INVALID) { print_colon(); if (primitive_util::IsIntegralType(pointer_primitive_type())) { printer->Append("*("); printer->Append( primitive_util::LowercasePrimitiveTypeName(pointer_primitive_type())); printer->Append(")"); } else { printer->Append("*(invalid)"); } } if (element_size_in_bits() != 0) { print_colon(); printer->Append("E("); printer->Append(element_size_in_bits()); printer->Append(")"); } if (memory_space() != 0) { print_colon(); printer->Append("S("); printer->Append(memory_space()); printer->Append(")"); } if (!split_configs().empty()) { print_colon(); printer->Append("SC"); for (const auto& split_config : split_configs()) { printer->Append(split_config.ToString()); } } if (has_physical_shape()) { print_colon(); printer->Append("P("); physical_shape_->Print(printer, true); printer->Append(")"); } if (dynamic_shape_metadata_prefix_bytes_ > 0) { print_colon(); printer->Append("M("); printer->Append(dynamic_shape_metadata_prefix_bytes()); printer->Append(")"); } printer->Append("}"); } std::string Layout::ToString() const { StringPrinter printer; Print(&printer); return std::move(printer).ToString(); } bool Layout::Equal::operator()(const Layout& lhs, const Layout& rhs) { if (!LayoutUtil::IsDense(lhs) || !LayoutUtil::IsDense(rhs)) { if (lhs.dim_level_types_size() != rhs.dim_level_types_size()) { return false; } for (int i = 0; i < lhs.dim_level_types_size(); i++) { if (lhs.dim_level_type(i) != rhs.dim_level_type(i)) { return false; } } if (lhs.dim_unique_size() != rhs.dim_unique_size()) { return false; } for (int i = 0; i < lhs.dim_unique_size(); i++) { if (lhs.dim_unique(i) != rhs.dim_unique(i)) { return false; } } if (lhs.dim_ordered_size() != rhs.dim_ordered_size()) { return false; } for (int i = 0; i < lhs.dim_ordered_size(); i++) { if (lhs.dim_ordered(i) != rhs.dim_ordered(i)) { return false; } } } if (lhs.minor_to_major() != rhs.minor_to_major()) { return false; } if (!ignore_tiles_ && lhs.tiles() != rhs.tiles()) { return false; } if (!ignore_tail_padding_alignment_in_elements_ && lhs.tail_padding_alignment_in_elements() != rhs.tail_padding_alignment_in_elements()) { return false; } if (!ignore_index_primitive_type_ && lhs.index_primitive_type() != rhs.index_primitive_type()) { return false; } if (!ignore_pointer_primitive_type_ && lhs.pointer_primitive_type() != rhs.pointer_primitive_type()) { return false; } if (!ignore_element_size_ && lhs.element_size_in_bits() != rhs.element_size_in_bits()) { return false; } if (!ignore_memory_space_ && lhs.memory_space() != rhs.memory_space()) { return false; } if (!ignore_split_configs_ && lhs.split_configs() != rhs.split_configs()) { return false; } if (!ignore_physical_shape_) { if (lhs.has_physical_shape() || rhs.has_physical_shape()) { if (!lhs.has_physical_shape() || !rhs.has_physical_shape()) { return false; } if (lhs.physical_shape() != rhs.physical_shape()) { return false; } } } return true; } bool Layout::operator==(const Layout& other) const { return Equal()(*this, other); } std::ostream& operator<<(std::ostream& out, const Tile& tile) { out << tile.ToString(); return out; } std::ostream& operator<<(std::ostream& out, const Layout& layout) { out << layout.ToString(); return out; } Shape* Layout::mutable_physical_shape() { if (physical_shape_ == nullptr) { physical_shape_ = std::make_unique<Shape>(); } return physical_shape_.get(); } void Layout::clear_physical_shape() { physical_shape_ = nullptr; } Layout& Layout::DeleteDimension(int64_t dim_to_delete) { for (int64_t i = 0; i < minor_to_major_.size();) { if (minor_to_major_[i] == dim_to_delete) { minor_to_major_.erase(minor_to_major_.begin() + i); continue; } if (minor_to_major_[i] > dim_to_delete) { minor_to_major_[i] -= 1; } ++i; } if (LayoutUtil::IsSparse(*this)) { if (dim_to_delete < n_dim_level_types_) n_dim_level_types_--; if (dim_to_delete < n_dim_unique_) n_dim_unique_--; if (dim_to_delete < n_dim_ordered_) n_dim_ordered_--; dim_attributes_.erase(dim_attributes_.begin() + dim_to_delete); } return *this; } }
#include "xla/layout.h" #include <cstdint> #include <memory> #include <sstream> #include <vector> #include "xla/shape_util.h" #include "xla/test.h" #include "xla/xla_data.pb.h" namespace xla { namespace { class LayoutTest : public ::testing::Test {}; TEST_F(LayoutTest, ToString) { EXPECT_EQ(Layout().ToString(), "{}"); EXPECT_EQ(Layout({4, 5, 6}).ToString(), "{4,5,6}"); EXPECT_EQ(Layout({4, 5, 6}).ToString(), "{4,5,6}"); EXPECT_EQ(Layout({3, 2, 1, 0}, {}, {}, {}, {Tile({42, 123}), Tile({4, 5})}) .ToString(), "{3,2,1,0:T(42,123)(4,5)}"); EXPECT_EQ(Layout({3, 2, 1, 0}, {}, {}, {}, {Tile({42, 123}), Tile({4, 5})}) .set_tail_padding_alignment_in_elements(100) .set_element_size_in_bits(42) .ToString(), "{3,2,1,0:T(42,123)(4,5)L(100)E(42)}"); EXPECT_EQ(Layout({3, 2, 1, 0}, {}, {}, {}, {Tile({42, 123}), Tile({4, 5})}) .set_memory_space(3) .ToString(), "{3,2,1,0:T(42,123)(4,5)S(3)}"); EXPECT_EQ(Layout({0, 1}, {}, {}, {}, {Tile({123})}) .add_split_configs(SplitConfig(0, {3})) .add_split_configs(SplitConfig(1, {0, 4})) .ToString(), "{0,1:T(123)SC(0:3)(1:0,4)}"); } TEST_F(LayoutTest, StreamOut) { { std::ostringstream oss; oss << Tile({7, 8}); EXPECT_EQ(oss.str(), "(7,8)"); } { std::ostringstream oss; oss << Layout({0, 1, 2}); EXPECT_EQ(oss.str(), "{0,1,2}"); } } TEST_F(LayoutTest, Equality) { EXPECT_EQ(Layout(), Layout()); const std::vector<int64_t> empty_dims; EXPECT_EQ(Layout(empty_dims), Layout(empty_dims)); EXPECT_EQ(Layout(), Layout(empty_dims)); EXPECT_EQ(Layout({0, 1, 2, 3}), Layout({0, 1, 2, 3})); EXPECT_NE(Layout({0, 1, 2, 3}), Layout({0, 1, 2})); EXPECT_EQ(Layout({0, 1, 2}, {}, {}, {}, {Tile({42, 44})}), Layout({0, 1, 2}, {}, {}, {}, {Tile({42, 44})})); EXPECT_NE(Layout({0, 1, 2}, {}, {}, {}, {Tile({42, 44})}), Layout({0, 1, 2}, {}, {}, {}, {Tile({42, 45})})); EXPECT_NE(Layout({0, 1, 2}, {}, {}, {}, {Tile({42, 44})}), Layout({0, 1, 2, 3})); EXPECT_EQ(Layout({0, 1, 2}).set_element_size_in_bits(33), Layout({0, 1, 2}).set_element_size_in_bits(33)); EXPECT_NE(Layout({0, 1, 2}).set_element_size_in_bits(33), Layout({0, 1, 2}).set_element_size_in_bits(7)); EXPECT_EQ(Layout({0, 1, 2}).set_memory_space(3), Layout({0, 1, 2}).set_memory_space(3)); EXPECT_NE(Layout({0, 1, 2}).set_memory_space(1), Layout({0, 1, 2}).set_memory_space(3)); EXPECT_FALSE(Layout::Equal()(Layout({0, 1, 2}, {}, {}, {}, {Tile({42, 44})}), Layout({0, 1, 2}))); EXPECT_EQ(Layout({0, 1, 2}).add_split_configs(SplitConfig(0, {2})), Layout({0, 1, 2}).add_split_configs(SplitConfig(0, {2}))); EXPECT_NE(Layout({0, 1, 2}).add_split_configs(SplitConfig(0, {2})), Layout({0, 1, 2}).add_split_configs(SplitConfig(0, {3}))); EXPECT_TRUE(Layout::Equal().IgnoreTiles()( Layout({0, 1, 2}, {}, {}, {}, {Tile({42, 44})}), Layout({0, 1, 2}))); EXPECT_FALSE(Layout::Equal()( Layout({0, 1, 2}, {}, {}, {}, {}, 1, PRIMITIVE_TYPE_INVALID, PRIMITIVE_TYPE_INVALID, 32), Layout({0, 1, 2}, {}, {}, {}, {}, 1, PRIMITIVE_TYPE_INVALID, PRIMITIVE_TYPE_INVALID, 1))); EXPECT_TRUE(Layout::Equal().IgnoreElementSize()( Layout({0, 1, 2}).set_element_size_in_bits(32), Layout({0, 1, 2}).set_element_size_in_bits(1))); EXPECT_TRUE(Layout::Equal().IgnoreMemorySpace()( Layout({0, 1, 2}).set_memory_space(1), Layout({0, 1, 2}).set_memory_space(3))); EXPECT_TRUE(Layout::Equal().IgnoreSplitConfigs()( Layout({0, 1, 2}).add_split_configs(SplitConfig(0, {2})), Layout({0, 1, 2}).add_split_configs(SplitConfig(0, {3})))); } TEST_F(LayoutTest, LayoutToFromProto) { auto expect_unchanged = [](const Layout& layout) { EXPECT_EQ(layout, Layout::CreateFromProto(layout.ToProto())); }; expect_unchanged(Layout()); expect_unchanged(Layout({1, 3, 2, 0})); expect_unchanged(Layout({0, 1}).set_element_size_in_bits(42)); expect_unchanged( Layout({3, 2, 1, 0}, {}, {}, {}, {Tile({42, 123}), Tile({4, 5})})); expect_unchanged(Layout({1, 0}, {DIM_DENSE, DIM_COMPRESSED}, {}, {}, {})); expect_unchanged( Layout({1, 0}, {DIM_DENSE, DIM_COMPRESSED}, {}, {}, {}, 1, PRIMITIVE_TYPE_INVALID, PRIMITIVE_TYPE_INVALID, 0, 0, {}, std::make_unique<Shape>(ShapeUtil::MakeShape(S32, {10, 10})))); expect_unchanged(Layout({0, 1}, {}, {}, {}, {Tile({123})}) .add_split_configs(SplitConfig(0, {3})) .add_split_configs(SplitConfig(1, {0, 4}))); } } }
https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/third_party/xla/xla/layout.cc
https://github.com/tensorflow/tensorflow/blob/4a29233a7b7c1a3a4294e4ccdd1772f9083944ea/third_party/xla/xla/layout_test.cc
4a29233a7b7c1a3a4294e4ccdd1772f9083944ea