Unnamed: 0
int64
0
409
Code
stringlengths
131
27.3k
Unit Test
stringlengths
89
30.5k
400
#ifndef THIRD_PARTY_CEL_CPP_EVAL_PUBLIC_CONTAINERS_CONTAINER_BACKED_MAP_IMPL_H_ #define THIRD_PARTY_CEL_CPP_EVAL_PUBLIC_CONTAINERS_CONTAINER_BACKED_MAP_IMPL_H_ #include <memory> #include <utility> #include "absl/container/node_hash_map.h" #include "absl/status/statusor.h" #include "absl/types/span.h" #include "eval/public/cel_value.h" namespace google::api::expr::runtime { class CelMapBuilder : public CelMap { public: CelMapBuilder() {} absl::Status Add(CelValue key, CelValue value); int size() const override { return values_map_.size(); } absl::optional<CelValue> operator[](CelValue cel_key) const override; absl::StatusOr<bool> Has(const CelValue& cel_key) const override { return values_map_.contains(cel_key); } absl::StatusOr<const CelList*> ListKeys() const override { return &key_list_; } private: class KeyList : public CelList { public: KeyList() {} int size() const override { return keys_.size(); } CelValue operator[](int index) const override { return keys_[index]; } void Add(const CelValue& key) { keys_.push_back(key); } private: std::vector<CelValue> keys_; }; struct Hasher { size_t operator()(const CelValue& key) const; }; struct Equal { bool operator()(const CelValue& key1, const CelValue& key2) const; }; absl::node_hash_map<CelValue, CelValue, Hasher, Equal> values_map_; KeyList key_list_; }; absl::StatusOr<std::unique_ptr<CelMap>> CreateContainerBackedMap( absl::Span<const std::pair<CelValue, CelValue>> key_values); } #endif #include "eval/public/containers/container_backed_map_impl.h" #include <memory> #include <utility> #include "absl/container/node_hash_map.h" #include "absl/hash/hash.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/types/optional.h" #include "absl/types/span.h" #include "eval/public/cel_value.h" namespace google { namespace api { namespace expr { namespace runtime { namespace { class HasherOp { public: template <class T> size_t operator()(const T& arg) { return std::hash<T>()(arg); } size_t operator()(const absl::Time arg) { return absl::Hash<absl::Time>()(arg); } size_t operator()(const absl::Duration arg) { return absl::Hash<absl::Duration>()(arg); } size_t operator()(const CelValue::StringHolder& arg) { return absl::Hash<absl::string_view>()(arg.value()); } size_t operator()(const CelValue::BytesHolder& arg) { return absl::Hash<absl::string_view>()(arg.value()); } size_t operator()(const CelValue::CelTypeHolder& arg) { return absl::Hash<absl::string_view>()(arg.value()); } size_t operator()(const std::nullptr_t&) { return 0; } }; template <class T> class EqualOp { public: explicit EqualOp(const T& arg) : arg_(arg) {} template <class U> bool operator()(const U&) const { return false; } bool operator()(const T& other) const { return other == arg_; } private: const T& arg_; }; class CelValueEq { public: explicit CelValueEq(const CelValue& other) : other_(other) {} template <class Type> bool operator()(const Type& arg) { return other_.template Visit<bool>(EqualOp<Type>(arg)); } private: const CelValue& other_; }; } absl::optional<CelValue> CelMapBuilder::operator[](CelValue cel_key) const { auto item = values_map_.find(cel_key); if (item == values_map_.end()) { return absl::nullopt; } return item->second; } absl::Status CelMapBuilder::Add(CelValue key, CelValue value) { auto [unused, inserted] = values_map_.emplace(key, value); if (!inserted) { return absl::InvalidArgumentError("duplicate map keys"); } key_list_.Add(key); return absl::OkStatus(); } size_t CelMapBuilder::Hasher::operator()(const CelValue& key) const { return key.template Visit<size_t>(HasherOp()); } bool CelMapBuilder::Equal::operator()(const CelValue& key1, const CelValue& key2) const { if (key1.type() != key2.type()) { return false; } return key1.template Visit<bool>(CelValueEq(key2)); } absl::StatusOr<std::unique_ptr<CelMap>> CreateContainerBackedMap( absl::Span<const std::pair<CelValue, CelValue>> key_values) { auto map = std::make_unique<CelMapBuilder>(); for (const auto& key_value : key_values) { CEL_RETURN_IF_ERROR(map->Add(key_value.first, key_value.second)); } return map; } } } } }
#include "eval/public/containers/container_backed_map_impl.h" #include <string> #include <utility> #include <vector> #include "absl/status/status.h" #include "eval/public/cel_value.h" #include "internal/testing.h" namespace google::api::expr::runtime { namespace { using testing::Eq; using testing::IsNull; using testing::Not; using cel::internal::StatusIs; TEST(ContainerBackedMapImplTest, TestMapInt64) { std::vector<std::pair<CelValue, CelValue>> args = { {CelValue::CreateInt64(1), CelValue::CreateInt64(2)}, {CelValue::CreateInt64(2), CelValue::CreateInt64(3)}}; auto cel_map = CreateContainerBackedMap( absl::Span<std::pair<CelValue, CelValue>>(args.data(), args.size())) .value(); ASSERT_THAT(cel_map, Not(IsNull())); EXPECT_THAT(cel_map->size(), Eq(2)); auto lookup1 = (*cel_map)[CelValue::CreateInt64(1)]; ASSERT_TRUE(lookup1); CelValue cel_value = lookup1.value(); ASSERT_TRUE(cel_value.IsInt64()); EXPECT_THAT(cel_value.Int64OrDie(), 2); auto lookup2 = (*cel_map)[CelValue::CreateUint64(1)]; ASSERT_FALSE(lookup2); auto lookup3 = (*cel_map)[CelValue::CreateInt64(3)]; ASSERT_FALSE(lookup3); } TEST(ContainerBackedMapImplTest, TestMapUint64) { std::vector<std::pair<CelValue, CelValue>> args = { {CelValue::CreateUint64(1), CelValue::CreateInt64(2)}, {CelValue::CreateUint64(2), CelValue::CreateInt64(3)}}; auto cel_map = CreateContainerBackedMap( absl::Span<std::pair<CelValue, CelValue>>(args.data(), args.size())) .value(); ASSERT_THAT(cel_map, Not(IsNull())); EXPECT_THAT(cel_map->size(), Eq(2)); auto lookup1 = (*cel_map)[CelValue::CreateUint64(1)]; ASSERT_TRUE(lookup1); CelValue cel_value = lookup1.value(); ASSERT_TRUE(cel_value.IsInt64()); EXPECT_THAT(cel_value.Int64OrDie(), 2); auto lookup2 = (*cel_map)[CelValue::CreateInt64(1)]; ASSERT_FALSE(lookup2); auto lookup3 = (*cel_map)[CelValue::CreateUint64(3)]; ASSERT_FALSE(lookup3); } TEST(ContainerBackedMapImplTest, TestMapString) { const std::string kKey1 = "1"; const std::string kKey2 = "2"; const std::string kKey3 = "3"; std::vector<std::pair<CelValue, CelValue>> args = { {CelValue::CreateString(&kKey1), CelValue::CreateInt64(2)}, {CelValue::CreateString(&kKey2), CelValue::CreateInt64(3)}}; auto cel_map = CreateContainerBackedMap( absl::Span<std::pair<CelValue, CelValue>>(args.data(), args.size())) .value(); ASSERT_THAT(cel_map, Not(IsNull())); EXPECT_THAT(cel_map->size(), Eq(2)); auto lookup1 = (*cel_map)[CelValue::CreateString(&kKey1)]; ASSERT_TRUE(lookup1); CelValue cel_value = lookup1.value(); ASSERT_TRUE(cel_value.IsInt64()); EXPECT_THAT(cel_value.Int64OrDie(), 2); auto lookup2 = (*cel_map)[CelValue::CreateInt64(1)]; ASSERT_FALSE(lookup2); auto lookup3 = (*cel_map)[CelValue::CreateString(&kKey3)]; ASSERT_FALSE(lookup3); } TEST(CelMapBuilder, TestMapString) { const std::string kKey1 = "1"; const std::string kKey2 = "2"; const std::string kKey3 = "3"; std::vector<std::pair<CelValue, CelValue>> args = { {CelValue::CreateString(&kKey1), CelValue::CreateInt64(2)}, {CelValue::CreateString(&kKey2), CelValue::CreateInt64(3)}}; CelMapBuilder builder; ASSERT_OK( builder.Add(CelValue::CreateString(&kKey1), CelValue::CreateInt64(2))); ASSERT_OK( builder.Add(CelValue::CreateString(&kKey2), CelValue::CreateInt64(3))); CelMap* cel_map = &builder; ASSERT_THAT(cel_map, Not(IsNull())); EXPECT_THAT(cel_map->size(), Eq(2)); auto lookup1 = (*cel_map)[CelValue::CreateString(&kKey1)]; ASSERT_TRUE(lookup1); CelValue cel_value = lookup1.value(); ASSERT_TRUE(cel_value.IsInt64()); EXPECT_THAT(cel_value.Int64OrDie(), 2); auto lookup2 = (*cel_map)[CelValue::CreateInt64(1)]; ASSERT_FALSE(lookup2); auto lookup3 = (*cel_map)[CelValue::CreateString(&kKey3)]; ASSERT_FALSE(lookup3); } TEST(CelMapBuilder, RepeatKeysFail) { const std::string kKey1 = "1"; const std::string kKey2 = "2"; std::vector<std::pair<CelValue, CelValue>> args = { {CelValue::CreateString(&kKey1), CelValue::CreateInt64(2)}, {CelValue::CreateString(&kKey2), CelValue::CreateInt64(3)}}; CelMapBuilder builder; ASSERT_OK( builder.Add(CelValue::CreateString(&kKey1), CelValue::CreateInt64(2))); ASSERT_OK( builder.Add(CelValue::CreateString(&kKey2), CelValue::CreateInt64(3))); EXPECT_THAT( builder.Add(CelValue::CreateString(&kKey2), CelValue::CreateInt64(3)), StatusIs(absl::StatusCode::kInvalidArgument, "duplicate map keys")); } } }
401
#ifndef QUICHE_HTTP2_HPACK_HUFFMAN_HPACK_HUFFMAN_ENCODER_H_ #define QUICHE_HTTP2_HPACK_HUFFMAN_HPACK_HUFFMAN_ENCODER_H_ #include <cstddef> #include <string> #include "absl/strings/string_view.h" #include "quiche/common/platform/api/quiche_export.h" namespace http2 { QUICHE_EXPORT size_t HuffmanSize(absl::string_view plain); QUICHE_EXPORT void HuffmanEncode(absl::string_view plain, size_t encoded_size, std::string* huffman); QUICHE_EXPORT void HuffmanEncodeFast(absl::string_view input, size_t encoded_size, std::string* output); } #endif #include "quiche/http2/hpack/huffman/hpack_huffman_encoder.h" #include <string> #include "quiche/http2/hpack/huffman/huffman_spec_tables.h" #include "quiche/common/platform/api/quiche_logging.h" namespace http2 { size_t HuffmanSize(absl::string_view plain) { size_t bits = 0; for (const uint8_t c : plain) { bits += HuffmanSpecTables::kCodeLengths[c]; } return (bits + 7) / 8; } void HuffmanEncode(absl::string_view plain, size_t encoded_size, std::string* huffman) { QUICHE_DCHECK(huffman != nullptr); huffman->reserve(huffman->size() + encoded_size); uint64_t bit_buffer = 0; size_t bits_unused = 64; for (uint8_t c : plain) { size_t code_length = HuffmanSpecTables::kCodeLengths[c]; if (bits_unused < code_length) { do { char h = static_cast<char>(bit_buffer >> 56); bit_buffer <<= 8; bits_unused += 8; huffman->push_back(h); } while (bits_unused <= 56); } uint64_t code = HuffmanSpecTables::kRightCodes[c]; size_t shift_by = bits_unused - code_length; bit_buffer |= (code << shift_by); bits_unused -= code_length; } size_t bits_used = 64 - bits_unused; while (bits_used >= 8) { char h = static_cast<char>(bit_buffer >> 56); bit_buffer <<= 8; bits_used -= 8; huffman->push_back(h); } if (bits_used > 0) { constexpr uint64_t leading_eos_bits = 0b11111111; bit_buffer |= (leading_eos_bits << (56 - bits_used)); char h = static_cast<char>(bit_buffer >> 56); huffman->push_back(h); } } void HuffmanEncodeFast(absl::string_view input, size_t encoded_size, std::string* output) { const size_t original_size = output->size(); const size_t final_size = original_size + encoded_size; output->resize(final_size + 4, 0); char* const first = &*output->begin() + original_size; size_t bit_counter = 0; for (uint8_t c : input) { uint64_t code = static_cast<uint64_t>(HuffmanSpecTables::kLeftCodes[c]) << (8 - (bit_counter % 8)); char* const current = first + (bit_counter / 8); bit_counter += HuffmanSpecTables::kCodeLengths[c]; *current |= code >> 32; *(current + 1) |= (code >> 24) & 0xff; if ((code & 0xff0000) == 0) { continue; } *(current + 2) |= (code >> 16) & 0xff; if ((code & 0xff00) == 0) { continue; } *(current + 3) |= (code >> 8) & 0xff; *(current + 4) |= code & 0xff; } QUICHE_DCHECK_EQ(encoded_size, (bit_counter + 7) / 8); if (bit_counter % 8 != 0) { *(first + encoded_size - 1) |= 0xff >> (bit_counter & 7); } output->resize(final_size); } }
#include "quiche/http2/hpack/huffman/hpack_huffman_encoder.h" #include <cstddef> #include <string> #include "absl/base/macros.h" #include "absl/strings/escaping.h" #include "quiche/common/platform/api/quiche_test.h" namespace http2 { namespace { class HuffmanEncoderTest : public quiche::test::QuicheTestWithParam<bool> { protected: HuffmanEncoderTest() : use_fast_encoder_(GetParam()) {} virtual ~HuffmanEncoderTest() = default; void Encode(absl::string_view input, size_t encoded_size, std::string* output) { use_fast_encoder_ ? HuffmanEncodeFast(input, encoded_size, output) : HuffmanEncode(input, encoded_size, output); } const bool use_fast_encoder_; }; INSTANTIATE_TEST_SUITE_P(TwoEncoders, HuffmanEncoderTest, ::testing::Bool()); TEST_P(HuffmanEncoderTest, Empty) { std::string empty(""); size_t encoded_size = HuffmanSize(empty); EXPECT_EQ(0u, encoded_size); std::string buffer; Encode(empty, encoded_size, &buffer); EXPECT_EQ("", buffer); } TEST_P(HuffmanEncoderTest, SpecRequestExamples) { std::string test_table[] = { "f1e3c2e5f23a6ba0ab90f4ff", "www.example.com", "a8eb10649cbf", "no-cache", "25a849e95ba97d7f", "custom-key", "25a849e95bb8e8b4bf", "custom-value", }; for (size_t i = 0; i != ABSL_ARRAYSIZE(test_table); i += 2) { std::string huffman_encoded; ASSERT_TRUE(absl::HexStringToBytes(test_table[i], &huffman_encoded)); const std::string& plain_string(test_table[i + 1]); size_t encoded_size = HuffmanSize(plain_string); EXPECT_EQ(huffman_encoded.size(), encoded_size); std::string buffer; buffer.reserve(huffman_encoded.size()); Encode(plain_string, encoded_size, &buffer); EXPECT_EQ(buffer, huffman_encoded) << "Error encoding " << plain_string; } } TEST_P(HuffmanEncoderTest, SpecResponseExamples) { std::string test_table[] = { "6402", "302", "aec3771a4b", "private", "d07abe941054d444a8200595040b8166e082a62d1bff", "Mon, 21 Oct 2013 20:13:21 GMT", "9d29ad171863c78f0b97c8e9ae82ae43d3", "https: "94e7821dd7f2e6c7b335dfdfcd5b3960d5af27087f3672c1ab270fb5291f9587316065c0" "03ed4ee5b1063d5007", "foo=ASDJKHQKBZXOQWEOPIUAXQWEOIU; max-age=3600; version=1", }; for (size_t i = 0; i != ABSL_ARRAYSIZE(test_table); i += 2) { std::string huffman_encoded; ASSERT_TRUE(absl::HexStringToBytes(test_table[i], &huffman_encoded)); const std::string& plain_string(test_table[i + 1]); size_t encoded_size = HuffmanSize(plain_string); EXPECT_EQ(huffman_encoded.size(), encoded_size); std::string buffer; Encode(plain_string, encoded_size, &buffer); EXPECT_EQ(buffer, huffman_encoded) << "Error encoding " << plain_string; } } TEST_P(HuffmanEncoderTest, EncodedSizeAgreesWithEncodeString) { std::string test_table[] = { "", "Mon, 21 Oct 2013 20:13:21 GMT", "https: "foo=ASDJKHQKBZXOQWEOPIUAXQWEOIU; max-age=3600; version=1", std::string(1, '\0'), std::string("foo\0bar", 7), std::string(256, '\0'), }; for (size_t i = 0; i != 256; ++i) { test_table[ABSL_ARRAYSIZE(test_table) - 1][i] = static_cast<char>(i); } for (size_t i = 0; i != ABSL_ARRAYSIZE(test_table); ++i) { const std::string& plain_string = test_table[i]; size_t encoded_size = HuffmanSize(plain_string); std::string huffman_encoded; Encode(plain_string, encoded_size, &huffman_encoded); EXPECT_EQ(encoded_size, huffman_encoded.size()); } } TEST_P(HuffmanEncoderTest, AppendToOutput) { size_t encoded_size = HuffmanSize("foo"); std::string buffer; Encode("foo", encoded_size, &buffer); std::string expected_encoding; ASSERT_TRUE(absl::HexStringToBytes("94e7", &expected_encoding)); EXPECT_EQ(expected_encoding, buffer); encoded_size = HuffmanSize("bar"); Encode("bar", encoded_size, &buffer); ASSERT_TRUE(absl::HexStringToBytes("94e78c767f", &expected_encoding)); EXPECT_EQ(expected_encoding, buffer); } } }
402
#ifndef QUICHE_QUIC_CORE_QUIC_CONNECTION_CONTEXT_H_ #define QUICHE_QUIC_CORE_QUIC_CONNECTION_CONTEXT_H_ #include <memory> #include "absl/strings/str_format.h" #include "absl/strings/string_view.h" #include "quiche/quic/platform/api/quic_export.h" #include "quiche/common/platform/api/quiche_logging.h" namespace quic { class QUICHE_EXPORT QuicConnectionTracer { public: virtual ~QuicConnectionTracer() = default; virtual void PrintLiteral(const char* literal) = 0; virtual void PrintString(absl::string_view s) = 0; template <typename... Args> void Printf(const absl::FormatSpec<Args...>& format, const Args&... args) { std::string s = absl::StrFormat(format, args...); PrintString(s); } }; class QUICHE_EXPORT QuicBugListener { public: virtual ~QuicBugListener() = default; virtual void OnQuicBug(const char* bug_id, const char* file, int line, absl::string_view bug_message) = 0; }; class QUICHE_EXPORT QuicConnectionContextListener { public: virtual ~QuicConnectionContextListener() = default; private: friend class QuicConnectionContextSwitcher; virtual void Activate() = 0; virtual void Deactivate() = 0; }; struct QUICHE_EXPORT QuicConnectionContext final { static QuicConnectionContext* Current(); std::unique_ptr<QuicConnectionContextListener> listener; std::unique_ptr<QuicConnectionTracer> tracer; std::unique_ptr<QuicBugListener> bug_listener; }; class QUICHE_EXPORT QuicConnectionContextSwitcher final { public: explicit QuicConnectionContextSwitcher(QuicConnectionContext* new_context); ~QuicConnectionContextSwitcher(); private: QuicConnectionContext* old_context_; }; inline void QUIC_TRACELITERAL(const char* literal) { QuicConnectionContext* current = QuicConnectionContext::Current(); if (current && current->tracer) { current->tracer->PrintLiteral(literal); } } inline void QUIC_TRACESTRING(absl::string_view s) { QuicConnectionContext* current = QuicConnectionContext::Current(); if (current && current->tracer) { current->tracer->PrintString(s); } } template <typename... Args> void QUIC_TRACEPRINTF(const absl::FormatSpec<Args...>& format, const Args&... args) { QuicConnectionContext* current = QuicConnectionContext::Current(); if (current && current->tracer) { current->tracer->Printf(format, args...); } } inline QuicBugListener* CurrentBugListener() { QuicConnectionContext* current = QuicConnectionContext::Current(); return (current != nullptr) ? current->bug_listener.get() : nullptr; } } #endif #include "quiche/quic/core/quic_connection_context.h" #include "absl/base/attributes.h" namespace quic { namespace { ABSL_CONST_INIT thread_local QuicConnectionContext* current_context = nullptr; } QuicConnectionContext* QuicConnectionContext::Current() { return current_context; } QuicConnectionContextSwitcher::QuicConnectionContextSwitcher( QuicConnectionContext* new_context) : old_context_(QuicConnectionContext::Current()) { current_context = new_context; if (new_context && new_context->listener) { new_context->listener->Activate(); } } QuicConnectionContextSwitcher::~QuicConnectionContextSwitcher() { QuicConnectionContext* current = QuicConnectionContext::Current(); if (current && current->listener) { current->listener->Deactivate(); } current_context = old_context_; } }
#include "quiche/quic/core/quic_connection_context.h" #include <memory> #include <string> #include <vector> #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/platform/api/quic_thread.h" using testing::ElementsAre; namespace quic::test { namespace { class TraceCollector : public QuicConnectionTracer { public: ~TraceCollector() override = default; void PrintLiteral(const char* literal) override { trace_.push_back(literal); } void PrintString(absl::string_view s) override { trace_.push_back(std::string(s)); } const std::vector<std::string>& trace() const { return trace_; } private: std::vector<std::string> trace_; }; struct FakeConnection { FakeConnection() { context.tracer = std::make_unique<TraceCollector>(); } const std::vector<std::string>& trace() const { return static_cast<const TraceCollector*>(context.tracer.get())->trace(); } QuicConnectionContext context; }; void SimpleSwitch() { FakeConnection connection; EXPECT_EQ(QuicConnectionContext::Current(), nullptr); QUIC_TRACELITERAL("before switch: literal"); QUIC_TRACESTRING(std::string("before switch: string")); QUIC_TRACEPRINTF("%s: %s", "before switch", "printf"); { QuicConnectionContextSwitcher switcher(&connection.context); QUIC_TRACELITERAL("literal"); QUIC_TRACESTRING(std::string("string")); QUIC_TRACEPRINTF("%s", "printf"); } EXPECT_EQ(QuicConnectionContext::Current(), nullptr); QUIC_TRACELITERAL("after switch: literal"); QUIC_TRACESTRING(std::string("after switch: string")); QUIC_TRACEPRINTF("%s: %s", "after switch", "printf"); EXPECT_THAT(connection.trace(), ElementsAre("literal", "string", "printf")); } void NestedSwitch() { FakeConnection outer, inner; { QuicConnectionContextSwitcher switcher(&outer.context); QUIC_TRACELITERAL("outer literal 0"); QUIC_TRACESTRING(std::string("outer string 0")); QUIC_TRACEPRINTF("%s %s %d", "outer", "printf", 0); { QuicConnectionContextSwitcher nested_switcher(&inner.context); QUIC_TRACELITERAL("inner literal"); QUIC_TRACESTRING(std::string("inner string")); QUIC_TRACEPRINTF("%s %s", "inner", "printf"); } QUIC_TRACELITERAL("outer literal 1"); QUIC_TRACESTRING(std::string("outer string 1")); QUIC_TRACEPRINTF("%s %s %d", "outer", "printf", 1); } EXPECT_THAT(outer.trace(), ElementsAre("outer literal 0", "outer string 0", "outer printf 0", "outer literal 1", "outer string 1", "outer printf 1")); EXPECT_THAT(inner.trace(), ElementsAre("inner literal", "inner string", "inner printf")); } void AlternatingSwitch() { FakeConnection zero, one, two; for (int i = 0; i < 15; ++i) { FakeConnection* connection = ((i % 3) == 0) ? &zero : (((i % 3) == 1) ? &one : &two); QuicConnectionContextSwitcher switcher(&connection->context); QUIC_TRACEPRINTF("%d", i); } EXPECT_THAT(zero.trace(), ElementsAre("0", "3", "6", "9", "12")); EXPECT_THAT(one.trace(), ElementsAre("1", "4", "7", "10", "13")); EXPECT_THAT(two.trace(), ElementsAre("2", "5", "8", "11", "14")); } typedef void (*ThreadFunction)(); template <ThreadFunction func> class TestThread : public QuicThread { public: TestThread() : QuicThread("TestThread") {} ~TestThread() override = default; protected: void Run() override { func(); } }; template <ThreadFunction func> void RunInThreads(size_t n_threads) { using ThreadType = TestThread<func>; std::vector<ThreadType> threads(n_threads); for (ThreadType& t : threads) { t.Start(); } for (ThreadType& t : threads) { t.Join(); } } class QuicConnectionContextTest : public QuicTest { protected: }; TEST_F(QuicConnectionContextTest, NullTracerOK) { FakeConnection connection; std::unique_ptr<QuicConnectionTracer> tracer; { QuicConnectionContextSwitcher switcher(&connection.context); QUIC_TRACELITERAL("msg 1 recorded"); } connection.context.tracer.swap(tracer); { QuicConnectionContextSwitcher switcher(&connection.context); QUIC_TRACELITERAL("msg 2 ignored"); } EXPECT_THAT(static_cast<TraceCollector*>(tracer.get())->trace(), ElementsAre("msg 1 recorded")); } TEST_F(QuicConnectionContextTest, TestSimpleSwitch) { RunInThreads<SimpleSwitch>(10); } TEST_F(QuicConnectionContextTest, TestNestedSwitch) { RunInThreads<NestedSwitch>(10); } TEST_F(QuicConnectionContextTest, TestAlternatingSwitch) { RunInThreads<AlternatingSwitch>(10); } } }
403
#ifndef THIRD_PARTY_CEL_CPP_EVAL_PUBLIC_EQUALITY_FUNCTION_REGISTRAR_H_ #define THIRD_PARTY_CEL_CPP_EVAL_PUBLIC_EQUALITY_FUNCTION_REGISTRAR_H_ #include "absl/status/status.h" #include "eval/internal/cel_value_equal.h" #include "eval/public/cel_function_registry.h" #include "eval/public/cel_options.h" namespace google::api::expr::runtime { using cel::interop_internal::CelValueEqualImpl; absl::Status RegisterEqualityFunctions(CelFunctionRegistry* registry, const InterpreterOptions& options); } #endif #include "eval/public/equality_function_registrar.h" #include "absl/status/status.h" #include "eval/public/cel_function_registry.h" #include "eval/public/cel_options.h" #include "runtime/runtime_options.h" #include "runtime/standard/equality_functions.h" namespace google::api::expr::runtime { absl::Status RegisterEqualityFunctions(CelFunctionRegistry* registry, const InterpreterOptions& options) { cel::RuntimeOptions runtime_options = ConvertToRuntimeOptions(options); return cel::RegisterEqualityFunctions(registry->InternalGetRegistry(), runtime_options); } }
#include "eval/public/equality_function_registrar.h" #include <array> #include <cmath> #include <cstdint> #include <limits> #include <memory> #include <string> #include <tuple> #include <utility> #include <vector> #include "google/api/expr/v1alpha1/syntax.pb.h" #include "google/protobuf/any.pb.h" #include "google/rpc/context/attribute_context.pb.h" #include "google/protobuf/descriptor.pb.h" #include "google/protobuf/arena.h" #include "google/protobuf/descriptor.h" #include "google/protobuf/dynamic_message.h" #include "google/protobuf/message.h" #include "google/protobuf/text_format.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/time/time.h" #include "absl/types/span.h" #include "absl/types/variant.h" #include "eval/public/activation.h" #include "eval/public/cel_builtins.h" #include "eval/public/cel_expr_builder_factory.h" #include "eval/public/cel_expression.h" #include "eval/public/cel_function_registry.h" #include "eval/public/cel_options.h" #include "eval/public/cel_value.h" #include "eval/public/containers/container_backed_list_impl.h" #include "eval/public/containers/container_backed_map_impl.h" #include "eval/public/message_wrapper.h" #include "eval/public/structs/cel_proto_wrapper.h" #include "eval/public/structs/trivial_legacy_type_info.h" #include "eval/public/testing/matchers.h" #include "eval/testutil/test_message.pb.h" #include "internal/benchmark.h" #include "internal/status_macros.h" #include "internal/testing.h" #include "parser/parser.h" namespace google::api::expr::runtime { namespace { using ::google::api::expr::v1alpha1::ParsedExpr; using ::google::rpc::context::AttributeContext; using testing::_; using testing::Combine; using testing::HasSubstr; using testing::Optional; using testing::Values; using testing::ValuesIn; using cel::internal::StatusIs; MATCHER_P2(DefinesHomogenousOverload, name, argument_type, absl::StrCat(name, " for ", CelValue::TypeName(argument_type))) { const CelFunctionRegistry& registry = arg; return !registry .FindOverloads(name, false, {argument_type, argument_type}) .empty(); return false; } struct EqualityTestCase { enum class ErrorKind { kMissingOverload, kMissingIdentifier }; absl::string_view expr; absl::variant<bool, ErrorKind> result; CelValue lhs = CelValue::CreateNull(); CelValue rhs = CelValue::CreateNull(); }; bool IsNumeric(CelValue::Type type) { return type == CelValue::Type::kDouble || type == CelValue::Type::kInt64 || type == CelValue::Type::kUint64; } const CelList& CelListExample1() { static ContainerBackedListImpl* example = new ContainerBackedListImpl({CelValue::CreateInt64(1)}); return *example; } const CelList& CelListExample2() { static ContainerBackedListImpl* example = new ContainerBackedListImpl({CelValue::CreateInt64(2)}); return *example; } const CelMap& CelMapExample1() { static CelMap* example = []() { std::vector<std::pair<CelValue, CelValue>> values{ {CelValue::CreateInt64(1), CelValue::CreateInt64(2)}}; auto map = CreateContainerBackedMap(absl::MakeSpan(values)); return map->release(); }(); return *example; } const CelMap& CelMapExample2() { static CelMap* example = []() { std::vector<std::pair<CelValue, CelValue>> values{ {CelValue::CreateInt64(2), CelValue::CreateInt64(4)}}; auto map = CreateContainerBackedMap(absl::MakeSpan(values)); return map->release(); }(); return *example; } const std::vector<CelValue>& ValueExamples1() { static std::vector<CelValue>* examples = []() { google::protobuf::Arena arena; auto result = std::make_unique<std::vector<CelValue>>(); result->push_back(CelValue::CreateNull()); result->push_back(CelValue::CreateBool(false)); result->push_back(CelValue::CreateInt64(1)); result->push_back(CelValue::CreateUint64(1)); result->push_back(CelValue::CreateDouble(1.0)); result->push_back(CelValue::CreateStringView("string")); result->push_back(CelValue::CreateBytesView("bytes")); result->push_back(CelProtoWrapper::CreateMessage( std::make_unique<TestMessage>().release(), &arena)); result->push_back(CelValue::CreateDuration(absl::Seconds(1))); result->push_back(CelValue::CreateTimestamp(absl::FromUnixSeconds(1))); result->push_back(CelValue::CreateList(&CelListExample1())); result->push_back(CelValue::CreateMap(&CelMapExample1())); result->push_back(CelValue::CreateCelTypeView("type")); return result.release(); }(); return *examples; } const std::vector<CelValue>& ValueExamples2() { static std::vector<CelValue>* examples = []() { google::protobuf::Arena arena; auto result = std::make_unique<std::vector<CelValue>>(); auto message2 = std::make_unique<TestMessage>(); message2->set_int64_value(2); result->push_back(CelValue::CreateNull()); result->push_back(CelValue::CreateBool(true)); result->push_back(CelValue::CreateInt64(2)); result->push_back(CelValue::CreateUint64(2)); result->push_back(CelValue::CreateDouble(2.0)); result->push_back(CelValue::CreateStringView("string2")); result->push_back(CelValue::CreateBytesView("bytes2")); result->push_back( CelProtoWrapper::CreateMessage(message2.release(), &arena)); result->push_back(CelValue::CreateDuration(absl::Seconds(2))); result->push_back(CelValue::CreateTimestamp(absl::FromUnixSeconds(2))); result->push_back(CelValue::CreateList(&CelListExample2())); result->push_back(CelValue::CreateMap(&CelMapExample2())); result->push_back(CelValue::CreateCelTypeView("type2")); return result.release(); }(); return *examples; } class CelValueEqualImplTypesTest : public testing::TestWithParam<std::tuple<CelValue, CelValue, bool>> { public: CelValueEqualImplTypesTest() = default; const CelValue& lhs() { return std::get<0>(GetParam()); } const CelValue& rhs() { return std::get<1>(GetParam()); } bool should_be_equal() { return std::get<2>(GetParam()); } }; std::string CelValueEqualTestName( const testing::TestParamInfo<std::tuple<CelValue, CelValue, bool>>& test_case) { return absl::StrCat(CelValue::TypeName(std::get<0>(test_case.param).type()), CelValue::TypeName(std::get<1>(test_case.param).type()), (std::get<2>(test_case.param)) ? "Equal" : "Inequal"); } TEST_P(CelValueEqualImplTypesTest, Basic) { absl::optional<bool> result = CelValueEqualImpl(lhs(), rhs()); if (lhs().IsNull() || rhs().IsNull()) { if (lhs().IsNull() && rhs().IsNull()) { EXPECT_THAT(result, Optional(true)); } else { EXPECT_THAT(result, Optional(false)); } } else if (lhs().type() == rhs().type() || (IsNumeric(lhs().type()) && IsNumeric(rhs().type()))) { EXPECT_THAT(result, Optional(should_be_equal())); } else { EXPECT_THAT(result, Optional(false)); } } INSTANTIATE_TEST_SUITE_P(EqualityBetweenTypes, CelValueEqualImplTypesTest, Combine(ValuesIn(ValueExamples1()), ValuesIn(ValueExamples1()), Values(true)), &CelValueEqualTestName); INSTANTIATE_TEST_SUITE_P(InequalityBetweenTypes, CelValueEqualImplTypesTest, Combine(ValuesIn(ValueExamples1()), ValuesIn(ValueExamples2()), Values(false)), &CelValueEqualTestName); struct NumericInequalityTestCase { std::string name; CelValue a; CelValue b; }; const std::vector<NumericInequalityTestCase>& NumericValuesNotEqualExample() { static std::vector<NumericInequalityTestCase>* examples = []() { google::protobuf::Arena arena; auto result = std::make_unique<std::vector<NumericInequalityTestCase>>(); result->push_back({"NegativeIntAndUint", CelValue::CreateInt64(-1), CelValue::CreateUint64(2)}); result->push_back( {"IntAndLargeUint", CelValue::CreateInt64(1), CelValue::CreateUint64( static_cast<uint64_t>(std::numeric_limits<int64_t>::max()) + 1)}); result->push_back( {"IntAndLargeDouble", CelValue::CreateInt64(2), CelValue::CreateDouble( static_cast<double>(std::numeric_limits<int64_t>::max()) + 1025)}); result->push_back( {"IntAndSmallDouble", CelValue::CreateInt64(2), CelValue::CreateDouble( static_cast<double>(std::numeric_limits<int64_t>::lowest()) - 1025)}); result->push_back( {"UintAndLargeDouble", CelValue::CreateUint64(2), CelValue::CreateDouble( static_cast<double>(std::numeric_limits<uint64_t>::max()) + 2049)}); result->push_back({"NegativeDoubleAndUint", CelValue::CreateDouble(-2.0), CelValue::CreateUint64(123)}); result->push_back({"NanAndDouble", CelValue::CreateDouble(NAN), CelValue::CreateDouble(1.0)}); result->push_back({"NanAndNan", CelValue::CreateDouble(NAN), CelValue::CreateDouble(NAN)}); result->push_back({"DoubleAndNan", CelValue::CreateDouble(1.0), CelValue::CreateDouble(NAN)}); result->push_back( {"IntAndNan", CelValue::CreateInt64(1), CelValue::CreateDouble(NAN)}); result->push_back( {"NanAndInt", CelValue::CreateDouble(NAN), CelValue::CreateInt64(1)}); result->push_back( {"UintAndNan", CelValue::CreateUint64(1), CelValue::CreateDouble(NAN)}); result->push_back( {"NanAndUint", CelValue::CreateDouble(NAN), CelValue::CreateUint64(1)}); return result.release(); }(); return *examples; } using NumericInequalityTest = testing::TestWithParam<NumericInequalityTestCase>; TEST_P(NumericInequalityTest, NumericValues) { NumericInequalityTestCase test_case = GetParam(); absl::optional<bool> result = CelValueEqualImpl(test_case.a, test_case.b); EXPECT_TRUE(result.has_value()); EXPECT_EQ(*result, false); } INSTANTIATE_TEST_SUITE_P( InequalityBetweenNumericTypesTest, NumericInequalityTest, ValuesIn(NumericValuesNotEqualExample()), [](const testing::TestParamInfo<NumericInequalityTest::ParamType>& info) { return info.param.name; }); TEST(CelValueEqualImplTest, LossyNumericEquality) { absl::optional<bool> result = CelValueEqualImpl( CelValue::CreateDouble( static_cast<double>(std::numeric_limits<int64_t>::max()) - 1), CelValue::CreateInt64(std::numeric_limits<int64_t>::max())); EXPECT_TRUE(result.has_value()); EXPECT_TRUE(*result); } TEST(CelValueEqualImplTest, ListMixedTypesInequal) { ContainerBackedListImpl lhs({CelValue::CreateInt64(1)}); ContainerBackedListImpl rhs({CelValue::CreateStringView("abc")}); EXPECT_THAT( CelValueEqualImpl(CelValue::CreateList(&lhs), CelValue::CreateList(&rhs)), Optional(false)); } TEST(CelValueEqualImplTest, NestedList) { ContainerBackedListImpl inner_lhs({CelValue::CreateInt64(1)}); ContainerBackedListImpl lhs({CelValue::CreateList(&inner_lhs)}); ContainerBackedListImpl inner_rhs({CelValue::CreateNull()}); ContainerBackedListImpl rhs({CelValue::CreateList(&inner_rhs)}); EXPECT_THAT( CelValueEqualImpl(CelValue::CreateList(&lhs), CelValue::CreateList(&rhs)), Optional(false)); } TEST(CelValueEqualImplTest, MapMixedValueTypesInequal) { std::vector<std::pair<CelValue, CelValue>> lhs_data{ {CelValue::CreateInt64(1), CelValue::CreateStringView("abc")}}; std::vector<std::pair<CelValue, CelValue>> rhs_data{ {CelValue::CreateInt64(1), CelValue::CreateInt64(2)}}; ASSERT_OK_AND_ASSIGN(std::unique_ptr<CelMap> lhs, CreateContainerBackedMap(absl::MakeSpan(lhs_data))); ASSERT_OK_AND_ASSIGN(std::unique_ptr<CelMap> rhs, CreateContainerBackedMap(absl::MakeSpan(rhs_data))); EXPECT_THAT(CelValueEqualImpl(CelValue::CreateMap(lhs.get()), CelValue::CreateMap(rhs.get())), Optional(false)); } TEST(CelValueEqualImplTest, MapMixedKeyTypesEqual) { std::vector<std::pair<CelValue, CelValue>> lhs_data{ {CelValue::CreateUint64(1), CelValue::CreateStringView("abc")}}; std::vector<std::pair<CelValue, CelValue>> rhs_data{ {CelValue::CreateInt64(1), CelValue::CreateStringView("abc")}}; ASSERT_OK_AND_ASSIGN(std::unique_ptr<CelMap> lhs, CreateContainerBackedMap(absl::MakeSpan(lhs_data))); ASSERT_OK_AND_ASSIGN(std::unique_ptr<CelMap> rhs, CreateContainerBackedMap(absl::MakeSpan(rhs_data))); EXPECT_THAT(CelValueEqualImpl(CelValue::CreateMap(lhs.get()), CelValue::CreateMap(rhs.get())), Optional(true)); } TEST(CelValueEqualImplTest, MapMixedKeyTypesInequal) { std::vector<std::pair<CelValue, CelValue>> lhs_data{ {CelValue::CreateInt64(1), CelValue::CreateStringView("abc")}}; std::vector<std::pair<CelValue, CelValue>> rhs_data{ {CelValue::CreateInt64(2), CelValue::CreateInt64(2)}}; ASSERT_OK_AND_ASSIGN(std::unique_ptr<CelMap> lhs, CreateContainerBackedMap(absl::MakeSpan(lhs_data))); ASSERT_OK_AND_ASSIGN(std::unique_ptr<CelMap> rhs, CreateContainerBackedMap(absl::MakeSpan(rhs_data))); EXPECT_THAT(CelValueEqualImpl(CelValue::CreateMap(lhs.get()), CelValue::CreateMap(rhs.get())), Optional(false)); } TEST(CelValueEqualImplTest, NestedMaps) { std::vector<std::pair<CelValue, CelValue>> inner_lhs_data{ {CelValue::CreateInt64(2), CelValue::CreateStringView("abc")}}; ASSERT_OK_AND_ASSIGN( std::unique_ptr<CelMap> inner_lhs, CreateContainerBackedMap(absl::MakeSpan(inner_lhs_data))); std::vector<std::pair<CelValue, CelValue>> lhs_data{ {CelValue::CreateInt64(1), CelValue::CreateMap(inner_lhs.get())}}; std::vector<std::pair<CelValue, CelValue>> inner_rhs_data{ {CelValue::CreateInt64(2), CelValue::CreateNull()}}; ASSERT_OK_AND_ASSIGN( std::unique_ptr<CelMap> inner_rhs, CreateContainerBackedMap(absl::MakeSpan(inner_rhs_data))); std::vector<std::pair<CelValue, CelValue>> rhs_data{ {CelValue::CreateInt64(1), CelValue::CreateMap(inner_rhs.get())}}; ASSERT_OK_AND_ASSIGN(std::unique_ptr<CelMap> lhs, CreateContainerBackedMap(absl::MakeSpan(lhs_data))); ASSERT_OK_AND_ASSIGN(std::unique_ptr<CelMap> rhs, CreateContainerBackedMap(absl::MakeSpan(rhs_data))); EXPECT_THAT(CelValueEqualImpl(CelValue::CreateMap(lhs.get()), CelValue::CreateMap(rhs.get())), Optional(false)); } TEST(CelValueEqualImplTest, ProtoEqualityDifferingTypenameInequal) { google::protobuf::Arena arena; TestMessage example; ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(R"( int32_value: 1 uint32_value: 2 string_value: "test" )", &example)); CelValue lhs = CelProtoWrapper::CreateMessage(&example, &arena); CelValue rhs = CelValue::CreateMessageWrapper( MessageWrapper(&example, TrivialTypeInfo::GetInstance())); EXPECT_THAT(CelValueEqualImpl(lhs, rhs), Optional(false)); } TEST(CelValueEqualImplTest, ProtoEqualityNoAccessorInequal) { google::protobuf::Arena arena; TestMessage example; ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(R"( int32_value: 1 uint32_value: 2 string_value: "test" )", &example)); CelValue lhs = CelValue::CreateMessageWrapper( MessageWrapper(&example, TrivialTypeInfo::GetInstance())); CelValue rhs = CelValue::CreateMessageWrapper( MessageWrapper(&example, TrivialTypeInfo::GetInstance())); EXPECT_THAT(CelValueEqualImpl(lhs, rhs), Optional(false)); } TEST(CelValueEqualImplTest, ProtoEqualityAny) { google::protobuf::Arena arena; TestMessage packed_value; ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(R"( int32_value: 1 uint32_value: 2 string_value: "test" )", &packed_value)); TestMessage lhs; lhs.mutable_any_value()->PackFrom(packed_value); TestMessage rhs; rhs.mutable_any_value()->PackFrom(packed_value); EXPECT_THAT(CelValueEqualImpl(CelProtoWrapper::CreateMessage(&lhs, &arena), CelProtoWrapper::CreateMessage(&rhs, &arena)), Optional(true)); lhs.mutable_any_value()->clear_type_url(); rhs.mutable_any_value()->clear_type_url(); EXPECT_THAT(CelValueEqualImpl(CelProtoWrapper::CreateMessage(&lhs, &arena), CelProtoWrapper::CreateMessage(&rhs, &arena)), Optional(true)); } bool AddDepsToPool(const google::protobuf::FileDescriptor* descriptor, google::protobuf::DescriptorPool& pool) { for (int i = 0; i < descriptor->dependency_count(); i++) { if (!AddDepsToPool(descriptor->dependency(i), pool)) { return false; } } google::protobuf::FileDescriptorProto descriptor_proto; descriptor->CopyTo(&descriptor_proto); return pool.BuildFile(descriptor_proto) != nullptr; } TEST(CelValueEqualImplTest, DynamicDescriptorAndGeneratedInequal) { google::protobuf::DescriptorPool pool; google::protobuf::DynamicMessageFactory factory; google::protobuf::Arena arena; factory.SetDelegateToGeneratedFactory(false); ASSERT_TRUE(AddDepsToPool(TestMessage::descriptor()->file(), pool)); TestMessage example_message; ASSERT_TRUE( google::protobuf::TextFormat::ParseFromString(R"pb( int64_value: 12345 bool_list: false bool_list: true message_value { float_value: 1.0 } )pb", &example_message)); std::unique_ptr<google::protobuf::Message> example_dynamic_message( factory .GetPrototype(pool.FindMessageTypeByName( TestMessage::descriptor()->full_name())) ->New()); ASSERT_TRUE(example_dynamic_message->ParseFromString( example_message.SerializeAsString())); EXPECT_THAT(CelValueEqualImpl( CelProtoWrapper::CreateMessage(&example_message, &arena), CelProtoWrapper::CreateMessage(example_dynamic_message.get(), &arena)), Optional(false)); } TEST(CelValueEqualImplTest, DynamicMessageAndMessageEqual) { google::protobuf::DynamicMessageFactory factory; google::protobuf::Arena arena; factory.SetDelegateToGeneratedFactory(false); TestMessage example_message; ASSERT_TRUE( google::protobuf::TextFormat::ParseFromString(R"pb( int64_value: 12345 bool_list: false bool_list: true message_value { float_value: 1.0 } )pb", &example_message)); std::unique_ptr<google::protobuf::Message> example_dynamic_message( factory.GetPrototype(TestMessage::descriptor())->New()); ASSERT_TRUE(example_dynamic_message->ParseFromString( example_message.SerializeAsString())); EXPECT_THAT(CelValueEqualImpl( CelProtoWrapper::CreateMessage(&example_message, &arena), CelProtoWrapper::CreateMessage(example_dynamic_message.get(), &arena)), Optional(true)); } class EqualityFunctionTest : public testing::TestWithParam<std::tuple<EqualityTestCase, bool>> { public: EqualityFunctionTest() { options_.enable_heterogeneous_equality = std::get<1>(GetParam()); options_.enable_empty_wrapper_null_unboxing = true; builder_ = CreateCelExpressionBuilder(options_); } CelFunctionRegistry& registry() { return *builder_->GetRegistry(); } absl::StatusOr<CelValue> Evaluate(absl::string_view expr, const CelValue& lhs, const CelValue& rhs) { CEL_ASSIGN_OR_RETURN(ParsedExpr parsed_expr, parser::Parse(expr)); Activation activation; activation.InsertValue("lhs", lhs); activation.InsertValue("rhs", rhs); CEL_ASSIGN_OR_RETURN(auto expression, builder_->CreateExpression( &parsed_expr.expr(), &parsed_expr.source_info())); return expression->Evaluate(activation, &arena_); } protected: std::unique_ptr<CelExpressionBuilder> builder_; InterpreterOptions options_; google::protobuf::Arena arena_; }; constexpr std::array<CelValue::Type, 11> kEqualableTypes = { CelValue::Type::kInt64, CelValue::Type::kUint64, CelValue::Type::kString, CelValue::Type::kDouble, CelValue::Type::kBytes, CelValue::Type::kDuration, CelValue::Type::kMap, CelValue::Type::kList, CelValue::Type::kBool, CelValue::Type::kTimestamp}; TEST(RegisterEqualityFunctionsTest, EqualDefined) { InterpreterOptions default_options; CelFunctionRegistry registry; ASSERT_OK(RegisterEqualityFunctions(&registry, default_options)); for (CelValue::Type type : kEqualableTypes) { EXPECT_THAT(registry, DefinesHomogenousOverload(builtin::kEqual, type)); } } TEST(RegisterEqualityFunctionsTest, InequalDefined) { InterpreterOptions default_options; CelFunctionRegistry registry; ASSERT_OK(RegisterEqualityFunctions(&registry, default_options)); for (CelValue::Type type : kEqualableTypes) { EXPECT_THAT(registry, DefinesHomogenousOverload(builtin::kInequal, type)); } } TEST_P(EqualityFunctionTest, SmokeTest) { EqualityTestCase test_case = std::get<0>(GetParam()); google::protobuf::LinkMessageReflection<AttributeContext>(); ASSERT_OK(RegisterEqualityFunctions(&registry(), options_)); ASSERT_OK_AND_ASSIGN(auto result, Evaluate(test_case.expr, test_case.lhs, test_case.rhs)); if (absl::holds_alternative<bool>(test_case.result)) { EXPECT_THAT(result, test::IsCelBool(absl::get<bool>(test_case.result))); } else { switch (absl::get<EqualityTestCase::ErrorKind>(test_case.result)) { case EqualityTestCase::ErrorKind::kMissingOverload: EXPECT_THAT(result, test::IsCelError( StatusIs(absl::StatusCode::kUnknown, HasSubstr("No matching overloads")))) << test_case.expr; break; case EqualityTestCase::ErrorKind::kMissingIdentifier: EXPECT_THAT(result, test::IsCelError( StatusIs(absl::StatusCode::kUnknown, HasSubstr("found in Activation")))); break; default: EXPECT_THAT(result, test::IsCelError(_)); break; } } } INSTANTIATE_TEST_SUITE_P( Equality, EqualityFunctionTest, Combine(testing::ValuesIn<EqualityTestCase>( {{"null == null", true}, {"true == false", false}, {"1 == 1", true}, {"-2 == -1", false}, {"1.1 == 1.2", false}, {"'a' == 'a'", true}, {"lhs == rhs", false, CelValue::CreateBytesView("a"), CelValue::CreateBytesView("b")}, {"lhs == rhs", false, CelValue::CreateDuration(absl::Seconds(1)), CelValue::CreateDuration(absl::Seconds(2))}, {"lhs == rhs", true, CelValue::CreateTimestamp(absl::FromUnixSeconds(20)), CelValue::CreateTimestamp(absl::FromUnixSeconds(20))}, {"no_such_identifier == 1", EqualityTestCase::ErrorKind::kMissingIdentifier}, {"{1: no_such_identifier} == {1: 1}", EqualityTestCase::ErrorKind::kMissingIdentifier}}), testing::Bool())); INSTANTIATE_TEST_SUITE_P( Inequality, EqualityFunctionTest, Combine(testing::ValuesIn<EqualityTestCase>( {{"null != null", false}, {"true != false", true}, {"1 != 1", false}, {"-2 != -1", true}, {"1.1 != 1.2", true}, {"'a' != 'a'", false}, {"lhs != rhs", true, CelValue::CreateBytesView("a"), CelValue::CreateBytesView("b")}, {"lhs != rhs", true, CelValue::CreateDuration(absl::Seconds(1)), CelValue::CreateDuration(absl::Seconds(2))}, {"lhs != rhs", true, CelValue::CreateTimestamp(absl::FromUnixSeconds(20)), CelValue::CreateTimestamp(absl::FromUnixSeconds(30))}, {"no_such_identifier != 1", EqualityTestCase::ErrorKind::kMissingIdentifier}, {"{1: no_such_identifier} != {1: 1}", EqualityTestCase::ErrorKind::kMissingIdentifier}}), testing::Bool())); INSTANTIATE_TEST_SUITE_P(HeterogeneousNumericContainers, EqualityFunctionTest, Combine(testing::ValuesIn<EqualityTestCase>({ {"{1: 2} == {1u: 2}", true}, {"{1: 2} == {2u: 2}", false}, {"{1: 2} == {true: 2}", false}, {"{1: 2} != {1u: 2}", false}, {"{1: 2} != {2u: 2}", true}, {"{1: 2} != {true: 2}", true}, {"[1u, 2u, 3.0] != [1, 2.0, 3]", false}, {"[1u, 2u, 3.0] == [1, 2.0, 3]", true}, {"[1u, 2u, 3.0] != [1, 2.1, 3]", true}, {"[1u, 2u, 3.0] == [1, 2.1, 3]", false}, }), testing::Values(true))); INSTANTIATE_TEST_SUITE_P( HomogenousNumericContainers, EqualityFunctionTest, Combine(testing::ValuesIn<EqualityTestCase>({ {"{1: 2} == {1u: 2}", false}, {"{1: 2} == {2u: 2}", false}, {"{1: 2} == {true: 2}", false}, {"{1: 2} != {1u: 2}", true}, {"{1: 2} != {2u: 2}", true}, {"{1: 2} != {true: 2}", true}, {"[1u, 2u, 3.0] != [1, 2.0, 3]", EqualityTestCase::ErrorKind::kMissingOverload}, {"[1u, 2u, 3.0] == [1, 2.0, 3]", EqualityTestCase::ErrorKind::kMissingOverload}, {"[1u, 2u, 3.0] != [1, 2.1, 3]", EqualityTestCase::ErrorKind::kMissingOverload}, {"[1u, 2u, 3.0] == [1, 2.1, 3]", EqualityTestCase::ErrorKind::kMissingOverload}, }), testing::Values(false))); INSTANTIATE_TEST_SUITE_P( NullInequalityLegacy, EqualityFunctionTest, Combine(testing::ValuesIn<EqualityTestCase>( {{"null != null", false}, {"true != null", EqualityTestCase::ErrorKind::kMissingOverload}, {"1 != null", EqualityTestCase::ErrorKind::kMissingOverload}, {"-2 != null", EqualityTestCase::ErrorKind::kMissingOverload}, {"1.1 != null", EqualityTestCase::ErrorKind::kMissingOverload}, {"'a' != null", EqualityTestCase::ErrorKind::kMissingOverload}, {"lhs != null", EqualityTestCase::ErrorKind::kMissingOverload, CelValue::CreateBytesView("a")}, {"lhs != null", EqualityTestCase::ErrorKind::kMissingOverload, CelValue::CreateDuration(absl::Seconds(1))}, {"lhs != null", EqualityTestCase::ErrorKind::kMissingOverload, CelValue::CreateTimestamp(absl::FromUnixSeconds(20))}}), testing::Values<bool>(false))); INSTANTIATE_TEST_SUITE_P( NullEqualityLegacy, EqualityFunctionTest, Combine(testing::ValuesIn<EqualityTestCase>( {{"null == null", true}, {"true == null", EqualityTestCase::ErrorKind::kMissingOverload}, {"1 == null", EqualityTestCase::ErrorKind::kMissingOverload}, {"-2 == null", EqualityTestCase::ErrorKind::kMissingOverload}, {"1.1 == null", EqualityTestCase::ErrorKind::kMissingOverload}, {"'a' == null", EqualityTestCase::ErrorKind::kMissingOverload}, {"lhs == null", EqualityTestCase::ErrorKind::kMissingOverload, CelValue::CreateBytesView("a")}, {"lhs == null", EqualityTestCase::ErrorKind::kMissingOverload, CelValue::CreateDuration(absl::Seconds(1))}, {"lhs == null", EqualityTestCase::ErrorKind::kMissingOverload, CelValue::CreateTimestamp(absl::FromUnixSeconds(20))}}), testing::Values<bool>(false))); INSTANTIATE_TEST_SUITE_P( NullInequality, EqualityFunctionTest, Combine(testing::ValuesIn<EqualityTestCase>( {{"null != null", false}, {"true != null", true}, {"null != false", true}, {"1 != null", true}, {"null != 1", true}, {"-2 != null", true}, {"null != -2", true}, {"1.1 != null", true}, {"null != 1.1", true}, {"'a' != null", true}, {"lhs != null", true, CelValue::CreateBytesView("a")}, {"lhs != null", true, CelValue::CreateDuration(absl::Seconds(1))}, {"google.api.expr.runtime.TestMessage{} != null", true}, {"google.api.expr.runtime.TestMessage{}.string_wrapper_value" " != null", false}, {"google.api.expr.runtime.TestMessage{string_wrapper_value: " "google.protobuf.StringValue{}}.string_wrapper_value != null", true}, {"{} != null", true}, {"[] != null", true}}),
404
#ifndef TENSORFLOW_CORE_COMMON_RUNTIME_DEVICE_RESOLVER_LOCAL_H_ #define TENSORFLOW_CORE_COMMON_RUNTIME_DEVICE_RESOLVER_LOCAL_H_ #include <string> #include <vector> #include "tensorflow/core/framework/collective.h" #include "tensorflow/core/framework/device_attributes.pb.h" #include "tensorflow/core/platform/status.h" namespace tensorflow { class DeviceMgr; class DeviceResolverLocal : public DeviceResolverInterface { public: explicit DeviceResolverLocal(const DeviceMgr* dev_mgr) : dev_mgr_(dev_mgr) {} Status GetDeviceAttributes(const string& device, DeviceAttributes* attributes) override; Status GetAllDeviceAttributes( const string& task, std::vector<DeviceAttributes>* attributes) override; Status UpdateDeviceAttributes( const std::vector<DeviceAttributes>& attributes) override; protected: const DeviceMgr* dev_mgr_; }; } #endif #include "tensorflow/core/common_runtime/device_resolver_local.h" #include "absl/status/status.h" #include "tensorflow/core/common_runtime/device_mgr.h" #include "tensorflow/core/platform/errors.h" namespace tensorflow { Status DeviceResolverLocal::GetDeviceAttributes(const string& device, DeviceAttributes* attributes) { Device* dev; Status s = dev_mgr_->LookupDevice(device, &dev); if (absl::IsInvalidArgument(s)) { return errors::NotFound(device, " not found"); } else if (!s.ok()) { return s; } *attributes = dev->attributes(); return absl::OkStatus(); } Status DeviceResolverLocal::GetAllDeviceAttributes( const string& task, std::vector<DeviceAttributes>* attributes) { return errors::Internal( "GetTaskCached is not supposed to be called in local collectives"); } Status DeviceResolverLocal::UpdateDeviceAttributes( const std::vector<DeviceAttributes>& attributes) { return errors::Internal( "UpdateDeviceAttributes shouldn't be called with local collectives"); } }
#include "tensorflow/core/common_runtime/device_resolver_local.h" #include "tensorflow/core/common_runtime/device.h" #include "tensorflow/core/common_runtime/device_factory.h" #include "tensorflow/core/common_runtime/device_mgr.h" #include "tensorflow/core/lib/core/status.h" #include "tensorflow/core/lib/core/status_test_util.h" #include "tensorflow/core/platform/test.h" #include "tensorflow/core/public/session_options.h" namespace tensorflow { namespace { #define NUM_DEVS 3 class DeviceResolverLocalTest : public ::testing::Test { protected: DeviceResolverLocalTest() { SessionOptions options; string task_name = "/job:localhost/replica:0/task:0"; auto* device_count = options.config.mutable_device_count(); device_count->insert({"CPU", NUM_DEVS}); std::vector<std::unique_ptr<Device>> devices; TF_CHECK_OK(DeviceFactory::AddDevices(options, task_name, &devices)); device_mgr_ = std::make_unique<StaticDeviceMgr>(std::move(devices)); drl_.reset(new DeviceResolverLocal(device_mgr_.get())); } std::unique_ptr<DeviceMgr> device_mgr_; std::unique_ptr<DeviceResolverLocal> drl_; }; TEST_F(DeviceResolverLocalTest, GetDeviceAttributesKnown) { DeviceAttributes attributes; TF_EXPECT_OK(drl_->GetDeviceAttributes( "/job:localhost/replica:0/task:0/device:CPU:1", &attributes)); EXPECT_EQ(attributes.name(), "/job:localhost/replica:0/task:0/device:CPU:1"); } TEST_F(DeviceResolverLocalTest, GetDeviceAttributesUnknown) { DeviceAttributes attributes; EXPECT_TRUE(errors::IsNotFound(drl_->GetDeviceAttributes( "/job:localhost/replica:0/task:0/device:CPU:9", &attributes))); } TEST_F(DeviceResolverLocalTest, GetAllDeviceAttributes) { std::vector<DeviceAttributes> attributes; EXPECT_TRUE(errors::IsInternal( drl_->GetAllDeviceAttributes( "", &attributes))); } TEST_F(DeviceResolverLocalTest, UpdateDeviceAttributes) { std::vector<DeviceAttributes> attributes; EXPECT_TRUE(errors::IsInternal(drl_->UpdateDeviceAttributes(attributes))); } } }
405
#ifndef TENSORFLOW_LITE_EXPERIMENTAL_ACCELERATION_MINI_BENCHMARK_VALIDATOR_RUNNER_H_ #define TENSORFLOW_LITE_EXPERIMENTAL_ACCELERATION_MINI_BENCHMARK_VALIDATOR_RUNNER_H_ #include <memory> #include <string> #include <vector> #include "tensorflow/lite/acceleration/configuration/configuration_generated.h" #include "tensorflow/lite/core/api/error_reporter.h" #include "tensorflow/lite/experimental/acceleration/mini_benchmark/fb_storage.h" #include "tensorflow/lite/experimental/acceleration/mini_benchmark/status_codes.h" #include "tensorflow/lite/experimental/acceleration/mini_benchmark/validator_runner_impl.h" #include "tensorflow/lite/experimental/acceleration/mini_benchmark/validator_runner_options.h" namespace tflite { namespace acceleration { class ValidatorRunner { public: static constexpr int64_t kDefaultEventTimeoutUs = 30 * 1000 * 1000; explicit ValidatorRunner(const ValidatorRunnerOptions& options); MinibenchmarkStatus Init(); int TriggerMissingValidation( const std::vector<const TFLiteSettings*>& for_settings); std::vector<const BenchmarkEvent*> GetSuccessfulResults() { return validator_runner_impl_->GetSuccessfulResultsFromStorage(); } int GetNumCompletedResults() { return validator_runner_impl_->GetNumCompletedResults(); } std::vector<const BenchmarkEvent*> GetAndFlushEventsToLog( int64_t timeout_us = kDefaultEventTimeoutUs); private: const std::string storage_path_; FlatbufferStorage<BenchmarkEvent> storage_; ErrorReporter* error_reporter_; bool triggered_ = false; std::unique_ptr<ValidatorRunnerImpl> validator_runner_impl_; }; } } #endif #include "tensorflow/lite/experimental/acceleration/mini_benchmark/validator_runner.h" #include <cstdlib> #include <memory> #include <string> #include <utility> #include <vector> #include "tensorflow/lite/acceleration/configuration/configuration_generated.h" #include "tensorflow/lite/experimental/acceleration/mini_benchmark/fb_storage.h" #include "tensorflow/lite/experimental/acceleration/mini_benchmark/status_codes.h" #include "tensorflow/lite/experimental/acceleration/mini_benchmark/validator.h" #include "tensorflow/lite/experimental/acceleration/mini_benchmark/validator_runner_options.h" #include "tensorflow/lite/minimal_logging.h" namespace tflite { namespace acceleration { constexpr int kMaxAttempts = 2; ValidatorRunner::ValidatorRunner(const ValidatorRunnerOptions& options) : storage_path_(options.storage_path), storage_(options.storage_path, options.error_reporter), error_reporter_(options.error_reporter) { validator_runner_impl_ = std::make_unique<ValidatorRunnerImpl>( CreateModelLoaderPath(options), options.storage_path, options.data_directory_path, options.per_test_timeout_ms, options.custom_input_data.empty() ? nullptr : std::make_unique<CustomValidationEmbedder>( options.custom_input_batch_size, options.custom_input_data, options.error_reporter), error_reporter_, options.nnapi_sl, options.gpu_plugin_handle, options.validation_entrypoint_name, options.benchmark_result_evaluator); } MinibenchmarkStatus ValidatorRunner::Init() { MinibenchmarkStatus status = storage_.Read(); if (status != kMinibenchmarkSuccess) { TF_LITE_REPORT_ERROR(error_reporter_, "Storage::Read failed"); return status; } return validator_runner_impl_->Init(); } int ValidatorRunner::TriggerMissingValidation( const std::vector<const TFLiteSettings*>& for_settings) { if (triggered_) { return 0; } triggered_ = true; storage_.Read(); std::vector<flatbuffers::FlatBufferBuilder> to_be_run; for (auto settings : for_settings) { TFLiteSettingsT tflite_settings; settings->UnPackTo(&tflite_settings); int started_count = 0; int results_count = 0; for (int i = 0; i < storage_.Count(); i++) { const BenchmarkEvent* event = storage_.Get(i); if (event->event_type() == BenchmarkEventType_LOGGED) { continue; } if (!event->tflite_settings()) { TFLITE_LOG_PROD(TFLITE_LOG_WARNING, "Got previous event %d type %d with no tflite settings", i, static_cast<int>(event->event_type())); continue; } TFLiteSettingsT event_settings; event->tflite_settings()->UnPackTo(&event_settings); if (event_settings != tflite_settings) { continue; } if (event->event_type() == BenchmarkEventType_START) { started_count++; } else if (event->event_type() == BenchmarkEventType_END) { results_count++; } } if (results_count > 0 || started_count >= kMaxAttempts) { continue; } flatbuffers::FlatBufferBuilder copy; copy.Finish(CreateTFLiteSettings(copy, &tflite_settings)); to_be_run.emplace_back(std::move(copy)); } int to_be_run_count = to_be_run.size(); validator_runner_impl_->TriggerValidationAsync(std::move(to_be_run), storage_path_); return to_be_run_count; } std::vector<const BenchmarkEvent*> ValidatorRunner::GetAndFlushEventsToLog( int64_t timeout_us) { std::vector<const BenchmarkEvent*> events; storage_.Read(); if (storage_.Count() == 0) { return events; } const BenchmarkEvent* last = storage_.Get(storage_.Count() - 1); if (!last || last->event_type() == BenchmarkEventType_LOGGED) { return events; } bool has_pending_event = false; for (int i = storage_.Count() - 1; i >= 0; i--) { const BenchmarkEvent* event = storage_.Get(i); if (!event || event->event_type() == BenchmarkEventType_LOGGED) { break; } else if (event->event_type() == BenchmarkEventType_END || event->event_type() == BenchmarkEventType_ERROR) { break; } else if (event->event_type() == BenchmarkEventType_START && std::abs(event->boottime_us() - Validator::BootTimeMicros()) < timeout_us) { has_pending_event = true; } } if (has_pending_event) { return events; } flatbuffers::FlatBufferBuilder fbb; int64_t boottime_us = Validator::BootTimeMicros(); storage_.Append( &fbb, CreateBenchmarkEvent(fbb, 0, BenchmarkEventType_LOGGED, 0, 0, boottime_us, Validator::WallTimeMicros())); storage_.Read(); bool seen_end = false; for (int i = storage_.Count() - 1; i >= 0; i--) { const BenchmarkEvent* event = storage_.Get(i); if (!event || (event->event_type() == BenchmarkEventType_LOGGED && event->boottime_us() != boottime_us)) { break; } if (event->event_type() == BenchmarkEventType_END || event->event_type() == BenchmarkEventType_ERROR || event->event_type() == BenchmarkEventType_RECOVERED_ERROR) { events.push_back(event); seen_end = true; } else if (event->event_type() == BenchmarkEventType_START) { if (!seen_end) { events.push_back(event); } else { seen_end = false; } } } return events; } } }
#include "tensorflow/lite/experimental/acceleration/mini_benchmark/validator_runner.h" #include <fcntl.h> #include <fstream> #include <iostream> #include <memory> #include <ostream> #include <string> #include <vector> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "tensorflow/lite/acceleration/configuration/configuration_generated.h" #include "tensorflow/lite/experimental/acceleration/compatibility/android_info.h" #include "tensorflow/lite/experimental/acceleration/mini_benchmark/embedded_mobilenet_validation_model.h" #include "tensorflow/lite/experimental/acceleration/mini_benchmark/embedded_nnapi_sl_fake_impl.h" #include "tensorflow/lite/experimental/acceleration/mini_benchmark/mini_benchmark_test_helper.h" #include "tensorflow/lite/experimental/acceleration/mini_benchmark/nnapi_sl_fake_impl.h" #include "tensorflow/lite/experimental/acceleration/mini_benchmark/status_codes.h" #include "tensorflow/lite/nnapi/sl/include/SupportLibrary.h" #ifdef __ANDROID__ #include <dlfcn.h> #include "tensorflow/lite/experimental/acceleration/mini_benchmark/embedded_validator_runner_entrypoint.h" #endif namespace tflite { namespace acceleration { namespace { std::vector<const TFLiteSettings*> BuildBenchmarkSettings( const AndroidInfo& android_info, flatbuffers::FlatBufferBuilder& fbb_cpu, flatbuffers::FlatBufferBuilder& fbb_nnapi, flatbuffers::FlatBufferBuilder& fbb_gpu, bool ignore_android_version = false) { std::vector<const TFLiteSettings*> settings; fbb_cpu.Finish(CreateTFLiteSettings(fbb_cpu, Delegate_NONE, CreateNNAPISettings(fbb_cpu))); settings.push_back( flatbuffers::GetRoot<TFLiteSettings>(fbb_cpu.GetBufferPointer())); if (ignore_android_version || android_info.android_sdk_version >= "28") { fbb_nnapi.Finish(CreateTFLiteSettings(fbb_nnapi, Delegate_NNAPI, CreateNNAPISettings(fbb_nnapi))); settings.push_back( flatbuffers::GetRoot<TFLiteSettings>(fbb_nnapi.GetBufferPointer())); } #ifdef __ANDROID__ fbb_gpu.Finish(CreateTFLiteSettings(fbb_gpu, Delegate_GPU)); settings.push_back( flatbuffers::GetRoot<TFLiteSettings>(fbb_gpu.GetBufferPointer())); #endif return settings; } std::string GetTargetDeviceName(const BenchmarkEvent* event) { if (event->tflite_settings()->delegate() == Delegate_GPU) { return "GPU"; } else if (event->tflite_settings()->delegate() == Delegate_NNAPI) { return "NNAPI"; } return "CPU"; } class ValidatorRunnerTest : public ::testing::Test { protected: void SetUp() override { MiniBenchmarkTestHelper helper; should_perform_test_ = helper.should_perform_test(); if (!should_perform_test_) { return; } model_path_ = helper.DumpToTempFile( "mobilenet_quant_with_validation.tflite", g_tflite_acceleration_embedded_mobilenet_validation_model, g_tflite_acceleration_embedded_mobilenet_validation_model_len); ASSERT_TRUE(!model_path_.empty()); } void CheckConfigurations(bool use_path = true) { if (!should_perform_test_) { std::cerr << "Skipping test"; return; } AndroidInfo android_info; auto status = RequestAndroidInfo(&android_info); ASSERT_TRUE(status.ok()); ValidatorRunnerOptions options; options.data_directory_path = ::testing::TempDir(); options.storage_path = ::testing::TempDir() + "/storage_path.fb"; (void)unlink(options.storage_path.c_str()); if (use_path) { options.model_path = model_path_; } else { options.model_fd = open(model_path_.c_str(), O_RDONLY); ASSERT_GE(options.model_fd, 0); struct stat stat_buf = {0}; ASSERT_EQ(fstat(options.model_fd, &stat_buf), 0); options.model_size = stat_buf.st_size; options.model_offset = 0; } auto validator1 = std::make_unique<ValidatorRunner>(options); auto validator2 = std::make_unique<ValidatorRunner>(options); ASSERT_EQ(validator1->Init(), kMinibenchmarkSuccess); ASSERT_EQ(validator2->Init(), kMinibenchmarkSuccess); std::vector<const BenchmarkEvent*> events = validator1->GetAndFlushEventsToLog(); ASSERT_TRUE(events.empty()); flatbuffers::FlatBufferBuilder fbb_cpu, fbb_nnapi, fbb_gpu; std::vector<const TFLiteSettings*> settings = BuildBenchmarkSettings(android_info, fbb_cpu, fbb_nnapi, fbb_gpu); ASSERT_EQ(validator1->TriggerMissingValidation(settings), settings.size()); int event_count = 0; while (event_count < settings.size()) { events = validator1->GetAndFlushEventsToLog(); event_count += events.size(); for (const BenchmarkEvent* event : events) { std::string delegate_name = GetTargetDeviceName(event); if (event->event_type() == BenchmarkEventType_END) { if (event->result()->ok()) { std::cout << "Validation passed on " << delegate_name << std::endl; } else { std::cout << "Validation did not pass on " << delegate_name << std::endl; } } else if (event->event_type() == BenchmarkEventType_ERROR) { std::cout << "Failed to run validation on " << delegate_name << std::endl; } } #ifndef _WIN32 sleep(1); #endif } EXPECT_EQ(validator2->TriggerMissingValidation(settings), 0); } bool should_perform_test_ = true; std::string model_path_; }; TEST_F(ValidatorRunnerTest, AllConfigurationsWithFilePath) { CheckConfigurations(true); } TEST_F(ValidatorRunnerTest, AllConfigurationsWithFd) { CheckConfigurations(false); } using ::tflite::nnapi::NnApiSupportLibrary; std::unique_ptr<const NnApiSupportLibrary> LoadNnApiSupportLibrary() { MiniBenchmarkTestHelper helper; std::string nnapi_sl_path = helper.DumpToTempFile( "libnnapi_fake.so", g_nnapi_sl_fake_impl, g_nnapi_sl_fake_impl_len); std::unique_ptr<const NnApiSupportLibrary> nnapi_sl = ::tflite::nnapi::loadNnApiSupportLibrary(nnapi_sl_path); return nnapi_sl; } TEST_F(ValidatorRunnerTest, ShouldUseNnApiSl) { if (!should_perform_test_) { std::cerr << "Skipping test"; return; } AndroidInfo android_info; auto status = RequestAndroidInfo(&android_info); ASSERT_TRUE(status.ok()); InitNnApiSlInvocationStatus(); std::unique_ptr<const NnApiSupportLibrary> nnapi_sl = LoadNnApiSupportLibrary(); ASSERT_THAT(nnapi_sl.get(), ::testing::NotNull()); ValidatorRunnerOptions options; options.model_path = model_path_; options.storage_path = ::testing::TempDir() + "/storage_path.fb"; (void)unlink(options.storage_path.c_str()); options.data_directory_path = ::testing::TempDir(); options.nnapi_sl = nnapi_sl->getFL5(); ValidatorRunner validator(options); ASSERT_EQ(validator.Init(), kMinibenchmarkSuccess); std::vector<const BenchmarkEvent*> events = validator.GetAndFlushEventsToLog(); ASSERT_TRUE(events.empty()); flatbuffers::FlatBufferBuilder fbb_cpu, fbb_nnapi, fbb_gpu; std::vector<const TFLiteSettings*> settings = BuildBenchmarkSettings(android_info, fbb_cpu, fbb_nnapi, fbb_gpu, true); ASSERT_EQ(validator.TriggerMissingValidation(settings), settings.size()); int event_count = 0; while (event_count < settings.size()) { events = validator.GetAndFlushEventsToLog(); event_count += events.size(); #ifndef _WIN32 sleep(1); #endif } ASSERT_EQ(validator.TriggerMissingValidation(settings), 0); EXPECT_TRUE(WasNnApiSlInvoked()); } TEST_F(ValidatorRunnerTest, ShouldFailIfItCannotFindNnApiSlPath) { if (!should_perform_test_) { std::cerr << "Skipping test"; return; } std::string storage_path = ::testing::TempDir() + "/storage_path.fb"; (void)unlink(storage_path.c_str()); NnApiSLDriverImplFL5 wrong_handle_nnapi_sl{}; ValidatorRunnerOptions options; options.model_path = model_path_; options.storage_path = ::testing::TempDir() + "/storage_path.fb"; (void)unlink(options.storage_path.c_str()); options.data_directory_path = ::testing::TempDir(); options.nnapi_sl = &wrong_handle_nnapi_sl; ValidatorRunner validator(options); ASSERT_EQ(validator.Init(), kMiniBenchmarkCannotLoadSupportLibrary); } } } }
406
#ifndef TENSORFLOW_LITE_KERNELS_INTERNAL_RUNTIME_SHAPE_H_ #define TENSORFLOW_LITE_KERNELS_INTERNAL_RUNTIME_SHAPE_H_ #include <cstdint> #include <cstring> #include <initializer_list> #include <iterator> #include <memory> #include "tensorflow/lite/kernels/internal/compatibility.h" namespace tflite { template <int N> struct Dims { int sizes[N]; int strides[N]; }; class RuntimeShape { public: static constexpr int kMaxSmallSize = 6; RuntimeShape& operator=(RuntimeShape const&) = delete; RuntimeShape() : size_(0) {} explicit RuntimeShape(int dimensions_count) : size_(dimensions_count) { if (dimensions_count > kMaxSmallSize) { dims_pointer_ = new int32_t[dimensions_count]; } } RuntimeShape(int shape_size, int32_t value) : size_(0) { Resize(shape_size); for (int i = 0; i < shape_size; ++i) { SetDim(i, value); } } RuntimeShape(int dimensions_count, const int32_t* dims_data) : size_(0) { ReplaceWith(dimensions_count, dims_data); } RuntimeShape(const std::initializer_list<int> init_list) : size_(0) { BuildFrom(init_list); } RuntimeShape(RuntimeShape const& other) : size_(other.DimensionsCount()) { if (size_ > kMaxSmallSize) { dims_pointer_ = new int32_t[size_]; } std::memcpy(DimsData(), other.DimsData(), sizeof(int32_t) * size_); } bool operator==(const RuntimeShape& comp) const { return this->size_ == comp.size_ && std::memcmp(DimsData(), comp.DimsData(), size_ * sizeof(int32_t)) == 0; } ~RuntimeShape(); inline int32_t DimensionsCount() const { return size_; } int32_t Dims(int i) const; inline void SetDim(int i, int32_t val) { TFLITE_DCHECK_GE(i, 0); TFLITE_DCHECK_LT(i, size_); if (size_ > kMaxSmallSize) { dims_pointer_[i] = val; } else { dims_[i] = val; } } inline int32_t* DimsData() { return size_ > kMaxSmallSize ? dims_pointer_ : dims_; } inline const int32_t* DimsData() const { return size_ > kMaxSmallSize ? dims_pointer_ : dims_; } inline const int32_t* DimsDataUpTo5D() const { return dims_; } inline void Resize(int dimensions_count) { const int32_t old_size = size_; size_ = dimensions_count; if (old_size <= kMaxSmallSize) { if (dimensions_count <= kMaxSmallSize) { return; } else { int32_t* new_big_data = new int32_t[dimensions_count]; memcpy(new_big_data, dims_, sizeof(int32_t) * old_size); dims_pointer_ = new_big_data; } } else { if (dimensions_count > kMaxSmallSize && dimensions_count <= old_size) { return; } std::unique_ptr<int32_t[]> old_data(dims_pointer_); if (dimensions_count <= old_size) { memcpy(dims_, old_data.get(), sizeof(int32_t) * dimensions_count); } else { dims_pointer_ = new int32_t[dimensions_count]; memcpy(dims_pointer_, old_data.get(), sizeof(int32_t) * old_size); } } } void ReplaceWith(int dimensions_count, const int32_t* dims_data); template <typename T> inline void BuildFrom(const T& src_iterable) { const int dimensions_count = std::distance(src_iterable.begin(), src_iterable.end()); Resize(dimensions_count); int32_t* data = DimsData(); for (auto it : src_iterable) { *data = it; ++data; } } inline static RuntimeShape ExtendedShape(int new_shape_size, const RuntimeShape& shape) { return RuntimeShape(new_shape_size, shape, 1); } inline void BuildFrom(const std::initializer_list<int> init_list) { BuildFrom<const std::initializer_list<int>>(init_list); } int FlatSize() const; bool operator!=(const RuntimeShape& comp) const { return !((*this) == comp); } private: RuntimeShape(int new_shape_size, const RuntimeShape& shape, int pad_value) : size_(0) { TFLITE_CHECK_GE(new_shape_size, shape.DimensionsCount()); Resize(new_shape_size); const int size_increase = new_shape_size - shape.DimensionsCount(); for (int i = 0; i < size_increase; ++i) { SetDim(i, pad_value); } std::memcpy(DimsData() + size_increase, shape.DimsData(), sizeof(int32_t) * shape.DimensionsCount()); } int32_t size_; union { int32_t dims_[kMaxSmallSize]; int32_t* dims_pointer_; }; }; inline tflite::Dims<4> ToRuntimeDims(const tflite::RuntimeShape& array_shape) { tflite::Dims<4> result; const int dimensions_count = array_shape.DimensionsCount(); TFLITE_CHECK_LE(dimensions_count, 4); int cum_prod = 1; for (int i = 0; i < 4; i++) { const int new_dim = (i < dimensions_count) ? array_shape.Dims(dimensions_count - 1 - i) : 1; result.sizes[i] = new_dim; result.strides[i] = cum_prod; cum_prod *= new_dim; } return result; } inline RuntimeShape DimsToShape(const tflite::Dims<4>& dims) { return RuntimeShape( {dims.sizes[3], dims.sizes[2], dims.sizes[1], dims.sizes[0]}); } inline int Offset(const RuntimeShape& shape, int i0, int i1, int i2, int i3) { TFLITE_DCHECK_EQ(shape.DimensionsCount(), 4); const int* dims_data = reinterpret_cast<const int*>(shape.DimsDataUpTo5D()); TFLITE_DCHECK((dims_data[0] == 0 && i0 == 0) || (i0 >= 0 && i0 < dims_data[0])); TFLITE_DCHECK((dims_data[1] == 0 && i1 == 0) || (i1 >= 0 && i1 < dims_data[1])); TFLITE_DCHECK((dims_data[2] == 0 && i2 == 0) || (i2 >= 0 && i2 < dims_data[2])); TFLITE_DCHECK((dims_data[3] == 0 && i3 == 0) || (i3 >= 0 && i3 < dims_data[3])); return ((i0 * dims_data[1] + i1) * dims_data[2] + i2) * dims_data[3] + i3; } inline int Offset(const RuntimeShape& shape, int i0, int i1, int i2, int i3, int i4) { TFLITE_DCHECK_EQ(shape.DimensionsCount(), 5); const int* dims_data = reinterpret_cast<const int*>(shape.DimsDataUpTo5D()); TFLITE_DCHECK((dims_data[0] == 0 && i0 == 0) || (i0 >= 0 && i0 < dims_data[0])); TFLITE_DCHECK((dims_data[1] == 0 && i1 == 0) || (i1 >= 0 && i1 < dims_data[1])); TFLITE_DCHECK((dims_data[2] == 0 && i2 == 0) || (i2 >= 0 && i2 < dims_data[2])); TFLITE_DCHECK((dims_data[3] == 0 && i3 == 0) || (i3 >= 0 && i3 < dims_data[3])); TFLITE_DCHECK((dims_data[4] == 0 && i4 == 0) || (i4 >= 0 && i4 < dims_data[4])); return (((i0 * dims_data[1] + i1) * dims_data[2] + i2) * dims_data[3] + i3) * dims_data[4] + i4; } inline int Offset(const RuntimeShape& shape, int* index) { return Offset(shape, index[0], index[1], index[2], index[3]); } } #endif #include "tensorflow/lite/kernels/internal/runtime_shape.h" #include <cstring> namespace tflite { RuntimeShape::~RuntimeShape() { if (size_ > kMaxSmallSize) { delete[] dims_pointer_; } } int32_t RuntimeShape::Dims(int i) const { TFLITE_DCHECK_GE(i, 0); TFLITE_DCHECK_LT(i, size_); return size_ > kMaxSmallSize ? dims_pointer_[i] : dims_[i]; } void RuntimeShape::ReplaceWith(int dimensions_count, const int32_t* dims_data) { Resize(dimensions_count); int32_t* dst_dims = DimsData(); std::memcpy(dst_dims, dims_data, dimensions_count * sizeof(int32_t)); } int RuntimeShape::FlatSize() const { int buffer_size = 1; const int* dims_data = reinterpret_cast<const int*>(DimsData()); for (int i = 0; i < size_; i++) { buffer_size *= dims_data[i]; } return buffer_size; } }
#include "tensorflow/lite/kernels/internal/runtime_shape.h" #include <algorithm> #include <cstdint> #include <functional> #include <initializer_list> #include <numeric> #include <vector> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "absl/algorithm/container.h" #include "absl/types/span.h" using testing::Each; using testing::ElementsAreArray; namespace tflite { namespace { constexpr int kSmallSize = RuntimeShape::kMaxSmallSize; constexpr int kBigSize = RuntimeShape::kMaxSmallSize + 1; std::vector<int32_t> IotaVector(int size, int start = 0) { std::vector<int32_t> vec(size); absl::c_iota(vec, start); return vec; } absl::Span<const int32_t> AsSpan(const RuntimeShape& shape) { return absl::Span<const int32_t>(shape.DimsData(), shape.DimensionsCount()); } class RuntimeShapeTest : public testing::TestWithParam<int> {}; TEST(RuntimeShapeTest, TestDefaultConstructor) { const RuntimeShape shape; EXPECT_EQ(shape.DimensionsCount(), 0); } TEST_P(RuntimeShapeTest, TestConstructorWithSize) { const int size = GetParam(); const RuntimeShape shape(size); EXPECT_EQ(shape.DimensionsCount(), size); } TEST_P(RuntimeShapeTest, TestConstructorWithSizeAndDefaultValue) { const int size = GetParam(); const RuntimeShape shape(size, 34); EXPECT_EQ(shape.DimensionsCount(), size); EXPECT_THAT(AsSpan(shape), Each(34)); } TEST_P(RuntimeShapeTest, TestConstructorFromCArray) { const int size = GetParam(); const std::vector<int32_t> src = IotaVector(size); const RuntimeShape shape(size, src.data()); EXPECT_EQ(shape.DimensionsCount(), size); EXPECT_THAT(AsSpan(shape), ElementsAreArray(src)); } TEST(RuntimeShapeTest, TestConstructorFromSmallInitList) { std::initializer_list<int> init{1, 2, 3}; ASSERT_LE(init.size(), RuntimeShape::kMaxSmallSize); const RuntimeShape shape(init); EXPECT_EQ(shape.DimensionsCount(), init.size()); EXPECT_THAT(AsSpan(shape), ElementsAreArray(init)); } TEST(RuntimeShapeTest, TestConstructorFromBigInitList) { std::initializer_list<int> init{1, 2, 3, 4, 5, 6, 7, 8, 9}; ASSERT_GT(init.size(), RuntimeShape::kMaxSmallSize); const RuntimeShape shape(init); EXPECT_EQ(shape.DimensionsCount(), init.size()); EXPECT_THAT(AsSpan(shape), ElementsAreArray(init)); } TEST_P(RuntimeShapeTest, TestCopyConstructorFromShape) { const int size = GetParam(); const RuntimeShape src(size, 34); const RuntimeShape dst(src); EXPECT_EQ(dst.DimensionsCount(), src.DimensionsCount()); EXPECT_THAT(AsSpan(dst), ElementsAreArray(AsSpan(src))); } TEST_P(RuntimeShapeTest, TestEqualityOperator) { const int size = GetParam(); const RuntimeShape shape1(size, 34); const RuntimeShape shape2(size, 34); EXPECT_TRUE(shape1 == shape2); EXPECT_FALSE(shape1 != shape2); } TEST_P(RuntimeShapeTest, TestEqualityOperatorDifferentSizes) { const int size = GetParam(); const RuntimeShape shape1(size, 34); const RuntimeShape shape2(size + 1, 34); EXPECT_FALSE(shape1 == shape2); EXPECT_TRUE(shape1 != shape2); } TEST_P(RuntimeShapeTest, TestEqualityOperatorDifferentValues) { const int size = GetParam(); const RuntimeShape shape1(size, 34); const RuntimeShape shape2(size, 43); EXPECT_FALSE(shape1 == shape2); EXPECT_TRUE(shape1 != shape2); } TEST_P(RuntimeShapeTest, TestSetterGetter) { const int size = GetParam(); RuntimeShape shape(size); for (int i = 0; i < size; ++i) { shape.SetDim(i, i); EXPECT_EQ(shape.Dims(i), i); } EXPECT_THAT(AsSpan(shape), ElementsAreArray(IotaVector(size))); } TEST(RuntimeShapeTest, TestResizeSmallSmall) { ASSERT_GE(kSmallSize, 1); RuntimeShape shape(kSmallSize - 1, 23); shape.Resize(kSmallSize); EXPECT_EQ(shape.DimensionsCount(), kSmallSize); EXPECT_THAT(absl::Span<const int32_t>(shape.DimsData(), kSmallSize - 1), Each(23)); } TEST(RuntimeShapeTest, TestResizeSmallBig) { RuntimeShape shape(kSmallSize, 23); shape.Resize(kBigSize); EXPECT_EQ(shape.DimensionsCount(), kBigSize); EXPECT_THAT(absl::Span<const int32_t>(shape.DimsData(), kSmallSize), Each(23)); } TEST(RuntimeShapeTest, TestResizeBigSmall) { RuntimeShape shape(kBigSize, 23); shape.Resize(kSmallSize); EXPECT_EQ(shape.DimensionsCount(), kSmallSize); EXPECT_THAT(absl::Span<const int32_t>(shape.DimsData(), kSmallSize), Each(23)); } TEST(RuntimeShapeTest, TestResizeDownBigBig) { RuntimeShape shape(kBigSize + 3, 23); shape.Resize(kBigSize); EXPECT_EQ(shape.DimensionsCount(), kBigSize); EXPECT_THAT(absl::Span<const int32_t>(shape.DimsData(), kBigSize), Each(23)); } TEST(RuntimeShapeTest, TestResizeUpBigBig) { RuntimeShape shape(kBigSize, 23); shape.Resize(kBigSize + 1); EXPECT_EQ(shape.DimensionsCount(), kBigSize + 1); EXPECT_THAT(absl::Span<const int32_t>(shape.DimsData(), kBigSize), Each(23)); } TEST_P(RuntimeShapeTest, TestReplaceWith) { static_assert( RuntimeShape::kMaxSmallSize > 2, "kMaxSmallSize should be greater than 2 for this test to work."); const int size = GetParam(); for (const int offset : {-2, 2}) { const std::vector<int32_t> src = IotaVector(offset + RuntimeShape::kMaxSmallSize); RuntimeShape shape(size); shape.ReplaceWith(src.size(), src.data()); EXPECT_EQ(shape.DimensionsCount(), src.size()); EXPECT_THAT(AsSpan(shape), testing::ElementsAreArray(src)); } } TEST_P(RuntimeShapeTest, TestBuildFrom) { const int size = GetParam(); const std::vector<int32_t> src = IotaVector(size); RuntimeShape shape; shape.BuildFrom(src); EXPECT_EQ(shape.DimensionsCount(), src.size()); EXPECT_THAT(AsSpan(shape), testing::ElementsAreArray(src)); } TEST(RuntimeShapeTest, TestExtendedShapeSmall) { ASSERT_GE(kSmallSize, 2); const std::vector<int32_t> dims = IotaVector(kSmallSize - 2); const RuntimeShape src(dims.size(), dims.data()); const RuntimeShape extended = RuntimeShape::ExtendedShape(kSmallSize, src); EXPECT_EQ(extended.DimensionsCount(), kSmallSize); EXPECT_EQ(extended.Dims(0), 1); EXPECT_EQ(extended.Dims(1), 1); EXPECT_THAT(absl::Span<const int32_t>(extended.DimsData() + 2, dims.size()), ElementsAreArray(dims)); } TEST(RuntimeShapeTest, TestExtendedShapeBig) { ASSERT_GE(kSmallSize, 2); const std::vector<int32_t> dims = IotaVector(kBigSize); const RuntimeShape src(dims.size(), dims.data()); const RuntimeShape extended = RuntimeShape::ExtendedShape(kBigSize + 2, src); EXPECT_EQ(extended.DimensionsCount(), kBigSize + 2); EXPECT_EQ(extended.Dims(0), 1); EXPECT_EQ(extended.Dims(1), 1); EXPECT_THAT(absl::Span<const int32_t>(extended.DimsData() + 2, dims.size()), ElementsAreArray(dims)); } TEST(RuntimeShapeTest, TestExtendedShapeSmallToBig) { const std::vector<int32_t> dims = IotaVector(kSmallSize); const RuntimeShape src(dims.size(), dims.data()); const RuntimeShape extended = RuntimeShape::ExtendedShape(kBigSize, src); EXPECT_EQ(extended.DimensionsCount(), kBigSize); EXPECT_THAT( absl::Span<const int32_t>(extended.DimsData(), kBigSize - kSmallSize), Each(1)); EXPECT_THAT(absl::Span<const int32_t>( extended.DimsData() + kBigSize - kSmallSize, dims.size()), ElementsAreArray(dims)); } TEST_P(RuntimeShapeTest, TestFlatSize) { const std::vector<int32_t> src = IotaVector(kSmallSize); const RuntimeShape shape(src.size(), src.data()); EXPECT_EQ(shape.FlatSize(), std::reduce(src.begin(), src.end(), 1, std::multiplies<int>{})); } INSTANTIATE_TEST_SUITE_P(BigSmall, RuntimeShapeTest, testing::Values(kSmallSize, kBigSize), [](const testing::TestParamInfo<int>& info) { return info.param == kSmallSize ? "Small" : "Big"; }); } }
407
#ifndef XLA_PJRT_C_PJRT_C_API_CPU_H_ #define XLA_PJRT_C_PJRT_C_API_CPU_H_ #include "xla/pjrt/c/pjrt_c_api.h" #ifdef __cplusplus extern "C" { #endif const PJRT_Api* GetPjrtApi(); #ifdef __cplusplus } #endif #endif #include "xla/pjrt/c/pjrt_c_api_cpu.h" #include "xla/pjrt/c/pjrt_c_api.h" #include "xla/pjrt/c/pjrt_c_api_cpu_internal.h" const PJRT_Api* GetPjrtApi() { return pjrt::cpu_plugin::GetCpuPjrtApi(); }
#include "xla/pjrt/c/pjrt_c_api_cpu.h" #include "xla/pjrt/c/pjrt_c_api_test.h" #include "xla/pjrt/c/pjrt_c_api_wrapper_impl.h" namespace pjrt { namespace { const bool kUnused = (RegisterPjRtCApiTestFactory([]() { return GetPjrtApi(); }, "cpu"), true); } }
408
#ifndef TENSORFLOW_CORE_KERNELS_DATA_CONCATENATE_DATASET_OP_H_ #define TENSORFLOW_CORE_KERNELS_DATA_CONCATENATE_DATASET_OP_H_ #include "tensorflow/core/framework/dataset.h" namespace tensorflow { namespace data { class ConcatenateDatasetOp : public BinaryDatasetOpKernel { public: static constexpr const char* const kDatasetType = "Concatenate"; static constexpr const char* const kInputDataset = "input_dataset"; static constexpr const char* const kAnotherDataset = "another_dataset"; static constexpr const char* const kOutputTypes = "output_types"; static constexpr const char* const kOutputShapes = "output_shapes"; explicit ConcatenateDatasetOp(OpKernelConstruction* ctx); protected: void MakeDataset(OpKernelContext* ctx, DatasetBase* input, DatasetBase* to_concatenate, DatasetBase** output) override; private: class Dataset; }; } } #endif #include "tensorflow/core/kernels/data/concatenate_dataset_op.h" #include <string> #include <utility> #include "tensorflow/core/data/name_utils.h" #include "tensorflow/core/data/split_utils.h" #include "tensorflow/core/framework/partial_tensor_shape.h" #include "tensorflow/core/framework/tensor.h" namespace tensorflow { namespace data { constexpr const char* const ConcatenateDatasetOp::kDatasetType; constexpr const char* const ConcatenateDatasetOp::kInputDataset; constexpr const char* const ConcatenateDatasetOp::kAnotherDataset; constexpr const char* const ConcatenateDatasetOp::kOutputTypes; constexpr const char* const ConcatenateDatasetOp::kOutputShapes; constexpr char kIndex[] = "i"; constexpr char kInputImplUninitialized[] = "input_impl_uninitialized"; class ConcatenateDatasetOp::Dataset : public DatasetBase { public: explicit Dataset(OpKernelContext* ctx, const DatasetBase* input, const DatasetBase* to_concatenate) : DatasetBase(DatasetContext(ctx)), input_(input), to_concatenate_(to_concatenate), input_cardinality_(input->Cardinality()), to_concatenate_cardinality_(to_concatenate_->Cardinality()) { input_->Ref(); to_concatenate_->Ref(); auto os_input = input->output_shapes(); auto os_concatenate = to_concatenate->output_shapes(); for (int i = 0; i < os_input.size(); i++) { PartialTensorShape output_tensorshape({}); OP_REQUIRES_OK(ctx, MostSpecificCompatibleShape(os_input[i], os_concatenate[i], &output_tensorshape)); output_shapes_.push_back(output_tensorshape); } } ~Dataset() override { input_->Unref(); to_concatenate_->Unref(); } std::unique_ptr<IteratorBase> MakeIteratorInternal( const string& prefix) const override { return std::make_unique<Iterator>(Iterator::Params{ this, name_utils::IteratorPrefix(kDatasetType, prefix)}); } Status MakeSplitProviders(std::vector<std::unique_ptr<SplitProvider>>* split_providers) const override { TF_ASSIGN_OR_RETURN(*split_providers, GetSplitProviders(this)); return absl::OkStatus(); } const DataTypeVector& output_dtypes() const override { return input_->output_dtypes(); } const std::vector<PartialTensorShape>& output_shapes() const override { return output_shapes_; } string DebugString() const override { return name_utils::DatasetDebugString(kDatasetType); } int64_t CardinalityInternal(CardinalityOptions options) const override { int64_t input_cardinality = input_->Cardinality(options); int64_t to_concatenate_cardinality = to_concatenate_->Cardinality(options); if (input_cardinality == kInfiniteCardinality || to_concatenate_cardinality == kInfiniteCardinality) { return kInfiniteCardinality; } if (input_cardinality == kUnknownCardinality || to_concatenate_cardinality == kUnknownCardinality) { return kUnknownCardinality; } return input_cardinality + to_concatenate_cardinality; } Status InputDatasets(std::vector<const DatasetBase*>* inputs) const override { inputs->push_back(input_); inputs->push_back(to_concatenate_); return absl::OkStatus(); } Status CheckExternalState() const override { TF_RETURN_IF_ERROR(input_->CheckExternalState()); return to_concatenate_->CheckExternalState(); } Status Get(OpKernelContext* ctx, int64 index, std::vector<Tensor>* out_tensors) const override { TF_RETURN_IF_ERROR(CheckRandomAccessCompatible(index)); if (index < input_cardinality_) { TF_RETURN_IF_ERROR(input_->Get(ctx, index, out_tensors)); } else { TF_RETURN_IF_ERROR( to_concatenate_->Get(ctx, index - input_cardinality_, out_tensors)); } return absl::OkStatus(); } protected: Status AsGraphDefInternal(SerializationContext* ctx, DatasetGraphDefBuilder* b, Node** output) const override { Node* input_graph = nullptr; TF_RETURN_IF_ERROR(b->AddInputDataset(ctx, input_, &input_graph)); Node* to_concatenate_graph = nullptr; TF_RETURN_IF_ERROR( b->AddInputDataset(ctx, to_concatenate_, &to_concatenate_graph)); TF_RETURN_IF_ERROR( b->AddDataset(this, {input_graph, to_concatenate_graph}, output)); return absl::OkStatus(); } private: class Iterator : public DatasetIterator<Dataset> { public: explicit Iterator(const Params& params) : DatasetIterator<Dataset>(params), i_(0) {} bool SymbolicCheckpointCompatible() const override { return true; } Status Initialize(IteratorContext* ctx) override { TF_ASSIGN_OR_RETURN(input_contexts_, CreateInputIteratorContexts(ctx, dataset())); TF_RETURN_IF_ERROR(dataset()->input_->MakeIterator( &input_contexts_[0], this, strings::StrCat(prefix(), "[0]"), &input_impl_)); ctx->MergeCheckpoint(input_contexts_[0].checkpoint()); return absl::OkStatus(); } Status GetNextInternal(IteratorContext* ctx, std::vector<Tensor>* out_tensors, bool* end_of_sequence) override { mutex_lock l(mu_); if (!input_impl_) { *end_of_sequence = true; return absl::OkStatus(); } while (i_ < 2) { TF_RETURN_IF_ERROR(input_impl_->GetNext(&input_contexts_[i_], out_tensors, end_of_sequence)); ctx->MergeCheckpoint(input_contexts_[i_].checkpoint()); if (!*end_of_sequence) { return absl::OkStatus(); } if (++i_ < 2) { TF_RETURN_IF_ERROR(dataset()->to_concatenate_->MakeIterator( &input_contexts_[i_], this, strings::StrCat(prefix(), "[1]"), &input_impl_)); } } *end_of_sequence = true; input_impl_.reset(); return absl::OkStatus(); } protected: std::shared_ptr<model::Node> CreateNode( IteratorContext* ctx, model::Node::Args args) const override { return model::MakeKnownRatioNode(std::move(args), 1); } Status SaveInternal(SerializationContext* ctx, IteratorStateWriter* writer) override { mutex_lock l(mu_); TF_RETURN_IF_ERROR(writer->WriteScalar(prefix(), kIndex, i_)); TF_RETURN_IF_ERROR( writer->WriteScalar(prefix(), kInputImplUninitialized, static_cast<int64_t>(!input_impl_))); if (input_impl_) { TF_RETURN_IF_ERROR(SaveInput(ctx, writer, input_impl_)); } return absl::OkStatus(); } Status RestoreInternal(IteratorContext* ctx, IteratorStateReader* reader) override { mutex_lock l(mu_); TF_RETURN_IF_ERROR(reader->ReadScalar(prefix(), kIndex, &i_)); int64_t input_uninitialized; TF_RETURN_IF_ERROR(reader->ReadScalar(prefix(), kInputImplUninitialized, &input_uninitialized)); if (static_cast<bool>(input_uninitialized)) { input_impl_.reset(); return absl::OkStatus(); } if (!TF_PREDICT_TRUE(i_ >= 0 && i_ <= 2)) return errors::InvalidArgument("i_ must be in range [0, 2]."); if (i_ == 1) { TF_RETURN_IF_ERROR(dataset()->to_concatenate_->MakeIterator( ctx, this, strings::StrCat(prefix(), "[1]"), &input_impl_)); } else if (i_ == 2) { input_impl_.reset(); } if (input_impl_) { TF_RETURN_IF_ERROR(RestoreInput(ctx, reader, input_impl_)); } return absl::OkStatus(); } private: mutex mu_; int64_t i_ TF_GUARDED_BY(mu_); std::unique_ptr<IteratorBase> input_impl_ TF_GUARDED_BY(mu_); std::vector<IteratorContext> input_contexts_; }; Status MostSpecificCompatibleShape(const PartialTensorShape& ts1, const PartialTensorShape& ts2, PartialTensorShape* output_tensorshape) { if (ts1.dims() != ts2.dims() || ts1.unknown_rank() || ts2.unknown_rank()) return absl::OkStatus(); auto dims1 = ts1.dim_sizes(); auto dims2 = ts2.dim_sizes(); for (int d = 0; d < ts1.dims(); d++) { if (dims1[d] == dims2[d]) TF_RETURN_IF_ERROR(output_tensorshape->AddDimWithStatus(dims1[d])); else TF_RETURN_IF_ERROR(output_tensorshape->AddDimWithStatus(-1)); } return absl::OkStatus(); } const DatasetBase* input_; const DatasetBase* to_concatenate_; const int64_t input_cardinality_; const int64_t to_concatenate_cardinality_; std::vector<PartialTensorShape> output_shapes_; }; ConcatenateDatasetOp::ConcatenateDatasetOp(OpKernelConstruction* ctx) : BinaryDatasetOpKernel(ctx) {} void ConcatenateDatasetOp::MakeDataset(OpKernelContext* ctx, DatasetBase* input, DatasetBase* to_concatenate, DatasetBase** output) { OP_REQUIRES(ctx, input->output_dtypes() == to_concatenate->output_dtypes(), errors::InvalidArgument( "input dataset and dataset to concatenate" " have different output_types %s and %s", (DataTypeVectorString(input->output_dtypes()), DataTypeVectorString(to_concatenate->output_dtypes())))); *output = new Dataset(ctx, input, to_concatenate); } namespace { REGISTER_KERNEL_BUILDER(Name("ConcatenateDataset").Device(DEVICE_CPU), ConcatenateDatasetOp); } } }
#include "tensorflow/core/kernels/data/concatenate_dataset_op.h" #include "tensorflow/core/data/dataset_test_base.h" namespace tensorflow { namespace data { namespace { constexpr char kNodeName[] = "concatenate_dataset"; ConcatenateDatasetParams SameShapeConcatenateDatasetParams() { auto tensor_slice_dataset_params_0 = TensorSliceDatasetParams( CreateTensors<int64_t>(TensorShape{2, 2}, {{1, 2, 3, 4}, {5, 6, 7, 8}}), "tensor_slice_0"); auto tensor_slice_dataset_params_1 = TensorSliceDatasetParams( CreateTensors<int64_t>( TensorShape{2, 2}, {{11, 12, 13, 14}, {15, 16, 17, 18}}), "tensor_slice_1"); return ConcatenateDatasetParams( std::move(tensor_slice_dataset_params_0), std::move(tensor_slice_dataset_params_1), {DT_INT64, DT_INT64}, {PartialTensorShape({2}), PartialTensorShape({2})}, kNodeName); } ConcatenateDatasetParams DifferentShapeConcatenateDatasetParams() { auto tensor_slice_dataset_params_0 = TensorSliceDatasetParams( {CreateTensor<int64_t>(TensorShape{2, 3}, {1, 2, 3, 4, 5, 6}), CreateTensor<int64_t>(TensorShape{2, 2}, {7, 8, 9, 10})}, "tensor_slice_0"); auto tensor_slice_dataset_params_1 = TensorSliceDatasetParams( {CreateTensor<int64_t>(TensorShape{2, 2}, {11, 12, 13, 14}), CreateTensor<int64_t>(TensorShape{2, 1}, {15, 16})}, "tensor_slice_1"); return ConcatenateDatasetParams( std::move(tensor_slice_dataset_params_0), std::move(tensor_slice_dataset_params_1), {DT_INT64, DT_INT64}, {PartialTensorShape({-1}), PartialTensorShape({-1})}, kNodeName); } ConcatenateDatasetParams DifferentDtypeConcatenateDatasetParams() { auto tensor_slice_dataset_params_0 = TensorSliceDatasetParams( CreateTensors<int64_t>(TensorShape{2, 2}, {{1, 2, 3, 4}}), "tensor_slice_0"); auto tensor_slice_dataset_params_1 = TensorSliceDatasetParams( CreateTensors<double>(TensorShape{2, 2}, {{1.0, 2.0, 3.0, 4.0}}), "tensor_slice_1"); return ConcatenateDatasetParams(std::move(tensor_slice_dataset_params_0), std::move(tensor_slice_dataset_params_1), {DT_INT64}, {PartialTensorShape({2})}, kNodeName); } class ConcatenateDatasetOpTest : public DatasetOpsTestBase {}; std::vector<GetNextTestCase<ConcatenateDatasetParams>> GetNextTestCases() { return {{SameShapeConcatenateDatasetParams(), CreateTensors<int64_t>(TensorShape({2}), {{1, 2}, {5, 6}, {3, 4}, {7, 8}, {11, 12}, {15, 16}, {13, 14}, {17, 18}})}, {DifferentShapeConcatenateDatasetParams(), {CreateTensor<int64_t>(TensorShape{3}, {1, 2, 3}), CreateTensor<int64_t>(TensorShape{2}, {7, 8}), CreateTensor<int64_t>(TensorShape{3}, {4, 5, 6}), CreateTensor<int64_t>(TensorShape{2}, {9, 10}), CreateTensor<int64_t>(TensorShape{2}, {11, 12}), CreateTensor<int64_t>(TensorShape{1}, {15}), CreateTensor<int64_t>(TensorShape{2}, {13, 14}), CreateTensor<int64_t>(TensorShape{1}, {16})}}}; } ITERATOR_GET_NEXT_TEST_P(ConcatenateDatasetOpTest, ConcatenateDatasetParams, GetNextTestCases()) TEST_F(ConcatenateDatasetOpTest, DifferentDtypes) { auto dataset_params = DifferentDtypeConcatenateDatasetParams(); EXPECT_EQ(Initialize(dataset_params).code(), absl::StatusCode::kInvalidArgument); } TEST_F(ConcatenateDatasetOpTest, DatasetNodeName) { auto dataset_params = SameShapeConcatenateDatasetParams(); TF_ASSERT_OK(Initialize(dataset_params)); TF_ASSERT_OK(CheckDatasetNodeName(dataset_params.node_name())); } TEST_F(ConcatenateDatasetOpTest, DatasetTypeString) { auto dataset_params = SameShapeConcatenateDatasetParams(); TF_ASSERT_OK(Initialize(dataset_params)); TF_ASSERT_OK(CheckDatasetTypeString( name_utils::OpName(ConcatenateDatasetOp::kDatasetType))); } std::vector<DatasetOutputDtypesTestCase<ConcatenateDatasetParams>> DatasetOutputDtypesTestCases() { return {{SameShapeConcatenateDatasetParams(), SameShapeConcatenateDatasetParams().output_dtypes()}, {DifferentShapeConcatenateDatasetParams(), DifferentShapeConcatenateDatasetParams().output_dtypes()}}; } DATASET_OUTPUT_DTYPES_TEST_P(ConcatenateDatasetOpTest, ConcatenateDatasetParams, DatasetOutputDtypesTestCases()) std::vector<DatasetOutputShapesTestCase<ConcatenateDatasetParams>> DatasetOutputShapesTestCases() { return {{SameShapeConcatenateDatasetParams(), SameShapeConcatenateDatasetParams().output_shapes()}, { DifferentShapeConcatenateDatasetParams(), DifferentShapeConcatenateDatasetParams().output_shapes()}}; } DATASET_OUTPUT_SHAPES_TEST_P(ConcatenateDatasetOpTest, ConcatenateDatasetParams, DatasetOutputShapesTestCases()) std::vector<CardinalityTestCase<ConcatenateDatasetParams>> CardinalityTestCases() { return {{SameShapeConcatenateDatasetParams(), 4}, {DifferentShapeConcatenateDatasetParams(), 4}}; } DATASET_CARDINALITY_TEST_P(ConcatenateDatasetOpTest, ConcatenateDatasetParams, CardinalityTestCases()) std::vector<IteratorOutputDtypesTestCase<ConcatenateDatasetParams>> IteratorOutputDtypesTestCases() { return {{SameShapeConcatenateDatasetParams(), SameShapeConcatenateDatasetParams().output_dtypes()}, {DifferentShapeConcatenateDatasetParams(), DifferentShapeConcatenateDatasetParams().output_dtypes()}}; } ITERATOR_OUTPUT_DTYPES_TEST_P(ConcatenateDatasetOpTest, ConcatenateDatasetParams, IteratorOutputDtypesTestCases()) std::vector<IteratorOutputShapesTestCase<ConcatenateDatasetParams>> IteratorOutputShapesTestCases() { return {{SameShapeConcatenateDatasetParams(), SameShapeConcatenateDatasetParams().output_shapes()}, {DifferentShapeConcatenateDatasetParams(), DifferentShapeConcatenateDatasetParams().output_shapes()}}; } ITERATOR_OUTPUT_SHAPES_TEST_P(ConcatenateDatasetOpTest, ConcatenateDatasetParams, IteratorOutputShapesTestCases()) TEST_F(ConcatenateDatasetOpTest, IteratorPrefix) { auto dataset_params = SameShapeConcatenateDatasetParams(); TF_ASSERT_OK(Initialize(dataset_params)); TF_ASSERT_OK(CheckIteratorPrefix(name_utils::IteratorPrefix( ConcatenateDatasetOp::kDatasetType, dataset_params.iterator_prefix()))); } std::vector<IteratorSaveAndRestoreTestCase<ConcatenateDatasetParams>> IteratorSaveAndRestoreTestCases() { return {{SameShapeConcatenateDatasetParams(), {0, 2, 5}, CreateTensors<int64_t>(TensorShape({2}), {{1, 2}, {5, 6}, {3, 4}, {7, 8}, {11, 12}, {15, 16}, {13, 14}, {17, 18}})}, {DifferentShapeConcatenateDatasetParams(), {0, 2, 5}, {CreateTensor<int64_t>(TensorShape{3}, {1, 2, 3}), CreateTensor<int64_t>(TensorShape{2}, {7, 8}), CreateTensor<int64_t>(TensorShape{3}, {4, 5, 6}), CreateTensor<int64_t>(TensorShape{2}, {9, 10}), CreateTensor<int64_t>(TensorShape{2}, {11, 12}), CreateTensor<int64_t>(TensorShape{1}, {15}), CreateTensor<int64_t>(TensorShape{2}, {13, 14}), CreateTensor<int64_t>(TensorShape{1}, {16})}}}; } ITERATOR_SAVE_AND_RESTORE_TEST_P(ConcatenateDatasetOpTest, ConcatenateDatasetParams, IteratorSaveAndRestoreTestCases()) } } }
409
#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")); } } }