ID
int64
0
2.65k
Language
stringclasses
1 value
Repository Name
stringclasses
14 values
File Name
stringlengths
2
48
File Path in Repository
stringlengths
11
111
File Path for Unit Test
stringlengths
16
116
Code
stringlengths
411
31.4k
Unit Test - (Ground Truth)
stringlengths
40
32.1k
2,300
cpp
tensorflow/tensorflow
trace_container
third_party/xla/third_party/tsl/tsl/profiler/convert/trace_container.cc
third_party/xla/third_party/tsl/tsl/profiler/convert/trace_container_test.cc
#ifndef TENSORFLOW_TSL_PROFILER_CONVERT_TRACE_CONTAINER_H_ #define TENSORFLOW_TSL_PROFILER_CONVERT_TRACE_CONTAINER_H_ #include <string> #include <string_view> #include <vector> #include "tsl/profiler/protobuf/trace_events.pb.h" namespace tsl { namespace profiler { using tsl::profiler::Device; using tsl::profiler::Trace; using tsl::profiler::TraceEvent; template <typename Event> class AnyTraceContainer { public: virtual ~AnyTraceContainer() = default; virtual TraceEvent* CreateEvent() = 0; virtual const std::vector<TraceEvent*>& UnsortedEvents() const = 0; }; class TraceContainer : public AnyTraceContainer<TraceEvent> { public: TraceContainer() = default; ~TraceContainer() final { for (const TraceEvent* event : events_) { delete event; } } const Trace& trace() const { return metadata_; } const std::vector<TraceEvent*>& UnsortedEvents() const final { return events_; } void CapEvents(uint32_t max_count); Device* MutableDevice(uint32_t device_id) { return &(*metadata_.mutable_devices())[device_id]; } TraceEvent* CreateEvent() final { TraceEvent* event = new TraceEvent; events_.push_back(event); return event; } void FlushAndSerializeEvents(std::string* output); bool ParseMetadataFromString(const std::string& description); private: Trace metadata_; std::vector<TraceEvent*> events_; }; } } #endif #include "tsl/profiler/convert/trace_container.h" #include <algorithm> #include <string> #include <string_view> #include <vector> #include "tsl/platform/protobuf.h" namespace tsl { namespace profiler { bool TraceContainer::ParseMetadataFromString(const std::string& description) { return protobuf::TextFormat::ParseFromString(description, &metadata_); } void TraceContainer::CapEvents(const uint32_t max_count) { const size_t total_count = events_.size(); if (total_count <= max_count) { return; } const std::vector<TraceEvent*>::iterator end = events_.begin() + max_count; std::partial_sort( events_.begin(), end, events_.end(), [](const TraceEvent* const lhs, const TraceEvent* const rhs) -> bool { return lhs->timestamp_ps() < rhs->timestamp_ps(); }); for (std::vector<TraceEvent*>::iterator i = end; i != events_.end(); ++i) { delete *i; } events_.erase(end, events_.end()); } void TraceContainer::FlushAndSerializeEvents(std::string* const output) { Trace trace = metadata_; for (TraceEvent* const event : events_) { trace.mutable_trace_events()->AddAllocated(event); } events_.clear(); trace.SerializeToString(output); } } }
#include "tsl/profiler/convert/trace_container.h" #include <string> #include "tsl/platform/protobuf.h" #include "tsl/platform/test.h" namespace tsl { namespace profiler { namespace { void PopulateDummyEvent(TraceEvent* const event) { event->set_device_id(1); event->set_resource_id(2); event->set_name("A"); event->set_timestamp_ps(3); event->set_duration_ps(4); } TEST(TraceContainer, TraceEventAllocation) { TraceContainer container; PopulateDummyEvent(container.CreateEvent()); } TEST(TraceContainer, FlushAndSerializeEvents) { TraceContainer container; PopulateDummyEvent(container.CreateEvent()); EXPECT_EQ(container.UnsortedEvents().size(), 1); std::string serialized; container.FlushAndSerializeEvents(&serialized); EXPECT_EQ(container.UnsortedEvents().size(), 0); PopulateDummyEvent(container.CreateEvent()); EXPECT_EQ(container.UnsortedEvents().size(), 1); std::string reserialized; container.FlushAndSerializeEvents(&reserialized); EXPECT_EQ(serialized, reserialized); EXPECT_EQ(container.UnsortedEvents().size(), 0); Trace trace; trace.ParseFromString(reserialized); EXPECT_EQ(trace.trace_events_size(), 1); } TEST(TraceContainer, CapEvents) { TraceContainer container; for (int i = 0; i < 100; i++) { container.CreateEvent()->set_timestamp_ps((100 - i) % 50); } container.CapEvents(101); EXPECT_EQ(container.UnsortedEvents().size(), 100); container.CapEvents(100); EXPECT_EQ(container.UnsortedEvents().size(), 100); container.CapEvents(99); EXPECT_EQ(container.UnsortedEvents().size(), 99); container.CapEvents(50); EXPECT_EQ(container.UnsortedEvents().size(), 50); for (const TraceEvent* const event : container.UnsortedEvents()) { EXPECT_LT(event->timestamp_ps(), 25); } } } } }
2,301
cpp
tensorflow/tensorflow
remote_profiler_session_manager
third_party/xla/third_party/tsl/tsl/profiler/rpc/client/remote_profiler_session_manager.cc
third_party/xla/third_party/tsl/tsl/profiler/rpc/client/remote_profiler_session_manager_test.cc
#ifndef TENSORFLOW_TSL_PROFILER_RPC_CLIENT_REMOTE_PROFILER_SESSION_MANAGER_H_ #define TENSORFLOW_TSL_PROFILER_RPC_CLIENT_REMOTE_PROFILER_SESSION_MANAGER_H_ #include <functional> #include <memory> #include <vector> #include "absl/strings/string_view.h" #include "tsl/platform/macros.h" #include "tsl/platform/mutex.h" #include "tsl/platform/status.h" #include "tsl/platform/thread_annotations.h" #include "tsl/platform/types.h" #include "tsl/profiler/rpc/client/profiler_client.h" namespace tsl { namespace profiler { using AddressResolver = std::function<std::string(absl::string_view)>; class RemoteProfilerSessionManager { public: struct Response { std::string service_address; std::unique_ptr<tensorflow::ProfileResponse> profile_response; absl::Status status; }; static std::unique_ptr<RemoteProfilerSessionManager> Create( const tensorflow::RemoteProfilerSessionManagerOptions& options, const tensorflow::ProfileRequest& request, absl::Status& out_status, AddressResolver resolver = nullptr); std::vector<Response> WaitForCompletion(); RemoteProfilerSessionManager(const RemoteProfilerSessionManager&) = delete; RemoteProfilerSessionManager& operator=(const RemoteProfilerSessionManager&) = delete; ~RemoteProfilerSessionManager(); private: explicit RemoteProfilerSessionManager( tensorflow::RemoteProfilerSessionManagerOptions options, tensorflow::ProfileRequest request, AddressResolver resolver); absl::Status Init(); mutex mutex_; tensorflow::RemoteProfilerSessionManagerOptions options_ TF_GUARDED_BY(mutex_); tensorflow::ProfileRequest request_ TF_GUARDED_BY(mutex_); std::vector<std::unique_ptr<RemoteProfilerSession>> clients_ TF_GUARDED_BY(mutex_); AddressResolver resolver_ TF_GUARDED_BY(mutex_); }; } } #endif #include "tsl/profiler/rpc/client/remote_profiler_session_manager.h" #include <cstddef> #include <memory> #include "absl/memory/memory.h" #include "absl/strings/string_view.h" #include "absl/time/clock.h" #include "absl/time/time.h" #include "tsl/platform/env_time.h" #include "tsl/platform/errors.h" #include "tsl/platform/logging.h" #include "tsl/platform/types.h" #include "tsl/profiler/rpc/client/profiler_client.h" #include "tsl/profiler/utils/time_utils.h" namespace tsl { namespace profiler { using tensorflow::ProfileRequest; using tensorflow::RemoteProfilerSessionManagerOptions; std::unique_ptr<RemoteProfilerSessionManager> RemoteProfilerSessionManager::Create( const RemoteProfilerSessionManagerOptions& options, const ProfileRequest& request, absl::Status& out_status, AddressResolver resolver) { VLOG(1) << "Creating a RemoteProfilerSessionManager."; auto session_manager = absl::WrapUnique( new RemoteProfilerSessionManager(options, request, resolver)); out_status = session_manager->Init(); if (!out_status.ok()) { return nullptr; } return session_manager; } RemoteProfilerSessionManager::RemoteProfilerSessionManager( RemoteProfilerSessionManagerOptions options, ProfileRequest request, AddressResolver resolver) : options_(options), request_(request) { if (resolver) { resolver_ = resolver; } else { resolver_ = [](absl::string_view addr) { return std::string(addr); }; } } RemoteProfilerSessionManager::~RemoteProfilerSessionManager() { VLOG(2) << "Destroying RemoteProfilerSessionManager."; } absl::Status RemoteProfilerSessionManager::Init() { mutex_lock lock(mutex_); VLOG(1) << "SessionManager initializing."; const absl::Time session_created_ts = absl::FromUnixNanos(options_.session_creation_timestamp_ns()); const absl::Time deadline = session_created_ts + absl::Milliseconds(options_.max_session_duration_ms()); LOG(INFO) << "Deadline set to " << deadline << " because max_session_duration_ms was " << options_.max_session_duration_ms() << " and session_creation_timestamp_ns was " << options_.session_creation_timestamp_ns() << " [" << session_created_ts << "]"; clients_.reserve(options_.service_addresses_size()); ProfileRequest request = request_; for (auto& service_address : options_.service_addresses()) { std::string resolved_service_address = resolver_(service_address); request.set_host_name(resolved_service_address); auto client = RemoteProfilerSession::Create(resolved_service_address, deadline, request); clients_.push_back(std::move(client)); } LOG(INFO) << "Issued Profile gRPC to " << clients_.size() << " clients"; return absl::OkStatus(); } std::vector<RemoteProfilerSessionManager::Response> RemoteProfilerSessionManager::WaitForCompletion() { mutex_lock lock(mutex_); std::vector<RemoteProfilerSessionManager::Response> remote_responses( clients_.size()); for (int32_t idx = 0; idx < clients_.size(); ++idx) { auto& remote_response = remote_responses[idx]; auto* client = clients_[idx].get(); remote_response.profile_response = client->WaitForCompletion(remote_response.status); remote_response.service_address = std::string(client->GetServiceAddress()); } return remote_responses; } } }
#include "tsl/profiler/rpc/client/remote_profiler_session_manager.h" #include <memory> #include <string> #include <vector> #include "absl/status/status.h" #include "absl/time/clock.h" #include "absl/time/time.h" #include "tsl/platform/errors.h" #include "tsl/platform/status.h" #include "tsl/platform/test.h" #include "tsl/platform/types.h" #include "tsl/profiler/protobuf/profiler_options.pb.h" #include "tsl/profiler/protobuf/profiler_service.pb.h" #include "tsl/profiler/rpc/client/profiler_client_test_util.h" namespace tsl { namespace profiler { namespace { using tensorflow::ProfileRequest; using tensorflow::RemoteProfilerSessionManagerOptions; using ::tsl::profiler::test::DurationApproxLess; using ::tsl::profiler::test::DurationNear; using ::tsl::profiler::test::StartServer; using ::tsl::testing::TmpDir; using Response = tsl::profiler::RemoteProfilerSessionManager::Response; constexpr double kGracePeriodSeconds = 10.0; ProfileRequest PopulateProfileRequest( absl::string_view repository_root, absl::string_view session_id, absl::string_view host_name, const RemoteProfilerSessionManagerOptions& options) { constexpr uint64 kMaxEvents = 1000000; const absl::string_view kXPlanePb = "xplane.pb"; ProfileRequest request; request.set_duration_ms(options.profiler_options().duration_ms()); request.set_max_events(kMaxEvents); request.set_repository_root(repository_root.data(), repository_root.size()); request.set_session_id(session_id.data(), session_id.size()); request.set_host_name(host_name.data(), host_name.size()); request.add_tools(kXPlanePb.data(), kXPlanePb.size()); *request.mutable_opts() = options.profiler_options(); return request; } TEST(RemoteProfilerSessionManagerTest, Simple) { absl::Duration duration = absl::Milliseconds(30); RemoteProfilerSessionManagerOptions options; *options.mutable_profiler_options() = tsl::ProfilerSession::DefaultOptions(); options.mutable_profiler_options()->set_duration_ms( absl::ToInt64Milliseconds(duration)); std::string service_address; auto server = StartServer(duration, &service_address); options.add_service_addresses(service_address); absl::Time approx_start = absl::Now(); absl::Duration grace = absl::Seconds(kGracePeriodSeconds); absl::Duration max_duration = duration + grace; options.set_max_session_duration_ms(absl::ToInt64Milliseconds(max_duration)); options.set_session_creation_timestamp_ns(absl::ToUnixNanos(approx_start)); ProfileRequest request = PopulateProfileRequest(TmpDir(), "session_id", service_address, options); absl::Status status; auto sessions = RemoteProfilerSessionManager::Create(options, request, status); EXPECT_TRUE(status.ok()); std::vector<Response> responses = sessions->WaitForCompletion(); absl::Duration elapsed = absl::Now() - approx_start; ASSERT_EQ(responses.size(), 1); EXPECT_TRUE(responses.back().status.ok()); EXPECT_TRUE(responses.back().profile_response->empty_trace()); EXPECT_EQ(responses.back().profile_response->tool_data_size(), 0); EXPECT_THAT(elapsed, DurationApproxLess(max_duration)); } TEST(RemoteProfilerSessionManagerTest, ExpiredDeadline) { absl::Duration duration = absl::Milliseconds(30); RemoteProfilerSessionManagerOptions options; *options.mutable_profiler_options() = tsl::ProfilerSession::DefaultOptions(); options.mutable_profiler_options()->set_duration_ms( absl::ToInt64Milliseconds(duration)); std::string service_address; auto server = StartServer(duration, &service_address); options.add_service_addresses(service_address); absl::Duration grace = absl::Seconds(kGracePeriodSeconds); absl::Duration max_duration = duration + grace; options.set_max_session_duration_ms(absl::ToInt64Milliseconds(max_duration)); options.set_session_creation_timestamp_ns(0); absl::Time approx_start = absl::Now(); ProfileRequest request = PopulateProfileRequest(TmpDir(), "session_id", service_address, options); absl::Status status; auto sessions = RemoteProfilerSessionManager::Create(options, request, status); EXPECT_TRUE(status.ok()); std::vector<Response> responses = sessions->WaitForCompletion(); absl::Duration elapsed = absl::Now() - approx_start; EXPECT_THAT(elapsed, DurationNear(absl::Seconds(0))); ASSERT_EQ(responses.size(), 1); EXPECT_TRUE(absl::IsDeadlineExceeded(responses.back().status)); EXPECT_TRUE(responses.back().profile_response->empty_trace()); EXPECT_EQ(responses.back().profile_response->tool_data_size(), 0); } TEST(RemoteProfilerSessionManagerTest, LongSession) { absl::Duration duration = absl::Seconds(3); RemoteProfilerSessionManagerOptions options; *options.mutable_profiler_options() = tsl::ProfilerSession::DefaultOptions(); options.mutable_profiler_options()->set_duration_ms( absl::ToInt64Milliseconds(duration)); std::string service_address; auto server = StartServer(duration, &service_address); options.add_service_addresses(service_address); absl::Time approx_start = absl::Now(); absl::Duration grace = absl::Seconds(kGracePeriodSeconds); absl::Duration max_duration = duration + grace; options.set_max_session_duration_ms(absl::ToInt64Milliseconds(max_duration)); options.set_session_creation_timestamp_ns(absl::ToUnixNanos(approx_start)); ProfileRequest request = PopulateProfileRequest(TmpDir(), "session_id", service_address, options); absl::Status status; auto sessions = RemoteProfilerSessionManager::Create(options, request, status); EXPECT_TRUE(status.ok()); std::vector<Response> responses = sessions->WaitForCompletion(); absl::Duration elapsed = absl::Now() - approx_start; ASSERT_EQ(responses.size(), 1); EXPECT_TRUE(responses.back().status.ok()); EXPECT_TRUE(responses.back().profile_response->empty_trace()); EXPECT_EQ(responses.back().profile_response->tool_data_size(), 0); EXPECT_THAT(elapsed, DurationApproxLess(max_duration)); } } } }
2,302
cpp
tensorflow/tensorflow
profiler_client
third_party/xla/third_party/tsl/tsl/profiler/rpc/client/profiler_client.cc
third_party/xla/third_party/tsl/tsl/profiler/rpc/client/profiler_client_test.cc
#ifndef TENSORFLOW_TSL_PROFILER_RPC_CLIENT_PROFILER_CLIENT_H_ #define TENSORFLOW_TSL_PROFILER_RPC_CLIENT_PROFILER_CLIENT_H_ #include <memory> #include <string> #include "absl/strings/string_view.h" #include "absl/time/time.h" #include "tsl/platform/status.h" #include "tsl/profiler/protobuf/profiler_analysis.grpc.pb.h" #include "tsl/profiler/protobuf/profiler_service.grpc.pb.h" namespace tsl { namespace profiler { absl::Status ProfileGrpc(const std::string& service_address, const tensorflow::ProfileRequest& request, tensorflow::ProfileResponse* response); absl::Status NewSessionGrpc(const std::string& service_address, const tensorflow::NewProfileSessionRequest& request, tensorflow::NewProfileSessionResponse* response); absl::Status MonitorGrpc(const std::string& service_address, const tensorflow::MonitorRequest& request, tensorflow::MonitorResponse* response); class RemoteProfilerSession { public: static std::unique_ptr<RemoteProfilerSession> Create( const std::string& service_address, absl::Time deadline, const tensorflow::ProfileRequest& profile_request); RemoteProfilerSession(const RemoteProfilerSession&) = delete; RemoteProfilerSession& operator=(const RemoteProfilerSession&) = delete; ~RemoteProfilerSession(); absl::string_view GetServiceAddress() const { return service_address_; } std::unique_ptr<tensorflow::ProfileResponse> WaitForCompletion( absl::Status& out_status); private: explicit RemoteProfilerSession( const std::string& service_addr, absl::Time deadline, const tensorflow::ProfileRequest& profile_request); void ProfileAsync(); absl::Status status_on_completion_; std::unique_ptr<tensorflow::ProfileResponse> response_; std::string service_address_; std::unique_ptr<tensorflow::grpc::ProfilerService::Stub> stub_; absl::Time deadline_; ::grpc::ClientContext grpc_context_; std::unique_ptr< ::grpc::ClientAsyncResponseReader<tensorflow::ProfileResponse>> rpc_; ::grpc::Status grpc_status_ = ::grpc::Status::OK; ::grpc::CompletionQueue cq_; tensorflow::ProfileRequest profile_request_; }; } } #endif #include "tsl/profiler/rpc/client/profiler_client.h" #include <limits> #include <memory> #include "grpcpp/grpcpp.h" #include "absl/memory/memory.h" #include "absl/time/clock.h" #include "absl/time/time.h" #include "tsl/platform/errors.h" #include "tsl/platform/logging.h" #include "tsl/platform/status.h" #include "tsl/platform/types.h" #include "tsl/protobuf/error_codes.pb.h" namespace tsl { namespace profiler { namespace { using tensorflow::MonitorRequest; using tensorflow::MonitorResponse; using tensorflow::NewProfileSessionRequest; using tensorflow::NewProfileSessionResponse; using tensorflow::ProfileRequest; using tensorflow::ProfileResponse; inline absl::Status FromGrpcStatus(const ::grpc::Status& s) { return s.ok() ? absl::OkStatus() : absl::Status(static_cast<absl::StatusCode>(s.error_code()), s.error_message()); } template <typename T> std::unique_ptr<typename T::Stub> CreateStub( const std::string& service_address) { ::grpc::ChannelArguments channel_args; channel_args.SetMaxReceiveMessageSize(std::numeric_limits<int32>::max()); auto channel = ::grpc::CreateCustomChannel( service_address, ::grpc::InsecureChannelCredentials(), channel_args); if (!channel) { LOG(ERROR) << "Unable to create channel" << service_address; return nullptr; } return T::NewStub(channel); } } absl::Status ProfileGrpc(const std::string& service_address, const ProfileRequest& request, ProfileResponse* response) { ::grpc::ClientContext context; std::unique_ptr<tensorflow::grpc::ProfilerService::Stub> stub = CreateStub<tensorflow::grpc::ProfilerService>(service_address); TF_RETURN_IF_ERROR( FromGrpcStatus(stub->Profile(&context, request, response))); return absl::OkStatus(); } absl::Status NewSessionGrpc(const std::string& service_address, const NewProfileSessionRequest& request, NewProfileSessionResponse* response) { ::grpc::ClientContext context; std::unique_ptr<tensorflow::grpc::ProfileAnalysis::Stub> stub = CreateStub<tensorflow::grpc::ProfileAnalysis>(service_address); TF_RETURN_IF_ERROR( FromGrpcStatus(stub->NewSession(&context, request, response))); return absl::OkStatus(); } absl::Status MonitorGrpc(const std::string& service_address, const MonitorRequest& request, MonitorResponse* response) { ::grpc::ClientContext context; std::unique_ptr<tensorflow::grpc::ProfilerService::Stub> stub = CreateStub<tensorflow::grpc::ProfilerService>(service_address); TF_RETURN_IF_ERROR( FromGrpcStatus(stub->Monitor(&context, request, response))); return absl::OkStatus(); } std::unique_ptr<RemoteProfilerSession> RemoteProfilerSession::Create( const std::string& service_address, absl::Time deadline, const ProfileRequest& profile_request) { auto instance = absl::WrapUnique( new RemoteProfilerSession(service_address, deadline, profile_request)); instance->ProfileAsync(); return instance; } RemoteProfilerSession::RemoteProfilerSession( const std::string& service_address, absl::Time deadline, const ProfileRequest& profile_request) : response_(absl::make_unique<ProfileResponse>()), service_address_(service_address), stub_(CreateStub<tensorflow::grpc::ProfilerService>(service_address_)), deadline_(deadline), profile_request_(profile_request) { response_->set_empty_trace(true); } RemoteProfilerSession::~RemoteProfilerSession() { absl::Status dummy; WaitForCompletion(dummy); grpc_context_.TryCancel(); } void RemoteProfilerSession::ProfileAsync() { LOG(INFO) << "Asynchronous gRPC Profile() to " << service_address_; grpc_context_.set_deadline(absl::ToChronoTime(deadline_)); VLOG(1) << "Deadline set to " << deadline_; rpc_ = stub_->AsyncProfile(&grpc_context_, profile_request_, &cq_); rpc_->Finish(response_.get(), &grpc_status_, static_cast<void*>(&status_on_completion_)); VLOG(2) << "Asynchronous gRPC Profile() issued." << absl::Now(); } std::unique_ptr<ProfileResponse> RemoteProfilerSession::WaitForCompletion( absl::Status& out_status) { if (!response_) { out_status = errors::FailedPrecondition( "WaitForCompletion must only be called once."); return nullptr; } LOG(INFO) << "Waiting for completion."; void* got_tag = nullptr; bool ok = false; bool success = cq_.Next(&got_tag, &ok); if (!success || !ok || got_tag == nullptr) { out_status = errors::Internal("Missing or invalid event from completion queue."); return nullptr; } VLOG(1) << "Writing out status."; DCHECK_EQ(got_tag, &status_on_completion_); status_on_completion_.Update(FromGrpcStatus(grpc_status_)); if (status_on_completion_.code() == error::DEADLINE_EXCEEDED) { LOG(WARNING) << status_on_completion_; } else if (!status_on_completion_.ok()) { LOG(ERROR) << status_on_completion_; } out_status = status_on_completion_; return std::move(response_); } } }
#include "tsl/profiler/rpc/client/profiler_client.h" #include <memory> #include <string> #include "absl/time/clock.h" #include "absl/time/time.h" #include "tsl/platform/errors.h" #include "tsl/platform/status.h" #include "tsl/platform/test.h" #include "tsl/platform/types.h" #include "tsl/profiler/protobuf/profiler_service.pb.h" #include "tsl/profiler/rpc/client/profiler_client_test_util.h" namespace tsl { namespace profiler { namespace { using tensorflow::ProfileRequest; using ::tsl::profiler::test::DurationApproxLess; using ::tsl::profiler::test::DurationNear; using ::tsl::profiler::test::StartServer; TEST(RemoteProfilerSession, Simple) { absl::Duration duration = absl::Milliseconds(10); ProfileRequest request; std::string service_addr; auto server = StartServer(duration, &service_addr, &request); absl::Duration grace = absl::Seconds(1); absl::Duration max_duration = duration + grace; absl::Time approx_start = absl::Now(); absl::Time deadline = approx_start + max_duration; auto remote_session = RemoteProfilerSession::Create(service_addr, deadline, request); absl::Status status; auto response = remote_session->WaitForCompletion(status); absl::Duration elapsed = absl::Now() - approx_start; EXPECT_TRUE(status.ok()); EXPECT_TRUE(response->empty_trace()); EXPECT_EQ(response->tool_data_size(), 0); EXPECT_THAT(elapsed, DurationApproxLess(max_duration)); } TEST(RemoteProfilerSession, WaitNotCalled) { absl::Duration duration = absl::Milliseconds(10); ProfileRequest request; std::string service_addr; auto server = StartServer(duration, &service_addr, &request); absl::Duration grace = absl::Seconds(1); absl::Duration max_duration = duration + grace; absl::Time approx_start = absl::Now(); absl::Time deadline = approx_start + max_duration; auto remote_session = RemoteProfilerSession::Create(service_addr, deadline, request); absl::Duration elapsed = absl::Now() - approx_start; EXPECT_THAT(elapsed, DurationApproxLess(max_duration)); } TEST(RemoteProfilerSession, Timeout) { absl::Duration duration = absl::Milliseconds(10); ProfileRequest request; std::string service_addr; auto server = StartServer(duration, &service_addr, &request); auto remote_session = RemoteProfilerSession::Create(service_addr, absl::Now(), request); absl::Status status; auto response = remote_session->WaitForCompletion(status); EXPECT_TRUE(errors::IsDeadlineExceeded(status)); EXPECT_TRUE(response->empty_trace()); EXPECT_EQ(response->tool_data_size(), 0); } TEST(RemoteProfilerSession, LongDeadline) { absl::Duration duration = absl::Milliseconds(10); ProfileRequest request; std::string service_addr; auto server = StartServer(duration, &service_addr, &request); absl::Time approx_start = absl::Now(); absl::Duration grace = absl::Seconds(1000); absl::Duration max_duration = duration + grace; const absl::Time deadline = approx_start + max_duration; auto remote_session = RemoteProfilerSession::Create(service_addr, deadline, request); absl::Status status; auto response = remote_session->WaitForCompletion(status); absl::Duration elapsed = absl::Now() - approx_start; EXPECT_TRUE(status.ok()); EXPECT_TRUE(response->empty_trace()); EXPECT_EQ(response->tool_data_size(), 0); EXPECT_THAT(elapsed, DurationNear(duration)); } TEST(RemoteProfilerSession, LongDuration) { absl::Duration duration = absl::Seconds(3); ProfileRequest request; std::string service_addr; auto server = StartServer(duration, &service_addr, &request); absl::Time approx_start = absl::Now(); absl::Duration grace = absl::Seconds(1); absl::Duration max_duration = duration + grace; const absl::Time deadline = approx_start + max_duration; auto remote_session = RemoteProfilerSession::Create(service_addr, deadline, request); absl::Status status; auto response = remote_session->WaitForCompletion(status); absl::Duration elapsed = absl::Now() - approx_start; EXPECT_TRUE(status.ok()); EXPECT_TRUE(response->empty_trace()); EXPECT_EQ(response->tool_data_size(), 0); EXPECT_THAT(elapsed, DurationApproxLess(max_duration)); } } } }
2,303
cpp
tensorflow/tensorflow
traceme_recorder
third_party/xla/third_party/tsl/tsl/profiler/backends/cpu/traceme_recorder.cc
third_party/xla/third_party/tsl/tsl/profiler/backends/cpu/traceme_recorder_test.cc
#ifndef TENSORFLOW_TSL_PROFILER_BACKENDS_CPU_TRACEME_RECORDER_H_ #define TENSORFLOW_TSL_PROFILER_BACKENDS_CPU_TRACEME_RECORDER_H_ #include <atomic> #include <cstdint> #include <deque> #include <string> #include <vector> #include "tsl/platform/macros.h" #include "tsl/platform/types.h" namespace tsl { namespace profiler { namespace internal { TF_EXPORT extern std::atomic<int> g_trace_level; } class TraceMeRecorder { public: struct Event { bool IsComplete() const { return start_time > 0 && end_time > 0; } bool IsStart() const { return end_time < 0; } bool IsEnd() const { return start_time < 0; } int64_t ActivityId() const { if (IsStart()) return -end_time; if (IsEnd()) return -start_time; return 1; } std::string name; int64_t start_time; int64_t end_time; }; struct ThreadInfo { uint32 tid; std::string name; }; struct ThreadEvents { ThreadInfo thread; std::deque<Event> events; }; using Events = std::vector<ThreadEvents>; static bool Start(int level); static Events Stop(); static inline bool Active(int level = 1) { return internal::g_trace_level.load(std::memory_order_acquire) >= level; } static constexpr int kTracingDisabled = -1; static void Record(Event&& event); static int64_t NewActivityId(); private: TraceMeRecorder() = delete; ~TraceMeRecorder() = delete; static void Clear(); static TF_MUST_USE_RESULT Events Consume(); }; } } #endif #include "tsl/profiler/backends/cpu/traceme_recorder.h" #include <stddef.h> #include <stdint.h> #include <algorithm> #include <atomic> #include <deque> #include <optional> #include <utility> #include <vector> #include "absl/container/flat_hash_map.h" #include "tsl/platform/env.h" #include "tsl/platform/logging.h" #include "tsl/platform/macros.h" #include "tsl/platform/types.h" #include "tsl/profiler/utils/lock_free_queue.h" #include "tsl/profiler/utils/per_thread.h" namespace tsl { namespace profiler { namespace internal { #ifdef _WIN32 #define DECL_DLL_EXPORT __declspec(dllexport) #else #define DECL_DLL_EXPORT #endif DECL_DLL_EXPORT std::atomic<int> g_trace_level( TraceMeRecorder::kTracingDisabled); static_assert(ATOMIC_INT_LOCK_FREE == 2, "Assumed atomic<int> was lock free"); } namespace { class SplitEventTracker { public: void AddStart(TraceMeRecorder::Event&& event) { DCHECK(event.IsStart()); start_events_.emplace(event.ActivityId(), std::move(event)); } void AddEnd(TraceMeRecorder::Event* event) { DCHECK(event->IsEnd()); if (!FindStartAndMerge(event)) { end_events_.push_back(event); } } void HandleCrossThreadEvents() { for (auto* event : end_events_) { FindStartAndMerge(event); } } private: bool FindStartAndMerge(TraceMeRecorder::Event* event) { auto iter = start_events_.find(event->ActivityId()); if (iter == start_events_.end()) return false; auto& start_event = iter->second; event->name = std::move(start_event.name); event->start_time = start_event.start_time; start_events_.erase(iter); return true; } absl::flat_hash_map<int64_t, TraceMeRecorder::Event> start_events_; std::vector<TraceMeRecorder::Event*> end_events_; }; class ThreadLocalRecorder { public: ThreadLocalRecorder() { auto* env = Env::Default(); info_.tid = env->GetCurrentThreadId(); env->GetCurrentThreadName(&info_.name); } const TraceMeRecorder::ThreadInfo& Info() const { return info_; } void Record(TraceMeRecorder::Event&& event) { queue_.Push(std::move(event)); } void Clear() { queue_.Clear(); } TF_MUST_USE_RESULT std::deque<TraceMeRecorder::Event> Consume( SplitEventTracker* split_event_tracker) { std::deque<TraceMeRecorder::Event> events; std::optional<TraceMeRecorder::Event> event; while ((event = queue_.Pop())) { if (event->IsStart()) { split_event_tracker->AddStart(*std::move(event)); continue; } events.push_back(*std::move(event)); if (events.back().IsEnd()) { split_event_tracker->AddEnd(&events.back()); } } return events; } private: TraceMeRecorder::ThreadInfo info_; LockFreeQueue<TraceMeRecorder::Event> queue_; }; } void TraceMeRecorder::Clear() { auto recorders = PerThread<ThreadLocalRecorder>::StartRecording(); for (auto& recorder : recorders) { recorder->Clear(); }; } TraceMeRecorder::Events TraceMeRecorder::Consume() { TraceMeRecorder::Events result; SplitEventTracker split_event_tracker; auto recorders = PerThread<ThreadLocalRecorder>::StopRecording(); for (auto& recorder : recorders) { auto events = recorder->Consume(&split_event_tracker); if (!events.empty()) { result.push_back({recorder->Info(), std::move(events)}); } }; split_event_tracker.HandleCrossThreadEvents(); return result; } bool TraceMeRecorder::Start(int level) { level = std::max(0, level); int expected = kTracingDisabled; bool started = internal::g_trace_level.compare_exchange_strong( expected, level, std::memory_order_acq_rel); if (started) { Clear(); } return started; } void TraceMeRecorder::Record(Event&& event) { PerThread<ThreadLocalRecorder>::Get().Record(std::move(event)); } TraceMeRecorder::Events TraceMeRecorder::Stop() { TraceMeRecorder::Events events; if (internal::g_trace_level.exchange( kTracingDisabled, std::memory_order_acq_rel) != kTracingDisabled) { events = Consume(); } return events; } int64_t TraceMeRecorder::NewActivityId() { static std::atomic<int32> thread_counter(1); const thread_local static int32_t thread_id = thread_counter.fetch_add(1, std::memory_order_relaxed); thread_local static uint32 per_thread_activity_id = 0; return static_cast<int64_t>(thread_id) << 32 | per_thread_activity_id++; } } }
#include "tsl/profiler/backends/cpu/traceme_recorder.h" #include <atomic> #include <set> #include <string> #include <utility> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/strings/numbers.h" #include "absl/strings/str_cat.h" #include "tsl/platform/env.h" #include "tsl/platform/logging.h" #include "tsl/platform/notification.h" #include "tsl/platform/test.h" #include "tsl/platform/threadpool.h" #include "tsl/platform/types.h" #include "tsl/profiler/utils/math_utils.h" #include "tsl/profiler/utils/time_utils.h" namespace tsl { namespace profiler { namespace { using ::testing::ElementsAre; MATCHER_P(Named, name, "") { return arg.name == name; } TEST(RecorderTest, SingleThreaded) { int64_t start_time = GetCurrentTimeNanos(); int64_t end_time = start_time + UniToNano(1); TraceMeRecorder::Record({"before", start_time, end_time}); TraceMeRecorder::Start(1); TraceMeRecorder::Record({"during1", start_time, end_time}); TraceMeRecorder::Record({"during2", start_time, end_time}); auto results = TraceMeRecorder::Stop(); TraceMeRecorder::Record({"after", start_time, end_time}); ASSERT_EQ(results.size(), 1); EXPECT_THAT(results[0].events, ElementsAre(Named("during1"), Named("during2"))); } TEST(RecorderTest, Multithreaded) { constexpr static int kNumThreads = 4; tsl::Notification start; tsl::Notification stop; thread::ThreadPool pool(tsl::Env::Default(), "testpool", kNumThreads); std::atomic<int> thread_count = {0}; for (int i = 0; i < kNumThreads; i++) { pool.Schedule([&start, &stop, &thread_count] { uint64 j = 0; bool was_active = false; auto record_event = [&j]() { int64_t start_time = GetCurrentTimeNanos(); int64_t end_time = start_time + UniToNano(1); TraceMeRecorder::Record( {absl::StrCat(j++), start_time, end_time}); }; thread_count.fetch_add(1, std::memory_order_relaxed); start.WaitForNotification(); while (!stop.HasBeenNotified()) { if (TraceMeRecorder::Active()) { record_event(); was_active = true; } if (was_active && !TraceMeRecorder::Active()) { record_event(); record_event(); was_active = false; } SpinForNanos(10); } }); } struct ThreadState { bool split_session = false; bool overlapping_sessions = false; std::set<uint64> events; }; absl::flat_hash_map<uint32 , ThreadState> thread_state; auto done = [&thread_state] { for (const auto& id_and_thread : thread_state) { auto& t = id_and_thread.second; if (t.events.size() < 2) return false; } return true; }; while (thread_count.load(std::memory_order_relaxed) < kNumThreads) { LOG(INFO) << "Waiting for all threads to spin up..."; SleepForMillis(1); } start.Notify(); constexpr static int kMaxIters = 100; for (int iters = 0; iters < kMaxIters && !done(); ++iters) { LOG(INFO) << "Looping until convergence, iteration: " << iters; TraceMeRecorder::Start(1); SleepForMillis(100); auto results = TraceMeRecorder::Stop(); for (const auto& thread : results) { if (thread.events.empty()) continue; auto& state = thread_state[thread.thread.tid]; std::set<uint64> session_events; uint64 current = 0; for (const auto& event : thread.events) { uint64 activity_id; ASSERT_TRUE(absl::SimpleAtoi(event.name, &activity_id)); session_events.emplace(activity_id); if (current != 0 && activity_id != current + 1) { state.split_session = true; } current = activity_id; } for (const auto& event : session_events) { auto result = state.events.emplace(event); if (!result.second) { state.overlapping_sessions = true; } } } SleepForMillis(1); } stop.Notify(); for (const auto& id_and_thread : thread_state) { auto& thread = id_and_thread.second; EXPECT_FALSE(thread.split_session) << "Expected contiguous events in a session"; EXPECT_FALSE(thread.overlapping_sessions) << "Expected disjoint sessions"; EXPECT_GT(thread.events.size(), 1) << "Expected gaps in thread events between sessions"; } } } } }
2,304
cpp
tensorflow/tensorflow
profiler_lock
third_party/xla/third_party/tsl/tsl/profiler/lib/profiler_lock.cc
third_party/xla/third_party/tsl/tsl/profiler/lib/profiler_lock_test.cc
#ifndef TENSORFLOW_TSL_PROFILER_LIB_PROFILER_LOCK_H_ #define TENSORFLOW_TSL_PROFILER_LIB_PROFILER_LOCK_H_ #include <utility> #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "tsl/platform/statusor.h" namespace tsl { namespace profiler { constexpr absl::string_view kProfilerLockContention = "Another profiling session active."; class ProfilerLock { public: static bool HasActiveSession(); static absl::StatusOr<ProfilerLock> Acquire(); ProfilerLock() = default; ProfilerLock(const ProfilerLock&) = delete; ProfilerLock& operator=(const ProfilerLock&) = delete; ProfilerLock(ProfilerLock&& other) : active_(std::exchange(other.active_, false)) {} ProfilerLock& operator=(ProfilerLock&& other) { active_ = std::exchange(other.active_, false); return *this; } ~ProfilerLock() { ReleaseIfActive(); } void ReleaseIfActive(); bool Active() const { return active_; } private: explicit ProfilerLock(bool active) : active_(active) {} bool active_ = false; }; } } #endif #include "tsl/profiler/lib/profiler_lock.h" #include <atomic> #include "absl/status/statusor.h" #include "xla/tsl/util/env_var.h" #include "tsl/platform/errors.h" #include "tsl/platform/macros.h" namespace tsl { namespace profiler { namespace { std::atomic<int> g_session_active = ATOMIC_VAR_INIT(0); static_assert(ATOMIC_INT_LOCK_FREE == 2, "Assumed atomic<int> was lock free"); } bool ProfilerLock::HasActiveSession() { return g_session_active.load(std::memory_order_relaxed) != 0; } absl::StatusOr<ProfilerLock> ProfilerLock::Acquire() { static bool tf_profiler_disabled = [] { bool disabled = false; ReadBoolFromEnvVar("TF_DISABLE_PROFILING", false, &disabled).IgnoreError(); return disabled; }(); if (TF_PREDICT_FALSE(tf_profiler_disabled)) { return errors::AlreadyExists( "TensorFlow Profiler is permanently disabled by env var " "TF_DISABLE_PROFILING."); } int already_active = g_session_active.exchange(1, std::memory_order_acq_rel); if (already_active) { return errors::AlreadyExists(kProfilerLockContention); } return ProfilerLock(true); } void ProfilerLock::ReleaseIfActive() { if (active_) { g_session_active.store(0, std::memory_order_release); active_ = false; } } } }
#include "tsl/profiler/lib/profiler_lock.h" #include <utility> #include "absl/status/statusor.h" #include "tsl/platform/test.h" namespace tsl { namespace profiler { namespace { TEST(ProfilerLockTest, DefaultConstructorCreatesInactiveInstance) { ProfilerLock profiler_lock; EXPECT_FALSE(profiler_lock.Active()); } TEST(ProfilerLockTest, AcquireAndReleaseExplicitly) { absl::StatusOr<ProfilerLock> profiler_lock = ProfilerLock::Acquire(); ASSERT_TRUE(profiler_lock.ok()); EXPECT_TRUE(profiler_lock->Active()); profiler_lock->ReleaseIfActive(); EXPECT_FALSE(profiler_lock->Active()); } TEST(ProfilerLockTest, AcquireAndReleaseOnDestruction) { absl::StatusOr<ProfilerLock> profiler_lock = ProfilerLock::Acquire(); ASSERT_TRUE(profiler_lock.ok()); EXPECT_TRUE(profiler_lock->Active()); } TEST(ProfilerLockTest, ReacquireWithoutReleaseFails) { absl::StatusOr<ProfilerLock> profiler_lock_1 = ProfilerLock::Acquire(); absl::StatusOr<ProfilerLock> profiler_lock_2 = ProfilerLock::Acquire(); ASSERT_TRUE(profiler_lock_1.ok()); EXPECT_TRUE(profiler_lock_1->Active()); EXPECT_FALSE(profiler_lock_2.ok()); } TEST(ProfilerLockTest, ReacquireAfterReleaseSucceeds) { auto profiler_lock_1 = ProfilerLock::Acquire(); ASSERT_TRUE(profiler_lock_1.ok()); ASSERT_TRUE(profiler_lock_1->Active()); profiler_lock_1->ReleaseIfActive(); ASSERT_FALSE(profiler_lock_1->Active()); auto profiler_lock_2 = ProfilerLock::Acquire(); EXPECT_TRUE(profiler_lock_2.ok()); EXPECT_TRUE(profiler_lock_2->Active()); } TEST(ProfilerLockTest, InactiveAfterMove) { absl::StatusOr<ProfilerLock> profiler_lock_1 = ProfilerLock::Acquire(); ASSERT_TRUE(profiler_lock_1.ok()); ASSERT_TRUE(profiler_lock_1->Active()); ProfilerLock profiler_lock_2 = std::move(*profiler_lock_1); EXPECT_FALSE(profiler_lock_1->Active()); EXPECT_TRUE(profiler_lock_2.Active()); } } } }
2,305
cpp
tensorflow/tensorflow
profiler_factory
third_party/xla/third_party/tsl/tsl/profiler/lib/profiler_factory.cc
third_party/xla/third_party/tsl/tsl/profiler/lib/profiler_factory_test.cc
#ifndef TENSORFLOW_TSL_PROFILER_LIB_PROFILER_FACTORY_H_ #define TENSORFLOW_TSL_PROFILER_LIB_PROFILER_FACTORY_H_ #include <functional> #include <memory> #include <vector> #include "tsl/profiler/lib/profiler_interface.h" #include "tsl/profiler/protobuf/profiler_options.pb.h" namespace tsl { namespace profiler { using ProfilerFactory = std::function<std::unique_ptr<ProfilerInterface>( const tensorflow::ProfileOptions&)>; void RegisterProfilerFactory(ProfilerFactory factory); std::vector<std::unique_ptr<ProfilerInterface>> CreateProfilers( const tensorflow::ProfileOptions& options); void ClearRegisteredProfilersForTest(); } } #endif #include "tsl/profiler/lib/profiler_factory.h" #include <memory> #include <utility> #include <vector> #include "tsl/platform/mutex.h" #include "tsl/profiler/lib/profiler_controller.h" #include "tsl/profiler/lib/profiler_interface.h" #include "tsl/profiler/protobuf/profiler_options.pb.h" namespace tsl { namespace profiler { namespace { mutex mu(LINKER_INITIALIZED); std::vector<ProfilerFactory>* GetFactories() { static auto factories = new std::vector<ProfilerFactory>(); return factories; } } void RegisterProfilerFactory(ProfilerFactory factory) { mutex_lock lock(mu); GetFactories()->push_back(std::move(factory)); } std::vector<std::unique_ptr<profiler::ProfilerInterface>> CreateProfilers( const tensorflow::ProfileOptions& options) { std::vector<std::unique_ptr<profiler::ProfilerInterface>> result; mutex_lock lock(mu); for (const auto& factory : *GetFactories()) { auto profiler = factory(options); if (profiler == nullptr) continue; result.emplace_back( std::make_unique<ProfilerController>(std::move(profiler))); } return result; } void ClearRegisteredProfilersForTest() { mutex_lock lock(mu); GetFactories()->clear(); } } }
#include "tsl/profiler/lib/profiler_factory.h" #include <functional> #include <utility> #include "absl/memory/memory.h" #include "absl/status/status.h" #include "tsl/platform/macros.h" #include "tsl/platform/test.h" #include "tsl/profiler/lib/profiler_interface.h" #include "tsl/profiler/protobuf/profiler_options.pb.h" #include "tsl/profiler/protobuf/xplane.pb.h" namespace tsl { namespace profiler { namespace { class TestProfiler : public ProfilerInterface { public: absl::Status Start() override { return absl::OkStatus(); } absl::Status Stop() override { return absl::OkStatus(); } absl::Status CollectData(tensorflow::profiler::XSpace*) override { return absl::OkStatus(); } }; std::unique_ptr<ProfilerInterface> TestFactoryFunction( const tensorflow::ProfileOptions& options) { return absl::make_unique<TestProfiler>(); } TEST(ProfilerFactoryTest, FactoryFunctionPointer) { ClearRegisteredProfilersForTest(); RegisterProfilerFactory(&TestFactoryFunction); auto profilers = CreateProfilers(tensorflow::ProfileOptions()); EXPECT_EQ(profilers.size(), 1); } TEST(ProfilerFactoryTest, FactoryLambda) { ClearRegisteredProfilersForTest(); RegisterProfilerFactory([](const tensorflow::ProfileOptions& options) { return absl::make_unique<TestProfiler>(); }); auto profilers = CreateProfilers(tensorflow::ProfileOptions()); EXPECT_EQ(profilers.size(), 1); } std::unique_ptr<ProfilerInterface> NullFactoryFunction( const tensorflow::ProfileOptions& options) { return nullptr; } TEST(ProfilerFactoryTest, FactoryReturnsNull) { ClearRegisteredProfilersForTest(); RegisterProfilerFactory(&NullFactoryFunction); auto profilers = CreateProfilers(tensorflow::ProfileOptions()); EXPECT_TRUE(profilers.empty()); } class FactoryClass { public: explicit FactoryClass(void* ptr) : ptr_(ptr) {} FactoryClass(const FactoryClass&) = default; FactoryClass(FactoryClass&&) = default; std::unique_ptr<ProfilerInterface> CreateProfiler( const tensorflow::ProfileOptions& options) const { return absl::make_unique<TestProfiler>(); } private: void* ptr_ TF_ATTRIBUTE_UNUSED = nullptr; }; TEST(ProfilerFactoryTest, FactoryClassCapturedByLambda) { ClearRegisteredProfilersForTest(); static int token = 42; FactoryClass factory(&token); RegisterProfilerFactory([factory = std::move(factory)]( const tensorflow::ProfileOptions& options) { return factory.CreateProfiler(options); }); auto profilers = CreateProfilers(tensorflow::ProfileOptions()); EXPECT_EQ(profilers.size(), 1); } } } }
2,306
cpp
tensorflow/tensorflow
sampler
third_party/xla/third_party/tsl/tsl/lib/monitoring/sampler.cc
tensorflow/core/lib/monitoring/sampler_test.cc
#ifndef TENSORFLOW_TSL_LIB_MONITORING_SAMPLER_H_ #define TENSORFLOW_TSL_LIB_MONITORING_SAMPLER_H_ #include "tsl/platform/platform.h" #ifdef IS_MOBILE_PLATFORM #include <memory> #include "tsl/lib/monitoring/metric_def.h" #include "tsl/platform/macros.h" #include "tsl/platform/status.h" #include "tsl/platform/types.h" #include "tsl/protobuf/histogram.pb.h" namespace tsl { namespace monitoring { using tensorflow::HistogramProto; class SamplerCell { public: SamplerCell() {} ~SamplerCell() {} void Add(double value) {} HistogramProto value() const { return HistogramProto(); } private: SamplerCell(const SamplerCell&) = delete; void operator=(const SamplerCell&) = delete; }; class Buckets { public: Buckets() = default; ~Buckets() = default; static std::unique_ptr<Buckets> Explicit( std::initializer_list<double> bucket_limits) { return std::unique_ptr<Buckets>(new Buckets()); } static std::unique_ptr<Buckets> Exponential(double scale, double growth_factor, int bucket_count) { return std::unique_ptr<Buckets>(new Buckets()); } const std::vector<double>& explicit_bounds() const { return explicit_bounds_; } private: std::vector<double> explicit_bounds_; Buckets(const Buckets&) = delete; void operator=(const Buckets&) = delete; }; template <int NumLabels> class Sampler { public: ~Sampler() {} template <typename... MetricDefArgs> static Sampler* New(const MetricDef<MetricKind::kCumulative, HistogramProto, NumLabels>& metric_def, std::unique_ptr<Buckets> buckets) { return new Sampler<NumLabels>(std::move(buckets)); } template <typename... Labels> SamplerCell* GetCell(const Labels&... labels) { return &default_sampler_cell_; } Status GetStatus() { return OkStatus(); } private: Sampler(std::unique_ptr<Buckets> buckets) : buckets_(std::move(buckets)) {} SamplerCell default_sampler_cell_; std::unique_ptr<Buckets> buckets_; Sampler(const Sampler&) = delete; void operator=(const Sampler&) = delete; }; } } #else #include <float.h> #include <map> #include <memory> #include <tuple> #include <utility> #include <vector> #include "tsl/lib/histogram/histogram.h" #include "tsl/lib/monitoring/collection_registry.h" #include "tsl/lib/monitoring/metric_def.h" #include "tsl/platform/macros.h" #include "tsl/platform/mutex.h" #include "tsl/platform/status.h" #include "tsl/platform/thread_annotations.h" #include "tsl/protobuf/histogram.pb.h" namespace tsl { namespace monitoring { using tensorflow::HistogramProto; class SamplerCell { public: explicit SamplerCell(const std::vector<double>& bucket_limits) : histogram_(bucket_limits) {} ~SamplerCell() {} void Add(double sample); HistogramProto value() const; private: histogram::ThreadSafeHistogram histogram_; SamplerCell(const SamplerCell&) = delete; void operator=(const SamplerCell&) = delete; }; class Buckets { public: virtual ~Buckets() = default; static std::unique_ptr<Buckets> Exponential(double scale, double growth_factor, int bucket_count); static std::unique_ptr<Buckets> Explicit( std::initializer_list<double> bucket_limits); static std::unique_ptr<Buckets> Explicit(std::vector<double> bucket_limits); virtual const std::vector<double>& explicit_bounds() const = 0; }; template <int NumLabels> class Sampler { public: ~Sampler() { registration_handle_.reset(); } static Sampler* New(const MetricDef<MetricKind::kCumulative, HistogramProto, NumLabels>& metric_def, std::unique_ptr<Buckets> buckets); template <typename... Labels> SamplerCell* GetCell(const Labels&... labels) TF_LOCKS_EXCLUDED(mu_); absl::Status GetStatus() { return status_; } private: friend class SamplerCell; Sampler(const MetricDef<MetricKind::kCumulative, HistogramProto, NumLabels>& metric_def, std::unique_ptr<Buckets> buckets) : metric_def_(metric_def), buckets_(std::move(buckets)), registration_handle_(CollectionRegistry::Default()->Register( &metric_def_, [&](MetricCollectorGetter getter) { auto metric_collector = getter.Get(&metric_def_); tf_shared_lock l(mu_); for (const auto& cell : cells_) { metric_collector.CollectValue(cell.first, cell.second.value()); } })) { if (registration_handle_) { status_ = absl::OkStatus(); } else { status_ = absl::Status(absl::StatusCode::kAlreadyExists, "Another metric with the same name already exists."); } } mutable mutex mu_; absl::Status status_; using LabelArray = std::array<string, NumLabels>; std::map<LabelArray, SamplerCell> cells_ TF_GUARDED_BY(mu_); const MetricDef<MetricKind::kCumulative, HistogramProto, NumLabels> metric_def_; std::unique_ptr<Buckets> buckets_; std::unique_ptr<CollectionRegistry::RegistrationHandle> registration_handle_; Sampler(const Sampler&) = delete; void operator=(const Sampler&) = delete; }; inline void SamplerCell::Add(const double sample) { histogram_.Add(sample); } inline HistogramProto SamplerCell::value() const { HistogramProto pb; histogram_.EncodeToProto(&pb, true ); return pb; } template <int NumLabels> Sampler<NumLabels>* Sampler<NumLabels>::New( const MetricDef<MetricKind::kCumulative, HistogramProto, NumLabels>& metric_def, std::unique_ptr<Buckets> buckets) { return new Sampler<NumLabels>(metric_def, std::move(buckets)); } template <int NumLabels> template <typename... Labels> SamplerCell* Sampler<NumLabels>::GetCell(const Labels&... labels) TF_LOCKS_EXCLUDED(mu_) { static_assert(sizeof...(Labels) == NumLabels, "Mismatch between Sampler<NumLabels> and number of labels " "provided in GetCell(...)."); const LabelArray& label_array = {{labels...}}; { tf_shared_lock l(mu_); const auto found_it = cells_.find(label_array); if (found_it != cells_.end()) { return &(found_it->second); } } mutex_lock l(mu_); return &(cells_ .emplace(std::piecewise_construct, std::forward_as_tuple(label_array), std::forward_as_tuple(buckets_->explicit_bounds())) .first->second); } } } #endif #endif #include "tsl/lib/monitoring/sampler.h" #include "tsl/platform/platform.h" #ifdef IS_MOBILE_PLATFORM #else namespace tsl { namespace monitoring { namespace { class ExplicitBuckets : public Buckets { public: ~ExplicitBuckets() override = default; explicit ExplicitBuckets(std::vector<double> bucket_limits) : bucket_limits_(std::move(bucket_limits)) { CHECK_GT(bucket_limits_.size(), 0); for (size_t i = 1; i < bucket_limits_.size(); i++) { CHECK_GT(bucket_limits_[i], bucket_limits_[i - 1]); } if (bucket_limits_.back() != DBL_MAX) { bucket_limits_.push_back(DBL_MAX); } } const std::vector<double>& explicit_bounds() const override { return bucket_limits_; } private: std::vector<double> bucket_limits_; ExplicitBuckets(const ExplicitBuckets&) = delete; void operator=(const ExplicitBuckets&) = delete; }; class ExponentialBuckets : public Buckets { public: ~ExponentialBuckets() override = default; ExponentialBuckets(double scale, double growth_factor, int bucket_count) : explicit_buckets_( ComputeBucketLimits(scale, growth_factor, bucket_count)) {} const std::vector<double>& explicit_bounds() const override { return explicit_buckets_.explicit_bounds(); } private: static std::vector<double> ComputeBucketLimits(double scale, double growth_factor, int bucket_count) { CHECK_GT(bucket_count, 0); std::vector<double> bucket_limits; double bound = scale; for (int i = 0; i < bucket_count; i++) { bucket_limits.push_back(bound); bound *= growth_factor; } return bucket_limits; } ExplicitBuckets explicit_buckets_; ExponentialBuckets(const ExponentialBuckets&) = delete; void operator=(const ExponentialBuckets&) = delete; }; } std::unique_ptr<Buckets> Buckets::Explicit(std::vector<double> bucket_limits) { return std::unique_ptr<Buckets>( new ExplicitBuckets(std::move(bucket_limits))); } std::unique_ptr<Buckets> Buckets::Explicit( std::initializer_list<double> bucket_limits) { return std::unique_ptr<Buckets>(new ExplicitBuckets(bucket_limits)); } std::unique_ptr<Buckets> Buckets::Exponential(double scale, double growth_factor, int bucket_count) { return std::unique_ptr<Buckets>( new ExponentialBuckets(scale, growth_factor, bucket_count)); } } } #endif
#include "tensorflow/core/lib/monitoring/sampler.h" #include "tensorflow/core/platform/test.h" namespace tensorflow { namespace monitoring { namespace { using histogram::Histogram; void EqHistograms(const Histogram& expected, const HistogramProto& actual_proto) { Histogram actual; ASSERT_TRUE(actual.DecodeFromProto(actual_proto)); EXPECT_EQ(expected.ToString(), actual.ToString()); } auto* sampler_with_labels = Sampler<1>::New({"/tensorflow/test/sampler_with_labels", "Sampler with one label.", "MyLabel"}, Buckets::Explicit({10.0, 20.0})); TEST(LabeledSamplerTest, InitializedEmpty) { Histogram empty; EqHistograms(empty, sampler_with_labels->GetCell("Empty")->value()); } TEST(LabeledSamplerTest, ExplicitBucketBoundaries) { Histogram expected({10.0, 20.0, DBL_MAX}); auto* cell = sampler_with_labels->GetCell("BucketBoundaries"); sampler_with_labels->GetCell("AddedToCheckPreviousCellValidity"); cell->Add(-1.0); expected.Add(-1.0); cell->Add(10.0); expected.Add(10.0); cell->Add(20.0); expected.Add(20.0); cell->Add(31.0); expected.Add(31.0); EqHistograms(expected, cell->value()); } auto* init_sampler_without_labels = Sampler<0>::New({"/tensorflow/test/init_sampler_without_labels", "Sampler without labels initialized as empty."}, Buckets::Explicit(std::vector<double>{1.5, 2.8})); TEST(UnlabeledSamplerTest, InitializedEmpty) { Histogram empty; EqHistograms(empty, init_sampler_without_labels->GetCell()->value()); } auto* sampler_without_labels = Sampler<0>::New({"/tensorflow/test/sampler_without_labels", "Sampler without labels initialized as empty."}, Buckets::Explicit({1.5, 2.8})); TEST(UnlabeledSamplerTest, ExplicitBucketBoundaries) { Histogram expected({1.5, 2.8, DBL_MAX}); auto* cell = sampler_without_labels->GetCell(); cell->Add(-1.0); expected.Add(-1.0); cell->Add(2.0); expected.Add(2.0); cell->Add(31.0); expected.Add(31.0); EqHistograms(expected, cell->value()); } auto* sampler_with_exponential = Sampler<1>::New({"/tensorflow/test/sampler_with_exponential", "Sampler with exponential buckets.", "MyLabel"}, Buckets::Exponential(1, 2, 3)); TEST(ExponentialSamplerTest, ExponentialBucketBoundaries) { Histogram expected({1.0, 2.0, 4.0, DBL_MAX}); auto* cell = sampler_with_exponential->GetCell("BucketBoundaries"); sampler_with_exponential->GetCell("AddedToCheckPreviousCellValidity"); cell->Add(-1.0); expected.Add(-1.0); cell->Add(0.5); expected.Add(0.5); cell->Add(1.001); expected.Add(1.001); cell->Add(3.999); expected.Add(3.999); cell->Add(6.0); expected.Add(6.0); EqHistograms(expected, cell->value()); } TEST(ExplicitSamplerTest, SameName) { auto* same_sampler = Sampler<1>::New({"/tensorflow/test/sampler_with_labels", "Sampler with one label.", "MyLabel"}, Buckets::Explicit({10.0, 20.0})); EXPECT_TRUE(sampler_with_labels->GetStatus().ok()); EXPECT_TRUE(same_sampler->GetStatus().ok()); delete same_sampler; } } } }
2,307
cpp
tensorflow/tensorflow
collection_registry
third_party/xla/third_party/tsl/tsl/lib/monitoring/collection_registry.cc
tensorflow/core/lib/monitoring/collection_registry_test.cc
#ifndef TENSORFLOW_TSL_LIB_MONITORING_COLLECTION_REGISTRY_H_ #define TENSORFLOW_TSL_LIB_MONITORING_COLLECTION_REGISTRY_H_ namespace tensorflow { namespace monitoring { namespace test_util { class CollectionRegistryTestAccess; } } } #include "tsl/platform/platform.h" #ifdef IS_MOBILE_PLATFORM #include <functional> #include <map> #include <memory> #include "tsl/lib/monitoring/metric_def.h" #include "tsl/platform/macros.h" namespace tsl { namespace monitoring { template <MetricKind metric_kind, typename Value, int NumLabels> class MetricCollector { public: ~MetricCollector() = default; void CollectValue(const std::array<std::string, NumLabels>& labels, Value value) {} private: friend class MetricCollectorGetter; MetricCollector() {} }; class MetricCollectorGetter { public: template <MetricKind metric_kind, typename Value, int NumLabels> MetricCollector<metric_kind, Value, NumLabels> Get( const MetricDef<metric_kind, Value, NumLabels>* const metric_def) { return MetricCollector<metric_kind, Value, NumLabels>(); } private: MetricCollectorGetter() {} }; class CollectionRegistry { public: ~CollectionRegistry() = default; static CollectionRegistry* Default() { return new CollectionRegistry(); } using CollectionFunction = std::function<void(MetricCollectorGetter getter)>; class RegistrationHandle { public: RegistrationHandle() {} ~RegistrationHandle() {} }; std::unique_ptr<RegistrationHandle> Register( const AbstractMetricDef* metric_def, const CollectionFunction& collection_function) { return std::unique_ptr<RegistrationHandle>(new RegistrationHandle()); } private: CollectionRegistry() {} CollectionRegistry(const CollectionRegistry&) = delete; void operator=(const CollectionRegistry&) = delete; }; } } #else #include <functional> #include <map> #include <memory> #include <utility> #include "tsl/lib/monitoring/collected_metrics.h" #include "tsl/lib/monitoring/metric_def.h" #include "tsl/lib/monitoring/types.h" #include "tsl/platform/env.h" #include "tsl/platform/logging.h" #include "tsl/platform/macros.h" #include "tsl/platform/mutex.h" #include "tsl/platform/stringpiece.h" #include "tsl/platform/thread_annotations.h" #include "tsl/platform/types.h" #include "tsl/protobuf/histogram.pb.h" namespace tsl { namespace monitoring { namespace internal { class Collector; } template <MetricKind metric_kind, typename Value, int NumLabels> class MetricCollector { public: ~MetricCollector() = default; void CollectValue(const std::array<std::string, NumLabels>& labels, Value value); private: friend class internal::Collector; MetricCollector( const MetricDef<metric_kind, Value, NumLabels>* const metric_def, const uint64 registration_time_millis, internal::Collector* const collector, PointSet* const point_set) : metric_def_(metric_def), registration_time_millis_(registration_time_millis), collector_(collector), point_set_(point_set) { point_set_->metric_name = std::string(metric_def->name()); } const MetricDef<metric_kind, Value, NumLabels>* const metric_def_; const uint64 registration_time_millis_; internal::Collector* const collector_; PointSet* const point_set_; }; class MetricCollectorGetter { public: template <MetricKind metric_kind, typename Value, int NumLabels> MetricCollector<metric_kind, Value, NumLabels> Get( const MetricDef<metric_kind, Value, NumLabels>* const metric_def); private: friend class internal::Collector; MetricCollectorGetter(internal::Collector* const collector, const AbstractMetricDef* const allowed_metric_def, const uint64 registration_time_millis) : collector_(collector), allowed_metric_def_(allowed_metric_def), registration_time_millis_(registration_time_millis) {} internal::Collector* const collector_; const AbstractMetricDef* const allowed_metric_def_; const uint64 registration_time_millis_; }; class CollectionRegistry { public: ~CollectionRegistry() = default; static CollectionRegistry* Default(); using CollectionFunction = std::function<void(MetricCollectorGetter getter)>; class RegistrationHandle; std::unique_ptr<RegistrationHandle> Register( const AbstractMetricDef* metric_def, const CollectionFunction& collection_function) TF_LOCKS_EXCLUDED(mu_) TF_MUST_USE_RESULT; struct CollectMetricsOptions { CollectMetricsOptions() {} bool collect_metric_descriptors = true; }; std::unique_ptr<CollectedMetrics> CollectMetrics( const CollectMetricsOptions& options) const; private: friend class ::tensorflow::monitoring::test_util:: CollectionRegistryTestAccess; friend class internal::Collector; explicit CollectionRegistry(Env* env); void Unregister(const AbstractMetricDef* metric_def) TF_LOCKS_EXCLUDED(mu_); Env* const env_; mutable mutex mu_; struct CollectionInfo { const AbstractMetricDef* const metric_def; CollectionFunction collection_function; uint64 registration_time_millis; }; std::map<StringPiece, CollectionInfo> registry_ TF_GUARDED_BY(mu_); CollectionRegistry(const CollectionRegistry&) = delete; void operator=(const CollectionRegistry&) = delete; }; class CollectionRegistry::RegistrationHandle { public: RegistrationHandle(CollectionRegistry* const export_registry, const AbstractMetricDef* const metric_def) : export_registry_(export_registry), metric_def_(metric_def) {} ~RegistrationHandle() { export_registry_->Unregister(metric_def_); } private: CollectionRegistry* const export_registry_; const AbstractMetricDef* const metric_def_; }; namespace internal { template <typename Value> void CollectValue(Value value, Point* point); template <> inline void CollectValue(int64_t value, Point* const point) { point->value_type = ValueType::kInt64; point->int64_value = value; } template <> inline void CollectValue(std::function<int64_t()> value_fn, Point* const point) { point->value_type = ValueType::kInt64; point->int64_value = value_fn(); } template <> inline void CollectValue(std::string value, Point* const point) { point->value_type = ValueType::kString; point->string_value = std::move(value); } template <> inline void CollectValue(std::function<std::string()> value_fn, Point* const point) { point->value_type = ValueType::kString; point->string_value = value_fn(); } template <> inline void CollectValue(bool value, Point* const point) { point->value_type = ValueType::kBool; point->bool_value = value; } template <> inline void CollectValue(std::function<bool()> value_fn, Point* const point) { point->value_type = ValueType::kBool; point->bool_value = value_fn(); } template <> inline void CollectValue(HistogramProto value, Point* const point) { point->value_type = ValueType::kHistogram; point->histogram_value = std::move(value); } template <> inline void CollectValue(Percentiles value, Point* const point) { point->value_type = ValueType::kPercentiles; point->percentiles_value = std::move(value); } template <> inline void CollectValue(double value, Point* const point) { point->value_type = ValueType::kDouble; point->double_value = value; } template <> inline void CollectValue(std::function<double()> value_fn, Point* const point) { point->value_type = ValueType::kDouble; point->double_value = value_fn(); } class Collector { public: explicit Collector(const uint64 collection_time_millis) : collected_metrics_(new CollectedMetrics()), collection_time_millis_(collection_time_millis) {} template <MetricKind metric_kind, typename Value, int NumLabels> MetricCollector<metric_kind, Value, NumLabels> GetMetricCollector( const MetricDef<metric_kind, Value, NumLabels>* const metric_def, const uint64 registration_time_millis, internal::Collector* const collector) TF_LOCKS_EXCLUDED(mu_) { auto* const point_set = [&]() { mutex_lock l(mu_); return collected_metrics_->point_set_map .insert(std::make_pair(std::string(metric_def->name()), std::unique_ptr<PointSet>(new PointSet()))) .first->second.get(); }(); return MetricCollector<metric_kind, Value, NumLabels>( metric_def, registration_time_millis, collector, point_set); } uint64 collection_time_millis() const { return collection_time_millis_; } void CollectMetricDescriptor(const AbstractMetricDef* const metric_def) TF_LOCKS_EXCLUDED(mu_); void CollectMetricValues( const CollectionRegistry::CollectionInfo& collection_info); std::unique_ptr<CollectedMetrics> ConsumeCollectedMetrics() TF_LOCKS_EXCLUDED(mu_); private: mutable mutex mu_; std::unique_ptr<CollectedMetrics> collected_metrics_ TF_GUARDED_BY(mu_); const uint64 collection_time_millis_; Collector(const Collector&) = delete; void operator=(const Collector&) = delete; }; template <MetricKind kind> void WriteTimestamps(const uint64 registration_time_millis, const uint64 collection_time_millis, Point* const point); template <> inline void WriteTimestamps<MetricKind::kGauge>( const uint64 registration_time_millis, const uint64 collection_time_millis, Point* const point) { point->start_timestamp_millis = collection_time_millis; point->end_timestamp_millis = collection_time_millis; } template <> inline void WriteTimestamps<MetricKind::kCumulative>( const uint64 registration_time_millis, const uint64 collection_time_millis, Point* const point) { point->start_timestamp_millis = registration_time_millis; point->end_timestamp_millis = registration_time_millis < collection_time_millis ? collection_time_millis : registration_time_millis; } } template <MetricKind metric_kind, typename Value, int NumLabels> void MetricCollector<metric_kind, Value, NumLabels>::CollectValue( const std::array<std::string, NumLabels>& labels, Value value) { point_set_->points.emplace_back(new Point()); auto* const point = point_set_->points.back().get(); const std::vector<std::string> label_descriptions = metric_def_->label_descriptions(); point->labels.reserve(NumLabels); for (int i = 0; i < NumLabels; ++i) { point->labels.push_back({}); auto* const label = &point->labels.back(); label->name = label_descriptions[i]; label->value = labels[i]; } internal::CollectValue(std::move(value), point); internal::WriteTimestamps<metric_kind>( registration_time_millis_, collector_->collection_time_millis(), point); } template <MetricKind metric_kind, typename Value, int NumLabels> MetricCollector<metric_kind, Value, NumLabels> MetricCollectorGetter::Get( const MetricDef<metric_kind, Value, NumLabels>* const metric_def) { if (allowed_metric_def_ != metric_def) { LOG(FATAL) << "Expected collection for: " << allowed_metric_def_->name() << " but instead got: " << metric_def->name(); } return collector_->GetMetricCollector(metric_def, registration_time_millis_, collector_); } class Exporter { public: virtual ~Exporter() {} virtual void PeriodicallyExportMetrics() = 0; virtual void ExportMetrics() = 0; }; namespace exporter_registration { class ExporterRegistration { public: explicit ExporterRegistration(Exporter* exporter) : exporter_(exporter) { exporter_->PeriodicallyExportMetrics(); } private: Exporter* exporter_; }; } #define REGISTER_TF_METRICS_EXPORTER(exporter) \ REGISTER_TF_METRICS_EXPORTER_UNIQ_HELPER(__COUNTER__, exporter) #define REGISTER_TF_METRICS_EXPORTER_UNIQ_HELPER(ctr, exporter) \ REGISTER_TF_METRICS_EXPORTER_UNIQ(ctr, exporter) #define REGISTER_TF_METRICS_EXPORTER_UNIQ(ctr, exporter) \ static ::tsl::monitoring::exporter_registration::ExporterRegistration \ exporter_registration_##ctr(new exporter()) } } #endif #endif #include "tsl/lib/monitoring/collection_registry.h" #ifndef IS_MOBILE_PLATFORM #include "tsl/platform/logging.h" namespace tsl { namespace monitoring { namespace internal { void Collector::CollectMetricValues( const CollectionRegistry::CollectionInfo& info) { info.collection_function(MetricCollectorGetter( this, info.metric_def, info.registration_time_millis)); } std::unique_ptr<CollectedMetrics> Collector::ConsumeCollectedMetrics() { mutex_lock l(mu_); return std::move(collected_metrics_); } void Collector::CollectMetricDescriptor( const AbstractMetricDef* const metric_def) { auto* const metric_descriptor = [&]() { mutex_lock l(mu_); return collected_metrics_->metric_descriptor_map .insert(std::make_pair( string(metric_def->name()), std::unique_ptr<MetricDescriptor>(new MetricDescriptor()))) .first->second.get(); }(); metric_descriptor->name = string(metric_def->name()); metric_descriptor->description = string(metric_def->description()); for (const StringPiece label_name : metric_def->label_descriptions()) { metric_descriptor->label_names.emplace_back(label_name); } metric_descriptor->metric_kind = metric_def->kind(); metric_descriptor->value_type = metric_def->value_type(); } } CollectionRegistry* CollectionRegistry::Default() { static CollectionRegistry* default_registry = new CollectionRegistry(Env::Default()); return default_registry; } CollectionRegistry::CollectionRegistry(Env* const env) : env_(env) {} std::unique_ptr<CollectionRegistry::RegistrationHandle> CollectionRegistry::Register(const AbstractMetricDef* const metric_def, const CollectionFunction& collection_function) { CHECK(collection_function) << "Requires collection_function to contain an implementation."; mutex_lock l(mu_); const auto found_it = registry_.find(metric_def->name()); if (found_it != registry_.end()) { LOG(WARNING) << "Trying to register 2 metrics with the same name: " << metric_def->name() << ". The old value will be erased in order to register a new one. " "Please check if you link the metric more than once, or " "if the name is already used by other metrics."; registry_.erase(found_it); } registry_.insert( {metric_def->name(), {metric_def, collection_function, env_->NowMicros() / 1000}}); return std::unique_ptr<RegistrationHandle>( new RegistrationHandle(this, metric_def)); } void CollectionRegistry::Unregister(const AbstractMetricDef* const metric_def) { mutex_lock l(mu_); registry_.erase(metric_def->name()); } std::unique_ptr<CollectedMetrics> CollectionRegistry::CollectMetrics( const CollectMetricsOptions& options) const { internal::Collector collector(env_->NowMicros() / 1000); mutex_lock l(mu_); for (const auto& registration : registry_) { if (options.collect_metric_descriptors) { collector.CollectMetricDescriptor(registration.second.metric_def); } collector.CollectMetricValues(registration.second ); } return collector.ConsumeCollectedMetrics(); } } } #endif
#include "tensorflow/core/lib/monitoring/collection_registry.h" #include <memory> #include "tensorflow/core/lib/monitoring/counter.h" #include "tensorflow/core/lib/monitoring/gauge.h" #include "tensorflow/core/lib/monitoring/percentile_sampler.h" #include "tensorflow/core/lib/monitoring/sampler.h" #include "tensorflow/core/lib/strings/strcat.h" #include "tensorflow/core/platform/protobuf.h" #include "tensorflow/core/platform/test.h" namespace tensorflow { namespace monitoring { using histogram::Histogram; namespace test_util { class CollectionRegistryTestAccess { public: static std::unique_ptr<CollectionRegistry> CreateRegistry(Env* const env) { return std::unique_ptr<CollectionRegistry>(new CollectionRegistry(env)); } }; } namespace { void EmptyCollectionFunction(MetricCollectorGetter getter) {} TEST(CollectionRegistryTest, RegistrationUnregistration) { auto* collection_registry = CollectionRegistry::Default(); const MetricDef<MetricKind::kCumulative, int64_t, 0> metric_def0( "/tensorflow/metric0", "An example metric with no labels."); const MetricDef<MetricKind::kGauge, HistogramProto, 1> metric_def1( "/tensorflow/metric1", "An example metric with one label.", "LabelName"); { std::unique_ptr<CollectionRegistry::RegistrationHandle> handle0 = collection_registry->Register(&metric_def0, EmptyCollectionFunction); std::unique_ptr<CollectionRegistry::RegistrationHandle> handle1 = collection_registry->Register(&metric_def1, EmptyCollectionFunction); handle0.reset(); handle0 = collection_registry->Register(&metric_def0, EmptyCollectionFunction); } } TEST(CollectionRegistryDeathTest, DuplicateRegistration) { auto* collection_registry = CollectionRegistry::Default(); const MetricDef<MetricKind::kCumulative, int64_t, 0> metric_def( "/tensorflow/metric", "An example metric with no labels."); auto handle = collection_registry->Register(&metric_def, EmptyCollectionFunction); auto duplicate_handle = collection_registry->Register(&metric_def, EmptyCollectionFunction); EXPECT_NE(duplicate_handle, nullptr); } TEST(CollectMetricsTest, Counter) { auto counter_with_labels = std::unique_ptr<Counter<2>>( Counter<2>::New("/tensorflow/test/counter_with_labels", "Counter with labels.", "MyLabel0", "MyLabel1")); auto counter_without_labels = std::unique_ptr<Counter<0>>(Counter<0>::New( "/tensorflow/test/counter_without_labels", "Counter without labels.")); counter_with_labels->GetCell("Label00", "Label10")->IncrementBy(42); counter_with_labels->GetCell("Label01", "Label11")->IncrementBy(58); counter_without_labels->GetCell()->IncrementBy(7); for (const bool collect_metric_descriptors : {true, false}) { SCOPED_TRACE(strings::StrCat("collect_metric_descriptors: ", collect_metric_descriptors)); auto* collection_registry = CollectionRegistry::Default(); CollectionRegistry::CollectMetricsOptions options; options.collect_metric_descriptors = collect_metric_descriptors; const std::unique_ptr<CollectedMetrics> collected_metrics = collection_registry->CollectMetrics(options); if (collect_metric_descriptors) { ASSERT_GE(collected_metrics->metric_descriptor_map.size(), 2); const MetricDescriptor& ld = *collected_metrics->metric_descriptor_map.at( "/tensorflow/test/counter_with_labels"); EXPECT_EQ("/tensorflow/test/counter_with_labels", ld.name); EXPECT_EQ("Counter with labels.", ld.description); ASSERT_EQ(2, ld.label_names.size()); EXPECT_EQ("MyLabel0", ld.label_names[0]); EXPECT_EQ("MyLabel1", ld.label_names[1]); EXPECT_EQ(MetricKind::kCumulative, ld.metric_kind); EXPECT_EQ(ValueType::kInt64, ld.value_type); const MetricDescriptor& ud = *collected_metrics->metric_descriptor_map.at( "/tensorflow/test/counter_without_labels"); EXPECT_EQ("/tensorflow/test/counter_without_labels", ud.name); EXPECT_EQ("Counter without labels.", ud.description); ASSERT_EQ(0, ud.label_names.size()); EXPECT_EQ(MetricKind::kCumulative, ud.metric_kind); EXPECT_EQ(ValueType::kInt64, ud.value_type); } else { EXPECT_EQ(0, collected_metrics->metric_descriptor_map.size()); } ASSERT_GE(collected_metrics->point_set_map.size(), 2); const PointSet& lps = *collected_metrics->point_set_map.at( "/tensorflow/test/counter_with_labels"); EXPECT_EQ("/tensorflow/test/counter_with_labels", lps.metric_name); ASSERT_EQ(2, lps.points.size()); ASSERT_EQ(2, lps.points[0]->labels.size()); EXPECT_EQ("MyLabel0", lps.points[0]->labels[0].name); EXPECT_EQ("Label00", lps.points[0]->labels[0].value); EXPECT_EQ("MyLabel1", lps.points[0]->labels[1].name); EXPECT_EQ("Label10", lps.points[0]->labels[1].value); EXPECT_EQ(ValueType::kInt64, lps.points[0]->value_type); EXPECT_EQ(42, lps.points[0]->int64_value); EXPECT_LT(0, lps.points[0]->start_timestamp_millis); EXPECT_LT(0, lps.points[0]->end_timestamp_millis); EXPECT_GE(lps.points[0]->end_timestamp_millis, lps.points[0]->start_timestamp_millis); ASSERT_EQ(2, lps.points[1]->labels.size()); EXPECT_EQ("MyLabel0", lps.points[1]->labels[0].name); EXPECT_EQ("Label01", lps.points[1]->labels[0].value); EXPECT_EQ("MyLabel1", lps.points[1]->labels[1].name); EXPECT_EQ("Label11", lps.points[1]->labels[1].value); EXPECT_EQ(ValueType::kInt64, lps.points[1]->value_type); EXPECT_EQ(58, lps.points[1]->int64_value); EXPECT_LT(0, lps.points[1]->start_timestamp_millis); EXPECT_LT(0, lps.points[1]->end_timestamp_millis); EXPECT_GE(lps.points[1]->end_timestamp_millis, lps.points[1]->start_timestamp_millis); const PointSet& ups = *collected_metrics->point_set_map.at( "/tensorflow/test/counter_without_labels"); EXPECT_EQ("/tensorflow/test/counter_without_labels", ups.metric_name); ASSERT_EQ(1, ups.points.size()); EXPECT_EQ(0, ups.points[0]->labels.size()); EXPECT_EQ(ValueType::kInt64, ups.points[0]->value_type); EXPECT_EQ(7, ups.points[0]->int64_value); EXPECT_LT(0, ups.points[0]->start_timestamp_millis); EXPECT_LT(0, ups.points[0]->end_timestamp_millis); EXPECT_GE(ups.points[0]->end_timestamp_millis, ups.points[0]->start_timestamp_millis); } } TEST(CollectMetricsTest, Gauge) { auto string_gauge_with_labels = std::unique_ptr<Gauge<string, 2>>(Gauge<string, 2>::New( "/tensorflow/test/string_gauge_with_labels", "String gauge with labels.", "MyLabel0", "MyLabel1")); auto inteter_gauge_without_labels = std::unique_ptr<Gauge<int64_t, 0>>( Gauge<int64_t, 0>::New("/tensorflow/test/integer_gauge_without_labels", "Integer gauge without labels.")); string_gauge_with_labels->GetCell("Label00", "Label10")->Set("test1"); string_gauge_with_labels->GetCell("Label01", "Label11")->Set("test2"); inteter_gauge_without_labels->GetCell()->Set(7); for (const bool collect_metric_descriptors : {true, false}) { SCOPED_TRACE(strings::StrCat("collect_metric_descriptors: ", collect_metric_descriptors)); auto* collection_registry = CollectionRegistry::Default(); CollectionRegistry::CollectMetricsOptions options; options.collect_metric_descriptors = collect_metric_descriptors; const std::unique_ptr<CollectedMetrics> collected_metrics = collection_registry->CollectMetrics(options); if (collect_metric_descriptors) { ASSERT_GE(collected_metrics->metric_descriptor_map.size(), 2); const MetricDescriptor& ld = *collected_metrics->metric_descriptor_map.at( "/tensorflow/test/string_gauge_with_labels"); EXPECT_EQ("/tensorflow/test/string_gauge_with_labels", ld.name); EXPECT_EQ("String gauge with labels.", ld.description); ASSERT_EQ(2, ld.label_names.size()); EXPECT_EQ("MyLabel0", ld.label_names[0]); EXPECT_EQ("MyLabel1", ld.label_names[1]); EXPECT_EQ(MetricKind::kGauge, ld.metric_kind); EXPECT_EQ(ValueType::kString, ld.value_type); const MetricDescriptor& ud = *collected_metrics->metric_descriptor_map.at( "/tensorflow/test/integer_gauge_without_labels"); EXPECT_EQ("/tensorflow/test/integer_gauge_without_labels", ud.name); EXPECT_EQ("Integer gauge without labels.", ud.description); ASSERT_EQ(0, ud.label_names.size()); EXPECT_EQ(MetricKind::kGauge, ud.metric_kind); EXPECT_EQ(ValueType::kInt64, ud.value_type); } else { EXPECT_EQ(0, collected_metrics->metric_descriptor_map.size()); } ASSERT_GE(collected_metrics->point_set_map.size(), 2); const PointSet& lps = *collected_metrics->point_set_map.at( "/tensorflow/test/string_gauge_with_labels"); EXPECT_EQ("/tensorflow/test/string_gauge_with_labels", lps.metric_name); ASSERT_EQ(2, lps.points.size()); ASSERT_EQ(2, lps.points[0]->labels.size()); EXPECT_EQ("MyLabel0", lps.points[0]->labels[0].name); EXPECT_EQ("Label00", lps.points[0]->labels[0].value); EXPECT_EQ("MyLabel1", lps.points[0]->labels[1].name); EXPECT_EQ("Label10", lps.points[0]->labels[1].value); EXPECT_EQ(ValueType::kString, lps.points[0]->value_type); EXPECT_EQ("test1", lps.points[0]->string_value); EXPECT_LT(0, lps.points[0]->start_timestamp_millis); EXPECT_LT(0, lps.points[0]->end_timestamp_millis); EXPECT_GE(lps.points[0]->end_timestamp_millis, lps.points[0]->start_timestamp_millis); ASSERT_EQ(2, lps.points[1]->labels.size()); EXPECT_EQ("MyLabel0", lps.points[1]->labels[0].name); EXPECT_EQ("Label01", lps.points[1]->labels[0].value); EXPECT_EQ("MyLabel1", lps.points[1]->labels[1].name); EXPECT_EQ("Label11", lps.points[1]->labels[1].value); EXPECT_EQ(ValueType::kString, lps.points[1]->value_type); EXPECT_EQ("test2", lps.points[1]->string_value); EXPECT_LT(0, lps.points[1]->start_timestamp_millis); EXPECT_LT(0, lps.points[1]->end_timestamp_millis); EXPECT_GE(lps.points[1]->end_timestamp_millis, lps.points[1]->start_timestamp_millis); const PointSet& ups = *collected_metrics->point_set_map.at( "/tensorflow/test/integer_gauge_without_labels"); EXPECT_EQ("/tensorflow/test/integer_gauge_without_labels", ups.metric_name); ASSERT_EQ(1, ups.points.size()); EXPECT_EQ(0, ups.points[0]->labels.size()); EXPECT_EQ(ValueType::kInt64, ups.points[0]->value_type); EXPECT_EQ(7, ups.points[0]->int64_value); EXPECT_LT(0, ups.points[0]->start_timestamp_millis); EXPECT_LT(0, ups.points[0]->end_timestamp_millis); EXPECT_GE(ups.points[0]->end_timestamp_millis, ups.points[0]->start_timestamp_millis); } } void EqHistograms(const Histogram& expected, const HistogramProto& actual_proto) { Histogram actual; ASSERT_TRUE(actual.DecodeFromProto(actual_proto)); EXPECT_EQ(expected.ToString(), actual.ToString()); } TEST(CollectMetricsTest, Sampler) { auto sampler_with_labels = std::unique_ptr<Sampler<2>>( Sampler<2>::New({"/tensorflow/test/sampler_with_labels", "Sampler with labels.", "MyLabel0", "MyLabel1"}, Buckets::Explicit({1.0, 2.0}))); auto sampler_without_labels = std::unique_ptr<Sampler<0>>(Sampler<0>::New( {"/tensorflow/test/sampler_without_labels", "Sampler without labels."}, Buckets::Explicit({0.0}))); Histogram with_labels0({1.0, 2.0, DBL_MAX}); sampler_with_labels->GetCell("Label00", "Label10")->Add(0.7); with_labels0.Add(0.7); Histogram with_labels1({1.0, 2.0, DBL_MAX}); sampler_with_labels->GetCell("Label01", "Label11")->Add(1.5); with_labels1.Add(1.5); Histogram without_labels({0.0, DBL_MAX}); sampler_without_labels->GetCell()->Add(0.5); without_labels.Add(0.5); for (const bool collect_metric_descriptors : {true, false}) { SCOPED_TRACE(strings::StrCat("collect_metric_descriptors: ", collect_metric_descriptors)); auto* collection_registry = CollectionRegistry::Default(); CollectionRegistry::CollectMetricsOptions options; options.collect_metric_descriptors = collect_metric_descriptors; const std::unique_ptr<CollectedMetrics> collected_metrics = collection_registry->CollectMetrics(options); if (collect_metric_descriptors) { ASSERT_GE(collected_metrics->metric_descriptor_map.size(), 2); const MetricDescriptor& ld = *collected_metrics->metric_descriptor_map.at( "/tensorflow/test/sampler_with_labels"); EXPECT_EQ("/tensorflow/test/sampler_with_labels", ld.name); EXPECT_EQ("Sampler with labels.", ld.description); ASSERT_EQ(2, ld.label_names.size()); EXPECT_EQ("MyLabel0", ld.label_names[0]); EXPECT_EQ("MyLabel1", ld.label_names[1]); EXPECT_EQ(MetricKind::kCumulative, ld.metric_kind); EXPECT_EQ(ValueType::kHistogram, ld.value_type); const MetricDescriptor& ud = *collected_metrics->metric_descriptor_map.at( "/tensorflow/test/sampler_without_labels"); EXPECT_EQ("/tensorflow/test/sampler_without_labels", ud.name); EXPECT_EQ("Sampler without labels.", ud.description); ASSERT_EQ(0, ud.label_names.size()); EXPECT_EQ(MetricKind::kCumulative, ud.metric_kind); EXPECT_EQ(ValueType::kHistogram, ud.value_type); } else { EXPECT_EQ(0, collected_metrics->metric_descriptor_map.size()); } ASSERT_GE(collected_metrics->point_set_map.size(), 2); const PointSet& lps = *collected_metrics->point_set_map.at( "/tensorflow/test/sampler_with_labels"); EXPECT_EQ("/tensorflow/test/sampler_with_labels", lps.metric_name); ASSERT_EQ(2, lps.points.size()); ASSERT_EQ(2, lps.points[0]->labels.size()); EXPECT_EQ("MyLabel0", lps.points[0]->labels[0].name); EXPECT_EQ("Label00", lps.points[0]->labels[0].value); EXPECT_EQ("MyLabel1", lps.points[0]->labels[1].name); EXPECT_EQ("Label10", lps.points[0]->labels[1].value); EXPECT_EQ(ValueType::kHistogram, lps.points[0]->value_type); EqHistograms(with_labels0, lps.points[0]->histogram_value); EXPECT_LT(0, lps.points[0]->start_timestamp_millis); EXPECT_LT(0, lps.points[0]->end_timestamp_millis); EXPECT_GE(lps.points[0]->end_timestamp_millis, lps.points[0]->start_timestamp_millis); ASSERT_EQ(2, lps.points[1]->labels.size()); EXPECT_EQ("MyLabel0", lps.points[1]->labels[0].name); EXPECT_EQ("Label01", lps.points[1]->labels[0].value); EXPECT_EQ("MyLabel1", lps.points[1]->labels[1].name); EXPECT_EQ("Label11", lps.points[1]->labels[1].value); EXPECT_EQ(ValueType::kHistogram, lps.points[1]->value_type); EqHistograms(with_labels1, lps.points[1]->histogram_value); EXPECT_LT(0, lps.points[1]->start_timestamp_millis); EXPECT_LT(0, lps.points[1]->end_timestamp_millis); EXPECT_GE(lps.points[1]->end_timestamp_millis, lps.points[1]->start_timestamp_millis); const PointSet& ups = *collected_metrics->point_set_map.at( "/tensorflow/test/sampler_without_labels"); EXPECT_EQ("/tensorflow/test/sampler_without_labels", ups.metric_name); ASSERT_EQ(1, ups.points.size()); EXPECT_EQ(0, ups.points[0]->labels.size()); EXPECT_EQ(ValueType::kHistogram, ups.points[0]->value_type); EqHistograms(without_labels, ups.points[0]->histogram_value); EXPECT_LT(0, ups.points[0]->start_timestamp_millis); EXPECT_LT(0, ups.points[0]->end_timestamp_millis); EXPECT_GE(ups.points[0]->end_timestamp_millis, ups.points[0]->start_timestamp_millis); } } TEST(CollectMetricsTest, PercentileSampler) { auto sampler_with_labels = std::unique_ptr<PercentileSampler<2>>(PercentileSampler<2>::New( {"/tensorflow/test/pctsampler_with_labels", "Percentile sampler with labels.", "MyLabel0", "MyLabel1"}, {25.0, 50.0, 75.0}, 1024, UnitOfMeasure::kNumber)); auto sampler_without_labels = std::unique_ptr<PercentileSampler<0>>(PercentileSampler<0>::New( {"/tensorflow/test/pctsampler_without_labels", "Percentile sampler without labels."}, {25.0, 50.0, 75.0}, 1024, UnitOfMeasure::kNumber)); sampler_with_labels->GetCell("Label00", "Label10")->Add(0.7); sampler_with_labels->GetCell("Label01", "Label11")->Add(1.5); sampler_without_labels->GetCell()->Add(0.5); for (const bool collect_metric_descriptors : {true, false}) { SCOPED_TRACE(strings::StrCat("collect_metric_descriptors: ", collect_metric_descriptors)); auto* collection_registry = CollectionRegistry::Default(); CollectionRegistry::CollectMetricsOptions options; options.collect_metric_descriptors = collect_metric_descriptors; const std::unique_ptr<CollectedMetrics> collected_metrics = collection_registry->CollectMetrics(options); if (collect_metric_descriptors) { ASSERT_GE(collected_metrics->metric_descriptor_map.size(), 2); const MetricDescriptor& ld = *collected_metrics->metric_descriptor_map.at( "/tensorflow/test/pctsampler_with_labels"); EXPECT_EQ("/tensorflow/test/pctsampler_with_labels", ld.name); EXPECT_EQ("Percentile sampler with labels.", ld.description); ASSERT_EQ(2, ld.label_names.size()); EXPECT_EQ("MyLabel0", ld.label_names[0]); EXPECT_EQ("MyLabel1", ld.label_names[1]); EXPECT_EQ(MetricKind::kCumulative, ld.metric_kind); EXPECT_EQ(ValueType::kPercentiles, ld.value_type); const MetricDescriptor& ud = *collected_metrics->metric_descriptor_map.at( "/tensorflow/test/pctsampler_without_labels"); EXPECT_EQ("/tensorflow/test/pctsampler_without_labels", ud.name); EXPECT_EQ("Percentile sampler without labels.", ud.description); ASSERT_EQ(0, ud.label_names.size()); EXPECT_EQ(MetricKind::kCumulative, ud.metric_kind); EXPECT_EQ(ValueType::kPercentiles, ud.value_type); } else { EXPECT_EQ(0, collected_metrics->metric_descriptor_map.size()); } ASSERT_GE(collected_metrics->point_set_map.size(), 2); const PointSet& lps = *collected_metrics->point_set_map.at( "/tensorflow/test/pctsampler_with_labels"); EXPECT_EQ("/tensorflow/test/pctsampler_with_labels", lps.metric_name); ASSERT_EQ(2, lps.points.size()); ASSERT_EQ(2, lps.points[0]->labels.size()); EXPECT_EQ("MyLabel0", lps.points[0]->labels[0].name); EXPECT_EQ("Label00", lps.points[0]->labels[0].value); EXPECT_EQ("MyLabel1", lps.points[0]->labels[1].name); EXPECT_EQ("Label10", lps.points[0]->labels[1].value); EXPECT_EQ(ValueType::kPercentiles, lps.points[0]->value_type); EXPECT_LT(0, lps.points[0]->start_timestamp_millis); EXPECT_LT(0, lps.points[0]->end_timestamp_millis); EXPECT_GE(lps.points[0]->end_timestamp_millis, lps.points[0]->start_timestamp_millis); ASSERT_EQ(2, lps.points[1]->labels.size()); EXPECT_EQ("MyLabel0", lps.points[1]->labels[0].name); EXPECT_EQ("Label01", lps.points[1]->labels[0].value); EXPECT_EQ("MyLabel1", lps.points[1]->labels[1].name); EXPECT_EQ("Label11", lps.points[1]->labels[1].value); EXPECT_EQ(ValueType::kPercentiles, lps.points[1]->value_type); EXPECT_LT(0, lps.points[1]->start_timestamp_millis); EXPECT_LT(0, lps.points[1]->end_timestamp_millis); EXPECT_GE(lps.points[1]->end_timestamp_millis, lps.points[1]->start_timestamp_millis); const PointSet& ups = *collected_metrics->point_set_map.at( "/tensorflow/test/pctsampler_without_labels"); EXPECT_EQ("/tensorflow/test/pctsampler_without_labels", ups.metric_name); ASSERT_EQ(1, ups.points.size()); EXPECT_EQ(0, ups.points[0]->labels.size()); EXPECT_EQ(ValueType::kPercentiles, ups.points[0]->value_type); EXPECT_LT(0, ups.points[0]->start_timestamp_millis); EXPECT_LT(0, ups.points[0]->end_timestamp_millis); EXPECT_GE(ups.points[0]->end_timestamp_millis, ups.points[0]->start_timestamp_millis); } } class FakeClockEnv : public EnvWrapper { public: FakeClockEnv() : EnvWrapper(Env::Default()), current_millis_(0) {} void AdvanceByMillis(const uint64 millis) { current_millis_ += millis; } uint64 NowMicros() const override { return current_millis_ * 1000; } private: uint64 current_millis_; }; TEST(CollectionRegistryTest, WriteTimestamps) { FakeClockEnv fake_clock_env; auto collection_registry = test_util::CollectionRegistryTestAccess::CreateRegistry(&fake_clock_env); fake_clock_env.AdvanceByMillis(25); { const MetricDef<MetricKind::kCumulative, int64_t, 0> cumulative_metric( "/tensorflow/cumulative/metric", "An example metric with no labels."); auto handle = collection_registry->Register( &cumulative_metric, [&](MetricCollectorGetter getter) { auto metric_collector = getter.Get(&cumulative_metric); metric_collector.CollectValue({}, 42); }); fake_clock_env.AdvanceByMillis(75); const std::unique_ptr<CollectedMetrics> collected_metrics = collection_registry->CollectMetrics({}); const PointSet& point_set = *collected_metrics->point_set_map.at("/tensorflow/cumulative/metric"); ASSERT_EQ(1, point_set.points.size()); EXPECT_EQ(25, point_set.points[0]->start_timestamp_millis); EXPECT_EQ(100, point_set.points[0]->end_timestamp_millis); } { const MetricDef<MetricKind::kGauge, int64_t, 0> gauge_metric( "/tensorflow/gauge/metric", "An example metric with no labels."); auto handle = collection_registry->Register( &gauge_metric, [&](MetricCollectorGetter getter) { auto metric_collector = getter.Get(&gauge_metric); metric_collector.CollectValue({}, 42); }); fake_clock_env.AdvanceByMillis(75); const std::unique_ptr<CollectedMetrics> collected_metrics = collection_registry->CollectMetrics({}); const PointSet& point_set = *collected_metrics->point_set_map.at("/tensorflow/gauge/metric"); ASSERT_EQ(1, point_set.points.size()); EXPECT_EQ(175, point_set.points[0]->start_timestamp_millis); EXPECT_EQ(175, point_set.points[0]->end_timestamp_millis); } } } } }
2,308
cpp
tensorflow/tensorflow
percentile_sampler
third_party/xla/third_party/tsl/tsl/lib/monitoring/percentile_sampler.cc
tensorflow/core/lib/monitoring/percentile_sampler_test.cc
#ifndef TENSORFLOW_TSL_LIB_MONITORING_PERCENTILE_SAMPLER_H_ #define TENSORFLOW_TSL_LIB_MONITORING_PERCENTILE_SAMPLER_H_ #include "tsl/platform/platform.h" #ifdef IS_MOBILE_PLATFORM #include "tsl/platform/status.h" #include "tsl/lib/monitoring/collection_registry.h" #include "tsl/lib/monitoring/metric_def.h" #include "tsl/lib/monitoring/types.h" #include "tsl/platform/macros.h" namespace tsl { namespace monitoring { class PercentileSamplerCell { public: void Add(double sample) {} Percentiles value() const { return Percentiles(); } }; template <int NumLabels> class PercentileSampler { public: static PercentileSampler* New( const MetricDef<MetricKind::kCumulative, Percentiles, NumLabels>& metric_def, std::vector<double> percentiles, size_t max_samples, UnitOfMeasure unit_of_measure); template <typename... Labels> PercentileSamplerCell* GetCell(const Labels&... labels) { return &default_cell_; } Status GetStatus() { return tsl::OkStatus(); } private: PercentileSamplerCell default_cell_; PercentileSampler() = default; PercentileSampler(const PercentileSampler&) = delete; void operator=(const PercentileSampler&) = delete; }; template <int NumLabels> PercentileSampler<NumLabels>* PercentileSampler<NumLabels>::New( const MetricDef<MetricKind::kCumulative, Percentiles, NumLabels>& , std::vector<double> , size_t , UnitOfMeasure ) { return new PercentileSampler<NumLabels>(); } } } #else #include <cmath> #include <map> #include "tsl/platform/status.h" #include "tsl/lib/monitoring/collection_registry.h" #include "tsl/lib/monitoring/metric_def.h" #include "tsl/lib/monitoring/types.h" #include "tsl/platform/macros.h" #include "tsl/platform/mutex.h" #include "tsl/platform/thread_annotations.h" namespace tsl { namespace monitoring { class PercentileSamplerCell { public: PercentileSamplerCell(UnitOfMeasure unit_of_measure, std::vector<double> percentiles, size_t max_samples) : unit_of_measure_(unit_of_measure), percentiles_(std::move(percentiles)), samples_(max_samples), num_samples_(0), next_position_(0), total_samples_(0), accumulator_(0.0) {} void Add(double sample); Percentiles value() const; private: struct Sample { bool operator<(const Sample& rhs) const { return value < rhs.value; } uint64 nstime = 0; double value = NAN; }; std::vector<Sample> GetSamples(size_t* total_samples, long double* accumulator) const; mutable mutex mu_; UnitOfMeasure unit_of_measure_; const std::vector<double> percentiles_; std::vector<Sample> samples_ TF_GUARDED_BY(mu_); size_t num_samples_ TF_GUARDED_BY(mu_); size_t next_position_ TF_GUARDED_BY(mu_); size_t total_samples_ TF_GUARDED_BY(mu_); long double accumulator_ TF_GUARDED_BY(mu_); PercentileSamplerCell(const PercentileSamplerCell&) = delete; void operator=(const PercentileSamplerCell&) = delete; }; template <int NumLabels> class PercentileSampler { public: ~PercentileSampler() { registration_handle_.reset(); } static PercentileSampler* New( const MetricDef<MetricKind::kCumulative, Percentiles, NumLabels>& metric_def, std::vector<double> percentiles, size_t max_samples, UnitOfMeasure unit_of_measure); template <typename... Labels> PercentileSamplerCell* GetCell(const Labels&... labels) TF_LOCKS_EXCLUDED(mu_); absl::Status GetStatus() { return status_; } private: friend class PercentileSamplerCell; PercentileSampler(const MetricDef<MetricKind::kCumulative, Percentiles, NumLabels>& metric_def, std::vector<double> percentiles, size_t max_samples, UnitOfMeasure unit_of_measure) : metric_def_(metric_def), unit_of_measure_(unit_of_measure), percentiles_(std::move(percentiles)), max_samples_(max_samples), registration_handle_(CollectionRegistry::Default()->Register( &metric_def_, [&](MetricCollectorGetter getter) { auto metric_collector = getter.Get(&metric_def_); mutex_lock l(mu_); for (const auto& cell : cells_) { metric_collector.CollectValue(cell.first, cell.second.value()); } })) { if (registration_handle_) { for (size_t i = 0; i < percentiles_.size(); ++i) { if (percentiles_[i] < 0.0 || percentiles_[i] > 100.0) { status_ = absl::Status(absl::StatusCode::kInvalidArgument, "Percentile values must be in [0, 100] range."); break; } if (i + 1 < percentiles_.size() && percentiles_[i] >= percentiles_[i + 1]) { status_ = absl::Status( absl::StatusCode::kInvalidArgument, "Percentile values must be in strictly ascending order."); break; } } } else { status_ = absl::Status(absl::StatusCode::kAlreadyExists, "Another metric with the same name already exists."); } } mutable mutex mu_; absl::Status status_; using LabelArray = std::array<string, NumLabels>; std::map<LabelArray, PercentileSamplerCell> cells_ TF_GUARDED_BY(mu_); const MetricDef<MetricKind::kCumulative, Percentiles, NumLabels> metric_def_; UnitOfMeasure unit_of_measure_ = UnitOfMeasure::kNumber; const std::vector<double> percentiles_; const size_t max_samples_ = 0; std::unique_ptr<CollectionRegistry::RegistrationHandle> registration_handle_; PercentileSampler(const PercentileSampler&) = delete; void operator=(const PercentileSampler&) = delete; }; template <int NumLabels> PercentileSampler<NumLabels>* PercentileSampler<NumLabels>::New( const MetricDef<MetricKind::kCumulative, Percentiles, NumLabels>& metric_def, std::vector<double> percentiles, size_t max_samples, UnitOfMeasure unit_of_measure) { return new PercentileSampler<NumLabels>(metric_def, std::move(percentiles), max_samples, unit_of_measure); } template <int NumLabels> template <typename... Labels> PercentileSamplerCell* PercentileSampler<NumLabels>::GetCell( const Labels&... labels) TF_LOCKS_EXCLUDED(mu_) { static_assert( sizeof...(Labels) == NumLabels, "Mismatch between PercentileSampler<NumLabels> and number of labels " "provided in GetCell(...)."); const LabelArray& label_array = {{labels...}}; mutex_lock l(mu_); const auto found_it = cells_.find(label_array); if (found_it != cells_.end()) { return &(found_it->second); } return &(cells_ .emplace(std::piecewise_construct, std::forward_as_tuple(label_array), std::forward_as_tuple(unit_of_measure_, percentiles_, max_samples_)) .first->second); } } } #endif #endif #include "tsl/lib/monitoring/percentile_sampler.h" #include <algorithm> #include <cmath> #include <vector> #ifdef IS_MOBILE_PLATFORM #else namespace tsl { namespace monitoring { void PercentileSamplerCell::Add(double sample) { uint64 nstime = EnvTime::NowNanos(); mutex_lock l(mu_); samples_[next_position_] = {nstime, sample}; ++next_position_; if (TF_PREDICT_FALSE(next_position_ >= samples_.size())) { next_position_ = 0; } if (TF_PREDICT_FALSE(num_samples_ < samples_.size())) { ++num_samples_; } ++total_samples_; accumulator_ += sample; } Percentiles PercentileSamplerCell::value() const { Percentiles pct_samples; pct_samples.unit_of_measure = unit_of_measure_; size_t total_samples; long double accumulator; std::vector<Sample> samples = GetSamples(&total_samples, &accumulator); if (!samples.empty()) { pct_samples.num_samples = samples.size(); pct_samples.total_samples = total_samples; pct_samples.accumulator = accumulator; pct_samples.start_nstime = samples.front().nstime; pct_samples.end_nstime = samples.back().nstime; long double total = 0.0; for (auto& sample : samples) { total += sample.value; } pct_samples.mean = total / pct_samples.num_samples; long double total_sigma = 0.0; for (auto& sample : samples) { double delta = sample.value - pct_samples.mean; total_sigma += delta * delta; } pct_samples.stddev = std::sqrt(total_sigma / pct_samples.num_samples); std::sort(samples.begin(), samples.end()); pct_samples.min_value = samples.front().value; pct_samples.max_value = samples.back().value; for (auto percentile : percentiles_) { size_t index = std::min<size_t>( static_cast<size_t>(percentile * pct_samples.num_samples / 100.0), pct_samples.num_samples - 1); PercentilePoint pct = {percentile, samples[index].value}; pct_samples.points.push_back(pct); } } return pct_samples; } std::vector<PercentileSamplerCell::Sample> PercentileSamplerCell::GetSamples( size_t* total_samples, long double* accumulator) const { mutex_lock l(mu_); std::vector<Sample> samples; if (num_samples_ == samples_.size()) { samples.insert(samples.end(), samples_.begin() + next_position_, samples_.end()); } samples.insert(samples.end(), samples_.begin(), samples_.begin() + next_position_); *total_samples = total_samples_; *accumulator = accumulator_; return samples; } } } #endif
#include "tensorflow/core/lib/monitoring/percentile_sampler.h" #include "tensorflow/core/platform/test.h" namespace tensorflow { namespace monitoring { namespace { auto* pctsampler_with_labels = PercentileSampler<1>::New( {"/tensorflow/test/percentile_sampler_with_labels", "Percentile sampler with one label.", "MyLabel"}, {25.0, 50.0, 90.0, 99.0}, 1024, UnitOfMeasure::kNumber); auto* pctsampler_without_labels = PercentileSampler<0>::New( {"/tensorflow/test/percentile_sampler_without_labels", "Percentile sampler without labels initialized as empty."}, {25.0, 50.0, 90.0, 99.0}, 1024, UnitOfMeasure::kNumber); TEST(LabeledPercentileSamplerTest, FixedPercentilesValues) { auto* cell = pctsampler_with_labels->GetCell("MyLabel"); cell->Add(10.0); cell->Add(4.0); cell->Add(1.0); cell->Add(0.6); auto value = cell->value(); EXPECT_EQ(value.min_value, 0.6); EXPECT_EQ(value.max_value, 10.0); EXPECT_EQ(value.num_samples, 4); EXPECT_EQ(value.points[0].value, 1.0); EXPECT_EQ(value.points[1].value, 4.0); EXPECT_EQ(value.points[2].value, 10.0); EXPECT_EQ(value.points[3].value, 10.0); } TEST(UnlabeledPercentileSamplerTest, FixedPercentilesValues) { auto* cell = pctsampler_without_labels->GetCell(); cell->Add(10.0); cell->Add(4.0); cell->Add(1.0); cell->Add(0.6); auto value = cell->value(); EXPECT_EQ(value.min_value, 0.6); EXPECT_EQ(value.max_value, 10.0); EXPECT_EQ(value.num_samples, 4); EXPECT_EQ(value.points[0].value, 1.0); EXPECT_EQ(value.points[1].value, 4.0); EXPECT_EQ(value.points[2].value, 10.0); EXPECT_EQ(value.points[3].value, 10.0); } } } }
2,309
cpp
tensorflow/tensorflow
weighted_picker
third_party/xla/third_party/tsl/tsl/lib/random/weighted_picker.cc
third_party/xla/third_party/tsl/tsl/lib/random/weighted_picker_test.cc
#ifndef TENSORFLOW_TSL_LIB_RANDOM_WEIGHTED_PICKER_H_ #define TENSORFLOW_TSL_LIB_RANDOM_WEIGHTED_PICKER_H_ #include <assert.h> #include "tsl/platform/logging.h" #include "tsl/platform/macros.h" #include "tsl/platform/types.h" namespace tsl { namespace random { class SimplePhilox; class WeightedPicker { public: explicit WeightedPicker(int N); ~WeightedPicker(); int Pick(SimplePhilox* rnd) const; int PickAt(int32_t weight_index) const; int32 get_weight(int index) const; void set_weight(int index, int32_t weight); int32 total_weight() const; int num_elements() const; void SetAllWeights(int32_t weight); void SetWeightsFromArray(int N, const int32* weights); void Resize(int N); void Append(int32_t weight); private: int N_; int num_levels_; int32** level_; static int LevelSize(int level) { return 1 << level; } void RebuildTreeWeights(); WeightedPicker(const WeightedPicker&) = delete; void operator=(const WeightedPicker&) = delete; }; inline int32 WeightedPicker::get_weight(int index) const { DCHECK_GE(index, 0); DCHECK_LT(index, N_); return level_[num_levels_ - 1][index]; } inline int32 WeightedPicker::total_weight() const { return level_[0][0]; } inline int WeightedPicker::num_elements() const { return N_; } } } #endif #include "tsl/lib/random/weighted_picker.h" #include <string.h> #include <algorithm> #include "tsl/lib/random/simple_philox.h" namespace tsl { namespace random { WeightedPicker::WeightedPicker(int N) { CHECK_GE(N, 0); N_ = N; num_levels_ = 1; while (LevelSize(num_levels_ - 1) < N) { num_levels_++; } level_ = new int32*[num_levels_]; for (int l = 0; l < num_levels_; l++) { level_[l] = new int32[LevelSize(l)]; } SetAllWeights(1); } WeightedPicker::~WeightedPicker() { for (int l = 0; l < num_levels_; l++) { delete[] level_[l]; } delete[] level_; } static int32 UnbiasedUniform(SimplePhilox* r, int32_t n) { CHECK_LE(0, n); const uint32 range = ~static_cast<uint32>(0); if (n == 0) { return r->Rand32() * n; } else if (0 == (n & (n - 1))) { return r->Rand32() & (n - 1); } else { uint32 rem = (range % n) + 1; uint32 rnd; do { rnd = r->Rand32(); } while (rnd < rem); return rnd % n; } } int WeightedPicker::Pick(SimplePhilox* rnd) const { if (total_weight() == 0) return -1; return PickAt(UnbiasedUniform(rnd, total_weight())); } int WeightedPicker::PickAt(int32_t weight_index) const { if (weight_index < 0 || weight_index >= total_weight()) return -1; int32_t position = weight_index; int index = 0; for (int l = 1; l < num_levels_; l++) { const int32_t left_weight = level_[l][2 * index]; if (position < left_weight) { index = 2 * index; } else { index = 2 * index + 1; position -= left_weight; } } CHECK_GE(index, 0); CHECK_LT(index, N_); CHECK_LE(position, level_[num_levels_ - 1][index]); return index; } void WeightedPicker::set_weight(int index, int32_t weight) { assert(index >= 0); assert(index < N_); const int32_t delta = weight - get_weight(index); for (int l = num_levels_ - 1; l >= 0; l--) { level_[l][index] += delta; index >>= 1; } } void WeightedPicker::SetAllWeights(int32_t weight) { int32* leaves = level_[num_levels_ - 1]; for (int i = 0; i < N_; i++) leaves[i] = weight; for (int i = N_; i < LevelSize(num_levels_ - 1); i++) leaves[i] = 0; RebuildTreeWeights(); } void WeightedPicker::SetWeightsFromArray(int N, const int32* weights) { Resize(N); int32* leaves = level_[num_levels_ - 1]; for (int i = 0; i < N_; i++) leaves[i] = weights[i]; for (int i = N_; i < LevelSize(num_levels_ - 1); i++) leaves[i] = 0; RebuildTreeWeights(); } void WeightedPicker::RebuildTreeWeights() { for (int l = num_levels_ - 2; l >= 0; l--) { int32* level = level_[l]; int32* children = level_[l + 1]; for (int i = 0; i < LevelSize(l); i++) { level[i] = children[2 * i] + children[2 * i + 1]; } } } void WeightedPicker::Append(int32_t weight) { Resize(num_elements() + 1); set_weight(num_elements() - 1, weight); } void WeightedPicker::Resize(int new_size) { CHECK_GE(new_size, 0); if (new_size <= LevelSize(num_levels_ - 1)) { for (int i = new_size; i < N_; i++) { set_weight(i, 0); } N_ = new_size; return; } assert(new_size > N_); WeightedPicker new_picker(new_size); int32* dst = new_picker.level_[new_picker.num_levels_ - 1]; int32* src = this->level_[this->num_levels_ - 1]; memcpy(dst, src, sizeof(dst[0]) * N_); memset(dst + N_, 0, sizeof(dst[0]) * (new_size - N_)); new_picker.RebuildTreeWeights(); std::swap(new_picker.N_, this->N_); std::swap(new_picker.num_levels_, this->num_levels_); std::swap(new_picker.level_, this->level_); assert(this->N_ == new_size); } } }
#include "tsl/lib/random/weighted_picker.h" #include <string.h> #include <vector> #include "tsl/lib/random/simple_philox.h" #include "tsl/platform/logging.h" #include "tsl/platform/macros.h" #include "tsl/platform/test.h" #include "tsl/platform/test_benchmark.h" #include "tsl/platform/types.h" namespace tsl { namespace random { static void TestPicker(SimplePhilox* rnd, int size); static void CheckUniform(SimplePhilox* rnd, WeightedPicker* picker, int trials); static void CheckSkewed(SimplePhilox* rnd, WeightedPicker* picker, int trials); static void TestPickAt(int items, const int32* weights); TEST(WeightedPicker, Simple) { PhiloxRandom philox(testing::RandomSeed(), 17); SimplePhilox rnd(&philox); { VLOG(0) << "======= Zero-length picker"; WeightedPicker picker(0); EXPECT_EQ(picker.Pick(&rnd), -1); } { VLOG(0) << "======= Singleton picker"; WeightedPicker picker(1); EXPECT_EQ(picker.Pick(&rnd), 0); EXPECT_EQ(picker.Pick(&rnd), 0); EXPECT_EQ(picker.Pick(&rnd), 0); } { VLOG(0) << "======= Grown picker"; WeightedPicker picker(0); for (int i = 0; i < 10; i++) { picker.Append(1); } CheckUniform(&rnd, &picker, 100000); } { VLOG(0) << "======= Grown picker with zero weights"; WeightedPicker picker(1); picker.Resize(10); EXPECT_EQ(picker.Pick(&rnd), 0); EXPECT_EQ(picker.Pick(&rnd), 0); EXPECT_EQ(picker.Pick(&rnd), 0); } { VLOG(0) << "======= Shrink picker and check weights"; WeightedPicker picker(1); picker.Resize(10); EXPECT_EQ(picker.Pick(&rnd), 0); EXPECT_EQ(picker.Pick(&rnd), 0); EXPECT_EQ(picker.Pick(&rnd), 0); for (int i = 0; i < 10; i++) { picker.set_weight(i, i); } EXPECT_EQ(picker.total_weight(), 45); picker.Resize(5); EXPECT_EQ(picker.total_weight(), 10); picker.Resize(2); EXPECT_EQ(picker.total_weight(), 1); picker.Resize(1); EXPECT_EQ(picker.total_weight(), 0); } } TEST(WeightedPicker, BigWeights) { PhiloxRandom philox(testing::RandomSeed() + 1, 17); SimplePhilox rnd(&philox); VLOG(0) << "======= Check uniform with big weights"; WeightedPicker picker(2); picker.SetAllWeights(2147483646L / 3); CheckUniform(&rnd, &picker, 100000); } TEST(WeightedPicker, Deterministic) { VLOG(0) << "======= Testing deterministic pick"; static const int32 weights[] = {1, 0, 200, 5, 42}; TestPickAt(TF_ARRAYSIZE(weights), weights); } TEST(WeightedPicker, Randomized) { PhiloxRandom philox(testing::RandomSeed() + 10, 17); SimplePhilox rnd(&philox); TestPicker(&rnd, 1); TestPicker(&rnd, 2); TestPicker(&rnd, 3); TestPicker(&rnd, 4); TestPicker(&rnd, 7); TestPicker(&rnd, 8); TestPicker(&rnd, 9); TestPicker(&rnd, 10); TestPicker(&rnd, 100); } static void TestPicker(SimplePhilox* rnd, int size) { VLOG(0) << "======= Testing size " << size; { WeightedPicker picker(size); picker.SetAllWeights(0); for (int i = 0; i < 100; i++) EXPECT_EQ(picker.Pick(rnd), -1); } std::vector<int32> weights(size); for (int elem = 0; elem < size; elem++) { weights[elem] = 0; } for (int elem = 0; elem < size; elem++) { WeightedPicker picker(size); picker.SetAllWeights(0); picker.set_weight(elem, elem + 1); for (int i = 0; i < 100; i++) EXPECT_EQ(picker.Pick(rnd), elem); weights[elem] = 10; picker.SetWeightsFromArray(size, &weights[0]); for (int i = 0; i < 100; i++) EXPECT_EQ(picker.Pick(rnd), elem); weights[elem] = 0; } { WeightedPicker picker(size); CheckUniform(rnd, &picker, 100000); } if (size / 3 > 0) { WeightedPicker picker(size / 3); while (picker.num_elements() != size) { picker.Append(1); } CheckUniform(rnd, &picker, 100000); } if (size <= 10) { WeightedPicker picker(size); int32_t weight = 1; for (int elem = 0; elem < size; elem++) { picker.set_weight(elem, weight); weights[elem] = weight; weight *= 2; } CheckSkewed(rnd, &picker, 1000000); WeightedPicker array_picker(0); array_picker.SetWeightsFromArray(size, &weights[0]); CheckSkewed(rnd, &array_picker, 1000000); } } static void CheckUniform(SimplePhilox* rnd, WeightedPicker* picker, int trials) { const int size = picker->num_elements(); int* count = new int[size]; memset(count, 0, sizeof(count[0]) * size); for (int i = 0; i < size * trials; i++) { const int elem = picker->Pick(rnd); EXPECT_GE(elem, 0); EXPECT_LT(elem, size); count[elem]++; } const int expected_min = int(0.9 * trials); const int expected_max = int(1.1 * trials); for (int i = 0; i < size; i++) { EXPECT_GE(count[i], expected_min); EXPECT_LE(count[i], expected_max); } delete[] count; } static void CheckSkewed(SimplePhilox* rnd, WeightedPicker* picker, int trials) { const int size = picker->num_elements(); int* count = new int[size]; memset(count, 0, sizeof(count[0]) * size); for (int i = 0; i < size * trials; i++) { const int elem = picker->Pick(rnd); EXPECT_GE(elem, 0); EXPECT_LT(elem, size); count[elem]++; } for (int i = 0; i < size - 1; i++) { LOG(INFO) << i << ": " << count[i]; const float ratio = float(count[i + 1]) / float(count[i]); EXPECT_GE(ratio, 1.6f); EXPECT_LE(ratio, 2.4f); } delete[] count; } static void TestPickAt(int items, const int32* weights) { WeightedPicker picker(items); picker.SetWeightsFromArray(items, weights); int weight_index = 0; for (int i = 0; i < items; ++i) { for (int j = 0; j < weights[i]; ++j) { int pick = picker.PickAt(weight_index); EXPECT_EQ(pick, i); ++weight_index; } } EXPECT_EQ(weight_index, picker.total_weight()); } static void BM_Create(::testing::benchmark::State& state) { int arg = state.range(0); for (auto s : state) { WeightedPicker p(arg); } } BENCHMARK(BM_Create)->Range(1, 1024); static void BM_CreateAndSetWeights(::testing::benchmark::State& state) { int arg = state.range(0); std::vector<int32> weights(arg); for (int i = 0; i < arg; i++) { weights[i] = i * 10; } for (auto s : state) { WeightedPicker p(arg); p.SetWeightsFromArray(arg, &weights[0]); } } BENCHMARK(BM_CreateAndSetWeights)->Range(1, 1024); static void BM_Pick(::testing::benchmark::State& state) { int arg = state.range(0); PhiloxRandom philox(301, 17); SimplePhilox rnd(&philox); WeightedPicker p(arg); int result = 0; for (auto s : state) { result += p.Pick(&rnd); } VLOG(4) << result; } BENCHMARK(BM_Pick)->Range(1, 1024); } }
2,310
cpp
tensorflow/tensorflow
random_distributions
third_party/xla/third_party/tsl/tsl/lib/random/random_distributions.cc
third_party/xla/third_party/tsl/tsl/lib/random/random_distributions_test.cc
#ifndef TENSORFLOW_TSL_LIB_RANDOM_RANDOM_DISTRIBUTIONS_H_ #define TENSORFLOW_TSL_LIB_RANDOM_RANDOM_DISTRIBUTIONS_H_ #include <algorithm> #include <cmath> #include <type_traits> #include "unsupported/Eigen/CXX11/Tensor" #include "tsl/lib/random/philox_random.h" #include "tsl/lib/random/random_distributions_utils.h" #include "tsl/platform/types.h" namespace tsl { namespace random { PHILOX_DEVICE_INLINE Eigen::half Uint16ToHalf(uint16 x); PHILOX_DEVICE_INLINE bfloat16 Uint16ToGfloat16(uint16 x); template <typename Int> PHILOX_DEVICE_INLINE Int SignedAdd(Int a, typename std::make_unsigned<Int>::type b) { auto b_div_2 = b >> 1; return a + static_cast<Int>(b_div_2) + static_cast<Int>(b - b_div_2); } template <class Generator, typename RealType> class UniformDistribution; template <class Generator> class UniformDistribution<Generator, Eigen::half> { public: static constexpr int kResultElementCount = Generator::kResultElementCount; static constexpr int kElementCost = 3; static constexpr bool kVariableSamplesPerOutput = false; typedef Array<Eigen::half, kResultElementCount> ResultType; typedef Eigen::half ResultElementType; PHILOX_DEVICE_INLINE ResultType operator()(Generator* gen) { typename Generator::ResultType sample = (*gen)(); ResultType result; for (int i = 0; i < kResultElementCount; ++i) { result[i] = Uint16ToHalf(sample[i]); } return result; } }; template <class Generator> class UniformDistribution<Generator, bfloat16> { public: static constexpr int kResultElementCount = Generator::kResultElementCount; static constexpr int kElementCost = 3; static constexpr bool kVariableSamplesPerOutput = false; typedef Array<bfloat16, kResultElementCount> ResultType; typedef bfloat16 ResultElementType; PHILOX_DEVICE_INLINE ResultType operator()(Generator* gen) { typename Generator::ResultType sample = (*gen)(); ResultType result; for (int i = 0; i < kResultElementCount; ++i) { result[i] = Uint16ToGfloat16(sample[i]); } return result; } }; template <class Generator> class UniformDistribution<Generator, float> { public: static constexpr int kResultElementCount = Generator::kResultElementCount; static constexpr int kElementCost = 3; static constexpr bool kVariableSamplesPerOutput = false; typedef Array<float, kResultElementCount> ResultType; typedef float ResultElementType; PHILOX_DEVICE_INLINE ResultType operator()(Generator* gen) { typename Generator::ResultType sample = (*gen)(); ResultType result; for (int i = 0; i < kResultElementCount; ++i) { result[i] = Uint32ToFloat(sample[i]); } return result; } }; template <class Generator> class UniformDistribution<Generator, double> { public: static constexpr int kResultElementCount = Generator::kResultElementCount / 2; static constexpr int kElementCost = 3; static constexpr bool kVariableSamplesPerOutput = false; typedef Array<double, kResultElementCount> ResultType; typedef double ResultElementType; PHILOX_DEVICE_INLINE ResultType operator()(Generator* gen) { typename Generator::ResultType sample = (*gen)(); ResultType result; for (int i = 0; i < kResultElementCount; ++i) { result[i] = Uint64ToDouble(sample[2 * i], sample[2 * i + 1]); } return result; } }; template <class Generator> class UniformDistribution<Generator, int32> { public: static constexpr int kResultElementCount = Generator::kResultElementCount; static constexpr int kElementCost = 3; static constexpr bool kVariableSamplesPerOutput = false; typedef Array<int32, kResultElementCount> ResultType; typedef int32 ResultElementType; UniformDistribution(int32_t lo, int32_t hi) : lo_(lo), range_(static_cast<uint32>(hi) - static_cast<uint32>(lo)) {} PHILOX_DEVICE_INLINE ResultType operator()(Generator* gen) { typename Generator::ResultType sample = (*gen)(); ResultType result; for (int i = 0; i < kResultElementCount; ++i) { result[i] = SignedAdd(lo_, sample[i] % range_); } return result; } private: int32 lo_; uint32 range_; }; template <class Generator> class UniformDistribution<Generator, int64_t> { public: static constexpr int kResultElementCount = Generator::kResultElementCount / 2; static constexpr int kElementCost = 3; static constexpr bool kVariableSamplesPerOutput = false; typedef Array<int64_t, kResultElementCount> ResultType; typedef int64_t ResultElementType; UniformDistribution(int64_t lo, int64_t hi) : lo_(lo), range_(static_cast<uint64>(hi) - static_cast<uint64>(lo)) {} PHILOX_DEVICE_INLINE ResultType operator()(Generator* gen) { typename Generator::ResultType sample = (*gen)(); ResultType result; for (int i = 0; i < kResultElementCount; ++i) { auto bits = sample[2 * i] | static_cast<uint64>(sample[2 * i + 1]) << 32; result[i] = SignedAdd(lo_, bits % range_); } return result; } private: int64_t lo_; uint64 range_; }; template <typename Generator, typename IntType> class UniformFullIntDistribution; template <typename Generator, typename IntType> class UniformFullIntDistribution32 { public: static constexpr int kResultElementCount = Generator::kResultElementCount; static constexpr int kElementCost = 3; static constexpr bool kVariableSamplesPerOutput = false; typedef Array<IntType, kResultElementCount> ResultType; typedef IntType ResultElementType; PHILOX_DEVICE_INLINE ResultType operator()(Generator* gen) { typename Generator::ResultType sample = (*gen)(); ResultType result; for (int i = 0; i < kResultElementCount; ++i) { result[i] = sample[i]; } return result; } }; template <typename Generator, typename IntType> class UniformFullIntDistribution64 { public: static constexpr int kResultElementCount = Generator::kResultElementCount / 2; static constexpr int kElementCost = 3; static constexpr bool kVariableSamplesPerOutput = false; typedef Array<IntType, kResultElementCount> ResultType; typedef IntType ResultElementType; PHILOX_DEVICE_INLINE ResultType operator()(Generator* gen) { typename Generator::ResultType sample = (*gen)(); ResultType result; for (int i = 0; i < kResultElementCount; ++i) { result[i] = sample[2 * i] | static_cast<uint64>(sample[2 * i + 1]) << 32; } return result; } }; template <typename Generator> class UniformFullIntDistribution<Generator, int32> : public UniformFullIntDistribution32<Generator, int32> {}; template <typename Generator> class UniformFullIntDistribution<Generator, uint32> : public UniformFullIntDistribution32<Generator, uint32> {}; template <typename Generator> class UniformFullIntDistribution<Generator, int64_t> : public UniformFullIntDistribution64<Generator, int64_t> {}; template <typename Generator> class UniformFullIntDistribution<Generator, uint64> : public UniformFullIntDistribution64<Generator, uint64> {}; template <class Generator> class SingleSampleAdapter { public: static constexpr int kResultElementCount = 1; static constexpr int kNativeElementCount = Generator::kResultElementCount; typedef typename Generator::ResultElementType ResultType; typedef typename Generator::ResultElementType ResultElementType; PHILOX_DEVICE_INLINE explicit SingleSampleAdapter(Generator* gen) : generator_(gen), used_result_index_(Generator::kResultElementCount) {} PHILOX_DEVICE_INLINE ResultType operator()() { if (used_result_index_ == Generator::kResultElementCount) { unused_results_ = (*generator_)(); used_result_index_ = 0; } return unused_results_[used_result_index_++]; } PHILOX_DEVICE_INLINE void Skip(uint64 num_skips) { if (!num_skips) { return; } int num_unused_results = kNativeElementCount - used_result_index_; if (num_skips <= num_unused_results) { used_result_index_ += num_skips; return; } num_skips -= num_unused_results; used_result_index_ = kNativeElementCount; SkipFromGenerator(num_skips / kNativeElementCount); num_skips = num_skips % kNativeElementCount; if (num_skips) { unused_results_ = (*generator_)(); used_result_index_ = num_skips; } } private: PHILOX_DEVICE_INLINE void SkipFromGenerator(uint64 num_skips) { while (num_skips--) { (*generator_)(); } } Generator* generator_; typename Generator::ResultType unused_results_; int used_result_index_; }; template <class Generator, typename RealType> class NormalDistribution; PHILOX_DEVICE_INLINE void BoxMullerDouble(uint32 x0, uint32 x1, uint32 x2, uint32 x3, double* d0, double* d1); template <class Generator> class NormalDistribution<Generator, Eigen::half> { public: static constexpr int kResultElementCount = Generator::kResultElementCount; static constexpr int kElementCost = 70; static constexpr bool kVariableSamplesPerOutput = false; typedef Array<Eigen::half, kResultElementCount> ResultType; typedef Eigen::half ResultElementType; PHILOX_DEVICE_INLINE ResultType operator()(Generator* gen) { typename Generator::ResultType sample = (*gen)(); ResultType result; for (int i = 0; i < kResultElementCount; i += 2) { float f[2]; BoxMullerFloat(sample[i], sample[i + 1], &f[0], &f[1]); result[i] = Eigen::half(f[0]); result[i + 1] = Eigen::half(f[1]); } return result; } }; template <class Generator> class NormalDistribution<Generator, bfloat16> { public: static constexpr int kResultElementCount = Generator::kResultElementCount; static constexpr int kElementCost = 70; static constexpr bool kVariableSamplesPerOutput = false; typedef Array<bfloat16, kResultElementCount> ResultType; typedef bfloat16 ResultElementType; PHILOX_DEVICE_INLINE ResultType operator()(Generator* gen) { typename Generator::ResultType sample = (*gen)(); ResultType result; static_assert(kResultElementCount % 2 == 0, "kResultElementCount should be an even number"); for (int i = 0; i < kResultElementCount; i += 2) { float f[2]; BoxMullerFloat(sample[i], sample[i + 1], &f[0], &f[1]); result[i] = bfloat16(f[0]); result[i + 1] = bfloat16(f[1]); } return result; } }; template <class Generator> class NormalDistribution<Generator, float> { public: static constexpr int kResultElementCount = Generator::kResultElementCount; static constexpr int kElementCost = 70; static constexpr bool kVariableSamplesPerOutput = false; typedef Array<float, kResultElementCount> ResultType; typedef float ResultElementType; PHILOX_DEVICE_INLINE ResultType operator()(Generator* gen) { typename Generator::ResultType sample = (*gen)(); ResultType result; for (int i = 0; i < kResultElementCount; i += 2) { BoxMullerFloat(sample[i], sample[i + 1], &result[i], &result[i + 1]); } return result; } }; template <class Generator> class NormalDistribution<Generator, double> { public: static constexpr int kResultElementCount = Generator::kResultElementCount / 2; static constexpr int kElementCost = 70; static constexpr bool kVariableSamplesPerOutput = false; typedef Array<double, kResultElementCount> ResultType; typedef double ResultElementType; PHILOX_DEVICE_INLINE ResultType operator()(Generator* gen) { typename Generator::ResultType sample = (*gen)(); ResultType result; for (int i = 0; i < kResultElementCount; i += 2) { const int i2 = 2 * i; BoxMullerDouble(sample[i2], sample[i2 + 1], sample[i2 + 2], sample[i2 + 3], &result[i], &result[i + 1]); } return result; } }; template <class SingleSampleGenerator, typename RealType> class TruncatedNormalDistribution; template <class SingleSampleGenerator> class TruncatedNormalDistribution<SingleSampleGenerator, Eigen::half> { public: static constexpr int kResultElementCount = SingleSampleGenerator::kNativeElementCount; static constexpr int kElementCost = 90; static constexpr bool kVariableSamplesPerOutput = true; const float kTruncateValue = 2.0f; typedef Array<Eigen::half, kResultElementCount> ResultType; typedef Eigen::half ResultElementType; PHILOX_DEVICE_INLINE ResultType operator()(SingleSampleGenerator* gen) { ResultType results; int index = 0; while (true) { const uint32 x0 = (*gen)(); const uint32 x1 = (*gen)(); float f[2]; BoxMullerFloat(x0, x1, &f[0], &f[1]); if (Eigen::numext::abs(f[0]) < kTruncateValue) { results[index++] = Eigen::half(f[0]); if (index >= kResultElementCount) { return results; } } if (Eigen::numext::abs(f[1]) < kTruncateValue) { results[index++] = Eigen::half(f[1]); if (index >= kResultElementCount) { return results; } } } } }; template <class SingleSampleGenerator> class TruncatedNormalDistribution<SingleSampleGenerator, bfloat16> { public: static constexpr int kResultElementCount = SingleSampleGenerator::kNativeElementCount; static constexpr int kElementCost = 90; static constexpr bool kVariableSamplesPerOutput = true; const float kTruncateValue = 2.0f; typedef Array<bfloat16, kResultElementCount> ResultType; typedef bfloat16 ResultElementType; PHILOX_DEVICE_INLINE ResultType operator()(SingleSampleGenerator* gen) { ResultType results; int index = 0; while (true) { const uint32 x0 = (*gen)(); const uint32 x1 = (*gen)(); float f[2]; BoxMullerFloat(x0, x1, &f[0], &f[1]); if (Eigen::numext::abs(f[0]) < kTruncateValue) { results[index++] = bfloat16(f[0]); if (index >= kResultElementCount) { return results; } } if (Eigen::numext::abs(f[1]) < kTruncateValue) { results[index++] = bfloat16(f[1]); if (index >= kResultElementCount) { return results; } } } } }; template <class SingleSampleGenerator> class TruncatedNormalDistribution<SingleSampleGenerator, float> { public: static constexpr int kResultElementCount = SingleSampleGenerator::kNativeElementCount; static constexpr int kElementCost = 90; static constexpr bool kVariableSamplesPerOutput = true; const float kTruncateValue = 2.0f; typedef Array<float, kResultElementCount> ResultType; typedef float ResultElementType; PHILOX_DEVICE_INLINE ResultType operator()(SingleSampleGenerator* gen) { ResultType results; int index = 0; while (true) { const uint32 x0 = (*gen)(); const uint32 x1 = (*gen)(); float f[2]; BoxMullerFloat(x0, x1, &f[0], &f[1]); if (Eigen::numext::abs(f[0]) < kTruncateValue) { results[index++] = f[0]; if (index >= kResultElementCount) { return results; } } if (Eigen::numext::abs(f[1]) < kTruncateValue) { results[index++] = f[1]; if (index >= kResultElementCount) { return results; } } } } }; template <class SingleSampleGenerator> class TruncatedNormalDistribution<SingleSampleGenerator, double> { public: static constexpr int kResultElementCount = (SingleSampleGenerator::kNativeElementCount > 1) ? SingleSampleGenerator::kNativeElementCount / 2 : 1; static constexpr int kElementCost = 90; static constexpr bool kVariableSamplesPerOutput = true; typedef Array<double, kResultElementCount> ResultType; typedef double ResultElementType; const double kTruncateValue = 2.0; PHILOX_DEVICE_INLINE ResultType operator()(SingleSampleGenerator* gen) { ResultType results; int index = 0; while (true) { const uint32 x0 = (*gen)(); const uint32 x1 = (*gen)(); const uint32 x2 = (*gen)(); const uint32 x3 = (*gen)(); double d[2]; BoxMullerDouble(x0, x1, x2, x3, &d[0], &d[1]); if (Eigen::numext::abs(d[0]) < kTruncateValue) { results[index++] = d[0]; if (index >= kResultElementCount) { return results; } } if (Eigen::numext::abs(d[1]) < kTruncateValue) { results[index++] = d[1]; if (index >= kResultElementCount) { return results; } } } } }; PHILOX_DEVICE_INLINE void BoxMullerDouble(uint32 x0, uint32 x1, uint32 x2, uint32 x3, double* d0, double* d1) { const double epsilon = 1.0e-7; double u1 = Uint64ToDouble(x0, x1); if (u1 < epsilon) { u1 = epsilon; } const double v1 = 2 * M_PI * Uint64ToDouble(x2, x3); const double u2 = Eigen::numext::sqrt(-2.0 * Eigen::numext::log(u1)); #if !defined(__linux__) *d0 = Eigen::numext::sin(v1); *d1 = Eigen::numext::cos(v1); #else sincos(v1, d0, d1); #endif *d0 *= u2; *d1 *= u2; } PHILOX_DEVICE_INLINE Eigen::half Uint16ToHalf(uint16 x) { const uint16 man = x & 0x3ffu; const uint16 exp = static_cast<uint16>(15); const uint16 val = (exp << 10) | man; Eigen::half result = Eigen::numext::bit_cast<Eigen::half>(val); return result - Eigen::half(1.0); } PHILOX_DEVICE_INLINE bfloat16 Uint16ToGfloat16(uint16 x) { const uint16 man = x & 0x7fu; const uint16 exp = static_cast<uint16>(127); const uint16 val = (exp << 7) | man; bfloat16 result; memcpy(&result, &val, sizeof(val)); return result - bfloat16(1.0); } } } #endif #include "tsl/lib/random/distribution_sampler.h" #include "tsl/lib/random/philox_random.h" namespace tsl { namespace random { template <> void SingleSampleAdapter<PhiloxRandom>::SkipFromGenerator(uint64 num_skips) { generator_->Skip(num_skips); } } }
#include "tsl/lib/random/random_distributions.h" #include <algorithm> #include <cmath> #include <functional> #include <numeric> #include <unordered_map> #include <vector> #include "tsl/lib/math/math_util.h" #include "tsl/lib/random/philox_random.h" #include "tsl/lib/random/philox_random_test_utils.h" #include "tsl/platform/logging.h" #include "tsl/platform/random.h" #include "tsl/platform/test.h" namespace tsl { namespace random { namespace { static constexpr float kZLimit = 6.0; static constexpr float kZLimitBfloat16 = 20.0; template <class Distribution> void FillRandomsWithSingles(PhiloxRandom gen, typename Distribution::ResultElementType* p, int64_t size) { int granularity = Distribution::kResultElementCount; CHECK(size % granularity == 0) << " size: " << size << " granularity: " << granularity; SingleSampleAdapter<PhiloxRandom> single_samples(&gen); Distribution dist; for (int i = 0; i < size; i += granularity) { auto sample = dist(&single_samples); std::copy(&sample[0], &sample[0] + granularity, &p[i]); } } template <typename T> bool CheckSamplesMoments(const std::vector<T>& samples, const std::function<double(int)>& theoretical_moments, int max_moments, int stride, T z_limit) { const T* const samples_data = &samples[0]; const int samples_size = samples.size(); std::vector<double> moments(max_moments + 1); double* const moments_data = &moments[0]; std::vector<int> moments_sample_count(max_moments + 1); int* const moments_sample_count_data = &moments_sample_count[0]; for (int k = 0; k < samples_size; ++k) { double moment = 1.; for (int i = 0; i <= max_moments; ++i) { int index = k + i * stride; if (index >= samples_size) { break; } moments_data[i] += moment; ++moments_sample_count_data[i]; moment *= static_cast<double>(samples_data[index]); } } for (int i = 0; i <= max_moments; ++i) { moments[i] /= moments_sample_count[i]; } bool status = true; for (int i = 1; i <= max_moments; ++i) { const double moments_i_mean = (stride == 0) ? theoretical_moments(i) : MathUtil::IPow(theoretical_moments(1), i); const double moments_i_squared = (stride == 0) ? theoretical_moments(2 * i) : MathUtil::IPow(theoretical_moments(2), i); const double moments_i_var = moments_i_squared - moments_i_mean * moments_i_mean; static const double kNumericalError = 1e-6; const double error_per_moment = i * kNumericalError; const double total_variance = moments_i_var / moments_sample_count[i] + error_per_moment; const double z_test = fabs((moments[i] - moments_i_mean) / sqrt(total_variance)); if (z_test > static_cast<double>(z_limit)) { LOG(ERROR) << "failing z_test:" << " moment: " << i << " stride: " << stride << " z_test: " << z_test << " z_limit: " << z_limit << " measured moments: " << moments[i] << " theoretical mean of the moments: " << moments_i_mean << " theoretical var of the moments: " << moments_i_var << " sample count: " << moments_sample_count[i]; status = false; } } return status; } template <typename T> void UniformMomentsTest(int count, int max_moments, const std::vector<int>& strides, T z_limit) { auto uniform_moments = [](int n) -> double { return 1. / (n + 1); }; std::vector<T> v1(count); uint64 seed = GetTestSeed(); PhiloxRandom gen(seed); FillRandoms<UniformDistribution<PhiloxRandom, T> >(gen, &v1[0], v1.size()); for (int stride : strides) { bool status = CheckSamplesMoments(v1, uniform_moments, max_moments, stride, z_limit); ASSERT_TRUE(status) << " UniformMomentsTest failing. seed: " << seed; } } template <typename T> void NormalMomentsTest(int count, int max_moments, const std::vector<int>& strides, T z_limit) { auto normal_moments = [](int n) -> double { if (n % 2 == 1) { return 0.; } else { double v = 1.; for (int i = n - 1; i >= 1; i -= 2) { v *= i; } return v; } }; std::vector<T> v1(count); uint64 seed = GetTestSeed(); PhiloxRandom gen(seed); FillRandoms<NormalDistribution<PhiloxRandom, T> >(gen, &v1[0], v1.size()); for (int stride : strides) { bool status = CheckSamplesMoments(v1, normal_moments, max_moments, stride, z_limit); ASSERT_TRUE(status) << " NormalMomentsTest failing. seed: " << seed; } } class TruncatedNormalMoments { public: double operator()(int n) { if (n == 0) { return 1; } if (n % 2 == 1) { return 0.; } auto iter = cached_results_.find(n); if (iter != cached_results_.end()) { return iter->second; } double bias = 2.0 * MathUtil::IPow(kV, n - 1) * kFV / (2.0 * kPhiV - 1.0); double moment_n_minus_2 = (*this)(n - 2); double moment_n = (n - 1) * moment_n_minus_2 - bias; cached_results_[n] = moment_n; return moment_n; } private: const double kV = 2.0; const double kFV = 1.0 / sqrt(2.0 * M_PI) * exp(-kV * kV / 2.0); const double kPhiV = 0.977249868051821; std::unordered_map<int, double> cached_results_; }; template <typename T> void RandomParametersMomentsTest(int count, int max_moments, const std::vector<int>& strides, T z_limit) { std::vector<T> v1(count); uint64 seed = GetTestSeed(); PhiloxRandom gen(seed); FillRandomsWithSingles< TruncatedNormalDistribution<SingleSampleAdapter<PhiloxRandom>, T> >( gen, &v1[0], v1.size()); for (int stride : strides) { bool status = CheckSamplesMoments(v1, TruncatedNormalMoments(), max_moments, stride, z_limit); ASSERT_TRUE(status) << " NormalMomentsTest failing. seed: " << seed; } } TEST(PhiloxRandomTest, UniformBfloat16MomentsTest) { const std::vector<int> strides = {0, 1, 4, 17}; UniformMomentsTest<bfloat16>(1 << 20, 40, strides, bfloat16(kZLimitBfloat16)); } TEST(PhiloxRandomTest, NormalBfloat16MomentsTest) { const std::vector<int> strides = {0, 1, 4, 17}; NormalMomentsTest<bfloat16>(8 << 20, 25, strides, bfloat16(kZLimitBfloat16)); } TEST(PhiloxRandomTest, RandomParametersBfloat16MomentsTest) { const std::vector<int> strides = {0, 1, 4, 17}; RandomParametersMomentsTest<bfloat16>(1 << 20, 40, strides, bfloat16(kZLimitBfloat16)); } TEST(PhiloxRandomTest, UniformFloatMomentsTest) { const std::vector<int> strides = {0, 1, 4, 17}; UniformMomentsTest<float>(1 << 20, 40, strides, kZLimit); } TEST(PhiloxRandomTest, NormalFloatMomentsTest) { const std::vector<int> strides = {0, 1, 4, 17}; NormalMomentsTest<float>(8 << 20, 25, strides, kZLimit); } TEST(PhiloxRandomTest, RandomParametersFloatMomentsTest) { const std::vector<int> strides = {0, 1, 4, 17}; RandomParametersMomentsTest<float>(1 << 20, 40, strides, kZLimit); } TEST(PhiloxRandomTest, UniformDoubleMomentsTest) { const std::vector<int> strides = {0, 1, 4, 17}; UniformMomentsTest<double>(1 << 20, 40, strides, kZLimit); } TEST(PhiloxRandomTest, NormalDoubleMomentsTest) { const std::vector<int> strides = {0, 1, 4, 17}; NormalMomentsTest<double>(8 << 20, 25, strides, kZLimit); } TEST(PhiloxRandomTest, RandomParametersDoubleMomentsTest) { const std::vector<int> strides = {0, 1, 4, 17}; RandomParametersMomentsTest<double>(1 << 20, 40, strides, kZLimit); } class MockGenerator { public: explicit MockGenerator(uint64 seed) : counter_(seed) {} using ResultType = std::vector<uint32>; using ResultElementType = uint32; static constexpr int kResultElementCount = 1; ResultType operator()() { ResultType result; result.push_back(counter_++); return result; } private: uint32 counter_; }; template <typename T> void SingleSampleAdapterSkipTest() { std::vector<uint64> skips(10); std::vector<uint64> skip_afters(10); std::iota(skips.begin(), skips.end(), 0); std::iota(skip_afters.begin(), skip_afters.end(), 0); uint64 total_samples = 100; uint64 seed = GetTestSeed(); for (uint64 skip : skips) { for (uint64 skip_after : skip_afters) { T parent_gen(seed); SingleSampleAdapter<T> gen(&parent_gen); T parent_gen_to_skip(seed); SingleSampleAdapter<T> gen_to_skip(&parent_gen_to_skip); int cur = 0; for (; cur < skip_after; cur++) { gen(); gen_to_skip(); } for (; cur < skip_after + skip; cur++) { gen(); } gen_to_skip.Skip(skip); for (; cur < total_samples; cur++) { ASSERT_EQ(gen(), gen_to_skip()); } } } } TEST(SingleSampleAdapterTest, PhiloxRandomSkip) { SingleSampleAdapterSkipTest<PhiloxRandom>(); } TEST(SingleSampleAdapterTest, MockGeneratorSkip) { SingleSampleAdapterSkipTest<MockGenerator>(); } } } }
2,311
cpp
tensorflow/tensorflow
distribution_sampler
third_party/xla/third_party/tsl/tsl/lib/random/distribution_sampler.cc
third_party/xla/third_party/tsl/tsl/lib/random/distribution_sampler_test.cc
#ifndef TENSORFLOW_TSL_LIB_RANDOM_DISTRIBUTION_SAMPLER_H_ #define TENSORFLOW_TSL_LIB_RANDOM_DISTRIBUTION_SAMPLER_H_ #include <memory> #include <utility> #include "absl/types/span.h" #include "tsl/lib/random/simple_philox.h" #include "tsl/platform/logging.h" #include "tsl/platform/macros.h" #include "tsl/platform/types.h" namespace tsl { namespace random { class DistributionSampler { public: explicit DistributionSampler(const absl::Span<const float> weights); ~DistributionSampler() {} int Sample(SimplePhilox* rand) const { float r = rand->RandFloat(); int idx = rand->Uniform(num_); if (r < prob(idx)) return idx; DCHECK_NE(-1, alt(idx)); return alt(idx); } int num() const { return num_; } private: float prob(int idx) const { DCHECK_LT(idx, num_); return data_[idx].first; } int alt(int idx) const { DCHECK_LT(idx, num_); return data_[idx].second; } void set_prob(int idx, float f) { DCHECK_LT(idx, num_); data_[idx].first = f; } void set_alt(int idx, int val) { DCHECK_LT(idx, num_); data_[idx].second = val; } int num_; std::unique_ptr<std::pair<float, int>[]> data_; DistributionSampler(const DistributionSampler&) = delete; void operator=(const DistributionSampler&) = delete; }; } } #endif #include "tsl/lib/random/distribution_sampler.h" #include <memory> #include <vector> #include "absl/types/span.h" namespace tsl { namespace random { DistributionSampler::DistributionSampler( const absl::Span<const float> weights) { DCHECK(!weights.empty()); int n = weights.size(); num_ = n; data_.reset(new std::pair<float, int>[n]); std::unique_ptr<double[]> pr(new double[n]); double sum = 0.0; for (int i = 0; i < n; i++) { sum += weights[i]; set_alt(i, -1); } std::vector<int> high; high.reserve(n); std::vector<int> low; low.reserve(n); for (int i = 0; i < n; i++) { double p = (weights[i] * n) / sum; pr[i] = p; if (p < 1.0) { low.push_back(i); } else { high.push_back(i); } } while (!high.empty() && !low.empty()) { int l = low.back(); low.pop_back(); int h = high.back(); high.pop_back(); set_alt(l, h); DCHECK_GE(pr[h], 1.0); double remaining = pr[h] - (1.0 - pr[l]); pr[h] = remaining; if (remaining < 1.0) { low.push_back(h); } else { high.push_back(h); } } for (int i = 0; i < n; i++) { set_prob(i, pr[i]); } for (size_t i = 0; i < high.size(); i++) { int idx = high[i]; set_prob(idx, 1.0); set_alt(idx, idx); } for (size_t i = 0; i < low.size(); i++) { int idx = low[i]; set_prob(idx, 1.0); set_alt(idx, idx); } } } }
#include "tsl/lib/random/distribution_sampler.h" #include <string.h> #include <memory> #include <vector> #include "tsl/lib/random/simple_philox.h" #include "tsl/platform/macros.h" #include "tsl/platform/test.h" #include "tsl/platform/test_benchmark.h" #include "tsl/platform/types.h" namespace tsl { namespace random { class DistributionSamplerTest : public ::testing::Test { protected: float TestWeights(const std::vector<float>& weights, int trials_per_bin) { int iters = weights.size() * trials_per_bin; std::unique_ptr<float[]> counts(new float[weights.size()]); memset(counts.get(), 0, sizeof(float) * weights.size()); DistributionSampler sampler(weights); PhiloxRandom philox(testing::RandomSeed(), 17); SimplePhilox random(&philox); for (int i = 0; i < iters; i++) { int r = sampler.Sample(&random); EXPECT_LT(r, weights.size()); EXPECT_GE(r, 0); counts[r] += 1.0; } float chi2 = 0.0; for (size_t i = 0; i < weights.size(); i++) { counts[i] /= iters; float err = (counts[i] - weights[i]); chi2 += (err * err) / weights[i]; } return chi2; } void TestDistribution(float* arr, int n) { std::vector<float> w; w.reserve(n); for (int i = 0; i < n; i++) { w.push_back(arr[i]); } float var = TestWeights(w, 1000); if (var < 0.001) return; var = TestWeights(w, 100000); if (var < 0.001) return; EXPECT_TRUE(false) << "Chi2 is " << var << " in " << n * 100000 << "iterations"; } }; TEST_F(DistributionSamplerTest, KnownDistribution) { float kEven2[] = {0.5, 0.5}; float kEven3[] = {0.33333333, 0.33333333, 0.33333333}; float kEven4[] = {0.25, 0.25, 0.25, 0.25}; float kDist1[] = {0.8, 0.15, 0.05}; TestDistribution(kEven2, TF_ARRAYSIZE(kEven2)); TestDistribution(kEven3, TF_ARRAYSIZE(kEven3)); TestDistribution(kEven4, TF_ARRAYSIZE(kEven4)); TestDistribution(kDist1, TF_ARRAYSIZE(kDist1)); } static void BM_DistributionSampler(::testing::benchmark::State& state) { const int n = state.range(0); PhiloxRandom philox(173, 371); SimplePhilox rand(&philox); std::vector<float> weights(n, 0); for (int i = 0; i < n; i++) { weights[i] = rand.Uniform(100); } DistributionSampler picker(weights); int r = 0; for (auto s : state) { r |= picker.Sample(&rand); } CHECK_NE(r, kint32max); } BENCHMARK(BM_DistributionSampler)->Arg(10)->Arg(100)->Arg(1000); } }
2,312
cpp
tensorflow/tensorflow
simple_philox
third_party/xla/third_party/tsl/tsl/lib/random/simple_philox.cc
third_party/xla/third_party/tsl/tsl/lib/random/simple_philox_test.cc
#ifndef TENSORFLOW_TSL_LIB_RANDOM_SIMPLE_PHILOX_H_ #define TENSORFLOW_TSL_LIB_RANDOM_SIMPLE_PHILOX_H_ #include <math.h> #include <string.h> #include <algorithm> #include "tsl/lib/random/philox_random.h" #include "tsl/lib/random/random_distributions.h" namespace tsl { namespace random { class SimplePhilox { public: PHILOX_DEVICE_INLINE explicit SimplePhilox(PhiloxRandom* gen) : single_(gen) {} PHILOX_DEVICE_INLINE uint32 Rand32() { return single_(); } PHILOX_DEVICE_INLINE uint64 Rand64() { const uint32 lo = single_(), hi = single_(); return lo | static_cast<uint64>(hi) << 32; } PHILOX_DEVICE_INLINE float RandFloat() { return Uint32ToFloat(single_()); } PHILOX_DEVICE_INLINE double RandDouble() { const uint32 x0 = single_(), x1 = single_(); return Uint64ToDouble(x0, x1); } uint32 Uniform(uint32 n); uint64 Uniform64(uint64 n); bool OneIn(uint32 n) { return Uniform(n) == 0; } uint32 Skewed(int max_log); private: SingleSampleAdapter<PhiloxRandom> single_; }; } } #endif #include "tsl/lib/random/simple_philox.h" #include "tsl/lib/random/exact_uniform_int.h" #include "tsl/platform/logging.h" namespace tsl { namespace random { uint32 SimplePhilox::Uniform(uint32 n) { return ExactUniformInt<uint32>(n, [this]() { return Rand32(); }); } uint64 SimplePhilox::Uniform64(uint64 n) { return ExactUniformInt<uint64>(n, [this]() { return Rand64(); }); } uint32 SimplePhilox::Skewed(int max_log) { CHECK(0 <= max_log && max_log <= 32); const int shift = Rand32() % (max_log + 1); const uint32 mask = shift == 32 ? ~static_cast<uint32>(0) : (1 << shift) - 1; return Rand32() & mask; } } }
#include "tsl/lib/random/simple_philox.h" #include <set> #include <string> #include "tsl/platform/logging.h" #include "tsl/platform/test.h" #include "tsl/platform/types.h" namespace tsl { namespace random { namespace { TEST(SimplePhiloxTest, FloatTest) { PhiloxRandom philox(7, 7); SimplePhilox gen(&philox); static const int kIters = 1000000; for (int i = 0; i < kIters; ++i) { float f = gen.RandFloat(); EXPECT_LE(0.0f, f); EXPECT_GT(1.0f, f); } for (int i = 0; i < kIters; ++i) { double d = gen.RandDouble(); EXPECT_LE(0.0, d); EXPECT_GT(1.0, d); } } static void DifferenceTest(const char *names, SimplePhilox *gen1, SimplePhilox *gen2) { static const int kIters = 100; bool different = false; for (int i = 0; i < kIters; ++i) { if (gen1->Rand32() != gen2->Rand32()) { different = true; break; } } CHECK(different) << "different seeds but same output!"; } TEST(SimplePhiloxTest, DifferenceTest) { PhiloxRandom philox1(1, 1), philox2(17, 17); SimplePhilox gen1(&philox1), gen2(&philox2); DifferenceTest("SimplePhilox: different seeds", &gen1, &gen2); } TEST(SimplePhiloxTest, DifferenceTestCloseSeeds) { PhiloxRandom philox1(1, 1), philox2(2, 1); SimplePhilox gen1(&philox1), gen2(&philox2); DifferenceTest("SimplePhilox: close seeds", &gen1, &gen2); } TEST(SimplePhiloxTest, Regression_CloseSeedsAreDifferent) { const int kCount = 1000; PhiloxRandom philox1(0, 1), philox2(1, 1); SimplePhilox gen1(&philox1), gen2(&philox2); std::set<uint32> first; std::set<uint32> all; for (int i = 0; i < kCount; ++i) { uint32 v = gen1.Rand32(); first.insert(v); all.insert(v); all.insert(gen2.Rand32()); } EXPECT_EQ(kCount, first.size()); EXPECT_EQ(2 * kCount, all.size()); } TEST(SimplePhiloxTest, TestUniform) { PhiloxRandom philox(17, 17); SimplePhilox gen(&philox); uint32 range = 3 * (1L << 29); uint32 threshold = 1L << 30; size_t count = 0; static const int kTrials = 100000; for (int i = 0; i < kTrials; ++i) { uint32 rnd = gen.Uniform(range); if (rnd < threshold) { ++count; } } EXPECT_LT(fabs((threshold + 0.0) / range - (count + 0.0) / kTrials), 0.005); } TEST(SimplePhiloxTest, TestUniform64) { PhiloxRandom philox(17, 17); SimplePhilox gen(&philox); uint64 range = 3 * (1LL << 59); uint64 threshold = 1LL << 60; size_t count = 0; static const int kTrials = 100000; for (int i = 0; i < kTrials; ++i) { uint64 rnd = gen.Uniform64(range); if (rnd < threshold) { ++count; } } EXPECT_LT(fabs((threshold + 0.0) / range - (count + 0.0) / kTrials), 0.005); } } } }
2,313
cpp
tensorflow/tensorflow
proto_serialization
third_party/xla/xla/tsl/lib/strings/proto_serialization.cc
tensorflow/core/lib/strings/proto_serialization_test.cc
#ifndef TENSORFLOW_TSL_LIB_STRINGS_PROTO_SERIALIZATION_H_ #define TENSORFLOW_TSL_LIB_STRINGS_PROTO_SERIALIZATION_H_ #include "tsl/platform/protobuf.h" namespace tsl { bool SerializeToStringDeterministic(const protobuf::MessageLite& msg, string* result); bool SerializeToBufferDeterministic(const protobuf::MessageLite& msg, char* buffer, size_t size); bool AreSerializedProtosEqual(const protobuf::MessageLite& x, const protobuf::MessageLite& y); uint64 DeterministicProtoHash64(const protobuf::MessageLite& proto); uint64 DeterministicProtoHash64(const protobuf::MessageLite& proto, uint64 seed); } #endif #include "tsl/lib/strings/proto_serialization.h" #include <cstring> #include <memory> #include "absl/memory/memory.h" #include "absl/strings/string_view.h" #include "tsl/lib/gtl/inlined_vector.h" #include "tsl/platform/hash.h" #include "tsl/platform/logging.h" #include "tsl/platform/macros.h" namespace tsl { namespace { class DeterministicSerializer { public: explicit DeterministicSerializer(const protobuf::MessageLite& msg) : DeterministicSerializer(msg, msg.ByteSizeLong()) {} DeterministicSerializer(const protobuf::MessageLite& msg, size_t size) : size_(size) { char* ptr = space_; if (size_ > sizeof(space_)) { ptr = new char[size_]; alloc_.reset(ptr); } bool ok = SerializeToBufferDeterministic(msg, ptr, size_); DCHECK(ok); } size_t size() const { return size_; } const char* data() const { return alloc_ == nullptr ? space_ : alloc_.get(); } private: static constexpr int kInlinedBufferSize = 256; const size_t size_; std::unique_ptr<char[]> alloc_; char space_[kInlinedBufferSize]; }; } bool SerializeToStringDeterministic(const protobuf::MessageLite& msg, string* result) { const size_t size = msg.ByteSizeLong(); DCHECK_LE(size, static_cast<size_t>(INT_MAX)); *result = string(size, '\0'); return SerializeToBufferDeterministic(msg, const_cast<char*>(result->data()), result->size()); } bool SerializeToBufferDeterministic(const protobuf::MessageLite& msg, char* buffer, size_t size) { DCHECK(msg.ByteSizeLong() == size && size <= static_cast<size_t>(INT_MAX)); protobuf::io::ArrayOutputStream array_stream(buffer, size); protobuf::io::CodedOutputStream output_stream(&array_stream); output_stream.SetSerializationDeterministic(true); msg.SerializeWithCachedSizes(&output_stream); return !output_stream.HadError() && size == static_cast<size_t>(output_stream.ByteCount()); } bool AreSerializedProtosEqual(const protobuf::MessageLite& x, const protobuf::MessageLite& y) { const size_t size = x.ByteSizeLong(); if (size != y.ByteSizeLong()) return false; if (size == 0) return true; DeterministicSerializer x_serialized(x, size); DeterministicSerializer y_serialized(y, size); return memcmp(x_serialized.data(), y_serialized.data(), size) == 0; } uint64 DeterministicProtoHash64(const protobuf::MessageLite& proto, uint64 seed) { DeterministicSerializer serialized(proto); return Hash64(serialized.data(), serialized.size(), seed); } uint64 DeterministicProtoHash64(const protobuf::MessageLite& proto) { DeterministicSerializer serialized(proto); return Hash64(serialized.data(), serialized.size()); } }
#include "tensorflow/core/lib/strings/proto_serialization.h" #include <string> #include "absl/memory/memory.h" #include "tensorflow/core/framework/attr_value.pb.h" #include "tensorflow/core/framework/graph.pb.h" #include "tensorflow/core/framework/node_def.pb.h" #include "tensorflow/core/lib/gtl/inlined_vector.h" #include "tensorflow/core/lib/strings/strcat.h" #include "tensorflow/core/platform/test.h" #include "tensorflow/core/platform/test_benchmark.h" namespace tensorflow { namespace { GraphDef MakeGraphDef(int num_nodes) { GraphDef graph_def; for (int i = 0; i < num_nodes; ++i) { NodeDef* node = graph_def.add_node(); node->set_name(strings::StrCat("node", i)); node->set_op(strings::StrCat("op", i % 10)); (*node->mutable_attr())["foo"].set_f(3.14f); (*node->mutable_attr())["bar"].set_s("baz"); } return graph_def; } } static void BM_ProtoSerializationToString(::testing::benchmark::State& state) { int num_nodes = state.range(0); GraphDef graph_def = MakeGraphDef(num_nodes); for (auto i : state) { string serialized; testing::DoNotOptimize( SerializeToStringDeterministic(graph_def, &serialized)); } } BENCHMARK(BM_ProtoSerializationToString)->Range(1, 10000); static void BM_ProtoSerializationToBuffer(::testing::benchmark::State& state) { int num_nodes = state.range(0); GraphDef graph_def = MakeGraphDef(num_nodes); const size_t size = graph_def.ByteSizeLong(); for (auto i : state) { gtl::InlinedVector<char, 1024> buf(size); testing::DoNotOptimize( SerializeToBufferDeterministic(graph_def, buf.data(), size)); } } BENCHMARK(BM_ProtoSerializationToBuffer)->Range(1, 10000); static void BM_DeterministicProtoHash64(::testing::benchmark::State& state) { int num_nodes = state.range(0); GraphDef graph_def = MakeGraphDef(num_nodes); for (auto i : state) { testing::DoNotOptimize(DeterministicProtoHash64(graph_def)); } } BENCHMARK(BM_DeterministicProtoHash64)->Range(1, 10000); static void BM_AreSerializedProtosEqual(::testing::benchmark::State& state) { int num_nodes = state.range(0); GraphDef graph_def_a = MakeGraphDef(num_nodes); GraphDef graph_def_b = MakeGraphDef(num_nodes); graph_def_b.mutable_node(0)->mutable_name()[0] = 'l'; for (auto i : state) { testing::DoNotOptimize(AreSerializedProtosEqual(graph_def_a, graph_def_a)); } } BENCHMARK(BM_AreSerializedProtosEqual)->Range(1, 10000); }
2,314
cpp
tensorflow/tensorflow
histogram
third_party/xla/xla/tsl/lib/histogram/histogram.cc
third_party/xla/xla/tsl/lib/histogram/histogram_test.cc
#ifndef TENSORFLOW_TSL_LIB_HISTOGRAM_HISTOGRAM_H_ #define TENSORFLOW_TSL_LIB_HISTOGRAM_HISTOGRAM_H_ #include <string> #include <vector> #include "tsl/platform/macros.h" #include "tsl/platform/mutex.h" #include "tsl/platform/thread_annotations.h" #include "tsl/platform/types.h" namespace tensorflow { class HistogramProto; } namespace tsl { using tensorflow::HistogramProto; namespace histogram { class Histogram { public: Histogram(); explicit Histogram(absl::Span<const double> custom_bucket_limits); bool DecodeFromProto(const HistogramProto& proto); ~Histogram() {} void Clear(); void Add(double value); void EncodeToProto(HistogramProto* proto, bool preserve_zero_buckets) const; double Median() const; double Percentile(double p) const; double Average() const; double StandardDeviation() const; std::string ToString() const; private: double min_; double max_; double num_; double sum_; double sum_squares_; std::vector<double> custom_bucket_limits_; absl::Span<const double> bucket_limits_; std::vector<double> buckets_; double Remap(double x, double x0, double x1, double y0, double y1) const; Histogram(const Histogram&) = delete; void operator=(const Histogram&) = delete; }; class ThreadSafeHistogram { public: ThreadSafeHistogram() {} explicit ThreadSafeHistogram(absl::Span<const double> custom_bucket_limits) : histogram_(custom_bucket_limits) {} bool DecodeFromProto(const HistogramProto& proto); ~ThreadSafeHistogram() {} void Clear(); void Add(double value); void EncodeToProto(HistogramProto* proto, bool preserve_zero_buckets) const; double Median() const; double Percentile(double p) const; double Average() const; double StandardDeviation() const; std::string ToString() const; private: mutable mutex mu_; Histogram histogram_ TF_GUARDED_BY(mu_); }; } } #endif #include "tsl/lib/histogram/histogram.h" #include <float.h> #include <math.h> #include <vector> #include "tsl/platform/logging.h" #include "tsl/platform/mutex.h" #include "tsl/platform/types.h" #include "tsl/protobuf/histogram.pb.h" namespace tsl { namespace histogram { static std::vector<double>* InitDefaultBucketsInner() { std::vector<double> buckets; std::vector<double> neg_buckets; double v = 1.0e-12; while (v < 1.0e20) { buckets.push_back(v); neg_buckets.push_back(-v); v *= 1.1; } buckets.push_back(DBL_MAX); neg_buckets.push_back(-DBL_MAX); std::reverse(neg_buckets.begin(), neg_buckets.end()); std::vector<double>* result = new std::vector<double>; result->insert(result->end(), neg_buckets.begin(), neg_buckets.end()); result->push_back(0.0); result->insert(result->end(), buckets.begin(), buckets.end()); return result; } static absl::Span<const double> InitDefaultBuckets() { static std::vector<double>* default_bucket_limits = InitDefaultBucketsInner(); return *default_bucket_limits; } Histogram::Histogram() : bucket_limits_(InitDefaultBuckets()) { Clear(); } Histogram::Histogram(absl::Span<const double> custom_bucket_limits) : custom_bucket_limits_(custom_bucket_limits.begin(), custom_bucket_limits.end()), bucket_limits_(custom_bucket_limits_) { #ifndef NDEBUG DCHECK_GT(bucket_limits_.size(), size_t{0}); for (size_t i = 1; i < bucket_limits_.size(); i++) { DCHECK_GT(bucket_limits_[i], bucket_limits_[i - 1]); } #endif Clear(); } bool Histogram::DecodeFromProto(const HistogramProto& proto) { if ((proto.bucket_size() != proto.bucket_limit_size()) || (proto.bucket_size() == 0)) { return false; } min_ = proto.min(); max_ = proto.max(); num_ = proto.num(); sum_ = proto.sum(); sum_squares_ = proto.sum_squares(); custom_bucket_limits_.clear(); custom_bucket_limits_.insert(custom_bucket_limits_.end(), proto.bucket_limit().begin(), proto.bucket_limit().end()); bucket_limits_ = custom_bucket_limits_; buckets_.clear(); buckets_.insert(buckets_.end(), proto.bucket().begin(), proto.bucket().end()); return true; } void Histogram::Clear() { min_ = bucket_limits_[bucket_limits_.size() - 1]; max_ = -DBL_MAX; num_ = 0; sum_ = 0; sum_squares_ = 0; buckets_.resize(bucket_limits_.size()); for (size_t i = 0; i < bucket_limits_.size(); i++) { buckets_[i] = 0; } } void Histogram::Add(double value) { int b = std::upper_bound(bucket_limits_.begin(), bucket_limits_.end(), value) - bucket_limits_.begin(); buckets_[b] += 1.0; if (min_ > value) min_ = value; if (max_ < value) max_ = value; num_++; sum_ += value; sum_squares_ += (value * value); } double Histogram::Median() const { return Percentile(50.0); } double Histogram::Remap(double x, double x0, double x1, double y0, double y1) const { return y0 + (x - x0) / (x1 - x0) * (y1 - y0); } double Histogram::Percentile(double p) const { if (num_ == 0.0) return 0.0; double threshold = num_ * (p / 100.0); double cumsum_prev = 0; for (size_t i = 0; i < buckets_.size(); i++) { double cumsum = cumsum_prev + buckets_[i]; if (cumsum >= threshold) { if (cumsum == cumsum_prev) { continue; } double lhs = (i == 0 || cumsum_prev == 0) ? min_ : bucket_limits_[i - 1]; lhs = std::max(lhs, min_); double rhs = bucket_limits_[i]; rhs = std::min(rhs, max_); double weight = Remap(threshold, cumsum_prev, cumsum, lhs, rhs); return weight; } cumsum_prev = cumsum; } return max_; } double Histogram::Average() const { if (num_ == 0.0) return 0; return sum_ / num_; } double Histogram::StandardDeviation() const { if (num_ == 0.0) return 0; double variance = (sum_squares_ * num_ - sum_ * sum_) / (num_ * num_); return sqrt(variance); } std::string Histogram::ToString() const { std::string r; char buf[200]; snprintf(buf, sizeof(buf), "Count: %.0f Average: %.4f StdDev: %.2f\n", num_, Average(), StandardDeviation()); r.append(buf); snprintf(buf, sizeof(buf), "Min: %.4f Median: %.4f Max: %.4f\n", (num_ == 0.0 ? 0.0 : min_), Median(), max_); r.append(buf); r.append("------------------------------------------------------\n"); const double mult = num_ > 0 ? 100.0 / num_ : 0.0; double sum = 0; for (size_t b = 0; b < buckets_.size(); b++) { if (buckets_[b] <= 0.0) continue; sum += buckets_[b]; snprintf(buf, sizeof(buf), "[ %10.2g, %10.2g ) %7.0f %7.3f%% %7.3f%% ", ((b == 0) ? -DBL_MAX : bucket_limits_[b - 1]), bucket_limits_[b], buckets_[b], mult * buckets_[b], mult * sum); r.append(buf); int marks = static_cast<int>(20 * (buckets_[b] / num_) + 0.5); r.append(marks, '#'); r.push_back('\n'); } return r; } void Histogram::EncodeToProto(HistogramProto* proto, bool preserve_zero_buckets) const { proto->Clear(); proto->set_min(min_); proto->set_max(max_); proto->set_num(num_); proto->set_sum(sum_); proto->set_sum_squares(sum_squares_); for (size_t i = 0; i < buckets_.size();) { double end = bucket_limits_[i]; double count = buckets_[i]; i++; if (!preserve_zero_buckets && count <= 0.0) { while (i < buckets_.size() && buckets_[i] <= 0.0) { end = bucket_limits_[i]; count = buckets_[i]; i++; } } proto->add_bucket_limit(end); proto->add_bucket(count); } if (proto->bucket_size() == 0.0) { proto->add_bucket_limit(DBL_MAX); proto->add_bucket(0.0); } } bool ThreadSafeHistogram::DecodeFromProto(const HistogramProto& proto) { mutex_lock l(mu_); return histogram_.DecodeFromProto(proto); } void ThreadSafeHistogram::Clear() { mutex_lock l(mu_); histogram_.Clear(); } void ThreadSafeHistogram::Add(double value) { mutex_lock l(mu_); histogram_.Add(value); } void ThreadSafeHistogram::EncodeToProto(HistogramProto* proto, bool preserve_zero_buckets) const { mutex_lock l(mu_); histogram_.EncodeToProto(proto, preserve_zero_buckets); } double ThreadSafeHistogram::Median() const { mutex_lock l(mu_); return histogram_.Median(); } double ThreadSafeHistogram::Percentile(double p) const { mutex_lock l(mu_); return histogram_.Percentile(p); } double ThreadSafeHistogram::Average() const { mutex_lock l(mu_); return histogram_.Average(); } double ThreadSafeHistogram::StandardDeviation() const { mutex_lock l(mu_); return histogram_.StandardDeviation(); } std::string ThreadSafeHistogram::ToString() const { mutex_lock l(mu_); return histogram_.ToString(); } } }
#include "tsl/lib/histogram/histogram.h" #include <float.h> #include "tsl/platform/logging.h" #include "tsl/platform/test.h" #include "tsl/protobuf/histogram.pb.h" namespace tsl { namespace histogram { static void Validate(const Histogram& h) { string s1 = h.ToString(); LOG(ERROR) << s1; HistogramProto proto_with_zeroes; h.EncodeToProto(&proto_with_zeroes, true); Histogram h2; EXPECT_TRUE(h2.DecodeFromProto(proto_with_zeroes)); string s2 = h2.ToString(); LOG(ERROR) << s2; EXPECT_EQ(s1, s2); HistogramProto proto_no_zeroes; h.EncodeToProto(&proto_no_zeroes, false); LOG(ERROR) << proto_no_zeroes.DebugString(); Histogram h3; EXPECT_TRUE(h3.DecodeFromProto(proto_no_zeroes)); string s3 = h3.ToString(); LOG(ERROR) << s3; EXPECT_EQ(s1, s3); } TEST(Histogram, Empty) { Histogram h; Validate(h); } TEST(Histogram, SingleValue) { Histogram h; h.Add(-3.0); Validate(h); } TEST(Histogram, CustomBuckets) { Histogram h({-10, -5, 0, 5, 10, 100, 1000, 10000, DBL_MAX}); h.Add(-3.0); h.Add(4.99); h.Add(5.0); h.Add(1000.0); Validate(h); } TEST(Histogram, Median) { Histogram h({0, 10, 100, DBL_MAX}); h.Add(-2); h.Add(-2); h.Add(0); double median = h.Median(); EXPECT_EQ(median, -0.5); } TEST(Histogram, Percentile) { Histogram h({1, 2, 3, 4}); h.Add(-1.0); h.Add(1.5); h.Add(1.5); h.Add(1.5); h.Add(2.5); h.Add(2.5); h.Add(2.5); h.Add(2.5); h.Add(3.5); h.Add(3.9); EXPECT_EQ(h.Percentile(0), -1.0); EXPECT_EQ(h.Percentile(25), 1.5); EXPECT_EQ(h.Percentile(50), 2.25); EXPECT_EQ(h.Percentile(75), 2.875); EXPECT_EQ(h.Percentile(90), 3.45); EXPECT_EQ(h.Percentile(100), 3.9); } TEST(Histogram, Basic) { Histogram h; for (int i = 0; i < 100; i++) { h.Add(i); } for (int i = 1000; i < 100000; i += 1000) { h.Add(i); } Validate(h); } TEST(ThreadSafeHistogram, Basic) { Histogram h; for (int i = 0; i < 100; i++) { h.Add(i); } ThreadSafeHistogram tsh; for (int i = 0; i < 100; i++) { tsh.Add(i); } for (int i = 0; i < 2; ++i) { bool preserve_zero_buckets = (i == 0); HistogramProto h_proto; h.EncodeToProto(&h_proto, preserve_zero_buckets); HistogramProto tsh_proto; tsh.EncodeToProto(&tsh_proto, preserve_zero_buckets); Histogram h2; EXPECT_TRUE(h2.DecodeFromProto(tsh_proto)); ThreadSafeHistogram tsh2; EXPECT_TRUE(tsh2.DecodeFromProto(h_proto)); EXPECT_EQ(h2.ToString(), tsh2.ToString()); } EXPECT_EQ(h.Median(), tsh.Median()); EXPECT_EQ(h.Percentile(40.0), tsh.Percentile(40.0)); EXPECT_EQ(h.Average(), tsh.Average()); EXPECT_EQ(h.StandardDeviation(), tsh.StandardDeviation()); EXPECT_EQ(h.ToString(), tsh.ToString()); } } }
2,315
cpp
tensorflow/tensorflow
crc32c
third_party/xla/third_party/tsl/tsl/lib/hash/crc32c.cc
third_party/xla/third_party/tsl/tsl/lib/hash/crc32c_test.cc
#ifndef TENSORFLOW_TSL_LIB_HASH_CRC32C_H_ #define TENSORFLOW_TSL_LIB_HASH_CRC32C_H_ #include <stddef.h> #include "absl/crc/crc32c.h" #include "absl/strings/string_view.h" #include "tsl/platform/cord.h" #include "tsl/platform/platform.h" #include "tsl/platform/types.h" namespace tsl { namespace crc32c { inline uint32 Extend(uint32 init_crc, const char* buf, size_t size) { return static_cast<uint32>(absl::ExtendCrc32c( static_cast<absl::crc32c_t>(init_crc), absl::string_view(buf, size))); } #if defined(TF_CORD_SUPPORT) extern uint32 Extend(uint32 init_crc, const absl::Cord& cord); #endif inline uint32 Value(const char* data, size_t n) { return Extend(0, data, n); } #if defined(TF_CORD_SUPPORT) inline uint32 Value(const absl::Cord& cord) { return Extend(0, cord); } #endif static const uint32 kMaskDelta = 0xa282ead8ul; inline uint32 Mask(uint32 crc) { return ((crc >> 15) | (crc << 17)) + kMaskDelta; } inline uint32 Unmask(uint32 masked_crc) { uint32 rot = masked_crc - kMaskDelta; return ((rot >> 17) | (rot << 15)); } } } #endif #include "tsl/lib/hash/crc32c.h" #include <stdint.h> #include "absl/strings/cord.h" #include "absl/strings/string_view.h" #include "tsl/platform/types.h" namespace tsl { namespace crc32c { #if defined(TF_CORD_SUPPORT) uint32 Extend(uint32 crc, const absl::Cord &cord) { for (absl::string_view fragment : cord.Chunks()) { crc = Extend(crc, fragment.data(), fragment.size()); } return crc; } #endif } }
#include "tsl/lib/hash/crc32c.h" #include <string> #include "absl/strings/cord.h" #include "tsl/platform/logging.h" #include "tsl/platform/test.h" #include "tsl/platform/test_benchmark.h" #include "tsl/platform/types.h" namespace tsl { namespace crc32c { TEST(CRC, StandardResults) { char buf[32]; memset(buf, 0, sizeof(buf)); ASSERT_EQ(0x8a9136aa, Value(buf, sizeof(buf))); memset(buf, 0xff, sizeof(buf)); ASSERT_EQ(0x62a8ab43, Value(buf, sizeof(buf))); for (int i = 0; i < 32; i++) { buf[i] = i; } ASSERT_EQ(0x46dd794e, Value(buf, sizeof(buf))); for (int i = 0; i < 32; i++) { buf[i] = 31 - i; } ASSERT_EQ(0x113fdb5c, Value(buf, sizeof(buf))); unsigned char data[48] = { 0x01, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x18, 0x28, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; ASSERT_EQ(0xd9963a56, Value(reinterpret_cast<char*>(data), sizeof(data))); ASSERT_EQ(0xdd1b19be, Value(reinterpret_cast<char*>(data), sizeof(data) - 7)); ASSERT_EQ(0x4930c4b1, Value(reinterpret_cast<char*>(data) + 1, sizeof(data) - 4)); } TEST(CRC, Values) { ASSERT_NE(Value("a", 1), Value("foo", 3)); } TEST(CRC, Extend) { ASSERT_EQ(Value("hello world", 11), Extend(Value("hello ", 6), "world", 5)); } TEST(CRC, Mask) { uint32 crc = Value("foo", 3); ASSERT_NE(crc, Mask(crc)); ASSERT_NE(crc, Mask(Mask(crc))); ASSERT_EQ(crc, Unmask(Mask(crc))); ASSERT_EQ(crc, Unmask(Unmask(Mask(Mask(crc))))); } #if defined(PLATFORM_GOOGLE) TEST(CRC, ValuesWithCord) { ASSERT_NE(Value(absl::Cord("a")), Value(absl::Cord("foo"))); } TEST(CRC, ExtendWithCord) { ASSERT_EQ(Value(absl::Cord("hello world")), Extend(Value(absl::Cord("hello ")), absl::Cord("world"))); } #endif static void BM_CRC(::testing::benchmark::State& state) { int len = state.range(0); std::string input(len, 'x'); uint32 h = 0; for (auto s : state) { h = Extend(h, input.data() + 1, len - 1); } state.SetBytesProcessed(state.iterations() * len); VLOG(1) << h; } BENCHMARK(BM_CRC)->Range(1, 256 * 1024); } }
2,316
cpp
tensorflow/tensorflow
bitmap
third_party/xla/xla/tsl/lib/core/bitmap.cc
third_party/xla/xla/tsl/lib/core/bitmap_test.cc
#ifndef TENSORFLOW_TSL_LIB_CORE_BITMAP_H_ #define TENSORFLOW_TSL_LIB_CORE_BITMAP_H_ #include <string> #include "tsl/platform/logging.h" namespace tsl { namespace core { class Bitmap { public: Bitmap(); explicit Bitmap(size_t n); ~Bitmap(); Bitmap(const Bitmap&) = delete; Bitmap& operator=(const Bitmap&) = delete; size_t bits() const; void Reset(size_t n); bool get(size_t i) const; void set(size_t i); void clear(size_t i); size_t FirstUnset(size_t start) const; std::string ToString() const; private: typedef uint32_t Word; static constexpr size_t kBits = 32; static size_t NumWords(size_t n) { return (n + kBits - 1) / kBits; } static Word Mask(size_t i) { return 1ull << i; } size_t nbits_; Word* word_; }; inline Bitmap::Bitmap() : nbits_(0), word_(nullptr) {} inline Bitmap::Bitmap(size_t n) : Bitmap() { Reset(n); } inline Bitmap::~Bitmap() { delete[] word_; } inline size_t Bitmap::bits() const { return nbits_; } inline bool Bitmap::get(size_t i) const { DCHECK_LT(i, nbits_); return word_[i / kBits] & Mask(i % kBits); } inline void Bitmap::set(size_t i) { DCHECK_LT(i, nbits_); word_[i / kBits] |= Mask(i % kBits); } inline void Bitmap::clear(size_t i) { DCHECK_LT(i, nbits_); word_[i / kBits] &= ~Mask(i % kBits); } } } #endif #include "tsl/lib/core/bitmap.h" #include <cstddef> #include <cstdint> #include <cstring> #include <string> #include "absl/numeric/bits.h" namespace tsl { namespace core { void Bitmap::Reset(size_t n) { const size_t num_words = NumWords(n); if (num_words != NumWords(nbits_)) { Word* w = new Word[num_words]; delete[] word_; word_ = w; } memset(word_, 0, sizeof(word_[0]) * num_words); nbits_ = n; } static size_t FindFirstSet(uint32_t w) { return w == 0 ? 0 : absl::countr_zero(w) + 1; } size_t Bitmap::FirstUnset(size_t start) const { if (start >= nbits_) { return nbits_; } size_t mask = (1ull << (start % kBits)) - 1; const size_t nwords = NumWords(nbits_); for (size_t i = start / kBits; i < nwords; i++) { Word word = word_[i] | mask; mask = 0; size_t r = FindFirstSet(~word); if (r) { size_t result = i * kBits + (r - 1); if (result > nbits_) result = nbits_; return result; } } return nbits_; } std::string Bitmap::ToString() const { std::string result; result.resize(bits()); for (size_t i = 0; i < nbits_; i++) { result[i] = get(i) ? '1' : '0'; } return result; } } }
#include "tsl/lib/core/bitmap.h" #include "tsl/lib/random/simple_philox.h" #include "tsl/platform/macros.h" #include "tsl/platform/test.h" namespace tsl { namespace core { namespace { size_t NextSize(size_t n) { return n + ((n < 75) ? 1 : 25); } static void MakeRandomBitmap(random::SimplePhilox* rnd, Bitmap* bitmap) { size_t n = rnd->Uniform(200); bitmap->Reset(n); for (size_t i = 0; i < n; i++) { if (rnd->OneIn(2)) bitmap->set(i); } } TEST(BitmapTest, Basic) { for (size_t n = 0; n < 200; n = NextSize(n)) { Bitmap bits(n); for (size_t i = 0; i < n; i++) { EXPECT_FALSE(bits.get(i)) << n << " " << i << " " << bits.ToString(); bits.set(i); EXPECT_TRUE(bits.get(i)) << n << " " << i << " " << bits.ToString(); bits.clear(i); EXPECT_FALSE(bits.get(i)) << n << " " << i << " " << bits.ToString(); } } } TEST(BitmapTest, ToString) { Bitmap bits(10); bits.set(1); bits.set(3); EXPECT_EQ(bits.ToString(), "0101000000"); } TEST(BitmapTest, FirstUnset) { for (size_t n = 0; n < 200; n = NextSize(n)) { for (size_t p = 0; p <= 100; p++) { for (size_t q = 0; q <= 100; q++) { Bitmap bitmap(n); int one_count = 0; size_t i = 0; while (i < p && i < n) { one_count++; bitmap.set(i); i++; } while (i < n) { i++; for (size_t j = 0; j < q && i < n; j++, i++) { one_count++; bitmap.set(i); } } int seen = 0; size_t pos = 0; while (true) { pos = bitmap.FirstUnset(pos); if (pos == n) break; ASSERT_FALSE(bitmap.get(pos)) << pos << " " << bitmap.ToString(); seen++; pos++; } EXPECT_EQ(seen, n - one_count) << " " << bitmap.ToString(); } } } } TEST(BitmapTest, FirstUnsetRandom) { random::PhiloxRandom philox(301, 17); random::SimplePhilox rnd(&philox); for (int iter = 0; iter < 10000; iter++) { Bitmap bitmap; MakeRandomBitmap(&rnd, &bitmap); size_t zero_bits = 0; for (size_t i = 0; i < bitmap.bits(); i++) { if (!bitmap.get(i)) zero_bits++; } int seen = 0; size_t pos = 0; while (true) { pos = bitmap.FirstUnset(pos); if (pos == bitmap.bits()) break; ASSERT_FALSE(bitmap.get(pos)) << pos << " " << bitmap.ToString(); seen++; pos++; } EXPECT_EQ(seen, zero_bits) << " " << bitmap.ToString(); } } } } }
2,317
cpp
tensorflow/tensorflow
random_inputstream
third_party/xla/third_party/tsl/tsl/lib/io/random_inputstream.cc
third_party/xla/third_party/tsl/tsl/lib/io/random_inputstream_test.cc
#ifndef TENSORFLOW_TSL_LIB_IO_RANDOM_INPUTSTREAM_H_ #define TENSORFLOW_TSL_LIB_IO_RANDOM_INPUTSTREAM_H_ #include "tsl/lib/io/inputstream_interface.h" #include "tsl/platform/cord.h" #include "tsl/platform/file_system.h" namespace tsl { namespace io { class RandomAccessInputStream : public InputStreamInterface { public: RandomAccessInputStream(RandomAccessFile* file, bool owns_file = false); ~RandomAccessInputStream() override; absl::Status ReadNBytes(int64_t bytes_to_read, tstring* result) override; #if defined(TF_CORD_SUPPORT) absl::Status ReadNBytes(int64_t bytes_to_read, absl::Cord* result) override; #endif absl::Status SkipNBytes(int64_t bytes_to_skip) override; int64_t Tell() const override; absl::Status Seek(int64_t position) { pos_ = position; return absl::OkStatus(); } absl::Status Reset() override { return Seek(0); } private: RandomAccessFile* file_; int64_t pos_ = 0; bool owns_file_ = false; }; } } #endif #include "tsl/lib/io/random_inputstream.h" #include <memory> namespace tsl { namespace io { RandomAccessInputStream::RandomAccessInputStream(RandomAccessFile* file, bool owns_file) : file_(file), owns_file_(owns_file) {} RandomAccessInputStream::~RandomAccessInputStream() { if (owns_file_) { delete file_; } } absl::Status RandomAccessInputStream::ReadNBytes(int64_t bytes_to_read, tstring* result) { if (bytes_to_read < 0) { return errors::InvalidArgument("Cannot read negative number of bytes"); } result->clear(); result->resize_uninitialized(bytes_to_read); char* result_buffer = &(*result)[0]; StringPiece data; absl::Status s = file_->Read(pos_, bytes_to_read, &data, result_buffer); if (data.data() != result_buffer) { memmove(result_buffer, data.data(), data.size()); } result->resize(data.size()); if (s.ok() || errors::IsOutOfRange(s)) { pos_ += data.size(); } return s; } #if defined(TF_CORD_SUPPORT) absl::Status RandomAccessInputStream::ReadNBytes(int64_t bytes_to_read, absl::Cord* result) { if (bytes_to_read < 0) { return errors::InvalidArgument("Cannot read negative number of bytes"); } int64_t current_size = result->size(); absl::Status s = file_->Read(pos_, bytes_to_read, result); if (s.ok() || errors::IsOutOfRange(s)) { pos_ += result->size() - current_size; } return s; } #endif static constexpr int64_t kMaxSkipSize = 8 * 1024 * 1024; absl::Status RandomAccessInputStream::SkipNBytes(int64_t bytes_to_skip) { if (bytes_to_skip < 0) { return errors::InvalidArgument("Can't skip a negative number of bytes"); } std::unique_ptr<char[]> scratch(new char[kMaxSkipSize]); if (bytes_to_skip > 0) { StringPiece data; absl::Status s = file_->Read(pos_ + bytes_to_skip - 1, 1, &data, scratch.get()); if ((s.ok() || errors::IsOutOfRange(s)) && data.size() == 1) { pos_ += bytes_to_skip; return absl::OkStatus(); } } while (bytes_to_skip > 0) { int64_t bytes_to_read = std::min<int64_t>(kMaxSkipSize, bytes_to_skip); StringPiece data; absl::Status s = file_->Read(pos_, bytes_to_read, &data, scratch.get()); if (s.ok() || errors::IsOutOfRange(s)) { pos_ += data.size(); } else { return s; } if (data.size() < static_cast<size_t>(bytes_to_read)) { return errors::OutOfRange("reached end of file"); } bytes_to_skip -= bytes_to_read; } return absl::OkStatus(); } int64_t RandomAccessInputStream::Tell() const { return pos_; } } }
#include "tsl/lib/io/random_inputstream.h" #include "tsl/lib/core/status_test_util.h" #include "tsl/platform/env.h" #include "tsl/platform/test.h" namespace tsl { namespace io { namespace { TEST(RandomInputStream, ReadNBytes) { Env* env = Env::Default(); string fname = testing::TmpDir() + "/random_inputbuffer_test"; TF_ASSERT_OK(WriteStringToFile(env, fname, "0123456789")); std::unique_ptr<RandomAccessFile> file; TF_ASSERT_OK(env->NewRandomAccessFile(fname, &file)); tstring read; RandomAccessInputStream in(file.get()); TF_ASSERT_OK(in.ReadNBytes(3, &read)); EXPECT_EQ(read, "012"); EXPECT_EQ(3, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(0, &read)); EXPECT_EQ(read, ""); EXPECT_EQ(3, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(5, &read)); EXPECT_EQ(read, "34567"); EXPECT_EQ(8, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(0, &read)); EXPECT_EQ(read, ""); EXPECT_EQ(8, in.Tell()); EXPECT_TRUE(errors::IsOutOfRange(in.ReadNBytes(20, &read))); EXPECT_EQ(read, "89"); EXPECT_EQ(10, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(0, &read)); EXPECT_EQ(read, ""); EXPECT_EQ(10, in.Tell()); } #if defined(TF_CORD_SUPPORT) TEST(RandomInputStream, ReadNBytesWithCords) { Env* env = Env::Default(); string fname = testing::TmpDir() + "/random_inputbuffer_test"; TF_ASSERT_OK(WriteStringToFile(env, fname, "0123456789")); std::unique_ptr<RandomAccessFile> file; TF_ASSERT_OK(env->NewRandomAccessFile(fname, &file)); absl::Cord read; RandomAccessInputStream in(file.get()); TF_ASSERT_OK(in.ReadNBytes(3, &read)); EXPECT_EQ(read, "012"); EXPECT_EQ(3, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(0, &read)); EXPECT_EQ(read, "012"); EXPECT_EQ(3, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(5, &read)); EXPECT_EQ(read, "01234567"); EXPECT_EQ(8, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(0, &read)); EXPECT_EQ(read, "01234567"); EXPECT_EQ(8, in.Tell()); EXPECT_TRUE(errors::IsOutOfRange(in.ReadNBytes(20, &read))); EXPECT_EQ(read, "0123456789"); EXPECT_EQ(10, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(0, &read)); EXPECT_EQ(read, "0123456789"); EXPECT_EQ(10, in.Tell()); } #endif TEST(RandomInputStream, SkipNBytes) { Env* env = Env::Default(); string fname = testing::TmpDir() + "/random_inputbuffer_test"; TF_ASSERT_OK(WriteStringToFile(env, fname, "0123456789")); std::unique_ptr<RandomAccessFile> file; TF_ASSERT_OK(env->NewRandomAccessFile(fname, &file)); tstring read; RandomAccessInputStream in(file.get()); TF_ASSERT_OK(in.SkipNBytes(3)); EXPECT_EQ(3, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(0, &read)); EXPECT_EQ(read, ""); EXPECT_EQ(3, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(4, &read)); EXPECT_EQ(read, "3456"); EXPECT_EQ(7, in.Tell()); TF_ASSERT_OK(in.SkipNBytes(0)); EXPECT_EQ(7, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(2, &read)); EXPECT_EQ(read, "78"); EXPECT_EQ(9, in.Tell()); EXPECT_TRUE(errors::IsOutOfRange(in.SkipNBytes(20))); EXPECT_EQ(10, in.Tell()); EXPECT_TRUE(errors::IsOutOfRange(in.ReadNBytes(5, &read))); EXPECT_EQ(read, ""); EXPECT_EQ(10, in.Tell()); } TEST(RandomInputStream, Seek) { Env* env = Env::Default(); string fname = testing::TmpDir() + "/random_inputbuffer_seek_test"; TF_ASSERT_OK(WriteStringToFile(env, fname, "0123456789")); std::unique_ptr<RandomAccessFile> file; TF_ASSERT_OK(env->NewRandomAccessFile(fname, &file)); tstring read; RandomAccessInputStream in(file.get()); TF_ASSERT_OK(in.Seek(3)); EXPECT_EQ(3, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(4, &read)); EXPECT_EQ(read, "3456"); EXPECT_EQ(7, in.Tell()); TF_ASSERT_OK(in.Seek(1)); TF_ASSERT_OK(in.ReadNBytes(4, &read)); EXPECT_EQ(read, "1234"); EXPECT_EQ(5, in.Tell()); } } } }
2,318
cpp
tensorflow/tensorflow
buffered_inputstream
third_party/xla/third_party/tsl/tsl/lib/io/buffered_inputstream.cc
third_party/xla/third_party/tsl/tsl/lib/io/buffered_inputstream_test.cc
#ifndef TENSORFLOW_TSL_LIB_IO_BUFFERED_INPUTSTREAM_H_ #define TENSORFLOW_TSL_LIB_IO_BUFFERED_INPUTSTREAM_H_ #include <string> #include "tsl/lib/io/inputstream_interface.h" #include "tsl/platform/file_system.h" namespace tsl { namespace io { class BufferedInputStream : public InputStreamInterface { public: BufferedInputStream(InputStreamInterface* input_stream, size_t buffer_bytes, bool owns_input_stream = false); BufferedInputStream(RandomAccessFile* file, size_t buffer_bytes); ~BufferedInputStream() override; absl::Status ReadNBytes(int64_t bytes_to_read, tstring* result) override; absl::Status SkipNBytes(int64_t bytes_to_skip) override; int64_t Tell() const override; absl::Status Seek(int64_t position); absl::Status ReadLine(std::string* result); absl::Status ReadLine(tstring* result); std::string ReadLineAsString(); absl::Status SkipLine(); template <typename T> absl::Status ReadAll(T* result); absl::Status Reset() override; private: absl::Status FillBuffer(); template <typename StringType> absl::Status ReadLineHelper(StringType* result, bool include_eol); InputStreamInterface* input_stream_; size_t size_; tstring buf_; size_t pos_ = 0; size_t limit_ = 0; bool owns_input_stream_ = false; absl::Status file_status_ = absl::OkStatus(); BufferedInputStream(const BufferedInputStream&) = delete; void operator=(const BufferedInputStream&) = delete; }; #ifndef SWIG extern template Status BufferedInputStream::ReadAll<std::string>( std::string* result); extern template Status BufferedInputStream::ReadAll<tstring>(tstring* result); #endif } } #endif #include "tsl/lib/io/buffered_inputstream.h" #include "absl/status/status.h" #include "tsl/lib/io/random_inputstream.h" namespace tsl { namespace io { BufferedInputStream::BufferedInputStream(InputStreamInterface* input_stream, size_t buffer_bytes, bool owns_input_stream) : input_stream_(input_stream), size_(buffer_bytes), owns_input_stream_(owns_input_stream) { buf_.reserve(size_); } BufferedInputStream::BufferedInputStream(RandomAccessFile* file, size_t buffer_bytes) : BufferedInputStream(new RandomAccessInputStream(file), buffer_bytes, true) {} BufferedInputStream::~BufferedInputStream() { if (owns_input_stream_) { delete input_stream_; } } absl::Status BufferedInputStream::FillBuffer() { if (!file_status_.ok()) { pos_ = 0; limit_ = 0; return file_status_; } absl::Status s = input_stream_->ReadNBytes(size_, &buf_); pos_ = 0; limit_ = buf_.size(); if (!s.ok()) { file_status_ = s; } return s; } template <typename StringType> absl::Status BufferedInputStream::ReadLineHelper(StringType* result, bool include_eol) { result->clear(); absl::Status s; size_t start_pos = pos_; while (true) { if (pos_ == limit_) { result->append(buf_.data() + start_pos, pos_ - start_pos); s = FillBuffer(); if (limit_ == 0) { break; } start_pos = pos_; } char c = buf_[pos_]; if (c == '\n') { result->append(buf_.data() + start_pos, pos_ - start_pos); if (include_eol) { result->append(1, c); } pos_++; return absl::OkStatus(); } if (c == '\r') { result->append(buf_.data() + start_pos, pos_ - start_pos); start_pos = pos_ + 1; } pos_++; } if (absl::IsOutOfRange(s) && !result->empty()) { return absl::OkStatus(); } return s; } absl::Status BufferedInputStream::ReadNBytes(int64_t bytes_to_read, tstring* result) { if (bytes_to_read < 0) { return errors::InvalidArgument("Can't read a negative number of bytes: ", bytes_to_read); } result->clear(); if (pos_ == limit_ && !file_status_.ok() && bytes_to_read > 0) { return file_status_; } result->reserve(bytes_to_read); absl::Status s; while (result->size() < static_cast<size_t>(bytes_to_read)) { if (pos_ == limit_) { s = FillBuffer(); if (limit_ == 0) { DCHECK(!s.ok()); file_status_ = s; break; } } const int64_t bytes_to_copy = std::min<int64_t>(limit_ - pos_, bytes_to_read - result->size()); result->insert(result->size(), buf_, pos_, bytes_to_copy); pos_ += bytes_to_copy; } if (absl::IsOutOfRange(s) && (result->size() == static_cast<size_t>(bytes_to_read))) { return absl::OkStatus(); } return s; } absl::Status BufferedInputStream::SkipNBytes(int64_t bytes_to_skip) { if (bytes_to_skip < 0) { return errors::InvalidArgument("Can only skip forward, not ", bytes_to_skip); } if (pos_ + bytes_to_skip < limit_) { pos_ += bytes_to_skip; } else { absl::Status s = input_stream_->SkipNBytes(bytes_to_skip - (limit_ - pos_)); pos_ = 0; limit_ = 0; if (absl::IsOutOfRange(s)) { file_status_ = s; } return s; } return absl::OkStatus(); } int64_t BufferedInputStream::Tell() const { return input_stream_->Tell() - (limit_ - pos_); } absl::Status BufferedInputStream::Seek(int64_t position) { if (position < 0) { return errors::InvalidArgument("Seeking to a negative position: ", position); } const int64_t buf_lower_limit = input_stream_->Tell() - limit_; if (position < buf_lower_limit) { TF_RETURN_IF_ERROR(Reset()); return SkipNBytes(position); } if (position < Tell()) { pos_ -= Tell() - position; return absl::OkStatus(); } return SkipNBytes(position - Tell()); } template <typename T> absl::Status BufferedInputStream::ReadAll(T* result) { result->clear(); absl::Status status; while (status.ok()) { status = FillBuffer(); if (limit_ == 0) { break; } result->append(buf_); pos_ = limit_; } if (absl::IsOutOfRange(status)) { file_status_ = status; return absl::OkStatus(); } return status; } template Status BufferedInputStream::ReadAll<std::string>(std::string* result); template Status BufferedInputStream::ReadAll<tstring>(tstring* result); absl::Status BufferedInputStream::Reset() { TF_RETURN_IF_ERROR(input_stream_->Reset()); pos_ = 0; limit_ = 0; file_status_ = absl::OkStatus(); return absl::OkStatus(); } absl::Status BufferedInputStream::ReadLine(std::string* result) { return ReadLineHelper(result, false); } absl::Status BufferedInputStream::ReadLine(tstring* result) { return ReadLineHelper(result, false); } std::string BufferedInputStream::ReadLineAsString() { std::string result; ReadLineHelper(&result, true).IgnoreError(); return result; } absl::Status BufferedInputStream::SkipLine() { absl::Status s; bool skipped = false; while (true) { if (pos_ == limit_) { s = FillBuffer(); if (limit_ == 0) { break; } } char c = buf_[pos_++]; skipped = true; if (c == '\n') { return absl::OkStatus(); } } if (absl::IsOutOfRange(s) && skipped) { return absl::OkStatus(); } return s; } } }
#include "tsl/lib/io/buffered_inputstream.h" #include "tsl/lib/core/status_test_util.h" #include "tsl/lib/io/random_inputstream.h" #include "tsl/platform/env.h" #include "tsl/platform/test.h" #include "tsl/platform/test_benchmark.h" namespace tsl { namespace io { namespace { static std::vector<int> BufferSizes() { return {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 65536}; } class ReadOnceInputStream : public InputStreamInterface { public: ReadOnceInputStream() : start_(true) {} virtual absl::Status ReadNBytes(int64_t bytes_to_read, tstring* result) { if (bytes_to_read < 11) { return errors::InvalidArgument("Not reading all bytes: ", bytes_to_read); } if (start_) { *result = "0123456789"; start_ = false; return errors::OutOfRange("Out of range."); } return errors::InvalidArgument( "Redudant call to ReadNBytes after an OutOfRange error."); } int64_t Tell() const override { return start_ ? 0 : 10; } absl::Status Reset() override { start_ = true; return absl::OkStatus(); } private: bool start_; }; TEST(BufferedInputStream, ReadLine_Empty) { Env* env = Env::Default(); string fname; ASSERT_TRUE(env->LocalTempFilename(&fname)); TF_ASSERT_OK(WriteStringToFile(env, fname, "")); std::unique_ptr<RandomAccessFile> file; TF_ASSERT_OK(env->NewRandomAccessFile(fname, &file)); for (auto buf_size : BufferSizes()) { std::unique_ptr<RandomAccessInputStream> input_stream( new RandomAccessInputStream(file.get())); BufferedInputStream in(input_stream.get(), buf_size); string line; EXPECT_TRUE(errors::IsOutOfRange(in.ReadLine(&line))); } } TEST(BufferedInputStream, ReadLine1) { Env* env = Env::Default(); string fname; ASSERT_TRUE(env->LocalTempFilename(&fname)); TF_ASSERT_OK( WriteStringToFile(env, fname, "line one\nline two\nline three\n")); std::unique_ptr<RandomAccessFile> file; TF_ASSERT_OK(env->NewRandomAccessFile(fname, &file)); for (auto buf_size : BufferSizes()) { std::unique_ptr<RandomAccessInputStream> input_stream( new RandomAccessInputStream(file.get())); BufferedInputStream in(input_stream.get(), buf_size); string line; TF_ASSERT_OK(in.ReadLine(&line)); EXPECT_EQ(line, "line one"); TF_ASSERT_OK(in.ReadLine(&line)); EXPECT_EQ(line, "line two"); TF_ASSERT_OK(in.ReadLine(&line)); EXPECT_EQ(line, "line three"); EXPECT_TRUE(errors::IsOutOfRange(in.ReadLine(&line))); EXPECT_TRUE(errors::IsOutOfRange(in.ReadLine(&line))); } } TEST(BufferedInputStream, ReadLine_NoTrailingNewLine) { Env* env = Env::Default(); string fname; ASSERT_TRUE(env->LocalTempFilename(&fname)); TF_ASSERT_OK(WriteStringToFile(env, fname, "line one\nline two\nline three")); std::unique_ptr<RandomAccessFile> file; TF_ASSERT_OK(env->NewRandomAccessFile(fname, &file)); for (auto buf_size : BufferSizes()) { std::unique_ptr<RandomAccessInputStream> input_stream( new RandomAccessInputStream(file.get())); BufferedInputStream in(input_stream.get(), buf_size); string line; TF_ASSERT_OK(in.ReadLine(&line)); EXPECT_EQ(line, "line one"); TF_ASSERT_OK(in.ReadLine(&line)); EXPECT_EQ(line, "line two"); TF_ASSERT_OK(in.ReadLine(&line)); EXPECT_EQ(line, "line three"); EXPECT_TRUE(errors::IsOutOfRange(in.ReadLine(&line))); EXPECT_TRUE(errors::IsOutOfRange(in.ReadLine(&line))); } } TEST(BufferedInputStream, ReadLine_EmptyLines) { Env* env = Env::Default(); string fname; ASSERT_TRUE(env->LocalTempFilename(&fname)); TF_ASSERT_OK( WriteStringToFile(env, fname, "line one\n\n\nline two\nline three")); std::unique_ptr<RandomAccessFile> file; TF_ASSERT_OK(env->NewRandomAccessFile(fname, &file)); for (auto buf_size : BufferSizes()) { std::unique_ptr<RandomAccessInputStream> input_stream( new RandomAccessInputStream(file.get())); BufferedInputStream in(input_stream.get(), buf_size); string line; TF_ASSERT_OK(in.ReadLine(&line)); EXPECT_EQ(line, "line one"); TF_ASSERT_OK(in.ReadLine(&line)); EXPECT_EQ(line, ""); TF_ASSERT_OK(in.ReadLine(&line)); EXPECT_EQ(line, ""); TF_ASSERT_OK(in.ReadLine(&line)); EXPECT_EQ(line, "line two"); TF_ASSERT_OK(in.ReadLine(&line)); EXPECT_EQ(line, "line three"); EXPECT_TRUE(errors::IsOutOfRange(in.ReadLine(&line))); EXPECT_TRUE(errors::IsOutOfRange(in.ReadLine(&line))); } } TEST(BufferedInputStream, ReadLine_CRLF) { Env* env = Env::Default(); string fname; ASSERT_TRUE(env->LocalTempFilename(&fname)); TF_ASSERT_OK(WriteStringToFile(env, fname, "line one\r\n\r\n\r\nline two\r\nline three")); std::unique_ptr<RandomAccessFile> file; TF_ASSERT_OK(env->NewRandomAccessFile(fname, &file)); for (auto buf_size : BufferSizes()) { std::unique_ptr<RandomAccessInputStream> input_stream( new RandomAccessInputStream(file.get())); BufferedInputStream in(input_stream.get(), buf_size); string line; TF_ASSERT_OK(in.ReadLine(&line)); EXPECT_EQ(line, "line one"); TF_ASSERT_OK(in.ReadLine(&line)); EXPECT_EQ(line, ""); TF_ASSERT_OK(in.ReadLine(&line)); EXPECT_EQ(line, ""); TF_ASSERT_OK(in.ReadLine(&line)); EXPECT_EQ(line, "line two"); TF_ASSERT_OK(in.ReadLine(&line)); EXPECT_EQ(line, "line three"); EXPECT_TRUE(errors::IsOutOfRange(in.ReadLine(&line))); EXPECT_TRUE(errors::IsOutOfRange(in.ReadLine(&line))); } } TEST(BufferedInputStream, SkipLine1) { Env* env = Env::Default(); string fname; ASSERT_TRUE(env->LocalTempFilename(&fname)); TF_ASSERT_OK( WriteStringToFile(env, fname, "line one\nline two\nline three\n")); std::unique_ptr<RandomAccessFile> file; TF_ASSERT_OK(env->NewRandomAccessFile(fname, &file)); for (auto buf_size : BufferSizes()) { std::unique_ptr<RandomAccessInputStream> input_stream( new RandomAccessInputStream(file.get())); BufferedInputStream in(input_stream.get(), buf_size); string line; TF_ASSERT_OK(in.SkipLine()); TF_ASSERT_OK(in.ReadLine(&line)); EXPECT_EQ(line, "line two"); TF_ASSERT_OK(in.SkipLine()); EXPECT_TRUE(errors::IsOutOfRange(in.SkipLine())); EXPECT_TRUE(errors::IsOutOfRange(in.SkipLine())); } } TEST(BufferedInputStream, SkipLine_NoTrailingNewLine) { Env* env = Env::Default(); string fname; ASSERT_TRUE(env->LocalTempFilename(&fname)); TF_ASSERT_OK(WriteStringToFile(env, fname, "line one\nline two\nline three")); std::unique_ptr<RandomAccessFile> file; TF_ASSERT_OK(env->NewRandomAccessFile(fname, &file)); for (auto buf_size : BufferSizes()) { std::unique_ptr<RandomAccessInputStream> input_stream( new RandomAccessInputStream(file.get())); BufferedInputStream in(input_stream.get(), buf_size); string line; TF_ASSERT_OK(in.SkipLine()); TF_ASSERT_OK(in.ReadLine(&line)); EXPECT_EQ(line, "line two"); TF_ASSERT_OK(in.SkipLine()); EXPECT_TRUE(errors::IsOutOfRange(in.SkipLine())); EXPECT_TRUE(errors::IsOutOfRange(in.SkipLine())); } } TEST(BufferedInputStream, SkipLine_EmptyLines) { Env* env = Env::Default(); string fname; ASSERT_TRUE(env->LocalTempFilename(&fname)); TF_ASSERT_OK(WriteStringToFile(env, fname, "line one\n\n\nline two")); std::unique_ptr<RandomAccessFile> file; TF_ASSERT_OK(env->NewRandomAccessFile(fname, &file)); for (auto buf_size : BufferSizes()) { std::unique_ptr<RandomAccessInputStream> input_stream( new RandomAccessInputStream(file.get())); BufferedInputStream in(input_stream.get(), buf_size); string line; TF_ASSERT_OK(in.SkipLine()); TF_ASSERT_OK(in.ReadLine(&line)); EXPECT_EQ(line, ""); TF_ASSERT_OK(in.SkipLine()); TF_ASSERT_OK(in.ReadLine(&line)); EXPECT_EQ(line, "line two"); } } TEST(BufferedInputStream, ReadNBytes) { Env* env = Env::Default(); string fname; ASSERT_TRUE(env->LocalTempFilename(&fname)); TF_ASSERT_OK(WriteStringToFile(env, fname, "0123456789")); std::unique_ptr<RandomAccessFile> file; TF_ASSERT_OK(env->NewRandomAccessFile(fname, &file)); for (auto buf_size : BufferSizes()) { std::unique_ptr<RandomAccessInputStream> input_stream( new RandomAccessInputStream(file.get())); tstring read; BufferedInputStream in(input_stream.get(), buf_size); EXPECT_EQ(0, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(3, &read)); EXPECT_EQ(read, "012"); EXPECT_EQ(3, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(0, &read)); EXPECT_EQ(read, ""); EXPECT_EQ(3, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(4, &read)); EXPECT_EQ(read, "3456"); EXPECT_EQ(7, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(0, &read)); EXPECT_EQ(read, ""); EXPECT_EQ(7, in.Tell()); EXPECT_TRUE(errors::IsOutOfRange(in.ReadNBytes(5, &read))); EXPECT_EQ(read, "789"); EXPECT_EQ(10, in.Tell()); EXPECT_TRUE(errors::IsOutOfRange(in.ReadNBytes(5, &read))); EXPECT_EQ(read, ""); EXPECT_EQ(10, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(0, &read)); EXPECT_EQ(read, ""); EXPECT_EQ(10, in.Tell()); } } TEST(BufferedInputStream, OutOfRangeCache) { for (auto buf_size : BufferSizes()) { if (buf_size < 11) { continue; } ReadOnceInputStream input_stream; tstring read; BufferedInputStream in(&input_stream, buf_size); EXPECT_EQ(0, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(3, &read)); EXPECT_EQ(read, "012"); EXPECT_EQ(3, in.Tell()); TF_ASSERT_OK((in.ReadNBytes(7, &read))); EXPECT_EQ(read, "3456789"); EXPECT_EQ(10, in.Tell()); absl::Status s = in.ReadNBytes(5, &read); EXPECT_EQ(error::OUT_OF_RANGE, s.code()) << s; EXPECT_EQ(read, ""); TF_ASSERT_OK(in.ReadNBytes(0, &read)); EXPECT_EQ(read, ""); } } TEST(BufferedInputStream, SkipNBytes) { Env* env = Env::Default(); string fname; ASSERT_TRUE(env->LocalTempFilename(&fname)); TF_ASSERT_OK(WriteStringToFile(env, fname, "0123456789")); std::unique_ptr<RandomAccessFile> file; TF_ASSERT_OK(env->NewRandomAccessFile(fname, &file)); for (auto buf_size : BufferSizes()) { std::unique_ptr<RandomAccessInputStream> input_stream( new RandomAccessInputStream(file.get())); tstring read; BufferedInputStream in(input_stream.get(), buf_size); EXPECT_EQ(0, in.Tell()); TF_ASSERT_OK(in.SkipNBytes(3)); EXPECT_EQ(3, in.Tell()); TF_ASSERT_OK(in.SkipNBytes(0)); EXPECT_EQ(3, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(2, &read)); EXPECT_EQ(read, "34"); EXPECT_EQ(5, in.Tell()); TF_ASSERT_OK(in.SkipNBytes(0)); EXPECT_EQ(5, in.Tell()); TF_ASSERT_OK(in.SkipNBytes(2)); EXPECT_EQ(7, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(1, &read)); EXPECT_EQ(read, "7"); EXPECT_EQ(8, in.Tell()); EXPECT_TRUE(errors::IsOutOfRange(in.SkipNBytes(5))); EXPECT_EQ(10, in.Tell()); EXPECT_TRUE(errors::IsOutOfRange(in.SkipNBytes(5))); EXPECT_EQ(10, in.Tell()); EXPECT_TRUE(errors::IsOutOfRange(in.ReadNBytes(5, &read))); EXPECT_EQ(read, ""); EXPECT_EQ(10, in.Tell()); } } TEST(BufferedInputStream, ReadNBytesRandomAccessFile) { Env* env = Env::Default(); string fname; ASSERT_TRUE(env->LocalTempFilename(&fname)); TF_ASSERT_OK(WriteStringToFile(env, fname, "0123456789")); std::unique_ptr<RandomAccessFile> file; TF_ASSERT_OK(env->NewRandomAccessFile(fname, &file)); for (auto buf_size : BufferSizes()) { tstring read; BufferedInputStream in(file.get(), buf_size); EXPECT_EQ(0, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(3, &read)); EXPECT_EQ(read, "012"); EXPECT_EQ(3, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(0, &read)); EXPECT_EQ(read, ""); EXPECT_EQ(3, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(4, &read)); EXPECT_EQ(read, "3456"); EXPECT_EQ(7, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(0, &read)); EXPECT_EQ(read, ""); EXPECT_EQ(7, in.Tell()); EXPECT_TRUE(errors::IsOutOfRange(in.ReadNBytes(5, &read))); EXPECT_EQ(read, "789"); EXPECT_EQ(10, in.Tell()); EXPECT_TRUE(errors::IsOutOfRange(in.ReadNBytes(5, &read))); EXPECT_EQ(read, ""); EXPECT_EQ(10, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(0, &read)); EXPECT_EQ(read, ""); EXPECT_EQ(10, in.Tell()); } } TEST(BufferedInputStream, SkipNBytesRandomAccessFile) { Env* env = Env::Default(); string fname; ASSERT_TRUE(env->LocalTempFilename(&fname)); TF_ASSERT_OK(WriteStringToFile(env, fname, "0123456789")); std::unique_ptr<RandomAccessFile> file; TF_ASSERT_OK(env->NewRandomAccessFile(fname, &file)); for (auto buf_size : BufferSizes()) { tstring read; BufferedInputStream in(file.get(), buf_size); EXPECT_EQ(0, in.Tell()); TF_ASSERT_OK(in.SkipNBytes(3)); EXPECT_EQ(3, in.Tell()); TF_ASSERT_OK(in.SkipNBytes(0)); EXPECT_EQ(3, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(2, &read)); EXPECT_EQ(read, "34"); EXPECT_EQ(5, in.Tell()); TF_ASSERT_OK(in.SkipNBytes(0)); EXPECT_EQ(5, in.Tell()); TF_ASSERT_OK(in.SkipNBytes(2)); EXPECT_EQ(7, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(1, &read)); EXPECT_EQ(read, "7"); EXPECT_EQ(8, in.Tell()); EXPECT_TRUE(errors::IsOutOfRange(in.SkipNBytes(5))); EXPECT_EQ(10, in.Tell()); EXPECT_TRUE(errors::IsOutOfRange(in.SkipNBytes(5))); EXPECT_EQ(10, in.Tell()); EXPECT_TRUE(errors::IsOutOfRange(in.ReadNBytes(5, &read))); EXPECT_EQ(read, ""); EXPECT_EQ(10, in.Tell()); } } TEST(BufferedInputStream, Seek) { Env* env = Env::Default(); string fname; ASSERT_TRUE(env->LocalTempFilename(&fname)); TF_ASSERT_OK(WriteStringToFile(env, fname, "0123456789")); std::unique_ptr<RandomAccessFile> file; TF_ASSERT_OK(env->NewRandomAccessFile(fname, &file)); for (auto buf_size : BufferSizes()) { std::unique_ptr<RandomAccessInputStream> input_stream( new RandomAccessInputStream(file.get())); tstring read; BufferedInputStream in(input_stream.get(), buf_size); TF_ASSERT_OK(in.Seek(3)); EXPECT_EQ(3, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(4, &read)); EXPECT_EQ(read, "3456"); EXPECT_EQ(7, in.Tell()); TF_ASSERT_OK(in.Seek(1)); TF_ASSERT_OK(in.ReadNBytes(4, &read)); EXPECT_EQ(read, "1234"); EXPECT_EQ(5, in.Tell()); } } TEST(BufferedInputStream, Seek_NotReset) { Env* env = Env::Default(); string fname; ASSERT_TRUE(env->LocalTempFilename(&fname)); TF_ASSERT_OK(WriteStringToFile(env, fname, "0123456789")); std::unique_ptr<RandomAccessFile> file; TF_ASSERT_OK(env->NewRandomAccessFile(fname, &file)); std::unique_ptr<RandomAccessInputStream> input_stream( new RandomAccessInputStream(file.get())); tstring read; BufferedInputStream in(input_stream.get(), 3); TF_ASSERT_OK(in.ReadNBytes(4, &read)); int before_tell = input_stream.get()->Tell(); EXPECT_EQ(before_tell, 6); TF_ASSERT_OK(in.Seek(3)); int after_tell = input_stream.get()->Tell(); EXPECT_EQ(before_tell, after_tell); } TEST(BufferedInputStream, ReadAll_Empty) { Env* env = Env::Default(); string fname; ASSERT_TRUE(env->LocalTempFilename(&fname)); const string expected = ""; TF_ASSERT_OK(WriteStringToFile(env, fname, expected)); std::unique_ptr<RandomAccessFile> file; TF_ASSERT_OK(env->NewRandomAccessFile(fname, &file)); for (auto buf_size : BufferSizes()) { RandomAccessInputStream input_stream(file.get()); BufferedInputStream in(&input_stream, buf_size); string contents; TF_ASSERT_OK(in.ReadAll(&contents)); EXPECT_EQ(expected, contents); } } TEST(BufferedInputStream, ReadAll_Text) { Env* env = Env::Default(); string fname; ASSERT_TRUE(env->LocalTempFilename(&fname)); const string expected = "line one\nline two\nline three"; TF_ASSERT_OK(WriteStringToFile(env, fname, expected)); std::unique_ptr<RandomAccessFile> file; TF_ASSERT_OK(env->NewRandomAccessFile(fname, &file)); for (auto buf_size : BufferSizes()) { RandomAccessInputStream input_stream(file.get()); BufferedInputStream in(&input_stream, buf_size); string contents; TF_ASSERT_OK(in.ReadAll(&contents)); EXPECT_EQ(expected, contents); } } void BM_BufferedReaderSmallReads(::testing::benchmark::State& state) { const int buff_size = state.range(0); const int file_size = state.range(1); Env* env = Env::Default(); string fname; ASSERT_TRUE(env->LocalTempFilename(&fname)); const string file_elem = "0123456789"; std::unique_ptr<WritableFile> write_file; TF_ASSERT_OK(env->NewWritableFile(fname, &write_file)); for (int i = 0; i < file_size; ++i) { TF_ASSERT_OK(write_file->Append(file_elem)); } TF_ASSERT_OK(write_file->Close()); std::unique_ptr<RandomAccessFile> file; TF_ASSERT_OK(env->NewRandomAccessFile(fname, &file)); tstring result; int itr = 0; for (auto s : state) { BufferedInputStream in(file.get(), buff_size); for (int64_t i = 0; i < 10 * file_size; ++i) { TF_ASSERT_OK(in.ReadNBytes(1, &result)) << "i: " << i << " itr: " << itr << " buff_size: " << buff_size << " file size: " << file_size; } ++itr; } } BENCHMARK(BM_BufferedReaderSmallReads) ->ArgPair(1, 5) ->ArgPair(1, 1024) ->ArgPair(10, 5) ->ArgPair(10, 1024) ->ArgPair(1024, 1024) ->ArgPair(1024 * 1024, 1024) ->ArgPair(1024 * 1024, 1024 * 1024) ->ArgPair(256 * 1024 * 1024, 1024); } } }
2,319
cpp
tensorflow/tensorflow
inputbuffer
third_party/xla/third_party/tsl/tsl/lib/io/inputbuffer.cc
third_party/xla/third_party/tsl/tsl/lib/io/inputbuffer_test.cc
#ifndef TENSORFLOW_TSL_LIB_IO_INPUTBUFFER_H_ #define TENSORFLOW_TSL_LIB_IO_INPUTBUFFER_H_ #include <string> #include "tsl/platform/coding.h" #include "tsl/platform/env.h" #include "tsl/platform/macros.h" #include "tsl/platform/status.h" #include "tsl/platform/types.h" namespace tsl { namespace io { class InputBuffer { public: InputBuffer(RandomAccessFile* file, size_t buffer_bytes); ~InputBuffer(); template <typename T> absl::Status ReadLine(T* result); absl::Status ReadNBytes(int64_t bytes_to_read, std::string* result); absl::Status ReadNBytes(int64_t bytes_to_read, char* result, size_t* bytes_read); absl::Status ReadVarint32(uint32* result); absl::Status ReadVarint64(uint64* result); absl::Status SkipNBytes(int64_t bytes_to_skip); absl::Status Seek(int64_t position); absl::Status Hint(int64_t bytes_to_read); int64_t Tell() const { return file_pos_ - (limit_ - pos_); } RandomAccessFile* file() const { return file_; } private: absl::Status FillBuffer(); absl::Status ReadVarint32Fallback(uint32* result); absl::Status ReadVarint64Fallback(uint64* result); template <typename T> absl::Status ReadVarintFallback(T* result, int max_bytes); RandomAccessFile* file_; int64_t file_pos_; size_t size_; char* buf_; char* pos_; char* limit_; InputBuffer(const InputBuffer&) = delete; void operator=(const InputBuffer&) = delete; }; extern template Status InputBuffer::ReadLine<std::string>(std::string* result); extern template Status InputBuffer::ReadLine<tstring>(tstring* result); inline absl::Status InputBuffer::ReadVarint32(uint32* result) { if (pos_ + core::kMaxVarint32Bytes <= limit_) { const char* offset = core::GetVarint32Ptr(pos_, limit_, result); if (offset == nullptr) return errors::OutOfRange("Parsed past limit."); pos_ = const_cast<char*>(offset); return absl::OkStatus(); } else { return ReadVarint32Fallback(result); } } inline absl::Status InputBuffer::ReadVarint64(uint64* result) { if (pos_ + core::kMaxVarint64Bytes <= limit_) { const char* offset = core::GetVarint64Ptr(pos_, limit_, result); if (offset == nullptr) return errors::OutOfRange("Parsed past limit."); pos_ = const_cast<char*>(offset); return absl::OkStatus(); } else { return ReadVarint64Fallback(result); } } } } #endif #include "tsl/lib/io/inputbuffer.h" #include <algorithm> #include "tsl/platform/errors.h" #include "tsl/platform/logging.h" namespace tsl { namespace io { InputBuffer::InputBuffer(RandomAccessFile* file, size_t buffer_bytes) : file_(file), file_pos_(0), size_(buffer_bytes), buf_(new char[size_]), pos_(buf_), limit_(buf_) {} InputBuffer::~InputBuffer() { delete[] buf_; } absl::Status InputBuffer::FillBuffer() { StringPiece data; absl::Status s = file_->Read(file_pos_, size_, &data, buf_); if (data.data() != buf_) { memmove(buf_, data.data(), data.size()); } pos_ = buf_; limit_ = pos_ + data.size(); file_pos_ += data.size(); return s; } template <typename T> absl::Status InputBuffer::ReadLine(T* result) { result->clear(); absl::Status s; do { size_t buf_remain = limit_ - pos_; char* newline = static_cast<char*>(memchr(pos_, '\n', buf_remain)); if (newline != nullptr) { size_t result_len = newline - pos_; result->append(pos_, result_len); pos_ = newline + 1; if (!result->empty() && result->back() == '\r') { result->resize(result->size() - 1); } return absl::OkStatus(); } if (buf_remain > 0) result->append(pos_, buf_remain); s = FillBuffer(); DCHECK_EQ(pos_, buf_); } while (limit_ != buf_); if (!result->empty() && result->back() == '\r') { result->resize(result->size() - 1); } if (errors::IsOutOfRange(s) && !result->empty()) { return absl::OkStatus(); } return s; } template Status InputBuffer::ReadLine<std::string>(std::string* result); template Status InputBuffer::ReadLine<tstring>(tstring* result); absl::Status InputBuffer::ReadNBytes(int64_t bytes_to_read, std::string* result) { result->clear(); if (bytes_to_read < 0) { return errors::InvalidArgument("Can't read a negative number of bytes: ", bytes_to_read); } result->resize(bytes_to_read); size_t bytes_read = 0; absl::Status status = ReadNBytes(bytes_to_read, &(*result)[0], &bytes_read); if (bytes_read < bytes_to_read) result->resize(bytes_read); return status; } absl::Status InputBuffer::ReadNBytes(int64_t bytes_to_read, char* result, size_t* bytes_read) { if (bytes_to_read < 0) { return errors::InvalidArgument("Can't read a negative number of bytes: ", bytes_to_read); } absl::Status status; *bytes_read = 0; while (*bytes_read < static_cast<size_t>(bytes_to_read)) { if (pos_ == limit_) { status = FillBuffer(); if (limit_ == buf_) { break; } } const int64_t bytes_to_copy = std::min<int64_t>(limit_ - pos_, bytes_to_read - *bytes_read); memcpy(result + *bytes_read, pos_, bytes_to_copy); pos_ += bytes_to_copy; *bytes_read += bytes_to_copy; } if (errors::IsOutOfRange(status) && (*bytes_read == static_cast<size_t>(bytes_to_read))) { return absl::OkStatus(); } return status; } absl::Status InputBuffer::ReadVarint32Fallback(uint32* result) { absl::Status s = ReadVarintFallback(result, core::kMaxVarint32Bytes); if (errors::IsDataLoss(s)) { return errors::DataLoss("Stored data is too large to be a varint32."); } return s; } absl::Status InputBuffer::ReadVarint64Fallback(uint64* result) { absl::Status s = ReadVarintFallback(result, core::kMaxVarint64Bytes); if (errors::IsDataLoss(s)) { return errors::DataLoss("Stored data is too large to be a varint64."); } return s; } template <typename T> absl::Status InputBuffer::ReadVarintFallback(T* result, int max_bytes) { uint8 scratch = 0; auto* p = reinterpret_cast<char*>(&scratch); size_t unused_bytes_read = 0; *result = 0; for (int index = 0; index < max_bytes; index++) { int shift = 7 * index; TF_RETURN_IF_ERROR(ReadNBytes(1, p, &unused_bytes_read)); *result |= (static_cast<T>(scratch) & 127) << shift; if (!(scratch & 128)) return absl::OkStatus(); } return errors::DataLoss("Stored data longer than ", max_bytes, " bytes."); } absl::Status InputBuffer::SkipNBytes(int64_t bytes_to_skip) { if (bytes_to_skip < 0) { return errors::InvalidArgument("Can only skip forward, not ", bytes_to_skip); } int64_t bytes_skipped = 0; absl::Status s; while (bytes_skipped < bytes_to_skip) { if (pos_ == limit_) { s = FillBuffer(); if (limit_ == buf_) { break; } } const int64_t bytes_to_advance = std::min<int64_t>(limit_ - pos_, bytes_to_skip - bytes_skipped); bytes_skipped += bytes_to_advance; pos_ += bytes_to_advance; } if (errors::IsOutOfRange(s) && bytes_skipped == bytes_to_skip) { return absl::OkStatus(); } return s; } absl::Status InputBuffer::Seek(int64_t position) { if (position < 0) { return errors::InvalidArgument("Seeking to a negative position: ", position); } const int64_t bufpos = file_pos_ - static_cast<int64_t>(limit_ - buf_); if (position >= bufpos && position < file_pos_) { pos_ = buf_ + (position - bufpos); DCHECK(pos_ >= buf_ && pos_ < limit_); } else { pos_ = limit_ = buf_; file_pos_ = position; } return absl::OkStatus(); } absl::Status InputBuffer::Hint(int64_t bytes_to_read) { if (bytes_to_read < 0) { return errors::InvalidArgument("Can't read a negative number of bytes: ", bytes_to_read); } if (bytes_to_read > size_) { return absl::OkStatus(); } const int64_t bytes_remain_in_buf = static_cast<int64_t>(limit_ - pos_); if (bytes_to_read <= bytes_remain_in_buf) { return absl::OkStatus(); } memmove(buf_, pos_, bytes_remain_in_buf); pos_ = buf_; limit_ = buf_ + bytes_remain_in_buf; bytes_to_read -= bytes_remain_in_buf; StringPiece data; absl::Status s = file_->Read(file_pos_, bytes_to_read, &data, limit_); if (data.data() != limit_) { memmove(limit_, data.data(), data.size()); } limit_ += data.size(); file_pos_ += data.size(); if (errors::IsOutOfRange(s) && data.size() == bytes_to_read) { return absl::OkStatus(); } else { return s; } } } }
#include "tsl/lib/io/inputbuffer.h" #include <vector> #include "tsl/lib/core/status_test_util.h" #include "tsl/platform/coding.h" #include "tsl/platform/env.h" #include "tsl/platform/errors.h" #include "tsl/platform/logging.h" #include "tsl/platform/status.h" #include "tsl/platform/str_util.h" #include "tsl/platform/strcat.h" #include "tsl/platform/test.h" namespace tsl { namespace { static std::vector<int> BufferSizes() { return {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 65536}; } TEST(InputBuffer, ReadLine_Empty) { Env* env = Env::Default(); string fname; ASSERT_TRUE(env->LocalTempFilename(&fname)); TF_ASSERT_OK(WriteStringToFile(env, fname, "")); for (auto buf_size : BufferSizes()) { std::unique_ptr<RandomAccessFile> file; TF_CHECK_OK(env->NewRandomAccessFile(fname, &file)); string line; io::InputBuffer in(file.get(), buf_size); EXPECT_TRUE(errors::IsOutOfRange(in.ReadLine(&line))); } } TEST(InputBuffer, ReadLine1) { Env* env = Env::Default(); string fname; ASSERT_TRUE(env->LocalTempFilename(&fname)); TF_CHECK_OK( WriteStringToFile(env, fname, "line one\nline two\nline three\n")); for (auto buf_size : BufferSizes()) { std::unique_ptr<RandomAccessFile> file; TF_CHECK_OK(env->NewRandomAccessFile(fname, &file)); string line; io::InputBuffer in(file.get(), buf_size); TF_CHECK_OK(in.ReadLine(&line)); EXPECT_EQ(line, "line one"); TF_CHECK_OK(in.ReadLine(&line)); EXPECT_EQ(line, "line two"); TF_CHECK_OK(in.ReadLine(&line)); EXPECT_EQ(line, "line three"); EXPECT_TRUE(errors::IsOutOfRange(in.ReadLine(&line))); EXPECT_TRUE(errors::IsOutOfRange(in.ReadLine(&line))); } } TEST(InputBuffer, ReadLine_NoTrailingNewLine) { Env* env = Env::Default(); string fname; ASSERT_TRUE(env->LocalTempFilename(&fname)); TF_ASSERT_OK(WriteStringToFile(env, fname, "line one\nline two\nline three")); for (auto buf_size : BufferSizes()) { std::unique_ptr<RandomAccessFile> file; TF_CHECK_OK(env->NewRandomAccessFile(fname, &file)); string line; io::InputBuffer in(file.get(), buf_size); TF_CHECK_OK(in.ReadLine(&line)); EXPECT_EQ(line, "line one"); TF_CHECK_OK(in.ReadLine(&line)); EXPECT_EQ(line, "line two"); TF_CHECK_OK(in.ReadLine(&line)); EXPECT_EQ(line, "line three"); EXPECT_TRUE(errors::IsOutOfRange(in.ReadLine(&line))); EXPECT_TRUE(errors::IsOutOfRange(in.ReadLine(&line))); } } TEST(InputBuffer, ReadLine_EmptyLines) { Env* env = Env::Default(); string fname; ASSERT_TRUE(env->LocalTempFilename(&fname)); TF_CHECK_OK( WriteStringToFile(env, fname, "line one\n\n\nline two\nline three")); for (auto buf_size : BufferSizes()) { std::unique_ptr<RandomAccessFile> file; TF_CHECK_OK(env->NewRandomAccessFile(fname, &file)); string line; io::InputBuffer in(file.get(), buf_size); TF_CHECK_OK(in.ReadLine(&line)); EXPECT_EQ(line, "line one"); TF_CHECK_OK(in.ReadLine(&line)); EXPECT_EQ(line, ""); TF_CHECK_OK(in.ReadLine(&line)); EXPECT_EQ(line, ""); TF_CHECK_OK(in.ReadLine(&line)); EXPECT_EQ(line, "line two"); TF_CHECK_OK(in.ReadLine(&line)); EXPECT_EQ(line, "line three"); EXPECT_TRUE(errors::IsOutOfRange(in.ReadLine(&line))); EXPECT_TRUE(errors::IsOutOfRange(in.ReadLine(&line))); } } TEST(InputBuffer, ReadLine_CRLF) { Env* env = Env::Default(); string fname; ASSERT_TRUE(env->LocalTempFilename(&fname)); TF_ASSERT_OK(WriteStringToFile(env, fname, "line one\r\n\r\n\r\nline two\r\nline three")); for (auto buf_size : BufferSizes()) { std::unique_ptr<RandomAccessFile> file; TF_CHECK_OK(env->NewRandomAccessFile(fname, &file)); string line; io::InputBuffer in(file.get(), buf_size); TF_CHECK_OK(in.ReadLine(&line)); EXPECT_EQ(line, "line one"); TF_CHECK_OK(in.ReadLine(&line)); EXPECT_EQ(line, ""); TF_CHECK_OK(in.ReadLine(&line)); EXPECT_EQ(line, ""); TF_CHECK_OK(in.ReadLine(&line)); EXPECT_EQ(line, "line two"); TF_CHECK_OK(in.ReadLine(&line)); EXPECT_EQ(line, "line three"); EXPECT_TRUE(errors::IsOutOfRange(in.ReadLine(&line))); EXPECT_TRUE(errors::IsOutOfRange(in.ReadLine(&line))); } } TEST(InputBuffer, ReadNBytes) { Env* env = Env::Default(); string fname; ASSERT_TRUE(env->LocalTempFilename(&fname)); TF_ASSERT_OK(WriteStringToFile(env, fname, "0123456789")); for (auto buf_size : BufferSizes()) { std::unique_ptr<RandomAccessFile> file; TF_CHECK_OK(env->NewRandomAccessFile(fname, &file)); string read; io::InputBuffer in(file.get(), buf_size); EXPECT_EQ(0, in.Tell()); TF_CHECK_OK(in.ReadNBytes(3, &read)); EXPECT_EQ(read, "012"); EXPECT_EQ(3, in.Tell()); TF_CHECK_OK(in.ReadNBytes(0, &read)); EXPECT_EQ(read, ""); EXPECT_EQ(3, in.Tell()); TF_CHECK_OK(in.ReadNBytes(4, &read)); EXPECT_EQ(read, "3456"); EXPECT_EQ(7, in.Tell()); TF_CHECK_OK(in.ReadNBytes(0, &read)); EXPECT_EQ(read, ""); EXPECT_EQ(7, in.Tell()); EXPECT_TRUE(errors::IsOutOfRange(in.ReadNBytes(5, &read))); EXPECT_EQ(read, "789"); EXPECT_EQ(10, in.Tell()); EXPECT_TRUE(errors::IsOutOfRange(in.ReadNBytes(5, &read))); EXPECT_EQ(read, ""); EXPECT_EQ(10, in.Tell()); TF_CHECK_OK(in.ReadNBytes(0, &read)); EXPECT_EQ(read, ""); EXPECT_EQ(10, in.Tell()); } size_t bytes_read; for (auto buf_size : BufferSizes()) { std::unique_ptr<RandomAccessFile> file; TF_CHECK_OK(env->NewRandomAccessFile(fname, &file)); char read[5]; io::InputBuffer in(file.get(), buf_size); EXPECT_EQ(0, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(3, read, &bytes_read)); EXPECT_EQ(StringPiece(read, 3), "012"); EXPECT_EQ(3, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(0, read, &bytes_read)); EXPECT_EQ(StringPiece(read, 3), "012"); EXPECT_EQ(3, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(4, read, &bytes_read)); EXPECT_EQ(StringPiece(read, 4), "3456"); EXPECT_EQ(7, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(0, read, &bytes_read)); EXPECT_EQ(StringPiece(read, 4), "3456"); EXPECT_EQ(7, in.Tell()); EXPECT_TRUE(errors::IsOutOfRange(in.ReadNBytes(5, read, &bytes_read))); EXPECT_EQ(StringPiece(read, 3), "789"); EXPECT_EQ(10, in.Tell()); EXPECT_TRUE(errors::IsOutOfRange(in.ReadNBytes(5, read, &bytes_read))); EXPECT_EQ(StringPiece(read, 3), "789"); EXPECT_EQ(10, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(0, read, &bytes_read)); EXPECT_EQ(StringPiece(read, 3), "789"); EXPECT_EQ(10, in.Tell()); } } TEST(InputBuffer, SkipNBytes) { Env* env = Env::Default(); string fname; ASSERT_TRUE(env->LocalTempFilename(&fname)); TF_ASSERT_OK(WriteStringToFile(env, fname, "0123456789")); for (auto buf_size : BufferSizes()) { std::unique_ptr<RandomAccessFile> file; TF_CHECK_OK(env->NewRandomAccessFile(fname, &file)); string read; io::InputBuffer in(file.get(), buf_size); EXPECT_EQ(0, in.Tell()); TF_CHECK_OK(in.SkipNBytes(3)); EXPECT_EQ(3, in.Tell()); TF_CHECK_OK(in.SkipNBytes(0)); EXPECT_EQ(3, in.Tell()); TF_CHECK_OK(in.ReadNBytes(2, &read)); EXPECT_EQ(read, "34"); EXPECT_EQ(5, in.Tell()); TF_CHECK_OK(in.SkipNBytes(0)); EXPECT_EQ(5, in.Tell()); TF_CHECK_OK(in.SkipNBytes(2)); EXPECT_EQ(7, in.Tell()); TF_CHECK_OK(in.ReadNBytes(1, &read)); EXPECT_EQ(read, "7"); EXPECT_EQ(8, in.Tell()); EXPECT_TRUE(errors::IsOutOfRange(in.SkipNBytes(5))); EXPECT_EQ(10, in.Tell()); EXPECT_TRUE(errors::IsOutOfRange(in.SkipNBytes(5))); EXPECT_EQ(10, in.Tell()); EXPECT_TRUE(errors::IsOutOfRange(in.ReadNBytes(5, &read))); EXPECT_EQ(read, ""); EXPECT_EQ(10, in.Tell()); } } TEST(InputBuffer, Seek) { Env* env = Env::Default(); string fname; ASSERT_TRUE(env->LocalTempFilename(&fname)); TF_ASSERT_OK(WriteStringToFile(env, fname, "0123456789")); for (auto buf_size : BufferSizes()) { std::unique_ptr<RandomAccessFile> file; TF_CHECK_OK(env->NewRandomAccessFile(fname, &file)); string read; io::InputBuffer in(file.get(), buf_size); TF_CHECK_OK(in.ReadNBytes(3, &read)); EXPECT_EQ(read, "012"); TF_CHECK_OK(in.ReadNBytes(3, &read)); EXPECT_EQ(read, "345"); TF_CHECK_OK(in.Seek(0)); TF_CHECK_OK(in.ReadNBytes(3, &read)); EXPECT_EQ(read, "012"); TF_CHECK_OK(in.Seek(3)); TF_CHECK_OK(in.ReadNBytes(4, &read)); EXPECT_EQ(read, "3456"); TF_CHECK_OK(in.Seek(4)); TF_CHECK_OK(in.ReadNBytes(4, &read)); EXPECT_EQ(read, "4567"); TF_CHECK_OK(in.Seek(1 << 25)); EXPECT_TRUE(errors::IsOutOfRange(in.ReadNBytes(1, &read))); EXPECT_TRUE(absl::StrContains(in.Seek(-1).ToString(), "negative position")); } } TEST(InputBuffer, ReadVarint32) { Env* env = Env::Default(); string fname; ASSERT_TRUE(env->LocalTempFilename(&fname)); std::vector<uint32> data; uint32 i = 0; for (; i < (1U << 10); i += 1) data.push_back(i); for (; i < (1U << 15); i += 5) data.push_back(i); for (; i < (1U << 31); i += 132817) data.push_back(i); data.push_back(std::numeric_limits<uint32>::max()); { std::unique_ptr<WritableFile> file; TF_CHECK_OK(env->NewWritableFile(fname, &file)); string varint; for (uint32 number : data) { varint.clear(); core::PutVarint32(&varint, number); TF_CHECK_OK(file->Append(StringPiece(varint))); } } for (auto buf_size : BufferSizes()) { std::unique_ptr<RandomAccessFile> file; TF_CHECK_OK(env->NewRandomAccessFile(fname, &file)); io::InputBuffer in(file.get(), buf_size); uint32 result = 0; for (uint32 expected : data) { TF_ASSERT_OK(in.ReadVarint32(&result)); EXPECT_EQ(expected, result); } EXPECT_TRUE(errors::IsOutOfRange(in.ReadVarint32(&result))); } } TEST(InputBuffer, ReadVarint64) { Env* env = Env::Default(); string fname; ASSERT_TRUE(env->LocalTempFilename(&fname)); std::vector<uint64> data; uint64 i = 0; for (; i < (1U << 10); i += 1) data.push_back(i); for (; i < (1U << 15); i += 5) data.push_back(i); for (; i < (1U << 31); i += 164817) data.push_back(i); for (; i < (1ULL << 63); i += 16481797854795663UL) data.push_back(i); data.push_back(std::numeric_limits<uint64>::max()); { std::unique_ptr<WritableFile> file; TF_CHECK_OK(env->NewWritableFile(fname, &file)); string varint; for (uint64 number : data) { varint.clear(); core::PutVarint64(&varint, number); TF_CHECK_OK(file->Append(StringPiece(varint))); } } for (auto buf_size : BufferSizes()) { std::unique_ptr<RandomAccessFile> file; TF_CHECK_OK(env->NewRandomAccessFile(fname, &file)); io::InputBuffer in(file.get(), buf_size); uint64 result = 0; for (uint64 expected : data) { TF_ASSERT_OK(in.ReadVarint64(&result)); EXPECT_EQ(expected, result); } EXPECT_TRUE(errors::IsOutOfRange(in.ReadVarint64(&result))); } } TEST(InputBuffer, Hint) { Env* env = Env::Default(); string fname; ASSERT_TRUE(env->LocalTempFilename(&fname)); TF_ASSERT_OK(WriteStringToFile(env, fname, "0123456789")); for (auto buf_size : BufferSizes()) { std::unique_ptr<RandomAccessFile> file; TF_CHECK_OK(env->NewRandomAccessFile(fname, &file)); string read; io::InputBuffer in(file.get(), buf_size); TF_CHECK_OK(in.ReadNBytes(3, &read)); EXPECT_EQ(read, "012"); TF_CHECK_OK(in.Hint(4)); TF_CHECK_OK(in.ReadNBytes(3, &read)); EXPECT_EQ(read, "345"); TF_CHECK_OK(in.Hint(1)); TF_CHECK_OK(in.ReadNBytes(3, &read)); EXPECT_EQ(read, "678"); TF_CHECK_OK(in.Seek(0)); TF_CHECK_OK(in.Hint(7)); TF_CHECK_OK(in.ReadNBytes(3, &read)); EXPECT_EQ(read, "012"); TF_CHECK_OK(in.ReadNBytes(4, &read)); EXPECT_EQ(read, "3456"); TF_CHECK_OK(in.Hint(2)); TF_CHECK_OK(in.Seek(4)); TF_CHECK_OK(in.ReadNBytes(4, &read)); EXPECT_EQ(read, "4567"); TF_CHECK_OK(in.Seek(0)); TF_CHECK_OK(in.Hint(1 << 25)); TF_CHECK_OK(in.Seek(1 << 25)); EXPECT_TRUE(errors::IsOutOfRange(in.Hint(1))); EXPECT_TRUE(errors::IsInvalidArgument(in.Hint(-1))); } } } }
2,320
cpp
tensorflow/tensorflow
cache
third_party/xla/third_party/tsl/tsl/lib/io/cache.cc
third_party/xla/third_party/tsl/tsl/lib/io/cache_test.cc
#ifndef TENSORFLOW_TSL_LIB_IO_CACHE_H_ #define TENSORFLOW_TSL_LIB_IO_CACHE_H_ #include <cstdint> #include "tsl/platform/stringpiece.h" namespace tsl { using Slice = StringPiece; namespace table { class Cache; Cache* NewLRUCache(size_t capacity); class Cache { public: Cache() = default; Cache(const Cache&) = delete; Cache& operator=(const Cache&) = delete; virtual ~Cache(); struct Handle {}; virtual Handle* Insert(const Slice& key, void* value, size_t charge, void (*deleter)(const Slice& key, void* value)) = 0; virtual Handle* Lookup(const Slice& key) = 0; virtual void Release(Handle* handle) = 0; virtual void* Value(Handle* handle) = 0; virtual void Erase(const Slice& key) = 0; virtual uint64_t NewId() = 0; virtual void Prune() {} virtual size_t TotalCharge() const = 0; private: void LRU_Remove(Handle* e); void LRU_Append(Handle* e); void Unref(Handle* e); struct Rep; Rep* rep_; }; } } #endif #include "tsl/lib/io/cache.h" #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "tsl/platform/mutex.h" #include "tsl/platform/raw_coding.h" namespace tsl { namespace table { Cache::~Cache() {} namespace { struct LRUHandle { void* value; void (*deleter)(const Slice&, void* value); LRUHandle* next_hash; LRUHandle* next; LRUHandle* prev; size_t charge; size_t key_length; bool in_cache; uint32_t refs; uint32_t hash; char key_data[1]; Slice key() const { assert(next != this); return Slice(key_data, key_length); } }; class HandleTable { public: HandleTable() : length_(0), elems_(0), list_(nullptr) { Resize(); } ~HandleTable() { delete[] list_; } LRUHandle* Lookup(const Slice& key, uint32_t hash) { return *FindPointer(key, hash); } LRUHandle* Insert(LRUHandle* h) { LRUHandle** ptr = FindPointer(h->key(), h->hash); LRUHandle* old = *ptr; h->next_hash = (old == nullptr ? nullptr : old->next_hash); *ptr = h; if (old == nullptr) { ++elems_; if (elems_ > length_) { Resize(); } } return old; } LRUHandle* Remove(const Slice& key, uint32_t hash) { LRUHandle** ptr = FindPointer(key, hash); LRUHandle* result = *ptr; if (result != nullptr) { *ptr = result->next_hash; --elems_; } return result; } private: uint32_t length_; uint32_t elems_; LRUHandle** list_; LRUHandle** FindPointer(const Slice& key, uint32_t hash) { LRUHandle** ptr = &list_[hash & (length_ - 1)]; while (*ptr != nullptr && ((*ptr)->hash != hash || key != (*ptr)->key())) { ptr = &(*ptr)->next_hash; } return ptr; } void Resize() { uint32_t new_length = 4; while (new_length < elems_) { new_length *= 2; } LRUHandle** new_list = new LRUHandle*[new_length]; memset(new_list, 0, sizeof(new_list[0]) * new_length); uint32_t count = 0; for (uint32_t i = 0; i < length_; i++) { LRUHandle* h = list_[i]; while (h != nullptr) { LRUHandle* next = h->next_hash; uint32_t hash = h->hash; LRUHandle** ptr = &new_list[hash & (new_length - 1)]; h->next_hash = *ptr; *ptr = h; h = next; count++; } } assert(elems_ == count); delete[] list_; list_ = new_list; length_ = new_length; } }; class LRUCache { public: LRUCache(); ~LRUCache(); void SetCapacity(size_t capacity) { capacity_ = capacity; } Cache::Handle* Insert(const Slice& key, uint32_t hash, void* value, size_t charge, void (*deleter)(const Slice& key, void* value)); Cache::Handle* Lookup(const Slice& key, uint32_t hash); void Release(Cache::Handle* handle); void Erase(const Slice& key, uint32_t hash); void Prune(); size_t TotalCharge() const { mutex_lock l(mutex_); return usage_; } private: void LRU_Remove(LRUHandle* e); void LRU_Append(LRUHandle* list, LRUHandle* e); void Ref(LRUHandle* e); void Unref(LRUHandle* e); bool FinishErase(LRUHandle* e) TF_EXCLUSIVE_LOCKS_REQUIRED(mutex_); size_t capacity_; mutable mutex mutex_; size_t usage_ TF_GUARDED_BY(mutex_); LRUHandle lru_ TF_GUARDED_BY(mutex_); LRUHandle in_use_ TF_GUARDED_BY(mutex_); HandleTable table_ TF_GUARDED_BY(mutex_); }; LRUCache::LRUCache() : capacity_(0), usage_(0) { lru_.next = &lru_; lru_.prev = &lru_; in_use_.next = &in_use_; in_use_.prev = &in_use_; } LRUCache::~LRUCache() { assert(in_use_.next == &in_use_); for (LRUHandle* e = lru_.next; e != &lru_;) { LRUHandle* next = e->next; assert(e->in_cache); e->in_cache = false; assert(e->refs == 1); Unref(e); e = next; } } void LRUCache::Ref(LRUHandle* e) { if (e->refs == 1 && e->in_cache) { LRU_Remove(e); LRU_Append(&in_use_, e); } e->refs++; } void LRUCache::Unref(LRUHandle* e) { assert(e->refs > 0); e->refs--; if (e->refs == 0) { assert(!e->in_cache); (*e->deleter)(e->key(), e->value); free(e); } else if (e->in_cache && e->refs == 1) { LRU_Remove(e); LRU_Append(&lru_, e); } } void LRUCache::LRU_Remove(LRUHandle* e) { e->next->prev = e->prev; e->prev->next = e->next; } void LRUCache::LRU_Append(LRUHandle* list, LRUHandle* e) { e->next = list; e->prev = list->prev; e->prev->next = e; e->next->prev = e; } Cache::Handle* LRUCache::Lookup(const Slice& key, uint32_t hash) { mutex_lock l(mutex_); LRUHandle* e = table_.Lookup(key, hash); if (e != nullptr) { Ref(e); } return reinterpret_cast<Cache::Handle*>(e); } void LRUCache::Release(Cache::Handle* handle) { mutex_lock l(mutex_); Unref(reinterpret_cast<LRUHandle*>(handle)); } Cache::Handle* LRUCache::Insert(const Slice& key, uint32_t hash, void* value, size_t charge, void (*deleter)(const Slice& key, void* value)) { mutex_lock l(mutex_); LRUHandle* e = reinterpret_cast<LRUHandle*>(malloc(sizeof(LRUHandle) - 1 + key.size())); e->value = value; e->deleter = deleter; e->charge = charge; e->key_length = key.size(); e->hash = hash; e->in_cache = false; e->refs = 1; memcpy(e->key_data, key.data(), key.size()); if (capacity_ > 0) { e->refs++; e->in_cache = true; LRU_Append(&in_use_, e); usage_ += charge; FinishErase(table_.Insert(e)); } else { e->next = nullptr; } while (usage_ > capacity_ && lru_.next != &lru_) { LRUHandle* old = lru_.next; assert(old->refs == 1); bool erased = FinishErase(table_.Remove(old->key(), old->hash)); if (!erased) { assert(erased); } } return reinterpret_cast<Cache::Handle*>(e); } bool LRUCache::FinishErase(LRUHandle* e) { if (e != nullptr) { assert(e->in_cache); LRU_Remove(e); e->in_cache = false; usage_ -= e->charge; Unref(e); } return e != nullptr; } void LRUCache::Erase(const Slice& key, uint32_t hash) { mutex_lock l(mutex_); FinishErase(table_.Remove(key, hash)); } void LRUCache::Prune() { mutex_lock l(mutex_); while (lru_.next != &lru_) { LRUHandle* e = lru_.next; assert(e->refs == 1); bool erased = FinishErase(table_.Remove(e->key(), e->hash)); if (!erased) { assert(erased); } } } static const int kNumShardBits = 4; static const int kNumShards = 1 << kNumShardBits; class ShardedLRUCache : public Cache { private: LRUCache shard_[kNumShards]; mutex id_mutex_; uint64_t last_id_; static inline uint32_t HashSlice(const Slice& s) { return Hash(s.data(), s.size(), 0); } static uint32_t Shard(uint32_t hash) { return hash >> (32 - kNumShardBits); } public: explicit ShardedLRUCache(size_t capacity) : last_id_(0) { const size_t per_shard = (capacity + (kNumShards - 1)) / kNumShards; for (int s = 0; s < kNumShards; s++) { shard_[s].SetCapacity(per_shard); } } ~ShardedLRUCache() override {} Handle* Insert(const Slice& key, void* value, size_t charge, void (*deleter)(const Slice& key, void* value)) override { const uint32_t hash = HashSlice(key); return shard_[Shard(hash)].Insert(key, hash, value, charge, deleter); } Handle* Lookup(const Slice& key) override { const uint32_t hash = HashSlice(key); return shard_[Shard(hash)].Lookup(key, hash); } void Release(Handle* handle) override { LRUHandle* h = reinterpret_cast<LRUHandle*>(handle); shard_[Shard(h->hash)].Release(handle); } void Erase(const Slice& key) override { const uint32_t hash = HashSlice(key); shard_[Shard(hash)].Erase(key, hash); } void* Value(Handle* handle) override { return reinterpret_cast<LRUHandle*>(handle)->value; } uint64_t NewId() override { mutex_lock l(id_mutex_); return ++(last_id_); } void Prune() override { for (int s = 0; s < kNumShards; s++) { shard_[s].Prune(); } } size_t TotalCharge() const override { size_t total = 0; for (int s = 0; s < kNumShards; s++) { total += shard_[s].TotalCharge(); } return total; } private: static uint32_t Hash(const char* data, size_t n, uint32_t seed) { const uint32_t m = 0xc6a4a793; const uint32_t r = 24; const char* limit = data + n; uint32_t h = seed ^ (n * m); while (data + 4 <= limit) { uint32_t w = core::DecodeFixed32(data); data += 4; h += w; h *= m; h ^= (h >> 16); } switch (limit - data) { case 3: h += static_cast<uint8_t>(data[2]) << 16; ABSL_FALLTHROUGH_INTENDED; case 2: h += static_cast<uint8_t>(data[1]) << 8; ABSL_FALLTHROUGH_INTENDED; case 1: h += static_cast<uint8_t>(data[0]); h *= m; h ^= (h >> r); break; } return h; } }; } Cache* NewLRUCache(size_t capacity) { return new ShardedLRUCache(capacity); } } }
#include "tsl/lib/io/cache.h" #include <string> #include <vector> #include "tsl/platform/coding.h" #include "tsl/platform/raw_coding.h" #include "tsl/platform/test.h" namespace tsl { namespace table { static std::string EncodeKey(int k) { std::string result; core::PutFixed32(&result, k); return result; } static int DecodeKey(const Slice& k) { assert(k.size() == 4); return core::DecodeFixed32(k.data()); } static void* EncodeValue(uintptr_t v) { return reinterpret_cast<void*>(v); } static int DecodeValue(void* v) { return reinterpret_cast<uintptr_t>(v); } class CacheTest : public ::testing::Test { public: static void Deleter(const Slice& key, void* v) { current_->deleted_keys_.push_back(DecodeKey(key)); current_->deleted_values_.push_back(DecodeValue(v)); } static constexpr int kCacheSize = 1000; std::vector<int> deleted_keys_; std::vector<int> deleted_values_; Cache* cache_; CacheTest() : cache_(NewLRUCache(kCacheSize)) { current_ = this; } ~CacheTest() { delete cache_; } int Lookup(int key) { Cache::Handle* handle = cache_->Lookup(EncodeKey(key)); const int r = (handle == nullptr) ? -1 : DecodeValue(cache_->Value(handle)); if (handle != nullptr) { cache_->Release(handle); } return r; } void Insert(int key, int value, int charge = 1) { cache_->Release(cache_->Insert(EncodeKey(key), EncodeValue(value), charge, &CacheTest::Deleter)); } Cache::Handle* InsertAndReturnHandle(int key, int value, int charge = 1) { return cache_->Insert(EncodeKey(key), EncodeValue(value), charge, &CacheTest::Deleter); } void Erase(int key) { cache_->Erase(EncodeKey(key)); } static CacheTest* current_; }; CacheTest* CacheTest::current_; TEST_F(CacheTest, HitAndMiss) { ASSERT_EQ(-1, Lookup(100)); Insert(100, 101); ASSERT_EQ(101, Lookup(100)); ASSERT_EQ(-1, Lookup(200)); ASSERT_EQ(-1, Lookup(300)); Insert(200, 201); ASSERT_EQ(101, Lookup(100)); ASSERT_EQ(201, Lookup(200)); ASSERT_EQ(-1, Lookup(300)); Insert(100, 102); ASSERT_EQ(102, Lookup(100)); ASSERT_EQ(201, Lookup(200)); ASSERT_EQ(-1, Lookup(300)); ASSERT_EQ(1, deleted_keys_.size()); ASSERT_EQ(100, deleted_keys_[0]); ASSERT_EQ(101, deleted_values_[0]); } TEST_F(CacheTest, Erase) { Erase(200); ASSERT_EQ(0, deleted_keys_.size()); Insert(100, 101); Insert(200, 201); Erase(100); ASSERT_EQ(-1, Lookup(100)); ASSERT_EQ(201, Lookup(200)); ASSERT_EQ(1, deleted_keys_.size()); ASSERT_EQ(100, deleted_keys_[0]); ASSERT_EQ(101, deleted_values_[0]); Erase(100); ASSERT_EQ(-1, Lookup(100)); ASSERT_EQ(201, Lookup(200)); ASSERT_EQ(1, deleted_keys_.size()); } TEST_F(CacheTest, EntriesArePinned) { Insert(100, 101); Cache::Handle* h1 = cache_->Lookup(EncodeKey(100)); ASSERT_EQ(101, DecodeValue(cache_->Value(h1))); Insert(100, 102); Cache::Handle* h2 = cache_->Lookup(EncodeKey(100)); ASSERT_EQ(102, DecodeValue(cache_->Value(h2))); ASSERT_EQ(0, deleted_keys_.size()); cache_->Release(h1); ASSERT_EQ(1, deleted_keys_.size()); ASSERT_EQ(100, deleted_keys_[0]); ASSERT_EQ(101, deleted_values_[0]); Erase(100); ASSERT_EQ(-1, Lookup(100)); ASSERT_EQ(1, deleted_keys_.size()); cache_->Release(h2); ASSERT_EQ(2, deleted_keys_.size()); ASSERT_EQ(100, deleted_keys_[1]); ASSERT_EQ(102, deleted_values_[1]); } TEST_F(CacheTest, EvictionPolicy) { Insert(100, 101); Insert(200, 201); Insert(300, 301); Cache::Handle* h = cache_->Lookup(EncodeKey(300)); for (int i = 0; i < kCacheSize + 100; i++) { Insert(1000 + i, 2000 + i); ASSERT_EQ(2000 + i, Lookup(1000 + i)); ASSERT_EQ(101, Lookup(100)); } ASSERT_EQ(101, Lookup(100)); ASSERT_EQ(-1, Lookup(200)); ASSERT_EQ(301, Lookup(300)); cache_->Release(h); } TEST_F(CacheTest, UseExceedsCacheSize) { std::vector<Cache::Handle*> h; for (int i = 0; i < kCacheSize + 100; i++) { h.push_back(InsertAndReturnHandle(1000 + i, 2000 + i)); } for (int i = 0; i < h.size(); i++) { ASSERT_EQ(2000 + i, Lookup(1000 + i)); } for (int i = 0; i < h.size(); i++) { cache_->Release(h[i]); } } TEST_F(CacheTest, HeavyEntries) { const int kLight = 1; const int kHeavy = 10; int added = 0; int index = 0; while (added < 2 * kCacheSize) { const int weight = (index & 1) ? kLight : kHeavy; Insert(index, 1000 + index, weight); added += weight; index++; } int cached_weight = 0; for (int i = 0; i < index; i++) { const int weight = (i & 1 ? kLight : kHeavy); int r = Lookup(i); if (r >= 0) { cached_weight += weight; ASSERT_EQ(1000 + i, r); } } ASSERT_LE(cached_weight, kCacheSize + kCacheSize / 10); } TEST_F(CacheTest, NewId) { uint64_t a = cache_->NewId(); uint64_t b = cache_->NewId(); ASSERT_NE(a, b); } TEST_F(CacheTest, Prune) { Insert(1, 100); Insert(2, 200); Cache::Handle* handle = cache_->Lookup(EncodeKey(1)); ASSERT_TRUE(handle); cache_->Prune(); cache_->Release(handle); ASSERT_EQ(100, Lookup(1)); ASSERT_EQ(-1, Lookup(2)); } TEST_F(CacheTest, ZeroSizeCache) { delete cache_; cache_ = NewLRUCache(0); Insert(1, 100); ASSERT_EQ(-1, Lookup(1)); } } }
2,321
cpp
tensorflow/tensorflow
inputstream_interface
third_party/xla/third_party/tsl/tsl/lib/io/inputstream_interface.cc
third_party/xla/third_party/tsl/tsl/lib/io/inputstream_interface_test.cc
#ifndef TENSORFLOW_TSL_LIB_IO_INPUTSTREAM_INTERFACE_H_ #define TENSORFLOW_TSL_LIB_IO_INPUTSTREAM_INTERFACE_H_ #include <string> #include "tsl/platform/cord.h" #include "tsl/platform/errors.h" #include "tsl/platform/status.h" #include "tsl/platform/types.h" namespace tsl { namespace io { class InputStreamInterface { public: InputStreamInterface() {} virtual ~InputStreamInterface() {} virtual absl::Status ReadNBytes(int64_t bytes_to_read, tstring* result) = 0; #if defined(TF_CORD_SUPPORT) virtual absl::Status ReadNBytes(int64_t bytes_to_read, absl::Cord* cord) { return errors::Unimplemented( "ReadNBytes(int64, absl::Cord*) is not implemented."); } #endif virtual absl::Status SkipNBytes(int64_t bytes_to_skip); virtual int64_t Tell() const = 0; virtual absl::Status Reset() = 0; }; } } #endif #include "tsl/lib/io/inputstream_interface.h" #include "tsl/platform/errors.h" namespace tsl { namespace io { static constexpr int64_t kMaxSkipSize = 8 * 1024 * 1024; absl::Status InputStreamInterface::SkipNBytes(int64_t bytes_to_skip) { if (bytes_to_skip < 0) { return errors::InvalidArgument("Can't skip a negative number of bytes"); } tstring unused; while (bytes_to_skip > 0) { int64_t bytes_to_read = std::min<int64_t>(kMaxSkipSize, bytes_to_skip); TF_RETURN_IF_ERROR(ReadNBytes(bytes_to_read, &unused)); bytes_to_skip -= bytes_to_read; } return absl::OkStatus(); } } }
#include "tsl/lib/io/inputstream_interface.h" #include "tsl/lib/core/status_test_util.h" #include "tsl/platform/errors.h" #include "tsl/platform/test.h" namespace tsl { namespace io { namespace { class TestStringStream : public InputStreamInterface { public: explicit TestStringStream(const string& content) : content_(content) {} absl::Status ReadNBytes(int64_t bytes_to_read, tstring* result) override { result->clear(); if (pos_ + bytes_to_read > content_.size()) { return errors::OutOfRange("limit reached"); } *result = content_.substr(pos_, bytes_to_read); pos_ += bytes_to_read; return absl::OkStatus(); } int64_t Tell() const override { return pos_; } absl::Status Reset() override { pos_ = 0; return absl::OkStatus(); } private: string content_; int64_t pos_ = 0; }; TEST(InputStreamInterface, Basic) { TestStringStream ss("This is a test string"); tstring res; TF_ASSERT_OK(ss.ReadNBytes(4, &res)); EXPECT_EQ("This", res); TF_ASSERT_OK(ss.SkipNBytes(6)); TF_ASSERT_OK(ss.ReadNBytes(11, &res)); EXPECT_EQ("test string", res); EXPECT_TRUE(errors::IsOutOfRange(ss.SkipNBytes(1))); TF_ASSERT_OK(ss.Reset()); TF_ASSERT_OK(ss.ReadNBytes(4, &res)); EXPECT_EQ("This", res); } } } }
2,322
cpp
google/googletest
sample1
googletest/samples/sample1.cc
googletest/samples/sample1_unittest.cc
#ifndef GOOGLETEST_SAMPLES_SAMPLE1_H_ #define GOOGLETEST_SAMPLES_SAMPLE1_H_ int Factorial(int n); bool IsPrime(int n); #endif #include "sample1.h" int Factorial(int n) { int result = 1; for (int i = 1; i <= n; i++) { result *= i; } return result; } bool IsPrime(int n) { if (n <= 1) return false; if (n % 2 == 0) return n == 2; for (int i = 3;; i += 2) { if (i > n / i) break; if (n % i == 0) return false; } return true; }
#include "sample1.h" #include <limits.h> #include "gtest/gtest.h" namespace { TEST(FactorialTest, Negative) { EXPECT_EQ(1, Factorial(-5)); EXPECT_EQ(1, Factorial(-1)); EXPECT_GT(Factorial(-10), 0); } TEST(FactorialTest, Zero) { EXPECT_EQ(1, Factorial(0)); } TEST(FactorialTest, Positive) { EXPECT_EQ(1, Factorial(1)); EXPECT_EQ(2, Factorial(2)); EXPECT_EQ(6, Factorial(3)); EXPECT_EQ(40320, Factorial(8)); } TEST(IsPrimeTest, Negative) { EXPECT_FALSE(IsPrime(-1)); EXPECT_FALSE(IsPrime(-2)); EXPECT_FALSE(IsPrime(INT_MIN)); } TEST(IsPrimeTest, Trivial) { EXPECT_FALSE(IsPrime(0)); EXPECT_FALSE(IsPrime(1)); EXPECT_TRUE(IsPrime(2)); EXPECT_TRUE(IsPrime(3)); } TEST(IsPrimeTest, Positive) { EXPECT_FALSE(IsPrime(4)); EXPECT_TRUE(IsPrime(5)); EXPECT_FALSE(IsPrime(6)); EXPECT_TRUE(IsPrime(23)); } }
2,323
cpp
google/googletest
sample4
googletest/samples/sample4.cc
googletest/samples/sample4_unittest.cc
#ifndef GOOGLETEST_SAMPLES_SAMPLE4_H_ #define GOOGLETEST_SAMPLES_SAMPLE4_H_ class Counter { private: int counter_; public: Counter() : counter_(0) {} int Increment(); int Decrement(); void Print() const; }; #endif #include "sample4.h" #include <stdio.h> int Counter::Increment() { return counter_++; } int Counter::Decrement() { if (counter_ == 0) { return counter_; } else { return counter_--; } } void Counter::Print() const { printf("%d", counter_); }
#include "sample4.h" #include "gtest/gtest.h" namespace { TEST(Counter, Increment) { Counter c; EXPECT_EQ(0, c.Decrement()); EXPECT_EQ(0, c.Increment()); EXPECT_EQ(1, c.Increment()); EXPECT_EQ(2, c.Increment()); EXPECT_EQ(3, c.Decrement()); } }
2,324
cpp
google/googletest
sample2
googletest/samples/sample2.cc
googletest/samples/sample2_unittest.cc
#ifndef GOOGLETEST_SAMPLES_SAMPLE2_H_ #define GOOGLETEST_SAMPLES_SAMPLE2_H_ #include <string.h> class MyString { private: const char* c_string_; const MyString& operator=(const MyString& rhs); public: static const char* CloneCString(const char* a_c_string); MyString() : c_string_(nullptr) {} explicit MyString(const char* a_c_string) : c_string_(nullptr) { Set(a_c_string); } MyString(const MyString& string) : c_string_(nullptr) { Set(string.c_string_); } ~MyString() { delete[] c_string_; } const char* c_string() const { return c_string_; } size_t Length() const { return c_string_ == nullptr ? 0 : strlen(c_string_); } void Set(const char* c_string); }; #endif #include "sample2.h" #include <string.h> const char* MyString::CloneCString(const char* a_c_string) { if (a_c_string == nullptr) return nullptr; const size_t len = strlen(a_c_string); char* const clone = new char[len + 1]; memcpy(clone, a_c_string, len + 1); return clone; } void MyString::Set(const char* a_c_string) { const char* const temp = MyString::CloneCString(a_c_string); delete[] c_string_; c_string_ = temp; }
#include "sample2.h" #include "gtest/gtest.h" namespace { TEST(MyString, DefaultConstructor) { const MyString s; EXPECT_STREQ(nullptr, s.c_string()); EXPECT_EQ(0u, s.Length()); } const char kHelloString[] = "Hello, world!"; TEST(MyString, ConstructorFromCString) { const MyString s(kHelloString); EXPECT_EQ(0, strcmp(s.c_string(), kHelloString)); EXPECT_EQ(sizeof(kHelloString) / sizeof(kHelloString[0]) - 1, s.Length()); } TEST(MyString, CopyConstructor) { const MyString s1(kHelloString); const MyString s2 = s1; EXPECT_EQ(0, strcmp(s2.c_string(), kHelloString)); } TEST(MyString, Set) { MyString s; s.Set(kHelloString); EXPECT_EQ(0, strcmp(s.c_string(), kHelloString)); s.Set(s.c_string()); EXPECT_EQ(0, strcmp(s.c_string(), kHelloString)); s.Set(nullptr); EXPECT_STREQ(nullptr, s.c_string()); } }
2,325
cpp
google/googletest
gtest-typed-test
googletest/src/gtest-typed-test.cc
googletest/test/gtest-typed-test_test.cc
#ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_ #define GOOGLETEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_ #if 0 template <typename T> class FooTest : public testing::Test { public: ... typedef std::list<T> List; static T shared_; T value_; }; typedef testing::Types<char, int, unsigned int> MyTypes; TYPED_TEST_SUITE(FooTest, MyTypes); TYPED_TEST(FooTest, DoesBlah) { TypeParam n = this->value_; n += TestFixture::shared_; typename TestFixture::List values; values.push_back(n); ... } TYPED_TEST(FooTest, HasPropertyA) { ... } #endif #if 0 template <typename T> class FooTest : public testing::Test { ... }; TYPED_TEST_SUITE_P(FooTest); TYPED_TEST_P(FooTest, DoesBlah) { TypeParam n = 0; ... } TYPED_TEST_P(FooTest, HasPropertyA) { ... } REGISTER_TYPED_TEST_SUITE_P(FooTest, DoesBlah, HasPropertyA); typedef testing::Types<char, int, unsigned int> MyTypes; INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes); #endif #include "gtest/internal/gtest-internal.h" #include "gtest/internal/gtest-port.h" #include "gtest/internal/gtest-type-util.h" #define GTEST_TYPE_PARAMS_(TestSuiteName) gtest_type_params_##TestSuiteName##_ #define GTEST_NAME_GENERATOR_(TestSuiteName) \ gtest_type_params_##TestSuiteName##_NameGenerator #define TYPED_TEST_SUITE(CaseName, Types, ...) \ typedef ::testing::internal::GenerateTypeList<Types>::type \ GTEST_TYPE_PARAMS_(CaseName); \ typedef ::testing::internal::NameGeneratorSelector<__VA_ARGS__>::type \ GTEST_NAME_GENERATOR_(CaseName) #define TYPED_TEST(CaseName, TestName) \ static_assert(sizeof(GTEST_STRINGIFY_(TestName)) > 1, \ "test-name must not be empty"); \ template <typename gtest_TypeParam_> \ class GTEST_TEST_CLASS_NAME_(CaseName, TestName) \ : public CaseName<gtest_TypeParam_> { \ private: \ typedef CaseName<gtest_TypeParam_> TestFixture; \ typedef gtest_TypeParam_ TypeParam; \ void TestBody() override; \ }; \ GTEST_INTERNAL_ATTRIBUTE_MAYBE_UNUSED static bool \ gtest_##CaseName##_##TestName##_registered_ = \ ::testing::internal::TypeParameterizedTest< \ CaseName, \ ::testing::internal::TemplateSel<GTEST_TEST_CLASS_NAME_( \ CaseName, TestName)>, \ GTEST_TYPE_PARAMS_( \ CaseName)>::Register("", \ ::testing::internal::CodeLocation( \ __FILE__, __LINE__), \ GTEST_STRINGIFY_(CaseName), \ GTEST_STRINGIFY_(TestName), 0, \ ::testing::internal::GenerateNames< \ GTEST_NAME_GENERATOR_(CaseName), \ GTEST_TYPE_PARAMS_(CaseName)>()); \ template <typename gtest_TypeParam_> \ void GTEST_TEST_CLASS_NAME_(CaseName, \ TestName)<gtest_TypeParam_>::TestBody() #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ #define TYPED_TEST_CASE \ static_assert(::testing::internal::TypedTestCaseIsDeprecated(), ""); \ TYPED_TEST_SUITE #endif #define GTEST_SUITE_NAMESPACE_(TestSuiteName) gtest_suite_##TestSuiteName##_ #define GTEST_TYPED_TEST_SUITE_P_STATE_(TestSuiteName) \ gtest_typed_test_suite_p_state_##TestSuiteName##_ #define GTEST_REGISTERED_TEST_NAMES_(TestSuiteName) \ gtest_registered_test_names_##TestSuiteName##_ #define TYPED_TEST_SUITE_P(SuiteName) \ static ::testing::internal::TypedTestSuitePState \ GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName) #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ #define TYPED_TEST_CASE_P \ static_assert(::testing::internal::TypedTestCase_P_IsDeprecated(), ""); \ TYPED_TEST_SUITE_P #endif #define TYPED_TEST_P(SuiteName, TestName) \ namespace GTEST_SUITE_NAMESPACE_(SuiteName) { \ template <typename gtest_TypeParam_> \ class TestName : public SuiteName<gtest_TypeParam_> { \ private: \ typedef SuiteName<gtest_TypeParam_> TestFixture; \ typedef gtest_TypeParam_ TypeParam; \ void TestBody() override; \ }; \ GTEST_INTERNAL_ATTRIBUTE_MAYBE_UNUSED static bool \ gtest_##TestName##_defined_ = \ GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName).AddTestName( \ __FILE__, __LINE__, GTEST_STRINGIFY_(SuiteName), \ GTEST_STRINGIFY_(TestName)); \ } \ template <typename gtest_TypeParam_> \ void GTEST_SUITE_NAMESPACE_( \ SuiteName)::TestName<gtest_TypeParam_>::TestBody() #define REGISTER_TYPED_TEST_SUITE_P(SuiteName, ...) \ namespace GTEST_SUITE_NAMESPACE_(SuiteName) { \ typedef ::testing::internal::Templates<__VA_ARGS__> gtest_AllTests_; \ } \ GTEST_INTERNAL_ATTRIBUTE_MAYBE_UNUSED static const char* const \ GTEST_REGISTERED_TEST_NAMES_(SuiteName) = \ GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName).VerifyRegisteredTestNames( \ GTEST_STRINGIFY_(SuiteName), __FILE__, __LINE__, #__VA_ARGS__) #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ #define REGISTER_TYPED_TEST_CASE_P \ static_assert(::testing::internal::RegisterTypedTestCase_P_IsDeprecated(), \ ""); \ REGISTER_TYPED_TEST_SUITE_P #endif #define INSTANTIATE_TYPED_TEST_SUITE_P(Prefix, SuiteName, Types, ...) \ static_assert(sizeof(GTEST_STRINGIFY_(Prefix)) > 1, \ "test-suit-prefix must not be empty"); \ GTEST_INTERNAL_ATTRIBUTE_MAYBE_UNUSED static bool \ gtest_##Prefix##_##SuiteName = \ ::testing::internal::TypeParameterizedTestSuite< \ SuiteName, GTEST_SUITE_NAMESPACE_(SuiteName)::gtest_AllTests_, \ ::testing::internal::GenerateTypeList<Types>::type>:: \ Register( \ GTEST_STRINGIFY_(Prefix), \ ::testing::internal::CodeLocation(__FILE__, __LINE__), \ &GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName), \ GTEST_STRINGIFY_(SuiteName), \ GTEST_REGISTERED_TEST_NAMES_(SuiteName), \ ::testing::internal::GenerateNames< \ ::testing::internal::NameGeneratorSelector< \ __VA_ARGS__>::type, \ ::testing::internal::GenerateTypeList<Types>::type>()) #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ #define INSTANTIATE_TYPED_TEST_CASE_P \ static_assert( \ ::testing::internal::InstantiateTypedTestCase_P_IsDeprecated(), ""); \ INSTANTIATE_TYPED_TEST_SUITE_P #endif #endif #include "gtest/gtest-typed-test.h" #include <set> #include <string> #include <vector> #include "gtest/gtest.h" namespace testing { namespace internal { static const char* SkipSpaces(const char* str) { while (IsSpace(*str)) str++; return str; } static std::vector<std::string> SplitIntoTestNames(const char* src) { std::vector<std::string> name_vec; src = SkipSpaces(src); for (; src != nullptr; src = SkipComma(src)) { name_vec.push_back(StripTrailingSpaces(GetPrefixUntilComma(src))); } return name_vec; } const char* TypedTestSuitePState::VerifyRegisteredTestNames( const char* test_suite_name, const char* file, int line, const char* registered_tests) { RegisterTypeParameterizedTestSuite(test_suite_name, CodeLocation(file, line)); typedef RegisteredTestsMap::const_iterator RegisteredTestIter; registered_ = true; std::vector<std::string> name_vec = SplitIntoTestNames(registered_tests); Message errors; std::set<std::string> tests; for (std::vector<std::string>::const_iterator name_it = name_vec.begin(); name_it != name_vec.end(); ++name_it) { const std::string& name = *name_it; if (tests.count(name) != 0) { errors << "Test " << name << " is listed more than once.\n"; continue; } if (registered_tests_.count(name) != 0) { tests.insert(name); } else { errors << "No test named " << name << " can be found in this test suite.\n"; } } for (RegisteredTestIter it = registered_tests_.begin(); it != registered_tests_.end(); ++it) { if (tests.count(it->first) == 0) { errors << "You forgot to list test " << it->first << ".\n"; } } const std::string& errors_str = errors.GetString(); if (!errors_str.empty()) { fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(), errors_str.c_str()); fflush(stderr); posix::Abort(); } return registered_tests; } } }
#include "test/gtest-typed-test_test.h" #include <set> #include <string> #include <type_traits> #include <vector> #include "gtest/gtest.h" GTEST_DISABLE_MSC_WARNINGS_PUSH_(4127 ) using testing::Test; template <typename T> class CommonTest : public Test { public: static void SetUpTestSuite() { shared_ = new T(5); } static void TearDownTestSuite() { delete shared_; shared_ = nullptr; } protected: typedef std::vector<T> Vector; typedef std::set<int> IntSet; CommonTest() : value_(1) {} ~CommonTest() override { EXPECT_EQ(3, value_); } void SetUp() override { EXPECT_EQ(1, value_); value_++; } void TearDown() override { EXPECT_EQ(2, value_); value_++; } T value_; static T* shared_; }; template <typename T> T* CommonTest<T>::shared_ = nullptr; using testing::Types; typedef Types<char, int> TwoTypes; TYPED_TEST_SUITE(CommonTest, TwoTypes); TYPED_TEST(CommonTest, ValuesAreCorrect) { EXPECT_EQ(5, *TestFixture::shared_); typename TestFixture::Vector empty; EXPECT_EQ(0U, empty.size()); typename TestFixture::IntSet empty2; EXPECT_EQ(0U, empty2.size()); EXPECT_EQ(2, this->value_); } TYPED_TEST(CommonTest, ValuesAreStillCorrect) { ASSERT_TRUE(this->shared_ != nullptr); EXPECT_EQ(5, *this->shared_); EXPECT_EQ(static_cast<TypeParam>(2), this->value_); } template <typename T> class TypedTest1 : public Test {}; TYPED_TEST_SUITE(TypedTest1, int); TYPED_TEST(TypedTest1, A) {} template <typename T> class TypedTest2 : public Test {}; TYPED_TEST_SUITE(TypedTest2, Types<int>); TYPED_TEST(TypedTest2, A) {} namespace library1 { template <typename T> class NumericTest : public Test {}; typedef Types<int, long> NumericTypes; TYPED_TEST_SUITE(NumericTest, NumericTypes); TYPED_TEST(NumericTest, DefaultIsZero) { EXPECT_EQ(0, TypeParam()); } } template <typename T> class TypedTestWithNames : public Test {}; class TypedTestNames { public: template <typename T> static std::string GetName(int i) { if (std::is_same<T, char>::value) { return std::string("char") + ::testing::PrintToString(i); } if (std::is_same<T, int>::value) { return std::string("int") + ::testing::PrintToString(i); } } }; TYPED_TEST_SUITE(TypedTestWithNames, TwoTypes, TypedTestNames); TYPED_TEST(TypedTestWithNames, TestSuiteName) { if (std::is_same<TypeParam, char>::value) { EXPECT_STREQ(::testing::UnitTest::GetInstance() ->current_test_info() ->test_suite_name(), "TypedTestWithNames/char0"); } if (std::is_same<TypeParam, int>::value) { EXPECT_STREQ(::testing::UnitTest::GetInstance() ->current_test_info() ->test_suite_name(), "TypedTestWithNames/int1"); } } using testing::Types; using testing::internal::TypedTestSuitePState; class TypedTestSuitePStateTest : public Test { protected: void SetUp() override { state_.AddTestName("foo.cc", 0, "FooTest", "A"); state_.AddTestName("foo.cc", 0, "FooTest", "B"); state_.AddTestName("foo.cc", 0, "FooTest", "C"); } TypedTestSuitePState state_; }; TEST_F(TypedTestSuitePStateTest, SucceedsForMatchingList) { const char* tests = "A, B, C"; EXPECT_EQ(tests, state_.VerifyRegisteredTestNames("Suite", "foo.cc", 1, tests)); } TEST_F(TypedTestSuitePStateTest, IgnoresOrderAndSpaces) { const char* tests = "A,C, B"; EXPECT_EQ(tests, state_.VerifyRegisteredTestNames("Suite", "foo.cc", 1, tests)); } using TypedTestSuitePStateDeathTest = TypedTestSuitePStateTest; TEST_F(TypedTestSuitePStateDeathTest, DetectsDuplicates) { EXPECT_DEATH_IF_SUPPORTED( state_.VerifyRegisteredTestNames("Suite", "foo.cc", 1, "A, B, A, C"), "foo\\.cc.1.?: Test A is listed more than once\\."); } TEST_F(TypedTestSuitePStateDeathTest, DetectsExtraTest) { EXPECT_DEATH_IF_SUPPORTED( state_.VerifyRegisteredTestNames("Suite", "foo.cc", 1, "A, B, C, D"), "foo\\.cc.1.?: No test named D can be found in this test suite\\."); } TEST_F(TypedTestSuitePStateDeathTest, DetectsMissedTest) { EXPECT_DEATH_IF_SUPPORTED( state_.VerifyRegisteredTestNames("Suite", "foo.cc", 1, "A, C"), "foo\\.cc.1.?: You forgot to list test B\\."); } TEST_F(TypedTestSuitePStateDeathTest, DetectsTestAfterRegistration) { state_.VerifyRegisteredTestNames("Suite", "foo.cc", 1, "A, B, C"); EXPECT_DEATH_IF_SUPPORTED( state_.AddTestName("foo.cc", 2, "FooTest", "D"), "foo\\.cc.2.?: Test D must be defined before REGISTER_TYPED_TEST_SUITE_P" "\\(FooTest, \\.\\.\\.\\)\\."); } template <typename T> class DerivedTest : public CommonTest<T> {}; TYPED_TEST_SUITE_P(DerivedTest); TYPED_TEST_P(DerivedTest, ValuesAreCorrect) { EXPECT_EQ(5, *TestFixture::shared_); EXPECT_EQ(2, this->value_); } TYPED_TEST_P(DerivedTest, ValuesAreStillCorrect) { ASSERT_TRUE(this->shared_ != nullptr); EXPECT_EQ(5, *this->shared_); EXPECT_EQ(2, this->value_); } REGISTER_TYPED_TEST_SUITE_P(DerivedTest, ValuesAreCorrect, ValuesAreStillCorrect); typedef Types<short, long> MyTwoTypes; INSTANTIATE_TYPED_TEST_SUITE_P(My, DerivedTest, MyTwoTypes); template <typename T> class TypeParametrizedTestWithNames : public Test {}; TYPED_TEST_SUITE_P(TypeParametrizedTestWithNames); TYPED_TEST_P(TypeParametrizedTestWithNames, TestSuiteName) { if (std::is_same<TypeParam, char>::value) { EXPECT_STREQ(::testing::UnitTest::GetInstance() ->current_test_info() ->test_suite_name(), "CustomName/TypeParametrizedTestWithNames/parChar0"); } if (std::is_same<TypeParam, int>::value) { EXPECT_STREQ(::testing::UnitTest::GetInstance() ->current_test_info() ->test_suite_name(), "CustomName/TypeParametrizedTestWithNames/parInt1"); } } REGISTER_TYPED_TEST_SUITE_P(TypeParametrizedTestWithNames, TestSuiteName); class TypeParametrizedTestNames { public: template <typename T> static std::string GetName(int i) { if (std::is_same<T, char>::value) { return std::string("parChar") + ::testing::PrintToString(i); } if (std::is_same<T, int>::value) { return std::string("parInt") + ::testing::PrintToString(i); } } }; INSTANTIATE_TYPED_TEST_SUITE_P(CustomName, TypeParametrizedTestWithNames, TwoTypes, TypeParametrizedTestNames); template <typename T> class TypedTestP1 : public Test {}; TYPED_TEST_SUITE_P(TypedTestP1); using IntAfterTypedTestSuiteP = int; TYPED_TEST_P(TypedTestP1, A) {} TYPED_TEST_P(TypedTestP1, B) {} using IntBeforeRegisterTypedTestSuiteP = int; REGISTER_TYPED_TEST_SUITE_P(TypedTestP1, A, B); template <typename T> class TypedTestP2 : public Test {}; TYPED_TEST_SUITE_P(TypedTestP2); TYPED_TEST_P(TypedTestP2, A) {} REGISTER_TYPED_TEST_SUITE_P(TypedTestP2, A); IntAfterTypedTestSuiteP after = 0; IntBeforeRegisterTypedTestSuiteP before = 0; INSTANTIATE_TYPED_TEST_SUITE_P(Int, TypedTestP1, int); INSTANTIATE_TYPED_TEST_SUITE_P(Int, TypedTestP2, Types<int>); INSTANTIATE_TYPED_TEST_SUITE_P(Double, TypedTestP2, Types<double>); typedef Types<std::vector<double>, std::set<char> > MyContainers; INSTANTIATE_TYPED_TEST_SUITE_P(My, ContainerTest, MyContainers); namespace library2 { template <typename T> class NumericTest : public Test {}; TYPED_TEST_SUITE_P(NumericTest); TYPED_TEST_P(NumericTest, DefaultIsZero) { EXPECT_EQ(0, TypeParam()); } TYPED_TEST_P(NumericTest, ZeroIsLessThanOne) { EXPECT_LT(TypeParam(0), TypeParam(1)); } REGISTER_TYPED_TEST_SUITE_P(NumericTest, DefaultIsZero, ZeroIsLessThanOne); typedef Types<int, double> NumericTypes; INSTANTIATE_TYPED_TEST_SUITE_P(My, NumericTest, NumericTypes); static const char* GetTestName() { return testing::UnitTest::GetInstance()->current_test_info()->name(); } template <typename T> class TrimmedTest : public Test {}; TYPED_TEST_SUITE_P(TrimmedTest); TYPED_TEST_P(TrimmedTest, Test1) { EXPECT_STREQ("Test1", GetTestName()); } TYPED_TEST_P(TrimmedTest, Test2) { EXPECT_STREQ("Test2", GetTestName()); } TYPED_TEST_P(TrimmedTest, Test3) { EXPECT_STREQ("Test3", GetTestName()); } TYPED_TEST_P(TrimmedTest, Test4) { EXPECT_STREQ("Test4", GetTestName()); } TYPED_TEST_P(TrimmedTest, Test5) { EXPECT_STREQ("Test5", GetTestName()); } REGISTER_TYPED_TEST_SUITE_P(TrimmedTest, Test1, Test2, Test3, Test4, Test5); template <typename T1, typename T2> struct MyPair {}; typedef Types<int, double, MyPair<int, int> > TrimTypes; INSTANTIATE_TYPED_TEST_SUITE_P(My, TrimmedTest, TrimTypes); } GTEST_DISABLE_MSC_WARNINGS_POP_()
2,326
cpp
google/googletest
gtest
googletest/src/gtest.cc
googletest/test/gtest_unittest.cc
#ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_H_ #define GOOGLETEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_H_ #endif #include "gtest/gtest.h" #include <ctype.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <wchar.h> #include <wctype.h> #include <algorithm> #include <chrono> #include <cmath> #include <csignal> #include <cstdint> #include <cstdlib> #include <cstring> #include <initializer_list> #include <iomanip> #include <ios> #include <iostream> #include <iterator> #include <limits> #include <list> #include <map> #include <ostream> #include <set> #include <sstream> #include <unordered_set> #include <utility> #include <vector> #include "gtest/gtest-assertion-result.h" #include "gtest/gtest-spi.h" #include "gtest/internal/custom/gtest.h" #include "gtest/internal/gtest-port.h" #ifdef GTEST_OS_LINUX #include <fcntl.h> #include <limits.h> #include <sched.h> #include <strings.h> #include <sys/mman.h> #include <sys/time.h> #include <unistd.h> #include <string> #elif defined(GTEST_OS_ZOS) #include <sys/time.h> #include <strings.h> #elif defined(GTEST_OS_WINDOWS_MOBILE) #include <windows.h> #undef min #elif defined(GTEST_OS_WINDOWS) #include <windows.h> #undef min #ifdef _MSC_VER #include <crtdbg.h> #endif #include <io.h> #include <sys/stat.h> #include <sys/timeb.h> #include <sys/types.h> #ifdef GTEST_OS_WINDOWS_MINGW #include <sys/time.h> #endif #else #include <sys/time.h> #include <unistd.h> #endif #if GTEST_HAS_EXCEPTIONS #include <stdexcept> #endif #if GTEST_CAN_STREAM_RESULTS_ #include <arpa/inet.h> #include <netdb.h> #include <sys/socket.h> #include <sys/types.h> #endif #include "src/gtest-internal-inl.h" #ifdef GTEST_OS_WINDOWS #define vsnprintf _vsnprintf #endif #ifdef GTEST_OS_MAC #ifndef GTEST_OS_IOS #include <crt_externs.h> #endif #endif #ifdef GTEST_HAS_ABSL #include "absl/container/flat_hash_set.h" #include "absl/debugging/failure_signal_handler.h" #include "absl/debugging/stacktrace.h" #include "absl/debugging/symbolize.h" #include "absl/flags/parse.h" #include "absl/flags/usage.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_replace.h" #include "absl/strings/string_view.h" #include "absl/strings/strip.h" #endif #if defined(__has_builtin) #define GTEST_HAS_BUILTIN(x) __has_builtin(x) #else #define GTEST_HAS_BUILTIN(x) 0 #endif #if defined(GTEST_HAS_ABSL) && !defined(GTEST_NO_ABSL_FLAGS) #define GTEST_HAS_ABSL_FLAGS #endif namespace testing { using internal::CountIf; using internal::ForEach; using internal::GetElementOr; using internal::Shuffle; static const char kDisableTestFilter[] = "DISABLED_*:*/DISABLED_*"; static const char kDeathTestSuiteFilter[] = "*DeathTest:*DeathTest/*"; static const char kUniversalFilter[] = "*"; static const char kDefaultOutputFormat[] = "xml"; static const char kDefaultOutputFile[] = "test_detail"; static const char kTestShardIndex[] = "GTEST_SHARD_INDEX"; static const char kTestTotalShards[] = "GTEST_TOTAL_SHARDS"; static const char kTestShardStatusFile[] = "GTEST_SHARD_STATUS_FILE"; namespace internal { const char kStackTraceMarker[] = "\nStack trace:\n"; bool g_help_flag = false; #if GTEST_HAS_FILE_SYSTEM static FILE* OpenFileForWriting(const std::string& output_file) { FILE* fileout = nullptr; FilePath output_file_path(output_file); FilePath output_dir(output_file_path.RemoveFileName()); if (output_dir.CreateDirectoriesRecursively()) { fileout = posix::FOpen(output_file.c_str(), "w"); } if (fileout == nullptr) { GTEST_LOG_(FATAL) << "Unable to open file \"" << output_file << "\""; } return fileout; } #endif } static const char* GetDefaultFilter() { const char* const testbridge_test_only = internal::posix::GetEnv("TESTBRIDGE_TEST_ONLY"); if (testbridge_test_only != nullptr) { return testbridge_test_only; } return kUniversalFilter; } static bool GetDefaultFailFast() { const char* const testbridge_test_runner_fail_fast = internal::posix::GetEnv("TESTBRIDGE_TEST_RUNNER_FAIL_FAST"); if (testbridge_test_runner_fail_fast != nullptr) { return strcmp(testbridge_test_runner_fail_fast, "1") == 0; } return false; } } GTEST_DEFINE_bool_( fail_fast, testing::internal::BoolFromGTestEnv("fail_fast", testing::GetDefaultFailFast()), "True if and only if a test failure should stop further test execution."); GTEST_DEFINE_bool_( also_run_disabled_tests, testing::internal::BoolFromGTestEnv("also_run_disabled_tests", false), "Run disabled tests too, in addition to the tests normally being run."); GTEST_DEFINE_bool_( break_on_failure, testing::internal::BoolFromGTestEnv("break_on_failure", false), "True if and only if a failed assertion should be a debugger " "break-point."); GTEST_DEFINE_bool_(catch_exceptions, testing::internal::BoolFromGTestEnv("catch_exceptions", true), "True if and only if " GTEST_NAME_ " should catch exceptions and treat them as test failures."); GTEST_DEFINE_string_( color, testing::internal::StringFromGTestEnv("color", "auto"), "Whether to use colors in the output. Valid values: yes, no, " "and auto. 'auto' means to use colors if the output is " "being sent to a terminal and the TERM environment variable " "is set to a terminal type that supports colors."); GTEST_DEFINE_string_( filter, testing::internal::StringFromGTestEnv("filter", testing::GetDefaultFilter()), "A colon-separated list of glob (not regex) patterns " "for filtering the tests to run, optionally followed by a " "'-' and a : separated list of negative patterns (tests to " "exclude). A test is run if it matches one of the positive " "patterns and does not match any of the negative patterns."); GTEST_DEFINE_bool_( install_failure_signal_handler, testing::internal::BoolFromGTestEnv("install_failure_signal_handler", false), "If true and supported on the current platform, " GTEST_NAME_ " should " "install a signal handler that dumps debugging information when fatal " "signals are raised."); GTEST_DEFINE_bool_(list_tests, false, "List all tests without running them."); GTEST_DEFINE_string_( output, testing::internal::StringFromGTestEnv( "output", testing::internal::OutputFlagAlsoCheckEnvVar().c_str()), "A format (defaults to \"xml\" but can be specified to be \"json\"), " "optionally followed by a colon and an output file name or directory. " "A directory is indicated by a trailing pathname separator. " "Examples: \"xml:filename.xml\", \"xml::directoryname/\". " "If a directory is specified, output files will be created " "within that directory, with file-names based on the test " "executable's name and, if necessary, made unique by adding " "digits."); GTEST_DEFINE_bool_( brief, testing::internal::BoolFromGTestEnv("brief", false), "True if only test failures should be displayed in text output."); GTEST_DEFINE_bool_(print_time, testing::internal::BoolFromGTestEnv("print_time", true), "True if and only if " GTEST_NAME_ " should display elapsed time in text output."); GTEST_DEFINE_bool_(print_utf8, testing::internal::BoolFromGTestEnv("print_utf8", true), "True if and only if " GTEST_NAME_ " prints UTF8 characters as text."); GTEST_DEFINE_int32_( random_seed, testing::internal::Int32FromGTestEnv("random_seed", 0), "Random number seed to use when shuffling test orders. Must be in range " "[1, 99999], or 0 to use a seed based on the current time."); GTEST_DEFINE_int32_( repeat, testing::internal::Int32FromGTestEnv("repeat", 1), "How many times to repeat each test. Specify a negative number " "for repeating forever. Useful for shaking out flaky tests."); GTEST_DEFINE_bool_( recreate_environments_when_repeating, testing::internal::BoolFromGTestEnv("recreate_environments_when_repeating", false), "Controls whether global test environments are recreated for each repeat " "of the tests. If set to false the global test environments are only set " "up once, for the first iteration, and only torn down once, for the last. " "Useful for shaking out flaky tests with stable, expensive test " "environments. If --gtest_repeat is set to a negative number, meaning " "there is no last run, the environments will always be recreated to avoid " "leaks."); GTEST_DEFINE_bool_(show_internal_stack_frames, false, "True if and only if " GTEST_NAME_ " should include internal stack frames when " "printing test failure stack traces."); GTEST_DEFINE_bool_(shuffle, testing::internal::BoolFromGTestEnv("shuffle", false), "True if and only if " GTEST_NAME_ " should randomize tests' order on every run."); GTEST_DEFINE_int32_( stack_trace_depth, testing::internal::Int32FromGTestEnv("stack_trace_depth", testing::kMaxStackTraceDepth), "The maximum number of stack frames to print when an " "assertion fails. The valid range is 0 through 100, inclusive."); GTEST_DEFINE_string_( stream_result_to, testing::internal::StringFromGTestEnv("stream_result_to", ""), "This flag specifies the host name and the port number on which to stream " "test results. Example: \"localhost:555\". The flag is effective only on " "Linux and macOS."); GTEST_DEFINE_bool_( throw_on_failure, testing::internal::BoolFromGTestEnv("throw_on_failure", false), "When this flag is specified, a failed assertion will throw an exception " "if exceptions are enabled or exit the program with a non-zero code " "otherwise. For use with an external test framework."); #if GTEST_USE_OWN_FLAGFILE_FLAG_ GTEST_DEFINE_string_( flagfile, testing::internal::StringFromGTestEnv("flagfile", ""), "This flag specifies the flagfile to read command-line flags from."); #endif namespace testing { namespace internal { const uint32_t Random::kMaxRange; uint32_t Random::Generate(uint32_t range) { state_ = static_cast<uint32_t>(1103515245ULL * state_ + 12345U) % kMaxRange; GTEST_CHECK_(range > 0) << "Cannot generate a number in the range [0, 0)."; GTEST_CHECK_(range <= kMaxRange) << "Generation of a number in [0, " << range << ") was requested, " << "but this can only generate numbers in [0, " << kMaxRange << ")."; return state_ % range; } static bool GTestIsInitialized() { return !GetArgvs().empty(); } static int SumOverTestSuiteList(const std::vector<TestSuite*>& case_list, int (TestSuite::*method)() const) { int sum = 0; for (size_t i = 0; i < case_list.size(); i++) { sum += (case_list[i]->*method)(); } return sum; } static bool TestSuitePassed(const TestSuite* test_suite) { return test_suite->should_run() && test_suite->Passed(); } static bool TestSuiteFailed(const TestSuite* test_suite) { return test_suite->should_run() && test_suite->Failed(); } static bool ShouldRunTestSuite(const TestSuite* test_suite) { return test_suite->should_run(); } namespace { bool ShouldEmitStackTraceForResultType(TestPartResult::Type type) { return type != TestPartResult::kSuccess && type != TestPartResult::kSkip; } } AssertHelper::AssertHelper(TestPartResult::Type type, const char* file, int line, const char* message) : data_(new AssertHelperData(type, file, line, message)) {} AssertHelper::~AssertHelper() { delete data_; } void AssertHelper::operator=(const Message& message) const { UnitTest::GetInstance()->AddTestPartResult( data_->type, data_->file, data_->line, AppendUserMessage(data_->message, message), ShouldEmitStackTraceForResultType(data_->type) ? UnitTest::GetInstance()->impl()->CurrentOsStackTraceExceptTop(1) : "" ); } namespace { constexpr bool kErrorOnUninstantiatedParameterizedTest = true; constexpr bool kErrorOnUninstantiatedTypeParameterizedTest = true; class FailureTest : public Test { public: explicit FailureTest(const CodeLocation& loc, std::string error_message, bool as_error) : loc_(loc), error_message_(std::move(error_message)), as_error_(as_error) {} void TestBody() override { if (as_error_) { AssertHelper(TestPartResult::kNonFatalFailure, loc_.file.c_str(), loc_.line, "") = Message() << error_message_; } else { std::cout << error_message_ << std::endl; } } private: const CodeLocation loc_; const std::string error_message_; const bool as_error_; }; } std::set<std::string>* GetIgnoredParameterizedTestSuites() { return UnitTest::GetInstance()->impl()->ignored_parameterized_test_suites(); } MarkAsIgnored::MarkAsIgnored(const char* test_suite) { GetIgnoredParameterizedTestSuites()->insert(test_suite); } void InsertSyntheticTestCase(const std::string& name, CodeLocation location, bool has_test_p) { const auto& ignored = *GetIgnoredParameterizedTestSuites(); if (ignored.find(name) != ignored.end()) return; const char kMissingInstantiation[] = " is defined via TEST_P, but never instantiated. None of the test " "cases " "will run. Either no INSTANTIATE_TEST_SUITE_P is provided or the only " "ones provided expand to nothing." "\n\n" "Ideally, TEST_P definitions should only ever be included as part of " "binaries that intend to use them. (As opposed to, for example, being " "placed in a library that may be linked in to get other utilities.)"; const char kMissingTestCase[] = " is instantiated via INSTANTIATE_TEST_SUITE_P, but no tests are " "defined via TEST_P . No test cases will run." "\n\n" "Ideally, INSTANTIATE_TEST_SUITE_P should only ever be invoked from " "code that always depend on code that provides TEST_P. Failing to do " "so is often an indication of dead code, e.g. the last TEST_P was " "removed but the rest got left behind."; std::string message = "Parameterized test suite " + name + (has_test_p ? kMissingInstantiation : kMissingTestCase) + "\n\n" "To suppress this error for this test suite, insert the following line " "(in a non-header) in the namespace it is defined in:" "\n\n" "GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(" + name + ");"; std::string full_name = "UninstantiatedParameterizedTestSuite<" + name + ">"; RegisterTest( "GoogleTestVerification", full_name.c_str(), nullptr, nullptr, location.file.c_str(), location.line, [message, location] { return new FailureTest(location, message, kErrorOnUninstantiatedParameterizedTest); }); } void RegisterTypeParameterizedTestSuite(const char* test_suite_name, CodeLocation code_location) { GetUnitTestImpl()->type_parameterized_test_registry().RegisterTestSuite( test_suite_name, std::move(code_location)); } void RegisterTypeParameterizedTestSuiteInstantiation(const char* case_name) { GetUnitTestImpl()->type_parameterized_test_registry().RegisterInstantiation( case_name); } void TypeParameterizedTestSuiteRegistry::RegisterTestSuite( const char* test_suite_name, CodeLocation code_location) { suites_.emplace(std::string(test_suite_name), TypeParameterizedTestSuiteInfo(std::move(code_location))); } void TypeParameterizedTestSuiteRegistry::RegisterInstantiation( const char* test_suite_name) { auto it = suites_.find(std::string(test_suite_name)); if (it != suites_.end()) { it->second.instantiated = true; } else { GTEST_LOG_(ERROR) << "Unknown type parameterized test suit '" << test_suite_name << "'"; } } void TypeParameterizedTestSuiteRegistry::CheckForInstantiations() { const auto& ignored = *GetIgnoredParameterizedTestSuites(); for (const auto& testcase : suites_) { if (testcase.second.instantiated) continue; if (ignored.find(testcase.first) != ignored.end()) continue; std::string message = "Type parameterized test suite " + testcase.first + " is defined via REGISTER_TYPED_TEST_SUITE_P, but never instantiated " "via INSTANTIATE_TYPED_TEST_SUITE_P. None of the test cases will run." "\n\n" "Ideally, TYPED_TEST_P definitions should only ever be included as " "part of binaries that intend to use them. (As opposed to, for " "example, being placed in a library that may be linked in to get " "other " "utilities.)" "\n\n" "To suppress this error for this test suite, insert the following " "line " "(in a non-header) in the namespace it is defined in:" "\n\n" "GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(" + testcase.first + ");"; std::string full_name = "UninstantiatedTypeParameterizedTestSuite<" + testcase.first + ">"; RegisterTest( "GoogleTestVerification", full_name.c_str(), nullptr, nullptr, testcase.second.code_location.file.c_str(), testcase.second.code_location.line, [message, testcase] { return new FailureTest(testcase.second.code_location, message, kErrorOnUninstantiatedTypeParameterizedTest); }); } } static ::std::vector<std::string> g_argvs; ::std::vector<std::string> GetArgvs() { #if defined(GTEST_CUSTOM_GET_ARGVS_) const auto& custom = GTEST_CUSTOM_GET_ARGVS_(); return ::std::vector<std::string>(custom.begin(), custom.end()); #else return g_argvs; #endif } #if GTEST_HAS_FILE_SYSTEM FilePath GetCurrentExecutableName() { FilePath result; #if defined(GTEST_OS_WINDOWS) || defined(GTEST_OS_OS2) result.Set(FilePath(GetArgvs()[0]).RemoveExtension("exe")); #else result.Set(FilePath(GetArgvs()[0])); #endif return result.RemoveDirectoryName(); } #endif std::string UnitTestOptions::GetOutputFormat() { std::string s = GTEST_FLAG_GET(output); const char* const gtest_output_flag = s.c_str(); const char* const colon = strchr(gtest_output_flag, ':'); return (colon == nullptr) ? std::string(gtest_output_flag) : std::string(gtest_output_flag, static_cast<size_t>(colon - gtest_output_flag)); } #if GTEST_HAS_FILE_SYSTEM std::string UnitTestOptions::GetAbsolutePathToOutputFile() { std::string s = GTEST_FLAG_GET(output); const char* const gtest_output_flag = s.c_str(); std::string format = GetOutputFormat(); if (format.empty()) format = std::string(kDefaultOutputFormat); const char* const colon = strchr(gtest_output_flag, ':'); if (colon == nullptr) return internal::FilePath::MakeFileName( internal::FilePath( UnitTest::GetInstance()->original_working_dir()), internal::FilePath(kDefaultOutputFile), 0, format.c_str()) .string(); internal::FilePath output_name(colon + 1); if (!output_name.IsAbsolutePath()) output_name = internal::FilePath::ConcatPaths( internal::FilePath(UnitTest::GetInstance()->original_working_dir()), internal::FilePath(colon + 1)); if (!output_name.IsDirectory()) return output_name.string(); internal::FilePath result(internal::FilePath::GenerateUniqueFileName( output_name, internal::GetCurrentExecutableName(), GetOutputFormat().c_str())); return result.string(); } #endif static bool PatternMatchesString(const std::string& name_str, const char* pattern, const char* pattern_end) { const char* name = name_str.c_str(); const char* const name_begin = name; const char* const name_end = name + name_str.size(); const char* pattern_next = pattern; const char* name_next = name; while (pattern < pattern_end || name < name_end) { if (pattern < pattern_end) { switch (*pattern) { default: if (name < name_end && *name == *pattern) { ++pattern; ++name; continue; } break; case '?': if (name < name_end) { ++pattern; ++name; continue; } break; case '*': pattern_next = pattern; name_next = name + 1; ++pattern; continue; } } if (name_begin < name_next && name_next <= name_end) { pattern = pattern_next; name = name_next; continue; } return false; } return true; } namespace { bool IsGlobPattern(const std::string& pattern) { return std::any_of(pattern.begin(), pattern.end(), [](const char c) { return c == '?' || c == '*'; }); } class UnitTestFilter { public: UnitTestFilter() = default; explicit UnitTestFilter(const std::string& filter) { std::vector<std::string> all_patterns; SplitString(filter, ':', &all_patterns); const auto exact_match_patterns_begin = std::partition( all_patterns.begin(), all_patterns.end(), &IsGlobPattern); glob_patterns_.reserve(static_cast<size_t>( std::distance(all_patterns.begin(), exact_match_patterns_begin))); std::move(all_patterns.begin(), exact_match_patterns_begin, std::inserter(glob_patterns_, glob_patterns_.begin())); std::move( exact_match_patterns_begin, all_patterns.end(), std::inserter(exact_match_patterns_, exact_match_patterns_.begin())); } bool MatchesName(const std::string& name) const { return exact_match_patterns_.find(name) != exact_match_patterns_.end() || std::any_of(glob_patterns_.begin(), glob_patterns_.end(), [&name](const std::string& pattern) { return PatternMatchesString( name, pattern.c_str(), pattern.c_str() + pattern.size()); }); } private: std::vector<std::string> glob_patterns_; std::unordered_set<std::string> exact_match_patterns_; }; class PositiveAndNegativeUnitTestFilter { public: explicit PositiveAndNegativeUnitTestFilter(const std::string& filter) { std::vector<std::string> positive_and_negative_filters; SplitString(filter, '-', &positive_and_negative_filters); const auto& positive_filter = positive_and_negative_filters.front(); if (positive_and_negative_filters.size() > 1) { positive_filter_ = UnitTestFilter( positive_filter.empty() ? kUniversalFilter : positive_filter);
#include "gtest/gtest.h" TEST(CommandLineFlagsTest, CanBeAccessedInCodeOnceGTestHIsIncluded) { bool dummy = GTEST_FLAG_GET(also_run_disabled_tests) || GTEST_FLAG_GET(break_on_failure) || GTEST_FLAG_GET(catch_exceptions) || GTEST_FLAG_GET(color) != "unknown" || GTEST_FLAG_GET(fail_fast) || GTEST_FLAG_GET(filter) != "unknown" || GTEST_FLAG_GET(list_tests) || GTEST_FLAG_GET(output) != "unknown" || GTEST_FLAG_GET(brief) || GTEST_FLAG_GET(print_time) || GTEST_FLAG_GET(random_seed) || GTEST_FLAG_GET(repeat) > 0 || GTEST_FLAG_GET(recreate_environments_when_repeating) || GTEST_FLAG_GET(show_internal_stack_frames) || GTEST_FLAG_GET(shuffle) || GTEST_FLAG_GET(stack_trace_depth) > 0 || GTEST_FLAG_GET(stream_result_to) != "unknown" || GTEST_FLAG_GET(throw_on_failure); EXPECT_TRUE(dummy || !dummy); } #include <limits.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <cstdint> #include <map> #include <memory> #include <ostream> #include <set> #include <stdexcept> #include <string> #include <type_traits> #include <unordered_set> #include <utility> #include <vector> #include "gtest/gtest-spi.h" #include "src/gtest-internal-inl.h" struct ConvertibleGlobalType { template < class T, std::enable_if_t< false, std::enable_if_t<std::is_constructible<T>::value, int>> = 0> operator T() const; }; void operator<<(ConvertibleGlobalType&, int); static_assert(sizeof(decltype(std::declval<ConvertibleGlobalType&>() << 1)(*)()) > 0, "error in operator<< overload resolution"); namespace testing { namespace internal { #if GTEST_CAN_STREAM_RESULTS_ class StreamingListenerTest : public Test { public: class FakeSocketWriter : public StreamingListener::AbstractSocketWriter { public: void Send(const std::string& message) override { output_ += message; } std::string output_; }; StreamingListenerTest() : fake_sock_writer_(new FakeSocketWriter), streamer_(fake_sock_writer_), test_info_obj_("FooTest", "Bar", nullptr, nullptr, CodeLocation(__FILE__, __LINE__), nullptr, nullptr) {} protected: std::string* output() { return &(fake_sock_writer_->output_); } FakeSocketWriter* const fake_sock_writer_; StreamingListener streamer_; UnitTest unit_test_; TestInfo test_info_obj_; }; TEST_F(StreamingListenerTest, OnTestProgramEnd) { *output() = ""; streamer_.OnTestProgramEnd(unit_test_); EXPECT_EQ("event=TestProgramEnd&passed=1\n", *output()); } TEST_F(StreamingListenerTest, OnTestIterationEnd) { *output() = ""; streamer_.OnTestIterationEnd(unit_test_, 42); EXPECT_EQ("event=TestIterationEnd&passed=1&elapsed_time=0ms\n", *output()); } TEST_F(StreamingListenerTest, OnTestSuiteStart) { *output() = ""; streamer_.OnTestSuiteStart(TestSuite("FooTest", "Bar", nullptr, nullptr)); EXPECT_EQ("event=TestCaseStart&name=FooTest\n", *output()); } TEST_F(StreamingListenerTest, OnTestSuiteEnd) { *output() = ""; streamer_.OnTestSuiteEnd(TestSuite("FooTest", "Bar", nullptr, nullptr)); EXPECT_EQ("event=TestCaseEnd&passed=1&elapsed_time=0ms\n", *output()); } TEST_F(StreamingListenerTest, OnTestStart) { *output() = ""; streamer_.OnTestStart(test_info_obj_); EXPECT_EQ("event=TestStart&name=Bar\n", *output()); } TEST_F(StreamingListenerTest, OnTestEnd) { *output() = ""; streamer_.OnTestEnd(test_info_obj_); EXPECT_EQ("event=TestEnd&passed=1&elapsed_time=0ms\n", *output()); } TEST_F(StreamingListenerTest, OnTestPartResult) { *output() = ""; streamer_.OnTestPartResult(TestPartResult(TestPartResult::kFatalFailure, "foo.cc", 42, "failed=\n&%")); EXPECT_EQ( "event=TestPartResult&file=foo.cc&line=42&message=failed%3D%0A%26%25\n", *output()); } #endif class TestEventListenersAccessor { public: static TestEventListener* GetRepeater(TestEventListeners* listeners) { return listeners->repeater(); } static void SetDefaultResultPrinter(TestEventListeners* listeners, TestEventListener* listener) { listeners->SetDefaultResultPrinter(listener); } static void SetDefaultXmlGenerator(TestEventListeners* listeners, TestEventListener* listener) { listeners->SetDefaultXmlGenerator(listener); } static bool EventForwardingEnabled(const TestEventListeners& listeners) { return listeners.EventForwardingEnabled(); } static void SuppressEventForwarding(TestEventListeners* listeners) { listeners->SuppressEventForwarding(true); } }; class UnitTestRecordPropertyTestHelper : public Test { protected: UnitTestRecordPropertyTestHelper() {} void UnitTestRecordProperty(const char* key, const std::string& value) { unit_test_.RecordProperty(key, value); } UnitTest unit_test_; }; } } using testing::AssertionFailure; using testing::AssertionResult; using testing::AssertionSuccess; using testing::DoubleLE; using testing::EmptyTestEventListener; using testing::Environment; using testing::FloatLE; using testing::IsNotSubstring; using testing::IsSubstring; using testing::kMaxStackTraceDepth; using testing::Message; using testing::ScopedFakeTestPartResultReporter; using testing::StaticAssertTypeEq; using testing::Test; using testing::TestEventListeners; using testing::TestInfo; using testing::TestPartResult; using testing::TestPartResultArray; using testing::TestProperty; using testing::TestResult; using testing::TimeInMillis; using testing::UnitTest; using testing::internal::AlwaysFalse; using testing::internal::AlwaysTrue; using testing::internal::AppendUserMessage; using testing::internal::ArrayAwareFind; using testing::internal::ArrayEq; using testing::internal::CodePointToUtf8; using testing::internal::CopyArray; using testing::internal::CountIf; using testing::internal::EqFailure; using testing::internal::FloatingPoint; using testing::internal::ForEach; using testing::internal::FormatEpochTimeInMillisAsIso8601; using testing::internal::FormatTimeInMillisAsSeconds; using testing::internal::GetElementOr; using testing::internal::GetNextRandomSeed; using testing::internal::GetRandomSeedFromFlag; using testing::internal::GetTestTypeId; using testing::internal::GetTimeInMillis; using testing::internal::GetTypeId; using testing::internal::GetUnitTestImpl; using testing::internal::GTestFlagSaver; using testing::internal::HasDebugStringAndShortDebugString; using testing::internal::Int32FromEnvOrDie; using testing::internal::IsContainer; using testing::internal::IsContainerTest; using testing::internal::IsNotContainer; using testing::internal::kMaxRandomSeed; using testing::internal::kTestTypeIdInGoogleTest; using testing::internal::NativeArray; using testing::internal::ParseFlag; using testing::internal::RelationToSourceCopy; using testing::internal::RelationToSourceReference; using testing::internal::ShouldRunTestOnShard; using testing::internal::ShouldShard; using testing::internal::ShouldUseColor; using testing::internal::Shuffle; using testing::internal::ShuffleRange; using testing::internal::SkipPrefix; using testing::internal::StreamableToString; using testing::internal::String; using testing::internal::TestEventListenersAccessor; using testing::internal::TestResultAccessor; using testing::internal::WideStringToUtf8; using testing::internal::edit_distance::CalculateOptimalEdits; using testing::internal::edit_distance::CreateUnifiedDiff; using testing::internal::edit_distance::EditType; #if GTEST_HAS_STREAM_REDIRECTION using testing::internal::CaptureStdout; using testing::internal::GetCapturedStdout; #endif #ifdef GTEST_IS_THREADSAFE using testing::internal::ThreadWithParam; #endif class TestingVector : public std::vector<int> {}; ::std::ostream& operator<<(::std::ostream& os, const TestingVector& vector) { os << "{ "; for (size_t i = 0; i < vector.size(); i++) { os << vector[i] << " "; } os << "}"; return os; } namespace { TEST(GetRandomSeedFromFlagTest, HandlesZero) { const int seed = GetRandomSeedFromFlag(0); EXPECT_LE(1, seed); EXPECT_LE(seed, static_cast<int>(kMaxRandomSeed)); } TEST(GetRandomSeedFromFlagTest, PreservesValidSeed) { EXPECT_EQ(1, GetRandomSeedFromFlag(1)); EXPECT_EQ(2, GetRandomSeedFromFlag(2)); EXPECT_EQ(kMaxRandomSeed - 1, GetRandomSeedFromFlag(kMaxRandomSeed - 1)); EXPECT_EQ(static_cast<int>(kMaxRandomSeed), GetRandomSeedFromFlag(kMaxRandomSeed)); } TEST(GetRandomSeedFromFlagTest, NormalizesInvalidSeed) { const int seed1 = GetRandomSeedFromFlag(-1); EXPECT_LE(1, seed1); EXPECT_LE(seed1, static_cast<int>(kMaxRandomSeed)); const int seed2 = GetRandomSeedFromFlag(kMaxRandomSeed + 1); EXPECT_LE(1, seed2); EXPECT_LE(seed2, static_cast<int>(kMaxRandomSeed)); } TEST(GetNextRandomSeedTest, WorksForValidInput) { EXPECT_EQ(2, GetNextRandomSeed(1)); EXPECT_EQ(3, GetNextRandomSeed(2)); EXPECT_EQ(static_cast<int>(kMaxRandomSeed), GetNextRandomSeed(kMaxRandomSeed - 1)); EXPECT_EQ(1, GetNextRandomSeed(kMaxRandomSeed)); } static void ClearCurrentTestPartResults() { TestResultAccessor::ClearTestPartResults( GetUnitTestImpl()->current_test_result()); } TEST(GetTypeIdTest, ReturnsSameValueForSameType) { EXPECT_EQ(GetTypeId<int>(), GetTypeId<int>()); EXPECT_EQ(GetTypeId<Test>(), GetTypeId<Test>()); } class SubClassOfTest : public Test {}; class AnotherSubClassOfTest : public Test {}; TEST(GetTypeIdTest, ReturnsDifferentValuesForDifferentTypes) { EXPECT_NE(GetTypeId<int>(), GetTypeId<const int>()); EXPECT_NE(GetTypeId<int>(), GetTypeId<char>()); EXPECT_NE(GetTypeId<int>(), GetTestTypeId()); EXPECT_NE(GetTypeId<SubClassOfTest>(), GetTestTypeId()); EXPECT_NE(GetTypeId<AnotherSubClassOfTest>(), GetTestTypeId()); EXPECT_NE(GetTypeId<AnotherSubClassOfTest>(), GetTypeId<SubClassOfTest>()); } TEST(GetTestTypeIdTest, ReturnsTheSameValueInsideOrOutsideOfGoogleTest) { EXPECT_EQ(kTestTypeIdInGoogleTest, GetTestTypeId()); } using ::testing::internal::CanonicalizeForStdLibVersioning; TEST(CanonicalizeForStdLibVersioning, LeavesUnversionedNamesUnchanged) { EXPECT_EQ("std::bind", CanonicalizeForStdLibVersioning("std::bind")); EXPECT_EQ("std::_", CanonicalizeForStdLibVersioning("std::_")); EXPECT_EQ("std::__foo", CanonicalizeForStdLibVersioning("std::__foo")); EXPECT_EQ("gtl::__1::x", CanonicalizeForStdLibVersioning("gtl::__1::x")); EXPECT_EQ("__1::x", CanonicalizeForStdLibVersioning("__1::x")); EXPECT_EQ("::__1::x", CanonicalizeForStdLibVersioning("::__1::x")); } TEST(CanonicalizeForStdLibVersioning, ElidesDoubleUnderNames) { EXPECT_EQ("std::bind", CanonicalizeForStdLibVersioning("std::__1::bind")); EXPECT_EQ("std::_", CanonicalizeForStdLibVersioning("std::__1::_")); EXPECT_EQ("std::bind", CanonicalizeForStdLibVersioning("std::__g::bind")); EXPECT_EQ("std::_", CanonicalizeForStdLibVersioning("std::__g::_")); EXPECT_EQ("std::bind", CanonicalizeForStdLibVersioning("std::__google::bind")); EXPECT_EQ("std::_", CanonicalizeForStdLibVersioning("std::__google::_")); } TEST(FormatTimeInMillisAsSecondsTest, FormatsZero) { EXPECT_EQ("0.", FormatTimeInMillisAsSeconds(0)); } TEST(FormatTimeInMillisAsSecondsTest, FormatsPositiveNumber) { EXPECT_EQ("0.003", FormatTimeInMillisAsSeconds(3)); EXPECT_EQ("0.01", FormatTimeInMillisAsSeconds(10)); EXPECT_EQ("0.2", FormatTimeInMillisAsSeconds(200)); EXPECT_EQ("1.2", FormatTimeInMillisAsSeconds(1200)); EXPECT_EQ("3.", FormatTimeInMillisAsSeconds(3000)); EXPECT_EQ("10.", FormatTimeInMillisAsSeconds(10000)); EXPECT_EQ("100.", FormatTimeInMillisAsSeconds(100000)); EXPECT_EQ("123.456", FormatTimeInMillisAsSeconds(123456)); EXPECT_EQ("1234567.89", FormatTimeInMillisAsSeconds(1234567890)); } TEST(FormatTimeInMillisAsSecondsTest, FormatsNegativeNumber) { EXPECT_EQ("-0.003", FormatTimeInMillisAsSeconds(-3)); EXPECT_EQ("-0.01", FormatTimeInMillisAsSeconds(-10)); EXPECT_EQ("-0.2", FormatTimeInMillisAsSeconds(-200)); EXPECT_EQ("-1.2", FormatTimeInMillisAsSeconds(-1200)); EXPECT_EQ("-3.", FormatTimeInMillisAsSeconds(-3000)); EXPECT_EQ("-10.", FormatTimeInMillisAsSeconds(-10000)); EXPECT_EQ("-100.", FormatTimeInMillisAsSeconds(-100000)); EXPECT_EQ("-123.456", FormatTimeInMillisAsSeconds(-123456)); EXPECT_EQ("-1234567.89", FormatTimeInMillisAsSeconds(-1234567890)); } #if !defined(__EMSCRIPTEN__) class FormatEpochTimeInMillisAsIso8601Test : public Test { public: static const TimeInMillis kMillisPerSec = 1000; private: void SetUp() override { saved_tz_.reset(); GTEST_DISABLE_MSC_DEPRECATED_PUSH_() if (const char* tz = getenv("TZ")) { saved_tz_ = std::make_unique<std::string>(tz); } GTEST_DISABLE_MSC_DEPRECATED_POP_() SetTimeZone("UTC+00"); } void TearDown() override { SetTimeZone(saved_tz_ != nullptr ? saved_tz_->c_str() : nullptr); saved_tz_.reset(); } static void SetTimeZone(const char* time_zone) { #if defined(_MSC_VER) || defined(GTEST_OS_WINDOWS_MINGW) const std::string env_var = std::string("TZ=") + (time_zone ? time_zone : ""); _putenv(env_var.c_str()); GTEST_DISABLE_MSC_WARNINGS_PUSH_(4996 ) tzset(); GTEST_DISABLE_MSC_WARNINGS_POP_() #else #if defined(GTEST_OS_LINUX_ANDROID) && __ANDROID_API__ < 21 setenv("TZ", "UTC", 1); tzset(); #endif if (time_zone) { setenv(("TZ"), time_zone, 1); } else { unsetenv("TZ"); } tzset(); #endif } std::unique_ptr<std::string> saved_tz_; }; const TimeInMillis FormatEpochTimeInMillisAsIso8601Test::kMillisPerSec; TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsTwoDigitSegments) { EXPECT_EQ("2011-10-31T18:52:42.000", FormatEpochTimeInMillisAsIso8601(1320087162 * kMillisPerSec)); } TEST_F(FormatEpochTimeInMillisAsIso8601Test, IncludesMillisecondsAfterDot) { EXPECT_EQ("2011-10-31T18:52:42.234", FormatEpochTimeInMillisAsIso8601(1320087162 * kMillisPerSec + 234)); } TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsLeadingZeroes) { EXPECT_EQ("2011-09-03T05:07:02.000", FormatEpochTimeInMillisAsIso8601(1315026422 * kMillisPerSec)); } TEST_F(FormatEpochTimeInMillisAsIso8601Test, Prints24HourTime) { EXPECT_EQ("2011-09-28T17:08:22.000", FormatEpochTimeInMillisAsIso8601(1317229702 * kMillisPerSec)); } TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsEpochStart) { EXPECT_EQ("1970-01-01T00:00:00.000", FormatEpochTimeInMillisAsIso8601(0)); } #endif #ifdef __BORLANDC__ #pragma option push -w-ccc -w-rch #endif TEST(NullLiteralTest, LHSAllowsNullLiterals) { EXPECT_EQ(0, static_cast<void*>(nullptr)); ASSERT_EQ(0, static_cast<void*>(nullptr)); EXPECT_EQ(NULL, static_cast<void*>(nullptr)); ASSERT_EQ(NULL, static_cast<void*>(nullptr)); EXPECT_EQ(nullptr, static_cast<void*>(nullptr)); ASSERT_EQ(nullptr, static_cast<void*>(nullptr)); const int* const p = nullptr; EXPECT_EQ(0, p); ASSERT_EQ(0, p); EXPECT_EQ(NULL, p); ASSERT_EQ(NULL, p); EXPECT_EQ(nullptr, p); ASSERT_EQ(nullptr, p); } struct ConvertToAll { template <typename T> operator T() const { return T(); } }; struct ConvertToPointer { template <class T> operator T*() const { return nullptr; } }; struct ConvertToAllButNoPointers { template <typename T, typename std::enable_if<!std::is_pointer<T>::value, int>::type = 0> operator T() const { return T(); } }; struct MyType {}; inline bool operator==(MyType const&, MyType const&) { return true; } TEST(NullLiteralTest, ImplicitConversion) { EXPECT_EQ(ConvertToPointer{}, static_cast<void*>(nullptr)); #if !defined(__GNUC__) || defined(__clang__) EXPECT_EQ(ConvertToAll{}, static_cast<void*>(nullptr)); #endif EXPECT_EQ(ConvertToAll{}, MyType{}); EXPECT_EQ(ConvertToAllButNoPointers{}, MyType{}); } #ifdef __clang__ #pragma clang diagnostic push #if __has_warning("-Wzero-as-null-pointer-constant") #pragma clang diagnostic error "-Wzero-as-null-pointer-constant" #endif #endif TEST(NullLiteralTest, NoConversionNoWarning) { EXPECT_EQ(0, 0); ASSERT_EQ(0, 0); } #ifdef __clang__ #pragma clang diagnostic pop #endif #ifdef __BORLANDC__ #pragma option pop #endif TEST(CodePointToUtf8Test, CanEncodeNul) { EXPECT_EQ("", CodePointToUtf8(L'\0')); } TEST(CodePointToUtf8Test, CanEncodeAscii) { EXPECT_EQ("a", CodePointToUtf8(L'a')); EXPECT_EQ("Z", CodePointToUtf8(L'Z')); EXPECT_EQ("&", CodePointToUtf8(L'&')); EXPECT_EQ("\x7F", CodePointToUtf8(L'\x7F')); } TEST(CodePointToUtf8Test, CanEncode8To11Bits) { EXPECT_EQ("\xC3\x93", CodePointToUtf8(L'\xD3')); EXPECT_EQ("\xD5\xB6", CodePointToUtf8(static_cast<wchar_t>(0x576))); } TEST(CodePointToUtf8Test, CanEncode12To16Bits) { EXPECT_EQ("\xE0\xA3\x93", CodePointToUtf8(static_cast<wchar_t>(0x8D3))); EXPECT_EQ("\xEC\x9D\x8D", CodePointToUtf8(static_cast<wchar_t>(0xC74D))); } #if !GTEST_WIDE_STRING_USES_UTF16_ TEST(CodePointToUtf8Test, CanEncode17To21Bits) { EXPECT_EQ("\xF0\x90\xA3\x93", CodePointToUtf8(L'\x108D3')); EXPECT_EQ("\xF0\x90\x90\x80", CodePointToUtf8(L'\x10400')); EXPECT_EQ("\xF4\x88\x98\xB4", CodePointToUtf8(L'\x108634')); } TEST(CodePointToUtf8Test, CanEncodeInvalidCodePoint) { EXPECT_EQ("(Invalid Unicode 0x1234ABCD)", CodePointToUtf8(L'\x1234ABCD')); } #endif TEST(WideStringToUtf8Test, CanEncodeNul) { EXPECT_STREQ("", WideStringToUtf8(L"", 0).c_str()); EXPECT_STREQ("", WideStringToUtf8(L"", -1).c_str()); } TEST(WideStringToUtf8Test, CanEncodeAscii) { EXPECT_STREQ("a", WideStringToUtf8(L"a", 1).c_str()); EXPECT_STREQ("ab", WideStringToUtf8(L"ab", 2).c_str()); EXPECT_STREQ("a", WideStringToUtf8(L"a", -1).c_str()); EXPECT_STREQ("ab", WideStringToUtf8(L"ab", -1).c_str()); } TEST(WideStringToUtf8Test, CanEncode8To11Bits) { EXPECT_STREQ("\xC3\x93", WideStringToUtf8(L"\xD3", 1).c_str()); EXPECT_STREQ("\xC3\x93", WideStringToUtf8(L"\xD3", -1).c_str()); const wchar_t s[] = {0x576, '\0'}; EXPECT_STREQ("\xD5\xB6", WideStringToUtf8(s, 1).c_str()); EXPECT_STREQ("\xD5\xB6", WideStringToUtf8(s, -1).c_str()); } TEST(WideStringToUtf8Test, CanEncode12To16Bits) { const wchar_t s1[] = {0x8D3, '\0'}; EXPECT_STREQ("\xE0\xA3\x93", WideStringToUtf8(s1, 1).c_str()); EXPECT_STREQ("\xE0\xA3\x93", WideStringToUtf8(s1, -1).c_str()); const wchar_t s2[] = {0xC74D, '\0'}; EXPECT_STREQ("\xEC\x9D\x8D", WideStringToUtf8(s2, 1).c_str()); EXPECT_STREQ("\xEC\x9D\x8D", WideStringToUtf8(s2, -1).c_str()); } TEST(WideStringToUtf8Test, StopsOnNulCharacter) { EXPECT_STREQ("ABC", WideStringToUtf8(L"ABC\0XYZ", 100).c_str()); } TEST(WideStringToUtf8Test, StopsWhenLengthLimitReached) { EXPECT_STREQ("ABC", WideStringToUtf8(L"ABCDEF", 3).c_str()); } #if !GTEST_WIDE_STRING_USES_UTF16_ TEST(WideStringToUtf8Test, CanEncode17To21Bits) { EXPECT_STREQ("\xF0\x90\xA3\x93", WideStringToUtf8(L"\x108D3", 1).c_str()); EXPECT_STREQ("\xF0\x90\xA3\x93", WideStringToUtf8(L"\x108D3", -1).c_str()); EXPECT_STREQ("\xF4\x88\x98\xB4", WideStringToUtf8(L"\x108634", 1).c_str()); EXPECT_STREQ("\xF4\x88\x98\xB4", WideStringToUtf8(L"\x108634", -1).c_str()); } TEST(WideStringToUtf8Test, CanEncodeInvalidCodePoint) { EXPECT_STREQ("(Invalid Unicode 0xABCDFF)", WideStringToUtf8(L"\xABCDFF", -1).c_str()); } #else TEST(WideStringToUtf8Test, CanEncodeValidUtf16SUrrogatePairs) { const wchar_t s[] = {0xD801, 0xDC00, '\0'}; EXPECT_STREQ("\xF0\x90\x90\x80", WideStringToUtf8(s, -1).c_str()); } TEST(WideStringToUtf8Test, CanEncodeInvalidUtf16SurrogatePair) { const wchar_t s1[] = {0xD800, '\0'}; EXPECT_STREQ("\xED\xA0\x80", WideStringToUtf8(s1, -1).c_str()); const wchar_t s2[] = {0xD800, 'M', '\0'}; EXPECT_STREQ("\xED\xA0\x80M", WideStringToUtf8(s2, -1).c_str()); const wchar_t s3[] = {0xDC00, 'P', 'Q', 'R', '\0'}; EXPECT_STREQ("\xED\xB0\x80PQR", WideStringToUtf8(s3, -1).c_str()); } #endif #if !GTEST_WIDE_STRING_USES_UTF16_ TEST(WideStringToUtf8Test, ConcatenatesCodepointsCorrectly) { const wchar_t s[] = {0x108634, 0xC74D, '\n', 0x576, 0x8D3, 0x108634, '\0'}; EXPECT_STREQ( "\xF4\x88\x98\xB4" "\xEC\x9D\x8D" "\n" "\xD5\xB6" "\xE0\xA3\x93" "\xF4\x88\x98\xB4", WideStringToUtf8(s, -1).c_str()); } #else TEST(WideStringToUtf8Test, ConcatenatesCodepointsCorrectly) { const wchar_t s[] = {0xC74D, '\n', 0x576, 0x8D3, '\0'}; EXPECT_STREQ( "\xEC\x9D\x8D" "\n" "\xD5\xB6" "\xE0\xA3\x93", WideStringToUtf8(s, -1).c_str()); } #endif TEST(RandomDeathTest, GeneratesCrashesOnInvalidRange) { testing::internal::Random random(42); EXPECT_DEATH_IF_SUPPORTED(random.Generate(0), "Cannot generate a number in the range \\[0, 0\\)"); EXPECT_DEATH_IF_SUPPORTED( random.Generate(testing::internal::Random::kMaxRange + 1), "Generation of a number in \\[0, 2147483649\\) was requested, " "but this can only generate numbers in \\[0, 2147483648\\)"); } TEST(RandomTest, GeneratesNumbersWithinRange) { constexpr uint32_t kRange = 10000; testing::internal::Random random(12345); for (int i = 0; i < 10; i++) { EXPECT_LT(random.Generate(kRange), kRange) << " for iteration " << i; } testing::internal::Random random2(testing::internal::Random::kMaxRange); for (int i = 0; i < 10; i++) { EXPECT_LT(random2.Generate(kRange), kRange) << " for iteration " << i; } } TEST(RandomTest, RepeatsWhenReseeded) { constexpr int kSeed = 123; constexpr int kArraySize = 10; constexpr uint32_t kRange = 10000; uint32_t values[kArraySize]; testing::internal::Random random(kSeed); for (int i = 0; i < kArraySize; i++) { values[i] = random.Generate(kRange); } random.Reseed(kSeed); for (int i = 0; i < kArraySize; i++) { EXPECT_EQ(values[i], random.Generate(kRange)) << " for iteration " << i; } } static bool IsPositive(int n) { return n > 0; } TEST(ContainerUtilityTest, CountIf) { std::vector<int> v; EXPECT_EQ(0, CountIf(v, IsPositive)); v.push_back(-1); v.push_back(0); EXPECT_EQ(0, CountIf(v, IsPositive)); v.push_back(2); v.push_back(-10); v.push_back(10); EXPECT_EQ(2, CountIf(v, IsPositive)); } static int g_sum = 0; static void Accumulate(int n) { g_sum += n; } TEST(ContainerUtilityTest, ForEach) { std::vector<int> v; g_sum = 0; ForEach(v, Accumulate); EXPECT_EQ(0, g_sum); g_sum = 0; v.push_back(1); ForEach(v, Accumulate); EXPECT_EQ(1, g_sum); g_sum = 0; v.push_back(20); v.push_back(300); ForEach(v, Accumulate); EXPECT_EQ(321, g_sum); } TEST(ContainerUtilityTest, GetElementOr) { std::vector<char> a; EXPECT_EQ('x', GetElementOr(a, 0, 'x')); a.push_back('a'); a.push_back('b'); EXPECT_EQ('a', GetElementOr(a, 0, 'x')); EXPECT_EQ('b', GetElementOr(a, 1, 'x')); EXPECT_EQ('x', GetElementOr(a, -2, 'x')); EXPECT_EQ('x', GetElementOr(a, 2, 'x')); } TEST(ContainerUtilityDeathTest, ShuffleRange) { std::vector<int> a; a.push_back(0); a.push_back(1); a.push_back(2); testing::internal::Random random(1); EXPECT_DEATH_IF_SUPPORTED( ShuffleRange(&random, -1, 1, &a), "Invalid shuffle range start -1: must be in range \\[0, 3\\]"); EXPECT_DEATH_IF_SUPPORTED( ShuffleRange(&random, 4, 4, &a), "Invalid shuffle range start 4: must be in range \\[0, 3\\]"); EXPECT_DEATH_IF_SUPPORTED( ShuffleRange(&random, 3, 2, &a), "Invalid shuffle range finish 2: must be in range \\[3, 3\\]"); EXPECT_DEATH_IF_SUPPORTED( ShuffleRange(&random, 3, 4, &a), "Invalid shuffle range finish 4: must be in range \\[3, 3\\]"); } class VectorShuffleTest : public Test { protected: static const size_t kVectorSize = 20; VectorShuffleTest() : random_(1) { for (int i = 0; i < static_cast<int>(kVectorSize); i++) { vector_.push_back(i); } } static bool VectorIsCorrupt(const TestingVector& vector) { if (kVectorSize != vector.size()) { return true; } bool found_in_vector[kVectorSize] = {false}; for (size_t i = 0; i < vector.size(); i++) { const int e = vector[i]; if (e < 0 || e >= static_cast<int>(kVectorSize) || found_in_vector[e]) { return true; } found_in_vector[e] = true; } return false; } static bool VectorIsNo
2,327
cpp
google/googletest
gmock-cardinalities
googlemock/src/gmock-cardinalities.cc
googlemock/test/gmock-cardinalities_test.cc
#ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_ #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_ #include <limits.h> #include <memory> #include <ostream> #include "gmock/internal/gmock-port.h" #include "gtest/gtest.h" GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \ ) namespace testing { class CardinalityInterface { public: virtual ~CardinalityInterface() = default; virtual int ConservativeLowerBound() const { return 0; } virtual int ConservativeUpperBound() const { return INT_MAX; } virtual bool IsSatisfiedByCallCount(int call_count) const = 0; virtual bool IsSaturatedByCallCount(int call_count) const = 0; virtual void DescribeTo(::std::ostream* os) const = 0; }; class GTEST_API_ Cardinality { public: Cardinality() = default; explicit Cardinality(const CardinalityInterface* impl) : impl_(impl) {} int ConservativeLowerBound() const { return impl_->ConservativeLowerBound(); } int ConservativeUpperBound() const { return impl_->ConservativeUpperBound(); } bool IsSatisfiedByCallCount(int call_count) const { return impl_->IsSatisfiedByCallCount(call_count); } bool IsSaturatedByCallCount(int call_count) const { return impl_->IsSaturatedByCallCount(call_count); } bool IsOverSaturatedByCallCount(int call_count) const { return impl_->IsSaturatedByCallCount(call_count) && !impl_->IsSatisfiedByCallCount(call_count); } void DescribeTo(::std::ostream* os) const { impl_->DescribeTo(os); } static void DescribeActualCallCountTo(int actual_call_count, ::std::ostream* os); private: std::shared_ptr<const CardinalityInterface> impl_; }; GTEST_API_ Cardinality AtLeast(int n); GTEST_API_ Cardinality AtMost(int n); GTEST_API_ Cardinality AnyNumber(); GTEST_API_ Cardinality Between(int min, int max); GTEST_API_ Cardinality Exactly(int n); inline Cardinality MakeCardinality(const CardinalityInterface* c) { return Cardinality(c); } } GTEST_DISABLE_MSC_WARNINGS_POP_() #endif #include "gmock/gmock-cardinalities.h" #include <limits.h> #include <ostream> #include <sstream> #include <string> #include "gmock/internal/gmock-internal-utils.h" #include "gtest/gtest.h" namespace testing { namespace { class BetweenCardinalityImpl : public CardinalityInterface { public: BetweenCardinalityImpl(int min, int max) : min_(min >= 0 ? min : 0), max_(max >= min_ ? max : min_) { std::stringstream ss; if (min < 0) { ss << "The invocation lower bound must be >= 0, " << "but is actually " << min << "."; internal::Expect(false, __FILE__, __LINE__, ss.str()); } else if (max < 0) { ss << "The invocation upper bound must be >= 0, " << "but is actually " << max << "."; internal::Expect(false, __FILE__, __LINE__, ss.str()); } else if (min > max) { ss << "The invocation upper bound (" << max << ") must be >= the invocation lower bound (" << min << ")."; internal::Expect(false, __FILE__, __LINE__, ss.str()); } } int ConservativeLowerBound() const override { return min_; } int ConservativeUpperBound() const override { return max_; } bool IsSatisfiedByCallCount(int call_count) const override { return min_ <= call_count && call_count <= max_; } bool IsSaturatedByCallCount(int call_count) const override { return call_count >= max_; } void DescribeTo(::std::ostream* os) const override; private: const int min_; const int max_; BetweenCardinalityImpl(const BetweenCardinalityImpl&) = delete; BetweenCardinalityImpl& operator=(const BetweenCardinalityImpl&) = delete; }; inline std::string FormatTimes(int n) { if (n == 1) { return "once"; } else if (n == 2) { return "twice"; } else { std::stringstream ss; ss << n << " times"; return ss.str(); } } void BetweenCardinalityImpl::DescribeTo(::std::ostream* os) const { if (min_ == 0) { if (max_ == 0) { *os << "never called"; } else if (max_ == INT_MAX) { *os << "called any number of times"; } else { *os << "called at most " << FormatTimes(max_); } } else if (min_ == max_) { *os << "called " << FormatTimes(min_); } else if (max_ == INT_MAX) { *os << "called at least " << FormatTimes(min_); } else { *os << "called between " << min_ << " and " << max_ << " times"; } } } void Cardinality::DescribeActualCallCountTo(int actual_call_count, ::std::ostream* os) { if (actual_call_count > 0) { *os << "called " << FormatTimes(actual_call_count); } else { *os << "never called"; } } GTEST_API_ Cardinality AtLeast(int n) { return Between(n, INT_MAX); } GTEST_API_ Cardinality AtMost(int n) { return Between(0, n); } GTEST_API_ Cardinality AnyNumber() { return AtLeast(0); } GTEST_API_ Cardinality Between(int min, int max) { return Cardinality(new BetweenCardinalityImpl(min, max)); } GTEST_API_ Cardinality Exactly(int n) { return Between(n, n); } }
#include <ostream> #include "gmock/gmock.h" #include "gtest/gtest-spi.h" #include "gtest/gtest.h" namespace { using std::stringstream; using testing::AnyNumber; using testing::AtLeast; using testing::AtMost; using testing::Between; using testing::Cardinality; using testing::CardinalityInterface; using testing::Exactly; using testing::IsSubstring; using testing::MakeCardinality; class MockFoo { public: MockFoo() = default; MOCK_METHOD0(Bar, int()); private: MockFoo(const MockFoo&) = delete; MockFoo& operator=(const MockFoo&) = delete; }; TEST(CardinalityTest, IsDefaultConstructable) { Cardinality c; } TEST(CardinalityTest, IsCopyable) { Cardinality c = Exactly(1); EXPECT_FALSE(c.IsSatisfiedByCallCount(0)); EXPECT_TRUE(c.IsSatisfiedByCallCount(1)); EXPECT_TRUE(c.IsSaturatedByCallCount(1)); c = Exactly(2); EXPECT_FALSE(c.IsSatisfiedByCallCount(1)); EXPECT_TRUE(c.IsSatisfiedByCallCount(2)); EXPECT_TRUE(c.IsSaturatedByCallCount(2)); } TEST(CardinalityTest, IsOverSaturatedByCallCountWorks) { const Cardinality c = AtMost(5); EXPECT_FALSE(c.IsOverSaturatedByCallCount(4)); EXPECT_FALSE(c.IsOverSaturatedByCallCount(5)); EXPECT_TRUE(c.IsOverSaturatedByCallCount(6)); } TEST(CardinalityTest, CanDescribeActualCallCount) { stringstream ss0; Cardinality::DescribeActualCallCountTo(0, &ss0); EXPECT_EQ("never called", ss0.str()); stringstream ss1; Cardinality::DescribeActualCallCountTo(1, &ss1); EXPECT_EQ("called once", ss1.str()); stringstream ss2; Cardinality::DescribeActualCallCountTo(2, &ss2); EXPECT_EQ("called twice", ss2.str()); stringstream ss3; Cardinality::DescribeActualCallCountTo(3, &ss3); EXPECT_EQ("called 3 times", ss3.str()); } TEST(AnyNumber, Works) { const Cardinality c = AnyNumber(); EXPECT_TRUE(c.IsSatisfiedByCallCount(0)); EXPECT_FALSE(c.IsSaturatedByCallCount(0)); EXPECT_TRUE(c.IsSatisfiedByCallCount(1)); EXPECT_FALSE(c.IsSaturatedByCallCount(1)); EXPECT_TRUE(c.IsSatisfiedByCallCount(9)); EXPECT_FALSE(c.IsSaturatedByCallCount(9)); stringstream ss; c.DescribeTo(&ss); EXPECT_PRED_FORMAT2(IsSubstring, "called any number of times", ss.str()); } TEST(AnyNumberTest, HasCorrectBounds) { const Cardinality c = AnyNumber(); EXPECT_EQ(0, c.ConservativeLowerBound()); EXPECT_EQ(INT_MAX, c.ConservativeUpperBound()); } TEST(AtLeastTest, OnNegativeNumber) { EXPECT_NONFATAL_FAILURE( { AtLeast(-1); }, "The invocation lower bound must be >= 0"); } TEST(AtLeastTest, OnZero) { const Cardinality c = AtLeast(0); EXPECT_TRUE(c.IsSatisfiedByCallCount(0)); EXPECT_FALSE(c.IsSaturatedByCallCount(0)); EXPECT_TRUE(c.IsSatisfiedByCallCount(1)); EXPECT_FALSE(c.IsSaturatedByCallCount(1)); stringstream ss; c.DescribeTo(&ss); EXPECT_PRED_FORMAT2(IsSubstring, "any number of times", ss.str()); } TEST(AtLeastTest, OnPositiveNumber) { const Cardinality c = AtLeast(2); EXPECT_FALSE(c.IsSatisfiedByCallCount(0)); EXPECT_FALSE(c.IsSaturatedByCallCount(0)); EXPECT_FALSE(c.IsSatisfiedByCallCount(1)); EXPECT_FALSE(c.IsSaturatedByCallCount(1)); EXPECT_TRUE(c.IsSatisfiedByCallCount(2)); EXPECT_FALSE(c.IsSaturatedByCallCount(2)); stringstream ss1; AtLeast(1).DescribeTo(&ss1); EXPECT_PRED_FORMAT2(IsSubstring, "at least once", ss1.str()); stringstream ss2; c.DescribeTo(&ss2); EXPECT_PRED_FORMAT2(IsSubstring, "at least twice", ss2.str()); stringstream ss3; AtLeast(3).DescribeTo(&ss3); EXPECT_PRED_FORMAT2(IsSubstring, "at least 3 times", ss3.str()); } TEST(AtLeastTest, HasCorrectBounds) { const Cardinality c = AtLeast(2); EXPECT_EQ(2, c.ConservativeLowerBound()); EXPECT_EQ(INT_MAX, c.ConservativeUpperBound()); } TEST(AtMostTest, OnNegativeNumber) { EXPECT_NONFATAL_FAILURE( { AtMost(-1); }, "The invocation upper bound must be >= 0"); } TEST(AtMostTest, OnZero) { const Cardinality c = AtMost(0); EXPECT_TRUE(c.IsSatisfiedByCallCount(0)); EXPECT_TRUE(c.IsSaturatedByCallCount(0)); EXPECT_FALSE(c.IsSatisfiedByCallCount(1)); EXPECT_TRUE(c.IsSaturatedByCallCount(1)); stringstream ss; c.DescribeTo(&ss); EXPECT_PRED_FORMAT2(IsSubstring, "never called", ss.str()); } TEST(AtMostTest, OnPositiveNumber) { const Cardinality c = AtMost(2); EXPECT_TRUE(c.IsSatisfiedByCallCount(0)); EXPECT_FALSE(c.IsSaturatedByCallCount(0)); EXPECT_TRUE(c.IsSatisfiedByCallCount(1)); EXPECT_FALSE(c.IsSaturatedByCallCount(1)); EXPECT_TRUE(c.IsSatisfiedByCallCount(2)); EXPECT_TRUE(c.IsSaturatedByCallCount(2)); stringstream ss1; AtMost(1).DescribeTo(&ss1); EXPECT_PRED_FORMAT2(IsSubstring, "called at most once", ss1.str()); stringstream ss2; c.DescribeTo(&ss2); EXPECT_PRED_FORMAT2(IsSubstring, "called at most twice", ss2.str()); stringstream ss3; AtMost(3).DescribeTo(&ss3); EXPECT_PRED_FORMAT2(IsSubstring, "called at most 3 times", ss3.str()); } TEST(AtMostTest, HasCorrectBounds) { const Cardinality c = AtMost(2); EXPECT_EQ(0, c.ConservativeLowerBound()); EXPECT_EQ(2, c.ConservativeUpperBound()); } TEST(BetweenTest, OnNegativeStart) { EXPECT_NONFATAL_FAILURE( { Between(-1, 2); }, "The invocation lower bound must be >= 0, but is actually -1"); } TEST(BetweenTest, OnNegativeEnd) { EXPECT_NONFATAL_FAILURE( { Between(1, -2); }, "The invocation upper bound must be >= 0, but is actually -2"); } TEST(BetweenTest, OnStartBiggerThanEnd) { EXPECT_NONFATAL_FAILURE( { Between(2, 1); }, "The invocation upper bound (1) must be >= " "the invocation lower bound (2)"); } TEST(BetweenTest, OnZeroStartAndZeroEnd) { const Cardinality c = Between(0, 0); EXPECT_TRUE(c.IsSatisfiedByCallCount(0)); EXPECT_TRUE(c.IsSaturatedByCallCount(0)); EXPECT_FALSE(c.IsSatisfiedByCallCount(1)); EXPECT_TRUE(c.IsSaturatedByCallCount(1)); stringstream ss; c.DescribeTo(&ss); EXPECT_PRED_FORMAT2(IsSubstring, "never called", ss.str()); } TEST(BetweenTest, OnZeroStartAndNonZeroEnd) { const Cardinality c = Between(0, 2); EXPECT_TRUE(c.IsSatisfiedByCallCount(0)); EXPECT_FALSE(c.IsSaturatedByCallCount(0)); EXPECT_TRUE(c.IsSatisfiedByCallCount(2)); EXPECT_TRUE(c.IsSaturatedByCallCount(2)); EXPECT_FALSE(c.IsSatisfiedByCallCount(4)); EXPECT_TRUE(c.IsSaturatedByCallCount(4)); stringstream ss; c.DescribeTo(&ss); EXPECT_PRED_FORMAT2(IsSubstring, "called at most twice", ss.str()); } TEST(BetweenTest, OnSameStartAndEnd) { const Cardinality c = Between(3, 3); EXPECT_FALSE(c.IsSatisfiedByCallCount(2)); EXPECT_FALSE(c.IsSaturatedByCallCount(2)); EXPECT_TRUE(c.IsSatisfiedByCallCount(3)); EXPECT_TRUE(c.IsSaturatedByCallCount(3)); EXPECT_FALSE(c.IsSatisfiedByCallCount(4)); EXPECT_TRUE(c.IsSaturatedByCallCount(4)); stringstream ss; c.DescribeTo(&ss); EXPECT_PRED_FORMAT2(IsSubstring, "called 3 times", ss.str()); } TEST(BetweenTest, OnDifferentStartAndEnd) { const Cardinality c = Between(3, 5); EXPECT_FALSE(c.IsSatisfiedByCallCount(2)); EXPECT_FALSE(c.IsSaturatedByCallCount(2)); EXPECT_TRUE(c.IsSatisfiedByCallCount(3)); EXPECT_FALSE(c.IsSaturatedByCallCount(3)); EXPECT_TRUE(c.IsSatisfiedByCallCount(5)); EXPECT_TRUE(c.IsSaturatedByCallCount(5)); EXPECT_FALSE(c.IsSatisfiedByCallCount(6)); EXPECT_TRUE(c.IsSaturatedByCallCount(6)); stringstream ss; c.DescribeTo(&ss); EXPECT_PRED_FORMAT2(IsSubstring, "called between 3 and 5 times", ss.str()); } TEST(BetweenTest, HasCorrectBounds) { const Cardinality c = Between(3, 5); EXPECT_EQ(3, c.ConservativeLowerBound()); EXPECT_EQ(5, c.ConservativeUpperBound()); } TEST(ExactlyTest, OnNegativeNumber) { EXPECT_NONFATAL_FAILURE( { Exactly(-1); }, "The invocation lower bound must be >= 0"); } TEST(ExactlyTest, OnZero) { const Cardinality c = Exactly(0); EXPECT_TRUE(c.IsSatisfiedByCallCount(0)); EXPECT_TRUE(c.IsSaturatedByCallCount(0)); EXPECT_FALSE(c.IsSatisfiedByCallCount(1)); EXPECT_TRUE(c.IsSaturatedByCallCount(1)); stringstream ss; c.DescribeTo(&ss); EXPECT_PRED_FORMAT2(IsSubstring, "never called", ss.str()); } TEST(ExactlyTest, OnPositiveNumber) { const Cardinality c = Exactly(2); EXPECT_FALSE(c.IsSatisfiedByCallCount(0)); EXPECT_FALSE(c.IsSaturatedByCallCount(0)); EXPECT_TRUE(c.IsSatisfiedByCallCount(2)); EXPECT_TRUE(c.IsSaturatedByCallCount(2)); stringstream ss1; Exactly(1).DescribeTo(&ss1); EXPECT_PRED_FORMAT2(IsSubstring, "called once", ss1.str()); stringstream ss2; c.DescribeTo(&ss2); EXPECT_PRED_FORMAT2(IsSubstring, "called twice", ss2.str()); stringstream ss3; Exactly(3).DescribeTo(&ss3); EXPECT_PRED_FORMAT2(IsSubstring, "called 3 times", ss3.str()); } TEST(ExactlyTest, HasCorrectBounds) { const Cardinality c = Exactly(3); EXPECT_EQ(3, c.ConservativeLowerBound()); EXPECT_EQ(3, c.ConservativeUpperBound()); } class EvenCardinality : public CardinalityInterface { public: bool IsSatisfiedByCallCount(int call_count) const override { return (call_count % 2 == 0); } bool IsSaturatedByCallCount(int ) const override { return false; } void DescribeTo(::std::ostream* ss) const override { *ss << "called even number of times"; } }; TEST(MakeCardinalityTest, ConstructsCardinalityFromInterface) { const Cardinality c = MakeCardinality(new EvenCardinality); EXPECT_TRUE(c.IsSatisfiedByCallCount(2)); EXPECT_FALSE(c.IsSatisfiedByCallCount(3)); EXPECT_FALSE(c.IsSaturatedByCallCount(10000)); stringstream ss; c.DescribeTo(&ss); EXPECT_EQ("called even number of times", ss.str()); } }
2,328
cpp
google/googletest
gmock-internal-utils
googlemock/src/gmock-internal-utils.cc
googlemock/test/gmock-internal-utils_test.cc
#ifndef GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_ #define GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_ #include <stdio.h> #include <ostream> #include <string> #include <type_traits> #include <utility> #include <vector> #include "gmock/internal/gmock-port.h" #include "gtest/gtest.h" namespace testing { template <typename> class Matcher; namespace internal { GTEST_DISABLE_MSC_WARNINGS_PUSH_(4100 4805) GTEST_API_ std::string JoinAsKeyValueTuple( const std::vector<const char*>& names, const Strings& values); GTEST_API_ std::string ConvertIdentifierNameToWords(const char* id_name); template <typename Pointer> inline const typename Pointer::element_type* GetRawPointer(const Pointer& p) { return p.get(); } template <typename Element> inline const Element* GetRawPointer(const std::reference_wrapper<Element>& r) { return &r.get(); } template <typename Element> inline Element* GetRawPointer(Element* p) { return p; } #define GMOCK_INTERNAL_WARNING_PUSH() #define GMOCK_INTERNAL_WARNING_CLANG(Level, Name) #define GMOCK_INTERNAL_WARNING_POP() #if defined(__clang__) #undef GMOCK_INTERNAL_WARNING_PUSH #define GMOCK_INTERNAL_WARNING_PUSH() _Pragma("clang diagnostic push") #undef GMOCK_INTERNAL_WARNING_CLANG #define GMOCK_INTERNAL_WARNING_CLANG(Level, Warning) \ _Pragma(GMOCK_PP_INTERNAL_STRINGIZE(clang diagnostic Level Warning)) #undef GMOCK_INTERNAL_WARNING_POP #define GMOCK_INTERNAL_WARNING_POP() _Pragma("clang diagnostic pop") #endif #if defined(_MSC_VER) && !defined(_NATIVE_WCHAR_T_DEFINED) #else #define GMOCK_WCHAR_T_IS_NATIVE_ 1 #endif enum TypeKind { kBool, kInteger, kFloatingPoint, kOther }; template <typename T> struct KindOf { enum { value = kOther }; }; #define GMOCK_DECLARE_KIND_(type, kind) \ template <> \ struct KindOf<type> { \ enum { value = kind }; \ } GMOCK_DECLARE_KIND_(bool, kBool); GMOCK_DECLARE_KIND_(char, kInteger); GMOCK_DECLARE_KIND_(signed char, kInteger); GMOCK_DECLARE_KIND_(unsigned char, kInteger); GMOCK_DECLARE_KIND_(short, kInteger); GMOCK_DECLARE_KIND_(unsigned short, kInteger); GMOCK_DECLARE_KIND_(int, kInteger); GMOCK_DECLARE_KIND_(unsigned int, kInteger); GMOCK_DECLARE_KIND_(long, kInteger); GMOCK_DECLARE_KIND_(unsigned long, kInteger); GMOCK_DECLARE_KIND_(long long, kInteger); GMOCK_DECLARE_KIND_(unsigned long long, kInteger); #if GMOCK_WCHAR_T_IS_NATIVE_ GMOCK_DECLARE_KIND_(wchar_t, kInteger); #endif GMOCK_DECLARE_KIND_(float, kFloatingPoint); GMOCK_DECLARE_KIND_(double, kFloatingPoint); GMOCK_DECLARE_KIND_(long double, kFloatingPoint); #undef GMOCK_DECLARE_KIND_ #define GMOCK_KIND_OF_(type) \ static_cast< ::testing::internal::TypeKind>( \ ::testing::internal::KindOf<type>::value) template <TypeKind kFromKind, typename From, TypeKind kToKind, typename To> using LosslessArithmeticConvertibleImpl = std::integral_constant< bool, (kFromKind == kBool) ? true : (kFromKind != kToKind) ? false : (kFromKind == kInteger && (((sizeof(From) < sizeof(To)) && !(std::is_signed<From>::value && !std::is_signed<To>::value)) || ((sizeof(From) == sizeof(To)) && (std::is_signed<From>::value == std::is_signed<To>::value))) ) ? true : (kFromKind == kFloatingPoint && (sizeof(From) <= sizeof(To))) ? true : false >; template <typename From, typename To> using LosslessArithmeticConvertible = LosslessArithmeticConvertibleImpl<GMOCK_KIND_OF_(From), From, GMOCK_KIND_OF_(To), To>; class FailureReporterInterface { public: enum FailureType { kNonfatal, kFatal }; virtual ~FailureReporterInterface() = default; virtual void ReportFailure(FailureType type, const char* file, int line, const std::string& message) = 0; }; GTEST_API_ FailureReporterInterface* GetFailureReporter(); inline void Assert(bool condition, const char* file, int line, const std::string& msg) { if (!condition) { GetFailureReporter()->ReportFailure(FailureReporterInterface::kFatal, file, line, msg); } } inline void Assert(bool condition, const char* file, int line) { Assert(condition, file, line, "Assertion failed."); } inline void Expect(bool condition, const char* file, int line, const std::string& msg) { if (!condition) { GetFailureReporter()->ReportFailure(FailureReporterInterface::kNonfatal, file, line, msg); } } inline void Expect(bool condition, const char* file, int line) { Expect(condition, file, line, "Expectation failed."); } enum LogSeverity { kInfo = 0, kWarning = 1 }; const char kInfoVerbosity[] = "info"; const char kWarningVerbosity[] = "warning"; const char kErrorVerbosity[] = "error"; GTEST_API_ bool LogIsVisible(LogSeverity severity); GTEST_API_ void Log(LogSeverity severity, const std::string& message, int stack_frames_to_skip); class WithoutMatchers { private: WithoutMatchers() {} friend GTEST_API_ WithoutMatchers GetWithoutMatchers(); }; GTEST_API_ WithoutMatchers GetWithoutMatchers(); template <typename T> inline T Invalid() { Assert(false, "", -1, "Internal error: attempt to return invalid value"); #if defined(__GNUC__) || defined(__clang__) __builtin_unreachable(); #elif defined(_MSC_VER) __assume(0); #else return Invalid<T>(); #endif } template <class RawContainer> class StlContainerView { public: typedef RawContainer type; typedef const type& const_reference; static const_reference ConstReference(const RawContainer& container) { static_assert(!std::is_const<RawContainer>::value, "RawContainer type must not be const"); return container; } static type Copy(const RawContainer& container) { return container; } }; template <typename Element, size_t N> class StlContainerView<Element[N]> { public: typedef typename std::remove_const<Element>::type RawElement; typedef internal::NativeArray<RawElement> type; typedef const type const_reference; static const_reference ConstReference(const Element (&array)[N]) { static_assert(std::is_same<Element, RawElement>::value, "Element type must not be const"); return type(array, N, RelationToSourceReference()); } static type Copy(const Element (&array)[N]) { return type(array, N, RelationToSourceCopy()); } }; template <typename ElementPointer, typename Size> class StlContainerView< ::std::tuple<ElementPointer, Size> > { public: typedef typename std::remove_const< typename std::pointer_traits<ElementPointer>::element_type>::type RawElement; typedef internal::NativeArray<RawElement> type; typedef const type const_reference; static const_reference ConstReference( const ::std::tuple<ElementPointer, Size>& array) { return type(std::get<0>(array), std::get<1>(array), RelationToSourceReference()); } static type Copy(const ::std::tuple<ElementPointer, Size>& array) { return type(std::get<0>(array), std::get<1>(array), RelationToSourceCopy()); } }; template <typename T> class StlContainerView<T&>; template <typename T> struct RemoveConstFromKey { typedef T type; }; template <typename K, typename V> struct RemoveConstFromKey<std::pair<const K, V> > { typedef std::pair<K, V> type; }; GTEST_API_ void IllegalDoDefault(const char* file, int line); template <typename F, typename Tuple, size_t... Idx> auto ApplyImpl(F&& f, Tuple&& args, std::index_sequence<Idx...>) -> decltype(std::forward<F>(f)( std::get<Idx>(std::forward<Tuple>(args))...)) { return std::forward<F>(f)(std::get<Idx>(std::forward<Tuple>(args))...); } template <typename F, typename Tuple> auto Apply(F&& f, Tuple&& args) -> decltype(ApplyImpl( std::forward<F>(f), std::forward<Tuple>(args), std::make_index_sequence<std::tuple_size< typename std::remove_reference<Tuple>::type>::value>())) { return ApplyImpl(std::forward<F>(f), std::forward<Tuple>(args), std::make_index_sequence<std::tuple_size< typename std::remove_reference<Tuple>::type>::value>()); } template <typename T> struct Function; template <typename R, typename... Args> struct Function<R(Args...)> { using Result = R; static constexpr size_t ArgumentCount = sizeof...(Args); template <size_t I> using Arg = ElemFromList<I, Args...>; using ArgumentTuple = std::tuple<Args...>; using ArgumentMatcherTuple = std::tuple<Matcher<Args>...>; using MakeResultVoid = void(Args...); using MakeResultIgnoredValue = IgnoredValue(Args...); }; #ifdef GTEST_INTERNAL_NEED_REDUNDANT_CONSTEXPR_DECL template <typename R, typename... Args> constexpr size_t Function<R(Args...)>::ArgumentCount; #endif template <size_t I, typename T> using TupleElement = typename std::tuple_element<I, T>::type; bool Base64Unescape(const std::string& encoded, std::string* decoded); GTEST_DISABLE_MSC_WARNINGS_POP_() } } #endif #include "gmock/internal/gmock-internal-utils.h" #include <ctype.h> #include <array> #include <cctype> #include <cstdint> #include <cstring> #include <iostream> #include <ostream> #include <string> #include <utility> #include <vector> #include "gmock/gmock.h" #include "gmock/internal/gmock-port.h" #include "gtest/gtest.h" namespace testing { namespace internal { GTEST_API_ std::string JoinAsKeyValueTuple( const std::vector<const char*>& names, const Strings& values) { GTEST_CHECK_(names.size() == values.size()); if (values.empty()) { return ""; } const auto build_one = [&](const size_t i) { return std::string(names[i]) + ": " + values[i]; }; std::string result = "(" + build_one(0); for (size_t i = 1; i < values.size(); i++) { result += ", "; result += build_one(i); } result += ")"; return result; } GTEST_API_ std::string ConvertIdentifierNameToWords(const char* id_name) { std::string result; char prev_char = '\0'; for (const char* p = id_name; *p != '\0'; prev_char = *(p++)) { const bool starts_new_word = IsUpper(*p) || (!IsAlpha(prev_char) && IsLower(*p)) || (!IsDigit(prev_char) && IsDigit(*p)); if (IsAlNum(*p)) { if (starts_new_word && !result.empty()) result += ' '; result += ToLower(*p); } } return result; } class GoogleTestFailureReporter : public FailureReporterInterface { public: void ReportFailure(FailureType type, const char* file, int line, const std::string& message) override { AssertHelper(type == kFatal ? TestPartResult::kFatalFailure : TestPartResult::kNonFatalFailure, file, line, message.c_str()) = Message(); if (type == kFatal) { posix::Abort(); } } }; GTEST_API_ FailureReporterInterface* GetFailureReporter() { static FailureReporterInterface* const failure_reporter = new GoogleTestFailureReporter(); return failure_reporter; } static GTEST_DEFINE_STATIC_MUTEX_(g_log_mutex); GTEST_API_ bool LogIsVisible(LogSeverity severity) { if (GMOCK_FLAG_GET(verbose) == kInfoVerbosity) { return true; } else if (GMOCK_FLAG_GET(verbose) == kErrorVerbosity) { return false; } else { return severity == kWarning; } } GTEST_API_ void Log(LogSeverity severity, const std::string& message, int stack_frames_to_skip) { if (!LogIsVisible(severity)) return; MutexLock l(&g_log_mutex); if (severity == kWarning) { std::cout << "\nGMOCK WARNING:"; } if (message.empty() || message[0] != '\n') { std::cout << "\n"; } std::cout << message; if (stack_frames_to_skip >= 0) { #ifdef NDEBUG const int actual_to_skip = 0; #else const int actual_to_skip = stack_frames_to_skip + 1; #endif if (!message.empty() && *message.rbegin() != '\n') { std::cout << "\n"; } std::cout << "Stack trace:\n" << ::testing::internal::GetCurrentOsStackTraceExceptTop( actual_to_skip); } std::cout << ::std::flush; } GTEST_API_ WithoutMatchers GetWithoutMatchers() { return WithoutMatchers(); } GTEST_API_ void IllegalDoDefault(const char* file, int line) { internal::Assert( false, file, line, "You are using DoDefault() inside a composite action like " "DoAll() or WithArgs(). This is not supported for technical " "reasons. Please instead spell out the default action, or " "assign the default action to an Action variable and use " "the variable in various places."); } constexpr char UndoWebSafeEncoding(char c) { return c == '-' ? '+' : c == '_' ? '/' : c; } constexpr char UnBase64Impl(char c, const char* const base64, char carry) { return *base64 == 0 ? static_cast<char>(65) : *base64 == c ? carry : UnBase64Impl(c, base64 + 1, static_cast<char>(carry + 1)); } template <size_t... I> constexpr std::array<char, 256> UnBase64Impl(std::index_sequence<I...>, const char* const base64) { return { {UnBase64Impl(UndoWebSafeEncoding(static_cast<char>(I)), base64, 0)...}}; } constexpr std::array<char, 256> UnBase64(const char* const base64) { return UnBase64Impl(std::make_index_sequence<256>{}, base64); } static constexpr char kBase64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; static constexpr std::array<char, 256> kUnBase64 = UnBase64(kBase64); bool Base64Unescape(const std::string& encoded, std::string* decoded) { decoded->clear(); size_t encoded_len = encoded.size(); decoded->reserve(3 * (encoded_len / 4) + (encoded_len % 4)); int bit_pos = 0; char dst = 0; for (int src : encoded) { if (std::isspace(src) || src == '=') { continue; } char src_bin = kUnBase64[static_cast<size_t>(src)]; if (src_bin >= 64) { decoded->clear(); return false; } if (bit_pos == 0) { dst |= static_cast<char>(src_bin << 2); bit_pos = 6; } else { dst |= static_cast<char>(src_bin >> (bit_pos - 2)); decoded->push_back(dst); dst = static_cast<char>(src_bin << (10 - bit_pos)); bit_pos = (bit_pos + 6) % 8; } } return true; } } }
#include "gmock/internal/gmock-internal-utils.h" #include <stdlib.h> #include <cstdint> #include <map> #include <memory> #include <sstream> #include <string> #include <tuple> #include <vector> #include "gmock/gmock.h" #include "gmock/internal/gmock-port.h" #include "gtest/gtest-spi.h" #include "gtest/gtest.h" #define GTEST_IMPLEMENTATION_ 1 #include "src/gtest-internal-inl.h" #undef GTEST_IMPLEMENTATION_ #ifdef GTEST_OS_CYGWIN #include <sys/types.h> #endif namespace proto2 { class Message; } namespace testing { namespace internal { namespace { TEST(JoinAsKeyValueTupleTest, JoinsEmptyTuple) { EXPECT_EQ("", JoinAsKeyValueTuple({}, Strings())); } TEST(JoinAsKeyValueTupleTest, JoinsOneTuple) { EXPECT_EQ("(a: 1)", JoinAsKeyValueTuple({"a"}, {"1"})); } TEST(JoinAsKeyValueTupleTest, JoinsTwoTuple) { EXPECT_EQ("(a: 1, b: 2)", JoinAsKeyValueTuple({"a", "b"}, {"1", "2"})); } TEST(JoinAsKeyValueTupleTest, JoinsTenTuple) { EXPECT_EQ( "(a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10)", JoinAsKeyValueTuple({"a", "b", "c", "d", "e", "f", "g", "h", "i", "j"}, {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"})); } TEST(ConvertIdentifierNameToWordsTest, WorksWhenNameContainsNoWord) { EXPECT_EQ("", ConvertIdentifierNameToWords("")); EXPECT_EQ("", ConvertIdentifierNameToWords("_")); EXPECT_EQ("", ConvertIdentifierNameToWords("__")); } TEST(ConvertIdentifierNameToWordsTest, WorksWhenNameContainsDigits) { EXPECT_EQ("1", ConvertIdentifierNameToWords("_1")); EXPECT_EQ("2", ConvertIdentifierNameToWords("2_")); EXPECT_EQ("34", ConvertIdentifierNameToWords("_34_")); EXPECT_EQ("34 56", ConvertIdentifierNameToWords("_34_56")); } TEST(ConvertIdentifierNameToWordsTest, WorksWhenNameContainsCamelCaseWords) { EXPECT_EQ("a big word", ConvertIdentifierNameToWords("ABigWord")); EXPECT_EQ("foo bar", ConvertIdentifierNameToWords("FooBar")); EXPECT_EQ("foo", ConvertIdentifierNameToWords("Foo_")); EXPECT_EQ("foo bar", ConvertIdentifierNameToWords("_Foo_Bar_")); EXPECT_EQ("foo and bar", ConvertIdentifierNameToWords("_Foo__And_Bar")); } TEST(ConvertIdentifierNameToWordsTest, WorksWhenNameContains_SeparatedWords) { EXPECT_EQ("foo bar", ConvertIdentifierNameToWords("foo_bar")); EXPECT_EQ("foo", ConvertIdentifierNameToWords("_foo_")); EXPECT_EQ("foo bar", ConvertIdentifierNameToWords("_foo_bar_")); EXPECT_EQ("foo and bar", ConvertIdentifierNameToWords("_foo__and_bar")); } TEST(ConvertIdentifierNameToWordsTest, WorksWhenNameIsMixture) { EXPECT_EQ("foo bar 123", ConvertIdentifierNameToWords("Foo_bar123")); EXPECT_EQ("chapter 11 section 1", ConvertIdentifierNameToWords("_Chapter11Section_1_")); } TEST(GetRawPointerTest, WorksForSmartPointers) { const char* const raw_p1 = new const char('a'); const std::unique_ptr<const char> p1(raw_p1); EXPECT_EQ(raw_p1, GetRawPointer(p1)); double* const raw_p2 = new double(2.5); const std::shared_ptr<double> p2(raw_p2); EXPECT_EQ(raw_p2, GetRawPointer(p2)); } TEST(GetRawPointerTest, WorksForRawPointers) { int* p = nullptr; EXPECT_TRUE(nullptr == GetRawPointer(p)); int n = 1; EXPECT_EQ(&n, GetRawPointer(&n)); } TEST(GetRawPointerTest, WorksForStdReferenceWrapper) { int n = 1; EXPECT_EQ(&n, GetRawPointer(std::ref(n))); EXPECT_EQ(&n, GetRawPointer(std::cref(n))); } class Base {}; class Derived : public Base {}; TEST(KindOfTest, Bool) { EXPECT_EQ(kBool, GMOCK_KIND_OF_(bool)); } TEST(KindOfTest, Integer) { EXPECT_EQ(kInteger, GMOCK_KIND_OF_(char)); EXPECT_EQ(kInteger, GMOCK_KIND_OF_(signed char)); EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned char)); EXPECT_EQ(kInteger, GMOCK_KIND_OF_(short)); EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned short)); EXPECT_EQ(kInteger, GMOCK_KIND_OF_(int)); EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned int)); EXPECT_EQ(kInteger, GMOCK_KIND_OF_(long)); EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned long)); EXPECT_EQ(kInteger, GMOCK_KIND_OF_(long long)); EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned long long)); EXPECT_EQ(kInteger, GMOCK_KIND_OF_(wchar_t)); EXPECT_EQ(kInteger, GMOCK_KIND_OF_(size_t)); #if defined(GTEST_OS_LINUX) || defined(GTEST_OS_MAC) || defined(GTEST_OS_CYGWIN) EXPECT_EQ(kInteger, GMOCK_KIND_OF_(ssize_t)); #endif } TEST(KindOfTest, FloatingPoint) { EXPECT_EQ(kFloatingPoint, GMOCK_KIND_OF_(float)); EXPECT_EQ(kFloatingPoint, GMOCK_KIND_OF_(double)); EXPECT_EQ(kFloatingPoint, GMOCK_KIND_OF_(long double)); } TEST(KindOfTest, Other) { EXPECT_EQ(kOther, GMOCK_KIND_OF_(void*)); EXPECT_EQ(kOther, GMOCK_KIND_OF_(char**)); EXPECT_EQ(kOther, GMOCK_KIND_OF_(Base)); } TEST(LosslessArithmeticConvertibleTest, BoolToBool) { EXPECT_TRUE((LosslessArithmeticConvertible<bool, bool>::value)); } TEST(LosslessArithmeticConvertibleTest, BoolToInteger) { EXPECT_TRUE((LosslessArithmeticConvertible<bool, char>::value)); EXPECT_TRUE((LosslessArithmeticConvertible<bool, int>::value)); EXPECT_TRUE( (LosslessArithmeticConvertible<bool, unsigned long>::value)); } TEST(LosslessArithmeticConvertibleTest, BoolToFloatingPoint) { EXPECT_TRUE((LosslessArithmeticConvertible<bool, float>::value)); EXPECT_TRUE((LosslessArithmeticConvertible<bool, double>::value)); } TEST(LosslessArithmeticConvertibleTest, IntegerToBool) { EXPECT_FALSE((LosslessArithmeticConvertible<unsigned char, bool>::value)); EXPECT_FALSE((LosslessArithmeticConvertible<int, bool>::value)); } TEST(LosslessArithmeticConvertibleTest, IntegerToInteger) { EXPECT_TRUE((LosslessArithmeticConvertible<unsigned char, int>::value)); EXPECT_TRUE((LosslessArithmeticConvertible<unsigned short, uint64_t>::value)); EXPECT_FALSE( (LosslessArithmeticConvertible<short, uint64_t>::value)); EXPECT_FALSE((LosslessArithmeticConvertible<signed char, unsigned int>::value)); EXPECT_TRUE( (LosslessArithmeticConvertible<unsigned char, unsigned char>::value)); EXPECT_TRUE((LosslessArithmeticConvertible<int, int>::value)); EXPECT_TRUE((LosslessArithmeticConvertible<wchar_t, wchar_t>::value)); EXPECT_TRUE((LosslessArithmeticConvertible<unsigned long, unsigned long>::value)); EXPECT_FALSE( (LosslessArithmeticConvertible<unsigned char, signed char>::value)); EXPECT_FALSE((LosslessArithmeticConvertible<int, unsigned int>::value)); EXPECT_FALSE((LosslessArithmeticConvertible<uint64_t, int64_t>::value)); EXPECT_FALSE((LosslessArithmeticConvertible<long, char>::value)); EXPECT_FALSE((LosslessArithmeticConvertible<int, signed char>::value)); EXPECT_FALSE((LosslessArithmeticConvertible<int64_t, unsigned int>::value)); } TEST(LosslessArithmeticConvertibleTest, IntegerToFloatingPoint) { EXPECT_FALSE((LosslessArithmeticConvertible<char, float>::value)); EXPECT_FALSE((LosslessArithmeticConvertible<int, double>::value)); EXPECT_FALSE( (LosslessArithmeticConvertible<short, long double>::value)); } TEST(LosslessArithmeticConvertibleTest, FloatingPointToBool) { EXPECT_FALSE((LosslessArithmeticConvertible<float, bool>::value)); EXPECT_FALSE((LosslessArithmeticConvertible<double, bool>::value)); } TEST(LosslessArithmeticConvertibleTest, FloatingPointToInteger) { EXPECT_FALSE((LosslessArithmeticConvertible<float, long>::value)); EXPECT_FALSE((LosslessArithmeticConvertible<double, int64_t>::value)); EXPECT_FALSE((LosslessArithmeticConvertible<long double, int>::value)); } TEST(LosslessArithmeticConvertibleTest, FloatingPointToFloatingPoint) { EXPECT_TRUE((LosslessArithmeticConvertible<float, double>::value)); EXPECT_TRUE((LosslessArithmeticConvertible<float, long double>::value)); EXPECT_TRUE((LosslessArithmeticConvertible<double, long double>::value)); EXPECT_TRUE((LosslessArithmeticConvertible<float, float>::value)); EXPECT_TRUE((LosslessArithmeticConvertible<double, double>::value)); EXPECT_FALSE((LosslessArithmeticConvertible<double, float>::value)); GTEST_INTENTIONAL_CONST_COND_PUSH_() if (sizeof(double) == sizeof(long double)) { GTEST_INTENTIONAL_CONST_COND_POP_() EXPECT_TRUE((LosslessArithmeticConvertible<long double, double>::value)); } else { EXPECT_FALSE((LosslessArithmeticConvertible<long double, double>::value)); } } TEST(TupleMatchesTest, WorksForSize0) { std::tuple<> matchers; std::tuple<> values; EXPECT_TRUE(TupleMatches(matchers, values)); } TEST(TupleMatchesTest, WorksForSize1) { std::tuple<Matcher<int>> matchers(Eq(1)); std::tuple<int> values1(1), values2(2); EXPECT_TRUE(TupleMatches(matchers, values1)); EXPECT_FALSE(TupleMatches(matchers, values2)); } TEST(TupleMatchesTest, WorksForSize2) { std::tuple<Matcher<int>, Matcher<char>> matchers(Eq(1), Eq('a')); std::tuple<int, char> values1(1, 'a'), values2(1, 'b'), values3(2, 'a'), values4(2, 'b'); EXPECT_TRUE(TupleMatches(matchers, values1)); EXPECT_FALSE(TupleMatches(matchers, values2)); EXPECT_FALSE(TupleMatches(matchers, values3)); EXPECT_FALSE(TupleMatches(matchers, values4)); } TEST(TupleMatchesTest, WorksForSize5) { std::tuple<Matcher<int>, Matcher<char>, Matcher<bool>, Matcher<long>, Matcher<std::string>> matchers(Eq(1), Eq('a'), Eq(true), Eq(2L), Eq("hi")); std::tuple<int, char, bool, long, std::string> values1(1, 'a', true, 2L, "hi"), values2(1, 'a', true, 2L, "hello"), values3(2, 'a', true, 2L, "hi"); EXPECT_TRUE(TupleMatches(matchers, values1)); EXPECT_FALSE(TupleMatches(matchers, values2)); EXPECT_FALSE(TupleMatches(matchers, values3)); } TEST(AssertTest, SucceedsOnTrue) { Assert(true, __FILE__, __LINE__, "This should succeed."); Assert(true, __FILE__, __LINE__); } TEST(AssertTest, FailsFatallyOnFalse) { EXPECT_DEATH_IF_SUPPORTED( { Assert(false, __FILE__, __LINE__, "This should fail."); }, ""); EXPECT_DEATH_IF_SUPPORTED({ Assert(false, __FILE__, __LINE__); }, ""); } TEST(ExpectTest, SucceedsOnTrue) { Expect(true, __FILE__, __LINE__, "This should succeed."); Expect(true, __FILE__, __LINE__); } TEST(ExpectTest, FailsNonfatallyOnFalse) { EXPECT_NONFATAL_FAILURE( { Expect(false, __FILE__, __LINE__, "This should fail."); }, "This should fail"); EXPECT_NONFATAL_FAILURE( { Expect(false, __FILE__, __LINE__); }, "Expectation failed"); } class LogIsVisibleTest : public ::testing::Test { protected: void SetUp() override { original_verbose_ = GMOCK_FLAG_GET(verbose); } void TearDown() override { GMOCK_FLAG_SET(verbose, original_verbose_); } std::string original_verbose_; }; TEST_F(LogIsVisibleTest, AlwaysReturnsTrueIfVerbosityIsInfo) { GMOCK_FLAG_SET(verbose, kInfoVerbosity); EXPECT_TRUE(LogIsVisible(kInfo)); EXPECT_TRUE(LogIsVisible(kWarning)); } TEST_F(LogIsVisibleTest, AlwaysReturnsFalseIfVerbosityIsError) { GMOCK_FLAG_SET(verbose, kErrorVerbosity); EXPECT_FALSE(LogIsVisible(kInfo)); EXPECT_FALSE(LogIsVisible(kWarning)); } TEST_F(LogIsVisibleTest, WorksWhenVerbosityIsWarning) { GMOCK_FLAG_SET(verbose, kWarningVerbosity); EXPECT_FALSE(LogIsVisible(kInfo)); EXPECT_TRUE(LogIsVisible(kWarning)); } #if GTEST_HAS_STREAM_REDIRECTION void TestLogWithSeverity(const std::string& verbosity, LogSeverity severity, bool should_print) { const std::string old_flag = GMOCK_FLAG_GET(verbose); GMOCK_FLAG_SET(verbose, verbosity); CaptureStdout(); Log(severity, "Test log.\n", 0); if (should_print) { EXPECT_THAT( GetCapturedStdout().c_str(), ContainsRegex(severity == kWarning ? "^\nGMOCK WARNING:\nTest log\\.\nStack trace:\n" : "^\nTest log\\.\nStack trace:\n")); } else { EXPECT_STREQ("", GetCapturedStdout().c_str()); } GMOCK_FLAG_SET(verbose, old_flag); } TEST(LogTest, NoStackTraceWhenStackFramesToSkipIsNegative) { const std::string saved_flag = GMOCK_FLAG_GET(verbose); GMOCK_FLAG_SET(verbose, kInfoVerbosity); CaptureStdout(); Log(kInfo, "Test log.\n", -1); EXPECT_STREQ("\nTest log.\n", GetCapturedStdout().c_str()); GMOCK_FLAG_SET(verbose, saved_flag); } struct MockStackTraceGetter : testing::internal::OsStackTraceGetterInterface { std::string CurrentStackTrace(int max_depth, int skip_count) override { return (testing::Message() << max_depth << "::" << skip_count << "\n") .GetString(); } void UponLeavingGTest() override {} }; TEST(LogTest, NoSkippingStackFrameInOptMode) { MockStackTraceGetter* mock_os_stack_trace_getter = new MockStackTraceGetter; GetUnitTestImpl()->set_os_stack_trace_getter(mock_os_stack_trace_getter); CaptureStdout(); Log(kWarning, "Test log.\n", 100); const std::string log = GetCapturedStdout(); std::string expected_trace = (testing::Message() << GTEST_FLAG_GET(stack_trace_depth) << "::") .GetString(); std::string expected_message = "\nGMOCK WARNING:\n" "Test log.\n" "Stack trace:\n" + expected_trace; EXPECT_THAT(log, HasSubstr(expected_message)); int skip_count = atoi(log.substr(expected_message.size()).c_str()); #if defined(NDEBUG) const int expected_skip_count = 0; #else const int expected_skip_count = 100; #endif EXPECT_THAT(skip_count, AllOf(Ge(expected_skip_count), Le(expected_skip_count + 10))); GetUnitTestImpl()->set_os_stack_trace_getter(nullptr); } TEST(LogTest, AllLogsArePrintedWhenVerbosityIsInfo) { TestLogWithSeverity(kInfoVerbosity, kInfo, true); TestLogWithSeverity(kInfoVerbosity, kWarning, true); } TEST(LogTest, OnlyWarningsArePrintedWhenVerbosityIsWarning) { TestLogWithSeverity(kWarningVerbosity, kInfo, false); TestLogWithSeverity(kWarningVerbosity, kWarning, true); } TEST(LogTest, NoLogsArePrintedWhenVerbosityIsError) { TestLogWithSeverity(kErrorVerbosity, kInfo, false); TestLogWithSeverity(kErrorVerbosity, kWarning, false); } TEST(LogTest, OnlyWarningsArePrintedWhenVerbosityIsInvalid) { TestLogWithSeverity("invalid", kInfo, false); TestLogWithSeverity("invalid", kWarning, true); } std::string GrabOutput(void (*logger)(), const char* verbosity) { const std::string saved_flag = GMOCK_FLAG_GET(verbose); GMOCK_FLAG_SET(verbose, verbosity); CaptureStdout(); logger(); GMOCK_FLAG_SET(verbose, saved_flag); return GetCapturedStdout(); } class DummyMock { public: MOCK_METHOD0(TestMethod, void()); MOCK_METHOD1(TestMethodArg, void(int dummy)); }; void ExpectCallLogger() { DummyMock mock; EXPECT_CALL(mock, TestMethod()); mock.TestMethod(); } TEST(ExpectCallTest, LogsWhenVerbosityIsInfo) { EXPECT_THAT(std::string(GrabOutput(ExpectCallLogger, kInfoVerbosity)), HasSubstr("EXPECT_CALL(mock, TestMethod())")); } TEST(ExpectCallTest, DoesNotLogWhenVerbosityIsWarning) { EXPECT_STREQ("", GrabOutput(ExpectCallLogger, kWarningVerbosity).c_str()); } TEST(ExpectCallTest, DoesNotLogWhenVerbosityIsError) { EXPECT_STREQ("", GrabOutput(ExpectCallLogger, kErrorVerbosity).c_str()); } void OnCallLogger() { DummyMock mock; ON_CALL(mock, TestMethod()); } TEST(OnCallTest, LogsWhenVerbosityIsInfo) { EXPECT_THAT(std::string(GrabOutput(OnCallLogger, kInfoVerbosity)), HasSubstr("ON_CALL(mock, TestMethod())")); } TEST(OnCallTest, DoesNotLogWhenVerbosityIsWarning) { EXPECT_STREQ("", GrabOutput(OnCallLogger, kWarningVerbosity).c_str()); } TEST(OnCallTest, DoesNotLogWhenVerbosityIsError) { EXPECT_STREQ("", GrabOutput(OnCallLogger, kErrorVerbosity).c_str()); } void OnCallAnyArgumentLogger() { DummyMock mock; ON_CALL(mock, TestMethodArg(_)); } TEST(OnCallTest, LogsAnythingArgument) { EXPECT_THAT(std::string(GrabOutput(OnCallAnyArgumentLogger, kInfoVerbosity)), HasSubstr("ON_CALL(mock, TestMethodArg(_)")); } #endif TEST(StlContainerViewTest, WorksForStlContainer) { StaticAssertTypeEq<std::vector<int>, StlContainerView<std::vector<int>>::type>(); StaticAssertTypeEq<const std::vector<double>&, StlContainerView<std::vector<double>>::const_reference>(); typedef std::vector<char> Chars; Chars v1; const Chars& v2(StlContainerView<Chars>::ConstReference(v1)); EXPECT_EQ(&v1, &v2); v1.push_back('a'); Chars v3 = StlContainerView<Chars>::Copy(v1); EXPECT_THAT(v3, Eq(v3)); } TEST(StlContainerViewTest, WorksForStaticNativeArray) { StaticAssertTypeEq<NativeArray<int>, StlContainerView<int[3]>::type>(); StaticAssertTypeEq<NativeArray<double>, StlContainerView<const double[4]>::type>(); StaticAssertTypeEq<NativeArray<char[3]>, StlContainerView<const char[2][3]>::type>(); StaticAssertTypeEq<const NativeArray<int>, StlContainerView<int[2]>::const_reference>(); int a1[3] = {0, 1, 2}; NativeArray<int> a2 = StlContainerView<int[3]>::ConstReference(a1); EXPECT_EQ(3U, a2.size()); EXPECT_EQ(a1, a2.begin()); const NativeArray<int> a3 = StlContainerView<int[3]>::Copy(a1); ASSERT_EQ(3U, a3.size()); EXPECT_EQ(0, a3.begin()[0]); EXPECT_EQ(1, a3.begin()[1]); EXPECT_EQ(2, a3.begin()[2]); a1[0] = 3; EXPECT_EQ(0, a3.begin()[0]); } TEST(StlContainerViewTest, WorksForDynamicNativeArray) { StaticAssertTypeEq<NativeArray<int>, StlContainerView<std::tuple<const int*, size_t>>::type>(); StaticAssertTypeEq< NativeArray<double>, StlContainerView<std::tuple<std::shared_ptr<double>, int>>::type>(); StaticAssertTypeEq< const NativeArray<int>, StlContainerView<std::tuple<const int*, int>>::const_reference>(); int a1[3] = {0, 1, 2}; const int* const p1 = a1; NativeArray<int> a2 = StlContainerView<std::tuple<const int*, int>>::ConstReference( std::make_tuple(p1, 3)); EXPECT_EQ(3U, a2.size()); EXPECT_EQ(a1, a2.begin()); const NativeArray<int> a3 = StlContainerView<std::tuple<int*, size_t>>::Copy( std::make_tuple(static_cast<int*>(a1), 3)); ASSERT_EQ(3U, a3.size()); EXPECT_EQ(0, a3.begin()[0]); EXPECT_EQ(1, a3.begin()[1]); EXPECT_EQ(2, a3.begin()[2]); a1[0] = 3; EXPECT_EQ(0, a3.begin()[0]); } TEST(FunctionTest, Nullary) { typedef Function<int()> F; EXPECT_EQ(0u, F::ArgumentCount); EXPECT_TRUE((std::is_same<int, F::Result>::value)); EXPECT_TRUE((std::is_same<std::tuple<>, F::ArgumentTuple>::value)); EXPECT_TRUE((std::is_same<std::tuple<>, F::ArgumentMatcherTuple>::value)); EXPECT_TRUE((std::is_same<void(), F::MakeResultVoid>::value)); EXPECT_TRUE((std::is_same<IgnoredValue(), F::MakeResultIgnoredValue>::value)); } TEST(FunctionTest, Unary) { typedef Function<int(bool)> F; EXPECT_EQ(1u, F::ArgumentCount); EXPECT_TRUE((std::is_same<int, F::Result>::value)); EXPECT_TRUE((std::is_same<bool, F::Arg<0>::type>::value)); EXPECT_TRUE((std::is_same<std::tuple<bool>, F::ArgumentTuple>::value)); EXPECT_TRUE(( std::is_same<std::tuple<Matcher<bool>>, F::ArgumentMatcherTuple>::value)); EXPECT_TRUE((std::is_same<void(bool), F::MakeResultVoid>::value)); EXPECT_TRUE((std::is_same<IgnoredValue(bool), F::MakeResultIgnoredValue>::value)); } TEST(FunctionTest, Binary) { typedef Function<int(bool, const long&)> F; EXPECT_EQ(2u, F::ArgumentCount); EXPECT_TRUE((std::is_same<int, F::Result>::value)); EXPECT_TRUE((std::is_same<bool, F::Arg<0>::type>::value)); EXPECT_TRUE((std::is_same<const long&, F::Arg<1>::type>::value)); EXPECT_TRUE((std::is_same<std::tuple<bool, const long&>, F::ArgumentTuple>::value)); EXPECT_TRUE( (std::is_same<std::tuple<Matcher<bool>, Matcher<const long&>>, F::ArgumentMatcherTuple>::value)); EXPECT_TRUE((std::is_same<void(bool, const long&), F::MakeResultVoid>::value)); EXPECT_TRUE((std::is_same<IgnoredValue(bool, const long&), F::MakeResultIgnoredValue>::value)); } TEST(FunctionTest, LongArgumentList) { typedef Function<char(bool, int, char*, int&, const long&)> F; EXPECT_EQ(5u, F::ArgumentCount); EXPECT_TRUE((std::is_same<char, F::Result>::value)); EXPECT_TRUE((std::is_same<bool, F::Arg<0>::type>::value)); EXPECT_TRUE((std::is_same<int, F::Arg<1>::type>::value)); EXPECT_TRUE((std::is_same<char*, F::Arg<2>::type>::value)); EXPECT_TRUE((std::is_same<int&, F::Arg<3>::type>::value)); EXPECT_TRUE((std::is_same<const long&, F::Arg<4>::type>::value)); EXPECT_TRUE( (std::is_same<std::tuple<bool, int, char*, int&, const long&>, F::ArgumentTuple>::value)); EXPECT_TRUE( (std::is_same< std::tuple<Matcher<bool>, Matcher<int>, Matcher<char*>, Matcher<int&>, Matcher<const long&>>, F::ArgumentMatcherTuple>::value)); EXPECT_TRUE( (std::is_same<void(bool, int, char*, int&, const long&), F::MakeResultVoid>::value)); EXPECT_TRUE(( std::is_same<IgnoredValue(bool, int, char*, int&, const long&), F::MakeResultIgnoredValue>::value)); } TEST(Base64Unescape, InvalidString) { std::string unescaped; EXPECT_FALSE(Base64Unescape("(invalid)", &unescaped)); } TEST(Base64Unescape, ShortString) { std::string unescaped; EXPECT_TRUE(Base64Unescape("SGVsbG8gd29ybGQh", &unescaped)); EXPECT_EQ("Hello world!", unescaped); } TEST(Base64Unescape, ShortStringWithPadding) { std::string unescaped; EXPECT_TRUE(Base64Unescape("SGVsbG8gd29ybGQ=", &unescaped)); EXPECT_EQ("Hello world", unescaped); } TEST(Base64Unescape, ShortStringWithoutPadding) { std::string unescaped; EXPECT_TRUE(Base64Unescape("SGVsbG8gd29ybGQ", &unescaped)); EXPECT_EQ("Hello world", unescaped); } TEST(Base64Unescape, LongStringWithWhiteSpaces) { std::string escaped = R"(TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlz IHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2Yg dGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGlu dWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRo ZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4=)"; std::string expected = "Man is distinguished, not only by his reason, but by this singular " "passion from other animals, which is a lust of the mind, that by a " "perseverance of delight in the continued and indefatigable generation " "of knowledge, exceeds the short vehemence of any carnal pleasure."; std::string unescaped; EXPECT_TRUE(Base64Unescape(escaped, &unescaped)); EXPECT_EQ(expected, unescaped); } } } }
2,329
cpp
google/googletest
gmock
googlemock/src/gmock.cc
googlemock/test/gmock_test.cc
#ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_H_ #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_H_ #include "gmock/gmock-actions.h" #include "gmock/gmock-cardinalities.h" #include "gmock/gmock-function-mocker.h" #include "gmock/gmock-matchers.h" #include "gmock/gmock-more-actions.h" #include "gmock/gmock-more-matchers.h" #include "gmock/gmock-nice-strict.h" #include "gmock/gmock-spec-builders.h" #include "gmock/internal/gmock-internal-utils.h" #include "gmock/internal/gmock-port.h" GMOCK_DECLARE_bool_(catch_leaked_mocks); GMOCK_DECLARE_string_(verbose); GMOCK_DECLARE_int32_(default_mock_behavior); namespace testing { GTEST_API_ void InitGoogleMock(int* argc, char** argv); GTEST_API_ void InitGoogleMock(int* argc, wchar_t** argv); GTEST_API_ void InitGoogleMock(); } #endif #include "gmock/gmock.h" #include <string> #include "gmock/internal/gmock-port.h" GMOCK_DEFINE_bool_(catch_leaked_mocks, true, "true if and only if Google Mock should report leaked " "mock objects as failures."); GMOCK_DEFINE_string_(verbose, testing::internal::kWarningVerbosity, "Controls how verbose Google Mock's output is." " Valid values:\n" " info - prints all messages.\n" " warning - prints warnings and errors.\n" " error - prints errors only."); GMOCK_DEFINE_int32_(default_mock_behavior, 1, "Controls the default behavior of mocks." " Valid values:\n" " 0 - by default, mocks act as NiceMocks.\n" " 1 - by default, mocks act as NaggyMocks.\n" " 2 - by default, mocks act as StrictMocks."); namespace testing { namespace internal { static const char* ParseGoogleMockFlagValue(const char* str, const char* flag_name, bool def_optional) { if (str == nullptr || flag_name == nullptr) return nullptr; const std::string flag_name_str = std::string("--gmock_") + flag_name; const size_t flag_name_len = flag_name_str.length(); if (strncmp(str, flag_name_str.c_str(), flag_name_len) != 0) return nullptr; const char* flag_end = str + flag_name_len; if (def_optional && (flag_end[0] == '\0')) { return flag_end; } if (flag_end[0] != '=') return nullptr; return flag_end + 1; } static bool ParseGoogleMockFlag(const char* str, const char* flag_name, bool* value) { const char* const value_str = ParseGoogleMockFlagValue(str, flag_name, true); if (value_str == nullptr) return false; *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F'); return true; } template <typename String> static bool ParseGoogleMockFlag(const char* str, const char* flag_name, String* value) { const char* const value_str = ParseGoogleMockFlagValue(str, flag_name, false); if (value_str == nullptr) return false; *value = value_str; return true; } static bool ParseGoogleMockFlag(const char* str, const char* flag_name, int32_t* value) { const char* const value_str = ParseGoogleMockFlagValue(str, flag_name, true); if (value_str == nullptr) return false; return ParseInt32(Message() << "The value of flag --" << flag_name, value_str, value); } template <typename CharType> void InitGoogleMockImpl(int* argc, CharType** argv) { InitGoogleTest(argc, argv); if (*argc <= 0) return; for (int i = 1; i != *argc; i++) { const std::string arg_string = StreamableToString(argv[i]); const char* const arg = arg_string.c_str(); bool found_gmock_flag = false; #define GMOCK_INTERNAL_PARSE_FLAG(flag_name) \ if (!found_gmock_flag) { \ auto value = GMOCK_FLAG_GET(flag_name); \ if (ParseGoogleMockFlag(arg, #flag_name, &value)) { \ GMOCK_FLAG_SET(flag_name, value); \ found_gmock_flag = true; \ } \ } GMOCK_INTERNAL_PARSE_FLAG(catch_leaked_mocks) GMOCK_INTERNAL_PARSE_FLAG(verbose) GMOCK_INTERNAL_PARSE_FLAG(default_mock_behavior) if (found_gmock_flag) { for (int j = i; j != *argc; j++) { argv[j] = argv[j + 1]; } (*argc)--; i--; } } } } GTEST_API_ void InitGoogleMock(int* argc, char** argv) { internal::InitGoogleMockImpl(argc, argv); } GTEST_API_ void InitGoogleMock(int* argc, wchar_t** argv) { internal::InitGoogleMockImpl(argc, argv); } GTEST_API_ void InitGoogleMock() { int argc = 1; const auto arg0 = "dummy"; char* argv0 = const_cast<char*>(arg0); char** argv = &argv0; internal::InitGoogleMockImpl(&argc, argv); } }
#include "gmock/gmock.h" #include <string> #include "gtest/gtest.h" #include "gtest/internal/custom/gtest.h" #if !defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) using testing::InitGoogleMock; template <typename Char, int M, int N> void TestInitGoogleMock(const Char* (&argv)[M], const Char* (&new_argv)[N], const ::std::string& expected_gmock_verbose) { const ::std::string old_verbose = GMOCK_FLAG_GET(verbose); int argc = M - 1; InitGoogleMock(&argc, const_cast<Char**>(argv)); ASSERT_EQ(N - 1, argc) << "The new argv has wrong number of elements."; for (int i = 0; i < N; i++) { EXPECT_STREQ(new_argv[i], argv[i]); } EXPECT_EQ(expected_gmock_verbose, GMOCK_FLAG_GET(verbose)); GMOCK_FLAG_SET(verbose, old_verbose); } TEST(InitGoogleMockTest, ParsesInvalidCommandLine) { const char* argv[] = {nullptr}; const char* new_argv[] = {nullptr}; TestInitGoogleMock(argv, new_argv, GMOCK_FLAG_GET(verbose)); } TEST(InitGoogleMockTest, ParsesEmptyCommandLine) { const char* argv[] = {"foo.exe", nullptr}; const char* new_argv[] = {"foo.exe", nullptr}; TestInitGoogleMock(argv, new_argv, GMOCK_FLAG_GET(verbose)); } TEST(InitGoogleMockTest, ParsesSingleFlag) { const char* argv[] = {"foo.exe", "--gmock_verbose=info", nullptr}; const char* new_argv[] = {"foo.exe", nullptr}; TestInitGoogleMock(argv, new_argv, "info"); } TEST(InitGoogleMockTest, ParsesMultipleFlags) { int old_default_behavior = GMOCK_FLAG_GET(default_mock_behavior); const wchar_t* argv[] = {L"foo.exe", L"--gmock_verbose=info", L"--gmock_default_mock_behavior=2", nullptr}; const wchar_t* new_argv[] = {L"foo.exe", nullptr}; TestInitGoogleMock(argv, new_argv, "info"); EXPECT_EQ(2, GMOCK_FLAG_GET(default_mock_behavior)); EXPECT_NE(2, old_default_behavior); GMOCK_FLAG_SET(default_mock_behavior, old_default_behavior); } TEST(InitGoogleMockTest, ParsesUnrecognizedFlag) { const char* argv[] = {"foo.exe", "--non_gmock_flag=blah", nullptr}; const char* new_argv[] = {"foo.exe", "--non_gmock_flag=blah", nullptr}; TestInitGoogleMock(argv, new_argv, GMOCK_FLAG_GET(verbose)); } TEST(InitGoogleMockTest, ParsesGoogleMockFlagAndUnrecognizedFlag) { const char* argv[] = {"foo.exe", "--non_gmock_flag=blah", "--gmock_verbose=error", nullptr}; const char* new_argv[] = {"foo.exe", "--non_gmock_flag=blah", nullptr}; TestInitGoogleMock(argv, new_argv, "error"); } TEST(WideInitGoogleMockTest, ParsesInvalidCommandLine) { const wchar_t* argv[] = {nullptr}; const wchar_t* new_argv[] = {nullptr}; TestInitGoogleMock(argv, new_argv, GMOCK_FLAG_GET(verbose)); } TEST(WideInitGoogleMockTest, ParsesEmptyCommandLine) { const wchar_t* argv[] = {L"foo.exe", nullptr}; const wchar_t* new_argv[] = {L"foo.exe", nullptr}; TestInitGoogleMock(argv, new_argv, GMOCK_FLAG_GET(verbose)); } TEST(WideInitGoogleMockTest, ParsesSingleFlag) { const wchar_t* argv[] = {L"foo.exe", L"--gmock_verbose=info", nullptr}; const wchar_t* new_argv[] = {L"foo.exe", nullptr}; TestInitGoogleMock(argv, new_argv, "info"); } TEST(WideInitGoogleMockTest, ParsesMultipleFlags) { int old_default_behavior = GMOCK_FLAG_GET(default_mock_behavior); const wchar_t* argv[] = {L"foo.exe", L"--gmock_verbose=info", L"--gmock_default_mock_behavior=2", nullptr}; const wchar_t* new_argv[] = {L"foo.exe", nullptr}; TestInitGoogleMock(argv, new_argv, "info"); EXPECT_EQ(2, GMOCK_FLAG_GET(default_mock_behavior)); EXPECT_NE(2, old_default_behavior); GMOCK_FLAG_SET(default_mock_behavior, old_default_behavior); } TEST(WideInitGoogleMockTest, ParsesUnrecognizedFlag) { const wchar_t* argv[] = {L"foo.exe", L"--non_gmock_flag=blah", nullptr}; const wchar_t* new_argv[] = {L"foo.exe", L"--non_gmock_flag=blah", nullptr}; TestInitGoogleMock(argv, new_argv, GMOCK_FLAG_GET(verbose)); } TEST(WideInitGoogleMockTest, ParsesGoogleMockFlagAndUnrecognizedFlag) { const wchar_t* argv[] = {L"foo.exe", L"--non_gmock_flag=blah", L"--gmock_verbose=error", nullptr}; const wchar_t* new_argv[] = {L"foo.exe", L"--non_gmock_flag=blah", nullptr}; TestInitGoogleMock(argv, new_argv, "error"); } #endif TEST(FlagTest, IsAccessibleInCode) { bool dummy = GMOCK_FLAG_GET(catch_leaked_mocks) && GMOCK_FLAG_GET(verbose).empty(); (void)dummy; }
2,330
cpp
google/googletest
gmock-spec-builders
googlemock/src/gmock-spec-builders.cc
googlemock/test/gmock-spec-builders_test.cc
#ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_ #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_ #include <cstdint> #include <functional> #include <map> #include <memory> #include <ostream> #include <set> #include <sstream> #include <string> #include <type_traits> #include <utility> #include <vector> #include "gmock/gmock-actions.h" #include "gmock/gmock-cardinalities.h" #include "gmock/gmock-matchers.h" #include "gmock/internal/gmock-internal-utils.h" #include "gmock/internal/gmock-port.h" #include "gtest/gtest.h" #if GTEST_HAS_EXCEPTIONS #include <stdexcept> #endif GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \ ) namespace testing { class Expectation; class ExpectationSet; namespace internal { template <typename F> class FunctionMocker; class ExpectationBase; template <typename F> class TypedExpectation; class ExpectationTester; template <typename MockClass> class NiceMockImpl; template <typename MockClass> class StrictMockImpl; template <typename MockClass> class NaggyMockImpl; GTEST_API_ GTEST_DECLARE_STATIC_MUTEX_(g_gmock_mutex); class GTEST_API_ UntypedFunctionMockerBase { public: UntypedFunctionMockerBase(); virtual ~UntypedFunctionMockerBase(); bool VerifyAndClearExpectationsLocked() GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex); virtual void ClearDefaultActionsLocked() GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) = 0; virtual void UntypedDescribeUninterestingCall(const void* untyped_args, ::std::ostream* os) const GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0; virtual const ExpectationBase* UntypedFindMatchingExpectation( const void* untyped_args, const void** untyped_action, bool* is_excessive, ::std::ostream* what, ::std::ostream* why) GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0; virtual void UntypedPrintArgs(const void* untyped_args, ::std::ostream* os) const = 0; void RegisterOwner(const void* mock_obj) GTEST_LOCK_EXCLUDED_(g_gmock_mutex); void SetOwnerAndName(const void* mock_obj, const char* name) GTEST_LOCK_EXCLUDED_(g_gmock_mutex); const void* MockObject() const GTEST_LOCK_EXCLUDED_(g_gmock_mutex); const char* Name() const GTEST_LOCK_EXCLUDED_(g_gmock_mutex); protected: typedef std::vector<const void*> UntypedOnCallSpecs; using UntypedExpectations = std::vector<std::shared_ptr<ExpectationBase>>; struct UninterestingCallCleanupHandler; struct FailureCleanupHandler; Expectation GetHandleOf(ExpectationBase* exp); const void* mock_obj_; const char* name_; UntypedOnCallSpecs untyped_on_call_specs_; UntypedExpectations untyped_expectations_; }; class UntypedOnCallSpecBase { public: UntypedOnCallSpecBase(const char* a_file, int a_line) : file_(a_file), line_(a_line), last_clause_(kNone) {} const char* file() const { return file_; } int line() const { return line_; } protected: enum Clause { kNone, kWith, kWillByDefault }; void AssertSpecProperty(bool property, const std::string& failure_message) const { Assert(property, file_, line_, failure_message); } void ExpectSpecProperty(bool property, const std::string& failure_message) const { Expect(property, file_, line_, failure_message); } const char* file_; int line_; Clause last_clause_; }; template <typename F> class OnCallSpec : public UntypedOnCallSpecBase { public: typedef typename Function<F>::ArgumentTuple ArgumentTuple; typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple; OnCallSpec(const char* a_file, int a_line, const ArgumentMatcherTuple& matchers) : UntypedOnCallSpecBase(a_file, a_line), matchers_(matchers), extra_matcher_(A<const ArgumentTuple&>()) {} OnCallSpec& With(const Matcher<const ArgumentTuple&>& m) { ExpectSpecProperty(last_clause_ < kWith, ".With() cannot appear " "more than once in an ON_CALL()."); last_clause_ = kWith; extra_matcher_ = m; return *this; } OnCallSpec& WillByDefault(const Action<F>& action) { ExpectSpecProperty(last_clause_ < kWillByDefault, ".WillByDefault() must appear " "exactly once in an ON_CALL()."); last_clause_ = kWillByDefault; ExpectSpecProperty(!action.IsDoDefault(), "DoDefault() cannot be used in ON_CALL()."); action_ = action; return *this; } bool Matches(const ArgumentTuple& args) const { return TupleMatches(matchers_, args) && extra_matcher_.Matches(args); } const Action<F>& GetAction() const { AssertSpecProperty(last_clause_ == kWillByDefault, ".WillByDefault() must appear exactly " "once in an ON_CALL()."); return action_; } private: ArgumentMatcherTuple matchers_; Matcher<const ArgumentTuple&> extra_matcher_; Action<F> action_; }; enum CallReaction { kAllow, kWarn, kFail, }; } class GTEST_API_ Mock { public: static void AllowLeak(const void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); static bool VerifyAndClearExpectations(void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); static bool VerifyAndClear(void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); static bool IsNaggy(void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); static bool IsNice(void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); static bool IsStrict(void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); private: friend class internal::UntypedFunctionMockerBase; template <typename F> friend class internal::FunctionMocker; template <typename MockClass> friend class internal::NiceMockImpl; template <typename MockClass> friend class internal::NaggyMockImpl; template <typename MockClass> friend class internal::StrictMockImpl; static void AllowUninterestingCalls(uintptr_t mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); static void WarnUninterestingCalls(uintptr_t mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); static void FailUninterestingCalls(uintptr_t mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); static void UnregisterCallReaction(uintptr_t mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); static internal::CallReaction GetReactionOnUninterestingCalls( const void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); static bool VerifyAndClearExpectationsLocked(void* mock_obj) GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex); static void ClearDefaultActionsLocked(void* mock_obj) GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex); static void Register(const void* mock_obj, internal::UntypedFunctionMockerBase* mocker) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); static void RegisterUseByOnCallOrExpectCall(const void* mock_obj, const char* file, int line) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); static void UnregisterLocked(internal::UntypedFunctionMockerBase* mocker) GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex); }; class GTEST_API_ Expectation { public: Expectation(); Expectation(Expectation&&) = default; Expectation(const Expectation&) = default; Expectation& operator=(Expectation&&) = default; Expectation& operator=(const Expectation&) = default; ~Expectation(); Expectation(internal::ExpectationBase& exp); bool operator==(const Expectation& rhs) const { return expectation_base_ == rhs.expectation_base_; } bool operator!=(const Expectation& rhs) const { return !(*this == rhs); } private: friend class ExpectationSet; friend class Sequence; friend class ::testing::internal::ExpectationBase; friend class ::testing::internal::UntypedFunctionMockerBase; template <typename F> friend class ::testing::internal::FunctionMocker; template <typename F> friend class ::testing::internal::TypedExpectation; class Less { public: bool operator()(const Expectation& lhs, const Expectation& rhs) const { return lhs.expectation_base_.get() < rhs.expectation_base_.get(); } }; typedef ::std::set<Expectation, Less> Set; Expectation( const std::shared_ptr<internal::ExpectationBase>& expectation_base); const std::shared_ptr<internal::ExpectationBase>& expectation_base() const { return expectation_base_; } std::shared_ptr<internal::ExpectationBase> expectation_base_; }; class ExpectationSet { public: typedef Expectation::Set::const_iterator const_iterator; typedef Expectation::Set::value_type value_type; ExpectationSet() = default; ExpectationSet(internal::ExpectationBase& exp) { *this += Expectation(exp); } ExpectationSet(const Expectation& e) { *this += e; } bool operator==(const ExpectationSet& rhs) const { return expectations_ == rhs.expectations_; } bool operator!=(const ExpectationSet& rhs) const { return !(*this == rhs); } ExpectationSet& operator+=(const Expectation& e) { expectations_.insert(e); return *this; } int size() const { return static_cast<int>(expectations_.size()); } const_iterator begin() const { return expectations_.begin(); } const_iterator end() const { return expectations_.end(); } private: Expectation::Set expectations_; }; class GTEST_API_ Sequence { public: Sequence() : last_expectation_(new Expectation) {} void AddExpectation(const Expectation& expectation) const; private: std::shared_ptr<Expectation> last_expectation_; }; class GTEST_API_ InSequence { public: InSequence(); ~InSequence(); private: bool sequence_created_; InSequence(const InSequence&) = delete; InSequence& operator=(const InSequence&) = delete; }; namespace internal { GTEST_API_ extern ThreadLocal<Sequence*> g_gmock_implicit_sequence; class GTEST_API_ ExpectationBase { public: ExpectationBase(const char* file, int line, const std::string& source_text); virtual ~ExpectationBase(); const char* file() const { return file_; } int line() const { return line_; } const char* source_text() const { return source_text_.c_str(); } const Cardinality& cardinality() const { return cardinality_; } void DescribeLocationTo(::std::ostream* os) const { *os << FormatFileLocation(file(), line()) << " "; } void DescribeCallCountTo(::std::ostream* os) const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex); virtual void MaybeDescribeExtraMatcherTo(::std::ostream* os) = 0; void UntypedDescription(std::string description) { description_ = std::move(description); } protected: friend class ::testing::Expectation; friend class UntypedFunctionMockerBase; enum Clause { kNone, kWith, kTimes, kInSequence, kAfter, kWillOnce, kWillRepeatedly, kRetiresOnSaturation }; typedef std::vector<const void*> UntypedActions; virtual Expectation GetHandle() = 0; void AssertSpecProperty(bool property, const std::string& failure_message) const { Assert(property, file_, line_, failure_message); } void ExpectSpecProperty(bool property, const std::string& failure_message) const { Expect(property, file_, line_, failure_message); } void SpecifyCardinality(const Cardinality& cardinality); bool cardinality_specified() const { return cardinality_specified_; } void set_cardinality(const Cardinality& a_cardinality) { cardinality_ = a_cardinality; } void RetireAllPreRequisites() GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex); bool is_retired() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); return retired_; } void Retire() GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); retired_ = true; } const std::string& GetDescription() const { return description_; } bool IsSatisfied() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); return cardinality().IsSatisfiedByCallCount(call_count_); } bool IsSaturated() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); return cardinality().IsSaturatedByCallCount(call_count_); } bool IsOverSaturated() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); return cardinality().IsOverSaturatedByCallCount(call_count_); } bool AllPrerequisitesAreSatisfied() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex); void FindUnsatisfiedPrerequisites(ExpectationSet* result) const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex); int call_count() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); return call_count_; } void IncrementCallCount() GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); call_count_++; } void CheckActionCountIfNotDone() const GTEST_LOCK_EXCLUDED_(mutex_); friend class ::testing::Sequence; friend class ::testing::internal::ExpectationTester; template <typename Function> friend class TypedExpectation; void UntypedTimes(const Cardinality& a_cardinality); const char* file_; int line_; const std::string source_text_; std::string description_; bool cardinality_specified_; Cardinality cardinality_; ExpectationSet immediate_prerequisites_; int call_count_; bool retired_; UntypedActions untyped_actions_; bool extra_matcher_specified_; bool repeated_action_specified_; bool retires_on_saturation_; Clause last_clause_; mutable bool action_count_checked_; mutable Mutex mutex_; }; template <typename F> class TypedExpectation
#include "gmock/gmock-spec-builders.h" #include <memory> #include <ostream> #include <sstream> #include <string> #include <type_traits> #include "gmock/gmock.h" #include "gmock/internal/gmock-port.h" #include "gtest/gtest-spi.h" #include "gtest/gtest.h" #include "gtest/internal/gtest-port.h" namespace testing { namespace { using ::testing::internal::FormatFileLocation; using ::testing::internal::kAllow; using ::testing::internal::kErrorVerbosity; using ::testing::internal::kFail; using ::testing::internal::kInfoVerbosity; using ::testing::internal::kWarn; using ::testing::internal::kWarningVerbosity; #if GTEST_HAS_STREAM_REDIRECTION using ::testing::internal::CaptureStdout; using ::testing::internal::GetCapturedStdout; #endif class Incomplete; class MockIncomplete { public: MOCK_METHOD1(ByRefFunc, void(const Incomplete& x)); }; void PrintTo(const Incomplete& x, ::std::ostream* os); TEST(MockMethodTest, CanInstantiateWithIncompleteArgType) { MockIncomplete incomplete; EXPECT_CALL(incomplete, ByRefFunc(_)).Times(AnyNumber()); } void PrintTo(const Incomplete& , ::std::ostream* os) { *os << "incomplete"; } class Result {}; class NonDefaultConstructible { public: explicit NonDefaultConstructible(int ) {} }; class MockA { public: MockA() = default; MOCK_METHOD1(DoA, void(int n)); MOCK_METHOD1(ReturnResult, Result(int n)); MOCK_METHOD0(ReturnNonDefaultConstructible, NonDefaultConstructible()); MOCK_METHOD2(Binary, bool(int x, int y)); MOCK_METHOD2(ReturnInt, int(int x, int y)); private: MockA(const MockA&) = delete; MockA& operator=(const MockA&) = delete; }; class MockB { public: MockB() = default; MOCK_CONST_METHOD0(DoB, int()); MOCK_METHOD1(DoB, int(int n)); private: MockB(const MockB&) = delete; MockB& operator=(const MockB&) = delete; }; class ReferenceHoldingMock { public: ReferenceHoldingMock() = default; MOCK_METHOD1(AcceptReference, void(std::shared_ptr<MockA>*)); private: ReferenceHoldingMock(const ReferenceHoldingMock&) = delete; ReferenceHoldingMock& operator=(const ReferenceHoldingMock&) = delete; }; #define Method MethodW class CC { public: virtual ~CC() = default; virtual int Method() = 0; }; class MockCC : public CC { public: MockCC() = default; MOCK_METHOD0(Method, int()); private: MockCC(const MockCC&) = delete; MockCC& operator=(const MockCC&) = delete; }; TEST(OnCallSyntaxTest, CompilesWithMethodNameExpandedFromMacro) { MockCC cc; ON_CALL(cc, Method()); } TEST(OnCallSyntaxTest, WorksWithMethodNameExpandedFromMacro) { MockCC cc; ON_CALL(cc, Method()).WillByDefault(Return(42)); EXPECT_EQ(42, cc.Method()); } TEST(ExpectCallSyntaxTest, CompilesWithMethodNameExpandedFromMacro) { MockCC cc; EXPECT_CALL(cc, Method()); cc.Method(); } TEST(ExpectCallSyntaxTest, WorksWithMethodNameExpandedFromMacro) { MockCC cc; EXPECT_CALL(cc, Method()).WillOnce(Return(42)); EXPECT_EQ(42, cc.Method()); } #undef Method TEST(OnCallSyntaxTest, EvaluatesFirstArgumentOnce) { MockA a; MockA* pa = &a; ON_CALL(*pa++, DoA(_)); EXPECT_EQ(&a + 1, pa); } TEST(OnCallSyntaxTest, EvaluatesSecondArgumentOnce) { MockA a; int n = 0; ON_CALL(a, DoA(n++)); EXPECT_EQ(1, n); } TEST(OnCallSyntaxTest, WithIsOptional) { MockA a; ON_CALL(a, DoA(5)).WillByDefault(Return()); ON_CALL(a, DoA(_)).With(_).WillByDefault(Return()); } TEST(OnCallSyntaxTest, WithCanAppearAtMostOnce) { MockA a; EXPECT_NONFATAL_FAILURE( { ON_CALL(a, ReturnResult(_)) .With(_) .With(_) .WillByDefault(Return(Result())); }, ".With() cannot appear more than once in an ON_CALL()"); } TEST(OnCallSyntaxTest, WillByDefaultIsMandatory) { MockA a; EXPECT_DEATH_IF_SUPPORTED( { ON_CALL(a, DoA(5)); a.DoA(5); }, ""); } TEST(OnCallSyntaxTest, WillByDefaultCanAppearAtMostOnce) { MockA a; EXPECT_NONFATAL_FAILURE( { ON_CALL(a, DoA(5)).WillByDefault(Return()).WillByDefault(Return()); }, ".WillByDefault() must appear exactly once in an ON_CALL()"); } TEST(ExpectCallSyntaxTest, EvaluatesFirstArgumentOnce) { MockA a; MockA* pa = &a; EXPECT_CALL(*pa++, DoA(_)); a.DoA(0); EXPECT_EQ(&a + 1, pa); } TEST(ExpectCallSyntaxTest, EvaluatesSecondArgumentOnce) { MockA a; int n = 0; EXPECT_CALL(a, DoA(n++)); a.DoA(0); EXPECT_EQ(1, n); } TEST(ExpectCallSyntaxTest, WithIsOptional) { MockA a; EXPECT_CALL(a, DoA(5)).Times(0); EXPECT_CALL(a, DoA(6)).With(_).Times(0); } TEST(ExpectCallSyntaxTest, WithCanAppearAtMostOnce) { MockA a; EXPECT_NONFATAL_FAILURE( { EXPECT_CALL(a, DoA(6)).With(_).With(_); }, ".With() cannot appear more than once in an EXPECT_CALL()"); a.DoA(6); } TEST(ExpectCallSyntaxTest, WithMustBeFirstClause) { MockA a; EXPECT_NONFATAL_FAILURE( { EXPECT_CALL(a, DoA(1)).Times(1).With(_); }, ".With() must be the first clause in an EXPECT_CALL()"); a.DoA(1); EXPECT_NONFATAL_FAILURE( { EXPECT_CALL(a, DoA(2)).WillOnce(Return()).With(_); }, ".With() must be the first clause in an EXPECT_CALL()"); a.DoA(2); } TEST(ExpectCallSyntaxTest, TimesCanBeInferred) { MockA a; EXPECT_CALL(a, DoA(1)).WillOnce(Return()); EXPECT_CALL(a, DoA(2)).WillOnce(Return()).WillRepeatedly(Return()); a.DoA(1); a.DoA(2); a.DoA(2); } TEST(ExpectCallSyntaxTest, TimesCanAppearAtMostOnce) { MockA a; EXPECT_NONFATAL_FAILURE( { EXPECT_CALL(a, DoA(1)).Times(1).Times(2); }, ".Times() cannot appear more than once in an EXPECT_CALL()"); a.DoA(1); a.DoA(1); } TEST(ExpectCallSyntaxTest, TimesMustBeBeforeInSequence) { MockA a; Sequence s; EXPECT_NONFATAL_FAILURE( { EXPECT_CALL(a, DoA(1)).InSequence(s).Times(1); }, ".Times() may only appear *before* "); a.DoA(1); } TEST(ExpectCallSyntaxTest, InSequenceIsOptional) { MockA a; Sequence s; EXPECT_CALL(a, DoA(1)); EXPECT_CALL(a, DoA(2)).InSequence(s); a.DoA(1); a.DoA(2); } TEST(ExpectCallSyntaxTest, InSequenceCanAppearMultipleTimes) { MockA a; Sequence s1, s2; EXPECT_CALL(a, DoA(1)).InSequence(s1, s2).InSequence(s1); a.DoA(1); } TEST(ExpectCallSyntaxTest, InSequenceMustBeBeforeAfter) { MockA a; Sequence s; Expectation e = EXPECT_CALL(a, DoA(1)).Times(AnyNumber()); EXPECT_NONFATAL_FAILURE( { EXPECT_CALL(a, DoA(2)).After(e).InSequence(s); }, ".InSequence() cannot appear after "); a.DoA(2); } TEST(ExpectCallSyntaxTest, InSequenceMustBeBeforeWillOnce) { MockA a; Sequence s; EXPECT_NONFATAL_FAILURE( { EXPECT_CALL(a, DoA(1)).WillOnce(Return()).InSequence(s); }, ".InSequence() cannot appear after "); a.DoA(1); } TEST(ExpectCallSyntaxTest, AfterMustBeBeforeWillOnce) { MockA a; Expectation e = EXPECT_CALL(a, DoA(1)); EXPECT_NONFATAL_FAILURE( { EXPECT_CALL(a, DoA(2)).WillOnce(Return()).After(e); }, ".After() cannot appear after "); a.DoA(1); a.DoA(2); } TEST(ExpectCallSyntaxTest, WillIsOptional) { MockA a; EXPECT_CALL(a, DoA(1)); EXPECT_CALL(a, DoA(2)).WillOnce(Return()); a.DoA(1); a.DoA(2); } TEST(ExpectCallSyntaxTest, WillCanAppearMultipleTimes) { MockA a; EXPECT_CALL(a, DoA(1)) .Times(AnyNumber()) .WillOnce(Return()) .WillOnce(Return()) .WillOnce(Return()); } TEST(ExpectCallSyntaxTest, WillMustBeBeforeWillRepeatedly) { MockA a; EXPECT_NONFATAL_FAILURE( { EXPECT_CALL(a, DoA(1)).WillRepeatedly(Return()).WillOnce(Return()); }, ".WillOnce() cannot appear after "); a.DoA(1); } TEST(ExpectCallSyntaxTest, WillRepeatedlyIsOptional) { MockA a; EXPECT_CALL(a, DoA(1)).WillOnce(Return()); EXPECT_CALL(a, DoA(2)).WillOnce(Return()).WillRepeatedly(Return()); a.DoA(1); a.DoA(2); a.DoA(2); } TEST(ExpectCallSyntaxTest, WillRepeatedlyCannotAppearMultipleTimes) { MockA a; EXPECT_NONFATAL_FAILURE( { EXPECT_CALL(a, DoA(1)).WillRepeatedly(Return()).WillRepeatedly( Return()); }, ".WillRepeatedly() cannot appear more than once in an " "EXPECT_CALL()"); } TEST(ExpectCallSyntaxTest, WillRepeatedlyMustBeBeforeRetiresOnSaturation) { MockA a; EXPECT_NONFATAL_FAILURE( { EXPECT_CALL(a, DoA(1)).RetiresOnSaturation().WillRepeatedly(Return()); }, ".WillRepeatedly() cannot appear after "); } TEST(ExpectCallSyntaxTest, RetiresOnSaturationIsOptional) { MockA a; EXPECT_CALL(a, DoA(1)); EXPECT_CALL(a, DoA(1)).RetiresOnSaturation(); a.DoA(1); a.DoA(1); } TEST(ExpectCallSyntaxTest, RetiresOnSaturationCannotAppearMultipleTimes) { MockA a; EXPECT_NONFATAL_FAILURE( { EXPECT_CALL(a, DoA(1)).RetiresOnSaturation().RetiresOnSaturation(); }, ".RetiresOnSaturation() cannot appear more than once"); a.DoA(1); } TEST(ExpectCallSyntaxTest, DefaultCardinalityIsOnce) { { MockA a; EXPECT_CALL(a, DoA(1)); a.DoA(1); } EXPECT_NONFATAL_FAILURE( { MockA a; EXPECT_CALL(a, DoA(1)); }, "to be called once"); EXPECT_NONFATAL_FAILURE( { MockA a; EXPECT_CALL(a, DoA(1)); a.DoA(1); a.DoA(1); }, "to be called once"); } #if GTEST_HAS_STREAM_REDIRECTION TEST(ExpectCallSyntaxTest, DoesNotWarnOnAdequateActionCount) { CaptureStdout(); { MockB b; EXPECT_CALL(b, DoB()).Times(0); EXPECT_CALL(b, DoB(1)).Times(AtMost(1)); EXPECT_CALL(b, DoB(2)).Times(1).WillRepeatedly(Return(1)); EXPECT_CALL(b, DoB(3)) .Times(Between(1, 2)) .WillOnce(Return(1)) .WillOnce(Return(2)); EXPECT_CALL(b, DoB(4)).Times(AtMost(3)).WillOnce(Return(1)).WillRepeatedly( Return(2)); b.DoB(2); b.DoB(3); } EXPECT_STREQ("", GetCapturedStdout().c_str()); } TEST(ExpectCallSyntaxTest, WarnsOnTooManyActions) { CaptureStdout(); { MockB b; EXPECT_CALL(b, DoB()).Times(0).WillOnce(Return(1)); EXPECT_CALL(b, DoB()).Times(AtMost(1)).WillOnce(Return(1)).WillOnce( Return(2)); EXPECT_CALL(b, DoB(1)) .Times(1) .WillOnce(Return(1)) .WillOnce(Return(2)) .RetiresOnSaturation(); EXPECT_CALL(b, DoB()).Times(0).WillRepeatedly(Return(1)); EXPECT_CALL(b, DoB(2)).Times(1).WillOnce(Return(1)).WillRepeatedly( Return(2)); b.DoB(1); b.DoB(2); } const std::string output = GetCapturedStdout(); EXPECT_PRED_FORMAT2(IsSubstring, "Too many actions specified in EXPECT_CALL(b, DoB())...\n" "Expected to be never called, but has 1 WillOnce().", output); EXPECT_PRED_FORMAT2(IsSubstring, "Too many actions specified in EXPECT_CALL(b, DoB())...\n" "Expected to be called at most once, " "but has 2 WillOnce()s.", output); EXPECT_PRED_FORMAT2( IsSubstring, "Too many actions specified in EXPECT_CALL(b, DoB(1))...\n" "Expected to be called once, but has 2 WillOnce()s.", output); EXPECT_PRED_FORMAT2(IsSubstring, "Too many actions specified in EXPECT_CALL(b, DoB())...\n" "Expected to be never called, but has 0 WillOnce()s " "and a WillRepeatedly().", output); EXPECT_PRED_FORMAT2( IsSubstring, "Too many actions specified in EXPECT_CALL(b, DoB(2))...\n" "Expected to be called once, but has 1 WillOnce() " "and a WillRepeatedly().", output); } TEST(ExpectCallSyntaxTest, WarnsOnTooFewActions) { MockB b; EXPECT_CALL(b, DoB()).Times(Between(2, 3)).WillOnce(Return(1)); CaptureStdout(); b.DoB(); const std::string output = GetCapturedStdout(); EXPECT_PRED_FORMAT2(IsSubstring, "Too few actions specified in EXPECT_CALL(b, DoB())...\n" "Expected to be called between 2 and 3 times, " "but has only 1 WillOnce().", output); b.DoB(); } TEST(ExpectCallSyntaxTest, WarningIsErrorWithFlag) { int original_behavior = GMOCK_FLAG_GET(default_mock_behavior); GMOCK_FLAG_SET(default_mock_behavior, kAllow); CaptureStdout(); { MockA a; a.DoA(0); } std::string output = GetCapturedStdout(); EXPECT_TRUE(output.empty()) << output; GMOCK_FLAG_SET(default_mock_behavior, kWarn); CaptureStdout(); { MockA a; a.DoA(0); } std::string warning_output = GetCapturedStdout(); EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", warning_output); EXPECT_PRED_FORMAT2(IsSubstring, "Uninteresting mock function call", warning_output); GMOCK_FLAG_SET(default_mock_behavior, kFail); EXPECT_NONFATAL_FAILURE( { MockA a; a.DoA(0); }, "Uninteresting mock function call"); GMOCK_FLAG_SET(default_mock_behavior, -1); CaptureStdout(); { MockA a; a.DoA(0); } warning_output = GetCapturedStdout(); EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", warning_output); EXPECT_PRED_FORMAT2(IsSubstring, "Uninteresting mock function call", warning_output); GMOCK_FLAG_SET(default_mock_behavior, 3); CaptureStdout(); { MockA a; a.DoA(0); } warning_output = GetCapturedStdout(); EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", warning_output); EXPECT_PRED_FORMAT2(IsSubstring, "Uninteresting mock function call", warning_output); GMOCK_FLAG_SET(default_mock_behavior, original_behavior); } #endif TEST(OnCallTest, TakesBuiltInDefaultActionWhenNoOnCall) { MockB b; EXPECT_CALL(b, DoB()); EXPECT_EQ(0, b.DoB()); } TEST(OnCallTest, TakesBuiltInDefaultActionWhenNoOnCallMatches) { MockB b; ON_CALL(b, DoB(1)).WillByDefault(Return(1)); EXPECT_CALL(b, DoB(_)); EXPECT_EQ(0, b.DoB(2)); } TEST(OnCallTest, PicksLastMatchingOnCall) { MockB b; ON_CALL(b, DoB(_)).WillByDefault(Return(3)); ON_CALL(b, DoB(2)).WillByDefault(Return(2)); ON_CALL(b, DoB(1)).WillByDefault(Return(1)); EXPECT_CALL(b, DoB(_)); EXPECT_EQ(2, b.DoB(2)); } TEST(ExpectCallTest, AllowsAnyCallWhenNoSpec) { MockB b; EXPECT_CALL(b, DoB()); b.DoB(); b.DoB(1); b.DoB(2); } TEST(ExpectCallTest, PicksLastMatchingExpectCall) { MockB b; EXPECT_CALL(b, DoB(_)).WillRepeatedly(Return(2)); EXPECT_CALL(b, DoB(1)).WillRepeatedly(Return(1)); EXPECT_EQ(1, b.DoB(1)); } TEST(ExpectCallTest, CatchesTooFewCalls) { EXPECT_NONFATAL_FAILURE( { MockB b; EXPECT_CALL(b, DoB(5)).Description("DoB Method").Times(AtLeast(2)); b.DoB(5); }, "Actual function \"DoB Method\" call count " "doesn't match EXPECT_CALL(b, DoB(5))...\n" " Expected: to be called at least twice\n" " Actual: called once - unsatisfied and active"); } TEST(ExpectCallTest, InfersCardinalityWhenThereIsNoWillRepeatedly) { { MockB b; EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillOnce(Return(2)); EXPECT_EQ(1, b.DoB()); EXPECT_EQ(2, b.DoB()); } EXPECT_NONFATAL_FAILURE( { MockB b; EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillOnce(Return(2)); EXPECT_EQ(1, b.DoB()); }, "to be called twice"); { MockB b; EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillOnce(Return(2)); EXPECT_EQ(1, b.DoB()); EXPECT_EQ(2, b.DoB()); EXPECT_NONFATAL_FAILURE(b.DoB(), "to be called twice"); } } TEST(ExpectCallTest, InfersCardinality1WhenThereIsWillRepeatedly) { { MockB b; EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillRepeatedly(Return(2)); EXPECT_EQ(1, b.DoB()); } { MockB b; EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillRepeatedly(Return(2)); EXPECT_EQ(1, b.DoB()); EXPECT_EQ(2, b.DoB()); EXPECT_EQ(2, b.DoB()); } EXPECT_NONFATAL_FAILURE( { MockB b; EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillRepeatedly(Return(2)); }, "to be called at least once"); } #if defined(GTEST_INTERNAL_CPLUSPLUS_LANG) && \ GTEST_INTERNAL_CPLUSPLUS_LANG >= 201703L TEST(ExpectCallTest, NonMoveableType) { struct NonMoveableStruct { explicit NonMoveableStruct(int x_in) : x(x_in) {} NonMoveableStruct(NonMoveableStruct&&) = delete; int x; }; static_assert(!std::is_move_constructible_v<NonMoveableStruct>); static_assert(!std::is_copy_constructible_v<NonMoveableStruct>); static_assert(!std::is_move_assignable_v<NonMoveableStruct>); static_assert(!std::is_copy_assignable_v<NonMoveableStruct>); const auto return_17 = [] { return NonMoveableStruct(17); }; static_cast<void>(OnceAction<NonMoveableStruct()>{return_17}); static_cast<void>(Action<NonMoveableStruct()>{return_17}); static_cast<void>(OnceAction<NonMoveableStruct(int)>{return_17}); static_cast<void>(Action<NonMoveableStruct(int)>{return_17}); MockFunction<NonMoveableStruct()> mock; EXPECT_CALL(mock, Call) .WillOnce(return_17) .WillRepeatedly(return_17); EXPECT_EQ(17, mock.AsStdFunction()().x); EXPECT_EQ(17, mock.AsStdFunction()().x); EXPECT_EQ(17, mock.AsStdFunction()().x); } #endif TEST(ExpectCallTest, NthMatchTakesNthAction) { MockB b; EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillOnce(Return(2)).WillOnce( Return(3)); EXPECT_EQ(1, b.DoB()); EXPECT_EQ(2, b.DoB()); EXPECT_EQ(3, b.DoB()); } TEST(ExpectCallTest, TakesRepeatedActionWhenWillListIsExhausted) { MockB b; EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillRepeatedly(Return(2)); EXPECT_EQ(1, b.DoB()); EXPECT_EQ(2, b.DoB()); EXPECT_EQ(2, b.DoB()); } #if GTEST_HAS_STREAM_REDIRECTION TEST(ExpectCallTest, TakesDefaultActionWhenWillListIsExhausted) { MockB b; EXPECT_CALL(b, DoB(_)).Times(1); EXPECT_CALL(b, DoB()) .Times(AnyNumber()) .WillOnce(Return(1)) .WillOnce(Return(2)); CaptureStdout(); EXPECT_EQ(0, b.DoB(1)); EXPECT_EQ(1, b.DoB()); EXPECT_EQ(2, b.DoB()); const std::string output1 = GetCapturedStdout(); EXPECT_STREQ("", output1.c_str()); CaptureStdout(); EXPECT_EQ(0, b.DoB()); EXPECT_EQ(0, b.DoB()); const std::string output2 = GetCapturedStdout(); EXPECT_THAT(output2.c_str(), HasSubstr("Actions ran out in EXPECT_CALL(b, DoB())...\n" "Called 3 times, but only 2 WillOnce()s are specified" " - returning default value.")); EXPECT_THAT(output2.c_str(), HasSubstr("Actions ran out in EXPECT_CALL(b, DoB())...\n" "Called 4 times, but only 2 WillOnce()s are specified" " - returning default value.")); } TEST(FunctionMockerMessageTest, ReportsExpectCallLocationForExhaustedActions) { MockB b; std::string expect_call_location = FormatFileLocation(__FILE__, __LINE__ + 1); EXPECT_CALL(b, DoB()).Times(AnyNumber()).WillOnce(Return(1)); EXPECT_EQ(1, b.DoB()); CaptureStdout(); EXPECT_EQ(0, b.DoB()); const std::string output = GetCapturedStdout(); EXPECT_PRED_FORMAT2(IsSubstring, expect_call_location, output); } TEST(FunctionMockerMessageTest, ReportsDefaultActionLocationOfUninterestingCallsForNaggyMock) { std::string on_call_location; CaptureStdout(); { NaggyMock<MockB> b; on_call_location = FormatFileLocation(__FILE__, __LINE__ + 1); ON_CALL(b, DoB(_)).WillByDefault(Return(0)); b.DoB(0); } EXPECT_PRED_FORMAT2(IsSubstring, on_call_location, GetCapturedStdout()); } #endif TEST(UninterestingCallTest, DoesDefaultAction) { MockA a; ON_CALL(a, Binary(_, _)).WillByDefault(Return(true)); EXPECT_TRUE(a.Binary(1, 2)); MockB b; EXPECT_EQ(0, b.DoB()); } TEST(UnexpectedCallTest, DoesDefaultAction) { MockA a; ON_CALL(a, Binary(_, _)).WillByDefault(Return(true)); EXPECT_CALL(a, Binary(0, 0)); a.Binary(0, 0); bool result = false; EXPECT_NONFATAL_FAILURE(result = a.Binary(1, 2), "Unexpected mock function call"); EXPECT_TRUE(result); MockB b; EXPECT_CALL(b, DoB(0)).Times(0); int n = -1; EXPECT_NONFATAL_FAILURE(n = b.DoB(1), "Unexpected mock function call"); EXPECT_EQ(0, n); } TEST(UnexpectedCallTest, GeneratesFailureForVoidFunction) { MockA a1; EXPECT_CALL(a1, DoA(1)); a1.DoA(1); EXPECT_NONFATAL_FAILURE( a1.DoA(9), "Unexpected mock function call - returning directly.\n" " Function call: DoA(9)\n" "Google Mock tried the following 1 expectation, but it didn't match:"); EXPECT_NONFATAL_FAILURE( a1.DoA(9), " Expected arg #0: is equal to 1\n" " Actual: 9\n" " Expected: to be called once\n" " Actual: called once - saturated and active"); MockA a2; EXPECT_CALL(a2, DoA(1)); EXPECT_CALL(a2, DoA(3)); a2.DoA(1); EXPECT_NONFATAL_FAILURE( a2.DoA(2), "Unexpected mock function call - returning directly.\n" " Function call: DoA(2)\n" "Google Mock tried the following 2 expectations, but none matched:"); EXPECT_NONFATAL_FAILURE( a2.DoA(2), "tried expectation #0: EXPECT_CALL(a2, DoA(1))...\n" " Expected arg #0: is equal to 1\n" " Actual: 2\n" " Expected: to be called once\n" " Actual: called once - saturated and active"); EXPECT_NONFATAL_FAILURE( a2.DoA(2), "tried expectation #1: EXPECT_CALL(a2, DoA(3))...\n" " Expected arg #0: is equal to 3\n" " Actual: 2\n" " Expected: to be called once\n" " Actual: never called - unsatisfied and active"); a2.DoA(3); } TEST(UnexpectedCallTest, GeneartesFailureForNonVoidFunction) { MockB b1; EXPECT_CALL(b1, DoB(1)); b1.DoB(1); EXPECT_NONFATAL_FAILURE( b1.DoB(2), "Unexpected mock function call - returning default value.\n" " Function call: DoB(2)\n" " Returns: 0\n" "Google Mock tried the following 1 expectation, but it didn't match:"); EXPECT_NONFATAL_FAILURE( b1.DoB(2), " Expected arg #0: is equal to 1\n" " Actual: 2\n" " Expected: to be called once\n" " Actual: called once - saturated and active"); } TEST(UnexpectedCallTest, RetiredExpectation) { MockB b; EXPECT_CALL(b, DoB(1)).RetiresOnSaturation(); b.DoB(1); EXPECT_NONFATAL_FAILURE(b.DoB(1), " Expected: the expectation is active\n" " Actual: it is retired"); } TEST(UnexpectedCallTest, UnmatchedArguments) { MockB b; EXPECT_CALL(b, DoB(1)); EXPECT_NONFATAL_FAILURE(b.DoB(2), " Expected arg #0: is equal to 1\n" " Actual: 2\n"); b.DoB(1); } TEST(UnexpectedCallTest, UnsatisfiedPrerequisites) { Sequence s1, s2; MockB b; EXPECT_CALL(b, DoB(1)).InSequence(s1); EXPECT_CALL(b, DoB(2)).Times(AnyNumber()).InSequence(s1); EXPECT_CALL(b, DoB(3)).InSequence(s2); EXPECT_CALL(b, DoB(4)).InSequence(s1, s2); ::testing::TestPartResultArray failures; { ::testing::ScopedFakeTestPartResultReporter reporter(&failures); b.DoB(4); } ASSERT_EQ(1, failures.size()); const ::testing::TestPartResult& r = failures.GetTestPartResult(0); EXPECT_EQ(::testing::TestPartResult::kNonFatalFailure, r.type()); #ifdef GTEST_USES_POSIX_RE EXPECT_THAT(r.message(), ContainsRegex( "the following immediate pre-requisites are not satisfied:\n" "(.|\n)*: pre-requisite #0\n" "(.|\n)*: pre-requisite #1")); #else EXPECT_THAT(r.message(), ContainsRegex( "the following immediate pre-requisites are not satisfied:")); EXPECT_THAT(r.message(), ContainsRegex(": pre-requisite #0")); EXPECT_THAT(r.message(), ContainsRegex(": pre-requisite #1")); #endif b.DoB(1); b.DoB(3); b.DoB(4); } TEST(UndefinedReturnValueTest, ReturnValueIsMandatoryWhenNotDefaultConstructible) { MockA a; #if GTEST_HAS_EXCEPTIONS EXPECT_ANY_THROW(a.ReturnNonDefaultConstructible()); #else EXPECT_DEATH_IF_SUPPORTED(a.ReturnNonDefaultConstructible(), ""); #endif } TEST(ExcessiveCallTest, DoesDefaultAction) { MockA a; ON_CALL(a, Binary(_, _)).WillByDefault(Return(true)); EXPECT_CALL(a, Binary(0, 0)); a.Binary(0, 0); bool result = false; EXPECT_NONFATAL_FAILURE(result = a.Binary(0, 0), "Mock f
2,331
cpp
google/arolla
complex
null
null
#ifndef AROLLA_EXAMPLES_CUSTOM_QTYPE_COMPLEX_H_ #define AROLLA_EXAMPLES_CUSTOM_QTYPE_COMPLEX_H_ #include "arolla/qtype/simple_qtype.h" #include "arolla/util/fingerprint.h" #include "arolla/util/repr.h" namespace my_namespace { struct MyComplex { double re; double im; }; } namespace arolla { AROLLA_DECLARE_FINGERPRINT_HASHER_TRAITS(my_namespace::MyComplex); AROLLA_DECLARE_REPR(my_namespace::MyComplex); AROLLA_DECLARE_SIMPLE_QTYPE(MY_COMPLEX, my_namespace::MyComplex); } #endif #include "arolla/examples/custom_qtype/complex.h" #include "absl/strings/str_format.h" #include "arolla/qtype/simple_qtype.h" #include "arolla/util/fingerprint.h" #include "arolla/util/repr.h" namespace arolla { void FingerprintHasherTraits<my_namespace::MyComplex>::operator()( FingerprintHasher* hasher, const my_namespace::MyComplex& value) const { hasher->Combine(value.im, value.re); } ReprToken ReprTraits<my_namespace::MyComplex>::operator()( const my_namespace::MyComplex& value) const { return ReprToken{absl::StrFormat("%v + %vi", value.re, value.im)}; } AROLLA_DEFINE_SIMPLE_QTYPE(MY_COMPLEX, my_namespace::MyComplex); }
#include "arolla/examples/custom_qtype/complex.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/util/fingerprint.h" #include "arolla/util/init_arolla.h" #include "arolla/util/repr.h" namespace my_namespace { namespace { using ::testing::Eq; using ::testing::Ne; class ComplexTest : public ::testing::Test { void SetUp() override { ASSERT_OK(arolla::InitArolla()); } }; TEST_F(ComplexTest, GetQType) { EXPECT_THAT(arolla::GetQType<MyComplex>()->name(), Eq("MY_COMPLEX")); } TEST_F(ComplexTest, Fingerprint) { MyComplex c{.re = 5.7, .im = 0.7}; auto c_fingerprint = arolla::FingerprintHasher("").Combine(c).Finish(); EXPECT_THAT(arolla::FingerprintHasher("").Combine(c).Finish(), Eq(c_fingerprint)); EXPECT_THAT(arolla::FingerprintHasher("") .Combine(MyComplex{.re = 0.7, .im = 5.7}) .Finish(), Ne(c_fingerprint)); } TEST_F(ComplexTest, Repr) { EXPECT_THAT(arolla::Repr(MyComplex{}), Eq("0 + 0i")); EXPECT_THAT(arolla::Repr(MyComplex{.re = 5.7, .im = 0.7}), Eq("5.7 + 0.7i")); } } }
2,332
cpp
google/arolla
table
arolla/naming/table.cc
arolla/naming/table_test.cc
#ifndef AROLLA_NAMING_TABLE_H_ #define AROLLA_NAMING_TABLE_H_ #include <cstddef> #include <optional> #include <ostream> #include <string> #include <utility> #include <vector> #include "absl/hash/hash.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "arolla/util/types.h" namespace arolla::naming { constexpr absl::string_view kSizeColumnName = "@size"; constexpr absl::string_view kExtensionFieldPrefix = "Ext::"; constexpr absl::string_view kIndexMarker = "[:]"; inline std::string FieldAccess(absl::string_view field_name) { return std::string(field_name); } inline std::string MapAccess(absl::string_view field_name, absl::string_view key) { return absl::StrCat(field_name, "[\"", key, "\"]"); } inline std::string ArrayAccess(absl::string_view field_name, size_t idx) { return absl::StrCat(field_name, "[", idx, "]"); } inline std::string ProtoExtensionAccess(absl::string_view ext_name) { return absl::StrCat(kExtensionFieldPrefix, ext_name); } class PathSegment { public: PathSegment(absl::string_view field_name, bool is_index) : field_name_(field_name), is_index_(is_index) {} const std::string& FieldName() const { return field_name_; } bool IsIndex() const { return is_index_; } template <typename H> friend H AbslHashValue(H h, const PathSegment& s) { return H::combine(std::move(h), s.field_name_, s.is_index_); } signed_size_t PythonHash() const { return absl::Hash<PathSegment>()(*this); } std::string DebugString() const; private: std::string field_name_; bool is_index_; }; inline bool operator==(const PathSegment& a, const PathSegment& b) { return std::pair(a.FieldName(), a.IsIndex()) == std::pair(b.FieldName(), b.IsIndex()); } inline bool operator!=(const PathSegment& a, const PathSegment& b) { return std::pair(a.FieldName(), a.IsIndex()) != std::pair(b.FieldName(), b.IsIndex()); } inline bool operator<(const PathSegment& a, const PathSegment& b) { return std::pair(a.FieldName(), a.IsIndex()) < std::pair(b.FieldName(), b.IsIndex()); } class ColumnPath; class TablePath { public: TablePath() = default; explicit TablePath(std::vector<PathSegment> path_segments) : path_segments_(std::move(path_segments)) {} explicit TablePath(absl::string_view name, bool is_index = false) : TablePath({PathSegment(name, is_index)}) {} TablePath Child(PathSegment path_segment) const& { std::vector<PathSegment> segments{path_segments_}; segments.push_back(std::move(path_segment)); return TablePath{std::move(segments)}; } TablePath Child(PathSegment path_segment) && { path_segments_.push_back(std::move(path_segment)); return TablePath{std::move(path_segments_)}; } TablePath Child(absl::string_view name, bool is_index = false) const& { return this->Child(PathSegment(name, is_index)); } TablePath Child(absl::string_view name, bool is_index = false) && { return std::move(*this).Child(PathSegment(name, is_index)); } TablePath Child(const TablePath& suffix) const { TablePath ret = *this; for (const PathSegment& path_segment : suffix.path_segments_) { ret = std::move(ret).Child(path_segment); } return ret; } ColumnPath Column(PathSegment path_segment) const; ColumnPath Column(absl::string_view name, bool is_index = false) const; ColumnPath Column(const ColumnPath& column) const; ColumnPath Size(absl::string_view name) const; ColumnPath Size(const TablePath& child) const; TablePath MapKeys() const { return Child("@key", false); } TablePath MapValues() const { return Child("@value", false); } const std::vector<PathSegment>& PathSegments() const { return path_segments_; } std::string FullName() const; std::optional<TablePath> ParentIndexPath() const; absl::StatusOr<TablePath> RemovePrefix(const TablePath& prefix) const; template <typename H> friend H AbslHashValue(H h, const TablePath& t) { return H::combine(std::move(h), t.path_segments_); } signed_size_t PythonHash() const { return absl::Hash<TablePath>()(*this); } std::string DebugString() const; private: std::vector<PathSegment> path_segments_; }; class ColumnPath { public: ColumnPath() = default; explicit ColumnPath(std::vector<PathSegment> path_segments) : path_segments_(std::move(path_segments)) {} explicit ColumnPath(absl::string_view name, bool is_index = false) : ColumnPath({PathSegment(name, is_index)}) {} const std::vector<PathSegment>& PathSegments() const { return path_segments_; } std::string FullName() const; TablePath ParentIndexPath() const; absl::StatusOr<ColumnPath> RemovePrefix(const TablePath& prefix) const; std::string DebugString() const; template <typename H> friend H AbslHashValue(H h, const ColumnPath& c) { return H::combine(std::move(h), c.FullName()); } signed_size_t PythonHash() const { return absl::Hash<ColumnPath>()(*this); } friend std::ostream& operator<<(std::ostream& stream, const ColumnPath& path) { stream << path.DebugString(); return stream; } private: std::vector<PathSegment> path_segments_; }; inline bool operator==(const TablePath& a, const TablePath& b) { return a.PathSegments() == b.PathSegments(); } inline bool operator!=(const TablePath& a, const TablePath& b) { return a.PathSegments() != b.PathSegments(); } inline bool operator<(const TablePath& a, const TablePath& b) { return a.PathSegments() < b.PathSegments(); } inline bool operator==(const ColumnPath& a, const ColumnPath& b) { return a.PathSegments() == b.PathSegments(); } inline bool operator!=(const ColumnPath& a, const ColumnPath& b) { return a.PathSegments() != b.PathSegments(); } inline bool operator<(const ColumnPath& a, const ColumnPath& b) { return a.PathSegments() < b.PathSegments(); } } #endif #include "arolla/naming/table.h" #include <cstddef> #include <optional> #include <string> #include <utility> #include <vector> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "arolla/util/status_macros_backport.h" namespace arolla::naming { namespace { std::string FormatSegments(const std::vector<PathSegment>& segments, bool show_index_markers) { std::string ret; for (const PathSegment& segment : segments) { ret += '/'; ret += segment.FieldName(); if (show_index_markers && segment.IsIndex()) { ret += std::string(kIndexMarker); } } return ret; } } std::string PathSegment::DebugString() const { return absl::StrFormat("PathSegment(\"%s\", is_index=%s)", field_name_, is_index_ ? "True" : "False"); } ColumnPath TablePath::Column(PathSegment segment) const { std::vector<PathSegment> segments{path_segments_}; segments.emplace_back(std::move(segment)); return ColumnPath(std::move(segments)); } ColumnPath TablePath::Column(absl::string_view name, bool is_index) const { return Column(PathSegment(name, is_index)); } ColumnPath TablePath::Column(const ColumnPath& column) const { std::vector<PathSegment> segments; segments.reserve(path_segments_.size() + column.PathSegments().size()); for (const PathSegment& path_segment : path_segments_) { segments.push_back(path_segment); } for (const PathSegment& path_segment : column.PathSegments()) { segments.push_back(path_segment); } return ColumnPath(std::move(segments)); } ColumnPath TablePath::Size(absl::string_view name) const { return name.empty() ? Column(kSizeColumnName) : Child(name).Column(kSizeColumnName); } ColumnPath TablePath::Size(const TablePath& child) const { return Child(child).Column(kSizeColumnName); } std::string TablePath::FullName() const { return FormatSegments(path_segments_, false); } std::string ColumnPath::FullName() const { return FormatSegments(path_segments_, false); } std::string TablePath::DebugString() const { return absl::StrFormat("TablePath(\"%s\")", FormatSegments(path_segments_, true)); } std::string ColumnPath::DebugString() const { return absl::StrFormat("ColumnPath(\"%s\")", FormatSegments(path_segments_, true)); } std::optional<TablePath> TablePath::ParentIndexPath() const { std::vector<PathSegment> segments{path_segments_}; if (segments.empty()) { return std::nullopt; } if (segments.back().IsIndex()) { segments.pop_back(); } while (!segments.empty() && !segments.back().IsIndex()) { segments.pop_back(); } return TablePath(std::move(segments)); } TablePath ColumnPath::ParentIndexPath() const { std::vector<PathSegment> segments = {path_segments_}; while (!segments.empty() && !segments.back().IsIndex()) { segments.pop_back(); } return TablePath(std::move(segments)); } namespace { absl::StatusOr<std::vector<PathSegment>> RemovePrefixSegments( const std::vector<PathSegment>& path_segments, const TablePath& prefix) { absl::Span<const PathSegment> segs = absl::MakeSpan(path_segments); const size_t prefix_len = prefix.PathSegments().size(); if (segs.subspan(0, prefix_len) != absl::MakeSpan(prefix.PathSegments())) { return absl::InvalidArgumentError( absl::StrFormat("%s must be a prefix of %s", prefix.DebugString(), FormatSegments(path_segments, true))); } absl::Span<const PathSegment> suffix = segs.subspan(prefix_len); return std::vector<PathSegment>(suffix.begin(), suffix.end()); } } absl::StatusOr<TablePath> TablePath::RemovePrefix( const TablePath& prefix) const { ASSIGN_OR_RETURN(std::vector<PathSegment> suffix, RemovePrefixSegments(PathSegments(), prefix)); return TablePath(std::move(suffix)); } absl::StatusOr<ColumnPath> ColumnPath::RemovePrefix( const TablePath& prefix) const { ASSIGN_OR_RETURN(std::vector<PathSegment> suffix, RemovePrefixSegments(PathSegments(), prefix)); return ColumnPath(std::move(suffix)); } }
#include "arolla/naming/table.h" #include <optional> #include <sstream> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "arolla/util/testing/status_matchers_backport.h" using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::StatusIs; namespace arolla::naming { namespace { TEST(Field, simple) { EXPECT_EQ(FieldAccess("aaa"), "aaa"); EXPECT_EQ(MapAccess("dict", "zz"), "dict[\"zz\"]"); EXPECT_EQ(ArrayAccess("lst", 3), "lst[3]"); EXPECT_EQ(ProtoExtensionAccess("package.bar"), "Ext::package.bar"); } TEST(PathSegment, simple) { PathSegment seg("foo", true); EXPECT_EQ(seg.FieldName(), "foo"); EXPECT_TRUE(seg.IsIndex()); EXPECT_EQ(seg, PathSegment("foo", true)); EXPECT_NE(seg, PathSegment("bar", true)); EXPECT_NE(seg.PythonHash(), PathSegment("bar", true).PythonHash()); EXPECT_EQ(seg.DebugString(), "PathSegment(\"foo\", is_index=True)"); } TEST(TablePath, simple) { TablePath scalar; EXPECT_EQ(scalar.FullName(), ""); TablePath query("query"); EXPECT_EQ(query.FullName(), "/query"); TablePath experiment = scalar.Child("exp"); EXPECT_EQ(experiment.FullName(), "/exp"); TablePath doc = query.Child("docs"); EXPECT_EQ(doc.FullName(), "/query/docs"); TablePath token = doc.Child("details").Child("token"); EXPECT_EQ(token.FullName(), "/query/docs/details/token"); TablePath term = query.Child("query_details").Child("terms"); EXPECT_EQ(term.FullName(), "/query/query_details/terms"); EXPECT_EQ(term.Child(doc).FullName(), "/query/query_details/terms/query/docs"); EXPECT_EQ(term.Child(scalar).FullName(), "/query/query_details/terms"); EXPECT_EQ(scalar.Child(scalar).FullName(), ""); } TEST(ColumnPath, simple) { EXPECT_EQ(ColumnPath("exp_id").FullName(), "/exp_id"); TablePath query("query"); EXPECT_EQ(query.Column("query_id").FullName(), "/query/query_id"); EXPECT_EQ(query.Child("docs").Child("doc_id").Column("id").FullName(), "/query/docs/doc_id/id"); EXPECT_EQ(query.Column(TablePath("query_details").Column("abc")).FullName(), "/query/query_details/abc"); EXPECT_EQ(query.Child("docs").Size("doc_id").FullName(), "/query/docs/doc_id/@size"); EXPECT_EQ( query.Child("docs").Size(TablePath("title").Child("terms")).FullName(), "/query/docs/title/terms/@size"); EXPECT_EQ(TablePath().Size("").FullName(), "/@size"); EXPECT_EQ(TablePath().Size(TablePath()).FullName(), "/@size"); EXPECT_EQ(query.Child("docs").Child("doc_id").MapKeys().FullName(), "/query/docs/doc_id/@key"); EXPECT_EQ(query.Child("docs").Child("doc_id").MapValues().FullName(), "/query/docs/doc_id/@value"); } TEST(TablePath, comparison) { EXPECT_EQ(TablePath("foo").Child("bar"), TablePath("foo").Child("bar")); EXPECT_NE(TablePath("foo").Child("bar"), TablePath("foo").Child("baz")); EXPECT_NE(TablePath("foo").Child("bar", false), TablePath("foo").Child("bar", true)); EXPECT_LT(TablePath("foo").Child("bar", false), TablePath("foo").Child("bar", true)); } TEST(ColumnPath, comparison) { EXPECT_EQ(TablePath("foo").Column("bar"), TablePath("foo").Column(PathSegment{"bar", false})); EXPECT_NE(TablePath("foo").Column("bar"), ColumnPath()); EXPECT_NE(TablePath("foo").Column("bar"), ColumnPath("foo/bar")); EXPECT_NE(TablePath("foo").Column("bar"), TablePath("foo").Column("baz")); EXPECT_NE(TablePath("foo").Column(PathSegment{"bar", true}), TablePath("foo").Column(PathSegment{"bar", false})); } TEST(TablePath, ParentIndexPath) { EXPECT_EQ(TablePath().ParentIndexPath(), std::nullopt); EXPECT_EQ(TablePath("foo").ParentIndexPath(), TablePath()); EXPECT_EQ(TablePath("foo").Child("bar").ParentIndexPath(), TablePath()); TablePath queries("queries", true); EXPECT_EQ(queries.ParentIndexPath(), TablePath()); EXPECT_EQ(queries.Child("docs", true).ParentIndexPath(), queries); EXPECT_EQ(queries.Child("first_doc", false).ParentIndexPath(), queries); } TEST(ColumnPath, ParentIndexPath) { EXPECT_EQ(ColumnPath("foo").ParentIndexPath(), TablePath()); EXPECT_EQ(TablePath("foo").Column("bar").ParentIndexPath(), TablePath()); TablePath queries("queries", true); EXPECT_EQ(queries.Column("query_text").ParentIndexPath(), queries); EXPECT_EQ(queries.Child("t").Column("c").ParentIndexPath(), queries); ColumnPath repeated_int_field = queries.Column("numbers", true); EXPECT_EQ(repeated_int_field.ParentIndexPath().PathSegments(), (std::vector<PathSegment>{{"queries", true}, {"numbers", true}})); } TEST(TablePath, RemovePrefix) { TablePath table_path = TablePath().Child("foo", true).Child("bar").Child("baz"); EXPECT_THAT(table_path.RemovePrefix(TablePath().Child("foo", true)), IsOkAndHolds(TablePath().Child("bar").Child("baz"))); EXPECT_THAT(table_path.RemovePrefix(TablePath()), IsOkAndHolds(table_path)); EXPECT_THAT(table_path.RemovePrefix(table_path), IsOkAndHolds(TablePath())); } TEST(ColumnPath, RemovePrefix) { ColumnPath column_path = TablePath().Child("foo", true).Child("bar").Column("baz"); EXPECT_THAT(column_path.RemovePrefix(TablePath().Child("foo", true)), IsOkAndHolds(TablePath().Child("bar").Column("baz"))); EXPECT_THAT(column_path.RemovePrefix(TablePath()), IsOkAndHolds(column_path)); EXPECT_THAT(column_path.RemovePrefix(TablePath().Child("fo", true)), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT(column_path.RemovePrefix( TablePath().Child("a").Child("b").Child("c").Child("d")), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT(column_path.RemovePrefix(TablePath().Child("foo", false)), StatusIs(absl::StatusCode::kInvalidArgument)); } TEST(TablePath, DebugString) { EXPECT_EQ(TablePath("foo").Child("bar", true).Child("baz").DebugString(), "TablePath(\"/foo/bar[:]/baz\")"); } TEST(ColumnPath, DebugString) { EXPECT_EQ(TablePath("foo").Child("bar", true).Column("baz").DebugString(), "ColumnPath(\"/foo/bar[:]/baz\")"); std::stringstream ss; ss << TablePath("foo").Child("bar", true).Column("baz"); EXPECT_EQ(ss.str(), "ColumnPath(\"/foo/bar[:]/baz\")"); } TEST(PathSegment, PythonHash) { EXPECT_EQ(PathSegment("foo", true).PythonHash(), PathSegment("foo", true).PythonHash()); EXPECT_NE(PathSegment("foo", true).PythonHash(), PathSegment("foo", false).PythonHash()); EXPECT_NE(PathSegment("foo", true).PythonHash(), PathSegment("bar", true).PythonHash()); EXPECT_NE(PathSegment("foo", true).PythonHash(), TablePath("foo", true).PythonHash()); EXPECT_NE(PathSegment("foo", true).PythonHash(), ColumnPath("foo", true).PythonHash()); EXPECT_NE(TablePath("foo", true).PythonHash(), ColumnPath("foo", true).PythonHash()); } } }
2,333
cpp
google/arolla
protopath_id
arolla/naming/protopath_id.cc
arolla/naming/protopath_id_test.cc
#ifndef AROLLA_NAMING_PROTOPATH_ID_H_ #define AROLLA_NAMING_PROTOPATH_ID_H_ #include <string> #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "arolla/naming/table.h" namespace arolla::naming { std::string TablePathToProtopathId(const TablePath& table_path); std::string ColumnPathToProtopathId(const ColumnPath& column_path); absl::StatusOr<TablePath> TablePathFromProtopathId( absl::string_view protopath_id); absl::StatusOr<ColumnPath> ColumnPathFromProtopathId( absl::string_view protopath_id); } #endif #include "arolla/naming/protopath_id.h" #include <cstddef> #include <string> #include <utility> #include <vector> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" #include "absl/strings/str_join.h" #include "absl/strings/string_view.h" #include "absl/strings/strip.h" #include "arolla/naming/table.h" #include "arolla/util/status_macros_backport.h" namespace arolla::naming { namespace { std::string FormatAsProtopathId(const std::vector<PathSegment>& segments) { return absl::StrJoin(segments, "", [](std::string* ret, const PathSegment& segment) { absl::StrAppend(ret, "/", segment.FieldName(), segment.IsIndex() ? kIndexMarker : ""); }); } PathSegment ParsePathSegment(absl::string_view segment_name) { bool is_index = absl::ConsumeSuffix(&segment_name, kIndexMarker); return PathSegment(segment_name, is_index); } absl::StatusOr<std::vector<PathSegment>> ParseProtopathId( absl::string_view protopath_id) { std::vector<PathSegment> parsed; if (protopath_id.empty()) { return parsed; } if (protopath_id[0] != '/') { return absl::InvalidArgumentError( absl::StrFormat("ProtopathId (%s) formatted incorrectly. " "Must start with a slash (/).", protopath_id)); } protopath_id.remove_prefix(1); while (!protopath_id.empty()) { const size_t segment_len = protopath_id.find_first_of('/'); const absl::string_view segment = protopath_id.substr(0, segment_len); parsed.push_back(ParsePathSegment(segment)); if (segment_len == std::string::npos) { break; } protopath_id.remove_prefix(segment_len + 1); } return parsed; } } std::string TablePathToProtopathId(const TablePath& table_path) { return FormatAsProtopathId(table_path.PathSegments()); } std::string ColumnPathToProtopathId(const ColumnPath& column_path) { return FormatAsProtopathId(column_path.PathSegments()); } absl::StatusOr<TablePath> TablePathFromProtopathId( absl::string_view protopath_id) { ASSIGN_OR_RETURN(auto segments, ParseProtopathId(protopath_id)); return TablePath(std::move(segments)); } absl::StatusOr<ColumnPath> ColumnPathFromProtopathId( absl::string_view protopath_id) { ASSIGN_OR_RETURN(auto segments, ParseProtopathId(protopath_id)); return ColumnPath(std::move(segments)); } }
#include "arolla/naming/protopath_id.h" #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "arolla/naming/table.h" #include "arolla/util/status_macros_backport.h" namespace arolla::naming { namespace { TEST(Formatter, Format) { TablePath root; EXPECT_EQ(TablePathToProtopathId(root), ""); EXPECT_EQ(TablePathToProtopathId(root.Child("foo", true).Child("bar", false)), "/foo[:]/bar"); EXPECT_EQ( ColumnPathToProtopathId( root.Child("foo", true).Child("bar", false).Column("baz", true)), "/foo[:]/bar/baz[:]"); } TEST(Formatter, FormatSizeColumn) { TablePath root; EXPECT_EQ(ColumnPathToProtopathId( root.Child("foo", true).Child("bar", false).Size("baz")), "/foo[:]/bar/baz/@size"); } TEST(Parser, ParseRootTablePath) { ASSERT_OK_AND_ASSIGN(TablePath root_path, TablePathFromProtopathId("/")); EXPECT_EQ(root_path.FullName(), ""); ASSERT_OK_AND_ASSIGN(root_path, TablePathFromProtopathId("")); EXPECT_EQ(root_path.FullName(), ""); } TEST(Parser, ParseInvalidTablePath) { EXPECT_FALSE(TablePathFromProtopathId("invalid/path").ok()); } TEST(Parser, ParseNestedTablePath) { ASSERT_OK_AND_ASSIGN(TablePath nested_path, TablePathFromProtopathId("/query/doc")); EXPECT_EQ(nested_path.FullName(), "/query/doc"); ASSERT_OK_AND_ASSIGN(nested_path, TablePathFromProtopathId("/query/doc/")); EXPECT_EQ(nested_path.FullName(), "/query/doc"); ASSERT_OK_AND_ASSIGN(nested_path, TablePathFromProtopathId("/query")); EXPECT_EQ(nested_path.FullName(), "/query"); ASSERT_OK_AND_ASSIGN(nested_path, TablePathFromProtopathId("/query/")); EXPECT_EQ(nested_path.FullName(), "/query"); } TEST(Parser, ParseNestedColumnPath) { ASSERT_OK_AND_ASSIGN(ColumnPath nested_path, ColumnPathFromProtopathId("/query[:]/query_text")); EXPECT_EQ(nested_path.PathSegments(), (std::vector<PathSegment>{{"query", true}, {"query_text", false}})); ASSERT_OK_AND_ASSIGN(nested_path, ColumnPathFromProtopathId("/query/query_text")); EXPECT_EQ( nested_path.PathSegments(), (std::vector<PathSegment>{{"query", false}, {"query_text", false}})); ASSERT_OK_AND_ASSIGN(nested_path, ColumnPathFromProtopathId("/query_count")); EXPECT_EQ(nested_path.PathSegments(), (std::vector<PathSegment>{{"query_count", false}})); } TEST(Parser, ParseTablePathWithIndexMarker) { ASSERT_OK_AND_ASSIGN(TablePath path, TablePathFromProtopathId("/query/doc[:]/url")); EXPECT_EQ(path.PathSegments(), (std::vector<PathSegment>{ {"query", false}, {"doc", true}, {"url", false}})); } } }
2,334
cpp
google/arolla
policy
arolla/naming/policy.cc
arolla/naming/policy_test.cc
#ifndef AROLLA_NAMING_POLICY_H_ #define AROLLA_NAMING_POLICY_H_ #include <string> #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "arolla/naming/table.h" namespace arolla::naming { class PolicyImpl; class Policy { public: explicit Policy(const PolicyImpl& policy_impl) : policy_impl_(&policy_impl) {} const std::string& Name() const; std::string Format(const ColumnPath& path) const; std::string Format(const TablePath& path) const; private: const PolicyImpl* policy_impl_; }; Policy DefaultPolicy(); constexpr absl::string_view kDefaultPolicyName = "default"; Policy DoubleUnderscorePolicy(); constexpr absl::string_view kDoubleUnderscorePolicyName = "double_underscore"; Policy SingleUnderscorePolicy(); constexpr absl::string_view kSingleUnderscorePolicyName = "single_underscore"; Policy LeafOnlyPolicy(); constexpr absl::string_view kLeafOnlyPolicyName = "leaf_only"; Policy ProtopathIdPolicy(); constexpr absl::string_view kProtopathIdPolicyName = "protopath_id"; Policy GoogleSQLPolicy(); constexpr absl::string_view kGoogleSQLPolicyName = "googlesql"; absl::StatusOr<Policy> GetPolicy(absl::string_view policy_name); } #endif #include "arolla/naming/policy.h" #include <string> #include <vector> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/ascii.h" #include "absl/strings/match.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" #include "absl/strings/str_join.h" #include "absl/strings/str_replace.h" #include "absl/strings/string_view.h" #include "absl/strings/strip.h" #include "arolla/naming/protopath_id.h" #include "arolla/naming/table.h" #include "arolla/util/indestructible.h" namespace arolla::naming { class PolicyImpl { public: explicit PolicyImpl(absl::string_view policy_name) : policy_name_(policy_name) {} virtual ~PolicyImpl() = default; virtual std::string Format(const ColumnPath& path) const = 0; virtual std::string Format(const TablePath& path) const = 0; const std::string& Name() const { return policy_name_; } private: std::string policy_name_; }; const std::string& Policy::Name() const { return policy_impl_->Name(); } std::string Policy::Format(const ColumnPath& path) const { return policy_impl_->Format(path); } std::string Policy::Format(const TablePath& path) const { return policy_impl_->Format(path); } namespace { class DefaultPolicyImpl : public PolicyImpl { public: DefaultPolicyImpl() : PolicyImpl(kDefaultPolicyName) {} std::string Format(const TablePath& table_path) const override { return std::string(table_path.FullName()); } std::string Format(const ColumnPath& column_path) const override { return std::string(column_path.FullName()); } }; class DoubleUnderscorePolicyImpl : public PolicyImpl { public: DoubleUnderscorePolicyImpl() : PolicyImpl(kDoubleUnderscorePolicyName) {} std::string Format(const TablePath& table_path) const override { return Format(table_path.PathSegments()); } std::string Format(const ColumnPath& column_path) const override { return Format(column_path.PathSegments()); } private: static std::string MangleExtensionFieldName(absl::string_view field_name) { if (absl::ConsumePrefix(&field_name, kExtensionFieldPrefix)) { return absl::StrReplaceAll(absl::AsciiStrToLower(field_name), {{".", "_"}}); } else { return std::string(field_name); } } std::string Format(const std::vector<PathSegment>& segments) const { return absl::StrJoin( segments, "__", [](std::string* ret, const PathSegment& segment) { std::string field_name = absl::StrReplaceAll(segment.FieldName(), {{"/", "__"}}); absl::StrAppend(ret, MangleExtensionFieldName(field_name)); }); } }; class SingleUnderscorePolicyImpl : public PolicyImpl { public: SingleUnderscorePolicyImpl() : PolicyImpl(kSingleUnderscorePolicyName) {} std::string Format(const TablePath& table_path) const override { return Reformat(table_path.FullName()); } std::string Format(const ColumnPath& column_path) const override { return Reformat(column_path.FullName()); } private: std::string Reformat(absl::string_view name) const { if (name.empty()) return ""; return absl::StrReplaceAll(name.substr(1), {{"/", "_"}}); } }; class LeafOnlyPolicyImpl : public PolicyImpl { public: LeafOnlyPolicyImpl() : PolicyImpl(kLeafOnlyPolicyName) {} std::string Format(const TablePath& table_path) const override { return Reformat(table_path.FullName()); } std::string Format(const ColumnPath& column_path) const override { return Reformat(column_path.FullName()); } private: std::string Reformat(absl::string_view name) const { return std::string(absl::EndsWith(name, "@size") ? name : name.substr(name.find_last_of('/') + 1)); } }; class ProtopathIdPolicyImpl : public PolicyImpl { public: ProtopathIdPolicyImpl() : PolicyImpl(kProtopathIdPolicyName) {} std::string Format(const TablePath& table_path) const override { return TablePathToProtopathId(table_path); } std::string Format(const ColumnPath& column_path) const override { return ColumnPathToProtopathId(column_path); } }; class GoogleSQLPolicyImpl : public PolicyImpl { public: GoogleSQLPolicyImpl() : PolicyImpl(kGoogleSQLPolicyName) {} std::string Format(const TablePath& table_path) const override { return Format(table_path.PathSegments()); } std::string Format(const ColumnPath& column_path) const override { return Format(column_path.PathSegments()); } private: std::string Format(const std::vector<PathSegment>& segments) const { return absl::StrJoin( segments, ".", [](std::string* ret, const PathSegment& segment) { absl::string_view field_name = segment.FieldName(); if (absl::ConsumePrefix(&field_name, kExtensionFieldPrefix)) { absl::StrAppend(ret, "(", field_name, ")"); } else { absl::StrAppend(ret, field_name); } }); } }; } Policy DefaultPolicy() { static const Indestructible<DefaultPolicyImpl> impl; return Policy{*impl}; } Policy DoubleUnderscorePolicy() { static const Indestructible<DoubleUnderscorePolicyImpl> impl; return Policy{*impl}; } Policy SingleUnderscorePolicy() { static const Indestructible<SingleUnderscorePolicyImpl> impl; return Policy{*impl}; } Policy LeafOnlyPolicy() { static const Indestructible<LeafOnlyPolicyImpl> impl; return Policy{*impl}; } Policy ProtopathIdPolicy() { static const Indestructible<ProtopathIdPolicyImpl> impl; return Policy{*impl}; } Policy GoogleSQLPolicy() { static const Indestructible<GoogleSQLPolicyImpl> impl; return Policy{*impl}; } absl::StatusOr<Policy> GetPolicy(absl::string_view policy_name) { if (policy_name == kDefaultPolicyName) { return DefaultPolicy(); } if (policy_name == kDoubleUnderscorePolicyName) { return DoubleUnderscorePolicy(); } if (policy_name == kSingleUnderscorePolicyName) { return SingleUnderscorePolicy(); } if (policy_name == kLeafOnlyPolicyName) { return LeafOnlyPolicy(); } if (policy_name == kProtopathIdPolicyName) { return ProtopathIdPolicy(); } if (policy_name == kGoogleSQLPolicyName) { return GoogleSQLPolicy(); } return absl::InvalidArgumentError( absl::StrFormat("undefined naming policy: %s", policy_name)); } }
#include "arolla/naming/policy.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "arolla/naming/table.h" #include "arolla/util/testing/status_matchers_backport.h" using ::arolla::testing::StatusIs; namespace arolla::naming { namespace { TEST(Policy, name) { EXPECT_EQ(DefaultPolicy().Name(), "default"); EXPECT_EQ(DoubleUnderscorePolicy().Name(), "double_underscore"); } TEST(Policy, format) { TablePath root; EXPECT_EQ(DefaultPolicy().Format(root), ""); EXPECT_EQ(DoubleUnderscorePolicy().Format(root), ""); EXPECT_EQ(SingleUnderscorePolicy().Format(root), ""); EXPECT_EQ(LeafOnlyPolicy().Format(root), ""); EXPECT_EQ(ProtopathIdPolicy().Format(root), ""); EXPECT_EQ(GoogleSQLPolicy().Format(root), ""); TablePath query("query"); EXPECT_EQ(DefaultPolicy().Format(query), "/query"); EXPECT_EQ(DoubleUnderscorePolicy().Format(query), "query"); EXPECT_EQ(SingleUnderscorePolicy().Format(query), "query"); EXPECT_EQ(LeafOnlyPolicy().Format(query), "query"); EXPECT_EQ(ProtopathIdPolicy().Format(query), "/query"); EXPECT_EQ(GoogleSQLPolicy().Format(query), "query"); TablePath doc = query.Child("docs", true); EXPECT_EQ(DefaultPolicy().Format(doc), "/query/docs"); EXPECT_EQ(DoubleUnderscorePolicy().Format(doc), "query__docs"); EXPECT_EQ(SingleUnderscorePolicy().Format(doc), "query_docs"); EXPECT_EQ(LeafOnlyPolicy().Format(doc), "docs"); EXPECT_EQ(ProtopathIdPolicy().Format(doc), "/query/docs[:]"); EXPECT_EQ(GoogleSQLPolicy().Format(doc), "query.docs"); ColumnPath quality = doc.Column("quality"); EXPECT_EQ(DefaultPolicy().Format(quality), "/query/docs/quality"); EXPECT_EQ(DoubleUnderscorePolicy().Format(quality), "query__docs__quality"); EXPECT_EQ(SingleUnderscorePolicy().Format(quality), "query_docs_quality"); EXPECT_EQ(LeafOnlyPolicy().Format(quality), "quality"); EXPECT_EQ(ProtopathIdPolicy().Format(quality), "/query/docs[:]/quality"); EXPECT_EQ(GoogleSQLPolicy().Format(quality), "query.docs.quality"); ColumnPath terms_size = doc.Size("terms"); EXPECT_EQ(DefaultPolicy().Format(terms_size), "/query/docs/terms/@size"); EXPECT_EQ(DoubleUnderscorePolicy().Format(terms_size), "query__docs__terms__@size"); EXPECT_EQ(SingleUnderscorePolicy().Format(terms_size), "query_docs_terms_@size"); EXPECT_EQ(LeafOnlyPolicy().Format(terms_size), "/query/docs/terms/@size"); EXPECT_EQ(ProtopathIdPolicy().Format(terms_size), "/query/docs[:]/terms/@size"); EXPECT_EQ(GoogleSQLPolicy().Format(terms_size), "query.docs.terms.@size"); TablePath ext = doc.Child(ProtoExtensionAccess("foo_pkg.Bar.baz_ext")); EXPECT_EQ(DefaultPolicy().Format(ext), "/query/docs/Ext::foo_pkg.Bar.baz_ext"); EXPECT_EQ(DoubleUnderscorePolicy().Format(ext), "query__docs__foo_pkg_bar_baz_ext"); EXPECT_EQ(SingleUnderscorePolicy().Format(ext), "query_docs_Ext::foo_pkg.Bar.baz_ext"); EXPECT_EQ(LeafOnlyPolicy().Format(ext), "Ext::foo_pkg.Bar.baz_ext"); EXPECT_EQ(ProtopathIdPolicy().Format(ext), "/query/docs[:]/Ext::foo_pkg.Bar.baz_ext"); EXPECT_EQ(GoogleSQLPolicy().Format(ext), "query.docs.(foo_pkg.Bar.baz_ext)"); } TEST(Policy, get_policy) { EXPECT_EQ(GetPolicy("default").value().Name(), "default"); EXPECT_EQ(GetPolicy("double_underscore").value().Name(), "double_underscore"); EXPECT_EQ(GetPolicy("single_underscore").value().Name(), "single_underscore"); EXPECT_EQ(GetPolicy("leaf_only").value().Name(), "leaf_only"); EXPECT_THAT(GetPolicy("unknown-policy-XYZ"), StatusIs(absl::StatusCode::kInvalidArgument, "undefined naming policy: unknown-policy-XYZ")); } } }
2,335
cpp
google/arolla
shape_qtype
arolla/qtype/shape_qtype.cc
arolla/qtype/shape_qtype_test.cc
#ifndef AROLLA_QTYPE_SHAPE_QTYPE_H_ #define AROLLA_QTYPE_SHAPE_QTYPE_H_ #include <string> #include <utility> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/simple_qtype.h" #include "arolla/util/api.h" #include "arolla/util/fingerprint.h" #include "arolla/util/meta.h" #include "arolla/util/repr.h" namespace arolla { class AROLLA_API ShapeQType : public SimpleQType { public: virtual absl::StatusOr<QTypePtr> WithValueQType( QTypePtr value_qtype) const = 0; virtual QTypePtr presence_qtype() const = 0; protected: template <typename T> ShapeQType(meta::type<T> type, std::string type_name) : SimpleQType(type, std::move(type_name)) {} }; inline bool IsShapeQType(const QType* qtype) { return dynamic_cast<const ShapeQType*>(qtype) != nullptr; } inline absl::StatusOr<const ShapeQType*> ToShapeQType(QTypePtr qtype) { const ShapeQType* shape_qtype = dynamic_cast<const ShapeQType*>(qtype); if (!shape_qtype) { return absl::InvalidArgumentError( absl::StrFormat("expected a shape, got %s", qtype->name())); } return shape_qtype; } struct AROLLA_API ScalarShape {}; inline bool operator==(ScalarShape, ScalarShape) { return true; } inline bool operator!=(ScalarShape, ScalarShape) { return false; } struct AROLLA_API OptionalScalarShape {}; inline bool operator==(OptionalScalarShape, OptionalScalarShape) { return true; } inline bool operator!=(OptionalScalarShape, OptionalScalarShape) { return false; } AROLLA_DECLARE_QTYPE(ScalarShape); AROLLA_DECLARE_REPR(ScalarShape); AROLLA_DECLARE_FINGERPRINT_HASHER_TRAITS(ScalarShape); AROLLA_DECLARE_QTYPE(OptionalScalarShape); AROLLA_DECLARE_REPR(OptionalScalarShape); AROLLA_DECLARE_FINGERPRINT_HASHER_TRAITS(OptionalScalarShape); } #endif #include "arolla/qtype/shape_qtype.h" #include <string> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "absl/strings/string_view.h" #include "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/fingerprint.h" #include "arolla/util/indestructible.h" #include "arolla/util/meta.h" #include "arolla/util/repr.h" #include "arolla/util/unit.h" #include "arolla/util/status_macros_backport.h" namespace arolla { namespace { absl::Status EnsureIsBaseType(QTypePtr qtype) { return IsScalarQType(qtype) || IsOptionalQType(qtype) ? absl::OkStatus() : absl::InvalidArgumentError(absl::StrFormat( "Shape::WithValueQType supports only scalar and " "optional values, got %s", qtype->name())); } class ScalarShapeQType final : public ShapeQType { public: ScalarShapeQType() : ShapeQType(meta::type<ScalarShape>(), "SCALAR_SHAPE") {} absl::StatusOr<QTypePtr> WithValueQType(QTypePtr value_qtype) const final { RETURN_IF_ERROR(EnsureIsBaseType(value_qtype)); return value_qtype; } QTypePtr presence_qtype() const final { return GetQType<Unit>(); } }; class OptionalScalarShapeQType final : public ShapeQType { public: OptionalScalarShapeQType() : ShapeQType(meta::type<OptionalScalarShape>(), "OPTIONAL_SCALAR_SHAPE") { } absl::StatusOr<QTypePtr> WithValueQType(QTypePtr value_qtype) const final { RETURN_IF_ERROR(EnsureIsBaseType(value_qtype)); return ToOptionalQType(value_qtype); } QTypePtr presence_qtype() const final { return GetOptionalQType<Unit>(); } }; } QTypePtr QTypeTraits<ScalarShape>::type() { static const Indestructible<ScalarShapeQType> shape_qtype; return shape_qtype.get(); } QTypePtr QTypeTraits<OptionalScalarShape>::type() { static const Indestructible<OptionalScalarShapeQType> shape_qtype; return shape_qtype.get(); } ReprToken ReprTraits<ScalarShape>::operator()( const ScalarShape& ) const { return ReprToken{"scalar_shape"}; } void FingerprintHasherTraits<ScalarShape>::operator()( FingerprintHasher* hasher, const ScalarShape& ) const { hasher->Combine(absl::string_view("scalar_shape")); } ReprToken ReprTraits<OptionalScalarShape>::operator()( const OptionalScalarShape& ) const { return ReprToken{"optional_scalar_shape"}; } void FingerprintHasherTraits<OptionalScalarShape>::operator()( FingerprintHasher* hasher, const OptionalScalarShape& ) const { hasher->Combine(absl::string_view("optional_scalar_shape")); } }
#include "arolla/qtype/shape_qtype.h" #include <cstdint> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/optional_qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/typed_value.h" #include "arolla/util/bytes.h" #include "arolla/util/repr.h" #include "arolla/util/testing/repr_token_eq.h" #include "arolla/util/testing/status_matchers_backport.h" namespace arolla { namespace { using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::ReprTokenEq; using ::testing::Eq; using ::testing::NotNull; TEST(ShapeQType, ScalarShape) { auto scalar_shape = dynamic_cast<const ShapeQType*>(GetQType<ScalarShape>()); ASSERT_THAT(scalar_shape, NotNull()); EXPECT_THAT(scalar_shape->WithValueQType(GetQType<int64_t>()), IsOkAndHolds(Eq(GetQType<int64_t>()))); EXPECT_THAT(scalar_shape->WithValueQType(GetQType<Bytes>()), IsOkAndHolds(Eq(GetQType<Bytes>()))); EXPECT_THAT(scalar_shape->WithValueQType(GetOptionalQType<int64_t>()), IsOkAndHolds(Eq(GetOptionalQType<int64_t>()))); } TEST(ShapeQType, OptionalScalarShape) { auto optional_shape = dynamic_cast<const ShapeQType*>(GetQType<OptionalScalarShape>()); ASSERT_THAT(optional_shape, NotNull()); EXPECT_THAT(optional_shape->WithValueQType(GetQType<int64_t>()), IsOkAndHolds(Eq(GetOptionalQType<int64_t>()))); EXPECT_THAT(optional_shape->WithValueQType(GetQType<Bytes>()), IsOkAndHolds(Eq(GetOptionalQType<Bytes>()))); EXPECT_THAT(optional_shape->WithValueQType(GetOptionalQType<int64_t>()), IsOkAndHolds(Eq(GetOptionalQType<int64_t>()))); } TEST(ShapeQType, ScalarShapeRepr) { EXPECT_THAT(GenReprToken(ScalarShape{}), ReprTokenEq("scalar_shape")); } TEST(ShapeQType, OptionalScalarShapeRepr) { EXPECT_THAT(GenReprToken(OptionalScalarShape{}), ReprTokenEq("optional_scalar_shape")); } TEST(ShapeQType, TypedValuScalarShapeRepr) { EXPECT_THAT(TypedValue::FromValue(ScalarShape{}).GenReprToken(), ReprTokenEq("scalar_shape")); } TEST(ShapeQType, TypedValueOptionalScalarShapeRepr) { EXPECT_THAT(TypedValue::FromValue(OptionalScalarShape{}).GenReprToken(), ReprTokenEq("optional_scalar_shape")); } TEST(ShapeQType, ScalarShapeFingerprint) { EXPECT_THAT(TypedValue::FromValue(ScalarShape{}).GetFingerprint(), Eq(TypedValue::FromValue(ScalarShape{}).GetFingerprint())); } TEST(ShapeQType, OptionalScalarShapeFingerprint) { EXPECT_THAT( TypedValue::FromValue(OptionalScalarShape{}).GetFingerprint(), Eq(TypedValue::FromValue(OptionalScalarShape{}).GetFingerprint())); } TEST(ShapeQType, IsShapeQType) { EXPECT_TRUE(IsShapeQType(GetQType<OptionalScalarShape>())); EXPECT_FALSE(IsShapeQType(GetQType<int32_t>())); } } }
2,336
cpp
google/arolla
slice_qtype
arolla/qtype/slice_qtype.cc
arolla/qtype/slice_qtype_test.cc
#ifndef AROLLA_QTYPE_SLICE_QTYPE_H_ #define AROLLA_QTYPE_SLICE_QTYPE_H_ #include "absl/strings/string_view.h" #include "arolla/qtype/qtype.h" namespace arolla { bool IsSliceQType(const QType* qtype); QTypePtr MakeSliceQType(QTypePtr start, QTypePtr stop, QTypePtr step); absl::string_view GetSliceQTypeSpecializationKey(); } #endif #include "arolla/qtype/slice_qtype.h" #include <memory> #include <string> #include <tuple> #include <utility> #include "absl/base/thread_annotations.h" #include "absl/container/flat_hash_map.h" #include "absl/container/flat_hash_set.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "absl/synchronization/mutex.h" #include "arolla/qtype/derived_qtype.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/tuple_qtype.h" #include "arolla/util/fast_dynamic_downcast_final.h" #include "arolla/util/indestructible.h" #include "arolla/util/repr.h" namespace arolla { namespace { std::string SliceQTypeName(QTypePtr start, QTypePtr stop, QTypePtr step) { return absl::StrCat("slice<", JoinTypeNames({start, stop, step}), ">"); } class SliceQType final : public BasicDerivedQType { public: SliceQType(QTypePtr start, QTypePtr stop, QTypePtr step) : BasicDerivedQType(ConstructorArgs{ .name = SliceQTypeName(start, stop, step), .base_qtype = MakeTupleQType({start, stop, step}), .qtype_specialization_key = std::string(GetSliceQTypeSpecializationKey()), }) {} ReprToken UnsafeReprToken(const void* source) const override { return ReprToken{ absl::StrCat("slice", GetBaseQType()->UnsafeReprToken(source).str)}; } }; class SliceQTypeRegistry { public: static SliceQTypeRegistry* instance() { static Indestructible<SliceQTypeRegistry> result; return result.get(); } QTypePtr GetQType(QTypePtr start, QTypePtr stop, QTypePtr step) ABSL_LOCKS_EXCLUDED(lock_) { { absl::ReaderMutexLock guard(&lock_); if (const auto it = registry_.find({start, stop, step}); it != registry_.end()) { return it->second.get(); } } auto slice_qtype = std::make_unique<SliceQType>(start, stop, step); absl::MutexLock guard(&lock_); return registry_.try_emplace({start, stop, step}, std::move(slice_qtype)) .first->second.get(); } private: using RegistryKey = std::tuple<QTypePtr, QTypePtr, QTypePtr>; absl::Mutex lock_; absl::flat_hash_map<RegistryKey, std::unique_ptr<SliceQType>> registry_ ABSL_GUARDED_BY(lock_); }; } bool IsSliceQType(const QType* qtype) { return fast_dynamic_downcast_final<const SliceQType*>(qtype) != nullptr; } QTypePtr MakeSliceQType(QTypePtr start, QTypePtr stop, QTypePtr step) { return SliceQTypeRegistry::instance()->GetQType(start, stop, step); } absl::string_view GetSliceQTypeSpecializationKey() { return "::arolla::SliceQType"; } }
#include "arolla/qtype/slice_qtype.h" #include <cstdint> #include "gtest/gtest.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/derived_qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/tuple_qtype.h" #include "arolla/util/bytes.h" namespace arolla::testing { namespace { TEST(SliceQType, MakeSliceQType) { auto start = GetQType<int32_t>(); auto stop = GetQType<double>(); auto step = GetQType<Bytes>(); auto qtype = MakeSliceQType(start, stop, step); EXPECT_EQ(qtype->name(), "slice<INT32,FLOAT64,BYTES>"); auto derived_qtype_interface = dynamic_cast<const DerivedQTypeInterface*>(qtype); ASSERT_NE(derived_qtype_interface, nullptr); auto tuple_qtype = MakeTupleQType({start, stop, step}); EXPECT_EQ(derived_qtype_interface->GetBaseQType(), tuple_qtype); { auto qtype2 = MakeSliceQType(start, stop, step); EXPECT_EQ(qtype, qtype2); } { auto qtype2 = MakeSliceQType(start, stop, start); EXPECT_EQ(qtype2->name(), "slice<INT32,FLOAT64,INT32>"); EXPECT_NE(qtype, qtype2); } } TEST(SliceQType, IsSliceQType) { auto start = GetQType<int32_t>(); auto stop = GetQType<double>(); auto step = GetQType<Bytes>(); auto tuple_qtype = MakeTupleQType({start, stop, step}); EXPECT_FALSE(IsSliceQType(tuple_qtype)); auto qtype = MakeSliceQType(start, stop, step); EXPECT_TRUE(IsSliceQType(qtype)); } } }
2,337
cpp
google/arolla
tuple_qtype
arolla/qtype/tuple_qtype.cc
arolla/qtype/tuple_qtype_test.cc
#ifndef AROLLA_QTYPE_TUPLE_QTYPE_H_ #define AROLLA_QTYPE_TUPLE_QTYPE_H_ #include <initializer_list> #include <string> #include <type_traits> #include "absl/status/statusor.h" #include "absl/types/span.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/typed_ref.h" #include "arolla/qtype/typed_value.h" namespace arolla { bool IsTupleQType(const QType* qtype); QTypePtr MakeTupleQType(absl::Span<const QTypePtr> field_qtypes); TypedValue MakeTuple(absl::Span<const TypedRef> fields); TypedValue MakeTuple(absl::Span<const TypedValue> fields); template <typename... Ts> TypedValue MakeTupleFromFields(const Ts&... fields) { auto typed_fields = std::initializer_list<TypedRef>{[](const auto& field) { using FieldType = std::decay_t<decltype(field)>; if constexpr (std::is_same_v<FieldType, TypedRef>) { return field; } else if constexpr (std::is_same_v<FieldType, TypedValue>) { return field.AsRef(); } else { return TypedRef::FromValue(field); } }(fields)...}; return MakeTuple(absl::Span<const TypedRef>(typed_fields)); } bool IsNamedTupleQType(const QType* qtype); absl::StatusOr<QTypePtr> MakeNamedTupleQType( absl::Span<const std::string> field_names, QTypePtr tuple_qtype); } #endif #include "arolla/qtype/tuple_qtype.h" #include <algorithm> #include <cstddef> #include <cstdint> #include <memory> #include <optional> #include <sstream> #include <string> #include <utility> #include <vector> #include "absl/base/thread_annotations.h" #include "absl/container/flat_hash_map.h" #include "absl/container/flat_hash_set.h" #include "absl/log/check.h" #include "absl/log/log.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/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/memory/frame.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/derived_qtype.h" #include "arolla/qtype/named_field_qtype.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/typed_ref.h" #include "arolla/qtype/typed_slot.h" #include "arolla/qtype/typed_value.h" #include "arolla/util/fast_dynamic_downcast_final.h" #include "arolla/util/fingerprint.h" #include "arolla/util/indestructible.h" #include "arolla/util/repr.h" #include "arolla/util/string.h" #include "arolla/util/unit.h" namespace arolla { namespace { class Tuple {}; class TupleQType final : public QType { public: static std::unique_ptr<TupleQType> Make( absl::Span<const QTypePtr> field_qtypes) { FrameLayout::Builder layout_builder; std::vector<TypedSlot> fields; fields.reserve(field_qtypes.size()); for (auto field_qtype : field_qtypes) { fields.push_back(AddSlot(field_qtype, &layout_builder)); } bool needTupleTag = true; for (const auto& field : fields) { if (field.byte_offset() == 0 && field.GetType()->type_layout().HasField(0, typeid(Tuple))) { needTupleTag = false; break; } } if (needTupleTag) { auto status = layout_builder.RegisterUnsafeSlot(0, 0, typeid(Tuple)); if (!status.ok()) { LOG(FATAL) << status; } } return std::make_unique<TupleQType>( field_qtypes, std::move(layout_builder).Build(), std::move(fields)); } TupleQType(absl::Span<const QTypePtr> field_qtypes, FrameLayout&& layout, std::vector<TypedSlot>&& fields) : QType(ConstructorArgs{ .name = absl::StrCat("tuple<", JoinTypeNames(field_qtypes), ">"), .type_info = typeid(Tuple), .type_layout = std::move(layout), .type_fields = std::move(fields), .qtype_specialization_key = "::arolla::TupleQType", }), field_qtypes_(field_qtypes.begin(), field_qtypes.end()) {} absl::Span<const QTypePtr> field_qtypes() const { return field_qtypes_; } void UnsafeCopy(const void* source, void* destination) const override { ConstFramePtr source_frame(source, &type_layout()); FramePtr destination_frame(destination, &type_layout()); for (const auto& field : type_fields()) { field.CopyTo(source_frame, field, destination_frame); } } void UnsafeCombineToFingerprintHasher( const void* source, FingerprintHasher* hasher) const override { hasher->Combine(type_fields().size()); for (const auto& field : type_fields()) { field.GetType()->UnsafeCombineToFingerprintHasher( static_cast<const char*>(source) + field.byte_offset(), hasher); } } ReprToken UnsafeReprToken(const void* source) const override { ConstFramePtr frame_ptr(source, &type_layout()); std::ostringstream result; result << "("; bool first = true; for (const auto& field : type_fields()) { result << NonFirstComma(first) << TypedRef::FromSlot(field, frame_ptr).Repr(); } result << ")"; return ReprToken{std::move(result).str()}; } private: std::vector<QTypePtr> field_qtypes_; }; class TupleQTypeRegistry { public: static TupleQTypeRegistry* instance() { static Indestructible<TupleQTypeRegistry> result; return result.get(); } QTypePtr GetQType(absl::Span<const QTypePtr> field_qtypes) ABSL_LOCKS_EXCLUDED(lock_) { { absl::ReaderMutexLock guard(&lock_); if (const auto it = registry_.find(field_qtypes); it != registry_.end()) { return it->second.get(); } } auto tuple_qtype = TupleQType::Make(field_qtypes); absl::MutexLock guard(&lock_); return registry_ .try_emplace(tuple_qtype->field_qtypes(), std::move(tuple_qtype)) .first->second.get(); } private: absl::Mutex lock_; absl::flat_hash_map<absl::Span<const QTypePtr>, std::unique_ptr<TupleQType>> registry_ ABSL_GUARDED_BY(lock_); }; template <typename TypedRef > TypedValue MakeTupleImpl(absl::Span<const TypedRef> fields) { std::vector<QTypePtr> field_types; field_types.reserve(fields.size()); for (const auto& field : fields) { field_types.push_back(field.GetType()); } auto status_or_result = TypedValue::FromFields(MakeTupleQType(field_types), fields); DCHECK_OK(status_or_result.status()); return status_or_result.value_or(TypedValue::FromValue(Unit{})); } std::string NamedTupleQTypeName(absl::Span<const std::string> field_names, QTypePtr tuple_qtype) { constexpr size_t kMaxFieldNames = 5; std::ostringstream o; o << "namedtuple<"; size_t fields_to_report = std::min(field_names.size(), kMaxFieldNames); for (size_t i = 0; i != fields_to_report; ++i) { if (i != 0) { o << ","; } o << field_names[i] << "=" << tuple_qtype->type_fields()[i].GetType()->name(); } if (fields_to_report < field_names.size()) { o << ", [" << field_names.size() - fields_to_report << " fields]"; } o << ">"; return o.str(); } class NamedTupleQType final : public BasicDerivedQType, public NamedFieldQTypeInterface { public: NamedTupleQType(absl::Span<const std::string> field_names, QTypePtr tuple_qtype) : BasicDerivedQType(ConstructorArgs{ .name = NamedTupleQTypeName(field_names, tuple_qtype), .base_qtype = tuple_qtype, .qtype_specialization_key = "::arolla::NamedTupleQType", }), field_names_(field_names.begin(), field_names.end()) { name2index_.reserve(field_names.size()); int64_t id = 0; for (const std::string& name : field_names_) { name2index_.emplace(name, id++); } } absl::Span<const std::string> GetFieldNames() const final { return field_names_; } std::optional<int64_t> GetFieldIndexByName( absl::string_view field_name) const final { if (auto it = name2index_.find(field_name); it != name2index_.end()) { return it->second; } return std::nullopt; } private: absl::flat_hash_map<absl::string_view, int64_t> name2index_; std::vector<std::string> field_names_; }; class NamedTupleQTypeRegistry { public: static NamedTupleQTypeRegistry* instance() { static Indestructible<NamedTupleQTypeRegistry> result; return result.get(); } QTypePtr GetQType(absl::Span<const std::string> field_names, QTypePtr tuple_qtype) ABSL_LOCKS_EXCLUDED(lock_) { { absl::ReaderMutexLock guard(&lock_); if (const auto it = registry_.find({field_names, tuple_qtype}); it != registry_.end()) { return it->second.get(); } } auto named_tuple_qtype = std::make_unique<NamedTupleQType>(field_names, tuple_qtype); absl::MutexLock guard(&lock_); return registry_ .try_emplace({named_tuple_qtype->GetFieldNames(), tuple_qtype}, std::move(named_tuple_qtype)) .first->second.get(); } private: using RegistryKey = std::pair<absl::Span<const std::string>, QTypePtr>; absl::Mutex lock_; absl::flat_hash_map<RegistryKey, std::unique_ptr<NamedTupleQType>> registry_ ABSL_GUARDED_BY(lock_); }; } bool IsTupleQType(const QType* qtype) { return fast_dynamic_downcast_final<const TupleQType*>(qtype) != nullptr; } QTypePtr MakeTupleQType(absl::Span<const QTypePtr> field_qtypes) { return TupleQTypeRegistry::instance()->GetQType(field_qtypes); } TypedValue MakeTuple(absl::Span<const TypedRef> fields) { return MakeTupleImpl(fields); } TypedValue MakeTuple(absl::Span<const TypedValue> fields) { return MakeTupleImpl(fields); } bool IsNamedTupleQType(const QType* qtype) { return fast_dynamic_downcast_final<const NamedTupleQType*>(qtype) != nullptr; } absl::StatusOr<QTypePtr> MakeNamedTupleQType( absl::Span<const std::string> field_names, QTypePtr tuple_qtype) { if (!IsTupleQType(tuple_qtype)) { return absl::FailedPreconditionError(absl::StrFormat( "incorrect NamedTupleQType: expected tuple, found %s", tuple_qtype != nullptr ? tuple_qtype->name() : std::string("nullptr"))); } if (field_names.size() != tuple_qtype->type_fields().size()) { return absl::FailedPreconditionError(absl::StrFormat( "incorrect NamedTupleQType #field_names != #fields: %d vs %d", field_names.size(), tuple_qtype->type_fields().size())); } absl::flat_hash_set<absl::string_view> name_set; for (const std::string& name : field_names) { if (!name_set.insert(name).second) { return absl::FailedPreconditionError(absl::StrFormat( "incorrect NamedTupleQType: field name %s is duplicated", name)); } } return NamedTupleQTypeRegistry::instance()->GetQType(field_names, tuple_qtype); } }
#include "arolla/qtype/tuple_qtype.h" #include <cstddef> #include <cstdint> #include <optional> #include <string> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/types/span.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/derived_qtype.h" #include "arolla/qtype/named_field_qtype.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/typed_ref.h" #include "arolla/qtype/typed_value.h" #include "arolla/util/bytes.h" #include "arolla/util/testing/repr_token_eq.h" #include "arolla/util/testing/status_matchers_backport.h" #include "arolla/util/status_macros_backport.h" namespace arolla::testing { namespace { using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::ReprTokenEq; using ::arolla::testing::StatusIs; using ::testing::ElementsAre; using ::testing::ElementsAreArray; using ::testing::HasSubstr; using ::testing::IsEmpty; using ::testing::Eq; using ::testing::MatchesRegex; TEST(TupleQType, Empty) { auto qtype = MakeTupleQType({}); EXPECT_TRUE(IsTupleQType(qtype)); EXPECT_EQ(qtype->name(), "tuple<>"); EXPECT_EQ(qtype->type_layout().AllocSize(), 0); EXPECT_EQ(qtype->type_layout().AllocAlignment().value, 1); auto value = MakeTupleFromFields(); EXPECT_EQ(value.GetType(), qtype); EXPECT_EQ(value.GetFieldCount(), 0); EXPECT_THAT(value.GenReprToken(), ReprTokenEq("()")); } TEST(TupleQType, EmptyRegression) { auto qtype_0 = MakeTupleQType({}); auto qtype_1 = MakeTupleQType({qtype_0, qtype_0}); EXPECT_TRUE(IsTupleQType(qtype_1)); EXPECT_EQ(qtype_1->name(), "tuple<tuple<>,tuple<>>"); EXPECT_EQ(qtype_1->type_layout().AllocSize(), 0); EXPECT_EQ(qtype_1->type_layout().AllocAlignment().value, 1); auto value_0 = MakeTupleFromFields(); auto value_1 = MakeTupleFromFields(value_0, value_0); EXPECT_EQ(value_1.GetType(), qtype_1); auto copy_1 = TypedValue(value_1.AsRef()); EXPECT_EQ(value_1.GetFingerprint(), copy_1.GetFingerprint()); EXPECT_THAT(value_1.GenReprToken(), ReprTokenEq("((), ())")); } TEST(TupleQType, Trivial) { auto qtype = MakeTupleQType( {GetQType<int32_t>(), GetQType<double>(), GetQType<Bytes>()}); EXPECT_TRUE(IsTupleQType(qtype)); EXPECT_EQ(qtype->name(), "tuple<INT32,FLOAT64,BYTES>"); auto value = MakeTupleFromFields(int32_t{34}, double{17}, Bytes("Hello")); EXPECT_EQ(value.GetType(), qtype); EXPECT_EQ(value.GetFieldCount(), 3); EXPECT_THAT(value.GetField(0).As<int32_t>(), IsOkAndHolds(int32_t{34})); EXPECT_THAT(value.GetField(1).As<double>(), IsOkAndHolds(double{17.})); ASSERT_OK_AND_ASSIGN(Bytes bytes, value.GetField(2).As<Bytes>()); EXPECT_THAT(bytes, Eq(Bytes("Hello"))); EXPECT_THAT(value.GenReprToken(), ReprTokenEq("(34, float64{17}, b'Hello')")); } TEST(TupleQType, CopyTo) { auto qtype = MakeTupleQType( {GetQType<int32_t>(), GetQType<double>(), GetQType<Bytes>()}); EXPECT_TRUE(IsTupleQType(qtype)); EXPECT_EQ(qtype->name(), "tuple<INT32,FLOAT64,BYTES>"); auto value = MakeTupleFromFields(int32_t{34}, double{17}, Bytes("Hello")); EXPECT_THAT(value.GetField(0).As<int32_t>(), IsOkAndHolds(int32_t{34})); EXPECT_THAT(value.GetField(1).As<double>(), IsOkAndHolds(double{17.})); auto copy = TypedValue(value.AsRef()); EXPECT_EQ(value.GetFingerprint(), copy.GetFingerprint()); EXPECT_THAT(copy.GenReprToken(), ReprTokenEq("(34, float64{17}, b'Hello')")); } TEST(TupleQType, QValueFromFields) { auto qtype = MakeTupleQType({GetQType<int>(), GetQType<float>()}); { ASSERT_OK_AND_ASSIGN(auto qvalue, TypedValue::FromFields( qtype, {TypedRef::FromValue(2), TypedRef::FromValue(3.14f)})); EXPECT_THAT(qvalue.GetField(0).As<int>(), IsOkAndHolds(2)); EXPECT_THAT(qvalue.GetField(1).As<float>(), IsOkAndHolds(3.14f)); } { ASSERT_OK_AND_ASSIGN( auto qvalue, TypedValue::FromFields( qtype, {TypedValue::FromValue(2), TypedValue::FromValue(3.14f)})); EXPECT_THAT(qvalue.GetField(0).As<int>(), IsOkAndHolds(2)); EXPECT_THAT(qvalue.GetField(1).As<float>(), IsOkAndHolds(3.14f)); } { EXPECT_THAT(TypedValue::FromFields(qtype, {TypedValue::FromValue(2)}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("expected 2 values, got 1; " "compound_qtype=tuple<INT32,FLOAT32>"))); } { EXPECT_THAT(TypedValue::FromFields(qtype, {TypedValue::FromValue(2), TypedValue::FromValue(3)}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("expected fields[1]: FLOAT32, got INT32; " "compound_qtype=tuple<INT32,FLOAT32>"))); } } TEST(NamedTupleQType, Empty) { auto tuple_qtype = MakeTupleQType({}); ASSERT_OK_AND_ASSIGN(auto qtype, MakeNamedTupleQType({}, tuple_qtype)); EXPECT_TRUE(IsNamedTupleQType(qtype)); EXPECT_THAT(GetFieldNames(qtype), IsEmpty()); } TEST(NamedTupleQType, Trivial) { auto tuple_qtype = MakeTupleQType( {GetQType<int32_t>(), GetQType<double>(), GetQType<Bytes>()}); ASSERT_OK_AND_ASSIGN(auto qtype, MakeNamedTupleQType({"a", "b", "c"}, tuple_qtype)); EXPECT_TRUE(IsNamedTupleQType(qtype)); EXPECT_EQ(qtype->name(), "namedtuple<a=INT32,b=FLOAT64,c=BYTES>"); EXPECT_EQ(GetFieldIndexByName(nullptr, "a"), std::nullopt); EXPECT_EQ(GetFieldIndexByName(qtype, "a"), 0); EXPECT_EQ(GetFieldIndexByName(qtype, "b"), 1); EXPECT_EQ(GetFieldIndexByName(qtype, "c"), 2); EXPECT_EQ(GetFieldIndexByName(qtype, "d"), std::nullopt); EXPECT_THAT(GetFieldNames(qtype), ElementsAre("a", "b", "c")); EXPECT_EQ(GetFieldQTypeByName(nullptr, "a"), nullptr); EXPECT_EQ(GetFieldQTypeByName(qtype, "a"), GetQType<int32_t>()); EXPECT_EQ(GetFieldQTypeByName(qtype, "b"), GetQType<double>()); EXPECT_EQ(GetFieldQTypeByName(qtype, "c"), GetQType<Bytes>()); EXPECT_EQ(GetFieldQTypeByName(qtype, "d"), nullptr); auto derived_qtype_interface = dynamic_cast<const DerivedQTypeInterface*>(qtype); ASSERT_NE(derived_qtype_interface, nullptr); EXPECT_EQ(derived_qtype_interface->GetBaseQType(), tuple_qtype); { ASSERT_OK_AND_ASSIGN(auto qtype2, MakeNamedTupleQType({"a", "b", "c"}, tuple_qtype)); EXPECT_EQ(qtype, qtype2); EXPECT_THAT(GetFieldNames(qtype2), ElementsAre("a", "b", "c")); } { ASSERT_OK_AND_ASSIGN(auto qtype2, MakeNamedTupleQType({"c", "b", "a"}, tuple_qtype)); EXPECT_EQ(qtype2->name(), "namedtuple<c=INT32,b=FLOAT64,a=BYTES>"); EXPECT_EQ(GetFieldIndexByName(qtype2, "c"), 0); EXPECT_NE(qtype, qtype2); EXPECT_THAT(GetFieldNames(qtype2), ElementsAre("c", "b", "a")); } { auto tuple_qtype2 = MakeTupleQType( {GetQType<int32_t>(), GetQType<double>(), GetQType<int32_t>()}); ASSERT_OK_AND_ASSIGN(auto qtype2, MakeNamedTupleQType({"a", "b", "c"}, tuple_qtype2)); EXPECT_EQ(qtype2->name(), "namedtuple<a=INT32,b=FLOAT64,c=INT32>"); EXPECT_NE(qtype, qtype2); EXPECT_THAT(GetFieldNames(qtype2), ElementsAre("a", "b", "c")); } } TEST(NamedTupleQType, QValueFromFields) { auto tuple_qtype = MakeTupleQType({GetQType<int>(), GetQType<float>()}); ASSERT_OK_AND_ASSIGN(auto qtype, MakeNamedTupleQType({"a", "b"}, tuple_qtype)); { ASSERT_OK_AND_ASSIGN(auto qvalue, TypedValue::FromFields( qtype, {TypedRef::FromValue(2), TypedRef::FromValue(3.14f)})); EXPECT_TRUE(IsNamedTupleQType(qvalue.GetType())); EXPECT_EQ(qvalue.GetType(), qtype); EXPECT_THAT(qvalue.GetField(0).As<int>(), IsOkAndHolds(2)); EXPECT_THAT(qvalue.GetField(1).As<float>(), IsOkAndHolds(3.14f)); } { ASSERT_OK_AND_ASSIGN( auto qvalue, TypedValue::FromFields( qtype, {TypedValue::FromValue(2), TypedValue::FromValue(3.14f)})); EXPECT_TRUE(IsNamedTupleQType(qvalue.GetType())); EXPECT_EQ(qvalue.GetType(), qtype); EXPECT_THAT(qvalue.GetField(0).As<int>(), IsOkAndHolds(2)); EXPECT_THAT(qvalue.GetField(1).As<float>(), IsOkAndHolds(3.14f)); } { EXPECT_THAT( TypedValue::FromFields(qtype, {TypedValue::FromValue(2)}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("expected 2 values, got 1; " "compound_qtype=namedtuple<a=INT32,b=FLOAT32>"))); } { EXPECT_THAT( TypedValue::FromFields(qtype, {TypedValue::FromValue(2), TypedValue::FromValue(3)}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("expected fields[1]: FLOAT32, got INT32; " "compound_qtype=namedtuple<a=INT32,b=FLOAT32>"))); } } TEST(NamedTupleQType, BigTuple) { constexpr size_t kFieldCount = 100; QTypePtr field_qtype = GetQType<int32_t>(); auto tuple_qtype = MakeTupleQType(std::vector<QTypePtr>{kFieldCount, field_qtype}); std::vector<std::string> names; for (size_t i = 0; i != kFieldCount; ++i) { names.push_back(std::to_string(i)); } ASSERT_OK_AND_ASSIGN(auto qtype, MakeNamedTupleQType(names, tuple_qtype)); EXPECT_TRUE(IsNamedTupleQType(qtype)); EXPECT_THAT(GetFieldNames(qtype), ElementsAreArray(names)); EXPECT_EQ(qtype->name(), "namedtuple<0=INT32,1=INT32,2=INT32,3=INT32,4=INT32, [95 fields]>"); } TEST(NamedTupleQType, Errors) { EXPECT_THAT( MakeNamedTupleQType({"a", "b"}, nullptr).status(), StatusIs(absl::StatusCode::kFailedPrecondition, MatchesRegex(".*NamedTupleQType.*tuple.*found.*nullptr.*"))); EXPECT_THAT( MakeNamedTupleQType({"a", "b"}, GetQType<int32_t>()).status(), StatusIs(absl::StatusCode::kFailedPrecondition, MatchesRegex(".*NamedTupleQType.*tuple.*found.*INT32.*"))); auto tuple_qtype = MakeTupleQType( {GetQType<int32_t>(), GetQType<double>(), GetQType<Bytes>()}); EXPECT_THAT(MakeNamedTupleQType({"a", "b"}, tuple_qtype).status(), StatusIs(absl::StatusCode::kFailedPrecondition, MatchesRegex(".*NamedTupleQType.*2 vs 3.*"))); EXPECT_THAT(MakeNamedTupleQType({"a", "b", "a"}, tuple_qtype).status(), StatusIs(absl::StatusCode::kFailedPrecondition, MatchesRegex(".*NamedTupleQType.*a.*duplicate.*"))); EXPECT_THAT(GetFieldNames(nullptr), IsEmpty()); EXPECT_THAT(GetFieldNames(GetQType<int32_t>()), IsEmpty()); } absl::StatusOr<TypedValue> CreateNamedTuple( absl::Span<const std::string> field_names, TypedValue tuple) { ASSIGN_OR_RETURN(auto namedtuple_qtype, MakeNamedTupleQType(field_names, tuple.GetType())); return UnsafeDowncastDerivedQValue(namedtuple_qtype, tuple); } TEST(NamedTupleQType, GetFieldByNameAs) { TypedValue tuple = MakeTupleFromFields(2.0f, 3); ASSERT_OK_AND_ASSIGN(TypedValue named_tuple, CreateNamedTuple({"a", "b"}, tuple)); EXPECT_THAT(GetFieldByNameAs<float>(named_tuple.AsRef(), "a"), IsOkAndHolds(2.0f)); EXPECT_THAT(GetFieldByNameAs<float>(named_tuple.AsRef(), "c").status(), StatusIs(absl::StatusCode::kInvalidArgument, MatchesRegex(".*no field named \"c\".*"))); EXPECT_THAT( GetFieldByNameAs<Bytes>(named_tuple.AsRef(), "a").status(), StatusIs( absl::StatusCode::kFailedPrecondition, HasSubstr("type mismatch: expected C++ type `float` (FLOAT32), got " "`arolla::Bytes`; while accessing field \"a\""))); } } }
2,338
cpp
google/arolla
typed_value
arolla/qtype/typed_value.cc
arolla/qtype/typed_value_test.cc
#ifndef AROLLA_QTYPE_TYPED_VALUE_H_ #define AROLLA_QTYPE_TYPED_VALUE_H_ #include <cstdint> #include <functional> #include <new> #include <string> #include <type_traits> #include <utility> #include "absl/base/attributes.h" #include "absl/base/call_once.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "arolla/memory/frame.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/typed_ref.h" #include "arolla/qtype/typed_slot.h" #include "arolla/util/fingerprint.h" #include "arolla/util/refcount.h" #include "arolla/util/repr.h" namespace arolla { class TypedValue { public: template <typename T> static TypedValue FromValue(T&& value); template <typename T> static TypedValue FromValue(const T& value); template <typename T> static absl::StatusOr<TypedValue> FromValueWithQType(T&& value, QTypePtr qtype); template <typename T> static absl::StatusOr<TypedValue> FromValueWithQType(const T& value, QTypePtr qtype); static TypedValue UnsafeFromTypeDefaultConstructed(QTypePtr type); static TypedValue FromSlot(TypedSlot slot, ConstFramePtr frame); static absl::StatusOr<TypedValue> FromFields( QTypePtr compound_type, absl::Span<const TypedRef> fields); static absl::StatusOr<TypedValue> FromFields( QTypePtr compound_type, absl::Span<const TypedValue> fields); explicit TypedValue(TypedRef value_ref); ~TypedValue() noexcept; TypedValue(TypedValue&& rhs) noexcept; TypedValue& operator=(TypedValue&& rhs) noexcept; TypedValue(const TypedValue& rhs) noexcept; TypedValue& operator=(const TypedValue& rhs) noexcept; QTypePtr GetType() const; const void* GetRawPointer() const ABSL_ATTRIBUTE_LIFETIME_BOUND; TypedRef AsRef() const ABSL_ATTRIBUTE_LIFETIME_BOUND; const Fingerprint& GetFingerprint() const ABSL_ATTRIBUTE_LIFETIME_BOUND; int64_t GetFieldCount() const; TypedRef GetField(int64_t index) const ABSL_ATTRIBUTE_LIFETIME_BOUND; absl::Status CopyToSlot(TypedSlot slot, FramePtr frame) const; template <typename T> absl::StatusOr<std::reference_wrapper<const T>> As() const ABSL_ATTRIBUTE_LIFETIME_BOUND; template <typename T> const T& UnsafeAs() const ABSL_ATTRIBUTE_LIFETIME_BOUND; std::string Repr() const; ReprToken GenReprToken() const; absl::string_view PyQValueSpecializationKey() const ABSL_ATTRIBUTE_LIFETIME_BOUND; private: struct Impl { Refcount refcount; absl::once_flag fingerprint_once; QTypePtr qtype; void* data; Fingerprint fingerprint; }; TypedValue(Impl* impl) noexcept : impl_(impl) {} static Impl* AllocRawImpl(QTypePtr qtype); static Impl* AllocImpl(QTypePtr qtype, const void* value); Impl* impl_; }; template <typename T> TypedValue TypedValue::FromValue(T&& value) { using V = std::decay_t<T>; static const QTypePtr qtype = GetQType<V>(); if constexpr (std::is_copy_constructible_v<V> || std::is_move_constructible_v<V>) { auto* raw_impl = AllocRawImpl(qtype); new (raw_impl->data) V(std::forward<T>(value)); return TypedValue(raw_impl); } else { return TypedValue(AllocImpl(qtype, &value)); } } template <typename T> TypedValue TypedValue::FromValue(const T& value) { static const QTypePtr qtype = GetQType<T>(); if constexpr (std::is_copy_constructible_v<T>) { auto* raw_impl = AllocRawImpl(qtype); new (raw_impl->data) T(value); return TypedValue(raw_impl); } else { return TypedValue(AllocImpl(qtype, &value)); } } template <typename T> absl::StatusOr<TypedValue> TypedValue::FromValueWithQType(T&& value, QTypePtr qtype) { using V = std::decay_t<T>; if (auto status = VerifyQTypeTypeInfo(qtype, typeid(V)); !status.ok()) { return status; } if constexpr (std::is_copy_constructible_v<V> || std::is_move_constructible_v<V>) { auto* raw_impl = AllocRawImpl(qtype); new (raw_impl->data) V(std::forward<T>(value)); return TypedValue(raw_impl); } else { return TypedValue(AllocImpl(qtype, &value)); } } template <typename T> absl::StatusOr<TypedValue> TypedValue::FromValueWithQType(const T& value, QTypePtr qtype) { if (auto status = VerifyQTypeTypeInfo(qtype, typeid(T)); !status.ok()) { return status; } if constexpr (std::is_copy_constructible_v<T>) { auto* raw_impl = AllocRawImpl(qtype); new (raw_impl->data) T(value); return TypedValue(raw_impl); } else { return TypedValue(AllocImpl(qtype, &value)); } } inline TypedValue TypedValue::FromSlot(TypedSlot slot, ConstFramePtr frame) { return TypedValue(TypedRef::FromSlot(slot, frame)); } inline TypedValue::TypedValue(TypedRef value_ref) : impl_(AllocImpl(value_ref.GetType(), value_ref.GetRawPointer())) {} inline TypedValue::~TypedValue() noexcept { if (impl_ != nullptr && !impl_->refcount.skewed_decrement()) { impl_->qtype->type_layout().DestroyAlloc(impl_->data); impl_->~Impl(); ::operator delete(impl_); } } inline TypedValue::TypedValue(TypedValue&& rhs) noexcept : impl_(rhs.impl_) { rhs.impl_ = nullptr; } inline TypedValue& TypedValue::operator=(TypedValue&& rhs) noexcept { using std::swap; swap(impl_, rhs.impl_); return *this; } inline TypedValue::TypedValue(const TypedValue& rhs) noexcept : impl_(rhs.impl_) { if (impl_ != nullptr) { impl_->refcount.increment(); } } inline TypedValue& TypedValue::operator=(const TypedValue& rhs) noexcept { if (impl_ != rhs.impl_) { *this = TypedValue(rhs); } return *this; } inline QTypePtr TypedValue::GetType() const { return impl_->qtype; } inline const void* TypedValue::GetRawPointer() const { return impl_->data; } inline TypedRef TypedValue::AsRef() const { return TypedRef::UnsafeFromRawPointer(impl_->qtype, impl_->data); } inline int64_t TypedValue::GetFieldCount() const { return impl_->qtype->type_fields().size(); } inline TypedRef TypedValue::GetField(int64_t index) const { return AsRef().GetField(index); } inline absl::Status TypedValue::CopyToSlot(TypedSlot slot, FramePtr frame) const { return AsRef().CopyToSlot(slot, frame); } template <typename T> absl::StatusOr<std::reference_wrapper<const T>> TypedValue::As() const { return AsRef().As<T>(); } template <typename T> const T& TypedValue::UnsafeAs() const { return AsRef().UnsafeAs<T>(); } inline std::string TypedValue::Repr() const { return std::move(AsRef().GenReprToken().str); } inline ReprToken TypedValue::GenReprToken() const { return AsRef().GenReprToken(); } inline absl::string_view TypedValue::PyQValueSpecializationKey() const { return AsRef().PyQValueSpecializationKey(); } } #endif #include "arolla/qtype/typed_value.h" #include <cstddef> #include <memory> #include <new> #include <utility> #include "absl/base/call_once.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/types/span.h" #include "arolla/memory/frame.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/typed_ref.h" #include "arolla/util/fingerprint.h" #include "arolla/util/memory.h" namespace arolla { namespace { template <typename TypedRef > absl::Status CheckPreconditionsForInitCompound( QTypePtr compound_qtype, absl::Span<const TypedRef> field_refs) { const auto& field_slots = compound_qtype->type_fields(); if (field_slots.size() != field_refs.size()) { return absl::InvalidArgumentError(absl::StrFormat( "expected %d values, got %d; compound_qtype=%s", field_slots.size(), field_refs.size(), compound_qtype->name())); } for (size_t i = 0; i < field_refs.size(); ++i) { if (field_refs[i].GetType() != field_slots[i].GetType()) { return absl::InvalidArgumentError(absl::StrFormat( "expected fields[%d]: %s, got %s; compound_qtype=%s", i, field_slots[i].GetType()->name(), field_refs[i].GetType()->name(), compound_qtype->name())); } } return absl::OkStatus(); } template <typename TypedRef > void InitCompound(QTypePtr compound_qtype, absl::Span<const TypedRef> field_refs, void* destination) { compound_qtype->type_layout().InitializeAlignedAlloc(destination); const auto& field_slots = compound_qtype->type_fields(); FramePtr frame(destination, &compound_qtype->type_layout()); for (size_t i = 0; i < field_refs.size(); ++i) { const auto& field_ref = field_refs[i]; field_ref.GetType()->UnsafeCopy( field_ref.GetRawPointer(), frame.GetRawPointer(field_slots[i].byte_offset())); } } } TypedValue::Impl* TypedValue::AllocRawImpl(QTypePtr qtype) { const auto& type_layout = qtype->type_layout(); const size_t alignment = type_layout.AllocAlignment().value; size_t extra_space = type_layout.AllocSize() + alignment; void* buffer = ::operator new(sizeof(Impl) + extra_space); Impl* impl = new (buffer) Impl; impl->qtype = qtype; impl->data = static_cast<char*>(buffer) + sizeof(Impl); void* tmp = std::align(alignment, extra_space, impl->data, extra_space); DCHECK_NE(tmp, nullptr); return impl; } TypedValue::Impl* TypedValue::AllocImpl(QTypePtr qtype, const void* value) { auto* impl = AllocRawImpl(qtype); qtype->type_layout().InitializeAlignedAlloc(impl->data); qtype->UnsafeCopy(value, impl->data); return impl; } TypedValue TypedValue::UnsafeFromTypeDefaultConstructed(QTypePtr qtype) { auto* impl = AllocRawImpl(qtype); qtype->type_layout().InitializeAlignedAlloc(impl->data); return TypedValue(impl); } absl::StatusOr<TypedValue> TypedValue::FromFields( QTypePtr compound_qtype, absl::Span<const TypedRef> fields) { if (auto status = CheckPreconditionsForInitCompound(compound_qtype, fields); !status.ok()) { return status; } auto* impl = AllocRawImpl(compound_qtype); InitCompound(compound_qtype, fields, impl->data); return TypedValue(impl); } absl::StatusOr<TypedValue> TypedValue::FromFields( QTypePtr compound_qtype, absl::Span<const TypedValue> fields) { if (auto status = CheckPreconditionsForInitCompound(compound_qtype, fields); !status.ok()) { return status; } auto* impl = AllocRawImpl(compound_qtype); InitCompound(compound_qtype, fields, impl->data); return TypedValue(impl); } const Fingerprint& TypedValue::GetFingerprint() const { absl::call_once(impl_->fingerprint_once, [impl = impl_] { FingerprintHasher hasher("TypedValue"); hasher.Combine(impl->qtype); impl->qtype->UnsafeCombineToFingerprintHasher(impl->data, &hasher); impl->fingerprint = std::move(hasher).Finish(); }); return impl_->fingerprint; } }
#include "arolla/qtype/typed_value.h" #include <cstdint> #include <utility> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/container/flat_hash_set.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "arolla/memory/frame.h" #include "arolla/memory/memory_allocation.h" #include "arolla/memory/optional_value.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/typed_slot.h" #include "arolla/util/bytes.h" #include "arolla/util/fingerprint.h" #include "arolla/util/testing/status_matchers_backport.h" struct WithoutQTypeTraits {}; namespace arolla { namespace { using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::StatusIs; using ::testing::Eq; using ::testing::HasSubstr; TEST(TypedValueTest, ReprBasic) { EXPECT_EQ(TypedValue::FromValue<bool>(true).Repr(), "true"); EXPECT_EQ(TypedValue::FromValue<int32_t>(5).Repr(), "5"); EXPECT_EQ(TypedValue::FromValue<int64_t>(5).Repr(), "int64{5}"); EXPECT_EQ(TypedValue::FromValue<uint64_t>(5).Repr(), "uint64{5}"); EXPECT_EQ(TypedValue::FromValue<float>(5.0f).Repr(), "5."); EXPECT_EQ(TypedValue::FromValue<double>(5.0).Repr(), "float64{5}"); } TEST(TypedValueTest, FromValue) { auto tval = TypedValue::FromValue<int64_t>(1); EXPECT_THAT(tval.GetType(), Eq(GetQType<int64_t>())); EXPECT_THAT(tval.As<int64_t>(), IsOkAndHolds(int64_t{1})); EXPECT_THAT(tval.As<float>().status(), StatusIs(absl::StatusCode::kFailedPrecondition)); } TEST(TypedValueTest, As) { auto int_value = TypedValue::FromValue<double>(1.0); EXPECT_THAT(int_value.As<double>(), IsOkAndHolds(1.0)); EXPECT_THAT(int_value.As<float>().status(), StatusIs(absl::StatusCode::kFailedPrecondition, HasSubstr("type mismatch: expected C++ type `double` " "(FLOAT64), got `float`"))); EXPECT_THAT(int_value.As<WithoutQTypeTraits>().status(), StatusIs(absl::StatusCode::kFailedPrecondition, HasSubstr("type mismatch: expected C++ type `double` " "(FLOAT64), got `WithoutQTypeTraits`"))); } TEST(TypedValueTest, FromValueWithQType) { auto f64 = GetQType<double>(); absl::StatusOr<TypedValue> tmp = TypedValue::FromValueWithQType(1.0, f64); auto tval = std::move(tmp).value(); EXPECT_THAT(tval.GetType(), Eq(f64)); EXPECT_THAT(tval.As<double>(), IsOkAndHolds(1.0)); EXPECT_THAT(tval.As<float>(), StatusIs(absl::StatusCode::kFailedPrecondition, HasSubstr("type mismatch: expected C++ type `double` " "(FLOAT64), got `float`"))); EXPECT_THAT(TypedValue::FromValueWithQType(1.0f, f64).status(), StatusIs(absl::StatusCode::kFailedPrecondition)); } TEST(TypedValueTest, UnsafeFromTypeDefaultConstructed) { { auto f64 = GetQType<double>(); auto tval = TypedValue::UnsafeFromTypeDefaultConstructed(f64); EXPECT_THAT(tval.GetType(), Eq(GetQType<double>())); EXPECT_THAT(tval.As<double>(), IsOkAndHolds(double{0.})); EXPECT_THAT(tval.As<float>().status(), StatusIs(absl::StatusCode::kFailedPrecondition)); } { auto bytes = GetQType<Bytes>(); auto tval = TypedValue::UnsafeFromTypeDefaultConstructed(bytes); EXPECT_THAT(tval.GetType(), Eq(GetQType<Bytes>())); ASSERT_OK_AND_ASSIGN(auto val_ref, tval.As<Bytes>()); EXPECT_THAT(val_ref.get(), Eq(Bytes())); EXPECT_THAT(tval.As<float>().status(), StatusIs(absl::StatusCode::kFailedPrecondition)); } { auto of64 = GetQType<OptionalValue<double>>(); auto tval = TypedValue::UnsafeFromTypeDefaultConstructed(of64); EXPECT_THAT(tval.GetType(), Eq(GetQType<OptionalValue<double>>())); ASSERT_OK_AND_ASSIGN(auto val_ref, tval.As<OptionalValue<double>>()); EXPECT_THAT(val_ref.get(), Eq(OptionalValue<double>())); EXPECT_THAT(tval.As<OptionalValue<float>>().status(), StatusIs(absl::StatusCode::kFailedPrecondition)); } } TEST(TypedValueTest, FromSlot) { FrameLayout::Builder builder; QTypePtr f32 = GetQType<float>(); TypedSlot tslot = AddSlot(f32, &builder); auto layout = std::move(builder).Build(); MemoryAllocation alloc(&layout); FramePtr ptr = alloc.frame(); EXPECT_OK(TypedValue::FromValue(7.5f).CopyToSlot(tslot, ptr)); auto tval = TypedValue::FromSlot(tslot, ptr); EXPECT_THAT(tval.GetType(), Eq(f32)); EXPECT_THAT(tval.As<float>(), IsOkAndHolds(7.5f)); } TEST(TypedValueTest, ToSlot) { FrameLayout::Builder builder; QTypePtr f64 = GetQType<double>(); TypedSlot tslot = AddSlot(f64, &builder); auto layout = std::move(builder).Build(); MemoryAllocation alloc(&layout); FramePtr ptr = alloc.frame(); auto tval = TypedValue::FromValue(double{1.0}); EXPECT_OK(tval.CopyToSlot(tslot, ptr)); auto slot = tslot.ToSlot<double>().value(); EXPECT_THAT(ptr.Get(slot), Eq(1.0)); } TEST(TypedValueTest, Copy) { auto tval = TypedValue::FromValue(double{1.0}); auto tval_copy = tval; EXPECT_THAT(tval_copy.As<double>(), IsOkAndHolds(1.0)); } TEST(TypedValueTest, FingerprintUniqueness) { absl::flat_hash_set<Fingerprint> fingerprints; EXPECT_TRUE( fingerprints.insert(TypedValue::FromValue(int32_t{0}).GetFingerprint()) .second); EXPECT_TRUE( fingerprints.insert(TypedValue::FromValue(int64_t{0}).GetFingerprint()) .second); EXPECT_TRUE( fingerprints.insert(TypedValue::FromValue(uint64_t{0}).GetFingerprint()) .second); EXPECT_TRUE( fingerprints.insert(TypedValue::FromValue(double{0}).GetFingerprint()) .second); EXPECT_TRUE( fingerprints.insert(TypedValue::FromValue(float{0}).GetFingerprint()) .second); } TEST(TypedValueTest, FingerprintReproducibility) { EXPECT_EQ(TypedValue::FromValue(int32_t{0}).GetFingerprint(), TypedValue::FromValue(int32_t{0}).GetFingerprint()); EXPECT_EQ(TypedValue::FromValue(int64_t{0}).GetFingerprint(), TypedValue::FromValue(int64_t{0}).GetFingerprint()); EXPECT_EQ(TypedValue::FromValue(uint64_t{0}).GetFingerprint(), TypedValue::FromValue(uint64_t{0}).GetFingerprint()); EXPECT_EQ(TypedValue::FromValue(float{0}).GetFingerprint(), TypedValue::FromValue(float{0}).GetFingerprint()); EXPECT_EQ(TypedValue::FromValue(double{0}).GetFingerprint(), TypedValue::FromValue(double{0}).GetFingerprint()); } TEST(TypedValueTest, UnsafeAs) { auto tval = TypedValue::FromValue<int64_t>(1); ASSERT_THAT(tval.GetType(), Eq(GetQType<int64_t>())); EXPECT_THAT(tval.UnsafeAs<int64_t>(), Eq(int64_t{1})); } TEST(TypedValueTest, CopyConstructor) { TypedValue x = TypedValue::FromValue<int64_t>(1); TypedValue y = x; EXPECT_EQ(x.GetType(), y.GetType()); EXPECT_EQ(x.GetRawPointer(), y.GetRawPointer()); } TEST(TypedValueTest, CopyOperator) { TypedValue x = TypedValue::FromValue<int64_t>(1); TypedValue y = TypedValue::FromValue<int64_t>(2); y = x; EXPECT_EQ(x.GetType(), y.GetType()); EXPECT_EQ(x.GetRawPointer(), y.GetRawPointer()); } TEST(TypedValueTest, MoveConstructor) { TypedValue x = TypedValue::FromValue<int64_t>(1); auto* x_type = x.GetType(); auto* x_raw_ptr = x.GetRawPointer(); TypedValue y = std::move(x); EXPECT_EQ(y.GetType(), x_type); EXPECT_EQ(y.GetRawPointer(), x_raw_ptr); } TEST(TypedValueTest, MoveOperator) { TypedValue x = TypedValue::FromValue<int64_t>(1); TypedValue y = TypedValue::FromValue<int64_t>(2); auto* x_type = x.GetType(); auto* x_raw_ptr = x.GetRawPointer(); y = std::move(x); EXPECT_EQ(y.GetType(), x_type); EXPECT_EQ(y.GetRawPointer(), x_raw_ptr); } TEST(TypedValueTest, CopyFromValue) { const Bytes bytes("data"); TypedValue x = TypedValue::FromValue(bytes); ASSERT_OK_AND_ASSIGN(Bytes x_bytes, x.As<Bytes>()); EXPECT_THAT(x_bytes, Eq(bytes)); } TEST(TypedValueTest, CopyFromValueT) { const Bytes bytes("data"); TypedValue x = TypedValue::FromValue<Bytes>(bytes); ASSERT_OK_AND_ASSIGN(Bytes x_bytes, x.As<Bytes>()); EXPECT_THAT(x_bytes, Eq(bytes)); } TEST(TypedValueTest, MoveFromValueT) { Bytes bytes("a long string literal to ensure memory allocation"); auto* data_raw_ptr = bytes.data(); TypedValue x = TypedValue::FromValue<Bytes>(std::move(bytes)); EXPECT_EQ(x.UnsafeAs<Bytes>().data(), data_raw_ptr); } TEST(TypedValueTest, CopyFromValueWithQType) { const Bytes bytes("data"); ASSERT_OK_AND_ASSIGN( TypedValue x, TypedValue::FromValueWithQType(bytes, GetQType<Bytes>())); ASSERT_OK_AND_ASSIGN(Bytes x_bytes, x.As<Bytes>()); EXPECT_THAT(x_bytes, Eq(bytes)); } TEST(TypedValueTest, MoveFromValueWithQType) { Bytes bytes("a long string literal to ensure memory allocation"); auto* data_raw_ptr = bytes.data(); ASSERT_OK_AND_ASSIGN(TypedValue x, TypedValue::FromValueWithQType( std::move(bytes), GetQType<Bytes>())); EXPECT_EQ(x.UnsafeAs<Bytes>().data(), data_raw_ptr); } } }
2,339
cpp
google/arolla
weak_qtype
arolla/qtype/weak_qtype.cc
arolla/qtype/weak_qtype_test.cc
#ifndef AROLLA_QTYPE_WEAK_QTYPE_H_ #define AROLLA_QTYPE_WEAK_QTYPE_H_ #include "arolla/qtype/qtype.h" namespace arolla { QTypePtr GetWeakFloatQType(); QTypePtr GetOptionalWeakFloatQType(); } #endif #include "arolla/qtype/weak_qtype.h" #include <utility> #include <vector> #include "absl/log/check.h" #include "absl/strings/str_cat.h" #include "arolla/memory/optional_value.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/fingerprint.h" #include "arolla/util/indestructible.h" #include "arolla/util/repr.h" namespace arolla { namespace { class WeakFloatQType final : public BasicDerivedQType { public: explicit WeakFloatQType() : BasicDerivedQType(ConstructorArgs{ .name = "WEAK_FLOAT", .base_qtype = GetQType<double>(), }) { CHECK_OK(VerifyDerivedQType(this)); } static QTypePtr get() { static const Indestructible<WeakFloatQType> result; return result.get(); } ReprToken UnsafeReprToken(const void* source) const override { return GenReprTokenWeakFloat(*static_cast<const double*>(source)); } }; class OptionalWeakFloatQType final : public QType, public DerivedQTypeInterface { public: OptionalWeakFloatQType() : QType(MakeConstructorArgs()) { CHECK_OK(VerifyDerivedQType(this)); } static QTypePtr get() { static const Indestructible<OptionalWeakFloatQType> result; return result.get(); } QTypePtr GetBaseQType() const final { return GetOptionalQType<double>(); } ReprToken UnsafeReprToken(const void* source) const final { const auto& value = *static_cast<const OptionalValue<double>*>(source); if (value.present) { return ReprToken{ absl::StrCat("optional_", GenReprTokenWeakFloat(value.value).str)}; } return ReprToken{"optional_weak_float{NA}"}; } void UnsafeCopy(const void* source, void* destination) const final { if (source != destination) { *static_cast<OptionalValue<double>*>(destination) = *static_cast<const OptionalValue<double>*>(source); } } void UnsafeCombineToFingerprintHasher(const void* source, FingerprintHasher* hasher) const final { hasher->Combine(*static_cast<const OptionalValue<double>*>(source)); } private: static ConstructorArgs MakeConstructorArgs() { auto base_qtype = GetOptionalQType<double>(); std::vector<TypedSlot> fields = base_qtype->type_fields(); DCHECK_EQ(fields.size(), 2); fields[1] = TypedSlot::UnsafeFromOffset(WeakFloatQType::get(), fields[1].byte_offset()); return ConstructorArgs{ .name = "OPTIONAL_WEAK_FLOAT", .type_info = base_qtype->type_info(), .type_layout = base_qtype->type_layout(), .type_fields = std::move(fields), .value_qtype = WeakFloatQType::get(), }; } }; } QTypePtr GetWeakFloatQType() { return WeakFloatQType::get(); } QTypePtr GetOptionalWeakFloatQType() { return OptionalWeakFloatQType::get(); } namespace { static const int optional_weak_float_registered = (RegisterOptionalQType(GetOptionalWeakFloatQType()), 1); } }
#include "arolla/qtype/weak_qtype.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "arolla/array/qtype/types.h" #include "arolla/memory/optional_value.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/optional_qtype.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/shape_qtype.h" #include "arolla/qtype/standard_type_properties/properties.h" #include "arolla/qtype/typed_value.h" #include "arolla/util/testing/repr_token_eq.h" #include "arolla/util/testing/status_matchers_backport.h" #include "arolla/util/unit.h" namespace arolla { namespace { using ::arolla::testing::ReprTokenEq; using ::arolla::testing::StatusIs; using ::testing::MatchesRegex; TEST(WeakQTypeTest, Smoke) { auto qtype = GetWeakFloatQType(); EXPECT_EQ(qtype->name(), "WEAK_FLOAT"); auto optional_qtype = GetOptionalWeakFloatQType(); EXPECT_EQ(optional_qtype->name(), "OPTIONAL_WEAK_FLOAT"); } TEST(WeakQTypeTest, Optional) { QTypePtr qtype = GetWeakFloatQType(); QTypePtr optional_qtype = GetOptionalWeakFloatQType(); EXPECT_EQ(optional_qtype->value_qtype(), qtype); EXPECT_TRUE(IsOptionalQType(optional_qtype)); ASSERT_OK_AND_ASSIGN(QTypePtr to_optional_res, ToOptionalQType(qtype)); EXPECT_EQ(to_optional_res, optional_qtype); EXPECT_EQ(DecayOptionalQType(optional_qtype), qtype); ASSERT_OK_AND_ASSIGN(TypedValue v, CreateMissingValue(optional_qtype)); ASSERT_EQ(v.GetType(), optional_qtype); } TEST(WeakQTypeTest, IsScalarQType) { EXPECT_TRUE(IsScalarQType(GetWeakFloatQType())); EXPECT_FALSE(IsScalarQType(GetOptionalWeakFloatQType())); } TEST(WeakQTypeTest, GetScalarQType) { { ASSERT_OK_AND_ASSIGN(QTypePtr scalar_qtype, GetScalarQType(GetWeakFloatQType())); EXPECT_EQ(scalar_qtype, GetWeakFloatQType()); } { ASSERT_OK_AND_ASSIGN(QTypePtr scalar_qtype, GetScalarQType(GetOptionalWeakFloatQType())); EXPECT_EQ(scalar_qtype, GetWeakFloatQType()); } } TEST(WeakQTypeTest, WithScalarQType) { { ASSERT_OK_AND_ASSIGN( QTypePtr res_qtype, WithScalarQType(GetQType<float>(), GetWeakFloatQType())); EXPECT_EQ(res_qtype, GetWeakFloatQType()); } { ASSERT_OK_AND_ASSIGN( QTypePtr res_qtype, WithScalarQType(GetOptionalQType<double>(), GetWeakFloatQType())); EXPECT_EQ(res_qtype, GetOptionalWeakFloatQType()); } EXPECT_THAT(WithScalarQType(GetArrayQType<float>(), GetWeakFloatQType()), StatusIs(absl::StatusCode::kInvalidArgument, MatchesRegex("Array type with elements of type " "WEAK_FLOAT is not registered."))); { ASSERT_OK_AND_ASSIGN( QTypePtr res_qtype, WithScalarQType(GetWeakFloatQType(), GetQType<double>())); EXPECT_EQ(res_qtype, GetQType<double>()); } { ASSERT_OK_AND_ASSIGN( QTypePtr res_qtype, WithScalarQType(GetOptionalWeakFloatQType(), GetQType<float>())); EXPECT_EQ(res_qtype, GetOptionalQType<float>()); } } TEST(WeakQTypeTest, DecayContainerQType) { EXPECT_EQ(DecayContainerQType(GetWeakFloatQType()), GetWeakFloatQType()); EXPECT_EQ(DecayContainerQType(GetOptionalWeakFloatQType()), GetWeakFloatQType()); } TEST(WeakQTypeTest, GetShapeQType) { { ASSERT_OK_AND_ASSIGN(QTypePtr shape_qtype, GetShapeQType(GetWeakFloatQType())); EXPECT_EQ(shape_qtype, GetQType<ScalarShape>()); } { ASSERT_OK_AND_ASSIGN(QTypePtr shape_qtype, GetShapeQType(GetOptionalWeakFloatQType())); EXPECT_EQ(shape_qtype, GetQType<OptionalScalarShape>()); } } TEST(WeakQTypeTest, GetPresenceQType) { { ASSERT_OK_AND_ASSIGN(QTypePtr presence_qtype, GetPresenceQType(GetWeakFloatQType())); EXPECT_EQ(presence_qtype, GetQType<Unit>()); } { ASSERT_OK_AND_ASSIGN(QTypePtr presence_qtype, GetPresenceQType(GetOptionalWeakFloatQType())); EXPECT_EQ(presence_qtype, GetOptionalQType<Unit>()); } } TEST(WeakQTypeTest, OptionalLike) { EXPECT_FALSE(IsOptionalLikeQType(GetWeakFloatQType())); EXPECT_TRUE(IsOptionalLikeQType(GetOptionalWeakFloatQType())); { ASSERT_OK_AND_ASSIGN(QTypePtr optional_like_qtype, ToOptionalLikeQType(GetWeakFloatQType())); EXPECT_EQ(optional_like_qtype, GetOptionalWeakFloatQType()); } { ASSERT_OK_AND_ASSIGN(QTypePtr optional_like_qtype, ToOptionalLikeQType(GetOptionalWeakFloatQType())); EXPECT_EQ(optional_like_qtype, GetOptionalWeakFloatQType()); } } TEST(WeakQTypeTest, WeakFloatFingerprint) { const double value_a = 1.5; const double value_b = 2.5; const auto float64_qvalue_a = TypedValue::FromValue(value_a); ASSERT_OK_AND_ASSIGN( const auto weak_float_qvalue_a1, TypedValue::FromValueWithQType(value_a, GetWeakFloatQType())); ASSERT_OK_AND_ASSIGN( const auto weak_float_qvalue_a2, TypedValue::FromValueWithQType(value_a, GetWeakFloatQType())); ASSERT_OK_AND_ASSIGN( const auto weak_float_qvalue_b, TypedValue::FromValueWithQType(value_b, GetWeakFloatQType())); EXPECT_NE(float64_qvalue_a.GetFingerprint(), weak_float_qvalue_a1.GetFingerprint()); EXPECT_EQ(weak_float_qvalue_a1.GetFingerprint(), weak_float_qvalue_a2.GetFingerprint()); EXPECT_NE(weak_float_qvalue_a1.GetFingerprint(), weak_float_qvalue_b.GetFingerprint()); } TEST(WeakQTypeTest, OptionalWeakFloatFingerprint) { const OptionalValue<double> value_a(1.5); const OptionalValue<double> value_b(2.5); const auto optional_float64_qvalue_a = TypedValue::FromValue(value_a); ASSERT_OK_AND_ASSIGN( const auto optional_weak_float_qvalue_a1, TypedValue::FromValueWithQType(value_a, GetOptionalWeakFloatQType())); ASSERT_OK_AND_ASSIGN( const auto optional_weak_float_qvalue_a2, TypedValue::FromValueWithQType(value_a, GetOptionalWeakFloatQType())); ASSERT_OK_AND_ASSIGN( const auto optional_weak_float_qvalue_b, TypedValue::FromValueWithQType(value_b, GetOptionalWeakFloatQType())); EXPECT_NE(optional_float64_qvalue_a.GetFingerprint(), optional_weak_float_qvalue_a1.GetFingerprint()); EXPECT_EQ(optional_weak_float_qvalue_a1.GetFingerprint(), optional_weak_float_qvalue_a2.GetFingerprint()); EXPECT_NE(optional_weak_float_qvalue_a1.GetFingerprint(), optional_weak_float_qvalue_b.GetFingerprint()); } TEST(WeakQTypeTest, WeakFloatRepr) { ASSERT_OK_AND_ASSIGN(auto qvalue, TypedValue::FromValueWithQType( double{1.5}, GetWeakFloatQType())); EXPECT_THAT(qvalue.GenReprToken(), ReprTokenEq("weak_float{1.5}")); } TEST(WeakQTypeTest, OptionalWeakFloatRepr) { ASSERT_OK_AND_ASSIGN( auto qvalue, TypedValue::FromValueWithQType(OptionalValue<double>(1.5), GetOptionalWeakFloatQType())); EXPECT_THAT(qvalue.GenReprToken(), ReprTokenEq("optional_weak_float{1.5}")); } TEST(WeakQTypeTest, OptionalWeakFloatMissingValueRepr) { ASSERT_OK_AND_ASSIGN( auto qvalue, TypedValue::FromValueWithQType(OptionalValue<double>(), GetOptionalWeakFloatQType())); EXPECT_THAT(qvalue.GenReprToken(), ReprTokenEq("optional_weak_float{NA}")); } } }
2,340
cpp
google/arolla
any_qtype
arolla/qtype/any_qtype.cc
arolla/qtype/any_qtype_test.cc
#ifndef AROLLA_QTYPE_ANY_QTYPE_H_ #define AROLLA_QTYPE_ANY_QTYPE_H_ #include <any> #include <cstdint> #include <functional> #include <type_traits> #include <typeinfo> #include "absl/random/distributions.h" #include "absl/random/random.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "arolla/qtype/simple_qtype.h" #include "arolla/util/fingerprint.h" namespace arolla { class Any { public: Any() = default; Any(Any&&) = default; Any(const Any&) = default; Any& operator=(Any&&) = default; Any& operator=(const Any&) = default; template <typename T, typename = std::enable_if_t<!std::is_same_v<Any, std::decay_t<T>>>> explicit Any(T&& v) : value_(std::forward<T>(v)) { absl::BitGen b; fingerprint_val1_ = absl::Uniform<uint64_t>(b); fingerprint_val2_ = absl::Uniform<uint64_t>(b); } template <typename T> absl::StatusOr<std::reference_wrapper<const T>> As() const { const T* v = std::any_cast<T>(&value_); if (v) { return *v; } else { return InvalidCast(typeid(T)); } } void ArollaFingerprint(FingerprintHasher* hasher) const { hasher->Combine(fingerprint_val1_, fingerprint_val2_); } private: std::any value_; uint64_t fingerprint_val1_, fingerprint_val2_; absl::Status InvalidCast(const std::type_info& t) const; }; AROLLA_DECLARE_SIMPLE_QTYPE(ANY, Any); } #endif #include "arolla/qtype/any_qtype.h" #include <typeinfo> #include "absl/status/status.h" #include "absl/strings/str_format.h" #include "arolla/qtype/simple_qtype.h" #include "arolla/util/demangle.h" namespace arolla { absl::Status Any::InvalidCast(const std::type_info& t) const { if (value_.has_value()) { return absl::FailedPreconditionError(absl::StrFormat( "can not cast Any(%s) to %s", TypeName(value_.type()), TypeName(t))); } else { return absl::FailedPreconditionError("can not cast an empty ::arolla::Any"); } } AROLLA_DEFINE_SIMPLE_QTYPE(ANY, Any); }
#include "arolla/qtype/any_qtype.h" #include <string> #include <utility> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "arolla/qtype/typed_value.h" #include "arolla/util/testing/status_matchers_backport.h" namespace arolla { namespace { using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::StatusIs; using ::testing::HasSubstr; TEST(AnyQType, AnyConstructorRegression) { Any any; Any copy_1 = any; Any copy_2(any); Any copy_3 = std::move(any); Any copy_4(std::move(copy_2)); } TEST(AnyQType, Any) { int v1 = 5; std::string v2 = "string"; TypedValue tv1 = TypedValue::FromValue(Any(v1)); TypedValue tv2 = TypedValue::FromValue(Any(v2)); TypedValue tv3 = TypedValue::FromValue(Any()); ASSERT_OK_AND_ASSIGN(const Any& a1, tv1.As<Any>()); ASSERT_OK_AND_ASSIGN(const Any& a2, tv2.As<Any>()); ASSERT_OK_AND_ASSIGN(const Any& a3, tv3.As<Any>()); EXPECT_THAT(a1.As<int>(), IsOkAndHolds(v1)); EXPECT_THAT(a1.As<double>(), StatusIs(absl::StatusCode::kFailedPrecondition, HasSubstr("can not cast Any"))); ASSERT_OK_AND_ASSIGN(const std::string& v2_res, a2.As<std::string>()); EXPECT_EQ(v2, v2_res); EXPECT_THAT(a2.As<double>(), StatusIs(absl::StatusCode::kFailedPrecondition, HasSubstr("can not cast Any"))); EXPECT_THAT(a3.As<double>(), StatusIs(absl::StatusCode::kFailedPrecondition, HasSubstr("can not cast an empty ::arolla::Any"))); } TEST(AnyQType, Fingerprint) { Any a = Any(1); Any b = Any(1); Any a_copy = a; EXPECT_NE(TypedValue::FromValue(a).GetFingerprint(), TypedValue::FromValue(b).GetFingerprint()); EXPECT_EQ(TypedValue::FromValue(a).GetFingerprint(), TypedValue::FromValue(a_copy).GetFingerprint()); } } }
2,341
cpp
google/arolla
derived_qtype
arolla/qtype/derived_qtype.cc
arolla/qtype/derived_qtype_test.cc
#ifndef AROLLA_QTYPE_DERIVED_QTYPE_H_ #define AROLLA_QTYPE_DERIVED_QTYPE_H_ #include <string> #include "absl/status/status.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/typed_ref.h" #include "arolla/qtype/typed_value.h" #include "arolla/util/fingerprint.h" #include "arolla/util/repr.h" namespace arolla { class DerivedQTypeInterface { public: virtual ~DerivedQTypeInterface() = default; virtual QTypePtr GetBaseQType() const = 0; }; class BasicDerivedQType : public QType, public DerivedQTypeInterface { public: ReprToken UnsafeReprToken(const void* source) const override; void UnsafeCombineToFingerprintHasher(const void* source, FingerprintHasher* hasher) const final; void UnsafeCopy(const void* source, void* destination) const final; QTypePtr GetBaseQType() const final { return base_qtype_; } protected: struct ConstructorArgs { std::string name; QTypePtr base_qtype; const QType* value_qtype = nullptr; std::string qtype_specialization_key; }; explicit BasicDerivedQType(ConstructorArgs args); private: QTypePtr base_qtype_; }; absl::Status VerifyDerivedQType(QTypePtr qtype); const QType* DecayDerivedQType(const QType* qtype); TypedRef DecayDerivedQValue(TypedRef qvalue); TypedValue DecayDerivedQValue(const TypedValue& qvalue); TypedRef UnsafeDowncastDerivedQValue(QTypePtr derived_qtype, TypedRef qvalue); TypedValue UnsafeDowncastDerivedQValue(QTypePtr derived_qtype, const TypedValue& qvalue); } #endif #include "arolla/qtype/derived_qtype.h" #include <cstddef> #include <utility> #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/typed_ref.h" #include "arolla/qtype/typed_slot.h" #include "arolla/qtype/typed_value.h" #include "arolla/util/fingerprint.h" #include "arolla/util/repr.h" namespace arolla { BasicDerivedQType::BasicDerivedQType(ConstructorArgs args) : QType(QType::ConstructorArgs{ .name = std::move(args.name), .type_info = args.base_qtype->type_info(), .type_layout = args.base_qtype->type_layout(), .type_fields = args.base_qtype->type_fields(), .value_qtype = args.value_qtype, .qtype_specialization_key = std::move(args.qtype_specialization_key), }), base_qtype_(args.base_qtype) { CHECK_OK(VerifyDerivedQType(this)); } ReprToken BasicDerivedQType::UnsafeReprToken(const void* source) const { return ReprToken{ absl::StrCat(name(), "{", base_qtype_->UnsafeReprToken(source).str, "}")}; } void BasicDerivedQType::UnsafeCopy(const void* source, void* destination) const { base_qtype_->UnsafeCopy(source, destination); } void BasicDerivedQType::UnsafeCombineToFingerprintHasher( const void* source, FingerprintHasher* hasher) const { base_qtype_->UnsafeCombineToFingerprintHasher(source, hasher); } const QType* DecayDerivedQType(const QType* qtype) { if (auto* derived_qtype_interface = dynamic_cast<const DerivedQTypeInterface*>(qtype)) { return derived_qtype_interface->GetBaseQType(); } return qtype; } absl::Status VerifyDerivedQType(QTypePtr qtype) { const auto* derived_qtype_interface = dynamic_cast<const DerivedQTypeInterface*>(qtype); if (derived_qtype_interface == nullptr) { return absl::InvalidArgumentError( absl::StrFormat("%s is not a derived qtype", qtype->name())); } const auto* base_qtype = derived_qtype_interface->GetBaseQType(); if (base_qtype == nullptr) { return absl::FailedPreconditionError(absl::StrFormat( "invalid derived_qtype=%s: base_qtype=nullptr", qtype->name())); } if (dynamic_cast<const DerivedQTypeInterface*>(base_qtype) != nullptr) { return absl::FailedPreconditionError(absl::StrFormat( "base_qtype=%s cannot be a derived qtype", base_qtype->name())); } const bool type_info_ok = (qtype->type_info() == base_qtype->type_info()); if (!type_info_ok) { return absl::FailedPreconditionError(absl::StrFormat( "invalid derived_qtype=%s: base_qtype=%s: incompatible type_info", qtype->name(), base_qtype->name())); } const bool type_layout_ok = (qtype->type_layout().AllocSize() == base_qtype->type_layout().AllocSize() && qtype->type_layout().AllocAlignment().value == base_qtype->type_layout().AllocAlignment().value); if (!type_layout_ok) { return absl::FailedPreconditionError(absl::StrFormat( "invalid derived_qtype=%s: base_qtype=%s: incompatible type_layout", qtype->name(), base_qtype->name())); } bool type_fields_ok = (qtype->type_fields().empty() || qtype->type_fields().size() == base_qtype->type_fields().size()); for (size_t i = 0; type_fields_ok && i < qtype->type_fields().size() && i < base_qtype->type_fields().size(); ++i) { const auto& derived_field = qtype->type_fields()[i]; const auto& base_field = base_qtype->type_fields()[i]; type_fields_ok = type_fields_ok && (derived_field.byte_offset() == base_field.byte_offset() && DecayDerivedQType(derived_field.GetType()) == DecayDerivedQType(base_field.GetType())); } if (!type_layout_ok) { return absl::FailedPreconditionError(absl::StrFormat( "invalid derived_qtype=%s: base_qtype=%s: incompatible type_fields", qtype->name(), base_qtype->name())); } const bool value_qtype_ok = (qtype->value_qtype() == nullptr || base_qtype->value_qtype() == nullptr || DecayDerivedQType(qtype->value_qtype()) == DecayDerivedQType(base_qtype->value_qtype())); if (!value_qtype_ok) { return absl::FailedPreconditionError(absl::StrFormat( "invalid derived_qtype=%s: base_qtype=%s: incompatible value_qtype", qtype->name(), base_qtype->name())); } return absl::OkStatus(); } TypedRef DecayDerivedQValue(TypedRef qvalue) { return TypedRef::UnsafeFromRawPointer(DecayDerivedQType(qvalue.GetType()), qvalue.GetRawPointer()); } TypedValue DecayDerivedQValue(const TypedValue& qvalue) { return TypedValue(DecayDerivedQValue(qvalue.AsRef())); } TypedRef UnsafeDowncastDerivedQValue(QTypePtr derived_qtype, TypedRef qvalue) { DCHECK_NE(derived_qtype, nullptr); auto* base_qtype = DecayDerivedQType(derived_qtype); DCHECK_EQ(qvalue.GetType(), base_qtype); return TypedRef::UnsafeFromRawPointer(derived_qtype, qvalue.GetRawPointer()); } TypedValue UnsafeDowncastDerivedQValue(QTypePtr derived_qtype, const TypedValue& qvalue) { return TypedValue(UnsafeDowncastDerivedQValue(derived_qtype, qvalue.AsRef())); } }
#include "arolla/qtype/derived_qtype.h" #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/tuple_qtype.h" #include "arolla/qtype/typed_ref.h" #include "arolla/qtype/typed_value.h" #include "arolla/util/fingerprint.h" #include "arolla/util/indestructible.h" #include "arolla/util/init_arolla.h" #include "arolla/util/testing/repr_token_eq.h" namespace arolla { namespace { using ::arolla::testing::ReprTokenEq; struct PointQType final : BasicDerivedQType { PointQType() : BasicDerivedQType(ConstructorArgs{ .name = "POINT", .base_qtype = MakeTupleQType({GetQType<double>(), GetQType<double>()}), .value_qtype = GetQType<double>(), .qtype_specialization_key = "::arolla::PointQType", }) {} static QTypePtr get() { static const Indestructible<PointQType> result; return result.get(); } }; class BasicDerivedQTypeTest : public ::testing::Test { void SetUp() override { ASSERT_OK(InitArolla()); } }; TEST_F(BasicDerivedQTypeTest, QTypeProperties) { const auto point_qtype = PointQType::get(); EXPECT_EQ(point_qtype->name(), "POINT"); EXPECT_EQ(point_qtype->value_qtype(), GetQType<double>()); EXPECT_EQ(point_qtype->qtype_specialization_key(), "::arolla::PointQType"); const auto tuple_qtype = MakeTupleQType({GetQType<double>(), GetQType<double>()}); EXPECT_EQ(point_qtype->type_info(), tuple_qtype->type_info()); EXPECT_EQ(point_qtype->type_layout().AllocSize(), tuple_qtype->type_layout().AllocSize()); EXPECT_EQ(point_qtype->type_layout().AllocAlignment().value, tuple_qtype->type_layout().AllocAlignment().value); EXPECT_EQ(point_qtype->type_fields().size(), 2); } TEST_F(BasicDerivedQTypeTest, DefaultRepr) { const auto tuple_qvalue = MakeTupleFromFields(1., 2.); const auto point_qvalue = UnsafeDowncastDerivedQValue(PointQType::get(), tuple_qvalue.AsRef()); EXPECT_THAT(point_qvalue.GenReprToken(), ReprTokenEq("POINT{(float64{1}, float64{2})}")); } TEST_F(BasicDerivedQTypeTest, UnsafeCombineToFingerprintHasher) { const auto tuple_qvalue = MakeTupleFromFields(1., 2.); const auto* tuple_qtype = tuple_qvalue.GetType(); const auto* point_qtype = PointQType::get(); FingerprintHasher hasher1("seed"); FingerprintHasher hasher2("seed"); tuple_qtype->UnsafeCombineToFingerprintHasher(tuple_qvalue.GetRawPointer(), &hasher1); point_qtype->UnsafeCombineToFingerprintHasher(tuple_qvalue.GetRawPointer(), &hasher2); EXPECT_EQ(std::move(hasher1).Finish(), std::move(hasher2).Finish()); } TEST_F(BasicDerivedQTypeTest, DecayDerivedQType) { const auto point_qtype = PointQType::get(); const auto tuple_qtype = MakeTupleQType({GetQType<double>(), GetQType<double>()}); EXPECT_NE(point_qtype, tuple_qtype); EXPECT_EQ(DecayDerivedQType(point_qtype), tuple_qtype); EXPECT_EQ(DecayDerivedQType(tuple_qtype), tuple_qtype); EXPECT_EQ(DecayDerivedQType(nullptr), nullptr); } TEST_F(BasicDerivedQTypeTest, UnsafeDowncastDerivedQRef) { const auto tuple_qvalue = MakeTupleFromFields(1., 2.); const auto point_qvalue = TypedValue( UnsafeDowncastDerivedQValue(PointQType::get(), tuple_qvalue.AsRef())); EXPECT_EQ(point_qvalue.GetType(), PointQType::get()); EXPECT_NE(point_qvalue.GetFingerprint(), tuple_qvalue.GetFingerprint()); } TEST_F(BasicDerivedQTypeTest, UnsafeDowncastDerivedQValue) { const auto tuple_qvalue = MakeTupleFromFields(1., 2.); const auto point_qvalue = UnsafeDowncastDerivedQValue(PointQType::get(), tuple_qvalue); EXPECT_EQ(point_qvalue.GetType(), PointQType::get()); EXPECT_NE(point_qvalue.GetFingerprint(), tuple_qvalue.GetFingerprint()); } TEST_F(BasicDerivedQTypeTest, DecayDerivedQRef) { const auto tuple_qvalue = MakeTupleFromFields(1., 2.); const auto point_qvalue = TypedValue( UnsafeDowncastDerivedQValue(PointQType::get(), tuple_qvalue.AsRef())); EXPECT_NE(point_qvalue.GetFingerprint(), tuple_qvalue.GetFingerprint()); EXPECT_EQ( TypedValue(DecayDerivedQValue(point_qvalue.AsRef())).GetFingerprint(), tuple_qvalue.GetFingerprint()); EXPECT_EQ( TypedValue(DecayDerivedQValue(tuple_qvalue.AsRef())).GetFingerprint(), tuple_qvalue.GetFingerprint()); } TEST_F(BasicDerivedQTypeTest, DecayDerivedQValue) { const auto tuple_qvalue = MakeTupleFromFields(1., 2.); const auto point_qvalue = UnsafeDowncastDerivedQValue(PointQType::get(), tuple_qvalue); EXPECT_NE(point_qvalue.GetFingerprint(), tuple_qvalue.GetFingerprint()); EXPECT_EQ(DecayDerivedQValue(point_qvalue).GetFingerprint(), tuple_qvalue.GetFingerprint()); EXPECT_EQ(TypedValue(DecayDerivedQValue(tuple_qvalue)).GetFingerprint(), tuple_qvalue.GetFingerprint()); } } }
2,342
cpp
google/arolla
typed_slot
arolla/qtype/typed_slot.cc
arolla/qtype/typed_slot_test.cc
#ifndef AROLLA_QTYPE_TYPED_SLOT_H_ #define AROLLA_QTYPE_TYPED_SLOT_H_ #include <array> #include <cstddef> #include <cstdint> #include <optional> #include <ostream> #include <string> #include <tuple> #include <typeinfo> #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/memory/frame.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/util/status.h" #include "arolla/util/status_macros_backport.h" namespace arolla { class TypedSlot { public: template <typename T> using Slot = FrameLayout::Slot<T>; TypedSlot(const TypedSlot&) = default; TypedSlot& operator=(const TypedSlot&) = default; static TypedSlot UnsafeFromOffset(QTypePtr type, size_t byte_offset) { return TypedSlot(type, byte_offset); } template <typename T> static TypedSlot FromSlot(Slot<T> slot, QTypePtr type) { DCHECK(type->type_info() == typeid(T)) << "Type mismatch"; return TypedSlot(type, slot.byte_offset()); } template <typename T> static TypedSlot FromSlot(Slot<T> slot) { return TypedSlot(GetQType<T>(), slot.byte_offset()); } template <class T> absl::StatusOr<Slot<T>> ToSlot() const { RETURN_IF_ERROR(VerifyType(typeid(T))); return Slot<T>::UnsafeSlotFromOffset(byte_offset_); } template <class T> Slot<T> UnsafeToSlot() const { DCHECK(GetType()->type_info() == typeid(T)); return Slot<T>::UnsafeSlotFromOffset(byte_offset_); } int64_t SubSlotCount() const { return type_->type_fields().size(); } TypedSlot SubSlot(int64_t index) const { DCHECK_GE(index, 0); DCHECK_LT(index, SubSlotCount()); const auto& field = type_->type_fields()[index]; return TypedSlot(field.GetType(), byte_offset_ + field.byte_offset()); } QTypePtr GetType() const { return type_; } size_t byte_offset() const { return byte_offset_; } void CopyTo(ConstFramePtr source_frame, TypedSlot destination_slot, FramePtr destination_frame) const { DCHECK_EQ(type_, destination_slot.type_) << "Type mismatch"; source_frame.DCheckFieldType(byte_offset_, type_->type_info()); destination_frame.DCheckFieldType(destination_slot.byte_offset_, destination_slot.type_->type_info()); type_->UnsafeCopy( source_frame.GetRawPointer(byte_offset_), destination_frame.GetRawPointer(destination_slot.byte_offset_)); } void Reset(FramePtr frame) const { frame.DCheckFieldType(byte_offset_, type_->type_info()); const auto& layout = type_->type_layout(); void* ptr = frame.GetRawPointer(byte_offset_); layout.DestroyAlloc(ptr); layout.InitializeAlignedAlloc(ptr); } friend bool operator==(const TypedSlot& a, const TypedSlot& b) { return a.type_ == b.type_ && a.byte_offset_ == b.byte_offset_; } friend bool operator!=(const TypedSlot& a, const TypedSlot& b) { return !(a == b); } template <typename H> friend H AbslHashValue(H h, const TypedSlot& a) { return H::combine(std::move(h), a.type_, a.byte_offset_); } friend std::ostream& operator<<(std::ostream& out, const TypedSlot& ts) { return out << "TypedSlot<" << ts.GetType()->name() << ">@" << ts.byte_offset_; } template <typename... Ts> static absl::StatusOr<std::tuple<FrameLayout::Slot<Ts>...>> ToSlots( absl::Span<const TypedSlot> slots) { if (slots.size() != sizeof...(Ts)) { return absl::Status( absl::StatusCode::kInvalidArgument, absl::StrFormat("wrong number of slots: expected %d, got %d", sizeof...(Ts), slots.size())); } return ToSlotsImpl<std::tuple<FrameLayout::Slot<Ts>...>>( slots, std::index_sequence_for<Ts...>{}); } private: TypedSlot(const QType* type, size_t byte_offset) : type_(type), byte_offset_(byte_offset) {} absl::Status VerifyType(const std::type_info& tpe) const; template <typename ResultTuple, std::size_t... is> static absl::StatusOr<ResultTuple> ToSlotsImpl( absl::Span<const TypedSlot> slots, std::index_sequence<is...>) { (void)slots; return LiftStatusUp(slots[is] .ToSlot<typename std::tuple_element_t< is, ResultTuple>::value_type>()...); } QTypePtr type_; size_t byte_offset_; }; template <typename... Slots> std::array<TypedSlot, sizeof...(Slots)> ToTypedSlots(Slots... slots) { return std::array<TypedSlot, sizeof...(Slots)>{TypedSlot::FromSlot(slots)...}; } std::vector<QTypePtr> SlotsToTypes(absl::Span<const TypedSlot> slots); absl::flat_hash_map<std::string, QTypePtr> SlotsToTypes( const absl::flat_hash_map<std::string, TypedSlot>& slots); inline TypedSlot AddSlot(QTypePtr type, FrameLayout::Builder* layout_builder) { return TypedSlot::UnsafeFromOffset( type, layout_builder->AddSubFrame(type->type_layout()).byte_offset()); } std::vector<TypedSlot> AddSlots(absl::Span<const QTypePtr> types, FrameLayout::Builder* layout_builder); std::vector<std::pair<std::string, TypedSlot>> AddNamedSlots( absl::Span<const std::pair<std::string, QTypePtr>> types, FrameLayout::Builder* layout_builder); absl::flat_hash_map<std::string, TypedSlot> AddSlotsMap( const absl::flat_hash_map<std::string, QTypePtr>& types, FrameLayout::Builder* layout_builder); absl::Status RegisterUnsafeSlots(absl::Span<const TypedSlot> slots, FrameLayout::Builder* layout_builder); absl::Status RegisterUnsafeSlotsMap( const absl::flat_hash_map<std::string, TypedSlot>& slots, FrameLayout::Builder* layout_builder); absl::StatusOr<std::vector<std::optional<TypedSlot>>> MaybeFindSlotsAndVerifyTypes( absl::Span<const std::pair<std::string, QTypePtr>> types_in_order, const absl::flat_hash_map<std::string, TypedSlot>& slots); absl::StatusOr<std::vector<TypedSlot>> FindSlotsAndVerifyTypes( absl::Span<const std::pair<std::string, QTypePtr>> types_in_order, const absl::flat_hash_map<std::string, TypedSlot>& slots); absl::Status VerifySlotTypes( const absl::flat_hash_map<std::string, QTypePtr>& types, const absl::flat_hash_map<std::string, TypedSlot>& slots, bool verify_unwanted_slots = true, bool verify_missed_slots = true); } #endif #include "arolla/qtype/typed_slot.h" #include <algorithm> #include <optional> #include <string> #include <typeinfo> #include <utility> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "absl/strings/str_join.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "arolla/memory/frame.h" #include "arolla/qtype/qtype.h" #include "arolla/util/demangle.h" #include "arolla/util/status_macros_backport.h" namespace arolla { namespace { std::string TypeMismatchError(absl::string_view name, QTypePtr expected_type, QTypePtr actual_type) { return absl::StrFormat("%s{expected:%s, actual:%s}", name, expected_type->name(), actual_type->name()); } absl::Status SlotTypesError(std::vector<std::string> missed_slots, std::vector<std::string> type_mismatch, std::vector<std::string> unwanted_slots) { if (missed_slots.empty() && type_mismatch.empty() && unwanted_slots.empty()) { return absl::OkStatus(); } std::string msg = "slots/types match errors:"; if (!missed_slots.empty()) { std::sort(missed_slots.begin(), missed_slots.end()); msg += absl::StrFormat("missed slots: %s;", absl::StrJoin(missed_slots, ",")); } if (!type_mismatch.empty()) { std::sort(type_mismatch.begin(), type_mismatch.end()); msg += absl::StrFormat("slot types mismatch: %s;", absl::StrJoin(type_mismatch, ",")); } if (!unwanted_slots.empty()) { std::sort(unwanted_slots.begin(), unwanted_slots.end()); msg += absl::StrFormat("unwanted slots: %s;", absl::StrJoin(unwanted_slots, ",")); } return absl::FailedPreconditionError(msg); } } std::vector<QTypePtr> SlotsToTypes(absl::Span<const TypedSlot> slots) { std::vector<QTypePtr> types; types.reserve(slots.size()); for (const auto& slot : slots) { types.push_back(slot.GetType()); } return types; } absl::Status TypedSlot::VerifyType(const std::type_info& tpe) const { if (GetType()->type_info() != tpe) { return absl::InvalidArgumentError(absl::StrFormat( "slot type does not match C++ type: expected %s, got %s", TypeName(tpe), TypeName(GetType()->type_info()))); } return absl::OkStatus(); } absl::flat_hash_map<std::string, QTypePtr> SlotsToTypes( const absl::flat_hash_map<std::string, TypedSlot>& slots) { absl::flat_hash_map<std::string, QTypePtr> types; types.reserve(slots.size()); for (const auto& kv : slots) { types[kv.first] = kv.second.GetType(); } return types; } std::vector<TypedSlot> AddSlots(absl::Span<const QTypePtr> types, FrameLayout::Builder* layout_builder) { std::vector<TypedSlot> slots; slots.reserve(types.size()); for (const auto* type : types) { slots.push_back(AddSlot(type, layout_builder)); } return slots; } std::vector<std::pair<std::string, TypedSlot>> AddNamedSlots( absl::Span<const std::pair<std::string, QTypePtr>> types, FrameLayout::Builder* layout_builder) { std::vector<std::pair<std::string, TypedSlot>> slots; slots.reserve(types.size()); for (const auto& [name, type] : types) { slots.emplace_back(name, AddSlot(type, layout_builder)); } return slots; } absl::flat_hash_map<std::string, TypedSlot> AddSlotsMap( const absl::flat_hash_map<std::string, const QType*>& types, FrameLayout::Builder* layout_builder) { absl::flat_hash_map<std::string, TypedSlot> slots; slots.reserve(types.size()); for (const auto& name_type : types) { slots.insert({name_type.first, AddSlot(name_type.second, layout_builder)}); } return slots; } absl::Status RegisterUnsafeSlots(absl::Span<const TypedSlot> slots, FrameLayout::Builder* layout_builder) { for (const auto& slot : slots) { RETURN_IF_ERROR(layout_builder->RegisterUnsafeSlot( slot.byte_offset(), slot.GetType()->type_layout().AllocSize(), slot.GetType()->type_info())); } return absl::OkStatus(); } absl::Status RegisterUnsafeSlotsMap( const absl::flat_hash_map<std::string, TypedSlot>& slots, FrameLayout::Builder* layout_builder) { for (const auto& name_slot : slots) { const auto& slot = name_slot.second; RETURN_IF_ERROR(layout_builder->RegisterUnsafeSlot( slot.byte_offset(), slot.GetType()->type_layout().AllocSize(), slot.GetType()->type_info())); } return absl::OkStatus(); } absl::StatusOr<std::vector<std::optional<TypedSlot>>> MaybeFindSlotsAndVerifyTypes( absl::Span<const std::pair<std::string, QTypePtr>> types_in_order, const absl::flat_hash_map<std::string, TypedSlot>& slots) { std::vector<std::string> type_mismatch; std::vector<std::optional<TypedSlot>> res_slots; res_slots.reserve(types_in_order.size()); for (const auto& [name, type] : types_in_order) { auto it = slots.find(name); if (it == slots.end()) { res_slots.push_back(std::nullopt); continue; } res_slots.push_back({it->second}); if (it->second.GetType() != type) { type_mismatch.push_back( TypeMismatchError(name, type, it->second.GetType())); } } RETURN_IF_ERROR(SlotTypesError({}, std::move(type_mismatch), {})); return {std::move(res_slots)}; } absl::StatusOr<std::vector<TypedSlot>> FindSlotsAndVerifyTypes( absl::Span<const std::pair<std::string, QTypePtr>> types_in_order, const absl::flat_hash_map<std::string, TypedSlot>& slots) { std::vector<std::string> missed_slots; std::vector<std::string> type_mismatch; std::vector<TypedSlot> res_slots; res_slots.reserve(types_in_order.size()); for (const auto& [name, type] : types_in_order) { auto it = slots.find(name); if (it == slots.end()) { missed_slots.push_back(name); continue; } res_slots.push_back({it->second}); if (it->second.GetType() != type) { type_mismatch.push_back( TypeMismatchError(name, type, it->second.GetType())); } } RETURN_IF_ERROR(SlotTypesError(std::move(missed_slots), std::move(type_mismatch), {})); return {std::move(res_slots)}; } absl::Status VerifySlotTypes( const absl::flat_hash_map<std::string, QTypePtr>& types, const absl::flat_hash_map<std::string, TypedSlot>& slots, bool verify_unwanted_slots, bool verify_missed_slots) { std::vector<std::string> missed_slots; std::vector<std::string> type_mismatch; std::vector<std::string> unwanted_slots; for (const auto& [name, type] : types) { auto it = slots.find(name); if (it == slots.end()) { if (verify_missed_slots) { missed_slots.push_back(name); } continue; } if (it->second.GetType() != type) { type_mismatch.push_back( TypeMismatchError(name, type, it->second.GetType())); } } if (verify_unwanted_slots) { for (const auto& [name, _] : slots) { if (!types.contains(name)) { unwanted_slots.push_back(name); } } } return SlotTypesError(std::move(missed_slots), std::move(type_mismatch), std::move(unwanted_slots)); } }
#include "arolla/qtype/typed_slot.h" #include <cstdint> #include <optional> #include <sstream> #include <string> #include <utility> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/container/flat_hash_map.h" #include "absl/status/status.h" #include "arolla/memory/frame.h" #include "arolla/memory/memory_allocation.h" #include "arolla/memory/optional_value.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/util/bytes.h" #include "arolla/util/testing/status_matchers_backport.h" namespace arolla { namespace { using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::StatusIs; using ::testing::ElementsAre; using ::testing::Eq; using ::testing::HasSubstr; using ::testing::MatchesRegex; using ::testing::Pair; using ::testing::StrEq; using ::testing::UnorderedElementsAre; TEST(TypedSlotTest, Copy) { FrameLayout::Builder layout_builder; auto slot = layout_builder.AddSlot<int>(); auto slot2 = layout_builder.AddSlot<float>(); auto typed_slot = TypedSlot::FromSlot(slot); auto typed_slot2 = TypedSlot::FromSlot(slot2); auto typed_slot_copy = typed_slot; EXPECT_EQ(typed_slot.GetType(), typed_slot_copy.GetType()); EXPECT_EQ(typed_slot, typed_slot_copy); typed_slot_copy = typed_slot2; EXPECT_EQ(typed_slot2.GetType(), typed_slot_copy.GetType()); EXPECT_EQ(typed_slot2, typed_slot_copy); } TEST(TypedSlotTest, PrimitiveTypes) { FrameLayout::Builder layout_builder; auto slot = layout_builder.AddSlot<int32_t>(); auto typed_slot = TypedSlot::FromSlot(slot); EXPECT_EQ(typed_slot.GetType(), GetQType<int32_t>()); FrameLayout::Slot<int32_t> new_slot = typed_slot.ToSlot<int32_t>().value(); EXPECT_EQ(slot.byte_offset(), new_slot.byte_offset()); EXPECT_THAT(typed_slot.ToSlot<int64_t>().status(), StatusIs(absl::StatusCode::kInvalidArgument)); } TEST(TypedSlotTest, SlotsToTypes) { FrameLayout::Builder layout_builder; auto slot1 = layout_builder.AddSlot<int32_t>(); auto slot2 = layout_builder.AddSlot<float>(); auto typed_slot1 = TypedSlot::FromSlot(slot1); auto typed_slot2 = TypedSlot::FromSlot(slot2); EXPECT_THAT(SlotsToTypes(std::vector<TypedSlot>{typed_slot1, typed_slot2}), ElementsAre(GetQType<int32_t>(), GetQType<float>())); EXPECT_THAT(SlotsToTypes(absl::flat_hash_map<std::string, TypedSlot>{ {"X", typed_slot1}, {"Y", typed_slot2}}), UnorderedElementsAre(Pair("X", GetQType<int32_t>()), Pair("Y", GetQType<float>()))); } TEST(TypedSlotTest, UnsafeFromOffset) { const QType* i32 = GetQType<int32_t>(); auto typed_slot = TypedSlot::UnsafeFromOffset(i32, 10); EXPECT_EQ(typed_slot.byte_offset(), 10); EXPECT_EQ(typed_slot.GetType(), i32); } TEST(TypedSlotTest, AddSlots) { FrameLayout::Builder layout_builder; const QType* i32 = GetQType<int32_t>(); const QType* i64 = GetQType<int64_t>(); std::vector<TypedSlot> slots = AddSlots({i32, i64}, &layout_builder); ASSERT_EQ(slots.size(), 2); EXPECT_EQ(i32, slots[0].GetType()); EXPECT_EQ(i64, slots[1].GetType()); } TEST(TypedSlotTest, AddNamedSlots) { FrameLayout::Builder layout_builder; const QType* i32 = GetQType<int32_t>(); const QType* i64 = GetQType<int64_t>(); std::vector<std::pair<std::string, TypedSlot>> slots = AddNamedSlots({{"c", i32}, {"b", i64}}, &layout_builder); ASSERT_EQ(slots.size(), 2); EXPECT_EQ("c", slots[0].first); EXPECT_EQ(i32, slots[0].second.GetType()); EXPECT_EQ("b", slots[1].first); EXPECT_EQ(i64, slots[1].second.GetType()); } TEST(TypedSlotTest, AddSlotsMap) { FrameLayout::Builder layout_builder; const QType* i32 = GetQType<int32_t>(); const QType* i64 = GetQType<int64_t>(); absl::flat_hash_map<std::string, TypedSlot> slots = AddSlotsMap({{"a", i32}, {"b", i64}}, &layout_builder); ASSERT_EQ(slots.size(), 2); EXPECT_EQ(i32, slots.at("a").GetType()); EXPECT_EQ(i64, slots.at("b").GetType()); } TEST(TypedSlotTest, RegisterUnsafeSlots) { FrameLayout::Builder layout_builder; layout_builder.AddSlot<int64_t>(); const QType* i32 = GetQType<int32_t>(); const QType* f32 = GetQType<float>(); auto slot_i32 = TypedSlot::UnsafeFromOffset(i32, 0); auto slot_f32 = TypedSlot::UnsafeFromOffset(f32, 4); ASSERT_OK(RegisterUnsafeSlots({slot_i32, slot_f32}, &layout_builder)); #ifndef NDEBUG ASSERT_FALSE(RegisterUnsafeSlots({slot_i32}, &layout_builder).ok()); #endif auto layout = std::move(layout_builder).Build(); layout.HasField(0, typeid(int32_t)); layout.HasField(4, typeid(float)); } TEST(TypedSlotTest, RegisterUnsafeSlotsMap) { FrameLayout::Builder layout_builder; layout_builder.AddSlot<int64_t>(); const QType* i32 = GetQType<int32_t>(); const QType* f32 = GetQType<float>(); auto slot_i32 = TypedSlot::UnsafeFromOffset(i32, 0); auto slot_f32 = TypedSlot::UnsafeFromOffset(f32, 4); ASSERT_OK(RegisterUnsafeSlotsMap({{"a", slot_i32}, {"b", slot_f32}}, &layout_builder)); #ifndef NDEBUG ASSERT_FALSE(RegisterUnsafeSlotsMap({{"a", slot_i32}}, &layout_builder).ok()); #endif auto layout = std::move(layout_builder).Build(); layout.HasField(0, typeid(int32_t)); layout.HasField(4, typeid(float)); } TEST(TypedSlotTest, GetSubslots) { FrameLayout::Builder layout_builder; auto opt_float_slot = layout_builder.AddSlot<OptionalValue<float>>(); auto opt_int32_slot = layout_builder.AddSlot<OptionalValue<int32_t>>(); auto float64_slot = layout_builder.AddSlot<double>(); FrameLayout layout = std::move(layout_builder).Build(); TypedSlot opt_float_tslot = TypedSlot::FromSlot(opt_float_slot); TypedSlot opt_int32_tslot = TypedSlot::FromSlot(opt_int32_slot); TypedSlot float64_tslot = TypedSlot::FromSlot(float64_slot); EXPECT_EQ(opt_float_tslot.SubSlotCount(), 2); EXPECT_EQ(opt_int32_tslot.SubSlotCount(), 2); EXPECT_EQ(float64_tslot.SubSlotCount(), 0); EXPECT_EQ(opt_float_tslot.SubSlot(0), TypedSlot::FromSlot(opt_float_slot.GetSubslot<0>())); EXPECT_EQ(opt_float_tslot.SubSlot(1), TypedSlot::FromSlot(opt_float_slot.GetSubslot<1>())); EXPECT_EQ(opt_int32_tslot.SubSlot(0), TypedSlot::FromSlot(opt_int32_slot.GetSubslot<0>())); EXPECT_EQ(opt_int32_tslot.SubSlot(1), TypedSlot::FromSlot(opt_int32_slot.GetSubslot<1>())); MemoryAllocation alloc_holder(&layout); FramePtr frame = alloc_holder.frame(); frame.Set(opt_float_slot, OptionalValue<float>(1.0)); frame.Set(opt_int32_slot, OptionalValue<int32_t>()); auto float_present_slot = opt_float_tslot.SubSlot(0).ToSlot<bool>().value(); auto int32_present_slot = opt_int32_tslot.SubSlot(0).ToSlot<bool>().value(); EXPECT_EQ(frame.Get(float_present_slot), true); EXPECT_EQ(frame.Get(int32_present_slot), false); auto int32_value_slot = opt_int32_tslot.SubSlot(1).ToSlot<int32_t>().value(); frame.Set(int32_present_slot, true); frame.Set(int32_value_slot, 2); EXPECT_EQ(frame.Get(opt_int32_slot), OptionalValue<int32_t>(2)); } TEST(TypedSlotTest, DebugPrintTypedSlot) { FrameLayout::Builder layout_builder; auto slot1 = layout_builder.AddSlot<int32_t>(); auto slot2 = layout_builder.AddSlot<float>(); auto slot3 = layout_builder.AddSlot<Bytes>(); auto typed_slot1 = TypedSlot::FromSlot(slot1); auto typed_slot2 = TypedSlot::FromSlot(slot2); auto typed_slot3 = TypedSlot::FromSlot(slot3); std::stringstream buffer; buffer << "typed_slot1 is: " << typed_slot1 << ", "; buffer << "typed_slot2 is: " << typed_slot2 << ", "; buffer << "typed_slot3 is: " << typed_slot3 << "."; EXPECT_THAT(buffer.str(), StrEq("typed_slot1 is: TypedSlot<INT32>@0, " "typed_slot2 is: TypedSlot<FLOAT32>@4, " "typed_slot3 is: TypedSlot<BYTES>@8.")); } TEST(TypedSlotTest, ToSlots) { FrameLayout::Builder layout_builder; auto slot1 = layout_builder.AddSlot<int32_t>(); auto slot2 = layout_builder.AddSlot<float>(); ASSERT_OK_AND_ASSIGN( auto slots_tuple, (TypedSlot::ToSlots<int32_t, float>( {TypedSlot::FromSlot(slot1), TypedSlot::FromSlot(slot2)}))); EXPECT_THAT(std::get<0>(slots_tuple).byte_offset(), Eq(slot1.byte_offset())); EXPECT_THAT(std::get<1>(slots_tuple).byte_offset(), Eq(slot2.byte_offset())); EXPECT_THAT(TypedSlot::ToSlots<float>({TypedSlot::FromSlot(slot1)}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("slot type does not match C++ type"))); EXPECT_THAT( (TypedSlot::ToSlots<int32_t, float>({TypedSlot::FromSlot(slot1)})), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("wrong number of slots: expected 2, got 1"))); } TEST(TypedSlotTest, MaybeFindSlotsAndVerifyTypesErrors) { FrameLayout::Builder layout_builder; auto float_slot = layout_builder.AddSlot<float>(); EXPECT_THAT( MaybeFindSlotsAndVerifyTypes({{"a", GetQType<int>()}}, {{"a", TypedSlot::FromSlot(float_slot)}}), StatusIs(absl::StatusCode::kFailedPrecondition, MatchesRegex(".*slot types " "mismatch.*a.*expected:INT32.*actual:FLOAT32.*"))); } TEST(TypedSlotTest, MaybeFindSlotsAndVerifyTypes) { FrameLayout::Builder layout_builder; auto int_slot = layout_builder.AddSlot<int>(); auto float_slot = layout_builder.AddSlot<float>(); EXPECT_THAT( MaybeFindSlotsAndVerifyTypes( {{"a", GetQType<int>()}, {"c", GetQType<float>()}}, {{"b", TypedSlot::FromSlot(float_slot)}, {"a", TypedSlot::FromSlot(int_slot)}}), IsOkAndHolds(ElementsAre(TypedSlot::FromSlot(int_slot), std::nullopt))); } TEST(TypedSlotTest, FindSlotsAndVerifyTypesErrors) { FrameLayout::Builder layout_builder; auto float_slot = layout_builder.AddSlot<float>(); EXPECT_THAT( FindSlotsAndVerifyTypes({{"NAME", GetQType<int>()}}, {{"NAME", TypedSlot::FromSlot(float_slot)}}), StatusIs( absl::StatusCode::kFailedPrecondition, MatchesRegex(".*slot types " "mismatch.*NAME.*expected:INT32.*actual:FLOAT32.*"))); EXPECT_THAT(FindSlotsAndVerifyTypes({{"FAKE", GetQType<int>()}}, {{"b", TypedSlot::FromSlot(float_slot)}}), StatusIs(absl::StatusCode::kFailedPrecondition, MatchesRegex(".*missed slots:.*FAKE.*"))); EXPECT_THAT( FindSlotsAndVerifyTypes( {{"NAME", GetQType<int>()}, {"FAKE", GetQType<int>()}}, {{"NAME", TypedSlot::FromSlot(float_slot)}}), StatusIs( absl::StatusCode::kFailedPrecondition, MatchesRegex(".*missed slots:.*FAKE.*slot types mismatch:.*NAME.*"))); } TEST(TypedSlotTest, FindSlotsAndVerifyTypes) { FrameLayout::Builder layout_builder; auto int_slot = layout_builder.AddSlot<int>(); auto float_slot = layout_builder.AddSlot<float>(); auto int8_slot = layout_builder.AddSlot<int32_t>(); EXPECT_THAT(FindSlotsAndVerifyTypes( {{"c", GetQType<float>()}, {"a", GetQType<int>()}}, {{"c", TypedSlot::FromSlot(float_slot)}, {"b", TypedSlot::FromSlot(int8_slot)}, {"a", TypedSlot::FromSlot(int_slot)}}), IsOkAndHolds(ElementsAre(TypedSlot::FromSlot(float_slot), TypedSlot::FromSlot(int_slot)))); } TEST(TypedSlotTest, VerifySlotTypes) { FrameLayout::Builder layout_builder; auto int_slot = layout_builder.AddSlot<int>(); auto float_slot = layout_builder.AddSlot<float>(); EXPECT_OK(VerifySlotTypes({{"a", GetQType<int>()}, {"c", GetQType<float>()}}, {{"c", TypedSlot::FromSlot(float_slot)}, {"a", TypedSlot::FromSlot(int_slot)}})); EXPECT_OK(VerifySlotTypes({{"a", GetQType<int>()}, {"c", GetQType<float>()}}, {{"c", TypedSlot::FromSlot(float_slot)}}, true, false)); EXPECT_OK(VerifySlotTypes({{"a", GetQType<int>()}}, {{"c", TypedSlot::FromSlot(float_slot)}, {"a", TypedSlot::FromSlot(int_slot)}}, false)); EXPECT_THAT( VerifySlotTypes({{"a", GetQType<int>()}}, {{"a", TypedSlot::FromSlot(float_slot)}}), StatusIs(absl::StatusCode::kFailedPrecondition, MatchesRegex(".*slot types " "mismatch.*a.*expected:INT32.*actual:FLOAT32.*"))); EXPECT_THAT( VerifySlotTypes({{"a", GetQType<int>()}, {"c", GetQType<float>()}}, {{"a", TypedSlot::FromSlot(float_slot)}}), StatusIs(absl::StatusCode::kFailedPrecondition, MatchesRegex(".*missed slots:.*c.*slot types mismatch:.*a.*"))); EXPECT_THAT( VerifySlotTypes({{"d", GetQType<int>()}}, {{"a", TypedSlot::FromSlot(float_slot)}}), StatusIs(absl::StatusCode::kFailedPrecondition, MatchesRegex(".*missed slots:.*d.*unwanted slots:.*a.*"))); } } }
2,343
cpp
google/arolla
simple_qtype
arolla/qtype/simple_qtype.cc
arolla/qtype/simple_qtype_test.cc
#ifndef AROLLA_QTYPE_SIMPLE_TYPE_H_ #define AROLLA_QTYPE_SIMPLE_TYPE_H_ #include <cstddef> #include <cstdint> #include <optional> #include <string> #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/strings/string_view.h" #include "absl/types/span.h" #include "arolla/memory/frame.h" #include "arolla/qtype/named_field_qtype.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/typed_slot.h" #include "arolla/util/fingerprint.h" #include "arolla/util/indestructible.h" #include "arolla/util/meta.h" #include "arolla/util/repr.h" #include "arolla/util/struct_field.h" namespace arolla { class SimpleQType : public QType, public NamedFieldQTypeInterface { public: template <typename CppType> ABSL_ATTRIBUTE_ALWAYS_INLINE SimpleQType( meta::type<CppType>, std::string type_name, const QType* value_qtype = nullptr, std::string qtype_specialization_key = "") : QType(ConstructorArgs{ .name = std::move(type_name), .type_info = typeid(CppType), .type_layout = MakeTypeLayout<CppType>(), .type_fields = GenTypeFields<CppType>(), .value_qtype = value_qtype, .qtype_specialization_key = std::move(qtype_specialization_key), }), field_names_(GenFieldNames<CppType>()) { CHECK_OK(InitNameMap()); if constexpr (std::is_invocable_v<ReprTraits<CppType>, CppType>) { unsafe_repr_token_fn_ = [](const void* source) { return ReprTraits<CppType>()(*static_cast<const CppType*>(source)); }; } unsafe_copy_fn_ = [](const void* source, void* destination) { *static_cast<CppType*>(destination) = *static_cast<const CppType*>(source); }; unsafe_combine_to_fingerprint_hasher_fn_ = [](const void* source, FingerprintHasher* hasher) { hasher->Combine(*static_cast<const CppType*>(source)); }; } protected: ReprToken UnsafeReprToken(const void* source) const override { if (unsafe_repr_token_fn_) { return unsafe_repr_token_fn_(source); } else { return QType::UnsafeReprToken(source); } } private: absl::Status InitNameMap(); absl::Span<const std::string> GetFieldNames() const final; std::optional<int64_t> GetFieldIndexByName( absl::string_view field_name) const final; void UnsafeCopy(const void* source, void* destination) const final { if (source != destination) { return unsafe_copy_fn_(source, destination); } } void UnsafeCombineToFingerprintHasher(const void* source, FingerprintHasher* hasher) const final { return unsafe_combine_to_fingerprint_hasher_fn_(source, hasher); } template <typename CppType> ABSL_ATTRIBUTE_ALWAYS_INLINE static std::vector<std::string> GenFieldNames() { std::vector<std::string> result; result.reserve(StructFieldCount<CppType>()); meta::foreach_tuple_element(GetStructFields<CppType>(), [&](const auto& struct_field) { result.emplace_back(struct_field.field_name); }); return result; } template <typename CppType> ABSL_ATTRIBUTE_ALWAYS_INLINE static std::vector<TypedSlot> GenTypeFields() { std::vector<TypedSlot> result; result.reserve(StructFieldCount<CppType>()); meta::foreach_tuple_element( GetStructFields<CppType>(), [&](const auto& struct_field) { result.push_back(TypedSlot::FromSlot( FrameLayout::Slot< typename std::decay_t<decltype(struct_field)>::field_type>:: UnsafeSlotFromOffset(struct_field.field_offset))); }); return result; } private: using UnsafeReprTokenFn = ReprToken (*)(const void* source); using UnsafeCopyFn = void (*)(const void* source, void* destination); using UnsafeCombineToFingerprintHasherFn = void (*)(const void* source, FingerprintHasher* hasher); using Name2IdMap = absl::flat_hash_map<std::string, size_t>; Name2IdMap name2index_; std::vector<std::string> field_names_; UnsafeReprTokenFn unsafe_repr_token_fn_ = nullptr; UnsafeCopyFn unsafe_copy_fn_ = nullptr; UnsafeCombineToFingerprintHasherFn unsafe_combine_to_fingerprint_hasher_fn_ = nullptr; }; #define AROLLA_DECLARE_SIMPLE_QTYPE(NAME, ...) \ AROLLA_DECLARE_QTYPE(__VA_ARGS__); #define AROLLA_DEFINE_SIMPLE_QTYPE(NAME, ...) \ QTypePtr QTypeTraits<__VA_ARGS__>::type() { \ static const Indestructible<SimpleQType> result(meta::type<__VA_ARGS__>(), \ #NAME); \ return result.get(); \ } } #endif #include "arolla/qtype/simple_qtype.h" #include <cstdint> #include <optional> #include <string> #include "absl/status/status.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" namespace arolla { absl::Status SimpleQType::InitNameMap() { name2index_.reserve(field_names_.size()); for (const auto& field_name : field_names_) { if (bool inserted = name2index_.emplace(field_name, name2index_.size()).second; !inserted) { return absl::FailedPreconditionError(absl::StrCat( "duplicated name field for QType ", name(), ": ", field_name)); } } return absl::OkStatus(); } absl::Span<const std::string> SimpleQType::GetFieldNames() const { return field_names_; } std::optional<int64_t> SimpleQType::GetFieldIndexByName( absl::string_view field_name) const { if (auto it = name2index_.find(field_name); it != name2index_.end()) { return it->second; } return std::nullopt; } }
#include "arolla/qtype/simple_qtype.h" #include <cstdint> #include <optional> #include <string> #include <tuple> #include <utility> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/strings/str_format.h" #include "absl/strings/string_view.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/named_field_qtype.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/util/fingerprint.h" #include "arolla/util/indestructible.h" #include "arolla/util/meta.h" #include "arolla/util/repr.h" #include "arolla/util/struct_field.h" #include "arolla/util/testing/repr_token_eq.h" namespace arolla { namespace { using ::arolla::testing::ReprTokenEq; using ::testing::ElementsAre; using ::testing::IsEmpty; using ::testing::MatchesRegex; struct TypeWithRepr {}; struct TypeWithoutRepr {}; struct FullFeaturedType { int32_t state; }; struct TypeWithNamedFields { float x; double y; constexpr static auto ArollaStructFields() { using CppType = TypeWithNamedFields; return std::tuple{ AROLLA_DECLARE_STRUCT_FIELD(x), AROLLA_DECLARE_STRUCT_FIELD(y), }; } void ArollaFingerprint(FingerprintHasher* hasher) const { CombineStructFields(hasher, *this); } }; } AROLLA_DECLARE_QTYPE(TypeWithRepr); AROLLA_DECLARE_QTYPE(TypeWithoutRepr); AROLLA_DECLARE_QTYPE(FullFeaturedType); AROLLA_DECLARE_QTYPE(TypeWithNamedFields); AROLLA_DECLARE_FINGERPRINT_HASHER_TRAITS(TypeWithRepr); void FingerprintHasherTraits<TypeWithRepr>::operator()( FingerprintHasher*, const TypeWithRepr&) const {} AROLLA_DECLARE_FINGERPRINT_HASHER_TRAITS(TypeWithoutRepr); void FingerprintHasherTraits<TypeWithoutRepr>::operator()( FingerprintHasher*, const TypeWithoutRepr&) const {} AROLLA_DECLARE_FINGERPRINT_HASHER_TRAITS(FullFeaturedType); void FingerprintHasherTraits<FullFeaturedType>::operator()( FingerprintHasher* hasher, const FullFeaturedType& value) const { hasher->Combine(value.state); } AROLLA_DECLARE_REPR(TypeWithRepr); ReprToken ReprTraits<TypeWithRepr>::operator()(const TypeWithRepr&) const { return ReprToken{"type_with_repr", {10, 50}}; } AROLLA_DECLARE_REPR(FullFeaturedType); ReprToken ReprTraits<FullFeaturedType>::operator()( const FullFeaturedType& value) const { return ReprToken{absl::StrFormat("FullFeaturedType{%d}", value.state), {31, 27}}; } AROLLA_DEFINE_SIMPLE_QTYPE(TYPE_WITH_REPR, TypeWithRepr); AROLLA_DEFINE_SIMPLE_QTYPE(TYPE_WITHOUT_REPR, TypeWithoutRepr); AROLLA_DEFINE_SIMPLE_QTYPE(TYPE_WITH_NAMED_FIELDS, TypeWithNamedFields); QTypePtr QTypeTraits<FullFeaturedType>::type() { struct FullFeaturedTypeQType final : SimpleQType { FullFeaturedTypeQType() : SimpleQType( meta::type<FullFeaturedType>(), "FullFeaturedType", GetQType<TypeWithoutRepr>(), "::arolla::FullFeaturedQType") {} absl::string_view UnsafePyQValueSpecializationKey( const void* ) const final { return "::arolla::FullFeaturedQValue"; } }; static const Indestructible<FullFeaturedTypeQType> result; return result.get(); } namespace { TEST(SimpleQType, TypeWithRepr) { TypeWithRepr x; EXPECT_THAT(GetQType<TypeWithRepr>()->UnsafeReprToken(&x), ReprTokenEq("type_with_repr", {10, 50})); } TEST(SimpleQType, TypeWithoutRepr) { TypeWithoutRepr x; const auto repr_result = GetQType<TypeWithoutRepr>()->UnsafeReprToken(&x); EXPECT_THAT(repr_result.str, MatchesRegex("<value of TYPE_WITHOUT_REPR at 0x[0-9a-f]+>")); EXPECT_THAT(repr_result.precedence.left, -1); EXPECT_THAT(repr_result.precedence.right, -1); } TEST(SimpleQType, FullFeaturedQType) { auto qtype = GetQType<FullFeaturedType>(); const FullFeaturedType x{4}; EXPECT_EQ(qtype->value_qtype(), GetQType<TypeWithoutRepr>()); EXPECT_EQ(qtype->qtype_specialization_key(), "::arolla::FullFeaturedQType"); EXPECT_THAT(qtype->UnsafeReprToken(&x), ReprTokenEq("FullFeaturedType{4}", {31, 27})); EXPECT_EQ(qtype->UnsafePyQValueSpecializationKey(&x), "::arolla::FullFeaturedQValue"); FingerprintHasher hx("salt"); FingerprintHasher hy("salt"); const FullFeaturedType y{3}; qtype->UnsafeCombineToFingerprintHasher(&x, &hx); qtype->UnsafeCombineToFingerprintHasher(&y, &hy); EXPECT_NE(std::move(hx).Finish(), std::move(hy).Finish()); } TEST(SimpleQType, TypeWithNames) { QTypePtr qtype = GetQType<TypeWithNamedFields>(); EXPECT_THAT(GetFieldNames(qtype), ElementsAre("x", "y")); EXPECT_EQ(GetFieldIndexByName(qtype, "x"), 0); EXPECT_EQ(GetFieldIndexByName(qtype, "y"), 1); EXPECT_EQ(GetFieldIndexByName(qtype, "z"), std::nullopt); } TEST(SimpleQType, TypeWithNamesErrors) { QTypePtr qtype = GetQType<int>(); EXPECT_THAT(GetFieldNames(qtype), IsEmpty()); EXPECT_EQ(GetFieldIndexByName(qtype, "y"), std::nullopt); EXPECT_EQ(GetFieldIndexByName(qtype, "x"), std::nullopt); } } }
2,344
cpp
google/arolla
unspecified_qtype
arolla/qtype/unspecified_qtype.cc
arolla/qtype/unspecified_qtype_test.cc
#ifndef AROLLA_QTYPE_UNSPECIFIED_QTYPE_H_ #define AROLLA_QTYPE_UNSPECIFIED_QTYPE_H_ #include "arolla/qtype/qtype.h" #include "arolla/qtype/typed_value.h" namespace arolla { QTypePtr GetUnspecifiedQType(); const TypedValue& GetUnspecifiedQValue(); } #endif #include "arolla/qtype/unspecified_qtype.h" #include "absl/strings/string_view.h" #include "arolla/memory/frame.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/typed_value.h" #include "arolla/util/fingerprint.h" #include "arolla/util/indestructible.h" #include "arolla/util/repr.h" namespace arolla { namespace { struct Unspecified {}; class UnspecifiedQType final : public QType { public: UnspecifiedQType() : QType(ConstructorArgs{.name = "UNSPECIFIED", .type_info = typeid(Unspecified), .type_layout = MakeTypeLayout<Unspecified>()}) {} ReprToken UnsafeReprToken(const void* source) const override { return ReprToken{"unspecified"}; } void UnsafeCopy(const void* , void* ) const override {} void UnsafeCombineToFingerprintHasher( const void* , FingerprintHasher* hasher) const override { hasher->Combine(absl::string_view("::arolla::UnspecifiedQValue")); } }; } QTypePtr GetUnspecifiedQType() { static const Indestructible<UnspecifiedQType> result; return result.get(); } const TypedValue& GetUnspecifiedQValue() { static const Indestructible<TypedValue> result( TypedValue::UnsafeFromTypeDefaultConstructed(GetUnspecifiedQType())); return *result; } }
#include "arolla/qtype/unspecified_qtype.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/typed_value.h" #include "arolla/util/init_arolla.h" #include "arolla/util/testing/repr_token_eq.h" namespace arolla { namespace { using ::arolla::testing::ReprTokenEq; class UnspecifiedQTypeTest : public ::testing::Test { void SetUp() override { ASSERT_OK(InitArolla()); } }; TEST_F(UnspecifiedQTypeTest, UnspecifiedQType) { const auto unspecified_qtype = GetUnspecifiedQType(); EXPECT_EQ(unspecified_qtype->name(), "UNSPECIFIED"); EXPECT_EQ(unspecified_qtype->type_layout().AllocSize(), 1); EXPECT_EQ(unspecified_qtype->type_layout().AllocAlignment().value, 1); EXPECT_TRUE(unspecified_qtype->type_fields().empty()); EXPECT_EQ(unspecified_qtype->value_qtype(), nullptr); } TEST_F(UnspecifiedQTypeTest, UnspecifiedQValue) { const auto unspecified_qvalue = GetUnspecifiedQValue(); EXPECT_EQ(unspecified_qvalue.GetType(), GetUnspecifiedQType()); EXPECT_THAT(unspecified_qvalue.GenReprToken(), ReprTokenEq("unspecified")); } } }
2,345
cpp
google/arolla
qtype
arolla/jagged_shape/dense_array/qtype/qtype.cc
arolla/jagged_shape/dense_array/qtype/qtype_test.cc
#ifndef AROLLA_JAGGED_SHAPE_DENSE_ARRAY_QTYPE_QTYPE_H_ #define AROLLA_JAGGED_SHAPE_DENSE_ARRAY_QTYPE_QTYPE_H_ #include "arolla/jagged_shape/dense_array/jagged_shape.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/util/fingerprint.h" #include "arolla/util/repr.h" namespace arolla { AROLLA_DECLARE_QTYPE(JaggedDenseArrayShapePtr); AROLLA_DECLARE_FINGERPRINT_HASHER_TRAITS(JaggedDenseArrayShapePtr); AROLLA_DECLARE_REPR(JaggedDenseArrayShapePtr); } #endif #include "arolla/jagged_shape/dense_array/qtype/qtype.h" #include "arolla/dense_array/edge.h" #include "arolla/dense_array/qtype/types.h" #include "arolla/jagged_shape/dense_array/jagged_shape.h" #include "arolla/jagged_shape/qtype/qtype.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/util/fingerprint.h" #include "arolla/util/indestructible.h" #include "arolla/util/init_arolla.h" #include "arolla/util/meta.h" #include "arolla/util/repr.h" namespace arolla { namespace { class JaggedDenseArrayShapeQType final : public JaggedShapeQType { public: static const JaggedDenseArrayShapeQType* GetInstance() { static Indestructible<JaggedDenseArrayShapeQType> result; return result.get(); } JaggedDenseArrayShapeQType() : JaggedShapeQType(meta::type<JaggedDenseArrayShapePtr>(), "JAGGED_DENSE_ARRAY_SHAPE") {} QTypePtr edge_qtype() const override { return GetQType<DenseArrayEdge>(); }; }; } QTypePtr QTypeTraits<JaggedDenseArrayShapePtr>::type() { return JaggedDenseArrayShapeQType::GetInstance(); } void FingerprintHasherTraits<JaggedDenseArrayShapePtr>::operator()( FingerprintHasher* hasher, const JaggedDenseArrayShapePtr& value) const { hasher->Combine(*value); } ReprToken ReprTraits<JaggedDenseArrayShapePtr>::operator()( const JaggedDenseArrayShapePtr& value) const { return GenReprToken(*value); } AROLLA_REGISTER_ANONYMOUS_INITIALIZER(kHighest, [] { return SetEdgeQTypeToJaggedShapeQType(GetQType<DenseArrayEdge>(), GetQType<JaggedDenseArrayShapePtr>()); }) }
#include "arolla/jagged_shape/dense_array/qtype/qtype.h" #include <cstdint> #include <string> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "arolla/dense_array/dense_array.h" #include "arolla/dense_array/edge.h" #include "arolla/dense_array/qtype/types.h" #include "arolla/jagged_shape/array/jagged_shape.h" #include "arolla/jagged_shape/array/qtype/qtype.h" #include "arolla/jagged_shape/dense_array/jagged_shape.h" #include "arolla/jagged_shape/qtype/qtype.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/typed_value.h" #include "arolla/util/init_arolla.h" #include "arolla/util/testing/repr_token_eq.h" #include "arolla/util/testing/status_matchers_backport.h" namespace arolla { namespace { using ::arolla::testing::ReprTokenEq; using ::arolla::testing::StatusIs; TEST(QTypeTest, TypedValueRepr) { ASSERT_OK_AND_ASSIGN(auto edge, DenseArrayEdge::FromSplitPoints( CreateDenseArray<int64_t>({0, 2}))); ASSERT_OK_AND_ASSIGN(auto shape, JaggedDenseArrayShape::FromEdges({edge})); auto tv = TypedValue::FromValue(shape); EXPECT_THAT(tv.GenReprToken(), ReprTokenEq("JaggedShape(2)")); } TEST(QTypeTest, JaggedDenseArrayShapeQType) { QTypePtr type = GetQType<JaggedDenseArrayShapePtr>(); EXPECT_NE(type, nullptr); EXPECT_EQ(type->name(), "JAGGED_DENSE_ARRAY_SHAPE"); EXPECT_EQ(type->type_info(), typeid(JaggedDenseArrayShapePtr)); EXPECT_EQ(type->value_qtype(), nullptr); EXPECT_TRUE(IsJaggedShapeQType(type)); EXPECT_EQ(type, GetQType<JaggedDenseArrayShapePtr>()); EXPECT_NE(type, GetQType<JaggedArrayShapePtr>()); } TEST(QTypeTest, JaggedDenseArrayShapeFingerprint) { 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 shape2, JaggedDenseArrayShape::FromEdges({edge1, edge2})); auto tv1 = TypedValue::FromValue(shape1); auto tv2 = TypedValue::FromValue(shape2); EXPECT_EQ(tv1.GetFingerprint(), tv2.GetFingerprint()); ASSERT_OK_AND_ASSIGN(auto edge3, DenseArrayEdge::FromSplitPoints( CreateDenseArray<int64_t>({0, 1, 4}))); ASSERT_OK_AND_ASSIGN(auto shape3, JaggedDenseArrayShape::FromEdges({edge1, edge3})); auto tv3 = TypedValue::FromValue(shape3); EXPECT_NE(tv1.GetFingerprint(), tv3.GetFingerprint()); } TEST(QTypeTest, CopyTo) { 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 shape, JaggedDenseArrayShape::FromEdges({edge1, edge2})); auto tv = TypedValue::FromValue(shape); auto tv_copy = TypedValue(tv.AsRef()); EXPECT_EQ(tv.GetFingerprint(), tv_copy.GetFingerprint()); } TEST(QTypeTest, JaggedShapeQTypeFromEdgeQType) { ASSERT_OK(InitArolla()); { ASSERT_OK_AND_ASSIGN(auto shape_qtype, GetJaggedShapeQTypeFromEdgeQType( GetQType<DenseArrayEdge>())); EXPECT_EQ(shape_qtype, GetQType<JaggedDenseArrayShapePtr>()); } { EXPECT_THAT( GetJaggedShapeQTypeFromEdgeQType(GetQType<DenseArrayGroupScalarEdge>()), StatusIs(absl::StatusCode::kInvalidArgument, "DENSE_ARRAY_TO_SCALAR_EDGE key is not registered")); } { EXPECT_THAT( SetEdgeQTypeToJaggedShapeQType(GetQType<DenseArrayEdge>(), GetQType<DenseArrayGroupScalarEdge>()), StatusIs(absl::StatusCode::kInvalidArgument, "DENSE_ARRAY_EDGE key is already registered")); } } TEST(QTypeTest, EdgeQType) { auto type = GetQType<JaggedDenseArrayShapePtr>(); auto shape_qtype = dynamic_cast<const JaggedShapeQType*>(type); EXPECT_EQ(shape_qtype->edge_qtype(), GetQType<DenseArrayEdge>()); } } }
2,346
cpp
google/arolla
optional_qtype
arolla/qtype/optional_qtype.cc
arolla/qtype/optional_qtype_test.cc
#ifndef AROLLA_QTYPE_OPTIONAL_QTYPE_H_ #define AROLLA_QTYPE_OPTIONAL_QTYPE_H_ #include "absl/log/check.h" #include "absl/status/statusor.h" #include "arolla/memory/frame.h" #include "arolla/memory/optional_value.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/util/indestructible.h" #include "arolla/util/meta.h" namespace arolla { template <typename T> QTypePtr GetOptionalQType() { return GetQType<OptionalValue<T>>(); } bool IsOptionalQType(const QType* qtype); absl::StatusOr<QTypePtr> ToOptionalQType(QTypePtr qtype); const QType* DecayOptionalQType(const QType* qtype); absl::StatusOr<FrameLayout::Slot<bool>> GetPresenceSubslotFromOptional( TypedSlot slot); inline FrameLayout::Slot<bool> UnsafePresenceSubslotFromOptional( TypedSlot slot) { DCHECK(IsOptionalQType(slot.GetType())); return slot.SubSlot(0).UnsafeToSlot<bool>(); } template <typename T> FrameLayout::Slot<bool> GetPresenceSubslotFromOptional( FrameLayout::Slot<OptionalValue<T>> slot) { return slot.template GetSubslot<0>(); } absl::StatusOr<TypedSlot> GetValueSubslotFromOptional(TypedSlot slot); inline TypedSlot UnsafeValueSubslotFromOptional(TypedSlot slot) { DCHECK(IsOptionalQType(slot.GetType())); DCHECK_EQ(slot.SubSlotCount(), 2); return slot.SubSlot(1); } inline bool UnsafeIsPresent(TypedRef optional) { DCHECK(IsOptionalQType(optional.GetType())); DCHECK_GE(optional.GetFieldCount(), 1); return optional.GetField(0).UnsafeAs<bool>(); } template <typename T> FrameLayout::Slot<T> GetValueSubslotFromOptional( FrameLayout::Slot<OptionalValue<T>> slot) { return slot.template GetSubslot<1>(); } absl::StatusOr<TypedValue> CreateMissingValue(QTypePtr optional_qtype); void RegisterOptionalQType(QTypePtr optional_qtype); #define AROLLA_DECLARE_OPTIONAL_QTYPE(NAME, ...) \ AROLLA_DECLARE_QTYPE(OptionalValue<__VA_ARGS__>) #define AROLLA_DEFINE_OPTIONAL_QTYPE(NAME, ...) \ QTypePtr QTypeTraits<OptionalValue<__VA_ARGS__>>::type() { \ static const Indestructible<SimpleQType> result( \ meta::type<OptionalValue<__VA_ARGS__>>(), ("OPTIONAL_" #NAME), \ GetQType<__VA_ARGS__>()); \ return result.get(); \ } \ static const int optional_##NAME##_registered = \ (RegisterOptionalQType(GetOptionalQType<__VA_ARGS__>()), 1); } #endif #include "arolla/qtype/optional_qtype.h" #include "absl/base/thread_annotations.h" #include "absl/container/flat_hash_map.h" #include "absl/container/flat_hash_set.h" #include "absl/log/check.h" #include "absl/log/log.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" #include "absl/synchronization/mutex.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_value.h" #include "arolla/util/indestructible.h" #include "arolla/util/unit.h" namespace arolla { namespace { class OptionalQTypeMaps { public: void Register(QTypePtr qtype, QTypePtr optional_qtype) { absl::MutexLock l(&lock_); to_optional_[qtype] = optional_qtype; to_optional_[optional_qtype] = optional_qtype; optional_qtypes_.insert(optional_qtype); } absl::StatusOr<QTypePtr> ToOptionalQType(QTypePtr qtype) { absl::ReaderMutexLock l(&lock_); auto iter = to_optional_.find(qtype); if (iter == to_optional_.end()) { return absl::InvalidArgumentError( absl::StrCat("no optional qtype for ", qtype->name())); } return iter->second; } bool IsOptionalQType(QTypePtr qtype) { absl::ReaderMutexLock l(&lock_); return optional_qtypes_.contains(qtype); } private: absl::Mutex lock_; absl::flat_hash_map<QTypePtr, QTypePtr> to_optional_ ABSL_GUARDED_BY(lock_); absl::flat_hash_set<QTypePtr> optional_qtypes_ ABSL_GUARDED_BY(lock_); }; OptionalQTypeMaps* GetOptionalQTypeMaps() { static Indestructible<OptionalQTypeMaps> instance; return instance.get(); } } void RegisterOptionalQType(QTypePtr optional_qtype) { const auto* value_qtype = optional_qtype->value_qtype(); DCHECK(value_qtype != nullptr); const auto& sub_slots = optional_qtype->type_fields(); DCHECK_GT(sub_slots.size(), 0); DCHECK(sub_slots[0].GetType()->type_info() == typeid(bool)); DCHECK_EQ(sub_slots[0].byte_offset(), 0); if (sub_slots.size() == 1) { DCHECK_EQ(value_qtype, GetQType<Unit>()); } else if (sub_slots.size() == 2) { DCHECK_EQ(sub_slots[1].GetType(), value_qtype); } else { LOG(FATAL) << "Unexpected number of subslots in optional: " << sub_slots.size(); } GetOptionalQTypeMaps()->Register(value_qtype, optional_qtype); } absl::StatusOr<QTypePtr> ToOptionalQType(QTypePtr qtype) { return GetOptionalQTypeMaps()->ToOptionalQType(qtype); } const QType* DecayOptionalQType(const QType* qtype) { return IsOptionalQType(qtype) ? qtype->value_qtype() : qtype; } bool IsOptionalQType(const QType* qtype) { return GetOptionalQTypeMaps()->IsOptionalQType(qtype); } absl::StatusOr<FrameLayout::Slot<bool>> GetPresenceSubslotFromOptional( TypedSlot slot) { if (!IsOptionalQType(slot.GetType())) { return absl::InvalidArgumentError( absl::StrCat("'", slot.GetType()->name(), "' is not optional qtype.")); } if (slot.SubSlotCount() == 0) { return absl::InternalError("optional value has no subslots."); } return slot.SubSlot(0).ToSlot<bool>(); } absl::StatusOr<TypedSlot> GetValueSubslotFromOptional(TypedSlot slot) { if (!IsOptionalQType(slot.GetType())) { return absl::InvalidArgumentError( absl::StrCat("'", slot.GetType()->name(), "' is not optional qtype.")); } if (slot.SubSlotCount() != 2) { return absl::InvalidArgumentError(absl::StrCat( "'", slot.GetType()->name(), "' does not have a value subslot.")); } return slot.SubSlot(1); } absl::StatusOr<TypedValue> CreateMissingValue(QTypePtr optional_qtype) { if (!IsOptionalQType(optional_qtype)) { return absl::InvalidArgumentError(absl::StrFormat( "cannot create a missing value for non-optional qtype `%s`", optional_qtype->name())); } return TypedValue::UnsafeFromTypeDefaultConstructed(optional_qtype); } }
#include "arolla/qtype/optional_qtype.h" #include <cstdint> #include <optional> #include <utility> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "arolla/memory/frame.h" #include "arolla/memory/memory_allocation.h" #include "arolla/memory/optional_value.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/testing/qtype.h" #include "arolla/qtype/typed_ref.h" #include "arolla/qtype/typed_slot.h" #include "arolla/qtype/typed_value.h" #include "arolla/util/testing/status_matchers_backport.h" namespace arolla { namespace { using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::StatusIs; using ::arolla::testing::TypedValueWith; using ::testing::FloatEq; using ::testing::IsFalse; using ::testing::IsTrue; template <typename T> using Slot = FrameLayout::Slot<T>; TEST(OptionalQType, SplitOptionalUnitSlot) { FrameLayout::Builder layout_builder; auto slot = layout_builder.AddSlot<OptionalUnit>(); auto layout = std::move(layout_builder).Build(); Slot<bool> presence_slot1 = GetPresenceSubslotFromOptional(slot); auto typed_slot = TypedSlot::FromSlot(slot); ASSERT_OK_AND_ASSIGN(Slot<bool> presence_slot2, GetPresenceSubslotFromOptional(typed_slot)); Slot<bool> presence_slot3 = UnsafePresenceSubslotFromOptional(typed_slot); EXPECT_THAT(GetValueSubslotFromOptional(typed_slot), StatusIs(absl::StatusCode::kInvalidArgument)); MemoryAllocation alloc(&layout); FramePtr frame = alloc.frame(); frame.Set(slot, kPresent); EXPECT_TRUE(frame.Get(presence_slot1)); EXPECT_TRUE(frame.Get(presence_slot2)); EXPECT_TRUE(frame.Get(presence_slot3)); frame.Set(slot, kMissing); EXPECT_FALSE(frame.Get(presence_slot1)); EXPECT_FALSE(frame.Get(presence_slot2)); EXPECT_FALSE(frame.Get(presence_slot3)); } TEST(OptionalQType, SplitOptionalFloatSlot) { FrameLayout::Builder layout_builder; auto slot = layout_builder.AddSlot<OptionalValue<float>>(); auto layout = std::move(layout_builder).Build(); Slot<bool> presence_slot1 = GetPresenceSubslotFromOptional(slot); Slot<float> value_slot1 = GetValueSubslotFromOptional(slot); auto typed_slot = TypedSlot::FromSlot(slot); ASSERT_OK_AND_ASSIGN(Slot<bool> presence_slot2, GetPresenceSubslotFromOptional(typed_slot)); ASSERT_OK_AND_ASSIGN(TypedSlot typed_value_slot2, GetValueSubslotFromOptional(typed_slot)); ASSERT_OK_AND_ASSIGN(Slot<float> value_slot2, typed_value_slot2.ToSlot<float>()); Slot<bool> presence_slot3 = UnsafePresenceSubslotFromOptional(typed_slot); Slot<float> value_slot3 = UnsafeValueSubslotFromOptional(typed_slot).UnsafeToSlot<float>(); MemoryAllocation alloc(&layout); FramePtr frame = alloc.frame(); frame.Set(slot, 17.5f); EXPECT_TRUE(frame.Get(presence_slot1)); EXPECT_TRUE(frame.Get(presence_slot2)); EXPECT_TRUE(frame.Get(presence_slot3)); EXPECT_THAT(frame.Get(value_slot1), FloatEq(17.5f)); EXPECT_THAT(frame.Get(value_slot2), FloatEq(17.5f)); EXPECT_THAT(frame.Get(value_slot3), FloatEq(17.5f)); frame.Set(slot, std::nullopt); EXPECT_FALSE(frame.Get(presence_slot1)); EXPECT_FALSE(frame.Get(presence_slot2)); EXPECT_FALSE(frame.Get(presence_slot3)); } TEST(OptionalQType, CreateMissingValue) { EXPECT_THAT( CreateMissingValue(GetOptionalQType<int64_t>()), IsOkAndHolds(TypedValueWith<OptionalValue<int64_t>>(std::nullopt))); EXPECT_THAT( CreateMissingValue(GetQType<int64_t>()), StatusIs(absl::StatusCode::kInvalidArgument, "cannot create a missing value for non-optional qtype `INT64`")); } TEST(OptionalQType, UnsafeIsPresent) { EXPECT_THAT(UnsafeIsPresent(TypedRef::FromValue(kPresent)), IsTrue()); EXPECT_THAT(UnsafeIsPresent(TypedRef::FromValue(kMissing)), IsFalse()); OptionalValue<float> present_float = 1; EXPECT_THAT(UnsafeIsPresent(TypedRef::FromValue(present_float)), IsTrue()); OptionalValue<float> missing_float = std::nullopt; EXPECT_THAT(UnsafeIsPresent(TypedRef::FromValue(missing_float)), IsFalse()); ASSERT_OK_AND_ASSIGN(TypedValue typed_missing_float, CreateMissingValue(GetOptionalQType<float>())); EXPECT_THAT(UnsafeIsPresent(typed_missing_float.AsRef()), IsFalse()); } } }
2,347
cpp
google/arolla
common_qtype
arolla/qtype/standard_type_properties/common_qtype.cc
arolla/qtype/standard_type_properties/common_qtype_test.cc
#ifndef AROLLA_QTYPE_STANDARD_TYPE_PROPERTIES_COMMON_QTYPE_H_ #define AROLLA_QTYPE_STANDARD_TYPE_PROPERTIES_COMMON_QTYPE_H_ #include "absl/types/span.h" #include "arolla/qtype/qtype.h" namespace arolla { const QType* CommonQType(const QType* lhs_qtype, const QType* rhs_qtype, bool enable_broadcasting); const QType* CommonQType(absl::Span<const QType* const> qtypes, bool enable_broadcasting); bool CanCastImplicitly(const QType* from_qtype, const QType* to_qtype, bool enable_broadcasting); const QType* BroadcastQType(absl::Span<QType const* const> target_qtypes, const QType* qtype); } #endif #include "arolla/qtype/standard_type_properties/common_qtype.h" #include <algorithm> #include <array> #include <cstdint> #include "absl/algorithm/container.h" #include "absl/types/span.h" #include "arolla/qtype/array_like/array_like_qtype.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/shape_qtype.h" #include "arolla/qtype/standard_type_properties/properties.h" #include "arolla/util/status_macros_backport.h" namespace arolla { namespace { const QType* CommonScalarQType(const QType* lhs_qtype, const QType* rhs_qtype) { if (lhs_qtype == rhs_qtype) { return lhs_qtype; } { static const std::array integral_qtypes = {GetQType<int64_t>(), GetQType<int32_t>()}; auto lhs_it = absl::c_find(integral_qtypes, lhs_qtype); auto rhs_it = absl::c_find(integral_qtypes, rhs_qtype); if (lhs_it != integral_qtypes.end() && rhs_it != integral_qtypes.end()) { return *std::min(lhs_it, rhs_it); } } { static const std::array floating_point_qtypes = { GetQType<double>(), GetQType<float>(), GetWeakFloatQType(), }; auto lhs_it = absl::c_find(floating_point_qtypes, lhs_qtype); auto rhs_it = absl::c_find(floating_point_qtypes, rhs_qtype); if (lhs_it != floating_point_qtypes.end() && rhs_it != floating_point_qtypes.end()) { return *std::min(lhs_it, rhs_it); } } return nullptr; } const ShapeQType* CommonShapeQType(const ShapeQType* lhs_qtype, const ShapeQType* rhs_qtype, bool enable_broadcasting) { if (lhs_qtype == rhs_qtype) { return rhs_qtype; } if (!enable_broadcasting && (IsArrayLikeShapeQType(lhs_qtype) || IsArrayLikeShapeQType(rhs_qtype))) { return nullptr; } if (lhs_qtype == GetQType<ScalarShape>()) { return rhs_qtype; } if (rhs_qtype == GetQType<ScalarShape>()) { return lhs_qtype; } if (lhs_qtype == GetQType<OptionalScalarShape>()) { return rhs_qtype; } if (rhs_qtype == GetQType<OptionalScalarShape>()) { return lhs_qtype; } return nullptr; } } const QType* CommonQType(const QType* lhs_qtype, const QType* rhs_qtype, bool enable_broadcasting) { if (lhs_qtype == nullptr || rhs_qtype == nullptr) { return nullptr; } if (lhs_qtype == rhs_qtype) { return lhs_qtype; } ASSIGN_OR_RETURN(auto lhs_scalar_qtype, GetScalarQType(lhs_qtype), nullptr); ASSIGN_OR_RETURN(auto rhs_scalar_qtype, GetScalarQType(rhs_qtype), nullptr); const auto* scalar_qtype = CommonScalarQType(lhs_scalar_qtype, rhs_scalar_qtype); if (!scalar_qtype) { return nullptr; } ASSIGN_OR_RETURN(auto lhs_shape_qtype, GetShapeQType(lhs_qtype), nullptr); ASSIGN_OR_RETURN(auto rhs_shape_qtype, GetShapeQType(rhs_qtype), nullptr); const auto* shape_qtype = CommonShapeQType(lhs_shape_qtype, rhs_shape_qtype, enable_broadcasting); if (!shape_qtype) { return nullptr; } return shape_qtype->WithValueQType(scalar_qtype).value_or(nullptr); } bool CanCastImplicitly(QTypePtr from_qtype, QTypePtr to_qtype, bool enable_broadcasting) { return to_qtype != nullptr && CommonQType(from_qtype, to_qtype, enable_broadcasting) == to_qtype; } const QType* CommonQType(absl::Span<const QType* const> qtypes, bool enable_broadcasting) { if (qtypes.empty()) { return nullptr; } const QType* result = qtypes[0]; for (const QType* qtype : qtypes.subspan(1)) { result = CommonQType(result, qtype, enable_broadcasting); } return result; } const QType* BroadcastQType(absl::Span<QType const* const> target_qtypes, const QType* qtype) { if (absl::c_any_of(target_qtypes, [](auto* qtype) { return qtype == nullptr; }) || qtype == nullptr) { return nullptr; } const ShapeQType* shape_qtype = GetShapeQType(qtype).value_or(nullptr); for (const auto* target_qtype : target_qtypes) { shape_qtype = CommonShapeQType( shape_qtype, GetShapeQType(target_qtype).value_or(nullptr), true); } if (shape_qtype == nullptr) { return nullptr; } ASSIGN_OR_RETURN(auto scalar_qtype, GetScalarQType(qtype), nullptr); return shape_qtype->WithValueQType(scalar_qtype).value_or(nullptr); } }
#include "arolla/qtype/standard_type_properties/common_qtype.h" #include <algorithm> #include <cstdint> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "arolla/array/qtype/types.h" #include "arolla/dense_array/qtype/types.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/optional_qtype.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/tuple_qtype.h" #include "arolla/qtype/weak_qtype.h" #include "arolla/util/bytes.h" #include "arolla/util/meta.h" #include "arolla/util/unit.h" namespace arolla { namespace { using ::testing::IsFalse; using ::testing::IsNull; using ::testing::IsTrue; const QType* ReferenceCommonQType(const QType* arg0, const QType* arg1, bool enable_broadcasting_) { if (arg0 == arg1) { return arg0; } const QType* result = nullptr; const auto gen_result = [&](QTypePtr a0, QTypePtr a1, QTypePtr r) { if (a0 == arg0 && a1 == arg1) { result = r; } }; const auto gen_results = [&](QTypePtr a0, QTypePtr a1, QTypePtr r) { ASSERT_OK_AND_ASSIGN(auto a0_optional, ToOptionalQType(a0)); ASSERT_OK_AND_ASSIGN(auto a0_dense_array, GetDenseArrayQTypeByValueQType(a0)); ASSERT_OK_AND_ASSIGN(auto a0_array, GetArrayQTypeByValueQType(a0)); ASSERT_OK_AND_ASSIGN(auto a1_optional, ToOptionalQType(a1)); ASSERT_OK_AND_ASSIGN(auto a1_dense_array, GetDenseArrayQTypeByValueQType(a1)); ASSERT_OK_AND_ASSIGN(auto a1_array, GetArrayQTypeByValueQType(a1)); ASSERT_OK_AND_ASSIGN(auto r_optional, ToOptionalQType(r)); ASSERT_OK_AND_ASSIGN(auto r_dense_array, GetDenseArrayQTypeByValueQType(r)); ASSERT_OK_AND_ASSIGN(auto r_array, GetArrayQTypeByValueQType(r)); gen_result(a0, a1, r); gen_result(a0, a1_optional, r_optional); gen_result(a0_optional, a1_optional, r_optional); gen_result(a0_optional, a1, r_optional); gen_result(a0_dense_array, a1_dense_array, r_dense_array); gen_result(a0_array, a1_array, r_array); if (enable_broadcasting_) { gen_result(a0, a1_dense_array, r_dense_array); gen_result(a0_optional, a1_dense_array, r_dense_array); gen_result(a0, a1_array, r_array); gen_result(a0_optional, a1_array, r_array); gen_result(a0_dense_array, a1_optional, r_dense_array); gen_result(a0_dense_array, a1, r_dense_array); gen_result(a0_array, a1_optional, r_array); gen_result(a0_array, a1, r_array); } }; meta::foreach_type<ScalarTypes>([&](auto meta_type) { auto x = GetQType<typename decltype(meta_type)::type>(); gen_results(x, x, x); }); static const auto integral_qtypes = { GetQType<int32_t>(), GetQType<int64_t>(), }; for (auto it = integral_qtypes.begin(); result == nullptr && it != integral_qtypes.end(); ++it) { for (auto jt = integral_qtypes.begin(); result == nullptr && jt != integral_qtypes.end(); ++jt) { gen_results(*it, *jt, *std::max(it, jt)); } } static const auto floating_qtypes = { GetWeakFloatQType(), GetQType<float>(), GetQType<double>(), }; for (auto it = floating_qtypes.begin(); result == nullptr && it != floating_qtypes.end(); ++it) { for (auto jt = floating_qtypes.begin(); result == nullptr && jt != floating_qtypes.end(); ++jt) { gen_results(*it, *jt, *std::max(it, jt)); } } return result; } class CommonQTypeMultipleParametersTests : public ::testing::TestWithParam<bool> { protected: CommonQTypeMultipleParametersTests() { meta::foreach_type<ScalarTypes>([&](auto meta_type) { using T = typename decltype(meta_type)::type; known_qtypes_.push_back(GetQType<T>()); known_qtypes_.push_back(GetOptionalQType<T>()); known_qtypes_.push_back(GetDenseArrayQType<T>()); known_qtypes_.push_back(GetArrayQType<T>()); }); known_qtypes_.push_back(nullptr); known_qtypes_.push_back(GetDenseArrayWeakFloatQType()); known_qtypes_.push_back(GetArrayWeakFloatQType()); known_qtypes_.push_back(MakeTupleQType({})); enable_broadcasting_ = GetParam(); } std::vector<const QType*> known_qtypes_; bool enable_broadcasting_; }; TEST_P(CommonQTypeMultipleParametersTests, VsReferenceImplementation) { for (auto lhs : known_qtypes_) { for (auto rhs : known_qtypes_) { EXPECT_EQ(CommonQType(lhs, rhs, enable_broadcasting_), ReferenceCommonQType(lhs, rhs, enable_broadcasting_)) << "lhs=" << (lhs ? lhs->name() : "nullptr") << ", rhs=" << (rhs ? rhs->name() : "nullptr"); } } } TEST_P(CommonQTypeMultipleParametersTests, SemiLatticeProperties) { for (auto arg_0 : known_qtypes_) { EXPECT_EQ( CommonQType(arg_0, arg_0, enable_broadcasting_), arg_0); for (auto arg_1 : known_qtypes_) { EXPECT_EQ( CommonQType(arg_0, arg_1, enable_broadcasting_), CommonQType(arg_1, arg_0, enable_broadcasting_)); for (auto arg_2 : known_qtypes_) { EXPECT_EQ( CommonQType(CommonQType(arg_0, arg_1, enable_broadcasting_), arg_2, enable_broadcasting_), CommonQType(arg_0, CommonQType(arg_1, arg_2, enable_broadcasting_), enable_broadcasting_)); } } } } INSTANTIATE_TEST_SUITE_P(CommonQTypeTests, CommonQTypeMultipleParametersTests, ::testing::Values(false, true)); class CommonQTypeTest : public ::testing::Test { protected: static void SetUpTestCase() { meta::foreach_type<ScalarTypes>([&](auto meta_type) { GetQType<typename decltype(meta_type)::type>(); GetOptionalQType<typename decltype(meta_type)::type>(); GetDenseArrayQType<typename decltype(meta_type)::type>(); }); } }; TEST_F(CommonQTypeTest, OnSpans) { EXPECT_THAT(CommonQType({}, true), IsNull()); EXPECT_EQ(CommonQType({GetQType<int64_t>()}, true), GetQType<int64_t>()); EXPECT_THAT( CommonQType({nullptr, GetQType<int64_t>()}, true), IsNull()); EXPECT_THAT( CommonQType({GetQType<int64_t>(), nullptr}, true), IsNull()); EXPECT_EQ(CommonQType({GetQType<int64_t>(), GetOptionalQType<int32_t>()}, true), GetOptionalQType<int64_t>()); EXPECT_EQ(CommonQType({GetQType<int64_t>(), GetOptionalQType<int32_t>(), GetDenseArrayQType<int32_t>()}, true), GetDenseArrayQType<int64_t>()); EXPECT_EQ( CommonQType(GetDenseArrayQType<int32_t>(), GetOptionalQType<int64_t>(), true), GetDenseArrayQType<int64_t>()); EXPECT_THAT(CommonQType({GetQType<int64_t>(), GetOptionalQType<int32_t>(), GetDenseArrayQType<int32_t>()}, false), IsNull()); } TEST_F(CommonQTypeTest, WeakQType) { EXPECT_EQ(CommonQType(GetQType<double>(), GetWeakFloatQType(), true), GetQType<double>()); EXPECT_EQ(CommonQType(GetQType<float>(), GetWeakFloatQType(), true), GetQType<float>()); EXPECT_EQ(CommonQType(GetWeakFloatQType(), GetWeakFloatQType(), true), GetWeakFloatQType()); EXPECT_EQ(CommonQType(GetOptionalWeakFloatQType(), GetWeakFloatQType(), true), GetOptionalWeakFloatQType()); EXPECT_EQ(CommonQType(GetOptionalWeakFloatQType(), GetQType<double>(), true), GetOptionalQType<double>()); EXPECT_EQ(CommonQType(GetOptionalWeakFloatQType(), GetQType<float>(), true), GetOptionalQType<float>()); EXPECT_EQ(CommonQType(GetWeakFloatQType(), GetOptionalQType<double>(), true), GetOptionalQType<double>()); EXPECT_EQ(CommonQType(GetWeakFloatQType(), GetOptionalQType<float>(), true), GetOptionalQType<float>()); EXPECT_EQ(CommonQType(GetOptionalWeakFloatQType(), GetOptionalQType<double>(), true), GetOptionalQType<double>()); EXPECT_EQ(CommonQType(GetOptionalWeakFloatQType(), GetOptionalQType<float>(), true), GetOptionalQType<float>()); EXPECT_EQ(CommonQType(GetWeakFloatQType(), GetArrayQType<double>(), true), GetArrayQType<double>()); EXPECT_EQ(CommonQType(GetWeakFloatQType(), GetArrayQType<float>(), true), GetArrayQType<float>()); EXPECT_EQ(CommonQType(GetOptionalWeakFloatQType(), GetArrayQType<double>(), true), GetArrayQType<double>()); EXPECT_EQ(CommonQType(GetOptionalWeakFloatQType(), GetArrayQType<float>(), true), GetArrayQType<float>()); } class CanCastImplicitlyTest : public ::testing::Test { protected: static void SetUpTestCase() { meta::foreach_type<ScalarTypes>([&](auto meta_type) { GetQType<typename decltype(meta_type)::type>(); GetOptionalQType<typename decltype(meta_type)::type>(); GetDenseArrayQType<typename decltype(meta_type)::type>(); }); } }; TEST_F(CanCastImplicitlyTest, OnScalars) { EXPECT_THAT(CanCastImplicitly(GetQType<int32_t>(), GetQType<int64_t>(), false), IsTrue()); EXPECT_THAT(CanCastImplicitly(GetQType<float>(), GetQType<double>(), false), IsTrue()); EXPECT_THAT(CanCastImplicitly(GetQType<float>(), GetOptionalQType<float>(), false), IsTrue()); EXPECT_THAT(CanCastImplicitly(GetQType<float>(), GetOptionalQType<double>(), false), IsTrue()); EXPECT_THAT(CanCastImplicitly(GetQType<int64_t>(), GetQType<int32_t>(), false), IsFalse()); EXPECT_THAT(CanCastImplicitly(GetQType<int32_t>(), GetQType<float>(), false), IsFalse()); EXPECT_THAT(CanCastImplicitly(GetQType<int32_t>(), GetQType<uint64_t>(), false), IsFalse()); EXPECT_THAT(CanCastImplicitly(GetQType<int32_t>(), nullptr, false), IsFalse()); EXPECT_THAT(CanCastImplicitly(nullptr, GetQType<int32_t>(), false), IsFalse()); EXPECT_THAT(CanCastImplicitly(nullptr, nullptr, false), IsFalse()); } TEST_F(CanCastImplicitlyTest, WithBroadcasting) { EXPECT_THAT( CanCastImplicitly(GetQType<int32_t>(), GetDenseArrayQType<int32_t>(), false), IsFalse()); EXPECT_THAT(CanCastImplicitly(GetOptionalQType<int32_t>(), GetDenseArrayQType<int32_t>(), false), IsFalse()); EXPECT_THAT( CanCastImplicitly(GetQType<int32_t>(), GetDenseArrayQType<int32_t>(), true), IsTrue()); EXPECT_THAT(CanCastImplicitly(GetOptionalQType<int32_t>(), GetDenseArrayQType<int32_t>(), true), IsTrue()); } TEST_F(CanCastImplicitlyTest, WeakQType) { EXPECT_THAT(CanCastImplicitly(GetQType<float>(), GetWeakFloatQType(), false), IsFalse()); EXPECT_THAT(CanCastImplicitly(GetQType<double>(), GetWeakFloatQType(), false), IsFalse()); EXPECT_THAT( CanCastImplicitly(GetQType<int32_t>(), GetWeakFloatQType(), false), IsFalse()); EXPECT_THAT(CanCastImplicitly(GetWeakFloatQType(), GetQType<float>(), false), IsTrue()); EXPECT_THAT(CanCastImplicitly(GetWeakFloatQType(), GetQType<double>(), false), IsTrue()); EXPECT_THAT( CanCastImplicitly(GetWeakFloatQType(), GetQType<int32_t>(), false), IsFalse()); EXPECT_THAT( CanCastImplicitly(GetWeakFloatQType(), GetOptionalQType<float>(), false), IsTrue()); EXPECT_THAT(CanCastImplicitly(GetOptionalWeakFloatQType(), GetOptionalQType<double>(), false), IsTrue()); EXPECT_THAT(CanCastImplicitly(GetWeakFloatQType(), GetArrayWeakFloatQType(), false), IsFalse()); EXPECT_THAT(CanCastImplicitly(GetWeakFloatQType(), GetArrayWeakFloatQType(), true), IsTrue()); EXPECT_THAT( CanCastImplicitly(GetOptionalWeakFloatQType(), GetArrayWeakFloatQType(), true), IsTrue()); EXPECT_THAT( CanCastImplicitly(GetWeakFloatQType(), GetDenseArrayQType<float>(), true), IsTrue()); EXPECT_THAT( CanCastImplicitly(GetWeakFloatQType(), GetDenseArrayQType<double>(), true), IsTrue()); } class BroadcastQTypeTests : public ::testing::Test { protected: static void SetUpTestCase() { meta::foreach_type<ScalarTypes>([&](auto meta_type) { using T = typename decltype(meta_type)::type; GetQType<T>(); GetOptionalQType<T>(); GetDenseArrayQType<T>(); GetArrayQType<T>(); }); GetDenseArrayWeakFloatQType(); GetArrayWeakFloatQType(); } }; TEST_F(BroadcastQTypeTests, Empty) { ASSERT_THAT(BroadcastQType({}, nullptr), IsNull()); } TEST_F(BroadcastQTypeTests, SingleScalarType) { ASSERT_EQ(BroadcastQType({}, GetQType<int32_t>()), GetQType<int32_t>()); } TEST_F(BroadcastQTypeTests, NullHandling) { ASSERT_THAT(BroadcastQType({nullptr}, GetQType<int32_t>()), IsNull()); ASSERT_THAT(BroadcastQType({GetQType<int32_t>()}, nullptr), IsNull()); ASSERT_THAT( BroadcastQType({GetQType<int32_t>(), nullptr}, GetQType<int32_t>()), IsNull()); } TEST_F(BroadcastQTypeTests, ScalarAndOptional) { ASSERT_EQ(BroadcastQType({GetOptionalQType<int32_t>()}, GetQType<int64_t>()), GetOptionalQType<int64_t>()); ASSERT_EQ(BroadcastQType({GetQType<int64_t>()}, GetOptionalQType<int32_t>()), GetOptionalQType<int32_t>()); } TEST_F(BroadcastQTypeTests, ArrayAndDenseArray) { EXPECT_THAT( BroadcastQType({GetArrayQType<float>()}, GetDenseArrayQType<float>()), IsNull()); EXPECT_THAT( BroadcastQType({GetArrayQType<float>(), GetDenseArrayQType<float>()}, GetQType<float>()), IsNull()); } TEST_F(BroadcastQTypeTests, Basic) { ASSERT_EQ( BroadcastQType({GetOptionalQType<float>(), GetDenseArrayQType<Bytes>()}, GetQType<int32_t>()), GetDenseArrayQType<int32_t>()); } TEST_F(BroadcastQTypeTests, WeakFloat) { ASSERT_EQ(BroadcastQType({GetDenseArrayQType<Unit>()}, GetWeakFloatQType()), GetDenseArrayWeakFloatQType()); ASSERT_EQ( BroadcastQType({GetDenseArrayQType<Unit>()}, GetOptionalWeakFloatQType()), GetDenseArrayWeakFloatQType()); ASSERT_EQ(BroadcastQType({GetArrayQType<Unit>()}, GetWeakFloatQType()), GetArrayWeakFloatQType()); ASSERT_EQ( BroadcastQType({GetArrayQType<Unit>()}, GetOptionalWeakFloatQType()), GetArrayWeakFloatQType()); } } }
2,348
cpp
google/arolla
properties
arolla/qtype/standard_type_properties/properties.cc
arolla/qtype/standard_type_properties/properties_test.cc
#ifndef AROLLA_QTYPE_STANDARD_TYPE_PROPERTIES_PROPERTIES_H_ #define AROLLA_QTYPE_STANDARD_TYPE_PROPERTIES_PROPERTIES_H_ #include "absl/status/statusor.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/shape_qtype.h" namespace arolla { absl::StatusOr<QTypePtr> GetScalarQType(QTypePtr qtype); absl::StatusOr<const ShapeQType*> GetShapeQType(QTypePtr qtype); QTypePtr DecayContainerQType(QTypePtr qtype); absl::StatusOr<QTypePtr> WithScalarQType(QTypePtr qtype, QTypePtr new_scalar_qtype); absl::StatusOr<QTypePtr> GetPresenceQType(QTypePtr qtype); bool IsOptionalLikeQType(const QType* qtype); absl::StatusOr<QTypePtr> ToOptionalLikeQType(QTypePtr qtype); } #endif #include "arolla/qtype/standard_type_properties/properties.h" #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "arolla/qtype/array_like/array_like_qtype.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/optional_qtype.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/shape_qtype.h" #include "arolla/util/status_macros_backport.h" namespace arolla { absl::StatusOr<QTypePtr> GetScalarQType(QTypePtr qtype) { DCHECK(qtype); if (IsScalarQType(qtype)) { return qtype; } if (qtype->value_qtype() != nullptr) { return qtype->value_qtype(); } return absl::InvalidArgumentError(absl::StrFormat( "there is no corresponding scalar type for %s", qtype->name())); } absl::StatusOr<const ShapeQType*> GetShapeQType(QTypePtr qtype) { DCHECK(qtype); if (IsScalarQType(qtype)) { return static_cast<const ShapeQType*>(GetQType<ScalarShape>()); } if (IsOptionalQType(qtype)) { return static_cast<const ShapeQType*>(GetQType<OptionalScalarShape>()); } if (auto* array_qtype = dynamic_cast<const ArrayLikeQType*>(qtype)) { return array_qtype->shape_qtype(); } return absl::InvalidArgumentError( absl::StrFormat("no shape type for %s", qtype->name())); } QTypePtr DecayContainerQType(QTypePtr qtype) { DCHECK(qtype); if (qtype->value_qtype() != nullptr) { return qtype->value_qtype(); } return qtype; } absl::StatusOr<QTypePtr> WithScalarQType(QTypePtr qtype, QTypePtr new_scalar_qtype) { DCHECK(qtype); DCHECK(new_scalar_qtype); if (!IsScalarQType(new_scalar_qtype)) { return absl::InvalidArgumentError(absl::StrFormat( "unable to replace scalar type in %s with a non-scalar type %s", qtype->name(), new_scalar_qtype->name())); } if (auto shape_qtype = GetShapeQType(qtype); shape_qtype.ok()) { return (**shape_qtype).WithValueQType(new_scalar_qtype); } return absl::InvalidArgumentError( absl::StrFormat("unable to replace scalar type in %s", qtype->name())); } absl::StatusOr<QTypePtr> GetPresenceQType(QTypePtr qtype) { DCHECK(qtype); if (auto shape_qtype = GetShapeQType(qtype); shape_qtype.ok()) { return (**shape_qtype).presence_qtype(); } return absl::InvalidArgumentError( absl::StrFormat("no type to represent presence in %s", qtype->name())); } bool IsOptionalLikeQType(const QType* qtype) { return IsOptionalQType(qtype) || IsArrayLikeQType(qtype); } absl::StatusOr<QTypePtr> ToOptionalLikeQType(QTypePtr qtype) { DCHECK(qtype); if (IsOptionalLikeQType(qtype)) { return qtype; } if (IsScalarQType(qtype)) { return ToOptionalQType(qtype); } if (auto* array_qtype = dynamic_cast<const ArrayLikeQType*>(qtype)) { ASSIGN_OR_RETURN(auto optional_qtype, ToOptionalQType(array_qtype->value_qtype())); return array_qtype->WithValueQType(optional_qtype); } return absl::InvalidArgumentError( absl::StrFormat("no optional-like qtype for %s", qtype->name())); } }
#include "arolla/qtype/standard_type_properties/properties.h" #include <cstdint> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.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/qtype/base_types.h" #include "arolla/qtype/optional_qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/shape_qtype.h" #include "arolla/qtype/tuple_qtype.h" #include "arolla/util/testing/status_matchers_backport.h" #include "arolla/util/unit.h" namespace arolla { namespace { using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::StatusIs; using ::testing::MatchesRegex; TEST(TypeProperties, GetScalarQType) { EXPECT_THAT(GetScalarQType(GetQType<int64_t>()), IsOkAndHolds(GetQType<int64_t>())); EXPECT_THAT(GetScalarQType(GetOptionalQType<int64_t>()), IsOkAndHolds(GetQType<int64_t>())); EXPECT_THAT(GetScalarQType(GetDenseArrayQType<int64_t>()), IsOkAndHolds(GetQType<int64_t>())); EXPECT_THAT(GetScalarQType(GetDenseArrayWeakFloatQType()), IsOkAndHolds(GetWeakFloatQType())); EXPECT_THAT(GetScalarQType(GetArrayWeakFloatQType()), IsOkAndHolds(GetWeakFloatQType())); EXPECT_THAT( GetScalarQType(MakeTupleQType({GetQType<int64_t>()})), StatusIs(absl::StatusCode::kInvalidArgument, MatchesRegex("there is no corresponding scalar type for .*"))); } TEST(TypeProperties, GetShapeQType) { EXPECT_THAT(GetShapeQType(GetQType<int64_t>()), IsOkAndHolds(GetQType<ScalarShape>())); EXPECT_THAT(GetShapeQType(GetOptionalQType<int64_t>()), IsOkAndHolds(GetQType<OptionalScalarShape>())); EXPECT_THAT(GetShapeQType(GetDenseArrayQType<int64_t>()), IsOkAndHolds(GetQType<DenseArrayShape>())); EXPECT_THAT(GetShapeQType(GetDenseArrayWeakFloatQType()), IsOkAndHolds(GetQType<DenseArrayShape>())); EXPECT_THAT(GetShapeQType(GetArrayWeakFloatQType()), IsOkAndHolds(GetQType<ArrayShape>())); EXPECT_THAT(GetShapeQType(MakeTupleQType({GetQType<int64_t>()})), StatusIs(absl::StatusCode::kInvalidArgument, MatchesRegex("no shape type for .*"))); } TEST(TypeProperties, WithScalarQType) { EXPECT_THAT(WithScalarQType(GetQType<int64_t>(), GetQType<float>()), IsOkAndHolds(GetQType<float>())); EXPECT_THAT(WithScalarQType(GetOptionalQType<int64_t>(), GetQType<float>()), IsOkAndHolds(GetOptionalQType<float>())); EXPECT_THAT(WithScalarQType(GetDenseArrayQType<int64_t>(), GetQType<float>()), IsOkAndHolds(GetDenseArrayQType<float>())); EXPECT_THAT( WithScalarQType(GetDenseArrayQType<int64_t>(), GetWeakFloatQType()), IsOkAndHolds(GetDenseArrayWeakFloatQType())); EXPECT_THAT(WithScalarQType(GetArrayQType<int64_t>(), GetWeakFloatQType()), IsOkAndHolds(GetArrayWeakFloatQType())); EXPECT_THAT(WithScalarQType(MakeTupleQType({GetQType<int64_t>()}), GetOptionalQType<float>()), StatusIs(absl::StatusCode::kInvalidArgument, MatchesRegex("unable to replace scalar type in .* with " "a non-scalar type .*"))); EXPECT_THAT( WithScalarQType(MakeTupleQType({GetQType<int64_t>()}), GetQType<float>()), StatusIs(absl::StatusCode::kInvalidArgument, MatchesRegex("unable to replace scalar type in .*"))); } TEST(TypeProperties, GetPresenceQType) { EXPECT_THAT(GetPresenceQType(GetQType<int64_t>()), IsOkAndHolds(GetQType<Unit>())); EXPECT_THAT(GetPresenceQType(GetOptionalQType<int64_t>()), IsOkAndHolds(GetQType<OptionalUnit>())); EXPECT_THAT(GetPresenceQType(GetDenseArrayQType<int64_t>()), IsOkAndHolds(GetDenseArrayQType<Unit>())); EXPECT_THAT(GetPresenceQType(GetDenseArrayWeakFloatQType()), IsOkAndHolds(GetDenseArrayQType<Unit>())); EXPECT_THAT(GetPresenceQType(GetArrayWeakFloatQType()), IsOkAndHolds(GetArrayQType<Unit>())); EXPECT_THAT(GetPresenceQType(MakeTupleQType({GetQType<int64_t>()})), StatusIs(absl::StatusCode::kInvalidArgument, MatchesRegex("no type to represent presence in .*"))); } TEST(TypeProperties, IsOptionalLikeQType) { EXPECT_FALSE(IsOptionalLikeQType(GetQType<int64_t>())); EXPECT_TRUE(IsOptionalLikeQType(GetOptionalQType<int64_t>())); EXPECT_TRUE(IsOptionalLikeQType(GetDenseArrayQType<int64_t>())); EXPECT_TRUE(IsOptionalLikeQType(GetDenseArrayWeakFloatQType())); EXPECT_TRUE(IsOptionalLikeQType(GetArrayWeakFloatQType())); } TEST(TypeProperties, ToOptionalLikeQType) { EXPECT_THAT(ToOptionalLikeQType(GetQType<int64_t>()), IsOkAndHolds(GetOptionalQType<int64_t>())); EXPECT_THAT(ToOptionalLikeQType(GetOptionalQType<int64_t>()), IsOkAndHolds(GetOptionalQType<int64_t>())); EXPECT_THAT(ToOptionalLikeQType(GetDenseArrayQType<int64_t>()), IsOkAndHolds(GetDenseArrayQType<int64_t>())); EXPECT_THAT(ToOptionalLikeQType(GetDenseArrayWeakFloatQType()), IsOkAndHolds(GetDenseArrayWeakFloatQType())); EXPECT_THAT(ToOptionalLikeQType(GetArrayWeakFloatQType()), IsOkAndHolds(GetArrayWeakFloatQType())); } } }
2,349
cpp
google/arolla
frame_iter
arolla/qtype/array_like/frame_iter.cc
arolla/qtype/array_like/frame_iter_test.cc
#ifndef AROLLA_QTYPE_ARRAY_LIKE_FRAME_ITER_H_ #define AROLLA_QTYPE_ARRAY_LIKE_FRAME_ITER_H_ #include <algorithm> #include <cstddef> #include <cstdint> #include <functional> #include <memory> #include <optional> #include <vector> #include "absl/log/check.h" #include "absl/status/statusor.h" #include "absl/synchronization/barrier.h" #include "absl/types/span.h" #include "arolla/memory/frame.h" #include "arolla/memory/raw_buffer_factory.h" #include "arolla/qtype/array_like/array_like_qtype.h" #include "arolla/qtype/typed_ref.h" #include "arolla/qtype/typed_slot.h" #include "arolla/util/threading.h" namespace arolla { class FrameIterator { public: FrameIterator(const FrameIterator&) = delete; FrameIterator(FrameIterator&&) = default; ~FrameIterator(); struct Options { static constexpr Options Default() { return {}; } std::optional<int64_t> row_count; int64_t frame_buffer_count = 64; RawBufferFactory* buffer_factory = nullptr; }; static absl::StatusOr<FrameIterator> Create( absl::Span<const TypedRef> input_arrays, absl::Span<const TypedSlot> input_scalar_slots, absl::Span<const TypedSlot> output_array_slots, absl::Span<const TypedSlot> output_scalar_slots, const FrameLayout* scalar_layout, Options options = Options::Default()); template <class Fn> void CustomFrameInitialization(Fn&& fn) { for (auto& frame : frames_) fn(frame); } int64_t row_count() const { return row_count_; } template <typename Fn> void ForEachFrame(Fn&& fn) { for (int64_t offset = 0; offset < row_count_; offset += frames_.size()) { int64_t count = std::min<int64_t>(frames_.size(), row_count_ - offset); PreloadFrames(count); for (int64_t i = 0; i < count; ++i) { fn(frames_[i]); } SaveOutputsOfProcessedFrames(count); } } template <typename Fn> void ForEachFrame(Fn&& fn, ThreadingInterface& threading, int thread_count) { DCHECK_GE(thread_count, 1); const int frames_per_worker = (frames_.size() + thread_count - 1) / thread_count; auto barrier1 = std::make_unique<absl::Barrier>(thread_count); auto barrier2 = std::make_unique<absl::Barrier>(thread_count); auto BarrierSync = [thread_count](std::unique_ptr<absl::Barrier>& b) { if (b->Block()) { b = std::make_unique<absl::Barrier>(thread_count); } }; auto worker_fn = [&](int worker_id) { for (int64_t offset = 0; offset < row_count_; offset += frames_.size()) { int64_t count = std::min<int64_t>(frames_.size(), row_count_ - offset); if (worker_id == 0) { PreloadFrames(count); } BarrierSync(barrier1); for (int64_t i = worker_id * frames_per_worker; i < std::min<int64_t>(count, (worker_id + 1) * frames_per_worker); ++i) { fn(frames_[i]); } BarrierSync(barrier2); if (worker_id == 0) { SaveOutputsOfProcessedFrames(count); } } }; threading.WithThreading([&] { std::vector<std::function<void()>> join_fns; join_fns.reserve(thread_count - 1); for (int i = 1; i < thread_count; ++i) { join_fns.push_back( threading.StartThread([&worker_fn, i] { worker_fn(i); })); } worker_fn(0); for (auto& join : join_fns) join(); }); } absl::Status StoreOutput(FramePtr output_frame); private: void* GetAllocByIndex(size_t index) { return buffer_.data() + index * dense_scalar_layout_size_; } void PreloadFrames(size_t frames_count); void SaveOutputsOfProcessedFrames(size_t frames_count); FrameIterator( std::vector<std::unique_ptr<BatchToFramesCopier>>&& input_copiers, std::vector<std::unique_ptr<BatchFromFramesCopier>>&& output_copiers, size_t row_count, size_t frame_buffer_count, const FrameLayout* scalar_layout); int64_t row_count_; std::vector<std::unique_ptr<BatchToFramesCopier>> input_copiers_; std::vector<std::unique_ptr<BatchFromFramesCopier>> output_copiers_; std::vector<FramePtr> frames_; std::vector<ConstFramePtr> const_frames_; std::vector<char> buffer_; const FrameLayout* scalar_layout_; size_t dense_scalar_layout_size_; }; } #endif #include "arolla/qtype/array_like/frame_iter.h" #include <algorithm> #include <cstddef> #include <cstdint> #include <memory> #include <optional> #include <utility> #include <vector> #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/types/span.h" #include "arolla/memory/frame.h" #include "arolla/memory/raw_buffer_factory.h" #include "arolla/qtype/array_like/array_like_qtype.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/typed_ref.h" #include "arolla/util/status_macros_backport.h" namespace arolla { namespace { absl::StatusOr<std::vector<std::unique_ptr<BatchToFramesCopier>>> CreateInputCopiers(absl::Span<const TypedRef> input_arrays, absl::Span<const TypedSlot> input_scalar_slots) { if (input_arrays.size() != input_scalar_slots.size()) { return absl::InvalidArgumentError( absl::StrFormat("size of input_arrays and input_scalar_slots should be " "the same: %d vs %d", input_arrays.size(), input_scalar_slots.size())); } absl::flat_hash_map<QTypePtr, std::unique_ptr<BatchToFramesCopier>> input_copiers; for (size_t i = 0; i < input_arrays.size(); ++i) { QTypePtr array_type = input_arrays[i].GetType(); if (!input_copiers.contains(array_type)) { ASSIGN_OR_RETURN(input_copiers[array_type], CreateBatchToFramesCopier(array_type)); } RETURN_IF_ERROR(input_copiers[array_type]->AddMapping( input_arrays[i], input_scalar_slots[i])); } std::vector<std::unique_ptr<BatchToFramesCopier>> input_copiers_vector; for (auto& [_, v] : input_copiers) input_copiers_vector.push_back(std::move(v)); return input_copiers_vector; } absl::StatusOr<std::vector<std::unique_ptr<BatchFromFramesCopier>>> CreateOutputCopiers(absl::Span<const TypedSlot> output_array_slots, absl::Span<const TypedSlot> output_scalar_slots, RawBufferFactory* buffer_factory) { if (output_array_slots.size() != output_scalar_slots.size()) { return absl::InvalidArgumentError(absl::StrFormat( "size of output_array_slots and output_scalar_slots should be " "the same: %d vs %d", output_array_slots.size(), output_scalar_slots.size())); } absl::flat_hash_map<QTypePtr, std::unique_ptr<BatchFromFramesCopier>> output_copiers; for (size_t i = 0; i < output_array_slots.size(); ++i) { QTypePtr array_type = output_array_slots[i].GetType(); if (!output_copiers.contains(array_type)) { ASSIGN_OR_RETURN(output_copiers[array_type], CreateBatchFromFramesCopier(array_type, buffer_factory)); } RETURN_IF_ERROR(output_copiers[array_type]->AddMapping( output_scalar_slots[i], output_array_slots[i])); } std::vector<std::unique_ptr<BatchFromFramesCopier>> output_copiers_vector; for (auto& [_, v] : output_copiers) output_copiers_vector.push_back(std::move(v)); return output_copiers_vector; } } absl::StatusOr<FrameIterator> FrameIterator::Create( absl::Span<const TypedRef> input_arrays, absl::Span<const TypedSlot> input_scalar_slots, absl::Span<const TypedSlot> output_array_slots, absl::Span<const TypedSlot> output_scalar_slots, const FrameLayout* scalar_layout, FrameIterator::Options options) { ASSIGN_OR_RETURN( std::vector<std::unique_ptr<BatchToFramesCopier>> input_copiers, CreateInputCopiers(input_arrays, input_scalar_slots)); RawBufferFactory* buf_factory = options.buffer_factory; if (!buf_factory) buf_factory = GetHeapBufferFactory(); ASSIGN_OR_RETURN( std::vector<std::unique_ptr<BatchFromFramesCopier>> output_copiers, CreateOutputCopiers(output_array_slots, output_scalar_slots, buf_factory)); std::optional<int64_t> row_count = std::nullopt; for (const auto& copier : input_copiers) { if (!copier->row_count() || (row_count && *row_count != *copier->row_count())) { return absl::InvalidArgumentError( absl::StrFormat("input arrays have different sizes: %d vs %d", *row_count, *copier->row_count())); } row_count = copier->row_count(); } if (!row_count.has_value()) { if (!options.row_count.has_value()) { return absl::InvalidArgumentError( "options.row_count can not be missed if there is no input arrays"); } row_count = options.row_count; } else if (options.row_count.has_value() && *options.row_count != *row_count) { return absl::InvalidArgumentError( absl::StrFormat("sizes of input arrays don't correspond " "to options.row_count: %d vs %d", *row_count, *options.row_count)); } return FrameIterator(std::move(input_copiers), std::move(output_copiers), *row_count, options.frame_buffer_count, scalar_layout); } FrameIterator::FrameIterator( std::vector<std::unique_ptr<BatchToFramesCopier>>&& input_copiers, std::vector<std::unique_ptr<BatchFromFramesCopier>>&& output_copiers, size_t row_count, size_t frame_buffer_count, const FrameLayout* scalar_layout) : row_count_(row_count), input_copiers_(std::move(input_copiers)), output_copiers_(std::move(output_copiers)), scalar_layout_(scalar_layout) { frame_buffer_count = std::min(row_count, frame_buffer_count); dense_scalar_layout_size_ = (scalar_layout_->AllocSize() + 7) & ~7; buffer_.resize(dense_scalar_layout_size_ * frame_buffer_count); for (size_t i = 0; i < frame_buffer_count; ++i) { void* alloc_ptr = GetAllocByIndex(i); scalar_layout->InitializeAlignedAlloc(alloc_ptr); frames_.emplace_back(alloc_ptr, scalar_layout); const_frames_.emplace_back(alloc_ptr, scalar_layout); } for (auto& copier : input_copiers_) copier->Start(); for (auto& copier : output_copiers_) copier->Start(row_count); } FrameIterator::~FrameIterator() { for (size_t i = 0; i < frames_.size(); ++i) { scalar_layout_->DestroyAlloc(GetAllocByIndex(i)); } } absl::Status FrameIterator::StoreOutput(FramePtr output_frame) { for (std::unique_ptr<BatchFromFramesCopier>& copier : output_copiers_) { RETURN_IF_ERROR(copier->Finalize(output_frame)); } return absl::OkStatus(); } void FrameIterator::PreloadFrames(size_t frames_count) { for (auto& copier : input_copiers_) { copier->CopyNextBatch({frames_.data(), frames_count}); } } void FrameIterator::SaveOutputsOfProcessedFrames(size_t frames_count) { for (auto& copier : output_copiers_) { absl::Status status = copier->CopyNextBatch({const_frames_.data(), frames_count}); DCHECK_OK(status); } } }
#include "arolla/qtype/array_like/frame_iter.h" #include <cstdint> #include <optional> #include <utility> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "arolla/dense_array/dense_array.h" #include "arolla/dense_array/qtype/types.h" #include "arolla/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" #include "arolla/util/testing/status_matchers_backport.h" #include "arolla/util/threading.h" namespace arolla { namespace { using ::arolla::testing::StatusIs; using ::testing::ElementsAre; using ::testing::HasSubstr; using ::testing::Test; TEST(FrameIterator, Iterate) { FrameLayout::Builder scalar_bldr; auto scalar_f_slot1 = scalar_bldr.AddSlot<OptionalValue<float>>(); auto scalar_i_slot1 = scalar_bldr.AddSlot<OptionalValue<int64_t>>(); auto scalar_i_slot2 = scalar_bldr.AddSlot<OptionalValue<int64_t>>(); auto scalar_f_slot2 = scalar_bldr.AddSlot<OptionalValue<float>>(); auto scalar_layout = std::move(scalar_bldr).Build(); std::vector<TypedSlot> scalar_slots = { TypedSlot::FromSlot(scalar_f_slot1), TypedSlot::FromSlot(scalar_i_slot1), TypedSlot::FromSlot(scalar_i_slot2), TypedSlot::FromSlot(scalar_f_slot2)}; DenseArray<float> arr_f1 = CreateDenseArray<float>({1.5, std::nullopt, 2.5, 3.5}); DenseArray<int64_t> arr_i1 = CreateDenseArray<int64_t>({3, 4, 5, 6}); DenseArray<int64_t> arr_i2 = CreateDenseArray<int64_t>({2, std::nullopt, 0, std::nullopt}); DenseArray<float> arr_f2 = CreateDenseArray<float>({3.2, 2.2, std::nullopt, 1.2}); FrameLayout::Builder vector_bldr; auto arr_output_f1 = vector_bldr.AddSlot<DenseArray<float>>(); auto arr_output_i1 = vector_bldr.AddSlot<DenseArray<int64_t>>(); auto arr_output_i2 = vector_bldr.AddSlot<DenseArray<int64_t>>(); auto arr_output_f2 = vector_bldr.AddSlot<DenseArray<float>>(); auto output_vector_layout = std::move(vector_bldr).Build(); std::vector<TypedRef> input_refs = { TypedRef::FromValue(arr_f1), TypedRef::FromValue(arr_i1), TypedRef::FromValue(arr_i2), TypedRef::FromValue(arr_f2)}; std::vector<TypedSlot> output_slots = { TypedSlot::FromSlot(arr_output_f1), TypedSlot::FromSlot(arr_output_i1), TypedSlot::FromSlot(arr_output_i2), TypedSlot::FromSlot(arr_output_f2)}; auto scalar_processing_fn = [&](FramePtr frame) { OptionalValue<float> f1 = frame.Get(scalar_f_slot1); OptionalValue<float> f2 = frame.Get(scalar_f_slot2); if (f1.present) frame.Set(scalar_f_slot1, f1.value + 1.0); if (f2.present) frame.Set(scalar_f_slot2, f2.value + 2.0); OptionalValue<int64_t> i1 = frame.Get(scalar_i_slot1); OptionalValue<int64_t> i2 = frame.Get(scalar_i_slot2); if (i1.present) frame.Set(scalar_i_slot1, i1.value + 3); if (i2.present) frame.Set(scalar_i_slot2, i2.value + 4); }; auto check_output_fn = [&](FrameIterator& frame_iterator) { MemoryAllocation alloc(&output_vector_layout); FramePtr output_frame = alloc.frame(); EXPECT_OK(frame_iterator.StoreOutput(output_frame)); EXPECT_THAT(output_frame.Get(arr_output_f1), ElementsAre(2.5, std::nullopt, 3.5, 4.5)); EXPECT_THAT(output_frame.Get(arr_output_f2), ElementsAre(5.2, 4.2, std::nullopt, 3.2)); EXPECT_THAT(output_frame.Get(arr_output_i1), ElementsAre(6, 7, 8, 9)); EXPECT_THAT(output_frame.Get(arr_output_i2), ElementsAre(6, std::nullopt, 4, std::nullopt)); }; { ASSERT_OK_AND_ASSIGN( auto frame_iterator, FrameIterator::Create(input_refs, scalar_slots, output_slots, scalar_slots, &scalar_layout, {.frame_buffer_count = 2})); frame_iterator.ForEachFrame(scalar_processing_fn); check_output_fn(frame_iterator); } StdThreading threading(4); for (int threads = 1; threads <= 4; ++threads) { ASSERT_OK_AND_ASSIGN( auto frame_iterator, FrameIterator::Create(input_refs, scalar_slots, output_slots, scalar_slots, &scalar_layout, {.frame_buffer_count = 3})); frame_iterator.ForEachFrame(scalar_processing_fn, threading, threads); check_output_fn(frame_iterator); } } TEST(FrameIterator, EmptyArrays) { FrameLayout::Builder scalar_bldr; auto scalar_slot = scalar_bldr.AddSlot<OptionalValue<float>>(); auto scalar_layout = std::move(scalar_bldr).Build(); std::vector<TypedSlot> scalar_slots = {TypedSlot::FromSlot(scalar_slot)}; FrameLayout::Builder arrays_layout_bldr; auto arr_output = arrays_layout_bldr.AddSlot<DenseArray<float>>(); auto output_arrays_layout = std::move(arrays_layout_bldr).Build(); DenseArray<float> arr; std::vector<TypedRef> input_refs = {TypedRef::FromValue(arr)}; std::vector<TypedSlot> output_slots = {TypedSlot::FromSlot(arr_output)}; auto scalar_processing_fn = [&](FramePtr frame) { ADD_FAILURE(); }; ASSERT_OK_AND_ASSIGN(auto frame_iterator, FrameIterator::Create( input_refs, scalar_slots, output_slots, scalar_slots, &scalar_layout, {.frame_buffer_count = 2})); frame_iterator.ForEachFrame(scalar_processing_fn); MemoryAllocation alloc(&output_arrays_layout); FramePtr output_frame = alloc.frame(); EXPECT_OK(frame_iterator.StoreOutput(output_frame)); EXPECT_EQ(output_frame.Get(arr_output).size(), 0); } TEST(FrameIterator, EmptyInputAndOutput) { FrameLayout::Builder scalar_bldr; auto scalar_layout = std::move(scalar_bldr).Build(); { auto frame_iterator_or_status = FrameIterator::Create({}, {}, {}, {}, &scalar_layout); EXPECT_THAT( frame_iterator_or_status, StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("options.row_count can not be missed if there " "is no input arrays"))); } { ASSERT_OK_AND_ASSIGN(auto frame_iterator, FrameIterator::Create({}, {}, {}, {}, &scalar_layout, {.row_count = 4})); EXPECT_EQ(frame_iterator.row_count(), 4); } } TEST(FrameIterator, IncorrectInputType) { FrameLayout::Builder scalar_bldr; auto scalar_slot = scalar_bldr.AddSlot<float>(); auto scalar_layout = std::move(scalar_bldr).Build(); std::vector<TypedSlot> scalar_slots = {TypedSlot::FromSlot(scalar_slot)}; DenseArray<int64_t> arr = CreateDenseArray<int64_t>({1, std::nullopt, 2, 3}); auto frame_iterator_or_status = FrameIterator::Create( {TypedRef::FromValue(arr)}, scalar_slots, {}, {}, &scalar_layout); EXPECT_THAT(frame_iterator_or_status, StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("slot type does not match"))); } TEST(FrameIterator, IncorrectOutputType) { FrameLayout::Builder vector_bldr; auto vector_slot = vector_bldr.AddSlot<DenseArray<float>>(); auto vector_layout = std::move(vector_bldr).Build(); FrameLayout::Builder scalar_bldr; auto scalar_slot = scalar_bldr.AddSlot<int64_t>(); auto scalar_layout = std::move(scalar_bldr).Build(); auto frame_iterator_or_status = FrameIterator::Create({}, {}, {TypedSlot::FromSlot(vector_slot)}, {TypedSlot::FromSlot(scalar_slot)}, &scalar_layout); EXPECT_THAT(frame_iterator_or_status, StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("slot type does not match"))); } TEST(FrameIterator, WrongSize) { FrameLayout::Builder scalar_bldr; auto scalar_f_slot1 = scalar_bldr.AddSlot<OptionalValue<float>>(); auto scalar_i_slot1 = scalar_bldr.AddSlot<OptionalValue<int64_t>>(); auto scalar_layout = std::move(scalar_bldr).Build(); std::vector<TypedSlot> scalar_slots = {TypedSlot::FromSlot(scalar_f_slot1), TypedSlot::FromSlot(scalar_i_slot1)}; DenseArray<float> arr_f1 = CreateDenseArray<float>({1.5, std::nullopt, 2.5, 3.5}); DenseArray<int64_t> arr_i1 = CreateDenseArray<int64_t>({3, 4, 5}); auto frame_iterator_or_status = FrameIterator::Create( {TypedRef::FromValue(arr_f1), TypedRef::FromValue(arr_i1)}, scalar_slots, {}, {}, &scalar_layout); EXPECT_THAT(frame_iterator_or_status, StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("input arrays have different sizes"))); } } }
2,350
cpp
google/arolla
regex
arolla/qtype/strings/regex.cc
arolla/qtype/strings/regex_test.cc
#ifndef AROLLA_QTYPE_STRINGS_REGEX_H_ #define AROLLA_QTYPE_STRINGS_REGEX_H_ #include <memory> #include <ostream> #include <utility> #include "absl/log/check.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/optional_qtype.h" #include "arolla/qtype/simple_qtype.h" #include "arolla/util/fingerprint.h" #include "re2/re2.h" namespace arolla { class Regex { public: Regex() {} static absl::StatusOr<Regex> FromPattern(absl::string_view pattern); bool has_value() const { return impl_ != nullptr; } const RE2& value() const { return has_value() ? *impl_ : default_value(); } private: static const RE2& default_value(); explicit Regex(std::shared_ptr<RE2> impl) : impl_(std::move(impl)) { DCHECK(impl_->ok()); } std::shared_ptr<const RE2> impl_; }; std::ostream& operator<<(std::ostream& stream, const Regex& regex); AROLLA_DECLARE_FINGERPRINT_HASHER_TRAITS(Regex); AROLLA_DECLARE_SIMPLE_QTYPE(REGEX, Regex); AROLLA_DECLARE_OPTIONAL_QTYPE(REGEX, Regex); } #endif #include "arolla/qtype/strings/regex.h" #include <memory> #include <ostream> #include <utility> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "absl/strings/string_view.h" #include "arolla/qtype/optional_qtype.h" #include "arolla/qtype/simple_qtype.h" #include "arolla/util/fingerprint.h" #include "re2/re2.h" namespace arolla { absl::StatusOr<Regex> Regex::FromPattern(absl::string_view pattern) { auto value = std::make_shared<RE2>(pattern, RE2::Quiet); if (value->ok()) { return Regex(std::move(value)); } else { return absl::InvalidArgumentError(absl::StrFormat( "Invalid regular expression: \"%s\"; %s.", pattern, value->error())); } } const RE2& Regex::default_value() { static LazyRE2 value = {".^"}; return *value; } std::ostream& operator<<(std::ostream& stream, const Regex& regex) { if (regex.has_value()) { return stream << "Regex{\"" << regex.value().pattern() << "\"}"; } else { return stream << "Regex{}"; } } void FingerprintHasherTraits<Regex>::operator()(FingerprintHasher* hasher, const Regex& value) const { hasher->Combine(value.value().pattern()); } AROLLA_DEFINE_SIMPLE_QTYPE(REGEX, Regex); AROLLA_DEFINE_OPTIONAL_QTYPE(REGEX, Regex); }
#include "arolla/qtype/strings/regex.h" #include <sstream> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "arolla/util/testing/status_matchers_backport.h" #include "re2/re2.h" using ::arolla::testing::StatusIs; using ::testing::HasSubstr; namespace arolla { namespace { TEST(Regex, DefaultConstructor) { Regex regex; EXPECT_FALSE(regex.has_value()); std::stringstream out; out << regex; EXPECT_EQ(out.str(), "Regex{}"); EXPECT_FALSE(RE2::PartialMatch("some string", regex.value())); } TEST(Regex, FromPattern) { ASSERT_OK_AND_ASSIGN(auto regex, Regex::FromPattern("\\d+ bottles of beer")); EXPECT_TRUE(regex.has_value()); EXPECT_TRUE(RE2::FullMatch("100 bottles of beer", regex.value())); std::stringstream out; out << regex; EXPECT_EQ(out.str(), "Regex{\"\\d+ bottles of beer\"}"); EXPECT_THAT(Regex::FromPattern("ab\\αcd"), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("Invalid regular expression: \"ab\\αcd\"; "))); } } }
2,351
cpp
google/arolla
dict_types
arolla/qtype/dict/dict_types.cc
arolla/qtype/dict/dict_types_test.cc
#ifndef AROLLA_QTYPE_DICT_DICT_TYPES_H_ #define AROLLA_QTYPE_DICT_DICT_TYPES_H_ #include <cstdint> #include <initializer_list> #include <memory> #include <sstream> #include <type_traits> #include <utility> #include <vector> #include "absl/base/attributes.h" #include "absl/container/flat_hash_map.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "arolla/memory/optional_value.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/simple_qtype.h" #include "arolla/util/bytes.h" #include "arolla/util/fingerprint.h" #include "arolla/util/indestructible.h" #include "arolla/util/map.h" #include "arolla/util/meta.h" #include "arolla/util/repr.h" #include "arolla/util/text.h" #include "arolla/util/unit.h" #include "arolla/util/view_types.h" namespace arolla { bool IsDictQType(const QType* qtype); template <typename Key> class KeyToRowDict { using KeyViewHashTable = absl::flat_hash_map<view_type_t<Key>, int64_t>; using Hasher = typename KeyViewHashTable::hasher; using KeyEqual = typename KeyViewHashTable::key_equal; public: using Map = absl::flat_hash_map<Key, int64_t, Hasher, KeyEqual>; KeyToRowDict() = default; explicit KeyToRowDict(Map dict) : dict_(std::make_shared<Map>(std::move(dict))) {} KeyToRowDict(std::initializer_list<typename Map::value_type> dict) : dict_(std::make_shared<Map>(std::move(dict))) {} const Map& map() const { static const Indestructible<Map> empty; return dict_ != nullptr ? *dict_ : *empty; } private: std::shared_ptr<const Map> dict_; }; namespace dict_impl { void RegisterKeyToRowDictQType(QTypePtr key_type, QTypePtr dict_type); } absl::StatusOr<QTypePtr> GetKeyToRowDictQType(QTypePtr key_type); template <typename Key> QTypePtr GetKeyToRowDictQType() { return GetQType<KeyToRowDict<Key>>(); } bool IsKeyToRowDictQType(QTypePtr type); absl::StatusOr<QTypePtr> GetDictQType(QTypePtr key_type, QTypePtr value_type); const QType* GetDictKeyQTypeOrNull(QTypePtr dict_type); const QType* GetDictValueQTypeOrNull(QTypePtr dict_type); template <typename Key> struct QTypeTraits<KeyToRowDict<Key>> { static_assert(!std::is_same_v<Key, Unit>); static_assert(!std::is_same_v<Key, float>); static_assert(!std::is_same_v<Key, double>); static_assert(is_scalar_type_v<strip_optional_t<Key>>); static QTypePtr type() { static const Indestructible<SimpleQType> result( meta::type<KeyToRowDict<Key>>(), absl::StrCat("DICT_", GetQType<Key>()->name()), GetQType<Key>(), "::arolla::KeyToRowDict"); static const int ABSL_ATTRIBUTE_UNUSED dict_registered = (dict_impl::RegisterKeyToRowDictQType(GetQType<Key>(), result.get()), 1); return result.get(); } }; template <class Key> struct ReprTraits<KeyToRowDict<Key>, std::enable_if_t<std::is_invocable_v<ReprTraits<Key>, Key>>> { ReprToken operator()(const KeyToRowDict<Key>& dict) const { std::ostringstream oss; oss << "dict{"; for (const auto& key : SortedMapKeys(dict.map())) { oss << Repr(Key(key)) << ":" << Repr(dict.map().at(key)) << ","; } oss << "}"; return ReprToken{std::move(oss).str()}; } }; template <class Key> struct FingerprintHasherTraits<KeyToRowDict<Key>> { void operator()(FingerprintHasher* hasher, const KeyToRowDict<Key>& dict) const { std::vector<std::pair<view_type_t<Key>, int64_t>> elements( dict.map().begin(), dict.map().end()); std::sort(elements.begin(), elements.end()); hasher->Combine(elements.size()); for (const auto& [k, v] : elements) { hasher->Combine(k, v); } } }; extern template struct QTypeTraits<KeyToRowDict<bool>>; extern template struct QTypeTraits<KeyToRowDict<int32_t>>; extern template struct QTypeTraits<KeyToRowDict<int64_t>>; extern template struct QTypeTraits<KeyToRowDict<Bytes>>; extern template struct QTypeTraits<KeyToRowDict<Text>>; } #endif #include "arolla/qtype/dict/dict_types.h" #include <cstdint> #include <memory> #include <string> #include <utility> #include "absl/base/thread_annotations.h" #include "absl/container/flat_hash_map.h" #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "absl/synchronization/mutex.h" #include "arolla/dense_array/qtype/types.h" #include "arolla/qtype/derived_qtype.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/tuple_qtype.h" #include "arolla/util/bytes.h" #include "arolla/util/fast_dynamic_downcast_final.h" #include "arolla/util/indestructible.h" #include "arolla/util/text.h" #include "arolla/util/status_macros_backport.h" namespace arolla { namespace { class KeyToRowDictTypeRegistry { public: static KeyToRowDictTypeRegistry& instance() { static Indestructible<KeyToRowDictTypeRegistry> result; return *result; } absl::Status Register(QTypePtr key_qtype, QTypePtr dict_qtype) { absl::MutexLock l(&lock_); auto [iter, inserted] = dict_types_.emplace(key_qtype, dict_qtype); if (!inserted) { return absl::FailedPreconditionError(absl::StrFormat( "attempt to register %s dict twice", dict_qtype->name())); } return absl::OkStatus(); } absl::StatusOr<QTypePtr> Get(QTypePtr qtype) { absl::ReaderMutexLock l(&lock_); auto iter = dict_types_.find(qtype); if (iter == dict_types_.end()) { return absl::NotFoundError( absl::StrFormat("no dict with %s keys found", qtype->name())); } return iter->second; } private: absl::Mutex lock_; absl::flat_hash_map<QTypePtr, QTypePtr> dict_types_ ABSL_GUARDED_BY(lock_); }; class DictQType final : public BasicDerivedQType { public: DictQType(std::string name, QTypePtr dict_type, QTypePtr values_array_type) : BasicDerivedQType(ConstructorArgs{ .name = std::move(name), .base_qtype = MakeTupleQType({dict_type, values_array_type}), .qtype_specialization_key = "::arolla::DictQType", }) {} }; class DictQTypeRegistry { public: static DictQTypeRegistry& instance() { static Indestructible<DictQTypeRegistry> result; return *result; } absl::StatusOr<QTypePtr> GetQType(QTypePtr key_type, QTypePtr value_type) { { absl::ReaderMutexLock guard(&lock_); if (const auto it = registry_.find({key_type, value_type}); it != registry_.end()) { return it->second.get(); } } ASSIGN_OR_RETURN(QTypePtr dict_type, GetKeyToRowDictQType(key_type)); ASSIGN_OR_RETURN(QTypePtr values_array_type, GetDenseArrayQTypeByValueQType(value_type)); auto kv_dict_type = std::make_unique<DictQType>( absl::StrFormat("Dict<%s,%s>", key_type->name(), value_type->name()), dict_type, values_array_type); absl::MutexLock guard(&lock_); return registry_ .emplace(std::make_pair(key_type, value_type), std::move(kv_dict_type)) .first->second.get(); } private: absl::Mutex lock_; absl::flat_hash_map<std::pair<QTypePtr, QTypePtr>, std::unique_ptr<QType>> registry_ ABSL_GUARDED_BY(lock_); }; } namespace dict_impl { void RegisterKeyToRowDictQType(QTypePtr key_type, QTypePtr dict_type) { auto status = KeyToRowDictTypeRegistry::instance().Register(key_type, dict_type); DCHECK_OK(status); } } absl::StatusOr<QTypePtr> GetKeyToRowDictQType(QTypePtr key_type) { return KeyToRowDictTypeRegistry::instance().Get(key_type); } bool IsKeyToRowDictQType(QTypePtr type) { if (type->value_qtype() == nullptr) { return false; } ASSIGN_OR_RETURN(QTypePtr dict_type, GetKeyToRowDictQType(type->value_qtype()), false); return dict_type == type; } absl::StatusOr<QTypePtr> GetDictQType(QTypePtr key_type, QTypePtr value_type) { return DictQTypeRegistry::instance().GetQType(key_type, value_type); } const QType* GetDictKeyQTypeOrNull(QTypePtr dict_type) { auto d = fast_dynamic_downcast_final<const DictQType*>(dict_type); return d != nullptr ? d->type_fields()[0].GetType()->value_qtype() : nullptr; } const QType* GetDictValueQTypeOrNull(QTypePtr dict_type) { auto d = fast_dynamic_downcast_final<const DictQType*>(dict_type); return d != nullptr ? d->type_fields()[1].GetType()->value_qtype() : nullptr; } bool IsDictQType(const QType* qtype) { return fast_dynamic_downcast_final<const DictQType*>(qtype) != nullptr; } template struct QTypeTraits<KeyToRowDict<bool>>; template struct QTypeTraits<KeyToRowDict<int32_t>>; template struct QTypeTraits<KeyToRowDict<int64_t>>; template struct QTypeTraits<KeyToRowDict<Bytes>>; template struct QTypeTraits<KeyToRowDict<Text>>; }
#include "arolla/qtype/dict/dict_types.h" #include <cstdint> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "arolla/dense_array/qtype/types.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/bytes.h" #include "arolla/util/repr.h" #include "arolla/util/testing/status_matchers_backport.h" #include "arolla/util/unit.h" namespace arolla { namespace { using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::StatusIs; using ::testing::ElementsAre; using ::testing::Eq; using ::testing::HasSubstr; using ::testing::Ne; using ::testing::Property; TEST(DictTypes, GetKeyToRowDictQType) { GetKeyToRowDictQType<int64_t>(); EXPECT_THAT(GetKeyToRowDictQType<int64_t>()->value_qtype(), Eq(GetQType<int64_t>())); EXPECT_THAT(GetKeyToRowDictQType(GetQType<int64_t>()), IsOkAndHolds(GetQType<KeyToRowDict<int64_t>>())); EXPECT_THAT(GetKeyToRowDictQType(GetQType<int64_t>()), IsOkAndHolds(GetKeyToRowDictQType<int64_t>())); EXPECT_THAT(GetKeyToRowDictQType(GetQType<KeyToRowDict<int64_t>>()), StatusIs(absl::StatusCode::kNotFound, HasSubstr("no dict with DICT_INT64 keys found"))); } TEST(DictTypes, GetDictQType) { GetKeyToRowDictQType<int64_t>(); GetDenseArrayQType<float>(); GetDenseArrayQType<double>(); ASSERT_OK_AND_ASSIGN(QTypePtr int_to_float_dict, GetDictQType(GetQType<int64_t>(), GetQType<float>())); EXPECT_THAT(int_to_float_dict->name(), Eq("Dict<INT64,FLOAT32>")); EXPECT_THAT(GetDictKeyQTypeOrNull(int_to_float_dict), Eq(GetQType<int64_t>())); EXPECT_THAT(GetDictValueQTypeOrNull(int_to_float_dict), Eq(GetQType<float>())); EXPECT_THAT( int_to_float_dict->type_fields(), ElementsAre( Property(&TypedSlot::GetType, Eq(GetKeyToRowDictQType<int64_t>())), Property(&TypedSlot::GetType, Eq(GetDenseArrayQType<float>())))); EXPECT_THAT(GetDictQType(GetQType<int64_t>(), GetQType<float>()), IsOkAndHolds(Eq(int_to_float_dict))); EXPECT_THAT(GetDictQType(GetQType<int64_t>(), GetQType<double>()), IsOkAndHolds(Ne(int_to_float_dict))); } TEST(DictTypes, IsDictQType) { GetKeyToRowDictQType<int64_t>(); GetDenseArrayQType<float>(); GetDenseArrayQType<Unit>(); { ASSERT_OK_AND_ASSIGN(QTypePtr int_to_float_dict, GetDictQType(GetQType<int64_t>(), GetQType<float>())); ASSERT_TRUE(IsDictQType(int_to_float_dict)); } { ASSERT_OK_AND_ASSIGN(QTypePtr int_to_unit_dict, GetDictQType(GetQType<int64_t>(), GetQType<Unit>())); ASSERT_TRUE(IsDictQType(int_to_unit_dict)); } { EXPECT_THAT(GetDictQType(GetQType<Unit>(), GetQType<float>()), StatusIs(absl::StatusCode::kNotFound, HasSubstr("no dict with UNIT keys found"))); } { EXPECT_THAT(GetDictQType(GetQType<float>(), GetQType<float>()), StatusIs(absl::StatusCode::kNotFound, HasSubstr("no dict with FLOAT32 keys found"))); } } TEST(DictTypes, ReprTraits) { EXPECT_EQ(Repr(KeyToRowDict<float>{}), "dict{}"); EXPECT_EQ(Repr(KeyToRowDict<float>{{{0.5, 1}}}), "dict{0.5:int64{1},}"); EXPECT_EQ(Repr(KeyToRowDict<float>{{{0.5, 1}, {2.5, 3}}}), "dict{0.5:int64{1},2.5:int64{3},}"); EXPECT_EQ(Repr(KeyToRowDict<Bytes>{{{Bytes("key"), 2}}}), "dict{b'key':int64{2},}"); } } }
2,352
cpp
google/arolla
inplace_expr_compiler
arolla/serving/inplace_expr_compiler.cc
arolla/serving/inplace_expr_compiler_test.cc
#ifndef AROLLA_SERVING_INPLACE_EXPR_COMPILER_H_ #define AROLLA_SERVING_INPLACE_EXPR_COMPILER_H_ #include <functional> #include <memory> #include <string> #include <type_traits> #include <utility> #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/expr/expr_node.h" #include "arolla/io/input_loader.h" #include "arolla/io/slot_listener.h" #include "arolla/io/struct_io.h" #include "arolla/memory/frame.h" #include "arolla/qexpr/eval_context.h" #include "arolla/qexpr/evaluation_engine.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/typed_slot.h" #include "arolla/util/status_macros_backport.h" namespace arolla { namespace inplace_expr_compiler_impl { using TypedSlotMap = absl::flat_hash_map<std::string, TypedSlot>; TypedSlotMap CollectInternalSlots(TypedSlot root_slot); struct IoSlots { TypedSlotMap input_slots; TypedSlot output_slot; TypedSlotMap named_output_slots; }; absl::StatusOr<IoSlots> CollectIoSlots(QTypePtr qtype, const CompiledExpr& compiled_expr, absl::string_view final_output_name); } template <class T> using InplaceModelFunction = std::function<absl::Status(T&)>; template <typename T> absl::StatusOr<InplaceModelFunction<T>> CompileInplaceExprOnStruct( const InplaceCompiledExpr& compiled_expr, absl::string_view final_output_name) { static_assert( std::is_standard_layout<T>::value, "Data must be standard layout to be used with CompileExprInplace."); QTypePtr qtype = GetQType<T>(); ASSIGN_OR_RETURN(inplace_expr_compiler_impl::IoSlots slots, inplace_expr_compiler_impl::CollectIoSlots( qtype, compiled_expr, final_output_name)); ASSIGN_OR_RETURN(auto executable, compiled_expr.InplaceBind( slots.input_slots, slots.output_slot, slots.named_output_slots)); return [qtype, executable(std::shared_ptr<BoundExpr>(std::move(executable)))]( T& input) -> absl::Status { FramePtr frame(&input, &qtype->type_layout()); EvaluationContext ctx; executable->Execute(&ctx, frame); return ctx.status(); }; } template <typename Struct> absl::StatusOr<InputLoaderPtr<Struct>> CreateStructInputLoader() { return StructInputLoader<Struct>::Create( inplace_expr_compiler_impl::CollectInternalSlots( TypedSlot::UnsafeFromOffset(GetQType<Struct>(), 0))); } template <typename Struct> absl::StatusOr<std::unique_ptr<SlotListener<Struct>>> CreateStructSlotListener() { return StructSlotListener<Struct>::Create( inplace_expr_compiler_impl::CollectInternalSlots( TypedSlot::UnsafeFromOffset(GetQType<Struct>(), 0))); } } #endif #include "arolla/serving/inplace_expr_compiler.h" #include <cstddef> #include <string> #include <utility> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "arolla/naming/table.h" #include "arolla/qexpr/evaluation_engine.h" #include "arolla/qtype/named_field_qtype.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/typed_slot.h" #include "arolla/util/status_macros_backport.h" namespace arolla::inplace_expr_compiler_impl { TypedSlotMap CollectInternalSlots(TypedSlot root_slot) { TypedSlotMap result; if (GetFieldNames(root_slot.GetType()).empty()) { return result; } std::vector<std::pair<TypedSlot, naming::TablePath>> stack{{root_slot, {}}}; while (!stack.empty()) { auto [slot, table] = stack.back(); stack.pop_back(); auto field_names = GetFieldNames(slot.GetType()); for (size_t i = 0; i < field_names.size(); ++i) { const auto& field_name = field_names[i]; const TypedSlot& field_slot = slot.SubSlot(i); result.emplace(table.Column(naming::FieldAccess(field_name)).FullName(), field_slot); if (!GetFieldNames(field_slot.GetType()).empty()) { stack.emplace_back(field_slot, table.Child(naming::FieldAccess(field_name))); } } } return result; } namespace { absl::Status CheckField(QTypePtr qtype, const TypedSlotMap& slot_map, QTypePtr field_qtype, absl::string_view field_name) { if (GetFieldNames(qtype).empty()) { return absl::FailedPreconditionError( absl::StrCat("no registered field names for ", qtype->name(), " in Compile.*ExprOnStructInput")); } if (!slot_map.contains(field_name)) { return absl::FailedPreconditionError( absl::StrCat("input `", field_name, "` not found in ", qtype->name(), " in Compile.*ExprOnStructInput")); } QTypePtr result_type = slot_map.at(field_name).GetType(); if (result_type != field_qtype) { return absl::FailedPreconditionError(absl::StrCat( "input `", field_name, "` type mismatch for ", qtype->name(), " in Compile.*ExprOnStructInput, expected in struct: ", result_type->name(), ", found in expr: ", field_qtype->name())); } return absl::OkStatus(); } absl::StatusOr<TypedSlotMap> CollectInputSlots( QTypePtr qtype, const TypedSlotMap& struct_slot_map, const CompiledExpr& compiled_expr) { TypedSlotMap input_slots; input_slots.reserve(compiled_expr.input_types().size()); for (const auto& [name, field_qtype] : compiled_expr.input_types()) { RETURN_IF_ERROR(CheckField(qtype, struct_slot_map, field_qtype, name)); input_slots.emplace(name, struct_slot_map.at(name)); } return input_slots; } } absl::StatusOr<IoSlots> CollectIoSlots(QTypePtr qtype, const CompiledExpr& compiled_expr, absl::string_view final_output_name) { TypedSlotMap struct_slot_map = CollectInternalSlots(TypedSlot::UnsafeFromOffset(qtype, 0)); ASSIGN_OR_RETURN(TypedSlotMap input_slots, CollectInputSlots(qtype, struct_slot_map, compiled_expr)); RETURN_IF_ERROR(CheckField(qtype, struct_slot_map, compiled_expr.output_type(), final_output_name)); if (compiled_expr.input_types().contains(final_output_name)) { return absl::FailedPreconditionError(absl::StrCat( final_output_name, " present both as an input and as final output")); } if (compiled_expr.named_output_types().contains(final_output_name)) { return absl::FailedPreconditionError( absl::StrCat(final_output_name, " present both as final output and as named output")); } for (const auto& [name, field_qtype] : compiled_expr.input_types()) { if (compiled_expr.named_output_types().contains(name)) { return absl::FailedPreconditionError( absl::StrCat(name, " present both as an input and as named output")); } } for (const auto& [name, field_qtype] : compiled_expr.named_output_types()) { RETURN_IF_ERROR(CheckField(qtype, struct_slot_map, field_qtype, name)); } absl::flat_hash_map<std::string, TypedSlot> named_output_slots; named_output_slots.reserve(compiled_expr.named_output_types().size()); for (const auto& [name, _] : compiled_expr.named_output_types()) { named_output_slots.emplace(name, struct_slot_map.at(name)); } return IoSlots{.input_slots = input_slots, .output_slot = struct_slot_map.at(final_output_name), .named_output_slots = named_output_slots}; } }
#include "arolla/serving/inplace_expr_compiler.h" #include <array> #include <cstdint> #include <functional> #include <memory> #include <optional> #include <string> #include <tuple> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/container/flat_hash_map.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_node.h" #include "arolla/memory/frame.h" #include "arolla/memory/optional_value.h" #include "arolla/qexpr/eval_context.h" #include "arolla/qexpr/evaluation_engine.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/simple_qtype.h" #include "arolla/qtype/typed_slot.h" #include "arolla/serving/expr_compiler.h" #include "arolla/util/bytes.h" #include "arolla/util/fingerprint.h" #include "arolla/util/init_arolla.h" #include "arolla/util/struct_field.h" #include "arolla/util/testing/status_matchers_backport.h" #include "arolla/util/text.h" #include "arolla/util/status_macros_backport.h" namespace arolla { namespace { using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::StatusIs; using ::testing::HasSubstr; using ::testing::MatchesRegex; struct UnsupportedType {}; struct TestOutputStruct { double x_plus_y; double x_times_y; UnsupportedType unsupported_type_field; double unused; static auto ArollaStructFields() { using CppType = TestOutputStruct; return std::tuple{ AROLLA_DECLARE_STRUCT_FIELD(x_plus_y), AROLLA_DECLARE_STRUCT_FIELD(x_times_y), AROLLA_SKIP_STRUCT_FIELD(unsupported_type_field), AROLLA_DECLARE_STRUCT_FIELD(unused), }; } void ArollaFingerprint(FingerprintHasher* hasher) const { CombineStructFields(hasher, *this); } }; struct TestStruct { float x; double y; void* unsupported_field; TestOutputStruct side_outputs; static auto ArollaStructFields() { using CppType = TestStruct; return std::tuple{ AROLLA_DECLARE_STRUCT_FIELD(x), AROLLA_DECLARE_STRUCT_FIELD(y), AROLLA_SKIP_STRUCT_FIELD(unsupported_field), AROLLA_DECLARE_STRUCT_FIELD(side_outputs), }; } void ArollaFingerprint(FingerprintHasher* hasher) const { CombineStructFields(hasher, *this); } }; struct TestStructWithOptional { OptionalValue<float> x; OptionalValue<double> y; std::array<int, 6> skip_me; OptionalValue<double> x_plus_y; constexpr static auto ArollaStructFields() { using CppType = TestStructWithOptional; return std::tuple{ AROLLA_DECLARE_STRUCT_FIELD(x), AROLLA_DECLARE_STRUCT_FIELD(y), AROLLA_SKIP_STRUCT_FIELD(skip_me), AROLLA_DECLARE_STRUCT_FIELD(x_plus_y), }; } void ArollaFingerprint(FingerprintHasher* hasher) const { CombineStructFields(hasher, *this); } }; struct TestStructWithString { std::string title; UnsupportedType it_is_not_supported; OptionalValue<::arolla::Bytes> name; UnsupportedType not_supported_sorry; std::string full_name; static auto ArollaStructFields() { using CppType = TestStructWithString; return std::tuple{ AROLLA_DECLARE_STRUCT_FIELD(title), AROLLA_SKIP_STRUCT_FIELD(it_is_not_supported), AROLLA_DECLARE_STRUCT_FIELD(name), AROLLA_SKIP_STRUCT_FIELD(not_supported_sorry), AROLLA_DECLARE_STRUCT_FIELD(full_name), }; } void ArollaFingerprint(FingerprintHasher* hasher) const { CombineStructFields(hasher, *this); } }; } AROLLA_DECLARE_SIMPLE_QTYPE(TEST_OUTPUT_STRUCT, TestOutputStruct); AROLLA_DEFINE_SIMPLE_QTYPE(TEST_OUTPUT_STRUCT, TestOutputStruct); AROLLA_DECLARE_SIMPLE_QTYPE(TEST_STRUCT, TestStruct); AROLLA_DEFINE_SIMPLE_QTYPE(TEST_STRUCT, TestStruct); AROLLA_DECLARE_SIMPLE_QTYPE(TEST_STRUCT_WITH_OPTIONAL, TestStructWithOptional); AROLLA_DEFINE_SIMPLE_QTYPE(TEST_STRUCT_WITH_OPTIONAL, TestStructWithOptional); AROLLA_DECLARE_SIMPLE_QTYPE(TEST_STRUCT_WITH_STRING, TestStructWithString); AROLLA_DEFINE_SIMPLE_QTYPE(TEST_STRUCT_WITH_STRING, TestStructWithString); namespace { class FailingCompiledExpr : public InplaceCompiledExpr { public: using InplaceCompiledExpr::InplaceCompiledExpr; absl::StatusOr<std::unique_ptr<BoundExpr>> InplaceBind( const absl::flat_hash_map<std::string, TypedSlot>& slots, TypedSlot output_slot, const absl::flat_hash_map<std::string, TypedSlot>& ) const final { return absl::InternalError("Fake:("); } }; TEST(CompileInplaceExprOnStruct, NoFieldNames) { FailingCompiledExpr compiled_expr({}, GetQType<double>(), {}); EXPECT_THAT( CompileInplaceExprOnStruct<int32_t>(compiled_expr, "/final_output"), StatusIs(absl::StatusCode::kFailedPrecondition, MatchesRegex(".*registered field.*INT32.*"))); } TEST(CompileInplaceExprOnStruct, NoFinalOutputName) { FailingCompiledExpr compiled_expr({}, GetQType<double>(), {}); EXPECT_THAT( CompileInplaceExprOnStruct<TestStruct>(compiled_expr, "/final_output"), StatusIs(absl::StatusCode::kFailedPrecondition, MatchesRegex(".*input.*/final_output.*TEST_STRUCT.*"))); } TEST(CompileInplaceExprOnStruct, InputTypeMismatch) { FailingCompiledExpr compiled_expr({}, GetQType<double>(), {}); EXPECT_THAT( CompileInplaceExprOnStruct<TestStruct>(compiled_expr, "/x"), StatusIs(absl::StatusCode::kFailedPrecondition, MatchesRegex( ".*/x.*TEST_STRUCT.*expected.*FLOAT32.*found.*FLOAT64"))); } TEST(CompileInplaceExprOnStruct, InputTypeUnknown) { FailingCompiledExpr compiled_expr({}, GetQType<double>(), {}); EXPECT_THAT(CompileInplaceExprOnStruct<TestStruct>(compiled_expr, "/qq"), StatusIs(absl::StatusCode::kFailedPrecondition, MatchesRegex(".*input.*/qq.*TEST_STRUCT.*"))); } TEST(CompileInplaceExprOnStruct, FinalOutputTypeMismatch) { FailingCompiledExpr compiled_expr({{"/x", GetQType<double>()}}, GetQType<double>(), {}); EXPECT_THAT( CompileInplaceExprOnStruct<TestStruct>(compiled_expr, "/side_outputs/x_plus_y"), StatusIs(absl::StatusCode::kFailedPrecondition, MatchesRegex( ".*/x.*TEST_STRUCT.*expected.*FLOAT32.*found.*FLOAT64"))); } TEST(CompileInplaceExprOnStruct, SideOutputTypeMismatch) { FailingCompiledExpr compiled_expr( {{"/x", GetQType<float>()}}, GetQType<double>(), {{"/side_outputs/x_times_y", GetQType<float>()}}); EXPECT_THAT( CompileInplaceExprOnStruct<TestStruct>(compiled_expr, "/side_outputs/x_plus_y"), StatusIs( absl::StatusCode::kFailedPrecondition, MatchesRegex( ".*/side_outputs/" "x_times_y.*TEST_STRUCT.*expected.*FLOAT64.*found.*FLOAT32"))); } TEST(CompileInplaceExprOnStruct, SideOutputUnknown) { FailingCompiledExpr compiled_expr( {{"/x", GetQType<float>()}}, GetQType<double>(), {{"/side_outputs/x_power_y", GetQType<double>()}}); EXPECT_THAT( CompileInplaceExprOnStruct<TestStruct>(compiled_expr, "/side_outputs/x_plus_y"), StatusIs( absl::StatusCode::kFailedPrecondition, MatchesRegex(".*/side_outputs/x_power_y.*not found.*TEST_STRUCT.*"))); } TEST(CompileInplaceExprOnStruct, CompiledExprBindingFailure) { FailingCompiledExpr compiled_expr({{"/x", GetQType<float>()}}, GetQType<double>(), {}); EXPECT_THAT(CompileInplaceExprOnStruct<TestStruct>(compiled_expr, "/side_outputs/x_plus_y"), StatusIs(absl::StatusCode::kInternal, "Fake:(")); } TEST(CompileInplaceExprOnStruct, InputSideOutputCollision) { FailingCompiledExpr compiled_expr({{"/y", GetQType<double>()}}, GetQType<double>(), {{"/y", GetQType<double>()}}); EXPECT_THAT(CompileInplaceExprOnStruct<TestStruct>(compiled_expr, "/side_outputs/x_plus_y"), StatusIs(absl::StatusCode::kFailedPrecondition, MatchesRegex(".*/y.*input.*named output.*"))); } TEST(CompileInplaceExprOnStruct, InputFinalOutputCollision) { FailingCompiledExpr compiled_expr( {{"/y", GetQType<double>()}}, GetQType<double>(), {{"/side_outputs/x_plus_y", GetQType<double>()}}); EXPECT_THAT(CompileInplaceExprOnStruct<TestStruct>(compiled_expr, "/y"), StatusIs(absl::StatusCode::kFailedPrecondition, MatchesRegex(".*/y.*input.*final output.*"))); } TEST(CompileInplaceExprOnStruct, SideOutputFinalOutputCollision) { FailingCompiledExpr compiled_expr( {{"/y", GetQType<double>()}}, GetQType<double>(), {{"/side_outputs/x_plus_y", GetQType<double>()}}); EXPECT_THAT( CompileInplaceExprOnStruct<TestStruct>(compiled_expr, "/side_outputs/x_plus_y"), StatusIs(absl::StatusCode::kFailedPrecondition, MatchesRegex( ".*/side_outputs/x_plus_y.*final output.*named output.*"))); } class TestBoundExpr final : public BoundExpr { public: TestBoundExpr(FrameLayout::Slot<float> x, FrameLayout::Slot<double> y, FrameLayout::Slot<double> x_plus_y, FrameLayout::Slot<double> x_times_y) : BoundExpr( {{"/x", TypedSlot::FromSlot(x)}, {"/y", TypedSlot::FromSlot(y)}}, TypedSlot::FromSlot(x_plus_y), {{"/side_outputs/x_times_y", TypedSlot::FromSlot(x_times_y)}}), x_(x), y_(y), x_plus_y_(x_plus_y), x_times_y_(x_times_y) {} void InitializeLiterals(EvaluationContext*, FramePtr) const final {} void Execute(EvaluationContext*, FramePtr frame) const final { frame.Set(x_plus_y_, frame.Get(x_) + frame.Get(y_)); frame.Set(x_times_y_, frame.Get(x_) * frame.Get(y_)); } private: FrameLayout::Slot<float> x_; FrameLayout::Slot<double> y_; FrameLayout::Slot<double> x_plus_y_; FrameLayout::Slot<double> x_times_y_; }; class TestCompiledExpr : public InplaceCompiledExpr { public: TestCompiledExpr() : InplaceCompiledExpr( {{"/x", GetQType<float>()}, {"/y", GetQType<double>()}}, GetQType<double>(), {{"/side_outputs/x_times_y", GetQType<double>()}}) {} absl::StatusOr<std::unique_ptr<BoundExpr>> InplaceBind( const absl::flat_hash_map<std::string, TypedSlot>& slots, TypedSlot output_slot, const absl::flat_hash_map<std::string, TypedSlot>& named_output_slots) const final { RETURN_IF_ERROR(VerifySlotTypes(input_types(), slots)); return std::make_unique<TestBoundExpr>( slots.at("/x").ToSlot<float>().value(), slots.at("/y").ToSlot<double>().value(), output_slot.ToSlot<double>().value(), named_output_slots.at("/side_outputs/x_times_y") .ToSlot<double>() .value()); } }; TEST(CompileInplaceExprOnStructTest, SuccessXPlusY) { TestCompiledExpr compiled_expr; ASSERT_OK_AND_ASSIGN(std::function<absl::Status(TestStruct&)> eval_fn, CompileInplaceExprOnStruct<TestStruct>( compiled_expr, "/side_outputs/x_plus_y")); TestStruct input{ .x = 5.f, .y = 7., .side_outputs = {.x_plus_y = -1, .x_times_y = -1, .unused = -1}}; ASSERT_OK(eval_fn(input)); EXPECT_EQ(input.side_outputs.x_plus_y, 12); EXPECT_EQ(input.side_outputs.x_times_y, 35.); EXPECT_EQ(input.x, 5); EXPECT_EQ(input.y, 7); EXPECT_EQ(input.side_outputs.unused, -1.); } class TestBoundExprWithOptionals final : public BoundExpr { public: TestBoundExprWithOptionals(FrameLayout::Slot<OptionalValue<float>> x, FrameLayout::Slot<OptionalValue<double>> y, FrameLayout::Slot<OptionalValue<double>> x_plus_y) : BoundExpr( {{"/x", TypedSlot::FromSlot(x)}, {"/y", TypedSlot::FromSlot(y)}}, TypedSlot::FromSlot(x_plus_y), {}), x_(x), y_(y), x_plus_y_(x_plus_y) {} void InitializeLiterals(EvaluationContext*, FramePtr) const final {} void Execute(EvaluationContext*, FramePtr frame) const final { if (frame.Get(x_).present && frame.Get(y_).present) { frame.Set(x_plus_y_, frame.Get(x_).value + frame.Get(y_).value); } else { frame.Set(x_plus_y_, std::nullopt); } } private: FrameLayout::Slot<OptionalValue<float>> x_; FrameLayout::Slot<OptionalValue<double>> y_; FrameLayout::Slot<OptionalValue<double>> x_plus_y_; }; class TestCompiledExprWithOptionals : public InplaceCompiledExpr { public: TestCompiledExprWithOptionals() : InplaceCompiledExpr({{"/x", GetQType<OptionalValue<float>>()}, {"/y", GetQType<OptionalValue<double>>()}}, GetQType<OptionalValue<double>>(), {}) {} absl::StatusOr<std::unique_ptr<BoundExpr>> InplaceBind( const absl::flat_hash_map<std::string, TypedSlot>& slots, TypedSlot output_slot, const absl::flat_hash_map<std::string, TypedSlot>& ) const final { RETURN_IF_ERROR(VerifySlotTypes(input_types(), slots)); return std::make_unique<TestBoundExprWithOptionals>( slots.at("/x").ToSlot<OptionalValue<float>>().value(), slots.at("/y").ToSlot<OptionalValue<double>>().value(), output_slot.ToSlot<OptionalValue<double>>().value()); } }; TEST(CompileInplaceExprOnStructTest, SuccessXPlusYWithOptionals) { TestCompiledExprWithOptionals compiled_expr; ASSERT_OK_AND_ASSIGN( std::function<absl::Status(TestStructWithOptional&)> eval_fn, CompileInplaceExprOnStruct<TestStructWithOptional>(compiled_expr, "/x_plus_y")); TestStructWithOptional input{.x = 5.f, .y = 7., .x_plus_y = -1}; ASSERT_OK(eval_fn(input)); EXPECT_EQ(input.x_plus_y, 12.); EXPECT_EQ(input.x, 5.f); EXPECT_EQ(input.y, 7.); } class TestBoundExprWithStrings final : public BoundExpr { public: TestBoundExprWithStrings(FrameLayout::Slot<arolla::Bytes> title, FrameLayout::Slot<OptionalValue<arolla::Bytes>> name, FrameLayout::Slot<arolla::Bytes> output) : BoundExpr({{"/title", TypedSlot::FromSlot(title)}, {"/name", TypedSlot::FromSlot(name)}}, TypedSlot::FromSlot(output), {}), title_(title), name_(name), output_(output) {} void InitializeLiterals(EvaluationContext*, FramePtr) const final {} void Execute(EvaluationContext*, FramePtr frame) const final { if (!frame.Get(name_).present) { frame.Set(output_, "UNKNOWN"); return; } frame.Set(output_, absl::StrCat(frame.Get(title_), " ", frame.Get(name_).value)); } private: FrameLayout::Slot<arolla::Bytes> title_; FrameLayout::Slot<OptionalValue<arolla::Bytes>> name_; FrameLayout::Slot<arolla::Bytes> output_; }; class TestCompiledExprWithStrings : public InplaceCompiledExpr { public: TestCompiledExprWithStrings() : InplaceCompiledExpr( {{"/title", GetQType<arolla::Bytes>()}, {"/name", GetQType<OptionalValue<arolla::Bytes>>()}}, GetQType<arolla::Bytes>(), {}) {} absl::StatusOr<std::unique_ptr<BoundExpr>> InplaceBind( const absl::flat_hash_map<std::string, TypedSlot>& slots, TypedSlot output_slot, const absl::flat_hash_map<std::string, TypedSlot>& ) const final { RETURN_IF_ERROR(VerifySlotTypes(input_types(), slots)); return std::make_unique<TestBoundExprWithStrings>( slots.at("/title").ToSlot<arolla::Bytes>().value(), slots.at("/name").ToSlot<OptionalValue<arolla::Bytes>>().value(), output_slot.ToSlot<arolla::Bytes>().value()); } }; TEST(CompileInplaceExprOnStructTest, SuccessStringsIO) { TestCompiledExprWithStrings compiled_expr; ASSERT_OK_AND_ASSIGN( std::function<absl::Status(TestStructWithString&)> eval_fn, CompileInplaceExprOnStruct<TestStructWithString>(compiled_expr, "/full_name")); TestStructWithString input{ .title = "Mr.", .name = arolla::Bytes("Abc"), .full_name = "????"}; ASSERT_OK(eval_fn(input)); EXPECT_EQ(input.full_name, "Mr. Abc"); input.name = std::nullopt; ASSERT_OK(eval_fn(input)); EXPECT_EQ(input.full_name, "UNKNOWN"); } TEST(CompileDynamicExprOnStructInputTest, TypeError) { ASSERT_OK(InitArolla()); ASSERT_OK_AND_ASSIGN( expr::ExprNodePtr expr, expr::CallOp("annotation.qtype", {expr::Leaf("/x"), expr::Literal(GetQType<int>())})); EXPECT_THAT((ExprCompiler<TestStruct, std::optional<double>>()) .SetInputLoader(CreateStructInputLoader<TestStruct>()) .Compile(expr) .status(), StatusIs(absl::StatusCode::kFailedPrecondition, MatchesRegex(".*inconsistent.*qtype.*INT32.*"))); } TEST(CompileDynamicExprOnStructInputTest, UnknownLeaf) { ASSERT_OK(InitArolla()); expr::ExprNodePtr expr = expr::Leaf("/unknown"); EXPECT_THAT((ExprCompiler<TestStruct, std::optional<double>>()) .SetInputLoader(CreateStructInputLoader<TestStruct>()) .Compile(expr) .status(), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("unknown inputs: /unknown"))); } TEST(CompileDynamicExprOnStructInputTest, TypeErrorOnCodegenModel) { ASSERT_OK(InitArolla()); TestCompiledExprWithOptionals compiled_expr; EXPECT_THAT((ExprCompiler<TestStruct, std::optional<double>>()) .SetInputLoader(CreateStructInputLoader<TestStruct>()) .Compile(compiled_expr) .status(), StatusIs(absl::StatusCode::kFailedPrecondition, MatchesRegex(".*slot types mismatch.*"))); } TEST(CompileDynamicExprOnStructInputTest, Nested) { ASSERT_OK(InitArolla()); ASSERT_OK_AND_ASSIGN( expr::ExprNodePtr expr, expr::CallOp("math.add", {expr::Leaf("/x"), expr::Leaf("/side_outputs/x_plus_y")})); ASSERT_OK_AND_ASSIGN( std::function<absl::StatusOr<double>(const TestStruct&)> eval_fn, (ExprCompiler<TestStruct, double>()) .SetInputLoader(CreateStructInputLoader<TestStruct>()) .Compile(expr)); TestStruct input{ .x = 5.f, .y = -1., .side_outputs = {.x_plus_y = 7., .x_times_y = -1, .unused = -1}}; EXPECT_THAT(eval_fn(input), IsOkAndHolds(12.)); } TEST(CompileDynamicExprOnStructInputTest, SuccessXPlusYWithOptionals) { ASSERT_OK(InitArolla()); ASSERT_OK_AND_ASSIGN( expr::ExprNodePtr expr, expr::CallOp("math.add", {expr::Leaf("/x"), expr::Leaf("/y")})); ASSERT_OK_AND_ASSIGN( std::function<absl::StatusOr<std::optional<double>>( const TestStructWithOptional&)> eval_fn, (ExprCompiler<TestStructWithOptional, std::optional<double>>()) .SetInputLoader(CreateStructInputLoader<TestStructWithOptional>()) .Compile(expr)); TestStructWithOptional input{.x = 5.f, .y = 7., .x_plus_y = -1}; EXPECT_THAT(eval_fn(input), IsOkAndHolds(12.)); input.x = std::nullopt; EXPECT_THAT(eval_fn(input), IsOkAndHolds(std::nullopt)); } TEST(CompileDynamicExprOnStructInputTest, ErrorStatus) { ASSERT_OK(InitArolla()); absl::StatusOr<expr::ExprNodePtr> status_or_expr = absl::InternalError("input error"); auto result = ExprCompiler<TestStructWithOptional, std::optional<double>>() .SetInputLoader(CreateStructInputLoader<TestStructWithOptional>()) .Compile(status_or_expr); EXPECT_THAT(result, StatusIs(absl::StatusCode::kInternal, MatchesRegex("input error"))); } TEST(CompileDynamicExprOnStructInputTest, SuccessXPlusYOnCodegenModel) { ASSERT_OK(InitArolla()); TestCompiledExpr compiled_expr; ASSERT_OK_AND_ASSIGN( std::function<absl::StatusOr<double>(const TestStruct&)> eval_fn, (ExprCompiler<TestStruct, double>()) .SetInputLoader(CreateStructInputLoader<TestStruct>()) .Compile(compiled_expr)); TestStruct input{.x = 5.f, .y = 7.}; EXPECT_THAT(eval_fn(input), IsOkAndHolds(12.)); } TEST(CompileDynamicExprOnStructInputTest, SuccessSideOutputOnCodegenModel) { ASSERT_OK(InitArolla()); TestCompiledExpr compiled_expr; ASSERT_OK_AND_ASSIGN( std::function<absl::StatusOr<double>(const TestStruct&, TestStruct*)> eval_fn, (ExprCompiler<TestStruct, double, TestStruct>()) .SetInputLoader(CreateStructInputLoader<TestStruct>()) .SetSlotListener(CreateStructSlotListener<TestStruct>()) .Compile(compiled_expr)); TestStruct input{.x = 5.f, .y = 7.}; EXPECT_THAT(eval_fn(input, nullptr), IsOkAndHolds(12.)); EXPECT_THAT(eval_fn(input, &input), IsOkAndHolds(12.)); EXPECT_EQ(input.side_outputs.x_times_y, 35); } TEST(CompileDynamicExprOnStructWithBytesInputTest, SuccessUpper) { ASSERT_OK(InitArolla()); ASSERT_OK_AND_ASSIGN(expr::ExprNodePtr title, expr::CallOp("strings.decode", {expr::Leaf("/title")})); ASSERT_OK_AND_ASSIGN( expr::ExprNodePtr name, expr::CallOp("strings.upper", {expr::CallOp("strings.decode", {expr::Leaf("/name")})})); ASSERT_OK_AND_ASSIGN( expr::ExprNodePtr expr, expr::CallOp("strings.join", {title, expr::Literal(Text(" ")), name})); ASSERT_OK_AND_ASSIGN(expr, expr::CallOp("core.get_optional_value", {expr::CallOp("strings.encode", {expr})})); ASSERT_OK_AND_ASSIGN( std::function<absl::StatusOr<arolla::Bytes>(const TestStructWithString&)> eval_fn, (ExprCompiler<TestStructWithString, arolla::Bytes>()) .SetInputLoader(CreateStructInputLoader<TestStructWithString>()) .Compile(expr)); TestStructWithString input{.title = "Mr.", .name = Bytes("abc")}; EXPECT_THAT(eval_fn(input), IsOkAndHolds(Bytes("Mr. ABC"))); input.name = std::nullopt; EXPECT_THAT(eval_fn(input), StatusIs(absl::StatusCode::kFailedPrecondition, HasSubstr("expects present value"))); } } }
2,353
cpp
google/arolla
expr_compiler
arolla/serving/expr_compiler.cc
arolla/serving/expr_compiler_test.cc
#ifndef AROLLA_SERVING_EXPR_COMPILER_H_ #define AROLLA_SERVING_EXPR_COMPILER_H_ #include <cstddef> #include <cstdint> #include <functional> #include <memory> #include <optional> #include <string> #include <tuple> #include <type_traits> #include <utility> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "absl/types/span.h" #include "arolla/expr/eval/model_executor.h" #include "arolla/expr/eval/thread_safe_model_executor.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/optimization/optimizer.h" #include "arolla/io/input_loader.h" #include "arolla/io/slot_listener.h" #include "arolla/io/tuple_input_loader.h" #include "arolla/io/typed_refs_input_loader.h" #include "arolla/qexpr/evaluation_engine.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/typed_ref.h" #include "arolla/util/indestructible.h" #include "arolla/util/status_macros_backport.h" namespace arolla { using ModelFunctionOptions = ::arolla::expr::ModelEvaluationOptions; struct ExprCompilerFlags { static constexpr int kDefault = 0; static constexpr int kEvalWithOptions = 1; }; namespace serving_impl { template <typename Input, typename Output, typename SideOutput> struct ToModelFunction { using without_options = std::function<absl::StatusOr<Output>(const Input&, SideOutput*)>; using with_options = std::function<absl::StatusOr<Output>( const ModelFunctionOptions&, const Input&, SideOutput*)>; }; template <typename Input, typename Output> struct ToModelFunction<Input, Output, void> { using without_options = std::function<absl::StatusOr<Output>(const Input&)>; using with_options = std::function<absl::StatusOr<Output>( const ModelFunctionOptions&, const Input&)>; }; class ExprCompilerDefaultOptimizer { public: static const std::optional<expr::Optimizer>& get() { return *optimizer_; } private: friend class ExprCompilerDefaultOptimizerInitializer; static Indestructible<std::optional<expr::Optimizer>> optimizer_; }; } template <typename Subclass, typename Input, typename Output, typename SideOutput> class ExprCompilerBase { using ModelExecutor = expr::ModelExecutor<Input, Output, SideOutput>; using ThreadSafePoolModelExecutor = expr::ThreadSafePoolModelExecutor<Input, Output, SideOutput>; using CopyableThreadUnsafeModelExecutor = expr::CopyableThreadUnsafeModelExecutor<Input, Output, SideOutput>; using ToFunctionHelper = serving_impl::ToModelFunction<Input, Output, SideOutput>; protected: template <int Flags> using Func = std::conditional_t<Flags & ExprCompilerFlags::kEvalWithOptions, typename ToFunctionHelper::with_options, typename ToFunctionHelper::without_options>; public: using Function = Func<ExprCompilerFlags::kDefault>; using FunctionWithOptions = Func<ExprCompilerFlags::kEvalWithOptions>; using input_type = Input; using output_type = Output; using side_output_type = SideOutput; ExprCompilerBase(ExprCompilerBase&&) = default; ExprCompilerBase& operator=(ExprCompilerBase&&) = default; ExprCompilerBase(const ExprCompilerBase&) = delete; ExprCompilerBase& operator=(const ExprCompilerBase&) = delete; ExprCompilerBase() { const std::optional<expr::Optimizer>& opt = serving_impl::ExprCompilerDefaultOptimizer::get(); if (opt.has_value()) { SetExprOptimizer(*opt); } } Subclass& SetInputLoader( absl::StatusOr<InputLoaderPtr<Input>> input_loader_or) & { ASSIGN_OR_RETURN(input_loader_, std::move(input_loader_or), RegisterError(_ << "in ExprCompiler::SetInputLoader")); return subclass(); } Subclass&& SetInputLoader( absl::StatusOr<InputLoaderPtr<Input>> input_loader_or) && { return std::move(SetInputLoader(std::move(input_loader_or))); } Subclass& SetSlotListener( absl::StatusOr<std::unique_ptr<const SlotListener<SideOutput>>> slot_listener_or) & { ASSIGN_OR_RETURN(slot_listener_, std::move(slot_listener_or), RegisterError(_ << "in ExprCompiler::SlotListener")); return subclass(); } Subclass&& SetSlotListener( absl::StatusOr<std::unique_ptr<const SlotListener<SideOutput>>> slot_listener_or) && { return std::move(SetSlotListener(std::move(slot_listener_or))); } Subclass& SetAlwaysCloneThreadSafetyPolicy() & { thread_safety_policy_ = ThreadSafetyPolicy::kAlwaysClone; return subclass(); } Subclass&& SetAlwaysCloneThreadSafetyPolicy() && { return std::move(SetAlwaysCloneThreadSafetyPolicy()); } Subclass& SetPoolThreadSafetyPolicy() & { thread_safety_policy_ = ThreadSafetyPolicy::kPool; return subclass(); } Subclass&& SetPoolThreadSafetyPolicy() && { return std::move(SetPoolThreadSafetyPolicy()); } Subclass& SetThreadUnsafe_I_SWEAR_TO_COPY_MODEL_FUNCTION_BEFORE_CALL() & { thread_safety_policy_ = ThreadSafetyPolicy::kUnsafe; return subclass(); } Subclass&& SetThreadUnsafe_I_SWEAR_TO_COPY_MODEL_FUNCTION_BEFORE_CALL() && { return std::move( SetThreadUnsafe_I_SWEAR_TO_COPY_MODEL_FUNCTION_BEFORE_CALL()); } Subclass& SetExperimentalArenaAllocator(int64_t page_size_bytes = (64 << 10)) & { model_executor_options_.arena_page_size = page_size_bytes; return subclass(); } Subclass&& SetExperimentalArenaAllocator( int64_t page_size_bytes = (64 << 10)) && { return std::move(SetExperimentalArenaAllocator(page_size_bytes)); } Subclass& SetExprOptimizer(absl::StatusOr<expr::Optimizer> optimizer_or) & { ASSIGN_OR_RETURN(auto optimizer, std::move(optimizer_or), RegisterError(_ << "in ExprCompiler::SetExprOptimizer")); model_executor_options_.eval_options.optimizer = std::move(optimizer); return subclass(); } Subclass&& SetExprOptimizer(absl::StatusOr<expr::Optimizer> optimizer_or) && { return std::move(SetExprOptimizer(std::move(optimizer_or))); } Subclass& ForceNonOptionalOutput() & { model_executor_options_.force_non_optional_output = true; return subclass(); } Subclass&& ForceNonOptionalOutput() && { return std::move(ForceNonOptionalOutput()); } Subclass& AllowOutputCasting() & { model_executor_options_.allow_output_casting = true; return subclass(); } Subclass&& AllowOutputCasting() && { return std::move(AllowOutputCasting()); } Subclass& AllowSideOutputsCasting() & { model_executor_options_.allow_side_outputs_casting = true; return subclass(); } Subclass&& AllowSideOutputsCasting() && { return std::move(AllowSideOutputsCasting()); } Subclass& IgnoreNotListenedNamedOutputs() & { model_executor_options_.ignore_not_listened_named_outputs = true; return subclass(); } Subclass&& IgnoreNotListenedNamedOutputs() && { return std::move(IgnoreNotListenedNamedOutputs()); } template <int Flags = ExprCompilerFlags::kDefault> absl::StatusOr<Func<Flags>> Compile(const CompiledExpr& compiled_expr) const { RETURN_IF_ERROR(Validate()); ASSIGN_OR_RETURN( auto model_executor, ModelExecutor::Bind(compiled_expr, *input_loader_, nullptr, slot_listener_.get(), model_executor_options_)); ThreadSafetyPolicy thread_safety_policy = thread_safety_policy_; if (thread_safety_policy == ThreadSafetyPolicy::kUnspecified && dynamic_cast<const InplaceCompiledExpr*>(&compiled_expr) != nullptr) { thread_safety_policy = ThreadSafetyPolicy::kAlwaysClone; } return MakeFunction<Flags>(std::move(model_executor), thread_safety_policy); } template <int Flags = ExprCompilerFlags::kDefault> absl::StatusOr<Func<Flags>> Compile(const expr::ExprNodePtr& expr) const { RETURN_IF_ERROR(Validate()); ASSIGN_OR_RETURN( auto model_executor, ModelExecutor::Compile(expr, *input_loader_, slot_listener_.get(), model_executor_options_)); return MakeFunction<Flags>(std::move(model_executor), thread_safety_policy_); } template <int Flags = ExprCompilerFlags::kDefault> absl::StatusOr<Func<Flags>> Compile( const absl::StatusOr<expr::ExprNodePtr>& expr) const { RETURN_IF_ERROR(expr.status()); return Compile<Flags>(*expr); } template <int Flags = ExprCompilerFlags::kDefault> absl::StatusOr<Func<Flags>> CompileOperator( absl::StatusOr<expr::ExprOperatorPtr> op) const { RETURN_IF_ERROR(ValidateCompileOperator()); constexpr size_t arg_count = std::tuple_size_v<Input>; std::vector<std::string> arg_names(arg_count); std::vector<absl::StatusOr<expr::ExprNodePtr>> args(arg_count); for (size_t i = 0; i < arg_count; ++i) { arg_names[i] = absl::StrCat("a", i); args[i] = expr::Leaf(arg_names[i]); } ASSIGN_OR_RETURN(expr::ExprNodePtr expr, expr::CallOp(std::move(op), std::move(args))); ASSIGN_OR_RETURN(InputLoaderPtr<Input> input_loader, TupleInputLoader<Input>::Create(std::move(arg_names))); ASSIGN_OR_RETURN( auto model_executor, ModelExecutor::Compile(expr, *input_loader, slot_listener_.get(), model_executor_options_)); return MakeFunction<Flags>(std::move(model_executor), thread_safety_policy_); } template <int Flags = ExprCompilerFlags::kDefault> absl::StatusOr<Func<Flags>> CompileOperator( absl::StatusOr<expr::ExprOperatorPtr> op, absl::Span<const QTypePtr> input_types) const { static_assert(std::is_same_v<Input, absl::Span<const TypedRef>>, "CompilerOperator(op, types) requires Input to be " "absl::Span<const TypedRef>"); RETURN_IF_ERROR(ValidateCompileOperator()); std::vector<std::pair<std::string, QTypePtr>> args(input_types.size()); std::vector<absl::StatusOr<expr::ExprNodePtr>> arg_exprs(args.size()); for (size_t i = 0; i < input_types.size(); ++i) { args[i] = {absl::StrCat("a", i), input_types[i]}; arg_exprs[i] = expr::Leaf(args[i].first); } ASSIGN_OR_RETURN(expr::ExprNodePtr expr, expr::CallOp(std::move(op), std::move(arg_exprs))); InputLoaderPtr<Input> input_loader = CreateTypedRefsInputLoader(args); ASSIGN_OR_RETURN( auto model_executor, ModelExecutor::Compile(expr, *input_loader, slot_listener_.get(), model_executor_options_)); return MakeFunction<Flags>(std::move(model_executor), thread_safety_policy_); } protected: Subclass& RegisterError(absl::Status error) { if (first_error_.ok()) { first_error_ = std::move(error); } return subclass(); } private: enum class ThreadSafetyPolicy { kUnspecified, kAlwaysClone, kPool, kUnsafe }; static constexpr size_t kMaxStackSize = 1024; Subclass& subclass() { return *static_cast<Subclass*>(this); } template <size_t kStackSize, int Flags> static Func<Flags> MakeStackBasedFunction( std::shared_ptr<ModelExecutor> executor) { if constexpr (Flags & ExprCompilerFlags::kEvalWithOptions) { if constexpr (std::is_same_v<SideOutput, void>) { return [executor(std::move(executor))]( const ModelFunctionOptions& options, const Input& input) -> absl::StatusOr<Output> { return executor->template ExecuteOnStack<kStackSize>(options, input, nullptr); }; } else { return [executor(std::move(executor))]( const ModelFunctionOptions& options, const Input& input, SideOutput* side_output) -> absl::StatusOr<Output> { return executor->template ExecuteOnStack<kStackSize>(options, input, side_output); }; } } else { if constexpr (std::is_same_v<SideOutput, void>) { return [executor(std::move(executor))]( const Input& input) -> absl::StatusOr<Output> { return executor->template ExecuteOnStack<kStackSize>({}, input, nullptr); }; } else { return [executor(std::move(executor))]( const Input& input, SideOutput* side_output) -> absl::StatusOr<Output> { return executor->template ExecuteOnStack<kStackSize>({}, input, side_output); }; } } } template <int Flags> static Func<Flags> MakeAlwaysCloneFunction(ModelExecutor&& executor) { auto shared_executor = std::make_shared<ModelExecutor>(std::move(executor)); if (shared_executor->CanExecuteOnStack(kMaxStackSize)) { return MakeStackBasedFunction<kMaxStackSize, Flags>( std::move(shared_executor)); } if constexpr (Flags & ExprCompilerFlags::kEvalWithOptions) { if constexpr (std::is_same_v<SideOutput, void>) { return [executor(std::move(shared_executor))]( const ModelFunctionOptions& options, const Input& input) -> absl::StatusOr<Output> { return executor->ExecuteOnHeap(options, input, nullptr); }; } else { return [executor(std::move(shared_executor))]( const ModelFunctionOptions& options, const Input& input, SideOutput* side_output) -> absl::StatusOr<Output> { return executor->ExecuteOnHeap(options, input, side_output); }; } } else { if constexpr (std::is_same_v<SideOutput, void>) { return [executor(std::move(shared_executor))]( const Input& input) -> absl::StatusOr<Output> { return executor->ExecuteOnHeap({}, input, nullptr); }; } else { return [executor(std::move(shared_executor))]( const Input& input, SideOutput* side_output) -> absl::StatusOr<Output> { return executor->ExecuteOnHeap({}, input, side_output); }; } } } template <bool EvalWithOptions> static absl::StatusOr<Func<EvalWithOptions>> MakeFunction( ModelExecutor&& executor, ThreadSafetyPolicy thread_safety_policy) { switch (thread_safety_policy) { case ThreadSafetyPolicy::kAlwaysClone: return MakeAlwaysCloneFunction<EvalWithOptions>(std::move(executor)); case ThreadSafetyPolicy::kUnspecified: case ThreadSafetyPolicy::kPool: return Func<EvalWithOptions>( ThreadSafePoolModelExecutor(std::move(executor))); case ThreadSafetyPolicy::kUnsafe: return Func<EvalWithOptions>( CopyableThreadUnsafeModelExecutor(std::move(executor))); } return absl::InternalError( absl::StrCat("Unsupported ThreadSafetyPolicy: ", thread_safety_policy)); } absl::Status Validate() const { RETURN_IF_ERROR(first_error_); if (input_loader_ == nullptr) { return absl::FailedPreconditionError( "InputLoader is not specified, use ExprCompiler::SetInputLoader()"); } if (!std::is_same_v<SideOutput, void> && slot_listener_ == nullptr) { return absl::FailedPreconditionError( "SlotListener is not specified, use ExprCompiler::SetSlotListener() " "or ExprCompiler<...> without SideOutput template parameter"); } if (std::is_same_v<SideOutput, void> && slot_listener_ != nullptr) { return absl::FailedPreconditionError( "SlotListener with SideOutput==void is not supported by " "ExprCompiler"); } return absl::OkStatus(); } absl::Status ValidateCompileOperator() const { RETURN_IF_ERROR(first_error_); static_assert(std::is_same_v<SideOutput, void>, "SideOutput can not be used together with " "ExprCompiler::CompilerOperator"); if (input_loader_ != nullptr) { return absl::FailedPreconditionError( "InputLoader is specified, but not needed for " "ExprCompiler::CompilerOperator"); } return absl::OkStatus(); } absl::Status first_error_; InputLoaderPtr<Input> input_loader_ = nullptr; std::unique_ptr<const SlotListener<SideOutput>> slot_listener_ = nullptr; ThreadSafetyPolicy thread_safety_policy_ = ThreadSafetyPolicy::kUnspecified; expr::ModelExecutorOptions model_executor_options_; }; template <typename Input, typename Output, typename SideOutput = void> class ExprCompiler final : public ExprCompilerBase<ExprCompiler<Input, Output, SideOutput>, Input, Output, SideOutput> {}; template <typename Compiler, typename Model> absl::StatusOr<absl::flat_hash_map<std::string, typename Compiler::Function>> CompileExprSet(const Compiler& compiler, absl::flat_hash_map<std::string, Model> model_set) { using Function = typename Compiler::Function; absl::flat_hash_map<std::string, Function> compiled_models; compiled_models.reserve(model_set.size()); for (const auto& [name, model] : model_set) { ASSIGN_OR_RETURN(compiled_models[name], compiler.Compile(model), _ << "while initializing model \"" << name << "\""); } return compiled_models; } } #endif #include "arolla/serving/expr_compiler.h" #include <optional> #include "arolla/expr/optimization/optimizer.h" #include "arolla/util/indestructible.h" namespace arolla::serving_impl { Indestructible<std::optional<expr::Optimizer>> ExprCompilerDefaultOptimizer::optimizer_; }
#include "arolla/serving/expr_compiler.h" #include <functional> #include <memory> #include <optional> #include <string> #include <tuple> #include <type_traits> #include <utility> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/container/flat_hash_map.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/types/span.h" #include "arolla/expr/eval/eval.h" #include "arolla/expr/eval/thread_safe_model_executor.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/registered_expr_operator.h" #include "arolla/expr/testing/testing.h" #include "arolla/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/io/tuple_input_loader.h" #include "arolla/memory/optional_value.h" #include "arolla/qexpr/evaluation_engine.h" #include "arolla/qexpr/operators.h" #include "arolla/qexpr/simple_executable.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/typed_value.h" #include "arolla/util/init_arolla.h" #include "arolla/util/testing/status_matchers_backport.h" #include "arolla/util/status_macros_backport.h" namespace { using ::arolla::CompiledExpr; using ::arolla::GetQType; using ::arolla::InputLoaderPtr; using ::arolla::SlotListener; using ::arolla::expr::CallOp; using ::arolla::expr::ExprNodePtr; using ::arolla::expr::Leaf; using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::StatusIs; using ::arolla::testing::WithExportValueAnnotation; using ::testing::_; using ::testing::Eq; using ::testing::HasSubstr; using ::testing::IsNull; using ::testing::NotNull; using ::testing::Pair; using ::testing::UnorderedElementsAre; 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<SlotListener<TestSideOutput>>> CreateSlotListener() { return ::arolla::CreateAccessorsSlotListener<TestSideOutput>( "subtract", [](float x, TestSideOutput* out) { out->subtract = x; }); } absl::StatusOr<ExprNodePtr> CreateExpr() { 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<CompiledExpr>> CreateCompiledExpr() { 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 arolla { namespace { class TestInplaceCompiledExpr : public InplaceCompiledExpr { public: TestInplaceCompiledExpr() : InplaceCompiledExpr( {}, GetQType<float>(), {}) {} absl::StatusOr<std::unique_ptr<BoundExpr>> InplaceBind( const absl::flat_hash_map<std::string, TypedSlot>& input_slots, TypedSlot output_slot, const absl::flat_hash_map<std::string, TypedSlot>& named_output_slots) const final { return std::make_unique<SimpleBoundExpr>( input_slots, output_slot, std::vector<std::unique_ptr<BoundOperator>>{}, std::vector<std::unique_ptr<BoundOperator>>{}, named_output_slots); } }; class ExprCompilerTest : public ::testing::Test { public: void SetUp() override { ASSERT_OK(InitArolla()); ASSERT_OK_AND_ASSIGN(auto add_expr, expr::CallOp("math.add", {Leaf("x"), Leaf("y")})); ASSERT_OK_AND_ASSIGN(auto subtract_expr, expr::CallOp("math.subtract", {Leaf("x"), Leaf("y")})); ASSERT_OK_AND_ASSIGN(expr_, CreateExpr()); ASSERT_OK_AND_ASSIGN(compiled_expr_, CreateCompiledExpr()); } expr::ExprNodePtr expr_; std::unique_ptr<const CompiledExpr> compiled_expr_; }; TEST_F(ExprCompilerTest, CompileExprNodePtr) { ASSERT_OK_AND_ASSIGN(auto model, (ExprCompiler<TestInput, std::optional<float>>()) .SetInputLoader(CreateInputLoader()) .AllowOutputCasting() .Compile(expr_)); ASSERT_OK_AND_ASSIGN( auto model_with_options, (ExprCompiler<TestInput, std::optional<float>>()) .SetInputLoader(CreateInputLoader()) .AllowOutputCasting() .Compile<ExprCompilerFlags::kEvalWithOptions>(expr_)); static_assert( std::is_same_v<decltype(model), std::function<absl::StatusOr<std::optional<float>>( const TestInput&)>>); static_assert( std::is_same_v<decltype(model_with_options), std::function<absl::StatusOr<std::optional<float>>( const ModelFunctionOptions&, const TestInput&)>>); TestInput input{.x = 28, .y = 29}; EXPECT_THAT(model(input), IsOkAndHolds(57)); EXPECT_THAT(model_with_options({}, input), IsOkAndHolds(57)); } TEST_F(ExprCompilerTest, CompileExprNodePtrWithSideOutput) { ASSERT_OK_AND_ASSIGN( auto model, (ExprCompiler<TestInput, std::optional<float>, TestSideOutput>()) .SetInputLoader(CreateInputLoader()) .SetSlotListener(CreateSlotListener()) .AllowOutputCasting() .Compile(expr_)); static_assert( std::is_same_v<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)); } TEST_F(ExprCompilerTest, CompileCompiledExpr) { ASSERT_OK_AND_ASSIGN(auto model, (ExprCompiler<TestInput, std::optional<float>>()) .SetInputLoader(CreateInputLoader()) .AllowOutputCasting() .Compile(*compiled_expr_)); static_assert( std::is_same_v<decltype(model), std::function<absl::StatusOr<std::optional<float>>( const TestInput&)>>); TestInput input{.x = 28, .y = 29}; EXPECT_THAT(model(input), IsOkAndHolds(57)); } TEST_F(ExprCompilerTest, CompileCompiledExprForceNonOptionalOutput) { ASSERT_OK_AND_ASSIGN(auto model, (ExprCompiler<TestInput, float>()) .SetInputLoader(CreateInputLoader()) .ForceNonOptionalOutput() .Compile(*compiled_expr_)); static_assert( std::is_same_v<decltype(model), std::function<absl::StatusOr<float>(const TestInput&)>>); TestInput input{.x = 28, .y = 29}; EXPECT_THAT(model(input), IsOkAndHolds(57)); } TEST_F(ExprCompilerTest, CompileCompiledExprWithSideOutput) { ASSERT_OK_AND_ASSIGN( auto model, (ExprCompiler<TestInput, std::optional<float>, TestSideOutput>()) .SetInputLoader(CreateInputLoader()) .SetSlotListener(CreateSlotListener()) .AllowOutputCasting() .Compile(*compiled_expr_)); static_assert( std::is_same_v<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)); } TEST_F(ExprCompilerTest, CompileExprOperatorWithTuple) { ASSERT_OK_AND_ASSIGN(auto model, (ExprCompiler<std::tuple<float, float>, float>()) .CompileOperator(expr::LookupOperator("math.add"))); static_assert( std::is_same_v<decltype(model), std::function<absl::StatusOr<float>( const std::tuple<float, float>&)>>); EXPECT_THAT(model({28, 29}), IsOkAndHolds(57)); } TEST_F(ExprCompilerTest, CompileExprOperatorWithTypedRefs) { ASSERT_OK_AND_ASSIGN( auto model, (ExprCompiler<absl::Span<const TypedRef>, TypedValue>()) .CompileOperator(expr::LookupOperator("math.add"), {GetQType<float>(), GetQType<float>()})); static_assert( std::is_same_v<decltype(model), std::function<absl::StatusOr<TypedValue>( const absl::Span<const TypedRef>&)>>); auto a = TypedValue::FromValue<float>(28); auto b = TypedValue::FromValue<float>(29); std::vector<TypedRef> args{a.AsRef(), b.AsRef()}; ASSERT_OK_AND_ASSIGN(TypedValue res, model(args)); EXPECT_THAT(res.As<float>(), IsOkAndHolds(57)); } TEST_F(ExprCompilerTest, Ownership) { ExprCompiler<TestInput, std::optional<float>, TestSideOutput> mc; mc.SetInputLoader(CreateInputLoader()); ExprCompiler<TestInput, std::optional<float>, TestSideOutput> other_mc = std::move(mc); other_mc.SetSlotListener(CreateSlotListener()); mc = std::move(other_mc); mc.AllowOutputCasting(); ASSERT_OK(mc.Compile(expr_)); } TEST_F(ExprCompilerTest, Move) { auto set_input_loader = [](auto mc) { return std::move(mc).SetInputLoader(CreateInputLoader()); }; ASSERT_OK_AND_ASSIGN( auto model, set_input_loader( ExprCompiler<TestInput, std::optional<float>, TestSideOutput>() .SetSlotListener(CreateSlotListener())) .SetExperimentalArenaAllocator() .AllowOutputCasting() .Compile(expr_)); TestInput input{.x = 28, .y = 29}; EXPECT_THAT(model(input, nullptr), IsOkAndHolds(57)); } TEST_F(ExprCompilerTest, Optimizer) { auto replace_add_with_subtract = [](expr::ExprNodePtr x) -> absl::StatusOr<expr::ExprNodePtr> { if (expr::IsBackendOperator(*expr::DecayRegisteredOperator(x->op()), "math.add")) { return expr::WithNewOperator(std::move(x), *expr::LookupOperator("math.subtract")); } return x; }; ASSERT_OK_AND_ASSIGN(auto model, (ExprCompiler<TestInput, std::optional<float>>()) .SetInputLoader(CreateInputLoader()) .SetExprOptimizer(replace_add_with_subtract) .AllowOutputCasting() .Compile(expr_)); TestInput input{.x = 28, .y = 29}; EXPECT_THAT(model(input), IsOkAndHolds(-1)); } TEST_F(ExprCompilerTest, OtherOptionsSmokeTest) { ASSERT_OK_AND_ASSIGN( auto model, (ExprCompiler<TestInput, std::optional<float>, TestSideOutput>()) .SetInputLoader(CreateInputLoader()) .SetSlotListener(CreateSlotListener()) .SetExperimentalArenaAllocator() .SetAlwaysCloneThreadSafetyPolicy() .AllowOutputCasting() .Compile(expr_)); 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)); } TEST_F(ExprCompilerTest, DefaultThreadSafetyPolicy) { ASSERT_OK_AND_ASSIGN( auto model, (ExprCompiler<TestInput, std::optional<float>, TestSideOutput>()) .SetInputLoader(CreateInputLoader()) .SetSlotListener(CreateSlotListener()) .AllowOutputCasting() .Compile(expr_)); TestInput input{.x = 28, .y = 29}; TestSideOutput side_output; EXPECT_THAT(model(input, &side_output), IsOkAndHolds(57)); EXPECT_THAT(side_output.subtract, Eq(-1)); EXPECT_THAT((model.target<expr::ThreadSafePoolModelExecutor< TestInput, std::optional<float>, TestSideOutput>>()), NotNull()); } TEST_F(ExprCompilerTest, DefaultThreadSafetyPolicy_Codegen) { ASSERT_OK_AND_ASSIGN(auto eval_model, (ExprCompiler<TestInput, float>()) .SetInputLoader(CreateInputLoader()) .Compile(*compiled_expr_)); ASSERT_OK_AND_ASSIGN(auto codegen_model, (ExprCompiler<TestInput, float>()) .SetInputLoader(CreateInputLoader()) .Compile(TestInplaceCompiledExpr())); EXPECT_THAT( (eval_model .target<expr::ThreadSafePoolModelExecutor<TestInput, float>>()), NotNull()); EXPECT_THAT( (codegen_model .target<expr::ThreadSafePoolModelExecutor<TestInput, float>>()), IsNull()); } TEST_F(ExprCompilerTest, PoolThreadSafetyPolicy) { ASSERT_OK_AND_ASSIGN( auto model, (ExprCompiler<TestInput, std::optional<float>, TestSideOutput>()) .SetInputLoader(CreateInputLoader()) .SetSlotListener(CreateSlotListener()) .SetPoolThreadSafetyPolicy() .AllowOutputCasting() .Compile(expr_)); TestInput input{.x = 28, .y = 29}; TestSideOutput side_output; EXPECT_THAT(model(input, &side_output), IsOkAndHolds(57)); EXPECT_THAT(side_output.subtract, Eq(-1)); EXPECT_THAT((model.target<expr::ThreadSafePoolModelExecutor< TestInput, std::optional<float>, TestSideOutput>>()), NotNull()); } TEST_F(ExprCompilerTest, AlwaysCloneThreadSafetyPolicy) { ASSERT_OK_AND_ASSIGN( auto model, (ExprCompiler<TestInput, std::optional<float>, TestSideOutput>()) .SetInputLoader(CreateInputLoader()) .SetSlotListener(CreateSlotListener()) .SetAlwaysCloneThreadSafetyPolicy() .AllowOutputCasting() .Compile(expr_)); TestInput input{.x = 28, .y = 29}; TestSideOutput side_output; EXPECT_THAT(model(input, &side_output), IsOkAndHolds(57)); EXPECT_THAT(side_output.subtract, Eq(-1)); } TEST_F(ExprCompilerTest, ThreadUnsafe) { ASSERT_OK_AND_ASSIGN( auto model, (ExprCompiler<TestInput, std::optional<float>, TestSideOutput>()) .SetInputLoader(CreateInputLoader()) .SetSlotListener(CreateSlotListener()) .SetThreadUnsafe_I_SWEAR_TO_COPY_MODEL_FUNCTION_BEFORE_CALL() .AllowOutputCasting() .Compile(expr_)); TestInput input{.x = 28, .y = 29}; TestSideOutput side_output; EXPECT_THAT(model(input, &side_output), IsOkAndHolds(57)); EXPECT_THAT(side_output.subtract, Eq(-1)); } TEST_F(ExprCompilerTest, ForceNonOptionalOutput) { ASSERT_OK_AND_ASSIGN(auto expr, CallOp("math.neg", {Leaf("x")})); ASSERT_OK_AND_ASSIGN( auto input_loader, ::arolla::CreateAccessorsInputLoader<std::optional<float>>( "x", [](const auto& x) { return OptionalValue<float>(x); })); ASSERT_OK_AND_ASSIGN( auto model, (ExprCompiler<std::optional<float>, std::optional<float>>()) .SetInputLoader(MakeNotOwningInputLoader(input_loader.get())) .Compile(expr)); EXPECT_THAT(model(std::nullopt), IsOkAndHolds(std::nullopt)); EXPECT_THAT((ExprCompiler<std::optional<float>, float>()) .SetInputLoader(MakeNotOwningInputLoader(input_loader.get())) .AllowOutputCasting() .Compile(expr), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("model output is deduced to optional, while " "non-optional is requested"))); ASSERT_OK_AND_ASSIGN( auto full_model, (ExprCompiler<std::optional<float>, float>()) .SetInputLoader(MakeNotOwningInputLoader(input_loader.get())) .ForceNonOptionalOutput() .Compile(expr)); EXPECT_THAT(full_model(-57), IsOkAndHolds(57)); EXPECT_THAT(full_model(std::nullopt), StatusIs(absl::StatusCode::kFailedPrecondition, HasSubstr("expects a present value, got missing"))); } class VoidSlotListener : public StaticSlotListener<void> { public: VoidSlotListener(): StaticSlotListener<void>({}) {} absl::StatusOr<BoundSlotListener<Output>> BindImpl( const absl::flat_hash_map<std::string, TypedSlot>& input_slots) const final { return absl::UnimplementedError("unimplemented"); } private: }; TEST_F(ExprCompilerTest, Errors) { EXPECT_THAT((ExprCompiler<TestInput, std::optional<float>, TestSideOutput>()) .SetSlotListener(CreateSlotListener()) .Compile(expr_), StatusIs(absl::StatusCode::kFailedPrecondition, HasSubstr("InputLoader is not specified, use " "ExprCompiler::SetInputLoader()"))); EXPECT_THAT( (ExprCompiler<TestInput, std::optional<float>, TestSideOutput>()) .SetInputLoader(CreateInputLoader()) .Compile(expr_), StatusIs(absl::StatusCode::kFailedPrecondition, HasSubstr("SlotListener is not specified, use " "ExprCompiler::SetSlotListener() or ExprCompiler<...> " "without SideOutput template parameter"))); EXPECT_THAT((ExprCompiler<TestInput, std::optional<float>, void>()) .SetInputLoader(CreateInputLoader()) .SetSlotListener(std::unique_ptr<SlotListener<void>>( new VoidSlotListener())) .Compile(expr_), StatusIs(absl::StatusCode::kFailedPrecondition, HasSubstr("SlotListener with SideOutput==void is not " "supported by ExprCompiler"))); EXPECT_THAT( (ExprCompiler<std::tuple<float, float>, std::optional<float>>()) .SetInputLoader( TupleInputLoader<std::tuple<float, float>>::Create({"x", "y"})) .CompileOperator(nullptr), StatusIs(absl::StatusCode::kFailedPrecondition, HasSubstr("InputLoader is specified, but not needed for " "ExprCompiler::CompilerOperator"))); } TEST_F(ExprCompilerTest, CompileExprSet) { ASSERT_OK_AND_ASSIGN( auto models, CompileExprSet( ExprCompiler<TestInput, std::optional<float>>() .SetInputLoader(CreateInputLoader()) .AllowOutputCasting(), absl::flat_hash_map<std::string, absl::StatusOr<expr::ExprNodePtr>>{ {"first", expr_}, {"second", expr_}})); ASSERT_THAT(models, UnorderedElementsAre(Pair("first", _), Pair("second", _))); static_assert( std::is_same_v<std::decay_t<decltype(models[""])>, std::function<absl::StatusOr<std::optional<float>>( const TestInput&)>>); TestInput input{.x = 28, .y = 29}; EXPECT_THAT(models["first"](input), IsOkAndHolds(57)); } TEST_F(ExprCompilerTest, CompileExprSet_Errors) { EXPECT_THAT( CompileExprSet( ExprCompiler<TestInput, std::optional<float>>() .SetInputLoader(CreateInputLoader()) .AllowOutputCasting(), absl::flat_hash_map<std::string, absl::StatusOr<expr::ExprNodePtr>>{ {"first", expr_}, {"bad_model", absl::FailedPreconditionError("very bad model")}}), StatusIs(absl::StatusCode::kFailedPrecondition, "very bad model; while initializing model \"bad_model\"")); } } }
2,354
cpp
google/arolla
operator_errors
arolla/qexpr/operator_errors.cc
arolla/qexpr/operator_errors_test.cc
#ifndef AROLLA_QEXPR_OPERATOR_ERRORS_H_ #define AROLLA_QEXPR_OPERATOR_ERRORS_H_ #include <string> #include "absl/status/status.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 { absl::Status OperatorNotDefinedError(absl::string_view operator_name, absl::Span<const QTypePtr> input_types, absl::string_view extra_message = ""); absl::Status VerifyInputSlotTypes(absl::Span<const TypedSlot> slots, absl::Span<const QTypePtr> expected_types, absl::string_view operator_name); absl::Status VerifyOutputSlotType(TypedSlot slot, QTypePtr expected_type, absl::string_view operator_name); absl::Status VerifyInputValueTypes(absl::Span<const TypedValue> values, absl::Span<const QTypePtr> expected_types, absl::string_view operator_name); absl::Status VerifyInputValueTypes(absl::Span<const TypedRef> values, absl::Span<const QTypePtr> expected_types, absl::string_view operator_name); absl::Status VerifyOutputValueType(const TypedValue& value, QTypePtr expected_type, absl::string_view operator_name); std::string GuessLibraryName(absl::string_view operator_name); std::string GuessOperatorLibraryName(absl::string_view operator_name); std::string SuggestMissingDependency(); std::string SuggestAvailableOverloads( absl::string_view operator_name, absl::Span<const QExprOperatorSignature* const> supported_qtypes); } #endif #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 operator_name, 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 for operator %s: expected %s, got %s", slots_kind, operator_name, 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 operator_name, absl::string_view slots_kind) { if (objects.size() != expected_types.size()) { return SlotTypesMismatchError(operator_name, slots_kind, expected_types, GetQTypes(objects)); } for (size_t i = 0; i < objects.size(); ++i) { if (objects[i].GetType() != expected_types[i]) { return SlotTypesMismatchError(operator_name, 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, absl::string_view operator_name) { return VerifyTypes(slots, expected_types, operator_name, "input"); } absl::Status VerifyOutputSlotType(TypedSlot slot, QTypePtr expected_type, absl::string_view operator_name) { return VerifyTypes<TypedSlot>({slot}, {expected_type}, operator_name, "output"); } absl::Status VerifyInputValueTypes(absl::Span<const TypedValue> values, absl::Span<const QTypePtr> expected_types, absl::string_view operator_name) { return VerifyTypes(values, expected_types, operator_name, "input"); } absl::Status VerifyInputValueTypes(absl::Span<const TypedRef> values, absl::Span<const QTypePtr> expected_types, absl::string_view operator_name) { return VerifyTypes(values, expected_types, operator_name, "input"); } absl::Status VerifyOutputValueType(const TypedValue& value, QTypePtr expected_type, absl::string_view operator_name) { return VerifyTypes<TypedValue>({value}, {expected_type}, operator_name, "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/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" #include "arolla/util/testing/status_matchers_backport.h" namespace arolla { namespace { using ::arolla::testing::IsOk; using ::arolla::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) { absl::string_view op_name = "test.Not"; 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>()}, op_name), IsOk()); EXPECT_THAT( VerifyInputSlotTypes(ToTypedSlots(int_slot, double_slot), {GetQType<int>(), GetQType<float>()}, op_name), StatusIs(absl::StatusCode::kFailedPrecondition, "incorrect input types for operator test.Not: expected " "(INT32,FLOAT32), got (INT32,FLOAT64)")); } TEST(OperatorErrorsTest, VerifyValueTypes) { absl::string_view op_name = "test.Not"; auto int_value = TypedValue::FromValue(57); auto double_value = TypedValue::FromValue(5.7); EXPECT_THAT( VerifyInputValueTypes({int_value, double_value}, {GetQType<int>(), GetQType<double>()}, op_name), IsOk()); EXPECT_THAT( VerifyInputValueTypes({int_value, double_value}, {GetQType<int>(), GetQType<float>()}, op_name), StatusIs(absl::StatusCode::kFailedPrecondition, "incorrect input types for operator test.Not: 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(" } } }
2,355
cpp
google/arolla
casting
arolla/expr/eval/casting.cc
arolla/expr/eval/casting_test.cc
#ifndef AROLLA_EXPR_EVAL_CASTING_H_ #define AROLLA_EXPR_EVAL_CASTING_H_ #include "absl/status/statusor.h" #include "arolla/expr/eval/eval.h" #include "arolla/expr/expr_node.h" namespace arolla::expr::eval_internal { absl::StatusOr<ExprNodePtr> CastingTransformation( const DynamicEvaluationEngineOptions& options, ExprNodePtr expr); } #endif #include "arolla/expr/eval/casting.h" #include <cstddef> #include <memory> #include <optional> #include <utility> #include <vector> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "absl/types/span.h" #include "arolla/expr/derived_qtype_cast_operator.h" #include "arolla/expr/eval/eval.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_debug_string.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/operators/casting_registry.h" #include "arolla/expr/registered_expr_operator.h" #include "arolla/qexpr/operators.h" #include "arolla/qtype/array_like/array_like_qtype.h" #include "arolla/qtype/derived_qtype.h" #include "arolla/qtype/qtype.h" #include "arolla/util/status_macros_backport.h" namespace arolla::expr::eval_internal { namespace { absl::StatusOr<std::vector<QTypePtr>> GetQTypesFromNodeDeps( const ExprNodePtr& expr) { std::vector<QTypePtr> qtypes; qtypes.reserve(expr->node_deps().size()); for (int i = 0; i < expr->node_deps().size(); i++) { const auto* qtype = expr->node_deps()[i]->qtype(); if (qtype == nullptr) { return absl::InternalError( absl::StrFormat("QType not set for %i-th argument of node %s", i, ToDebugString(expr))); } qtypes.push_back(qtype); } return qtypes; } absl::StatusOr<std::optional<ExprNodePtr>> GetShapeForBroadcasting( absl::Span<const ExprNodePtr> deps) { ExprNodePtr array_dep_or = nullptr; for (const auto& dep : deps) { if (IsArrayLikeQType(dep->qtype())) { array_dep_or = dep; break; } } if (array_dep_or != nullptr) { return CallOp("core.shape_of", {array_dep_or}); } return std::nullopt; } absl::StatusOr<std::vector<ExprNodePtr>> BuildNodeDepsWithCasts( absl::Span<const ExprNodePtr> deps, absl::Span<const QTypePtr> dep_types, absl::Span<const QTypePtr> required_types) { const auto* casting_registry = expr_operators::CastingRegistry::GetInstance(); ASSIGN_OR_RETURN(std::optional<ExprNodePtr> shape_for_broadcasting, GetShapeForBroadcasting(deps)); std::vector<ExprNodePtr> new_deps; new_deps.reserve(deps.size()); for (size_t i = 0; i < deps.size(); ++i) { auto dep = deps[i]; if (dep->qtype() != required_types[i]) { ASSIGN_OR_RETURN(dep, casting_registry->GetCast(dep, required_types[i], true, shape_for_broadcasting), _ << "while casting arguments " << FormatTypeVector(dep_types) << " into " << FormatTypeVector(required_types)); } new_deps.push_back(std::move(dep)); } return new_deps; } } absl::StatusOr<ExprNodePtr> CastingTransformation( const DynamicEvaluationEngineOptions& options, ExprNodePtr expr) { const OperatorDirectory& backend_operators = options.operator_directory != nullptr ? *options.operator_directory : *OperatorRegistry::GetInstance(); if (!expr->is_op()) { return expr; } ASSIGN_OR_RETURN(auto op, DecayRegisteredOperator(expr->op())); if (!HasBackendExprOperatorTag(op)) { return expr; } auto backend_op_name = op->display_name(); ASSIGN_OR_RETURN(auto dep_types, GetQTypesFromNodeDeps(expr)); QTypePtr result_qtype = expr->qtype(); if (result_qtype == nullptr) { return absl::InternalError( "all QTypes must be known before the casting compilation step"); } ASSIGN_OR_RETURN( auto backend_op, backend_operators.LookupOperator(backend_op_name, dep_types, result_qtype), expr); auto* backend_op_signature = backend_op->signature(); if (backend_op_signature->input_types() != dep_types) { ASSIGN_OR_RETURN(auto cast_deps, BuildNodeDepsWithCasts( expr->node_deps(), dep_types, backend_op_signature->input_types())); ASSIGN_OR_RETURN(expr, WithNewDependencies(expr, std::move(cast_deps))); if (expr->qtype() != DecayDerivedQType(result_qtype)) { return absl::FailedPreconditionError(absl::StrFormat( "expr output QType changed after input casting: was %s, became %s", result_qtype->name(), expr->qtype()->name())); } } if (backend_op_signature->output_type() == result_qtype) { return expr; } if (backend_op_signature->output_type() == DecayDerivedQType(result_qtype)) { auto downcast_op = std::make_shared<expr::DerivedQTypeDowncastOperator>(result_qtype); return CallOp(downcast_op, {expr}); } return absl::FailedPreconditionError(absl::StrFormat( "inconsistent output types for QExpr and expr %s operator: %s", backend_op_name, JoinTypeNames({result_qtype, backend_op_signature->output_type()}))); } }
#include "arolla/expr/eval/casting.h" #include <memory> #include <utility> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "arolla/dense_array/dense_array.h" #include "arolla/dense_array/qtype/types.h" #include "arolla/expr/derived_qtype_cast_operator.h" #include "arolla/expr/eval/eval.h" #include "arolla/expr/expr.h" #include "arolla/expr/testing/testing.h" #include "arolla/qexpr/operator_factory.h" #include "arolla/qexpr/operators.h" #include "arolla/qtype/optional_qtype.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/typed_value.h" #include "arolla/qtype/weak_qtype.h" #include "arolla/util/init_arolla.h" #include "arolla/util/testing/status_matchers_backport.h" #include "arolla/util/text.h" #include "arolla/util/status_macros_backport.h" namespace arolla::expr::eval_internal { namespace { using ::arolla::testing::EqualsExpr; using ::arolla::testing::WithQTypeAnnotation; using ::testing::Test; template <typename T> absl::Status AddFakeAddOperator(OperatorRegistry& registry) { ASSIGN_OR_RETURN( auto op, OperatorFactory().WithName("math.add").BuildFromFunction([](T x, T) { return x; })); return registry.RegisterOperator(std::move(op)); } absl::Status AddFakeLowerOperator(OperatorRegistry& registry) { ASSIGN_OR_RETURN( auto op, OperatorFactory().WithName("strings.lower").BuildFromFunction([](Text x) { return x; })); return registry.RegisterOperator(std::move(op)); } class CastingTest : public Test { protected: void SetUp() override { ASSERT_OK(InitArolla()); backend_directory_ = std::make_shared<OperatorRegistry>(); ASSERT_OK(AddFakeAddOperator<float>(*backend_directory_)); ASSERT_OK(AddFakeAddOperator<double>(*backend_directory_)); ASSERT_OK(AddFakeAddOperator<DenseArray<float>>(*backend_directory_)); ASSERT_OK(AddFakeAddOperator<DenseArray<double>>(*backend_directory_)); ASSERT_OK(AddFakeLowerOperator(*backend_directory_)); options_ = DynamicEvaluationEngineOptions{.operator_directory = backend_directory_.get()}; } const QTypePtr f32_ = GetQType<float>(); const QTypePtr f64_ = GetQType<double>(); const QTypePtr of64_ = GetOptionalQType<double>(); const QTypePtr text_ = GetQType<Text>(); std::shared_ptr<OperatorRegistry> backend_directory_; DynamicEvaluationEngineOptions options_; }; TEST_F(CastingTest, Basic) { ASSERT_OK_AND_ASSIGN(auto expr, CallOp("math.add", {Literal<double>(2.), Literal<float>(1.f)})); ASSERT_OK_AND_ASSIGN( auto cast_expr, CallOp("math.add", {Literal<double>(2.), CallOp("core.to_float64", {Literal<float>(1.f)})})); ASSERT_OK_AND_ASSIGN(auto actual_expr, CastingTransformation(options_, expr)); EXPECT_THAT(actual_expr, EqualsExpr(cast_expr)); } TEST_F(CastingTest, WithOutputCasting_WeakFloat) { ASSERT_OK_AND_ASSIGN(auto weak_1, TypedValue::FromValueWithQType(1., GetWeakFloatQType())); ASSERT_OK_AND_ASSIGN(auto weak_2, TypedValue::FromValueWithQType(2., GetWeakFloatQType())); ASSERT_OK_AND_ASSIGN(auto expr, CallOp("math.add", {Literal(weak_1), Literal(weak_2)})); const auto upcast_op = std::make_shared<expr::DerivedQTypeUpcastOperator>(GetWeakFloatQType()); const auto downcast_op = std::make_shared<expr::DerivedQTypeDowncastOperator>(GetWeakFloatQType()); ASSERT_OK_AND_ASSIGN( auto cast_expr, CallOp(downcast_op, {CallOp("math.add", {CallOp(upcast_op, {Literal(weak_1)}), CallOp(upcast_op, {Literal(weak_2)})})})); ASSERT_OK_AND_ASSIGN(auto actual_expr, CastingTransformation(options_, expr)); EXPECT_THAT(actual_expr, EqualsExpr(cast_expr)); } TEST_F(CastingTest, WithOutputCasting_WeakFloatArray) { auto x = WithQTypeAnnotation(Leaf("x"), GetDenseArrayWeakFloatQType()); auto y = WithQTypeAnnotation(Leaf("y"), GetDenseArrayWeakFloatQType()); ASSERT_OK_AND_ASSIGN(auto expr, CallOp("math.add", {x, y})); const auto upcast_op = std::make_shared<expr::DerivedQTypeUpcastOperator>( GetDenseArrayWeakFloatQType()); const auto downcast_op = std::make_shared<expr::DerivedQTypeDowncastOperator>( GetDenseArrayWeakFloatQType()); ASSERT_OK_AND_ASSIGN( auto cast_expr, CallOp(downcast_op, {CallOp("math.add", {CallOp(upcast_op, {x}), CallOp(upcast_op, {y})})})); ASSERT_OK_AND_ASSIGN(auto actual_expr, CastingTransformation(options_, expr)); EXPECT_THAT(actual_expr, EqualsExpr(cast_expr)); } TEST_F(CastingTest, PassThroughSupportedOperator) { auto x = WithQTypeAnnotation(Leaf("x"), GetDenseArrayQType<double>()); auto y = WithQTypeAnnotation(Leaf("x"), GetDenseArrayQType<double>()); ASSERT_OK_AND_ASSIGN(auto expr, CallOp("math.add", {x, y})); EXPECT_THAT(CastingTransformation(options_, expr), IsOkAndHolds(EqualsExpr(expr))); } TEST_F(CastingTest, CastDenseArrayToDoubleOperator) { auto x = WithQTypeAnnotation(Leaf("x"), GetDenseArrayQType<float>()); auto y = WithQTypeAnnotation(Leaf("x"), GetDenseArrayQType<double>()); ASSERT_OK_AND_ASSIGN(auto expr, CallOp("math.add", {x, y})); ASSERT_OK_AND_ASSIGN(auto expected_expr, CallOp("math.add", {CallOp("core.to_float64", {x}), y})); EXPECT_THAT(CastingTransformation(options_, expr), IsOkAndHolds(EqualsExpr(expected_expr))); } TEST_F(CastingTest, Broadcasting) { auto x = WithQTypeAnnotation(Leaf("x"), f64_); auto y = WithQTypeAnnotation(Leaf("x"), GetDenseArrayQType<double>()); ASSERT_OK_AND_ASSIGN(auto expr, CallOp("math.add", {x, y})); EXPECT_THAT(CastingTransformation(options_, expr), IsOkAndHolds(EqualsExpr( CallOp("math.add", {CallOp("core.const_with_shape", {CallOp("core.shape_of", {y}), x}), y})))); } TEST_F(CastingTest, BroadcastingWithCasting) { auto x = WithQTypeAnnotation(Leaf("x"), f32_); auto y = WithQTypeAnnotation(Leaf("x"), GetDenseArrayQType<double>()); ASSERT_OK_AND_ASSIGN(auto expr, CallOp("math.add", {x, y})); EXPECT_THAT(CastingTransformation(options_, expr), IsOkAndHolds(EqualsExpr( CallOp("math.add", {CallOp("core.const_with_shape", {CallOp("core.shape_of", {y}), CallOp("core.to_float64", {x})}), y})))); } TEST_F(CastingTest, BroadcastingWithCastingToOptional) { auto x = WithQTypeAnnotation(Leaf("x"), of64_); auto y = WithQTypeAnnotation(Leaf("x"), GetDenseArrayQType<double>()); ASSERT_OK_AND_ASSIGN(auto expr, CallOp("math.add", {x, y})); EXPECT_THAT(CastingTransformation(options_, expr), IsOkAndHolds(EqualsExpr( CallOp("math.add", {CallOp("core.const_with_shape", {CallOp("core.shape_of", {y}), x}), y})))); } } }
2,356
cpp
google/arolla
operator_factory
arolla/qexpr/operator_factory.cc
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/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/strings/string_view.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 { class OperatorFactory { public: OperatorFactory& WithName(std::string name); template <typename FUNC> absl::StatusOr<OperatorPtr> BuildFromFunction(FUNC func) const; template <typename FUNC> absl::StatusOr<OperatorPtr> BuildFromFunction( FUNC func, const QExprOperatorSignature* signature) const; template <typename FUNC, typename... ARG_Ts> absl::StatusOr<OperatorPtr> BuildFromFunctor() const; private: template <typename CTX_FUNC, typename... ARGs> absl::StatusOr<OperatorPtr> BuildFromFunctionImpl( CTX_FUNC func, const QExprOperatorSignature* signature, meta::type_list<ARGs...>) const; absl::StatusOr<std::string> name_; }; 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(std::string name, const QExprOperatorSignature* qtype, CTX_FUNC func) : QExprOperator(std::move(name), qtype), 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 FUNC> absl::StatusOr<OperatorPtr> OperatorFactory::BuildFromFunction( FUNC func) const { auto context_func = operator_factory_impl::WrapIntoContextFunc( std::move(func), typename meta::function_traits<FUNC>::arg_types()); using CtxFunc = decltype(context_func); const QExprOperatorSignature* qtype = operator_factory_impl::DeduceOperatorSignature<CtxFunc>(); return BuildFromFunctionImpl( std::move(context_func), qtype, meta::tail_t<typename meta::function_traits<CtxFunc>::arg_types>()); } template <typename FUNC> absl::StatusOr<OperatorPtr> OperatorFactory::BuildFromFunction( FUNC func, const QExprOperatorSignature* qtype) const { 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>(qtype)); return BuildFromFunctionImpl( std::move(context_func), qtype, meta::tail_t<typename meta::function_traits<CtxFunc>::arg_types>()); } template <typename FUNC, typename... ARG_Ts> absl::StatusOr<OperatorPtr> OperatorFactory::BuildFromFunctor() const { return BuildFromFunction([](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 CTX_FUNC, typename... ARGs> absl::StatusOr<OperatorPtr> OperatorFactory::BuildFromFunctionImpl( CTX_FUNC func, const QExprOperatorSignature* qtype, meta::type_list<ARGs...>) const { if (name_.status().code() == absl::StatusCode::kUnknown) { return absl::Status(absl::StatusCode::kFailedPrecondition, "operator name should be specified"); } RETURN_IF_ERROR(name_.status()); return OperatorPtr{std::make_shared<operator_factory_impl::OpImpl< CTX_FUNC, typename meta::function_traits<CTX_FUNC>::return_type, ARGs...>>(*name_, qtype, std::move(func))}; } } #endif #include "arolla/qexpr/operator_factory.h" #include <string> #include <utility> #include "absl/status/status.h" #include "absl/strings/str_format.h" #include "arolla/util/operator_name.h" namespace arolla { OperatorFactory& OperatorFactory::WithName(std::string name) { if (IsOperatorName(name)) { name_ = std::move(name); } else { name_ = absl::InvalidArgumentError( absl::StrFormat("incorrect operator name \"%s\"", name)); } return *this; } }
#include "arolla/qexpr/operator_factory.h" #include <cstdint> #include <tuple> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "arolla/qexpr/eval_context.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" #include "arolla/util/testing/status_matchers_backport.h" namespace arolla { using ::arolla::testing::IsOk; using ::arolla::testing::IsOkAndHolds; using ::arolla::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, OperatorFactory() .WithName("test.mul") .BuildFromFunction([](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>()))); ASSERT_OK_AND_ASSIGN( auto fixture, (OperatorFixture<std::tuple<int64_t, int64_t>, int64_t>::Create(*op))); EXPECT_THAT(fixture.Call(3, 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, OperatorFactory().WithName("test.mul").BuildFromFunction(Multiply)); ASSERT_THAT(op->signature(), Eq(QExprOperatorSignature::Get( {GetQType<int64_t>(), GetQType<int64_t>()}, GetQType<int64_t>()))); ASSERT_OK_AND_ASSIGN( auto fixture, (OperatorFixture<std::tuple<int64_t, int64_t>, int64_t>::Create(*op))); EXPECT_THAT(fixture.Call(3, 19), IsOkAndHolds(Eq(57))); } TEST(OperatorFactory, MultiOutputOperator) { using Pair = std::tuple<int64_t, int64_t>; ASSERT_OK_AND_ASSIGN(auto op, OperatorFactory() .WithName("test.EuclidsStep") .BuildFromFunction([](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, OperatorFactory() .WithName("test.AlwaysFail") .BuildFromFunction([]() -> absl::StatusOr<int64_t> { return absl::Status(absl::StatusCode::kFailedPrecondition, "failed"); })); ASSERT_THAT(op->signature(), Eq(QExprOperatorSignature::Get({}, GetQType<int64_t>()))); ASSERT_OK_AND_ASSIGN(auto fixture, (OperatorFixture<std::tuple<>, int64_t>::Create(*op))); EXPECT_THAT(fixture.Call(), StatusIs(absl::StatusCode::kFailedPrecondition)); } TEST(OperatorFactory, ReturnsStatusOrMultipleOutputs) { using Pair = std::tuple<int64_t, int64_t>; ASSERT_OK_AND_ASSIGN( auto op, OperatorFactory() .WithName("test.EuclidsStep") .BuildFromFunction([](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); })); 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, 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, OperatorFactory() .WithName("test.EuclidsStep") .BuildFromFunction( [](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, OperatorFactory().WithName("test.Op").BuildFromFunction( [](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, OperatorFactory().WithName("test.Op").BuildFromFunction( [](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, OperatorFactory().WithName("test.Op").BuildFromFunction( [](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, OperatorFactory().WithName("test.Op").BuildFromFunction( [](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, OperatorFactory().WithName("test.Op").BuildFromFunction( [](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, OperatorFactory().WithName("test.Op").BuildFromFunction( [](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, OperatorFactory() .WithName("test.ContextOp") .BuildFromFunction([](EvaluationContext* ctx, float x) { ctx->buffer_factory().CreateRawBuffer(0); return std::tuple<>(); })); ASSERT_OK_AND_ASSIGN( auto fixture, (OperatorFixture<std::tuple<float>, std::tuple<>>::Create(*op))); EXPECT_THAT(fixture.Call(5.7), IsOk()); } 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, (OperatorFactory() .WithName("test.add") .BuildFromFunctor<AddOp, int64_t, int64_t>())); EXPECT_THAT(op->name(), Eq("test.add")); ASSERT_OK_AND_ASSIGN(auto non_template_op, (OperatorFactory() .WithName("test.add") .BuildFromFunctor<Int64AddOp, int64_t, int64_t>())); EXPECT_THAT(non_template_op->name(), Eq("test.add")); ASSERT_OK_AND_ASSIGN( auto context_op, (OperatorFactory() .WithName("test.add") .BuildFromFunctor<ContextAddOp, int64_t, int64_t>())); EXPECT_THAT(context_op->name(), Eq("test.add")); } TEST(OperatorFactory, Errors) { EXPECT_THAT(OperatorFactory().BuildFromFunction( [](int64_t a, int64_t b) { return a * b; }), StatusIs(absl::StatusCode::kFailedPrecondition, "operator name should be specified")); auto qtype = QExprOperatorSignature::Get( {GetQType<float>(), GetQType<int32_t>()}, GetQType<int>()); EXPECT_THAT( OperatorFactory() .WithName("test.MakeOp") .BuildFromFunction( [](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 .*->.*\\."))); } } }
2,357
cpp
google/arolla
simple_executable
arolla/qexpr/simple_executable.cc
arolla/qexpr/simple_executable_test.cc
#ifndef AROLLA_QEXPR_SIMPLE_EXECUTABLE_H_ #define AROLLA_QEXPR_SIMPLE_EXECUTABLE_H_ #include <memory> #include <string> #include <utility> #include <vector> #include "absl/container/flat_hash_map.h" #include "arolla/memory/frame.h" #include "arolla/qexpr/eval_context.h" #include "arolla/qexpr/evaluation_engine.h" #include "arolla/qexpr/operators.h" #include "arolla/qtype/typed_slot.h" namespace arolla { class SimpleBoundExpr : public BoundExpr { public: SimpleBoundExpr( absl::flat_hash_map<std::string, TypedSlot> input_slots, TypedSlot output_slot, std::vector<std::unique_ptr<BoundOperator>> init_ops, std::vector<std::unique_ptr<BoundOperator>> eval_ops, absl::flat_hash_map<std::string, TypedSlot> named_output_slots = {}) : BoundExpr(std::move(input_slots), output_slot, std::move(named_output_slots)), init_ops_(std::move(init_ops)), eval_ops_(std::move(eval_ops)) {} void InitializeLiterals(EvaluationContext* ctx, FramePtr frame) const override; void Execute(EvaluationContext* ctx, FramePtr frame) const override; private: std::vector<std::unique_ptr<BoundOperator>> init_ops_; std::vector<std::unique_ptr<BoundOperator>> eval_ops_; }; class CombinedBoundExpr : public BoundExpr { public: CombinedBoundExpr( absl::flat_hash_map<std::string, TypedSlot> input_slots, TypedSlot output_slot, absl::flat_hash_map<std::string, TypedSlot> named_output_slots, std::vector<std::unique_ptr<BoundExpr>> subexprs) : BoundExpr(std::move(input_slots), output_slot, std::move(named_output_slots)), subexprs_(std::move(subexprs)) {} void InitializeLiterals(EvaluationContext* ctx, FramePtr frame) const override; void Execute(EvaluationContext* ctx, FramePtr frame) const override; private: std::vector<std::unique_ptr<BoundExpr>> subexprs_; }; } #endif #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 "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/testing/status_matchers_backport.h" #include "arolla/util/unit.h" namespace arolla { namespace { using ::arolla::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)); } } }
2,358
cpp
google/arolla
bound_operators
arolla/dense_array/testing/bound_operators.cc
arolla/qexpr/bound_operators_test.cc
#ifndef AROLLA_BLOCK_TESTING_BOUND_OPERATORS_H #define AROLLA_BLOCK_TESTING_BOUND_OPERATORS_H #include <memory> #include "arolla/dense_array/dense_array.h" #include "arolla/memory/frame.h" #include "arolla/qexpr/operators.h" namespace arolla { std::unique_ptr<BoundOperator> DenseArrayAddOperator( FrameLayout::Slot<DenseArray<float>> arg1, FrameLayout::Slot<DenseArray<float>> arg2, FrameLayout::Slot<DenseArray<float>> result); std::unique_ptr<BoundOperator> DenseArrayEigenAddOperator( FrameLayout::Slot<DenseArray<float>> arg1, FrameLayout::Slot<DenseArray<float>> arg2, FrameLayout::Slot<DenseArray<float>> result); std::unique_ptr<BoundOperator> DenseArrayUnionAddOperator( FrameLayout::Slot<DenseArray<float>> arg1, FrameLayout::Slot<DenseArray<float>> arg2, FrameLayout::Slot<DenseArray<float>> result); } #endif #include "arolla/dense_array/testing/bound_operators.h" #include <memory> #include "absl/status/status.h" #include "arolla/dense_array/dense_array.h" #include "arolla/dense_array/ops/dense_ops.h" #include "arolla/memory/frame.h" #include "arolla/memory/optional_value.h" #include "arolla/qexpr/eval_context.h" #include "arolla/qexpr/operators.h" #include "arolla/qexpr/operators/math/batch_arithmetic.h" namespace arolla { namespace { class TestAdd : public BoundOperator { public: explicit TestAdd(FrameLayout::Slot<DenseArray<float>> arg1, FrameLayout::Slot<DenseArray<float>> arg2, FrameLayout::Slot<DenseArray<float>> result) : arg1_(arg1), arg2_(arg2), result_(result) {} void Run(EvaluationContext* ctx, FramePtr frame) const override { if (frame.Get(arg1_).size() != frame.Get(arg2_).size()) { ctx->set_status(absl::InvalidArgumentError("size mismatch")); } else { auto op = CreateDenseOp<DenseOpFlags::kRunOnMissing | DenseOpFlags::kNoBitmapOffset | DenseOpFlags::kNoSizeValidation>( [](float a, float b) { return a + b; }, &ctx->buffer_factory()); *frame.GetMutable(result_) = op(frame.Get(arg1_), frame.Get(arg2_)); } } private: FrameLayout::Slot<DenseArray<float>> arg1_; FrameLayout::Slot<DenseArray<float>> arg2_; FrameLayout::Slot<DenseArray<float>> result_; }; class TestEigenAdd : public BoundOperator { public: explicit TestEigenAdd(FrameLayout::Slot<DenseArray<float>> arg1, FrameLayout::Slot<DenseArray<float>> arg2, FrameLayout::Slot<DenseArray<float>> result) : arg1_(arg1), arg2_(arg2), result_(result) {} void Run(EvaluationContext* ctx, FramePtr frame) const override { if (frame.Get(arg1_).size() != frame.Get(arg2_).size()) { ctx->set_status(absl::InvalidArgumentError("size mismatch")); } else { auto op = CreateDenseBinaryOpFromSpanOp<float, DenseOpFlags::kNoBitmapOffset | DenseOpFlags::kNoSizeValidation>( BatchAdd<float>(), &ctx->buffer_factory()); *frame.GetMutable(result_) = op(frame.Get(arg1_), frame.Get(arg2_)); } } private: FrameLayout::Slot<DenseArray<float>> arg1_; FrameLayout::Slot<DenseArray<float>> arg2_; FrameLayout::Slot<DenseArray<float>> result_; }; class TestUnionAdd : public BoundOperator { public: explicit TestUnionAdd(FrameLayout::Slot<DenseArray<float>> arg1, FrameLayout::Slot<DenseArray<float>> arg2, FrameLayout::Slot<DenseArray<float>> result) : arg1_(arg1), arg2_(arg2), result_(result) {} void Run(EvaluationContext* ctx, FramePtr frame) const override { if (frame.Get(arg1_).size() != frame.Get(arg2_).size()) { ctx->set_status(absl::InvalidArgumentError("size mismatch")); } else { auto fn = [](OptionalValue<float> a, OptionalValue<float> b) { OptionalValue<float> res; res.present = a.present || b.present; res.value = (a.present ? a.value : 0.f) + (b.present ? b.value : 0.f); return res; }; auto op = CreateDenseOp<DenseOpFlags::kNoBitmapOffset | DenseOpFlags::kNoSizeValidation>( fn, &ctx->buffer_factory()); *frame.GetMutable(result_) = op(frame.Get(arg1_), frame.Get(arg2_)); } } private: FrameLayout::Slot<DenseArray<float>> arg1_; FrameLayout::Slot<DenseArray<float>> arg2_; FrameLayout::Slot<DenseArray<float>> result_; }; } std::unique_ptr<BoundOperator> DenseArrayAddOperator( FrameLayout::Slot<DenseArray<float>> arg1, FrameLayout::Slot<DenseArray<float>> arg2, FrameLayout::Slot<DenseArray<float>> result) { return std::make_unique<TestAdd>(arg1, arg2, result); } std::unique_ptr<BoundOperator> DenseArrayEigenAddOperator( FrameLayout::Slot<DenseArray<float>> arg1, FrameLayout::Slot<DenseArray<float>> arg2, FrameLayout::Slot<DenseArray<float>> result) { return std::make_unique<TestEigenAdd>(arg1, arg2, result); } std::unique_ptr<BoundOperator> DenseArrayUnionAddOperator( FrameLayout::Slot<DenseArray<float>> arg1, FrameLayout::Slot<DenseArray<float>> arg2, FrameLayout::Slot<DenseArray<float>> result) { return std::make_unique<TestUnionAdd>(arg1, arg2, result); } }
#include "arolla/qexpr/bound_operators.h" #include <cstdint> #include <memory> #include <optional> #include <utility> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/types/span.h" #include "arolla/memory/frame.h" #include "arolla/memory/memory_allocation.h" #include "arolla/memory/optional_value.h" #include "arolla/qexpr/eval_context.h" #include "arolla/qexpr/operators.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/optional_qtype.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/typed_slot.h" #include "arolla/util/testing/status_matchers_backport.h" #include "arolla/util/status_macros_backport.h" namespace arolla { namespace { using ::arolla::testing::IsOk; using ::arolla::testing::StatusIs; using ::testing::Eq; template <typename T> using Slot = FrameLayout::Slot<T>; absl::StatusOr<std::unique_ptr<BoundOperator>> CreateAddFloatsBoundOp( absl::Span<const TypedSlot> input_slots, Slot<OptionalValue<float>> output_slot) { std::vector<Slot<bool>> input_cond_slots; std::vector<Slot<float>> input_value_slots; for (const auto& typed_input_slot : input_slots) { QTypePtr input_type = typed_input_slot.GetType(); if (IsOptionalQType(input_type)) { ASSIGN_OR_RETURN(auto input_slot, typed_input_slot.ToSlot<OptionalValue<float>>()); input_cond_slots.push_back(GetPresenceSubslotFromOptional(input_slot)); input_value_slots.push_back(GetValueSubslotFromOptional(input_slot)); } else { ASSIGN_OR_RETURN(auto value_slot, typed_input_slot.ToSlot<float>()); input_value_slots.push_back(value_slot); } } Slot<bool> output_presence_slot = output_slot.GetSubslot<0>(); Slot<float> output_value_slot = output_slot.GetSubslot<1>(); auto add_op = FunctorBoundOperator([input_value_slots, output_value_slot]( EvaluationContext* ctx, FramePtr frame) { float result = 0.0f; for (auto input_value_slot : input_value_slots) { result += frame.Get(input_value_slot); } frame.Set(output_value_slot, result); }); return std::unique_ptr<BoundOperator>(new WhereAllBoundOperator( input_cond_slots, output_presence_slot, add_op)); } TEST(BoundOperators, RunBoundOperators) { FrameLayout::Builder layout_builder; Slot<int32_t> x_slot = layout_builder.AddSlot<int32_t>(); FrameLayout layout = std::move(layout_builder).Build(); MemoryAllocation alloc(&layout); ASSERT_THAT(alloc.frame().Get(x_slot), Eq(0)); auto make_increment_operator = [x_slot](int32_t increment) { return MakeBoundOperator( [x_slot, increment](EvaluationContext* ctx, FramePtr frame) { frame.Set(x_slot, frame.Get(x_slot) + increment); }); }; std::vector<std::unique_ptr<BoundOperator>> bound_operators; bound_operators.push_back(make_increment_operator(1)); bound_operators.push_back(make_increment_operator(10)); bound_operators.push_back(make_increment_operator(100)); EvaluationContext ctx; EXPECT_EQ(RunBoundOperators(bound_operators, &ctx, alloc.frame()), 2); EXPECT_THAT(alloc.frame().Get(x_slot), Eq(111)); EXPECT_THAT(ctx.status(), IsOk()); } TEST(BoundOperators, RunBoundOperators_WithError) { FrameLayout::Builder layout_builder; Slot<int32_t> x_slot = layout_builder.AddSlot<int32_t>(); FrameLayout layout = std::move(layout_builder).Build(); MemoryAllocation alloc(&layout); ASSERT_THAT(alloc.frame().Get(x_slot), Eq(0)); auto make_increment_operator = [x_slot](int32_t increment) { return MakeBoundOperator( [x_slot, increment](EvaluationContext* ctx, FramePtr frame) { frame.Set(x_slot, frame.Get(x_slot) + increment); }); }; std::vector<std::unique_ptr<BoundOperator>> bound_operators; bound_operators.push_back(make_increment_operator(1)); bound_operators.push_back(make_increment_operator(10)); bound_operators.push_back( MakeBoundOperator([](EvaluationContext* ctx, FramePtr frame) { ctx->set_status(absl::InvalidArgumentError("foo")); })); bound_operators.push_back(make_increment_operator(100)); EvaluationContext ctx; EXPECT_EQ(RunBoundOperators(bound_operators, &ctx, alloc.frame()), 2); EXPECT_THAT(alloc.frame().Get(x_slot), Eq(11)); EXPECT_THAT(ctx.status(), StatusIs(absl::StatusCode::kInvalidArgument, "foo")); } TEST(BoundOperators, RunBoundOperators_WithJump) { FrameLayout::Builder layout_builder; Slot<int32_t> x_slot = layout_builder.AddSlot<int32_t>(); FrameLayout layout = std::move(layout_builder).Build(); MemoryAllocation alloc(&layout); ASSERT_THAT(alloc.frame().Get(x_slot), Eq(0)); auto make_increment_operator = [x_slot](int32_t increment) { return MakeBoundOperator( [x_slot, increment](EvaluationContext* ctx, FramePtr frame) { frame.Set(x_slot, frame.Get(x_slot) + increment); }); }; std::vector<std::unique_ptr<BoundOperator>> bound_operators; bound_operators.push_back(make_increment_operator(1)); bound_operators.push_back(JumpBoundOperator(1)); bound_operators.push_back(make_increment_operator(10)); bound_operators.push_back(make_increment_operator(100)); EvaluationContext ctx; EXPECT_EQ(RunBoundOperators(bound_operators, &ctx, alloc.frame()), 3); EXPECT_THAT(alloc.frame().Get(x_slot), Eq(101)); EXPECT_THAT(ctx.status(), IsOk()); } TEST(BoundOperators, WhereAll) { FrameLayout::Builder layout_builder; auto input1 = layout_builder.AddSlot<OptionalValue<float>>(); auto input2 = layout_builder.AddSlot<OptionalValue<float>>(); auto input3 = layout_builder.AddSlot<float>(); auto input4 = layout_builder.AddSlot<float>(); auto result = layout_builder.AddSlot<OptionalValue<float>>(); ASSERT_OK_AND_ASSIGN( auto op1, CreateAddFloatsBoundOp( ToTypedSlots(input1, input2, input3, input4), result)); FrameLayout layout = std::move(layout_builder).Build(); RootEvaluationContext root_ctx(&layout); root_ctx.Set(input1, 1.0f); root_ctx.Set(input2, 10.0f); root_ctx.Set(input3, 100.0f); root_ctx.Set(input4, 1000.0f); EvaluationContext ctx(root_ctx); op1->Run(&ctx, root_ctx.frame()); EXPECT_OK(ctx.status()); EXPECT_EQ(root_ctx.Get(result), OptionalValue<float>{1111.0f}); root_ctx.Set(input2, std::nullopt); root_ctx.Set(result, 0.0f); op1->Run(&ctx, root_ctx.frame()); EXPECT_OK(ctx.status()); EXPECT_EQ(root_ctx.Get(result), OptionalValue<float>{}); EXPECT_EQ(root_ctx.Get(result).value, 0.0f); } } }
2,359
cpp
google/arolla
operator_metadata
arolla/qexpr/operator_metadata.cc
arolla/qexpr/operator_metadata_test.cc
#ifndef AROLLA_QEXPR_OPERATOR_METADATA_H_ #define AROLLA_QEXPR_OPERATOR_METADATA_H_ #include <optional> #include <set> #include <string> #include <vector> #include "absl/base/thread_annotations.h" #include "absl/container/flat_hash_map.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "absl/synchronization/mutex.h" #include "absl/types/span.h" #include "arolla/qtype/qtype.h" namespace arolla { struct OpClassDetails { bool returns_status_or; bool accepts_context; std::vector<int> arg_as_function_ids; }; struct BuildDetails { std::string build_target; std::string op_class; std::optional<OpClassDetails> op_class_details; std::string op_family_class; std::vector<std::string> hdrs; std::vector<std::string> deps; }; struct QExprOperatorMetadata { std::string name; std::vector<QTypePtr> input_qtypes; BuildDetails build_details; }; struct QExprOperatorFamilyMetadata { std::string name; BuildDetails family_build_details = {}; }; class QExprOperatorMetadataRegistry final { public: QExprOperatorMetadataRegistry() = default; absl::Status AddOperatorFamilyMetadata(QExprOperatorFamilyMetadata metadata); absl::Status AddOperatorMetadata(QExprOperatorMetadata metadata); absl::StatusOr<QExprOperatorMetadata> LookupOperatorMetadata( absl::string_view op_name, absl::Span<const QTypePtr> input_qtypes) const; absl::flat_hash_map<std::string, std::set<std::string>> OperatorBuildDependencies() const; static QExprOperatorMetadataRegistry& GetInstance(); private: using TypeToMetadata = absl::flat_hash_map<std::vector<QTypePtr>, QExprOperatorMetadata>; absl::flat_hash_map<std::string, QExprOperatorFamilyMetadata> family_metadatas_ ABSL_GUARDED_BY(mutex_); absl::flat_hash_map<std::string, TypeToMetadata> operator_metadatas_ ABSL_GUARDED_BY(mutex_); mutable absl::Mutex mutex_; }; int RegisterOperatorFamilyMetadataOrDie(QExprOperatorFamilyMetadata metadata); int RegisterOperatorMetadataOrDie(QExprOperatorMetadata metadata); } #endif #include "arolla/qexpr/operator_metadata.h" #include <set> #include <string> #include <utility> #include <vector> #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" #include "arolla/util/indestructible.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 Indestructible<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 "arolla/qtype/base_types.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/util/operator_name.h" #include "arolla/util/testing/status_matchers_backport.h" namespace arolla { namespace { using ::arolla::testing::IsOkAndHolds; using ::arolla::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")))); } } }
2,360
cpp
google/arolla
operators
arolla/qexpr/operators.cc
arolla/qexpr/operators_test.cc
#ifndef AROLLA_QEXPR_OPERATORS_H_ #define AROLLA_QEXPR_OPERATORS_H_ #include <memory> #include <string> #include <utility> #include <vector> #include "absl/base/thread_annotations.h" #include "absl/container/flat_hash_map.h" #include "absl/log/log.h" #include "absl/status/statusor.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/eval_context.h" #include "arolla/qexpr/qexpr_operator_signature.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/typed_value.h" #include "arolla/util/status_macros_backport.h" namespace arolla { class BoundOperator { public: virtual ~BoundOperator() = default; virtual void Run(EvaluationContext* ctx, FramePtr frame) const = 0; }; class QExprOperator { public: template <typename T> using Slot = FrameLayout::Slot<T>; virtual ~QExprOperator() = default; explicit QExprOperator(std::string name, const QExprOperatorSignature* signature) : name_(std::move(name)), signature_(signature) {} const QExprOperatorSignature* signature() const { return signature_; } absl::string_view name() const { return name_; } absl::StatusOr<std::unique_ptr<BoundOperator>> Bind( absl::Span<const TypedSlot> input_slots, TypedSlot output_slot) const; private: virtual absl::StatusOr<std::unique_ptr<BoundOperator>> DoBind( absl::Span<const TypedSlot> input_slots, TypedSlot output_slot) const = 0; std::string name_; const QExprOperatorSignature* signature_; }; class InlineOperator : public QExprOperator { using QExprOperator::QExprOperator; }; absl::StatusOr<TypedValue> InvokeOperator(const QExprOperator& op, absl::Span<const TypedValue> args); absl::StatusOr<TypedValue> InvokeOperator(absl::string_view op_name, absl::Span<const TypedValue> args, QTypePtr output_qtype); template <typename OutputType, typename... InputTypes> absl::StatusOr<OutputType> InvokeOperator(absl::string_view op_name, InputTypes&&... inputs) { ASSIGN_OR_RETURN( auto output, InvokeOperator( op_name, {TypedValue::FromValue(std::forward<InputTypes>(inputs))...}, GetQType<OutputType>())); ASSIGN_OR_RETURN(auto result_ref, output.template As<OutputType>()); return result_ref.get(); } using OperatorPtr = std::shared_ptr<const QExprOperator>; class OperatorFamily { public: virtual ~OperatorFamily() = default; absl::StatusOr<OperatorPtr> GetOperator( absl::Span<const QTypePtr> input_types, QTypePtr output_type) const { return DoGetOperator(input_types, output_type); } private: virtual absl::StatusOr<OperatorPtr> DoGetOperator( absl::Span<const QTypePtr> input_types, QTypePtr output_type) const = 0; }; absl::StatusOr<OperatorPtr> EnsureOutputQTypeMatches( absl::StatusOr<OperatorPtr> op_or, absl::Span<const QTypePtr> input_types, QTypePtr output_type); class OperatorDirectory { public: absl::StatusOr<OperatorPtr> LookupOperator( absl::string_view name, absl::Span<const QTypePtr> input_types, QTypePtr output_type) const { return DoLookupOperator(name, input_types, output_type); } virtual ~OperatorDirectory() = default; private: virtual absl::StatusOr<OperatorPtr> DoLookupOperator( absl::string_view name, absl::Span<const QTypePtr> input_types, QTypePtr output_type) const = 0; }; class OperatorRegistry final : public OperatorDirectory { public: absl::Status RegisterOperatorFamily( absl::string_view name, std::unique_ptr<OperatorFamily> operation); absl::Status RegisterOperator(OperatorPtr op); std::vector<std::string> ListRegisteredOperators(); static OperatorRegistry* GetInstance(); private: absl::StatusOr<OperatorPtr> DoLookupOperator( absl::string_view name, absl::Span<const QTypePtr> input_types, QTypePtr output_type) const final; absl::StatusOr<const OperatorFamily*> LookupOperatorFamily( absl::string_view name) const; absl::flat_hash_map<std::string, std::unique_ptr<OperatorFamily>> families_ ABSL_GUARDED_BY(mutex_); mutable absl::Mutex mutex_; }; constexpr absl::string_view kCoreOperatorsNamespace = "core"; template <typename T> int RegisterOperatorFamily(absl::string_view name) { auto status = OperatorRegistry::GetInstance()->RegisterOperatorFamily( name, std::make_unique<T>()); if (!status.ok()) { LOG(FATAL) << status; } return 57; } } #endif #include "arolla/qexpr/operators.h" #include <cstddef> #include <memory> #include <string> #include <utility> #include <vector> #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_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/indestructible.h" #include "arolla/util/operator_name.h" #include "arolla/util/status_macros_backport.h" namespace arolla { namespace { class CombinedOperatorFamily : 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 override { auto it = operators_.find(input_types); if (it != operators_.end() && it->second->signature()->output_type() == output_type) { return it->second; } ASSIGN_OR_RETURN(const QExprOperatorSignature* matching_signature, FindMatchingSignature( QExprOperatorSignature::Get(input_types, output_type), supported_signatures_, name_)); return operators_.at(matching_signature->input_types()); } absl::Status Insert(OperatorPtr op) { auto* signature = op->signature(); if (!operators_.emplace(signature->input_types(), std::move(op)).second) { return absl::OkStatus(); } supported_signatures_.push_back(signature); return absl::OkStatus(); } private: std::string name_; absl::flat_hash_map<absl::Span<const QTypePtr>, OperatorPtr> 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(OperatorPtr op) { absl::WriterMutexLock lock(&mutex_); if (!IsOperatorName(op->name())) { return absl::InvalidArgumentError( absl::StrFormat("incorrect operator name \"%s\"", op->name())); } auto found = families_.find(op->name()); if (found == families_.end()) { auto inserted = families_.emplace( op->name(), std::make_unique<CombinedOperatorFamily>(std::string(op->name()))); found = inserted.first; } if (auto* combined_family = dynamic_cast<CombinedOperatorFamily*>(found->second.get())) { return combined_family->Insert(std::move(op)); } else { return absl::Status( absl::StatusCode::kAlreadyExists, absl::StrFormat("trying to register a single QExpr operator and an " "operator family under the same name %s", op->name())); } } 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 Indestructible<OperatorRegistry> instance( [](auto* self) { new (self) OperatorRegistry; }); 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(), op.name())); return VerifyOutputSlotType(output_slot, signature->output_type(), op.name()); } } 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( "operator %s%s->%s not found: unexpected output type %s", op->name(), 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(), op.name())); 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 <utility> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "absl/strings/str_cat.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" #include "arolla/util/init_arolla.h" #include "arolla/util/testing/status_matchers_backport.h" namespace arolla { namespace { using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::StatusIs; using ::testing::ContainsRegex; using ::testing::ElementsAre; using ::testing::Eq; using ::testing::HasSubstr; using ::testing::Property; class OperatorsTest : public ::testing::Test { void SetUp() final { ASSERT_OK(InitArolla()); } }; TEST_F(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_F(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_F(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 for operator test.add: 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 for operator test.add: 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 for operator test.add: " "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_F(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_F(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_F(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_F(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 for operator test.mul: expected " "(INT64,INT64), got (FLOAT64,INT64)")); } TEST_F(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_F(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_F(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_F(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()); } } }
2,361
cpp
google/arolla
array_ops
arolla/qexpr/operators/dense_array/array_ops.cc
arolla/qexpr/operators/dense_array/array_ops_test.cc
#ifndef AROLLA_QEXPR_OPERATORS_DENSE_ARRAY_DENSE_ARRAY_OPS_H_ #define AROLLA_QEXPR_OPERATORS_DENSE_ARRAY_DENSE_ARRAY_OPS_H_ #include <algorithm> #include <cstddef> #include <cstdint> #include <optional> #include <utility> #include "absl/base/optimization.h" #include "absl/container/flat_hash_set.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "absl/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" #include "arolla/util/status_macros_backport.h" namespace arolla { struct DenseArrayAtOp { template <typename T> OptionalValue<T> operator()(EvaluationContext* ctx, const DenseArray<T>& arr, int64_t id) const { if (ABSL_PREDICT_FALSE(id < 0 || id >= arr.size())) { ReportIndexOutOfRangeError(ctx, id, arr.size()); return std::nullopt; } return {arr.present(id), T{arr.values[id]}}; } template <typename T> OptionalValue<T> operator()(EvaluationContext* ctx, const DenseArray<T>& arr, OptionalValue<int64_t> id) const { return id.present ? (*this)(ctx, arr, id.value) : std::nullopt; } template <typename T> DenseArray<T> operator()(EvaluationContext* ctx, const DenseArray<T>& arr, const DenseArray<int64_t>& ids) const { auto fn = [ctx, &arr](int64_t id) -> OptionalValue<view_type_t<T>> { if (ABSL_PREDICT_FALSE(id < 0 || id >= arr.size())) { ReportIndexOutOfRangeError(ctx, id, arr.size()); return std::nullopt; } if (!arr.present(id)) { return std::nullopt; } return arr.values[id]; }; auto op = CreateDenseOp<DenseOpFlags::kNoBitmapOffset, decltype(fn), T>( fn, &ctx->buffer_factory()); return op(ids); } private: static void ReportIndexOutOfRangeError(EvaluationContext* ctx, int64_t index, int64_t size); }; struct DenseArraySliceOp { template <typename T> absl::StatusOr<DenseArray<T>> operator()(EvaluationContext* ctx, const DenseArray<T>& array, int64_t offset, int64_t size) const { if (offset < 0 || offset > array.size()) { return absl::InvalidArgumentError(absl::StrFormat( "expected `offset` in [0, %d], but got %d", array.size(), offset)); } if (size < -1 || size > array.size() - offset) { return absl::InvalidArgumentError( absl::StrFormat("expected `size` in [0, %d], but got %d", array.size() - offset, size)); } if (size == -1) { size = array.size() - offset; } return array.Slice(offset, size) .ForceNoBitmapBitOffset(&ctx->buffer_factory()); } }; struct DenseArrayConcatOp { template <typename T> DenseArray<T> operator()(EvaluationContext* ctx, const DenseArray<T>& arr1, const DenseArray<T>& arr2) const { typename Buffer<T>::Builder values_bldr(arr1.size() + arr2.size(), &ctx->buffer_factory()); auto values_inserter = values_bldr.GetInserter(); for (const auto& v : arr1.values) values_inserter.Add(v); for (const auto& v : arr2.values) values_inserter.Add(v); if (arr1.bitmap.empty() && arr2.bitmap.empty()) { return {std::move(values_bldr).Build()}; } size_t bitmap_size = bitmap::BitmapSize(arr1.size() + arr2.size()); bitmap::Bitmap::Builder bitmap_bldr(bitmap_size, &ctx->buffer_factory()); absl::Span<bitmap::Word> bitmap = bitmap_bldr.GetMutableSpan(); std::fill(bitmap.begin(), bitmap.end(), bitmap::kFullWord); if (!arr1.bitmap.empty()) { CopyBits<bitmap::Word>(arr1.size(), arr1.bitmap.begin(), arr1.bitmap_bit_offset, bitmap.begin(), 0); } if (!arr2.bitmap.empty()) { size_t offset = arr1.size(); CopyBits<bitmap::Word>(arr2.size(), arr2.bitmap.begin(), arr2.bitmap_bit_offset, bitmap.begin() + offset / bitmap::kWordBitCount, offset % bitmap::kWordBitCount); } return {std::move(values_bldr).Build(), std::move(bitmap_bldr).Build()}; } }; class DenseArrayPresentIndicesOp { public: DenseArray<int64_t> operator()(EvaluationContext* ctx, const DenseArray<Unit>& input) const { const int64_t count = bitmap::CountBits(input.bitmap, input.bitmap_bit_offset, input.size()); Buffer<int64_t>::Builder buffer_builder(count, &ctx->buffer_factory()); auto inserter = buffer_builder.GetInserter(); input.ForEach([&](int64_t index, bool present, const auto& ) { if (present) { inserter.Add(index); } }); return DenseArray<int64_t>{std::move(buffer_builder).Build(count)}; } }; class DenseArrayPresentValuesOp { public: template <typename T> DenseArray<T> operator()(EvaluationContext* ctx, const DenseArray<T>& input) const { const int64_t count = bitmap::CountBits(input.bitmap, input.bitmap_bit_offset, input.size()); typename Buffer<T>::Builder buffer_builder(count, &ctx->buffer_factory()); auto inserter = buffer_builder.GetInserter(); input.ForEach([&](int64_t , bool present, const auto& value) { if (present) { inserter.Add(value); } }); return DenseArray<T>{std::move(buffer_builder).Build(count)}; } }; class DenseArrayFromIndicesAndValues { public: template <typename T> DenseArray<T> operator()(EvaluationContext* ctx, const DenseArray<int64_t>& indices, const DenseArray<T>& values, int64_t size) const { if (!ValidateInputs(ctx, indices, values.size(), size)) { return DenseArray<T>{Buffer<T>(), Buffer<bitmap::Word>()}; } DenseArrayBuilder<T> builder(size, &ctx->buffer_factory()); const int64_t n = indices.size(); for (int64_t i = 0; i < n; ++i) { if (values.present(i)) { builder.Set(indices.values[i], values.values[i]); } } return std::move(builder).Build(); } private: static bool ValidateInputs(EvaluationContext* ctx, const DenseArray<int64_t>& indices, int64_t values_size, int64_t size); }; struct DenseArrayUniqueOp { template <typename T> DenseArray<T> operator()(EvaluationContext* ctx, const DenseArray<T>& input) const { typename Buffer<T>::Builder bldr(input.size(), &ctx->buffer_factory()); auto inserter = bldr.GetInserter(); absl::flat_hash_set<view_type_t<T>> unique_values; input.ForEachPresent([&](int64_t , const auto& value) { if (auto [it, inserted] = unique_values.insert(value); inserted) { inserter.Add(value); } }); return DenseArray<T>{std::move(bldr).Build(unique_values.size())}; } }; struct DenseArraySelectOp { template <typename T> absl::StatusOr<DenseArray<T>> operator()( EvaluationContext* ctx, const DenseArray<T>& input, const DenseArray<Unit>& filter) const { if (ABSL_PREDICT_FALSE(input.size() != filter.size())) { return SizeMismatchError({input.size(), filter.size()}); } if (filter.bitmap.empty()) { return input; } const int64_t count = filter.PresentCount(); if (count == 0) { return DenseArray<T>(); } DenseArrayBuilder<T> builder(count); int64_t offset = 0; using view_type = arolla::view_type_t<T>; auto fn = [&](int64_t id, Unit mask, OptionalValue<view_type> value) { builder.Set(offset++, value); }; RETURN_IF_ERROR(DenseArraysForEachPresent(fn, filter, input)); return std::move(builder).Build(); } }; } #endif #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 "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/util/init_arolla.h" #include "arolla/util/testing/status_matchers_backport.h" namespace arolla::testing { namespace { using ::arolla::testing::StatusIs; using ::testing::ElementsAre; class ArrayOpsTest : public ::testing::Test { void SetUp() final { ASSERT_OK(InitArolla()); } }; TEST_F(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_F(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_F(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_F(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_F(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_F(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_F(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_F(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))); } } }
2,362
cpp
google/arolla
factory_ops
arolla/qexpr/operators/dense_array/factory_ops.cc
arolla/qexpr/operators/dense_array/factory_ops_test.cc
#ifndef AROLLA_QEXPR_OPERATORS_DENSE_ARRAY_FACTORY_OPS_H_ #define AROLLA_QEXPR_OPERATORS_DENSE_ARRAY_FACTORY_OPS_H_ #include <cstdint> #include <numeric> #include <utility> #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/buffer.h" #include "arolla/memory/optional_value.h" #include "arolla/qexpr/eval_context.h" #include "arolla/qexpr/operators.h" #include "arolla/qtype/qtype.h" #include "arolla/util/unit.h" namespace arolla { struct DenseArrayShapeOfOp { DenseArrayShape operator()(const DenseArray<Unit>& array) const { return {array.size()}; } }; struct DenseArrayShapeSizeOp { int64_t operator()(DenseArrayShape shape) const { return shape.size; } }; struct DenseArrayResizeShapeOp { absl::StatusOr<DenseArrayShape> operator()(DenseArrayShape, int64_t size) const { if (size < 0) { return absl::InvalidArgumentError(absl::StrFormat("bad size: %d", size)); } return DenseArrayShape{size}; } }; struct DenseArrayConstWithShapeOp { template <typename T> DenseArray<T> operator()(EvaluationContext* ctx, const DenseArrayShape& shape, const T& fill_value) const { return CreateConstDenseArray<T>(shape.size, fill_value, &ctx->buffer_factory()); } template <typename T> DenseArray<T> operator()(EvaluationContext* ctx, const DenseArrayShape& shape, const OptionalValue<T>& fill_value) const { if (fill_value.present) { return CreateConstDenseArray<T>(shape.size, fill_value.value, &ctx->buffer_factory()); } else { return CreateEmptyDenseArray<T>(shape.size, &ctx->buffer_factory()); } } }; struct DenseArrayIotaOp { DenseArray<int64_t> operator()(EvaluationContext* ctx, const DenseArrayShape& shape) const { Buffer<int64_t>::Builder bldr(shape.size, &ctx->buffer_factory()); std::iota(bldr.GetMutableSpan().begin(), bldr.GetMutableSpan().end(), int64_t{0}); return {std::move(bldr).Build()}; } }; class MakeDenseArrayOperatorFamily : public OperatorFamily { absl::StatusOr<OperatorPtr> DoGetOperator( absl::Span<const QTypePtr> input_types, QTypePtr output_type) const final; }; } #endif #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( "array.make_dense_array", 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 "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/init_arolla.h" #include "arolla/util/testing/status_matchers_backport.h" #include "arolla/util/unit.h" namespace arolla { namespace { using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::StatusIs; using ::testing::ElementsAre; using ::testing::Eq; class FactoryOpsTest : public ::testing::Test { protected: void SetUp() final { ASSERT_OK(InitArolla()); } }; TEST_F(FactoryOpsTest, DenseArrayShapeOfOp) { EXPECT_THAT(InvokeOperator<DenseArrayShape>("core._array_shape_of", DenseArray<Unit>{VoidBuffer(3)}), IsOkAndHolds(DenseArrayShape{3})); } TEST_F(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_F(FactoryOpsTest, ArrayShapeSize_DenseArray) { EXPECT_THAT( InvokeOperator<int64_t>("array.array_shape_size", DenseArrayShape{3}), IsOkAndHolds(Eq(3))); } TEST_F(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")); } } }
2,363
cpp
google/arolla
join
arolla/qexpr/operators/strings/join.cc
arolla/qexpr/operators/strings/join_test.cc
#ifndef AROLLA_QEXPR_OPERATORS_STRINGS_JOIN_H_ #define AROLLA_QEXPR_OPERATORS_STRINGS_JOIN_H_ #include <type_traits> #include "absl/status/statusor.h" #include "absl/strings/str_join.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "arolla/memory/optional_value.h" #include "arolla/qexpr/operators.h" #include "arolla/qtype/qtype.h" #include "arolla/util/bytes.h" #include "arolla/util/text.h" namespace arolla { constexpr absl::string_view kJoinOperatorName = "strings._join_with_separator"; class JoinOperatorFamily : public OperatorFamily { public: template <class Delimiter, class... Args> auto operator()(const Delimiter& delimiter, const Args&... args) const { static_assert(sizeof...(Args) > 0, "expected at least 2 arguments"); static_assert( std::is_same_v<Delimiter, Bytes> || std::is_same_v<Delimiter, Text>, "delimiter must be either Bytes or Text"); auto fn = [&delimiter](const strip_optional_t<Args>&... args) { return Delimiter(absl::StrJoin({args...}, delimiter)); }; if constexpr ((::arolla::is_optional_v<Args> || ...)) { return WrapFnToAcceptOptionalArgs(fn)(args...); } else { return fn(args...); } } private: absl::StatusOr<OperatorPtr> DoGetOperator( absl::Span<const QTypePtr> input_types, QTypePtr output_type) const final; }; } #endif #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(std::string(kJoinOperatorName), 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/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/testing/status_matchers_backport.h" #include "arolla/util/text.h" using ::testing::HasSubstr; namespace arolla { using ::arolla::testing::IsOkAndHolds; using ::arolla::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); } }
2,364
cpp
google/arolla
strings
arolla/qexpr/operators/strings/strings.cc
arolla/qexpr/operators/strings/strings_test.cc
#ifndef AROLLA_QEXPR_OPERATORS_STRINGS_STRINGS_H_ #define AROLLA_QEXPR_OPERATORS_STRINGS_STRINGS_H_ #include <bitset> #include <cctype> #include <charconv> #include <cstdint> #include <limits> #include <optional> #include <string> #include <system_error> #include <utility> #include "absl/container/flat_hash_set.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/ascii.h" #include "absl/strings/charconv.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "icu4c/source/common/unicode/uchar.h" #include "icu4c/source/common/unicode/unistr.h" #include "icu4c/source/common/unicode/utf16.h" #include "icu4c/source/common/unicode/utf8.h" #include "icu4c/source/common/unicode/utypes.h" #include "arolla/memory/optional_value.h" #include "arolla/qtype/base_types.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 { struct LowerOp { absl::StatusOr<Text> operator()( absl::string_view in, std::optional<absl::string_view> locale = std::nullopt) const; absl::StatusOr<Text> operator()(const Text& in) const { return this->operator()(absl::string_view(in)); } absl::StatusOr<Text> operator()(const Text& in, const Text& locale) const { return this->operator()(absl::string_view(in), absl::string_view(locale)); } }; struct UpperOp { absl::StatusOr<Text> operator()( absl::string_view in, std::optional<absl::string_view> locale = std::nullopt) const; absl::StatusOr<Text> operator()(const Text& in) const { return this->operator()(absl::string_view(in)); } absl::StatusOr<Text> operator()(const Text& in, const Text& locale) const { return this->operator()(absl::string_view(in), absl::string_view(locale)); } }; struct ReplaceOp { absl::StatusOr<std::string> operator()(absl::string_view s, absl::string_view old_sub, absl::string_view new_sub, OptionalValue<int32_t> max_subs) const; template <typename StringType> absl::StatusOr<StringType> operator()(const StringType& str, const StringType& old_sub, const StringType& new_sub, OptionalValue<int32_t> max_subs) const { ASSIGN_OR_RETURN( auto result, this->operator()(absl::string_view(str), absl::string_view(old_sub), absl::string_view(new_sub), max_subs)); return StringType(result); } }; struct LStripOp { Bytes operator()(const Bytes& bytes, const OptionalValue<Bytes>& chars) const { auto do_lstrip = [](absl::string_view s, auto strip_test) { const char* b = s.data(); const char* e = s.data() + s.length() - 1; while (b <= e && strip_test(*b)) { ++b; } return absl::string_view(b, e - b + 1); }; if (chars.present) { std::bitset<256> char_set(256); for (char c : absl::string_view(chars.value)) { char_set.set(static_cast<int>(c)); } return Bytes(do_lstrip(bytes, [&](char c) { return char_set.test(c); })); } else { return Bytes( do_lstrip(bytes, [&](char c) { return absl::ascii_isspace(c); })); } } Text operator()(const Text& text, const OptionalValue<Text>& chars) const { auto do_lstrip = [](absl::string_view s, auto strip_test) { int pref = 0; for (int i = 0; i < s.length();) { UChar32 c; U8_NEXT(s.data(), i, s.length(), c); if (!strip_test(c)) { break; } pref = i; } return Text(absl::string_view(s.data() + pref, s.length() - pref)); }; if (!chars.present) { return Text( do_lstrip(text, [](UChar32 c) { return u_isUWhiteSpace(c); })); } absl::string_view chars_bytes = chars.value; absl::flat_hash_set<UChar32> set; for (int i = 0; i < chars_bytes.length();) { UChar32 c; U8_NEXT(chars_bytes.data(), i, chars_bytes.length(), c); set.insert(c); } return Text(do_lstrip(text, [&](UChar32 c) { return set.contains(c); })); } }; struct RStripOp { Bytes operator()(const Bytes& bytes, const OptionalValue<Bytes>& chars) const { auto do_rstrip = [](absl::string_view s, auto strip_test) { const char* b = s.data(); const char* e = s.data() + s.length() - 1; while (b <= e && strip_test(*e)) { --e; } return absl::string_view(b, e - b + 1); }; if (chars.present) { std::bitset<256> char_set(256); for (char c : absl::string_view(chars.value)) { char_set.set(static_cast<int>(c)); } return Bytes(do_rstrip(bytes, [&](char c) { return char_set.test(c); })); } else { return Bytes( do_rstrip(bytes, [&](char c) { return absl::ascii_isspace(c); })); } } Text operator()(const Text& text, const OptionalValue<Text>& chars) const { auto do_rstrip = [](absl::string_view s, auto strip_test) { int len = s.length(); for (int i = s.length(); i > 0;) { UChar32 c; U8_PREV(s.data(), 0, i, c); if (!strip_test(c)) { break; } len = i; } return Text(absl::string_view(s.data(), len)); }; if (!chars.present) { return Text( do_rstrip(text, [](UChar32 c) { return u_isUWhiteSpace(c); })); } absl::string_view chars_bytes = chars.value; absl::flat_hash_set<UChar32> set; for (int i = 0; i < chars_bytes.length();) { UChar32 c; U8_NEXT(chars_bytes.data(), i, chars_bytes.length(), c); set.insert(c); } return Text(do_rstrip(text, [&](UChar32 c) { return set.contains(c); })); } }; struct StripOp { absl::StatusOr<Bytes> operator()(const Bytes& bytes, const OptionalValue<Bytes>& chars) const { return RStripOp()(LStripOp()(bytes, chars), chars); } absl::StatusOr<Text> operator()(const Text& text, const OptionalValue<Text>& chars) const { return RStripOp()(LStripOp()(text, chars), chars); } }; struct BytesLengthOp { int32_t operator()(absl::string_view s) const { return s.length(); } int32_t operator()(const Bytes& bytes) const { return this->operator()(absl::string_view(bytes)); } }; struct TextLengthOp { int32_t operator()(absl::string_view s) const { return icu::UnicodeString::fromUTF8(s).countChar32(); } int32_t operator()(const Text& text) const { return this->operator()(absl::string_view(text)); } }; struct AsTextOp { Text operator()(absl::string_view s) const; Text operator()(const Bytes& x) const; Text operator()(Unit) const; Text operator()(int32_t x) const; Text operator()(int64_t x) const; Text operator()(uint64_t x) const; Text operator()(float x) const; Text operator()(double x) const; Text operator()(bool x) const; }; struct TextAsTextOp { Text operator()(absl::string_view s) const; Text operator()(const Text& s) const; }; struct EncodeOp { Bytes operator()(absl::string_view s) const { return Bytes(s); } Bytes operator()(const Text& text) const { return Bytes(absl::string_view(text)); } }; struct DecodeOp { absl::StatusOr<Text> operator()(absl::string_view s) const; auto operator()(const Bytes& bytes) const { return (*this)(absl::string_view(bytes)); } }; struct CompileRegexOp { absl::StatusOr<Regex> operator()(const Text& pattern) const { return Regex::FromPattern(pattern); } }; struct ContainsRegexOp { OptionalUnit operator()(const Text& text, const Regex& regexp) const; OptionalUnit operator()(const OptionalValue<Text>& text, const Regex& regexp) const { return text.present ? (*this)(text.value, regexp) : kMissing; } }; struct ExtractRegexOp { absl::StatusOr<OptionalValue<Text>> operator()(const Text& text, const Regex& regexp) const; absl::StatusOr<OptionalValue<Text>> operator()( const OptionalValue<Text>& text, const Regex& regexp) const { return text.present ? (*this)(text.value, regexp) : OptionalValue<Text>{}; } }; template <typename FloatT> bool ParseFloatT(absl::string_view str, FloatT& result) { if (!str.empty() && str[0] == '+') { str.remove_prefix(1); if (!str.empty() && str[0] == '-') { return false; } } if (str.size() >= 2 && (str[1] == 'x' || str[1] == 'X')) { return false; if (str.size() >= 3 && (str[2] == 'x' || str[2] == 'X')) { return false; } } auto [ptr, ec] = absl::from_chars(str.data(), str.data() + str.size(), result); if (ptr != str.data() + str.size()) { return false; } if (ec == std::errc::result_out_of_range) { if (result > 1.0) { result = std::numeric_limits<FloatT>::infinity(); } else if (result < -1.0) { result = -std::numeric_limits<FloatT>::infinity(); } return true; } return ec == std::errc(); } template <typename IntT> bool ParseIntT(absl::string_view str, IntT& result) { if (!str.empty() && str[0] == '+') { str.remove_prefix(1); if (!str.empty() && str[0] == '-') { return false; } } auto [ptr, ec] = std::from_chars(str.data(), str.data() + str.size(), result, 10); return ec == std::errc() && ptr == str.data() + str.size(); } struct StringsParseFloat32 { absl::StatusOr<float> operator()(absl::string_view str) const { float result; if (ParseFloatT(str, result)) { return result; } return absl::InvalidArgumentError( absl::StrCat("unable to parse FLOAT32: ", str)); } auto operator()(const ::arolla::Bytes& s) const { return (*this)(absl::string_view(s)); } auto operator()(const ::arolla::Text& s) const { return (*this)(absl::string_view(s)); } }; struct StringsParseFloat64 { absl::StatusOr<double> operator()(absl::string_view str) const { double result; if (ParseFloatT(str, result)) { return result; } return absl::InvalidArgumentError( absl::StrCat("unable to parse FLOAT64: ", str)); } auto operator()(const ::arolla::Bytes& s) const { return (*this)(absl::string_view(s)); } auto operator()(const ::arolla::Text& s) const { return (*this)(absl::string_view(s)); } }; struct StringsParseInt32 { absl::StatusOr<int32_t> operator()(absl::string_view str) const { int32_t result; if (ParseIntT(str, result)) { return result; } return absl::InvalidArgumentError( absl::StrCat("unable to parse INT32: ", str)); } auto operator()(const ::arolla::Bytes& s) const { return (*this)(absl::string_view(s)); } auto operator()(const ::arolla::Text& s) const { return (*this)(absl::string_view(s)); } }; struct StringsParseInt64 { absl::StatusOr<int64_t> operator()(absl::string_view str) const { int64_t result; if (ParseIntT(str, result)) { return result; } return absl::InvalidArgumentError( absl::StrCat("unable to parse INT64: ", str)); } auto operator()(const ::arolla::Bytes& s) const { return (*this)(absl::string_view(s)); } auto operator()(const ::arolla::Text& s) const { return (*this)(absl::string_view(s)); } }; } #endif #include "arolla/qexpr/operators/strings/strings.h" #include <cstddef> #include <cstdint> #include <limits> #include <optional> #include <string> #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/indestructible.h" #include "arolla/util/text.h" #include "arolla/util/unit.h" #include "re2/re2.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(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(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 && (max_subs.value >= 0)) { count = max_subs.value; } std::string res; if (count == 0) { return 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; } OptionalUnit ContainsRegexOp::operator()(const Text& text, const Regex& regexp) const { return OptionalUnit{ RE2::PartialMatch(absl::string_view(text), regexp.value())}; } absl::StatusOr<OptionalValue<Text>> ExtractRegexOp::operator()( const Text& text, const Regex& regexp) const { const auto& re = regexp.value(); if (re.NumberOfCapturingGroups() != 1) { return absl::InvalidArgumentError( absl::StrFormat("ExtractRegexOp expected regular expression with " "exactly one capturing group; got `%s` which " "contains %d capturing groups.", re.pattern(), re.NumberOfCapturingGroups())); } std::string match; if (RE2::PartialMatch(text.view(), re, &match)) { return Text(match); } else { return OptionalValue<Text>(); } } 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("unit"); } 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 Indestructible<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 Indestructible<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 "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/strings/regex.h" #include "arolla/util/bytes.h" #include "arolla/util/init_arolla.h" #include "arolla/util/testing/status_matchers_backport.h" #include "arolla/util/text.h" #include "arolla/util/unit.h" using ::testing::HasSubstr; namespace arolla { using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::StatusIs; using ::testing::ElementsAre; using ::testing::HasSubstr; namespace { class StringsTest : public ::testing::Test { void SetUp() final { ASSERT_OK(InitArolla()); } }; TEST_F(StringsTest, AsText) { EXPECT_THAT(InvokeOperator<Text>("strings.as_text", kUnit), IsOkAndHolds(Text("unit"))); 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_F(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_F(StringsTest, Lower) { Text input("Hello World."); Text expected_output("hello world."); EXPECT_THAT(InvokeOperator<Text>("strings.lower", input), IsOkAndHolds(expected_output)); } TEST_F(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_F(StringsTest, LowerWithLocale) { Text input("TITLE"); Text locale("TR_tr"); EXPECT_THAT(InvokeOperator<Text>("strings.lower", input, locale), IsOkAndHolds(Text("tıtle"))); } TEST_F(StringsTest, Upper) { Text input("Hello World."); EXPECT_THAT(InvokeOperator<Text>("strings.upper", input), IsOkAndHolds(Text("HELLO WORLD."))); } TEST_F(StringsTest, UpperWithLocale) { Text input("istanbul"); Text locale("TR_tr"); EXPECT_THAT(InvokeOperator<Text>("strings.upper", input, locale), IsOkAndHolds(Text("İSTANBUL"))); } TEST_F(StringsTest, BytesLength) { EXPECT_THAT(InvokeOperator<int32_t>("strings.length", Bytes("古池や蛙飛び込む水の音")), IsOkAndHolds(33)); } TEST_F(StringsTest, TextLength) { EXPECT_THAT( InvokeOperator<int32_t>("strings.length", Text("古池や蛙飛び込む水の音")), IsOkAndHolds(11)); } TEST_F(StringsTest, ContainsRegex) { ASSERT_OK_AND_ASSIGN( Regex regex, InvokeOperator<Regex>("strings._compile_regex", Text("^\\d{1,3} bottles of beer"))); EXPECT_THAT(InvokeOperator<OptionalUnit>("strings._contains_regex", Text("999 bottles of beer"), regex), IsOkAndHolds(kPresent)); EXPECT_THAT(InvokeOperator<OptionalUnit>("strings._contains_regex", Text("1000 bottles of beer"), regex), IsOkAndHolds(kMissing)); } TEST_F(StringsTest, ExtractRegex) { using OT = OptionalValue<Text>; ASSERT_OK_AND_ASSIGN( Regex regex1, InvokeOperator<Regex>("strings._compile_regex", Text("bar:(\\w*)"))); EXPECT_THAT(InvokeOperator<OT>("strings._extract_regex", Text("foo:abc, bar:def, baz:ghi"), regex1), IsOkAndHolds(Text("def"))); EXPECT_THAT(InvokeOperator<OT>("strings._extract_regex", Text("foo:abc, baz:ghi"), regex1), IsOkAndHolds(OT{})); ASSERT_OK_AND_ASSIGN( Regex regex2, InvokeOperator<Regex>("strings._compile_regex", Text("bar:\\w*"))); EXPECT_THAT( InvokeOperator<OT>("strings._extract_regex", Text("foo:abc, bar:def, baz:ghi"), regex2), StatusIs( absl::StatusCode::kInvalidArgument, HasSubstr( "expected regular expression with exactly one capturing group"))); } TEST_F(StringsTest, InvalidRegex) { EXPECT_THAT(InvokeOperator<Regex>("strings._compile_regex", Text("ab\\αcd")), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("Invalid regular expression: \"ab\\αcd\"; "))); } } }
2,365
cpp
google/arolla
format
arolla/qexpr/operators/strings/format.cc
arolla/qexpr/operators/strings/format_test.cc
#ifndef AROLLA_QEXPR_OPERATORS_STRINGS_FORMAT_H_ #define AROLLA_QEXPR_OPERATORS_STRINGS_FORMAT_H_ #include <cstdint> #include <string> #include <type_traits> #include <utility> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "arolla/memory/optional_value.h" #include "arolla/qexpr/operators.h" #include "arolla/qtype/qtype.h" #include "arolla/util/bytes.h" namespace arolla { constexpr absl::string_view kFormatOperatorName = "strings.format"; class FormatOperatorFamily : public OperatorFamily { public: using returns_status_or = std::true_type; template <class... Args> auto operator()(const Args&... args) const { if constexpr ((is_optional_v<Args> || ...)) { if ((ArgPresent(args) && ...)) { auto res_or = FormatImpl(ArgValue(args)...); if (res_or.ok()) { return absl::StatusOr<OptionalValue<Bytes>>(res_or.value()); } else { return absl::StatusOr<OptionalValue<Bytes>>(res_or.status()); } } else { return absl::StatusOr<OptionalValue<Bytes>>(OptionalValue<Bytes>()); } } else { return FormatImpl(args...); } } private: template <typename T> bool ArgPresent(const T& arg) const { if constexpr (is_optional_v<T>) { return arg.present; } else { return true; } } template <typename T> const auto& ArgValue(const T& arg) const { if constexpr (is_optional_v<T>) { return arg.value; } else { return arg; } } template <typename T> static constexpr bool IsSupportedArgType() { return std::is_same_v<T, int32_t> || std::is_same_v<T, int64_t> || std::is_same_v<T, float> || std::is_same_v<T, double> || std::is_same_v<T, Bytes> || std::is_same_v<T, bool>; } template <typename... Args> struct FirstUnsupported; template <typename Arg> struct FirstUnsupported<Arg> { using type = Arg; }; template <typename Arg, typename... Args> struct FirstUnsupported<Arg, Args...> { using type = std::conditional_t<IsSupportedArgType<Arg>(), typename FirstUnsupported<Args...>::type, Arg>; }; template <class... Args> absl::StatusOr<Bytes> FormatImpl(const Bytes& format_spec, const Args&... args) const { if constexpr ((IsSupportedArgType<Args>() && ...)) { absl::UntypedFormatSpec fmt(format_spec); std::string out; if (absl::FormatUntyped(&out, fmt, {absl::FormatArg(args)...})) { return Bytes(std::move(out)); } else { return absl::InvalidArgumentError(absl::StrFormat( "format specification '%s' doesn't match format arguments", format_spec)); } } else { return absl::InvalidArgumentError(absl::StrFormat( "%s is not a supported format argument type", GetQType<typename FirstUnsupported<Args...>::type>()->name())); } } absl::StatusOr<OperatorPtr> DoGetOperator( absl::Span<const QTypePtr> input_types, QTypePtr output_type) const final; }; } #endif #include "arolla/qexpr/operators/strings/format.h" #include <cstddef> #include <cstdint> #include <deque> #include <memory> #include <string> #include <utility> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "absl/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/qtype/typed_ref.h" #include "arolla/qtype/typed_slot.h" #include "arolla/qtype/weak_qtype.h" #include "arolla/util/bytes.h" #include "arolla/util/indestructible.h" #include "arolla/util/status_macros_backport.h" namespace arolla { namespace { 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 Indestructible<absl::flat_hash_map<QTypePtr, WrapValueFn>> converter_map([](void* self) { new (self) absl::flat_hash_map<QTypePtr, WrapValueFn>{ {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_; }; class FormatBoundOperator : public BoundOperator { public: FormatBoundOperator(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 FormatOperator : public QExprOperator { public: explicit FormatOperator(const QExprOperatorSignature* type) : QExprOperator(std::string(kFormatOperatorName), 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; Slot<Bytes> format_spec_slot = Slot<Bytes>::UnsafeSlotFromOffset( 0); if (IsOptionalQType(typed_input_slots[0].GetType())) { DCHECK_EQ(typed_input_slots[0].SubSlotCount(), 2); ASSIGN_OR_RETURN(auto presence_slot, typed_input_slots[0].SubSlot(0).ToSlot<bool>()); presence_slots.push_back(presence_slot); ASSIGN_OR_RETURN(format_spec_slot, typed_input_slots[0].SubSlot(1).ToSlot<Bytes>()); } else { ASSIGN_OR_RETURN(format_spec_slot, typed_input_slots[0].ToSlot<Bytes>()); } auto arg_slots = typed_input_slots.subspan(1); std::vector<SlotFormatter> slot_formatters; slot_formatters.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)); } 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<FormatBoundOperator>( format_spec_slot, slot_formatters, output_slot)}; } else { ASSIGN_OR_RETURN(Slot<OptionalValue<Bytes>> output_slot, typed_output_slot.ToSlot<OptionalValue<Bytes>>()); FormatBoundOperator format_op(format_spec_slot, slot_formatters, GetValueSubslotFromOptional(output_slot)); return {std::unique_ptr<BoundOperator>(new WhereAllBoundOperator( presence_slots, GetPresenceSubslotFromOptional(output_slot), std::move(format_op)))}; } } }; } absl::StatusOr<OperatorPtr> FormatOperatorFamily::DoGetOperator( absl::Span<const QTypePtr> input_types, QTypePtr output_type) const { if (input_types.empty()) { return OperatorNotDefinedError(kFormatOperatorName, input_types, "expected at least 1 argument"); } if (DecayOptionalQType(input_types[0]) != GetQType<Bytes>()) { return OperatorNotDefinedError(kFormatOperatorName, 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<FormatOperator>( QExprOperatorSignature::Get(input_types, result_type))), input_types, output_type); } }
#include "arolla/qexpr/operators/strings/format.h" #include <cstdint> #include <type_traits> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.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/testing/status_matchers_backport.h" #include "arolla/util/text.h" namespace arolla { using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::StatusIs; using ::testing::HasSubstr; namespace { template <typename EvalAsFunctor> class FormatTest : public ::testing::Test { public: template <typename... Args> absl::StatusOr<Bytes> InvokeOperator(const Args&... args) { if constexpr (EvalAsFunctor::value) { auto result = FormatOperatorFamily{}(args...); static_assert(std::is_same_v<decltype(result), absl::StatusOr<Bytes>>); return result; } else { return ::arolla::InvokeOperator<Bytes>("strings._format_bytes", args...); } } template <typename... Args> absl::StatusOr<OptionalValue<Bytes>> InvokeOperatorOptional( const Args&... args) { if constexpr (EvalAsFunctor::value) { auto result = FormatOperatorFamily{}(args...); static_assert(std::is_same_v<decltype(result), absl::StatusOr<OptionalValue<Bytes>>>); return result; } else { return ::arolla::InvokeOperator<OptionalValue<Bytes>>( "strings._format_bytes", args...); } } }; TYPED_TEST_SUITE_P(FormatTest); TYPED_TEST_P(FormatTest, 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(FormatTest, 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(FormatTest, 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(FormatTest, 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(FormatTest, 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(FormatTest, 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(FormatTest, FormatFloats, FormatIntegers, FormatText, FormatOptional, FormatMismatchedTypes, FormatUnsupportedType); INSTANTIATE_TYPED_TEST_SUITE_P(Operator, FormatTest, std::bool_constant<false>); INSTANTIATE_TYPED_TEST_SUITE_P(Functor, FormatTest, std::bool_constant<true>); } }
2,366
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 <type_traits> #include "absl/status/statusor.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/operators.h" #include "arolla/qtype/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; } }; class PresenceOrVarargsOperatorFamily : public OperatorFamily { absl::StatusOr<OperatorPtr> DoGetOperator( absl::Span<const QTypePtr> input_types, QTypePtr output_type) const final; }; 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 : public OperatorFamily { absl::StatusOr<OperatorPtr> DoGetOperator( absl::Span<const QTypePtr> input_types, QTypePtr output_type) const final; }; } #endif #include "arolla/qexpr/operators/core/logic_operators.h" #include <algorithm> #include <iterator> #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/string_view.h" #include "absl/types/span.h" #include "arolla/memory/frame.h" #include "arolla/memory/optional_value.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/standard_type_properties/common_qtype.h" #include "arolla/util/unit.h" #include "arolla/util/status_macros_backport.h" namespace arolla { template <typename T> using Slot = FrameLayout::Slot<T>; constexpr absl::string_view kPresenceOrVarargsOperatorName = "core._presence_or"; namespace { class PresenceOrVarargsOperator : public QExprOperator { public: explicit PresenceOrVarargsOperator(const QExprOperatorSignature* qtype) : QExprOperator(std::string(kPresenceOrVarargsOperatorName), qtype) {} private: absl::StatusOr<std::unique_ptr<BoundOperator>> DoBind( absl::Span<const TypedSlot> input_slots, TypedSlot output_slot) const override { std::vector<Slot<bool>> presence_in_slots; presence_in_slots.reserve(input_slots.size()); std::vector<TypedSlot> value_in_slots; value_in_slots.reserve(input_slots.size()); for (int i = 0; i < input_slots.size(); ++i) { if (IsOptionalQType(input_slots[i].GetType())) { ASSIGN_OR_RETURN(Slot<bool> presence_in_slot, GetPresenceSubslotFromOptional(input_slots[i])); presence_in_slots.push_back(presence_in_slot); ASSIGN_OR_RETURN(TypedSlot value_in_slot, GetValueSubslotFromOptional(input_slots[i])); value_in_slots.push_back(value_in_slot); } else { DCHECK(i == input_slots.size() - 1); value_in_slots.push_back(input_slots[i]); } } if (IsOptionalQType(output_slot.GetType())) { ASSIGN_OR_RETURN(Slot<bool> presence_out_slot, GetPresenceSubslotFromOptional(output_slot)); ASSIGN_OR_RETURN(TypedSlot value_out_slot, GetValueSubslotFromOptional(output_slot)); return std::make_unique<BoundImpl>(presence_in_slots, value_in_slots, presence_out_slot, value_out_slot); } else { return std::make_unique<BoundImpl>(presence_in_slots, value_in_slots, std::nullopt, output_slot); } } class BoundImpl : public BoundOperator { public: BoundImpl(std::vector<Slot<bool>> presence_in_slots, std::vector<TypedSlot> value_in_slots, std::optional<Slot<bool>> presence_out_slot, TypedSlot value_out_slot) : presence_in_slots_(std::move(presence_in_slots)), value_in_slots_(std::move(value_in_slots)), presence_out_slot_(presence_out_slot), value_out_slot_(value_out_slot) { if (presence_out_slot_.has_value()) { DCHECK_EQ(value_in_slots_.size(), presence_in_slots_.size()); } else { DCHECK_EQ(value_in_slots_.size(), presence_in_slots_.size() + 1); } } void Run(EvaluationContext*, FramePtr frame) const override { auto iter = std::find_if(presence_in_slots_.begin(), presence_in_slots_.end(), [&frame](Slot<bool> slot) { return frame.Get(slot); }); int position = std::distance(presence_in_slots_.begin(), iter); bool has_output = position < value_in_slots_.size(); if (presence_out_slot_.has_value()) { frame.Set(*presence_out_slot_, has_output); } if (has_output) { value_in_slots_[position].CopyTo(frame, value_out_slot_, frame); } } private: std::vector<Slot<bool>> presence_in_slots_; std::vector<TypedSlot> value_in_slots_; std::optional<Slot<bool>> presence_out_slot_; TypedSlot value_out_slot_; }; }; class PresenceOrVarargsUnitOperator : public QExprOperator { public: explicit PresenceOrVarargsUnitOperator(const QExprOperatorSignature* qtype) : QExprOperator(std::string(kPresenceOrVarargsOperatorName), qtype) {} private: absl::StatusOr<std::unique_ptr<BoundOperator>> DoBind( absl::Span<const TypedSlot> input_slots, TypedSlot output_slot) const override { std::vector<Slot<bool>> presence_in_slots; presence_in_slots.reserve(input_slots.size()); for (int i = 0; i < input_slots.size(); ++i) { ASSIGN_OR_RETURN(Slot<bool> presence_in_slot, GetPresenceSubslotFromOptional(input_slots[i])); presence_in_slots.push_back(presence_in_slot); } ASSIGN_OR_RETURN(Slot<bool> presence_out_slot, GetPresenceSubslotFromOptional(output_slot)); return std::make_unique<BoundImpl>(presence_in_slots, presence_out_slot); } class BoundImpl : public BoundOperator { public: BoundImpl(std::vector<Slot<bool>> presence_in_slots, Slot<bool> presence_out_slot) : presence_in_slots_(std::move(presence_in_slots)), presence_out_slot_(presence_out_slot) {} void Run(EvaluationContext*, FramePtr frame) const override { bool any_present = std::any_of(presence_in_slots_.begin(), presence_in_slots_.end(), [&frame](Slot<bool> slot) { return frame.Get(slot); }); frame.Set(presence_out_slot_, any_present); } private: std::vector<Slot<bool>> presence_in_slots_; Slot<bool> presence_out_slot_; }; }; class FakeShortCircuitWhereOperator : public QExprOperator { public: explicit FakeShortCircuitWhereOperator(const QExprOperatorSignature* qtype) : QExprOperator("core._short_circuit_where", qtype) {} 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"); } }; } absl::StatusOr<OperatorPtr> PresenceOrVarargsOperatorFamily::DoGetOperator( absl::Span<const QTypePtr> input_types, QTypePtr output_type) const { auto not_defined_error = [&](absl::string_view detail) { return OperatorNotDefinedError(kPresenceOrVarargsOperatorName, input_types, detail); }; if (input_types.size() < 2) { return not_defined_error("expected at least two arguments"); } for (int i = 0; i < input_types.size() - 1; ++i) { if (!IsOptionalQType(input_types[i])) { return not_defined_error( "expected all except last argument to be optional"); } } QTypePtr first_value_type = DecayOptionalQType(input_types[0]); for (int i = 1; i < input_types.size(); ++i) { QTypePtr value_type = DecayOptionalQType(input_types[i]); if (value_type != first_value_type) { return not_defined_error( "expected all arguments to have a common value type"); } } bool has_optional_output = IsOptionalQType(input_types.back()); const QExprOperatorSignature* op_qtype = QExprOperatorSignature::Get(input_types, input_types.back()); OperatorPtr op; if (first_value_type == GetQType<Unit>()) { if (has_optional_output) { op = std::make_unique<PresenceOrVarargsUnitOperator>(op_qtype); } else { return not_defined_error( "for Unit value type, expected final argument to be optional"); } } else { op = std::make_unique<PresenceOrVarargsOperator>(op_qtype); } return EnsureOutputQTypeMatches(op, input_types, output_type); } absl::StatusOr<OperatorPtr> FakeShortCircuitWhereOperatorFamily::DoGetOperator( absl::Span<const QTypePtr> input_types, QTypePtr output_type) const { 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); } }
#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/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/init_arolla.h" #include "arolla/util/testing/status_matchers_backport.h" #include "arolla/util/text.h" #include "arolla/util/unit.h" namespace arolla { namespace { using ::arolla::testing::IsOkAndHolds; using ::arolla::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; class LogicOperatorsTest : public ::testing::Test { void SetUp() final { ASSERT_OK(InitArolla()); } }; TEST_F(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_F(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_F(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_F(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_F(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_F(LogicOperatorsTest, PresenceOrVarargs) { 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<OptionalUnit>("core._presence_or", kMissing, kMissing, kMissing, kPresent), IsOkAndHolds(kPresent)); EXPECT_THAT(InvokeOperator<OptionalUnit>("core._presence_or", kMissing, kMissing, kMissing, kMissing), IsOkAndHolds(kMissing)); 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<int64_t>("core._presence_or", missing, missing, optional_two, one), IsOkAndHolds(two)); EXPECT_THAT(InvokeOperator<int64_t>("core._presence_or", missing, missing, missing, one), IsOkAndHolds(one)); 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)); EXPECT_THAT(InvokeOperator<Oi64>("core._presence_or", missing, missing, optional_two, missing, optional_one), IsOkAndHolds(optional_two)); EXPECT_THAT(InvokeOperator<Oi64>("core._presence_or", missing, missing, missing, missing, missing), IsOkAndHolds(missing)); EXPECT_THAT(InvokeOperator<OptionalUnit>("core._presence_or", kMissing), StatusIs(absl::StatusCode::kNotFound, HasSubstr("expected at least two arguments"))); EXPECT_THAT( InvokeOperator<int64_t>("core._presence_or", one, two), StatusIs(absl::StatusCode::kNotFound, HasSubstr("expected all except last argument to be optional"))); EXPECT_THAT( InvokeOperator<OptionalUnit>("core._presence_or", kMissing, two), StatusIs( absl::StatusCode::kNotFound, HasSubstr("expected all arguments to have a common value type"))); EXPECT_THAT( InvokeOperator<OptionalUnit>("core._presence_or", kMissing, Unit{}), StatusIs( absl::StatusCode::kNotFound, HasSubstr( "for Unit value type, expected final argument to be optional"))); } TEST_F(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_F(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_F(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_F(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_F(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_F(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_F(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_F(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_F(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_F(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_F(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); } } }
2,367
cpp
google/arolla
utility_operators
arolla/qexpr/operators/core/utility_operators.cc
arolla/qexpr/operators/core/utility_operators_test.cc
#ifndef AROLLA_QEXPR_CORE_UTILITY_OPERATORS_H_ #define AROLLA_QEXPR_CORE_UTILITY_OPERATORS_H_ #include "arolla/qexpr/operators.h" #include "arolla/qtype/qtype.h" namespace arolla { OperatorPtr MakeCopyOp(QTypePtr type); } #endif #include "arolla/qexpr/operators/core/utility_operators.h" #include <memory> #include <string> #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("core._copy", 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)); } } }
2,368
cpp
google/arolla
seq_reduce_operator
arolla/qexpr/eval_extensions/seq_reduce_operator.cc
arolla/qexpr/eval_extensions/seq_reduce_operator_test.cc
#ifndef AROLLA_QEXPR_EVAL_EXTENSIONS_SEQ_REDUCE_OPERATOR_H_ #define AROLLA_QEXPR_EVAL_EXTENSIONS_SEQ_REDUCE_OPERATOR_H_ #include "absl/status/statusor.h" #include "absl/types/span.h" #include "arolla/expr/basic_expr_operator.h" #include "arolla/expr/expr_attributes.h" #include "arolla/expr/expr_operator.h" namespace arolla::expr::eval_internal { class PackedSeqReduceOperator final : public BuiltinExprOperatorTag, public ExprOperatorWithFixedSignature { public: explicit PackedSeqReduceOperator(ExprOperatorPtr op); const ExprOperatorPtr& op() const { return op_; } absl::StatusOr<ExprAttributes> InferAttributes( absl::Span<const ExprAttributes> inputs) const final; private: ExprOperatorPtr op_; }; } #endif #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_REGISTER_INITIALIZER( kRegisterQExprOperators, seq_reduce_operator_eval_extensions, [] { ::arolla::expr::eval_internal::CompilerExtensionRegistry::GetInstance() .RegisterNodeTransformationFn(SeqReduceOperatorTransformation); ::arolla::expr::eval_internal::CompilerExtensionRegistry::GetInstance() .RegisterCompileOperatorFn(CompilePackedSeqReduceOperator); }); }
#include "arolla/qexpr/eval_extensions/seq_reduce_operator.h" #include <cstdint> #include "gmock/gmock.h" #include "gtest/gtest.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" #include "arolla/util/init_arolla.h" #include "arolla/util/testing/status_matchers_backport.h" namespace arolla::expr::eval_internal { namespace { using ::arolla::testing::EqualsExpr; using ::arolla::testing::IsOkAndHolds; using ::testing::ElementsAre; using ::testing::Eq; using ::testing::NotNull; class SeqReduceOperatorTest : public ::testing::Test { protected: void SetUp() override { ASSERT_OK(InitArolla()); } }; TEST_F(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_F(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])")))); } } }
2,369
cpp
google/arolla
seq_map_operator
arolla/qexpr/eval_extensions/seq_map_operator.cc
arolla/qexpr/eval_extensions/seq_map_operator_test.cc
#ifndef AROLLA_QEXPR_EVAL_EXTENSIONS_SEQ_MAP_OPERATOR_H_ #define AROLLA_QEXPR_EVAL_EXTENSIONS_SEQ_MAP_OPERATOR_H_ #include "absl/status/statusor.h" #include "absl/types/span.h" #include "arolla/expr/basic_expr_operator.h" #include "arolla/expr/expr_attributes.h" #include "arolla/expr/expr_operator.h" namespace arolla::expr::eval_internal { class PackedSeqMapOperator final : public BuiltinExprOperatorTag, public ExprOperatorWithFixedSignature { public: explicit PackedSeqMapOperator(ExprOperatorPtr op); const ExprOperatorPtr& op() const { return op_; } absl::StatusOr<ExprAttributes> InferAttributes( absl::Span<const ExprAttributes> inputs) const final; private: ExprOperatorPtr op_; }; } #endif #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_REGISTER_INITIALIZER( kRegisterQExprOperators, seq_map_operator_eval_extensions, [] { 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 "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" #include "arolla/util/init_arolla.h" #include "arolla/util/testing/status_matchers_backport.h" namespace arolla::expr::eval_internal { namespace { using ::arolla::testing::EqualsExpr; using ::arolla::testing::IsOkAndHolds; using ::testing::ElementsAre; using ::testing::Eq; using ::testing::NotNull; class SeqMapOperatorTest : public ::testing::Test { protected: void SetUp() override { ASSERT_OK(InitArolla()); } }; TEST_F(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_F(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])")))); } } }
2,370
cpp
google/arolla
lazy
arolla/lazy/lazy.cc
arolla/lazy/lazy_test.cc
#ifndef AROLLA_LAZY_LAZY_H_ #define AROLLA_LAZY_LAZY_H_ #include <memory> #include "absl/functional/any_invocable.h" #include "absl/status/statusor.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/typed_value.h" #include "arolla/util/fingerprint.h" #include "arolla/util/repr.h" namespace arolla { class Lazy { public: Lazy(const Lazy&) = delete; Lazy& operator=(const Lazy&) = delete; QTypePtr value_qtype() const { return value_qtype_; } const Fingerprint& fingerprint() const { return fingerprint_; } virtual absl::StatusOr<TypedValue> Get() const = 0; virtual ~Lazy() = default; protected: Lazy(QTypePtr value_qtype, const Fingerprint& fingerprint) : value_qtype_(value_qtype), fingerprint_(fingerprint) {} private: QTypePtr value_qtype_; Fingerprint fingerprint_; }; using LazyPtr = std::shared_ptr<const Lazy>; LazyPtr MakeLazyFromQValue(TypedValue value); LazyPtr MakeLazyFromCallable( QTypePtr value_qtype, absl::AnyInvocable<absl::StatusOr<TypedValue>() const> callable); AROLLA_DECLARE_FINGERPRINT_HASHER_TRAITS(LazyPtr); AROLLA_DECLARE_REPR(LazyPtr); } #endif #include "arolla/lazy/lazy.h" #include <memory> #include <utility> #include "absl/functional/any_invocable.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/qtype/qtype.h" #include "arolla/qtype/typed_value.h" #include "arolla/util/fingerprint.h" #include "arolla/util/repr.h" namespace arolla { namespace { class LazyValue final : public Lazy { public: explicit LazyValue(TypedValue&& value) : Lazy(value.GetType(), FingerprintHasher("::arolla::LazyValue") .Combine(value.GetFingerprint()) .Finish()), value_(std::move(value)) {} absl::StatusOr<TypedValue> Get() const final { return value_; } private: TypedValue value_; }; class LazyCallable final : public Lazy { public: using Callable = absl::AnyInvocable<absl::StatusOr<TypedValue>() const>; explicit LazyCallable(QTypePtr value_qtype, Callable&& callable) : Lazy(value_qtype, RandomFingerprint()), callable_(std::move(callable)) {} absl::StatusOr<TypedValue> Get() const final { auto result = callable_(); if (result.ok() && result->GetType() != value_qtype()) { return absl::FailedPreconditionError( absl::StrFormat("expected a lazy callable to return %s, got %s", value_qtype()->name(), result->GetType()->name())); } return result; } private: Callable callable_; }; } LazyPtr MakeLazyFromQValue(TypedValue value) { return std::make_shared<LazyValue>(std::move(value)); } LazyPtr MakeLazyFromCallable(QTypePtr value_qtype, LazyCallable::Callable callable) { return std::make_shared<LazyCallable>(value_qtype, std::move(callable)); } void FingerprintHasherTraits<LazyPtr>::operator()(FingerprintHasher* hasher, const LazyPtr& value) const { if (value != nullptr) { hasher->Combine(value->fingerprint()); } } ReprToken ReprTraits<LazyPtr>::operator()(const LazyPtr& value) const { if (value == nullptr) { return ReprToken{"lazy[?]{nullptr}"}; } return ReprToken{absl::StrCat("lazy[", value->value_qtype()->name(), "]")}; } }
#include "arolla/lazy/lazy.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/testing/qtype.h" #include "arolla/qtype/typed_value.h" #include "arolla/util/fingerprint.h" #include "arolla/util/init_arolla.h" #include "arolla/util/repr.h" #include "arolla/util/testing/status_matchers_backport.h" namespace arolla { namespace { using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::StatusIs; using ::arolla::testing::TypedValueWith; class LazyTest : public ::testing::Test { void SetUp() override { ASSERT_OK(InitArolla()); } }; TEST_F(LazyTest, MakeLazyFromQValue) { auto x = MakeLazyFromQValue(TypedValue::FromValue(GetQTypeQType())); EXPECT_EQ(x->value_qtype(), GetQTypeQType()); EXPECT_EQ(Repr(x), "lazy[QTYPE]"); EXPECT_THAT(x->Get(), IsOkAndHolds(TypedValueWith<QTypePtr>(GetQTypeQType()))); } TEST_F(LazyTest, LazyValueFingerprint) { EXPECT_EQ( MakeLazyFromQValue(TypedValue::FromValue(GetQTypeQType()))->fingerprint(), MakeLazyFromQValue(TypedValue::FromValue(GetQTypeQType())) ->fingerprint()); EXPECT_NE( MakeLazyFromQValue(TypedValue::FromValue(GetQTypeQType()))->fingerprint(), MakeLazyFromQValue(TypedValue::FromValue(GetNothingQType())) ->fingerprint()); } TEST_F(LazyTest, MakeLazyFromCallable) { auto x = MakeLazyFromCallable( GetQTypeQType(), [] { return TypedValue::FromValue(GetNothingQType()); }); EXPECT_EQ(x->value_qtype(), GetQTypeQType()); EXPECT_EQ(Repr(x), "lazy[QTYPE]"); EXPECT_THAT(x->Get(), IsOkAndHolds(TypedValueWith<QTypePtr>(GetNothingQType()))); } TEST_F(LazyTest, LazyCallableFingerprint) { auto x = MakeLazyFromCallable( GetQTypeQType(), [] { return TypedValue::FromValue(GetNothingQType()); }); auto y = MakeLazyFromCallable( GetQTypeQType(), [] { return TypedValue::FromValue(GetNothingQType()); }); EXPECT_EQ(x->fingerprint(), x->fingerprint()); EXPECT_NE(x->fingerprint(), y->fingerprint()); } TEST_F(LazyTest, LazyCallableError) { auto x = MakeLazyFromCallable( GetQTypeQType(), [] { return absl::InvalidArgumentError("error"); }); EXPECT_EQ(x->value_qtype(), GetQTypeQType()); EXPECT_EQ(Repr(x), "lazy[QTYPE]"); EXPECT_THAT(x->Get(), StatusIs(absl::StatusCode::kInvalidArgument, "error")); } TEST_F(LazyTest, Nullptr) { LazyPtr x; EXPECT_EQ(Repr(x), "lazy[?]{nullptr}"); EXPECT_EQ(FingerprintHasher("salt").Combine(x).Finish(), FingerprintHasher("salt").Combine(x).Finish()); } } }
2,371
cpp
google/arolla
lazy_qtype
arolla/lazy/lazy_qtype.cc
arolla/lazy/lazy_qtype_test.cc
#ifndef AROLLA_LAZY_LAZY_QTYPE_H_ #define AROLLA_LAZY_LAZY_QTYPE_H_ #include "absl/base/nullability.h" #include "arolla/lazy/lazy.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/typed_value.h" namespace arolla { bool IsLazyQType(absl::Nullable<const QType*> qtype); QTypePtr GetLazyQType(QTypePtr value_qtype); template <typename T> QTypePtr GetLazyQType() { return GetLazyQType(GetQType<T>()); } TypedValue MakeLazyQValue(LazyPtr lazy); } #endif #include "arolla/lazy/lazy_qtype.h" #include <memory> #include <string> #include <utility> #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/indestructible.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 Indestructible<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 "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/init_arolla.h" #include "arolla/util/testing/repr_token_eq.h" #include "arolla/util/testing/status_matchers_backport.h" namespace arolla { namespace { using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::ReprTokenEq; using ::arolla::testing::TypedValueWith; class LazyQTypeTest : public ::testing::Test { void SetUp() override { ASSERT_OK(InitArolla()); } }; TEST_F(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_F(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_F(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()); } } }
2,372
cpp
google/arolla
jagged_shape
arolla/jagged_shape/dense_array/jagged_shape.cc
arolla/jagged_shape/jagged_shape_test.cc
#ifndef AROLLA_JAGGED_SHAPE_DENSE_ARRAY_JAGGED_SHAPE_H_ #define AROLLA_JAGGED_SHAPE_DENSE_ARRAY_JAGGED_SHAPE_H_ #include "arolla/dense_array/edge.h" #include "arolla/jagged_shape/jagged_shape.h" #include "arolla/util/repr.h" namespace arolla { using JaggedDenseArrayShape = JaggedShape<DenseArrayEdge>; using JaggedDenseArrayShapePtr = JaggedDenseArrayShape::ShapePtr; AROLLA_DECLARE_REPR(JaggedDenseArrayShape); } #endif #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/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" #include "arolla/util/testing/status_matchers_backport.h" using ::arolla::testing::ReprTokenEq; using ::arolla::testing::StatusIs; using ::testing::ElementsAre; namespace arolla { namespace { class JaggedArrayShapeHelper { public: using Shape = JaggedArrayShape; using ShapePtr = Shape::ShapePtr; 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 ShapePtr = Shape::ShapePtr; 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 ShapePtr = typename JaggedShapeHelper::ShapePtr; }; 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, NotMovableAndCopyableClass) { using Shape = typename TestFixture::Shape; 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>); } TYPED_TEST(JaggedShapeTest, MovableAndCopyablePtr) { using Shape = typename TestFixture::Shape; using ShapePtr = typename TestFixture::ShapePtr; 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)})); ShapePtr 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)})); ShapePtr 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, PtrT) { using ShapePtr = typename TestFixture::Shape::ShapePtr; using TestShapePtr = typename TestFixture::Helper::ShapePtr; static_assert(std::is_same_v<S
2,373
cpp
google/arolla
decoder
arolla/jagged_shape/dense_array/serialization_codecs/decoder.cc
arolla/serialization_base/decoder_test.cc
#ifndef AROLLA_SERIALIZATION_BASE_DECODER_H_ #define AROLLA_SERIALIZATION_BASE_DECODER_H_ #include <cstdint> #include <deque> #include <functional> #include <string> #include <vector> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "arolla/expr/expr_node.h" #include "arolla/qtype/typed_value.h" #include "arolla/serialization_base/base.pb.h" #include "arolla/serialization_base/container.h" namespace arolla::serialization_base { struct NoExtensionFound {}; using ValueDecoderResult = std::variant<TypedValue, NoExtensionFound>; using ValueDecoder = std::function<absl::StatusOr<ValueDecoderResult>( const ValueProto& value_proto, absl::Span<const TypedValue> input_values, absl::Span<const arolla::expr::ExprNodePtr> input_exprs)>; using ValueDecoderProvider = std::function<absl::StatusOr<ValueDecoder>(absl::string_view codec_name)>; class Decoder final : public ContainerProcessor { public: struct Options { bool infer_attributes_for_operator_nodes = true; }; struct Result { std::vector<TypedValue> values; std::vector<arolla::expr::ExprNodePtr> exprs; }; Decoder(ValueDecoderProvider value_decoder_provider, const Options& options); absl::Status OnDecodingStep( uint64_t decoding_step_index, const DecodingStepProto& decoding_step_proto) final; Result Finish() &&; private: struct Codec { std::string codec_name; ValueDecoder value_decoder; }; struct DecodingStepResult { const TypedValue* value = nullptr; const arolla::expr::ExprNode* expr = nullptr; const Codec* codec = nullptr; }; absl::StatusOr<arolla::expr::ExprNodePtr> DecodeLiteralNode( const LiteralNodeProto& literal_node_proto) const; absl::StatusOr<arolla::expr::ExprNodePtr> DecodeLeafNode( const LeafNodeProto& leaf_node_proto) const; absl::StatusOr<arolla::expr::ExprNodePtr> DecodePlaceholderNode( const PlaceholderNodeProto& placeholder_node_proto) const; absl::StatusOr<arolla::expr::ExprNodePtr> DecodeOperatorNode( const OperatorNodeProto& operator_node_proto) const; absl::StatusOr<TypedValue> DecodeValue(const ValueProto& value_proto) const; absl::StatusOr<TypedValue> DecodeValueWithKnownCodec( const ValueProto& value_proto, uint64_t codec_index, absl::Span<const TypedValue> input_values, absl::Span<const arolla::expr::ExprNodePtr> input_exprs) const; absl::StatusOr<TypedValue> DecodeValueWithUnknownCodec( const ValueProto& value_proto, absl::Span<const TypedValue> input_values, absl::Span<const arolla::expr::ExprNodePtr> input_exprs) const; absl::StatusOr<Codec> DecodeCodec(const CodecProto& codec_proto) const; absl::Status StoreDecodedValue(uint64_t value_index, TypedValue&& value); absl::Status StoreDecodedExpr(uint64_t expr_index, arolla::expr::ExprNodePtr&& expr); absl::Status StoreDecodedCodec(uint64_t codec_index, Codec&& codec); absl::StatusOr<TypedValue> LoadDecodedValue(uint64_t value_index) const; absl::StatusOr<arolla::expr::ExprNodePtr> LoadDecodedExpr( uint64_t expr_index) const; ValueDecoderProvider value_decoder_provider_; Options options_; std::deque<TypedValue> know_values_; std::deque<arolla::expr::ExprNodePtr> know_exprs_; std::deque<Codec> know_codecs_; std::vector<DecodingStepResult> decoding_step_results_; Result result_; }; } #endif #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/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" #include "arolla/util/init_arolla.h" #include "arolla/util/testing/status_matchers_backport.h" namespace arolla::serialization_base { namespace { 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::StatusIs; 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)>; class DecodeTest : public ::testing::Test { protected: void SetUp() override { ASSERT_OK(InitArolla()); } }; TEST_F(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_F(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_F(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_F(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_F(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_F(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_F(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_F(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_F(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_F(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_F(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_F(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_F(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_F(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_F(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_F(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_F(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_F(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_F(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_F(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_F(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_F(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_F(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_F(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_F(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_F(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_F(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_F(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_F(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_F(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_F(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; " "
2,374
cpp
google/arolla
encoder
arolla/jagged_shape/dense_array/serialization_codecs/encoder.cc
arolla/serialization_base/encoder_test.cc
#ifndef AROLLA_SERIALIZATION_BASE_ENCODER_H_ #define AROLLA_SERIALIZATION_BASE_ENCODER_H_ #include <cstdint> #include <functional> #include <string> #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/expr/expr_node.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/fingerprint.h" namespace arolla::serialization_base { class Encoder; using ValueEncoder = std::function<absl::StatusOr<ValueProto>(TypedRef value, Encoder& encoder)>; class Encoder { public: explicit Encoder(ValueEncoder value_encoder, ContainerBuilder& container_builder); virtual ~Encoder() = default; Encoder(const Encoder&) = delete; Encoder& operator=(const Encoder&) = delete; absl::StatusOr<uint64_t> EncodeCodec(absl::string_view codec); absl::StatusOr<uint64_t> EncodeValue(const TypedValue& value); absl::StatusOr<uint64_t> EncodeExpr(const arolla::expr::ExprNodePtr& expr); private: absl::Status EncodeExprNode(const arolla::expr::ExprNode& expr_node); absl::Status EncodeLiteralNode(const arolla::expr::ExprNode& expr_node); absl::Status EncodeLeafNode(const arolla::expr::ExprNode& expr_node); absl::Status EncodePlaceholderNode(const arolla::expr::ExprNode& expr_node); absl::Status EncodeOperatorNode(const arolla::expr::ExprNode& expr_node); ValueEncoder value_encoder_; ContainerBuilder& container_builder_; uint64_t nesting_ = 0; absl::flat_hash_map<std::string, uint64_t> known_codecs_; absl::flat_hash_map<Fingerprint, uint64_t> known_values_; absl::flat_hash_map<Fingerprint, uint64_t> known_exprs_; }; } #endif #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/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/init_arolla.h" #include "arolla/util/testing/equals_proto.h" #include "arolla/util/testing/status_matchers_backport.h" namespace arolla::serialization_base { namespace { 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 ::arolla::testing::IsOkAndHolds; using ::arolla::testing::StatusIs; 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: void SetUp() override { ASSERT_OK(InitArolla()); } 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)); } } }
2,375
cpp
google/arolla
repr
arolla/jagged_shape/util/repr.cc
arolla/jagged_shape/util/repr_test.cc
#ifndef AROLLA_UTIL_REPR_H_ #define AROLLA_UTIL_REPR_H_ #include <cstdint> #include <string> #include <type_traits> #include <vector> #include "arolla/util/fingerprint.h" namespace arolla { struct ReprToken { struct Precedence { int8_t left = -1; int8_t right = -1; }; static constexpr Precedence kHighest{-1, -1}; static constexpr Precedence kSafeForSubscription = kHighest; static constexpr Precedence kSafeForNegation{0, 0}; static constexpr Precedence kSafeForArithmetic{1, 1}; static constexpr Precedence kOpSubscription{0, -1}; std::string str; Precedence precedence = kHighest; }; AROLLA_DECLARE_FINGERPRINT_HASHER_TRAITS(ReprToken::Precedence); AROLLA_DECLARE_FINGERPRINT_HASHER_TRAITS(ReprToken); template <typename T, typename Enabled = void> struct ReprTraits {}; template <typename T> struct ReprTraits<T, std::void_t<decltype(static_cast<ReprToken (T::*)() const>( &T::ArollaReprToken))>> { ReprToken operator()(const T& value) const { return value.ArollaReprToken(); } }; template <typename T> auto GenReprToken(const T& value) -> decltype(ReprTraits<T>()(value)) { return ReprTraits<T>()(value); } template <typename T> auto Repr(const T& value) -> decltype(GenReprToken(value).str) { return std::move(GenReprToken(value).str); } ReprToken GenReprTokenWeakFloat(double value); #define AROLLA_DECLARE_REPR(CPP_TYPE) \ template <> \ struct ReprTraits<CPP_TYPE> { \ ReprToken operator()(const CPP_TYPE& value) const; \ } AROLLA_DECLARE_REPR(bool); AROLLA_DECLARE_REPR(int32_t); AROLLA_DECLARE_REPR(int64_t); AROLLA_DECLARE_REPR(uint64_t); AROLLA_DECLARE_REPR(float); AROLLA_DECLARE_REPR(double); namespace repr_traits_vector_bool_ref_impl { struct FakeStdVectorBoolConstRef; using StdVectorBoolConstRef = std::conditional_t< std::is_same_v<bool, std::decay_t<std::vector<bool>::const_reference>>, repr_traits_vector_bool_ref_impl::FakeStdVectorBoolConstRef, std::decay_t<std::vector<bool>::const_reference>>; } template <> struct ReprTraits<repr_traits_vector_bool_ref_impl::StdVectorBoolConstRef> : ReprTraits<bool> {}; } #endif #include "arolla/util/repr.h" #include <cstdint> #include <string> #include "absl/strings/str_cat.h" #include "double-conversion/double-to-string.h" #include "double-conversion/utils.h" #include "arolla/util/fingerprint.h" namespace arolla { ReprToken ReprTraits<bool>::operator()(const bool& value) const { return ReprToken{value ? "true" : "false"}; } ReprToken ReprTraits<int32_t>::operator()(const int32_t& value) const { ReprToken result{absl::StrCat(value)}; if (result.str[0] == '-') { result.precedence = ReprToken::kSafeForArithmetic; } else { result.precedence = ReprToken::kSafeForNegation; } return result; } ReprToken ReprTraits<int64_t>::operator()(const int64_t& value) const { return ReprToken{absl::StrCat("int64{", value, "}")}; } ReprToken ReprTraits<uint64_t>::operator()(const uint64_t& value) const { return ReprToken{absl::StrCat("uint64{", value, "}")}; } using double_conversion::DoubleToStringConverter; ReprToken ReprTraits<float>::operator()(const float& value) const { static const DoubleToStringConverter converter( DoubleToStringConverter::EMIT_TRAILING_DECIMAL_POINT, "inf", "nan", 'e', -6, 21, 6, 0); char buf[128]; double_conversion::StringBuilder builder(buf, sizeof(buf)); converter.ToShortestSingle(value, &builder); ReprToken result{builder.Finalize()}; if (result.str[0] == '-') { result.precedence = ReprToken::kSafeForArithmetic; } else { result.precedence = ReprToken::kSafeForNegation; } return result; } ReprToken ReprTraits<double>::operator()(const double& value) const { static const DoubleToStringConverter converter( DoubleToStringConverter::NO_FLAGS, "inf", "nan", 'e', -6, 21, 6, 0); char buf[128]; double_conversion::StringBuilder builder(buf, sizeof(buf)); builder.AddString("float64{"); converter.ToShortest(value, &builder); builder.AddString("}"); return ReprToken{builder.Finalize()}; } ReprToken GenReprTokenWeakFloat(double value) { static const DoubleToStringConverter converter( DoubleToStringConverter::NO_FLAGS, "inf", "nan", 'e', -6, 21, 6, 0); char buf[128]; double_conversion::StringBuilder builder(buf, sizeof(buf)); builder.AddString("weak_float{"); converter.ToShortest(value, &builder); builder.AddString("}"); return ReprToken{builder.Finalize()}; } void FingerprintHasherTraits<ReprToken::Precedence>::operator()( FingerprintHasher* hasher, const ReprToken::Precedence& value) const { hasher->Combine(value.left, value.right); } void FingerprintHasherTraits<ReprToken>::operator()( FingerprintHasher* hasher, const ReprToken& value) const { hasher->Combine(value.str, value.precedence); } }
#include "arolla/util/repr.h" #include <cstdint> #include <limits> #include <string> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "arolla/util/fingerprint.h" #include "arolla/util/testing/repr_token_eq.h" namespace arolla { namespace { using ::arolla::testing::ReprTokenEq; TEST(ReprTest, Bool) { EXPECT_THAT(GenReprToken(true), ReprTokenEq("true")); EXPECT_THAT(GenReprToken(false), ReprTokenEq("false")); } TEST(ReprTest, VectorBoolConstReference) { const std::vector<bool> vector = {true}; EXPECT_THAT(GenReprToken(vector[0]), ReprTokenEq("true")); } TEST(ReprTest, int32_t) { EXPECT_THAT(GenReprToken(int32_t{-1}), ReprTokenEq("-1", ReprToken::kSafeForArithmetic)); EXPECT_THAT(GenReprToken(int32_t{0}), ReprTokenEq("0", ReprToken::kSafeForNegation)); EXPECT_THAT(GenReprToken(int32_t{1}), ReprTokenEq("1", ReprToken::kSafeForNegation)); } TEST(ReprTest, int64_t) { EXPECT_THAT(GenReprToken(int64_t{-1}), ReprTokenEq("int64{-1}")); EXPECT_THAT(GenReprToken(int64_t{0}), ReprTokenEq("int64{0}")); EXPECT_THAT(GenReprToken(int64_t{1}), ReprTokenEq("int64{1}")); } TEST(ReprTest, float32) { EXPECT_THAT(GenReprToken(float{-1.}), ReprTokenEq("-1.", ReprToken::kSafeForArithmetic)); EXPECT_THAT(GenReprToken(float{-0.}), ReprTokenEq("-0.", ReprToken::kSafeForArithmetic)); EXPECT_THAT(GenReprToken(float{0.}), ReprTokenEq("0.", ReprToken::kSafeForNegation)); EXPECT_THAT(GenReprToken(float{1}), ReprTokenEq("1.", ReprToken::kSafeForNegation)); EXPECT_THAT(GenReprToken(float{0.2}), ReprTokenEq("0.2", ReprToken::kSafeForNegation)); EXPECT_THAT(GenReprToken(float{1e30}), ReprTokenEq("1e30", ReprToken::kSafeForNegation)); EXPECT_THAT(GenReprToken(float{1e-30}), ReprTokenEq("1e-30", ReprToken::kSafeForNegation)); EXPECT_THAT(GenReprToken(std::numeric_limits<float>::infinity()), ReprTokenEq("inf", ReprToken::kSafeForNegation)); EXPECT_THAT(GenReprToken(-std::numeric_limits<float>::infinity()), ReprTokenEq("-inf", ReprToken::kSafeForArithmetic)); EXPECT_THAT(GenReprToken(std::numeric_limits<float>::quiet_NaN()), ReprTokenEq("nan", ReprToken::kSafeForNegation)); EXPECT_THAT(GenReprToken(-std::numeric_limits<float>::quiet_NaN()), ReprTokenEq("nan", ReprToken::kSafeForNegation)); EXPECT_THAT(GenReprToken(std::numeric_limits<float>::signaling_NaN()), ReprTokenEq("nan", ReprToken::kSafeForNegation)); EXPECT_THAT(GenReprToken(-std::numeric_limits<float>::signaling_NaN()), ReprTokenEq("nan", ReprToken::kSafeForNegation)); } TEST(ReprTest, float64) { EXPECT_THAT(GenReprToken(double{-1.}), ReprTokenEq("float64{-1}")); EXPECT_THAT(GenReprToken(double{-0.}), ReprTokenEq("float64{-0}")); EXPECT_THAT(GenReprToken(double{0.}), ReprTokenEq("float64{0}")); EXPECT_THAT(GenReprToken(double{1}), ReprTokenEq("float64{1}")); EXPECT_THAT(GenReprToken(double{0.2}), ReprTokenEq("float64{0.2}")); EXPECT_THAT(GenReprToken(double{1e30}), ReprTokenEq("float64{1e30}")); EXPECT_THAT(GenReprToken(double{1e-30}), ReprTokenEq("float64{1e-30}")); EXPECT_THAT(GenReprToken(std::numeric_limits<double>::infinity()), ReprTokenEq("float64{inf}")); EXPECT_THAT(GenReprToken(-std::numeric_limits<double>::infinity()), ReprTokenEq("float64{-inf}")); EXPECT_THAT(GenReprToken(std::numeric_limits<double>::quiet_NaN()), ReprTokenEq("float64{nan}")); EXPECT_THAT(GenReprToken(-std::numeric_limits<double>::quiet_NaN()), ReprTokenEq("float64{nan}")); EXPECT_THAT(GenReprToken(double{0.2f}), ReprTokenEq("float64{0.20000000298023224}")); } TEST(ReprTest, weak_float) { EXPECT_THAT(GenReprTokenWeakFloat(double{-1.}), ReprTokenEq("weak_float{-1}")); EXPECT_THAT(GenReprTokenWeakFloat(double{-0.}), ReprTokenEq("weak_float{-0}")); EXPECT_THAT(GenReprTokenWeakFloat(double{0.}), ReprTokenEq("weak_float{0}")); EXPECT_THAT(GenReprTokenWeakFloat(double{1}), ReprTokenEq("weak_float{1}")); EXPECT_THAT(GenReprTokenWeakFloat(double{0.2}), ReprTokenEq("weak_float{0.2}")); EXPECT_THAT(GenReprTokenWeakFloat(double{1e30}), ReprTokenEq("weak_float{1e30}")); EXPECT_THAT(GenReprTokenWeakFloat(double{1e-30}), ReprTokenEq("weak_float{1e-30}")); EXPECT_THAT(GenReprTokenWeakFloat(std::numeric_limits<double>::infinity()), ReprTokenEq("weak_float{inf}")); EXPECT_THAT(GenReprTokenWeakFloat(-std::numeric_limits<double>::infinity()), ReprTokenEq("weak_float{-inf}")); EXPECT_THAT(GenReprTokenWeakFloat(std::numeric_limits<double>::quiet_NaN()), ReprTokenEq("weak_float{nan}")); EXPECT_THAT(GenReprTokenWeakFloat(-std::numeric_limits<double>::quiet_NaN()), ReprTokenEq("weak_float{nan}")); EXPECT_THAT(GenReprTokenWeakFloat(double{0.2f}), ReprTokenEq("weak_float{0.20000000298023224}")); } TEST(ReprTest, fingerprint) { auto fp = [](const auto& value) { return FingerprintHasher("").Combine(value).Finish(); }; ReprToken::Precedence p01{0, 1}; { auto p01_hash = fp(p01); EXPECT_EQ(p01_hash, fp(p01)); EXPECT_NE(p01_hash, fp(ReprToken::Precedence{0, 0})); EXPECT_NE(p01_hash, fp(ReprToken::Precedence{1, 1})); } { ReprToken abc{.str = "abc"}; auto abc_hash = fp(abc); EXPECT_EQ(abc_hash, fp(abc)); EXPECT_NE(abc_hash, fp(ReprToken{.str = "foo"})); auto abc_p01_hash = fp(ReprToken{.str = "abc", .precedence = p01}); EXPECT_EQ(abc_p01_hash, fp(ReprToken{.str = "abc", .precedence = p01})); EXPECT_NE( abc_p01_hash, fp(ReprToken{.str = "abc", .precedence = ReprToken::Precedence{0, 0}})); } } struct ClassWithArollaReprToken { std::string v; ReprToken ArollaReprToken() const { return {v}; } }; TEST(ReprTest, ClassWithArollaReprToken) { ReprTraits<ClassWithArollaReprToken> traits; EXPECT_EQ(traits(ClassWithArollaReprToken{"x"}).str, "x"); EXPECT_EQ(GenReprToken(ClassWithArollaReprToken{"x"}).str, "x"); EXPECT_EQ(Repr(ClassWithArollaReprToken{"x"}), "x"); } } }
2,376
cpp
google/arolla
control_flow_graph
arolla/algorithm/control_flow_graph.cc
arolla/algorithm/control_flow_graph_test.cc
#ifndef AROLLA_ALGORITHM_CONTROL_FLOW_GRAPH_H_ #define AROLLA_ALGORITHM_CONTROL_FLOW_GRAPH_H_ #include <cstdint> #include <memory> #include <utility> #include <vector> #include "absl/container/flat_hash_set.h" #include "absl/status/statusor.h" #include "absl/types/span.h" namespace arolla { class AcyclicCFG { public: using NodeId = int64_t; static absl::StatusOr<std::unique_ptr<AcyclicCFG>> Create( std::vector<std::vector<int64_t>> deps); int64_t num_nodes() const { return deps_.size(); } absl::Span<const NodeId> deps(NodeId id) const { return deps_[id]; } absl::Span<const NodeId> reverse_deps(NodeId id) const { return reverse_deps_[id]; } private: explicit AcyclicCFG(std::vector<std::vector<NodeId>> deps, std::vector<std::vector<NodeId>> reverse_deps) : deps_(std::move(deps)), reverse_deps_(std::move(reverse_deps)) {} std::vector<std::vector<NodeId>> deps_; std::vector<std::vector<NodeId>> reverse_deps_; }; class DominatorTree { public: using NodeId = AcyclicCFG::NodeId; explicit DominatorTree(const AcyclicCFG& graph); int64_t num_nodes() const { return infos_.size(); } NodeId parent(NodeId node_id) const { return infos_[node_id].parent; } std::vector<NodeId> parents() const { std::vector<NodeId> result(num_nodes()); for (NodeId node_id = 0; node_id != num_nodes(); ++node_id) { result[node_id] = infos_[node_id].parent; } return result; } int64_t depth(NodeId node_id) const { return infos_[node_id].depth; } absl::Span<const NodeId> children(NodeId node_id) const { return infos_[node_id].children; } private: struct Info { NodeId parent; int64_t depth; std::vector<NodeId> children; }; NodeId Lca(NodeId a, NodeId b); NodeId Lca(absl::Span<const NodeId> nodes); std::vector<Info> infos_; }; absl::StatusOr<std::unique_ptr<AcyclicCFG>> ExternalizeNodes( const AcyclicCFG& graph, const DominatorTree& tree, const absl::flat_hash_set<AcyclicCFG::NodeId>& global_nodes = {}); std::vector<bool> FindVerticesWithEmptyDominanceFrontier( const AcyclicCFG& graph, const DominatorTree& tree); } #endif #include "arolla/algorithm/control_flow_graph.h" #include <algorithm> #include <cstdint> #include <memory> #include <utility> #include <vector> #include "absl/container/flat_hash_set.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "absl/types/span.h" namespace arolla { using NodeId = AcyclicCFG::NodeId; absl::StatusOr<std::unique_ptr<AcyclicCFG>> AcyclicCFG::Create( std::vector<std::vector<NodeId>> deps) { const int64_t n = deps.size(); if (n == 0) { return absl::FailedPreconditionError("at least one node is expected"); } std::vector<std::vector<int64_t>> reverse_deps(n); for (NodeId node = 0; node != n; ++node) { for (int64_t dep : deps[node]) { if (dep <= node) { return absl::FailedPreconditionError(absl::StrFormat( "all edges must be directed to the larger index, found %d -> %d", node, dep)); } if (dep >= n) { return absl::FailedPreconditionError( absl::StrFormat("vertex id %d is out of range", dep)); } reverse_deps[dep].push_back(node); } } for (NodeId node = 1; node != n; ++node) { if (reverse_deps[node].empty()) { return absl::FailedPreconditionError(absl::StrFormat( "all vertices must be reachable from root, %d has no reverse deps", node)); } } return std::unique_ptr<AcyclicCFG>( new AcyclicCFG(std::move(deps), std::move(reverse_deps))); } DominatorTree::DominatorTree(const AcyclicCFG& graph) : infos_(graph.num_nodes()) { const int64_t n = graph.num_nodes(); infos_[0].parent = 0; infos_[0].depth = 0; for (NodeId node = 1; node != n; ++node) { auto& info = infos_[node]; info.parent = Lca(graph.reverse_deps(node)); info.depth = depth(info.parent) + 1; infos_[info.parent].children.push_back(node); } } NodeId DominatorTree::Lca(NodeId a, NodeId b) { if (depth(a) < depth(b)) { using std::swap; swap(a, b); } while (depth(a) > depth(b)) { a = parent(a); } while (a != b) { a = parent(a); b = parent(b); } return a; } NodeId DominatorTree::Lca(absl::Span<const NodeId> nodes) { auto res = nodes[0]; for (const auto& node : nodes) { res = Lca(res, node); } return res; } absl::StatusOr<std::unique_ptr<AcyclicCFG>> ExternalizeNodes( const AcyclicCFG& graph, const DominatorTree& tree, const absl::flat_hash_set<NodeId>& global_nodes) { const int64_t n = graph.num_nodes(); std::vector<std::vector<NodeId>> deps(n); for (NodeId node_id = 0; node_id < n; ++node_id) { if (global_nodes.contains(node_id) && node_id != 0) { deps[tree.parent(node_id)].push_back(node_id); } deps[node_id].reserve(graph.deps(node_id).size()); for (NodeId dep : graph.deps(node_id)) { if (!global_nodes.contains(dep)) { deps[node_id].push_back(dep); } } } return AcyclicCFG::Create(std::move(deps)); } std::vector<bool> FindVerticesWithEmptyDominanceFrontier( const AcyclicCFG& graph, const DominatorTree& tree) { int64_t n = graph.num_nodes(); std::vector<int64_t> min_over_deps_dominator_depth(n); std::vector<bool> empty_frontier(n); for (NodeId node_id = n - 1; node_id >= 0; --node_id) { int64_t min_depth = tree.depth(node_id); for (NodeId dep : graph.deps(node_id)) { min_depth = std::min(min_depth, std::min(min_over_deps_dominator_depth[dep], tree.depth(dep) - 1)); } empty_frontier[node_id] = (min_depth == tree.depth(node_id)); min_over_deps_dominator_depth[node_id] = min_depth; } return empty_frontier; } }
#include "arolla/algorithm/control_flow_graph.h" #include <cstddef> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "arolla/util/testing/status_matchers_backport.h" namespace arolla { namespace { using ::arolla::testing::StatusIs; using ::testing::ElementsAre; using ::testing::HasSubstr; using ::testing::IsEmpty; TEST(AcyclicCFG, Empty) { ASSERT_OK_AND_ASSIGN(auto g, AcyclicCFG::Create({{}})); EXPECT_EQ(g->num_nodes(), 1); EXPECT_THAT(g->deps(0), IsEmpty()); EXPECT_THAT(g->reverse_deps(0), IsEmpty()); } TEST(AcyclicCFG, Simple) { ASSERT_OK_AND_ASSIGN(auto g, AcyclicCFG::Create({ {1, 3}, {2, 3}, {}, {}, })); EXPECT_EQ(g->num_nodes(), 4); EXPECT_THAT(g->deps(0), ElementsAre(1, 3)); EXPECT_THAT(g->deps(1), ElementsAre(2, 3)); EXPECT_THAT(g->deps(2), IsEmpty()); EXPECT_THAT(g->deps(3), IsEmpty()); EXPECT_THAT(g->reverse_deps(0), IsEmpty()); EXPECT_THAT(g->reverse_deps(1), ElementsAre(0)); EXPECT_THAT(g->reverse_deps(2), ElementsAre(1)); EXPECT_THAT(g->reverse_deps(3), ElementsAre(0, 1)); } TEST(AcyclicCFG, Errors) { EXPECT_THAT( AcyclicCFG::Create({{0}}).status(), StatusIs(absl::StatusCode::kFailedPrecondition, HasSubstr("directed"))); EXPECT_THAT(AcyclicCFG::Create({{1}}).status(), StatusIs(absl::StatusCode::kFailedPrecondition, HasSubstr("out of range"))); EXPECT_THAT( AcyclicCFG::Create({{1}, {0}}).status(), StatusIs(absl::StatusCode::kFailedPrecondition, HasSubstr("directed"))); EXPECT_THAT( AcyclicCFG::Create({{1}, {}, {}}).status(), StatusIs(absl::StatusCode::kFailedPrecondition, HasSubstr("reachable"))); } TEST(DominatorTree, Chain) { ASSERT_OK_AND_ASSIGN(auto graph, AcyclicCFG::Create({{1}, {2}, {3}, {}})); DominatorTree tree(*graph); auto empty_frontier = FindVerticesWithEmptyDominanceFrontier(*graph, tree); for (size_t i = 0; i != graph->num_nodes(); ++i) { EXPECT_EQ(tree.depth(i), i); EXPECT_EQ(tree.parent(i), i == 0 ? i : i - 1) << i; if (i + 1 != graph->num_nodes()) { EXPECT_THAT(tree.children(i), ElementsAre(i + 1)); } else { EXPECT_THAT(tree.children(i), IsEmpty()) << i; } EXPECT_TRUE(empty_frontier[i]) << i; } } TEST(DominatorTree, WikiTest) { ASSERT_OK_AND_ASSIGN(auto graph, AcyclicCFG::Create({ {1}, {2, 3, 5}, {4}, {4}, {}, {} })); DominatorTree tree(*graph); auto empty_frontier = FindVerticesWithEmptyDominanceFrontier(*graph, tree); EXPECT_EQ(tree.depth(0), 0); EXPECT_EQ(tree.parent(0), 0); EXPECT_THAT(tree.children(0), ElementsAre(1)); EXPECT_TRUE(empty_frontier[0]); EXPECT_EQ(tree.depth(1), 1); EXPECT_EQ(tree.parent(1), 0); EXPECT_THAT(tree.children(1), ElementsAre(2, 3, 4, 5)); EXPECT_TRUE(empty_frontier[1]); for (size_t i = 2; i != 6; ++i) { EXPECT_EQ(tree.depth(i), 2) << i; EXPECT_EQ(tree.parent(i), 1) << i; EXPECT_THAT(tree.children(i), IsEmpty()) << i; } EXPECT_FALSE(empty_frontier[2]); EXPECT_FALSE(empty_frontier[3]); EXPECT_TRUE(empty_frontier[4]); EXPECT_TRUE(empty_frontier[5]); } TEST(DominatorTree, TwoChainsConnectedNearTheMiddle) { ASSERT_OK_AND_ASSIGN(auto graph, AcyclicCFG::Create({ {1}, {2, 6}, {3}, {4}, {5, 7}, {8}, {7}, {8}, {9}, {}, })); DominatorTree tree(*graph); auto empty_frontier = FindVerticesWithEmptyDominanceFrontier(*graph, tree); EXPECT_THAT(tree.parents(), ElementsAre(0, 0, 1, 2, 3, 4, 1, 1, 1, 8)); EXPECT_THAT(empty_frontier, ElementsAre(true, true, false, false, false, false, false, false, true, true)); } TEST(FindVerticesWithEmptyDominanceFrontier, ExternalizeLeaves) { ASSERT_OK_AND_ASSIGN(auto graph, AcyclicCFG::Create({ {1, 2}, {3}, {3}, {}, })); DominatorTree tree(*graph); ASSERT_OK_AND_ASSIGN(auto extern3_graph, ExternalizeNodes(*graph, tree, {3})); EXPECT_THAT(extern3_graph->deps(0), ElementsAre(1, 2, 3)); EXPECT_THAT(extern3_graph->deps(1), IsEmpty()); EXPECT_THAT(extern3_graph->deps(2), IsEmpty()); EXPECT_THAT(extern3_graph->deps(3), IsEmpty()); EXPECT_THAT(tree.parents(), ElementsAre(0, 0, 0, 0)); EXPECT_THAT(FindVerticesWithEmptyDominanceFrontier(*extern3_graph, tree), ElementsAre(true, true, true, true)); } TEST(FindVerticesWithEmptyDominanceFrontier, ExternalizeInternalNode) { ASSERT_OK_AND_ASSIGN(auto graph, AcyclicCFG::Create({ {1, 2}, {3}, {3}, {4}, {}, })); DominatorTree tree(*graph); EXPECT_THAT(tree.parents(), ElementsAre(0, 0, 0, 0, 3)); ASSERT_OK_AND_ASSIGN(auto extern3_graph, ExternalizeNodes(*graph, tree, {3})); EXPECT_THAT(extern3_graph->deps(0), ElementsAre(1, 2, 3)); EXPECT_THAT(extern3_graph->deps(1), IsEmpty()); EXPECT_THAT(extern3_graph->deps(2), IsEmpty()); EXPECT_THAT(extern3_graph->deps(3), ElementsAre(4)); EXPECT_THAT(extern3_graph->deps(4), IsEmpty()); EXPECT_THAT(FindVerticesWithEmptyDominanceFrontier(*extern3_graph, tree), ElementsAre(true, true, true, true, true)); } } }
2,377
cpp
google/arolla
types
arolla/proto/types.cc
arolla/proto/types_test.cc
#ifndef AROLLA_UTIL_TYPES_H_ #define AROLLA_UTIL_TYPES_H_ #include <cstddef> #include <type_traits> namespace arolla { using signed_size_t = typename std::make_signed<size_t>::type; } #endif #include "arolla/codegen/expr/types.h" #include <cstdint> #include <functional> #include <sstream> #include <string> #include <utility> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "absl/strings/str_join.h" #include "absl/strings/string_view.h" #include "absl/synchronization/mutex.h" #include "double-conversion/double-to-string.h" #include "double-conversion/utils.h" #include "arolla/dense_array/dense_array.h" #include "arolla/dense_array/edge.h" #include "arolla/dense_array/qtype/types.h" #include "arolla/memory/optional_value.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/optional_qtype.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/tuple_qtype.h" #include "arolla/qtype/typed_ref.h" #include "arolla/util/bytes.h" #include "arolla/util/indestructible.h" #include "arolla/util/string.h" #include "arolla/util/text.h" #include "arolla/util/unit.h" #include "arolla/util/status_macros_backport.h" namespace arolla::codegen { namespace { std::string CppLiteralReprImpl(Unit) { return "::arolla::kUnit"; } std::string CppLiteralReprImpl(bool value) { return value ? "true" : "false"; } std::string CppLiteralReprImpl(int32_t value) { return absl::StrFormat("int32_t{%d}", value); } std::string CppLiteralReprImpl(int64_t value) { return absl::StrFormat("int64_t{%d}", value); } std::string CppLiteralReprImpl(uint64_t value) { return absl::StrFormat("uint64_t{%dull}", value); } using double_conversion::DoubleToStringConverter; std::string CppLiteralReprImpl(float value) { static const DoubleToStringConverter converter( DoubleToStringConverter::EMIT_TRAILING_DECIMAL_POINT, "std::numeric_limits<float>::infinity()", "std::numeric_limits<float>::quiet_NaN()", 'e', -8, 21, 6, 0); char buf[128]; double_conversion::StringBuilder builder(buf, sizeof(buf)); builder.AddString("float{"); converter.ToShortestSingle(value, &builder); builder.AddString("}"); return builder.Finalize(); } std::string CppLiteralReprImpl(double value) { static const DoubleToStringConverter converter( DoubleToStringConverter::EMIT_TRAILING_DECIMAL_POINT, "std::numeric_limits<double>::infinity()", "std::numeric_limits<double>::quiet_NaN()", 'e', -12, 21, 6, 0); char buf[128]; double_conversion::StringBuilder builder(buf, sizeof(buf)); builder.AddString("double{"); converter.ToShortest(value, &builder); builder.AddString("}"); return builder.Finalize(); } const char kRawStringDelimiter[] = "RL_CODEGEN_DELIM"; std::string CppRawStringLiteral(absl::string_view view) { return absl::StrFormat("R\"%s(%s)%s\"", kRawStringDelimiter, view, kRawStringDelimiter); } std::string CppLiteralReprImpl(const Bytes& bytes) { return absl::StrFormat("::arolla::Bytes(%s)", CppRawStringLiteral(bytes)); } std::string CppLiteralReprImpl(const Text& text) { return absl::StrFormat("::arolla::Text(%s)", CppRawStringLiteral(text.view())); } absl::StatusOr<std::string> DefaultConstructedCppLiteralRepr(QTypePtr qtype) { ASSIGN_OR_RETURN(std::string type_name, CppTypeName(qtype)); return absl::StrFormat("%s{}", type_name); } absl::StatusOr<std::string> OptionalCppLiteralRepr(TypedRef value) { auto qtype = value.GetType(); if (IsScalarQType(DecayOptionalQType(qtype))) { bool is_correct_optional = (qtype == GetQType<OptionalUnit>() && value.GetFieldCount() == 1) || (qtype != GetQType<OptionalUnit>() && value.GetFieldCount() == 2); if (!is_correct_optional) { return absl::InternalError(absl::StrFormat( "Wrong number of fields in optional type %s", qtype->name())); } ASSIGN_OR_RETURN(bool present, value.GetField(0).As<bool>()); if (!present) { return DefaultConstructedCppLiteralRepr(qtype); } else { ASSIGN_OR_RETURN(std::string type_name, CppTypeName(qtype)); ASSIGN_OR_RETURN(std::string value_repr, qtype == GetQType<OptionalUnit>() ? CppLiteralReprImpl(kUnit) : CppLiteralRepr(value.GetField(1))); return absl::StrFormat("::arolla::MakeOptionalValue(%s)", value_repr); } } return absl::UnimplementedError( absl::StrFormat("CppLiteralRepr is unknown for type %s", qtype->name())); } template <class T> absl::StatusOr<std::string> CppLiteralReprImpl(const DenseArray<T>& values) { std::vector<std::string> values_str; values_str.reserve(values.size()); for (int64_t i = 0; i != values.size(); ++i) { OptionalValue<T> value; if (values.present(i)) { value = T(values.values[i]); } ASSIGN_OR_RETURN(auto value_str, OptionalCppLiteralRepr(TypedRef::FromValue(value))); values_str.push_back(value_str); } ASSIGN_OR_RETURN(std::string type_name, CppTypeName(GetQType<T>())); return absl::StrFormat("::arolla::CreateDenseArray<%s>({%s})", type_name, absl::StrJoin(values_str, ",")); } template <class T> absl::StatusOr<std::string> CppLiteralReprImpl( const absl::StatusOr<std::reference_wrapper<T>>& value_or) { ASSIGN_OR_RETURN(auto value, value_or); return CppLiteralReprImpl(value.get()); } #define RETURN_CPP_LITERAL_IF_SAME_TYPE(_, CTYPE) \ if (GetQType<CTYPE>() == value.GetType()) { \ return CppLiteralReprImpl(value.As<CTYPE>().value()); \ } absl::StatusOr<std::string> NonOptionalCppLiteralRepr(TypedRef value) { AROLLA_FOREACH_BASE_TYPE(RETURN_CPP_LITERAL_IF_SAME_TYPE); RETURN_CPP_LITERAL_IF_SAME_TYPE(UNIT, Unit); return absl::FailedPreconditionError(absl::StrFormat( "Unsupported literal QType: %s", value.GetType()->name())); } #define RETURN_CPP_LITERAL_IF_SAME_DENSE_ARRAY_TYPE(_, CTYPE) \ if (GetQType<DenseArray<CTYPE>>() == value.GetType()) { \ return CppLiteralReprImpl(value.As<DenseArray<CTYPE>>()); \ } absl::StatusOr<std::string> DenseArrayCppLiteralRepr(TypedRef value) { AROLLA_FOREACH_BASE_TYPE(RETURN_CPP_LITERAL_IF_SAME_DENSE_ARRAY_TYPE); return absl::UnimplementedError(absl::StrFormat( "CppLiteralRepr is unknown for type %s", value.GetType()->name())); } #undef RETURN_CPP_LITERAL_IF_SAME_DENSE_ARRAY_TYPE absl::StatusOr<std::string> DenseArrayEdgeCppLiteralRepr(DenseArrayEdge edge) { auto wrap_as_lambda = [](absl::string_view x) { return absl::StrFormat("[]() { return %s; }()", x); }; if (edge.edge_type() == DenseArrayEdge::SPLIT_POINTS) { ASSIGN_OR_RETURN(std::string split_points, CppLiteralReprImpl(edge.edge_values())); return wrap_as_lambda(absl::StrFormat( "::arolla::DenseArrayEdge::FromSplitPoints(%s).value()", split_points)); } else if (edge.edge_type() == DenseArrayEdge::MAPPING) { ASSIGN_OR_RETURN(std::string mapping, CppLiteralReprImpl(edge.edge_values())); return wrap_as_lambda( absl::StrFormat("::arolla::DenseArrayEdge::FromMapping(%s, %d).value()", mapping, edge.parent_size())); } return absl::UnimplementedError(absl::StrFormat( "CppLiteralRepr is unknown for %d DenseArrayEdge edge_type", edge.edge_type())); } struct TypeMap { absl::Mutex lock; absl::flat_hash_map<QTypePtr, std::string> cpp_type_name; absl::flat_hash_map<QTypePtr, std::function<absl::StatusOr<std::string>(TypedRef)>> cpp_literal_repr_fn; }; TypeMap& GetTypeMap() { static Indestructible<TypeMap> kTypeMap; return *kTypeMap; } absl::StatusOr<std::string> CppTupleLiteralRepr(TypedRef value) { if (!IsTupleQType(value.GetType())) { return absl::InternalError("expected tuple QType"); } std::ostringstream res; res << "::arolla::MakeTupleFromFields("; bool first = true; for (int64_t i = 0; i != value.GetFieldCount(); ++i) { TypedRef f_slot = value.GetField(i); ASSIGN_OR_RETURN(std::string value, CppLiteralRepr(f_slot)); res << NonFirstComma(first) << value; } res << ")"; return res.str(); } absl::StatusOr<std::string> CppTupleQTypeConstruction(QTypePtr qtype) { if (!IsTupleQType(qtype)) { return absl::InternalError("expected tuple QType"); } std::ostringstream res; res << "::arolla::MakeTupleQType({"; bool first = true; for (const auto& f_slot : qtype->type_fields()) { ASSIGN_OR_RETURN(std::string qtype, CppQTypeConstruction(f_slot.GetType())); res << NonFirstComma(first) << qtype; } res << "})"; return res.str(); } } absl::Status RegisterCppType( QTypePtr qtype, absl::string_view cpp_type_name, std::function<absl::StatusOr<std::string>(TypedRef)> cpp_literal_repr) { TypeMap& type_map = GetTypeMap(); absl::MutexLock l(&type_map.lock); if (type_map.cpp_type_name.contains(qtype) || type_map.cpp_literal_repr_fn.contains(qtype)) { return absl::FailedPreconditionError( absl::StrFormat("RegisterCppType called twice for %s", qtype->name())); } type_map.cpp_type_name.emplace(qtype, std::string(cpp_type_name)); type_map.cpp_literal_repr_fn.emplace(qtype, std::move(cpp_literal_repr)); return absl::OkStatus(); } absl::StatusOr<std::string> CppTypeName(QTypePtr qtype) { const TypeMap& type_map = GetTypeMap(); if (auto it = type_map.cpp_type_name.find(qtype); it != type_map.cpp_type_name.end()) { return it->second; } if (IsScalarQType(qtype)) { if (qtype == GetQType<bool>()) { return "bool"; } if (qtype == GetQType<int32_t>()) { return "int32_t"; } if (qtype == GetQType<int64_t>()) { return "int64_t"; } if (qtype == GetQType<float>()) { return "float"; } if (qtype == GetQType<double>()) { return "double"; } if (qtype == GetQType<uint64_t>()) { return "uint64_t"; } if (qtype == GetQType<Unit>()) { return "::arolla::Unit"; } if (qtype == GetQType<Bytes>()) { return "::arolla::Bytes"; } if (qtype == GetQType<Text>()) { return "::arolla::Text"; } } if (IsOptionalQType(qtype)) { if (qtype == GetOptionalQType<Unit>()) { return "::arolla::OptionalUnit"; } if (IsScalarQType(qtype->value_qtype())) { ASSIGN_OR_RETURN(auto value_type_name, CppTypeName(DecayOptionalQType(qtype))); return absl::StrFormat("::arolla::OptionalValue<%s>", value_type_name); } } if (IsDenseArrayQType(qtype)) { if (IsScalarQType(qtype->value_qtype())) { ASSIGN_OR_RETURN(auto value_type_name, CppTypeName(qtype->value_qtype())); return absl::StrFormat("::arolla::DenseArray<%s>", value_type_name); } } if (qtype == GetQType<DenseArrayShape>()) { return "::arolla::DenseArrayShape"; } if (qtype == GetQType<DenseArrayEdge>()) { return "::arolla::DenseArrayEdge"; } if (qtype == GetQType<DenseArrayGroupScalarEdge>()) { return "::arolla::DenseArrayGroupScalarEdge"; } if (IsTupleQType(qtype)) { return "::arolla::TypedValue"; } return absl::UnimplementedError( absl::StrFormat("CppTypeName is unknown for type %s", qtype->name())); } absl::StatusOr<std::string> CppQTypeConstruction(QTypePtr qtype) { if (IsTupleQType(qtype)) { return CppTupleQTypeConstruction(qtype); } ASSIGN_OR_RETURN(std::string type_name, CppTypeName(qtype)); return absl::StrFormat("::arolla::GetQType<%s>()", type_name); } absl::StatusOr<std::string> CppLiteralRepr(TypedRef value) { auto qtype = value.GetType(); const TypeMap& type_map = GetTypeMap(); if (auto it = type_map.cpp_literal_repr_fn.find(qtype); it != type_map.cpp_literal_repr_fn.end()) { return it->second(value); } if (IsScalarQType(qtype)) { return NonOptionalCppLiteralRepr(value); } if (IsOptionalQType(qtype)) { return OptionalCppLiteralRepr(value); } if (IsDenseArrayQType(qtype)) { return DenseArrayCppLiteralRepr(value); } if (qtype == GetQType<DenseArrayShape>()) { return absl::StrFormat("::arolla::DenseArrayShape{%d}", value.UnsafeAs<DenseArrayShape>().size); } if (qtype == GetQType<DenseArrayEdge>()) { ASSIGN_OR_RETURN(auto edge, value.As<DenseArrayEdge>()); return DenseArrayEdgeCppLiteralRepr(edge); } if (qtype == GetQType<DenseArrayGroupScalarEdge>()) { return absl::StrFormat( "::arolla::DenseArrayGroupScalarEdge{%d}", value.UnsafeAs<DenseArrayGroupScalarEdge>().child_size()); } if (IsTupleQType(qtype)) { return CppTupleLiteralRepr(value); } return absl::UnimplementedError( absl::StrFormat("CppLiteralRepr is unknown for type %s", qtype->name())); } }
#include "arolla/codegen/expr/types.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/simple_qtype.h" #include "arolla/qtype/typed_ref.h" #include "arolla/util/fingerprint.h" #include "arolla/util/testing/status_matchers_backport.h" namespace arolla { namespace { struct NonExistentFake {}; } AROLLA_DECLARE_FINGERPRINT_HASHER_TRAITS(NonExistentFake); void FingerprintHasherTraits<NonExistentFake>::operator()( FingerprintHasher* hasher, const NonExistentFake&) const { hasher->Combine(7); } AROLLA_DECLARE_SIMPLE_QTYPE(FAKE_TEST, NonExistentFake); AROLLA_DEFINE_SIMPLE_QTYPE(FAKE_TEST, NonExistentFake); } namespace arolla::codegen { namespace { using ::arolla::testing::IsOk; using ::arolla::testing::IsOkAndHolds; TEST(CppTypeName, Sanity) { EXPECT_THAT(CppTypeName(GetQType<float>()), IsOkAndHolds("float")); } TEST(CppLiteralRepr, Sanity) { EXPECT_THAT(CppLiteralRepr(TypedRef::FromValue(1)), IsOkAndHolds("int32_t{1}")); } TEST(RegisterCppType, Sanity) { EXPECT_THAT( RegisterCppType(GetQType<NonExistentFake>(), "::arolla::NonExistentFake", [](TypedRef) { return "::arolla::NonExistentFake{}"; }), IsOk()); EXPECT_THAT(CppTypeName(GetQType<NonExistentFake>()), IsOkAndHolds("::arolla::NonExistentFake")); EXPECT_THAT(CppLiteralRepr(TypedRef::FromValue(NonExistentFake{})), IsOkAndHolds("::arolla::NonExistentFake{}")); } } }
2,378
cpp
google/arolla
proto_qtype_map
arolla/proto/qtype/proto_qtype_map.cc
arolla/proto/qtype/proto_qtype_map_test.cc
#ifndef AROLLA_PROTO_QTYPE_PROTO_QTYPE_MAP_H_ #define AROLLA_PROTO_QTYPE_PROTO_QTYPE_MAP_H_ #include "absl/status/statusor.h" #include "google/protobuf/descriptor.h" #include "arolla/qtype/qtype.h" namespace arolla::proto { absl::StatusOr<arolla::QTypePtr> ProtoFieldTypeToQType( google::protobuf::FieldDescriptor::Type field_type); } #endif #include <cstdint> #include <string> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "google/protobuf/descriptor.h" #include "arolla/proto/types.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/util/bytes.h" namespace arolla::proto { using ::arolla::GetQType; using ::arolla::QTypePtr; using ::google::protobuf::FieldDescriptor; absl::StatusOr<QTypePtr> ProtoFieldTypeToQType( FieldDescriptor::Type field_type) { switch (field_type) { case FieldDescriptor::TYPE_INT32: case FieldDescriptor::TYPE_SINT32: case FieldDescriptor::TYPE_SFIXED32: return GetQType<arolla_single_value_t<int32_t>>(); case FieldDescriptor::TYPE_INT64: case FieldDescriptor::TYPE_SINT64: case FieldDescriptor::TYPE_SFIXED64: return GetQType<arolla_single_value_t<int64_t>>(); case FieldDescriptor::TYPE_UINT32: case FieldDescriptor::TYPE_FIXED32: return GetQType<arolla_single_value_t<uint32_t>>(); case FieldDescriptor::TYPE_UINT64: case FieldDescriptor::TYPE_FIXED64: return GetQType<arolla_single_value_t<uint64_t>>(); case FieldDescriptor::TYPE_DOUBLE: return GetQType<arolla_single_value_t<double>>(); case FieldDescriptor::TYPE_FLOAT: return GetQType<arolla_single_value_t<float>>(); case FieldDescriptor::TYPE_BOOL: return GetQType<arolla_single_value_t<bool>>(); case FieldDescriptor::TYPE_STRING: return GetQType<arolla_single_value_t<std::string>>(); case FieldDescriptor::TYPE_BYTES: return GetQType<arolla::Bytes>(); case FieldDescriptor::TYPE_ENUM: return GetQType<arolla_single_value_t<int32_t>>(); default: return absl::InvalidArgumentError( absl::StrCat("type ", field_type, " is not supported")); } } }
#include "arolla/proto/qtype/proto_qtype_map.h" #include <cstdint> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "google/protobuf/descriptor.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/util/bytes.h" #include "arolla/util/testing/status_matchers_backport.h" namespace arolla::proto { namespace { using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::StatusIs; TEST(ProtoFieldTypeToQTypeTest, Get) { EXPECT_THAT(ProtoFieldTypeToQType(google::protobuf::FieldDescriptor::TYPE_SFIXED32), IsOkAndHolds(arolla::GetQType<int32_t>())); EXPECT_THAT(ProtoFieldTypeToQType(google::protobuf::FieldDescriptor::TYPE_FIXED32), IsOkAndHolds(arolla::GetQType<int64_t>())); EXPECT_THAT(ProtoFieldTypeToQType(google::protobuf::FieldDescriptor::TYPE_SFIXED64), IsOkAndHolds(arolla::GetQType<int64_t>())); EXPECT_THAT(ProtoFieldTypeToQType(google::protobuf::FieldDescriptor::TYPE_FIXED64), IsOkAndHolds(arolla::GetQType<uint64_t>())); EXPECT_THAT(ProtoFieldTypeToQType(google::protobuf::FieldDescriptor::TYPE_FLOAT), IsOkAndHolds(arolla::GetQType<float>())); EXPECT_THAT(ProtoFieldTypeToQType(google::protobuf::FieldDescriptor::TYPE_DOUBLE), IsOkAndHolds(arolla::GetQType<double>())); EXPECT_THAT(ProtoFieldTypeToQType(google::protobuf::FieldDescriptor::TYPE_BOOL), IsOkAndHolds(arolla::GetQType<bool>())); EXPECT_THAT(ProtoFieldTypeToQType(google::protobuf::FieldDescriptor::TYPE_ENUM), IsOkAndHolds(arolla::GetQType<int32_t>())); EXPECT_THAT(ProtoFieldTypeToQType(google::protobuf::FieldDescriptor::TYPE_STRING), IsOkAndHolds(arolla::GetQType<arolla::Bytes>())); EXPECT_THAT(ProtoFieldTypeToQType(google::protobuf::FieldDescriptor::TYPE_BYTES), IsOkAndHolds(arolla::GetQType<arolla::Bytes>())); EXPECT_THAT(ProtoFieldTypeToQType(google::protobuf::FieldDescriptor::TYPE_MESSAGE), StatusIs(absl::StatusCode::kInvalidArgument)); } } }
2,379
cpp
google/arolla
reader
arolla/proto/reflection/reader.cc
arolla/proto/reflection/reader_test.cc
#ifndef AROLLA_PROTO_REFLECTION_READER_H_ #define AROLLA_PROTO_REFLECTION_READER_H_ #include <cstddef> #include <functional> #include <memory> #include <utility> #include <variant> #include <vector> #include "absl/status/statusor.h" #include "absl/types/span.h" #include "google/protobuf/descriptor.h" #include "google/protobuf/message.h" #include "arolla/memory/frame.h" #include "arolla/proto/types.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/typed_slot.h" namespace arolla::proto { struct RegularFieldAccess {}; struct RepeatedFieldIndexAccess { explicit RepeatedFieldIndexAccess(size_t idx) : idx(idx) {} size_t idx; }; struct RepeatedFieldAccess {}; struct RepeatedFieldSizeAccess {}; using ProtoFieldAccessInfo = std::variant<RegularFieldAccess, RepeatedFieldIndexAccess, RepeatedFieldAccess, RepeatedFieldSizeAccess>; class ProtoTypeReader { public: using BoundReadFn = std::function<void(const google::protobuf::Message&, FramePtr)>; static absl::StatusOr<std::unique_ptr<ProtoTypeReader>> CreateOptionalReader( absl::Span<const google::protobuf::FieldDescriptor* const> fields, std::vector<ProtoFieldAccessInfo> access_infos, proto::StringFieldType string_type = StringFieldType::kText); static absl::StatusOr<std::unique_ptr<ProtoTypeReader>> CreateDenseArrayShapeReader( absl::Span<const google::protobuf::FieldDescriptor* const> fields, std::vector<ProtoFieldAccessInfo> access_infos, proto::StringFieldType string_type = StringFieldType::kText); static absl::StatusOr<std::unique_ptr<ProtoTypeReader>> CreateDenseArrayReader( absl::Span<const google::protobuf::FieldDescriptor* const> fields, std::vector<ProtoFieldAccessInfo> access_infos, proto::StringFieldType string_type = StringFieldType::kText); ProtoTypeReader( QTypePtr qtype, std::function<absl::StatusOr<BoundReadFn>(TypedSlot)> read_fn_factory) : qtype_(qtype), read_fn_factory_(std::move(read_fn_factory)) {} QTypePtr qtype() const { return qtype_; } absl::StatusOr<BoundReadFn> BindReadFn(TypedSlot slot) const { return read_fn_factory_(slot); } private: QTypePtr qtype_; std::function<absl::StatusOr<BoundReadFn>(TypedSlot)> read_fn_factory_; }; } #endif #include "arolla/proto/reflection/reader.h" #include <algorithm> #include <cstddef> #include <cstdint> #include <functional> #include <memory> #include <optional> #include <string> #include <type_traits> #include <utility> #include <variant> #include <vector> #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "absl/types/span.h" #include "google/protobuf/descriptor.h" #include "google/protobuf/reflection.h" #include "arolla/dense_array/dense_array.h" #include "arolla/dense_array/qtype/types.h" #include "arolla/memory/buffer.h" #include "arolla/memory/frame.h" #include "arolla/proto/types.h" #include "arolla/qtype/optional_qtype.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/util/bytes.h" #include "arolla/util/text.h" #include "arolla/util/status_macros_backport.h" namespace { using ::google::protobuf::FieldDescriptor; using ::google::protobuf::Message; using ::google::protobuf::Reflection; using ::absl::StatusOr; using ::arolla::Bytes; using ::arolla::FrameLayout; using ::arolla::FramePtr; using ::arolla::GetDenseArrayQType; using ::arolla::GetOptionalQType; using ::arolla::GetQType; using ::arolla::OptionalValue; using ::arolla::QTypePtr; using ::arolla::Text; using ::arolla::TypedSlot; using ::arolla::DenseArrayShape; using ::arolla::proto::arolla_size_t; using ::arolla::proto::ProtoFieldAccessInfo; using ::arolla::proto::ProtoTypeReader; using ::arolla::proto::RegularFieldAccess; using ::arolla::proto::RepeatedFieldAccess; using ::arolla::proto::RepeatedFieldIndexAccess; using ::arolla::proto::RepeatedFieldSizeAccess; using ::arolla::proto::StringFieldType; using ReadValueFn = std::function<void(const Message&, void*)>; template <class T, class ProtoGetFn> struct ByIndexReader { void operator()(const Message& m, void* res_void) const { auto* res = reinterpret_cast<OptionalValue<T>*>(res_void); const auto* ref = m.GetReflection(); if (access_info.idx < ref->FieldSize(m, field)) { *res = static_cast<T>( getter.GetFromRepeated(ref, m, field, access_info.idx)); } else { *res = std::nullopt; } } const FieldDescriptor* field; RepeatedFieldIndexAccess access_info; ProtoGetFn getter; }; template <class T, class ProtoGetFn> struct FieldReader { void operator()(const Message& m, void* res_void) const { auto* res = reinterpret_cast<OptionalValue<T>*>(res_void); const auto* ref = m.GetReflection(); if (ref->HasField(m, field)) { *res = static_cast<T>(getter.GetSingular(ref, m, field)); } else { *res = std::nullopt; } } const FieldDescriptor* field; ProtoGetFn getter; }; using PushbackFn = std::function<void(const Message&, void*)>; template <class T, class ProtoGetFn> struct ManyPushBackFn { void operator()(const Message& m, void* res_void) const { auto* res = reinterpret_cast<std::vector<OptionalValue<T>>*>(res_void); const auto* ref = m.GetReflection(); for (const auto& val : getter.GetRepeated(ref, m, field)) { res->push_back(static_cast<T>(val)); } } const FieldDescriptor* field; ProtoGetFn getter; }; struct SizePushBackFn { void operator()(const Message& m, void* res_void) const { auto* res = reinterpret_cast<std::vector<arolla_size_t>*>(res_void); const auto* ref = m.GetReflection(); res->push_back(ref->FieldSize(m, field)); } const FieldDescriptor* field; }; struct SizeToShapeFn { void operator()(const Message& m, void* res_void) const { auto* res = reinterpret_cast<DenseArrayShape*>(res_void); const auto* ref = m.GetReflection(); res->size = ref->FieldSize(m, field); } const FieldDescriptor* field; }; template <class ResultT> struct SinglePushBackFn { void operator()(const Message& m, void* res_void) const { auto* res = reinterpret_cast<std::vector<OptionalValue<ResultT>>*>(res_void); res->emplace_back(); get_fn(m, &res->back()); } ReadValueFn get_fn; }; #define PROTO_GETTER_OBJ(TYPE, CPP_TYPE) \ struct PFG##TYPE { \ auto GetSingular(const Reflection* ref, const Message& m, \ const FieldDescriptor* field) const { \ return ref->Get##TYPE(m, field); \ } \ auto GetFromRepeated(const Reflection* ref, const Message& m, \ const FieldDescriptor* field, int index) const { \ return ref->GetRepeated##TYPE(m, field, index); \ } \ auto GetRepeated(const Reflection* ref, const Message& m, \ const FieldDescriptor* field) const { \ return ref->GetRepeatedFieldRef<CPP_TYPE>(m, field); \ } \ }; \ constexpr auto kProtoGetter##TYPE = PFG##TYPE{}; PROTO_GETTER_OBJ(Int32, int32_t); PROTO_GETTER_OBJ(Int64, int64_t); PROTO_GETTER_OBJ(UInt32, uint32_t); PROTO_GETTER_OBJ(UInt64, uint64_t); PROTO_GETTER_OBJ(Float, float); PROTO_GETTER_OBJ(Double, double); PROTO_GETTER_OBJ(Bool, bool); PROTO_GETTER_OBJ(String, std::string); PROTO_GETTER_OBJ(EnumValue, int32_t); #undef PROTO_GETTER_OBJ absl::Status CheckAccessInfo(const FieldDescriptor* field, const ProtoFieldAccessInfo& info, bool allow_repeated, bool is_last) { if (field == nullptr) { return absl::FailedPreconditionError( "field is nullptr (incorrect name passed into FindFieldByName?)"); } if (field->is_repeated()) { if (std::holds_alternative<RepeatedFieldIndexAccess>(info)) { return absl::OkStatus(); } if (allow_repeated && std::holds_alternative<RepeatedFieldAccess>(info)) { return absl::OkStatus(); } if (allow_repeated && is_last && std::holds_alternative<RepeatedFieldSizeAccess>(info)) { return absl::OkStatus(); } return absl::FailedPreconditionError(absl::StrCat( "incorrect access to the repeated field: ", field->full_name())); } else { if (!std::holds_alternative<RegularFieldAccess>(info)) { return absl::FailedPreconditionError(absl::StrCat( "incorrect access to the regular field: ", field->full_name())); } } return absl::OkStatus(); } class Traverser { public: Traverser(std::vector<const FieldDescriptor*> fields, std::vector<ProtoFieldAccessInfo> access_infos) : fields_(std::move(fields)), access_infos_(std::move(access_infos)) { DCHECK_EQ(fields_.size(), access_infos_.size()); } const Message* GetLastSubMessage(const Message& m) const { const Message* current_message = &m; for (size_t i = 0; i != fields_.size(); ++i) { current_message = GetSubMessage(*current_message, i); if (current_message == nullptr) { return nullptr; } } return current_message; } void TraverseSubmessages(const Message& m, PushbackFn callback, void* res) const { using IndexedMessage = std::pair<const Message*, size_t>; std::vector<IndexedMessage> stack; stack.emplace_back(&m, 0); while (!stack.empty()) { auto [current_message, i] = stack.back(); stack.pop_back(); if (i != fields_.size()) { size_t end_id = stack.size(); const auto* field = fields_[i]; const auto& access_info = access_infos_[i]; DCHECK(!std::holds_alternative<RepeatedFieldSizeAccess>(access_info)); if (std::holds_alternative<RepeatedFieldAccess>(access_info)) { const auto* ref = m.GetReflection(); for (const Message& sub_message : ref->GetRepeatedFieldRef<Message>(m, field)) { stack.emplace_back(&sub_message, i + 1); } } else { stack.emplace_back(GetSubMessage(m, i), i + 1); } std::reverse(stack.begin() + end_id, stack.end()); } else { callback(*current_message, res); } } } private: const Message* GetSubMessage(const Message& m, int i) const { const auto* field = fields_[i]; const auto& access_info = access_infos_[i]; DCHECK(!std::holds_alternative<RepeatedFieldAccess>(access_info)); const auto* ref = m.GetReflection(); if (field->is_repeated()) { auto& access = *std::get_if<RepeatedFieldIndexAccess>(&access_info); if (access.idx < ref->FieldSize(m, field)) { return &ref->GetRepeatedMessage(m, field, access.idx); } else { return nullptr; } } else { if (ref->HasField(m, field)) { return &ref->GetMessage(m, field); } else { return nullptr; } } } std::vector<const FieldDescriptor*> fields_; std::vector<ProtoFieldAccessInfo> access_infos_; }; template <class T> struct OptionalReader { void operator()(const Message& m, FramePtr frame) const { const Message* last_message = traverser.GetLastSubMessage(m); if (last_message == nullptr) { frame.Set(slot, {}); } else { get_fn(*last_message, frame.GetMutable(slot)); } } Traverser traverser; FrameLayout::Slot<OptionalValue<T>> slot; ReadValueFn get_fn; }; template <class T> struct OptionalReaderFactory { absl::StatusOr<ProtoTypeReader::BoundReadFn> operator()( TypedSlot typed_slot) const { ASSIGN_OR_RETURN(auto slot, typed_slot.ToSlot<OptionalValue<T>>()); return OptionalReader<T>{traverser, slot, get_fn}; } Traverser traverser; ReadValueFn get_fn; }; struct ArraySizeReader { void operator()(const Message& m, FramePtr frame) const { std::vector<arolla_size_t> res; traverser.TraverseSubmessages(m, last_push_back_fn, &res); frame.Set(slot, ::arolla::DenseArray<arolla_size_t>{ ::arolla::Buffer<arolla_size_t>::Create(std::move(res))}); } Traverser traverser; FrameLayout::Slot<::arolla::DenseArray<arolla_size_t>> slot; PushbackFn last_push_back_fn; }; struct ArraySizeReaderFactory { absl::StatusOr<ProtoTypeReader::BoundReadFn> operator()( TypedSlot typed_slot) const { ASSIGN_OR_RETURN(auto slot, typed_slot.ToSlot<::arolla::DenseArray<arolla_size_t>>()); return ArraySizeReader{traverser, slot, SizePushBackFn{last_field}}; } Traverser traverser; const FieldDescriptor* last_field; }; struct ShapeSizeReader { void operator()(const Message& m, FramePtr frame) const { DenseArrayShape res; traverser.TraverseSubmessages(m, last_push_back_fn, &res); frame.Set(slot, res); } Traverser traverser; FrameLayout::Slot<::arolla::DenseArrayShape> slot; PushbackFn last_push_back_fn; }; struct ShapeSizeReaderFactory { absl::StatusOr<ProtoTypeReader::BoundReadFn> operator()( TypedSlot typed_slot) const { ASSIGN_OR_RETURN(auto slot, typed_slot.ToSlot<::arolla::DenseArrayShape>()); return ShapeSizeReader{traverser, slot, SizeToShapeFn{last_field}}; } Traverser traverser; const FieldDescriptor* last_field; }; template <class T> struct DenseArrayReader { void operator()(const Message& m, FramePtr frame) const { std::vector<OptionalValue<T>> res; traverser.TraverseSubmessages(m, last_push_back_fn, &res); frame.Set(slot, ::arolla::CreateDenseArray<T>(res)); } Traverser traverser; FrameLayout::Slot<::arolla::DenseArray<T>> slot; PushbackFn last_push_back_fn; }; template <class T> struct DenseArrayReaderFactory { absl::StatusOr<ProtoTypeReader::BoundReadFn> operator()( TypedSlot typed_slot) const { ASSIGN_OR_RETURN(auto slot, typed_slot.ToSlot<::arolla::DenseArray<T>>()); return DenseArrayReader<T>{traverser, slot, last_push_back_fn}; } Traverser traverser; PushbackFn last_push_back_fn; }; template <class CallBackFn> auto SwitchByProtoType(FieldDescriptor::Type type, CallBackFn callback, StringFieldType string_type) -> decltype(std::declval<CallBackFn>()(std::decay<int32_t>(), kProtoGetterInt32)) { switch (type) { case FieldDescriptor::TYPE_INT32: case FieldDescriptor::TYPE_SINT32: case FieldDescriptor::TYPE_SFIXED32: return callback(std::decay<int32_t>{}, kProtoGetterInt32); case FieldDescriptor::TYPE_INT64: case FieldDescriptor::TYPE_SINT64: case FieldDescriptor::TYPE_SFIXED64: return callback(std::decay<int64_t>{}, kProtoGetterInt64); case FieldDescriptor::TYPE_UINT32: case FieldDescriptor::TYPE_FIXED32: return callback(std::decay<int64_t>{}, kProtoGetterUInt32); case FieldDescriptor::TYPE_UINT64: case FieldDescriptor::TYPE_FIXED64: return callback(std::decay<uint64_t>{}, kProtoGetterUInt64); case FieldDescriptor::TYPE_DOUBLE: return callback(std::decay<double>{}, kProtoGetterDouble); case FieldDescriptor::TYPE_FLOAT: return callback(std::decay<float>{}, kProtoGetterFloat); case FieldDescriptor::TYPE_BOOL: return callback(std::decay<bool>{}, kProtoGetterBool); case FieldDescriptor::TYPE_STRING: { switch (string_type) { case StringFieldType::kText: return callback(std::decay<Text>{}, kProtoGetterString); case StringFieldType::kBytes: return callback(std::decay<Bytes>{}, kProtoGetterString); } } case FieldDescriptor::TYPE_BYTES: return callback(std::decay<Bytes>{}, kProtoGetterString); case FieldDescriptor::TYPE_ENUM: return callback(std::decay<int32_t>{}, kProtoGetterEnumValue); default: return absl::FailedPreconditionError( absl::StrCat("type ", type, " is not supported")); } } absl::Status VerifyFieldsAndAccessInfos( absl::Span<const FieldDescriptor* const> fields, const std::vector<ProtoFieldAccessInfo>& access_infos, bool allow_repeated = false) { if (fields.empty()) { return absl::FailedPreconditionError("fields must be non empty"); } if (fields.size() != access_infos.size()) { return absl::FailedPreconditionError( "fields and access_info must be same size if access_info is not empty"); } for (size_t i = 0; i != fields.size(); ++i) { RETURN_IF_ERROR(CheckAccessInfo(fields[i], access_infos[i], allow_repeated, i + 1 == fields.size())); } return absl::OkStatus(); } class OptionalReaderCallback { public: OptionalReaderCallback(absl::Span<const FieldDescriptor* const> fields, absl::Span<const ProtoFieldAccessInfo> access_infos) : fields_(fields), access_infos_(access_infos), traverser_( std::vector(fields_.begin(), fields_.end() - 1), std::vector(access_infos_.begin(), access_infos_.end() - 1)) {} template <class ResultMetaFn, class ProtoFieldGetter> absl::StatusOr<std::unique_ptr<ProtoTypeReader>> operator()( ResultMetaFn, ProtoFieldGetter last_field_getter) const { using ResultT = typename ResultMetaFn::type; ProtoFieldAccessInfo last_access_info = access_infos_.back(); const FieldDescriptor* last_field = fields_.back(); ReadValueFn read_fn; if (last_field->is_repeated()) { DCHECK( std::holds_alternative<RepeatedFieldIndexAccess>(last_access_info)); read_fn = ByIndexReader<ResultT, ProtoFieldGetter>{ last_field, *std::get_if<RepeatedFieldIndexAccess>(&last_access_info), last_field_getter}; } else { read_fn = FieldReader<ResultT, ProtoFieldGetter>{last_field, last_field_getter}; } return std::make_unique<ProtoTypeReader>( GetOptionalQType<ResultT>(), OptionalReaderFactory<ResultT>{traverser_, read_fn}); } absl::StatusOr<std::unique_ptr<ProtoTypeReader>> CreateSizeAccessor() const { ProtoFieldAccessInfo last_access_info = access_infos_.back(); if (!std::holds_alternative<RepeatedFieldSizeAccess>(last_access_info)) { return absl::InternalError("size accessor creation expected"); } const FieldDescriptor* last_field = fields_.back(); return std::make_unique<ProtoTypeReader>( GetQType<DenseArrayShape>(), ShapeSizeReaderFactory{traverser_, last_field}); } private: absl::Span<const FieldDescriptor* const> fields_; absl::Span<const ProtoFieldAccessInfo> access_infos_; Traverser traverser_; }; class DenseArrayReaderCallback { public: DenseArrayReaderCallback(absl::Span<const FieldDescriptor* const> fields, absl::Span<const ProtoFieldAccessInfo> access_infos) : fields_(fields), access_infos_(access_infos), traverser_( std::vector(fields_.begin(), fields_.end() - 1), std::vector(access_infos_.begin(), access_infos_.end() - 1)) {} absl::StatusOr<std::unique_ptr<ProtoTypeReader>> CreateSizeAccessor() const { ProtoFieldAccessInfo last_access_info = access_infos_.back(); if (!std::holds_alternative<RepeatedFieldSizeAccess>(last_access_info)) { return absl::InternalError("size accessor creation expected"); } const FieldDescriptor* last_field = fields_.back(); return std::make_unique<ProtoTypeReader>( GetDenseArrayQType<arolla_size_t>(), ArraySizeReaderFactory{traverser_, last_field}); } template <class ResultMetaFn, class ProtoFieldGetter> absl::StatusOr<std::unique_ptr<ProtoTypeReader>> operator()( ResultMetaFn, ProtoFieldGetter last_field_getter) const { using ResultT = typename ResultMetaFn::type; using DenseArrayResultT = ::arolla::DenseArray<ResultT>; ProtoFieldAccessInfo last_access_info = access_infos_.back(); const FieldDescriptor* last_field = fields_.back(); PushbackFn pb_fn; if (std::holds_alternative<RepeatedFieldAccess>(last_access_info)) { pb_fn = ManyPushBackFn<ResultT, ProtoFieldGetter>{last_field, last_field_getter}; } else if (std::holds_alternative<RepeatedFieldSizeAccess>( last_access_info)) { return absl::InternalError( "size accessor must be created with CreateSizeAccessor"); } else if (last_field->is_repeated()) { DCHECK( std::holds_alternative<RepeatedFieldIndexAccess>(last_access_info)); pb_fn = SinglePushBackFn<ResultT>{ByIndexReader<ResultT, ProtoFieldGetter>{ last_field, *std::get_if<RepeatedFieldIndexAccess>(&last_access_info), last_field_getter}}; } else { pb_fn = SinglePushBackFn<ResultT>{FieldReader<ResultT, ProtoFieldGetter>{ last_field, last_field_getter}}; } return std::make_unique<ProtoTypeReader>( GetQType<DenseArrayResultT>(), DenseArrayReaderFactory<ResultT>{traverser_, pb_fn}); } private: absl::Span<const FieldDescriptor* const> fields_; absl::Span<const ProtoFieldAccessInfo> access_infos_; Traverser traverser_; }; } namespace arolla::proto { absl::StatusOr<std::unique_ptr<ProtoTypeReader>> ProtoTypeReader::CreateOptionalReader( absl::Span<const FieldDescriptor* const> fields, std::vector<ProtoFieldAccessInfo> access_infos, proto::StringFieldType string_type) { RETURN_IF_ERROR(VerifyFieldsAndAccessInfos(fields, access_infos)); const FieldDescriptor* last_field = fields.back(); return SwitchByProtoType( last_field->type(), OptionalReaderCallback(fields, std::move(access_infos)), string_type); } absl::StatusOr<std::unique_ptr<ProtoTypeReader>> ProtoTypeReader::CreateDenseArrayShapeReader( absl::Span<const FieldDescriptor* const> fields, std::vector<ProtoFieldAccessInfo> access_infos, proto::StringFieldType string_type) { RETURN_IF_ERROR(VerifyFieldsAndAccessInfos(fields, access_infos, true)); return OptionalReaderCallback(fields, std::move(access_infos)) .CreateSizeAccessor(); } absl::StatusOr<std::unique_ptr<ProtoTypeReader>> ProtoTypeReader::CreateDenseArrayReader( absl::Span<const FieldDescriptor* const> fields, std::vector<ProtoFieldAccessInfo> access_infos, proto::StringFieldType string_type) { RETURN_IF_ERROR(VerifyFieldsAndAccessInfos(fields, access_infos, true)); const FieldDescriptor* last_field = fields.back(); auto last_access = access_infos.back(); DenseArrayReaderCallback callback(fields, std::move(access_infos)); if (std::holds_alternative<proto::RepeatedFieldSizeAccess>(last_access)) { return callback.CreateSizeAccessor(); } else { return SwitchByProtoType(last_field->type(), callback, string_type); } } }
#include "arolla/proto/reflection/reader.h" #include <cstddef> #include <cstdint> #include <optional> #include <string> #include <utility> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "absl/strings/str_join.h" #include "google/protobuf/descriptor.h" #include "arolla/dense_array/dense_array.h" #include "arolla/dense_array/qtype/types.h" #include "arolla/memory/frame.h" #include "arolla/memory/memory_allocation.h" #include "arolla/memory/optional_value.h" #include "arolla/proto/test.pb.h" #include "arolla/proto/types.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/typed_slot.h" #include "arolla/util/bytes.h" #include "arolla/util/testing/status_matchers_backport.h" #include "arolla/util/text.h" #include "arolla/util/status_macros_backport.h" namespace arolla::proto { namespace { using ::arolla::testing::IsOkAndHolds; using ::testing::ElementsAre; using ::testing::IsEmpty; using ProtoRoot = ::testing_namespace::Root; const auto* kRootDescr = ProtoRoot::descriptor(); auto BuildDescriptorSequence(const std::vector<std::string>& field_names) { std::vector<const google::protobuf::FieldDescriptor*> fields; const google::protobuf::Descriptor* root_descriptor = kRootDescr; for (const auto& name : field_names) { CHECK(root_descriptor != nullptr) << "incorrect test fields: " << absl::StrJoin(field_names, ","); const google::protobuf::FieldDescriptor* field_descriptor = root_descriptor->FindFieldByName(name); fields.push_back(field_descriptor); root_descriptor = field_descriptor->message_type(); } return fields; } template <class T> absl::StatusOr<T> ReadValue(const ProtoTypeReader& reader, const google::protobuf::Message& m, T garbage = T{}) { if (reader.qtype() != GetQType<T>()) { return absl::FailedPreconditionError( absl::StrFormat("QType mismatch: expected %s, found %s", GetQType<T>()->name(), reader.qtype()->name())); } FrameLayout::Builder layout_builder; auto slot = layout_builder.AddSlot<T>(); ASSIGN_OR_RETURN(auto read_fn, reader.BindReadFn(TypedSlot::FromSlot(slot))); FrameLayout memory_layout = std::move(layout_builder).Build(); MemoryAllocation alloc(&memory_layout); FramePtr frame = alloc.frame(); frame.Set(slot, garbage); read_fn(m, frame); return frame.Get(slot); } template <class T> absl::StatusOr<OptionalValue<T>> ReadOptionalValue( const ProtoTypeReader& reader, const google::protobuf::Message& m) { return ReadValue<OptionalValue<T>>(reader, m, T{}); } template <class T> absl::StatusOr<OptionalValue<T>> ReadOptionalTopLevelValue( const std::string& field_name, const google::protobuf::Message& m) { ASSIGN_OR_RETURN(auto reader, ProtoTypeReader::CreateOptionalReader( {kRootDescr->FindFieldByName(field_name)}, {{}})); return ReadValue<OptionalValue<T>>(*reader, m); } TEST(TopLevelOptionalReaderTest, All) { ::testing_namespace::Root m; EXPECT_THAT(ReadOptionalTopLevelValue<int32_t>("x", m), IsOkAndHolds(std::nullopt)); m.set_x(19); EXPECT_THAT(ReadOptionalTopLevelValue<int32_t>("x", m), IsOkAndHolds(19)); m.set_x_enum(ProtoRoot::SECOND_VALUE); EXPECT_THAT(ReadOptionalTopLevelValue<int32_t>("x_enum", m), IsOkAndHolds(ProtoRoot::SECOND_VALUE)); m.set_str("19"); EXPECT_THAT(ReadOptionalTopLevelValue<Text>("str", m), IsOkAndHolds(Text{"19"})); m.set_raw_bytes("19"); EXPECT_THAT(ReadOptionalTopLevelValue<Bytes>("raw_bytes", m), IsOkAndHolds(Bytes{"19"})); m.set_x_int64(19); EXPECT_THAT(ReadOptionalTopLevelValue<int64_t>("x_int64", m), IsOkAndHolds(19)); m.set_x_uint32(19); EXPECT_THAT(ReadOptionalTopLevelValue<int64_t>("x_uint32", m), IsOkAndHolds(19)); m.set_x_uint64(19); EXPECT_THAT(ReadOptionalTopLevelValue<uint64_t>("x_uint64", m), IsOkAndHolds(19)); m.set_x_float(19.0f); EXPECT_THAT(ReadOptionalTopLevelValue<float>("x_float", m), IsOkAndHolds(19.0f)); m.set_x_double(19.0); EXPECT_THAT(ReadOptionalTopLevelValue<double>("x_double", m), IsOkAndHolds(19.0)); m.set_x_fixed64(19); EXPECT_THAT(ReadOptionalTopLevelValue<uint64_t>("x_fixed64", m), IsOkAndHolds(19)); { ASSERT_OK_AND_ASSIGN(auto reader, ProtoTypeReader::CreateOptionalReader( {kRootDescr->FindFieldByName("raw_bytes")}, {{}}, StringFieldType::kBytes)); m.set_raw_bytes("19"); EXPECT_THAT(ReadOptionalValue<Bytes>(*reader, m), IsOkAndHolds(Bytes("19"))); } { ASSERT_OK_AND_ASSIGN(auto reader, ProtoTypeReader::CreateOptionalReader( {kRootDescr->FindFieldByName("str")}, {{}}, StringFieldType::kBytes)); m.set_str("19"); EXPECT_THAT(ReadOptionalValue<Bytes>(*reader, m), IsOkAndHolds(Bytes("19"))); } } template <class T> absl::StatusOr<::arolla::DenseArray<T>> ReadDenseArrayValue( const ProtoTypeReader& reader, const google::protobuf::Message& m) { return ReadValue<::arolla::DenseArray<T>>( reader, m, ::arolla::CreateDenseArray<T>({T{}, T{}})); } template <class T> absl::StatusOr<::arolla::DenseArray<T>> ReadDenseArrayValue( const std::vector<std::string>& field_names, std::vector<ProtoFieldAccessInfo> access_infos, const google::protobuf::Message& m) { ASSIGN_OR_RETURN(auto reader, ProtoTypeReader::CreateDenseArrayReader( BuildDescriptorSequence(field_names), access_infos)); return ReadDenseArrayValue<T>(*reader, m); } TEST(ProtoTypeReader, CreateTopLevelDenseArrayReaderNonRepeatedField) { ::testing_namespace::Root m; EXPECT_THAT(ReadDenseArrayValue<int32_t>({"x"}, {{}}, m), IsOkAndHolds(ElementsAre(std::nullopt))); m.set_x(19); EXPECT_THAT(ReadDenseArrayValue<int32_t>({"x"}, {{}}, m), IsOkAndHolds(ElementsAre(19))); m.set_str("19"); EXPECT_THAT(ReadDenseArrayValue<Text>({"str"}, {{}}, m), IsOkAndHolds(ElementsAre("19"))); m.set_raw_bytes("19"); EXPECT_THAT(ReadDenseArrayValue<Bytes>({"raw_bytes"}, {{}}, m), IsOkAndHolds(ElementsAre("19"))); m.set_x_int64(19); EXPECT_THAT(ReadDenseArrayValue<int64_t>({"x_int64"}, {{}}, m), IsOkAndHolds(ElementsAre(19))); m.set_x_uint32(19); EXPECT_THAT(ReadDenseArrayValue<int64_t>({"x_uint32"}, {{}}, m), IsOkAndHolds(ElementsAre(19))); m.set_x_uint64(19); EXPECT_THAT(ReadDenseArrayValue<uint64_t>({"x_uint64"}, {{}}, m), IsOkAndHolds(ElementsAre(19))); m.set_x_float(19.0f); EXPECT_THAT(ReadDenseArrayValue<float>({"x_float"}, {{}}, m), IsOkAndHolds(ElementsAre(19.0f))); m.set_x_double(19.0); EXPECT_THAT(ReadDenseArrayValue<double>({"x_double"}, {{}}, m), IsOkAndHolds(ElementsAre(19.0))); { ASSERT_OK_AND_ASSIGN(auto reader, ProtoTypeReader::CreateDenseArrayReader( {kRootDescr->FindFieldByName("raw_bytes")}, {{}}, StringFieldType::kBytes)); m.set_raw_bytes("19"); EXPECT_THAT(ReadDenseArrayValue<Bytes>(*reader, m), IsOkAndHolds(ElementsAre("19"))); } { ASSERT_OK_AND_ASSIGN(auto reader, ProtoTypeReader::CreateDenseArrayReader( {kRootDescr->FindFieldByName("str")}, {{}}, StringFieldType::kBytes)); m.set_str("19"); EXPECT_THAT(ReadDenseArrayValue<Bytes>(*reader, m), IsOkAndHolds(ElementsAre("19"))); } } template <class T> absl::StatusOr<OptionalValue<T>> ReadOptionalValue( const std::vector<std::string>& field_names, std::vector<ProtoFieldAccessInfo> access_infos, const google::protobuf::Message& m) { std::vector<const google::protobuf::FieldDescriptor*> fields = BuildDescriptorSequence(field_names); ASSIGN_OR_RETURN(auto reader, ProtoTypeReader::CreateOptionalReader(fields, access_infos)); return ReadValue<OptionalValue<T>>(*reader, m); } template <class T> absl::StatusOr<OptionalValue<T>> ReadOptionalValue( const std::vector<std::string>& field_names, const google::protobuf::Message& m) { return ReadOptionalValue<T>( field_names, std::vector<ProtoFieldAccessInfo>(field_names.size()), m); } TEST(ProtoTypeReader, CreateInnerOptionalReader) { ::testing_namespace::Root m; EXPECT_THAT(ReadOptionalValue<int32_t>({"inner", "a"}, m), IsOkAndHolds(std::nullopt)); m.mutable_inner()->set_a(19); EXPECT_THAT(ReadOptionalValue<int32_t>({"inner", "a"}, m), IsOkAndHolds(19)); EXPECT_THAT(ReadOptionalValue<int32_t>({"inner", "inner2", "z"}, m), IsOkAndHolds(std::nullopt)); m.mutable_inner()->mutable_inner2(); EXPECT_THAT(ReadOptionalValue<int32_t>({"inner", "inner2", "z"}, m), IsOkAndHolds(std::nullopt)); m.mutable_inner()->mutable_inner2()->set_z(19); EXPECT_THAT(ReadOptionalValue<int32_t>({"inner", "inner2", "z"}, m), IsOkAndHolds(19)); } template <class T> absl::StatusOr<OptionalValue<T>> ReadOptionalTopLevelFromRepeatedValue( const std::string& field_name, const google::protobuf::Message& m, size_t index = 0) { return ReadOptionalValue<T>({field_name}, {RepeatedFieldIndexAccess{index}}, m); } TEST(ProtoTypeReader, CreateRepeatedIndexAccessOptionalReader) { ::testing_namespace::Root m; auto read_ys = [](const auto& m) { return ReadOptionalValue<int32_t>({"ys"}, {RepeatedFieldIndexAccess{1}}, m); }; EXPECT_THAT(read_ys(m), IsOkAndHolds(std::nullopt)); m.add_ys(89); EXPECT_THAT(read_ys(m), IsOkAndHolds(std::nullopt)); m.add_ys(77); EXPECT_THAT(read_ys(m), IsOkAndHolds(77)); auto read_inners_a = [](const auto& m) { return ReadOptionalValue<int32_t>({"inners", "a"}, {RepeatedFieldIndexAccess{1}, {}}, m); }; EXPECT_THAT(read_inners_a(m), IsOkAndHolds(std::nullopt)); m.add_inners(); EXPECT_THAT(read_inners_a(m), IsOkAndHolds(std::nullopt)); m.add_inners()->set_a(7); EXPECT_THAT(read_inners_a(m), IsOkAndHolds(7)); auto read_inners_as = [](const auto& m) { return ReadOptionalValue<int32_t>( {"inners", "as"}, {RepeatedFieldIndexAccess{1}, RepeatedFieldIndexAccess{1}}, m); }; m.mutable_inners(1)->add_as(0); EXPECT_THAT(read_inners_as(m), IsOkAndHolds(std::nullopt)); m.mutable_inners(1)->add_as(57); EXPECT_THAT(read_inners_as(m), IsOkAndHolds(57)); *m.add_repeated_str() = "19"; EXPECT_THAT(ReadOptionalTopLevelFromRepeatedValue<Text>("repeated_str", m), IsOkAndHolds(Text("19"))); *m.add_repeated_raw_bytes() = "19"; EXPECT_THAT( ReadOptionalTopLevelFromRepeatedValue<Bytes>("repeated_raw_bytes", m), IsOkAndHolds(Bytes("19"))); m.add_repeated_floats(19.0f); EXPECT_THAT( ReadOptionalTopLevelFromRepeatedValue<float>("repeated_floats", m), IsOkAndHolds(19.0f)); m.add_repeated_doubles(19.0); EXPECT_THAT( ReadOptionalTopLevelFromRepeatedValue<double>("repeated_doubles", m), IsOkAndHolds(19.0)); m.add_repeated_int32s(19); EXPECT_THAT(ReadOptionalTopLevelFromRepeatedValue<int>("repeated_int32s", m), IsOkAndHolds(19)); m.add_repeated_int64s(19); EXPECT_THAT( ReadOptionalTopLevelFromRepeatedValue<int64_t>("repeated_int64s", m), IsOkAndHolds(19)); m.add_repeated_uint32s(19); EXPECT_THAT( ReadOptionalTopLevelFromRepeatedValue<int64_t>("repeated_uint32s", m), IsOkAndHolds(19)); m.add_repeated_uint64s(19); EXPECT_THAT( ReadOptionalTopLevelFromRepeatedValue<uint64_t>("repeated_uint64s", m), IsOkAndHolds(19)); m.add_repeated_bools(true); EXPECT_THAT(ReadOptionalTopLevelFromRepeatedValue<bool>("repeated_bools", m), IsOkAndHolds(true)); m.add_repeated_enums(ProtoRoot::SECOND_VALUE); EXPECT_THAT(ReadOptionalTopLevelFromRepeatedValue<int>("repeated_enums", m), IsOkAndHolds(ProtoRoot::SECOND_VALUE)); } template <class T> absl::StatusOr<::arolla::DenseArray<T>> ReadDenseArrayTopLevelValue( const std::string& field_name, const google::protobuf::Message& m) { return ReadDenseArrayValue<T>({field_name}, {RepeatedFieldAccess{}}, m); } TEST(ProtoTypeReader, CreateRepeatedAccessOptionalReader) { ::testing_namespace::Root m; EXPECT_THAT(ReadDenseArrayTopLevelValue<int>("ys", m), IsOkAndHolds(IsEmpty())); m.add_ys(89); m.add_ys(57); EXPECT_THAT(ReadDenseArrayTopLevelValue<int>("ys", m), IsOkAndHolds(ElementsAre(89, 57))); auto read_inners_a = [](const auto& m) { return ReadDenseArrayValue<int32_t>({"inners", "a"}, {RepeatedFieldAccess{}, {}}, m); }; EXPECT_THAT(read_inners_a(m), IsOkAndHolds(IsEmpty())); m.add_inners(); EXPECT_THAT(read_inners_a(m), IsOkAndHolds(ElementsAre(std::nullopt))); m.add_inners()->set_a(7); EXPECT_THAT(read_inners_a(m), IsOkAndHolds(ElementsAre(std::nullopt, 7))); m.add_inners()->set_a(37); EXPECT_THAT(read_inners_a(m), IsOkAndHolds(ElementsAre(std::nullopt, 7, 37))); auto read_inners_as = [](const auto& m) { return ReadDenseArrayValue<int32_t>( {"inners", "as"}, {RepeatedFieldAccess{}, RepeatedFieldAccess{}}, m); }; EXPECT_THAT(read_inners_as(m), IsOkAndHolds(IsEmpty())); m.mutable_inners(0)->add_as(0); m.mutable_inners(0)->add_as(57); m.mutable_inners(2)->add_as(19); m.mutable_inners(2)->add_as(3); m.mutable_inners(2)->add_as(17); EXPECT_THAT(read_inners_as(m), IsOkAndHolds(ElementsAre(0, 57, 19, 3, 17))); *m.add_repeated_str() = "19"; *m.add_repeated_str() = "17"; EXPECT_THAT(ReadDenseArrayTopLevelValue<Text>("repeated_str", m), IsOkAndHolds(ElementsAre("19", "17"))); *m.add_repeated_raw_bytes() = "17"; *m.add_repeated_raw_bytes() = "19"; EXPECT_THAT(ReadDenseArrayTopLevelValue<Bytes>("repeated_raw_bytes", m), IsOkAndHolds(ElementsAre("17", "19"))); m.add_repeated_floats(19.0f); m.add_repeated_floats(17.0f); EXPECT_THAT(ReadDenseArrayTopLevelValue<float>("repeated_floats", m), IsOkAndHolds(ElementsAre(19.0f, 17.0f))); m.add_repeated_doubles(19.0); m.add_repeated_doubles(17.0); EXPECT_THAT(ReadDenseArrayTopLevelValue<double>("repeated_doubles", m), IsOkAndHolds(ElementsAre(19.0, 17.0))); m.add_repeated_int32s(19); m.add_repeated_int32s(17); EXPECT_THAT(ReadDenseArrayTopLevelValue<int>("repeated_int32s", m), IsOkAndHolds(ElementsAre(19, 17))); m.add_repeated_int64s(19); m.add_repeated_int64s(17); EXPECT_THAT(ReadDenseArrayTopLevelValue<int64_t>("repeated_int64s", m), IsOkAndHolds(ElementsAre(19, 17))); m.add_repeated_uint32s(19); m.add_repeated_uint32s(17); EXPECT_THAT(ReadDenseArrayTopLevelValue<int64_t>("repeated_uint32s", m), IsOkAndHolds(ElementsAre(19, 17))); m.add_repeated_uint64s(19); m.add_repeated_uint64s(17); EXPECT_THAT(ReadDenseArrayTopLevelValue<uint64_t>("repeated_uint64s", m), IsOkAndHolds(ElementsAre(19, 17))); m.add_repeated_bools(true); m.add_repeated_bools(false); EXPECT_THAT(ReadDenseArrayTopLevelValue<bool>("repeated_bools", m), IsOkAndHolds(ElementsAre(true, false))); m.add_repeated_enums(ProtoRoot::SECOND_VALUE); m.add_repeated_enums(ProtoRoot::DEFAULT); EXPECT_THAT( ReadDenseArrayTopLevelValue<int>("repeated_enums", m), IsOkAndHolds(ElementsAre(ProtoRoot::SECOND_VALUE, ProtoRoot::DEFAULT))); } absl::StatusOr<::arolla::DenseArray<proto::arolla_size_t>> ReadTopLevelSizeAsArray(const std::string& field_name, const google::protobuf::Message& m) { return ReadDenseArrayValue<proto::arolla_size_t>( {field_name}, {RepeatedFieldSizeAccess{}}, m); } absl::StatusOr<::arolla::DenseArrayShape> ReadTopLevelSizeAsShape( const std::string& field_name, const google::protobuf::Message& m) { ASSIGN_OR_RETURN(auto reader, ProtoTypeReader::CreateDenseArrayShapeReader( {kRootDescr->FindFieldByName(field_name)}, {RepeatedFieldSizeAccess{}})); return ReadValue<::arolla::DenseArrayShape>(*reader, m); } TEST(ProtoTypeReader, CreateRepeatedSizeAccessReader) { ::testing_namespace::Root m; EXPECT_THAT(ReadTopLevelSizeAsArray("ys", m), IsOkAndHolds(ElementsAre(0))); EXPECT_THAT(ReadTopLevelSizeAsShape("ys", m), IsOkAndHolds(DenseArrayShape{0})); m.add_ys(89); m.add_ys(57); EXPECT_THAT(ReadTopLevelSizeAsArray("ys", m), IsOkAndHolds(ElementsAre(2))); EXPECT_THAT(ReadTopLevelSizeAsShape("ys", m), IsOkAndHolds(DenseArrayShape{2})); EXPECT_THAT(ReadTopLevelSizeAsArray("inners", m), IsOkAndHolds(ElementsAre(0))); EXPECT_THAT(ReadTopLevelSizeAsShape("inners", m), IsOkAndHolds(DenseArrayShape{0})); m.add_inners(); EXPECT_THAT(ReadTopLevelSizeAsArray("inners", m), IsOkAndHolds(ElementsAre(1))); EXPECT_THAT(ReadTopLevelSizeAsShape("inners", m), IsOkAndHolds(DenseArrayShape{1})); m.add_inners(); EXPECT_THAT(ReadTopLevelSizeAsArray("inners", m), IsOkAndHolds(ElementsAre(2))); EXPECT_THAT(ReadTopLevelSizeAsShape("inners", m), IsOkAndHolds(DenseArrayShape{2})); m.clear_inners(); auto read_inners_as_size = [](const auto& m) { return ReadDenseArrayValue<proto::arolla_size_t>( {"inners", "as"}, {RepeatedFieldAccess{}, RepeatedFieldSizeAccess{}}, m); }; EXPECT_THAT(read_inners_as_size(m), IsOkAndHolds(IsEmpty())); m.add_inners(); m.mutable_inners(0)->add_as(0); m.mutable_inners(0)->add_as(57); m.add_inners(); m.add_inners(); m.mutable_inners(2)->add_as(19); m.mutable_inners(2)->add_as(3); m.mutable_inners(2)->add_as(17); EXPECT_THAT(read_inners_as_size(m), IsOkAndHolds(ElementsAre(2, 0, 3))); } } }
2,380
cpp
google/arolla
edge
arolla/dense_array/edge.cc
arolla/dense_array/edge_test.cc
#ifndef AROLLA_DENSE_ARRAY_EDGE_H_ #define AROLLA_DENSE_ARRAY_EDGE_H_ #include <cstdint> #include <utility> #include "absl/status/statusor.h" #include "absl/types/span.h" #include "arolla/dense_array/dense_array.h" #include "arolla/memory/raw_buffer_factory.h" #include "arolla/util/api.h" #include "arolla/util/fingerprint.h" namespace arolla { class AROLLA_API DenseArrayEdge { public: DenseArrayEdge() : edge_type_(MAPPING), parent_size_(0), child_size_(0) {} static absl::StatusOr<DenseArrayEdge> FromSplitPoints( DenseArray<int64_t> split_points); static absl::StatusOr<DenseArrayEdge> FromMapping(DenseArray<int64_t> mapping, int64_t parent_size); static absl::StatusOr<DenseArrayEdge> FromUniformGroups( int64_t parent_size, int64_t group_size, RawBufferFactory& buf_factory = *GetHeapBufferFactory()); static DenseArrayEdge UnsafeFromMapping(DenseArray<int64_t> mapping, int64_t parent_size); static DenseArrayEdge UnsafeFromSplitPoints(DenseArray<int64_t> split_points); static absl::StatusOr<DenseArrayEdge> ComposeEdges( absl::Span<const DenseArrayEdge> edges, RawBufferFactory& buf_factory = *GetHeapBufferFactory()); enum EdgeType { MAPPING = 1, SPLIT_POINTS = 2, }; EdgeType edge_type() const { return edge_type_; } int64_t parent_size() const { return parent_size_; } int64_t child_size() const { return child_size_; } const DenseArray<int64_t>& edge_values() const { return edge_values_; } absl::StatusOr<DenseArrayEdge> ToSplitPointsEdge( RawBufferFactory& buf_factory = *GetHeapBufferFactory()) const; DenseArrayEdge ToMappingEdge( RawBufferFactory& buf_factory = *GetHeapBufferFactory()) const; bool IsEquivalentTo(const DenseArrayEdge& other) const; private: friend class ArrayEdge; DenseArrayEdge(EdgeType edge_values_type, int64_t parent_size, int64_t child_size, DenseArray<int64_t> edge_values) : edge_type_(edge_values_type), parent_size_(parent_size), child_size_(child_size), edge_values_(std::move(edge_values)) {} EdgeType edge_type_; int64_t parent_size_; int64_t child_size_; DenseArray<int64_t> edge_values_; }; class AROLLA_API DenseArrayGroupScalarEdge { public: DenseArrayGroupScalarEdge() : size_(0) {} explicit DenseArrayGroupScalarEdge(int64_t size) : size_{size} {} int64_t child_size() const { return size_; } private: int64_t size_; }; AROLLA_DECLARE_FINGERPRINT_HASHER_TRAITS(DenseArrayEdge); AROLLA_DECLARE_FINGERPRINT_HASHER_TRAITS(DenseArrayGroupScalarEdge); } #endif #include "arolla/dense_array/edge.h" #include <algorithm> #include <cstddef> #include <cstdint> #include <utility> #include <vector> #include "absl/base/optimization.h" #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "absl/types/span.h" #include "arolla/dense_array/dense_array.h" #include "arolla/memory/buffer.h" #include "arolla/memory/raw_buffer_factory.h" #include "arolla/util/fingerprint.h" #include "arolla/util/status_macros_backport.h" namespace arolla { namespace { absl::StatusOr<DenseArrayEdge> ComposeMappingEdge( absl::Span<const DenseArrayEdge> edges, RawBufferFactory& buf_factory) { DCHECK_GE(edges.size(), 2); DenseArray<int64_t> mapping = edges.back().ToMappingEdge(buf_factory).edge_values(); for (int i = edges.size() - 2; i >= 0; --i) { const auto mapping_edge = edges[i].ToMappingEdge(buf_factory); DenseArrayBuilder<int64_t> bldr(edges.back().child_size(), &buf_factory); mapping.ForEachPresent([&bldr, &mapping_edge](int64_t id, int64_t value) { bldr.Set(id, mapping_edge.edge_values()[value]); }); mapping = std::move(bldr).Build(); } return DenseArrayEdge::UnsafeFromMapping(std::move(mapping), edges.front().parent_size()); } absl::StatusOr<DenseArrayEdge> ComposeSplitPointsEdge( absl::Span<const DenseArrayEdge> edges, RawBufferFactory& buf_factory) { DCHECK_GE(edges.size(), 2); Buffer<int64_t>::Builder bldr(edges.front().edge_values().size(), &buf_factory); auto mut_bldr_span = bldr.GetMutableSpan(); auto previous_split_points = edges.front().edge_values().values.span(); for (size_t i = 1; i < edges.size(); ++i) { auto split_points = edges[i].edge_values().values.span(); for (size_t j = 0; j < mut_bldr_span.size(); ++j) { mut_bldr_span[j] = split_points[previous_split_points[j]]; } previous_split_points = mut_bldr_span; } return DenseArrayEdge::UnsafeFromSplitPoints({std::move(bldr).Build()}); } } absl::StatusOr<DenseArrayEdge> DenseArrayEdge::FromSplitPoints( DenseArray<int64_t> split_points) { if (!split_points.IsFull()) { return absl::InvalidArgumentError("split points must be full"); } if (split_points.empty()) { return absl::InvalidArgumentError( "split points array must have at least 1 element"); } if (split_points.values[0] != 0) { return absl::InvalidArgumentError( "split points array must have first element equal to 0"); } int64_t parent_size = split_points.size() - 1; int64_t child_size = split_points.values.back(); if (!std::is_sorted(split_points.values.begin(), split_points.values.end())) { return absl::InvalidArgumentError("split points must be sorted"); } return DenseArrayEdge(DenseArrayEdge::SPLIT_POINTS, parent_size, child_size, std::move(split_points)); } absl::StatusOr<DenseArrayEdge> DenseArrayEdge::FromMapping( DenseArray<int64_t> mapping, int64_t parent_size) { if (parent_size < 0) { return absl::InvalidArgumentError("parent_size can not be negative"); } int64_t max_value = -1; bool negative = false; mapping.ForEach([&max_value, &negative](int64_t, bool present, int64_t v) { if (present) { max_value = std::max(max_value, v); if (v < 0) negative = true; } }); if (negative) { return absl::InvalidArgumentError("mapping can't contain negative values"); } if (max_value >= parent_size) { return absl::InvalidArgumentError(absl::StrFormat( "parent_size=%d, but parent id %d is used", parent_size, max_value)); } return UnsafeFromMapping(std::move(mapping), parent_size); } absl::StatusOr<DenseArrayEdge> DenseArrayEdge::FromUniformGroups( int64_t parent_size, int64_t group_size, RawBufferFactory& buf_factory) { if (parent_size < 0 || group_size < 0) { return absl::InvalidArgumentError( "parent_size and group_size cannot be negative"); } Buffer<int64_t>::Builder split_points_builder(parent_size + 1, &buf_factory); auto inserter = split_points_builder.GetInserter(); for (int64_t i = 0; i <= parent_size; ++i) inserter.Add(i * group_size); return UnsafeFromSplitPoints({std::move(split_points_builder).Build()}); } DenseArrayEdge DenseArrayEdge::UnsafeFromMapping(DenseArray<int64_t> mapping, int64_t parent_size) { int64_t child_size = mapping.size(); return DenseArrayEdge(DenseArrayEdge::MAPPING, parent_size, child_size, std::move(mapping)); } DenseArrayEdge DenseArrayEdge::UnsafeFromSplitPoints( DenseArray<int64_t> split_points) { int64_t parent_size = split_points.size() - 1; int64_t child_size = split_points.values.back(); return DenseArrayEdge(DenseArrayEdge::SPLIT_POINTS, parent_size, child_size, std::move(split_points)); } DenseArrayEdge DenseArrayEdge::ToMappingEdge( RawBufferFactory& buf_factory) const { switch (edge_type()) { case DenseArrayEdge::MAPPING: return *this; case DenseArrayEdge::SPLIT_POINTS: { Buffer<int64_t>::Builder bldr(child_size(), &buf_factory); int64_t* mapping = bldr.GetMutableSpan().begin(); const int64_t* splits = edge_values().values.begin(); for (int64_t parent_id = 0; parent_id < parent_size(); ++parent_id) { std::fill(mapping + splits[parent_id], mapping + splits[parent_id + 1], parent_id); } return DenseArrayEdge::UnsafeFromMapping({std::move(bldr).Build()}, parent_size()); } } ABSL_UNREACHABLE(); } absl::StatusOr<DenseArrayEdge> DenseArrayEdge::ToSplitPointsEdge( RawBufferFactory& buf_factory) const { if (edge_type() == DenseArrayEdge::SPLIT_POINTS) return *this; if (!edge_values().IsFull()) { return absl::InvalidArgumentError("expected a full mapping"); } Buffer<int64_t>::Builder split_points_builder(parent_size() + 1, &buf_factory); auto inserter = split_points_builder.GetInserter(); inserter.Add(0); int64_t current_bin = 0; auto values = edge_values().values.span(); for (size_t i = 0; i < values.size(); ++i) { DCHECK_LE(values[i], parent_size()); if (values[i] < current_bin) { return absl::InvalidArgumentError("expected a sorted mapping"); } for (; current_bin < values[i]; ++current_bin) inserter.Add(i); } for (; current_bin < parent_size(); ++current_bin) { inserter.Add(edge_values().size()); } return DenseArrayEdge::UnsafeFromSplitPoints( DenseArray<int64_t>{std::move(split_points_builder).Build()}); } bool DenseArrayEdge::IsEquivalentTo(const DenseArrayEdge& other) const { if (parent_size() != other.parent_size() || child_size() != other.child_size()) { return false; } if (edge_type() == other.edge_type()) { return ArraysAreEquivalent(edge_values(), other.edge_values()); } ASSIGN_OR_RETURN(auto this_edge, ToSplitPointsEdge(), _.With([](const auto&) { return false; })); ASSIGN_OR_RETURN(auto other_edge, other.ToSplitPointsEdge(), _.With([](const auto&) { return false; })); return ArraysAreEquivalent(this_edge.edge_values(), other_edge.edge_values()); } absl::StatusOr<DenseArrayEdge> DenseArrayEdge::ComposeEdges( absl::Span<const DenseArrayEdge> edges, RawBufferFactory& buf_factory) { if (edges.empty()) { return absl::InvalidArgumentError("at least one edge must be present"); } if (edges.size() == 1) return edges[0]; int64_t prior_child_size = edges[0].parent_size(); for (size_t i = 0; i < edges.size(); ++i) { if (edges[i].parent_size() != prior_child_size) { return absl::InvalidArgumentError( absl::StrFormat("incompatible edges: edges[%d].child_size (%d) != " "edges[%d].parent_size (%d)", i - 1, prior_child_size, i, edges[i].parent_size())); } prior_child_size = edges[i].child_size(); } std::vector<DenseArrayEdge> transformed_edges; transformed_edges.reserve(edges.size()); size_t i = 0; while (i < edges.size()) { size_t split_points_end = i; while (split_points_end < edges.size() && edges[split_points_end].edge_type() == DenseArrayEdge::SPLIT_POINTS) { split_points_end++; } if (split_points_end - i >= 2) { ASSIGN_OR_RETURN(auto composed_edge, ComposeSplitPointsEdge( absl::MakeSpan(edges.begin() + i, edges.begin() + split_points_end), buf_factory)); transformed_edges.push_back(std::move(composed_edge)); i = split_points_end; } else { transformed_edges.push_back(edges[i]); i++; } } if (transformed_edges.size() == 1) { return std::move(transformed_edges[0]); } else { return ComposeMappingEdge(transformed_edges, buf_factory); } } void FingerprintHasherTraits<DenseArrayEdge>::operator()( FingerprintHasher* hasher, const DenseArrayEdge& value) const { hasher->Combine(value.edge_type(), value.parent_size(), value.child_size(), value.edge_values()); } void FingerprintHasherTraits<DenseArrayGroupScalarEdge>::operator()( FingerprintHasher* hasher, const DenseArrayGroupScalarEdge& value) const { hasher->Combine(value.child_size()); } }
#include "arolla/dense_array/edge.h" #include <cstdint> #include <optional> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "absl/types/span.h" #include "arolla/dense_array/dense_array.h" #include "arolla/memory/buffer.h" #include "arolla/memory/raw_buffer_factory.h" #include "arolla/util/fingerprint.h" #include "arolla/util/testing/status_matchers_backport.h" using ::arolla::testing::StatusIs; using ::testing::ElementsAre; using ::testing::Eq; namespace arolla { namespace { TEST(DenseArrayEdgeTest, FromSplitPoints) { DenseArray<int64_t> split_points{CreateBuffer<int64_t>({0, 10, 20})}; ASSERT_OK_AND_ASSIGN(auto edge, DenseArrayEdge::FromSplitPoints(split_points)); EXPECT_THAT(edge.edge_type(), Eq(DenseArrayEdge::SPLIT_POINTS)); EXPECT_THAT(edge.edge_values().values, ElementsAre(0, 10, 20)); EXPECT_EQ(edge.parent_size(), 2); EXPECT_EQ(edge.child_size(), 20); } TEST(DenseArrayEdgeTest, FromSplitPointsEmptyGroup) { DenseArray<int64_t> split_points{CreateBuffer<int64_t>({0})}; ASSERT_OK_AND_ASSIGN(auto edge, DenseArrayEdge::FromSplitPoints(split_points)); EXPECT_THAT(edge.edge_type(), Eq(DenseArrayEdge::SPLIT_POINTS)); EXPECT_THAT(edge.edge_values().values, ElementsAre(0)); EXPECT_EQ(edge.parent_size(), 0); EXPECT_EQ(edge.child_size(), 0); } TEST(DenseArrayEdgeTest, FromSplitPointsNotFull) { auto split_points = CreateDenseArray<int64_t>({0, 3, std::nullopt, 10}); EXPECT_THAT(DenseArrayEdge::FromSplitPoints(split_points), StatusIs(absl::StatusCode::kInvalidArgument, ::testing::HasSubstr("split points must be full"))); } TEST(DenseArrayEdgeTest, FromSplitPointsTooFew) { EXPECT_THAT(DenseArrayEdge::FromSplitPoints(DenseArray<int64_t>()), StatusIs(absl::StatusCode::kInvalidArgument, ::testing::HasSubstr( "split points array must have at least 1 element"))); } TEST(DenseArrayEdgeTest, FromSplitPointsInBadOrder) { EXPECT_THAT( DenseArrayEdge::FromSplitPoints({CreateBuffer<int64_t>({10, 20, 30})}), StatusIs(absl::StatusCode::kInvalidArgument, ::testing::HasSubstr( "split points array must have first element equal to 0"))); EXPECT_THAT( DenseArrayEdge::FromSplitPoints({CreateBuffer<int64_t>({0, 40, 10})}), StatusIs(absl::StatusCode::kInvalidArgument, ::testing::HasSubstr("split points must be sorted"))); } TEST(DenseArrayEdgeTest, FromMapping) { DenseArray<int64_t> mapping{ CreateBuffer<int64_t>({0, 1, 2, 0, 1, 2, 0, 1, 2})}; DenseArray<int64_t> bad_mapping{ CreateBuffer<int64_t>({0, -1, 2, 0, 1, 2, 0, 1, 2})}; EXPECT_THAT( DenseArrayEdge::FromMapping(mapping, -1), StatusIs(absl::StatusCode::kInvalidArgument, ::testing::HasSubstr("parent_size can not be negative"))); EXPECT_THAT( DenseArrayEdge::FromMapping(mapping, 2), StatusIs(absl::StatusCode::kInvalidArgument, ::testing::HasSubstr("parent_size=2, but parent id 2 is used"))); EXPECT_THAT( DenseArrayEdge::FromMapping(bad_mapping, 3), StatusIs(absl::StatusCode::kInvalidArgument, ::testing::HasSubstr("mapping can't contain negative values"))); ASSERT_OK_AND_ASSIGN(auto edge, DenseArrayEdge::FromMapping(mapping, 3)); EXPECT_THAT(edge.edge_type(), Eq(DenseArrayEdge::MAPPING)); EXPECT_THAT(edge.edge_values().values, Eq(mapping.values)); EXPECT_EQ(edge.parent_size(), 3); EXPECT_EQ(edge.child_size(), 9); } TEST(DenseArrayEdgeTest, FromUniformGroups) { { ASSERT_OK_AND_ASSIGN(auto edge, DenseArrayEdge::FromUniformGroups(0, 5)); EXPECT_THAT(edge.edge_type(), DenseArrayEdge::SPLIT_POINTS); EXPECT_EQ(edge.parent_size(), 0); EXPECT_EQ(edge.child_size(), 0); EXPECT_THAT(edge.edge_values(), ElementsAre(0)); } { ASSERT_OK_AND_ASSIGN(auto edge, DenseArrayEdge::FromUniformGroups(3, 0)); EXPECT_THAT(edge.edge_type(), DenseArrayEdge::SPLIT_POINTS); EXPECT_EQ(edge.parent_size(), 3); EXPECT_EQ(edge.child_size(), 0); EXPECT_THAT(edge.edge_values(), ElementsAre(0, 0, 0, 0)); } { ASSERT_OK_AND_ASSIGN(auto edge, DenseArrayEdge::FromUniformGroups(3, 4)); EXPECT_THAT(edge.edge_type(), DenseArrayEdge::SPLIT_POINTS); EXPECT_EQ(edge.parent_size(), 3); EXPECT_EQ(edge.child_size(), 12); EXPECT_THAT(edge.edge_values(), ElementsAre(0, 4, 8, 12)); } { EXPECT_THAT(DenseArrayEdge::FromUniformGroups(-1, 3), StatusIs(absl::StatusCode::kInvalidArgument, "parent_size and group_size cannot be negative")); EXPECT_THAT(DenseArrayEdge::FromUniformGroups(3, -1), StatusIs(absl::StatusCode::kInvalidArgument, "parent_size and group_size cannot be negative")); } { ASSERT_OK_AND_ASSIGN(auto edge, DenseArrayEdge::FromUniformGroups(1, 1)); EXPECT_TRUE(edge.edge_values().values.is_owner()); } { UnsafeArenaBufferFactory arena{128}; ASSERT_OK_AND_ASSIGN(auto edge, DenseArrayEdge::FromUniformGroups(1, 1, arena)); EXPECT_FALSE(edge.edge_values().values.is_owner()); } } TEST(DenseArrayEdgeTest, DefaultEdge) { DenseArrayEdge edge; EXPECT_THAT(edge.edge_type(), Eq(DenseArrayEdge::MAPPING)); EXPECT_THAT(edge.edge_values().values, ElementsAre()); EXPECT_EQ(edge.parent_size(), 0); EXPECT_EQ(edge.child_size(), 0); } TEST(DenseArrayEdgeTest, Fingerprint) { const auto mapping = CreateDenseArray<int64_t>({0, 0, 0, 1, 1}); const auto split_points = CreateDenseArray<int64_t>({0, 3, 5}); ASSERT_OK_AND_ASSIGN(auto edge_from_mapping_1, DenseArrayEdge::FromMapping(mapping, 2)); ASSERT_OK_AND_ASSIGN(auto edge_from_mapping_2, DenseArrayEdge::FromMapping(mapping, 2)); ASSERT_OK_AND_ASSIGN(auto edge_from_split_points, DenseArrayEdge::FromSplitPoints(split_points)); EXPECT_EQ(FingerprintHasher("salt").Combine(edge_from_mapping_1).Finish(), FingerprintHasher("salt").Combine(edge_from_mapping_2).Finish()); EXPECT_NE(FingerprintHasher("salt").Combine(edge_from_mapping_1).Finish(), FingerprintHasher("salt").Combine(edge_from_split_points).Finish()); } TEST(DenseArrayEdgeTest, ToSplitPointsEdge_Success) { { const auto split_points = CreateDenseArray<int64_t>({0, 3, 5}); ASSERT_OK_AND_ASSIGN(auto edge, DenseArrayEdge::FromSplitPoints(split_points)); ASSERT_OK_AND_ASSIGN(auto edge2, edge.ToSplitPointsEdge()); EXPECT_EQ(edge.parent_size(), edge2.parent_size()); EXPECT_EQ(edge.child_size(), edge2.child_size()); EXPECT_EQ(edge2.edge_type(), DenseArrayEdge::SPLIT_POINTS); EXPECT_THAT(edge2.edge_values().values, ElementsAre(0, 3, 5)); } { const auto mapping = CreateDenseArray<int64_t>({0, 0, 1, 1, 3, 5}); ASSERT_OK_AND_ASSIGN(auto mapping_edge, DenseArrayEdge::FromMapping(mapping, 8)); ASSERT_OK_AND_ASSIGN(auto split_point_edge, mapping_edge.ToSplitPointsEdge()); EXPECT_EQ(mapping_edge.parent_size(), split_point_edge.parent_size()); EXPECT_EQ(mapping_edge.child_size(), split_point_edge.child_size()); EXPECT_EQ(split_point_edge.edge_type(), DenseArrayEdge::SPLIT_POINTS); EXPECT_THAT(split_point_edge.edge_values().values, ElementsAre(0, 2, 4, 4, 5, 5, 6, 6, 6)); } } TEST(DenseArrayEdgeTest, ToSplitPointsEdge_Errors) { { const auto mapping = CreateDenseArray<int64_t>({0, std::nullopt}); ASSERT_OK_AND_ASSIGN(auto mapping_edge, DenseArrayEdge::FromMapping(mapping, 2)); EXPECT_THAT(mapping_edge.ToSplitPointsEdge(), StatusIs(absl::StatusCode::kInvalidArgument, "expected a full mapping")); } { const auto mapping = CreateDenseArray<int64_t>({1, 0}); ASSERT_OK_AND_ASSIGN(auto mapping_edge, DenseArrayEdge::FromMapping(mapping, 2)); EXPECT_THAT(mapping_edge.ToSplitPointsEdge(), StatusIs(absl::StatusCode::kInvalidArgument, "expected a sorted mapping")); } } TEST(DenseArrayEdgeTest, ToSplitPointsEdge_BufferFactory) { { const auto mapping = CreateDenseArray<int64_t>({0, 0, 1, 1, 3, 5}); ASSERT_OK_AND_ASSIGN(auto mapping_edge, DenseArrayEdge::FromMapping(mapping, 8)); ASSERT_OK_AND_ASSIGN(auto split_point_edge, mapping_edge.ToSplitPointsEdge()); EXPECT_TRUE(split_point_edge.edge_values().values.is_owner()); } { const auto mapping = CreateDenseArray<int64_t>({0, 0, 1, 1, 3, 5}); ASSERT_OK_AND_ASSIGN(auto mapping_edge, DenseArrayEdge::FromMapping(mapping, 8)); UnsafeArenaBufferFactory arena{128}; ASSERT_OK_AND_ASSIGN(auto split_point_edge, mapping_edge.ToSplitPointsEdge(arena)); EXPECT_FALSE(split_point_edge.edge_values().values.is_owner()); } } TEST(DenseArrayEdgeTest, ToMappingEdge) { { const auto mapping = CreateDenseArray<int64_t>({0, 1, 0, std::nullopt, 3, 5}); ASSERT_OK_AND_ASSIGN(auto edge, DenseArrayEdge::FromMapping(mapping, 8)); auto edge2 = edge.ToMappingEdge(); EXPECT_EQ(edge.parent_size(), edge2.parent_size()); EXPECT_EQ(edge.child_size(), edge2.child_size()); EXPECT_EQ(edge2.edge_type(), DenseArrayEdge::MAPPING); EXPECT_THAT(edge2.edge_values(), ElementsAre(0, 1, 0, std::nullopt, 3, 5)); } { const auto split_points = CreateDenseArray<int64_t>({0, 3, 5}); ASSERT_OK_AND_ASSIGN(auto split_points_edge, DenseArrayEdge::FromSplitPoints(split_points)); auto mapping_edge = split_points_edge.ToMappingEdge(); EXPECT_EQ(split_points_edge.parent_size(), mapping_edge.parent_size()); EXPECT_EQ(split_points_edge.child_size(), mapping_edge.child_size()); EXPECT_EQ(mapping_edge.edge_type(), DenseArrayEdge::MAPPING); EXPECT_THAT(mapping_edge.edge_values(), ElementsAre(0, 0, 0, 1, 1)); } { const auto split_points = CreateDenseArray<int64_t>({0, 3, 5}); ASSERT_OK_AND_ASSIGN(auto split_points_edge, DenseArrayEdge::FromSplitPoints(split_points)); auto mapping_edge = split_points_edge.ToMappingEdge(); EXPECT_TRUE(mapping_edge.edge_values().values.is_owner()); UnsafeArenaBufferFactory arena{128}; mapping_edge = split_points_edge.ToMappingEdge(arena); EXPECT_FALSE(mapping_edge.edge_values().values.is_owner()); } } TEST(DenseArrayEdgeTest, IsEquivalentTo) { { const auto split_points = CreateDenseArray<int64_t>({0, 3, 5}); ASSERT_OK_AND_ASSIGN(auto edge1, DenseArrayEdge::FromSplitPoints(split_points)); ASSERT_OK_AND_ASSIGN(auto edge2, DenseArrayEdge::FromSplitPoints(split_points)); EXPECT_TRUE(edge1.IsEquivalentTo(edge2)); } { const auto mapping = CreateDenseArray<int64_t>({0, 0, std::nullopt, 1, 3, 5}); ASSERT_OK_AND_ASSIGN(auto edge1, DenseArrayEdge::FromMapping(mapping, 8)); ASSERT_OK_AND_ASSIGN(auto edge2, DenseArrayEdge::FromMapping(mapping, 8)); EXPECT_TRUE(edge1.IsEquivalentTo(edge2)); } { const auto mapping = CreateDenseArray<int64_t>({0, 0, 0, 1, 1}); ASSERT_OK_AND_ASSIGN(auto edge1, DenseArrayEdge::FromMapping(mapping, 2)); const auto split_points = CreateDenseArray<int64_t>({0, 3, 5}); ASSERT_OK_AND_ASSIGN(auto edge2, DenseArrayEdge::FromSplitPoints(split_points)); EXPECT_TRUE(edge1.IsEquivalentTo(edge2)); } { const auto mapping = CreateDenseArray<int64_t>({0, 0, 1, 0, 1}); ASSERT_OK_AND_ASSIGN(auto edge1, DenseArrayEdge::FromMapping(mapping, 2)); const auto split_points = CreateDenseArray<int64_t>({0, 3, 5}); ASSERT_OK_AND_ASSIGN(auto edge2, DenseArrayEdge::FromSplitPoints(split_points)); EXPECT_FALSE(edge1.IsEquivalentTo(edge2)); } { const auto mapping = CreateDenseArray<int64_t>({0, 0, 0, 1, 1}); ASSERT_OK_AND_ASSIGN(auto edge1, DenseArrayEdge::FromMapping(mapping, 2)); ASSERT_OK_AND_ASSIGN(auto edge2, DenseArrayEdge::FromMapping(mapping, 3)); EXPECT_FALSE(edge1.IsEquivalentTo(edge2)); } { const auto mapping1 = CreateDenseArray<int64_t>({0, 0, 0, 1, 1}); ASSERT_OK_AND_ASSIGN(auto edge1, DenseArrayEdge::FromMapping(mapping1, 2)); const auto mapping2 = CreateDenseArray<int64_t>({0, 1, 1}); ASSERT_OK_AND_ASSIGN(auto edge2, DenseArrayEdge::FromMapping(mapping2, 2)); EXPECT_FALSE(edge1.IsEquivalentTo(edge2)); } { const auto mapping1 = CreateDenseArray<int64_t>({0, 0, 0, 1, 1}); ASSERT_OK_AND_ASSIGN(auto edge1, DenseArrayEdge::FromMapping(mapping1, 2)); const auto mapping2 = CreateDenseArray<int64_t>({0, 0, 1, 1, 1}); ASSERT_OK_AND_ASSIGN(auto edge2, DenseArrayEdge::FromMapping(mapping2, 2)); EXPECT_FALSE(edge1.IsEquivalentTo(edge2)); } } TEST(DenseArrayEdgeTest, ComposeEdges_SplitPoint) { ASSERT_OK_AND_ASSIGN(auto edge1, DenseArrayEdge::FromSplitPoints( CreateDenseArray<int64_t>({0, 2}))); ASSERT_OK_AND_ASSIGN(auto edge2, DenseArrayEdge::FromSplitPoints( CreateDenseArray<int64_t>({0, 1, 3}))); ASSERT_OK_AND_ASSIGN( auto edge3, DenseArrayEdge::FromSplitPoints(CreateDenseArray<int64_t>({0, 1, 2, 4}))); ASSERT_OK_AND_ASSIGN(auto edge4, DenseArrayEdge::FromSplitPoints( CreateDenseArray<int64_t>({0, 3, 4, 11, 12}))); { ASSERT_OK_AND_ASSIGN(auto composed_edge, DenseArrayEdge::ComposeEdges( {edge1, edge2, edge3, edge4})); EXPECT_EQ(composed_edge.edge_type(), DenseArrayEdge::SPLIT_POINTS); EXPECT_THAT(composed_edge.edge_values(), ElementsAre(0, 12)); } { ASSERT_OK_AND_ASSIGN(auto composed_edge, DenseArrayEdge::ComposeEdges({edge2, edge3, edge4})); EXPECT_EQ(composed_edge.edge_type(), DenseArrayEdge::SPLIT_POINTS); EXPECT_THAT(composed_edge.edge_values(), ElementsAre(0, 3, 12)); } { ASSERT_OK_AND_ASSIGN(auto composed_edge, DenseArrayEdge::ComposeEdges({edge3, edge4})); EXPECT_EQ(composed_edge.edge_type(), DenseArrayEdge::SPLIT_POINTS); EXPECT_THAT(composed_edge.edge_values(), ElementsAre(0, 3, 4, 12)); } { ASSERT_OK_AND_ASSIGN(auto composed_edge, DenseArrayEdge::ComposeEdges({edge4})); EXPECT_EQ(composed_edge.edge_type(), DenseArrayEdge::SPLIT_POINTS); EXPECT_THAT(composed_edge.edge_values(), ElementsAre(0, 3, 4, 11, 12)); } { EXPECT_THAT(DenseArrayEdge::ComposeEdges({}), StatusIs(absl::StatusCode::kInvalidArgument, "at least one edge must be present")); } { EXPECT_THAT(DenseArrayEdge::ComposeEdges({edge1, edge3}), StatusIs(absl::StatusCode::kInvalidArgument, "incompatible edges: edges[0].child_size (2) != " "edges[1].parent_size (3)")); } } TEST(DenseArrayEdgeTest, ComposeEdges_Mapping) { ASSERT_OK_AND_ASSIGN(auto edge1, DenseArrayEdge::FromMapping( CreateDenseArray<int64_t>({0, std::nullopt}), 5)); ASSERT_OK_AND_ASSIGN(auto edge2, DenseArrayEdge::FromMapping( CreateDenseArray<int64_t>({0, 1, std::nullopt}), 2)); ASSERT_OK_AND_ASSIGN( auto edge3, DenseArrayEdge::FromMapping(CreateDenseArray<int64_t>({1, 2, 0, 2}), 3)); ASSERT_OK_AND_ASSIGN(auto edge4, DenseArrayEdge::FromSplitPoints( CreateDenseArray<int64_t>({0, 3, 4, 11, 12}))); ASSERT_OK_AND_ASSIGN( auto edge5, DenseArrayEdge::FromSplitPoints(CreateDenseArray<int64_t>( {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}))); { ASSERT_OK_AND_ASSIGN( auto composed_edge, DenseArrayEdge::ComposeEdges({edge1, edge2, edge3, edge4, edge5})); EXPECT_EQ(composed_edge.edge_type(), DenseArrayEdge::MAPPING); EXPECT_EQ(composed_edge.parent_size(), 5); EXPECT_THAT(composed_edge.edge_values(), ElementsAre(std::nullopt, std::nullopt, std::nullopt, std::nullopt, 0, 0, 0, 0, 0, 0, 0, std::nullopt)); } { ASSERT_OK_AND_ASSIGN(auto composed_edge, DenseArrayEdge::ComposeEdges({edge2, edge3, edge4})); EXPECT_EQ(composed_edge.edge_type(), DenseArrayEdge::MAPPING); EXPECT_EQ(composed_edge.parent_size(), 2); EXPECT_THAT( composed_edge.edge_values(), ElementsAre(1, 1, 1, std::nullopt, 0, 0, 0, 0, 0, 0, 0, std::nullopt)); } { ASSERT_OK_AND_ASSIGN(auto composed_edge, DenseArrayEdge::ComposeEdges({edge3, edge4})); EXPECT_EQ(composed_edge.edge_type(), DenseArrayEdge::MAPPING); EXPECT_EQ(composed_edge.parent_size(), 3); EXPECT_THAT(composed_edge.edge_values(), ElementsAre(1, 1, 1, 2, 0, 0, 0, 0, 0, 0, 0, 2)); } { ASSERT_OK_AND_ASSIGN( auto composed_edge, DenseArrayEdge::ComposeEdges({edge4, edge5.ToMappingEdge()})); EXPECT_EQ(composed_edge.edge_type(), DenseArrayEdge::MAPPING); EXPECT_EQ(composed_edge.parent_size(), 4); EXPECT_THAT(composed_edge.edge_values(), ElementsAre(0, 0, 0, 1, 2, 2, 2, 2, 2, 2, 2, 3)); } { ASSERT_OK_AND_ASSIGN(auto composed_edge, DenseArrayEdge::ComposeEdges({edge2, edge3})); EXPECT_EQ(composed_edge.edge_type(), DenseArrayEdge::MAPPING); EXPECT_EQ(composed_edge.parent_size(), 2); EXPECT_THAT(composed_edge.edge_values(), ElementsAre(1, std::nullopt, 0, std::nullopt)); } { ASSERT_OK_AND_ASSIGN(auto composed_edge, DenseArrayEdge::ComposeEdges({edge4.ToMappingEdge()})); EXPECT_EQ(composed_edge.edge_type(), DenseArrayEdge::MAPPING); EXPECT_EQ(composed_edge.parent_size(), 4); EXPECT_THAT(composed_edge.edge_values(), ElementsAre(0, 0, 0, 1, 2, 2, 2, 2, 2, 2, 2, 3)); } { EXPECT_THAT(DenseArrayEdge::ComposeEdges({}), StatusIs(absl::StatusCode::kInvalidArgument, "at least one edge must be present")); } { EXPECT_THAT(DenseArrayEdge::ComposeEdges({edge1, edge3}), StatusIs(absl::StatusCode::kInvalidArgument, "incompatible edges: edges[0].child_size (2) != " "edges[1].parent_size (3)")); } } TEST(DenseArrayEdgeTest, ComposeEdges_BufferFactory) { ASSERT_OK_AND_ASSIGN(auto edge1, DenseArrayEdge::FromSplitPoints( CreateDenseArray<int64_t>({0, 2}))); ASSERT_OK_AND_ASSIGN(auto edge2, DenseArrayEdge::FromSplitPoints( CreateDenseArray<int64_t>({0, 1, 3}))); { ASSERT_OK_AND_ASSIGN(auto composed_edge, DenseArrayEdge::ComposeEdges({edge1, edge2})); EXPECT_TRUE(composed_edge.edge_values().values.is_owner()); } { UnsafeArenaBufferFactory arena{128}; ASSERT_OK_AND_ASSIGN(auto composed_edge, DenseArrayEdge::ComposeEdges({edge1, edge2}, arena)); EXPECT_FALSE(composed_edge.edge_values().values.is_owner()); } } } }
2,381
cpp
google/arolla
array
arolla/array/array.cc
arolla/array/array_test.cc
#ifndef AROLLA_ARRAY_ARRAY_H_ #define AROLLA_ARRAY_ARRAY_H_ #include <algorithm> #include <cstddef> #include <cstdint> #include <cstring> #include <iterator> #include <optional> #include <type_traits> #include <utility> #include "absl/base/attributes.h" #include "absl/log/check.h" #include "absl/types/span.h" #include "arolla/array/id_filter.h" #include "arolla/dense_array/bitmap.h" #include "arolla/dense_array/dense_array.h" #include "arolla/memory/buffer.h" #include "arolla/memory/optional_value.h" #include "arolla/memory/raw_buffer_factory.h" #include "arolla/util/api.h" #include "arolla/util/fingerprint.h" #include "arolla/util/iterator.h" #include "arolla/util/repr.h" #include "arolla/util/view_types.h" namespace arolla { template <class T> class AROLLA_API Array { public: explicit Array(int64_t size = 0, OptionalValue<T> value = std::nullopt) : size_(size), id_filter_(IdFilter::kEmpty), missing_id_value_(std::move(value)) { DCHECK_GE(size_, 0); } explicit Array(DenseArray<T> data) : size_(data.size()), id_filter_(IdFilter::kFull), dense_data_(std::move(data)) { DCHECK(dense_data_.CheckBitmapMatchesValues()); } explicit Array(Buffer<T> data) : size_(data.size()), id_filter_(IdFilter::kFull), dense_data_(DenseArray<T>{std::move(data)}) {} explicit Array(int64_t size, IdFilter ids, DenseArray<T> data, OptionalValue<T> missing_id_value = std::nullopt) : size_(size), id_filter_(std::move(ids)), dense_data_(std::move(data)), missing_id_value_(std::move(missing_id_value)) { DCHECK_GE(size_, 0); DCHECK(dense_data_.CheckBitmapMatchesValues()); switch (id_filter_.type()) { case IdFilter::kEmpty: DCHECK(dense_data_.empty()); break; case IdFilter::kPartial: DCHECK_LT(id_filter_.ids().size(), size_); DCHECK_EQ(id_filter_.ids().size(), dense_data_.size()); DCHECK_LT(id_filter_.ids().back() - id_filter_.ids_offset(), size_); break; case IdFilter::kFull: DCHECK_EQ(dense_data_.size(), size_); missing_id_value_ = std::nullopt; break; } } int64_t size() const { return size_; } bool empty() const { return size_ == 0; } const IdFilter& id_filter() const { return id_filter_; } const DenseArray<T>& dense_data() const { return dense_data_; } const OptionalValue<T>& missing_id_value() const { return missing_id_value_; } const OptionalValue<view_type_t<T>> operator[]( int64_t index) const { DCHECK_GE(index, 0); DCHECK_LT(index, size_); OptionalValue<int64_t> offset = id_filter_.IdToOffset(index); if (offset.present) { return dense_data_[offset.value]; } else { return missing_id_value_; } } bool IsConstForm() const { return id_filter_.type() == IdFilter::kEmpty; } bool IsDenseForm() const { return id_filter_.type() == IdFilter::kFull; } bool IsSparseForm() const { return id_filter_.type() == IdFilter::kPartial; } bool IsAllMissingForm() const { return IsConstForm() && !missing_id_value_.present; } bool IsFullForm() const { return IsDenseForm() && dense_data_.bitmap.empty(); } bool HasMissingIdValue() const { return !IsDenseForm() && missing_id_value_.present && size_ > 0; } Array WithIds(const IdFilter& ids, const OptionalValue<T>& missing_id_value, RawBufferFactory* buf_factory = GetHeapBufferFactory()) const; Array ToDenseForm( RawBufferFactory* buf_factory = GetHeapBufferFactory()) const { return WithIds(IdFilter::kFull, std::nullopt, buf_factory); } Array ToSparseForm( OptionalValue<T> missing_id_value = std::nullopt, RawBufferFactory* buf_factory = GetHeapBufferFactory()) const; bool is_owned() const { return dense_data_.is_owned() && (id_filter_.type() != IdFilter::kPartial || id_filter_.ids().is_owner()); } Array MakeOwned( RawBufferFactory* buf_factory = GetHeapBufferFactory()) const { IdFilter ids = id_filter_.type() == IdFilter::kPartial ? IdFilter(size_, id_filter_.ids().DeepCopy(buf_factory), id_filter_.ids_offset()) : id_filter_; return Array(size_, std::move(ids), dense_data_.MakeOwned(buf_factory), missing_id_value_); } Array Slice(int64_t start_id, int64_t row_count) const { DCHECK_GE(start_id, 0); DCHECK_GE(row_count, 0); DCHECK_LE(start_id + row_count, size_); if (id_filter_.type() == IdFilter::kEmpty) { return Array(row_count, missing_id_value_); } IdFilter filter = IdFilter::kFull; int64_t start_offset = start_id; int64_t dense_count = row_count; if (id_filter_.type() == IdFilter::kPartial) { int64_t new_ids_offset = id_filter_.ids_offset() + start_id; const Buffer<int64_t>& ids = id_filter_.ids(); auto iter_start = std::lower_bound(ids.begin(), ids.end(), new_ids_offset); auto iter_end = std::lower_bound(ids.begin(), ids.end(), new_ids_offset + row_count); start_offset = std::distance(ids.begin(), iter_start); dense_count = std::distance(iter_start, iter_end); filter = IdFilter(row_count, ids.Slice(start_offset, dense_count), new_ids_offset); } return Array(row_count, std::move(filter), dense_data_.Slice(start_offset, dense_count), missing_id_value_); } int64_t PresentCount() const { int64_t res = bitmap::CountBits( dense_data_.bitmap, dense_data_.bitmap_bit_offset, dense_data_.size()); if (HasMissingIdValue()) res += size_ - dense_data_.size(); return res; } using base_type = T; using value_type = OptionalValue<view_type_t<T>>; using size_type = int64_t; using const_iterator = ConstArrayIterator<Array<T>>; using difference_type = int64_t; using offset_type = int64_t; const_iterator begin() const { return const_iterator{this, 0}; } const_iterator end() const { return const_iterator{this, size()}; } template <typename Fn, typename RepeatedFn> void ForEach(Fn&& fn, RepeatedFn&& repeated_fn) const { if (IsConstForm()) { repeated_fn(0, size_, missing_id_value_.present, missing_id_value_.value); return; } if (IsDenseForm()) { dense_data_.ForEach(fn); return; } int64_t id = 0; dense_data_.ForEach([&](int64_t offset, bool present, view_type_t<T> v) { int64_t new_id = id_filter_.IdsOffsetToId(offset); if (id < new_id) repeated_fn(id, new_id - id, missing_id_value_.present, missing_id_value_.value); fn(id_filter_.IdsOffsetToId(offset), present, v); id = new_id + 1; }); if (id < size_) { repeated_fn(id, size_ - id, missing_id_value_.present, missing_id_value_.value); } } template <typename Fn> void ForEach(Fn&& fn) const { ForEach(fn, [&](int64_t first_id, int64_t count, bool present, view_type_t<T> value) { for (int64_t i = 0; i < count; ++i) { fn(first_id + i, present, value); } }); } template <typename Fn, typename RepeatedFn> void ForEachPresent(Fn&& fn, RepeatedFn&& repeated_fn) const { if (IsAllMissingForm()) return; if (IsConstForm()) { repeated_fn(0, size_, missing_id_value_.value); return; } if (IsDenseForm()) { dense_data_.ForEach([&fn](int64_t id, bool present, view_type_t<T> v) { if (present) fn(id, v); }); return; } if (HasMissingIdValue()) { int64_t id = 0; dense_data_.ForEach([&](int64_t offset, bool present, view_type_t<T> v) { int64_t new_id = id_filter_.IdsOffsetToId(offset); if (id < new_id) repeated_fn(id, new_id - id, missing_id_value_.value); if (present) fn(id_filter_.IdsOffsetToId(offset), v); id = new_id + 1; }); if (id < size_) { repeated_fn(id, size_ - id, missing_id_value_.value); } } else { dense_data_.ForEach( [this, &fn](int64_t offset, bool present, view_type_t<T> v) { if (present) fn(id_filter_.IdsOffsetToId(offset), v); }); } } template <typename Fn> void ForEachPresent(Fn&& fn) const { ForEachPresent(fn, [&](int64_t first_id, int64_t count, view_type_t<T> value) { for (int64_t i = 0; i < count; ++i) { fn(first_id + i, value); } }); } private: DenseArray<T> WithIdsFromSparse(const IdFilter& ids, RawBufferFactory* buf_factory) const; DenseArray<T> WithIdsDenseToSparse(const IdFilter& ids, RawBufferFactory* buf_factory) const; Array<T> ToSparseFormWithChangedMissedIdValue( OptionalValue<T> missing_id_value, RawBufferFactory* buf_factory) const; Array<T> ToSparseFormWithMissedIdValue(const T& missing_id_value, RawBufferFactory* buf_factory) const; Array<T> ToSparseFormWithoutMissedIdValue( RawBufferFactory* buf_factory) const; int64_t size_; IdFilter id_filter_; DenseArray<T> dense_data_; OptionalValue<T> missing_id_value_; }; template <typename T> bool ArraysAreEquivalent(const Array<T>& lhs, const Array<T>& rhs) { if (lhs.size() != rhs.size()) return false; if (lhs.IsDenseForm() && rhs.IsDenseForm()) { return ArraysAreEquivalent(lhs.dense_data(), rhs.dense_data()); } IdFilter id_union = IdFilter::UpperBoundMerge( lhs.size(), GetHeapBufferFactory(), lhs.id_filter(), rhs.id_filter()); auto lhs_transformed = lhs.WithIds(id_union, lhs.missing_id_value()); auto rhs_transformed = rhs.WithIds(id_union, rhs.missing_id_value()); return lhs_transformed.missing_id_value() == rhs_transformed.missing_id_value() && ArraysAreEquivalent(lhs_transformed.dense_data(), rhs_transformed.dense_data()); } template <class T> Array<T> CreateArray(absl::Span<const OptionalValue<T>> data) { return Array<T>(CreateDenseArray<T>(data)); } template <class T, class ValueT = T> Array<T> CreateArray(int64_t size, absl::Span<const int64_t> ids, absl::Span<const ValueT> values) { DCHECK_EQ(ids.size(), values.size()); DCHECK_LE(values.size(), size); if (values.size() > size * IdFilter::kDenseSparsityLimit) { DenseArrayBuilder<T> bldr(size); for (int64_t i = 0; i < values.size(); ++i) { bldr.Set(ids[i], values[i]); } return Array<T>(std::move(bldr).Build()); } else { Buffer<int64_t>::Builder ids_bldr(ids.size()); DenseArrayBuilder<T> values_bldr(values.size()); for (int64_t i = 0; i < values.size(); ++i) { ids_bldr.Set(i, ids[i]); values_bldr.Set(i, values[i]); } return Array<T>(size, IdFilter(size, std::move(ids_bldr).Build()), std::move(values_bldr).Build()); } } template <class T> using AsArray = Array<strip_optional_t<std::decay_t<T>>>; struct AROLLA_API ArrayShape { int64_t size; bool operator==(const ArrayShape& other) const { return size == other.size; } }; AROLLA_DECLARE_REPR(ArrayShape); AROLLA_DECLARE_FINGERPRINT_HASHER_TRAITS(ArrayShape); template <class T> Array<T> Array<T>::WithIds(const IdFilter& ids, const OptionalValue<T>& missing_id_value, RawBufferFactory* buf_factory) const { if (ids.type() == IdFilter::kEmpty || size_ == 0) { return Array(size_, missing_id_value); } if (id_filter_.IsSame(ids)) { return Array(size_, ids, dense_data_, missing_id_value); } DenseArray<T> new_data; switch (id_filter_.type()) { case IdFilter::kEmpty: { int64_t data_size = ids.type() == IdFilter::kPartial ? ids.ids().size() : size_; if (missing_id_value_.present) { new_data = CreateConstDenseArray<T>(data_size, missing_id_value_.value, buf_factory); } else { new_data = CreateEmptyDenseArray<T>(data_size, buf_factory); } } break; case IdFilter::kPartial: { new_data = WithIdsFromSparse(ids, buf_factory); } break; case IdFilter::kFull: { new_data = WithIdsDenseToSparse(ids, buf_factory); } break; } return Array(size_, ids, std::move(new_data), missing_id_value); } template <class T> ABSL_ATTRIBUTE_NOINLINE DenseArray<T> Array<T>::WithIdsFromSparse( const IdFilter& ids, RawBufferFactory* buf_factory) const { DCHECK_EQ(id_filter_.type(), IdFilter::kPartial); DCHECK_NE(ids.type(), IdFilter::kEmpty); size_t data_size = ids.type() == IdFilter::kPartial ? ids.ids().size() : size_; typename Buffer<T>::ReshuffleBuilder values_bldr( data_size, dense_data_.values, missing_id_value_, buf_factory); bitmap::RawBuilder bitmap_bldr(bitmap::BitmapSize(data_size), buf_factory); auto bitmap = bitmap_bldr.GetMutableSpan(); std::memset(bitmap.begin(), missing_id_value_.present ? 0xff : 0, bitmap.size() * sizeof(bitmap::Word)); if (ids.type() == IdFilter::kPartial) { IdFilter::IntersectPartial_ForEach( id_filter_, ids, [&](int64_t , int64_t old_offset, int64_t new_offset) { if (dense_data_.present(old_offset)) { values_bldr.CopyValue(new_offset, old_offset); bitmap::SetBit(bitmap.begin(), new_offset); } else { bitmap::UnsetBit(bitmap.begin(), new_offset); } }); } else if (missing_id_value_.present) { DCHECK_EQ(ids.type(), IdFilter::kFull); dense_data_.ForEach([&](int64_t offset, bool present, view_type_t<T>) { int64_t new_offset = id_filter_.IdsOffsetToId(offset); if (present) { values_bldr.CopyValue(new_offset, offset); } else { bitmap::UnsetBit(bitmap.begin(), new_offset); } }); } else { DCHECK_EQ(ids.type(), IdFilter::kFull); dense_data_.ForEach([&](int64_t offset, bool present, view_type_t<T>) { int64_t new_offset = id_filter_.IdsOffsetToId(offset); if (present) { values_bldr.CopyValue(new_offset, offset); bitmap::SetBit(bitmap.begin(), new_offset); } }); } if (bitmap::AreAllBitsSet(bitmap.begin(), data_size)) { return {std::move(values_bldr).Build()}; } else { return {std::move(values_bldr).Build(), std::move(bitmap_bldr).Build()}; } } template <class T> ABSL_ATTRIBUTE_NOINLINE DenseArray<T> Array<T>::WithIdsDenseToSparse( const IdFilter& ids, RawBufferFactory* buf_factory) const { DCHECK_EQ(id_filter_.type(), IdFilter::kFull); DCHECK_EQ(ids.type(), IdFilter::kPartial); typename Buffer<T>::ReshuffleBuilder values_bldr( ids.ids().size(), dense_data_.values, std::nullopt, buf_factory); int64_t index = 0; if (dense_data_.bitmap.empty()) { for (IdFilter::IdWithOffset id : ids.ids()) { values_bldr.CopyValue(index++, id - ids.ids_offset()); } return {std::move(values_bldr).Build()}; } else { bitmap::Builder bitmap_bldr(ids.ids().size(), buf_factory); bitmap_bldr.AddForEach(ids.ids(), [&](IdFilter::IdWithOffset id_with_offset) { int64_t id = id_with_offset - ids.ids_offset(); values_bldr.CopyValue(index++, id); return dense_data_.present(id); }); return {std::move(values_bldr).Build(), std::move(bitmap_bldr).Build()}; } } template <class T> Array<T> Array<T>::ToSparseForm(OptionalValue<T> missing_id_value, RawBufferFactory* buf_factory) const { if (!IsDenseForm() && missing_id_value != missing_id_value_) { return ToSparseFormWithChangedMissedIdValue(missing_id_value, buf_factory); } else if (missing_id_value.present) { return ToSparseFormWithMissedIdValue(missing_id_value.value, buf_factory); } else { return ToSparseFormWithoutMissedIdValue(buf_factory); } } template <class T> Array<T> Array<T>::ToSparseFormWithChangedMissedIdValue( OptionalValue<T> missing_id_value, RawBufferFactory* buf_factory) const { DCHECK(!IsDenseForm() && missing_id_value != missing_id_value_); Buffer<IdFilter::IdWithOffset>::Builder bldr(size_, buf_factory); auto inserter = bldr.GetInserter(); int64_t next_id = 0; dense_data_.ForEach([&](int64_t offset, bool presence, view_type_t<T> value) { int64_t id = id_filter_.IdsOffsetToId(offset); while (next_id < id) inserter.Add(next_id++); if (presence != missing_id_value.present || (presence && missing_id_value.value != value)) { inserter.Add(id); } next_id = id + 1; }); while (next_id < size_) inserter.Add(next_id++); return WithIds(IdFilter(size_, std::move(bldr).Build(inserter)), missing_id_value, buf_factory); } template <class T> Array<T> Array<T>::ToSparseFormWithMissedIdValue( const T& missing_id_value, RawBufferFactory* buf_factory) const { DCHECK(IsDenseForm() || missing_id_value_ == missing_id_value); Buffer<IdFilter::IdWithOffset>::Builder ids_bldr(dense_data_.size(), buf_factory); auto ids_inserter = ids_bldr.GetInserter(); if (IsDenseForm() && !dense_data_.bitmap.empty()) { dense_data_.ForEach( [&](int64_t offset, bool presence, view_type_t<T> value) { if (!presence || value != missing_id_value) { ids_inserter.Add(offset); } }); return WithIds(IdFilter(size_, std::move(ids_bldr).Build(ids_inserter)), missing_id_value, buf_factory); } typename Buffer<T>::ReshuffleBuilder values_bldr( dense_data_.size(), dense_data_.values, std::nullopt, buf_factory); bitmap::Bitmap bitmap; int64_t new_offset = 0; if (dense_data_.bitmap.empty()) { if (IsDenseForm()) { for (int64_t offset = 0; offset < dense_data_.size(); ++offset) { if (dense_data_.values[offset] != missing_id_value) { ids_inserter.Add(offset); values_bldr.CopyValue(new_offset++, offset); } } } else { for (int64_t offset = 0; offset < dense_data_.size(); ++offset) { if (dense_data_.values[offset] != missing_id_value) { ids_inserter.Add(id_filter_.IdsOffsetToId(offset)); values_bldr.CopyValue(new_offset++, offset); } } } } else { bitmap::AlmostFullBuilder bitmap_bldr(dense_data_.size(), buf_factory); dense_data_.ForEach( [&](int64_t offset, bool presence, view_type_t<T> value) { if (presence && value == missing_id_value) return; ids_inserter.Add(id_filter_.IdsOffsetToId(offset)); if (presence) { values_bldr.CopyValue(new_offset++, offset); } else { bitmap_bldr.AddMissed(new_offset++); } }); bitmap = std::move(bitmap_bldr).Build(new_offset); } IdFilter id_filter(size_, std::move(ids_bldr).Build(ids_inserter)); Buffer<T> values = std::move(values_bldr).Build(new_offset); return Array(size_, std::move(id_filter), {std::move(values), std::move(bitmap)}, missing_id_value); } template <class T> Array<T> Array<T>::ToSparseFormWithoutMissedIdValue( RawBufferFactory* buf_factory) const { DCHECK(!HasMissingIdValue()); if (dense_data_.bitmap.empty()) return *this; Buffer<IdFilter::IdWithOffset>::Builder ids_bldr(dense_data_.size(), buf_factory); typename Buffer<T>::ReshuffleBuilder values_bldr( dense_data_.size(), dense_data_.values, std::nullopt, buf_factory); auto ids_inserter = ids_bldr.GetInserter(); int64_t new_offset = 0; if (IsDenseForm()) { dense_data_.ForEach([&](int64_t offset, bool presence, view_type_t<T>) { if (presence) { ids_inserter.Add(offset); values_bldr.CopyValue(new_offset++, offset); } }); } else { dense_data_.ForEach([&](int64_t offset, bool presence, view_type_t<T>) { if (presence) { ids_inserter.Add(id_filter_.IdsOffsetToId(offset)); values_bldr.CopyValue(new_offset++, offset); } }); } IdFilter id_filter(size_, std::move(ids_bldr).Build(ids_inserter)); Buffer<T> values = std::move(values_bldr).Build(new_offset); return Array(size_, std::move(id_filter), {std::move(values)}); } template <typename T> struct ArenaTraits<Array<T>> { static Array<T> MakeOwned(Array<T>&& v, RawBufferFactory* buf_factory) { return v.MakeOwned(buf_factory); } }; template <typename T> struct FingerprintHasherTraits<Array<T>> { void operator()(FingerprintHasher* hasher, const Array<T>& arg) const { hasher->Combine(arg.size(), arg.dense_data(), arg.missing_id_value(), arg.id_filter()); } }; template <typename T> class SparseArrayBuilder { public: explicit SparseArrayBuilder( int64_t size, int64_t max_present_count, RawBufferFactory* buf_factory = GetHeapBufferFactory()) : size_(size), dense_builder_(max_present_count, buf_factory), ids_builder_(max_present_count, buf_factory) {} template <typename V> void Add(int64_t id, const V& v) { dense_builder_.Set(offset_, v); AddId(id); } void AddId(int64_t id) { DCHECK(id >= 0 && id < size_); DCHECK(offset_ == 0 || ids_builder_.GetMutableSpan()[offset_ - 1] < id); ids_builder_.Set(offset_++, id); } int64_t NextOffset() const { return offset_; } template <typename V> void SetByOffset(int64_t offset, const V& v) { dense_builder_.Set(offset, v); } Array<T> Build() && { return Array<T>(size_, IdFilter(size_, std::move(ids_builder_).Build(offset_)), std::move(dense_builder_).Build(offset_)); } private: int64_t size_; int64_t offset_ = 0; DenseArrayBuilder<T> dense_builder_; Buffer<int64_t>::Builder ids_builder_; }; } #endif #include "arolla/array/array.h" #include "absl/strings/str_cat.h" #include "arolla/util/fingerprint.h" #include "arolla/util/repr.h" namespace arolla { void FingerprintHasherTraits<ArrayShape>::operator()( FingerprintHasher* hasher, const ArrayShape& value) const { hasher->Combine(value.size); } ReprToken ReprTraits<ArrayShape>::operator()(const ArrayShape& value) const { return ReprToken{absl::StrCat("array_shape{size=", value.size, "}")}; } }
#include "arolla/array/array.h" #include <cstdint> #include <optional> #include <type_traits> #include <utility> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/strings/string_view.h" #include "arolla/array/id_filter.h" #include "arolla/dense_array/dense_array.h" #include "arolla/memory/buffer.h" #include "arolla/memory/optional_value.h" #include "arolla/memory/raw_buffer_factory.h" #include "arolla/util/bytes.h" #include "arolla/util/repr.h" #include "arolla/util/testing/repr_token_eq.h" namespace arolla { namespace { using ::arolla::testing::ReprTokenEq; using ::testing::ElementsAre; struct TryCompileAssignment { template <typename T> auto operator()(T v) -> decltype(v[0] = std::nullopt) { return v[0]; } }; struct TryCompileMutation { template <typename A, typename V> auto operator()(A a, V v) -> decltype(a[0].value = V()) { return a[0].value; } }; static_assert(!std::is_invocable_v<TryCompileAssignment, Array<int>>); static_assert( !std::is_invocable_v<TryCompileMutation, Array<Bytes>, absl::string_view>); TEST(DenseArrayTest, ArrayShapeRepr) { EXPECT_THAT(GenReprToken(ArrayShape{5}), ReprTokenEq("array_shape{size=5}")); } TEST(ArrayTest, BaseType) { static_assert(std::is_same_v<int, Array<int>::base_type>); static_assert(std::is_same_v<float, Array<float>::base_type>); } TEST(ArrayTest, Const) { { Array<int> block(0, {}); EXPECT_EQ(block.size(), 0); EXPECT_EQ(block.id_filter().type(), IdFilter::kEmpty); EXPECT_TRUE(block.IsConstForm()); EXPECT_TRUE(block.IsAllMissingForm()); EXPECT_FALSE(block.IsDenseForm()); } { Array<int> block(5, {}); EXPECT_EQ(block.id_filter().type(), IdFilter::kEmpty); EXPECT_TRUE(block.IsConstForm()); EXPECT_TRUE(block.IsAllMissingForm()); EXPECT_FALSE(block.IsDenseForm()); EXPECT_THAT(block, ElementsAre(std::nullopt, std::nullopt, std::nullopt, std::nullopt, std::nullopt)); } { Array<int> block(5, 3); EXPECT_EQ(block.id_filter().type(), IdFilter::kEmpty); EXPECT_TRUE(block.IsConstForm()); EXPECT_FALSE(block.IsAllMissingForm()); EXPECT_FALSE(block.IsDenseForm()); EXPECT_FALSE(block.IsSparseForm()); EXPECT_TRUE(block.HasMissingIdValue()); EXPECT_THAT(block, ElementsAre(3, 3, 3, 3, 3)); } } TEST(ArrayTest, Dense) { { Array<int> block = CreateArray<int>({2, 3, std::nullopt, 7}); EXPECT_EQ(block.id_filter().type(), IdFilter::kFull); EXPECT_FALSE(block.IsAllMissingForm()); EXPECT_FALSE(block.IsConstForm()); EXPECT_TRUE(block.IsDenseForm()); EXPECT_FALSE(block.IsFullForm()); EXPECT_FALSE(block.IsSparseForm()); EXPECT_FALSE(block.HasMissingIdValue()); EXPECT_THAT(block, ElementsAre(2, 3, std::nullopt, 7)); } { auto buffer = CreateBuffer<int>({2, 3, 5, 7}); Array<int> block(buffer); EXPECT_EQ(block.size(), buffer.size()); EXPECT_EQ(block.id_filter().type(), IdFilter::kFull); EXPECT_FALSE(block.IsAllMissingForm()); EXPECT_FALSE(block.IsConstForm()); EXPECT_TRUE(block.IsDenseForm()); EXPECT_TRUE(block.IsFullForm()); for (int i = 0; i < buffer.size(); ++i) { EXPECT_EQ(block[i], buffer[i]); } } } TEST(ArrayTest, Sparse) { IdFilter id_filter(8, CreateBuffer<int64_t>({101, 104, 105, 106}), 100); auto dense_data = CreateDenseArray<int>({2, 3, std::nullopt, 7}); Array<int> block(8, id_filter, dense_data, -1); EXPECT_EQ(block.size(), 8); EXPECT_EQ(block.id_filter().type(), IdFilter::kPartial); EXPECT_FALSE(block.IsConstForm()); EXPECT_FALSE(block.IsDenseForm()); EXPECT_TRUE(block.IsSparseForm()); EXPECT_TRUE(block.HasMissingIdValue()); EXPECT_THAT(block, ElementsAre(-1, 2, -1, -1, 3, std::nullopt, 7, -1)); } TEST(ArrayTest, SparseArrayBuilder) { SparseArrayBuilder<int> bldr(8, 4); bldr.Add(1, 2); bldr.AddId(4); bldr.Add(5, OptionalValue<int>()); bldr.Add(6, 7); bldr.SetByOffset(1, 3); Array<int> res = std::move(bldr).Build(); EXPECT_EQ(res.size(), 8); EXPECT_TRUE(res.IsSparseForm()); EXPECT_THAT(res, ElementsAre(std::nullopt, 2, std::nullopt, std::nullopt, 3, std::nullopt, 7, std::nullopt)); } TEST(ArrayTest, CreateFromIdsAndValues) { constexpr auto NA = std::nullopt; { auto array = CreateArray<int>(10, {1, 4}, {3, 7}); EXPECT_TRUE(array.IsSparseForm()); EXPECT_THAT(array, ElementsAre(NA, 3, NA, NA, 7, NA, NA, NA, NA, NA)); } { auto array = CreateArray<int>(10, {1, 4, 5}, {3, 7, 0}); EXPECT_TRUE(array.IsDenseForm()); EXPECT_THAT(array, ElementsAre(NA, 3, NA, NA, 7, 0, NA, NA, NA, NA)); } { auto array = CreateArray<int, OptionalValue<int>>(10, {1, 4, 5}, {3, NA, 0}); EXPECT_TRUE(array.IsDenseForm()); EXPECT_THAT(array, ElementsAre(NA, 3, NA, NA, NA, 0, NA, NA, NA, NA)); } } TEST(ArrayTest, ForEach) { struct V { bool repeated; int64_t id; int64_t count; OptionalValue<int64_t> value; bool operator==(const V& v) const { return repeated == v.repeated && id == v.id && count == v.count && value == v.value; } }; std::vector<V> res; auto fn = [&res](int64_t id, bool present, int64_t v) { res.push_back({false, id, 1, {present, v}}); }; auto repeated_fn = [&res](int64_t id, int64_t count, bool present, int64_t v) { res.push_back({true, id, count, {present, v}}); }; { res.clear(); Array<int64_t> block(10, std::nullopt); block.ForEach(fn, repeated_fn); EXPECT_THAT(res, ElementsAre(V{true, 0, 10, std::nullopt})); } { res.clear(); Array<int64_t> block(10, 5); block.ForEach(fn, repeated_fn); EXPECT_THAT(res, ElementsAre(V{true, 0, 10, 5})); } { res.clear(); auto block = CreateArray<int64_t>({2, 1, std::nullopt, std::nullopt, 3}); block.ForEach(fn, repeated_fn); EXPECT_THAT(res, ElementsAre(V{false, 0, 1, 2}, V{false, 1, 1, 1}, V{false, 2, 1, {}}, V{false, 3, 1, {}}, V{false, 4, 1, 3})); } { res.clear(); auto block = CreateArray<int64_t>({2, 1, std::nullopt, std::nullopt, 3}) .ToSparseForm(); block.ForEach(fn, repeated_fn); EXPECT_THAT(res, ElementsAre(V{false, 0, 1, 2}, V{false, 1, 1, 1}, V{true, 2, 2, {}}, V{false, 4, 1, 3})); } { res.clear(); auto block = CreateArray<int64_t>({2, 1, 4, 4, 3, 4}).ToSparseForm(4); block.ForEach(fn, repeated_fn); EXPECT_THAT(res, ElementsAre(V{false, 0, 1, 2}, V{false, 1, 1, 1}, V{true, 2, 2, 4}, V{false, 4, 1, 3}, V{true, 5, 1, 4})); } { res.clear(); auto block = CreateArray<int64_t>({2, 1, 4, 4, 3, 4}).ToSparseForm(4); block.ForEach(fn); EXPECT_THAT(res, ElementsAre(V{false, 0, 1, 2}, V{false, 1, 1, 1}, V{false, 2, 1, 4}, V{false, 3, 1, 4}, V{false, 4, 1, 3}, V{false, 5, 1, 4})); } } TEST(ArrayTest, ForEachPresent) { struct V { bool repeated; int64_t id, count, value; bool operator==(const V& v) const { return repeated == v.repeated && id == v.id && count == v.count && value == v.value; } }; std::vector<V> res; auto fn = [&res](int64_t id, int64_t v) { res.push_back({false, id, 1, v}); }; auto repeated_fn = [&res](int64_t id, int64_t count, int64_t v) { res.push_back({true, id, count, v}); }; { res.clear(); Array<int64_t> block(10, std::nullopt); block.ForEachPresent(fn, repeated_fn); EXPECT_THAT(res, ElementsAre()); } { res.clear(); Array<int64_t> block(10, 5); block.ForEachPresent(fn, repeated_fn); EXPECT_THAT(res, ElementsAre(V{true, 0, 10, 5})); } { res.clear(); auto block = CreateArray<int64_t>({2, 1, std::nullopt, std::nullopt, 3}); block.ForEachPresent(fn, repeated_fn); EXPECT_THAT(res, ElementsAre(V{false, 0, 1, 2}, V{false, 1, 1, 1}, V{false, 4, 1, 3})); } { res.clear(); auto block = CreateArray<int64_t>({2, 1, std::nullopt, std::nullopt, 3}) .ToSparseForm(); block.ForEachPresent(fn, repeated_fn); EXPECT_THAT(res, ElementsAre(V{false, 0, 1, 2}, V{false, 1, 1, 1}, V{false, 4, 1, 3})); } { res.clear(); auto block = CreateArray<int64_t>({2, 1, 4, 4, 3, 4}).ToSparseForm(4); block.ForEachPresent(fn, repeated_fn); EXPECT_THAT( res, ElementsAre(V{false, 0, 1, 2}, V{false, 1, 1, 1}, V{true, 2, 2, 4}, V{false, 4, 1, 3}, V{true, 5, 1, 4})); } { res.clear(); auto block = CreateArray<int64_t>({2, 1, 4, 4, 3, 4}).ToSparseForm(4); block.ForEachPresent(fn); EXPECT_THAT(res, ElementsAre(V{false, 0, 1, 2}, V{false, 1, 1, 1}, V{false, 2, 1, 4}, V{false, 3, 1, 4}, V{false, 4, 1, 3}, V{false, 5, 1, 4})); } } TEST(ArrayTest, WithIds_Empty) { { Array<int> original_block(10, std::nullopt); IdFilter filter(10, CreateBuffer<int64_t>({101, 104, 105, 106}), 100); auto block = original_block.WithIds(filter, 0); EXPECT_TRUE(block.id_filter().IsSame(filter)); EXPECT_THAT(block, ElementsAre(0, std::nullopt, 0, 0, std::nullopt, std::nullopt, std::nullopt, 0, 0, 0)); } { Array<int> original_block(10, 1); auto block = original_block.WithIds({IdFilter::kFull}, 0); EXPECT_TRUE(block.IsDenseForm()); EXPECT_THAT(block, ElementsAre(1, 1, 1, 1, 1, 1, 1, 1, 1, 1)); } } TEST(ArrayTest, WithIds_Sparse) { IdFilter original_filter(8, CreateBuffer<int64_t>({101, 104, 105, 106}), 100); auto original_data = CreateDenseArray<int>({2, 3, std::nullopt, 7}); Array<int> original_block(8, original_filter, original_data, -1); { auto block = original_block.WithIds({IdFilter::kEmpty}, std::nullopt); EXPECT_EQ(block.size(), original_block.size()); EXPECT_TRUE(block.IsAllMissingForm()); } { auto block = original_block.WithIds(original_block.id_filter(), 0); EXPECT_EQ(block.size(), original_block.size()); EXPECT_EQ(block.dense_data().values.begin(), original_block.dense_data().values.begin()); EXPECT_EQ(block.dense_data().bitmap.begin(), original_block.dense_data().bitmap.begin()); EXPECT_THAT(block, ElementsAre(0, 2, 0, 0, 3, std::nullopt, 7, 0)); } { IdFilter new_ids(8, CreateBuffer<int64_t>({10, 11, 12, 16}), 10); auto block = original_block.WithIds(new_ids, std::nullopt); EXPECT_THAT(block, ElementsAre(-1, 2, -1, std::nullopt, std::nullopt, std::nullopt, 7, std::nullopt)); } } TEST(ArrayTest, WithIds_Dense) { IdFilter filter(8, CreateBuffer<int64_t>({101, 104, 105, 106}), 100); { Array<int> original_block = CreateArray<int>({1, 2, 3, 4, std::nullopt, 6, 7, 8}); auto block = original_block.WithIds(filter, 0); EXPECT_TRUE(block.id_filter().IsSame(filter)); EXPECT_THAT(block, ElementsAre(0, 2, 0, 0, std::nullopt, 6, 7, 0)); } { DenseArray<int> array{CreateBuffer<int>({1, 2, 3, 4, 5, 6, 7, 8})}; Array<int> original_block(array); auto block = original_block.WithIds(filter, 0); EXPECT_TRUE(block.id_filter().IsSame(filter)); EXPECT_THAT(block, ElementsAre(0, 2, 0, 0, 5, 6, 7, 0)); } } TEST(ArrayTest, WithIds_Strings) { IdFilter original_filter(8, CreateBuffer<int64_t>({101, 104, 105, 106}), 100); IdFilter new_filter(8, CreateBuffer<int64_t>({10, 11, 12, 16}), 10); auto original_data = CreateDenseArray<Bytes>( {Bytes("22"), Bytes("333"), std::nullopt, Bytes("7")}); using V = absl::string_view; { Array<Bytes> original_block(8, original_filter, original_data); auto block = original_block.WithIds(new_filter, std::nullopt); EXPECT_EQ(block.dense_data().values.characters().begin(), original_data.values.characters().begin()); EXPECT_THAT(block, ElementsAre(std::nullopt, V("22"), std::nullopt, std::nullopt, std::nullopt, std::nullopt, V("7"), std::nullopt)); } { Array<Bytes> original_block(8, original_filter, original_data, Bytes("")); auto block = original_block.WithIds(new_filter, std::nullopt); EXPECT_EQ(block.dense_data().values.characters().begin(), original_data.values.characters().begin()); EXPECT_THAT(block, ElementsAre(V(""), V("22"), V(""), std::nullopt, std::nullopt, std::nullopt, V("7"), std::nullopt)); } { Array<Bytes> original_block(8, original_filter, original_data, Bytes("abc")); auto block = original_block.WithIds(new_filter, std::nullopt); EXPECT_NE(block.dense_data().values.characters().begin(), original_data.values.characters().begin()); EXPECT_THAT(block, ElementsAre(V("abc"), V("22"), V("abc"), std::nullopt, std::nullopt, std::nullopt, V("7"), std::nullopt)); } } TEST(ArrayTest, ToSparseForm_FromEmpty) { Array<int> block(5, 1); { auto res = block.ToSparseForm(); EXPECT_TRUE(res.IsFullForm()); EXPECT_THAT(res, ElementsAre(1, 1, 1, 1, 1)); } { auto res = block.ToSparseForm(2); EXPECT_TRUE(res.IsFullForm()); EXPECT_THAT(res, ElementsAre(1, 1, 1, 1, 1)); } { auto res = block.ToSparseForm(1); EXPECT_TRUE(res.IsConstForm()); EXPECT_THAT(res, ElementsAre(1, 1, 1, 1, 1)); } } TEST(ArrayTest, ToSparseForm_FromDense) { Array<int> block = CreateArray<int>({1, 2, 3, std::nullopt, 2, std::nullopt, 2}); { auto res = block.ToSparseForm(); EXPECT_THAT(res.id_filter().ids(), ElementsAre(0, 1, 2, 4, 6)); EXPECT_THAT(res.dense_data(), ElementsAre(1, 2, 3, 2, 2)); EXPECT_TRUE(res.dense_data().bitmap.empty()); } { auto res = block.ToSparseForm(2); EXPECT_THAT(res.id_filter().ids(), ElementsAre(0, 2, 3, 5)); EXPECT_THAT(res.dense_data(), ElementsAre(1, 3, std::nullopt, std::nullopt)); } { Array<int> block2 = CreateArray<int>({1, 2, 3, 4, 2, 5, 2}); auto res = block2.ToSparseForm(2); EXPECT_THAT(res.id_filter().ids(), ElementsAre(0, 2, 3, 5)); EXPECT_THAT(res.dense_data(), ElementsAre(1, 3, 4, 5)); } } TEST(ArrayTest, ToSparseForm_FromSparse) { IdFilter filter(8, CreateBuffer<int64_t>({101, 104, 105, 106}), 100); auto data = CreateDenseArray<int>({1, 2, 3, std::nullopt}); { DenseArray<int> d{CreateBuffer<int>({1, 2, 3, 4})}; Array<int> block(8, filter, d, std::nullopt); auto res = block.ToSparseForm(); EXPECT_TRUE(filter.IsSame(res.id_filter())); EXPECT_EQ(d.values.begin(), res.dense_data().values.begin()); EXPECT_TRUE(res.dense_data().bitmap.empty()); } { Array<int> block(8, filter, data); auto res = block.ToSparseForm(); EXPECT_THAT(res.id_filter().ids(), ElementsAre(1, 4, 5)); EXPECT_THAT(res.dense_data(), ElementsAre(1, 2, 3)); EXPECT_TRUE(res.dense_data().bitmap.empty()); } { Array<int> block(8, filter, data, 2); auto res = block.ToSparseForm(2); EXPECT_THAT(res.id_filter().ids(), ElementsAre(1, 5, 6)); EXPECT_THAT(res.dense_data(), ElementsAre(1, 3, std::nullopt)); } { auto data2 = CreateDenseArray<int>({1, 2, 3, 4}); Array<int> block(8, filter, data2, 2); auto res = block.ToSparseForm(2); EXPECT_THAT(res.id_filter().ids(), ElementsAre(1, 5, 6)); EXPECT_THAT(res.dense_data(), ElementsAre(1, 3, 4)); } { Array<int> block(8, filter, data, 4); auto res = block.ToSparseForm(); EXPECT_THAT(res.id_filter().ids(), ElementsAre(0, 1, 2, 3, 4, 5, 7)); EXPECT_THAT(res.dense_data(), ElementsAre(4, 1, 4, 4, 2, 3, 4)); EXPECT_TRUE(res.dense_data().bitmap.empty()); } { Array<int> block(8, filter, data); auto res = block.ToSparseForm(2); EXPECT_THAT(res.id_filter().ids(), ElementsAre(0, 1, 2, 3, 5, 6, 7)); EXPECT_THAT(res.dense_data(), ElementsAre(std::nullopt, 1, std::nullopt, std::nullopt, 3, std::nullopt, std::nullopt)); } { Array<int> block(8, filter, data, 3); auto res = block.ToSparseForm(2); EXPECT_THAT(res.id_filter().ids(), ElementsAre(0, 1, 2, 3, 5, 6, 7)); EXPECT_THAT(res.dense_data(), ElementsAre(3, 1, 3, 3, 3, std::nullopt, 3)); } } TEST(ArrayTest, MakeOwned) { std::vector<int> values{1, 2, 3, 4, 5}; std::vector<uint32_t> bitmap{0x15}; std::vector<int64_t> ids{0, 2, 3, 4, 5}; DenseArray<int> data{Buffer<int>(nullptr, values), Buffer<uint32_t>(nullptr, bitmap)}; Array<int> dense(data); Array<int> sparse(7, IdFilter(7, Buffer<int64_t>(nullptr, ids)), data); EXPECT_FALSE(dense.is_owned()); EXPECT_FALSE(sparse.is_owned()); dense = ArenaTraits<Array<int>>::MakeOwned(std::move(dense), GetHeapBufferFactory()); sparse = ArenaTraits<Array<int>>::MakeOwned(std::move(sparse), GetHeapBufferFactory()); EXPECT_TRUE(dense.is_owned()); EXPECT_THAT(dense, ElementsAre(1, std::nullopt, 3, std::nullopt, 5)); EXPECT_TRUE(sparse.is_owned()); EXPECT_THAT(sparse, ElementsAre(1, std::nullopt, std::nullopt, 3, std::nullopt, 5, std::nullopt)); } TEST(ArrayTest, Slice) { EXPECT_THAT(Array<int>(7, 3).Slice(2, 4), ElementsAre(3, 3, 3, 3)); EXPECT_THAT(CreateArray<int>({5, 4, 3, 2, 1}).Slice(1, 3), ElementsAre(4, 3, 2)); { auto array = CreateArray<int>({5, std::nullopt, 3, std::nullopt, 1}); array = array.ToSparseForm(); auto sliced = array.Slice(1, 3); EXPECT_EQ(sliced.dense_data().size(), 1); EXPECT_EQ(sliced.id_filter().type(), IdFilter::kPartial); EXPECT_EQ(sliced.id_filter().ids_offset(), 1); EXPECT_THAT(sliced, ElementsAre(std::nullopt, 3, std::nullopt)); } } TEST(ArrayTest, PresentCount) { auto block = CreateArray<int>({1, 2, 1, 3, std::nullopt, 2, std::nullopt}); EXPECT_EQ(block.PresentCount(), 5); EXPECT_EQ(block.ToSparseForm().PresentCount(), 5); EXPECT_EQ(block.ToSparseForm(1).PresentCount(), 5); EXPECT_EQ(Array<int>(10, std::nullopt).PresentCount(), 0); EXPECT_EQ(Array<int>(10, 0).PresentCount(), 10); } TEST(ArrayTest, ArraysAreEquivalent) { { Array<int32_t> array1; Array<int32_t> array2; EXPECT_TRUE(ArraysAreEquivalent(array1, array2)); } { auto array1 = CreateArray<int>({1, 2}); auto array2 = CreateArray<int>({1}); EXPECT_FALSE(ArraysAreEquivalent(array1, array2)); } { auto array1 = Array<int32_t>(3, 1); auto array2 = Array<int32_t>(3, 1); ASSERT_TRUE(array1.IsConstForm()); EXPECT_TRUE(ArraysAreEquivalent(array1, array2)); auto array3 = Array<int32_t>(3, 0); EXPECT_FALSE(ArraysAreEquivalent(array1, array3)); } { Array<int32_t> array1 = CreateArray<int32_t>({2, 3, std::nullopt, 7}); Array<int32_t> array2 = CreateArray<int32_t>({2, 3, std::nullopt, 7}); ASSERT_TRUE(array1.IsDenseForm()); EXPECT_TRUE(ArraysAreEquivalent(array1, array2)); Array<int32_t> array3 = CreateArray<int32_t>({3, 4, std::nullopt, 1}); EXPECT_FALSE(ArraysAreEquivalent(array1, array3)); } { IdFilter id_filter(8, CreateBuffer<int64_t>({101, 104, 105, 106}), 100); auto dense_data = CreateDenseArray<int32_t>({2, 3, std::nullopt, 7}); Array<int32_t> array1(8, id_filter, dense_data, -1); Array<int32_t> array2(8, id_filter, dense_data, -1); ASSERT_TRUE(array1.IsSparseForm() && !array1.IsDenseForm() && !array1.IsConstForm()); EXPECT_TRUE(ArraysAreEquivalent(array1, array2)); auto dense_data2 = CreateDenseArray<int32_t>({3, 4, std::nullopt, 1}); Array<int32_t> array3(8, id_filter, dense_data2, -1); EXPECT_FALSE(ArraysAreEquivalent(array1, array3)); } } } }
2,382
cpp
google/arolla
id_filter
arolla/array/id_filter.cc
arolla/array/id_filter_test.cc
#ifndef AROLLA_ARRAY_ID_FILTER_H_ #define AROLLA_ARRAY_ID_FILTER_H_ #include <algorithm> #include <cstdint> #include <iterator> #include <utility> #include "absl/base/attributes.h" #include "absl/log/check.h" #include "absl/types/span.h" #include "arolla/memory/buffer.h" #include "arolla/memory/optional_value.h" #include "arolla/memory/raw_buffer_factory.h" #include "arolla/util/fingerprint.h" namespace arolla { class IdFilter { public: using IdWithOffset = int64_t; enum Type { kEmpty, kPartial, kFull }; static constexpr double kDenseSparsityLimit = 0.25; IdFilter(Type type) : type_(type) { DCHECK_NE(type, kPartial); } explicit IdFilter(int64_t size, Buffer<IdWithOffset> ids, int64_t ids_offset = 0) : type_(kPartial), ids_(std::move(ids)), ids_offset_(ids_offset) { if (ids.empty()) { type_ = kEmpty; ids_offset_ = 0; } else if (ids.size() == size) { type_ = kFull; ids_ = Buffer<IdWithOffset>(); ids_offset_ = 0; } else { DCHECK_GE(ids.front(), ids_offset); #ifndef NDEBUG for (int64_t i = 1; i < ids.size(); ++i) { DCHECK_LT(ids[i - 1], ids[i]); } #endif DCHECK_LT(ids.back(), ids_offset + size); } } OptionalValue<int64_t> IdToOffset(int64_t id) const { switch (type_) { case kFull: return id; case kPartial: { auto iter = std::lower_bound(ids_.begin(), ids_.end(), id + ids_offset_); int64_t offset = std::distance(ids_.begin(), iter); bool present = iter != ids_.end() && ids_[offset] == id + ids_offset_; return {present, offset}; } case kEmpty: default: return {}; } } int64_t IdsOffsetToId(int64_t offset) const { DCHECK_EQ(type_, kPartial); DCHECK_GE(offset, 0); DCHECK_LT(offset, ids_.size()); return ids_[offset] - ids_offset_; } bool IsSame(const IdFilter& other) const { if (type_ != other.type_) return false; if (type_ == kPartial) { return ids_.begin() == other.ids_.begin() && ids_.end() == other.ids_.end() && ids_offset_ == other.ids_offset_; } else { return true; } } Type type() const { return type_; } const Buffer<IdWithOffset>& ids() const { DCHECK_NE(type_, kFull) << "Requesting ids on full filter is error prone. Ids are empty, which " "can be used incorrectly."; return ids_; } int64_t ids_offset() const { return ids_offset_; } template <class Id1, class Id2, class Fn> static void ForEachCommonId(absl::Span<const Id1> f1, Id1 ids_offset1, absl::Span<const Id2> f2, Id2 ids_offset2, Fn&& fn); template <class Fn> static void IntersectPartial_ForEach(const IdFilter& f1, const IdFilter& f2, Fn&& fn) { DCHECK_EQ(f1.type_, kPartial); DCHECK_EQ(f2.type_, kPartial); ForEachCommonId(f1.ids_.span(), f1.ids_offset_, f2.ids_.span(), f2.ids_offset_, std::forward<Fn>(fn)); } template <class... IdFilters> static IdFilter UpperBoundMerge(int64_t size, RawBufferFactory* buf_factory, const IdFilter& f, const IdFilters&... fs); template <class... IdFilters> static const IdFilter& UpperBoundIntersect(const IdFilter& f, const IdFilters&... fs); private: static IdFilter UpperBoundMergeImpl(int64_t size, RawBufferFactory* buf_factory, const IdFilter& a, const IdFilter& b); static const IdFilter& UpperBoundIntersectImpl(const IdFilter& a, const IdFilter& b); Type type_; Buffer<IdWithOffset> ids_; int64_t ids_offset_ = 0; }; template <class Id1, class Id2, class Fn> ABSL_ATTRIBUTE_ALWAYS_INLINE inline void IdFilter::ForEachCommonId( absl::Span<const Id1> f1, Id1 ids_offset1, absl::Span<const Id2> f2, Id2 ids_offset2, Fn&& fn) { DCHECK(!f1.empty()); DCHECK(!f2.empty()); auto iter1 = f1.begin(); auto iter2 = f2.begin(); int64_t id1 = *iter1 - ids_offset1; int64_t id2 = *iter2 - ids_offset2; int64_t max_id = std::min<int64_t>(f1.back() - ids_offset1, f2.back() - ids_offset2); while (id1 < max_id && id2 < max_id) { if (id1 == id2) { fn(id1, iter1 - f1.begin(), iter2 - f2.begin()); id1 = *(++iter1) - ids_offset1; id2 = *(++iter2) - ids_offset2; } while (id1 < std::min(max_id, id2)) { id1 = *(++iter1) - ids_offset1; } if (id2 < std::min(max_id, id1)) { id2 = *(++iter2) - ids_offset2; } } while (id1 < max_id) { id1 = *(++iter1) - ids_offset1; } while (id2 < max_id) { id2 = *(++iter2) - ids_offset2; } if (id1 == id2) { fn(id1, iter1 - f1.begin(), iter2 - f2.begin()); } } template <class... IdFilters> IdFilter IdFilter::UpperBoundMerge( int64_t size ABSL_ATTRIBUTE_UNUSED, RawBufferFactory* buf_factory ABSL_ATTRIBUTE_UNUSED, const IdFilter& f, const IdFilters&... fs) { if constexpr (sizeof...(fs) == 0) { return f; } else { return UpperBoundMergeImpl(size, buf_factory, f, UpperBoundMerge(size, buf_factory, fs...)); } } template <class... IdFilters> const IdFilter& IdFilter::UpperBoundIntersect(const IdFilter& f, const IdFilters&... fs) { if constexpr (sizeof...(fs) == 0) { return f; } else { return UpperBoundIntersectImpl(f, UpperBoundIntersect(fs...)); } } inline const IdFilter& IdFilter::UpperBoundIntersectImpl(const IdFilter& a, const IdFilter& b) { if (a.type() == kEmpty || b.type() == kFull) return a; if (b.type() == kEmpty || a.type() == kFull) return b; return a.ids().size() < b.ids().size() ? a : b; } AROLLA_DECLARE_FINGERPRINT_HASHER_TRAITS(IdFilter); } #endif #include "arolla/array/id_filter.h" #include <algorithm> #include <cstdint> #include <utility> #include "arolla/memory/buffer.h" #include "arolla/memory/raw_buffer_factory.h" #include "arolla/util/fingerprint.h" namespace arolla { IdFilter IdFilter::UpperBoundMergeImpl(int64_t size, RawBufferFactory* buf_factory, const IdFilter& a, const IdFilter& b) { if (a.type() == kEmpty || b.type() == kFull) return b; if (b.type() == kEmpty || a.type() == kFull) return a; if (a.IsSame(b)) return a; if (std::max(a.ids().size(), b.ids().size()) >= size * kDenseSparsityLimit) { return kFull; } Buffer<int64_t>::Builder bldr(a.ids().size() + b.ids().size(), buf_factory); auto inserter = bldr.GetInserter(); auto ia = a.ids().begin(); auto ib = b.ids().begin(); while (ia != a.ids().end() && ib != b.ids().end()) { int64_t va = *ia - a.ids_offset(); int64_t vb = *ib - b.ids_offset(); int64_t v = std::min(va, vb); if (va == v) ia++; if (vb == v) ib++; inserter.Add(v); } while (ia != a.ids().end()) inserter.Add(*(ia++) - a.ids_offset()); while (ib != b.ids().end()) inserter.Add(*(ib++) - b.ids_offset()); return IdFilter(size, std::move(bldr).Build(inserter)); } void FingerprintHasherTraits<IdFilter>::operator()( FingerprintHasher* hasher, const IdFilter& value) const { hasher->Combine(value.type()); if (value.type() != IdFilter::Type::kFull) { hasher->Combine(value.ids()); } } }
#include "arolla/array/id_filter.h" #include <cstdint> #include <tuple> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "arolla/memory/buffer.h" #include "arolla/memory/raw_buffer_factory.h" namespace arolla { namespace { TEST(IdFilterTest, UpperBoundIntersect) { IdFilter empty(IdFilter::kEmpty); IdFilter full(IdFilter::kFull); IdFilter a = IdFilter(5, CreateBuffer<int64_t>({3, 4})); IdFilter b = IdFilter(5, CreateBuffer<int64_t>({0, 2, 3})); IdFilter c = IdFilter(5, CreateBuffer<int64_t>({0, 1, 3, 4})); EXPECT_TRUE(IdFilter::UpperBoundIntersect(a).IsSame(a)); EXPECT_TRUE(IdFilter::UpperBoundIntersect(a, empty).IsSame(empty)); EXPECT_TRUE(IdFilter::UpperBoundIntersect(empty, a).IsSame(empty)); EXPECT_TRUE(IdFilter::UpperBoundIntersect(a, full).IsSame(a)); EXPECT_TRUE(IdFilter::UpperBoundIntersect(full, a).IsSame(a)); EXPECT_TRUE(IdFilter::UpperBoundIntersect(a, b).IsSame(a)); EXPECT_TRUE(IdFilter::UpperBoundIntersect(b, a).IsSame(a)); EXPECT_TRUE(IdFilter::UpperBoundIntersect(a, b, c).IsSame(a)); EXPECT_TRUE(IdFilter::UpperBoundIntersect(c, b, a).IsSame(a)); EXPECT_TRUE(IdFilter::UpperBoundIntersect(a, empty, c).IsSame(empty)); EXPECT_TRUE(IdFilter::UpperBoundIntersect(full, b, c).IsSame(b)); } TEST(IdFilterTest, UpperBoundMerge) { IdFilter empty(IdFilter::kEmpty); IdFilter full(IdFilter::kFull); IdFilter a = IdFilter(5, CreateBuffer<int64_t>({3, 4})); IdFilter b = IdFilter(5, CreateBuffer<int64_t>({0, 2, 3})); RawBufferFactory* bf = GetHeapBufferFactory(); EXPECT_TRUE(IdFilter::UpperBoundMerge(5, bf, a).IsSame(a)); EXPECT_TRUE(IdFilter::UpperBoundMerge(5, bf, a, empty).IsSame(a)); EXPECT_TRUE(IdFilter::UpperBoundMerge(5, bf, empty, a).IsSame(a)); EXPECT_TRUE(IdFilter::UpperBoundMerge(25, bf, a, full).IsSame(full)); EXPECT_TRUE(IdFilter::UpperBoundMerge(25, bf, a, full, b).IsSame(full)); EXPECT_TRUE(IdFilter::UpperBoundMerge(5, bf, a, b).IsSame(full)); EXPECT_THAT(IdFilter::UpperBoundMerge(25, bf, a, b).ids(), testing::ElementsAre(0, 2, 3, 4)); } TEST(IdFilterTest, IntersectPartial_ForEach) { IdFilter a = IdFilter(5, CreateBuffer<int64_t>({3, 4})); IdFilter b = IdFilter(5, CreateBuffer<int64_t>({0, 2, 3})); IdFilter c = IdFilter(5, CreateBuffer<int64_t>({0, 1, 3, 4})); using FnArgs = std::tuple<int64_t, int64_t, int64_t>; std::vector<FnArgs> res; auto fn = [&](int64_t id, int64_t offset1, int64_t offset2) { res.push_back({id, offset1, offset2}); }; IdFilter::IntersectPartial_ForEach(a, b, fn); EXPECT_EQ(res, (std::vector<FnArgs>{{3, 0, 2}})); res.clear(); IdFilter::IntersectPartial_ForEach(b, a, fn); EXPECT_EQ(res, (std::vector<FnArgs>{{3, 2, 0}})); res.clear(); IdFilter::IntersectPartial_ForEach(a, c, fn); EXPECT_EQ(res, (std::vector<FnArgs>{{3, 0, 2}, {4, 1, 3}})); res.clear(); IdFilter::IntersectPartial_ForEach(c, a, fn); EXPECT_EQ(res, (std::vector<FnArgs>{{3, 2, 0}, {4, 3, 1}})); res.clear(); IdFilter::IntersectPartial_ForEach(b, c, fn); EXPECT_EQ(res, (std::vector<FnArgs>{{0, 0, 0}, {3, 2, 2}})); res.clear(); IdFilter::IntersectPartial_ForEach(c, b, fn); EXPECT_EQ(res, (std::vector<FnArgs>{{0, 0, 0}, {3, 2, 2}})); res.clear(); } } }
2,383
cpp
google/arolla
array_util
arolla/array/array_util.cc
arolla/array/array_util_test.cc
#ifndef AROLLA_ARRAY_ARRAY_UTIL_H_ #define AROLLA_ARRAY_ARRAY_UTIL_H_ #include <cstdint> #include <utility> #include <vector> #include "absl/base/attributes.h" #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/types/span.h" #include "arolla/array/array.h" #include "arolla/array/id_filter.h" #include "arolla/dense_array/bitmap.h" #include "arolla/dense_array/dense_array.h" #include "arolla/memory/buffer.h" #include "arolla/memory/optional_value.h" #include "arolla/util/unit.h" namespace arolla { template <typename T> Array<Unit> ToArrayMask(const Array<T>& array) { DenseArray<Unit> dense{VoidBuffer(array.dense_data().size()), array.dense_data().bitmap, array.dense_data().bitmap_bit_offset}; return Array<Unit>(array.size(), array.id_filter(), std::move(dense), OptionalUnit(array.missing_id_value().present)); } template <typename T> DenseArray<T> ToDenseArray(const Array<T>& array) { return array.ToDenseForm().dense_data().ForceNoBitmapBitOffset(); } template <typename T> absl::StatusOr<Buffer<T>> ToBuffer(const Array<T>& array) { DenseArray<T> dense_array = array.ToDenseForm().dense_data(); if (dense_array.IsFull()) { return dense_array.values; } else { return absl::InvalidArgumentError( "Array with missing values can not be converted to a Buffer"); } } std::vector<int64_t> ArrayFirstPresentIds(const Array<Unit>& array, int64_t max_count); std::vector<int64_t> ArrayLastPresentIds(const Array<Unit>& array, int64_t max_count); namespace array_foreach_in_subset_impl { template <class T, class IdT, class Fn> ABSL_ATTRIBUTE_NOINLINE void SparseArrayForEachInSubset( const Array<T>& a, absl::Span<const IdT> subset, int64_t subset_ids_offset, Fn&& fn) { const Buffer<T>& values = a.dense_data().values; const IdFilter& f = a.id_filter(); auto array_it = f.ids().begin(); auto subset_it = subset.begin(); while (subset_it != subset.end() && array_it != f.ids().end()) { int64_t id_in_subset = *subset_it - subset_ids_offset; int64_t id_in_array = *array_it - f.ids_offset(); if (id_in_array == id_in_subset) { int64_t offset = array_it - f.ids().begin(); fn(id_in_subset, a.dense_data().present(offset), values[offset]); array_it++; subset_it++; } else if (id_in_array < id_in_subset) { array_it++; } else { fn(id_in_subset, a.missing_id_value().present, a.missing_id_value().value); subset_it++; } } for (; subset_it != subset.end(); ++subset_it) { int64_t id_in_subset = *subset_it - subset_ids_offset; fn(id_in_subset, a.missing_id_value().present, a.missing_id_value().value); } } } template <class T, class IdT, class Fn> void ArrayForEachInSubset(const Array<T>& a, absl::Span<const IdT> subset, int64_t subset_ids_offset, Fn&& fn) { if (a.IsConstForm()) { for (IdT s : subset) { fn(s - subset_ids_offset, a.missing_id_value().present, a.missing_id_value().value); } } else if (a.IsFullForm()) { const Buffer<T>& values = a.dense_data().values; for (IdT s : subset) { DCHECK(0 <= s - subset_ids_offset && s - subset_ids_offset < values.size()); int64_t id = std::clamp<int64_t>(s - subset_ids_offset, 0, values.size() - 1); fn(id, true, values[id]); } } else if (a.IsDenseForm()) { const Buffer<T>& values = a.dense_data().values; DCHECK_GE( a.dense_data().bitmap.size(), bitmap::BitmapSize(values.size() + a.dense_data().bitmap_bit_offset)); const bitmap::Word* presence = a.dense_data().bitmap.begin(); for (IdT s : subset) { DCHECK(0 <= s - subset_ids_offset && s - subset_ids_offset < values.size()); int64_t id = std::clamp<int64_t>(s - subset_ids_offset, 0, values.size() - 1); fn(id, bitmap::GetBit(presence, id + a.dense_data().bitmap_bit_offset), values[id]); } } else { array_foreach_in_subset_impl::SparseArrayForEachInSubset( a, subset, subset_ids_offset, std::forward<Fn>(fn)); } } } #endif #include "arolla/array/array_util.h" #include <cstdint> #include <vector> #include "arolla/array/array.h" #include "arolla/util/unit.h" namespace arolla { std::vector<int64_t> ArrayFirstPresentIds(const Array<Unit>& array, int64_t max_count) { std::vector<int64_t> res; if (max_count <= 0) { return res; } res.reserve(max_count); if (array.IsDenseForm() || array.HasMissingIdValue()) { int64_t index = 0; while (index < array.size() && res.size() < max_count) { if (array[index].present) res.push_back(index); index++; } } else { int64_t offset = 0; while (offset < array.dense_data().size() && res.size() < max_count) { if (array.dense_data().present(offset)) { res.push_back(array.id_filter().IdsOffsetToId(offset)); } offset++; } } return res; } std::vector<int64_t> ArrayLastPresentIds(const Array<Unit>& array, int64_t max_count) { std::vector<int64_t> res; if (max_count <= 0) { return res; } res.reserve(max_count); if (array.IsDenseForm() || array.HasMissingIdValue()) { int64_t index = array.size() - 1; while (index >= 0 && res.size() < max_count) { if (array[index].present) res.push_back(index); index--; } } else { int64_t offset = array.dense_data().size() - 1; while (offset >= 0 && res.size() < max_count) { if (array.dense_data().present(offset)) { res.push_back(array.id_filter().IdsOffsetToId(offset)); } offset--; } } return res; } }
#include "arolla/array/array_util.h" #include <cstdint> #include <optional> #include <utility> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "absl/types/span.h" #include "arolla/array/array.h" #include "arolla/dense_array/dense_array.h" #include "arolla/memory/optional_value.h" #include "arolla/util/testing/status_matchers_backport.h" #include "arolla/util/unit.h" using ::testing::ElementsAre; namespace arolla::testing { TEST(ArrayUtilTest, ToArrayMask) { Array<int> array = CreateArray<int>({1, 2, 3, std::nullopt, 1, 1, std::nullopt, 2}) .ToSparseForm(1); array = array.Slice(1, 7); Array<Unit> mask = ToArrayMask(array); EXPECT_THAT(mask, ElementsAre(kUnit, kUnit, std::nullopt, kUnit, kUnit, std::nullopt, kUnit)); } TEST(ArrayUtilTest, ToDenseArray) { Array<int> array = CreateArray<int>({1, 2, 3, std::nullopt, 1, 1, std::nullopt, 2}) .ToSparseForm(1); array = array.Slice(1, 7); DenseArray<int> dense_array = ToDenseArray(array); EXPECT_THAT(dense_array, ElementsAre(2, 3, std::nullopt, 1, 1, std::nullopt, 2)); } TEST(ArrayUtilTest, ToBuffer) { EXPECT_THAT( ToBuffer(CreateArray<int>({1, 2, std::nullopt})), StatusIs( absl::StatusCode::kInvalidArgument, ::testing::HasSubstr( "Array with missing values can not be converted to a Buffer"))); EXPECT_THAT(ToBuffer(CreateArray<int>({1, 2, 3})), IsOkAndHolds(ElementsAre(1, 2, 3))); } TEST(ArrayUtilTest, FirstAndLastPresentIds) { { Array<Unit> array(5, std::nullopt); EXPECT_THAT(ArrayFirstPresentIds(array, 3), ElementsAre()); EXPECT_THAT(ArrayLastPresentIds(array, 3), ElementsAre()); } { Array<Unit> array(5, kUnit); EXPECT_THAT(ArrayFirstPresentIds(array, 3), ElementsAre(0, 1, 2)); EXPECT_THAT(ArrayLastPresentIds(array, 3), ElementsAre(4, 3, 2)); EXPECT_THAT(ArrayFirstPresentIds(array, 10), ElementsAre(0, 1, 2, 3, 4)); EXPECT_THAT(ArrayLastPresentIds(array, 10), ElementsAre(4, 3, 2, 1, 0)); } { Array<Unit> array = CreateArray<Unit>({kUnit, kUnit, kUnit}); EXPECT_THAT(ArrayFirstPresentIds(array, 2), ElementsAre(0, 1)); EXPECT_THAT(ArrayLastPresentIds(array, 2), ElementsAre(2, 1)); } { Array<Unit> array = CreateArray<Unit>({kUnit, std::nullopt, kUnit}); EXPECT_THAT(ArrayFirstPresentIds(array, 2), ElementsAre(0, 2)); EXPECT_THAT(ArrayLastPresentIds(array, 2), ElementsAre(2, 0)); } { Array<Unit> array = CreateArray<Unit>({kUnit, std::nullopt, kUnit, std::nullopt, kUnit}) .ToSparseForm(); EXPECT_THAT(ArrayFirstPresentIds(array, 2), ElementsAre(0, 2)); EXPECT_THAT(ArrayLastPresentIds(array, 2), ElementsAre(4, 2)); } { Array<Unit> array = CreateArray<Unit>({kUnit, std::nullopt, kUnit, std::nullopt, kUnit}) .ToSparseForm(kUnit); EXPECT_THAT(ArrayFirstPresentIds(array, 2), ElementsAre(0, 2)); EXPECT_THAT(ArrayLastPresentIds(array, 2), ElementsAre(4, 2)); } { Array<Unit> array; EXPECT_THAT(ArrayFirstPresentIds(array, -1), ElementsAre()); EXPECT_THAT(ArrayLastPresentIds(array, -1), ElementsAre()); } } TEST(ArrayUtilTest, ArrayForEachInSubset) { using V = std::pair<int64_t, OptionalValue<float>>; std::vector<V> res; auto fn = [&res](int64_t id, bool present, float v) { res.push_back({id, {present, v}}); }; auto check = [&res](absl::Span<const V> expected) { ASSERT_EQ(res.size(), expected.size()); for (int i = 0; i < res.size(); ++i) { EXPECT_EQ(res[i].first, expected[i].first); EXPECT_EQ(res[i].second, expected[i].second); } res.clear(); }; { Array<float> array(5, std::nullopt); ArrayForEachInSubset<float, int>(array, {40, 41, 43}, 40, fn); check({{0, std::nullopt}, {1, std::nullopt}, {3, std::nullopt}}); } { Array<float> array(5, 7.0); ArrayForEachInSubset<float, int>(array, {40, 41, 43}, 40, fn); check({{0, 7.0}, {1, 7.0}, {3, 7.0}}); } { Array<float> array = CreateArray<float>({7.0, 8.0, 7.5, 8.5, 9.0}); ArrayForEachInSubset<float, int>(array, {40, 41, 43}, 40, fn); check({{0, 7.0}, {1, 8.0}, {3, 8.5}}); } { Array<float> array = CreateArray<float>({7.0, std::nullopt, std::nullopt, 8.5, 9.0}); ArrayForEachInSubset<float, int>(array, {40, 41, 43}, 40, fn); check({{0, 7.0}, {1, std::nullopt}, {3, 8.5}}); } { Array<float> array = CreateArray<float>({7.0, std::nullopt, std::nullopt, 8.5, 9.0}) .ToSparseForm(); ArrayForEachInSubset<float, int>(array, {40, 41, 43}, 40, fn); check({{0, 7.0}, {1, std::nullopt}, {3, 8.5}}); } { Array<float> array = CreateArray<float>({7.0, std::nullopt, std::nullopt, 8.5, 9.0}) .ToSparseForm(7.0); ArrayForEachInSubset<float, int>(array, {40, 41, 43}, 40, fn); check({{0, 7.0}, {1, std::nullopt}, {3, 8.5}}); } } }
2,384
cpp
google/arolla
decision_forest
arolla/decision_forest/decision_forest.cc
arolla/decision_forest/decision_forest_test.cc
#ifndef AROLLA_DECISION_FOREST_DECISION_FOREST_H_ #define AROLLA_DECISION_FOREST_DECISION_FOREST_H_ #include <cstdint> #include <memory> #include <string> #include <utility> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/container/flat_hash_set.h" #include "absl/log/check.h" #include "absl/status/statusor.h" #include "absl/types/span.h" #include "arolla/decision_forest/split_condition.h" #include "arolla/memory/frame.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/util/fingerprint.h" namespace arolla { class DecisionTreeNodeId { public: static DecisionTreeNodeId SplitNodeId(int64_t split_node_index) { DecisionTreeNodeId n; n.val_ = split_node_index; return n; } static DecisionTreeNodeId AdjustmentId(int64_t adjustment_index) { DecisionTreeNodeId n; n.val_ = -adjustment_index - 1; return n; } bool is_leaf() const { return val_ < 0; } int64_t split_node_index() const { DCHECK(!is_leaf()); return val_; } int64_t adjustment_index() const { DCHECK(is_leaf()); return -val_ - 1; } int64_t raw_index() const { return val_; } bool operator==(const DecisionTreeNodeId& other) const { return val_ == other.val_; } bool operator!=(const DecisionTreeNodeId& other) const { return val_ != other.val_; } private: int64_t val_ = 0; }; struct SplitNode { DecisionTreeNodeId child_if_false; DecisionTreeNodeId child_if_true; std::shared_ptr<const SplitCondition> condition; }; struct DecisionTree { std::vector<SplitNode> split_nodes; std::vector<float> adjustments; float weight = 1.0f; struct Tag { int step = 0; int submodel_id = 0; }; Tag tag; }; inline DecisionTreeNodeId GetTreeRootId(const DecisionTree& tree) { return tree.split_nodes.empty() ? DecisionTreeNodeId::AdjustmentId(0) : DecisionTreeNodeId::SplitNodeId(0); } struct TreeFilter { bool operator()(const DecisionTree::Tag& tree) const { return tree.step >= step_range_from && (step_range_to == -1 || tree.step < step_range_to) && (submodels.empty() || submodels.contains(tree.submodel_id)); } int step_range_from = 0; int step_range_to = -1; absl::flat_hash_set<int> submodels; }; class DecisionForest { public: static absl::StatusOr<std::unique_ptr<DecisionForest>> FromTrees( std::vector<DecisionTree>&& trees); absl::Status ValidateInputSlots( absl::Span<const TypedSlot> input_slots) const; const absl::flat_hash_map<int, QTypePtr>& GetRequiredQTypes() const { return required_qtypes_; } absl::Span<const DecisionTree> GetTrees() const { return trees_; } std::vector<DecisionTree> TreesCopy() const { return trees_; } int submodel_count() const { return submodel_count_; } int step_count() const { return step_count_; } Fingerprint fingerprint() const { return fingerprint_; } private: explicit DecisionForest(std::vector<DecisionTree>&& trees) : trees_(std::move(trees)) {} absl::Status Initialize(); std::vector<DecisionTree> trees_; absl::flat_hash_map<int, QTypePtr> required_qtypes_; Fingerprint fingerprint_; int submodel_count_; int step_count_; }; std::string ToDebugString(const DecisionTree& tree); std::string ToDebugString(const DecisionForest& forest); float DecisionForestNaiveEvaluation(const DecisionForest& forest, const ConstFramePtr ctx, absl::Span<const TypedSlot> inputs, const TreeFilter& filter = {}); using DecisionForestPtr = std::shared_ptr<const DecisionForest>; AROLLA_DECLARE_FINGERPRINT_HASHER_TRAITS(SplitNode); AROLLA_DECLARE_FINGERPRINT_HASHER_TRAITS(TreeFilter); AROLLA_DECLARE_FINGERPRINT_HASHER_TRAITS(DecisionForestPtr); AROLLA_DECLARE_QTYPE(DecisionForestPtr); AROLLA_DECLARE_QTYPE(TreeFilter); } #endif #include "arolla/decision_forest/decision_forest.h" #include <algorithm> #include <cstddef> #include <map> #include <memory> #include <string> #include <utility> #include <vector> #include "absl/algorithm/container.h" #include "absl/log/check.h" #include "absl/memory/memory.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" #include "absl/types/span.h" #include "arolla/memory/frame.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/simple_qtype.h" #include "arolla/util/fingerprint.h" #include "arolla/util/status_macros_backport.h" namespace arolla { using NodeId = DecisionTreeNodeId; float DecisionForestNaiveEvaluation(const DecisionForest& forest, const ConstFramePtr ctx, absl::Span<const TypedSlot> inputs, const TreeFilter& filter) { DCHECK_OK(forest.ValidateInputSlots(inputs)); double res = 0; for (const auto& tree : forest.GetTrees()) { if (!filter(tree.tag)) continue; NodeId node_id = GetTreeRootId(tree); while (!node_id.is_leaf()) { DCHECK(node_id.split_node_index() >= 0 && node_id.split_node_index() < tree.split_nodes.size()); const auto& node = tree.split_nodes[node_id.split_node_index()]; if (node.condition->EvaluateCondition(ctx, inputs)) { node_id = node.child_if_true; } else { node_id = node.child_if_false; } } DCHECK(node_id.adjustment_index() >= 0 && node_id.adjustment_index() < tree.adjustments.size()); res += tree.adjustments[node_id.adjustment_index()] * tree.weight; } return res; } namespace { std::string NodeIdToString(DecisionTreeNodeId id) { if (id.is_leaf()) { return absl::StrFormat("adjustments[%d]", id.adjustment_index()); } else { return absl::StrFormat("goto %d", id.split_node_index()); } } } std::string ToDebugString(const DecisionTree& tree) { std::string res = " DecisionTree {\n"; absl::StrAppendFormat(&res, " tag { step: %d submodel_id: %d }\n", tree.tag.step, tree.tag.submodel_id); absl::StrAppendFormat(&res, " weight: %f\n", tree.weight); absl::StrAppend(&res, " split_nodes {\n"); for (size_t i = 0; i < tree.split_nodes.size(); ++i) { const SplitNode& node = tree.split_nodes[i]; absl::StrAppendFormat(&res, " %d: IF %s THEN %s ELSE %s\n", i, node.condition->ToString(), NodeIdToString(node.child_if_true), NodeIdToString(node.child_if_false)); } absl::StrAppend(&res, " }\n"); absl::StrAppend(&res, " adjustments:"); for (float adj : tree.adjustments) { absl::StrAppendFormat(&res, " %f", adj); } absl::StrAppend(&res, "\n }"); return res; } std::string ToDebugString(const DecisionForest& forest) { std::string res = "DecisionForest {\n"; auto required_qtypes = forest.GetRequiredQTypes(); for (const auto& [k, v] : std::map<int, QTypePtr>(required_qtypes.begin(), required_qtypes.end())) { absl::StrAppendFormat(&res, " input #%d: %s\n", k, v->name()); } for (const auto& tree : forest.GetTrees()) { absl::StrAppend(&res, ToDebugString(tree), "\n"); } absl::StrAppend(&res, "}"); return res; } absl::StatusOr<std::unique_ptr<DecisionForest>> DecisionForest::FromTrees( std::vector<DecisionTree>&& trees) { auto forest = absl::WrapUnique(new DecisionForest(std::move(trees))); RETURN_IF_ERROR(forest->Initialize()); return forest; } absl::Status DecisionForest::ValidateInputSlots( absl::Span<const TypedSlot> input_slots) const { for (const auto& kv : required_qtypes_) { if (kv.first >= input_slots.size()) { return absl::InvalidArgumentError("not enough arguments"); } if (input_slots[kv.first].GetType() != kv.second) { return absl::InvalidArgumentError("type mismatch"); } } return absl::OkStatus(); } absl::Status DecisionForest::Initialize() { FingerprintHasher hasher("::arolla::DecisionForest"); hasher.Combine(trees_.size()); submodel_count_ = 0; step_count_ = 0; for (const auto& tree : trees_) { hasher.CombineSpan(tree.split_nodes) .CombineSpan(tree.adjustments) .Combine(tree.weight, tree.tag.step, tree.tag.submodel_id); if (tree.tag.submodel_id < 0) { return absl::InvalidArgumentError("submodel_id can not be negative"); } if (tree.tag.step < 0) { return absl::InvalidArgumentError("step can not be negative"); } submodel_count_ = std::max(submodel_count_, tree.tag.submodel_id + 1); step_count_ = std::max(step_count_, tree.tag.step + 1); if (tree.split_nodes.size() + 1 != tree.adjustments.size()) { return absl::InvalidArgumentError("incorrect number of regions"); } for (const auto& node : tree.split_nodes) { bool is_correct = true; DecisionTreeNodeId child = node.child_if_false; if (child.is_leaf()) { is_correct &= child.adjustment_index() < tree.adjustments.size(); } else { is_correct &= child.split_node_index() < tree.split_nodes.size(); } child = node.child_if_true; if (child.is_leaf()) { is_correct &= child.adjustment_index() < tree.adjustments.size(); } else { is_correct &= child.split_node_index() < tree.split_nodes.size(); } if (!is_correct) return absl::InvalidArgumentError("incorrect split node"); for (auto id_type : node.condition->GetInputSignatures()) { auto it = required_qtypes_.emplace(id_type.id, id_type.type); if (it.first->second != id_type.type) { return absl::InvalidArgumentError( "types mismatch in decision forest"); } } } } fingerprint_ = std::move(hasher).Finish(); return absl::OkStatus(); } void FingerprintHasherTraits<SplitNode>::operator()( FingerprintHasher* hasher, const SplitNode& value) const { hasher->Combine(value.child_if_false.raw_index(), value.child_if_true.raw_index()); value.condition->CombineToFingerprintHasher(hasher); } void FingerprintHasherTraits<TreeFilter>::operator()( FingerprintHasher* hasher, const TreeFilter& value) const { std::vector<int> submodels(value.submodels.begin(), value.submodels.end()); absl::c_sort(submodels); hasher->Combine(value.step_range_from, value.step_range_to) .CombineSpan(submodels); } void FingerprintHasherTraits<DecisionForestPtr>::operator()( FingerprintHasher* hasher, const DecisionForestPtr& value) const { hasher->Combine(value->fingerprint()); } AROLLA_DEFINE_SIMPLE_QTYPE(DECISION_FOREST, DecisionForestPtr); AROLLA_DEFINE_SIMPLE_QTYPE(TREE_FILTER, TreeFilter); }
#include "arolla/decision_forest/decision_forest.h" #include <cmath> #include <cstdint> #include <limits> #include <utility> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "arolla/decision_forest/split_conditions/interval_split_condition.h" #include "arolla/decision_forest/split_conditions/set_of_values_split_condition.h" #include "arolla/memory/frame.h" #include "arolla/memory/memory_allocation.h" #include "arolla/memory/optional_value.h" #include "arolla/qtype/typed_slot.h" #include "arolla/util/testing/status_matchers_backport.h" namespace arolla::testing { namespace { using ::arolla::testing::StatusIs; using ::testing::HasSubstr; using ::testing::Test; constexpr float inf = std::numeric_limits<float>::infinity(); constexpr auto S = DecisionTreeNodeId::SplitNodeId; constexpr auto A = DecisionTreeNodeId::AdjustmentId; TEST(DecisionForestTest, ForestValidation) { DecisionTree tree1; tree1.adjustments = {0.5, 1.5, 2.5, 3.5}; tree1.split_nodes = {{S(1), S(2), IntervalSplit(0, 1.5, inf)}, {A(0), A(1), SetOfValuesSplit<int64_t>(1, {5}, false)}, {A(2), A(3), IntervalSplit(0, -inf, 10)}}; DecisionTree tree2; tree2.adjustments = {1., 2.}; tree2.split_nodes = {{A(0), A(1), IntervalSplit(0, 1.5, inf)}}; DecisionTree tree3; tree3.adjustments = {1., 2., 3.}; tree3.split_nodes = {{A(0), A(1), IntervalSplit(0, 1.5, inf)}}; DecisionTree tree4; tree4.adjustments = {1., 2.}; tree4.split_nodes = { {A(0), A(1), IntervalSplit(1, 1.5, inf)}}; EXPECT_OK(DecisionForest::FromTrees({tree1, tree2})); EXPECT_THAT(DecisionForest::FromTrees({tree1, tree3}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("incorrect number of regions"))); EXPECT_THAT(DecisionForest::FromTrees({tree1, tree4}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("types mismatch in decision forest"))); } TEST(DecisionForestTest, Fingerprint) { DecisionTree tree; tree.adjustments = {0.5, 1.5, 2.5, 3.5}; tree.split_nodes = {{S(1), S(2), IntervalSplit(0, 1.5, inf)}, {A(0), A(1), SetOfValuesSplit<int64_t>(1, {5}, false)}, {A(2), A(3), IntervalSplit(0, -inf, 10)}}; ASSERT_OK_AND_ASSIGN(auto forest1, DecisionForest::FromTrees({tree})); ASSERT_OK_AND_ASSIGN(auto forest2, DecisionForest::FromTrees({tree})); tree.adjustments[1] += 0.1; ASSERT_OK_AND_ASSIGN(auto forest3, DecisionForest::FromTrees({tree})); EXPECT_EQ(forest1->fingerprint(), forest2->fingerprint()); EXPECT_NE(forest1->fingerprint(), forest3->fingerprint()); } TEST(DecisionForestTest, ToDebugString) { std::vector<DecisionTree> trees(2); trees[0].adjustments = {0.5, 1.5, 2.5, 3.5}; trees[0].split_nodes = { {S(1), S(2), IntervalSplit(0, 1.5, inf)}, {A(0), A(1), SetOfValuesSplit<int64_t>(1, {5}, false)}, {A(2), A(3), IntervalSplit(0, -inf, 10)}}; trees[1].adjustments = {5}; trees[1].tag.step = 1; ASSERT_OK_AND_ASSIGN(auto forest, DecisionForest::FromTrees(std::move(trees))); EXPECT_EQ(ToDebugString(*forest), "DecisionForest {\n" " input #0: OPTIONAL_FLOAT32\n" " input #1: OPTIONAL_INT64\n" " DecisionTree {\n" " tag { step: 0 submodel_id: 0 }\n" " weight: 1.000000\n" " split_nodes {\n" " 0: IF #0 in range [1.500000 inf] THEN goto 2 ELSE goto 1\n" " 1: IF #1 in set [5] " "THEN adjustments[1] ELSE adjustments[0]\n" " 2: IF #0 in range [-inf 10.000000] " "THEN adjustments[3] ELSE adjustments[2]\n" " }\n" " adjustments: 0.500000 1.500000 2.500000 3.500000\n" " }\n" " DecisionTree {\n" " tag { step: 1 submodel_id: 0 }\n" " weight: 1.000000\n" " split_nodes {\n" " }\n" " adjustments: 5.000000\n" " }\n" "}"); } TEST(DecisionForestTest, InputsValidation) { std::vector<DecisionTree> trees(1); DecisionTree& tree = trees[0]; tree.adjustments = {0.5, 1.5, 2.5, 3.5}; tree.split_nodes = {{S(1), S(2), IntervalSplit(0, 1.5, inf)}, {A(0), A(1), SetOfValuesSplit<int64_t>(1, {5}, false)}, {A(2), A(3), IntervalSplit(0, -inf, 10)}}; FrameLayout::Builder bldr; auto slot_float = bldr.AddSlot<OptionalValue<float>>(); auto slot_int64 = bldr.AddSlot<OptionalValue<int64_t>>(); FrameLayout layout = std::move(bldr).Build(); ASSERT_OK_AND_ASSIGN(auto forest, DecisionForest::FromTrees(std::move(trees))); EXPECT_OK(forest->ValidateInputSlots( {TypedSlot::FromSlot(slot_float), TypedSlot::FromSlot(slot_int64)})); EXPECT_THAT(forest->ValidateInputSlots({}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("not enough arguments"))); EXPECT_THAT( forest->ValidateInputSlots( {TypedSlot::FromSlot(slot_float), TypedSlot::FromSlot(slot_float)}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("type mismatch"))); } TEST(DecisionForestTest, TreeFilter) { DecisionTree::Tag t0{.step = 0, .submodel_id = 0}; DecisionTree::Tag t1{.step = 1, .submodel_id = 1}; DecisionTree::Tag t2{.step = 2, .submodel_id = 0}; TreeFilter f0{}; TreeFilter f1{.submodels = {0}}; TreeFilter f2{.submodels = {1}}; TreeFilter f3{.submodels = {0, 1}}; TreeFilter f4{.step_range_from = 1}; TreeFilter f5{.step_range_to = 2}; TreeFilter f6{.step_range_from = 1, .step_range_to = 2, .submodels = {0}}; EXPECT_EQ((std::vector<bool>{f0(t0), f0(t1), f0(t2)}), (std::vector<bool>{true, true, true})); EXPECT_EQ((std::vector<bool>{f1(t0), f1(t1), f1(t2)}), (std::vector<bool>{true, false, true})); EXPECT_EQ((std::vector<bool>{f2(t0), f2(t1), f2(t2)}), (std::vector<bool>{false, true, false})); EXPECT_EQ((std::vector<bool>{f3(t0), f3(t1), f3(t2)}), (std::vector<bool>{true, true, true})); EXPECT_EQ((std::vector<bool>{f4(t0), f4(t1), f4(t2)}), (std::vector<bool>{false, true, true})); EXPECT_EQ((std::vector<bool>{f5(t0), f5(t1), f5(t2)}), (std::vector<bool>{true, true, false})); EXPECT_EQ((std::vector<bool>{f6(t0), f6(t1), f6(t2)}), (std::vector<bool>{false, false, false})); } TEST(DecisionForestTest, GetTreeRootId) { DecisionTree tree1; tree1.adjustments = {1.0}; EXPECT_TRUE(GetTreeRootId(tree1).is_leaf()); DecisionTree tree2; tree2.split_nodes = {{A(0), A(1), IntervalSplit(0, 1, 2)}}; tree2.adjustments = {1.0, 2.0}; EXPECT_FALSE(GetTreeRootId(tree2).is_leaf()); } TEST(DecisionForestTest, NaiveEvaluation) { std::vector<DecisionTree> trees(3); trees[0].adjustments = {0.5, 1.5, 2.5, 3.5}; trees[0].split_nodes = { {S(1), S(2), IntervalSplit(0, 1.5, inf)}, {A(0), A(1), SetOfValuesSplit<int64_t>(1, {5}, false)}, {A(2), A(3), IntervalSplit(0, -inf, 10)}}; trees[1].adjustments = {5.0}; trees[1].tag = {1, 1}; trees[2].adjustments = {2.0}; trees[2].tag = {2, 0}; ASSERT_OK_AND_ASSIGN(auto forest, DecisionForest::FromTrees(std::move(trees))); EXPECT_EQ(forest->step_count(), 3); EXPECT_EQ(forest->submodel_count(), 2); FrameLayout::Builder bldr; auto input1_slot = bldr.AddSlot<OptionalValue<float>>(); auto input2_slot = bldr.AddSlot<OptionalValue<int64_t>>(); std::vector<TypedSlot> slots = {TypedSlot::FromSlot(input1_slot), TypedSlot::FromSlot(input2_slot)}; FrameLayout layout = std::move(bldr).Build(); MemoryAllocation alloc(&layout); FramePtr frame = alloc.frame(); frame.Set(input1_slot, 1.0f); frame.Set(input2_slot, 5); EXPECT_EQ(DecisionForestNaiveEvaluation(*forest, frame, slots), 8.5); frame.Set(input1_slot, NAN); frame.Set(input2_slot, {}); EXPECT_EQ(DecisionForestNaiveEvaluation(*forest, frame, slots), 7.5); frame.Set(input1_slot, 2.0f); frame.Set(input2_slot, 4); EXPECT_EQ(DecisionForestNaiveEvaluation(*forest, frame, slots), 10.5); EXPECT_EQ(DecisionForestNaiveEvaluation(*forest, frame, slots, TreeFilter{.submodels = {0}}), 5.5); EXPECT_EQ(DecisionForestNaiveEvaluation(*forest, frame, slots, TreeFilter{.submodels = {1}}), 5.0); EXPECT_EQ(DecisionForestNaiveEvaluation(*forest, frame, slots, TreeFilter{.submodels = {0, 1}}), 10.5); EXPECT_EQ(DecisionForestNaiveEvaluation(*forest, frame, slots, TreeFilter{.step_range_from = 1}), 7.0); EXPECT_EQ(DecisionForestNaiveEvaluation(*forest, frame, slots, TreeFilter{.step_range_to = 2}), 8.5); } } }
2,385
cpp
google/arolla
test_util
arolla/decision_forest/testing/test_util.cc
arolla/decision_forest/testing/test_util_test.cc
#ifndef AROLLA_DECISION_FOREST_TEST_UTIL_TEST_UTIL_H_ #define AROLLA_DECISION_FOREST_TEST_UTIL_TEST_UTIL_H_ #include <cstdint> #include <memory> #include <vector> #include "absl/random/random.h" #include "absl/status/status.h" #include "absl/types/span.h" #include "arolla/decision_forest/decision_forest.h" #include "arolla/memory/frame.h" #include "arolla/qtype/qtype.h" namespace arolla { absl::Status FillWithRandomValue(TypedSlot tslot, FramePtr ctx, absl::BitGen* rnd, double missed_prob = 0); absl::Status FillArrayWithRandomValues(int64_t size, TypedSlot tslot, FramePtr ctx, absl::BitGen* rnd, double missed_prob = 0); void CreateSlotsForForest(const DecisionForest& forest, FrameLayout::Builder* layout_builder, std::vector<TypedSlot>* slots); absl::Status CreateArraySlotsForForest(const DecisionForest& forest, FrameLayout::Builder* layout_builder, std::vector<TypedSlot>* slots); DecisionTree CreateRandomFloatTree(absl::BitGen* rnd, int num_features, bool interactions, int num_splits, double range_split_prob = 0.0, double equality_split_prob = 0.0); std::unique_ptr<const DecisionForest> CreateRandomFloatForest( absl::BitGen* rnd, int num_features, bool interactions, int min_num_splits, int max_num_splits, int num_trees); DecisionTree CreateRandomTree(absl::BitGen* rnd, bool interactions, int num_splits, std::vector<QTypePtr>* feature_types); DecisionTree CreateRandomObliviousTree(absl::BitGen* rnd, int depth, std::vector<QTypePtr>* feature_types); std::unique_ptr<const DecisionForest> CreateRandomForest( absl::BitGen* rnd, int num_features, bool interactions, int min_num_splits, int max_num_splits, int num_trees, absl::Span<const QTypePtr> feature_types = {}); } #endif #include "arolla/decision_forest/testing/test_util.h" #include <algorithm> #include <cmath> #include <cstdint> #include <limits> #include <memory> #include <string> #include <utility> #include <vector> #include "absl/container/flat_hash_set.h" #include "absl/random/distributions.h" #include "absl/random/random.h" #include "absl/status/status.h" #include "absl/types/span.h" #include "arolla/decision_forest/decision_forest.h" #include "arolla/decision_forest/split_condition.h" #include "arolla/decision_forest/split_conditions/interval_split_condition.h" #include "arolla/decision_forest/split_conditions/set_of_values_split_condition.h" #include "arolla/dense_array/dense_array.h" #include "arolla/dense_array/qtype/types.h" #include "arolla/memory/frame.h" #include "arolla/memory/optional_value.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/optional_qtype.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/typed_slot.h" namespace arolla { namespace { constexpr int kSetOfValuesSize = 10; template <typename ConditionFactoryFn> DecisionTree CreateRandomTreeImpl(absl::BitGen* rnd, int num_features, bool interactions, int num_splits, ConditionFactoryFn condition_factory) { DecisionTree tree; tree.adjustments.resize(num_splits + 1); for (float& val : tree.adjustments) { val = absl::Uniform<uint8_t>(*rnd); } int single_feature_id = absl::Uniform<int32_t>(*rnd, 0, num_features); for (int i = 0; i < num_splits; ++i) { auto child1 = i * 2 + 1 < num_splits ? DecisionTreeNodeId::SplitNodeId(i * 2 + 1) : DecisionTreeNodeId::AdjustmentId(i * 2 + 1 - num_splits); auto child2 = i * 2 + 2 < num_splits ? DecisionTreeNodeId::SplitNodeId(i * 2 + 2) : DecisionTreeNodeId::AdjustmentId(i * 2 + 2 - num_splits); int feature_id; if (interactions) { feature_id = absl::Uniform<int32_t>(*rnd, 0, num_features); } else { feature_id = single_feature_id; } tree.split_nodes.push_back({child1, child2, condition_factory(feature_id)}); } return tree; } } absl::Status FillWithRandomValue(TypedSlot tslot, FramePtr ctx, absl::BitGen* rnd, double missed_prob) { if (tslot.byte_offset() == FrameLayout::Slot<float>::kUninitializedOffset) { return absl::OkStatus(); } bool missed = (absl::Uniform<float>(*rnd, 0, 1) < missed_prob); if (tslot.GetType() == GetOptionalQType<float>()) { auto slot = tslot.ToSlot<OptionalValue<float>>().value(); auto val = OptionalValue<float>(absl::Uniform<float>(*rnd, 0, 1)); ctx.Set(slot, missed ? OptionalValue<float>{} : val); } else if (tslot.GetType() == GetOptionalQType<int64_t>()) { auto slot = tslot.ToSlot<OptionalValue<int64_t>>().value(); auto val = OptionalValue<int64_t>(absl::Uniform<int64_t>(*rnd, 0, 1000)); ctx.Set(slot, missed ? OptionalValue<int64_t>{} : val); } else { return absl::UnimplementedError(std::string("Unimplemented for type: ") + std::string(tslot.GetType()->name())); } return absl::OkStatus(); } absl::Status FillArrayWithRandomValues(int64_t size, TypedSlot tslot, FramePtr ctx, absl::BitGen* rnd, double missed_prob) { if (tslot.byte_offset() == FrameLayout::Slot<float>::kUninitializedOffset) { return absl::OkStatus(); } if (tslot.GetType() == GetDenseArrayQType<float>()) { auto slot = tslot.UnsafeToSlot<DenseArray<float>>(); DenseArrayBuilder<float> bldr(size); for (int64_t i = 0; i < size; ++i) { bool missed = (absl::Uniform<float>(*rnd, 0, 1) < missed_prob); if (!missed) { bldr.Set(i, absl::Uniform<float>(*rnd, 0, 1)); } } ctx.Set(slot, std::move(bldr).Build()); } else if (tslot.GetType() == GetDenseArrayQType<int64_t>()) { auto slot = tslot.UnsafeToSlot<DenseArray<int64_t>>(); DenseArrayBuilder<int64_t> bldr(size); for (int64_t i = 0; i < size; ++i) { bool missed = (absl::Uniform<float>(*rnd, 0, 1) < missed_prob); if (!missed) { bldr.Set(i, absl::Uniform<int64_t>(*rnd, 0, 1000)); } } ctx.Set(slot, std::move(bldr).Build()); } else { return absl::UnimplementedError(std::string("Unimplemented for type: ") + std::string(tslot.GetType()->name())); } return absl::OkStatus(); } void CreateSlotsForForest(const DecisionForest& forest, FrameLayout::Builder* layout_builder, std::vector<TypedSlot>* slots) { auto placeholder = TypedSlot::FromSlot(FrameLayout::Slot<float>::UnsafeUninitializedSlot()); for (auto id_qtype : forest.GetRequiredQTypes()) { while (slots->size() <= id_qtype.first) { slots->push_back(placeholder); } QTypePtr qtype = id_qtype.second; (*slots)[id_qtype.first] = AddSlot(qtype, layout_builder); } } absl::Status CreateArraySlotsForForest(const DecisionForest& forest, FrameLayout::Builder* layout_builder, std::vector<TypedSlot>* slots) { auto placeholder = TypedSlot::FromSlot(FrameLayout::Slot<float>::UnsafeUninitializedSlot()); for (auto id_qtype : forest.GetRequiredQTypes()) { while (slots->size() <= id_qtype.first) { slots->push_back(placeholder); } QTypePtr qtype = id_qtype.second; if (qtype == GetOptionalQType<float>()) { (*slots)[id_qtype.first] = TypedSlot::FromSlot(layout_builder->AddSlot<DenseArray<float>>()); } else if (qtype == GetOptionalQType<int64_t>()) { (*slots)[id_qtype.first] = TypedSlot::FromSlot(layout_builder->AddSlot<DenseArray<int64_t>>()); } else { return absl::UnimplementedError(std::string("Unimplemented for type: ") + std::string(qtype->name())); } } if (slots->empty()) { slots->push_back( TypedSlot::FromSlot(layout_builder->AddSlot<DenseArray<float>>())); } return absl::OkStatus(); } DecisionTree CreateRandomFloatTree(absl::BitGen* rnd, int num_features, bool interactions, int num_splits, double range_split_prob, double equality_split_prob) { return CreateRandomTreeImpl( rnd, num_features, interactions, num_splits, [&](int feature_id) { float split_type_rnd = absl::Uniform<float>(*rnd, 0, 1); if (split_type_rnd < range_split_prob + equality_split_prob) { float sp0 = absl::Uniform<uint8_t>(*rnd) / 256.0; float sp1 = split_type_rnd < range_split_prob ? absl::Uniform<uint8_t>(*rnd) / 256.0 : sp0; return IntervalSplit(feature_id, std::min(sp0, sp1), std::max(sp0, sp1)); } else { float split_point = absl::Uniform<uint8_t>(*rnd) / 256.0; if (absl::Bernoulli(*rnd, 0.5)) { return IntervalSplit(feature_id, -INFINITY, split_point); } else { return IntervalSplit(feature_id, split_point, +INFINITY); } } }); } std::unique_ptr<const DecisionForest> CreateRandomFloatForest( absl::BitGen* rnd, int num_features, bool interactions, int min_num_splits, int max_num_splits, int num_trees) { std::vector<DecisionTree> trees; trees.reserve(num_trees); for (int i = 0; i < num_trees; ++i) { int num_splits = absl::Uniform<int32_t>(*rnd, min_num_splits, max_num_splits); trees.push_back( CreateRandomFloatTree(rnd, num_features, interactions, num_splits)); } return DecisionForest::FromTrees(std::move(trees)).value(); } DecisionTree CreateRandomTree(absl::BitGen* rnd, bool interactions, int num_splits, std::vector<QTypePtr>* feature_types) { const float inf = std::numeric_limits<float>::infinity(); return CreateRandomTreeImpl( rnd, feature_types->size(), interactions, num_splits, [&](int feature_id) -> std::shared_ptr<SplitCondition> { QTypePtr& type = (*feature_types)[feature_id]; if (!type) { type = absl::Bernoulli(*rnd, 0.5) ? GetOptionalQType<float>() : GetOptionalQType<int64_t>(); } if (type == GetOptionalQType<float>()) { float split_point = absl::Uniform<uint8_t>(*rnd) / 256.0; if (absl::Bernoulli(*rnd, 0.5)) { return IntervalSplit(feature_id, -inf, split_point); } else { return IntervalSplit(feature_id, split_point, +inf); } } else { absl::flat_hash_set<int64_t> values; for (int i = 0; i < kSetOfValuesSize; ++i) { values.insert(absl::Uniform<int64_t>(*rnd, 0, 1000)); } return SetOfValuesSplit<int64_t>(feature_id, values, absl::Bernoulli(*rnd, 0.5)); } }); } DecisionTree CreateRandomObliviousTree(absl::BitGen* rnd, int depth, std::vector<QTypePtr>* feature_types) { const float inf = std::numeric_limits<float>::infinity(); std::vector<std::shared_ptr<SplitCondition>> conditions(depth); for (int i = 0; i < depth; ++i) { int feature_id = absl::Uniform<int32_t>(*rnd, 0, feature_types->size()); QTypePtr& type = (*feature_types)[feature_id]; if (!type) { type = absl::Bernoulli(*rnd, 0.5) ? GetOptionalQType<float>() : GetOptionalQType<int64_t>(); } if (type == GetOptionalQType<float>()) { float split_point = absl::Uniform<uint8_t>(*rnd) / 256.0; if (absl::Bernoulli(*rnd, 0.5)) { conditions[i] = IntervalSplit(feature_id, -inf, split_point); } else { conditions[i] = IntervalSplit(feature_id, split_point, +inf); } } else { absl::flat_hash_set<int64_t> values; for (int i = 0; i < kSetOfValuesSize; ++i) { values.insert(absl::Uniform<int64_t>(*rnd, 0, 1000)); } conditions[i] = SetOfValuesSplit<int64_t>(feature_id, values, absl::Bernoulli(*rnd, 0.5)); } } int cond_id = 0; int node_id = 0; return CreateRandomTreeImpl(rnd, feature_types->size(), false, (1 << depth) - 1, [&](int) { node_id++; bool last_in_the_row = node_id & (node_id + 1); if (last_in_the_row) { return conditions[cond_id]; } else { return conditions[cond_id++]; } }); } std::unique_ptr<const DecisionForest> CreateRandomForest( absl::BitGen* rnd, int num_features, bool interactions, int min_num_splits, int max_num_splits, int num_trees, absl::Span<const QTypePtr> feature_types) { std::vector<QTypePtr> types; for (int feature_id = 0; feature_id < num_features; feature_id++) { if (feature_id < feature_types.size() && feature_types[feature_id]) { types.push_back(feature_types[feature_id]); } else { types.push_back(nullptr); } } std::vector<DecisionTree> trees; trees.reserve(num_trees); for (int i = 0; i < num_trees; ++i) { int num_splits = absl::Uniform<int32_t>(*rnd, min_num_splits, max_num_splits); trees.push_back(CreateRandomTree(rnd, interactions, num_splits, &types)); } return DecisionForest::FromTrees(std::move(trees)).value(); } }
#include "arolla/decision_forest/testing/test_util.h" #include <cstddef> #include <cstdint> #include <utility> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/log/check.h" #include "absl/random/random.h" #include "arolla/decision_forest/decision_forest.h" #include "arolla/memory/frame.h" #include "arolla/memory/optional_value.h" #include "arolla/qexpr/eval_context.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/typed_slot.h" namespace arolla { namespace { TEST(TestUtilTest, FillWithRandomValue) { absl::BitGen rnd; FrameLayout::Builder bldr; auto opt_float_slot = bldr.AddSlot<OptionalValue<float>>(); auto opt_int64_slot = bldr.AddSlot<OptionalValue<int64_t>>(); auto layout = std::move(bldr).Build(); RootEvaluationContext ctx(&layout); ctx.Set(opt_float_slot, OptionalValue<float>(-1.0)); ctx.Set(opt_int64_slot, OptionalValue<int64_t>(-1)); CHECK_OK(FillWithRandomValue(TypedSlot::FromSlot(opt_float_slot), ctx.frame(), &rnd)); CHECK_OK(FillWithRandomValue(TypedSlot::FromSlot(opt_int64_slot), ctx.frame(), &rnd)); EXPECT_NE(OptionalValue<float>(-1.0), ctx.Get(opt_float_slot)); EXPECT_NE(OptionalValue<int64_t>(-1), ctx.Get(opt_int64_slot)); } TEST(TestUtilTest, CreateSlotsForForest) { absl::BitGen rnd; auto forest = CreateRandomForest(&rnd, 5, true, 1, 64, 16); FrameLayout::Builder bldr; std::vector<TypedSlot> slots; CreateSlotsForForest(*forest, &bldr, &slots); EXPECT_OK(forest->ValidateInputSlots(slots)); } TEST(TestUtilTest, CreateRandomFloatTree) { absl::BitGen rnd; for (size_t depth = 0; depth <= 15; ++depth) { auto tree = CreateRandomFloatTree(&rnd, 5, true, (1 << depth) - 1); EXPECT_EQ(tree.adjustments.size(), 1 << depth); EXPECT_EQ(tree.split_nodes.size(), (1 << depth) - 1); } } TEST(TestUtilTest, CreateRandomFloatForest) { absl::BitGen rnd; auto forest = CreateRandomFloatForest(&rnd, 5, true, 1, 64, 16); EXPECT_EQ(forest->GetTrees().size(), 16); EXPECT_GE(forest->GetRequiredQTypes().size(), 1); EXPECT_LE(forest->GetRequiredQTypes().size(), 5); for (const DecisionTree& tree : forest->GetTrees()) { EXPECT_LE(tree.split_nodes.size(), 64); } } TEST(TestUtilTest, CreateRandomForest) { absl::BitGen rnd; auto forest = CreateRandomForest(&rnd, 5, true, 1, 64, 16); EXPECT_EQ(forest->GetTrees().size(), 16); EXPECT_GE(forest->GetRequiredQTypes().size(), 1); EXPECT_LE(forest->GetRequiredQTypes().size(), 5); for (const DecisionTree& tree : forest->GetTrees()) { EXPECT_LE(tree.split_nodes.size(), 64); } } TEST(TestUtilTest, CreateRandomObliviousTree) { absl::BitGen rnd; std::vector<QTypePtr> types(10); auto tree = CreateRandomObliviousTree(&rnd, 3, &types); ASSERT_EQ(tree.split_nodes.size(), 7); EXPECT_EQ(tree.split_nodes[1].condition, tree.split_nodes[2].condition); EXPECT_EQ(tree.split_nodes[3].condition, tree.split_nodes[4].condition); EXPECT_EQ(tree.split_nodes[4].condition, tree.split_nodes[5].condition); EXPECT_EQ(tree.split_nodes[5].condition, tree.split_nodes[6].condition); } TEST(TestUtilTest, CreateRandomForestWithoutInteractions) { absl::BitGen rnd; auto forest = CreateRandomForest(&rnd, 5, false, 512, 512, 1); EXPECT_EQ(forest->GetTrees().size(), 1); EXPECT_EQ(forest->GetRequiredQTypes().size(), 1); } } }
2,386
cpp
google/arolla
forest_evaluator
arolla/decision_forest/pointwise_evaluation/forest_evaluator.cc
arolla/decision_forest/pointwise_evaluation/forest_evaluator_test.cc
#ifndef AROLLA_DECISION_FOREST_POINTWISE_EVALUATION_FOREST_EVALUATOR_H_ #define AROLLA_DECISION_FOREST_POINTWISE_EVALUATION_FOREST_EVALUATOR_H_ #include <cstdint> #include <functional> #include <memory> #include <utility> #include <vector> #include "absl/container/inlined_vector.h" #include "absl/log/check.h" #include "absl/status/statusor.h" #include "absl/types/span.h" #include "arolla/decision_forest/decision_forest.h" #include "arolla/decision_forest/pointwise_evaluation/bitmask_eval.h" #include "arolla/decision_forest/pointwise_evaluation/bound_split_conditions.h" #include "arolla/decision_forest/pointwise_evaluation/pointwise.h" #include "arolla/decision_forest/pointwise_evaluation/single_input_eval.h" #include "arolla/memory/frame.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/typed_slot.h" #include "arolla/util/status_macros_backport.h" namespace arolla { class ForestEvaluator { public: struct CompilationParams { static constexpr CompilationParams Default() { return {}; } bool enable_regular_eval = true; bool enable_bitmask_eval = true; bool enable_single_input_eval = true; }; struct Output { TreeFilter filter; FrameLayout::Slot<float> slot; }; static absl::StatusOr<ForestEvaluator> Compile( const DecisionForest& decision_forest, absl::Span<const TypedSlot> input_slots, absl::Span<const Output> outputs, CompilationParams params = CompilationParams::Default()); void Eval(ConstFramePtr input_ctx, FramePtr output_ctx) const; private: template <class T> using Predictor = BoostedPredictor<float, T, std::plus<double>, int>; template <class T> using PredictorCompiler = BoostedPredictorCompiler<float, T, std::plus<double>, int>; using UniversalBoundCondition = VariantBoundCondition<IntervalBoundCondition, SetOfValuesBoundCondition<int64_t>, VirtualBoundCondition>; struct RegularPredictors { Predictor<UniversalBoundCondition> universal_predictor; Predictor<IntervalBoundCondition> interval_splits_predictor; float Predict(ConstFramePtr input_ctx) const { return universal_predictor.Predict(input_ctx, 0.0) + interval_splits_predictor.Predict(input_ctx, 0.0); } }; using RegularPredictorsList = absl::InlinedVector<RegularPredictors, 2>; class RegularPredictorsBuilder; explicit ForestEvaluator(std::vector<FrameLayout::Slot<float>>&& output_slots, RegularPredictorsList&& predictors, std::unique_ptr<BitmaskEval>&& bitmask_predictor, SingleInputEval&& single_input_predictor) : output_slots_(std::move(output_slots)), regular_predictors_(std::move(predictors)), bitmask_predictor_(std::move(bitmask_predictor)), single_input_predictor_(std::move(single_input_predictor)) {} std::vector<FrameLayout::Slot<float>> output_slots_; RegularPredictorsList regular_predictors_; std::unique_ptr<BitmaskEval> bitmask_predictor_; SingleInputEval single_input_predictor_; }; class SimpleForestEvaluator { public: static absl::StatusOr<SimpleForestEvaluator> Compile( const DecisionForest& decision_forest, absl::Span<const TypedSlot> input_slots, ForestEvaluator::CompilationParams params = ForestEvaluator::CompilationParams::Default()) { DCHECK(GetQType<float>()->type_layout().HasField(0, typeid(float))); ForestEvaluator::Output output{ .filter = {}, .slot = FrameLayout::Slot<float>::UnsafeSlotFromOffset(0)}; ASSIGN_OR_RETURN(auto evaluator, ForestEvaluator::Compile(decision_forest, input_slots, {output}, params)); return SimpleForestEvaluator(std::move(evaluator)); } float Eval(ConstFramePtr ctx) const { float res; FramePtr output_ctx(&res, &GetQType<float>()->type_layout()); evaluator_.Eval(ctx, output_ctx); return res; } private: explicit SimpleForestEvaluator(ForestEvaluator&& evaluator) : evaluator_(std::move(evaluator)) {} ForestEvaluator evaluator_; }; } #endif #include "arolla/decision_forest/pointwise_evaluation/forest_evaluator.h" #include <algorithm> #include <cstddef> #include <cstdint> #include <map> #include <memory> #include <optional> #include <utility> #include <vector> #include "absl/container/inlined_vector.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "absl/types/span.h" #include "arolla/decision_forest/decision_forest.h" #include "arolla/decision_forest/pointwise_evaluation/bitmask_builder.h" #include "arolla/decision_forest/pointwise_evaluation/bound_split_conditions.h" #include "arolla/decision_forest/pointwise_evaluation/oblivious.h" #include "arolla/decision_forest/pointwise_evaluation/single_input_eval.h" #include "arolla/decision_forest/split_condition.h" #include "arolla/decision_forest/split_conditions/interval_split_condition.h" #include "arolla/memory/frame.h" #include "arolla/qtype/typed_slot.h" #include "arolla/util/fast_dynamic_downcast_final.h" #include "arolla/util/status_macros_backport.h" namespace arolla { namespace { bool HasOnlyIntervalSplitConditions(const DecisionTree& tree) { for (const auto& split_node : tree.split_nodes) { if (!fast_dynamic_downcast_final<const IntervalSplitCondition*>( split_node.condition.get())) return false; } return true; } absl::StatusOr<std::vector<int>> SplitTreesByGroups( absl::Span<const DecisionTree> trees, absl::Span<const ForestEvaluator::Output> outputs) { if (outputs.empty()) { return absl::InvalidArgumentError("at least one output is expected"); } std::vector<int> tree2group(trees.size(), -1); for (int group_id = 0; group_id < outputs.size(); ++group_id) { for (int tree_id = 0; tree_id < trees.size(); ++tree_id) { if (!outputs[group_id].filter(trees[tree_id].tag)) continue; if (tree2group[tree_id] != -1) { return absl::InvalidArgumentError(absl::StrFormat( "intersection of groups for outputs #%d and #%d is not empty", tree2group[tree_id], group_id)); } tree2group[tree_id] = group_id; } } return tree2group; } std::optional<SplitCondition::InputSignature> GetSingleInputSignature( const DecisionTree& tree) { std::optional<SplitCondition::InputSignature> input_signature; for (const auto& node : tree.split_nodes) { auto signatures = node.condition->GetInputSignatures(); if (signatures.size() != 1 || (input_signature && input_signature->id != signatures[0].id)) { return std::nullopt; } input_signature = signatures[0]; } return input_signature; } } class ForestEvaluator::RegularPredictorsBuilder { public: RegularPredictorsBuilder(int group_count, absl::Span<const TypedSlot> input_slots) : group_count_(group_count), input_slots_(input_slots.begin(), input_slots.end()), universal_compilers_(group_count), interval_splits_compilers_(group_count) {} absl::Status AddTree(const DecisionTree& tree, int group_id) { if (HasOnlyIntervalSplitConditions(tree)) { return AddTreeToRegularForestCompiler( tree, [this](const std::shared_ptr<const SplitCondition>& cond) { auto interval_cond = std::static_pointer_cast<const IntervalSplitCondition>(cond); return IntervalBoundCondition::Create(interval_cond, input_slots_); }, &interval_splits_compilers_[group_id]); } else { return AddTreeToRegularForestCompiler( tree, [this](const std::shared_ptr<const SplitCondition>& cond) { return UniversalBoundCondition::Create(cond, input_slots_); }, &universal_compilers_[group_id]); } } absl::StatusOr<RegularPredictorsList> Build() && { RegularPredictorsList res; res.reserve(group_count_); for (int i = 0; i < group_count_; ++i) { ASSIGN_OR_RETURN(auto universal_predictor, universal_compilers_[i].Compile()); ASSIGN_OR_RETURN(auto interval_splits_predictor, interval_splits_compilers_[i].Compile()); res.push_back({std::move(universal_predictor), std::move(interval_splits_predictor)}); } return res; } private: template <typename ForestCompiler, typename CreateConditionFunc> absl::Status AddTreeToRegularForestCompiler(const DecisionTree& tree, CreateConditionFunc create_cond, ForestCompiler* forest_compiler) { auto tree_compiler = forest_compiler->AddTree( tree.split_nodes.size() + tree.adjustments.size(), tree.tag.submodel_id); for (int64_t id = 0; id < tree.split_nodes.size(); ++id) { const auto& split_node = tree.split_nodes[id]; auto child_if_false = split_node.child_if_false.is_leaf() ? split_node.child_if_false.adjustment_index() + tree.split_nodes.size() : split_node.child_if_false.split_node_index(); auto child_if_true = split_node.child_if_true.is_leaf() ? split_node.child_if_true.adjustment_index() + tree.split_nodes.size() : split_node.child_if_true.split_node_index(); ASSIGN_OR_RETURN(auto cond, create_cond(split_node.condition)); RETURN_IF_ERROR( tree_compiler.SetNode(id, child_if_true, child_if_false, cond)); } for (int64_t i = 0; i < tree.adjustments.size(); ++i) { RETURN_IF_ERROR(tree_compiler.SetLeaf(i + tree.split_nodes.size(), tree.adjustments[i] * tree.weight)); } return absl::OkStatus(); } int group_count_; std::vector<TypedSlot> input_slots_; std::vector<PredictorCompiler<UniversalBoundCondition>> universal_compilers_; std::vector<PredictorCompiler<IntervalBoundCondition>> interval_splits_compilers_; }; absl::StatusOr<ForestEvaluator> ForestEvaluator::Compile( const DecisionForest& decision_forest, absl::Span<const TypedSlot> input_slots, absl::Span<const Output> outputs, CompilationParams params) { ASSIGN_OR_RETURN(auto tree2group, SplitTreesByGroups(decision_forest.GetTrees(), outputs)); std::vector<FrameLayout::Slot<float>> output_slots; output_slots.reserve(outputs.size()); for (const auto& output : outputs) { output_slots.push_back(output.slot); } RegularPredictorsBuilder regular_builder(outputs.size(), input_slots); BitmaskBuilder bitmask_builder(input_slots, output_slots); SingleInputBuilder single_input_builder(input_slots, output_slots); std::vector<std::map<int, double>> consts(outputs.size()); if (tree2group.size() != decision_forest.GetTrees().size()) { return absl::InternalError("size of tree2group doesn't match trees"); } for (size_t i = 0; i < decision_forest.GetTrees().size(); ++i) { if (tree2group[i] == -1) { continue; } if (tree2group[i] < 0 || tree2group[i] >= outputs.size()) { return absl::InternalError("invalid tree2group mapping"); } const DecisionTree& tree = decision_forest.GetTrees()[i]; if (params.enable_regular_eval && tree.split_nodes.empty()) { consts[tree2group[i]][tree.tag.submodel_id] += tree.adjustments[0] * tree.weight; continue; } if (params.enable_single_input_eval) { if (std::optional<SplitCondition::InputSignature> input_signature = GetSingleInputSignature(tree)) { if (single_input_builder.IsInputTypeSupported(input_signature->type)) { RETURN_IF_ERROR(single_input_builder.AddTree(tree, *input_signature, tree2group[i])); continue; } } } if (params.enable_bitmask_eval && std::all_of(tree.split_nodes.begin(), tree.split_nodes.end(), BitmaskBuilder::IsSplitNodeSupported)) { auto oblivious = ToObliviousTree(tree); if (oblivious.has_value() && (oblivious->layer_splits.size() <= BitmaskBuilder::kMaxRegionsForBitmask)) { bitmask_builder.AddObliviousTree(std::move(*oblivious), tree2group[i]); continue; } if (tree.adjustments.size() <= BitmaskBuilder::kMaxRegionsForBitmask) { bitmask_builder.AddSmallTree(tree, tree2group[i]); continue; } } if (params.enable_regular_eval) { RETURN_IF_ERROR(regular_builder.AddTree(tree, tree2group[i])); } else { return absl::InvalidArgumentError( "No suitable evaluator. Use enable_regular_eval=true."); } } for (int group_id = 0; group_id < consts.size(); ++group_id) { for (const auto& [submodel_id, value] : consts[group_id]) { DecisionTree tree; tree.adjustments = {static_cast<float>(value)}; tree.tag.submodel_id = submodel_id; RETURN_IF_ERROR(regular_builder.AddTree(tree, group_id)); } } ASSIGN_OR_RETURN(auto regular_predictors, std::move(regular_builder).Build()); ASSIGN_OR_RETURN(auto bitmask_predictor, std::move(bitmask_builder).Build()); ASSIGN_OR_RETURN(auto single_input_predictor, std::move(single_input_builder).Build()); return ForestEvaluator(std::move(output_slots), std::move(regular_predictors), std::move(bitmask_predictor), std::move(single_input_predictor)); } void ForestEvaluator::Eval(const ConstFramePtr input_ctx, FramePtr output_ctx) const { for (size_t i = 0; i < output_slots_.size(); ++i) { *output_ctx.GetMutable(output_slots_[i]) = regular_predictors_[i].Predict(input_ctx); } if (bitmask_predictor_) { bitmask_predictor_->IncrementalEval(input_ctx, output_ctx); } single_input_predictor_.IncrementalEval(input_ctx, output_ctx); } }
#include "arolla/decision_forest/pointwise_evaluation/forest_evaluator.h" #include <cmath> #include <cstdint> #include <limits> #include <memory> #include <string> #include <utility> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/random/distributions.h" #include "absl/random/random.h" #include "absl/status/status.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" #include "absl/types/span.h" #include "arolla/decision_forest/decision_forest.h" #include "arolla/decision_forest/split_condition.h" #include "arolla/decision_forest/split_conditions/interval_split_condition.h" #include "arolla/decision_forest/split_conditions/set_of_values_split_condition.h" #include "arolla/decision_forest/testing/test_util.h" #include "arolla/memory/frame.h" #include "arolla/memory/memory_allocation.h" #include "arolla/memory/optional_value.h" #include "arolla/qtype/optional_qtype.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/typed_slot.h" #include "arolla/util/bytes.h" #include "arolla/util/testing/status_matchers_backport.h" namespace arolla { namespace { using ::arolla::testing::StatusIs; using ::testing::HasSubstr; constexpr float kInf = std::numeric_limits<float>::infinity(); constexpr auto S = DecisionTreeNodeId::SplitNodeId; constexpr auto A = DecisionTreeNodeId::AdjustmentId; const ForestEvaluator::CompilationParams kDefaultEval{ .enable_regular_eval = true, .enable_bitmask_eval = true, .enable_single_input_eval = true}; const ForestEvaluator::CompilationParams kRegularEval{ .enable_regular_eval = true, .enable_bitmask_eval = false, .enable_single_input_eval = false}; const ForestEvaluator::CompilationParams kBitmaskEval{ .enable_regular_eval = false, .enable_bitmask_eval = true, .enable_single_input_eval = false}; const ForestEvaluator::CompilationParams kSingleInputEval{ .enable_regular_eval = false, .enable_bitmask_eval = false, .enable_single_input_eval = true}; void FillArgs(FramePtr ctx, int row_id, absl::Span<const TypedSlot> slots) {} template <typename T, typename... Tn> void FillArgs(FramePtr frame, int row_id, absl::Span<const TypedSlot> slots, const std::vector<OptionalValue<T>>& inputs1, const std::vector<OptionalValue<Tn>>&... inputsN) { auto slot = slots[0].ToSlot<OptionalValue<T>>().value(); frame.Set(slot, inputs1[row_id]); FillArgs(frame, row_id, slots.subspan(1), inputsN...); } class SourceLocation { public: SourceLocation(int line, const char* filename) : line_(line), file_name_(filename) {} const char* file_name() { return file_name_.c_str(); } constexpr int line() const { return line_; } static SourceLocation current(int line = __builtin_LINE(), const char* file_name = __builtin_FILE()) { return SourceLocation(line, file_name); } private: int line_ = 0; std::string file_name_; }; std::string ErrFormat(SourceLocation loc, ForestEvaluator::CompilationParams params, const std::string& msg, int row_id) { return absl::StrFormat( "%s Test at %s:%d, row_id=%d, params = " "{enable_regular_eval=%d, enable_bitmask_eval=%d, " "enable_single_input_eval=%d}", msg, loc.file_name(), loc.line(), row_id, params.enable_regular_eval, params.enable_bitmask_eval, params.enable_single_input_eval); } template <typename... T> void TestCases(SourceLocation loc, const DecisionForest& forest, absl::Span<const TreeFilter> groups, ForestEvaluator::CompilationParams params, absl::Span<const std::vector<float>> expected_outputs, const std::vector<OptionalValue<T>>&... inputs) { ASSERT_TRUE(((expected_outputs.size() == inputs.size()) && ...)) << absl::StrCat( "Input and output vector sizes are different: (", absl::StrJoin({expected_outputs.size(), inputs.size()...}, ", "), ")"); std::vector<TypedSlot> input_slots; std::vector<ForestEvaluator::Output> outputs; FrameLayout::Builder layout_builder; CreateSlotsForForest(forest, &layout_builder, &input_slots); outputs.reserve(groups.size()); for (const TreeFilter& filter : groups) { outputs.push_back({filter, layout_builder.AddSlot<float>()}); } FrameLayout layout = std::move(layout_builder).Build(); ASSERT_OK_AND_ASSIGN( auto evaluator, ForestEvaluator::Compile(forest, input_slots, outputs, params)); MemoryAllocation alloc(&layout); auto frame = alloc.frame(); for (int i = 0; i < expected_outputs.size(); ++i) { FillArgs(frame, i, input_slots, inputs...); evaluator.Eval(frame, frame); for (int j = 0; j < outputs.size(); ++j) { EXPECT_EQ(frame.Get(outputs[j].slot), expected_outputs[i][j]) << ErrFormat(loc, params, "Incorrect output.", i); } } } void RandomTestAgainstReferenceImplementation( SourceLocation loc, std::vector<DecisionTree> trees, const std::vector<ForestEvaluator::CompilationParams>& params, absl::BitGen* rnd) { for (int i = 0; i < trees.size(); ++i) { trees[i].tag.submodel_id = i % 4; } TreeFilter group0{.submodels{0, 3}}; TreeFilter group1{.submodels{1, 2}}; ASSERT_OK_AND_ASSIGN(auto forest, DecisionForest::FromTrees(std::move(trees))); std::vector<TypedSlot> input_slots; std::vector<ForestEvaluator::Output> outputs; FrameLayout::Builder layout_builder; CreateSlotsForForest(*forest, &layout_builder, &input_slots); outputs.push_back({group0, layout_builder.AddSlot<float>()}); outputs.push_back({group1, layout_builder.AddSlot<float>()}); FrameLayout layout = std::move(layout_builder).Build(); std::vector<ForestEvaluator> evaluators; for (auto p : params) { ASSERT_OK_AND_ASSIGN(auto evaluator, ForestEvaluator::Compile( *forest, input_slots, outputs, p)); evaluators.push_back(std::move(evaluator)); } MemoryAllocation alloc(&layout); FramePtr frame = alloc.frame(); for (int item_id = 0; item_id < 15; ++item_id) { for (auto slot : input_slots) { ASSERT_OK(FillWithRandomValue(slot, frame, rnd, 0.25)); } float reference_implementation_res0 = DecisionForestNaiveEvaluation(*forest, frame, input_slots, group0); float reference_implementation_res1 = DecisionForestNaiveEvaluation(*forest, frame, input_slots, group1); for (int eval_id = 0; eval_id < evaluators.size(); ++eval_id) { const ForestEvaluator& evaluator = evaluators[eval_id]; frame.Set(outputs[0].slot, 0.0f); frame.Set(outputs[1].slot, 0.0f); evaluator.Eval(frame, frame); EXPECT_FLOAT_EQ(reference_implementation_res0, frame.Get(outputs[0].slot)) << ErrFormat(loc, params[eval_id], "Incorrect output #0 in Eval", item_id); EXPECT_FLOAT_EQ(reference_implementation_res1, frame.Get(outputs[1].slot)) << ErrFormat(loc, params[eval_id], "Incorrect output #1 in Eval", item_id); } } } TEST(ForestEvaluator, GroupsValidation) { std::vector<DecisionTree> trees(3); trees[0].tag.submodel_id = 3; trees[0].adjustments = {1.0}; trees[1].tag.submodel_id = 2; trees[1].adjustments = {1.0}; trees[2].tag.submodel_id = 1; trees[2].adjustments = {1.0}; ASSERT_OK_AND_ASSIGN(auto forest, DecisionForest::FromTrees(std::move(trees))); EXPECT_THAT(ForestEvaluator::Compile(*forest, {}, {}).status(), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("at least one output is expected"))); auto fake_slot = FrameLayout::Slot<float>::UnsafeUninitializedSlot(); EXPECT_THAT( ForestEvaluator::Compile( *forest, {}, {ForestEvaluator::Output{{.submodels = {1, 3}}, fake_slot}, ForestEvaluator::Output{{.submodels = {2, 3}}, fake_slot}}) .status(), StatusIs( absl::StatusCode::kInvalidArgument, HasSubstr( "intersection of groups for outputs #0 and #1 is not empty"))); EXPECT_OK(ForestEvaluator::Compile( *forest, {}, {ForestEvaluator::Output{{.submodels = {1, 3}}, fake_slot}, ForestEvaluator::Output{{.submodels = {2}}, fake_slot}}) .status()); EXPECT_OK(ForestEvaluator::Compile( *forest, {}, {ForestEvaluator::Output{{.submodels = {1}}, fake_slot}, ForestEvaluator::Output{{.submodels = {2}}, fake_slot}}) .status()); } TEST(ForestEvaluator, EmptyForest) { ASSERT_OK_AND_ASSIGN(auto forest, DecisionForest::FromTrees({})); for (auto params : {kDefaultEval, kRegularEval, kBitmaskEval, kSingleInputEval}) { TestCases<>(SourceLocation::current(), *forest, {{.submodels = {0}}, {.submodels = {1}}}, params, {{0.0, 0.0}}); } } TEST(ForestEvaluator, Constant) { std::vector<DecisionTree> trees(2); trees[0].tag = {.submodel_id = 0}; trees[0].adjustments = {1.5}; trees[1].tag = {.submodel_id = 1}; trees[1].adjustments = {2.5}; ASSERT_OK_AND_ASSIGN(auto forest, DecisionForest::FromTrees(std::move(trees))); for (auto params : {kDefaultEval, kRegularEval, kBitmaskEval}) { TestCases<>(SourceLocation::current(), *forest, {{.submodels = {0}}, {.submodels = {1}}}, params, {{1.5, 2.5}}); } } TEST(ForestEvaluator, SmallForest) { std::vector<DecisionTree> trees(2); trees[0].tag = {.submodel_id = 0}; trees[0].adjustments = {0.5, 1.5, 2.5, 3.5}; trees[0].split_nodes = { {S(1), S(2), IntervalSplit(0, 1.5, kInf)}, {A(0), A(2), SetOfValuesSplit<int64_t>(1, {1, 2}, false)}, {A(1), A(3), IntervalSplit(0, -kInf, 10)}}; trees[1].tag = {.submodel_id = 1}; trees[1].adjustments = {-1.0, 1.0}; trees[1].split_nodes = {{A(0), A(1), IntervalSplit(0, 1, 5)}}; ASSERT_OK_AND_ASSIGN(auto forest, DecisionForest::FromTrees(std::move(trees))); for (auto params : {kDefaultEval, kRegularEval, kBitmaskEval}) { TestCases<float, int64_t>( SourceLocation::current(), *forest, {{.submodels = {0}}, {.submodels = {1}}}, params, {{0.5, -1}, {2.5, -1}, {2.5, 1}, {3.5, 1}, {3.5, -1}, {1.5, -1}, {2.5, -1}, {0.5, -1}}, {0, 0, 1.2, 1.6, 7.0, 13.5, NAN, {}}, {3, 1, 1, 1, 1, 1, 1, {}}); } } TEST(ForestEvaluator, RangesSplits) { DecisionTree tree; tree.split_nodes = {{S(2), S(1), IntervalSplit(0, -1.0, 1.0)}, {A(1), A(2), IntervalSplit(0, 0.5, 0.5)}, {A(0), A(3), IntervalSplit(0, 2.5, 3.5)}}; tree.adjustments = {0.0, 1.0, 2.0, 3.0}; ASSERT_OK_AND_ASSIGN(auto forest, DecisionForest::FromTrees({tree})); for (auto params : {kDefaultEval, kRegularEval, kBitmaskEval, kSingleInputEval}) { TestCases<float>( SourceLocation::current(), *forest, {{}}, params, {{0}, {0}, {0}, {1}, {2}, {3}, {3}, {3}}, {{}, -5, 5, -1, 0.5, 2.5, 3.0, 3.5}); } } TEST(ForestEvaluator, EqualSplits) { DecisionTree tree; tree.split_nodes = {{S(2), S(1), IntervalSplit(0, 1.0, 1.0)}, {A(1), A(2), IntervalSplit(1, 5.0, 5.0)}, {A(0), A(3), IntervalSplit(1, -5.0, -5.0)}}; tree.adjustments = {0.0, 1.0, 2.0, 3.0}; ASSERT_OK_AND_ASSIGN(auto forest, DecisionForest::FromTrees({tree})); for (auto params : {kDefaultEval, kRegularEval, kBitmaskEval}) { TestCases<float, float>( SourceLocation::current(), *forest, {{}}, params, {{0}, {0}, {0}, {1}, {1}, {2}, {3}, {3}}, {{}, 0.0, -5.0, 1.0, 1.0, 1.0, 0.0, {}}, {{}, {}, {}, {}, -5.0, +5.0, -5.0, -5.0}); } } TEST(ForestEvaluator, BytesInput) { DecisionTree tree; tree.split_nodes = { {A(0), A(1), SetOfValuesSplit<Bytes>(0, {Bytes("X")}, false)}}; tree.adjustments = {0.0, 1.0}; ASSERT_OK_AND_ASSIGN(auto forest, DecisionForest::FromTrees({tree})); for (auto params : {kDefaultEval, kRegularEval}) { TestCases<Bytes>(SourceLocation::current(), *forest, {{}}, params, {{0}, {1}, {0}}, {{}, Bytes("X"), Bytes("Y")}); } } TEST(ForestEvaluator, BitmaskNotPossible) { absl::BitGen rnd; auto forest = CreateRandomForest(&rnd, 10, true, 70, 70, 1); std::vector<TypedSlot> slots; FrameLayout::Builder layout_builder; CreateSlotsForForest(*forest, &layout_builder, &slots); EXPECT_THAT( SimpleForestEvaluator::Compile(*forest, slots, kBitmaskEval), StatusIs( absl::StatusCode::kInvalidArgument, HasSubstr("No suitable evaluator. Use enable_regular_eval=true."))); } TEST(ForestEvaluator, SingleInputEvalNotPossible) { DecisionTree tree; tree.split_nodes = {{S(2), S(1), IntervalSplit(0, 1.0, 1.0)}, {A(1), A(2), IntervalSplit(1, 5.0, 5.0)}, {A(0), A(3), IntervalSplit(1, -5.0, -5.0)}}; tree.adjustments = {0.0, 1.0, 2.0, 3.0}; ASSERT_OK_AND_ASSIGN(auto forest, DecisionForest::FromTrees({tree})); std::vector<TypedSlot> slots; FrameLayout::Builder layout_builder; CreateSlotsForForest(*forest, &layout_builder, &slots); EXPECT_THAT( SimpleForestEvaluator::Compile(*forest, slots, kSingleInputEval), StatusIs( absl::StatusCode::kInvalidArgument, HasSubstr("No suitable evaluator. Use enable_regular_eval=true."))); } TEST(ForestEvaluator, ObliviousTree) { DecisionTree tree; std::vector<std::shared_ptr<SplitCondition>> conditions = { IntervalSplit(0, -5, 5), IntervalSplit(1, 0, kInf), SetOfValuesSplit<int64_t>(2, {1, 2}, false), IntervalSplit(3, -kInf, 3.0), SetOfValuesSplit<int64_t>(4, {4, 2}, true), IntervalSplit(5, -1, 7), IntervalSplit(6, -kInf, -5)}; int layer_size = 1; for (int layer = 0; layer < conditions.size(); ++layer) { int layer_offset = tree.split_nodes.size() + layer_size; for (int i = 0; i < layer_size; ++i) { auto left = (layer == conditions.size() - 1) ? A(i * 2) : S(layer_offset + i * 2); auto right = (layer == conditions.size() - 1) ? A(i * 2 + 1) : S(layer_offset + i * 2 + 1); tree.split_nodes.push_back({left, right, conditions[layer]}); } layer_size *= 2; } for (int i = 0; i < layer_size; ++i) { tree.adjustments.push_back(i); } ASSERT_OK_AND_ASSIGN(auto forest, DecisionForest::FromTrees({tree})); for (auto params : {kDefaultEval, kRegularEval, kBitmaskEval}) { TestCases<float, float, int64_t, float, int64_t, float, float>( SourceLocation::current(), *forest, {{}}, params, {{58}, {86}, {12}, {39}, {112}}, {{}, 3, -7, 15, -4}, {10, -1, {}, 25, 1}, {2, 1, 3, {}, 1}, {0, {}, -5, 8, 14}, {1, 2, {}, 4, 5}, {0, 4, -3, 7, {}}, {10, 5, -3, -8, {}}); } } TEST(ForestEvaluator, TestAgainstReferenceOnSmallTrees) { absl::BitGen rnd; std::vector<QTypePtr> types; for (int input_id = 0; input_id < 10; input_id++) { types.push_back(GetOptionalQType<float>()); } for (int input_id = 10; input_id < 15; input_id++) { types.push_back(GetOptionalQType<int64_t>()); } for (int iteration = 0; iteration < 10; ++iteration) { std::vector<DecisionTree> trees; for (int i = 0; i < 10; ++i) { int num_splits = absl::Uniform<int32_t>(rnd, 0, 32); trees.push_back( CreateRandomTree(&rnd, true, num_splits, &types)); } RandomTestAgainstReferenceImplementation( SourceLocation::current(), trees, {kDefaultEval, kRegularEval, kBitmaskEval}, &rnd); } } TEST(ForestEvaluator, TestAgainstReferenceOnSingleInputTrees) { absl::BitGen rnd; std::vector<QTypePtr> types; for (int input_id = 0; input_id < 10; input_id++) { types.push_back(GetOptionalQType<float>()); } for (int input_id = 10; input_id < 15; input_id++) { types.push_back(GetOptionalQType<int64_t>()); } for (int iteration = 0; iteration < 10; ++iteration) { std::vector<DecisionTree> trees; for (int i = 0; i < 10; ++i) { int num_splits = absl::Uniform<int32_t>(rnd, 1, 1024); trees.push_back( CreateRandomTree(&rnd, false, num_splits, &types)); } RandomTestAgainstReferenceImplementation( SourceLocation::current(), trees, {kDefaultEval, kRegularEval, kSingleInputEval}, &rnd); } } TEST(ForestEvaluator, TestAgainstReference) { absl::BitGen rnd; std::vector<QTypePtr> types; for (int feature_id = 0; feature_id < 10; feature_id++) { types.push_back(GetOptionalQType<float>()); } for (int feature_id = 10; feature_id < 15; feature_id++) { types.push_back(GetOptionalQType<int64_t>()); } for (int iteration = 0; iteration < 5; ++iteration) { std::vector<DecisionTree> trees; for (int i = 0; i < 10; ++i) { int num_splits = absl::Uniform<int32_t>(rnd, 0, 1024); trees.push_back( CreateRandomTree(&rnd, true, num_splits, &types)); } for (int i = 0; i < 10; ++i) { int num_splits = absl::Uniform<int32_t>(rnd, 0, 1024); trees.push_back( CreateRandomTree(&rnd, false, num_splits, &types)); } for (int i = 0; i < 10; ++i) { int num_splits = absl::Uniform<int32_t>(rnd, 0, 1024); trees.push_back(CreateRandomFloatTree( &rnd, 10, true, num_splits, 0.4, 0.4)); } for (int i = 0; i < 10; ++i) { int num_splits = absl::Uniform<int32_t>(rnd, 0, 32); trees.push_back( CreateRandomTree(&rnd, true, num_splits, &types)); } for (int i = 0; i < 5; ++i) { int depth = absl::Uniform<int32_t>(rnd, 1, 20); trees.push_back(CreateRandomObliviousTree(&rnd, depth, &types)); } RandomTestAgainstReferenceImplementation( SourceLocation::current(), trees, {kDefaultEval, kRegularEval}, &rnd); } } } }
2,387
cpp
google/arolla
oblivious
arolla/decision_forest/pointwise_evaluation/oblivious.cc
arolla/decision_forest/pointwise_evaluation/oblivious_test.cc
#ifndef AROLLA_DECISION_FOREST_POINTWISE_EVALUATION_OBLIVIOUS_H_ #define AROLLA_DECISION_FOREST_POINTWISE_EVALUATION_OBLIVIOUS_H_ #include <memory> #include <optional> #include <vector> #include "arolla/decision_forest/decision_forest.h" #include "arolla/decision_forest/split_condition.h" namespace arolla { struct ObliviousDecisionTree { DecisionTree::Tag tag; std::vector<std::shared_ptr<const SplitCondition>> layer_splits; std::vector<float> adjustments; }; std::optional<ObliviousDecisionTree> ToObliviousTree(const DecisionTree& tree); } #endif #include "arolla/decision_forest/pointwise_evaluation/oblivious.h" #include <cstddef> #include <memory> #include <optional> #include <utility> #include <vector> #include "absl/log/check.h" #include "arolla/decision_forest/decision_forest.h" #include "arolla/decision_forest/split_condition.h" namespace arolla { namespace { bool IsPowerOf2(size_t x) { return (x & (x - 1)) == 0; } struct StackEntry { DecisionTreeNodeId node_id; int depth; }; template <typename CallbackFn> bool TraverseTree(const DecisionTree& tree, CallbackFn callback) { std::vector<StackEntry> stack; stack.reserve(32); stack.push_back(StackEntry{GetTreeRootId(tree), 0}); while (!stack.empty()) { auto [node_id, depth] = stack.back(); stack.pop_back(); if (!callback(node_id, depth)) { return false; } if (!node_id.is_leaf()) { const auto& node = tree.split_nodes[node_id.split_node_index()]; stack.push_back(StackEntry{node.child_if_true, depth + 1}); stack.push_back(StackEntry{node.child_if_false, depth + 1}); } } return true; } } std::optional<ObliviousDecisionTree> ToObliviousTree(const DecisionTree& tree) { size_t region_count = tree.adjustments.size(); if (!IsPowerOf2(region_count)) { return std::nullopt; } size_t depth = region_count ? __builtin_ctz(region_count) : 0; std::vector<std::shared_ptr<const SplitCondition>> layer_splits; layer_splits.reserve(depth); std::vector<float> adjustments; adjustments.reserve(region_count); auto process_node = [&](DecisionTreeNodeId node_id, int current_depth) { if (node_id.is_leaf()) { if (current_depth != depth) { return false; } adjustments.push_back(tree.adjustments[node_id.adjustment_index()] * tree.weight); } else { if (current_depth >= depth) { return false; } const auto& node = tree.split_nodes[node_id.split_node_index()]; if (layer_splits.size() == current_depth) { layer_splits.push_back(node.condition); } else { DCHECK_LT(current_depth, layer_splits.size()); if (*layer_splits[current_depth] != *node.condition) { return false; } } } return true; }; if (!TraverseTree(tree, process_node)) { return std::nullopt; } return ObliviousDecisionTree{tree.tag, std::move(layer_splits), std::move(adjustments)}; } }
#include "arolla/decision_forest/pointwise_evaluation/oblivious.h" #include <limits> #include <memory> #include <optional> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "arolla/decision_forest/decision_forest.h" #include "arolla/decision_forest/split_condition.h" #include "arolla/decision_forest/split_conditions/interval_split_condition.h" namespace arolla { namespace { using ::testing::ElementsAre; constexpr auto S = DecisionTreeNodeId::SplitNodeId; constexpr auto A = DecisionTreeNodeId::AdjustmentId; constexpr float inf = std::numeric_limits<float>::infinity(); std::shared_ptr<SplitCondition> Cond(int input_id, float left, float right) { return std::make_shared<IntervalSplitCondition>(input_id, left, right); } TEST(ObliviousTest, Errors) { { DecisionTree tree; tree.split_nodes = {{A(0), S(1), Cond(0, -inf, 1.0)}, {A(1), A(2), Cond(0, -1.0, inf)}}; tree.adjustments = {0.0, 1.0, 2.0}; EXPECT_EQ(ToObliviousTree(tree), std::nullopt); } { DecisionTree tree; tree.split_nodes = {{A(0), S(1), Cond(0, -inf, 1.0)}, {S(2), A(2), Cond(0, -1.0, inf)}, {A(1), A(3), Cond(0, -1.0, inf)}}; tree.adjustments = {0.0, 1.0, 2.0, 3.0}; EXPECT_EQ(ToObliviousTree(tree), std::nullopt); } { DecisionTree tree; tree.split_nodes = {{S(2), S(1), Cond(0, -inf, 1.0)}, {A(1), A(2), Cond(0, -1.0, inf)}, {A(0), A(3), Cond(0, 1.0, inf)}}; tree.adjustments = {0.0, 1.0, 2.0, 3.0}; EXPECT_EQ(ToObliviousTree(tree), std::nullopt); } } TEST(ObliviousTest, Ok) { { DecisionTree tree; tree.adjustments = {2.0}; tree.weight = 0.5; auto oblivious_tree = ToObliviousTree(tree); ASSERT_TRUE(oblivious_tree.has_value()); EXPECT_THAT(oblivious_tree->layer_splits, ElementsAre()); EXPECT_THAT(oblivious_tree->adjustments, ElementsAre(1.0)); } { DecisionTree tree; tree.split_nodes = {{A(0), A(1), Cond(0, -inf, 1.0)}}; tree.adjustments = {7.0, 3.0}; tree.weight = 2.0; auto oblivious_tree = ToObliviousTree(tree); ASSERT_TRUE(oblivious_tree.has_value()); EXPECT_EQ(oblivious_tree->layer_splits.size(), 1); EXPECT_EQ(*oblivious_tree->layer_splits[0], *Cond(0, -inf, 1.0)); EXPECT_THAT(oblivious_tree->adjustments, ElementsAre(14.0, 6.0)); } { DecisionTree tree; tree.split_nodes = {{S(2), S(1), Cond(0, -inf, 1.0)}, {A(1), A(2), Cond(0, -1.0, inf)}, {A(0), A(3), Cond(0, -1.0, inf)}}; tree.adjustments = {0.0, 1.0, 2.0, 3.0}; auto oblivious_tree = ToObliviousTree(tree); ASSERT_TRUE(oblivious_tree.has_value()); EXPECT_EQ(oblivious_tree->layer_splits.size(), 2); EXPECT_EQ(*oblivious_tree->layer_splits[0], *Cond(0, -inf, 1.0)); EXPECT_EQ(*oblivious_tree->layer_splits[1], *Cond(0, -1.0, inf)); EXPECT_THAT(oblivious_tree->adjustments, ElementsAre(0.0, 3.0, 1.0, 2.0)); } } } }
2,388
cpp
google/arolla
batched_forest_evaluator
arolla/decision_forest/batched_evaluation/batched_forest_evaluator.cc
arolla/decision_forest/batched_evaluation/batched_forest_evaluator_test.cc
#ifndef AROLLA_DECISION_FOREST_BATCHED_EVALUATION_BATCHED_FOREST_EVALUATOR_H_ #define AROLLA_DECISION_FOREST_BATCHED_EVALUATION_BATCHED_FOREST_EVALUATOR_H_ #include <algorithm> #include <cstdint> #include <memory> #include <optional> #include <utility> #include <vector> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/types/span.h" #include "arolla/decision_forest/decision_forest.h" #include "arolla/decision_forest/pointwise_evaluation/forest_evaluator.h" #include "arolla/memory/frame.h" #include "arolla/memory/raw_buffer_factory.h" #include "arolla/qtype/typed_ref.h" #include "arolla/qtype/typed_slot.h" #include "arolla/util/indestructible.h" #include "arolla/util/threading.h" namespace arolla { class BatchedForestEvaluator { public: struct CompilationParams { static constexpr CompilationParams Default() { return {}; } int64_t optimal_splits_per_evaluator = 500000; }; struct SlotMapping { int input_index; TypedSlot pointwise_slot; }; static absl::StatusOr<std::unique_ptr<BatchedForestEvaluator>> Compile( const DecisionForest& decision_forest, absl::Span<const TreeFilter> groups = {{}}, const CompilationParams& params = CompilationParams::Default()); absl::Status EvalBatch(absl::Span<const TypedSlot> input_slots, absl::Span<const TypedSlot> output_slots, FramePtr frame, RawBufferFactory* = GetHeapBufferFactory(), std::optional<int64_t> row_count = {}) const; static void SetThreading(std::unique_ptr<ThreadingInterface> threading, int64_t min_rows_per_thread = 128) { *threading_ = std::move(threading); min_rows_per_thread_ = min_rows_per_thread; } private: static ::arolla::Indestructible<std::unique_ptr<ThreadingInterface>> threading_; static int64_t min_rows_per_thread_; BatchedForestEvaluator(FrameLayout&& pointwise_layout, std::vector<SlotMapping>&& input_mapping, std::vector<TypedSlot>&& output_pointwise_slots, std::vector<ForestEvaluator>&& pointwise_evaluators) : pointwise_layout_(std::move(pointwise_layout)), input_mapping_(std::move(input_mapping)), output_pointwise_slots_(output_pointwise_slots), pointwise_evaluators_(std::move(pointwise_evaluators)) { input_pointwise_slots_.reserve(input_mapping_.size()); input_count_ = 0; for (const auto& m : input_mapping_) { input_pointwise_slots_.push_back(m.pointwise_slot); input_count_ = std::max(input_count_, m.input_index + 1); } } absl::Status GetInputsFromSlots(absl::Span<const TypedSlot> input_slots, ConstFramePtr frame, std::vector<TypedRef>* input_arrays) const; FrameLayout pointwise_layout_; std::vector<SlotMapping> input_mapping_; std::vector<TypedSlot> input_pointwise_slots_; std::vector<TypedSlot> output_pointwise_slots_; int input_count_; std::vector<ForestEvaluator> pointwise_evaluators_; }; } #endif #include "arolla/decision_forest/batched_evaluation/batched_forest_evaluator.h" #include <algorithm> #include <cstdint> #include <memory> #include <optional> #include <utility> #include <vector> #include "absl/log/check.h" #include "absl/memory/memory.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "absl/types/span.h" #include "arolla/array/array.h" #include "arolla/array/qtype/types.h" #include "arolla/decision_forest/decision_forest.h" #include "arolla/decision_forest/pointwise_evaluation/forest_evaluator.h" #include "arolla/dense_array/dense_array.h" #include "arolla/dense_array/qtype/types.h" #include "arolla/memory/buffer.h" #include "arolla/memory/frame.h" #include "arolla/memory/raw_buffer_factory.h" #include "arolla/qtype/array_like/array_like_qtype.h" #include "arolla/qtype/array_like/frame_iter.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/typed_ref.h" #include "arolla/qtype/typed_slot.h" #include "arolla/qtype/typed_value.h" #include "arolla/util/indestructible.h" #include "arolla/util/threading.h" #include "arolla/util/status_macros_backport.h" namespace arolla { namespace { absl::StatusOr<TypedValue> AddFullFloatArrays(TypedRef a, TypedRef b) { if (a.GetType() == GetDenseArrayQType<float>() && b.GetType() == GetDenseArrayQType<float>()) { const auto& va = a.UnsafeAs<DenseArray<float>>(); const auto& vb = b.UnsafeAs<DenseArray<float>>(); DCHECK_EQ(va.size(), vb.size()); DCHECK(va.IsFull() && vb.IsFull()); Buffer<float>::Builder bldr(va.size()); auto sa = va.values.span(); auto sb = vb.values.span(); auto sr = bldr.GetMutableSpan(); for (int64_t i = 0; i < va.size(); ++i) { sr[i] = sa[i] + sb[i]; } return TypedValue::FromValue(DenseArray<float>{std::move(bldr).Build()}); } else if (a.GetType() == GetArrayQType<float>() && b.GetType() == GetArrayQType<float>()) { const auto& va = a.UnsafeAs<Array<float>>(); const auto& vb = b.UnsafeAs<Array<float>>(); DCHECK_EQ(va.size(), vb.size()); DCHECK(va.IsFullForm() && vb.IsFullForm()); Buffer<float>::Builder bldr(va.size()); auto sa = va.dense_data().values.span(); auto sb = vb.dense_data().values.span(); auto sr = bldr.GetMutableSpan(); for (int64_t i = 0; i < va.size(); ++i) { sr[i] = sa[i] + sb[i]; } return TypedValue::FromValue(Array<float>{std::move(bldr).Build()}); } else { return absl::InternalError("Invalid type in BatchedForestEvaluator/Add"); } } absl::StatusOr<std::vector<ForestEvaluator>> CreatePointwiseEvaluators( const BatchedForestEvaluator::CompilationParams& params, const DecisionForest& decision_forest, const std::vector<TypedSlot>& inputs, const std::vector<ForestEvaluator::Output>& outputs) { int64_t split_count = 0; for (const auto& tree : decision_forest.GetTrees()) { split_count += tree.split_nodes.size(); } int64_t evaluator_count = std::max<int64_t>( 1, (split_count + params.optimal_splits_per_evaluator - 1) / params.optimal_splits_per_evaluator); std::vector<ForestEvaluator> evaluators; evaluators.reserve(evaluator_count); if (evaluator_count == 1) { ASSIGN_OR_RETURN(auto evaluator, ForestEvaluator::Compile(decision_forest, inputs, outputs)); evaluators.push_back(std::move(evaluator)); return evaluators; } int64_t splits_per_evaluator = (split_count + evaluator_count - 1) / evaluator_count; int64_t estimated_trees_per_evaluator = (decision_forest.GetTrees().size() + evaluator_count - 1) / evaluator_count; std::vector<DecisionTree> trees; trees.reserve(estimated_trees_per_evaluator); int64_t current_split_count = 0; for (const auto& tree : decision_forest.GetTrees()) { trees.push_back(tree); current_split_count += tree.split_nodes.size(); if (current_split_count >= splits_per_evaluator) { ASSIGN_OR_RETURN(auto partial_forest, DecisionForest::FromTrees(std::move(trees))); ASSIGN_OR_RETURN(auto evaluator, ForestEvaluator::Compile( *partial_forest, inputs, outputs)); evaluators.push_back(std::move(evaluator)); trees.clear(); trees.reserve(estimated_trees_per_evaluator); current_split_count = 0; } } if (!trees.empty()) { ASSIGN_OR_RETURN(auto partial_forest, DecisionForest::FromTrees(std::move(trees))); ASSIGN_OR_RETURN(auto evaluator, ForestEvaluator::Compile(*partial_forest, inputs, outputs)); evaluators.push_back(std::move(evaluator)); } return evaluators; } } Indestructible<std::unique_ptr<ThreadingInterface>> BatchedForestEvaluator::threading_; int64_t BatchedForestEvaluator::min_rows_per_thread_; absl::StatusOr<std::unique_ptr<BatchedForestEvaluator>> BatchedForestEvaluator::Compile(const DecisionForest& decision_forest, absl::Span<const TreeFilter> groups, const CompilationParams& params) { FrameLayout::Builder bldr; std::vector<SlotMapping> input_slots_mapping; TypedSlot placeholder = TypedSlot::FromSlot(FrameLayout::Slot<float>::UnsafeUninitializedSlot()); std::vector<TypedSlot> input_pointwise_slots; for (const auto& kv : decision_forest.GetRequiredQTypes()) { TypedSlot pointwise_slot = AddSlot(kv.second, &bldr); while (input_pointwise_slots.size() <= kv.first) { input_pointwise_slots.push_back(placeholder); } input_pointwise_slots[kv.first] = pointwise_slot; input_slots_mapping.push_back({kv.first, pointwise_slot}); } std::vector<ForestEvaluator::Output> pointwise_outputs; std::vector<TypedSlot> output_pointwise_slots; pointwise_outputs.reserve(groups.size()); output_pointwise_slots.reserve(groups.size()); for (const TreeFilter& filter : groups) { auto slot = bldr.AddSlot<float>(); pointwise_outputs.push_back({filter, slot}); output_pointwise_slots.push_back(TypedSlot::FromSlot(slot)); } auto pointwise_layout = std::move(bldr).Build(); ASSIGN_OR_RETURN( std::vector<ForestEvaluator> pointwise_evaluators, CreatePointwiseEvaluators(params, decision_forest, input_pointwise_slots, pointwise_outputs)); return absl::WrapUnique(new BatchedForestEvaluator( std::move(pointwise_layout), std::move(input_slots_mapping), std::move(output_pointwise_slots), std::move(pointwise_evaluators))); } absl::Status BatchedForestEvaluator::GetInputsFromSlots( absl::Span<const TypedSlot> input_slots, ConstFramePtr frame, std::vector<TypedRef>* input_arrays) const { if (input_slots.size() < input_count_) { return absl::InvalidArgumentError( absl::StrFormat("not enough inputs: at least %d expected, %d found", input_count_, input_slots.size())); } for (auto m : input_mapping_) { input_arrays->push_back( TypedRef::FromSlot(input_slots[m.input_index], frame)); } return absl::OkStatus(); } absl::Status BatchedForestEvaluator::EvalBatch( absl::Span<const TypedSlot> input_slots, absl::Span<const TypedSlot> output_slots, FramePtr frame, RawBufferFactory* buffer_factory, std::optional<int64_t> row_count) const { std::vector<TypedRef> input_arrays; input_arrays.reserve(input_mapping_.size()); RETURN_IF_ERROR(GetInputsFromSlots(input_slots, frame, &input_arrays)); if (!row_count.has_value()) { if (!input_arrays.empty()) { ASSIGN_OR_RETURN(row_count, GetArraySize(input_arrays[0])); } else if (!input_slots.empty()) { ASSIGN_OR_RETURN(row_count, GetArraySize(TypedRef::FromSlot(input_slots[0], frame))); } } int thread_count = 1; auto run_evaluator = [&](const ForestEvaluator& eval) -> absl::Status { ASSIGN_OR_RETURN( auto frame_iterator, FrameIterator::Create( input_arrays, {input_pointwise_slots_.data(), input_arrays.size()}, output_slots, output_pointwise_slots_, &pointwise_layout_, FrameIterator::Options{.row_count = row_count, .frame_buffer_count = 64 * thread_count, .buffer_factory = buffer_factory})); if (thread_count > 1) { frame_iterator.ForEachFrame([&eval](FramePtr f) { eval.Eval(f, f); }, **threading_, thread_count); } else { frame_iterator.ForEachFrame([&eval](FramePtr f) { eval.Eval(f, f); }); } return frame_iterator.StoreOutput(frame); }; if (pointwise_evaluators_.size() == 1) { return run_evaluator(pointwise_evaluators_.front()); } else { std::vector<TypedValue> res_sum; res_sum.reserve(output_slots.size()); RETURN_IF_ERROR(run_evaluator(pointwise_evaluators_.front())); for (const auto& s : output_slots) { res_sum.push_back(TypedValue::FromSlot(s, frame)); } for (int eval_id = 1; eval_id < pointwise_evaluators_.size() - 1; ++eval_id) { RETURN_IF_ERROR(run_evaluator(pointwise_evaluators_[eval_id])); for (int i = 0; i < output_slots.size(); ++i) { ASSIGN_OR_RETURN( res_sum[i], AddFullFloatArrays(res_sum[i].AsRef(), TypedRef::FromSlot(output_slots[i], frame))); } } RETURN_IF_ERROR(run_evaluator(pointwise_evaluators_.back())); for (int i = 0; i < output_slots.size(); ++i) { ASSIGN_OR_RETURN( TypedValue full_sum, AddFullFloatArrays(res_sum[i].AsRef(), TypedRef::FromSlot(output_slots[i], frame))); RETURN_IF_ERROR(full_sum.CopyToSlot(output_slots[i], frame)); } return absl::OkStatus(); } } }
#include "arolla/decision_forest/batched_evaluation/batched_forest_evaluator.h" #include <cmath> #include <cstdint> #include <limits> #include <memory> #include <utility> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/random/distributions.h" #include "absl/random/random.h" #include "absl/status/statusor.h" #include "arolla/array/array.h" #include "arolla/array/qtype/types.h" #include "arolla/decision_forest/decision_forest.h" #include "arolla/decision_forest/split_conditions/interval_split_condition.h" #include "arolla/decision_forest/split_conditions/set_of_values_split_condition.h" #include "arolla/decision_forest/testing/test_util.h" #include "arolla/dense_array/dense_array.h" #include "arolla/dense_array/qtype/types.h" #include "arolla/memory/frame.h" #include "arolla/memory/memory_allocation.h" #include "arolla/qtype/typed_slot.h" #include "arolla/util/threading.h" namespace arolla { namespace { absl::StatusOr<DecisionForestPtr> CreateTestForest() { constexpr float kInf = std::numeric_limits<float>::infinity(); constexpr auto S = DecisionTreeNodeId::SplitNodeId; constexpr auto A = DecisionTreeNodeId::AdjustmentId; std::vector<DecisionTree> trees(2); trees[0].tag = {.submodel_id = 0}; trees[0].adjustments = {0.5, 1.5, 2.5, 3.5}; trees[0].split_nodes = { {S(1), S(2), IntervalSplit(0, 1.5, kInf)}, {A(0), A(2), SetOfValuesSplit<int64_t>(1, {1, 2}, false)}, {A(1), A(3), IntervalSplit(0, -kInf, 10)}}; trees[1].tag = {.submodel_id = 1}; trees[1].adjustments = {-1.0, 1.0}; trees[1].split_nodes = {{A(0), A(1), IntervalSplit(0, 1, 5)}}; return DecisionForest::FromTrees(std::move(trees)); } TEST(BatchedForestEvaluator, EvalBatch) { ASSERT_OK_AND_ASSIGN(auto forest, CreateTestForest()); std::vector<TreeFilter> groups{{.submodels = {0}}, {.submodels = {1}}}; ASSERT_OK_AND_ASSIGN(auto eval, BatchedForestEvaluator::Compile(*forest, groups)); FrameLayout::Builder bldr; auto in1_slot = bldr.AddSlot<DenseArray<float>>(); auto in2_slot = bldr.AddSlot<DenseArray<int64_t>>(); auto out1_slot = bldr.AddSlot<DenseArray<float>>(); auto out2_slot = bldr.AddSlot<DenseArray<float>>(); FrameLayout layout = std::move(bldr).Build(); MemoryAllocation alloc(&layout); FramePtr frame = alloc.frame(); frame.Set(in1_slot, CreateDenseArray<float>({0, 0, 1.2, 1.6, 7.0, 13.5, NAN})); frame.Set(in2_slot, CreateDenseArray<int64_t>({3, 1, 1, 1, 1, 1, {}})); { ASSERT_OK(eval->EvalBatch( {TypedSlot::FromSlot(in1_slot), TypedSlot::FromSlot(in2_slot)}, {TypedSlot::FromSlot(out1_slot), TypedSlot::FromSlot(out2_slot)}, frame)); EXPECT_THAT(frame.Get(out1_slot), ::testing::ElementsAre(0.5, 2.5, 2.5, 3.5, 3.5, 1.5, 0.5)); EXPECT_THAT(frame.Get(out2_slot), ::testing::ElementsAre(-1, -1, 1, 1, -1, -1, -1)); } frame.Set(out1_slot, DenseArray<float>()); frame.Set(out2_slot, DenseArray<float>()); { BatchedForestEvaluator::SetThreading(std::make_unique<StdThreading>(2)); ASSERT_OK(eval->EvalBatch( {TypedSlot::FromSlot(in1_slot), TypedSlot::FromSlot(in2_slot)}, {TypedSlot::FromSlot(out1_slot), TypedSlot::FromSlot(out2_slot)}, frame)); EXPECT_THAT(frame.Get(out1_slot), ::testing::ElementsAre(0.5, 2.5, 2.5, 3.5, 3.5, 1.5, 0.5)); EXPECT_THAT(frame.Get(out2_slot), ::testing::ElementsAre(-1, -1, 1, 1, -1, -1, -1)); BatchedForestEvaluator::SetThreading(nullptr); } frame.Set(out1_slot, DenseArray<float>()); frame.Set(out2_slot, DenseArray<float>()); { BatchedForestEvaluator::SetThreading(std::make_unique<StdThreading>(2), 1); ASSERT_OK(eval->EvalBatch( {TypedSlot::FromSlot(in1_slot), TypedSlot::FromSlot(in2_slot)}, {TypedSlot::FromSlot(out1_slot), TypedSlot::FromSlot(out2_slot)}, frame)); EXPECT_THAT(frame.Get(out1_slot), ::testing::ElementsAre(0.5, 2.5, 2.5, 3.5, 3.5, 1.5, 0.5)); EXPECT_THAT(frame.Get(out2_slot), ::testing::ElementsAre(-1, -1, 1, 1, -1, -1, -1)); BatchedForestEvaluator::SetThreading(nullptr); } } TEST(BatchedForestEvaluator, UnusedInputs) { constexpr auto A = DecisionTreeNodeId::AdjustmentId; DecisionTree tree; tree.adjustments = {-1, 1}; tree.split_nodes = {{A(0), A(1), IntervalSplit(2, 0, 1)}}; ASSERT_OK_AND_ASSIGN(auto forest, DecisionForest::FromTrees({tree})); ASSERT_OK_AND_ASSIGN(auto eval, BatchedForestEvaluator::Compile(*forest)); FrameLayout::Builder bldr; auto unused1_slot = bldr.AddSlot<DenseArray<int64_t>>(); auto unused2_slot = bldr.AddSlot<DenseArray<int64_t>>(); auto in_slot = bldr.AddSlot<DenseArray<float>>(); auto out_slot = bldr.AddSlot<DenseArray<float>>(); FrameLayout layout = std::move(bldr).Build(); MemoryAllocation alloc(&layout); FramePtr frame = alloc.frame(); frame.Set(in_slot, CreateDenseArray<float>({-1, 0.5, 2})); ASSERT_OK(eval->EvalBatch( {TypedSlot::FromSlot(unused1_slot), TypedSlot::FromSlot(unused2_slot), TypedSlot::FromSlot(in_slot)}, {TypedSlot::FromSlot(out_slot)}, frame)); EXPECT_THAT(frame.Get(out_slot), ::testing::ElementsAre(-1, 1, -1)); } TEST(BatchedForestEvaluator, AllInputUnused) { std::vector<DecisionTree> trees(1); trees[0].adjustments = {1.5}; ASSERT_OK_AND_ASSIGN(DecisionForestPtr forest, DecisionForest::FromTrees(std::move(trees))); std::vector<TreeFilter> groups{{.submodels = {0}}}; ASSERT_OK_AND_ASSIGN(auto eval, BatchedForestEvaluator::Compile(*forest, groups)); FrameLayout::Builder bldr; auto in1_slot = bldr.AddSlot<DenseArray<float>>(); auto in2_slot = bldr.AddSlot<DenseArray<int64_t>>(); auto out_slot = bldr.AddSlot<DenseArray<float>>(); FrameLayout layout = std::move(bldr).Build(); MemoryAllocation alloc(&layout); FramePtr frame = alloc.frame(); frame.Set(in1_slot, CreateDenseArray<float>({0, 0, 1.2, 1.6, 7.0, 13.5, NAN})); frame.Set(in2_slot, CreateDenseArray<int64_t>({3, 1, 1, 1, 1, 1, {}})); ASSERT_OK(eval->EvalBatch( {TypedSlot::FromSlot(in1_slot), TypedSlot::FromSlot(in2_slot)}, {TypedSlot::FromSlot(out_slot)}, frame)); EXPECT_THAT(frame.Get(out_slot), ::testing::ElementsAre(1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5)); } TEST(BatchedForestEvaluator, SplitCountPerEvaluator) { constexpr int64_t min_num_splits = 10; constexpr int64_t max_num_splits = 30; constexpr int64_t num_trees = 100; constexpr int64_t batch_size = 10; absl::BitGen rnd; constexpr int64_t min_total_split_count = num_trees * min_num_splits; int64_t split_count_per_evaluator = absl::Uniform<int64_t>( rnd, min_total_split_count / 5, min_total_split_count * 4 / 5); auto forest = CreateRandomFloatForest(&rnd, 10, true, min_num_splits, max_num_splits, num_trees); ASSERT_OK_AND_ASSIGN(auto evaluator, BatchedForestEvaluator::Compile(*forest)); ASSERT_OK_AND_ASSIGN( auto subdivided_evaluator, BatchedForestEvaluator::Compile(*forest, {TreeFilter()}, {split_count_per_evaluator})); std::vector<TypedSlot> slots; FrameLayout::Builder layout_builder; ASSERT_OK(CreateArraySlotsForForest(*forest, &layout_builder, &slots)); auto dense_array_output_slot = layout_builder.AddSlot<DenseArray<float>>(); auto array_output_slot = layout_builder.AddSlot<Array<float>>(); FrameLayout layout = std::move(layout_builder).Build(); MemoryAllocation ctx(&layout); FramePtr frame = ctx.frame(); for (auto slot : slots) { ASSERT_OK(FillArrayWithRandomValues(batch_size, slot, frame, &rnd)); } ASSERT_OK(evaluator->EvalBatch(slots, {TypedSlot::FromSlot(dense_array_output_slot)}, frame, nullptr, batch_size)); ASSERT_OK(evaluator->EvalBatch(slots, {TypedSlot::FromSlot(array_output_slot)}, frame, nullptr, batch_size)); DenseArray<float> dense_array1 = frame.Get(dense_array_output_slot); Array<float> array1 = frame.Get(array_output_slot); frame.Set(dense_array_output_slot, DenseArray<float>()); frame.Set(array_output_slot, Array<float>()); ASSERT_OK(subdivided_evaluator->EvalBatch( slots, {TypedSlot::FromSlot(dense_array_output_slot)}, frame, nullptr, batch_size)); ASSERT_OK(subdivided_evaluator->EvalBatch( slots, {TypedSlot::FromSlot(array_output_slot)}, frame, nullptr, batch_size)); DenseArray<float> dense_array2 = frame.Get(dense_array_output_slot); Array<float> array2 = frame.Get(array_output_slot); ASSERT_EQ(dense_array1.size(), batch_size); ASSERT_EQ(array1.size(), batch_size); ASSERT_EQ(dense_array2.size(), batch_size); ASSERT_EQ(array2.size(), batch_size); for (int64_t i = 0; i < batch_size; ++i) { bool present = array1[i].present; EXPECT_EQ(array2[i].present, present); EXPECT_EQ(dense_array1[i].present, present); EXPECT_EQ(dense_array2[i].present, present); if (present) { float value = array1[i].value; EXPECT_FLOAT_EQ(array2[i].value, value); EXPECT_FLOAT_EQ(dense_array1[i].value, value); EXPECT_FLOAT_EQ(dense_array2[i].value, value); } } } } }
2,389
cpp
google/arolla
forest_model
arolla/decision_forest/expr_operator/forest_model.cc
arolla/decision_forest/expr_operator/forest_model_test.cc
#ifndef AROLLA_DECISION_FOREST_EXPR_OPERATOR_FOREST_MODEL_H_ #define AROLLA_DECISION_FOREST_EXPR_OPERATOR_FOREST_MODEL_H_ #include <cstddef> #include <map> #include <memory> #include <optional> #include <string> #include <utility> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "arolla/decision_forest/decision_forest.h" #include "arolla/expr/basic_expr_operator.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/qtype/qtype.h" #include "arolla/util/fingerprint.h" namespace arolla { constexpr absl::string_view kForestModelQValueSpecializationKey = "::arolla::ForestModel"; class ForestModel; using ForestModelPtr = std::shared_ptr<const ForestModel>; class ForestModel : public expr::BasicExprOperator { public: using SubmodelIds = std::map<std::string, std::vector<int>>; struct Parameter { std::string name; expr::ExprNodePtr preprocessing = nullptr; }; struct ConstructorArgs { DecisionForestPtr forest; SubmodelIds submodel_ids; std::vector<Parameter> inputs; expr::ExprNodePtr expression; std::optional<std::vector<expr::ExprNodePtr>> oob_filters; std::optional<size_t> truncation_step; }; static absl::StatusOr<ForestModelPtr> Create(ConstructorArgs args); absl::StatusOr<expr::ExprNodePtr> ToLowerLevel( const expr::ExprNodePtr& node) const override; absl::StatusOr<std::vector<expr::ExprNodePtr>> PreprocessInputs( const expr::ExprNodePtr& node) const; absl::StatusOr<expr::ExprNodePtr> ApplyPostprocessing( const expr::ExprNodePtr& node, const expr::ExprNodePtr& raw_result) const; absl::StatusOr<expr::ExprNodePtr> CreatePartialEvaluator( absl::Span<const std::pair<int, int>> step_ranges, absl::Span<const expr::ExprNodePtr> preprocessed_inputs) const; DecisionForestPtr forest() const { return forest_; } const SubmodelIds& submodel_ids() const { return submodel_ids_; } const std::optional<std::vector<expr::ExprNodePtr>>& oob_filters() const { return oob_filters_; } size_t bag_count() const { return bag_count_; } std::optional<size_t> truncation_step() const { return truncation_step_; } const std::vector<Parameter>& inputs() const { return inputs_; } expr::ExprNodePtr expression() const { return expression_; } absl::string_view py_qvalue_specialization_key() const override; private: ForestModel(expr::ExprOperatorSignature&& signature, Fingerprint&& fingerprint, ConstructorArgs&& args); absl::Status Initialize(); absl::StatusOr<QTypePtr> GetOutputQType( absl::Span<const QTypePtr> input_qtypes) const override; struct ExpressionAnalysisResult { bool plain_sum = true; int bag_count = 0; std::vector<expr::ExprNodePtr> submodel_nodes; std::vector<expr::ExprNodePtr> plain_sum_nodes; }; absl::StatusOr<ExpressionAnalysisResult> AnalyzeExpression() const; absl::Status HandlePlainSumExpression( const std::vector<expr::ExprNodePtr>& submodel_nodes, std::vector<expr::ExprNodePtr>&& plain_sum_nodes); absl::Status HandleExpressionWithoutBags(); absl::Status HandleExpressionWithBags(); absl::StatusOr<expr::ExprNodePtr> UsedBagCountExpr() const; absl::StatusOr<expr::ExprOperatorPtr> CreateDecisionForestOperator( std::vector<TreeFilter> tree_filters) const; absl::StatusOr<expr::ExprNodePtr> ApplyEvaluator( expr::ExprNodePtr forest_evaluator, absl::Span<const expr::ExprNodePtr> args) const; absl::StatusOr<expr::ExprNodePtr> CastAndValidateArgType( int input_id, expr::ExprNodePtr arg) const; absl::StatusOr<QTypePtr> InferTypeOfFirstForestInputAfterPreprocessing( absl::Span<const QTypePtr> input_qtypes) const; DecisionForestPtr forest_; SubmodelIds submodel_ids_; std::optional<std::vector<expr::ExprNodePtr>> oob_filters_; std::optional<size_t> truncation_step_; std::vector<Parameter> inputs_; expr::ExprNodePtr expression_; std::optional<std::string> res_tuple_key_; std::vector<TreeFilter> tree_filters_; expr::ExprNodePtr processed_expression_; bool is_plain_sum_ = false; absl::flat_hash_map<int, float> submodel_weight_multipliers_; size_t bag_count_; std::optional<int> first_forest_input_id_; }; } #endif #include "arolla/decision_forest/expr_operator/forest_model.h" #include <algorithm> #include <cstddef> #include <cstdint> #include <memory> #include <optional> #include <string> #include <utility> #include <vector> #include "absl/algorithm/container.h" #include "absl/container/flat_hash_map.h" #include "absl/container/flat_hash_set.h" #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" #include "absl/strings/str_join.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "arolla/decision_forest/decision_forest.h" #include "arolla/decision_forest/expr_operator/decision_forest_operator.h" #include "arolla/expr/annotation_utils.h" #include "arolla/expr/basic_expr_operator.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_attributes.h" #include "arolla/expr/expr_debug_string.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/expr/expr_visitor.h" #include "arolla/expr/lambda_expr_operator.h" #include "arolla/expr/registered_expr_operator.h" #include "arolla/expr/visitors/substitution.h" #include "arolla/memory/optional_value.h" #include "arolla/qtype/array_like/array_like_qtype.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/optional_qtype.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/standard_type_properties/properties.h" #include "arolla/util/fingerprint.h" #include "arolla/util/text.h" #include "arolla/util/status_macros_backport.h" namespace arolla { namespace { absl::Status ValidateExpression( const expr::ExprNodePtr& expression, const ForestModel::SubmodelIds& submodel_ids, const absl::flat_hash_set<std::string>& input_names) { absl::flat_hash_set<std::string> unused_submodels; for (const auto& [k, _] : submodel_ids) unused_submodels.insert(k); for (const auto& node : expr::VisitorOrder(expression)) { if (node->is_leaf()) { return absl::InvalidArgumentError( "leaves are not allowed in an expression"); } if (node->is_placeholder()) { if (submodel_ids.count(node->placeholder_key()) > 0) { unused_submodels.erase(node->placeholder_key()); } else if (!input_names.contains(node->placeholder_key())) { return absl::InvalidArgumentError(absl::StrFormat( "P.%s doesn't correspond to any input and it is not " "found in submodel_ids", node->placeholder_key())); } } } if (!unused_submodels.empty()) { std::vector<std::string> unused_vec(unused_submodels.begin(), unused_submodels.end()); absl::c_sort(unused_vec); return absl::InvalidArgumentError( absl::StrFormat("submodels [%s] are not used in the expression, but " "are mentioned in submodel_ids", absl::StrJoin(unused_vec, ", "))); } return absl::OkStatus(); } absl::Status ValidateInputs(const DecisionForestPtr& forest, const ForestModel::SubmodelIds& submodel_ids, const std::vector<ForestModel::Parameter>& inputs) { for (const auto& input : inputs) { if (submodel_ids.count(input.name) > 0) { return absl::InvalidArgumentError(absl::StrFormat( "name collision of an input and a submodel: '%s'", input.name)); } } for (const auto& [key, unused] : forest->GetRequiredQTypes()) { if (key >= inputs.size()) { return absl::InvalidArgumentError(absl::StrFormat( "not enough args: used_input_index=%d size=%d", key, inputs.size())); } } return absl::OkStatus(); } absl::Status ValidateOOBFilters( const std::vector<expr::ExprNodePtr>& oob_filters, const DecisionForestPtr& forest, const absl::flat_hash_set<std::string>& input_names) { for (const expr::ExprNodePtr& filter : oob_filters) { if (filter == nullptr) { return absl::InvalidArgumentError("OOB filter can't be nullptr"); } for (const auto& node : expr::VisitorOrder(filter)) { if (node->is_leaf()) { return absl::InvalidArgumentError( "leaves are not allowed in an OOB filter expressing"); } if (node->is_placeholder() && !input_names.contains(node->placeholder_key())) { return absl::InvalidArgumentError( absl::StrCat("no input matches P.", node->placeholder_key(), " in OOB filter ", expr::ToDebugString(node))); } } } return absl::OkStatus(); } absl::StatusOr<expr::ExprNodePtr> AddAll( const expr::ExprNodePtr& first, absl::Span<const expr::ExprNodePtr> nodes) { auto res = first; for (const auto& node : nodes) { ASSIGN_OR_RETURN(res, expr::CallOp("math.add", {res, node})); } return res; } using NodeCountMap = absl::flat_hash_map<Fingerprint, int>; NodeCountMap GetNodeCountMap(const expr::ExprNodePtr& expr) { return PostOrderTraverse(expr, [&](const expr::ExprNodePtr& node, absl::Span<const NodeCountMap* const> visits) { NodeCountMap res{{node->fingerprint(), 1}}; for (const NodeCountMap* visit : visits) { for (const auto& [k, v] : *visit) { if (res.contains(k)) { res[k] += v; } else { res[k] = v; } } } return res; }); } } absl::StatusOr<ForestModelPtr> ForestModel::Create( ForestModel::ConstructorArgs args) { expr::ExprOperatorSignature signature; signature.parameters.reserve(args.inputs.size()); for (const Parameter& param : args.inputs) { signature.parameters.push_back({param.name}); } RETURN_IF_ERROR(expr::ValidateSignature(signature)); RETURN_IF_ERROR(ValidateInputs(args.forest, args.submodel_ids, args.inputs)); absl::flat_hash_set<std::string> input_names; input_names.reserve(args.inputs.size()); for (const auto& input : args.inputs) { input_names.insert(input.name); } RETURN_IF_ERROR( ValidateExpression(args.expression, args.submodel_ids, input_names)); if (args.oob_filters.has_value()) { RETURN_IF_ERROR( ValidateOOBFilters(*args.oob_filters, args.forest, input_names)); } FingerprintHasher hasher("d18261c6a5414ee8e5b0af80dc480ea8"); hasher.Combine(args.forest->fingerprint(), args.expression->fingerprint(), signature); hasher.Combine(args.submodel_ids.size()); for (const auto& [k, v] : args.submodel_ids) { hasher.Combine(k).CombineSpan(v); } hasher.Combine(args.inputs.size()); for (const auto& input : args.inputs) { if (input.preprocessing != nullptr) { hasher.Combine(input.preprocessing->fingerprint()); } else { hasher.Combine(Fingerprint{}); } } if (args.oob_filters.has_value()) { for (const auto& oob_filter : *args.oob_filters) { hasher.Combine(oob_filter->fingerprint()); } } else { hasher.Combine(Fingerprint{}); } if (args.truncation_step.has_value()) { hasher.Combine(*args.truncation_step); } else { hasher.Combine(Fingerprint{}); } std::shared_ptr<ForestModel> model(new ForestModel( std::move(signature), std::move(hasher).Finish(), std::move(args))); RETURN_IF_ERROR(model->Initialize()); return model; } absl::StatusOr<std::vector<expr::ExprNodePtr>> ForestModel::PreprocessInputs( const expr::ExprNodePtr& node) const { RETURN_IF_ERROR(ValidateNodeDepsCount(*node)); std::vector<expr::ExprNodePtr> args(inputs_.size()); for (int i = 0; i < inputs_.size(); ++i) { expr::ExprNodePtr arg = node->node_deps()[i]; if (inputs_[i].preprocessing != nullptr) { ASSIGN_OR_RETURN(auto lambda, expr::LambdaOperator::Make(inputs_[i].preprocessing)); ASSIGN_OR_RETURN(arg, expr::CallOp(lambda, {arg})); ASSIGN_OR_RETURN(arg, expr::ToLowerNode(arg)); } if (arg->qtype() == nullptr) { return absl::InternalError( absl::StrFormat("invalid preprocessing for input #%d: QType metadata " "can not be propagated", i)); } ASSIGN_OR_RETURN(args[i], CastAndValidateArgType(i, std::move(arg))); } return args; } absl::StatusOr<expr::ExprNodePtr> ForestModel::ApplyPostprocessing( const expr::ExprNodePtr& node, const expr::ExprNodePtr& raw_result) const { RETURN_IF_ERROR(ValidateNodeDepsCount(*node)); absl::flat_hash_map<std::string, expr::ExprNodePtr> expression_params; expression_params.reserve(inputs_.size() + 1); for (int i = 0; i < inputs_.size(); ++i) { expression_params[inputs_[i].name] = node->node_deps()[i]; } if (res_tuple_key_) { if (raw_result == nullptr) { return absl::InvalidArgumentError( "raw_result can be nullptr only if expression doesn't use decision " "forest"); } expression_params[*res_tuple_key_] = raw_result; } ASSIGN_OR_RETURN(auto result, SubstitutePlaceholders( processed_expression_, expression_params, true)); if (IsNameAnnotation(node)) { return expr::CallOp( "annotation.name", {result, expr::Literal(Text(expr::ReadNameAnnotation(node)))}); } return result; } absl::StatusOr<expr::ExprNodePtr> ForestModel::ToLowerLevel( const expr::ExprNodePtr& node) const { RETURN_IF_ERROR(ValidateNodeDepsCount(*node)); for (size_t i = 0; i < inputs_.size(); ++i) { if (node->node_deps()[i]->qtype() == nullptr) { return node; } } if (!res_tuple_key_) { return ApplyPostprocessing(node, nullptr); } ASSIGN_OR_RETURN(std::vector<expr::ExprNodePtr> args, PreprocessInputs(node)); ASSIGN_OR_RETURN(auto op, CreateDecisionForestOperator(tree_filters_)); ASSIGN_OR_RETURN(auto res_tuple, expr::MakeOpNode(op, std::move(args))); return ApplyPostprocessing(node, res_tuple); } absl::StatusOr<expr::ExprNodePtr> ForestModel::CreatePartialEvaluator( absl::Span<const std::pair<int, int>> step_ranges, absl::Span<const expr::ExprNodePtr> preprocessed_inputs) const { std::vector<TreeFilter> filters; filters.reserve(step_ranges.size() * tree_filters_.size()); for (auto& [from, to] : step_ranges) { for (const TreeFilter& filter : tree_filters_) { if ((filter.step_range_from > from) || (filter.step_range_to >= 0 && filter.step_range_to < to)) { return absl::InvalidArgumentError("requested range is not available"); } filters.push_back({from, to, filter.submodels}); } } ASSIGN_OR_RETURN(auto op, CreateDecisionForestOperator(std::move(filters))); return expr::MakeOpNode( op, std::vector(preprocessed_inputs.begin(), preprocessed_inputs.end())); } absl::StatusOr<QTypePtr> ForestModel::InferTypeOfFirstForestInputAfterPreprocessing( absl::Span<const QTypePtr> input_qtypes) const { if (!first_forest_input_id_.has_value()) { return absl::FailedPreconditionError("forest has no inputs"); } QTypePtr in_type = input_qtypes[*first_forest_input_id_]; if (inputs_[*first_forest_input_id_].preprocessing != nullptr) { ASSIGN_OR_RETURN(auto lambda, expr::LambdaOperator::Make( inputs_[*first_forest_input_id_].preprocessing)); ASSIGN_OR_RETURN(expr::ExprAttributes attr, lambda->InferAttributes({expr::ExprAttributes(in_type)})); if (attr.qtype() == nullptr) { return absl::InternalError("can't infer preprocessed input type"); } return attr.qtype(); } else { return in_type; } } absl::StatusOr<QTypePtr> ForestModel::GetOutputQType( absl::Span<const QTypePtr> input_qtypes) const { QTypePtr out_type = GetQType<float>(); if (first_forest_input_id_.has_value()) { ASSIGN_OR_RETURN( QTypePtr in_type, InferTypeOfFirstForestInputAfterPreprocessing(input_qtypes)); if (IsArrayLikeQType(in_type)) { ASSIGN_OR_RETURN(const ArrayLikeQType* array_qtype, ToArrayLikeQType(in_type)); ASSIGN_OR_RETURN(out_type, array_qtype->WithValueQType(GetQType<float>())); } } ASSIGN_OR_RETURN(auto fake_res, expr::CallOp("annotation.qtype", {expr::Leaf("fake_res"), expr::Literal(out_type)})); ASSIGN_OR_RETURN( auto fake_res_tuple, expr::BindOp( "core.make_tuple", std::vector<expr::ExprNodePtr>(tree_filters_.size(), fake_res), {})); absl::flat_hash_map<std::string, expr::ExprNodePtr> expression_params; if (res_tuple_key_) { expression_params[*res_tuple_key_] = fake_res_tuple; } for (int i = 0; i < inputs_.size(); ++i) { ASSIGN_OR_RETURN( expression_params[inputs_[i].name], expr::CallOp("annotation.qtype", {expr::Leaf("fake_input"), expr::Literal(input_qtypes[i])})); } ASSIGN_OR_RETURN(auto expr, SubstitutePlaceholders( processed_expression_, expression_params, true)); const auto result = expr->qtype(); if (result == nullptr) { return absl::FailedPreconditionError("unable to deduce output qtype"); } return result; } absl::StatusOr<expr::ExprNodePtr> ForestModel::CastAndValidateArgType( int input_id, expr::ExprNodePtr arg) const { const auto& required_qtypes = forest_->GetRequiredQTypes(); auto required_qtype_iter = required_qtypes.find(input_id); if (required_qtype_iter == required_qtypes.end()) { return arg; } QTypePtr required_qtype = required_qtype_iter->second; QTypePtr required_scalar_qtype = DecayOptionalQType(required_qtype); ASSIGN_OR_RETURN(QTypePtr actual_scalar_qtype, GetScalarQType(arg->qtype())); if (required_scalar_qtype == GetQType<float>() && actual_scalar_qtype != GetQType<float>() && IsNumericScalarQType(actual_scalar_qtype)) { ASSIGN_OR_RETURN(arg, expr::BindOp("core.to_float32", {std::move(arg)}, {})); } else if (required_scalar_qtype != actual_scalar_qtype) { return absl::InvalidArgumentError( absl::StrFormat("value type of input #%d (%s) doesn't match: " "expected to be compatible with %s, got %s", input_id, expr::GetDebugSnippet(arg), required_qtype->name(), arg->qtype()->name())); } if (IsScalarQType(arg->qtype()) && IsOptionalQType(required_qtype)) { ASSIGN_OR_RETURN(arg, expr::BindOp("core.to_optional", {std::move(arg)}, {})); } return arg; } absl::StatusOr<ForestModel::ExpressionAnalysisResult> ForestModel::AnalyzeExpression() const { ExpressionAnalysisResult res; ASSIGN_OR_RETURN(auto expression, expr::ToLowest(expression_)); for (const auto& node : expr::VisitorOrder(expression)) { if (node->is_op()) { ASSIGN_OR_RETURN(auto op, expr::DecayRegisteredOperator(node->op())); res.plain_sum = res.plain_sum && expr::IsBackendOperator(op, "math.add"); } else if (node->is_placeholder() && submodel_ids_.count(node->placeholder_key()) > 0) { res.submodel_nodes.push_back(node); const auto& submodels = submodel_ids_.at(node->placeholder_key()); if (submodels.empty()) { return absl::InvalidArgumentError(absl::StrFormat( "submodel_ids[%s] is empty", node->placeholder_key())); } if (res.bag_count != 0 && res.bag_count != submodels.size()) { return absl::InvalidArgumentError( "all submodels should have the same number of bags"); } res.bag_count = submodels.size(); } else { res.plain_sum_nodes.push_back(node); } } res.bag_count = std::max(res.bag_count, 1); return res; } absl::Status ForestModel::HandlePlainSumExpression( const std::vector<expr::ExprNodePtr>& submodel_nodes, std::vector<expr::ExprNodePtr>&& plain_sum_nodes) { ASSIGN_OR_RETURN( processed_expression_, expr::CallOp("core.get_first", {expr::Placeholder(*res_tuple_key_)})); auto count_map = GetNodeCountMap(expression_); for (auto& node : plain_sum_nodes) { int count = count_map[node->fingerprint()]; if (count > 1) { ASSIGN_OR_RETURN(node, expr::CallOp("math.multiply", {node, expr::Literal<float>(count)})); } } ASSIGN_OR_RETURN(processed_expression_, AddAll(processed_expression_, plain_sum_nodes)); TreeFilter used_trees; for (const auto& node : submodel_nodes) { int count = count_map[node->fingerprint()]; for (int submodel_id : submodel_ids_[node->placeholder_key()]) { used_trees.submodels.insert(submodel_id); if (count > 1) submodel_weight_multipliers_[submodel_id] = count; } } tree_filters_.push_back(used_trees); return absl::OkStatus(); } absl::Status ForestModel::HandleExpressionWithoutBags() { absl::flat_hash_map<std::string, expr::ExprNodePtr> params; for (const auto& [key, submodels] : submodel_ids_) { ASSIGN_OR_RETURN( params[key], expr::CallOp("core.get_nth", {expr::Placeholder(*res_tuple_key_), expr::Literal<int64_t>(tree_filters_.size())})); TreeFilter filter; filter.submodels.insert(submodels.begin(), submodels.end()); tree_filters_.push_back(std::move(filter)); } ASSIGN_OR_RETURN(processed_expression_, SubstitutePlaceholders(expression_, params)); return absl::OkStatus(); } absl::StatusOr<expr::ExprNodePtr> ForestModel::UsedBagCountExpr() const { DCHECK_GT(bag_count_, 0); if (!oob_filters_.has_value()) { return expr::Literal<float>(bag_count_); } expr::ExprNodePtr used_bag_count = nullptr; for (int bag_id = 0; bag_id < bag_count_; ++bag_id) { ASSIGN_OR_RETURN(expr::ExprNodePtr used, expr::CallOp("core.where", {(*oob_filters_)[bag_id], expr::Literal<float>(1), expr::Literal<float>(0)})); if (used_bag_count != nullptr) { ASSIGN_OR_RETURN(used_bag_count, expr::CallOp("math.add", {used_bag_count, used})); } else { used_bag_count = used; } } ASSIGN_OR_RETURN( used_bag_count, expr::CallOp( "core.where", {expr::CallOp("core.greater", {used_bag_count, expr::Literal<float>(0)}), used_bag_count, expr::Literal<OptionalValue<float>>(std::nullopt)})); return used_bag_count; } absl::Status ForestModel::HandleExpressionWithBags() { std::vector<expr::ExprNodePtr> bags(bag_count_); for (int bag_id = 0; bag_id < bag_count_; ++bag_id) { absl::flat_hash_map<std::string, expr::ExprNodePtr> params; for (const auto& [key, submodels] : submodel_ids_) { expr::ExprNodePtr& param = params[key]; ASSIGN_OR_RETURN( param, expr::CallOp("core.get_nth", {expr::Placeholder(*res_tuple_key_), expr::Literal<int64_t>(tree_filters_.size())})); TreeFilter filter; if (submodels.size() <= bag_id) { return absl::InternalError("invalid submodel_ids"); } filter.submodels.insert(submodels[bag_id]); tree_filters_.push_back(std::move(filter)); submodel_weight_multipliers_[submodels[bag_id]] = bag_count_; } ASSIGN_OR_RETURN(bags[bag_id], SubstitutePlaceholders(expression_, params)); if (oob_filters_.has_value()) { ASSIGN_OR_RETURN( bags[bag_id], expr::CallOp("core.where", {(*oob_filters_)[bag_id], bags[bag_id], expr::Literal<float>(0)})); } } ASSIGN_OR_RETURN( auto sum, AddAll(bags[0], absl::Span<expr::ExprNodePtr>(bags.data() + 1, bag_count_ - 1))); ASSIGN_OR_RETURN(processed_expression_, expr::CallOp("math.divide", {sum, UsedBagCountExpr()})); return absl::OkStatus(); } absl::Status ForestModel::Initialize() { if (submodel_ids_.empty()) { res_tuple_key_ = std::nullopt; processed_expression_ = expression_; bag_count_ = 1; return absl::OkStatus(); } else { res_tuple_key_ = submodel_ids_.begin()->first; } ASSIGN_OR_RETURN(auto info, AnalyzeExpression()); is_plain_sum_ = info.plain_sum; bag_count_ = info.bag_count; if (oob_filters_.has_value() && oob_filters_->size() != bag_count_) { return absl::FailedPreconditionError( "if oob_filters is prese
#include "arolla/decision_forest/expr_operator/forest_model.h" #include <cstdint> #include <limits> #include <string> #include <tuple> #include <utility> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "arolla/decision_forest/decision_forest.h" #include "arolla/decision_forest/split_conditions/interval_split_condition.h" #include "arolla/decision_forest/split_conditions/set_of_values_split_condition.h" #include "arolla/dense_array/dense_array.h" #include "arolla/dense_array/qtype/types.h" #include "arolla/expr/annotation_utils.h" #include "arolla/expr/eval/eval.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/registered_expr_operator.h" #include "arolla/expr/testing/testing.h" #include "arolla/expr/tuple_expr_operator.h" #include "arolla/memory/frame.h" #include "arolla/memory/optional_value.h" #include "arolla/qexpr/eval_context.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/typed_slot.h" #include "arolla/serving/expr_compiler.h" #include "arolla/util/indestructible.h" #include "arolla/util/init_arolla.h" #include "arolla/util/testing/status_matchers_backport.h" #include "arolla/util/status_macros_backport.h" namespace arolla { namespace { using ::arolla::testing::EqualsExpr; using ::arolla::testing::IsOk; using ::arolla::testing::StatusIs; using ::arolla::testing::WithNameAnnotation; using ::testing::ElementsAre; using ::testing::Eq; using ::testing::HasSubstr; using ::testing::NotNull; using ::testing::WhenDynamicCastTo; constexpr float inf = std::numeric_limits<float>::infinity(); constexpr auto S = DecisionTreeNodeId::SplitNodeId; constexpr auto A = DecisionTreeNodeId::AdjustmentId; absl::StatusOr<DecisionForestPtr> CreateForest() { std::vector<DecisionTree> trees(2); trees[0].adjustments = {0.5, 1.5, 2.5, 3.5}; trees[0].tag.submodel_id = 0; trees[0].split_nodes = { {S(1), S(2), IntervalSplit(0, 1.5, inf)}, {A(0), A(1), SetOfValuesSplit<int64_t>(1, {5}, false)}, {A(2), A(3), IntervalSplit(0, -inf, 10)}}; trees[1].adjustments = {5}; trees[1].tag.submodel_id = 1; return DecisionForest::FromTrees(std::move(trees)); } absl::StatusOr<ForestModelPtr> CreateForestModelOp() { ForestModel::SubmodelIds submodel_ids = {{"X", {0}}, {"Y", {1}}}; ASSIGN_OR_RETURN(auto preprocessing, expr::CallOp("math.add", {expr::Placeholder("arg"), expr::Literal<int64_t>(1)})); ASSIGN_OR_RETURN(auto expression, expr::CallOp("math.add", {expr::Placeholder("X"), expr::Placeholder("Y")})); ASSIGN_OR_RETURN(auto forest, CreateForest()); return ForestModel::Create({.forest = std::move(forest), .submodel_ids = std::move(submodel_ids), .inputs = {{"p1"}, {"p2", preprocessing}}, .expression = expression}); } absl::Status InitAlias() { static Indestructible<absl::Status> init_status( expr::RegisterOperatorAlias("alias_math.add", "math.add").status()); return *init_status; } class ForestModelTest : public ::testing::Test { void SetUp() override { CHECK_OK(InitArolla()); CHECK_OK(InitAlias()); } }; TEST_F(ForestModelTest, NotEnoughArgs) { ForestModel::ConstructorArgs model_data; model_data.submodel_ids = {{"X", {0}}, {"Y", {1}}}; ASSERT_OK_AND_ASSIGN(model_data.expression, expr::CallOp("math.add", {expr::Placeholder("X"), expr::Placeholder("Y")})); ASSERT_OK_AND_ASSIGN(model_data.forest, CreateForest()); model_data.inputs = {{"p1"}}; EXPECT_THAT(ForestModel::Create(model_data), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("not enough args"))); } TEST_F(ForestModelTest, ParameterNameCollision) { ForestModel::ConstructorArgs model_data; model_data.submodel_ids = {{"X", {0}}, {"Y", {1}}}; ASSERT_OK_AND_ASSIGN( auto preprocessing, expr::CallOp("math.add", {expr::Placeholder("arg"), expr::Literal<OptionalValue<int64_t>>(1)})); ASSERT_OK_AND_ASSIGN(model_data.expression, expr::CallOp("math.add", {expr::Placeholder("X"), expr::Placeholder("Y")})); ASSERT_OK_AND_ASSIGN(model_data.forest, CreateForest()); model_data.inputs = {{"p1"}, {"p1", preprocessing}}; EXPECT_THAT(ForestModel::Create(model_data), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("non-unique parameter name: 'p1'"))); model_data.inputs = {{"X"}, {"p2", preprocessing}}; EXPECT_THAT( ForestModel::Create(model_data), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("name collision of an input and a submodel: 'X'"))); } TEST_F(ForestModelTest, IncorrectExpression) { ASSERT_OK_AND_ASSIGN(DecisionForestPtr forest, DecisionForest::FromTrees({})); { ASSERT_OK_AND_ASSIGN(expr::ExprNodePtr expression, expr::CallOp("math.add", {expr::Placeholder("X"), expr::Placeholder("Y")})); EXPECT_THAT(ForestModel::Create({.forest = forest, .submodel_ids = {{"X", {0}}}, .inputs = {{"p1"}, {"p2"}}, .expression = expression}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("P.Y doesn't correspond to any input and it " "is not found in submodel_ids"))); } { expr::ExprNodePtr expression = expr::Placeholder("X"); EXPECT_THAT( ForestModel::Create({.forest = forest, .submodel_ids = {{"X", {0}}, {"Y", {1}}}, .expression = expression}), StatusIs( absl::StatusCode::kInvalidArgument, HasSubstr("submodels [Y] are not used in the expression, but are " "mentioned in submodel_ids"))); } { expr::ExprNodePtr expression = expr::Leaf("X"); EXPECT_THAT( ForestModel::Create({.forest = forest, .expression = expression}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("leaves are not allowed in an expression"))); } } TEST_F(ForestModelTest, UsingInputInExpression) { ASSERT_OK_AND_ASSIGN(auto expression, expr::CallOp("math.add", {expr::Placeholder("X"), expr::Placeholder("p1")})); auto f1 = expr::Literal<float>(1.0); auto i5 = expr::Literal<int64_t>(5); ASSERT_OK_AND_ASSIGN(auto forest, CreateForest()); ASSERT_OK_AND_ASSIGN(auto model_op, ForestModel::Create({.forest = forest, .submodel_ids = {{"X", {0}}}, .inputs = {{"p1"}, {"p2"}}, .expression = expression})); ASSERT_OK_AND_ASSIGN(auto model, expr::CallOp(model_op, {f1, i5})); ASSERT_OK_AND_ASSIGN(auto expanded_model, expr::ToLowest(model)); ASSERT_TRUE(expanded_model->is_op()); EXPECT_TRUE(IsRegisteredOperator(expanded_model->op())); EXPECT_TRUE(IsBackendOperator(*DecayRegisteredOperator(expanded_model->op()), "math.add")); EXPECT_THAT(expanded_model->node_deps()[1], EqualsExpr(f1)); } TEST_F(ForestModelTest, QTypePropagation) { ASSERT_OK_AND_ASSIGN(auto model_op, CreateForestModelOp()); ASSERT_OK_AND_ASSIGN( auto model, expr::CallOp(model_op, {expr::Literal<OptionalValue<float>>(1.0), expr::Literal<int64_t>(5)})); EXPECT_EQ(model->qtype(), GetQType<float>()); } TEST_F(ForestModelTest, QTypePropagationUsesPreprocessing) { ForestModel::ConstructorArgs model_data; model_data.submodel_ids = {{"X", {0, 1}}}; ASSERT_OK_AND_ASSIGN(auto preprocessing, expr::CallOp("core.const_with_shape", {expr::Literal<DenseArrayShape>({5}), expr::Placeholder("arg")})); model_data.expression = expr::Placeholder("X"); ASSERT_OK_AND_ASSIGN(model_data.forest, CreateForest()); model_data.inputs = {{"p1", preprocessing}, {"p2", preprocessing}}; ASSERT_OK_AND_ASSIGN(auto model_op, ForestModel::Create(model_data)); ASSERT_OK_AND_ASSIGN( auto model, expr::CallOp(model_op, {expr::Literal<OptionalValue<float>>(1.0), expr::Literal<int64_t>(5)})); EXPECT_EQ(model->qtype(), GetDenseArrayQType<float>()); } TEST_F(ForestModelTest, QTypePropagationPlainSumWithBroadcasting) { ForestModel::ConstructorArgs model_data; model_data.submodel_ids = {{"X", {0, 1}}}; ASSERT_OK_AND_ASSIGN( model_data.expression, expr::CallOp("math.add", {expr::Literal(CreateDenseArray<float>({1., 2., 3.})), expr::Placeholder("X")})); ASSERT_OK_AND_ASSIGN(model_data.forest, CreateForest()); model_data.inputs = {{"p1"}, {"p2"}}; ASSERT_OK_AND_ASSIGN(auto model_op, ForestModel::Create(model_data)); ASSERT_OK_AND_ASSIGN( auto model, expr::CallOp(model_op, {expr::Literal<OptionalValue<float>>(1.0), expr::Literal<int64_t>(5)})); EXPECT_EQ(model->qtype(), GetDenseArrayQType<float>()); ASSERT_OK_AND_ASSIGN(auto lowered, expr::ToLowest(model)); EXPECT_EQ(lowered->qtype(), GetDenseArrayQType<float>()); } TEST_F(ForestModelTest, EmptyForest) { ASSERT_OK_AND_ASSIGN(auto forest, DecisionForest::FromTrees({})); expr::ExprNodePtr expression = expr::Literal<float>(0.5); ASSERT_OK_AND_ASSIGN(auto model_op, ForestModel::Create({.forest = std::move(forest), .expression = expression})); ASSERT_OK_AND_ASSIGN(auto model, expr::CallOp(model_op, {})); ASSERT_OK_AND_ASSIGN(auto expanded_model, expr::ToLowest(model)); EXPECT_THAT(expanded_model, EqualsExpr(expression)); } TEST_F(ForestModelTest, ToLower) { ASSERT_OK_AND_ASSIGN(auto model_op, CreateForestModelOp()); { ASSERT_OK_AND_ASSIGN(auto model, expr::CallOp(model_op, {expr::Literal<float>(1.0), expr::Literal<int64_t>(5)})); ASSERT_OK_AND_ASSIGN(model, WithNameAnnotation(model, "forest")); ASSERT_OK_AND_ASSIGN(auto expanded_model, expr::ToLowest(model)); EXPECT_NE(model->fingerprint(), expanded_model->fingerprint()); EXPECT_EQ(ReadNameAnnotation(expanded_model), "forest"); } { ASSERT_OK_AND_ASSIGN( auto model, expr::CallOp(model_op, {expr::Leaf("f"), expr::Leaf("i")})); ASSERT_OK_AND_ASSIGN(auto expanded_model, expr::ToLowest(model)); EXPECT_EQ(model->fingerprint(), expanded_model->fingerprint()); } } absl::StatusOr<expr::ExprNodePtr> GetExpressionForTest(std::string A, std::string B, std::string C, std::string op) { return expr::CallOp( "alias_math.add", {expr::Placeholder(A), expr::CallOp(op, {expr::Placeholder(B), expr::Placeholder(C)})}); } TEST_F(ForestModelTest, ToLowerMergeSubmodels) { ASSERT_OK_AND_ASSIGN(auto forest, DecisionForest::FromTrees({})); ASSERT_OK_AND_ASSIGN(auto expression, GetExpressionForTest("input", "X", "Y", "math.add")); ASSERT_OK_AND_ASSIGN( auto model_op, ForestModel::Create({.forest = std::move(forest), .submodel_ids = {{"X", {0, 2}}, {"Y", {1, 3}}}, .inputs = {{"input"}}, .expression = expression})); ASSERT_OK_AND_ASSIGN(auto model, expr::CallOp(model_op, {expr::Literal<float>(1.0)})); ASSERT_OK_AND_ASSIGN(auto expanded_model, expr::ToLowest(model)); EXPECT_TRUE(IsRegisteredOperator(expanded_model->op())); EXPECT_TRUE(IsBackendOperator(*DecayRegisteredOperator(expanded_model->op()), "math.add")); EXPECT_THAT(expanded_model->node_deps()[0]->op().get(), WhenDynamicCastTo<const expr::GetNthOperator*>(NotNull())); } TEST_F(ForestModelTest, MergeDuplicatedSubmodels) { std::vector<DecisionTree> trees(2); trees[0].adjustments = {1.0}; trees[0].tag.submodel_id = 0; trees[1].adjustments = {3.0}; trees[1].tag.submodel_id = 1; ASSERT_OK_AND_ASSIGN(auto forest, DecisionForest::FromTrees({std::move(trees)})); ASSERT_OK_AND_ASSIGN(auto expression, GetExpressionForTest("X", "Y", "X", "math.add")); ASSERT_OK_AND_ASSIGN( auto model_op, ForestModel::Create({.forest = std::move(forest), .submodel_ids = {{"X", {0}}, {"Y", {1}}}, .expression = expression})); ASSERT_OK_AND_ASSIGN(auto model, expr::CallOp(model_op, {})); FrameLayout::Builder layout_builder; ASSERT_OK_AND_ASSIGN( auto executable_model, CompileAndBindForDynamicEvaluation(expr::DynamicEvaluationEngineOptions(), &layout_builder, model, {})); FrameLayout layout = std::move(layout_builder).Build(); ASSERT_OK_AND_ASSIGN(const FrameLayout::Slot<float> output, executable_model->output_slot().ToSlot<float>()); RootEvaluationContext ctx(&layout); EXPECT_OK(executable_model->InitializeLiterals(&ctx)); EXPECT_THAT(executable_model->Execute(&ctx), IsOk()); EXPECT_THAT(ctx.Get(output), Eq(5.0f)); } TEST_F(ForestModelTest, DuplicatedNodes) { ASSERT_OK_AND_ASSIGN(auto forest, DecisionForest::FromTrees({})); ASSERT_OK_AND_ASSIGN(auto expression, GetExpressionForTest("input", "X", "input", "math.add")); ASSERT_OK_AND_ASSIGN(auto model_op, ForestModel::Create({.forest = std::move(forest), .submodel_ids = {{"X", {0}}}, .inputs = {{"input"}}, .expression = expression})); ASSERT_OK_AND_ASSIGN(auto model, expr::CallOp(model_op, {expr::Leaf("input")})); FrameLayout::Builder layout_builder; auto input_slot = layout_builder.AddSlot<float>(); ASSERT_OK_AND_ASSIGN( auto executable_model, CompileAndBindForDynamicEvaluation( expr::DynamicEvaluationEngineOptions(), &layout_builder, model, {{"input", TypedSlot::FromSlot(input_slot)}})); FrameLayout layout = std::move(layout_builder).Build(); ASSERT_OK_AND_ASSIGN(const FrameLayout::Slot<float> output, executable_model->output_slot().ToSlot<float>()); RootEvaluationContext ctx(&layout); EXPECT_OK(executable_model->InitializeLiterals(&ctx)); ctx.Set(input_slot, 3.1f); EXPECT_THAT(executable_model->Execute(&ctx), IsOk()); EXPECT_FLOAT_EQ(ctx.Get(output), 6.2f); } TEST_F(ForestModelTest, ToLowerSingleBag) { ASSERT_OK_AND_ASSIGN(auto forest, DecisionForest::FromTrees({})); ASSERT_OK_AND_ASSIGN( auto expression, GetExpressionForTest("input", "X", "Y", "math.multiply")); ASSERT_OK_AND_ASSIGN( auto model_op, ForestModel::Create({.forest = std::move(forest), .submodel_ids = {{"X", {0}}, {"Y", {1}}}, .inputs = {{"input"}}, .expression = expression})); ASSERT_OK_AND_ASSIGN(auto model, expr::CallOp(model_op, {expr::Literal<float>(1.0)})); ASSERT_OK_AND_ASSIGN(auto expanded_model, expr::ToLowest(model)); EXPECT_TRUE(IsRegisteredOperator(expanded_model->op())); EXPECT_TRUE(IsBackendOperator(*DecayRegisteredOperator(expanded_model->op()), "math.add")); EXPECT_TRUE(expanded_model->node_deps()[0]->is_literal()); EXPECT_TRUE(IsRegisteredOperator(expanded_model->node_deps()[1]->op())); EXPECT_TRUE(IsBackendOperator( *DecayRegisteredOperator(expanded_model->node_deps()[1]->op()), "math.multiply")); } TEST_F(ForestModelTest, ToLowerExpandBags) { std::vector<DecisionTree> trees(4); trees[0].adjustments = {1.0}; trees[0].tag.submodel_id = 0; trees[1].adjustments = {2.0}; trees[1].tag.submodel_id = 1; trees[2].adjustments = {4.0}; trees[2].tag.submodel_id = 2; trees[3].adjustments = {8.0}; trees[3].tag.submodel_id = 3; ASSERT_OK_AND_ASSIGN(auto forest, DecisionForest::FromTrees({std::move(trees)})); ASSERT_OK_AND_ASSIGN( auto expression, GetExpressionForTest("input", "X", "Y", "math.multiply")); ASSERT_OK_AND_ASSIGN( auto model_op, ForestModel::Create({.forest = std::move(forest), .submodel_ids = {{"X", {0, 2}}, {"Y", {1, 3}}}, .inputs = {{"input"}}, .expression = expression})); ASSERT_OK_AND_ASSIGN(auto model, expr::CallOp(model_op, {expr::Literal<float>(1.2)})); ASSERT_OK_AND_ASSIGN(auto expanded_model, expr::ToLowest(model)); EXPECT_TRUE(IsBackendOperator(*DecayRegisteredOperator(expanded_model->op()), "math.divide")); ASSERT_OK_AND_ASSIGN( auto model_fn, (ExprCompiler<std::tuple<float>, float>()).CompileOperator(model_op)); ASSERT_OK_AND_ASSIGN(float res, model_fn(1.2)); EXPECT_FLOAT_EQ(res, 69.2f); } TEST_F(ForestModelTest, OutOfBagFilters) { std::vector<DecisionTree> trees(4); trees[0].adjustments = {1.0}; trees[0].tag.submodel_id = 0; trees[1].adjustments = {2.0}; trees[1].tag.submodel_id = 1; trees[2].adjustments = {4.0}; trees[2].tag.submodel_id = 2; trees[3].adjustments = {8.0}; trees[3].tag.submodel_id = 3; ASSERT_OK_AND_ASSIGN(auto forest, DecisionForest::FromTrees({std::move(trees)})); ASSERT_OK_AND_ASSIGN( auto expression, GetExpressionForTest("input", "X", "Y", "math.multiply")); ASSERT_OK_AND_ASSIGN(auto filter0, expr::CallOp("core.less", {expr::Placeholder("input"), expr::Literal(2.0f)})); ASSERT_OK_AND_ASSIGN(auto filter1, expr::CallOp("core.less", {expr::Literal(2.0f), expr::Placeholder("input")})); ASSERT_OK_AND_ASSIGN( auto model_op, ForestModel::Create({.forest = std::move(forest), .submodel_ids = {{"X", {0, 2}}, {"Y", {1, 3}}}, .inputs = {{"input"}}, .expression = expression, .oob_filters = std::vector{filter0, filter1}})); ASSERT_OK_AND_ASSIGN(auto model, expr::CallOp(model_op, {expr::Literal<float>(1.2)})); ASSERT_OK_AND_ASSIGN(auto expanded_model, expr::ToLowest(model)); EXPECT_TRUE(IsBackendOperator(*DecayRegisteredOperator(expanded_model->op()), "math.divide")); ASSERT_OK_AND_ASSIGN(auto model_fn, (ExprCompiler<std::tuple<float>, OptionalValue<float>>()) .CompileOperator(model_op)); { ASSERT_OK_AND_ASSIGN(OptionalValue<float> res, model_fn(1)); EXPECT_EQ(res, 9.0f); } { ASSERT_OK_AND_ASSIGN(OptionalValue<float> res, model_fn(2)); EXPECT_EQ(res, OptionalValue<float>{}); } { ASSERT_OK_AND_ASSIGN(OptionalValue<float> res, model_fn(3)); EXPECT_EQ(res, 131.0f); } } TEST_F(ForestModelTest, BagsAndTruncation) { std::vector<DecisionTree> trees(4); trees[0].adjustments = {1.0}; trees[0].tag = {.step = 0, .submodel_id = 0}; trees[1].adjustments = {2.0}; trees[1].tag = {.step = 0, .submodel_id = 1}; trees[2].adjustments = {4.0}; trees[2].tag = {.step = 1, .submodel_id = 2}; trees[3].adjustments = {8.0}; trees[3].tag = {.step = 1, .submodel_id = 3}; ASSERT_OK_AND_ASSIGN(auto forest, DecisionForest::FromTrees({std::move(trees)})); ASSERT_OK_AND_ASSIGN( auto expression, GetExpressionForTest("input", "X", "Y", "math.multiply")); ASSERT_OK_AND_ASSIGN( auto model_op, ForestModel::Create({.forest = std::move(forest), .submodel_ids = {{"X", {0, 2}}, {"Y", {1, 3}}}, .inputs = {{"input"}}, .expression = expression, .truncation_step = 1})); ASSERT_OK_AND_ASSIGN( auto model_fn, (ExprCompiler<std::tuple<float>, float>()).CompileOperator(model_op)); ASSERT_OK_AND_ASSIGN(float res, model_fn(1.2)); EXPECT_FLOAT_EQ(res, 5.2f); } TEST_F(ForestModelTest, ConversionToOptional) { ASSERT_OK_AND_ASSIGN(const auto model_op, CreateForestModelOp()); const auto input = expr::Literal<float>(1.0); ASSERT_OK_AND_ASSIGN(const auto converted_input, expr::CallOp("core.to_optional", {input})); ASSERT_OK_AND_ASSIGN( auto model, expr::CallOp(model_op, {input, expr::Literal<int64_t>(5)})); ASSERT_OK_AND_ASSIGN(auto expanded_model, expr::ToLowest(model)); ASSERT_OK_AND_ASSIGN( auto model_with_converted_input, expr::CallOp(model_op, {converted_input, expr::Literal<int64_t>(5)})); ASSERT_OK_AND_ASSIGN(auto expanded_model_with_converted_input, expr::ToLowest(model_with_converted_input)); EXPECT_THAT(expanded_model_with_converted_input, EqualsExpr(expanded_model)); } TEST_F(ForestModelTest, ConversionFromDouble) { ASSERT_OK_AND_ASSIGN(const auto model_op, CreateForestModelOp()); const auto input = expr::Literal<double>(1.0); ASSERT_OK_AND_ASSIGN(const auto converted_input, expr::CallOp("core.to_float32", {input})); ASSERT_OK_AND_ASSIGN( auto model, expr::CallOp(model_op, {input, expr::Literal<int64_t>(5)})); ASSERT_OK_AND_ASSIGN(auto expanded_model, expr::ToLowest(model)); ASSERT_OK_AND_ASSIGN( auto model_with_converted_input, expr::CallOp(model_op, {converted_input, expr::Literal<int64_t>(5)})); ASSERT_OK_AND_ASSIGN(auto expanded_model_with_converted_input, expr::ToLowest(model_with_converted_input)); EXPECT_THAT(expanded_model_with_converted_input, EqualsExpr(expanded_model)); } TEST_F(ForestModelTest, ConversionFromInteger) { ASSERT_OK_AND_ASSIGN(const auto model_op, CreateForestModelOp()); const auto input = expr::Literal<int>(1); ASSERT_OK_AND_ASSIGN(const auto converted_input, expr::CallOp("core.to_float32", {input})); ASSERT_OK_AND_ASSIGN( auto model, expr::CallOp(model_op, {input, expr::Literal<int64_t>(5)})); ASSERT_OK_AND_ASSIGN(auto expanded_model, expr::ToLowest(model)); ASSERT_OK_AND_ASSIGN( auto model_with_converted_input, expr::CallOp(model_op, {converted_input, expr::Literal<int64_t>(5)})); ASSERT_OK_AND_ASSIGN(auto expanded_model_with_converted_input, expr::ToLowest(model_with_converted_input)); EXPECT_THAT(expanded_model_with_converted_input, EqualsExpr(expanded_model)); } TEST_F(ForestModelTest, EvaluateOnScalars) { ASSERT_OK_AND_ASSIGN(auto forest_model, CreateForestModelOp()); ASSERT_OK_AND_ASSIGN( auto model, expr::CallOp(forest_model, {expr::Leaf("f"), expr::Leaf("i")})); FrameLayout::Builder layout_builder; auto f_slot = layout_builder.AddSlot<float>(); auto i_slot = layout_builder.AddSlot<int64_t>(); ASSERT_OK_AND_ASSIGN( auto executable_model, CompileAndBindForDynamicEvaluation(expr::DynamicEvaluationEngineOptions(), &layout_builder, model, {{"f", TypedSlot::FromSlot(f_slot)}, {"i", TypedSlot::FromSlot(i_slot)}})); FrameLayout layout = std::move(layout_builder).Build(); ASSERT_OK_AND_ASSIGN(const FrameLayout::Slot<float> output, executable_model->output_slot().ToSlot<float>()); RootEvaluationContext ctx(&layout); EXPECT_OK(executable_model->InitializeLiterals(&ctx)); ctx.Set(f_slot, 1.0f); ctx.Set(i_slot, 5); EXPECT_THAT(executable_model->Execute(&ctx), IsOk()); EXPECT_FLOAT_EQ(ctx.Get(output), 5.5f); ctx.Set(f_slot, 3.0f); ctx.Set(i_slot, 0); EXPECT_THAT(executable_model->Execute(&ctx), IsOk()); EXPECT_FLOAT_EQ(ctx.Get(output), 8.5f); } TEST_F(ForestModelTest, EvaluateOnScalarAndArray) { ASSERT_OK_AND_ASSIGN(auto forest_model, CreateForestModelOp()); ASSERT_OK_AND_ASSIGN( auto model, expr::CallOp(forest_model, {expr::Leaf("f"), expr::Leaf("i")})); FrameLayout::Builder layout_builder; auto f_slot = layout_builder.AddSlot<DenseArray<float>>(); auto i_slot = layout_builder.AddSlot<int64_t>(); EXPECT_THAT( CompileAndBindForDynamicEvaluation(expr::DynamicEvaluationEngineOptions(), &layout_builder, model, {{"f", TypedSlot::FromSlot(f_slot)}, {"i", TypedSlot::FromSlot(i_slot)}}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("either all forest inputs must be scalars or all " "forest inputs must be arrays, but arg[0] is " "DENSE_ARRAY_FLOAT32 and " "arg[1] is OPTIONAL_INT64"))); } TEST_F(ForestModelTest, EvaluateOnDenseArrays) { ASSERT_OK_AND_ASSIGN(const auto model_op, CreateForestModelOp()); ASSERT_OK_AND_ASSIGN( auto model, expr::CallOp(model_op, {expr::Leaf("f"), expr::Leaf("i")})); FrameLayout::Builder layout_builder; auto f_slot = layout_builder.AddSlot<DenseArray<float>>(); auto i_slot = layout_builder.AddSlot<DenseArray<int64_t>>(); ASSERT_OK_AND_ASSIGN( auto executable_model, CompileAndBindForDynamicEvaluation(expr::DynamicEvaluationEngineOptions(), &layout_builder, model, {{"f", TypedSlot::FromSlot(f_slot)}, {"i", TypedSlot::FromSlot(i_slot)}})); FrameLayout layout = std::move(layout_builder).Build(); ASSERT_OK_AND_ASSIGN( const FrameLayout::Slot<DenseArray<float>> output, executable_model->output_slot().ToSlot<DenseArray<float>>()); RootEvaluationContext ctx(&layout); EXPECT_OK(executable_model->InitializeLiterals(&ctx)); ctx.Set(f_slot, CreateDenseArray<float>({1.0f, 3.0f})); ctx.Set(i_slot, CreateDenseArray<int64_t>({5, 0})); EXPECT_THAT(executable_model->Execute(&ctx), IsOk()); EXPECT_THAT(ctx.Get(output), ElementsAre(5.5f, 8.5f)); } } }
2,390
cpp
google/arolla
decision_forest_operator
arolla/decision_forest/expr_operator/decision_forest_operator.cc
arolla/decision_forest/expr_operator/decision_forest_operator_test.cc
#ifndef AROLLA_DECISION_FOREST_EXPR_OPERATOR_DECISION_FOREST_OPERATOR_H_ #define AROLLA_DECISION_FOREST_EXPR_OPERATOR_DECISION_FOREST_OPERATOR_H_ #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "arolla/decision_forest/decision_forest.h" #include "arolla/expr/basic_expr_operator.h" #include "arolla/expr/expr_operator.h" #include "arolla/qtype/qtype.h" namespace arolla { class DecisionForestOperator : public expr::BasicExprOperator, public expr::BuiltinExprOperatorTag { public: DecisionForestOperator(DecisionForestPtr forest, std::vector<TreeFilter> tree_filters); DecisionForestOperator( DecisionForestPtr forest, std::vector<TreeFilter> tree_filters, const absl::flat_hash_map<int, QTypePtr>& required_types); absl::StatusOr<QTypePtr> GetOutputQType( absl::Span<const QTypePtr> input_qtypes) const final; DecisionForestPtr forest() const { return forest_; } const std::vector<TreeFilter>& tree_filters() const { return tree_filters_; } absl::string_view py_qvalue_specialization_key() const final { return "::arolla::DecisionForestOperator"; } private: DecisionForestOperator(std::vector<int> required_input_ids, DecisionForestPtr forest, std::vector<TreeFilter> tree_filters); DecisionForestPtr forest_; std::vector<TreeFilter> tree_filters_; std::vector<int> required_input_ids_; }; } #endif #include "arolla/decision_forest/expr_operator/decision_forest_operator.h" #include <algorithm> #include <utility> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "absl/types/span.h" #include "arolla/decision_forest/decision_forest.h" #include "arolla/expr/basic_expr_operator.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/qtype/array_like/array_like_qtype.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/tuple_qtype.h" #include "arolla/util/fingerprint.h" #include "arolla/util/status_macros_backport.h" namespace arolla { namespace { std::vector<int> GetRequiredInputIds( const absl::flat_hash_map<int, QTypePtr>& required_types) { std::vector<int> result; result.reserve(required_types.size()); for (const auto& [id, _] : required_types) { result.push_back(id); } return result; } } DecisionForestOperator::DecisionForestOperator( DecisionForestPtr forest, std::vector<TreeFilter> tree_filters) : DecisionForestOperator(GetRequiredInputIds(forest->GetRequiredQTypes()), forest, std::move(tree_filters)) {} DecisionForestOperator::DecisionForestOperator( DecisionForestPtr forest, std::vector<TreeFilter> tree_filters, const absl::flat_hash_map<int, QTypePtr>& required_types) : DecisionForestOperator(GetRequiredInputIds(required_types), std::move(forest), std::move(tree_filters)) {} DecisionForestOperator::DecisionForestOperator( std::vector<int> required_input_ids, DecisionForestPtr forest, std::vector<TreeFilter> tree_filters) : BasicExprOperator( "anonymous.decision_forest_operator", expr::ExprOperatorSignature::MakeVariadicArgs(), "Evaluates decision forest stored in the operator state.", FingerprintHasher("::arolla::DecisionForestOperator") .Combine(forest->fingerprint()) .CombineSpan(tree_filters) .Finish()), forest_(std::move(forest)), tree_filters_(std::move(tree_filters)), required_input_ids_(std::move(required_input_ids)) { std::sort(required_input_ids_.begin(), required_input_ids_.end()); } absl::StatusOr<QTypePtr> DecisionForestOperator::GetOutputQType( absl::Span<const QTypePtr> input_qtypes) const { int last_forest_input_id = required_input_ids_.empty() ? -1 : required_input_ids_.back(); if (last_forest_input_id >= static_cast<int>(input_qtypes.size())) { return absl::InvalidArgumentError(absl::StrFormat( "not enough arguments for the decision forest: expected at least %d, " "got %d", last_forest_input_id + 1, input_qtypes.size())); } bool batched = !input_qtypes.empty() && !required_input_ids_.empty() && IsArrayLikeQType(input_qtypes[required_input_ids_[0]]); for (int id : required_input_ids_) { if (IsArrayLikeQType(input_qtypes[id]) != batched) { DCHECK(!required_input_ids_.empty()); return absl::InvalidArgumentError(absl::StrFormat( "either all forest inputs must be scalars or all forest inputs " "must be arrays, but arg[%d] is %s and arg[%d] is %s", required_input_ids_[0], input_qtypes[required_input_ids_[0]]->name(), id, input_qtypes[id]->name())); } } QTypePtr output_type; if (batched) { DCHECK(!required_input_ids_.empty()); ASSIGN_OR_RETURN(const ArrayLikeQType* array_type, ToArrayLikeQType(input_qtypes[required_input_ids_[0]])); ASSIGN_OR_RETURN(output_type, array_type->WithValueQType(GetQType<float>())); } else { output_type = GetQType<float>(); } return MakeTupleQType( std::vector<QTypePtr>(tree_filters_.size(), output_type)); } }
#include "arolla/decision_forest/expr_operator/decision_forest_operator.h" #include <cstdint> #include <limits> #include <memory> #include <utility> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "arolla/decision_forest/decision_forest.h" #include "arolla/decision_forest/split_conditions/interval_split_condition.h" #include "arolla/decision_forest/split_conditions/set_of_values_split_condition.h" #include "arolla/dense_array/qtype/types.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/tuple_qtype.h" #include "arolla/util/init_arolla.h" #include "arolla/util/testing/status_matchers_backport.h" namespace arolla { namespace { using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::StatusIs; using ::testing::HasSubstr; constexpr float inf = std::numeric_limits<float>::infinity(); constexpr auto S = DecisionTreeNodeId::SplitNodeId; constexpr auto A = DecisionTreeNodeId::AdjustmentId; absl::StatusOr<DecisionForestPtr> CreateForest() { std::vector<DecisionTree> trees(2); trees[0].adjustments = {0.5, 1.5, 2.5, 3.5}; trees[0].tag.submodel_id = 0; trees[0].split_nodes = { {S(1), S(2), IntervalSplit(0, 1.5, inf)}, {A(0), A(1), SetOfValuesSplit<int64_t>(1, {5}, false)}, {A(2), A(3), IntervalSplit(0, -inf, 10)}}; trees[1].adjustments = {5}; trees[1].tag.submodel_id = 1; return DecisionForest::FromTrees(std::move(trees)); } class DecisionForestOperatorTest : public ::testing::Test { void SetUp() override { CHECK_OK(InitArolla()); } }; TEST_F(DecisionForestOperatorTest, GetOutputQType) { ASSERT_OK_AND_ASSIGN(const DecisionForestPtr forest, CreateForest()); { auto forest_op = std::make_shared<DecisionForestOperator>( forest, std::vector<TreeFilter>{}); EXPECT_THAT(forest_op->GetOutputQType({GetQType<float>()}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("not enough arguments for the decision " "forest: expected at least 2, got 1"))); EXPECT_THAT( forest_op->GetOutputQType( {GetQType<float>(), GetDenseArrayQType<float>()}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("either all forest inputs must be scalars or all " "forest inputs must be arrays, but arg[0] is " "FLOAT32 and arg[1] is DENSE_ARRAY_FLOAT32"))); EXPECT_THAT( forest_op->GetOutputQType({GetQType<float>(), GetQType<float>()}), IsOkAndHolds(MakeTupleQType({}))); } { auto forest_op = std::make_shared<DecisionForestOperator>( forest, std::vector<TreeFilter>{TreeFilter{.submodels = {0}}, TreeFilter{.submodels = {1, 2}}}); EXPECT_THAT(forest_op->GetOutputQType({GetQType<float>()}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("not enough arguments for the decision " "forest: expected at least 2, got 1"))); EXPECT_THAT( forest_op->GetOutputQType( {GetQType<float>(), GetDenseArrayQType<float>()}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("either all forest inputs must be scalars or all " "forest inputs must be arrays, but arg[0] is " "FLOAT32 and arg[1] is DENSE_ARRAY_FLOAT32"))); EXPECT_THAT( forest_op->GetOutputQType({GetQType<float>(), GetQType<float>()}), IsOkAndHolds(MakeTupleQType({GetQType<float>(), GetQType<float>()}))); } } } }
2,391
cpp
google/arolla
dense_array
arolla/dense_array/dense_array.cc
arolla/dense_array/dense_array_test.cc
#ifndef AROLLA_DENSE_ARRAY_DENSE_ARRAY_H_ #define AROLLA_DENSE_ARRAY_DENSE_ARRAY_H_ #include <cstdint> #include <cstring> #include <initializer_list> #include <optional> #include <type_traits> #include <utility> #include <vector> #include "absl/log/check.h" #include "absl/types/span.h" #include "arolla/dense_array/bitmap.h" #include "arolla/memory/buffer.h" #include "arolla/memory/optional_value.h" #include "arolla/memory/raw_buffer_factory.h" #include "arolla/util/api.h" #include "arolla/util/bits.h" #include "arolla/util/fingerprint.h" #include "arolla/util/iterator.h" #include "arolla/util/unit.h" #include "arolla/util/view_types.h" namespace arolla { template <typename T> struct AROLLA_API DenseArray { using base_type = T; using value_type = OptionalValue<view_type_t<T>>; using size_type = int64_t; using const_iterator = ConstArrayIterator<DenseArray<T>>; using difference_type = int64_t; using offset_type = int64_t; Buffer<T> values; Buffer<bitmap::Word> bitmap; int bitmap_bit_offset = 0; int64_t size() const { return values.size(); } bool empty() const { return values.empty(); } bool IsFull() const { return PresentCount() == size(); } int64_t PresentCount() const { return bitmap::CountBits(bitmap, bitmap_bit_offset, size()); } bool IsAllMissing() const { return PresentCount() == 0; } bool IsAllPresent() const { return bitmap.empty() || PresentCount() == size(); } bool present(int64_t offset) const { DCHECK_GE(offset, 0); DCHECK_LT(offset, size()); DCHECK(CheckBitmapMatchesValues()); return bitmap::GetBit(bitmap, offset + bitmap_bit_offset); } const OptionalValue<view_type_t<T>> operator[]( int64_t offset) const { if (present(offset)) { return values[offset]; } else { return std::nullopt; } } bool is_owned() const { return values.is_owner() && bitmap.is_owner(); } DenseArray MakeOwned( RawBufferFactory* buf_factory = GetHeapBufferFactory()) const { return {values.DeepCopy(buf_factory), bitmap.DeepCopy(buf_factory), bitmap_bit_offset}; } DenseArray MakeUnowned() const { return {values.ShallowCopy(), bitmap.ShallowCopy(), bitmap_bit_offset}; } DenseArray Slice(int64_t start_id, int64_t row_count) const { DCHECK_GE(start_id, 0); DCHECK_GE(row_count, 0); DCHECK_LE(start_id + row_count, size()); DenseArray res; res.values = values.Slice(start_id, row_count); if (!bitmap.empty()) { res.bitmap_bit_offset = (start_id + bitmap_bit_offset) & (bitmap::kWordBitCount - 1); int64_t b_start = (start_id + bitmap_bit_offset) / bitmap::kWordBitCount; int64_t b_size = bitmap::BitmapSize(res.bitmap_bit_offset + row_count); res.bitmap = bitmap.Slice(b_start, b_size); } return res; } DenseArray ForceNoBitmapBitOffset( RawBufferFactory* factory = GetHeapBufferFactory()) && { if (bitmap_bit_offset > 0) { int64_t bitmap_size = bitmap::BitmapSize(size()); bitmap::Bitmap::Builder bldr(bitmap_size, factory); for (int64_t i = 0; i < bitmap_size; ++i) { bldr.Set(i, bitmap::GetWordWithOffset(bitmap, i, bitmap_bit_offset)); } bitmap = std::move(bldr).Build(); bitmap_bit_offset = 0; } return std::move(*this); } DenseArray ForceNoBitmapBitOffset( RawBufferFactory* factory = GetHeapBufferFactory()) const& { DenseArray copy = *this; return std::move(copy).ForceNoBitmapBitOffset(factory); } template <typename Fn> void ForEach(Fn&& fn) const { DCHECK(CheckBitmapMatchesValues()); if (bitmap.empty()) { auto iter = values.begin(); for (int64_t id = 0; id < size(); ++id) fn(id, true, *(iter++)); } else { bitmap::IterateByGroups( bitmap.begin(), bitmap_bit_offset, size(), [&](int64_t offset) { auto values_group = values.begin() + offset; return [&fn, values_group, offset](int i, bool present) { fn(offset + i, present, values_group[i]); }; }); } } template <typename Fn> void ForEachPresent(Fn&& fn) const { ForEach([&](int64_t id, bool presence, view_type_t<T> value) { if (presence) { fn(id, value); } }); } template <typename Fn> void ForEachByGroups(Fn init_group_fn) const { DCHECK(CheckBitmapMatchesValues()); if (bitmap.empty()) { auto fn = init_group_fn(0); auto iter = values.begin(); for (int64_t id = 0; id < size(); ++id) fn(id, true, *(iter++)); } else { bitmap::IterateByGroups(bitmap.begin(), bitmap_bit_offset, size(), [&](int64_t offset) { auto values_group = values.begin() + offset; auto fn = init_group_fn(offset); return [=](int i, bool present) mutable { fn(offset + i, present, values_group[i]); }; }); } } const_iterator begin() const { return const_iterator{this, 0}; } const_iterator end() const { return const_iterator{this, size()}; } bool CheckBitmapMatchesValues() const { return bitmap.empty() || bitmap.size() == bitmap::BitmapSize(values.size() + bitmap_bit_offset); } }; template <typename T> bool ArraysAreEquivalent(const DenseArray<T>& lhs, const DenseArray<T>& rhs) { if (lhs.bitmap.empty() && rhs.bitmap.empty()) { return lhs.values == rhs.values; } if (lhs.size() != rhs.size()) return false; for (int64_t i = 0; i < lhs.size(); ++i) { if (lhs[i] != rhs[i]) return false; } return true; } template <class T> using AsDenseArray = DenseArray<strip_optional_t<std::decay_t<T>>>; struct AROLLA_API DenseArrayShape { int64_t size; bool operator==(const DenseArrayShape& other) const { return size == other.size; } }; template <typename T> class DenseArrayBuilder { public: using base_type = T; explicit DenseArrayBuilder(int64_t size, RawBufferFactory* factory = GetHeapBufferFactory()) : values_bldr_(size, factory), bitmap_bldr_(bitmap::BitmapSize(size), factory) { bitmap_ = bitmap_bldr_.GetMutableSpan().begin(); std::memset(bitmap_, 0, bitmap_bldr_.GetMutableSpan().size() * sizeof(bitmap::Word)); } template <typename ValueT> void Set(int64_t id, const ValueT& v) { if constexpr (std::is_same_v<ValueT, std::nullopt_t>) { return; } else if constexpr (is_optional_v<ValueT>) { if (!v.present) return; values_bldr_.Set(id, v.value); } else if constexpr (meta::is_wrapped_with_v<std::optional, ValueT>) { if (!v) return; if constexpr (!std::is_same_v<T, Unit>) { values_bldr_.Set(id, *v); } } else { values_bldr_.Set(id, v); } SetBit(bitmap_, id); } template <typename ValueT> void SetNConst(int64_t id, int64_t count, const ValueT& v) { if constexpr (std::is_same_v<ValueT, std::nullopt_t>) { return; } else if constexpr (is_optional_v<ValueT>) { if (!v.present) return; values_bldr_.SetNConst(id, count, v.value); } else if constexpr (meta::is_wrapped_with_v<std::optional, ValueT>) { if (!v) return; if constexpr (!std::is_same_v<T, Unit>) { values_bldr_.SetNConst(id, count, *v); } } else { values_bldr_.SetNConst(id, count, v); } SetBitsInRange(bitmap_, id, id + count); } template <typename ValueT> void Add(int64_t id, const ValueT& v) { Set(id, v); } DenseArray<T> Build() && { return {std::move(values_bldr_).Build(), std::move(bitmap_bldr_).Build()}; } DenseArray<T> Build(int64_t size) && { return {std::move(values_bldr_).Build(size), std::move(bitmap_bldr_).Build(bitmap::BitmapSize(size))}; } private: typename Buffer<T>::Builder values_bldr_; bitmap::Bitmap::Builder bitmap_bldr_; bitmap::Word* bitmap_; }; template <typename T> DenseArray<T> CreateDenseArray( absl::Span<const OptionalValue<T>> data, RawBufferFactory* factory = GetHeapBufferFactory()) { typename Buffer<T>::Builder values_builder(data.size(), factory); auto values_inserter = values_builder.GetInserter(); bitmap::Builder bitmap_builder(data.size(), factory); bitmap_builder.AddForEach(data, [&](OptionalValue<T> v) { values_inserter.Add(v.value); return v.present; }); return {std::move(values_builder).Build(), std::move(bitmap_builder).Build()}; } template <typename DestType, class InputIt> DenseArray<DestType> CreateDenseArray( InputIt start, InputIt end, RawBufferFactory* factory = GetHeapBufferFactory()) { static_assert( std::is_same_v<typename InputIt::value_type, std::optional<typename InputIt::value_type::value_type>>, "InputIt should be iterator to container of std::optional of some " "type."); static_assert( std::is_same_v<DestType, Unit> || std::is_constructible_v<DestType, typename InputIt::value_type::value_type>, "Source type is not convertible to destination type."); auto size = std::distance(start, end); bitmap::Builder bitmap_builder(size, factory); typename Buffer<DestType>::Builder values_builder(size, factory); bitmap_builder.AddForEach( start, end, [inserter = values_builder.GetInserter()](const auto& v) mutable { if (v.has_value()) { if constexpr (std::is_same_v<DestType, Unit>) { inserter.Add(kUnit); } else { inserter.Add(static_cast<view_type_t<DestType>>(*v)); } } else { inserter.SkipN(1); } return v.has_value(); }); return DenseArray<DestType>{std::move(values_builder).Build(), std::move(bitmap_builder).Build()}; } template <typename T, typename InputIt> DenseArray<T> CreateFullDenseArray( InputIt start, InputIt end, RawBufferFactory* factory = GetHeapBufferFactory()) { return {Buffer<T>::Create(start, end, factory), Buffer<bitmap::Word>()}; } template <typename T> DenseArray<T> CreateFullDenseArray( std::initializer_list<T> data, RawBufferFactory* factory = GetHeapBufferFactory()) { return CreateFullDenseArray<T>(data.begin(), data.end(), factory); } template <typename T> DenseArray<T> CreateFullDenseArray( const std::vector<T>& data, RawBufferFactory* factory = GetHeapBufferFactory()) { return CreateFullDenseArray<T>(data.begin(), data.end(), factory); } template <typename T> DenseArray<T> CreateFullDenseArray(std::vector<T>&& data, RawBufferFactory* = GetHeapBufferFactory()) { return {Buffer<T>::Create(std::move(data)), Buffer<bitmap::Word>()}; } template <typename T> DenseArray<T> CreateConstDenseArray( int64_t size, view_type_t<T> value, RawBufferFactory* buf_factory = GetHeapBufferFactory()) { typename Buffer<T>::Builder values_builder(size, buf_factory); values_builder.SetNConst(0, size, value); return DenseArray<T>{std::move(values_builder).Build()}; } template <typename T> DenseArray<T> CreateEmptyDenseArray( int64_t size, RawBufferFactory* buf_factory = GetHeapBufferFactory()) { return {Buffer<T>::CreateUninitialized(size, buf_factory), bitmap::CreateEmptyBitmap(size, buf_factory)}; } AROLLA_DECLARE_FINGERPRINT_HASHER_TRAITS(DenseArrayShape); template <typename T> struct FingerprintHasherTraits<DenseArray<T>> { void operator()(FingerprintHasher* hasher, const DenseArray<T>& arg) const { hasher->Combine(arg.size()); for (int64_t i = 0; i < arg.size(); ++i) { hasher->Combine(arg[i]); } } }; template <typename T> struct ArenaTraits<DenseArray<T>> { static DenseArray<T> MakeOwned(DenseArray<T>&& v, RawBufferFactory* buf_factory) { return v.MakeOwned(buf_factory); } }; } #endif #include "arolla/dense_array/dense_array.h" #include "arolla/util/fingerprint.h" namespace arolla { void FingerprintHasherTraits<DenseArrayShape>::operator()( FingerprintHasher* hasher, const DenseArrayShape& value) const { hasher->Combine(value.size); } }
#include "arolla/dense_array/dense_array.h" #include <cstdint> #include <optional> #include <string> #include <type_traits> #include <utility> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/strings/string_view.h" #include "arolla/memory/buffer.h" #include "arolla/memory/optional_value.h" #include "arolla/memory/raw_buffer_factory.h" #include "arolla/util/bytes.h" #include "arolla/util/text.h" #include "arolla/util/unit.h" namespace arolla { namespace { using ::testing::ElementsAre; using ::testing::ElementsAreArray; TEST(DenseArrayTest, BaseType) { static_assert(std::is_same_v<int, DenseArray<int>::base_type>); static_assert(std::is_same_v<float, DenseArray<float>::base_type>); } struct TryCompileAssignment { template <typename T> auto operator()(T v) -> decltype(v[0] = std::nullopt) { return v[0]; } }; struct TryCompileMutation { template <typename A, typename V> auto operator()(A a, V v) -> decltype(a[0].value = V()) { return a[0].value; } }; static_assert(!std::is_invocable_v<TryCompileAssignment, DenseArray<int>>); static_assert(!std::is_invocable_v<TryCompileMutation, DenseArray<Text>, absl::string_view>); TEST(DenseArrayTest, Builder) { DenseArrayBuilder<float> builder(5); EXPECT_TRUE((std::is_same_v<DenseArrayBuilder<float>::base_type, float>)); builder.Set(1, 3.0); builder.Set(2, std::optional<float>()); builder.Set(3, OptionalValue<float>(2.0)); builder.Set(4, std::nullopt); DenseArray<float> res = std::move(builder).Build(); EXPECT_THAT(res, ElementsAre(std::nullopt, 3.0, std::nullopt, 2.0, std::nullopt)); } TEST(DenseArrayTest, BuilderResizing) { DenseArrayBuilder<float> builder(10); builder.Set(1, 3.0); builder.Set(2, std::optional<float>()); builder.Set(3, OptionalValue<float>(2.0)); builder.Set(4, std::nullopt); DenseArray<float> res = std::move(builder).Build(5); EXPECT_THAT(res, ElementsAre(std::nullopt, 3.0, std::nullopt, 2.0, std::nullopt)); } TEST(DenseArrayTest, ForEach) { auto arr = CreateDenseArray<int>({2, 3, std::nullopt, 7}); int64_t expected_id = 0; arr.ForEach([&](int64_t id, bool present, int v) { EXPECT_EQ(id, expected_id); EXPECT_EQ((OptionalValue<int>{present, v}), arr[id]); EXPECT_EQ(present, arr.present(id)); if (present) { EXPECT_EQ(v, arr.values[id]); } expected_id++; }); EXPECT_EQ(expected_id, arr.size()); } TEST(DenseArrayTest, ForEachPresent) { auto arr = CreateDenseArray<int>({2, 3, std::nullopt, 7}); std::vector<int64_t> ids; std::vector<int> values; arr.ForEachPresent([&](int64_t id, int v) { ids.push_back(id); values.push_back(v); }); EXPECT_THAT(ids, ElementsAre(0, 1, 3)); EXPECT_THAT(values, ElementsAre(2, 3, 7)); } TEST(DenseArrayTest, ForEachByGroups) { constexpr int size = 100; auto gen_fn = [](int i) { return OptionalValue<int>{i % 2 == 1, i * 2}; }; DenseArrayBuilder<int> bldr(size); for (int i = 0; i < size; ++i) bldr.Set(i, gen_fn(i)); DenseArray<int> arr = std::move(bldr).Build(); int64_t expected_id = 0; int64_t expected_offset = 0; arr.ForEachByGroups([&](int64_t offset) { EXPECT_EQ(offset, expected_offset); expected_offset += 32; return [&, offset](int64_t id, bool present, int v) { EXPECT_EQ(id, expected_id); EXPECT_LT(id - offset, 32); EXPECT_EQ((OptionalValue<int>{present, v}), gen_fn(id)); expected_id++; }; }); EXPECT_EQ(expected_id, arr.size()); } TEST(DenseArrayTest, RangeFor) { auto arr = CreateDenseArray<int>({2, 3, std::nullopt, 7}); std::vector<OptionalValue<int>> res; res.reserve(arr.size()); for (const auto& v : arr) res.push_back(v); EXPECT_EQ(res.size(), arr.size()); for (int64_t i = 0; i < arr.size(); ++i) { EXPECT_EQ(res[i], arr[i]); } } TEST(DenseArrayTest, ElementsAre) { auto test_array = CreateDenseArray<float>({10.0, 20.0, 30.0, std::nullopt}); EXPECT_THAT(test_array, ElementsAre(10.0, 20.0, 30.0, std::nullopt)); } TEST(DenseArrayTest, IsFull) { { DenseArray<float> array; EXPECT_TRUE(array.IsFull()); array.values = CreateBuffer<float>({1, 2, 3}); EXPECT_TRUE(array.IsFull()); array.bitmap = CreateBuffer<uint32_t>({1}); EXPECT_FALSE(array.IsFull()); array.bitmap = CreateBuffer<uint32_t>({7}); EXPECT_TRUE(array.IsFull()); } { auto array = CreateDenseArray<float>({10.0, 20.0, 30.0, std::nullopt}); EXPECT_FALSE(array.IsFull()); } { auto array = CreateDenseArray<float>({10.0, 20.0, 30.0}); EXPECT_TRUE(array.IsFull()); } { DenseArray<float> array; array.values = CreateBuffer<float>({1.0, 2.0, 3.0}); array.bitmap = CreateBuffer<uint32_t>({7}); EXPECT_TRUE(array.IsFull()); array.bitmap_bit_offset = 1; EXPECT_FALSE(array.IsFull()); } } TEST(DenseArrayTest, AllMissing) { { DenseArray<float> array; EXPECT_TRUE(array.IsAllMissing()); array.values = CreateBuffer<float>({1, 2, 3}); EXPECT_FALSE(array.IsAllMissing()); array.bitmap = CreateBuffer<uint32_t>({1}); EXPECT_FALSE(array.IsAllMissing()); array.bitmap = CreateBuffer<uint32_t>({0}); EXPECT_TRUE(array.IsAllMissing()); } { auto array = CreateDenseArray<float>({std::nullopt, std::nullopt}); EXPECT_TRUE(array.IsAllMissing()); } { auto array = CreateDenseArray<float>({10.0, 20.0, std::nullopt}); EXPECT_FALSE(array.IsAllMissing()); } { DenseArray<float> array; array.values = CreateBuffer<float>({1.0, 2.0, 3.0}); array.bitmap = CreateBuffer<uint32_t>({5}); EXPECT_FALSE(array.IsAllMissing()); array.bitmap_bit_offset = 3; EXPECT_TRUE(array.IsAllMissing()); } } TEST(DenseArrayTest, AllPresent) { { DenseArray<float> array; EXPECT_TRUE(array.IsAllPresent()); array.values = CreateBuffer<float>({1, 2, 3}); EXPECT_TRUE(array.IsAllPresent()); array.bitmap = CreateBuffer<uint32_t>({1}); EXPECT_FALSE(array.IsAllPresent()); array.bitmap = CreateBuffer<uint32_t>({0}); EXPECT_FALSE(array.IsAllPresent()); array.bitmap = CreateBuffer<uint32_t>({0b111}); EXPECT_TRUE(array.IsAllPresent()); } { auto array = CreateDenseArray<float>({1.0f, 2.0f}); EXPECT_TRUE(array.IsAllPresent()); } { auto array = CreateDenseArray<float>({10.0, 20.0, std::nullopt}); EXPECT_FALSE(array.IsAllPresent()); } { DenseArray<float> array; array.values = CreateBuffer<float>({1.0, 2.0, 3.0}); array.bitmap = CreateBuffer<uint32_t>({0b111}); EXPECT_TRUE(array.IsAllPresent()); array.bitmap_bit_offset = 1; EXPECT_FALSE(array.IsAllPresent()); } } TEST(DenseArrayTest, PresentCount) { { DenseArray<float> array; EXPECT_EQ(array.PresentCount(), 0); array.values = CreateBuffer<float>({1, 2, 3}); EXPECT_EQ(array.PresentCount(), 3); array.bitmap = CreateBuffer<uint32_t>({1}); EXPECT_EQ(array.PresentCount(), 1); array.bitmap = CreateBuffer<uint32_t>({4}); EXPECT_EQ(array.PresentCount(), 1); array.bitmap = CreateBuffer<uint32_t>({5}); EXPECT_EQ(array.PresentCount(), 2); array.bitmap = CreateBuffer<uint32_t>({3}); EXPECT_EQ(array.PresentCount(), 2); array.bitmap = CreateBuffer<uint32_t>({7}); EXPECT_EQ(array.PresentCount(), 3); } { auto array = CreateDenseArray<float>({10.0, 20.0, 30.0, std::nullopt}); EXPECT_EQ(array.PresentCount(), 3); } { auto array = CreateDenseArray<float>({10.0, 20.0, 30.0}); EXPECT_EQ(array.PresentCount(), 3); } { DenseArray<float> array; array.values = CreateBuffer<float>({1.0, 2.0, 3.0}); array.bitmap = CreateBuffer<uint32_t>({7}); EXPECT_EQ(array.PresentCount(), 3); array.bitmap_bit_offset = 1; EXPECT_EQ(array.PresentCount(), 2); } } TEST(DenseArrayTest, MakeOwned) { std::vector<int> values{1, 2, 3, 4, 5}; std::vector<uint32_t> bitmap{0x15}; DenseArray<int> array{Buffer<int>(nullptr, values), Buffer<uint32_t>(nullptr, bitmap)}; EXPECT_FALSE(array.is_owned()); array = ArenaTraits<DenseArray<int>>::MakeOwned(std::move(array), GetHeapBufferFactory()); EXPECT_TRUE(array.is_owned()); EXPECT_THAT(array.values, ElementsAre(1, 2, 3, 4, 5)); EXPECT_THAT(array.bitmap, ElementsAre(0x15)); } TEST(DenseArrayTest, MakeUnowned) { DenseArray<int> arr = CreateDenseArray<int>({1, 2, std::nullopt, 3}); DenseArray<int> arr2 = arr.MakeUnowned(); EXPECT_TRUE(arr.is_owned()); EXPECT_FALSE(arr2.is_owned()); EXPECT_FALSE(arr2.values.is_owner()); EXPECT_FALSE(arr2.bitmap.is_owner()); EXPECT_THAT(arr2, ElementsAre(1, 2, std::nullopt, 3)); } TEST(DenseArrayTest, Slice) { DenseArray<int> full = CreateDenseArray<int>({5, 1, 3, 4, 5}); DenseArray<int> dense = CreateDenseArray<int>({5, 1, {}, {}, 5}); EXPECT_THAT(full.Slice(1, 3), ElementsAre(1, 3, 4)); EXPECT_THAT(dense.Slice(1, 4), ElementsAre(1, std::nullopt, std::nullopt, 5)); EXPECT_THAT(dense.Slice(1, 4).Slice(2, 2), ElementsAre(std::nullopt, 5)); EXPECT_THAT(dense.Slice(3, 0), ElementsAre()); EXPECT_THAT(dense.Slice(0, 3), ElementsAre(5, 1, std::nullopt)); } TEST(DenseArrayTest, ForceNoBitmapBitOffset) { DenseArray<int> with_offset = CreateDenseArray<int>({5, 1, {}, {}, 5}).Slice(1, 4); ASSERT_THAT(with_offset.bitmap_bit_offset, 1); ASSERT_THAT(with_offset, ElementsAre(1, std::nullopt, std::nullopt, 5)); DenseArray<int> without_offset = with_offset.ForceNoBitmapBitOffset(); EXPECT_THAT(without_offset.bitmap_bit_offset, 0); EXPECT_THAT(without_offset, ElementsAre(1, std::nullopt, std::nullopt, 5)); } TEST(DenseArrayTest, CreateDenseArray) { { std::vector<std::optional<int>> v{1, std::nullopt, 2, 3, std::nullopt}; auto test_array = CreateDenseArray<int64_t>(v.begin(), v.end()); EXPECT_THAT(test_array, ElementsAre(1, std::nullopt, 2, 3, std::nullopt)); EXPECT_TRUE(test_array.is_owned()); } { std::vector<std::optional<std::string>> v{"Hello", "world", std::nullopt}; auto test_array = CreateDenseArray<Bytes>(v.begin(), v.end()); EXPECT_THAT(test_array, ElementsAre("Hello", "world", std::nullopt)); } { std::vector<std::optional<absl::string_view>> v{"Hello", "world", std::nullopt}; auto test_array = CreateDenseArray<Bytes>(v.begin(), v.end()); EXPECT_THAT(test_array, ElementsAre("Hello", "world", std::nullopt)); } { std::vector<std::optional<bool>> v{false, true, std::nullopt}; auto test_array = CreateDenseArray<Unit>(v.begin(), v.end()); EXPECT_THAT(test_array, ElementsAre(kUnit, kUnit, std::nullopt)); } { UnsafeArenaBufferFactory factory(1000); std::vector<std::optional<int>> v{1, std::nullopt, 2, 3, std::nullopt}; auto test_array = CreateDenseArray<int64_t>(v.begin(), v.end(), &factory); EXPECT_THAT(test_array, ElementsAre(1, std::nullopt, 2, 3, std::nullopt)); EXPECT_FALSE(test_array.is_owned()); } } TEST(DenseArrayTest, CreateFullDenseArray) { { std::vector<int64_t> v{1, 2, 3}; DenseArray<int64_t> test_array = CreateFullDenseArray(v); EXPECT_THAT(test_array, ElementsAre(1, 2, 3)); EXPECT_TRUE(test_array.is_owned()); EXPECT_TRUE(test_array.IsFull()); } { std::vector<int> v{1, 2, 3}; auto test_array = CreateFullDenseArray<int64_t>(v.begin(), v.end()); EXPECT_THAT(test_array, ElementsAre(1, 2, 3)); EXPECT_TRUE(test_array.is_owned()); EXPECT_TRUE(test_array.IsFull()); } { std::vector<std::string> v{"Hello", "world"}; auto test_array = CreateFullDenseArray<Bytes>(v.begin(), v.end()); EXPECT_THAT(test_array, ElementsAre("Hello", "world")); EXPECT_TRUE(test_array.IsFull()); } { std::vector<absl::string_view> v{"Hello", "world"}; auto test_array = CreateFullDenseArray<Bytes>(v.begin(), v.end()); EXPECT_THAT(test_array, ElementsAre("Hello", "world")); EXPECT_TRUE(test_array.IsFull()); } { std::vector<bool> v{false, true}; auto test_array = CreateFullDenseArray<Unit>(v.begin(), v.end()); EXPECT_THAT(test_array, ElementsAre(kUnit, kUnit)); EXPECT_TRUE(test_array.IsFull()); } { UnsafeArenaBufferFactory factory(1000); std::vector<int64_t> v{1, 2, 3}; auto test_array = CreateFullDenseArray<int64_t>(v, &factory); EXPECT_THAT(test_array, ElementsAre(1, 2, 3)); EXPECT_FALSE(test_array.is_owned()); EXPECT_TRUE(test_array.IsFull()); } { std::vector<int64_t> v{1, 2, 3}; const int64_t* data = v.data(); auto test_array = CreateFullDenseArray<int64_t>(std::move(v)); EXPECT_THAT(test_array, ElementsAre(1, 2, 3)); EXPECT_EQ(test_array.values.span().data(), data); EXPECT_TRUE(test_array.is_owned()); EXPECT_TRUE(test_array.IsFull()); } { auto test_array = CreateFullDenseArray({Bytes("Hello"), Bytes("world")}); static_assert(std::is_same_v<decltype(test_array), DenseArray<Bytes>>); EXPECT_THAT(test_array, ElementsAre("Hello", "world")); EXPECT_TRUE(test_array.IsFull()); } } TEST(DenseArrayTest, ArraysAreEquivalent) { { DenseArray<int32_t> array1; DenseArray<int32_t> array2; EXPECT_TRUE(ArraysAreEquivalent(array1, array2)); } { auto array1 = CreateDenseArray<int32_t>({1, 2, std::nullopt}); auto array2 = CreateDenseArray<int32_t>({1, 2, std::nullopt}); EXPECT_TRUE(ArraysAreEquivalent(array1, array2)); } { auto array1 = CreateDenseArray<int32_t>({1, 2, std::nullopt}); auto array2 = CreateDenseArray<int32_t>({1, 3, std::nullopt}); EXPECT_FALSE(ArraysAreEquivalent(array1, array2)); } { auto array1 = CreateDenseArray<int32_t>({1, 2, std::nullopt}); auto array2 = CreateDenseArray<int32_t>({1, 2}); EXPECT_FALSE(ArraysAreEquivalent(array1, array2)); } { auto array1 = CreateDenseArray<int32_t>({1, 2, std::nullopt}); auto array2 = CreateDenseArray<int32_t>({1, 2, 3}); EXPECT_FALSE(ArraysAreEquivalent(array1, array2)); } { DenseArray<int32_t> array1; array1.values = CreateBuffer<int32_t>({1, 2, 3}); array1.bitmap = CreateBuffer<uint32_t>({7}); DenseArray<int32_t> array2; array2.values = CreateBuffer<int32_t>({1, 2, 3}); array2.bitmap = CreateBuffer<uint32_t>({14}); EXPECT_FALSE(ArraysAreEquivalent(array1, array2)); array2.bitmap_bit_offset = 1; EXPECT_TRUE(ArraysAreEquivalent(array1, array2)); } { DenseArray<int32_t> array1; array1.values = CreateBuffer<int32_t>({1, 2, 3}); EXPECT_TRUE(array1.bitmap.empty()); auto array2 = array1; EXPECT_TRUE(ArraysAreEquivalent(array1, array2)); array1.bitmap = CreateBuffer<uint32_t>({6}); EXPECT_FALSE(ArraysAreEquivalent(array1, array2)); array1.bitmap = CreateBuffer<uint32_t>({7}); EXPECT_TRUE(ArraysAreEquivalent(array1, array2)); array2.bitmap = CreateBuffer<uint32_t>({7}); EXPECT_TRUE(ArraysAreEquivalent(array1, array2)); } } template <typename T> class DenseArrayTypedTest : public ::testing::Test { public: typedef T value_type; }; using ArrayTypes = testing::Types<int, float, int64_t, double, uint64_t, Bytes, Text, Unit>; TYPED_TEST_SUITE(DenseArrayTypedTest, ArrayTypes); TYPED_TEST(DenseArrayTypedTest, CreateEmptyDenseArray) { using T = typename TestFixture::value_type; for (int64_t size = 0; size < (1ull << 20); size = size * 2 + 1) { DenseArray<T> test_array = CreateEmptyDenseArray<T>(size); EXPECT_THAT(test_array, ElementsAreArray(std::vector<std::nullopt_t>( size, std::nullopt))); EXPECT_TRUE(test_array.IsAllMissing()); } } } }
2,392
cpp
google/arolla
bitmap
arolla/dense_array/bitmap.cc
arolla/dense_array/bitmap_test.cc
#ifndef AROLLA_DENSE_ARRAY_BITMAP_H_ #define AROLLA_DENSE_ARRAY_BITMAP_H_ #include <algorithm> #include <cstddef> #include <cstdint> #include <cstdlib> #include <cstring> #include <utility> #include "absl/base/attributes.h" #include "absl/base/optimization.h" #include "absl/log/check.h" #include "absl/types/span.h" #include "arolla/memory/buffer.h" #include "arolla/memory/raw_buffer_factory.h" #include "arolla/util/preallocated_buffers.h" namespace arolla::bitmap { using Word = uint32_t; constexpr int kWordBitCount = sizeof(Word) * 8; constexpr Word kFullWord = ~Word(0); using Bitmap = Buffer<Word>; inline int64_t BitmapSize(int64_t bit_count) { return (bit_count + kWordBitCount - 1) / kWordBitCount; } inline Word GetWord(const Bitmap& bitmap, int64_t index) { if (bitmap.size() <= index) { return kFullWord; } else { return bitmap[index]; } } inline Word GetWordWithOffset(const Bitmap& bitmap, int64_t index, int offset) { DCHECK_LT(offset, kWordBitCount); if (bitmap.size() <= index) return kFullWord; Word mask = bitmap[index] >> offset; if (offset == 0 || index + 1 == bitmap.size()) { return mask; } else { return mask | (bitmap[index + 1] << (kWordBitCount - offset)); } } bool AreAllBitsSet(const Word* bitmap, int64_t bitCount); inline bool AreAllBitsUnset(const Word* bitmap, int64_t bitCount) { for (size_t i = 0; i < static_cast<size_t>(bitCount) / kWordBitCount; ++i) { if (*(bitmap++) != 0) return false; } size_t suffixBitCount = static_cast<size_t>(bitCount) % kWordBitCount; return suffixBitCount == 0 || ((*bitmap >> suffixBitCount) << suffixBitCount) == *bitmap; } ABSL_ATTRIBUTE_ALWAYS_INLINE inline void Intersect(const Bitmap& a, const Bitmap& b, absl::Span<Word> result) { DCHECK_EQ(a.size(), b.size()); DCHECK_EQ(a.size(), result.size()); Word* res = result.begin(); const Word* ra = a.begin(); const Word* rb = b.begin(); for (int64_t i = 0; i < a.size(); ++i) { res[i] = ra[i] & rb[i]; } } ABSL_ATTRIBUTE_ALWAYS_INLINE inline void Intersect(const Bitmap& a, const Bitmap& b, int bit_offset_a, int bit_offset_b, absl::Span<Word> result) { DCHECK_EQ(std::min(a.size(), b.size()), result.size()); if (bit_offset_a == bit_offset_b) { Intersect(a, b, result); } else { Word* res = result.begin(); const Word* first = a.begin(); const Word* second = b.begin(); int64_t size1 = a.size(); int64_t size2 = b.size(); if (bit_offset_a > bit_offset_b) { first = b.begin(); second = a.begin(); size1 = b.size(); size2 = a.size(); } const int offset = std::abs(bit_offset_b - bit_offset_a); for (int64_t i = 0; i < std::min(size1, size2 - 1); ++i) { Word second_shifted = (second[i] >> offset) | (second[i + 1] << (kWordBitCount - offset)); res[i] = first[i] & second_shifted; } if (size2 > 0 && size2 - 1 < size1) { res[size2 - 1] = first[size2 - 1] & (second[size2 - 1] >> offset); } } } inline bool GetBit(Word word, int bit) { return word & (Word(1) << bit); } inline bool GetBit(const Word* bitmap, int64_t bit_index) { Word word = bitmap[bit_index / kWordBitCount]; int bit = bit_index & (kWordBitCount - 1); return GetBit(word, bit); } inline bool GetBit(const Bitmap& bitmap, int64_t bit_index) { DCHECK_GE(bit_index, 0); DCHECK(bitmap.empty() || bit_index / kWordBitCount < bitmap.size()); if (bitmap.empty()) return true; Word word = bitmap[bit_index / kWordBitCount]; int bit = bit_index & (kWordBitCount - 1); return GetBit(word, bit); } inline void SetBit(Word* bitmap, int64_t bit_index) { bitmap[static_cast<size_t>(bit_index) / kWordBitCount] |= Word{1} << (bit_index & (kWordBitCount - 1)); } inline void UnsetBit(Word* bitmap, int64_t bit_index) { bitmap[static_cast<size_t>(bit_index) / kWordBitCount] &= ~(Word{1} << (bit_index & (kWordBitCount - 1))); } template <class Fn> void IterateWord(Word word, Fn&& fn, int count = kWordBitCount) { DCHECK_LE(count, kWordBitCount); for (int i = 0; i < count; ++i) { fn(i, GetBit(word, i)); } } template <class Fn> void IterateByGroups(const Word* bitmap, int64_t first_bit, int64_t count, Fn&& init_group_fn) { bitmap += static_cast<size_t>(first_bit) / kWordBitCount; int64_t bit_offset = first_bit & (kWordBitCount - 1); int64_t group_offset = 0; if (bit_offset > 0 && count > 0) { int first_word_size = std::min(count, kWordBitCount - bit_offset); bitmap::IterateWord(*(bitmap++) >> bit_offset, init_group_fn(group_offset), first_word_size); group_offset = first_word_size; } for (; group_offset <= count - kWordBitCount; group_offset += kWordBitCount) { bitmap::IterateWord(*(bitmap++), init_group_fn(group_offset)); } if (group_offset != count) { bitmap::IterateWord(*bitmap, init_group_fn(group_offset), count - group_offset); } } template <class Fn> void Iterate(const Bitmap& bitmap, int64_t first_bit, int64_t count, Fn&& fn) { if (bitmap.empty()) { for (int64_t i = 0; i < count; ++i) fn(true); } else { DCHECK_GE(bitmap.size(), BitmapSize(first_bit + count)); auto wrapped_fn = [&fn](int, bool present) { fn(present); }; IterateByGroups(bitmap.begin(), first_bit, count, [&](int64_t) { return wrapped_fn; }); } } int64_t CountBits(const Bitmap& bitmap, int64_t offset, int64_t size); using RawBuilder = Buffer<Word>::Builder; inline Bitmap CreateEmptyBitmap( int64_t bit_count, RawBufferFactory* buf_factory = GetHeapBufferFactory()) { if (bit_count <= kZeroInitializedBufferSize * 8) { return Buffer<Word>( nullptr, absl::Span<const Word>( static_cast<const Word*>(GetZeroInitializedBuffer()), BitmapSize(bit_count))); } int64_t bitmap_size = BitmapSize(bit_count); RawBuilder bldr(bitmap_size, buf_factory); std::memset(bldr.GetMutableSpan().data(), 0, bitmap_size * sizeof(Word)); return std::move(bldr).Build(); } class AlmostFullBuilder { public: explicit AlmostFullBuilder( int64_t bit_count, RawBufferFactory* buf_factory = GetHeapBufferFactory()) : bit_count_(bit_count), factory_(buf_factory) {} void AddMissed(int64_t id) { DCHECK_GE(id, 0); DCHECK_LT(id, bit_count_); if (ABSL_PREDICT_FALSE(!bitmap_)) { CreateFullBitmap(); } UnsetBit(bitmap_, id); } Bitmap Build() && { return std::move(bitmap_buffer_); } Bitmap Build(int64_t size) && { return std::move(bitmap_buffer_).Slice(0, BitmapSize(size)); } private: void CreateFullBitmap(); int64_t bit_count_; RawBufferFactory* factory_; Word* bitmap_ = nullptr; Bitmap bitmap_buffer_; }; class Builder { public: explicit Builder(int64_t bit_count, RawBufferFactory* buf_factory = GetHeapBufferFactory()) : bldr_(BitmapSize(bit_count), buf_factory) {} template <typename Fn> void AddByGroups(int64_t count, Fn&& init_group_fn) { DCHECK_LE(current_bit_ + count, bldr_.GetMutableSpan().size() * kWordBitCount); int bit_offset = current_bit_ & (kWordBitCount - 1); int64_t offset = 0; if (bit_offset == 0) { Word* data = bldr_.GetMutableSpan().begin() + (current_bit_ / kWordBitCount); for (; offset + kWordBitCount <= count; offset += kWordBitCount) { *(data++) = Group(kWordBitCount, init_group_fn(offset)); } if (offset < count) { *data = Group(count - offset, init_group_fn(offset)); } } else { absl::Span<Word> data = bldr_.GetMutableSpan(); auto add_word_fn = [&](Word w) { size_t word_id = (current_bit_ + offset) / kWordBitCount; data[word_id] |= w << bit_offset; if (word_id + 1 < data.size()) { data[word_id + 1] = w >> (kWordBitCount - bit_offset); } }; for (; offset + kWordBitCount <= count; offset += kWordBitCount) { add_word_fn(Group(kWordBitCount, init_group_fn(offset))); } if (offset < count) { add_word_fn(Group(count - offset, init_group_fn(offset))); } } current_bit_ += count; } template <typename Container, typename Fn> void AddForEach(const Container& c, Fn&& fn) { AddByGroups(std::size(c), [&](int64_t offset) { auto g = std::begin(c) + offset; return [&fn, g](int i) { return fn(g[i]); }; }); } template <typename Iterator, typename Fn> void AddForEach(Iterator from, Iterator to, Fn&& fn) { AddByGroups(to - from, [&](int64_t offset) { auto g = from + offset; return [&fn, g](int i) { return fn(g[i]); }; }); } Bitmap Build() && { if (all_present_) return Bitmap(); return std::move(bldr_).Build(); } private: template <typename Fn> Word Group(int count, Fn&& fn) { Word res = 0; for (int i = 0; i < count; ++i) { if (fn(i)) { res |= (1 << i); } else { all_present_ = false; } } return res; } Bitmap::Builder bldr_; uint64_t current_bit_ = 0; bool all_present_ = true; }; } #endif #include "arolla/dense_array/bitmap.h" #include <algorithm> #include <cstdint> #include <cstring> #include <utility> #include "absl/log/check.h" #include "arolla/util/bits.h" namespace arolla::bitmap { bool AreAllBitsSet(const Word* bitmap, int64_t bitCount) { while (bitCount >= kWordBitCount) { if (*bitmap != kFullWord) return false; bitmap++; bitCount -= kWordBitCount; } if (bitCount > 0) { auto mask = kFullWord >> (kWordBitCount - bitCount); return (*bitmap & mask) == mask; } return true; } int64_t CountBits(const Bitmap& bitmap, int64_t offset, int64_t size) { DCHECK_GE(size, 0); const int64_t begin = std::max<int64_t>( 0, std::min<int64_t>(bitmap.size() * kWordBitCount, offset)); const int64_t end = std::max<int64_t>( begin, std::min<int64_t>(bitmap.size() * kWordBitCount, offset + size)); return size - (end - begin) + GetOnesCountInRange(bitmap.span().data(), begin, end); } void AlmostFullBuilder::CreateFullBitmap() { Bitmap::Builder bldr(BitmapSize(bit_count_), factory_); auto span = bldr.GetMutableSpan(); bitmap_ = span.begin(); std::memset(bitmap_, 0xff, span.size() * sizeof(Word)); int64_t last_bits = bit_count_ & (kWordBitCount - 1); if (last_bits != 0) { span.back() &= ((Word{1} << last_bits) - 1); } bitmap_buffer_ = std::move(bldr).Build(); } }
#include "arolla/dense_array/bitmap.h" #include <algorithm> #include <cstdint> #include <memory> #include <utility> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/random/distributions.h" #include "absl/random/random.h" #include "absl/types/span.h" #include "arolla/memory/buffer.h" namespace arolla::bitmap { namespace { TEST(BitmapTest, BitmapSize) { EXPECT_EQ(BitmapSize(0), 0); EXPECT_EQ(BitmapSize(1), 1); EXPECT_EQ(BitmapSize(32), 1); EXPECT_EQ(BitmapSize(33), 2); EXPECT_EQ(BitmapSize(320), 10); EXPECT_EQ(BitmapSize(351), 11); } TEST(BitmapTest, SetBit) { Word bitmap[3] = {0, kFullWord, 0}; SetBit(bitmap, 3); UnsetBit(bitmap, 32); SetBit(bitmap, 64); UnsetBit(bitmap, 65); EXPECT_EQ(bitmap[0], 8); EXPECT_EQ(bitmap[1], kFullWord - 1); EXPECT_EQ(bitmap[2], 1); } TEST(BitmapTest, GetBit) { Word bitmap[3] = {8, kFullWord - 1, 1}; EXPECT_TRUE(GetBit(bitmap, 3)); EXPECT_FALSE(GetBit(bitmap, 32)); EXPECT_TRUE(GetBit(bitmap, 64)); EXPECT_FALSE(GetBit(bitmap, 65)); } TEST(BitmapTest, AreAllBitsSet) { Word bitmap[4] = {kFullWord, kFullWord, 3, kFullWord}; EXPECT_TRUE(AreAllBitsSet(bitmap, 64)); EXPECT_TRUE(AreAllBitsSet(bitmap, 65)); EXPECT_TRUE(AreAllBitsSet(bitmap, 66)); EXPECT_FALSE(AreAllBitsSet(bitmap, 67)); EXPECT_FALSE(AreAllBitsSet(bitmap, 128)); } TEST(BitmapTest, AreAllBitsUnset) { Word bitmap[4] = {0, 0, 12}; EXPECT_TRUE(AreAllBitsUnset(bitmap, 0)); EXPECT_TRUE(AreAllBitsUnset(bitmap, 64)); EXPECT_TRUE(AreAllBitsUnset(bitmap, 65)); EXPECT_TRUE(AreAllBitsUnset(bitmap, 66)); EXPECT_FALSE(AreAllBitsUnset(bitmap, 67)); EXPECT_FALSE(AreAllBitsUnset(bitmap, 95)); EXPECT_FALSE(AreAllBitsUnset(bitmap, 96)); } TEST(BitmapTest, Empty) { Bitmap bitmap; EXPECT_EQ(GetWord(bitmap, 0), kFullWord); EXPECT_EQ(GetWord(bitmap, 13), kFullWord); EXPECT_EQ(GetWordWithOffset(bitmap, 0, 7), kFullWord); EXPECT_EQ(GetWordWithOffset(bitmap, 13, 7), kFullWord); EXPECT_TRUE(GetBit(bitmap, 0)); EXPECT_TRUE(GetBit(bitmap, 1)); EXPECT_TRUE(GetBit(bitmap, 999)); int64_t count = 0; auto check_fn = [&](bool v) { count++; EXPECT_TRUE(v); }; Iterate(bitmap, 0, 0, check_fn); EXPECT_EQ(count, 0); Iterate(bitmap, 2, 17, check_fn); EXPECT_EQ(count, 17); count = 0; Iterate(bitmap, 99, 138, check_fn); EXPECT_EQ(count, 138); } TEST(BitmapTest, CreateEmpty) { for (int64_t size = 0; size < (1 << 20); size = (size + 1) * 2) { Bitmap bitmap = CreateEmptyBitmap(size); for (int64_t i = 0; i < BitmapSize(size); ++i) { EXPECT_EQ(GetWord(bitmap, i), 0); } for (int64_t i = 0; i < size; ++i) { EXPECT_FALSE(GetBit(bitmap, i)); } EXPECT_TRUE(AreAllBitsUnset(bitmap.span().data(), size)); } } TEST(BitmapTest, Iterate) { Bitmap bitmap = CreateBuffer<Word>({0xffff4321, 0x0, 0xf0f0f0f0, 0xffffffff}); EXPECT_EQ(GetWord(bitmap, 0), 0xffff4321); EXPECT_EQ(GetWord(bitmap, 2), 0xf0f0f0f0); EXPECT_EQ(GetWordWithOffset(bitmap, 0, 0), 0xffff4321); EXPECT_EQ(GetWordWithOffset(bitmap, 0, 31), 0x1); EXPECT_EQ(GetWordWithOffset(bitmap, 2, 8), 0xfff0f0f0); EXPECT_TRUE(GetBit(bitmap, 0)); EXPECT_FALSE(GetBit(bitmap, 1)); EXPECT_TRUE(GetBit(bitmap, 31)); EXPECT_FALSE(GetBit(bitmap, 32)); EXPECT_FALSE(GetBit(bitmap, 67)); EXPECT_TRUE(GetBit(bitmap, 68)); EXPECT_TRUE(GetBit(bitmap, 127)); int64_t bit = 0; std::unique_ptr<int> x; auto check_fn = [&, x(std::move(x))](bool v) { EXPECT_EQ(v, GetBit(bitmap, bit)); bit++; }; Iterate(bitmap, 0, 0, check_fn); EXPECT_EQ(bit, 0); Iterate(bitmap, 0, 17, check_fn); EXPECT_EQ(bit, 17); Iterate(bitmap, 17, 32, check_fn); EXPECT_EQ(bit, 17 + 32); Iterate(bitmap, 17 + 32, 69, check_fn); EXPECT_EQ(bit, 17 + 32 + 69); } TEST(BitmapTest, Intersect) { Bitmap b1 = CreateBuffer<Word>({0xffff4321, 0x0, 0xf0f0f0f0, 0xffffffff}); Bitmap b2 = CreateBuffer<Word>({0x43214321, 0x1, 0x0f0ff0f0, 0xffffffff}); Bitmap b3 = CreateBuffer<Word>({0x43214321, 0x1, 0x0f0ff0f0, 0xffffffff, 0x8}); { std::vector<Word> res(4); Intersect(b1, b2, {res.data(), res.size()}); EXPECT_THAT(res, testing::ElementsAre(0x43214321, 0x0, 0xf0f0, 0xffffffff)); } { std::vector<Word> res(4); Intersect(b1, b2, 5, 5, {res.data(), res.size()}); EXPECT_THAT(res, testing::ElementsAre(0x43214321, 0x0, 0xf0f0, 0xffffffff)); } { std::vector<Word> res(4); Intersect(b1, b3, 4, 8, {res.data(), res.size()}); EXPECT_THAT(res, testing::ElementsAre(0x14320020, 0x0, 0xf0f0f000, 0x8fffffff)); } { std::vector<Word> res(4); Intersect(b3, b1, 8, 4, {res.data(), res.size()}); EXPECT_THAT(res, testing::ElementsAre(0x14320020, 0x0, 0xf0f0f000, 0x8fffffff)); } } TEST(CountBits, Trivial) { const std::vector<uint32_t> bitmap = {1664460009U, 1830791933U, 2649253042U, 1615775603U}; const auto bit = [&](int64_t i) { return (bitmap[i / 32] >> (i % 32)) & 1; }; const auto bitmap_buffer = CreateBuffer(bitmap); const int64_t n = 32 * bitmap.size(); for (int64_t i = 0; i <= n; ++i) { int64_t count = 0; for (int64_t j = i; j < n; ++j) { ASSERT_EQ(count, CountBits(bitmap_buffer, i, j - i)) << i << ' ' << j; count += bit(j); } ASSERT_EQ(count, CountBits(bitmap_buffer, i, n - i)); } } TEST(CountBits, OutOfRange) { const auto bitmap_buffer = CreateBuffer({0xffff0000}); ASSERT_EQ(CountBits(bitmap_buffer, -30, 24), 24); ASSERT_EQ(CountBits(bitmap_buffer, -20, 24), 20); ASSERT_EQ(CountBits(bitmap_buffer, -10, 24), 10); ASSERT_EQ(CountBits(bitmap_buffer, -5, 24), 8); ASSERT_EQ(CountBits(bitmap_buffer, 0, 24), 8); ASSERT_EQ(CountBits(bitmap_buffer, 5, 24), 13); ASSERT_EQ(CountBits(bitmap_buffer, 10, 24), 18); ASSERT_EQ(CountBits(bitmap_buffer, 20, 24), 24); ASSERT_EQ(CountBits(bitmap_buffer, 30, 24), 24); ASSERT_EQ(CountBits(bitmap_buffer, 40, 24), 24); } TEST(BuilderTest, AddByGroups) { int64_t size = 16384; absl::BitGen gen; std::vector<bool> bits; Builder bldr(size); auto add_fn = [&](int) { bool v = absl::Bernoulli(gen, 0.5); bits.push_back(v); return v; }; for (int64_t remaining_count = size; remaining_count > 0;) { int64_t count = std::min(remaining_count, absl::Uniform<int64_t>(gen, 0, 256)); remaining_count -= count; bldr.AddByGroups(count, [&](int64_t) { return add_fn; }); } Bitmap bitmap = std::move(bldr).Build(); EXPECT_EQ(size, bits.size()); for (int64_t i = 0; i < bits.size(); ++i) { EXPECT_EQ(GetBit(bitmap, i), bits[i]); } } TEST(BuilderTest, AddForEachNeverCopyAFunction) { int cont[1]{0}; { std::unique_ptr<int> x; Builder b(1); b.AddForEach(cont, [x(std::move(x))](int) { return true; }); } { std::unique_ptr<int> x; Builder b(1); const auto fn = [x(std::move(x))](int) { return true; }; b.AddForEach(cont, fn); } { std::unique_ptr<int> x; int cnt = 0; Builder b(1); auto fn = [&cnt, x(std::move(x))](int) mutable { ++cnt; return true; }; b.AddForEach(cont, fn); EXPECT_EQ(cnt, 1); } } #define TEST_BITS(bitmap_expr, fn, N) \ Bitmap bitmap = bitmap_expr; \ ASSERT_EQ(bitmap.size(), BitmapSize(N)); \ for (int i = 0; i < (N); ++i) { \ ASSERT_EQ(GetBit(bitmap, i), fn(i)) << i << " of " << N; \ } TEST(BuilderTest, AddForEachSingle) { constexpr int kMaxN = 1000; std::vector<int> v(kMaxN); for (int n = 0; n < kMaxN; ++n) { v[n] = n; } auto is_5_divisible = [](int x) { return x % 5 == 0; }; for (int n = 2; n < kMaxN; ++n) { { Builder b(n); b.AddForEach(std::vector(v.begin(), v.begin() + n), is_5_divisible); TEST_BITS(std::move(b).Build(), is_5_divisible, n); } { Builder b(n); b.AddForEach(absl::MakeConstSpan(v.data(), n), is_5_divisible); TEST_BITS(std::move(b).Build(), is_5_divisible, n); } } } TEST(BuilderTest, AddForEachMany) { constexpr int kMaxN = 4027; std::vector<int> v(kMaxN); for (int n = 0; n < kMaxN; ++n) { v[n] = n; } auto is_5_divisible = [](int x) { return x % 5 == 0; }; Builder b(kMaxN); int beg = 0; for (int cnt : {2, 3, 4, 6, 9, 13, 18, 27, 47, 94, 188, 376, 752, kMaxN}) { b.AddForEach( absl::MakeConstSpan(v.data() + beg, std::min(cnt, kMaxN - beg)), is_5_divisible); beg += cnt; } TEST_BITS(std::move(b).Build(), is_5_divisible, kMaxN); } TEST(BuilderTest, Full) { Builder builder(10); builder.AddForEach(std::vector<int>(10), [](int) { return true; }); EXPECT_TRUE(std::move(builder).Build().empty()); } TEST(AlmostFullBuilderTest, Full) { AlmostFullBuilder builder(555); EXPECT_TRUE(std::move(builder).Build().empty()); } TEST(AlmostFullBuilderTest, Empty) { int64_t size = 555; AlmostFullBuilder builder(size); for (int64_t i = 0; i < size; ++i) { builder.AddMissed(i); } auto bitmap = std::move(builder).Build(); ASSERT_EQ(bitmap.size(), BitmapSize(size)); EXPECT_TRUE(AreAllBitsUnset(bitmap.span().data(), size)); for (int64_t i = 0; i < size; ++i) { EXPECT_EQ(GetBit(bitmap, i), 0); } } TEST(AlmostFullBuilderTest, NotFull) { int64_t size = 555; AlmostFullBuilder builder(size); for (int64_t i = 0; i < size; ++i) { if (i % 5 == 1) builder.AddMissed(i); } auto bitmap = std::move(builder).Build(); EXPECT_EQ(bitmap.size(), BitmapSize(size)); for (int64_t i = 0; i < size; ++i) { EXPECT_EQ(GetBit(bitmap, i), i % 5 != 1); } } TEST(AlmostFullBuilderTest, EmptyThanFull) { int64_t size = 155; for (int64_t split_point = 1; split_point < size; ++split_point) { AlmostFullBuilder builder(size); for (int64_t i = 0; i < split_point; ++i) { builder.AddMissed(i); } auto bitmap = std::move(builder).Build(); EXPECT_EQ(bitmap.size(), BitmapSize(size)); for (int64_t i = 0; i < size; ++i) { ASSERT_EQ(GetBit(bitmap, i), i >= split_point) << i << " " << split_point; } } } TEST(AlmostFullBuilderTest, EmptyConsequentlyAtStartAndAFewMissed) { int64_t size = 155; int64_t split_point = 71; AlmostFullBuilder builder(size); for (int64_t i = 0; i < split_point; ++i) { builder.AddMissed(i); } builder.AddMissed(93); builder.AddMissed(107); auto bitmap = std::move(builder).Build(); EXPECT_EQ(bitmap.size(), BitmapSize(size)); for (int64_t i = 0; i < size; ++i) { bool present = (i >= split_point) && (i != 93) && (i != 107); ASSERT_EQ(GetBit(bitmap, i), present) << i; } } } }
2,393
cpp
google/arolla
qtype_utils
arolla/codegen/qtype_utils.cc
arolla/codegen/qtype_utils_test.cc
#ifndef AROLLA_EXPR_QTYPE_UTILS_H_ #define AROLLA_EXPR_QTYPE_UTILS_H_ #include <optional> #include <string> #include <vector> #include "absl/base/nullability.h" #include "absl/container/flat_hash_map.h" #include "absl/functional/function_ref.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "arolla/expr/expr_attributes.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_visitor.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/typed_value.h" namespace arolla::expr { absl::StatusOr<absl::flat_hash_map<std::string, QTypePtr>> CollectLeafQTypes( ExprNodePtr expr); absl::StatusOr<absl::flat_hash_map<std::string, QTypePtr>> CollectLeafQTypesOnPostOrder(const PostOrder& post_order); absl::StatusOr<ExprNodePtr> PopulateQTypes( ExprNodePtr expr, absl::FunctionRef<absl::Nullable<const QType*>(absl::string_view)> get_qtype, bool allow_incomplete_type_information = false); absl::StatusOr<ExprNodePtr> PopulateQTypes( ExprNodePtr expr, const absl::flat_hash_map<std::string, QTypePtr>& leaf_qtypes, bool allow_incomplete_type_information = false); std::vector<const QType*> GetExprQTypes(absl::Span<const ExprNodePtr> nodes); std::vector<std::optional<TypedValue>> GetExprQValues( absl::Span<const ExprNodePtr> nodes); bool IsDefaultEdgeArg(const ExprNodePtr& arg); absl::StatusOr<bool> IsGroupScalarEdge(const ExprNodePtr& edge); std::vector<ExprAttributes> GetExprAttrs(absl::Span<const ExprNodePtr> nodes); std::vector<const QType* > GetAttrQTypes( absl::Span<const ExprAttributes> attrs); std::vector<const QType* > GetValueQTypes( absl::Span<const QTypePtr> qtypes); bool HasAllAttrQTypes(absl::Span<const ExprAttributes> attrs); } #endif #include "arolla/expr/qtype_utils.h" #include <cstddef> #include <optional> #include <set> #include <string> #include <utility> #include <vector> #include "absl/base/nullability.h" #include "absl/container/flat_hash_map.h" #include "absl/functional/function_ref.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "absl/strings/str_join.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "arolla/expr/annotation_expr_operators.h" #include "arolla/expr/annotation_utils.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_attributes.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_visitor.h" #include "arolla/qtype/array_like/array_like_qtype.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/shape_qtype.h" #include "arolla/qtype/typed_value.h" #include "arolla/util/unit.h" #include "arolla/util/status_macros_backport.h" namespace arolla::expr { absl::StatusOr<absl::flat_hash_map<std::string, QTypePtr>> CollectLeafQTypes( ExprNodePtr expr) { return CollectLeafQTypesOnPostOrder(PostOrder(expr)); } absl::StatusOr<absl::flat_hash_map<std::string, QTypePtr>> CollectLeafQTypesOnPostOrder(const PostOrder& post_order) { absl::flat_hash_map<std::string, QTypePtr> result; std::vector<absl::string_view> leaf_keys(post_order.nodes_size()); for (size_t i = 0; i < post_order.nodes_size(); ++i) { const auto node = post_order.node(i); if (node->is_leaf()) { leaf_keys[i] = node->leaf_key(); continue; } const auto node_dep_indices = post_order.dep_indices(i); if (node_dep_indices.empty() || leaf_keys[node_dep_indices[0]].empty()) { continue; } const absl::string_view leaf_key = leaf_keys[node_dep_indices[0]]; ASSIGN_OR_RETURN(bool is_annotation, IsAnnotation(node)); if (is_annotation) { leaf_keys[i] = leaf_key; } auto* qtype = ReadQTypeAnnotation(node); if (qtype == nullptr) { continue; } if (auto it = result.try_emplace(leaf_key, qtype).first; it->second != qtype) { return absl::InvalidArgumentError( absl::StrFormat("inconsistent qtype annotations for L.%s: %s != %s", leaf_key, qtype->name(), it->second->name())); } } return result; } absl::StatusOr<ExprNodePtr> PopulateQTypes( ExprNodePtr expr, absl::FunctionRef<absl::Nullable<const QType*>(absl::string_view)> get_qtype, bool allow_incomplete_type_information) { const auto post_order = PostOrder(expr); ASSIGN_OR_RETURN(auto expr_leaf_qtypes, CollectLeafQTypesOnPostOrder(post_order)); std::set<absl::string_view> untyped_leaves; ASSIGN_OR_RETURN( ExprNodePtr result, TransformOnPostOrder( post_order, [&](ExprNodePtr node) -> absl::StatusOr<ExprNodePtr> { if (node->is_leaf()) { if (auto qtype = get_qtype(node->leaf_key()); qtype != nullptr) { return CallOp(QTypeAnnotation::Make(), {std::move(node), Literal(qtype)}); } if (auto it = expr_leaf_qtypes.find(node->leaf_key()); it != expr_leaf_qtypes.end()) { return CallOp(QTypeAnnotation::Make(), {std::move(node), Literal(it->second)}); } if (!allow_incomplete_type_information) { untyped_leaves.insert(node->leaf_key()); } return node; } if (IsQTypeAnnotation(node) && !node->node_deps().empty()) { const auto& arg = node->node_deps().front(); if (arg->qtype() != nullptr) { return arg; } } return node; })); if (!untyped_leaves.empty()) { return absl::InvalidArgumentError( absl::StrFormat("QType for the leaves {%s} are missing, which may be " "caused by missing input features", absl::StrJoin(untyped_leaves, ", "))); } return result; } absl::StatusOr<ExprNodePtr> PopulateQTypes( ExprNodePtr expr, const absl::flat_hash_map<std::string, QTypePtr>& leaf_qtypes, bool allow_incomplete_type_information) { return PopulateQTypes( expr, [&](absl::string_view leaf_key) { auto it = leaf_qtypes.find(leaf_key); return it == leaf_qtypes.end() ? nullptr : it->second; }, allow_incomplete_type_information); } const QType* GetExprQType(ExprNodePtr node) { return node->qtype(); } std::vector<const QType*> GetExprQTypes(absl::Span<const ExprNodePtr> nodes) { std::vector<const QType*> qtypes; qtypes.reserve(nodes.size()); for (const auto& dep : nodes) { qtypes.push_back(dep->qtype()); } return qtypes; } std::vector<std::optional<TypedValue>> GetExprQValues( absl::Span<const ExprNodePtr> nodes) { std::vector<std::optional<TypedValue>> result; result.reserve(nodes.size()); for (const auto& dep : nodes) { result.emplace_back(dep->qvalue()); } return result; } namespace { bool IsDefaultEdgeQType(const QTypePtr& arg_qtype) { return arg_qtype == GetQType<Unit>(); } } bool IsDefaultEdgeArg(const ExprNodePtr& arg) { return IsDefaultEdgeQType(arg->qtype()); } absl::StatusOr<bool> IsGroupScalarEdge(const ExprNodePtr& edge) { if (edge == nullptr) { return absl::FailedPreconditionError( "Null node pointer passed to IsGroupScalarEdge."); } auto edge_type = edge->qtype(); ASSIGN_OR_RETURN(auto identified_edge_type, ToEdgeQType(edge_type)); ASSIGN_OR_RETURN(auto shape_type, ToShapeQType(identified_edge_type->parent_shape_qtype())); return shape_type == GetQType<OptionalScalarShape>(); } std::vector<ExprAttributes> GetExprAttrs(absl::Span<const ExprNodePtr> nodes) { std::vector<ExprAttributes> result; result.reserve(nodes.size()); for (const auto& node : nodes) { result.push_back(node->attr()); } return result; } std::vector<const QType*> GetAttrQTypes( absl::Span<const ExprAttributes> attrs) { std::vector<const QType*> result; result.reserve(attrs.size()); for (const auto& attr : attrs) { result.push_back(attr.qtype()); } return result; } std::vector<const QType*> GetValueQTypes(absl::Span<const QTypePtr> qtypes) { std::vector<const QType*> result; result.reserve(qtypes.size()); for (const auto qtype : qtypes) { result.push_back(qtype->value_qtype()); } return result; } bool HasAllAttrQTypes(absl::Span<const ExprAttributes> attrs) { for (const auto& attr : attrs) { if (!attr.qtype()) { return false; } } return true; } }
#include "arolla/expr/qtype_utils.h" #include <cstdint> #include <optional> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "absl/strings/string_view.h" #include "arolla/expr/annotation_expr_operators.h" #include "arolla/expr/basic_expr_operator.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_attributes.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/expr/lambda_expr_operator.h" #include "arolla/expr/testing/testing.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/optional_qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/testing/qtype.h" #include "arolla/qtype/typed_value.h" #include "arolla/util/init_arolla.h" #include "arolla/util/testing/status_matchers_backport.h" namespace arolla::expr { namespace { using ::arolla::testing::EqualsAttr; using ::arolla::testing::EqualsExpr; using ::arolla::testing::IsOk; using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::StatusIs; using ::arolla::testing::TypedValueWith; using ::arolla::testing::WithNameAnnotation; using ::arolla::testing::WithQTypeAnnotation; using ::testing::ElementsAre; using ::testing::Eq; using ::testing::HasSubstr; using ::testing::IsNull; using ::testing::Optional; using ::testing::Pair; using ::testing::UnorderedElementsAre; using Attr = ::arolla::expr::ExprAttributes; class QTypeMetadataTest : public ::testing::Test { void SetUp() override { ASSERT_OK(InitArolla()); } }; TEST_F(QTypeMetadataTest, GetExprQType_LeafWithoutQType) { ExprNodePtr leaf = Leaf("a"); EXPECT_THAT(leaf->qtype(), IsNull()); } TEST_F(QTypeMetadataTest, GetExprQType_LeafWithQType) { ASSERT_OK_AND_ASSIGN(ExprNodePtr leaf_with_qtype, WithQTypeAnnotation(Leaf("a"), GetQType<float>())); EXPECT_EQ(leaf_with_qtype->qtype(), GetQType<float>()); } TEST_F(QTypeMetadataTest, GetExprQType_ArgumentlessOperator) { ASSERT_OK_AND_ASSIGN( auto argumentless_operator, MakeLambdaOperator(ExprOperatorSignature{}, Literal(1.f))); ASSERT_OK_AND_ASSIGN(ExprNodePtr node, BindOp(argumentless_operator, {}, {})); EXPECT_THAT(node->qtype(), GetQType<float>()); } TEST_F(QTypeMetadataTest, GetExprQType) { ExprNodePtr leaf = Leaf("a"); ASSERT_OK_AND_ASSIGN(ExprNodePtr leaf_with_qtype, WithQTypeAnnotation(Leaf("a"), GetQType<float>())); ExprNodePtr literal = Literal<int64_t>(57); EXPECT_THAT(GetExprQTypes({leaf, leaf_with_qtype, literal}), ElementsAre(nullptr, GetQType<float>(), GetQType<int64_t>())); } TEST_F(QTypeMetadataTest, GetExprQValues) { ExprNodePtr literal = Literal<int64_t>(57); ExprNodePtr leaf = Leaf("a"); ASSERT_OK_AND_ASSIGN( auto argumentless_operator, MakeLambdaOperator(ExprOperatorSignature{}, Literal(1.f))); ASSERT_OK_AND_ASSIGN(ExprNodePtr argumentless_node, BindOp(argumentless_operator, {}, {})); EXPECT_THAT( GetExprQValues({literal, leaf, argumentless_node}), ElementsAre(Optional(TypedValueWith<int64_t>(57)), Eq(std::nullopt), Optional(TypedValueWith<float>(1.f)))); } TEST_F(QTypeMetadataTest, CollectLeafQTypes_Basic) { ASSERT_OK_AND_ASSIGN( ExprNodePtr expr, CallOp("test.power", {WithQTypeAnnotation(Leaf("x"), GetQType<float>()), WithQTypeAnnotation(WithNameAnnotation(Leaf("y"), "name"), GetQType<float>())})); EXPECT_THAT(CollectLeafQTypes(expr), IsOkAndHolds(UnorderedElementsAre(Pair("x", GetQType<float>()), Pair("y", GetQType<float>())))); } TEST_F(QTypeMetadataTest, CollectLeafQTypes_Partial) { ASSERT_OK_AND_ASSIGN( ExprNodePtr expr, CallOp("test.power", {WithQTypeAnnotation(Leaf("x"), GetQType<float>()), Leaf("y")})); EXPECT_THAT(CollectLeafQTypes(expr), IsOkAndHolds(UnorderedElementsAre(Pair("x", GetQType<float>())))); } TEST_F(QTypeMetadataTest, CollectLeafQTypes_Duplicate) { ASSERT_OK_AND_ASSIGN( ExprNodePtr expr, CallOp("test.power", {WithQTypeAnnotation(Leaf("x"), GetQType<float>()), WithQTypeAnnotation(WithNameAnnotation(Leaf("x"), "x"), GetQType<float>())})); EXPECT_THAT(CollectLeafQTypes(expr), IsOkAndHolds(UnorderedElementsAre(Pair("x", GetQType<float>())))); } TEST_F(QTypeMetadataTest, CollectLeafQTypes_Inconsistent) { ASSERT_OK_AND_ASSIGN( ExprNodePtr expr, CallOp("test.power", {WithQTypeAnnotation(Leaf("x"), GetQType<float>()), WithQTypeAnnotation(Leaf("x"), GetQType<int32_t>())})); EXPECT_THAT( CollectLeafQTypes(expr), StatusIs(absl::StatusCode::kInvalidArgument, "inconsistent qtype annotations for L.x: INT32 != FLOAT32")); } TEST_F(QTypeMetadataTest, CollectLeafQTypes_InconsistentNested) { auto leaf_x = Leaf("x"); auto literal_float32_qtype = Literal(GetQType<float>()); auto literal_int32_qtype = Literal(GetQType<int32_t>()); auto sub_expr = ExprNode::UnsafeMakeOperatorNode( QTypeAnnotation::Make(), {leaf_x, literal_float32_qtype}, ExprAttributes{}); auto expr = ExprNode::UnsafeMakeOperatorNode(QTypeAnnotation::Make(), {sub_expr, literal_int32_qtype}, ExprAttributes{}); EXPECT_THAT(CollectLeafQTypes(expr), StatusIs(absl::StatusCode::kInvalidArgument, "inconsistent qtype annotations for L.x: " "INT32 != FLOAT32")); } TEST_F(QTypeMetadataTest, PopulateQTypes) { ASSERT_OK_AND_ASSIGN(ExprNodePtr expr, CallOp("test.add3", {Leaf("a"), Leaf("b"), Leaf("a")})); EXPECT_THAT(PopulateQTypes(expr, {{"a", GetQType<float>()}}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("QType for the leaves {b} are missing"))); EXPECT_THAT(PopulateQTypes(expr, {}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("QType for the leaves {a, b} are missing"))); EXPECT_THAT(PopulateQTypes(expr, {{"a", GetQType<float>()}}, true), IsOk()); ASSERT_OK_AND_ASSIGN(ExprNodePtr expr_float, PopulateQTypes(expr, {{"a", GetQType<float>()}, {"b", GetQType<float>()}})); EXPECT_EQ(expr_float->qtype(), GetQType<float>()); } TEST_F(QTypeMetadataTest, PopulateQTypes_WithGetter) { ASSERT_OK_AND_ASSIGN(ExprNodePtr expr, CallOp("test.add3", {Leaf("a"), Leaf("b"), Leaf("a")})); EXPECT_THAT(PopulateQTypes(expr, [](auto) { return nullptr; }), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("QType for the leaves {a, b} are missing"))); EXPECT_THAT(PopulateQTypes(expr, [](absl::string_view leaf_name) { return leaf_name == "a" ? GetQType<float>() : nullptr; }), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("QType for the leaves {b} are missing"))); EXPECT_THAT(PopulateQTypes( expr, [](auto) { return nullptr; }, true), IsOk()); ASSERT_OK_AND_ASSIGN(ExprNodePtr expr_float, PopulateQTypes(expr, [](auto) { return GetQType<float>(); })); EXPECT_EQ(expr_float->qtype(), GetQType<float>()); } TEST_F(QTypeMetadataTest, PopulateQTypes_CollectingQTypesFromExpr) { ASSERT_OK_AND_ASSIGN( auto expr, CallOp("test.add3", {WithQTypeAnnotation(Leaf("a"), GetQType<float>()), Leaf("b"), Leaf("a")})); ASSERT_OK_AND_ASSIGN(auto actual_expr, PopulateQTypes(expr, {{"b", GetQType<double>()}})); ASSERT_OK_AND_ASSIGN( auto expected_expr, CallOp("test.add3", {CallOp(QTypeAnnotation::Make(), {Leaf("a"), Literal(GetQType<float>())}), CallOp(QTypeAnnotation::Make(), {Leaf("b"), Literal(GetQType<double>())}), CallOp(QTypeAnnotation::Make(), {Leaf("a"), Literal(GetQType<float>())})})); EXPECT_THAT(actual_expr, EqualsExpr(expected_expr)); } TEST_F(QTypeMetadataTest, PopulateQType_QTypeMismatch) { ASSERT_OK_AND_ASSIGN(ExprNodePtr expr, WithQTypeAnnotation(Leaf("a"), GetQType<int32_t>())); EXPECT_THAT( PopulateQTypes(expr, {{"a", GetQType<float>()}}), StatusIs( absl::StatusCode::kInvalidArgument, HasSubstr( "inconsistent annotation.qtype(expr: FLOAT32, qtype=INT32)"))); } TEST_F(QTypeMetadataTest, BackendWrappingOperator) { ASSERT_OK_AND_ASSIGN(ExprNodePtr expr, CallOp("math.add", {Leaf("a"), Leaf("b")})); { ASSERT_OK_AND_ASSIGN(ExprNodePtr typed_expr, PopulateQTypes(expr, {{"a", GetQType<double>()}, {"b", GetQType<float>()}})); EXPECT_EQ(typed_expr->qtype(), GetQType<double>()); } { ASSERT_OK_AND_ASSIGN(ExprNodePtr typed_expr, PopulateQTypes(expr, {{"a", GetQType<float>()}, {"b", GetQType<float>()}})); EXPECT_EQ(typed_expr->qtype(), GetQType<float>()); } { EXPECT_THAT( PopulateQTypes(expr, {{"a", GetQType<int32_t>()}, {"b", GetQType<float>()}}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("incompatible types x: INT32 and y: FLOAT32"))); } } TEST_F(QTypeMetadataTest, GetExprAttrs) { ASSERT_OK_AND_ASSIGN(ExprNodePtr a, WithQTypeAnnotation(Leaf("a"), GetQType<int32_t>())); ExprNodePtr b = Literal(1.0f); ExprNodePtr c = Placeholder("c"); EXPECT_THAT(GetExprAttrs({}), ElementsAre()); EXPECT_THAT(GetExprAttrs({a, b, c}), ElementsAre(EqualsAttr(GetQType<int32_t>()), EqualsAttr(TypedValue::FromValue(1.0f)), EqualsAttr(nullptr))); } TEST_F(QTypeMetadataTest, GetAttrQTypes) { EXPECT_THAT(GetAttrQTypes({}), ElementsAre()); EXPECT_THAT(GetAttrQTypes({Attr{}}), ElementsAre(nullptr)); EXPECT_THAT(GetAttrQTypes( {Attr(GetQType<int32_t>()), Attr(GetQType<float>()), Attr{}}), ElementsAre(GetQType<int32_t>(), GetQType<float>(), nullptr)); } TEST_F(QTypeMetadataTest, GetValueQTypes) { EXPECT_THAT(GetValueQTypes({}), ElementsAre()); EXPECT_THAT(GetValueQTypes({GetQType<int32_t>()}), ElementsAre(nullptr)); EXPECT_THAT(GetValueQTypes({GetOptionalQType<int32_t>(), GetOptionalQType<float>(), GetQType<float>()}), ElementsAre(GetQType<int32_t>(), GetQType<float>(), nullptr)); } TEST_F(QTypeMetadataTest, HasAllAttrQTypes) { EXPECT_TRUE(HasAllAttrQTypes({})); EXPECT_TRUE( HasAllAttrQTypes({Attr(GetQType<int32_t>()), Attr(GetQType<float>())})); EXPECT_FALSE(HasAllAttrQTypes({Attr{}})); EXPECT_FALSE(HasAllAttrQTypes( {Attr(GetQType<int32_t>()), Attr(GetQType<float>()), Attr{}})); } } }
2,394
cpp
google/arolla
load_operator_package
null
null
#ifndef AROLLA_CODEGEN_OPERATOR_PACKAGE_LOAD_OPERATOR_PACKAGE_H_ #define AROLLA_CODEGEN_OPERATOR_PACKAGE_LOAD_OPERATOR_PACKAGE_H_ #include "absl/status/status.h" #include "absl/strings/string_view.h" #include "arolla/codegen/operator_package/operator_package.pb.h" namespace arolla::operator_package { absl::Status ParseEmbeddedOperatorPackage( absl::string_view embedded_zlib_data, OperatorPackageProto* operator_package_proto); absl::Status LoadOperatorPackage( const OperatorPackageProto& operator_package_proto); } #endif #include "arolla/codegen/operator_package/load_operator_package.h" #include <set> #include "absl/status/status.h" #include "absl/strings/str_format.h" #include "absl/strings/str_join.h" #include "absl/strings/string_view.h" #include "google/protobuf/io/gzip_stream.h" #include "google/protobuf/io/zero_copy_stream_impl_lite.h" #include "arolla/codegen/operator_package/operator_package.pb.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/registered_expr_operator.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/serialization/decode.h" #include "arolla/util/status_macros_backport.h" namespace arolla::operator_package { using ::arolla::expr::ExprOperatorPtr; using ::arolla::expr::ExprOperatorRegistry; absl::Status ParseEmbeddedOperatorPackage( absl::string_view embedded_zlib_data, OperatorPackageProto* operator_package_proto) { ::google::protobuf::io::ArrayInputStream input_stream(embedded_zlib_data.data(), embedded_zlib_data.size()); ::google::protobuf::io::GzipInputStream gzip_input_stream(&input_stream); if (!operator_package_proto->ParseFromZeroCopyStream(&gzip_input_stream) || gzip_input_stream.ZlibErrorMessage() != nullptr) { return absl::InternalError("unable to parse an embedded operator package"); } return absl::OkStatus(); } absl::Status LoadOperatorPackage( const OperatorPackageProto& operator_package_proto) { if (operator_package_proto.version() != 1) { return absl::InvalidArgumentError( absl::StrFormat("expected operator_package_proto.version=1, got %d", operator_package_proto.version())); } auto* const operator_registry = ExprOperatorRegistry::GetInstance(); auto check_registered_operator_presence = [&](absl::string_view name) { return operator_registry->LookupOperatorOrNull(name) != nullptr; }; std::set<absl::string_view> missing_operators; for (absl::string_view operator_name : operator_package_proto.required_registered_operators()) { if (!check_registered_operator_presence(operator_name)) { missing_operators.insert(operator_name); } } if (!missing_operators.empty()) { return absl::FailedPreconditionError( "missing dependencies: M." + absl::StrJoin(missing_operators, ", M.")); } std::set<absl::string_view> already_registered_operators; for (const auto& operator_proto : operator_package_proto.operators()) { if (check_registered_operator_presence( operator_proto.registration_name())) { already_registered_operators.insert(operator_proto.registration_name()); } } if (!already_registered_operators.empty()) { return absl::FailedPreconditionError( "already present in the registry: M." + absl::StrJoin(already_registered_operators, ", M.")); } for (int i = 0; i < operator_package_proto.operators_size(); ++i) { const auto& operator_proto = operator_package_proto.operators(i); ASSIGN_OR_RETURN(auto decode_result, serialization::Decode(operator_proto.implementation()), _ << "operators[" << i << "].registration_name=" << operator_proto.registration_name()); if (decode_result.values.size() != 1 || !decode_result.exprs.empty()) { return absl::InvalidArgumentError(absl::StrFormat( "expected to get a value, got %d values and %d exprs; " "operators[%d].registration_name=%s", decode_result.values.size(), decode_result.exprs.size(), i, operator_proto.registration_name())); } const auto& qvalue = decode_result.values[0]; if (qvalue.GetType() != GetQType<ExprOperatorPtr>()) { return absl::InvalidArgumentError(absl::StrFormat( "expected to get %s, got %s; operators[%d].registration_name=%s", GetQType<ExprOperatorPtr>()->name(), qvalue.GetType()->name(), i, operator_proto.registration_name())); } RETURN_IF_ERROR(operator_registry ->Register(operator_proto.registration_name(), qvalue.UnsafeAs<ExprOperatorPtr>()) .status()); } return absl::OkStatus(); } }
#include "arolla/codegen/operator_package/load_operator_package.h" #include <cstdint> #include <string> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "arolla/codegen/operator_package/operator_package.pb.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/lambda_expr_operator.h" #include "arolla/expr/registered_expr_operator.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/typed_value.h" #include "arolla/serialization/encode.h" #include "arolla/util/init_arolla.h" #include "arolla/util/testing/status_matchers_backport.h" namespace arolla::operator_package { namespace { using ::arolla::expr::ExprOperatorPtr; using ::arolla::expr::LookupOperator; using ::arolla::expr::Placeholder; using ::arolla::testing::StatusIs; using ::testing::HasSubstr; class ParseEmbeddedOperatorPackageTest : public ::testing::Test { protected: void SetUp() override { ASSERT_OK(InitArolla()); } }; TEST_F(ParseEmbeddedOperatorPackageTest, TrivialOperatorPackage) { OperatorPackageProto operator_package_proto; ASSERT_OK(ParseEmbeddedOperatorPackage("x\x9c\xe3`\x04\x00\x00\x13\x00\n", &operator_package_proto)); EXPECT_THAT(operator_package_proto.version(), 1); } TEST_F(ParseEmbeddedOperatorPackageTest, ZLibError) { OperatorPackageProto operator_package_proto; EXPECT_THAT(ParseEmbeddedOperatorPackage("abc", &operator_package_proto), StatusIs(absl::StatusCode::kInternal, "unable to parse an embedded operator package")); } TEST_F(ParseEmbeddedOperatorPackageTest, ProtoError) { OperatorPackageProto operator_package_proto; EXPECT_THAT( ParseEmbeddedOperatorPackage("x\xda\xe3\x98\x06\x00\x00\xa8\x00\x9f", &operator_package_proto), StatusIs(absl::StatusCode::kInternal, "unable to parse an embedded operator package")); } class LoadOperatorPackageTest : public ::testing::Test { protected: void SetUp() override { ASSERT_OK(InitArolla()); } template <typename Proto> static absl::StatusOr<std::string> SerializeToString(const Proto& proto) { if (std::string result; proto.SerializeToString(&result)) { return result; } return absl::InvalidArgumentError("unable to serialize a proto message"); } }; TEST_F(LoadOperatorPackageTest, Registration) { ASSERT_OK_AND_ASSIGN(ExprOperatorPtr op, MakeLambdaOperator(Placeholder("x"))); OperatorPackageProto operator_package_proto; operator_package_proto.set_version(1); auto* operator_proto = operator_package_proto.add_operators(); operator_proto->set_registration_name("foo.bar.registration"); ASSERT_OK_AND_ASSIGN(*operator_proto->mutable_implementation(), serialization::Encode({TypedValue::FromValue(op)}, {})); EXPECT_OK(LoadOperatorPackage(operator_package_proto)); ASSERT_OK_AND_ASSIGN(auto reg_op, LookupOperator("foo.bar.registration")); ASSERT_OK_AND_ASSIGN(auto op_impl, reg_op->GetImplementation()); ASSERT_NE(op_impl, nullptr); EXPECT_EQ(op_impl->fingerprint(), op->fingerprint()); } TEST_F(LoadOperatorPackageTest, ErrorAlreadyRegistered) { ASSERT_OK_AND_ASSIGN(ExprOperatorPtr op, MakeLambdaOperator(Placeholder("x"))); OperatorPackageProto operator_package_proto; operator_package_proto.set_version(1); auto* operator_proto = operator_package_proto.add_operators(); operator_proto->set_registration_name("foo.bar.already_registered"); ASSERT_OK_AND_ASSIGN(*operator_proto->mutable_implementation(), serialization::Encode({TypedValue::FromValue(op)}, {})); EXPECT_OK(LoadOperatorPackage(operator_package_proto)); EXPECT_THAT(LoadOperatorPackage(operator_package_proto), StatusIs(absl::StatusCode::kFailedPrecondition, "already present in the registry: " "M.foo.bar.already_registered")); } TEST_F(LoadOperatorPackageTest, ErrorUnexpectedFormatVersion) { OperatorPackageProto operator_package_proto; EXPECT_THAT(LoadOperatorPackage(operator_package_proto), StatusIs(absl::StatusCode::kInvalidArgument, "expected operator_package_proto.version=1, got 0")); } TEST_F(LoadOperatorPackageTest, ErrorMissingDependency) { OperatorPackageProto operator_package_proto; operator_package_proto.set_version(1); operator_package_proto.add_required_registered_operators("foo.bar"); operator_package_proto.add_required_registered_operators("far.boo"); EXPECT_THAT(LoadOperatorPackage(operator_package_proto), StatusIs(absl::StatusCode::kFailedPrecondition, "missing dependencies: M.far.boo, M.foo.bar")); } TEST_F(LoadOperatorPackageTest, ErrorBrokenOperatorImplementation) { OperatorPackageProto operator_package_proto; operator_package_proto.set_version(1); operator_package_proto.add_operators()->set_registration_name("foo.bar"); EXPECT_THAT(LoadOperatorPackage(operator_package_proto), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("; operators[0].registration_name=foo.bar"))); } TEST_F(LoadOperatorPackageTest, ErrorNoValueInOperatorImplementation) { OperatorPackageProto operator_package_proto; operator_package_proto.set_version(1); auto* operator_proto = operator_package_proto.add_operators(); operator_proto->set_registration_name("foo.bar"); ASSERT_OK_AND_ASSIGN(*operator_proto->mutable_implementation(), serialization::Encode({}, {})); EXPECT_THAT( LoadOperatorPackage(operator_package_proto), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("expected to get a value, got 0 values and 0 exprs; " "operators[0].registration_name=foo.bar"))); } TEST_F(LoadOperatorPackageTest, ErrorUnexpectedValueInOperatorImplementation) { OperatorPackageProto operator_package_proto; operator_package_proto.set_version(1); auto* operator_proto = operator_package_proto.add_operators(); operator_proto->set_registration_name("foo.bar"); ASSERT_OK_AND_ASSIGN( *operator_proto->mutable_implementation(), serialization::Encode({TypedValue::FromValue<int64_t>(0)}, {})); EXPECT_THAT(LoadOperatorPackage(operator_package_proto), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("expected to get EXPR_OPERATOR, got INT64; " "operators[0].registration_name=foo.bar"))); } } }
2,395
cpp
google/arolla
multi_loader
arolla/codegen/io/multi_loader.cc
arolla/codegen/io/multi_loader_test.cc
#ifndef AROLLA_CODEGEN_IO_MULTI_LOADER_H_ #define AROLLA_CODEGEN_IO_MULTI_LOADER_H_ #include <cstddef> #include <cstdint> #include <limits> #include <optional> #include <string> #include <utility> #include <vector> #include "absl/types/span.h" #include "google/protobuf/repeated_ptr_field.h" #include "arolla/dense_array/dense_array.h" #include "arolla/memory/optional_value.h" #include "arolla/proto/types.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/typed_slot.h" namespace arolla::codegen::io { constexpr size_t kSkippedOffset = std::numeric_limits<size_t>::max(); struct HierarchicalSingleValueClearInfo { uint16_t range_begin = std::numeric_limits<uint16_t>::max(); uint16_t range_end = 0; bool operator==(const HierarchicalSingleValueClearInfo& other) const { return range_begin == other.range_begin && range_end == other.range_end; } }; template <size_t kLeafCount, size_t kNodeCount> struct HierarchicalRequestedInputsData { size_t leaf_frame_offsets[kLeafCount]; bool node_requested[kNodeCount - kLeafCount] = {false}; }; template <size_t kLeafCount, size_t kNodeCount> struct HierarchicalSingleValueRequestedInputsData { template <class T> using value_type = ::arolla::OptionalValue<::arolla::proto::arolla_single_value_t<T>>; using size_type = ::arolla::DenseArrayShape; HierarchicalRequestedInputsData<kLeafCount, kNodeCount> common; HierarchicalSingleValueClearInfo node_optional_clear_infos[kNodeCount - kLeafCount]; size_t requested_offsets[kLeafCount]; HierarchicalSingleValueClearInfo node_size_clear_infos[kNodeCount - kLeafCount]; }; template <size_t kLeafCount, size_t kNodeCount> struct HierarchicalMultiValueRequestedInputsData { template <class T> using value_type = ::arolla::DenseArray<::arolla::proto::arolla_single_value_t<T>>; using size_type = ::arolla::DenseArray<::arolla::proto::arolla_size_t>; HierarchicalRequestedInputsData<kLeafCount, kNodeCount> common; }; namespace multi_loader_internal { struct HierarchicalRequestedInputsDataView { absl::Span<size_t> leaf_frame_offsets; absl::Span<bool> node_requested; }; struct HierarchicalSingleValueRequestedInputsDataView { absl::Span<HierarchicalSingleValueClearInfo> node_optional_clear_infos; absl::Span<size_t> requested_offsets; absl::Span<HierarchicalSingleValueClearInfo> node_size_clear_infos; }; void CreateHierarchicalRequestedInputs( const std::vector<std::optional<TypedSlot>>& leaf_slots, const std::vector<std::vector<size_t>>& tree, HierarchicalRequestedInputsDataView output); void CreateHierarchicalSingleValueRequestedInputs( const std::vector<std::optional<TypedSlot>>& leaf_slots, const std::vector<size_t>& size_leaves, const std::vector<std::vector<size_t>>& tree, HierarchicalSingleValueRequestedInputsDataView output); template <size_t kLeafCount, size_t kNodeCount> void CreateHierarchicalRequestedInputs( const std::vector<std::optional<TypedSlot>>& leaf_slots, const std::vector<std::vector<size_t>>& tree, HierarchicalRequestedInputsData<kLeafCount, kNodeCount>* inputs) { static_assert(kLeafCount < (1 << 16), "Too many input leaves for generated code"); multi_loader_internal::CreateHierarchicalRequestedInputs( leaf_slots, tree, multi_loader_internal::HierarchicalRequestedInputsDataView{ absl::MakeSpan(inputs->leaf_frame_offsets), absl::MakeSpan(inputs->node_requested)}); } } template <size_t kLeafCount, size_t kNodeCount> void CreateHierarchicalSingleValueRequestedInputs( const std::vector<std::optional<TypedSlot>>& leaf_slots, const std::vector<size_t>& size_leaves, const std::vector<std::vector<size_t>>& tree, HierarchicalSingleValueRequestedInputsData<kLeafCount, kNodeCount>* inputs) { static_assert(kLeafCount < (1 << 16), "Too many input leaves for generated code"); multi_loader_internal::CreateHierarchicalRequestedInputs(leaf_slots, tree, &inputs->common); multi_loader_internal::CreateHierarchicalSingleValueRequestedInputs( leaf_slots, size_leaves, tree, multi_loader_internal::HierarchicalSingleValueRequestedInputsDataView{ absl::MakeSpan(inputs->node_optional_clear_infos), absl::MakeSpan(inputs->requested_offsets), absl::MakeSpan(inputs->node_size_clear_infos)}); } template <size_t kLeafCount, size_t kNodeCount> void CreateHierarchicalMultiValueRequestedInputs( const std::vector<std::optional<TypedSlot>>& leaf_slots, const std::vector<std::vector<size_t>>& tree, HierarchicalMultiValueRequestedInputsData<kLeafCount, kNodeCount>* inputs) { static_assert(kLeafCount < (1 << 16), "Too many input leaves for generated code"); multi_loader_internal::CreateHierarchicalRequestedInputs(leaf_slots, tree, &inputs->common); } template <class T> void ResizeRepeatedProtoField(google::protobuf::RepeatedPtrField<T>* field, size_t size) { arolla::proto::ResizeContainer(*field, size); } } #endif #include "arolla/codegen/io/multi_loader.h" #include <algorithm> #include <cstddef> #include <optional> #include <vector> #include "absl/log/check.h" #include "arolla/qtype/optional_qtype.h" #include "arolla/qtype/qtype.h" namespace arolla::codegen::io { namespace multi_loader_internal { void CreateHierarchicalRequestedInputs( const std::vector<std::optional<TypedSlot>>& leaf_slots, const std::vector<std::vector<size_t>>& tree, HierarchicalRequestedInputsDataView output) { CHECK_LT(leaf_slots.size(), 1 << 16) << "Too many input leaves for generated code"; std::vector<size_t> leaf_frame_offsets; std::vector<char> node_requested; node_requested.resize(tree.size(), false); for (size_t node_id = 0; node_id != tree.size(); ++node_id) { const std::vector<size_t>& children = tree[node_id]; if (children.empty()) { size_t leaf_id = leaf_frame_offsets.size(); const std::optional<TypedSlot>& slot = leaf_slots[leaf_id]; size_t offset = slot.has_value() ? slot->byte_offset() : kSkippedOffset; leaf_frame_offsets.push_back(offset); node_requested[node_id] = slot.has_value(); } else { node_requested[node_id] = false; for (size_t child : children) { CHECK_LT(child, node_id); node_requested[node_id] |= node_requested[child]; } } } std::copy(leaf_frame_offsets.begin(), leaf_frame_offsets.end(), output.leaf_frame_offsets.begin()); size_t intermediate_id = 0; for (size_t i = 0; i != tree.size(); ++i) { if (tree[i].empty()) { continue; } CHECK_LT(intermediate_id, output.node_requested.size()); output.node_requested[intermediate_id++] = node_requested[i]; } } void CreateHierarchicalSingleValueRequestedInputs( const std::vector<std::optional<TypedSlot>>& leaf_slots, const std::vector<size_t>& size_leaves, const std::vector<std::vector<size_t>>& tree, HierarchicalSingleValueRequestedInputsDataView output) { CHECK_LT(leaf_slots.size(), 1 << 16) << "Too many input leaves for generated code"; std::vector<HierarchicalSingleValueClearInfo> node_optional_clear_infos; std::vector<HierarchicalSingleValueClearInfo> node_size_clear_infos; std::vector<size_t> presence_offsets; std::vector<size_t> size_offsets; node_optional_clear_infos.resize(tree.size(), HierarchicalSingleValueClearInfo{}); node_size_clear_infos.resize(tree.size(), HierarchicalSingleValueClearInfo{}); size_t leaf_id = 0; for (size_t node_id = 0; node_id != tree.size(); ++node_id) { const std::vector<size_t>& children = tree[node_id]; auto& node_optional_clear_info = node_optional_clear_infos[node_id]; auto& node_size_clear_info = node_size_clear_infos[node_id]; if (children.empty()) { const std::optional<TypedSlot>& slot = leaf_slots[leaf_id]; size_t offset = slot.has_value() ? slot->byte_offset() : kSkippedOffset; node_optional_clear_info.range_begin = presence_offsets.size(); node_size_clear_info.range_begin = size_offsets.size(); if (offset != kSkippedOffset) { if (std::binary_search(size_leaves.begin(), size_leaves.end(), leaf_id)) { size_offsets.push_back(offset); } else if (::arolla::IsOptionalQType(slot->GetType())) { presence_offsets.push_back(offset); } } node_optional_clear_info.range_end = presence_offsets.size(); node_size_clear_info.range_end = size_offsets.size(); ++leaf_id; } else { node_optional_clear_info.range_begin = node_optional_clear_infos[children.front()].range_begin; node_optional_clear_info.range_end = node_optional_clear_infos[children.back()].range_end; node_size_clear_info.range_begin = node_size_clear_infos[children.front()].range_begin; node_size_clear_info.range_end = node_size_clear_infos[children.back()].range_end; } } CHECK_GE(output.requested_offsets.size(), presence_offsets.size() + size_offsets.size()); std::copy(presence_offsets.begin(), presence_offsets.end(), output.requested_offsets.begin()); std::copy(size_offsets.begin(), size_offsets.end(), output.requested_offsets.begin() + presence_offsets.size()); std::fill(output.requested_offsets.begin() + presence_offsets.size() + size_offsets.size(), output.requested_offsets.end(), kSkippedOffset); size_t leaf_count = 0; for (size_t i = 0; i != tree.size(); ++i) { if (tree[i].empty()) { ++leaf_count; continue; } size_t intermediate_id = i - leaf_count; output.node_optional_clear_infos[intermediate_id] = node_optional_clear_infos[i]; output.node_size_clear_infos[intermediate_id] = node_size_clear_infos[i]; output.node_size_clear_infos[intermediate_id].range_begin += presence_offsets.size(); output.node_size_clear_infos[intermediate_id].range_end += presence_offsets.size(); } } } }
#include "arolla/codegen/io/multi_loader.h" #include <optional> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "arolla/dense_array/dense_array.h" #include "arolla/dense_array/qtype/types.h" #include "arolla/memory/frame.h" #include "arolla/memory/optional_value.h" #include "arolla/proto/test.pb.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/typed_slot.h" namespace arolla::codegen::io { namespace { using ::testing::ElementsAre; TEST(SingleValueTest, CreateHierarchicalSingleValueRequestedInputsTrivialAllRequested) { FrameLayout::Builder layout_builder; auto a_slot = layout_builder.AddSlot<OptionalValue<int>>(); auto b_slot = layout_builder.AddSlot<OptionalValue<int>>(); auto c_slot = layout_builder.AddSlot<OptionalValue<int>>(); HierarchicalSingleValueRequestedInputsData<3, 4> inputs; CreateHierarchicalSingleValueRequestedInputs( {TypedSlot::FromSlot(a_slot), TypedSlot::FromSlot(b_slot), TypedSlot::FromSlot(c_slot)}, {1}, {{}, {}, {}, {0, 1, 2}}, &inputs); EXPECT_THAT(inputs.common.leaf_frame_offsets, ElementsAre(a_slot.byte_offset(), b_slot.byte_offset(), c_slot.byte_offset())); EXPECT_THAT(inputs.common.node_requested, ElementsAre(true)); EXPECT_THAT(inputs.requested_offsets, ElementsAre(a_slot.byte_offset(), c_slot.byte_offset(), b_slot.byte_offset())); EXPECT_THAT(inputs.node_optional_clear_infos, ElementsAre(HierarchicalSingleValueClearInfo{0, 2})); EXPECT_THAT(inputs.node_size_clear_infos, ElementsAre(HierarchicalSingleValueClearInfo{2, 3})); } TEST(SingleValueTest, CreateHierarchicalSingleValueRequestedInputsTrivialNothingRequested) { HierarchicalSingleValueRequestedInputsData<3, 4> inputs; CreateHierarchicalSingleValueRequestedInputs( {std::nullopt, std::nullopt, std::nullopt}, {1}, {{}, {}, {}, {0, 1, 2}}, &inputs); EXPECT_THAT(inputs.common.leaf_frame_offsets, ElementsAre(kSkippedOffset, kSkippedOffset, kSkippedOffset)); EXPECT_THAT(inputs.common.node_requested, ElementsAre(false)); EXPECT_THAT(inputs.requested_offsets, ElementsAre(kSkippedOffset, kSkippedOffset, kSkippedOffset)); EXPECT_THAT(inputs.node_optional_clear_infos, ElementsAre(HierarchicalSingleValueClearInfo{0, 0})); EXPECT_THAT(inputs.node_size_clear_infos, ElementsAre(HierarchicalSingleValueClearInfo{0, 0})); } TEST(SingleValueTest, CreateHierarchicalSingleValueRequestedInputsTrivialSizeRequested) { FrameLayout::Builder layout_builder; auto b_slot = layout_builder.AddSlot<OptionalValue<int>>(); HierarchicalSingleValueRequestedInputsData<3, 4> inputs; CreateHierarchicalSingleValueRequestedInputs( {std::nullopt, TypedSlot::FromSlot(b_slot), std::nullopt}, {1}, {{}, {}, {}, {0, 1, 2}}, &inputs); EXPECT_THAT( inputs.common.leaf_frame_offsets, ElementsAre(kSkippedOffset, b_slot.byte_offset(), kSkippedOffset)); EXPECT_THAT(inputs.common.node_requested, ElementsAre(true)); EXPECT_THAT( inputs.requested_offsets, ElementsAre(b_slot.byte_offset(), kSkippedOffset, kSkippedOffset)); EXPECT_THAT(inputs.node_optional_clear_infos, ElementsAre(HierarchicalSingleValueClearInfo{0, 0})); EXPECT_THAT(inputs.node_size_clear_infos, ElementsAre(HierarchicalSingleValueClearInfo{0, 1})); } TEST(SingleValueTest, CreateHierarchicalSingleValueRequestedInputsTrivialOptionalRequested) { FrameLayout::Builder layout_builder; auto a_slot = layout_builder.AddSlot<OptionalValue<int>>(); HierarchicalSingleValueRequestedInputsData<3, 4> inputs; CreateHierarchicalSingleValueRequestedInputs( {TypedSlot::FromSlot(a_slot), std::nullopt, std::nullopt}, {1}, {{}, {}, {}, {0, 1, 2}}, &inputs); EXPECT_THAT( inputs.common.leaf_frame_offsets, ElementsAre(a_slot.byte_offset(), kSkippedOffset, kSkippedOffset)); EXPECT_THAT(inputs.common.node_requested, ElementsAre(true)); EXPECT_THAT( inputs.requested_offsets, ElementsAre(a_slot.byte_offset(), kSkippedOffset, kSkippedOffset)); EXPECT_THAT(inputs.node_optional_clear_infos, ElementsAre(HierarchicalSingleValueClearInfo{0, 1})); EXPECT_THAT(inputs.node_size_clear_infos, ElementsAre(HierarchicalSingleValueClearInfo{1, 1})); } TEST(SingleValueTest, CreateHierarchicalSingleValueRequestedInputsHierarchyAllRequested) { FrameLayout::Builder layout_builder; auto a_slot = layout_builder.AddSlot<OptionalValue<int>>(); auto b_slot = layout_builder.AddSlot<DenseArrayShape>(); auto c_slot = layout_builder.AddSlot<OptionalValue<int>>(); auto d_slot = layout_builder.AddSlot<OptionalValue<int>>(); HierarchicalSingleValueRequestedInputsData<4, 7> inputs; CreateHierarchicalSingleValueRequestedInputs( {TypedSlot::FromSlot(a_slot), TypedSlot::FromSlot(b_slot), TypedSlot::FromSlot(c_slot), TypedSlot::FromSlot(d_slot)}, {1}, {{}, {}, {0, 1}, {}, {3}, {}, {2, 4, 5}}, &inputs); EXPECT_THAT(inputs.common.leaf_frame_offsets, ElementsAre(a_slot.byte_offset(), b_slot.byte_offset(), c_slot.byte_offset(), d_slot.byte_offset())); EXPECT_THAT(inputs.common.node_requested, ElementsAre(true, true, true)); EXPECT_THAT(inputs.requested_offsets, ElementsAre(a_slot.byte_offset(), c_slot.byte_offset(), d_slot.byte_offset(), b_slot.byte_offset())); using CI = HierarchicalSingleValueClearInfo; EXPECT_THAT(inputs.node_optional_clear_infos, ElementsAre(CI{0, 1}, CI{1, 2}, CI{0, 3})); EXPECT_THAT(inputs.node_size_clear_infos, ElementsAre(CI{3, 4}, CI{4, 4}, CI{3, 4})); } TEST(SingleValueTest, CreateHierarchicalSingleValueRequestedInputsAFewRequestedWithFullValue) { FrameLayout::Builder layout_builder; auto a_slot = layout_builder.AddSlot<OptionalValue<int>>(); auto c_slot = layout_builder.AddSlot<int>(); HierarchicalSingleValueRequestedInputsData<4, 7> inputs; CreateHierarchicalSingleValueRequestedInputs( {TypedSlot::FromSlot(a_slot), std::nullopt, TypedSlot::FromSlot(c_slot), std::nullopt}, {1}, {{}, {}, {0, 1}, {}, {3}, {}, {2, 4, 5}}, &inputs); EXPECT_THAT(inputs.common.leaf_frame_offsets, ElementsAre(a_slot.byte_offset(), kSkippedOffset, c_slot.byte_offset(), kSkippedOffset)); EXPECT_THAT(inputs.common.node_requested, ElementsAre(true, true, true)); EXPECT_THAT(inputs.requested_offsets, ElementsAre(a_slot.byte_offset(), kSkippedOffset, kSkippedOffset, kSkippedOffset)); using CI = HierarchicalSingleValueClearInfo; EXPECT_THAT(inputs.node_optional_clear_infos, ElementsAre(CI{0, 1}, CI{1, 1}, CI{0, 1})); EXPECT_THAT(inputs.node_size_clear_infos, ElementsAre(CI{1, 1}, CI{1, 1}, CI{1, 1})); } TEST(SingleValueTest, CreateHierarchicalSingleValueRequestedInputsAllRequestedWithFullValue) { FrameLayout::Builder layout_builder; auto a_slot = layout_builder.AddSlot<OptionalValue<int>>(); auto b_slot = layout_builder.AddSlot<DenseArrayShape>(); auto c_slot = layout_builder.AddSlot<int>(); auto d_slot = layout_builder.AddSlot<OptionalValue<int>>(); HierarchicalSingleValueRequestedInputsData<4, 7> inputs; CreateHierarchicalSingleValueRequestedInputs( {TypedSlot::FromSlot(a_slot), TypedSlot::FromSlot(b_slot), TypedSlot::FromSlot(c_slot), TypedSlot::FromSlot(d_slot)}, {1}, {{}, {}, {0, 1}, {}, {3}, {}, {2, 4, 5}}, &inputs); EXPECT_THAT(inputs.common.leaf_frame_offsets, ElementsAre(a_slot.byte_offset(), b_slot.byte_offset(), c_slot.byte_offset(), d_slot.byte_offset())); EXPECT_THAT(inputs.common.node_requested, ElementsAre(true, true, true)); EXPECT_THAT(inputs.requested_offsets, ElementsAre(a_slot.byte_offset(), d_slot.byte_offset(), b_slot.byte_offset(), kSkippedOffset)); using CI = HierarchicalSingleValueClearInfo; EXPECT_THAT(inputs.node_optional_clear_infos, ElementsAre(CI{0, 1}, CI{1, 1}, CI{0, 2})); EXPECT_THAT(inputs.node_size_clear_infos, ElementsAre(CI{2, 3}, CI{3, 3}, CI{2, 3})); } TEST(SingleValueTest, CreateHierarchicalSingleValueRequestedInputsHierarchySizeRequested) { FrameLayout::Builder layout_builder; auto b_slot = layout_builder.AddSlot<OptionalValue<int>>(); HierarchicalSingleValueRequestedInputsData<4, 7> inputs; CreateHierarchicalSingleValueRequestedInputs( {std::nullopt, TypedSlot::FromSlot(b_slot), std::nullopt, std::nullopt}, {1}, {{}, {}, {0, 1}, {}, {3}, {}, {2, 4}}, &inputs); EXPECT_THAT(inputs.common.leaf_frame_offsets, ElementsAre(kSkippedOffset, b_slot.byte_offset(), kSkippedOffset, kSkippedOffset)); EXPECT_THAT(inputs.common.node_requested, ElementsAre(true, false, true)); EXPECT_THAT(inputs.requested_offsets, ElementsAre(b_slot.byte_offset(), kSkippedOffset, kSkippedOffset, kSkippedOffset)); using CI = HierarchicalSingleValueClearInfo; EXPECT_THAT(inputs.node_optional_clear_infos, ElementsAre(CI{0, 0}, CI{0, 0}, CI{0, 0})); EXPECT_THAT(inputs.node_size_clear_infos, ElementsAre(CI{0, 1}, CI{1, 1}, CI{0, 1})); } TEST(SingleValueTest, CreateHierarchicalSingleValueRequestedInputsHierarchyOptionalRequested) { FrameLayout::Builder layout_builder; auto c_slot = layout_builder.AddSlot<OptionalValue<int>>(); HierarchicalSingleValueRequestedInputsData<4, 7> inputs; CreateHierarchicalSingleValueRequestedInputs( {std::nullopt, std::nullopt, TypedSlot::FromSlot(c_slot), std::nullopt}, {1}, {{}, {}, {0, 1}, {}, {3}, {}, {2, 4}}, &inputs); EXPECT_THAT(inputs.common.leaf_frame_offsets, ElementsAre(kSkippedOffset, kSkippedOffset, c_slot.byte_offset(), kSkippedOffset)); EXPECT_THAT(inputs.common.node_requested, ElementsAre(false, true, true)); EXPECT_THAT(inputs.requested_offsets, ElementsAre(c_slot.byte_offset(), kSkippedOffset, kSkippedOffset, kSkippedOffset)); using CI = HierarchicalSingleValueClearInfo; EXPECT_THAT(inputs.node_optional_clear_infos, ElementsAre(CI{0, 0}, CI{0, 1}, CI{0, 1})); EXPECT_THAT(inputs.node_size_clear_infos, ElementsAre(CI{1, 1}, CI{1, 1}, CI{1, 1})); } TEST(ResizeRepeatedProtoFieldTest, MessageResize) { testing_namespace::Root root; ResizeRepeatedProtoField(root.mutable_inners(), 5); EXPECT_EQ(root.inners_size(), 5); EXPECT_FALSE(root.inners(0).has_a()); root.mutable_inners(0)->set_a(13); ResizeRepeatedProtoField(root.mutable_inners(), 7); EXPECT_EQ(root.inners_size(), 7); EXPECT_TRUE(root.inners(0).has_a()); EXPECT_EQ(root.inners(0).a(), 13); ResizeRepeatedProtoField(root.mutable_inners(), 3); EXPECT_EQ(root.inners_size(), 3); EXPECT_TRUE(root.inners(0).has_a()); EXPECT_EQ(root.inners(0).a(), 13); ResizeRepeatedProtoField(root.mutable_inners(), 3); EXPECT_EQ(root.inners_size(), 3); EXPECT_TRUE(root.inners(0).has_a()); EXPECT_EQ(root.inners(0).a(), 13); } } }
2,396
cpp
google/arolla
codegen_operator
arolla/codegen/expr/codegen_operator.cc
arolla/codegen/expr/codegen_operator_test.cc
#ifndef AROLLA_CODEGEN_EXPR_CODEGEN_OPERATOR_H_ #define AROLLA_CODEGEN_EXPR_CODEGEN_OPERATOR_H_ #include <cstddef> #include <cstdint> #include <map> #include <ostream> #include <set> #include <string> #include <utility> #include <vector> #include "absl/status/statusor.h" #include "absl/strings/str_join.h" #include "absl/strings/string_view.h" #include "arolla/expr/expr_node.h" #include "arolla/qtype/qtype.h" namespace arolla::codegen { namespace codegen_impl { bool IsInlinableLiteralType(const QType* qtype); } enum struct LValueKind : int { kLiteral, kInput, kLocal, }; struct LValue { std::string type_name; bool is_entire_expr_status_or; bool is_local_expr_status_or; QTypePtr qtype; LValueKind kind; absl::StatusOr<std::string> QTypeConstruction() const; friend std::ostream& operator<<(std::ostream& out, const LValue& v) { return out << static_cast<int>(v.kind) << " " << v.qtype->name() << " is_entire_expr_status_or=" << v.is_entire_expr_status_or << " is_local_expr_status_or=" << v.is_local_expr_status_or; } friend bool operator==(const LValue& a, const LValue& b) { return a.type_name == b.type_name && a.is_entire_expr_status_or == b.is_entire_expr_status_or && a.is_local_expr_status_or == b.is_local_expr_status_or && a.qtype == b.qtype && a.kind == b.kind; } }; using LValueId = int64_t; enum struct RValueKind : int { kInput, kVerbatim, kFunctionCall, kFunctionWithContextCall, kFirst, kOutput, }; struct RValue { RValueKind kind; bool operator_returns_status_or; std::string code; std::vector<LValueId> argument_ids; std::vector<int> argument_as_function_offsets = {}; std::string comment; static RValue CreateInput() { return RValue{.kind = RValueKind::kInput, .operator_returns_status_or = false, .code = "", .argument_ids = {}}; } static RValue CreateLiteral(std::string code) { return RValue{.kind = RValueKind::kVerbatim, .operator_returns_status_or = false, .code = std::move(code), .argument_ids = {}}; } friend std::ostream& operator<<(std::ostream& out, const RValue& v) { return out << static_cast<int>(v.kind) << "returns_status_or=" << v.operator_returns_status_or << " " << v.code << " {" << absl::StrJoin(v.argument_ids, ",") << "}"; } friend bool operator==(const RValue& a, const RValue& b) { return a.kind == b.kind && a.operator_returns_status_or == b.operator_returns_status_or && a.code == b.code && a.argument_ids == b.argument_ids; } }; class Assignment { public: Assignment() = default; Assignment(LValue lvalue, RValue rvalue, bool inlinable = false) : lvalue_(std::move(lvalue)), rvalue_(std::move(rvalue)), inlinable_(inlinable) {} const LValue& lvalue() const { return lvalue_; } LValue& lvalue() { return lvalue_; } const RValue& rvalue() const { return rvalue_; } RValue& rvalue() { return rvalue_; } bool is_inlinable() const { return inlinable_; } void set_inlinable(bool inlinable) { inlinable_ = inlinable; } friend std::ostream& operator<<(std::ostream& out, const Assignment& s) { return out << s.lvalue_ << " = " << s.rvalue_ << ";"; } private: LValue lvalue_; RValue rvalue_; bool inlinable_; }; struct Function { std::vector<LValueId> assignment_ids; LValueId output_id; bool is_result_status_or; }; struct OperatorCodegenData { std::vector<LValueId> literal_ids() const { std::vector<LValueId> res; for (int64_t i = 0; i != assignments.size(); ++i) { if (assignments[i].lvalue().kind == LValueKind::kLiteral) { res.push_back(i); } } return res; } std::map<LValueId, std::string> input_id_to_name() const { std::map<LValueId, std::string> res; for (const auto& [name, id] : inputs) { res.emplace(id, name); } return res; } std::map<LValueId, int64_t> function_entry_points() const { std::map<LValueId, int64_t> res; size_t fn_id = 0; for (const auto& fn : functions) { res.emplace(fn.output_id, fn_id++); } return res; } std::set<std::string> deps; std::set<std::string> headers; std::map<std::string, LValueId> inputs; std::vector<std::pair<std::string, LValueId>> side_outputs; std::vector<Assignment> assignments; std::vector<Function> functions; std::vector<Function> lambdas; LValueId output_id; }; absl::StatusOr<OperatorCodegenData> GenerateOperatorCode( expr::ExprNodePtr expr, bool inputs_are_cheap_to_read); } #endif #include "arolla/codegen/expr/codegen_operator.h" #include <algorithm> #include <cstddef> #include <cstdint> #include <functional> #include <memory> #include <optional> #include <string> #include <utility> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/container/flat_hash_set.h" #include "absl/flags/flag.h" #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" #include "absl/types/span.h" #include "arolla/algorithm/control_flow_graph.h" #include "arolla/codegen/expr/optimizations.h" #include "arolla/codegen/expr/types.h" #include "arolla/expr/annotation_utils.h" #include "arolla/expr/basic_expr_operator.h" #include "arolla/expr/derived_qtype_cast_operator.h" #include "arolla/expr/eval/eval.h" #include "arolla/expr/eval/prepare_expression.h" #include "arolla/expr/eval/side_output.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_debug_string.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/expr/expr_visitor.h" #include "arolla/expr/registered_expr_operator.h" #include "arolla/qexpr/operator_metadata.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/derived_qtype.h" #include "arolla/qtype/optional_qtype.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/util/bytes.h" #include "arolla/util/fast_dynamic_downcast_final.h" #include "arolla/util/fingerprint.h" #include "arolla/util/map.h" #include "arolla/util/text.h" #include "arolla/util/status_macros_backport.h" ABSL_FLAG(int64_t, arolla_codegen_min_local_variables_per_lambda, 50, R"""( Minimum number of local variables required in order to create lambda. There are several things to consider for tuning this parameter. 1. maximum depth of braces is limited in C++, so we shouldn't create too deep structure. 2. C++ compiler can be not good in optimizing too many lambda functions. 3. On other hand smaller number can eliminate stack usage more. 4. It is not clear whenever compiler can successfully reuse stack memory for several variables with the same type. )"""); ABSL_FLAG(int64_t, arolla_codegen_max_allowed_inline_depth, 50, R"""( Maximim depth in inlining function calls that used only once. There are several things to consider for tuning this parameter. 1. Inlining may help compiler to optimize better and take advantage of temporary variables, save stack pressure. 2. Inlining making code slightly more readable. 3. maximum depth of braces is limited in C++, so we shouldn't create too deep structure. )"""); namespace arolla::codegen { namespace codegen_impl { bool IsInlinableLiteralType(const QType* qtype) { auto is_primitive_type = [](const QType* type) { return IsScalarQType(type) && type != GetQType<Text>() && type != GetQType<Bytes>(); }; return qtype != nullptr && is_primitive_type(DecayOptionalQType(qtype)); } } namespace { using expr::BackendExprOperatorTag; using expr::DecayRegisteredOperator; using expr::ExprNodePtr; using expr::ExprNodeType; using expr::ExprOperatorPtr; using expr::ExprOperatorSignature; using expr::UnnamedExprOperator; using expr::eval_internal::InternalRootOperator; using NodeId = AcyclicCFG::NodeId; class InternalNamedOutputExportOperator final : public UnnamedExprOperator { public: explicit InternalNamedOutputExportOperator(int64_t export_id) : UnnamedExprOperator( ExprOperatorSignature({{"x"}}), FingerprintHasher("codegen::InternalNamedOutputExportOperator") .Combine(export_id) .Finish()), export_id_(export_id) {} absl::StatusOr<QTypePtr> GetOutputQType( absl::Span<const QTypePtr> input_qtypes) const final { return input_qtypes[0]; } int64_t ExportId() const { return export_id_; } private: int64_t export_id_; }; std::optional<int64_t> MaybeGetExportId(const ExprNodePtr& node) { if (auto* export_op = fast_dynamic_downcast_final<const InternalNamedOutputExportOperator*>( node->op().get())) { return export_op->ExportId(); } return std::nullopt; } absl::StatusOr<std::vector<QTypePtr>> DependencyTypes( const ExprNodePtr& node, std::function<absl::StatusOr<QTypePtr>(const ExprNodePtr&)> qtype_from_expr_fn) { std::vector<QTypePtr> result; result.reserve(node->node_deps().size()); for (const ExprNodePtr& dep : node->node_deps()) { ASSIGN_OR_RETURN(result.emplace_back(), qtype_from_expr_fn(dep)); } return result; } absl::StatusOr<std::optional<QExprOperatorMetadata>> GetOperatorMetadata( const QExprOperatorMetadataRegistry& op_registry, const ExprNodePtr& node, std::function<absl::StatusOr<QTypePtr>(const ExprNodePtr&)> qtype_from_expr_fn) { ASSIGN_OR_RETURN(auto op, DecayRegisteredOperator(node->op())); if (op == InternalRootOperator()) { return std::nullopt; } if (expr::IsQTypeAnnotation(node)) { return std::nullopt; } if (auto export_id_opt = MaybeGetExportId(node); export_id_opt.has_value()) { return std::nullopt; } if (typeid(*op) == typeid(expr::DerivedQTypeUpcastOperator) || typeid(*op) == typeid(expr::DerivedQTypeDowncastOperator)) { return std::nullopt; } if (dynamic_cast<const BackendExprOperatorTag*>(op.get()) == nullptr) { return absl::InvalidArgumentError(absl::StrCat( node->op()->display_name(), " is not a backend ExprOperator")); } ASSIGN_OR_RETURN(auto dependency_types, DependencyTypes(node, qtype_from_expr_fn)); ASSIGN_OR_RETURN( auto metadata, op_registry.LookupOperatorMetadata(op->display_name(), dependency_types), _ << "while processing: " << expr::GetDebugSnippet(node)); return {metadata}; } absl::StatusOr<std::pair<std::unique_ptr<AcyclicCFG>, std::vector<ExprNodePtr>>> BuildEvalCfg(const ExprNodePtr& entry_node) { auto nodes_order = expr::VisitorOrder(entry_node); std::reverse(nodes_order.begin(), nodes_order.end()); absl::flat_hash_map<Fingerprint, NodeId> node_id; node_id.reserve(nodes_order.size()); for (const auto& node : nodes_order) { NodeId id = node_id.size(); node_id[node->fingerprint()] = id; } std::vector<std::vector<NodeId>> deps; deps.reserve(nodes_order.size()); for (const auto& node : nodes_order) { std::vector<NodeId> cur_deps; cur_deps.reserve(node->node_deps().size()); for (const auto& dep : node->node_deps()) { cur_deps.push_back(node_id[dep->fingerprint()]); } deps.push_back(std::move(cur_deps)); } ASSIGN_OR_RETURN(auto graph, AcyclicCFG::Create(std::move(deps))); return {std::pair{std::move(graph), std::move(nodes_order)}}; } std::vector<bool> FindInlinableNodes(const AcyclicCFG& graph) { std::vector<bool> inlinable(graph.num_nodes(), false); std::vector<size_t> inline_depth(graph.num_nodes(), 0); for (NodeId node_id = graph.num_nodes() - 1; node_id > 0; --node_id) { bool used_once = graph.reverse_deps(node_id).size() == 1; if (used_once) { size_t max_inline_depth = 0; for (NodeId dep : graph.deps(node_id)) { max_inline_depth = std::max(max_inline_depth, inline_depth[dep]); } if (max_inline_depth < absl::GetFlag(FLAGS_arolla_codegen_max_allowed_inline_depth)) { inlinable[node_id] = true; inline_depth[node_id] = max_inline_depth + 1; } } } inlinable[0] = true; return inlinable; } class Codegen { public: Codegen(const QExprOperatorMetadataRegistry& op_registry, const AcyclicCFG& graph, std::vector<ExprNodePtr> exprs, absl::flat_hash_map<Fingerprint, QTypePtr> node_qtypes, std::vector<std::string> side_output_names, bool inputs_are_cheap_to_read) : op_registry_(op_registry), graph_(graph), dominator_tree_(graph_), exprs_(std::move(exprs)), node_qtypes_(std::move(node_qtypes)), side_output_names_(std::move(side_output_names)), inputs_are_cheap_to_read_(inputs_are_cheap_to_read) {} absl::StatusOr<OperatorCodegenData> Process() { std::vector<bool> inlinable = FindInlinableNodes(graph_); OperatorCodegenData data; data.side_outputs.reserve(side_output_names_.size()); for (const auto& name : side_output_names_) { data.side_outputs.emplace_back(name, -1); } for (NodeId node_id = graph_.num_nodes() - 1; node_id >= 0; --node_id) { RETURN_IF_ERROR(ProcessSingleNode(node_id, inlinable[node_id], &data)); } for (const auto& [name, assignment_id] : data.side_outputs) { if (assignment_id == -1) { return absl::InternalError(absl::StrFormat( "named output `%s` is lost in transformations", name)); } } ASSIGN_OR_RETURN(data.functions, SplitOnFunctions(data)); FilterArgumentsAsFunction(data); LambdifyFunctions(data); ComputeLocalExprStatus(data); data.output_id = ToAssignmentId(0); return data; } private: absl::StatusOr<QTypePtr> QTypeFromExpr(const ExprNodePtr& node) const { DCHECK(node_qtypes_.contains(node->fingerprint())); auto qtype = node_qtypes_.at(node->fingerprint()); if (qtype == nullptr) { return absl::FailedPreconditionError(absl::StrFormat( "unable to deduce QType for %s", expr::ToDebugString(node))); } return qtype; } LValueId ToAssignmentId(NodeId node_id) const { return graph_.num_nodes() - node_id - 1; } NodeId ToNodeId(LValueId assignment_id) const { return graph_.num_nodes() - assignment_id - 1; } bool IsLiteralNode(NodeId node_id) const { return exprs_[node_id]->is_literal(); } bool IsLeafNode(NodeId node_id) const { return exprs_[node_id]->is_leaf(); } absl::StatusOr<std::vector<bool>> FindSeparableNodes() const { int64_t n = graph_.num_nodes(); absl::flat_hash_set<NodeId> global_nodes; for (int64_t node_id = 0; node_id != n; ++node_id) { if (IsLiteralNode(node_id) || (inputs_are_cheap_to_read_ && IsLeafNode(node_id))) { global_nodes.insert(node_id); } } ASSIGN_OR_RETURN(auto externalized_graph, ExternalizeNodes(graph_, dominator_tree_, global_nodes)); auto is_separable = FindVerticesWithEmptyDominanceFrontier( *externalized_graph, dominator_tree_); for (NodeId node_id = 0; node_id != n; ++node_id) { if (IsLiteralNode(node_id) || IsLeafNode(node_id)) { is_separable[node_id] = false; } } return is_separable; } absl::StatusOr<std::vector<Function>> SplitOnFunctions( OperatorCodegenData& data) const { int64_t n = graph_.num_nodes(); ASSIGN_OR_RETURN(auto is_separable, FindSeparableNodes()); CHECK(is_separable[0] || IsLiteralNode(0) || IsLeafNode(0)) << "InternalError: entry node should be always separable"; std::vector<Function> functions; constexpr int64_t kUndefined = -1; std::vector<int64_t> function_id(n, kUndefined); for (NodeId node_id = n - 1; node_id >= 0; --node_id) { if (is_separable[node_id]) { function_id[node_id] = functions.size(); Function new_fn; new_fn.output_id = ToAssignmentId(node_id); new_fn.is_result_status_or = data.assignments[new_fn.output_id] .lvalue() .is_entire_expr_status_or; functions.push_back(std::move(new_fn)); } } CHECK((function_id[0] != kUndefined) || IsLiteralNode(0) || IsLeafNode(0)) << "InternalError: entry node should be assigned to the function"; for (NodeId node_id = 0; node_id != n; ++node_id) { for (NodeId dep : graph_.deps(node_id)) { if (function_id[dep] == kUndefined) { function_id[dep] = function_id[node_id]; } } } for (NodeId node_id = n - 1; node_id >= 0; --node_id) { LValueId assignment_id = ToAssignmentId(node_id); int64_t cur_function_id = function_id[node_id]; if (IsLiteralNode(node_id)) { continue; } if ((inputs_are_cheap_to_read_ || node_id == 0) && IsLeafNode(node_id)) { continue; } if (!is_separable[node_id]) { functions[cur_function_id].assignment_ids.push_back(assignment_id); for (NodeId rdep : graph_.reverse_deps(node_id)) { CHECK_EQ(function_id[rdep], cur_function_id) << "InternalError: only separable nodes can be used by other " "functions"; } continue; } int64_t rdep_function = kUndefined; for (NodeId rdep : graph_.reverse_deps(node_id)) { if (function_id[rdep] != cur_function_id) { if (rdep_function == kUndefined) { rdep_function = function_id[rdep]; functions[rdep_function].assignment_ids.push_back(assignment_id); } else { CHECK_EQ(rdep_function, function_id[rdep]) << "InternalError: non leaf function node must be used by not " "more than one other function"; } } } } return functions; } void LambdifyFunctions(OperatorCodegenData& data) const { for (Function& function : data.functions) { LambdifyFunction(data, function); } } void ComputeLocalExprStatus(OperatorCodegenData& data) const { absl::flat_hash_map<LValueId, int64_t> id2lambda; for (int64_t i = 0; i < data.lambdas.size(); ++i) { id2lambda.emplace(data.lambdas[i].output_id, i); } absl::flat_hash_map<LValueId, int64_t> id2function; for (int64_t i = 0; i < data.functions.size(); ++i) { id2function.emplace(data.functions[i].output_id, i); } for (LValueId assignment_id = 0; assignment_id != data.assignments.size(); ++assignment_id) { auto& assignment = data.assignments[assignment_id]; bool is_local_expr_status_or = assignment.rvalue().operator_returns_status_or; if (id2function.contains(assignment_id)) { is_local_expr_status_or = data.functions[id2function[assignment_id]].is_result_status_or; } else { std::vector<LValueId> output_assignments = DependencyArgs(ToNodeId(assignment_id)); for (LValueId dep_id : output_assignments) { is_local_expr_status_or = is_local_expr_status_or || (data.assignments[dep_id].is_inlinable() && data.assignments[dep_id].lvalue().is_local_expr_status_or); } if (id2lambda.contains(assignment_id)) { Function& lambda = data.lambdas[id2lambda[assignment_id]]; for (LValueId assignment_id : lambda.assignment_ids) { is_local_expr_status_or |= data.assignments[assignment_id] .lvalue() .is_local_expr_status_or; } lambda.is_result_status_or = is_local_expr_status_or; } } assignment.lvalue().is_local_expr_status_or = is_local_expr_status_or; } } void FilterArgumentsAsFunction(OperatorCodegenData& data) const { for (Assignment& assignment : data.assignments) { RValue& rvalue = assignment.rvalue(); if (rvalue.kind != RValueKind::kFunctionCall && rvalue.kind != RValueKind::kFunctionWithContextCall) { continue; } if (rvalue.argument_as_function_offsets.empty()) { continue; } auto new_end = std::remove_if( rvalue.argument_as_function_offsets.begin(), rvalue.argument_as_function_offsets.end(), [&](int offset) { const Assignment& cur_assignment = data.assignments[rvalue.argument_ids[offset]]; return !cur_assignment.is_inlinable() || cur_assignment.lvalue().kind == LValueKind::kLiteral; }); rvalue.argument_as_function_offsets.erase( new_end, rvalue.argument_as_function_offsets.end()); } } bool IsInlinableAsFunctionArgument(LValueId assignment_id, const OperatorCodegenData& data) const { auto& cur_assignment = data.assignments[assignment_id]; if (cur_assignment.lvalue().kind == LValueKind::kLiteral) { return false; } if (!cur_assignment.is_inlinable()) { return false; } NodeId dominator_node_id = dominator_tree_.parent(ToNodeId(assignment_id)); LValueId dominator_assignment_id = ToAssignmentId(dominator_node_id); auto& parent_assignment = data.assignments[dominator_assignment_id]; const std::vector<LValueId>& parent_arg_ids = parent_assignment.rvalue().argument_ids; int arg_in_parent_id = std::find(parent_arg_ids.begin(), parent_arg_ids.end(), assignment_id) - parent_arg_ids.begin(); const std::vector<int>& argument_as_function_offsets = parent_assignment.rvalue().argument_as_function_offsets; return std::count(argument_as_function_offsets.begin(), argument_as_function_offsets.end(), arg_in_parent_id) != 0; } void LambdifyFunction(OperatorCodegenData& data, Function& function) const { absl::flat_hash_map<int64_t, std::vector<LValueId>> lambda_local_assignments; for (LValueId assignment_id : function.assignment_ids) { auto& cur_assignment = data.assignments[assignment_id]; NodeId node_id = ToNodeId(assignment_id); NodeId dominator_node_id = dominator_tree_.parent(node_id); LValueId dominator_assignment_id = ToAssignmentId(dominator_node_id); auto cur_lambda_assignments = std::move(lambda_local_assignments[assignmen
#include "arolla/codegen/expr/codegen_operator.h" #include <cstdint> #include <initializer_list> #include <set> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/statusor.h" #include "arolla/dense_array/qtype/types.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/expr/lambda_expr_operator.h" #include "arolla/expr/testing/testing.h" #include "arolla/qtype/optional_qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/weak_qtype.h" #include "arolla/util/bytes.h" #include "arolla/util/init_arolla.h" #include "arolla/util/text.h" #include "arolla/util/unit.h" namespace arolla::codegen { namespace { using ::arolla::expr::Leaf; using ::arolla::expr::Literal; using ::arolla::testing::WithExportAnnotation; using ::arolla::testing::WithQTypeAnnotation; using ::testing::_; using ::testing::ElementsAre; using ::testing::Eq; using ::testing::IsEmpty; using ::testing::Pair; using ::testing::UnorderedElementsAre; int64_t MinUnused(std::set<int64_t> used) { for (int64_t i = 0; i != used.size(); ++i) { if (used.count(i) == 0) { return i; } } return used.size(); } class CodegenTest : public ::testing::Test { void SetUp() override { ASSERT_OK(InitArolla()); } }; TEST_F(CodegenTest, IsInlinableLiteralTypeTest) { EXPECT_TRUE(codegen_impl::IsInlinableLiteralType(GetQType<int>())); EXPECT_TRUE(codegen_impl::IsInlinableLiteralType(GetQType<float>())); EXPECT_TRUE(codegen_impl::IsInlinableLiteralType(GetQType<double>())); EXPECT_TRUE(codegen_impl::IsInlinableLiteralType(GetQType<int64_t>())); EXPECT_TRUE(codegen_impl::IsInlinableLiteralType(GetQType<uint64_t>())); EXPECT_TRUE(codegen_impl::IsInlinableLiteralType(GetQType<bool>())); EXPECT_TRUE(codegen_impl::IsInlinableLiteralType(GetQType<Unit>())); EXPECT_FALSE(codegen_impl::IsInlinableLiteralType(GetQType<Bytes>())); EXPECT_FALSE(codegen_impl::IsInlinableLiteralType(GetQType<Text>())); EXPECT_TRUE(codegen_impl::IsInlinableLiteralType(GetOptionalQType<int>())); EXPECT_TRUE(codegen_impl::IsInlinableLiteralType(GetOptionalQType<float>())); EXPECT_TRUE(codegen_impl::IsInlinableLiteralType(GetOptionalQType<double>())); EXPECT_TRUE( codegen_impl::IsInlinableLiteralType(GetOptionalQType<int64_t>())); EXPECT_TRUE( codegen_impl::IsInlinableLiteralType(GetOptionalQType<uint64_t>())); EXPECT_TRUE(codegen_impl::IsInlinableLiteralType(GetOptionalQType<bool>())); EXPECT_TRUE(codegen_impl::IsInlinableLiteralType(GetOptionalQType<Unit>())); EXPECT_FALSE(codegen_impl::IsInlinableLiteralType(GetOptionalQType<Bytes>())); EXPECT_FALSE(codegen_impl::IsInlinableLiteralType(GetOptionalQType<Text>())); EXPECT_FALSE( codegen_impl::IsInlinableLiteralType(GetDenseArrayQType<bool>())); EXPECT_FALSE(codegen_impl::IsInlinableLiteralType(GetDenseArrayQType<int>())); EXPECT_FALSE( codegen_impl::IsInlinableLiteralType(GetDenseArrayQType<float>())); EXPECT_FALSE( codegen_impl::IsInlinableLiteralType(GetDenseArrayQType<double>())); } TEST_F(CodegenTest, SmokeTest) { ASSERT_OK_AND_ASSIGN( auto expr, expr::CallOp("math.add", {expr::CallOp("math.add", {WithQTypeAnnotation( Leaf("x"), GetQType<float>()), Literal(1.f)}), WithQTypeAnnotation(Leaf("y"), GetQType<float>())})); ASSERT_OK_AND_ASSIGN( OperatorCodegenData op, GenerateOperatorCode(expr, true)); EXPECT_THAT(op.headers, ElementsAre( "arolla/" "qexpr/operators/math/arithmetic.h")); EXPECT_THAT(op.deps, ElementsAre(" "arolla/" "qexpr/operators/math:lib")); EXPECT_THAT(op.inputs, ElementsAre(Pair("x", _), Pair("y", _))); int64_t input_x_id = op.inputs["x"]; EXPECT_THAT(op.assignments[input_x_id].lvalue(), Eq(LValue{.type_name = "float", .is_entire_expr_status_or = false, .qtype = GetQType<float>(), .kind = LValueKind::kInput})); EXPECT_THAT(op.assignments[input_x_id].rvalue(), Eq(RValue::CreateInput())); EXPECT_TRUE(op.assignments[input_x_id].is_inlinable()); int64_t input_y_id = op.inputs["y"]; EXPECT_THAT(op.assignments[input_y_id].lvalue(), Eq(LValue{.type_name = "float", .is_entire_expr_status_or = false, .qtype = GetQType<float>(), .kind = LValueKind::kInput})); EXPECT_THAT(op.assignments[input_y_id].rvalue(), Eq(RValue::CreateInput())); EXPECT_TRUE(op.assignments[input_x_id].is_inlinable()); EXPECT_EQ(op.assignments.size(), 3 + 2 ); int64_t literal_id = MinUnused({input_x_id, input_y_id}); ASSERT_LT(literal_id, op.assignments.size()); EXPECT_THAT(op.assignments[literal_id].lvalue(), Eq(LValue{.type_name = "float", .is_entire_expr_status_or = false, .qtype = GetQType<float>(), .kind = LValueKind::kLiteral})); EXPECT_THAT(op.assignments[literal_id].rvalue(), Eq(RValue::CreateLiteral("float{1.}"))); int64_t tmp0_id = MinUnused({input_x_id, input_y_id, literal_id}); ASSERT_LT(tmp0_id, op.assignments.size()); EXPECT_TRUE(op.assignments[tmp0_id].is_inlinable()); EXPECT_THAT(op.assignments[tmp0_id].lvalue(), Eq(LValue{.type_name = "float", .is_entire_expr_status_or = false, .qtype = GetQType<float>(), .kind = LValueKind::kLocal})); EXPECT_THAT(op.assignments[tmp0_id].rvalue(), Eq(RValue{.kind = RValueKind::kFunctionCall, .operator_returns_status_or = false, .code = "::arolla::AddOp{}", .argument_ids = {input_x_id, literal_id}})); int64_t tmp1_id = 4; EXPECT_THAT(op.assignments[tmp1_id].lvalue(), Eq(LValue{.type_name = "float", .is_entire_expr_status_or = false, .qtype = GetQType<float>(), .kind = LValueKind::kLocal})); EXPECT_THAT(op.assignments[tmp1_id].rvalue(), Eq(RValue{.kind = RValueKind::kFunctionCall, .operator_returns_status_or = false, .code = "::arolla::AddOp{}", .argument_ids = {tmp0_id, input_y_id}})); EXPECT_EQ(op.output_id, tmp1_id); EXPECT_THAT(op.function_entry_points(), UnorderedElementsAre(Pair(tmp0_id, 0), Pair(tmp1_id, 1))); } TEST_F(CodegenTest, SmokeWithNonGlobalInputsTest) { ASSERT_OK_AND_ASSIGN(auto x, WithQTypeAnnotation(Leaf("x"), GetQType<float>())); ASSERT_OK_AND_ASSIGN( auto expr, expr::CallOp("math.add", {expr::CallOp("math.add", {x, x}), WithQTypeAnnotation( Leaf("y"), GetQType<float>())})); ASSERT_OK_AND_ASSIGN( OperatorCodegenData op, GenerateOperatorCode(expr, false)); EXPECT_THAT(op.headers, ElementsAre( "arolla/" "qexpr/operators/math/arithmetic.h")); EXPECT_THAT(op.deps, ElementsAre(" "arolla/" "qexpr/operators/math:lib")); EXPECT_THAT(op.inputs, ElementsAre(Pair("x", _), Pair("y", _))); int64_t input_x_id = op.inputs["x"]; EXPECT_THAT(op.assignments[input_x_id].lvalue(), Eq(LValue{.type_name = "float", .is_entire_expr_status_or = false, .qtype = GetQType<float>(), .kind = LValueKind::kInput})); EXPECT_THAT(op.assignments[input_x_id].rvalue(), Eq(RValue::CreateInput())); EXPECT_FALSE(op.assignments[input_x_id].is_inlinable()); int64_t input_y_id = op.inputs["y"]; EXPECT_THAT(op.assignments[input_y_id].lvalue(), Eq(LValue{.type_name = "float", .is_entire_expr_status_or = false, .qtype = GetQType<float>(), .kind = LValueKind::kInput})); EXPECT_THAT(op.assignments[input_y_id].rvalue(), Eq(RValue::CreateInput())); EXPECT_TRUE(op.assignments[input_y_id].is_inlinable()); ASSERT_EQ(op.assignments.size(), 2 + 2 ); int64_t tmp0_id = 1; ASSERT_LT(tmp0_id, op.assignments.size()); EXPECT_TRUE(op.assignments[tmp0_id].is_inlinable()); EXPECT_THAT(op.assignments[tmp0_id].lvalue(), Eq(LValue{.type_name = "float", .is_entire_expr_status_or = false, .qtype = GetQType<float>(), .kind = LValueKind::kLocal})); EXPECT_THAT(op.assignments[tmp0_id].rvalue(), Eq(RValue{.kind = RValueKind::kFunctionCall, .operator_returns_status_or = false, .code = "::arolla::AddOp{}", .argument_ids = {input_x_id, input_x_id}})); int64_t tmp1_id = 3; EXPECT_THAT(op.assignments[tmp1_id].lvalue(), Eq(LValue{.type_name = "float", .is_entire_expr_status_or = false, .qtype = GetQType<float>(), .kind = LValueKind::kLocal})); EXPECT_THAT(op.assignments[tmp1_id].rvalue(), Eq(RValue{.kind = RValueKind::kFunctionCall, .operator_returns_status_or = false, .code = "::arolla::AddOp{}", .argument_ids = {tmp0_id, input_y_id}})); EXPECT_EQ(op.output_id, tmp1_id); EXPECT_THAT(op.function_entry_points(), UnorderedElementsAre(Pair(tmp0_id, 0), Pair(tmp1_id, 1))); } TEST_F(CodegenTest, SmokeWithStatusOrTest) { ASSERT_OK_AND_ASSIGN(auto x, WithQTypeAnnotation(Leaf("x"), GetQType<float>())); ASSERT_OK_AND_ASSIGN(auto y, WithQTypeAnnotation(Leaf("y"), GetQType<float>())); ASSERT_OK_AND_ASSIGN(auto floor_div, expr::CallOp("math.floordiv", {x, y})); ASSERT_OK_AND_ASSIGN(auto expr, expr::CallOp("math.add", {floor_div, y})); ASSERT_OK_AND_ASSIGN( OperatorCodegenData op, GenerateOperatorCode(expr, true)); EXPECT_THAT(op.headers, ElementsAre( "arolla/" "qexpr/operators/math/arithmetic.h")); EXPECT_THAT(op.deps, ElementsAre(" "arolla/" "qexpr/operators/math:lib")); EXPECT_THAT(op.inputs, ElementsAre(Pair("x", _), Pair("y", _))); int64_t input_x_id = op.inputs["x"]; EXPECT_THAT(op.assignments[input_x_id].lvalue(), Eq(LValue{.type_name = "float", .is_entire_expr_status_or = false, .is_local_expr_status_or = false, .qtype = GetQType<float>(), .kind = LValueKind::kInput})); EXPECT_THAT(op.assignments[input_x_id].rvalue(), Eq(RValue::CreateInput())); int64_t input_y_id = op.inputs["y"]; EXPECT_THAT(op.assignments[input_y_id].lvalue(), Eq(LValue{.type_name = "float", .is_entire_expr_status_or = false, .is_local_expr_status_or = false, .qtype = GetQType<float>(), .kind = LValueKind::kInput})); EXPECT_THAT(op.assignments[input_y_id].rvalue(), Eq(RValue::CreateInput())); EXPECT_EQ(op.assignments.size(), 2 + 2 ); int64_t tmp0_id = 2; ASSERT_LT(tmp0_id, op.assignments.size()); EXPECT_TRUE(op.assignments[tmp0_id].is_inlinable()); EXPECT_THAT(op.assignments[tmp0_id].lvalue(), Eq(LValue{.type_name = "float", .is_entire_expr_status_or = true, .is_local_expr_status_or = true, .qtype = GetQType<float>(), .kind = LValueKind::kLocal})); EXPECT_THAT(op.assignments[tmp0_id].rvalue(), Eq(RValue{.kind = RValueKind::kFunctionCall, .operator_returns_status_or = true, .code = "::arolla::FloorDivOp{}", .argument_ids = {input_x_id, input_y_id}})); int64_t tmp1_id = 3; ASSERT_LT(tmp1_id, op.assignments.size()); EXPECT_TRUE(op.assignments[tmp1_id].is_inlinable()); EXPECT_THAT(op.assignments[tmp1_id].lvalue(), Eq(LValue{.type_name = "float", .is_entire_expr_status_or = true, .is_local_expr_status_or = true, .qtype = GetQType<float>(), .kind = LValueKind::kLocal})); EXPECT_THAT(op.assignments[tmp1_id].rvalue(), Eq(RValue{.kind = RValueKind::kFunctionCall, .operator_returns_status_or = false, .code = "::arolla::AddOp{}", .argument_ids = {tmp0_id, input_y_id}})); EXPECT_EQ(op.output_id, tmp1_id); } TEST_F(CodegenTest, SmokeWithContextTest) { ASSERT_OK_AND_ASSIGN( auto x, WithQTypeAnnotation(Leaf("x"), GetDenseArrayQType<float>())); ASSERT_OK_AND_ASSIGN( auto y, WithQTypeAnnotation(Leaf("y"), GetDenseArrayQType<float>())); ASSERT_OK_AND_ASSIGN(auto expr, expr::CallOp("math.add", {x, y})); ASSERT_OK_AND_ASSIGN( OperatorCodegenData op, GenerateOperatorCode(expr, true)); EXPECT_THAT(op.headers, ElementsAre( "arolla/" "dense_array/qtype/types.h", "arolla/" "qexpr/operators/dense_array/lifter.h", "arolla/" "qexpr/operators/math/arithmetic.h")); EXPECT_THAT(op.deps, ElementsAre( " "arolla/" "dense_array/qtype", " "arolla/" "qexpr/operators/dense_array:lib", " "arolla/" "qexpr/operators/math:lib")); EXPECT_THAT(op.inputs, ElementsAre(Pair("x", _), Pair("y", _))); int64_t input_x_id = op.inputs["x"]; EXPECT_THAT(op.assignments[input_x_id].lvalue(), Eq(LValue{.type_name = "::arolla::DenseArray<float>", .is_entire_expr_status_or = false, .is_local_expr_status_or = false, .qtype = GetDenseArrayQType<float>(), .kind = LValueKind::kInput})); EXPECT_THAT(op.assignments[input_x_id].rvalue(), Eq(RValue::CreateInput())); int64_t input_y_id = op.inputs["y"]; EXPECT_THAT(op.assignments[input_y_id].lvalue(), Eq(LValue{.type_name = "::arolla::DenseArray<float>", .is_entire_expr_status_or = false, .is_local_expr_status_or = false, .qtype = GetDenseArrayQType<float>(), .kind = LValueKind::kInput})); EXPECT_THAT(op.assignments[input_y_id].rvalue(), Eq(RValue::CreateInput())); EXPECT_EQ(op.assignments.size(), 1 + 2 ); int64_t tmp0_id = 2; ASSERT_LT(tmp0_id, op.assignments.size()); EXPECT_TRUE(op.assignments[tmp0_id].is_inlinable()); EXPECT_THAT(op.assignments[tmp0_id].lvalue(), Eq(LValue{.type_name = "::arolla::DenseArray<float>", .is_entire_expr_status_or = true, .is_local_expr_status_or = true, .qtype = GetDenseArrayQType<float>(), .kind = LValueKind::kLocal})); EXPECT_THAT(op.assignments[tmp0_id].rvalue(), Eq(RValue{.kind = RValueKind::kFunctionWithContextCall, .operator_returns_status_or = true, .code = "::arolla::DenseArrayLifter<::arolla::AddOp, " "::arolla::meta::type_list<float, float>, " "true>{}", .argument_ids = {input_x_id, input_y_id}})); EXPECT_EQ(op.output_id, tmp0_id); } TEST_F(CodegenTest, SmokeTestWithExport) { ASSERT_OK_AND_ASSIGN( auto expr, expr::CallOp( "math.add", {WithExportAnnotation( expr::CallOp("math.add", {WithQTypeAnnotation(Leaf("x"), GetQType<float>()), Literal(1.f)}), "output"), WithQTypeAnnotation(Leaf("y"), GetQType<float>())})); ASSERT_OK_AND_ASSIGN( OperatorCodegenData op, GenerateOperatorCode(expr, true)); EXPECT_THAT(op.headers, ElementsAre( "arolla/" "qexpr/operators/math/arithmetic.h")); EXPECT_THAT(op.deps, ElementsAre(" "arolla/" "qexpr/operators/math:lib")); EXPECT_THAT(op.inputs, ElementsAre(Pair("x", _), Pair("y", _))); int64_t input_x_id = op.inputs["x"]; EXPECT_THAT(op.assignments[input_x_id].lvalue(), Eq(LValue{.type_name = "float", .is_entire_expr_status_or = false, .qtype = GetQType<float>(), .kind = LValueKind::kInput})); EXPECT_THAT(op.assignments[input_x_id].rvalue(), Eq(RValue::CreateInput())); int64_t input_y_id = op.inputs["y"]; EXPECT_THAT(op.assignments[input_y_id].lvalue(), Eq(LValue{.type_name = "float", .is_entire_expr_status_or = false, .qtype = GetQType<float>(), .kind = LValueKind::kInput})); EXPECT_THAT(op.assignments[input_y_id].rvalue(), Eq(RValue::CreateInput())); EXPECT_EQ(op.assignments.size(), 4 + 2 ); int64_t literal_id = MinUnused({input_x_id, input_y_id}); ASSERT_LT(literal_id, op.assignments.size()); EXPECT_THAT(op.assignments[literal_id].lvalue(), Eq(LValue{.type_name = "float", .is_entire_expr_status_or = false, .qtype = GetQType<float>(), .kind = LValueKind::kLiteral})); EXPECT_THAT(op.assignments[literal_id].rvalue(), Eq(RValue::CreateLiteral("float{1.}"))); int64_t tmp0_id = MinUnused({input_x_id, input_y_id, literal_id}); ASSERT_LT(tmp0_id, op.assignments.size()); EXPECT_TRUE(op.assignments[tmp0_id].is_inlinable()) << "used for output, but export is inside of the expression"; EXPECT_THAT(op.assignments[tmp0_id].lvalue(), Eq(LValue{.type_name = "float", .is_entire_expr_status_or = false, .qtype = GetQType<float>(), .kind = LValueKind::kLocal})); EXPECT_THAT(op.assignments[tmp0_id].rvalue(), Eq(RValue{.kind = RValueKind::kFunctionCall, .operator_returns_status_or = false, .code = "::arolla::AddOp{}", .argument_ids = {input_x_id, literal_id}})); int64_t tmp1_id = MinUnused({input_x_id, input_y_id, literal_id, tmp0_id}); ASSERT_LT(tmp1_id, op.assignments.size()); EXPECT_TRUE(op.assignments[tmp1_id].is_inlinable()); EXPECT_THAT(op.assignments[tmp1_id].lvalue(), Eq(LValue{.type_name = "float", .is_entire_expr_status_or = false, .qtype = GetQType<float>(), .kind = LValueKind::kLocal})); EXPECT_THAT(op.assignments[tmp1_id].rvalue(), Eq(RValue{.kind = RValueKind::kOutput, .operator_returns_status_or = false, .code = "0", .argument_ids = {tmp0_id}})); int64_t tmp2_id = 5; EXPECT_THAT(op.assignments[tmp2_id].lvalue(), Eq(LValue{.type_name = "float", .is_entire_expr_status_or = false, .qtype = GetQType<float>(), .kind = LValueKind::kLocal})); EXPECT_THAT(op.assignments[tmp2_id].rvalue(), Eq(RValue{.kind = RValueKind::kFunctionCall, .operator_returns_status_or = false, .code = "::arolla::AddOp{}", .argument_ids = {tmp1_id, input_y_id}})); EXPECT_EQ(op.output_id, tmp2_id); EXPECT_THAT(op.side_outputs, ElementsAre(Pair("output", tmp1_id))); } TEST_F(CodegenTest, SmokeTestWithDerivedQTypeDowncast) { ASSERT_OK_AND_ASSIGN( auto expr, expr::CallOp("derived_qtype.downcast", {Literal(GetWeakFloatQType()), WithQTypeAnnotation(Leaf("x"), GetQType<double>())})); ASSERT_OK_AND_ASSIGN( OperatorCodegenData op, GenerateOperatorCode(expr, true)); EXPECT_THAT(op.inputs, ElementsAre(Pair("x", _))); int64_t input_x_id = op.inputs["x"]; EXPECT_THAT(op.assignments[input_x_id].lvalue(), Eq(LValue{.type_name = "double", .is_entire_expr_status_or = false, .qtype = GetQType<double>(), .kind = LValueKind::kInput})); EXPECT_THAT(op.assignments[input_x_id].rvalue(), Eq(RValue::CreateInput())); EXPECT_EQ(op.assignments.size(), 1 + 1 ); int64_t tmp0_id = MinUnused({input_x_id}); ASSERT_LT(tmp0_id, op.assignments.size()); EXPECT_TRUE(op.assignments[tmp0_id].is_inlinable()) << "used for output, but export is inside of the expression"; EXPECT_THAT(op.assignments[tmp0_id].lvalue(), Eq(LValue{.type_name = "double", .is_entire_expr_status_or = false, .qtype = GetQType<double>(), .kind = LValueKind::kLocal})); EXPECT_THAT(op.assignments[tmp0_id].rvalue(), Eq(RValue{.kind = RValueKind::kFirst, .operator_returns_status_or = false, .code = "", .argument_ids = {input_x_id}})); EXPECT_EQ(op.output_id, tmp0_id); } TEST_F(CodegenTest, SmokeTestWithExportUnusedForMainOutput) { ASSERT_OK_AND_ASSIGN( auto get_first_op, expr::MakeLambdaOperator(expr::ExprOperatorSignature({{"x"}, {"y"}}), expr::Placeholder("x"))); ASSERT_OK_AND_ASSIGN( auto expr, expr::CallOp( get_first_op, {WithExportAnnotation( WithQTypeAnnotation(Leaf("y"), GetQType<float>()), "named_main_output"), WithExportAnnotation( expr::CallOp("math.add", {WithQTypeAnnotation(Leaf("x"), GetQType<float>()), Literal(1.f)}), "output")})); ASSERT_OK_AND_ASSIGN( OperatorCodegenData op, GenerateOperatorCode(expr, true)); EXPECT_THAT(op.headers, ElementsAre( "arolla/" "qexpr/operators/math/arithmetic.h")); EXPECT_THAT(op.deps, ElementsAre(" "arolla/" "qexpr/operators/math:lib")); EXPECT_THAT(op.inputs, ElementsAre(Pair("x", _), Pair("y", _))); int64_t input_x_id = op.inputs["x"]; EXPECT_THAT(op.assignments[input_x_id].lvalue(), Eq(LValue{.type_name = "float", .is_entire_expr_status_or = false, .qtype = GetQType<float>(), .kind = LValueKind::kInput})); EXPECT_THAT(op.assignments[input_x_id].rvalue(), Eq(RValue::CreateInput())); int64_t input_y_id = op.inputs["y"]; EXPECT_THAT(op.assignments[input_y_id].lvalue(), Eq(LValue{.type_name = "float", .is_entire_expr_status_or = false, .qtype = GetQType<float>(), .kind = LValueKind::kInput})); EXPECT_THAT(op.assignments[input_y_id].rvalue(), Eq(RValue::CreateInput())); EXPECT_EQ(op.assignments.size(), 5 + 2 ); int64_t tmp0_id = MinUnused({input_x_id, input_y_id}); ASSERT_LT(tmp0_id, op.assignments.size()); EXPECT_TRUE(op.assignments[tmp0_id].is_inlinable()) << "used for output, but export is inside of the expression"; EXPECT_THAT(op.assignments[tmp0_id].lvalue(), Eq(LValue{.type_name = "float", .is_entire_expr_status_or = false, .qtype = GetQType<float>(), .kind = LValueKind::kLocal})); EXPECT_THAT(op.assignments[tmp0_id].rvalue(), Eq(RValue{.kind = RValueKind::kOutput, .operator_returns_status_or = false, .code = "0", .argument_ids = {input_y_id}})); int64_t literal_id = MinUnused({input_x_id, input_y_id, tmp0_id}); ASSERT_LT(literal_id, op.assignments.size()); EXPECT_THAT(op.assignments[literal_id].lvalue(), Eq(LValue{.type_name = "float", .is_entire_expr_status_or = false, .qtype = GetQType<float>(), .kind = LValueKind::kLiteral})); EXPECT_THAT(op.assignments[literal_id].rvalue(), Eq(RValue::CreateLiteral("float{1.}"))); int64_t tmp1_id = MinUnused({input_x_id, input_y_id, literal_id, tmp0_id}); ASSERT_LT(tmp1_id, op.assignments.size()); EXPECT_TRUE(op.assignments[tmp1_id].is_inlinable()); EXPECT_THAT(op.assignments[tmp1_id].lvalue(), Eq(LValue{.type_name = "float", .is_entire_expr_status_or = false, .qtype = GetQType<float>(), .kind = LValueKind::kLocal})); EXPECT_THAT(op.assignments[tmp1_id].rvalue(), Eq(RValue{.kind = RValueKind::kFunctionCall, .operator_returns_status_or = false, .code = "::arolla::AddOp{}", .argument_ids = {input_x_id, literal_id}})); int64_t tmp2_id = 5; EXPECT_THAT(op.assignments[tmp2_id].lvalue(), Eq(LValue{.type_name = "float", .is_entire_expr_status_or = false, .qtype = GetQType<float>(), .kind = LValueKind::kLocal})); EXPECT_THAT(op.assignments[tmp2_id].rvalue(), Eq(RValue{.kind = RValueKind::kOutput, .operator_returns_status_or = false, .code = "1", .argument_ids = {tmp1_id}})); int64_t tmp3_id = 6; EXPECT_THAT(op.assignments[tmp3_id].lvalue(), Eq(LValue{.type_name = "float", .is_entire_expr_status_or = false, .qtype = GetQType<float>(), .kind = LValueKind::kLocal})); EXPECT_THAT(op.assignments[tmp3_id].rvalue(), Eq(RValue{.kind = RValueKind::kFirst, .operator_returns_status_or = false, .code = "", .argument_ids = {tmp0_id, tmp2_id}})); EXPECT_EQ(op.output_id, tmp3_id); EXPECT_THAT(op.side_outputs, ElementsAre(Pair("named_main_output", tmp0_id), Pair("output", tmp2_id))); } TEST_F(CodegenTest, LambdaAndFunctionSinityTest) { auto lx = WithQTypeAnnotation(Leaf("x"), GetQType<float>()); auto ly = WithQTypeAnnotation(Leaf("y"), GetQType<float>()); auto x = expr::CallOp("math.add", {lx, ly}); auto y = expr::CallOp("math.subtract", {lx, ly}); auto a = expr::CallOp("math.add", {x, y}); auto b = expr::CallOp("math.subtract", {x, y}); constexpr int64_t kChainLength = 500; for (int i = 0; i != kChainLength; ++i) { auto na = expr::CallOp("math.mod", {a, x}); x = a; a = na; auto nb = expr::CallOp("math.mod", {b, y}); y = b; b = nb; } ASSERT_OK_AND_ASSIGN(auto expr, expr::CallOp("math.add", {a, b})); ASSERT_OK_AND_ASSIGN( OperatorCodegenData op, GenerateOperatorCode(expr, true)); EXPECT_THAT(op.functions.size(), Eq(3)); for (int i = 0; i != 2; ++i) { EXPECT_THAT(op.functions[i].assignment_ids, IsEmpty()) << i; } EXPECT_THAT(op.functions[2].assignment_ids.size(), Eq(4)); EXPECT_THAT(op.lambdas.size(), Eq(2)); EXPECT_THAT(op.lambdas[0].assignment_ids.size(), Eq(kChainLength - 1)); EXPECT_THAT(op.lambdas[1].assignment_ids.size(), Eq(kChainLength - 1)); } } }
2,397
cpp
google/arolla
optimizations
arolla/codegen/expr/optimizations.cc
arolla/codegen/expr/optimizations_test.cc
#ifndef AROLLA_CODEGEN_EXPR_OPTIMIZATIONS_H_ #define AROLLA_CODEGEN_EXPR_OPTIMIZATIONS_H_ #include <string> #include "absl/flags/declare.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "arolla/expr/optimization/optimizer.h" ABSL_DECLARE_FLAG(std::string, arolla_codegen_optimizer_name); namespace arolla::codegen { absl::Status RegisterOptimization(absl::string_view optimization_name, expr::Optimizer optimizer); absl::StatusOr<expr::Optimizer> GetOptimizer(absl::string_view name); } #endif #include "arolla/codegen/expr/optimizations.h" #include <string> #include "absl/base/thread_annotations.h" #include "absl/container/flat_hash_map.h" #include "absl/flags/flag.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "absl/strings/string_view.h" #include "absl/synchronization/mutex.h" #include "arolla/expr/optimization/default/default_optimizer.h" #include "arolla/expr/optimization/optimizer.h" #include "arolla/util/indestructible.h" ABSL_FLAG(std::string, arolla_codegen_optimizer_name, "", "Name of the optimizer, which must be registered using " "RegisterOptimization at initialization time."); namespace arolla::codegen { namespace { struct OptimizationMap { absl::Mutex lock; absl::flat_hash_map<std::string, expr::Optimizer> optimizers ABSL_GUARDED_BY(lock); }; OptimizationMap& GetOptimizationMap() { static Indestructible<OptimizationMap> kOptMap; return *kOptMap; } } absl::Status RegisterOptimization(absl::string_view optimization_name, expr::Optimizer optimizer) { OptimizationMap& opt_map = GetOptimizationMap(); absl::MutexLock l(&opt_map.lock); if (opt_map.optimizers.contains(optimization_name)) { return absl::FailedPreconditionError(absl::StrFormat( "RegisterOptimization called twice for %s", optimization_name)); } opt_map.optimizers.emplace(std::string(optimization_name), optimizer); return absl::OkStatus(); } absl::StatusOr<expr::Optimizer> GetOptimizer(absl::string_view name) { if (name.empty()) { return expr::CodegenOptimizer(); } OptimizationMap& opt_map = GetOptimizationMap(); absl::MutexLock l(&opt_map.lock); if (auto it = opt_map.optimizers.find(name); it != opt_map.optimizers.end()) { return it->second; } return absl::NotFoundError( absl::StrFormat("unrecognized optimization name: %s", name)); } }
#include "arolla/codegen/expr/optimizations.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_node.h" #include "arolla/util/testing/status_matchers_backport.h" namespace arolla::codegen { namespace { using ::arolla::testing::IsOk; using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::StatusIs; using ::testing::_; using ::testing::HasSubstr; TEST(GetOptimizer, DefaultIsOk) { EXPECT_THAT(GetOptimizer(""), IsOkAndHolds(_)); } TEST(GetOptimizer, Unknown) { EXPECT_THAT(GetOptimizer("unknown_name").status(), StatusIs(absl::StatusCode::kNotFound, HasSubstr("unknown_name"))); } TEST(GetOptimizer, Register) { EXPECT_THAT(RegisterOptimization( "new_opt", [](expr::ExprNodePtr) -> absl::StatusOr<expr::ExprNodePtr> { return absl::InternalError("fake optimization"); }), IsOk()); ASSERT_OK_AND_ASSIGN(auto optimizer, GetOptimizer("new_opt")); EXPECT_THAT( optimizer(expr::Leaf("x")).status(), StatusIs(absl::StatusCode::kInternal, HasSubstr("fake optimization"))); } } }
2,398
cpp
google/arolla
sequence
arolla/sequence/sequence.cc
arolla/sequence/sequence_test.cc
#ifndef AROLLA_SEQUENCE_SEQUENCE_H_ #define AROLLA_SEQUENCE_SEQUENCE_H_ #include <algorithm> #include <cstddef> #include <memory> #include <utility> #include "absl/log/check.h" #include "absl/types/span.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/typed_ref.h" #include "arolla/util/api.h" #include "arolla/util/demangle.h" #include "arolla/util/fingerprint.h" #include "arolla/util/repr.h" namespace arolla { class AROLLA_API Sequence { public: Sequence() = default; Sequence(QTypePtr value_qtype, size_t size, std::shared_ptr<const void>&& data) : value_qtype_(value_qtype), size_(size), data_(std::move(data)) { DCHECK_NE(value_qtype, nullptr); } Sequence(const Sequence&) = default; Sequence(Sequence&&) = default; Sequence& operator=(const Sequence&) = default; Sequence& operator=(Sequence&&) = default; QTypePtr value_qtype() const; size_t size() const; const void* RawData() const; const void* RawAt(size_t i, size_t element_alloc_size) const; template <typename T> absl::Span<const T> UnsafeSpan() const; TypedRef GetRef(size_t i) const; Sequence subsequence(size_t offset, size_t count) const; private: QTypePtr value_qtype_ = GetNothingQType(); size_t size_ = 0; std::shared_ptr<const void> data_; }; inline QTypePtr Sequence::value_qtype() const { return value_qtype_; } inline size_t Sequence::size() const { return size_; } inline const void* Sequence::RawData() const { return data_.get(); } inline const void* Sequence::RawAt(size_t i, size_t element_alloc_size) const { DCHECK_LT(i, size_) << "index is out of range: " << i << " >= size=" << size_; DCHECK_EQ(element_alloc_size, value_qtype_->type_layout().AllocSize()) << "element size mismatched: expected " << value_qtype_->type_layout().AllocSize() << ", got " << element_alloc_size; return reinterpret_cast<const char*>(RawData()) + i * element_alloc_size; } template <typename T> absl::Span<const T> Sequence::UnsafeSpan() const { DCHECK(typeid(T) == value_qtype_->type_info()) << "element type mismatched: expected " << TypeName(value_qtype_->type_info()) << ", got " << TypeName<T>(); return absl::Span<const T>(reinterpret_cast<const T*>(data_.get()), size_); } inline TypedRef Sequence::GetRef(size_t i) const { DCHECK_LT(i, size_) << "index is out of range: " << i << " >= size=" << size_; const char* const data = reinterpret_cast<const char*>(data_.get()); return TypedRef::UnsafeFromRawPointer( value_qtype_, data + i * value_qtype_->type_layout().AllocSize()); } inline Sequence Sequence::subsequence(size_t offset, size_t count) const { DCHECK_LE(offset, size_) << "offset is out of range: " << offset << " > size=" << size_; count = std::min(count, size_ - offset); if (count == 0) { return Sequence(value_qtype_, 0, nullptr); } const char* const data = reinterpret_cast<const char*>(data_.get()); return Sequence( value_qtype_, count, std::shared_ptr<const void>( data_, data + offset * value_qtype_->type_layout().AllocSize())); } AROLLA_DECLARE_FINGERPRINT_HASHER_TRAITS(Sequence); AROLLA_DECLARE_REPR(Sequence); } #endif #include "arolla/sequence/sequence.h" #include <algorithm> #include <cstddef> #include <sstream> #include <utility> #include "arolla/qtype/qtype.h" #include "arolla/util/fingerprint.h" #include "arolla/util/repr.h" namespace arolla { void FingerprintHasherTraits<Sequence>::operator()( FingerprintHasher* hasher, const Sequence& sequence) const { const QTypePtr value_qtype = sequence.value_qtype(); const size_t value_byte_size = value_qtype->type_layout().AllocSize(); hasher->Combine(value_qtype, sequence.size()); for (size_t i = 0; i < sequence.size(); ++i) { value_qtype->UnsafeCombineToFingerprintHasher( sequence.RawAt(i, value_byte_size), hasher); } } ReprToken ReprTraits<Sequence>::operator()(const Sequence& sequence) const { std::ostringstream result; result << "sequence("; const auto n = std::min<size_t>(sequence.size(), 10); for (size_t i = 0; i < n; ++i) { result << sequence.GetRef(i).Repr() << ", "; } if (n < sequence.size()) { result << "..., size=" << sequence.size() << ", "; } result << "value_qtype=" << sequence.value_qtype()->name() << ")"; return ReprToken{std::move(result).str()}; } }
#include "arolla/sequence/sequence.h" #include <algorithm> #include <cstdint> #include <utility> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/types/span.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/sequence/mutable_sequence.h" #include "arolla/util/fingerprint.h" #include "arolla/util/init_arolla.h" #include "arolla/util/repr.h" #include "arolla/util/testing/repr_token_eq.h" #include "arolla/util/unit.h" namespace arolla { namespace { using ::arolla::testing::ReprTokenEq; class SequenceTest : public ::testing::Test { void SetUp() override { ASSERT_OK(InitArolla()); } }; TEST_F(SequenceTest, DefaultConstructor) { Sequence seq; EXPECT_EQ(seq.value_qtype(), GetNothingQType()); EXPECT_EQ(seq.size(), 0); EXPECT_EQ(seq.RawData(), nullptr); } TEST_F(SequenceTest, MakeSize1) { ASSERT_OK_AND_ASSIGN(auto mutable_seq, MutableSequence::Make(GetQType<int32_t>(), 1)); const auto seq = std::move(mutable_seq).Finish(); EXPECT_EQ(seq.value_qtype(), GetQType<int32_t>()); EXPECT_EQ(seq.size(), 1); EXPECT_NE(seq.RawData(), nullptr); } TEST_F(SequenceTest, RawAt) { ASSERT_OK_AND_ASSIGN(auto mutable_seq, MutableSequence::Make(GetQType<int32_t>(), 100)); const auto seq = std::move(mutable_seq).Finish(); for (int i = 0; i < 100; i += 10) { EXPECT_EQ(seq.RawAt(i, sizeof(int32_t)), static_cast<const char*>(seq.RawData()) + i * sizeof(int32_t)); } } TEST_F(SequenceTest, UnsafeSpan) { ASSERT_OK_AND_ASSIGN(auto mutable_seq, MutableSequence::Make(GetQType<float>(), 100)); const auto seq = std::move(mutable_seq).Finish(); absl::Span<const float> span = seq.UnsafeSpan<float>(); EXPECT_EQ(span.data(), seq.RawData()); EXPECT_EQ(span.size(), 100); } TEST_F(SequenceTest, GetRef) { ASSERT_OK_AND_ASSIGN(auto mutable_seq, MutableSequence::Make(GetQType<double>(), 100)); const auto seq = std::move(mutable_seq).Finish(); for (int i = 0; i < 100; i += 10) { auto ref = seq.GetRef(i); EXPECT_EQ(ref.GetType(), GetQType<double>()); EXPECT_EQ(ref.GetRawPointer(), seq.RawAt(i, sizeof(double))); } } TEST_F(SequenceTest, subsequence) { ASSERT_OK_AND_ASSIGN(auto mutable_seq, MutableSequence::Make(GetQType<int32_t>(), 100)); const auto seq = std::move(mutable_seq).Finish(); for (int offset = 0; offset < 100; offset += 10) { for (int count = 10; count <= 100; count += 30) { const auto subseq = seq.subsequence(offset, count); EXPECT_EQ(subseq.value_qtype(), GetQType<int32_t>()); EXPECT_EQ(subseq.size(), std::min(count, 100 - offset)); EXPECT_EQ( static_cast<const char*>(subseq.RawData()), static_cast<const char*>(seq.RawData()) + offset * sizeof(int32_t)); } } for (int offset = 0; offset < 100; offset += 10) { const auto subseq = seq.subsequence(offset, 0); EXPECT_EQ(subseq.size(), 0); EXPECT_EQ(subseq.RawData(), nullptr); EXPECT_EQ(subseq.value_qtype(), GetQType<int32_t>()); } for (int count = 0; count <= 100; count += 25) { const auto subseq = seq.subsequence(100, count); EXPECT_EQ(subseq.size(), 0); EXPECT_EQ(subseq.RawData(), nullptr); EXPECT_EQ(subseq.value_qtype(), GetQType<int32_t>()); } } #ifndef NDEBUG using SequenceDeathTest = SequenceTest; TEST_F(SequenceDeathTest, RawAtDCheckIndexIsOutOfRange) { ASSERT_OK_AND_ASSIGN(auto mutable_seq, MutableSequence::Make(GetQType<int32_t>(), 100)); const auto seq = std::move(mutable_seq).Finish(); EXPECT_DEATH(seq.RawAt(100, sizeof(int32_t)), "index is out of range: 100 >= size=100"); } TEST_F(SequenceDeathTest, RawAtDCheckElementSizeMismatch) { ASSERT_OK_AND_ASSIGN(auto mutable_seq, MutableSequence::Make(GetQType<int32_t>(), 100)); const auto seq = std::move(mutable_seq).Finish(); EXPECT_DEATH(seq.RawAt(0, 3), "element size mismatched: expected 4, got 3"); } TEST_F(SequenceDeathTest, UnsafeSpanDCheckElementTypeMismatch) { ASSERT_OK_AND_ASSIGN(auto mutable_seq, MutableSequence::Make(GetQType<int>(), 100)); const auto seq = std::move(mutable_seq).Finish(); EXPECT_DEATH(seq.UnsafeSpan<float>(), "element type mismatched: expected int, got float"); } TEST_F(SequenceDeathTest, GetRefDCheckIndexIsOutOfRange) { ASSERT_OK_AND_ASSIGN(auto mutable_seq, MutableSequence::Make(GetQType<int32_t>(), 100)); const auto seq = std::move(mutable_seq).Finish(); EXPECT_DEATH(seq.GetRef(100), "index is out of range: 100 >= size=100"); } #endif TEST_F(SequenceTest, ReprEmpty) { EXPECT_THAT(GenReprToken(Sequence()), ReprTokenEq("sequence(value_qtype=NOTHING)")); } TEST_F(SequenceTest, Repr) { ASSERT_OK_AND_ASSIGN(auto mutable_seq, MutableSequence::Make(GetQTypeQType(), 4)); auto mutable_span = mutable_seq.UnsafeSpan<QTypePtr>(); mutable_span[0] = GetQType<Unit>(); mutable_span[1] = GetQType<bool>(); mutable_span[2] = GetQType<int32_t>(); mutable_span[3] = GetQType<float>(); auto seq = std::move(mutable_seq).Finish(); EXPECT_THAT( GenReprToken(seq), ReprTokenEq( "sequence(UNIT, BOOLEAN, INT32, FLOAT32, value_qtype=QTYPE)")); } TEST_F(SequenceTest, ReprLarge) { ASSERT_OK_AND_ASSIGN(auto mutable_seq, MutableSequence::Make(GetQTypeQType(), 11)); for (auto& x : mutable_seq.UnsafeSpan<QTypePtr>()) { x = GetQType<Unit>(); } auto seq = std::move(mutable_seq).Finish(); EXPECT_THAT( GenReprToken(seq), ReprTokenEq( "sequence(UNIT, UNIT, UNIT, UNIT, UNIT, UNIT, UNIT, UNIT, UNIT, " "UNIT, ..., size=11, value_qtype=QTYPE)")); } TEST_F(SequenceTest, Fingerprint) { std::vector<Sequence> sequences; { sequences.push_back(Sequence()); } { ASSERT_OK_AND_ASSIGN(auto mutable_seq, MutableSequence::Make(GetQTypeQType(), 0)); sequences.push_back(std::move(mutable_seq).Finish()); } { ASSERT_OK_AND_ASSIGN(auto mutable_seq, MutableSequence::Make(GetQType<int32_t>(), 2)); auto mutable_span = mutable_seq.UnsafeSpan<int32_t>(); mutable_span[0] = 0; mutable_span[1] = 1; sequences.push_back(std::move(mutable_seq).Finish()); } { ASSERT_OK_AND_ASSIGN(auto mutable_seq, MutableSequence::Make(GetQType<int32_t>(), 2)); auto mutable_span = mutable_seq.UnsafeSpan<int32_t>(); mutable_span[0] = 0; mutable_span[1] = 0; sequences.push_back(std::move(mutable_seq).Finish()); } for (auto& s0 : sequences) { for (auto& s1 : sequences) { const auto f0 = FingerprintHasher("salt").Combine(s0).Finish(); const auto f1 = FingerprintHasher("salt").Combine( Sequence(s1)).Finish(); if (&s0 == &s1) { EXPECT_EQ(f0, f1) << Repr(s0) << ".fingerprint != " << Repr(s1) << ".fingerprint"; } else { EXPECT_NE(f0, f1) << Repr(s0) << ".fingerprint != " << Repr(s1) << ".fingerprint"; } } } } } }
2,399
cpp
google/arolla
sequence_qtype
arolla/sequence/sequence_qtype.cc
arolla/sequence/sequence_qtype_test.cc
#ifndef AROLLA_SEQUENCE_SEQUENCE_QTYPE_H_ #define AROLLA_SEQUENCE_SEQUENCE_QTYPE_H_ #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" namespace arolla { bool IsSequenceQType(const QType* qtype); QTypePtr GetSequenceQType(QTypePtr value_qtype); template <typename T> QTypePtr GetSequenceQType() { return GetSequenceQType(GetQType<T>()); } } #endif #include "arolla/sequence/sequence_qtype.h" #include <memory> #include <string> #include "absl/base/thread_annotations.h" #include "absl/container/flat_hash_map.h" #include "absl/synchronization/mutex.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/simple_qtype.h" #include "arolla/sequence/sequence.h" #include "arolla/util/fast_dynamic_downcast_final.h" #include "arolla/util/indestructible.h" #include "arolla/util/meta.h" namespace arolla { namespace { class SequenceQType final : public SimpleQType { public: explicit SequenceQType(QTypePtr value_qtype) : SimpleQType(meta::type<Sequence>(), "SEQUENCE[" + std::string(value_qtype->name()) + "]", value_qtype, "::arolla::SequenceQType") {} }; class SequenceQTypeRegistry { public: QTypePtr GetSequenceQType(QTypePtr value_qtype) { absl::WriterMutexLock l(&lock_); auto& result = registry_[value_qtype]; if (!result) { result = std::make_unique<SequenceQType>(value_qtype); } return result.get(); } private: absl::Mutex lock_; absl::flat_hash_map<QTypePtr, std::unique_ptr<SequenceQType>> registry_ ABSL_GUARDED_BY(lock_); }; } bool IsSequenceQType(const QType* qtype) { return fast_dynamic_downcast_final<const SequenceQType*>(qtype) != nullptr; } QTypePtr GetSequenceQType(QTypePtr value_qtype) { static Indestructible<SequenceQTypeRegistry> registry; return registry->GetSequenceQType(value_qtype); } }
#include "arolla/sequence/sequence_qtype.h" #include <cstdint> #include <utility> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/typed_value.h" #include "arolla/sequence/mutable_sequence.h" #include "arolla/sequence/sequence.h" #include "arolla/util/init_arolla.h" #include "arolla/util/testing/repr_token_eq.h" namespace arolla { namespace { using ::arolla::testing::ReprTokenEq; class SequenceQTypeTest : public ::testing::Test { void SetUp() override { ASSERT_OK(InitArolla()); } }; TEST_F(SequenceQTypeTest, Basics) { const auto* qtype = GetSequenceQType<QTypePtr>(); EXPECT_EQ(qtype->name(), "SEQUENCE[QTYPE]"); EXPECT_EQ(qtype->type_info(), typeid(Sequence)); EXPECT_EQ(qtype->type_layout().AllocSize(), sizeof(Sequence)); EXPECT_EQ(qtype->type_layout().AllocAlignment().value, alignof(Sequence)); EXPECT_TRUE(qtype->type_fields().empty()); EXPECT_EQ(qtype->value_qtype(), GetQTypeQType()); EXPECT_EQ(qtype->qtype_specialization_key(), "::arolla::SequenceQType"); } TEST_F(SequenceQTypeTest, IsSequenceQType) { EXPECT_TRUE(IsSequenceQType(GetSequenceQType<QTypePtr>())); EXPECT_TRUE(IsSequenceQType(GetSequenceQType<int32_t>())); EXPECT_TRUE(IsSequenceQType(GetSequenceQType<float>())); EXPECT_FALSE(IsSequenceQType(GetQTypeQType())); EXPECT_FALSE(IsSequenceQType(GetQType<int32_t>())); EXPECT_FALSE(IsSequenceQType(GetQType<float>())); } TEST_F(SequenceQTypeTest, TypedValue) { ASSERT_OK_AND_ASSIGN(auto mutable_seq, MutableSequence::Make(GetQType<int32_t>(), 3)); auto mutable_span = mutable_seq.UnsafeSpan<int32_t>(); mutable_span[0] = 1; mutable_span[1] = 2; mutable_span[2] = 3; ASSERT_OK_AND_ASSIGN(auto typed_value, TypedValue::FromValueWithQType( std::move(mutable_seq).Finish(), GetSequenceQType<int32_t>())); EXPECT_EQ(typed_value.GetType()->name(), "SEQUENCE[INT32]"); EXPECT_THAT(typed_value.GenReprToken(), ReprTokenEq("sequence(1, 2, 3, value_qtype=INT32)")); } } }