ID
int64
0
2.65k
Language
stringclasses
1 value
Repository Name
stringclasses
14 values
File Name
stringlengths
2
48
File Path in Repository
stringlengths
11
111
File Path for Unit Test
stringlengths
16
116
Code
stringlengths
411
31.4k
Unit Test - (Ground Truth)
stringlengths
40
32.1k
2,600
cpp
google/tsl
strcat
tsl/platform/strcat.cc
tsl/platform/strcat_test.cc
#ifndef TENSORFLOW_TSL_PLATFORM_STRCAT_H_ #define TENSORFLOW_TSL_PLATFORM_STRCAT_H_ #include <string> #include "tsl/platform/macros.h" #include "tsl/platform/numbers.h" #include "tsl/platform/stringpiece.h" #include "tsl/platform/types.h" namespace tsl { namespace strings { enum PadSpec { kNoPad = 1, kZeroPad2, kZeroPad3, kZeroPad4, kZeroPad5, kZeroPad6, kZeroPad7, kZeroPad8, kZeroPad9, kZeroPad10, kZeroPad11, kZeroPad12, kZeroPad13, kZeroPad14, kZeroPad15, kZeroPad16 }; struct Hex { uint64 value; enum PadSpec spec; template <class Int> explicit Hex(Int v, PadSpec s = kNoPad) : spec(s) { static_assert( sizeof(v) == 1 || sizeof(v) == 2 || sizeof(v) == 4 || sizeof(v) == 8, "Unknown integer type"); value = sizeof(v) == 1 ? static_cast<uint8>(v) : sizeof(v) == 2 ? static_cast<uint16>(v) : sizeof(v) == 4 ? static_cast<uint32>(v) : static_cast<uint64>(v); } }; class AlphaNum { public: AlphaNum(int i32) : piece_(digits_, FastInt32ToBufferLeft(i32, digits_)) {} AlphaNum(unsigned int u32) : piece_(digits_, FastUInt32ToBufferLeft(u32, digits_)) {} AlphaNum(long x) : piece_(digits_, FastInt64ToBufferLeft(x, digits_)) {} AlphaNum(unsigned long x) : piece_(digits_, FastUInt64ToBufferLeft(x, digits_)) {} AlphaNum(long long int i64) : piece_(digits_, FastInt64ToBufferLeft(i64, digits_)) {} AlphaNum(unsigned long long int u64) : piece_(digits_, FastUInt64ToBufferLeft(u64, digits_)) {} AlphaNum(float f) : piece_(digits_, FloatToBuffer(f, digits_)) {} AlphaNum(double f) : piece_(digits_, DoubleToBuffer(f, digits_)) {} AlphaNum(bfloat16 bf) : piece_(digits_, FloatToBuffer(static_cast<float>(bf), digits_)) {} AlphaNum(Hex hex); AlphaNum(const char *c_str) : piece_(c_str) {} AlphaNum(const StringPiece &pc) : piece_(pc) {} AlphaNum(const std::string &str) : piece_(str) {} AlphaNum(const tstring &str) : piece_(str) {} template <typename A> AlphaNum(const std::basic_string<char, std::char_traits<char>, A> &str) : piece_(str) {} StringPiece::size_type size() const { return piece_.size(); } const char *data() const { return piece_.data(); } StringPiece Piece() const { return piece_; } private: StringPiece piece_; char digits_[kFastToBufferSize]; AlphaNum(char c); AlphaNum(const AlphaNum &) = delete; void operator=(const AlphaNum &) = delete; }; std::string StrCat(const AlphaNum &a) TF_MUST_USE_RESULT; std::string StrCat(const AlphaNum &a, const AlphaNum &b) TF_MUST_USE_RESULT; std::string StrCat(const AlphaNum &a, const AlphaNum &b, const AlphaNum &c) TF_MUST_USE_RESULT; std::string StrCat(const AlphaNum &a, const AlphaNum &b, const AlphaNum &c, const AlphaNum &d) TF_MUST_USE_RESULT; namespace internal { std::string CatPieces(std::initializer_list<StringPiece> pieces); void AppendPieces(std::string *dest, std::initializer_list<StringPiece> pieces); } template <typename... AV> std::string StrCat(const AlphaNum &a, const AlphaNum &b, const AlphaNum &c, const AlphaNum &d, const AlphaNum &e, const AV &...args) TF_MUST_USE_RESULT; template <typename... AV> std::string StrCat(const AlphaNum &a, const AlphaNum &b, const AlphaNum &c, const AlphaNum &d, const AlphaNum &e, const AV &...args) { return internal::CatPieces({a.Piece(), b.Piece(), c.Piece(), d.Piece(), e.Piece(), static_cast<const AlphaNum &>(args).Piece()...}); } void StrAppend(std::string *dest, const AlphaNum &a); void StrAppend(std::string *dest, const AlphaNum &a, const AlphaNum &b); void StrAppend(std::string *dest, const AlphaNum &a, const AlphaNum &b, const AlphaNum &c); void StrAppend(std::string *dest, const AlphaNum &a, const AlphaNum &b, const AlphaNum &c, const AlphaNum &d); template <typename... AV> inline void StrAppend(std::string *dest, const AlphaNum &a, const AlphaNum &b, const AlphaNum &c, const AlphaNum &d, const AlphaNum &e, const AV &...args) { internal::AppendPieces(dest, {a.Piece(), b.Piece(), c.Piece(), d.Piece(), e.Piece(), static_cast<const AlphaNum &>(args).Piece()...}); } } } #endif #include "tsl/platform/strcat.h" #include <stdarg.h> #include <stdint.h> #include <stdio.h> #include <string.h> #include <algorithm> #include "absl/meta/type_traits.h" #include "tsl/platform/logging.h" namespace tsl { namespace strings { AlphaNum::AlphaNum(Hex hex) { char *const end = &digits_[kFastToBufferSize]; char *writer = end; uint64 value = hex.value; uint64 width = hex.spec; uint64 mask = (static_cast<uint64>(1) << (width - 1) * 4) | value; static const char hexdigits[] = "0123456789abcdef"; do { *--writer = hexdigits[value & 0xF]; value >>= 4; mask >>= 4; } while (mask != 0); piece_ = StringPiece(writer, end - writer); } static char *Append1(char *out, const AlphaNum &x) { if (x.data() == nullptr) return out; memcpy(out, x.data(), x.size()); return out + x.size(); } static char *Append2(char *out, const AlphaNum &x1, const AlphaNum &x2) { if (x1.data() != nullptr) { memcpy(out, x1.data(), x1.size()); out += x1.size(); } if (x2.data() == nullptr) return out; memcpy(out, x2.data(), x2.size()); return out + x2.size(); } static char *Append4(char *out, const AlphaNum &x1, const AlphaNum &x2, const AlphaNum &x3, const AlphaNum &x4) { if (x1.data() != nullptr) { memcpy(out, x1.data(), x1.size()); out += x1.size(); } if (x2.data() != nullptr) { memcpy(out, x2.data(), x2.size()); out += x2.size(); } if (x3.data() != nullptr) { memcpy(out, x3.data(), x3.size()); out += x3.size(); } if (x4.data() == nullptr) return out; memcpy(out, x4.data(), x4.size()); return out + x4.size(); } string StrCat(const AlphaNum &a) { return string(a.data(), a.size()); } string StrCat(const AlphaNum &a, const AlphaNum &b) { string result(a.size() + b.size(), '\0'); char *const begin = &*result.begin(); char *out = Append2(begin, a, b); DCHECK_EQ(out, begin + result.size()); return result; } string StrCat(const AlphaNum &a, const AlphaNum &b, const AlphaNum &c) { string result(a.size() + b.size() + c.size(), '\0'); char *const begin = &*result.begin(); char *out = Append2(begin, a, b); out = Append1(out, c); DCHECK_EQ(out, begin + result.size()); return result; } string StrCat(const AlphaNum &a, const AlphaNum &b, const AlphaNum &c, const AlphaNum &d) { string result(a.size() + b.size() + c.size() + d.size(), '\0'); char *const begin = &*result.begin(); char *out = Append4(begin, a, b, c, d); DCHECK_EQ(out, begin + result.size()); return result; } namespace { template <typename string_type, typename = void> struct ResizeUninitializedTraits { using HasMember = std::false_type; static void Resize(string_type *s, size_t new_size) { s->resize(new_size); } }; template <typename string_type> struct ResizeUninitializedTraits< string_type, absl::void_t<decltype(std::declval<string_type &>() .__resize_default_init(237))> > { using HasMember = std::true_type; static void Resize(string_type *s, size_t new_size) { s->__resize_default_init(new_size); } }; static inline void STLStringResizeUninitialized(string *s, size_t new_size) { ResizeUninitializedTraits<string>::Resize(s, new_size); } template <typename string_type> void STLStringReserveAmortized(string_type *s, size_t new_size) { const size_t cap = s->capacity(); if (new_size > cap) { s->reserve((std::max)(new_size, 2 * cap)); } } template <typename string_type> void STLStringResizeUninitializedAmortized(string_type *s, size_t new_size) { STLStringReserveAmortized(s, new_size); STLStringResizeUninitialized(s, new_size); } } namespace internal { string CatPieces(std::initializer_list<StringPiece> pieces) { size_t total_size = 0; for (const StringPiece piece : pieces) total_size += piece.size(); string result(total_size, '\0'); char *const begin = &*result.begin(); char *out = begin; for (const StringPiece piece : pieces) { const size_t this_size = piece.size(); memcpy(out, piece.data(), this_size); out += this_size; } DCHECK_EQ(out, begin + result.size()); return result; } #define DCHECK_NO_OVERLAP(dest, src) \ DCHECK_GE(uintptr_t((src).data() - (dest).data()), uintptr_t((dest).size())) void AppendPieces(string *result, std::initializer_list<StringPiece> pieces) { size_t old_size = result->size(); size_t total_size = old_size; for (const StringPiece piece : pieces) { DCHECK_NO_OVERLAP(*result, piece); total_size += piece.size(); } STLStringResizeUninitializedAmortized(result, total_size); char *const begin = &*result->begin(); char *out = begin + old_size; for (const StringPiece piece : pieces) { const size_t this_size = piece.size(); memcpy(out, piece.data(), this_size); out += this_size; } DCHECK_EQ(out, begin + result->size()); } } void StrAppend(string *result, const AlphaNum &a) { DCHECK_NO_OVERLAP(*result, a); result->append(a.data(), a.size()); } void StrAppend(string *result, const AlphaNum &a, const AlphaNum &b) { DCHECK_NO_OVERLAP(*result, a); DCHECK_NO_OVERLAP(*result, b); string::size_type old_size = result->size(); STLStringResizeUninitializedAmortized(result, old_size + a.size() + b.size()); char *const begin = &*result->begin(); char *out = Append2(begin + old_size, a, b); DCHECK_EQ(out, begin + result->size()); } void StrAppend(string *result, const AlphaNum &a, const AlphaNum &b, const AlphaNum &c) { DCHECK_NO_OVERLAP(*result, a); DCHECK_NO_OVERLAP(*result, b); DCHECK_NO_OVERLAP(*result, c); string::size_type old_size = result->size(); STLStringResizeUninitializedAmortized( result, old_size + a.size() + b.size() + c.size()); char *const begin = &*result->begin(); char *out = Append2(begin + old_size, a, b); out = Append1(out, c); DCHECK_EQ(out, begin + result->size()); } void StrAppend(string *result, const AlphaNum &a, const AlphaNum &b, const AlphaNum &c, const AlphaNum &d) { DCHECK_NO_OVERLAP(*result, a); DCHECK_NO_OVERLAP(*result, b); DCHECK_NO_OVERLAP(*result, c); DCHECK_NO_OVERLAP(*result, d); string::size_type old_size = result->size(); STLStringResizeUninitializedAmortized( result, old_size + a.size() + b.size() + c.size() + d.size()); char *const begin = &*result->begin(); char *out = Append4(begin + old_size, a, b, c, d); DCHECK_EQ(out, begin + result->size()); } } }
#include "tsl/platform/strcat.h" #include <string> #include "absl/strings/string_view.h" #include "tsl/platform/stringprintf.h" #include "tsl/platform/test.h" #include "tsl/platform/types.h" #ifdef _MSC_VER typedef ptrdiff_t ssize_t; #endif namespace tsl { namespace strings { TEST(StrCat, Ints) { const int16_t s = -1; const uint16 us = 2; const int i = -3; const unsigned int ui = 4; const int32_t l = -5; const uint32 ul = 6; const int64_t ll = -7; const uint64 ull = 8; const ptrdiff_t ptrdiff = -9; const size_t size = 10; const ssize_t ssize = -11; const intptr_t intptr = -12; const uintptr_t uintptr = 13; string answer; answer = StrCat(s, us); EXPECT_EQ(answer, "-12"); answer = StrCat(i, ui); EXPECT_EQ(answer, "-34"); answer = StrCat(l, ul); EXPECT_EQ(answer, "-56"); answer = StrCat(ll, ull); EXPECT_EQ(answer, "-78"); answer = StrCat(ptrdiff, size); EXPECT_EQ(answer, "-910"); answer = StrCat(ssize, intptr); EXPECT_EQ(answer, "-11-12"); answer = StrCat(uintptr, 0); EXPECT_EQ(answer, "130"); } TEST(StrCat, Floats) { const int s = 0; const float f = 1.5f; const double d = 1.5; const bfloat16 bf(1.5f); string answer; answer = StrCat(s, f); EXPECT_EQ(answer, "01.5"); answer = StrCat(s, d); EXPECT_EQ(answer, "01.5"); answer = StrCat(s, bf); EXPECT_EQ(answer, "01.5"); } TEST(StrCat, Nulls) { string result; absl::string_view v; string strs[] = {"Hello", "Cruel", "World"}; result = StrCat(v); EXPECT_EQ(result, ""); result = StrCat(strs[0], v); EXPECT_EQ(result, "Hello"); result = StrCat(v, strs[0]); EXPECT_EQ(result, "Hello"); result = StrCat(v, strs[0], strs[1]); EXPECT_EQ(result, "HelloCruel"); result = StrCat(strs[0], v, strs[1]); EXPECT_EQ(result, "HelloCruel"); result = StrCat(strs[0], strs[1], v); EXPECT_EQ(result, "HelloCruel"); result = StrCat(v, strs[0], strs[1], strs[2]); EXPECT_EQ(result, "HelloCruelWorld"); result = StrCat(strs[0], v, strs[1], strs[2]); EXPECT_EQ(result, "HelloCruelWorld"); result = StrCat(strs[0], strs[1], v, strs[2]); EXPECT_EQ(result, "HelloCruelWorld"); result = StrCat(strs[0], strs[1], strs[2], v); EXPECT_EQ(result, "HelloCruelWorld"); } TEST(StrCat, Basics) { string result; string strs[] = {"Hello", "Cruel", "World"}; StringPiece pieces[] = {"Hello", "Cruel", "World"}; const char *c_strs[] = {"Hello", "Cruel", "World"}; int32 i32s[] = {'H', 'C', 'W'}; uint64 ui64s[] = {12345678910LL, 10987654321LL}; result = StrCat(false, true, 2, 3); EXPECT_EQ(result, "0123"); result = StrCat(-1); EXPECT_EQ(result, "-1"); result = StrCat(0.5); EXPECT_EQ(result, "0.5"); result = StrCat(strs[1], pieces[2]); EXPECT_EQ(result, "CruelWorld"); result = StrCat(strs[0], ", ", pieces[2]); EXPECT_EQ(result, "Hello, World"); result = StrCat(strs[0], ", ", strs[1], " ", strs[2], "!"); EXPECT_EQ(result, "Hello, Cruel World!"); result = StrCat(pieces[0], ", ", pieces[1], " ", pieces[2]); EXPECT_EQ(result, "Hello, Cruel World"); result = StrCat(c_strs[0], ", ", c_strs[1], " ", c_strs[2]); EXPECT_EQ(result, "Hello, Cruel World"); result = StrCat("ASCII ", i32s[0], ", ", i32s[1], " ", i32s[2], "!"); EXPECT_EQ(result, "ASCII 72, 67 87!"); result = StrCat(ui64s[0], ", ", ui64s[1], "!"); EXPECT_EQ(result, "12345678910, 10987654321!"); string one = "1"; result = StrCat("And a ", one.size(), " and a ", &result[2] - &result[0], " and a ", one, " 2 3 4", "!"); EXPECT_EQ(result, "And a 1 and a 2 and a 1 2 3 4!"); result = StrCat("To output a char by ASCII/numeric value, use +: ", '!' + 0); EXPECT_EQ(result, "To output a char by ASCII/numeric value, use +: 33"); float f = 100000.5; result = StrCat("A hundred K and a half is ", f); EXPECT_EQ(result, "A hundred K and a half is 100000.5"); double d = f; d *= d; result = StrCat("A hundred K and a half squared is ", d); EXPECT_EQ(result, "A hundred K and a half squared is 10000100000.25"); result = StrCat(1, 2, 333, 4444, 55555, 666666, 7777777, 88888888, 999999999); EXPECT_EQ(result, "12333444455555666666777777788888888999999999"); } TEST(StrCat, MaxArgs) { string result; result = StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, "a"); EXPECT_EQ(result, "123456789a"); result = StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b"); EXPECT_EQ(result, "123456789ab"); result = StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c"); EXPECT_EQ(result, "123456789abc"); result = StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d"); EXPECT_EQ(result, "123456789abcd"); result = StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e"); EXPECT_EQ(result, "123456789abcde"); result = StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e", "f"); EXPECT_EQ(result, "123456789abcdef"); result = StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e", "f", "g"); EXPECT_EQ(result, "123456789abcdefg"); result = StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e", "f", "g", "h"); EXPECT_EQ(result, "123456789abcdefgh"); result = StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e", "f", "g", "h", "i"); EXPECT_EQ(result, "123456789abcdefghi"); result = StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e", "f", "g", "h", "i", "j"); EXPECT_EQ(result, "123456789abcdefghij"); result = StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k"); EXPECT_EQ(result, "123456789abcdefghijk"); result = StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l"); EXPECT_EQ(result, "123456789abcdefghijkl"); result = StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m"); EXPECT_EQ(result, "123456789abcdefghijklm"); result = StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n"); EXPECT_EQ(result, "123456789abcdefghijklmn"); result = StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o"); EXPECT_EQ(result, "123456789abcdefghijklmno"); result = StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p"); EXPECT_EQ(result, "123456789abcdefghijklmnop"); result = StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q"); EXPECT_EQ(result, "123456789abcdefghijklmnopq"); result = StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"); EXPECT_EQ(result, "12345678910abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"); } TEST(StrAppend, Basics) { string result = "existing text"; string strs[] = {"Hello", "Cruel", "World"}; StringPiece pieces[] = {"Hello", "Cruel", "World"}; const char *c_strs[] = {"Hello", "Cruel", "World"}; int32 i32s[] = {'H', 'C', 'W'}; uint64 ui64s[] = {12345678910LL, 10987654321LL}; string::size_type old_size = result.size(); StrAppend(&result, strs[0]); EXPECT_EQ(result.substr(old_size), "Hello"); old_size = result.size(); StrAppend(&result, strs[1], pieces[2]); EXPECT_EQ(result.substr(old_size), "CruelWorld"); old_size = result.size(); StrAppend(&result, strs[0], ", ", pieces[2]); EXPECT_EQ(result.substr(old_size), "Hello, World"); old_size = result.size(); StrAppend(&result, strs[0], ", ", strs[1], " ", strs[2], "!"); EXPECT_EQ(result.substr(old_size), "Hello, Cruel World!"); old_size = result.size(); StrAppend(&result, pieces[0], ", ", pieces[1], " ", pieces[2]); EXPECT_EQ(result.substr(old_size), "Hello, Cruel World"); old_size = result.size(); StrAppend(&result, c_strs[0], ", ", c_strs[1], " ", c_strs[2]); EXPECT_EQ(result.substr(old_size), "Hello, Cruel World"); old_size = result.size(); StrAppend(&result, "ASCII ", i32s[0], ", ", i32s[1], " ", i32s[2], "!"); EXPECT_EQ(result.substr(old_size), "ASCII 72, 67 87!"); old_size = result.size(); StrAppend(&result, ui64s[0], ", ", ui64s[1], "!"); EXPECT_EQ(result.substr(old_size), "12345678910, 10987654321!"); string one = "1"; old_size = result.size(); StrAppend(&result, "And a ", one.size(), " and a ", &result[2] - &result[0], " and a ", one, " 2 3 4", "!"); EXPECT_EQ(result.substr(old_size), "And a 1 and a 2 and a 1 2 3 4!"); old_size = result.size(); StrAppend(&result, "To output a char by ASCII/numeric value, use +: ", '!' + 0); EXPECT_EQ(result.substr(old_size), "To output a char by ASCII/numeric value, use +: 33"); float f = 100000.5; old_size = result.size(); StrAppend(&result, "A hundred K and a half is ", f); EXPECT_EQ(result.substr(old_size), "A hundred K and a half is 100000.5"); double d = f; d *= d; old_size = result.size(); StrAppend(&result, "A hundred K and a half squared is ", d); EXPECT_EQ(result.substr(old_size), "A hundred K and a half squared is 10000100000.25"); old_size = result.size(); StrAppend(&result, 1, 22, 333, 4444, 55555, 666666, 7777777, 88888888, 9); EXPECT_EQ(result.substr(old_size), "1223334444555556666667777777888888889"); old_size = result.size(); StrAppend(&result, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "No limit thanks to C++11's variadic templates"); EXPECT_EQ(result.substr(old_size), "12345678910abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" "No limit thanks to C++11's variadic templates"); } TEST(StrAppend, Death) { string s = "self"; EXPECT_DEBUG_DEATH(StrAppend(&s, s.c_str() + 1), "Check failed:"); EXPECT_DEBUG_DEATH(StrAppend(&s, s), "Check failed:"); } static void CheckHex64(uint64 v) { string actual = StrCat(Hex(v, kZeroPad16)); string expected = Printf("%016llx", static_cast<unsigned long long>(v)); EXPECT_EQ(expected, actual) << " decimal value " << v; actual = StrCat(Hex(v, kZeroPad8)); expected = Printf("%08llx", static_cast<unsigned long long>(v)); EXPECT_EQ(expected, actual) << " decimal value " << v; actual = StrCat(Hex(v)); expected = Printf("%llx", static_cast<unsigned long long>(v)); EXPECT_EQ(expected, actual) << " decimal value " << v; } static void CheckHex32(uint32 v) { string actual = StrCat(Hex(v, kZeroPad8)); string expected = Printf("%08x", v); EXPECT_EQ(expected, actual) << " decimal value " << v; actual = StrCat(Hex(v)); expected = Printf("%x", v); EXPECT_EQ(expected, actual) << " decimal value " << v; } static void CheckHexSigned32(int32_t v) { string actual = StrCat(Hex(v, kZeroPad8)); string expected = Printf("%08x", v); EXPECT_EQ(expected, actual) << " decimal value " << v; actual = StrCat(Hex(v)); expected = Printf("%x", v); EXPECT_EQ(expected, actual) << " decimal value " << v; } static void TestFastPrints() { for (int i = 0; i < 10000; i++) { CheckHex64(i); CheckHex32(i); CheckHexSigned32(i); CheckHexSigned32(-i); } CheckHex64(0x123456789abcdef0ull); CheckHex32(0x12345678); int8_t minus_one_8bit = -1; EXPECT_EQ("ff", StrCat(Hex(minus_one_8bit))); int16_t minus_one_16bit = -1; EXPECT_EQ("ffff", StrCat(Hex(minus_one_16bit))); } TEST(Numbers, TestFunctionsMovedOverFromNumbersMain) { TestFastPrints(); } } }
2,601
cpp
google/tsl
hash
tsl/platform/hash.cc
tsl/platform/hash_test.cc
#ifndef TENSORFLOW_TSL_PLATFORM_HASH_H_ #define TENSORFLOW_TSL_PLATFORM_HASH_H_ #include <stddef.h> #include <stdint.h> #include <functional> #include <string> #include "tsl/platform/stringpiece.h" #include "tsl/platform/types.h" namespace tsl { extern uint32 Hash32(const char* data, size_t n, uint32 seed); extern uint64 Hash64(const char* data, size_t n, uint64 seed); inline uint64 Hash64(const char* data, size_t n) { return Hash64(data, n, 0xDECAFCAFFE); } inline uint64 Hash64(const char* data) { return Hash64(data, ::strlen(data)); } inline uint64 Hash64(const std::string& str) { return Hash64(str.data(), str.size()); } inline uint64 Hash64(const tstring& str) { return Hash64(str.data(), str.size()); } inline uint64 Hash64Combine(uint64 a, uint64 b) { return a ^ (b + 0x9e3779b97f4a7800ULL + (a << 10) + (a >> 4)); } inline uint64 Hash64CombineUnordered(uint64 a, uint64 b) { return a + b; } template <typename T, typename = void> struct hash { size_t operator()(const T& t) const { return std::hash<T>()(t); } }; template <typename T> struct hash<T, typename std::enable_if<std::is_enum<T>::value>::type> { size_t operator()(T value) const { return std::hash<uint64>()(static_cast<uint64>(value)); } }; template <typename T> struct hash<T*> { size_t operator()(const T* t) const { size_t k = static_cast<size_t>(reinterpret_cast<uintptr_t>(t)); return k + (k >> 6); } }; template <> struct hash<string> { size_t operator()(const string& s) const { return static_cast<size_t>(Hash64(s)); } }; template <> struct hash<tstring> { size_t operator()(const tstring& s) const { return static_cast<size_t>(Hash64(s.data(), s.size())); } }; template <> struct hash<StringPiece> { size_t operator()(StringPiece sp) const { return static_cast<size_t>(Hash64(sp.data(), sp.size())); } }; using StringPieceHasher = ::tsl::hash<StringPiece>; template <typename T, typename U> struct hash<std::pair<T, U>> { size_t operator()(const std::pair<T, U>& p) const { return Hash64Combine(hash<T>()(p.first), hash<U>()(p.second)); } }; } namespace std { template <> struct hash<tsl::tstring> { size_t operator()(const tsl::tstring& s) const { return static_cast<size_t>(tsl::Hash64(s.data(), s.size())); } }; } #endif #include "tsl/platform/hash.h" #include <string.h> #include "tsl/platform/macros.h" #include "tsl/platform/raw_coding.h" #include "tsl/platform/types.h" namespace tsl { static inline uint32 ByteAs32(char c) { return static_cast<uint32>(c) & 0xff; } static inline uint64 ByteAs64(char c) { return static_cast<uint64>(c) & 0xff; } uint32 Hash32(const char* data, size_t n, uint32 seed) { const uint32 m = 0x5bd1e995; const int r = 24; uint32 h = seed ^ n; while (n >= 4) { uint32 k = core::DecodeFixed32(data); k *= m; k ^= k >> r; k *= m; h *= m; h ^= k; data += 4; n -= 4; } switch (n) { case 3: h ^= ByteAs32(data[2]) << 16; TF_FALLTHROUGH_INTENDED; case 2: h ^= ByteAs32(data[1]) << 8; TF_FALLTHROUGH_INTENDED; case 1: h ^= ByteAs32(data[0]); h *= m; } h ^= h >> 13; h *= m; h ^= h >> 15; return h; } uint64 Hash64(const char* data, size_t n, uint64 seed) { const uint64 m = 0xc6a4a7935bd1e995; const int r = 47; uint64 h = seed ^ (n * m); while (n >= 8) { uint64 k = core::DecodeFixed64(data); data += 8; n -= 8; k *= m; k ^= k >> r; k *= m; h ^= k; h *= m; } switch (n) { case 7: h ^= ByteAs64(data[6]) << 48; TF_FALLTHROUGH_INTENDED; case 6: h ^= ByteAs64(data[5]) << 40; TF_FALLTHROUGH_INTENDED; case 5: h ^= ByteAs64(data[4]) << 32; TF_FALLTHROUGH_INTENDED; case 4: h ^= ByteAs64(data[3]) << 24; TF_FALLTHROUGH_INTENDED; case 3: h ^= ByteAs64(data[2]) << 16; TF_FALLTHROUGH_INTENDED; case 2: h ^= ByteAs64(data[1]) << 8; TF_FALLTHROUGH_INTENDED; case 1: h ^= ByteAs64(data[0]); h *= m; } h ^= h >> r; h *= m; h ^= h >> r; return h; } }
#include <map> #include <unordered_map> #include <vector> #include "tsl/platform/hash.h" #include "tsl/platform/logging.h" #include "tsl/platform/test.h" #include "tsl/platform/test_benchmark.h" namespace tsl { TEST(Hash, SignedUnsignedIssue) { const unsigned char d1[1] = {0x62}; const unsigned char d2[2] = {0xc3, 0x97}; const unsigned char d3[3] = {0xe2, 0x99, 0xa5}; const unsigned char d4[4] = {0xe1, 0x80, 0xb9, 0x32}; const unsigned char d5[48] = { 0x01, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x18, 0x28, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; struct Case { uint32 hash32; uint64 hash64; const unsigned char* data; size_t size; uint32 seed; }; for (Case c : std::vector<Case>{ {0x471a8188u, 0x4c61ea3eeda4cb87ull, nullptr, 0, 0xbc9f1d34}, {0xd615eba5u, 0x091309f7ef916c8aull, d1, sizeof(d1), 0xbc9f1d34}, {0x0c3cccdau, 0xa815bcdf1d1af01cull, d2, sizeof(d2), 0xbc9f1d34}, {0x3ba37e0eu, 0x02167564e4d06430ull, d3, sizeof(d3), 0xbc9f1d34}, {0x16174eb3u, 0x8f7ed82ffc21071full, d4, sizeof(d4), 0xbc9f1d34}, {0x98b1926cu, 0xce196580c97aff1eull, d5, sizeof(d5), 0x12345678}, }) { EXPECT_EQ(c.hash32, Hash32(reinterpret_cast<const char*>(c.data), c.size, c.seed)); EXPECT_EQ(c.hash64, Hash64(reinterpret_cast<const char*>(c.data), c.size, c.seed)); for (int align = 1; align <= 7; align++) { std::string input(align, 'x'); input.append(reinterpret_cast<const char*>(c.data), c.size); EXPECT_EQ(c.hash32, Hash32(&input[align], c.size, c.seed)); EXPECT_EQ(c.hash64, Hash64(&input[align], c.size, c.seed)); } } } TEST(Hash, HashPtrIsNotIdentityFunction) { int* ptr = reinterpret_cast<int*>(0xcafe0000); EXPECT_NE(hash<int*>()(ptr), size_t{0xcafe0000}); } static void BM_Hash32(::testing::benchmark::State& state) { int len = state.range(0); std::string input(len, 'x'); uint32 h = 0; for (auto s : state) { h = Hash32(input.data(), len, 1); } state.SetBytesProcessed(state.iterations() * len); VLOG(1) << h; } BENCHMARK(BM_Hash32)->Range(1, 1024); TEST(StringPieceHasher, Equality) { StringPieceHasher hasher; StringPiece s1("foo"); StringPiece s2("bar"); StringPiece s3("baz"); StringPiece s4("zot"); EXPECT_TRUE(hasher(s1) != hasher(s2)); EXPECT_TRUE(hasher(s1) != hasher(s3)); EXPECT_TRUE(hasher(s1) != hasher(s4)); EXPECT_TRUE(hasher(s2) != hasher(s3)); EXPECT_TRUE(hasher(s2) != hasher(s4)); EXPECT_TRUE(hasher(s3) != hasher(s4)); EXPECT_TRUE(hasher(s1) == hasher(s1)); EXPECT_TRUE(hasher(s2) == hasher(s2)); EXPECT_TRUE(hasher(s3) == hasher(s3)); EXPECT_TRUE(hasher(s4) == hasher(s4)); } TEST(StringPieceHasher, HashMap) { string s1("foo"); string s2("bar"); string s3("baz"); StringPiece p1(s1); StringPiece p2(s2); StringPiece p3(s3); std::unordered_map<StringPiece, int, StringPieceHasher> map; map.insert(std::make_pair(p1, 0)); map.insert(std::make_pair(p2, 1)); map.insert(std::make_pair(p3, 2)); EXPECT_EQ(map.size(), 3); bool found[3] = {false, false, false}; for (auto const& val : map) { int x = val.second; EXPECT_TRUE(x >= 0 && x < 3); EXPECT_TRUE(!found[x]); found[x] = true; } EXPECT_EQ(found[0], true); EXPECT_EQ(found[1], true); EXPECT_EQ(found[2], true); auto new_iter = map.find("zot"); EXPECT_TRUE(new_iter == map.end()); new_iter = map.find("bar"); EXPECT_TRUE(new_iter != map.end()); map.erase(new_iter); EXPECT_EQ(map.size(), 2); found[0] = false; found[1] = false; found[2] = false; for (const auto& iter : map) { int x = iter.second; EXPECT_TRUE(x >= 0 && x < 3); EXPECT_TRUE(!found[x]); found[x] = true; } EXPECT_EQ(found[0], true); EXPECT_EQ(found[1], false); EXPECT_EQ(found[2], true); } }
2,602
cpp
google/tsl
setround
tsl/platform/setround.cc
tsl/platform/setround_test.cc
#ifndef TENSORFLOW_TSL_PLATFORM_SETROUND_H_ #define TENSORFLOW_TSL_PLATFORM_SETROUND_H_ #if defined(__ANDROID_API__) && (__ANDROID_API__ < 21) #define TF_BROKEN_CFENV #endif #if defined(TF_BROKEN_CFENV) #include <fenv.h> #else #include <cfenv> #endif #include "tsl/platform/macros.h" namespace tsl { namespace port { class ScopedSetRound { public: ScopedSetRound(int mode); ~ScopedSetRound(); private: int original_mode_; ScopedSetRound(const ScopedSetRound&) = delete; void operator=(const ScopedSetRound&) = delete; }; } } #endif #include "tsl/platform/setround.h" #include "tsl/platform/logging.h" namespace tsl { namespace port { #if defined(TF_BROKEN_CFENV) ScopedSetRound::ScopedSetRound(const int mode) : original_mode_(mode) { DCHECK_EQ(mode, FE_TONEAREST); } ScopedSetRound::~ScopedSetRound() {} #else ScopedSetRound::ScopedSetRound(const int mode) { original_mode_ = std::fegetround(); if (original_mode_ < 0) { original_mode_ = FE_TONEAREST; } std::fesetround(mode); } ScopedSetRound::~ScopedSetRound() { std::fesetround(original_mode_); } #endif } }
#include "tsl/platform/setround.h" #include <cmath> #include "tsl/platform/test.h" #if !defined(__clang__) || !defined(__OPTIMIZE__) namespace tsl { namespace { void CheckDownward() { EXPECT_EQ(12, std::nearbyint(12.0)); EXPECT_EQ(12, std::nearbyint(12.1)); EXPECT_EQ(-13, std::nearbyint(-12.1)); EXPECT_EQ(12, std::nearbyint(12.5)); EXPECT_EQ(12, std::nearbyint(12.9)); EXPECT_EQ(-13, std::nearbyint(-12.9)); EXPECT_EQ(13, std::nearbyint(13.0)); } void CheckToNearest() { EXPECT_EQ(12, std::nearbyint(12.0)); EXPECT_EQ(12, std::nearbyint(12.1)); EXPECT_EQ(-12, std::nearbyint(-12.1)); EXPECT_EQ(12, std::nearbyint(12.5)); EXPECT_EQ(13, std::nearbyint(12.9)); EXPECT_EQ(-13, std::nearbyint(-12.9)); EXPECT_EQ(13, std::nearbyint(13.0)); } void CheckTowardZero() { EXPECT_EQ(12, std::nearbyint(12.0)); EXPECT_EQ(12, std::nearbyint(12.1)); EXPECT_EQ(-12, std::nearbyint(-12.1)); EXPECT_EQ(12, std::nearbyint(12.5)); EXPECT_EQ(12, std::nearbyint(12.9)); EXPECT_EQ(-12, std::nearbyint(-12.9)); EXPECT_EQ(13, std::nearbyint(13.0)); } void CheckUpward() { EXPECT_EQ(12, std::nearbyint(12.0)); EXPECT_EQ(13, std::nearbyint(12.1)); EXPECT_EQ(-12, std::nearbyint(-12.1)); EXPECT_EQ(13, std::nearbyint(12.5)); EXPECT_EQ(13, std::nearbyint(12.9)); EXPECT_EQ(-12, std::nearbyint(-12.9)); EXPECT_EQ(13, std::nearbyint(13.0)); } TEST(SetScopedSetRound, Downward) { port::ScopedSetRound round(FE_DOWNWARD); CheckDownward(); } TEST(SetScopedSetRound, ToNearest) { port::ScopedSetRound round(FE_TONEAREST); CheckToNearest(); } TEST(SetScopedSetRound, TowardZero) { port::ScopedSetRound round(FE_TOWARDZERO); CheckTowardZero(); } TEST(SetScopedSetRound, Upward) { port::ScopedSetRound round(FE_UPWARD); CheckUpward(); } TEST(SetScopedSetRound, Scoped) { std::fesetround(FE_TONEAREST); CheckToNearest(); { port::ScopedSetRound round(FE_UPWARD); CheckUpward(); } CheckToNearest(); } } } #endif
2,603
cpp
google/tsl
path
tsl/platform/path.cc
tsl/platform/path_test.cc
#ifndef TENSORFLOW_TSL_PLATFORM_PATH_H_ #define TENSORFLOW_TSL_PLATFORM_PATH_H_ #include <string> #include "tsl/platform/stringpiece.h" #include "tsl/platform/types.h" namespace tsl { namespace io { namespace internal { std::string JoinPathImpl(std::initializer_list<tsl::StringPiece> paths); } #ifndef SWIG template <typename... T> std::string JoinPath(const T&... args) { return internal::JoinPathImpl({args...}); } #endif bool IsAbsolutePath(tsl::StringPiece path); tsl::StringPiece Dirname(tsl::StringPiece path); tsl::StringPiece Basename(tsl::StringPiece path); tsl::StringPiece Extension(tsl::StringPiece path); tsl::StringPiece BasenamePrefix(tsl::StringPiece path); std::string CommonPathPrefix(absl::Span<std::string const> paths); std::string CleanPath(tsl::StringPiece path); void ParseURI(tsl::StringPiece uri, tsl::StringPiece* scheme, tsl::StringPiece* host, tsl::StringPiece* path); std::string CreateURI(tsl::StringPiece scheme, tsl::StringPiece host, tsl::StringPiece path); std::string GetTempFilename(const std::string& extension); bool GetTestWorkspaceDir(std::string* dir); bool GetTestUndeclaredOutputsDir(std::string* dir); bool ResolveTestPrefixes(tsl::StringPiece path, std::string& resolved_path); [[maybe_unused]] std::string& AppendDotExeIfWindows(std::string& path); } } #endif #include "tsl/platform/path.h" #include <errno.h> #include <fcntl.h> #include <stdlib.h> #include <sys/stat.h> #include <sys/types.h> #if defined(PLATFORM_WINDOWS) #include <windows.h> #else #include <unistd.h> #endif #include <string> #include <vector> #include "absl/algorithm/container.h" #include "tsl/platform/logging.h" #include "tsl/platform/mutex.h" #include "tsl/platform/scanner.h" #include "tsl/platform/str_util.h" #include "tsl/platform/strcat.h" #include "tsl/platform/stringpiece.h" #include "tsl/platform/types.h" namespace tsl { namespace io { namespace internal { namespace { const char kPathSep[] = "/"; } string JoinPathImpl(std::initializer_list<StringPiece> paths) { string result; for (StringPiece path : paths) { if (path.empty()) continue; if (result.empty()) { result = string(path); continue; } if (IsAbsolutePath(path)) path = path.substr(1); if (result[result.size() - 1] == kPathSep[0]) { strings::StrAppend(&result, path); } else { strings::StrAppend(&result, kPathSep, path); } } return result; } std::pair<StringPiece, StringPiece> SplitPath(StringPiece uri) { StringPiece scheme, host, path; ParseURI(uri, &scheme, &host, &path); auto pos = path.rfind('/'); #ifdef PLATFORM_WINDOWS if (pos == StringPiece::npos) pos = path.rfind('\\'); #endif if (pos == StringPiece::npos) return std::make_pair(StringPiece(uri.data(), host.end() - uri.begin()), path); if (pos == 0) return std::make_pair( StringPiece(uri.data(), path.begin() + 1 - uri.begin()), StringPiece(path.data() + 1, path.size() - 1)); return std::make_pair( StringPiece(uri.data(), path.begin() + pos - uri.begin()), StringPiece(path.data() + pos + 1, path.size() - (pos + 1))); } std::pair<StringPiece, StringPiece> SplitBasename(StringPiece path) { path = Basename(path); auto pos = path.rfind('.'); if (pos == StringPiece::npos) return std::make_pair(path, StringPiece(path.data() + path.size(), 0)); return std::make_pair( StringPiece(path.data(), pos), StringPiece(path.data() + pos + 1, path.size() - (pos + 1))); } } bool IsAbsolutePath(StringPiece path) { return !path.empty() && path[0] == '/'; } StringPiece Dirname(StringPiece path) { return internal::SplitPath(path).first; } StringPiece Basename(StringPiece path) { return internal::SplitPath(path).second; } StringPiece Extension(StringPiece path) { return internal::SplitBasename(path).second; } StringPiece BasenamePrefix(StringPiece path) { return internal::SplitBasename(path).first; } string CleanPath(StringPiece unclean_path) { string path(unclean_path); const char* src = path.c_str(); string::iterator dst = path.begin(); const bool is_absolute_path = *src == '/'; if (is_absolute_path) { *dst++ = *src++; while (*src == '/') ++src; } string::const_iterator backtrack_limit = dst; while (*src) { bool parsed = false; if (src[0] == '.') { if (src[1] == '/' || !src[1]) { if (*++src) { ++src; } parsed = true; } else if (src[1] == '.' && (src[2] == '/' || !src[2])) { src += 2; if (dst != backtrack_limit) { for (--dst; dst != backtrack_limit && dst[-1] != '/'; --dst) { } } else if (!is_absolute_path) { src -= 2; *dst++ = *src++; *dst++ = *src++; if (*src) { *dst++ = *src; } backtrack_limit = dst; } if (*src) { ++src; } parsed = true; } } if (!parsed) { while (*src && *src != '/') { *dst++ = *src++; } if (*src) { *dst++ = *src++; } } while (*src == '/') { ++src; } } string::difference_type path_length = dst - path.begin(); if (path_length != 0) { if (path_length > 1 && path[path_length - 1] == '/') { --path_length; } path.resize(path_length); } else { path.assign(1, '.'); } return path; } void ParseURI(StringPiece uri, StringPiece* scheme, StringPiece* host, StringPiece* path) { if (!strings::Scanner(uri) .One(strings::Scanner::LETTER) .Many(strings::Scanner::LETTER_DIGIT_DOT) .StopCapture() .OneLiteral(": .GetResult(&uri, scheme)) { *scheme = StringPiece(uri.data(), 0); *host = StringPiece(uri.data(), 0); *path = uri; return; } if (!strings::Scanner(uri).ScanUntil('/').GetResult(&uri, host)) { *host = uri; *path = StringPiece(); return; } *path = uri; } string CreateURI(StringPiece scheme, StringPiece host, StringPiece path) { if (scheme.empty()) { return string(path); } return strings::StrCat(scheme, ": } int64_t UniqueId() { static mutex mu(LINKER_INITIALIZED); static int64_t id = 0; mutex_lock l(mu); return ++id; } string CommonPathPrefix(absl::Span<const string> paths) { if (paths.empty()) return ""; size_t min_filename_size = absl::c_min_element(paths, [](const string& a, const string& b) { return a.size() < b.size(); })->size(); if (min_filename_size == 0) return ""; size_t common_prefix_size = [&] { for (size_t prefix_size = 0; prefix_size < min_filename_size; prefix_size++) { char c = paths[0][prefix_size]; for (int f = 1; f < paths.size(); f++) { if (paths[f][prefix_size] != c) { return prefix_size; } } } return min_filename_size; }(); size_t rpos = absl::string_view(paths[0]) .substr(0, common_prefix_size) .rfind(internal::kPathSep); return rpos == std::string::npos ? "" : std::string(absl::string_view(paths[0]).substr(0, rpos + 1)); } string GetTempFilename(const string& extension) { #if defined(__ANDROID__) LOG(FATAL) << "GetTempFilename is not implemented in this platform."; #elif defined(PLATFORM_WINDOWS) char temp_dir[_MAX_PATH]; DWORD retval; retval = GetTempPath(_MAX_PATH, temp_dir); if (retval > _MAX_PATH || retval == 0) { LOG(FATAL) << "Cannot get the directory for temporary files."; } char temp_file_name[_MAX_PATH]; retval = GetTempFileName(temp_dir, "", UniqueId(), temp_file_name); if (retval > _MAX_PATH || retval == 0) { LOG(FATAL) << "Cannot get a temporary file in: " << temp_dir; } string full_tmp_file_name(temp_file_name); full_tmp_file_name.append(extension); return full_tmp_file_name; #else for (const char* dir : std::vector<const char*>( {getenv("TEST_TMPDIR"), getenv("TMPDIR"), getenv("TMP"), "/tmp"})) { if (!dir || !dir[0]) { continue; } struct stat statbuf; if (!stat(dir, &statbuf) && S_ISDIR(statbuf.st_mode)) { string tmp_filepath; int fd; if (extension.length()) { tmp_filepath = io::JoinPath( dir, strings::StrCat("tmp_file_tensorflow_", UniqueId(), "_XXXXXX.", extension)); fd = mkstemps(&tmp_filepath[0], extension.length() + 1); } else { tmp_filepath = io::JoinPath( dir, strings::StrCat("tmp_file_tensorflow_", UniqueId(), "_XXXXXX")); fd = mkstemp(&tmp_filepath[0]); } if (fd < 0) { LOG(FATAL) << "Failed to create temp file."; } else { if (close(fd) < 0) { LOG(ERROR) << "close() failed: " << strerror(errno); } return tmp_filepath; } } } LOG(FATAL) << "No temp directory found."; std::abort(); #endif } namespace { bool StartsWithSegment(tsl::StringPiece path, tsl::StringPiece segment) { return tsl::str_util::StartsWith(path, segment) && (path.size() == segment.size() || path.at(segment.size()) == internal::kPathSep[0]); } } bool GetTestWorkspaceDir(string* dir) { const char* srcdir = getenv("TEST_SRCDIR"); if (srcdir == nullptr) { return false; } const char* workspace = getenv("TEST_WORKSPACE"); if (workspace == nullptr) { return false; } if (dir != nullptr) { *dir = tsl::io::JoinPath(srcdir, workspace); } return true; } bool GetTestUndeclaredOutputsDir(string* dir) { const char* outputs_dir = getenv("TEST_UNDECLARED_OUTPUTS_DIR"); if (outputs_dir == nullptr) { return false; } if (dir != nullptr) { *dir = outputs_dir; } return true; } bool ResolveTestPrefixes(tsl::StringPiece path, string& resolved_path) { constexpr tsl::StringPiece kTestWorkspaceSegment = "TEST_WORKSPACE"; constexpr tsl::StringPiece kOutputDirSegment = "TEST_UNDECLARED_OUTPUTS_DIR"; if (StartsWithSegment(path, kTestWorkspaceSegment)) { if (!GetTestWorkspaceDir(&resolved_path)) { return false; } resolved_path += path.substr(kTestWorkspaceSegment.size()); return true; } else if (StartsWithSegment(path, kOutputDirSegment)) { if (!GetTestUndeclaredOutputsDir(&resolved_path)) { return false; } resolved_path += path.substr(kOutputDirSegment.size()); return true; } else { resolved_path = path; return true; } } [[maybe_unused]] std::string& AppendDotExeIfWindows(std::string& path) { #ifdef PLATFORM_WINDOWS path.append(".exe"); #endif return path; } } }
#include "tsl/platform/path.h" #include <string> #include "tsl/platform/env.h" #include "tsl/platform/stringpiece.h" #include "tsl/platform/test.h" namespace tsl { namespace io { TEST(PathTest, JoinPath) { EXPECT_EQ("/foo/bar", JoinPath("/foo", "bar")); EXPECT_EQ("foo/bar", JoinPath("foo", "bar")); EXPECT_EQ("foo/bar", JoinPath("foo", "/bar")); EXPECT_EQ("/foo/bar", JoinPath("/foo", "/bar")); EXPECT_EQ("/bar", JoinPath("", "/bar")); EXPECT_EQ("bar", JoinPath("", "bar")); EXPECT_EQ("/foo", JoinPath("/foo", "")); EXPECT_EQ("/foo/bar/baz/blah/blink/biz", JoinPath("/foo/bar/baz/", "/blah/blink/biz")); EXPECT_EQ("/foo/bar/baz/blah", JoinPath("/foo", "bar", "baz", "blah")); } TEST(PathTest, IsAbsolutePath) { EXPECT_FALSE(IsAbsolutePath("")); EXPECT_FALSE(IsAbsolutePath("../foo")); EXPECT_FALSE(IsAbsolutePath("foo")); EXPECT_FALSE(IsAbsolutePath("./foo")); EXPECT_FALSE(IsAbsolutePath("foo/bar/baz/")); EXPECT_TRUE(IsAbsolutePath("/foo")); EXPECT_TRUE(IsAbsolutePath("/foo/bar/../baz")); } TEST(PathTest, Dirname) { EXPECT_EQ("hdfs: Dirname("hdfs: EXPECT_EQ("/hello", Dirname("/hello/")); EXPECT_EQ("/", Dirname("/hello")); EXPECT_EQ("hello", Dirname("hello/world")); EXPECT_EQ("hello", Dirname("hello/")); EXPECT_EQ("", Dirname("world")); EXPECT_EQ("/", Dirname("/")); EXPECT_EQ("", Dirname("")); } TEST(PathTest, Basename) { EXPECT_EQ("", Basename("/hello/")); EXPECT_EQ("hello", Basename("/hello")); EXPECT_EQ("world", Basename("hello/world")); EXPECT_EQ("", Basename("hello/")); EXPECT_EQ("world", Basename("world")); EXPECT_EQ("", Basename("/")); EXPECT_EQ("", Basename("")); } TEST(PathTest, Extension) { EXPECT_EQ("gif", Extension("foo.gif")); EXPECT_EQ("", Extension("foo.")); EXPECT_EQ("", Extension("")); EXPECT_EQ("", Extension("/")); EXPECT_EQ("", Extension("foo")); EXPECT_EQ("", Extension("foo/")); EXPECT_EQ("gif", Extension("/a/path/to/foo.gif")); EXPECT_EQ("html", Extension("/a/path.bar/to/foo.html")); EXPECT_EQ("", Extension("/a/path.bar/to/foo")); EXPECT_EQ("baz", Extension("/a/path.bar/to/foo.bar.baz")); } TEST(PathTest, CleanPath) { EXPECT_EQ(".", CleanPath("")); EXPECT_EQ("x", CleanPath("x")); EXPECT_EQ("/a/b/c/d", CleanPath("/a/b/c/d")); EXPECT_EQ("/a/b/c/dtrue); tsl::setenv("TEST_WORKSPACE", "my/workspace", true); EXPECT_TRUE(GetTestWorkspaceDir(&dir)); EXPECT_EQ(dir, "/repo/src/my/workspace"); EXPECT_TRUE(GetTestWorkspaceDir(nullptr)); dir = kOriginalValue; tsl::unsetenv("TEST_SRCDIR"); tsl::setenv("TEST_WORKSPACE", "my/workspace", true); EXPECT_FALSE(GetTestWorkspaceDir(&dir)); EXPECT_EQ(dir, kOriginalValue); EXPECT_FALSE(GetTestWorkspaceDir(nullptr)); dir = kOriginalValue; tsl::setenv("TEST_SRCDIR", "/repo/src", true); tsl::unsetenv("TEST_WORKSPACE"); EXPECT_FALSE(GetTestWorkspaceDir(&dir)); EXPECT_EQ(dir, kOriginalValue); EXPECT_FALSE(GetTestWorkspaceDir(nullptr)); dir = kOriginalValue; tsl::unsetenv("TEST_SRCDIR"); tsl::unsetenv("TEST_WORKSPACE"); EXPECT_FALSE(GetTestWorkspaceDir(&dir)); EXPECT_EQ(dir, kOriginalValue); EXPECT_FALSE(GetTestWorkspaceDir(nullptr)); } TEST(PathTest, GetTestUndeclaredOutputsDir) { constexpr tsl::StringPiece kOriginalValue = "original value"; std::string dir; dir = kOriginalValue; tsl::setenv("TEST_UNDECLARED_OUTPUTS_DIR", "/test/outputs", true); EXPECT_TRUE(GetTestUndeclaredOutputsDir(&dir)); EXPECT_EQ(dir, "/test/outputs"); EXPECT_TRUE(GetTestUndeclaredOutputsDir(nullptr)); dir = kOriginalValue; tsl::unsetenv("TEST_UNDECLARED_OUTPUTS_DIR"); EXPECT_FALSE(GetTestUndeclaredOutputsDir(&dir)); EXPECT_EQ(dir, kOriginalValue); EXPECT_FALSE(GetTestUndeclaredOutputsDir(nullptr)); } TEST(PathTest, ResolveTestPrefixesKeepsThePathUnchanged) { constexpr tsl::StringPiece kOriginalValue = "original value"; std::string resolved_path; resolved_path = kOriginalValue; EXPECT_TRUE(ResolveTestPrefixes("", resolved_path)); EXPECT_EQ(resolved_path, ""); resolved_path = kOriginalValue; EXPECT_TRUE(ResolveTestPrefixes("/", resolved_path)); EXPECT_EQ(resolved_path, "/"); resolved_path = kOriginalValue; EXPECT_TRUE(ResolveTestPrefixes("alpha/beta", resolved_path)); EXPECT_EQ(resolved_path, "alpha/beta"); resolved_path = kOriginalValue; EXPECT_TRUE(ResolveTestPrefixes("/alpha/beta", resolved_path)); EXPECT_EQ(resolved_path, "/alpha/beta"); } TEST(PathTest, ResolveTestPrefixesCanResolveTestWorkspace) { constexpr tsl::StringPiece kOriginalValue = "original value"; std::string resolved_path; tsl::setenv("TEST_SRCDIR", "/repo/src", true); tsl::setenv("TEST_WORKSPACE", "my/workspace", true); resolved_path = kOriginalValue; EXPECT_TRUE(ResolveTestPrefixes("TEST_WORKSPACE", resolved_path)); EXPECT_EQ(resolved_path, "/repo/src/my/workspace"); resolved_path = kOriginalValue; EXPECT_TRUE(ResolveTestPrefixes("TEST_WORKSPACE/", resolved_path)); EXPECT_EQ(resolved_path, "/repo/src/my/workspace/"); resolved_path = kOriginalValue; EXPECT_TRUE(ResolveTestPrefixes("TEST_WORKSPACE/a/b", resolved_path)); EXPECT_EQ(resolved_path, "/repo/src/my/workspace/a/b"); resolved_path = kOriginalValue; EXPECT_TRUE(ResolveTestPrefixes("TEST_WORKSPACEE", resolved_path)); EXPECT_EQ(resolved_path, "TEST_WORKSPACEE"); resolved_path = kOriginalValue; EXPECT_TRUE(ResolveTestPrefixes("/TEST_WORKSPACE", resolved_path)); EXPECT_EQ(resolved_path, "/TEST_WORKSPACE"); } TEST(PathTest, ResolveTestPrefixesCannotResolveTestWorkspace) { constexpr tsl::StringPiece kOriginalValue = "original value"; std::string resolved_path; tsl::unsetenv("TEST_SRCDIR"); tsl::unsetenv("TEST_WORKSPACE"); resolved_path = kOriginalValue; EXPECT_FALSE(ResolveTestPrefixes("TEST_WORKSPACE", resolved_path)); EXPECT_EQ(resolved_path, kOriginalValue); } TEST(PathTest, ResolveTestPrefixesCanResolveTestUndeclaredOutputsDir) { constexpr tsl::StringPiece kOriginalValue = "original value"; std::string resolved_path; tsl::setenv("TEST_UNDECLARED_OUTPUTS_DIR", "/test/outputs", true); resolved_path = kOriginalValue; EXPECT_TRUE( ResolveTestPrefixes("TEST_UNDECLARED_OUTPUTS_DIR", resolved_path)); EXPECT_EQ(resolved_path, "/test/outputs"); resolved_path = kOriginalValue; EXPECT_TRUE( ResolveTestPrefixes("TEST_UNDECLARED_OUTPUTS_DIR/", resolved_path)); EXPECT_EQ(resolved_path, "/test/outputs/"); resolved_path = kOriginalValue; EXPECT_TRUE( ResolveTestPrefixes("TEST_UNDECLARED_OUTPUTS_DIR/a/b", resolved_path)); EXPECT_EQ(resolved_path, "/test/outputs/a/b"); resolved_path = kOriginalValue; EXPECT_TRUE( ResolveTestPrefixes("TEST_UNDECLARED_OUTPUTS_DIRR", resolved_path)); EXPECT_EQ(resolved_path, "TEST_UNDECLARED_OUTPUTS_DIRR"); resolved_path = kOriginalValue; EXPECT_TRUE( ResolveTestPrefixes("/TEST_UNDECLARED_OUTPUTS_DIR", resolved_path)); EXPECT_EQ(resolved_path, "/TEST_UNDECLARED_OUTPUTS_DIR"); } TEST(PathTest, ResolveTestPrefixesCannotResolveTestUndeclaredOutputsDir) { constexpr tsl::StringPiece kOriginalValue = "original value"; std::string resolved_path; tsl::unsetenv("TEST_UNDECLARED_OUTPUTS_DIR"); resolved_path = kOriginalValue; EXPECT_FALSE( ResolveTestPrefixes("TEST_UNDECLARED_OUTPUTS_DIR", resolved_path)); EXPECT_EQ(resolved_path, kOriginalValue); } } }
2,604
cpp
google/tsl
status
tsl/platform/status.cc
tsl/platform/status_test.cc
#ifndef TENSORFLOW_TSL_PLATFORM_DEFAULT_STATUS_H_ #define TENSORFLOW_TSL_PLATFORM_DEFAULT_STATUS_H_ #define MAYBE_ADD_SOURCE_LOCATION(status) \ {} #define ADD_SOURCE_LOCATION(status) status #endif #include "tsl/platform/status.h" #include <stdio.h> #include <deque> #include <functional> #include <memory> #include <ostream> #include <sstream> #include <string> #include <unordered_map> #include <utility> #include <vector> #include "absl/base/call_once.h" #include "absl/functional/function_ref.h" #include "absl/status/status.h" #include "absl/strings/cord.h" #include "absl/strings/escaping.h" #include "absl/strings/match.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_join.h" #include "absl/strings/str_replace.h" #include "absl/strings/str_split.h" #include "absl/strings/string_view.h" #include "absl/types/optional.h" #include "tsl/platform/mutex.h" #include "tsl/platform/stack_frame.h" #include "tsl/platform/stacktrace.h" #include "tsl/platform/str_util.h" #include "tsl/platform/strcat.h" #include "tsl/platform/stringprintf.h" #include "tsl/protobuf/error_codes.pb.h" namespace tsl { namespace { class StatusLogSink : public TFLogSink { public: static StatusLogSink* GetInstance() { static StatusLogSink* sink = new StatusLogSink(); return sink; } void enable() { absl::call_once(flag_, [this] { num_messages_ = 5; if (const char* num_msgs_str = getenv("TF_WORKER_NUM_FORWARDED_LOG_MESSAGES")) { if (!absl::SimpleAtoi(num_msgs_str, &num_messages_)) { LOG(WARNING) << "Failed to parse env variable " "TF_WORKER_NUM_WARNING_ERROR_LOG_IN_STATUS=" << num_msgs_str << " as int. Using the default value " << num_messages_ << "."; } } if (num_messages_ > 0) { TFAddLogSink(this); } }); } void GetMessages(std::vector<std::string>* logs) TF_LOCKS_EXCLUDED(mu_) { mutex_lock lock(mu_); for (auto& msg : messages_) { logs->push_back(msg); } } void Send(const TFLogEntry& entry) override TF_LOCKS_EXCLUDED(mu_) { if (entry.log_severity() < absl::LogSeverity::kWarning) return; mutex_lock lock(mu_); messages_.emplace_back(entry.ToString()); if (messages_.size() > static_cast<size_t>(num_messages_)) { messages_.pop_front(); } } private: mutex mu_; absl::once_flag flag_; int num_messages_ = 0; std::deque<std::string> messages_ TF_GUARDED_BY(mu_); }; } namespace errors { static constexpr const char kStackTraceProtoUrl[] = "type.googleapis.com/tensorflow.StackTracePayload"; void SetStackTrace(absl::Status& status, std::vector<StackFrame> stack_trace) { std::vector<std::string> items; items.reserve(stack_trace.size()); for (StackFrame& frame : stack_trace) { items.push_back( absl::StrCat(absl::StrReplaceAll(frame.file_name, {{"\n", ""}}), "\n", frame.line_number, "\n", absl::StrReplaceAll(frame.function_name, {{"\n", ""}}))); } status.SetPayload(kStackTraceProtoUrl, absl::Cord(absl::StrJoin(items, "\n"))); } std::vector<StackFrame> GetStackTrace(const absl::Status& status) { std::vector<StackFrame> stack_trace; absl::optional<absl::Cord> maybe_serialized_payload = status.GetPayload(kStackTraceProtoUrl); if (maybe_serialized_payload.has_value()) { std::vector<std::string> split = absl::StrSplit(maybe_serialized_payload.value().Flatten(), '\n'); assert(split.size() % 3 == 0); for (int i = 0; i < split.size() / 3; ++i) { const int idx = 3 * i; int line_number = -1; CHECK(absl::SimpleAtoi(split[idx + 1], &line_number)); stack_trace.emplace_back(std::move(split[idx]), line_number, std::move(split[idx + 2])); } } return stack_trace; } } #ifdef _WIN32 const char* NullTerminatedMessage(const absl::Status& status) { return absl::StatusMessageAsCStr(status); } #endif std::string* TfCheckOpHelperOutOfLine(const absl::Status& v, const char* msg) { std::stringstream ss; ss << "Non-OK-status: " << msg << "\nStatus: " << v; return new std::string(ss.str()); } StatusGroup::StatusGroup() {} StatusGroup::StatusGroup(std::initializer_list<absl::Status> statuses) { for (const absl::Status& s : statuses) { Update(s); } } static constexpr const char kDerivedStatusProtoUrl[] = "type.googleapis.com/tensorflow.DerivedStatus"; absl::Status StatusGroup::MakeDerived(const absl::Status& s) { if (IsDerived(s)) { return s; } else { absl::Status derived(s); derived.SetPayload(kDerivedStatusProtoUrl, absl::Cord("")); return derived; } } bool StatusGroup::IsDerived(const absl::Status& s) { return s.GetPayload(kDerivedStatusProtoUrl).has_value(); } void StatusGroup::ConfigureLogHistory() { StatusLogSink::GetInstance()->enable(); } void StatusGroup::Update(const absl::Status& s) { if (s.ok()) { ++num_ok_; } else { ok_ = false; if (IsDerived(s)) { derived_.insert(s); } else { non_derived_.insert(s); } } } static constexpr int kMaxAggregatedStatusMessageSize = 8 * 1024; static constexpr int kMaxAttachedLogMessageSize = 512; std::unordered_map<std::string, absl::Cord> StatusGroup::GetPayloads() const { std::unordered_map<std::string, absl::Cord> payloads; auto capture_payload = [&payloads](absl::string_view key, const absl::Cord& value) { payloads[std::string(key)] = value; }; for (const auto& status : derived_) { status.ForEachPayload(capture_payload); } for (const auto& status : non_derived_) { status.ForEachPayload(capture_payload); } payloads.erase(kDerivedStatusProtoUrl); return payloads; } absl::Status MakeStatus( absl::StatusCode code, absl::string_view message, const std::unordered_map<std::string, absl::Cord>& payloads) { absl::Status status(code, message); for (const auto& payload : payloads) { status.SetPayload(payload.first, payload.second); } return status; } std::string MakeString(const absl::Status& status) { return absl::StrCat(absl::StatusCodeToString(status.code()), ": ", status.message()); } absl::Status StatusGroup::as_summary_status() const { if (ok_) { return absl::OkStatus(); } auto get_recent_logs = [this]() -> std::string { if (!recent_logs_.empty()) { std::vector<std::string> fmt; fmt.push_back("\nRecent warning and error logs:"); for (auto& log : recent_logs_) { fmt.push_back(" " + log.substr(0, kMaxAttachedLogMessageSize)); } return absl::StrJoin(fmt, "\n"); } else { return ""; } }; if (non_derived_.size() == 1) { return MakeStatus( non_derived_.begin()->code(), strings::StrCat(non_derived_.begin()->message(), get_recent_logs()), GetPayloads()); } if (!non_derived_.empty()) { std::vector<std::string> fmt; fmt.push_back( strings::Printf("%zu root error(s) found.", non_derived_.size())); int index = 0; auto code = absl::StatusCode::kCancelled; for (const auto& s : non_derived_) { if (code == absl::StatusCode::kCancelled && s.code() != absl::StatusCode::kCancelled) { code = s.code(); } fmt.emplace_back(strings::StrCat(" (", index, ") ", MakeString(s))); ++index; } fmt.push_back(strings::Printf("%zu successful operations.", num_ok_)); fmt.push_back( strings::Printf("%zu derived errors ignored.", derived_.size())); std::string error_msg = absl::StrJoin(fmt, "\n").substr(0, kMaxAggregatedStatusMessageSize); return MakeStatus(code, strings::StrCat(error_msg, get_recent_logs()), GetPayloads()); } else { return MakeDerived(MakeStatus(derived_.begin()->code(), derived_.begin()->message(), GetPayloads())); } } absl::Status StatusGroup::as_concatenated_status() const { if (ok_) { return absl::OkStatus(); } if (non_derived_.size() == 1) { return MakeStatus(non_derived_.begin()->code(), non_derived_.begin()->message(), GetPayloads()); } if (!non_derived_.empty()) { std::vector<string> fmt; fmt.emplace_back("\n====================="); for (const auto& s : non_derived_) { fmt.emplace_back(MakeString(s)); } fmt.emplace_back("=====================\n"); return MakeStatus( non_derived_.begin()->code(), absl::StrJoin(fmt, "\n").substr(0, kMaxAggregatedStatusMessageSize), GetPayloads()); } else { return MakeDerived(MakeStatus(derived_.begin()->code(), derived_.begin()->message(), GetPayloads())); } } void StatusGroup::AttachLogMessages() { recent_logs_.clear(); StatusLogSink::GetInstance()->GetMessages(&recent_logs_); } }
#include "tsl/platform/status.h" #include <unordered_map> #include <vector> #include "absl/status/status.h" #include "absl/strings/cord.h" #include "absl/strings/str_format.h" #include "tsl/platform/errors.h" #include "tsl/platform/stack_frame.h" #include "tsl/platform/status_matchers.h" #include "tsl/platform/status_to_from_proto.h" #include "tsl/platform/test.h" #include "tsl/protobuf/error_codes.pb.h" #include "tsl/protobuf/status.pb.h" namespace tsl { namespace { using ::testing::IsEmpty; using ::tsl::testing::IsOk; using ::tsl::testing::StatusIs; TEST(ToStringTest, PayloadsArePrinted) { absl::Status status = errors::Aborted("Aborted Error Message"); status.SetPayload("payload_key", absl::Cord(absl::StrFormat( "payload_value %c%c%c", 1, 2, 3))); EXPECT_EQ(status.ToString(), "ABORTED: Aborted Error Message [payload_key='payload_value " "\\x01\\x02\\x03']"); } TEST(ToStringTest, MatchesAbslStatus) { absl::Status status = errors::Aborted("Aborted Error Message"); status.SetPayload("payload_key", absl::Cord(absl::StrFormat( "payload_value %c%c%c", 1, 2, 3))); absl::Status absl_status = absl::Status(absl::StatusCode::kAborted, status.message()); absl_status.SetPayload("payload_key", absl::Cord(absl::StrFormat( "payload_value %c%c%c", 1, 2, 3))); EXPECT_EQ(status.ToString(), absl_status.ToString()); } TEST(StackTrace, SerializeAndDeserializeCorrectly) { absl::Status status = errors::Aborted("Aborted Error Message"); std::vector<StackFrame> stack_trace; stack_trace.push_back(StackFrame("filename_1", 33, "func_name_1")); stack_trace.push_back(StackFrame("filename_2", 66, "func_name_2")); errors::SetStackTrace(status, stack_trace); std::vector<StackFrame> deserialized = errors::GetStackTrace(status); EXPECT_EQ(stack_trace.size(), deserialized.size()); for (size_t i = 0; i < stack_trace.size(); ++i) { EXPECT_EQ(stack_trace[i], deserialized[i]); } } TEST(StatusGroupTest, DeterministicOrderWithoutPayloads) { absl::Status status_a = errors::Aborted("Status A"); absl::Status status_b = errors::Aborted("Status B"); absl::Status status_c = errors::Aborted("Status C"); absl::Status combined = StatusGroup({status_a, status_b, status_c}).as_summary_status(); EXPECT_EQ(combined, StatusGroup({status_a, status_b, status_c}).as_summary_status()); EXPECT_EQ(combined, StatusGroup({status_a, status_c, status_b}).as_summary_status()); EXPECT_EQ(combined, StatusGroup({status_b, status_a, status_c}).as_summary_status()); EXPECT_EQ(combined, StatusGroup({status_b, status_c, status_a}).as_summary_status()); EXPECT_EQ(combined, StatusGroup({status_c, status_a, status_b}).as_summary_status()); EXPECT_EQ(combined, StatusGroup({status_c, status_b, status_a}).as_summary_status()); } TEST(StatusGroupTest, DeterministicOrderWithPayloads) { absl::Status status_a = errors::Aborted("Status A"); status_a.SetPayload("payload_key", absl::Cord("payload_value_a")); absl::Status status_b = errors::Aborted("Status B"); status_b.SetPayload("payload_key", absl::Cord("payload_value_b")); absl::Status status_c = errors::Aborted("Status C"); status_c.SetPayload("payload_key", absl::Cord("payload_value_c")); absl::Status combined = StatusGroup({status_a, status_b, status_c}).as_summary_status(); ASSERT_TRUE(combined.GetPayload("payload_key").has_value()); std::string payload(combined.GetPayload("payload_key").value()); EXPECT_EQ(payload, StatusGroup({status_a, status_b, status_c}) .as_summary_status() .GetPayload("payload_key")); EXPECT_EQ(payload, StatusGroup({status_a, status_c, status_b}) .as_summary_status() .GetPayload("payload_key")); EXPECT_EQ(payload, StatusGroup({status_b, status_a, status_c}) .as_summary_status() .GetPayload("payload_key")); EXPECT_EQ(payload, StatusGroup({status_b, status_c, status_a}) .as_summary_status() .GetPayload("payload_key")); EXPECT_EQ(payload, StatusGroup({status_c, status_a, status_b}) .as_summary_status() .GetPayload("payload_key")); EXPECT_EQ(payload, StatusGroup({status_c, status_b, status_a}) .as_summary_status() .GetPayload("payload_key")); } TEST(StatusGroupTest, PayloadsMergedProperly) { absl::Status status_a = errors::Aborted("Status A"); status_a.SetPayload("payload_key_a", absl::Cord(std::string("payload_value_a"))); absl::Status status_b = errors::Aborted("Status B"); status_b.SetPayload("payload_key_b", absl::Cord(std::string("payload_value_b"))); absl::Status status_c = errors::Aborted("Status C"); status_c.SetPayload("payload_key_c", absl::Cord(std::string("payload_value_c"))); absl::Status derived_status_c = StatusGroup::MakeDerived(errors::Aborted("Status C")); derived_status_c.SetPayload( "payload_key_c", absl::Cord(std::string("derived_payload_value_c"))); StatusGroup status_group({status_a, status_b, status_c, derived_status_c}); EXPECT_THAT(status_group.GetPayloads(), ::testing::SizeIs(3)); absl::Status combined = status_group.as_summary_status(); EXPECT_EQ(combined.GetPayload("payload_key_a"), "payload_value_a"); EXPECT_EQ(combined.GetPayload("payload_key_b"), "payload_value_b"); EXPECT_EQ(combined.GetPayload("payload_key_c"), "payload_value_c"); } TEST(Status, ErrorStatusForEachPayloadIteratesOverAll) { absl::Status s(absl::StatusCode::kInternal, "Error message"); s.SetPayload("key1", absl::Cord("value1")); s.SetPayload("key2", absl::Cord("value2")); s.SetPayload("key3", absl::Cord("value3")); std::unordered_map<std::string, absl::Cord> payloads; s.ForEachPayload([&payloads](StringPiece key, const absl::Cord& value) { payloads[std::string(key)] = value; }); EXPECT_EQ(payloads.size(), 3); EXPECT_EQ(payloads["key1"], "value1"); EXPECT_EQ(payloads["key2"], "value2"); EXPECT_EQ(payloads["key3"], "value3"); } TEST(Status, OkStatusForEachPayloadNoIteration) { absl::Status s = absl::OkStatus(); s.SetPayload("key1", absl::Cord("value1")); s.SetPayload("key2", absl::Cord("value2")); s.SetPayload("key3", absl::Cord("value3")); std::unordered_map<std::string, absl::Cord> payloads; s.ForEachPayload([&payloads](StringPiece key, const absl::Cord& value) { payloads[std::string(key)] = value; }); EXPECT_EQ(payloads.size(), 0); } TEST(Status, SaveOKStatusToProto) { tensorflow::StatusProto status_proto = StatusToProto(absl::OkStatus()); EXPECT_EQ(status_proto.code(), error::OK); EXPECT_THAT(status_proto.message(), IsEmpty()); } TEST(Status, SaveErrorStatusToProto) { tensorflow::StatusProto status_proto = StatusToProto(errors::NotFound("Not found")); EXPECT_EQ(status_proto.code(), error::NOT_FOUND); EXPECT_EQ(status_proto.message(), "Not found"); } TEST(Status, SaveEmptyStatusToProto) { tensorflow::StatusProto status_proto = StatusToProto(absl::Status()); EXPECT_EQ(status_proto.code(), error::OK); EXPECT_THAT(status_proto.message(), IsEmpty()); } TEST(Status, MakeOKStatusFromProto) { tensorflow::StatusProto status_proto; status_proto.set_code(error::OK); EXPECT_THAT(StatusFromProto(status_proto), IsOk()); } TEST(Status, MakeErrorStatusFromProto) { tensorflow::StatusProto status_proto; status_proto.set_code(error::INVALID_ARGUMENT); status_proto.set_message("Invalid argument"); EXPECT_THAT(StatusFromProto(status_proto), StatusIs(error::INVALID_ARGUMENT, "Invalid argument")); } TEST(Status, MakeStatusFromEmptyProto) { EXPECT_THAT(StatusFromProto(tensorflow::StatusProto()), IsOk()); } } }
2,605
cpp
google/tsl
gcs_throttle
tsl/platform/cloud/gcs_throttle.cc
tsl/platform/cloud/gcs_throttle_test.cc
#ifndef TENSORFLOW_TSL_PLATFORM_CLOUD_GCS_THROTTLE_H_ #define TENSORFLOW_TSL_PLATFORM_CLOUD_GCS_THROTTLE_H_ #include "tsl/platform/env.h" namespace tsl { struct GcsThrottleConfig { bool enabled = false; int64_t token_rate = 100000; int64_t bucket_size = 10000000; int64_t tokens_per_request = 100; int64_t initial_tokens = 0; }; class GcsThrottle { public: explicit GcsThrottle(EnvTime* env_time = nullptr); bool AdmitRequest(); void RecordResponse(size_t num_bytes); void SetConfig(GcsThrottleConfig config); inline int64_t available_tokens() TF_LOCKS_EXCLUDED(mu_) { mutex_lock l(mu_); UpdateState(); return available_tokens_; } bool is_enabled() TF_LOCKS_EXCLUDED(mu_) { mutex_lock l(mu_); return config_.enabled; } private: void UpdateState() TF_EXCLUSIVE_LOCKS_REQUIRED(mu_); inline uint64 request_bytes_to_tokens(size_t num_bytes) { return num_bytes >> 10; } mutex mu_; uint64 last_updated_secs_ TF_GUARDED_BY(mu_) = 0; int64_t available_tokens_ TF_GUARDED_BY(mu_) = 0; EnvTime* const env_time_; GcsThrottleConfig config_ TF_GUARDED_BY(mu_); }; } #endif #include "tsl/platform/cloud/gcs_throttle.h" #include <algorithm> namespace tsl { namespace { EnvTime* get_default_env_time() { static EnvTime* default_env_time = new EnvTime; return default_env_time; } } GcsThrottle::GcsThrottle(EnvTime* env_time) : last_updated_secs_(env_time ? env_time->GetOverridableNowSeconds() : EnvTime::NowSeconds()), available_tokens_(0), env_time_(env_time ? env_time : get_default_env_time()) {} bool GcsThrottle::AdmitRequest() { mutex_lock l(mu_); UpdateState(); if (available_tokens_ < config_.tokens_per_request) { return false || !config_.enabled; } available_tokens_ -= config_.tokens_per_request; return true; } void GcsThrottle::RecordResponse(size_t num_bytes) { mutex_lock l(mu_); UpdateState(); available_tokens_ -= request_bytes_to_tokens(num_bytes); } void GcsThrottle::SetConfig(GcsThrottleConfig config) { mutex_lock l(mu_); config_ = config; available_tokens_ = config.initial_tokens; last_updated_secs_ = env_time_->GetOverridableNowSeconds(); } void GcsThrottle::UpdateState() { int64_t now = env_time_->GetOverridableNowSeconds(); uint64 delta_secs = std::max(int64_t{0}, now - static_cast<int64_t>(last_updated_secs_)); available_tokens_ += delta_secs * config_.token_rate; available_tokens_ = std::min(available_tokens_, config_.bucket_size); last_updated_secs_ = now; } }
#include "tsl/platform/cloud/gcs_throttle.h" #include "tsl/lib/core/status_test_util.h" #include "tsl/platform/str_util.h" #include "tsl/platform/test.h" namespace tsl { namespace { class TestTime : public EnvTime { public: uint64 GetOverridableNowNanos() const override { return now_micros_ * kMicrosToNanos; } void SetTime(uint64 now_micros) { now_micros_ = now_micros; } void AdvanceSeconds(int64_t secs) { now_micros_ += secs * kSecondsToMicros; } private: uint64 now_micros_ = 1234567890000000ULL; }; class GcsThrottleTest : public ::testing::Test { protected: GcsThrottleTest() : throttle_(&time_) { config_.enabled = true; throttle_.SetConfig(config_); } GcsThrottleConfig config_; TestTime time_; GcsThrottle throttle_; }; TEST_F(GcsThrottleTest, ReplenishTokens) { EXPECT_EQ(0, throttle_.available_tokens()); time_.AdvanceSeconds(1); EXPECT_EQ(100000, throttle_.available_tokens()); time_.AdvanceSeconds(2); EXPECT_EQ(300000, throttle_.available_tokens()); } TEST_F(GcsThrottleTest, RejectRequest) { EXPECT_EQ(0, throttle_.available_tokens()); time_.AdvanceSeconds(1); EXPECT_TRUE(throttle_.AdmitRequest()); EXPECT_EQ(99900, throttle_.available_tokens()); for (int i = 1; i < 1000; i++) { EXPECT_TRUE(throttle_.AdmitRequest()); } EXPECT_FALSE(throttle_.AdmitRequest()); } TEST_F(GcsThrottleTest, MarkResponses) { time_.AdvanceSeconds(1); EXPECT_TRUE(throttle_.AdmitRequest()); throttle_.RecordResponse(128000000); EXPECT_EQ(-25100, throttle_.available_tokens()); EXPECT_FALSE(throttle_.AdmitRequest()); time_.AdvanceSeconds(1); EXPECT_TRUE(throttle_.AdmitRequest()) << "Available tokens: " << throttle_.available_tokens(); } TEST_F(GcsThrottleTest, Skippingtime_) { EXPECT_EQ(0, throttle_.available_tokens()); time_.AdvanceSeconds(90); EXPECT_EQ(9000000, throttle_.available_tokens()); } TEST_F(GcsThrottleTest, BucketLimit) { time_.AdvanceSeconds(120); EXPECT_EQ(10000000, throttle_.available_tokens()); } TEST_F(GcsThrottleTest, ReverseTime) { time_.AdvanceSeconds(1); EXPECT_EQ(100000, throttle_.available_tokens()); time_.AdvanceSeconds(-3600); EXPECT_EQ(100000, throttle_.available_tokens()); time_.AdvanceSeconds(1); EXPECT_EQ(200000, throttle_.available_tokens()); } TEST(GcsThrottleDisabledTest, Disabled) { TestTime time; GcsThrottle throttle(&time); ASSERT_FALSE(throttle.is_enabled()); EXPECT_EQ(0, throttle.available_tokens()); time.AdvanceSeconds(1); EXPECT_EQ(100000, throttle.available_tokens()); EXPECT_TRUE(throttle.AdmitRequest()); EXPECT_EQ(99900, throttle.available_tokens()); time.AdvanceSeconds(1); EXPECT_EQ(199900, throttle.available_tokens()); throttle.RecordResponse(128000000); EXPECT_LT(0, throttle.available_tokens()); EXPECT_TRUE(throttle.AdmitRequest()); } } }
2,606
cpp
google/tsl
curl_http_request
tsl/platform/cloud/curl_http_request.cc
tsl/platform/cloud/curl_http_request_test.cc
#ifndef TENSORFLOW_TSL_PLATFORM_CLOUD_CURL_HTTP_REQUEST_H_ #define TENSORFLOW_TSL_PLATFORM_CLOUD_CURL_HTTP_REQUEST_H_ #include <string> #include <unordered_map> #include <vector> #include <curl/curl.h> #include "tsl/platform/cloud/http_request.h" #include "tsl/platform/env.h" #include "tsl/platform/errors.h" #include "tsl/platform/macros.h" #include "tsl/platform/protobuf.h" #include "tsl/platform/status.h" #include "tsl/platform/stringpiece.h" #include "tsl/platform/types.h" namespace tsl { class LibCurl; class CurlHttpRequest : public HttpRequest { public: class Factory : public HttpRequest::Factory { public: virtual ~Factory() {} virtual HttpRequest* Create() { return new CurlHttpRequest(); } }; CurlHttpRequest(); explicit CurlHttpRequest(LibCurl* libcurl) : CurlHttpRequest(libcurl, Env::Default()) {} CurlHttpRequest(LibCurl* libcurl, Env* env); ~CurlHttpRequest() override; void SetUri(const string& uri) override; void SetRange(uint64 start, uint64 end) override; void AddHeader(const string& name, const string& value) override; void AddResolveOverride(const string& hostname, int64_t port, const string& ip_addr) override; void AddAuthBearerHeader(const string& auth_token) override; void SetRequestStats(RequestStats* stats) override; void SetDeleteRequest() override; Status SetPutFromFile(const string& body_filepath, size_t offset) override; void SetPutEmptyBody() override; void SetPostFromBuffer(const char* buffer, size_t size) override; void SetPostEmptyBody() override; void SetResultBuffer(std::vector<char>* out_buffer) override; void SetResultBufferDirect(char* buffer, size_t size) override; bool IsDirectResponse() const; size_t GetResultBufferDirectBytesTransferred() override; string GetResponseHeader(const string& name) const override; uint64 GetResponseCode() const override; Status Send() override; string EscapeString(const string& str) override; void SetTimeouts(uint32 connection, uint32 inactivity, uint32 total) override; private: static size_t WriteCallback(const void* ptr, size_t size, size_t nmemb, void* userdata); static size_t WriteCallbackDirect(const void* ptr, size_t size, size_t nmemb, void* userdata); static size_t ReadCallback(void* ptr, size_t size, size_t nmemb, FILE* userdata); static size_t HeaderCallback(const void* ptr, size_t size, size_t nmemb, void* this_object); static int ProgressCallback(void* this_object, curl_off_t dltotal, curl_off_t dlnow, curl_off_t ultotal, curl_off_t ulnow); void CheckMethodNotSet() const; void CheckNotSent() const; StringPiece GetResponse() const; Status CURLcodeToStatus(CURLcode code, const char* error_buffer); LibCurl* libcurl_; Env* env_; FILE* put_body_ = nullptr; StringPiece post_body_buffer_; size_t post_body_read_ = 0; std::vector<char>* response_buffer_ = nullptr; struct DirectResponseState { char* buffer_; size_t buffer_size_; size_t bytes_transferred_; size_t bytes_received_; }; DirectResponseState direct_response_ = {}; CURL* curl_ = nullptr; curl_slist* curl_headers_ = nullptr; curl_slist* resolve_list_ = nullptr; RequestStats* stats_ = nullptr; std::vector<char> default_response_buffer_; std::unordered_map<string, string> response_headers_; uint64 response_code_ = 0; uint64 last_progress_timestamp_ = 0; curl_off_t last_progress_bytes_ = 0; uint32 inactivity_timeout_secs_ = 60; uint32 connect_timeout_secs_ = 120; uint32 request_timeout_secs_ = 3600; bool is_uri_set_ = false; bool is_method_set_ = false; bool is_sent_ = false; string uri_; RequestMethod method_ = RequestMethod::kGet; const size_t response_to_error_limit_ = 500; CurlHttpRequest(const CurlHttpRequest&) = delete; void operator=(const CurlHttpRequest&) = delete; }; class LibCurl { public: virtual ~LibCurl() {} virtual CURL* curl_easy_init() = 0; virtual CURLcode curl_easy_setopt(CURL* curl, CURLoption option, uint64 param) TF_MUST_USE_RESULT = 0; virtual CURLcode curl_easy_setopt(CURL* curl, CURLoption option, const char* param) TF_MUST_USE_RESULT = 0; virtual CURLcode curl_easy_setopt(CURL* curl, CURLoption option, void* param) TF_MUST_USE_RESULT = 0; virtual CURLcode curl_easy_setopt( CURL* curl, CURLoption option, size_t (*param)(void*, size_t, size_t, FILE*)) TF_MUST_USE_RESULT = 0; virtual CURLcode curl_easy_setopt(CURL* curl, CURLoption option, size_t (*param)(const void*, size_t, size_t, void*)) TF_MUST_USE_RESULT = 0; virtual CURLcode curl_easy_setopt( CURL* curl, CURLoption option, int (*param)(void* clientp, curl_off_t dltotal, curl_off_t dlnow, curl_off_t ultotal, curl_off_t ulnow)) TF_MUST_USE_RESULT = 0; virtual CURLcode curl_easy_perform(CURL* curl) TF_MUST_USE_RESULT = 0; virtual CURLcode curl_easy_getinfo(CURL* curl, CURLINFO info, uint64* value) TF_MUST_USE_RESULT = 0; virtual CURLcode curl_easy_getinfo(CURL* curl, CURLINFO info, double* value) TF_MUST_USE_RESULT = 0; virtual void curl_easy_cleanup(CURL* curl) = 0; virtual curl_slist* curl_slist_append(curl_slist* list, const char* str) = 0; virtual void curl_slist_free_all(curl_slist* list) = 0; virtual char* curl_easy_escape(CURL* curl, const char* str, int length) = 0; virtual void curl_free(void* p) = 0; }; } #endif #include "tsl/platform/cloud/curl_http_request.h" #include <algorithm> #include "xla/tsl/util/env_var.h" #include "tsl/lib/gtl/map_util.h" #include "tsl/platform/errors.h" #include "tsl/platform/macros.h" #include "tsl/platform/scanner.h" #include "tsl/platform/str_util.h" #include "tsl/platform/types.h" #define CHECK_CURL_OK(expr) CHECK_EQ(expr, CURLE_OK) namespace tsl { namespace { constexpr uint64 kVerboseOutput = 0; class LibCurlProxy : public LibCurl { public: static LibCurlProxy* Load() { static LibCurlProxy* libcurl = []() -> LibCurlProxy* { curl_global_init(CURL_GLOBAL_ALL); return new LibCurlProxy; }(); return libcurl; } CURL* curl_easy_init() override { return ::curl_easy_init(); } CURLcode curl_easy_setopt(CURL* curl, CURLoption option, uint64 param) override { return ::curl_easy_setopt(curl, option, param); } CURLcode curl_easy_setopt(CURL* curl, CURLoption option, const char* param) override { return ::curl_easy_setopt(curl, option, param); } CURLcode curl_easy_setopt(CURL* curl, CURLoption option, void* param) override { return ::curl_easy_setopt(curl, option, param); } CURLcode curl_easy_setopt(CURL* curl, CURLoption option, size_t (*param)(void*, size_t, size_t, FILE*)) override { return ::curl_easy_setopt(curl, option, param); } CURLcode curl_easy_setopt(CURL* curl, CURLoption option, size_t (*param)(const void*, size_t, size_t, void*)) override { return ::curl_easy_setopt(curl, option, param); } CURLcode curl_easy_setopt(CURL* curl, CURLoption option, int (*param)(void* clientp, curl_off_t dltotal, curl_off_t dlnow, curl_off_t ultotal, curl_off_t ulnow)) override { return ::curl_easy_setopt(curl, option, param); } CURLcode curl_easy_perform(CURL* curl) override { return ::curl_easy_perform(curl); } CURLcode curl_easy_getinfo(CURL* curl, CURLINFO info, uint64* value) override { return ::curl_easy_getinfo(curl, info, value); } CURLcode curl_easy_getinfo(CURL* curl, CURLINFO info, double* value) override { return ::curl_easy_getinfo(curl, info, value); } void curl_easy_cleanup(CURL* curl) override { return ::curl_easy_cleanup(curl); } char* curl_easy_escape(CURL* curl, const char* str, int length) override { return ::curl_easy_escape(curl, str, length); } curl_slist* curl_slist_append(curl_slist* list, const char* str) override { return ::curl_slist_append(list, str); } void curl_slist_free_all(curl_slist* list) override { return ::curl_slist_free_all(list); } void curl_free(void* p) override { ::curl_free(p); } }; } CurlHttpRequest::CurlHttpRequest() : CurlHttpRequest(LibCurlProxy::Load()) {} CurlHttpRequest::CurlHttpRequest(LibCurl* libcurl, Env* env) : libcurl_(libcurl), env_(env) { default_response_buffer_.reserve(CURL_MAX_WRITE_SIZE); curl_ = libcurl_->curl_easy_init(); CHECK(curl_ != nullptr) << "Couldn't initialize a curl session."; std::string value = ""; TF_CHECK_OK(ReadStringFromEnvVar("CURL_CA_BUNDLE", "", &value)); if (!value.empty()) { CHECK_CURL_OK( libcurl_->curl_easy_setopt(curl_, CURLOPT_CAINFO, value.c_str())); } CHECK_CURL_OK( libcurl_->curl_easy_setopt(curl_, CURLOPT_VERBOSE, kVerboseOutput)); CHECK_CURL_OK(libcurl_->curl_easy_setopt(curl_, CURLOPT_USERAGENT, "TSL")); CHECK_CURL_OK(libcurl_->curl_easy_setopt(curl_, CURLOPT_NOSIGNAL, 1L)); CHECK_CURL_OK(libcurl_->curl_easy_setopt(curl_, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1)); CHECK_CURL_OK( libcurl_->curl_easy_setopt(curl_, CURLOPT_NOPROGRESS, uint64{0})); CHECK_CURL_OK(libcurl_->curl_easy_setopt(curl_, CURLOPT_XFERINFODATA, this)); CHECK_CURL_OK(libcurl_->curl_easy_setopt(curl_, CURLOPT_XFERINFOFUNCTION, &CurlHttpRequest::ProgressCallback)); SetResultBuffer(&default_response_buffer_); } CurlHttpRequest::~CurlHttpRequest() { if (curl_headers_) { libcurl_->curl_slist_free_all(curl_headers_); } if (resolve_list_) { libcurl_->curl_slist_free_all(resolve_list_); } if (put_body_) { if (fclose(put_body_) != 0) { LOG(ERROR) << "fclose() failed: " << strerror(errno); } } if (curl_) { libcurl_->curl_easy_cleanup(curl_); } } string CurlHttpRequest::EscapeString(const string& str) { char* out_char_str = libcurl_->curl_easy_escape(curl_, str.c_str(), 0); string out_str(out_char_str); libcurl_->curl_free(out_char_str); return out_str; } void CurlHttpRequest::SetUri(const string& uri) { CheckNotSent(); is_uri_set_ = true; uri_ = uri; CHECK_CURL_OK(libcurl_->curl_easy_setopt(curl_, CURLOPT_URL, uri.c_str())); } void CurlHttpRequest::SetRange(uint64 start, uint64 end) { CheckNotSent(); CHECK_CURL_OK(libcurl_->curl_easy_setopt( curl_, CURLOPT_RANGE, strings::StrCat(start, "-", end).c_str())); } void CurlHttpRequest::AddHeader(const string& name, const string& value) { CheckNotSent(); curl_headers_ = libcurl_->curl_slist_append( curl_headers_, strings::StrCat(name, ": ", value).c_str()); } void CurlHttpRequest::AddResolveOverride(const string& hostname, int64_t port, const string& ip_addr) { CheckNotSent(); resolve_list_ = libcurl_->curl_slist_append( resolve_list_, strings::StrCat(hostname, ":", port, ":", ip_addr).c_str()); } void CurlHttpRequest::AddAuthBearerHeader(const string& auth_token) { CheckNotSent(); if (!auth_token.empty()) { AddHeader("Authorization", strings::StrCat("Bearer ", auth_token)); } } void CurlHttpRequest::SetRequestStats(RequestStats* stats) { CheckNotSent(); CHECK(stats_ == nullptr) << "SetRequestStats already called"; stats_ = stats; } void CurlHttpRequest::SetDeleteRequest() { CheckNotSent(); CheckMethodNotSet(); is_method_set_ = true; method_ = RequestMethod::kDelete; CHECK_CURL_OK( libcurl_->curl_easy_setopt(curl_, CURLOPT_CUSTOMREQUEST, "DELETE")); } Status CurlHttpRequest::SetPutFromFile(const string& body_filepath, size_t offset) { CheckNotSent(); CheckMethodNotSet(); is_method_set_ = true; method_ = RequestMethod::kPut; if (put_body_) { if (fclose(put_body_) != 0) { LOG(ERROR) << "fclose() failed: " << strerror(errno); } } put_body_ = fopen(body_filepath.c_str(), "r"); if (!put_body_) { return errors::InvalidArgument("Couldn't open the specified file: " + body_filepath); } fseek(put_body_, 0, SEEK_END); const auto size = ftell(put_body_) - offset; fseek(put_body_, offset, SEEK_SET); curl_headers_ = libcurl_->curl_slist_append( curl_headers_, strings::StrCat("Content-Length: ", size).c_str()); CHECK_CURL_OK(libcurl_->curl_easy_setopt(curl_, CURLOPT_PUT, 1)); CHECK_CURL_OK(libcurl_->curl_easy_setopt(curl_, CURLOPT_READDATA, reinterpret_cast<void*>(put_body_))); return OkStatus(); } void CurlHttpRequest::SetPutEmptyBody() { CheckNotSent(); CheckMethodNotSet(); is_method_set_ = true; method_ = RequestMethod::kPut; CHECK_CURL_OK(libcurl_->curl_easy_setopt(curl_, CURLOPT_PUT, 1)); AddHeader("Content-Length", "0"); AddHeader("Transfer-Encoding", "identity"); CHECK_CURL_OK(libcurl_->curl_easy_setopt(curl_, CURLOPT_READDATA, reinterpret_cast<void*>(this))); CHECK_CURL_OK(libcurl_->curl_easy_setopt(curl_, CURLOPT_READFUNCTION, &CurlHttpRequest::ReadCallback)); } void CurlHttpRequest::SetPostFromBuffer(const char* buffer, size_t size) { CheckNotSent(); CheckMethodNotSet(); is_method_set_ = true; method_ = RequestMethod::kPost; curl_headers_ = libcurl_->curl_slist_append( curl_headers_, strings::StrCat("Content-Length: ", size).c_str()); CHECK_CURL_OK(libcurl_->curl_easy_setopt(curl_, CURLOPT_POST, 1)); CHECK_CURL_OK(libcurl_->curl_easy_setopt(curl_, CURLOPT_READDATA, reinterpret_cast<void*>(this))); CHECK_CURL_OK(libcurl_->curl_easy_setopt(curl_, CURLOPT_READFUNCTION, &CurlHttpRequest::ReadCallback)); post_body_buffer_ = StringPiece(buffer, size); } void CurlHttpRequest::SetPostEmptyBody() { CheckNotSent(); CheckMethodNotSet(); is_method_set_ = true; method_ = RequestMethod::kPost; CHECK_CURL_OK(libcurl_->curl_easy_setopt(curl_, CURLOPT_POST, 1)); AddHeader("Content-Length", "0"); AddHeader("Transfer-Encoding", "identity"); CHECK_CURL_OK(libcurl_->curl_easy_setopt(curl_, CURLOPT_READDATA, reinterpret_cast<void*>(this))); CHECK_CURL_OK(libcurl_->curl_easy_setopt(curl_, CURLOPT_READFUNCTION, &CurlHttpRequest::ReadCallback)); } void CurlHttpRequest::SetResultBuffer(std::vector<char>* out_buffer) { CheckNotSent(); CHECK(out_buffer != nullptr); out_buffer->clear(); response_buffer_ = out_buffer; CHECK_CURL_OK(libcurl_->curl_easy_setopt(curl_, CURLOPT_WRITEDATA, reinterpret_cast<void*>(this))); CHECK_CURL_OK(libcurl_->curl_easy_setopt(curl_, CURLOPT_WRITEFUNCTION, &CurlHttpRequest::WriteCallback)); } void CurlHttpRequest::SetResultBufferDirect(char* buffer, size_t size) { CHECK(buffer != nullptr); CheckNotSent(); direct_response_ = DirectResponseState{buffer, size, 0, 0}; CHECK_CURL_OK(libcurl_->curl_easy_setopt(curl_, CURLOPT_WRITEDATA, reinterpret_cast<void*>(this))); CHECK_CURL_OK(libcurl_->curl_easy_setopt( curl_, CURLOPT_WRITEFUNCTION, &CurlHttpRequest::WriteCallbackDirect)); } bool CurlHttpRequest::IsDirectResponse() const { return direct_response_.buffer_ != nullptr; } size_t CurlHttpRequest::WriteCallbackDirect(const void* ptr, size_t size, size_t nmemb, void* userdata) { CHECK(ptr != nullptr); auto that = reinterpret_cast<CurlHttpRequest*>(userdata); DirectResponseState* state = &that->direct_response_; CHECK(state->buffer_ != nullptr); CHECK(state->bytes_transferred_ <= state->buffer_size_); size_t curl_bytes_received = size * nmemb; size_t user_buffer_bytes_available = state->buffer_size_ - state->bytes_transferred_; size_t bytes_to_copy = std::min<size_t>(curl_bytes_received, user_buffer_bytes_available); memcpy(&state->buffer_[state->bytes_transferred_], ptr, bytes_to_copy); state->bytes_transferred_ += bytes_to_copy; state->bytes_received_ += curl_bytes_received; return bytes_to_copy; } size_t CurlHttpRequest::GetResultBufferDirectBytesTransferred() { CHECK(direct_response_.buffer_ != nullptr); return direct_response_.bytes_transferred_; } void CurlHttpRequest::SetTimeouts(uint32 connection, uint32 inactivity, uint32 total) { CheckNotSent(); connect_timeout_secs_ = connection; inactivity_timeout_secs_ = inactivity; request_timeout_secs_ = total; } size_t CurlHttpRequest::WriteCallback(const void* ptr, size_t size, size_t nmemb, void* this_object) { CHECK(ptr); auto that = reinterpret_cast<CurlHttpRequest*>(this_object); CHECK(that->response_buffer_); const size_t bytes_to_copy = size * nmemb; that->response_buffer_->insert( that->response_buffer_->end(), reinterpret_cast<const char*>(ptr), reinterpret_cast<const char*>(ptr) + bytes_to_copy); return bytes_to_copy; } size_t CurlHttpRequest::ReadCallback(void* ptr, size_t size, size_t nmemb, FILE* this_object) { CHECK(ptr); auto that = reinterpret_cast<CurlHttpRequest*>(this_object); CHECK(that->post_body_read_ <= that->post_body_buffer_.size()); const size_t bytes_to_copy = std::min( size * nmemb, that->post_body_buffer_.size() - that->post_body_read_); memcpy(ptr, that->post_body_buffer_.data() + that->post_body_read_, bytes_to_copy); that->post_body_read_ += bytes_to_copy; return bytes_to_copy; } size_t CurlHttpRequest::HeaderCallback(const void* ptr, size_t size, size_t nmemb, void* this_object) { CHECK(ptr); auto that = reinterpret_cast<CurlHttpRequest*>(this_object); StringPiece header(reinterpret_cast<const char*>(ptr), size * nmemb); StringPiece name, value; if (strings::Scanner(header) .ScanEscapedUntil(':') .StopCapture() .OneLiteral(": ") .GetResult(&value, &name)) { string str_value(value); absl::StripTrailingAsciiWhitespace(&str_value); that->response_headers_[string(name)] = str_value; } return size * nmemb; } Status CurlHttpRequest::Send() { CheckNotSent(); CHECK(is_uri_set_) << "URI has not been set."; is_sent_ = true; if (curl_headers_) { CHECK_CURL_OK( libcurl_->curl_easy_setopt(curl_, CURLOPT_HTTPHEADER, curl_headers_)); } if (resolve_list_) { CHECK_CURL_OK( libcurl_->curl_easy_setopt(curl_, CURLOPT_RESOLVE, resolve_list_)); } CHECK_CURL_OK(libcurl_->curl_easy_setopt(curl_, CURLOPT_HEADERDATA, reinterpret_cast<void*>(this))); CHECK_CURL_OK(libcurl_->curl_easy_setopt(curl_, CURLOPT_HEADERFUNCTION, &CurlHttpRequest::HeaderCallback)); CHECK_CURL_OK(libcurl_->curl_easy_setopt(curl_, CURLOPT_TIMEOUT, request_timeout_secs_)); CHECK_CURL_OK(libcurl_->curl_easy_setopt(curl_, CURLOPT_CONNECTTIMEOUT, connect_timeout_secs_)); char error_buffer[CURL_ERROR_SIZE] = {0}; CHECK_CURL_OK( libcurl_->curl_easy_setopt(curl_, CURLOPT_ERRORBUFFER, error_buffer)); if (stats_ != nullptr) { stats_->RecordRequest(this, uri_, method_); } const CURLcode curl_result = libcurl_->curl_easy_perform(curl_); TF_RETURN_IF_ERROR(CURLcodeToStatus(curl_result, error_buffer)); double written_size = 0; CHECK_CURL_OK(libcurl_->curl_easy_getinfo(curl_, CURLINFO_SIZE_DOWNLOAD, &written_size)); CHECK_CURL_OK(libcurl_->curl_easy_getinfo(curl_, CURLINFO_RESPONSE_CODE, &response_code_)); auto get_error_message = [this]() -> string { string error_message = strings::StrCat( "Error executing an HTTP request: HTTP response code ", response_code_); StringPiece body = GetResponse(); if (!body.empty()) { return strings::StrCat( error_message, " with body '", body.substr(0, std::min(body.size(), response_to_error_limit_)), "'"); } return error_message; }; Status result; switch (response_code_) { case 200: case 201: case 204: case 206: result = OkStatus(); break; case 416: response_buffer_->clear(); if (IsDirectResponse()) { direct_response_.bytes_transferred_ = 0; } result = OkStatus(); break; case 400: case 406: case 411: case 414: result = errors::InvalidArgument(get_error_message()); break; case 401: case 403: case 407: result = errors::PermissionDenied(get_error_message()); break; case 404: case 410: result = errors::NotFound(get_error_message()); break; case 302: case 303: case 304: case 307: case 412: case 413: result = errors::FailedPrecondition(get_error_message()); break; case 308: case 409: case 429: case 500: case 502: case 503: default: result = errors::Unavailable(get_error_message()); break; } if (!result.ok()) { response_buffer_->clear(); } if (stats_ != nullptr) { stats_->RecordResponse(this, uri_, method_, result); } return result; } void CurlHttpRequest::CheckMethodNotSet() const { CHECK(!is_method_set_) << "HTTP method has been already set."; } void CurlHttpRequest::CheckNotSent() const { CHECK(!is_sent_) << "The request has already been sent."; } StringPiece CurlHttpRequest::GetResponse() const { StringPiece response; if (IsDirectResponse()) { response = StringPiece(direct_response_.buffer_, direct_response_.bytes_transferred_); } else { response = StringPiece(response_buffer_->data(), response_buffer_->size()); } return response; } string CurlHttpRequest::GetResponseHeader(const string& name) const { const auto& header = response_headers_.find(name); return header != response_headers_.end() ? header->second : ""; } uint64 CurlHttpRequest::GetResponseCode() const { return response_code_; } int CurlHttpRequest::ProgressCallback(void* this_object, curl_off_t dltotal, curl_off_t dlnow, curl_off_t ultotal, curl_off_t ulnow) { auto that = reinterpret_cast<CurlHttpRequest*>(this_object); const auto now = that->env_->NowSeconds(); const auto current_progress = dlnow + ulnow; if (that->last_progress_timestamp_ == 0 || current_progress > that->last_progress_bytes_) { that->last_progress_timestamp_ = now; that->last_progress_bytes_ = current_progress; return 0; } if (now - that->last_progress_timestamp_ > that->inactivity_timeout_secs_) { double lookup_time = -1; const auto lookup_time_status = that->libcurl_->curl_easy_getinfo( that->curl_, CURLINFO_NAMELOOKUP_TIME, &lookup_time); double connect_time = -1
#include "tsl/platform/cloud/curl_http_request.h" #include <fstream> #include <string> #include "absl/status/status.h" #include "tsl/lib/core/status_test_util.h" #include "tsl/platform/mem.h" #include "tsl/platform/path.h" #include "tsl/platform/test.h" namespace tsl { namespace { const string kTestContent = "random original scratch content"; class FakeEnv : public EnvWrapper { public: FakeEnv() : EnvWrapper(Env::Default()) {} uint64 NowSeconds() const override { return now_; } uint64 now_ = 10000; }; class FakeLibCurl : public LibCurl { public: FakeLibCurl(const string& response_content, uint64 response_code) : response_content_(response_content), response_code_(response_code) {} FakeLibCurl(const string& response_content, uint64 response_code, std::vector<std::tuple<uint64, curl_off_t>> progress_ticks, FakeEnv* env) : response_content_(response_content), response_code_(response_code), progress_ticks_(std::move(progress_ticks)), env_(env) {} FakeLibCurl(const string& response_content, uint64 response_code, const std::vector<string>& response_headers) : response_content_(response_content), response_code_(response_code), response_headers_(response_headers) {} CURL* curl_easy_init() override { is_initialized_ = true; return reinterpret_cast<CURL*>(this); } CURLcode curl_easy_setopt(CURL* curl, CURLoption option, uint64 param) override { switch (option) { case CURLOPT_POST: is_post_ = param; break; case CURLOPT_PUT: is_put_ = param; break; default: break; } return CURLE_OK; } CURLcode curl_easy_setopt(CURL* curl, CURLoption option, const char* param) override { return curl_easy_setopt(curl, option, reinterpret_cast<void*>(const_cast<char*>(param))); } CURLcode curl_easy_setopt(CURL* curl, CURLoption option, void* param) override { switch (option) { case CURLOPT_URL: url_ = reinterpret_cast<char*>(param); break; case CURLOPT_RANGE: range_ = reinterpret_cast<char*>(param); break; case CURLOPT_CUSTOMREQUEST: custom_request_ = reinterpret_cast<char*>(param); break; case CURLOPT_HTTPHEADER: headers_ = reinterpret_cast<std::vector<string>*>(param); break; case CURLOPT_ERRORBUFFER: error_buffer_ = reinterpret_cast<char*>(param); break; case CURLOPT_CAINFO: ca_info_ = reinterpret_cast<char*>(param); break; case CURLOPT_WRITEDATA: write_data_ = reinterpret_cast<FILE*>(param); break; case CURLOPT_HEADERDATA: header_data_ = reinterpret_cast<FILE*>(param); break; case CURLOPT_READDATA: read_data_ = reinterpret_cast<FILE*>(param); break; case CURLOPT_XFERINFODATA: progress_data_ = param; break; default: break; } return CURLE_OK; } CURLcode curl_easy_setopt(CURL* curl, CURLoption option, size_t (*param)(void*, size_t, size_t, FILE*)) override { read_callback_ = param; return CURLE_OK; } CURLcode curl_easy_setopt(CURL* curl, CURLoption option, size_t (*param)(const void*, size_t, size_t, void*)) override { switch (option) { case CURLOPT_WRITEFUNCTION: write_callback_ = param; break; case CURLOPT_HEADERFUNCTION: header_callback_ = param; break; default: break; } return CURLE_OK; } CURLcode curl_easy_setopt(CURL* curl, CURLoption option, int (*param)(void* clientp, curl_off_t dltotal, curl_off_t dlnow, curl_off_t ultotal, curl_off_t ulnow)) override { progress_callback_ = param; return CURLE_OK; } CURLcode curl_easy_perform(CURL* curl) override { if (is_post_ || is_put_) { char buffer[3]; int bytes_read; posted_content_ = ""; do { bytes_read = read_callback_(buffer, 1, sizeof(buffer), read_data_); posted_content_ = strings::StrCat(posted_content_, StringPiece(buffer, bytes_read)); } while (bytes_read > 0); } if (write_data_ || write_callback_) { size_t bytes_handled = write_callback_( response_content_.c_str(), 1, response_content_.size(), write_data_); if (bytes_handled != response_content_.size()) { curl_easy_perform_result_ = CURLE_WRITE_ERROR; } } for (const auto& header : response_headers_) { header_callback_(header.c_str(), 1, header.size(), header_data_); } if (error_buffer_) { strncpy(error_buffer_, curl_easy_perform_error_message_.c_str(), curl_easy_perform_error_message_.size() + 1); } for (const auto& tick : progress_ticks_) { env_->now_ = std::get<0>(tick); if (progress_callback_(progress_data_, 0, std::get<1>(tick), 0, 0)) { return CURLE_ABORTED_BY_CALLBACK; } } return curl_easy_perform_result_; } CURLcode curl_easy_getinfo(CURL* curl, CURLINFO info, uint64* value) override { switch (info) { case CURLINFO_RESPONSE_CODE: *value = response_code_; break; default: break; } return CURLE_OK; } CURLcode curl_easy_getinfo(CURL* curl, CURLINFO info, double* value) override { switch (info) { case CURLINFO_SIZE_DOWNLOAD: *value = response_content_.size(); break; default: break; } return CURLE_OK; } void curl_easy_cleanup(CURL* curl) override { is_cleaned_up_ = true; } curl_slist* curl_slist_append(curl_slist* list, const char* str) override { std::vector<string>* v = list ? reinterpret_cast<std::vector<string>*>(list) : new std::vector<string>(); v->push_back(str); return reinterpret_cast<curl_slist*>(v); } char* curl_easy_escape(CURL* curl, const char* str, int length) override { const string victim = "/"; const string encoded = "%2F"; string temp_str = str; std::string::size_type n = 0; while ((n = temp_str.find(victim, n)) != std::string::npos) { temp_str.replace(n, victim.size(), encoded); n += encoded.size(); } char* out_char_str = reinterpret_cast<char*>( port::Malloc(sizeof(char) * temp_str.size() + 1)); std::copy(temp_str.begin(), temp_str.end(), out_char_str); out_char_str[temp_str.size()] = '\0'; return out_char_str; } void curl_slist_free_all(curl_slist* list) override { delete reinterpret_cast<std::vector<string>*>(list); } void curl_free(void* p) override { port::Free(p); } string response_content_; uint64 response_code_; std::vector<string> response_headers_; string url_; string range_; string custom_request_; string ca_info_; char* error_buffer_ = nullptr; bool is_initialized_ = false; bool is_cleaned_up_ = false; std::vector<string>* headers_ = nullptr; bool is_post_ = false; bool is_put_ = false; void* write_data_ = nullptr; size_t (*write_callback_)(const void* ptr, size_t size, size_t nmemb, void* userdata) = nullptr; void* header_data_ = nullptr; size_t (*header_callback_)(const void* ptr, size_t size, size_t nmemb, void* userdata) = nullptr; FILE* read_data_ = nullptr; size_t (*read_callback_)(void* ptr, size_t size, size_t nmemb, FILE* userdata) = &fread; int (*progress_callback_)(void* clientp, curl_off_t dltotal, curl_off_t dlnow, curl_off_t ultotal, curl_off_t ulnow) = nullptr; void* progress_data_ = nullptr; string posted_content_; CURLcode curl_easy_perform_result_ = CURLE_OK; string curl_easy_perform_error_message_; std::vector<std::tuple<uint64, curl_off_t>> progress_ticks_; FakeEnv* env_ = nullptr; }; TEST(CurlHttpRequestTest, GetRequest) { FakeLibCurl libcurl("get response", 200); CurlHttpRequest http_request(&libcurl); std::vector<char> scratch; scratch.insert(scratch.begin(), kTestContent.begin(), kTestContent.end()); scratch.reserve(100); http_request.SetUri("http: http_request.AddAuthBearerHeader("fake-bearer"); http_request.SetRange(100, 199); http_request.SetResultBuffer(&scratch); TF_EXPECT_OK(http_request.Send()); EXPECT_EQ("get response", string(scratch.begin(), scratch.end())); EXPECT_TRUE(libcurl.is_initialized_); EXPECT_EQ("http: EXPECT_EQ("100-199", libcurl.range_); EXPECT_EQ("", libcurl.custom_request_); EXPECT_EQ("", libcurl.ca_info_); EXPECT_EQ(1, libcurl.headers_->size()); EXPECT_EQ("Authorization: Bearer fake-bearer", (*libcurl.headers_)[0]); EXPECT_FALSE(libcurl.is_post_); EXPECT_EQ(200, http_request.GetResponseCode()); } TEST(CurlHttpRequestTest, GetRequest_Direct) { FakeLibCurl libcurl("get response", 200); CurlHttpRequest http_request(&libcurl); std::vector<char> scratch(100, 0); http_request.SetUri("http: http_request.AddAuthBearerHeader("fake-bearer"); http_request.SetRange(100, 199); http_request.SetResultBufferDirect(scratch.data(), scratch.capacity()); TF_EXPECT_OK(http_request.Send()); string expected_response = "get response"; size_t response_bytes_transferred = http_request.GetResultBufferDirectBytesTransferred(); EXPECT_EQ(expected_response.size(), response_bytes_transferred); EXPECT_EQ( "get response", string(scratch.begin(), scratch.begin() + response_bytes_transferred)); EXPECT_TRUE(libcurl.is_initialized_); EXPECT_EQ("http: EXPECT_EQ("100-199", libcurl.range_); EXPECT_EQ("", libcurl.custom_request_); EXPECT_EQ("", libcurl.ca_info_); EXPECT_EQ(1, libcurl.headers_->size()); EXPECT_EQ("Authorization: Bearer fake-bearer", (*libcurl.headers_)[0]); EXPECT_FALSE(libcurl.is_post_); EXPECT_EQ(200, http_request.GetResponseCode()); } TEST(CurlHttpRequestTest, GetRequest_CustomCaInfoFlag) { static char set_var[] = "CURL_CA_BUNDLE=test"; putenv(set_var); FakeLibCurl libcurl("get response", 200); CurlHttpRequest http_request(&libcurl); std::vector<char> scratch; scratch.insert(scratch.begin(), kTestContent.begin(), kTestContent.end()); scratch.reserve(100); http_request.SetUri("http: http_request.AddAuthBearerHeader("fake-bearer"); http_request.SetRange(100, 199); http_request.SetResultBuffer(&scratch); TF_EXPECT_OK(http_request.Send()); EXPECT_EQ("get response", string(scratch.begin(), scratch.end())); EXPECT_TRUE(libcurl.is_initialized_); EXPECT_EQ("http: EXPECT_EQ("100-199", libcurl.range_); EXPECT_EQ("", libcurl.custom_request_); EXPECT_EQ("test", libcurl.ca_info_); EXPECT_EQ(1, libcurl.headers_->size()); EXPECT_EQ("Authorization: Bearer fake-bearer", (*libcurl.headers_)[0]); EXPECT_FALSE(libcurl.is_post_); EXPECT_EQ(200, http_request.GetResponseCode()); } TEST(CurlHttpRequestTest, GetRequest_Direct_ResponseTooLarge) { FakeLibCurl libcurl("get response", 200); CurlHttpRequest http_request(&libcurl); std::vector<char> scratch(5, 0); http_request.SetUri("http: http_request.SetResultBufferDirect(scratch.data(), scratch.size()); const Status& status = http_request.Send(); EXPECT_EQ(error::FAILED_PRECONDITION, status.code()); EXPECT_EQ( "Error executing an HTTP request: libcurl code 23 meaning " "'Failed writing received data to disk/application', error details: " "Received 12 response bytes for a 5-byte buffer", status.message()); EXPECT_EQ(5, http_request.GetResultBufferDirectBytesTransferred()); EXPECT_EQ("get r", string(scratch.begin(), scratch.begin() + 5)); } TEST(CurlHttpRequestTest, GetRequest_Direct_RangeOutOfBound) { FakeLibCurl libcurl("get response", 416); CurlHttpRequest http_request(&libcurl); const string initialScratch = "abcde"; std::vector<char> scratch; scratch.insert(scratch.end(), initialScratch.begin(), initialScratch.end()); http_request.SetUri("http: http_request.SetRange(0, 4); http_request.SetResultBufferDirect(scratch.data(), scratch.size()); TF_EXPECT_OK(http_request.Send()); EXPECT_EQ(416, http_request.GetResponseCode()); EXPECT_EQ(0, http_request.GetResultBufferDirectBytesTransferred()); EXPECT_EQ("get r", string(scratch.begin(), scratch.end())); } TEST(CurlHttpRequestTest, GetRequest_Empty) { FakeLibCurl libcurl("", 200); CurlHttpRequest http_request(&libcurl); std::vector<char> scratch; scratch.resize(0); http_request.SetUri("http: http_request.AddAuthBearerHeader("fake-bearer"); http_request.SetRange(100, 199); http_request.SetResultBuffer(&scratch); TF_EXPECT_OK(http_request.Send()); EXPECT_TRUE(scratch.empty()); EXPECT_TRUE(libcurl.is_initialized_); EXPECT_EQ("http: EXPECT_EQ("100-199", libcurl.range_); EXPECT_EQ("", libcurl.custom_request_); EXPECT_EQ(1, libcurl.headers_->size()); EXPECT_EQ("Authorization: Bearer fake-bearer", (*libcurl.headers_)[0]); EXPECT_FALSE(libcurl.is_post_); EXPECT_EQ(200, http_request.GetResponseCode()); } TEST(CurlHttpRequestTest, GetRequest_RangeOutOfBound) { FakeLibCurl libcurl("get response", 416); CurlHttpRequest http_request(&libcurl); std::vector<char> scratch; scratch.insert(scratch.end(), kTestContent.begin(), kTestContent.end()); http_request.SetUri("http: http_request.AddAuthBearerHeader("fake-bearer"); http_request.SetRange(100, 199); http_request.SetResultBuffer(&scratch); TF_EXPECT_OK(http_request.Send()); EXPECT_TRUE(scratch.empty()); EXPECT_EQ(416, http_request.GetResponseCode()); } TEST(CurlHttpRequestTest, GetRequest_503) { FakeLibCurl libcurl("get response", 503); CurlHttpRequest http_request(&libcurl); std::vector<char> scratch; scratch.insert(scratch.end(), kTestContent.begin(), kTestContent.end()); http_request.SetUri("http: http_request.SetResultBuffer(&scratch); const auto& status = http_request.Send(); EXPECT_EQ(error::UNAVAILABLE, status.code()); EXPECT_EQ( "Error executing an HTTP request: HTTP response code 503 with body " "'get response'", status.message()); } TEST(CurlHttpRequestTest, GetRequest_HttpCode0) { FakeLibCurl libcurl("get response", 0); libcurl.curl_easy_perform_result_ = CURLE_OPERATION_TIMEDOUT; libcurl.curl_easy_perform_error_message_ = "Operation timed out"; CurlHttpRequest http_request(&libcurl); std::vector<char> scratch; scratch.insert(scratch.end(), kTestContent.begin(), kTestContent.end()); http_request.SetUri("http: const auto& status = http_request.Send(); EXPECT_EQ(error::UNAVAILABLE, status.code()); EXPECT_EQ( "Error executing an HTTP request: libcurl code 28 meaning " "'Timeout was reached', error details: Operation timed out", status.message()); EXPECT_EQ(0, http_request.GetResponseCode()); } TEST(CurlHttpRequestTest, GetRequest_CouldntResolveHost) { FakeLibCurl libcurl("get response", 0); libcurl.curl_easy_perform_result_ = CURLE_COULDNT_RESOLVE_HOST; libcurl.curl_easy_perform_error_message_ = "Could not resolve host 'metadata'"; CurlHttpRequest http_request(&libcurl); std::vector<char> scratch; scratch.insert(scratch.end(), kTestContent.begin(), kTestContent.end()); http_request.SetUri("http: const auto& status = http_request.Send(); EXPECT_EQ(error::FAILED_PRECONDITION, status.code()); EXPECT_EQ( "Error executing an HTTP request: libcurl code 6 meaning " "'Couldn't resolve host name', error details: Could not resolve host " "'metadata'", status.message()); EXPECT_EQ(0, http_request.GetResponseCode()); } TEST(CurlHttpRequestTest, GetRequest_SslBadCertfile) { FakeLibCurl libcurl("get response", 0); libcurl.curl_easy_perform_result_ = CURLE_SSL_CACERT_BADFILE; libcurl.curl_easy_perform_error_message_ = "error setting certificate verify locations:"; CurlHttpRequest http_request(&libcurl); std::vector<char> scratch; scratch.insert(scratch.end(), kTestContent.begin(), kTestContent.end()); http_request.SetUri("http: const auto& status = http_request.Send(); EXPECT_EQ(error::FAILED_PRECONDITION, status.code()); EXPECT_EQ( "Error executing an HTTP request: libcurl code 77 meaning " "'Problem with the SSL CA cert (path? access rights?)', error details: " "error setting certificate verify locations:", status.message()); EXPECT_EQ(0, http_request.GetResponseCode()); } TEST(CurlHttpRequestTest, ResponseHeaders) { FakeLibCurl libcurl( "get response", 200, {"Location: abcd", "Content-Type: text", "unparsable header"}); CurlHttpRequest http_request(&libcurl); http_request.SetUri("http: TF_EXPECT_OK(http_request.Send()); EXPECT_EQ("abcd", http_request.GetResponseHeader("Location")); EXPECT_EQ("text", http_request.GetResponseHeader("Content-Type")); EXPECT_EQ("", http_request.GetResponseHeader("Not-Seen-Header")); } TEST(CurlHttpRequestTest, PutRequest_WithBody_FromFile) { FakeLibCurl libcurl("", 200); CurlHttpRequest http_request(&libcurl); auto content_filename = io::JoinPath(testing::TmpDir(), "content"); std::ofstream content(content_filename, std::ofstream::binary); content << "post body content"; content.close(); http_request.SetUri("http: http_request.AddAuthBearerHeader("fake-bearer"); TF_EXPECT_OK(http_request.SetPutFromFile(content_filename, 0)); TF_EXPECT_OK(http_request.Send()); EXPECT_TRUE(libcurl.is_initialized_); EXPECT_EQ("http: EXPECT_EQ("", libcurl.custom_request_); EXPECT_EQ(2, libcurl.headers_->size()); EXPECT_EQ("Authorization: Bearer fake-bearer", (*libcurl.headers_)[0]); EXPECT_EQ("Content-Length: 17", (*libcurl.headers_)[1]); EXPECT_TRUE(libcurl.is_put_); EXPECT_EQ("post body content", libcurl.posted_content_); std::remove(content_filename.c_str()); } TEST(CurlHttpRequestTest, PutRequest_WithBody_FromFile_NonZeroOffset) { FakeLibCurl libcurl("", 200); CurlHttpRequest http_request(&libcurl); auto content_filename = io::JoinPath(testing::TmpDir(), "content"); std::ofstream content(content_filename, std::ofstream::binary); content << "post body content"; content.close(); http_request.SetUri("http: http_request.AddAuthBearerHeader("fake-bearer"); TF_EXPECT_OK(http_request.SetPutFromFile(content_filename, 7)); TF_EXPECT_OK(http_request.Send()); EXPECT_EQ("dy content", libcurl.posted_content_); std::remove(content_filename.c_str()); } TEST(CurlHttpRequestTest, PutRequest_WithoutBody) { FakeLibCurl libcurl("", 200); CurlHttpRequest http_request(&libcurl); http_request.SetUri("http: http_request.AddAuthBearerHeader("fake-bearer"); http_request.SetPutEmptyBody(); TF_EXPECT_OK(http_request.Send()); EXPECT_TRUE(libcurl.is_initialized_); EXPECT_EQ("http: EXPECT_EQ("", libcurl.custom_request_); EXPECT_EQ(3, libcurl.headers_->size()); EXPECT_EQ("Authorization: Bearer fake-bearer", (*libcurl.headers_)[0]); EXPECT_EQ("Content-Length: 0", (*libcurl.headers_)[1]); EXPECT_EQ("Transfer-Encoding: identity", (*libcurl.headers_)[2]); EXPECT_TRUE(libcurl.is_put_); EXPECT_EQ("", libcurl.posted_content_); } TEST(CurlHttpRequestTest, PostRequest_WithBody_FromMemory) { FakeLibCurl libcurl("", 200); CurlHttpRequest http_request(&libcurl); string content = "post body content"; http_request.SetUri("http: http_request.AddAuthBearerHeader("fake-bearer"); http_request.SetPostFromBuffer(content.c_str(), content.size()); TF_EXPECT_OK(http_request.Send()); EXPECT_TRUE(libcurl.is_initialized_); EXPECT_EQ("http: EXPECT_EQ("", libcurl.custom_request_); EXPECT_EQ(2, libcurl.headers_->size()); EXPECT_EQ("Authorization: Bearer fake-bearer", (*libcurl.headers_)[0]); EXPECT_EQ("Content-Length: 17", (*libcurl.headers_)[1]); EXPECT_TRUE(libcurl.is_post_); EXPECT_EQ("post body content", libcurl.posted_content_); } TEST(CurlHttpRequestTest, PostRequest_WithoutBody) { FakeLibCurl libcurl("", 200); CurlHttpRequest http_request(&libcurl); http_request.SetUri("http: http_request.AddAuthBearerHeader("fake-bearer"); http_request.SetPostEmptyBody(); TF_EXPECT_OK(http_request.Send()); EXPECT_TRUE(libcurl.is_initialized_); EXPECT_EQ("http: EXPECT_EQ("", libcurl.custom_request_); EXPECT_EQ(3, libcurl.headers_->size()); EXPECT_EQ("Authorization: Bearer fake-bearer", (*libcurl.headers_)[0]); EXPECT_EQ("Content-Length: 0", (*libcurl.headers_)[1]); EXPECT_EQ("Transfer-Encoding: identity", (*libcurl.headers_)[2]); EXPECT_TRUE(libcurl.is_post_); EXPECT_EQ("", libcurl.posted_content_); } TEST(CurlHttpRequestTest, DeleteRequest) { FakeLibCurl libcurl("", 200); CurlHttpRequest http_request(&libcurl); http_request.SetUri("http: http_request.AddAuthBearerHeader("fake-bearer"); http_request.SetDeleteRequest(); TF_EXPECT_OK(http_request.Send()); EXPECT_TRUE(libcurl.is_initialized_); EXPECT_EQ("http: EXPECT_EQ("DELETE", libcurl.custom_request_); EXPECT_EQ(1, libcurl.headers_->size()); EXPECT_EQ("Authorization: Bearer fake-bearer", (*libcurl.headers_)[0]); EXPECT_FALSE(libcurl.is_post_); } TEST(CurlHttpRequestTest, WrongSequenceOfCalls_NoUri) { FakeLibCurl libcurl("", 200); CurlHttpRequest http_request(&libcurl); ASSERT_DEATH((void)http_request.Send(), "URI has not been set"); } TEST(CurlHttpRequestTest, WrongSequenceOfCalls_TwoSends) { FakeLibCurl libcurl("", 200); CurlHttpRequest http_request(&libcurl); http_request.SetUri("http: TF_EXPECT_OK(http_request.Send()); ASSERT_DEATH((void)http_request.Send(), "The request has already been sent"); } TEST(CurlHttpRequestTest, WrongSequenceOfCalls_ReusingAfterSend) { FakeLibCurl libcurl("", 200); CurlHttpRequest http_request(&libcurl); http_request.SetUri("http: TF_EXPECT_OK(http_request.Send()); ASSERT_DEATH(http_request.SetUri("http: "The request has already been sent"); } TEST(CurlHttpRequestTest, WrongSequenceOfCalls_SettingMethodTwice) { FakeLibCurl libcurl("", 200); CurlHttpRequest http_request(&libcurl); http_request.SetDeleteRequest(); ASSERT_DEATH(http_request.SetPostEmptyBody(), "HTTP method has been already set"); } TEST(CurlHttpRequestTest, EscapeString) { FakeLibCurl libcurl("get response", 200); CurlHttpRequest http_request(&libcurl); const string test_string = "a/b/c"; EXPECT_EQ("a%2Fb%2Fc", http_request.EscapeString(test_string)); } TEST(CurlHttpRequestTest, ErrorReturnsNoResponse) { FakeLibCurl libcurl("get response", 500); CurlHttpRequest http_request(&libcurl); std::vector<char> scratch; scratch.insert(scratch.begin(), kTestContent.begin(), kTestContent.end()); scratch.reserve(100); http_request.SetUri("http: http_request.AddAuthBearerHeader("fake-bearer"); http_request.SetRange(100, 199); http_request.SetResultBuffer(&scratch); EXPECT_EQ(error::UNAVAILABLE, http_request.Send().code()); EXPECT_EQ("", string(scratch.begin(), scratch.end())); } TEST(CurlHttpRequestTest, ProgressIsOk) { FakeEnv env; FakeLibCurl libcurl( "test", 200, { std::make_tuple(100, 0) , std::make_tuple(110, 0) , std::make_tuple(200, 100) }, &env); CurlHttpRequest http_request(&libcurl, &env); http_request.SetUri("http: TF_EXPECT_OK(http_request.Send()); } TEST(CurlHttpRequestTest, ProgressIsStuck) { FakeEnv env; FakeLibCurl libcurl( "test", 200, { std::make_tuple(100, 10) , std::make_tuple(130, 10) , std::make_tuple(170, 10) }, &env); CurlHttpRequest http_request(&libcurl, &env); http_request.SetUri("http: auto status = http_request.Send(); EXPECT_EQ(error::UNAVAILABLE, status.code()); EXPECT_EQ( "Error executing an HTTP request: libcurl code 42 meaning 'Operation " "was aborted by an application callback', error details: (none)", status.message()); } class TestStats : public HttpRequest::RequestStats { public: ~TestStats() override = default; void RecordRequest(const HttpRequest* request, const string& uri, HttpRequest::RequestMethod method) override { has_recorded_request_ = true; record_request_request_ = request; record_request_uri_ = uri; record_request_method_ = method; } void RecordResponse(const HttpRequest* request, const string& uri, HttpRequest::RequestMethod method, const Status& result) override { has_recorded_response_ = true; record_response_request_ = request; record_response_uri_ = uri; record_response_method_ = method; record_response_result_ = result; } const HttpRequest* record_request_request_ = nullptr; string record_request_uri_ = "http: HttpRequest::RequestMethod record_request_method_ = HttpRequest::RequestMethod::kGet; const HttpRequest* record_response_request_ = nullptr; string record_response_uri_ = "http: HttpRequest::RequestMethod record_response_method_ = HttpRequest::RequestMethod::kGet; Status record_response_result_; bool has_recorded_request_ = false; bool has_recorded_response_ = false; }; class StatsTestFakeLibCurl : public FakeLibCurl { public: StatsTestFakeLibCurl(TestStats* stats, const string& response_content, uint64 response_code) : FakeLibCurl(response_content, response_code), stats_(stats) {} CURLcode curl_easy_perform(CURL* curl) override { CHECK(!performed_request_); performed_request_ = true; stats_had_recorded_request_ = stats_->has_recorded_request_; stats_had_recorded_response_ = stats_->has_recorded_response_; return FakeLibCurl::curl_easy_perform(curl); }; TestStats* stats_; bool performed_request_ = false; bool stats_had_recorded_request_; bool stats_had_recorded_response_; }; TEST(CurlHttpRequestTest, StatsGetSuccessful) { TestStats stats; StatsTestFakeLibCurl libcurl(&stats, "get response", 200); CurlHttpRequest http_request(&libcurl); std::vector<char> scratch; scratch.insert(scratch.begin(), kTestContent.begin(), kTestContent.end()); scratch.reserve(100); http_request.SetRequestStats(&stats); http_request.SetUri("http: http_request.AddAuthBearerHeader("fake-bearer"); http_request.SetRange(100, 199); http_request.SetResultBuffer(&scratch); TF_EXPECT_OK(http_request.Send()); EXPECT_EQ("get response", string(scratch.begin(), scratch.end())); ASSERT_TRUE(stats.has_recorded_request_); EXPECT_EQ(&http_request, stats.record_request_request_); EXPECT_EQ("http: EXPECT_EQ(HttpRequest::RequestMethod::kGet, stats.record_request_method_); ASSERT_TRUE(stats.has_recorded_response_); EXPECT_EQ(&http_request, stats.record_response_request_); EXPECT_EQ("http: EXPECT_EQ(HttpRequest::RequestMethod::kGet, stats.record_response_method_); TF_EXPECT_OK(stats.record_response_result_); EXPECT_TRUE(libcurl.performed_request_); EXPECT_TRUE(libcurl.stats_had_recorded_request_); EXPECT_FALSE(libcurl.stats_had_recorded_response_); } TEST(CurlHttpRequestTest, StatsGetNotFound) { TestStats stats; StatsTestFakeLibCurl libcurl(&stats, "get other response", 404); CurlHttpRequest http_request(&libcurl); std::vector<char> scratch; scratch.insert(scratch.begin(), kTestContent.begin(), kTestContent.end()); scratch.reserve(100); http_request.SetRequestStats(&stats); http_request.SetUri("http: http_request.AddAuthBearerHeader("fake-bearer"); http_request.SetRange(100, 199); http_request.SetResultBuffer(&scratch); Status s = http_request.Send(); ASSERT_TRUE(stats.has_recorded_request_); EXPECT_EQ(&http_request, stats.record_request_request_); EXPECT_EQ("http: EXPECT_EQ(HttpRequest::RequestMethod::kGet, stats.record_request_method_); ASSERT_TRUE(stats.has_recorded_response_); EXPECT_EQ(&http_request, stats.record_response_request_); EXPECT_EQ("http: EXPECT_EQ(HttpRequest::RequestMethod::kGet, stats.record_response_method_); EXPECT_TRUE(absl::IsNotFound(stats.record_response_result_)); EXPECT_EQ(s, stats.record_response_result_); EXPECT_TRUE(libcurl.performed_request_); EXPECT_TRUE(libcurl.stats_had_recorded_request_); EXPECT_FALSE(libcurl.stats_had_recorded_response_); } TEST(CurlHttpRequestTest, StatsPost) { TestStats stats; FakeLibCurl libcurl("", 200); CurlHttpRequest http_request(&libcurl); http_request.SetRequestStats(&stats); string content = "post body content"; http_request.SetUri("http: http_request.SetPostFromBuffer(content.c_str(), content.size()); TF_EXPECT_OK(http_request.Send()); ASSERT_TRUE(stats.has_recorded_request_); EXPECT_EQ(&http_request, stats.record_request_request_); EXPECT_EQ("http: EXPECT_EQ(HttpR
2,607
cpp
google/tsl
ram_file_block_cache
tsl/platform/cloud/ram_file_block_cache.cc
tsl/platform/cloud/ram_file_block_cache_test.cc
#ifndef TENSORFLOW_TSL_PLATFORM_CLOUD_RAM_FILE_BLOCK_CACHE_H_ #define TENSORFLOW_TSL_PLATFORM_CLOUD_RAM_FILE_BLOCK_CACHE_H_ #include <functional> #include <list> #include <map> #include <memory> #include <string> #include <vector> #include "tsl/platform/cloud/file_block_cache.h" #include "tsl/platform/env.h" #include "tsl/platform/mutex.h" #include "tsl/platform/notification.h" #include "tsl/platform/status.h" #include "tsl/platform/stringpiece.h" #include "tsl/platform/thread_annotations.h" #include "tsl/platform/types.h" namespace tsl { class RamFileBlockCache : public FileBlockCache { public: typedef std::function<Status(const string& filename, size_t offset, size_t buffer_size, char* buffer, size_t* bytes_transferred)> BlockFetcher; RamFileBlockCache(size_t block_size, size_t max_bytes, uint64 max_staleness, BlockFetcher block_fetcher, Env* env = Env::Default()) : block_size_(block_size), max_bytes_(max_bytes), max_staleness_(max_staleness), block_fetcher_(block_fetcher), env_(env) { if (max_staleness_ > 0) { pruning_thread_.reset(env_->StartThread(ThreadOptions(), "TF_prune_FBC", [this] { Prune(); })); } VLOG(1) << "GCS file block cache is " << (IsCacheEnabled() ? "enabled" : "disabled"); } ~RamFileBlockCache() override { if (pruning_thread_) { stop_pruning_thread_.Notify(); pruning_thread_.reset(); } } Status Read(const string& filename, size_t offset, size_t n, char* buffer, size_t* bytes_transferred) override; bool ValidateAndUpdateFileSignature(const string& filename, int64_t file_signature) override TF_LOCKS_EXCLUDED(mu_); void RemoveFile(const string& filename) override TF_LOCKS_EXCLUDED(mu_); void Flush() override TF_LOCKS_EXCLUDED(mu_); size_t block_size() const override { return block_size_; } size_t max_bytes() const override { return max_bytes_; } uint64 max_staleness() const override { return max_staleness_; } size_t CacheSize() const override TF_LOCKS_EXCLUDED(mu_); bool IsCacheEnabled() const override { return block_size_ > 0 && max_bytes_ > 0; } private: const size_t block_size_; const size_t max_bytes_; const uint64 max_staleness_; const BlockFetcher block_fetcher_; Env* const env_; typedef std::pair<string, size_t> Key; enum class FetchState { CREATED, FETCHING, FINISHED, ERROR, }; struct Block { std::vector<char> data; std::list<Key>::iterator lru_iterator; std::list<Key>::iterator lra_iterator; uint64 timestamp; mutex mu; FetchState state TF_GUARDED_BY(mu) = FetchState::CREATED; condition_variable cond_var; }; typedef std::map<Key, std::shared_ptr<Block>> BlockMap; void Prune() TF_LOCKS_EXCLUDED(mu_); bool BlockNotStale(const std::shared_ptr<Block>& block) TF_EXCLUSIVE_LOCKS_REQUIRED(mu_); std::shared_ptr<Block> Lookup(const Key& key) TF_LOCKS_EXCLUDED(mu_); Status MaybeFetch(const Key& key, const std::shared_ptr<Block>& block) TF_LOCKS_EXCLUDED(mu_); void Trim() TF_EXCLUSIVE_LOCKS_REQUIRED(mu_); Status UpdateLRU(const Key& key, const std::shared_ptr<Block>& block) TF_LOCKS_EXCLUDED(mu_); void RemoveFile_Locked(const string& filename) TF_EXCLUSIVE_LOCKS_REQUIRED(mu_); void RemoveBlock(BlockMap::iterator entry) TF_EXCLUSIVE_LOCKS_REQUIRED(mu_); std::unique_ptr<Thread> pruning_thread_; Notification stop_pruning_thread_; mutable mutex mu_; BlockMap block_map_ TF_GUARDED_BY(mu_); std::list<Key> lru_list_ TF_GUARDED_BY(mu_); std::list<Key> lra_list_ TF_GUARDED_BY(mu_); size_t cache_size_ TF_GUARDED_BY(mu_) = 0; std::map<string, int64_t> file_signature_map_ TF_GUARDED_BY(mu_); }; } #endif #include "tsl/platform/cloud/ram_file_block_cache.h" #include <cstring> #include <memory> #include "absl/cleanup/cleanup.h" #include "tsl/platform/env.h" namespace tsl { bool RamFileBlockCache::BlockNotStale(const std::shared_ptr<Block>& block) { mutex_lock l(block->mu); if (block->state != FetchState::FINISHED) { return true; } if (max_staleness_ == 0) return true; return env_->NowSeconds() - block->timestamp <= max_staleness_; } std::shared_ptr<RamFileBlockCache::Block> RamFileBlockCache::Lookup( const Key& key) { mutex_lock lock(mu_); auto entry = block_map_.find(key); if (entry != block_map_.end()) { if (BlockNotStale(entry->second)) { if (cache_stats_ != nullptr) { cache_stats_->RecordCacheHitBlockSize(entry->second->data.size()); } return entry->second; } else { RemoveFile_Locked(key.first); } } auto new_entry = std::make_shared<Block>(); lru_list_.push_front(key); lra_list_.push_front(key); new_entry->lru_iterator = lru_list_.begin(); new_entry->lra_iterator = lra_list_.begin(); new_entry->timestamp = env_->NowSeconds(); block_map_.emplace(std::make_pair(key, new_entry)); return new_entry; } void RamFileBlockCache::Trim() { while (!lru_list_.empty() && cache_size_ > max_bytes_) { RemoveBlock(block_map_.find(lru_list_.back())); } } Status RamFileBlockCache::UpdateLRU(const Key& key, const std::shared_ptr<Block>& block) { mutex_lock lock(mu_); if (block->timestamp == 0) { return OkStatus(); } if (block->lru_iterator != lru_list_.begin()) { lru_list_.erase(block->lru_iterator); lru_list_.push_front(key); block->lru_iterator = lru_list_.begin(); } if (block->data.size() < block_size_) { Key fmax = std::make_pair(key.first, std::numeric_limits<size_t>::max()); auto fcmp = block_map_.upper_bound(fmax); if (fcmp != block_map_.begin() && key < (--fcmp)->first) { return errors::Internal("Block cache contents are inconsistent."); } } Trim(); return OkStatus(); } Status RamFileBlockCache::MaybeFetch(const Key& key, const std::shared_ptr<Block>& block) { bool downloaded_block = false; auto reconcile_state = absl::MakeCleanup([this, &downloaded_block, &key, &block] { if (downloaded_block) { mutex_lock l(mu_); if (block->timestamp != 0) { cache_size_ += block->data.capacity(); lra_list_.erase(block->lra_iterator); lra_list_.push_front(key); block->lra_iterator = lra_list_.begin(); block->timestamp = env_->NowSeconds(); } } }); mutex_lock l(block->mu); Status status = OkStatus(); while (true) { switch (block->state) { case FetchState::ERROR: TF_FALLTHROUGH_INTENDED; case FetchState::CREATED: block->state = FetchState::FETCHING; block->mu.unlock(); block->data.clear(); block->data.resize(block_size_, 0); size_t bytes_transferred; status.Update(block_fetcher_(key.first, key.second, block_size_, block->data.data(), &bytes_transferred)); if (cache_stats_ != nullptr) { cache_stats_->RecordCacheMissBlockSize(bytes_transferred); } block->mu.lock(); if (status.ok()) { block->data.resize(bytes_transferred, 0); std::vector<char>(block->data).swap(block->data); downloaded_block = true; block->state = FetchState::FINISHED; } else { block->state = FetchState::ERROR; } block->cond_var.notify_all(); return status; case FetchState::FETCHING: block->cond_var.wait_for(l, std::chrono::seconds(60)); if (block->state == FetchState::FINISHED) { return OkStatus(); } break; case FetchState::FINISHED: return OkStatus(); } } return errors::Internal( "Control flow should never reach the end of RamFileBlockCache::Fetch."); } Status RamFileBlockCache::Read(const string& filename, size_t offset, size_t n, char* buffer, size_t* bytes_transferred) { *bytes_transferred = 0; if (n == 0) { return OkStatus(); } if (!IsCacheEnabled() || (n > max_bytes_)) { return block_fetcher_(filename, offset, n, buffer, bytes_transferred); } size_t start = block_size_ * (offset / block_size_); size_t finish = block_size_ * ((offset + n) / block_size_); if (finish < offset + n) { finish += block_size_; } size_t total_bytes_transferred = 0; for (size_t pos = start; pos < finish; pos += block_size_) { Key key = std::make_pair(filename, pos); std::shared_ptr<Block> block = Lookup(key); DCHECK(block) << "No block for key " << key.first << "@" << key.second; TF_RETURN_IF_ERROR(MaybeFetch(key, block)); TF_RETURN_IF_ERROR(UpdateLRU(key, block)); const auto& data = block->data; if (offset >= pos + data.size()) { *bytes_transferred = total_bytes_transferred; return errors::OutOfRange("EOF at offset ", offset, " in file ", filename, " at position ", pos, "with data size ", data.size()); } auto begin = data.begin(); if (offset > pos) { begin += offset - pos; } auto end = data.end(); if (pos + data.size() > offset + n) { end -= (pos + data.size()) - (offset + n); } if (begin < end) { size_t bytes_to_copy = end - begin; memcpy(&buffer[total_bytes_transferred], &*begin, bytes_to_copy); total_bytes_transferred += bytes_to_copy; } if (data.size() < block_size_) { break; } } *bytes_transferred = total_bytes_transferred; return OkStatus(); } bool RamFileBlockCache::ValidateAndUpdateFileSignature(const string& filename, int64_t file_signature) { mutex_lock lock(mu_); auto it = file_signature_map_.find(filename); if (it != file_signature_map_.end()) { if (it->second == file_signature) { return true; } RemoveFile_Locked(filename); it->second = file_signature; return false; } file_signature_map_[filename] = file_signature; return true; } size_t RamFileBlockCache::CacheSize() const { mutex_lock lock(mu_); return cache_size_; } void RamFileBlockCache::Prune() { while (!WaitForNotificationWithTimeout(&stop_pruning_thread_, 1000000)) { mutex_lock lock(mu_); uint64 now = env_->NowSeconds(); while (!lra_list_.empty()) { auto it = block_map_.find(lra_list_.back()); if (now - it->second->timestamp <= max_staleness_) { break; } RemoveFile_Locked(std::string(it->first.first)); } } } void RamFileBlockCache::Flush() { mutex_lock lock(mu_); block_map_.clear(); lru_list_.clear(); lra_list_.clear(); cache_size_ = 0; } void RamFileBlockCache::RemoveFile(const string& filename) { mutex_lock lock(mu_); RemoveFile_Locked(filename); } void RamFileBlockCache::RemoveFile_Locked(const string& filename) { Key begin = std::make_pair(filename, 0); auto it = block_map_.lower_bound(begin); while (it != block_map_.end() && it->first.first == filename) { auto next = std::next(it); RemoveBlock(it); it = next; } } void RamFileBlockCache::RemoveBlock(BlockMap::iterator entry) { entry->second->timestamp = 0; lru_list_.erase(entry->second->lru_iterator); lra_list_.erase(entry->second->lra_iterator); cache_size_ -= entry->second->data.capacity(); block_map_.erase(entry); } }
#include "tsl/platform/cloud/ram_file_block_cache.h" #include <cstring> #include "tsl/lib/core/status_test_util.h" #include "tsl/platform/blocking_counter.h" #include "tsl/platform/cloud/now_seconds_env.h" #include "tsl/platform/env.h" #include "tsl/platform/notification.h" #include "tsl/platform/test.h" namespace tsl { namespace { Status ReadCache(RamFileBlockCache* cache, const string& filename, size_t offset, size_t n, std::vector<char>* out) { out->clear(); out->resize(n, 0); size_t bytes_transferred = 0; Status status = cache->Read(filename, offset, n, out->data(), &bytes_transferred); EXPECT_LE(bytes_transferred, n); out->resize(bytes_transferred, n); return status; } TEST(RamFileBlockCacheTest, IsCacheEnabled) { auto fetcher = [](const string& filename, size_t offset, size_t n, char* buffer, size_t* bytes_transferred) { return OkStatus(); }; RamFileBlockCache cache1(0, 0, 0, fetcher); RamFileBlockCache cache2(16, 0, 0, fetcher); RamFileBlockCache cache3(0, 32, 0, fetcher); RamFileBlockCache cache4(16, 32, 0, fetcher); EXPECT_FALSE(cache1.IsCacheEnabled()); EXPECT_FALSE(cache2.IsCacheEnabled()); EXPECT_FALSE(cache3.IsCacheEnabled()); EXPECT_TRUE(cache4.IsCacheEnabled()); } TEST(RamFileBlockCacheTest, ValidateAndUpdateFileSignature) { int calls = 0; auto fetcher = [&calls](const string& filename, size_t offset, size_t n, char* buffer, size_t* bytes_transferred) { calls++; memset(buffer, 'x', n); *bytes_transferred = n; return OkStatus(); }; string filename = "file"; RamFileBlockCache cache(16, 32, 0, fetcher); std::vector<char> out; EXPECT_TRUE(cache.ValidateAndUpdateFileSignature(filename, 123)); TF_EXPECT_OK(ReadCache(&cache, filename, 0, 16, &out)); EXPECT_EQ(calls, 1); EXPECT_TRUE(cache.ValidateAndUpdateFileSignature(filename, 123)); TF_EXPECT_OK(ReadCache(&cache, filename, 0, 16, &out)); EXPECT_EQ(calls, 1); EXPECT_FALSE(cache.ValidateAndUpdateFileSignature(filename, 321)); TF_EXPECT_OK(ReadCache(&cache, filename, 0, 16, &out)); EXPECT_EQ(calls, 2); } TEST(RamFileBlockCacheTest, PassThrough) { const string want_filename = "foo/bar"; const size_t want_offset = 42; const size_t want_n = 1024; int calls = 0; auto fetcher = [&calls, want_filename, want_offset, want_n]( const string& got_filename, size_t got_offset, size_t got_n, char* buffer, size_t* bytes_transferred) { EXPECT_EQ(got_filename, want_filename); EXPECT_EQ(got_offset, want_offset); EXPECT_EQ(got_n, want_n); calls++; memset(buffer, 'x', got_n); *bytes_transferred = got_n; return OkStatus(); }; RamFileBlockCache cache1(1, 0, 0, fetcher); RamFileBlockCache cache2(0, 1, 0, fetcher); RamFileBlockCache cache3(0, 0, 0, fetcher); RamFileBlockCache cache4(1000, 1000, 0, fetcher); std::vector<char> out; TF_EXPECT_OK(ReadCache(&cache1, want_filename, want_offset, want_n, &out)); EXPECT_EQ(calls, 1); TF_EXPECT_OK(ReadCache(&cache2, want_filename, want_offset, want_n, &out)); EXPECT_EQ(calls, 2); TF_EXPECT_OK(ReadCache(&cache3, want_filename, want_offset, want_n, &out)); EXPECT_EQ(calls, 3); TF_EXPECT_OK(ReadCache(&cache4, want_filename, want_offset, want_n, &out)); EXPECT_EQ(calls, 4); } TEST(RamFileBlockCacheTest, BlockAlignment) { const size_t size = 256; std::vector<char> buf; for (int i = 0; i < size; i++) { buf.push_back(i); } auto fetcher = [&buf](const string& filename, size_t offset, size_t n, char* buffer, size_t* bytes_transferred) { if (offset < buf.size()) { size_t bytes_to_copy = std::min<size_t>(buf.size() - offset, n); memcpy(buffer, buf.data() + offset, bytes_to_copy); *bytes_transferred = bytes_to_copy; } else { *bytes_transferred = 0; } return OkStatus(); }; for (size_t block_size = 2; block_size <= 4; block_size++) { RamFileBlockCache cache(block_size, block_size, 0, fetcher); for (size_t offset = 0; offset < 10; offset++) { for (size_t n = block_size - 2; n <= block_size + 2; n++) { std::vector<char> got; TF_EXPECT_OK(ReadCache(&cache, "", offset, n, &got)); if (offset + n <= size) { EXPECT_EQ(got.size(), n) << "block size = " << block_size << ", offset = " << offset << ", n = " << n; } else { EXPECT_EQ(got.size(), size - offset) << "block size = " << block_size << ", offset = " << offset << ", n = " << n; } std::vector<char>::const_iterator begin = buf.begin() + offset; std::vector<char>::const_iterator end = offset + n > buf.size() ? buf.end() : begin + n; std::vector<char> want(begin, end); EXPECT_EQ(got, want) << "block size = " << block_size << ", offset = " << offset << ", n = " << n; } } } } TEST(RamFileBlockCacheTest, CacheHits) { const size_t block_size = 16; std::set<size_t> calls; auto fetcher = [&calls, block_size](const string& filename, size_t offset, size_t n, char* buffer, size_t* bytes_transferred) { EXPECT_EQ(n, block_size); EXPECT_EQ(offset % block_size, 0); EXPECT_EQ(calls.find(offset), calls.end()) << "at offset " << offset; calls.insert(offset); memset(buffer, 'x', n); *bytes_transferred = n; return OkStatus(); }; const uint32 block_count = 256; RamFileBlockCache cache(block_size, block_count * block_size, 0, fetcher); std::vector<char> out; out.resize(block_count, 0); for (int i = 0; i < 2; i++) { for (int j = 0; j < block_count; j++) { TF_EXPECT_OK(ReadCache(&cache, "", block_size * j, block_size, &out)); } } } TEST(RamFileBlockCacheTest, OutOfRange) { const size_t block_size = 16; const size_t file_size = 24; bool first_block = false; bool second_block = false; auto fetcher = [block_size, file_size, &first_block, &second_block]( const string& filename, size_t offset, size_t n, char* buffer, size_t* bytes_transferred) { EXPECT_EQ(n, block_size); EXPECT_EQ(offset % block_size, 0); size_t bytes_to_copy = 0; if (offset == 0) { memset(buffer, 'x', n); bytes_to_copy = n; first_block = true; } else if (offset == block_size) { bytes_to_copy = file_size - block_size; memset(buffer, 'x', bytes_to_copy); second_block = true; } *bytes_transferred = bytes_to_copy; return OkStatus(); }; RamFileBlockCache cache(block_size, block_size, 0, fetcher); std::vector<char> out; TF_EXPECT_OK(ReadCache(&cache, "", 0, block_size, &out)); EXPECT_TRUE(first_block); EXPECT_EQ(out.size(), block_size); Status status = ReadCache(&cache, "", file_size + 4, 4, &out); EXPECT_EQ(status.code(), error::OUT_OF_RANGE); EXPECT_TRUE(second_block); second_block = false; TF_EXPECT_OK(ReadCache(&cache, "", block_size, block_size, &out)); EXPECT_FALSE(second_block); EXPECT_EQ(out.size(), file_size - block_size); } TEST(RamFileBlockCacheTest, Inconsistent) { const size_t block_size = 16; auto fetcher = [block_size](const string& filename, size_t offset, size_t n, char* buffer, size_t* bytes_transferred) { EXPECT_EQ(n, block_size); EXPECT_EQ(offset % block_size, 0); EXPECT_GE(n, 1); memset(buffer, 'x', 1); *bytes_transferred = 1; return OkStatus(); }; RamFileBlockCache cache(block_size, 2 * block_size, 0, fetcher); std::vector<char> out; TF_EXPECT_OK(ReadCache(&cache, "", block_size, block_size, &out)); EXPECT_EQ(out.size(), 1); Status status = ReadCache(&cache, "", 0, block_size, &out); EXPECT_EQ(status.code(), error::INTERNAL); } TEST(RamFileBlockCacheTest, LRU) { const size_t block_size = 16; std::list<size_t> calls; auto fetcher = [&calls, block_size](const string& filename, size_t offset, size_t n, char* buffer, size_t* bytes_transferred) { EXPECT_EQ(n, block_size); EXPECT_FALSE(calls.empty()) << "at offset = " << offset; if (!calls.empty()) { EXPECT_EQ(offset, calls.front()); calls.pop_front(); } memset(buffer, 'x', n); *bytes_transferred = n; return OkStatus(); }; const uint32 block_count = 2; RamFileBlockCache cache(block_size, block_count * block_size, 0, fetcher); std::vector<char> out; calls.push_back(0); TF_EXPECT_OK(ReadCache(&cache, "", 0, 1, &out)); TF_EXPECT_OK(ReadCache(&cache, "", 0, 1, &out)); calls.push_back(block_size); TF_EXPECT_OK(ReadCache(&cache, "", block_size, 1, &out)); TF_EXPECT_OK(ReadCache(&cache, "", block_size, 1, &out)); calls.push_back(2 * block_size); TF_EXPECT_OK(ReadCache(&cache, "", 2 * block_size, 1, &out)); TF_EXPECT_OK(ReadCache(&cache, "", 2 * block_size, 1, &out)); calls.push_back(0); TF_EXPECT_OK(ReadCache(&cache, "", 0, 1, &out)); TF_EXPECT_OK(ReadCache(&cache, "", 2 * block_size, 1, &out)); calls.push_back(block_size); TF_EXPECT_OK(ReadCache(&cache, "", block_size, 1, &out)); calls.push_back(0); TF_EXPECT_OK(ReadCache(&cache, "", 0, 1, &out)); } TEST(RamFileBlockCacheTest, MaxStaleness) { int calls = 0; auto fetcher = [&calls](const string& filename, size_t offset, size_t n, char* buffer, size_t* bytes_transferred) { calls++; memset(buffer, 'x', n); *bytes_transferred = n; return OkStatus(); }; std::vector<char> out; std::unique_ptr<NowSecondsEnv> env(new NowSecondsEnv); RamFileBlockCache cache1(8, 16, 2 , fetcher, env.get()); TF_EXPECT_OK(ReadCache(&cache1, "", 0, 1, &out)); EXPECT_EQ(calls, 1); for (int i = 1; i <= 10; i++) { env->SetNowSeconds(i + 1); TF_EXPECT_OK(ReadCache(&cache1, "", 0, 1, &out)); EXPECT_EQ(calls, 1 + i / 3); } calls = 0; env->SetNowSeconds(0); RamFileBlockCache cache2(8, 16, 0 , fetcher, env.get()); TF_EXPECT_OK(ReadCache(&cache2, "", 0, 1, &out)); EXPECT_EQ(calls, 1); env->SetNowSeconds(365 * 24 * 60 * 60); TF_EXPECT_OK(ReadCache(&cache2, "", 0, 1, &out)); EXPECT_EQ(calls, 1); } TEST(RamFileBlockCacheTest, RemoveFile) { int calls = 0; auto fetcher = [&calls](const string& filename, size_t offset, size_t n, char* buffer, size_t* bytes_transferred) { calls++; char c = (filename == "a") ? 'a' : (filename == "b") ? 'b' : 'x'; if (offset > 0) { c = toupper(c); } memset(buffer, c, n); *bytes_transferred = n; return OkStatus(); }; const size_t n = 3; RamFileBlockCache cache(8, 32, 0, fetcher); std::vector<char> out; std::vector<char> a(n, 'a'); std::vector<char> b(n, 'b'); std::vector<char> A(n, 'A'); std::vector<char> B(n, 'B'); TF_EXPECT_OK(ReadCache(&cache, "a", 0, n, &out)); EXPECT_EQ(out, a); EXPECT_EQ(calls, 1); TF_EXPECT_OK(ReadCache(&cache, "a", 8, n, &out)); EXPECT_EQ(out, A); EXPECT_EQ(calls, 2); TF_EXPECT_OK(ReadCache(&cache, "b", 0, n, &out)); EXPECT_EQ(out, b); EXPECT_EQ(calls, 3); TF_EXPECT_OK(ReadCache(&cache, "b", 8, n, &out)); EXPECT_EQ(out, B); EXPECT_EQ(calls, 4); TF_EXPECT_OK(ReadCache(&cache, "a", 0, n, &out)); EXPECT_EQ(out, a); TF_EXPECT_OK(ReadCache(&cache, "a", 8, n, &out)); EXPECT_EQ(out, A); TF_EXPECT_OK(ReadCache(&cache, "b", 0, n, &out)); EXPECT_EQ(out, b); TF_EXPECT_OK(ReadCache(&cache, "b", 8, n, &out)); EXPECT_EQ(out, B); EXPECT_EQ(calls, 4); cache.RemoveFile("a"); TF_EXPECT_OK(ReadCache(&cache, "b", 0, n, &out)); EXPECT_EQ(out, b); TF_EXPECT_OK(ReadCache(&cache, "b", 8, n, &out)); EXPECT_EQ(out, B); EXPECT_EQ(calls, 4); TF_EXPECT_OK(ReadCache(&cache, "a", 0, n, &out)); EXPECT_EQ(out, a); EXPECT_EQ(calls, 5); TF_EXPECT_OK(ReadCache(&cache, "a", 8, n, &out)); EXPECT_EQ(out, A); EXPECT_EQ(calls, 6); } TEST(RamFileBlockCacheTest, Prune) { int calls = 0; auto fetcher = [&calls](const string& filename, size_t offset, size_t n, char* buffer, size_t* bytes_transferred) { calls++; memset(buffer, 'x', n); *bytes_transferred = n; return OkStatus(); }; std::vector<char> out; std::unique_ptr<NowSecondsEnv> env(new NowSecondsEnv); uint64 now = Env::Default()->NowSeconds(); env->SetNowSeconds(now); RamFileBlockCache cache(8, 32, 1 , fetcher, env.get()); TF_EXPECT_OK(ReadCache(&cache, "a", 0, 1, &out)); env->SetNowSeconds(now + 1); TF_EXPECT_OK(ReadCache(&cache, "b", 0, 1, &out)); TF_EXPECT_OK(ReadCache(&cache, "a", 8, 1, &out)); EXPECT_EQ(cache.CacheSize(), 24); EXPECT_EQ(calls, 3); TF_EXPECT_OK(ReadCache(&cache, "a", 0, 1, &out)); TF_EXPECT_OK(ReadCache(&cache, "b", 0, 1, &out)); TF_EXPECT_OK(ReadCache(&cache, "a", 8, 1, &out)); EXPECT_EQ(calls, 3); env->SetNowSeconds(now + 2); uint64 start = Env::Default()->NowSeconds(); do { Env::Default()->SleepForMicroseconds(100000); } while (cache.CacheSize() == 24 && Env::Default()->NowSeconds() - start < 3); EXPECT_EQ(cache.CacheSize(), 8); TF_EXPECT_OK(ReadCache(&cache, "b", 0, 1, &out)); EXPECT_EQ(calls, 3); env->SetNowSeconds(now + 3); start = Env::Default()->NowSeconds(); do { Env::Default()->SleepForMicroseconds(100000); } while (cache.CacheSize() == 8 && Env::Default()->NowSeconds() - start < 3); EXPECT_EQ(cache.CacheSize(), 0); } TEST(RamFileBlockCacheTest, ParallelReads) { const int callers = 4; BlockingCounter counter(callers); auto fetcher = [&counter](const string& filename, size_t offset, size_t n, char* buffer, size_t* bytes_transferred) { counter.DecrementCount(); if (!counter.WaitFor(std::chrono::seconds(10))) { return errors::FailedPrecondition("desired concurrency not reached"); } memset(buffer, 'x', n); *bytes_transferred = n; return OkStatus(); }; const int block_size = 8; RamFileBlockCache cache(block_size, 2 * callers * block_size, 0, fetcher); std::vector<std::unique_ptr<Thread>> threads; for (int i = 0; i < callers; i++) { threads.emplace_back( Env::Default()->StartThread({}, "caller", [&cache, i, block_size]() { std::vector<char> out; TF_EXPECT_OK( ReadCache(&cache, "a", i * block_size, block_size, &out)); std::vector<char> x(block_size, 'x'); EXPECT_EQ(out, x); })); } } TEST(RamFileBlockCacheTest, CoalesceConcurrentReads) { const size_t block_size = 16; int num_requests = 0; Notification notification; auto fetcher = [&num_requests, &notification, block_size]( const string& filename, size_t offset, size_t n, char* buffer, size_t* bytes_transferred) { EXPECT_EQ(n, block_size); EXPECT_EQ(offset, 0); num_requests++; memset(buffer, 'x', n); *bytes_transferred = n; notification.Notify(); Env::Default()->SleepForMicroseconds(100000); return OkStatus(); }; RamFileBlockCache cache(block_size, block_size, 0, fetcher); std::unique_ptr<Thread> concurrent( Env::Default()->StartThread({}, "concurrent", [&cache, block_size] { std::vector<char> out; TF_EXPECT_OK(ReadCache(&cache, "", 0, block_size / 2, &out)); EXPECT_EQ(out.size(), block_size / 2); })); notification.WaitForNotification(); std::vector<char> out; TF_EXPECT_OK(ReadCache(&cache, "", block_size / 2, block_size / 2, &out)); EXPECT_EQ(out.size(), block_size / 2); EXPECT_EQ(1, num_requests); } TEST(RamFileBlockCacheTest, Flush) { int calls = 0; auto fetcher = [&calls](const string& filename, size_t offset, size_t n, char* buffer, size_t* bytes_transferred) { calls++; memset(buffer, 'x', n); *bytes_transferred = n; return OkStatus(); }; RamFileBlockCache cache(16, 32, 0, fetcher); std::vector<char> out; TF_EXPECT_OK(ReadCache(&cache, "", 0, 16, &out)); TF_EXPECT_OK(ReadCache(&cache, "", 0, 16, &out)); EXPECT_EQ(calls, 1); cache.Flush(); TF_EXPECT_OK(ReadCache(&cache, "", 0, 16, &out)); EXPECT_EQ(calls, 2); } } }
2,608
cpp
google/tsl
time_util
tsl/platform/cloud/time_util.cc
tsl/platform/cloud/time_util_test.cc
#ifndef TENSORFLOW_TSL_PLATFORM_CLOUD_TIME_UTIL_H_ #define TENSORFLOW_TSL_PLATFORM_CLOUD_TIME_UTIL_H_ #include "tsl/platform/status.h" namespace tsl { Status ParseRfc3339Time(const string& time, int64_t* mtime_nsec); } #endif #include "tsl/platform/cloud/time_util.h" #include <time.h> #include <cmath> #include <cstdio> #include <ctime> #ifdef _WIN32 #define timegm _mkgmtime #endif #include "tsl/platform/errors.h" namespace tsl { namespace { constexpr int64_t kNanosecondsPerSecond = 1000 * 1000 * 1000; } Status ParseRfc3339Time(const string& time, int64_t* mtime_nsec) { tm parsed{0}; float seconds; if (sscanf(time.c_str(), "%4d-%2d-%2dT%2d:%2d:%fZ", &(parsed.tm_year), &(parsed.tm_mon), &(parsed.tm_mday), &(parsed.tm_hour), &(parsed.tm_min), &seconds) != 6) { return errors::Internal( strings::StrCat("Unrecognized RFC 3339 time format: ", time)); } const int int_seconds = std::floor(seconds); parsed.tm_year -= 1900; parsed.tm_mon -= 1; parsed.tm_sec = int_seconds; *mtime_nsec = timegm(&parsed) * kNanosecondsPerSecond + static_cast<int64_t>(std::floor((seconds - int_seconds) * kNanosecondsPerSecond)); return OkStatus(); } }
#include "tsl/platform/cloud/time_util.h" #include "tsl/lib/core/status_test_util.h" #include "tsl/platform/test.h" namespace tsl { TEST(TimeUtil, ParseRfc3339Time) { int64_t mtime_nsec; TF_EXPECT_OK(ParseRfc3339Time("2016-04-29T23:15:24.896Z", &mtime_nsec)); EXPECT_NEAR(1461971724896, mtime_nsec / 1000 / 1000, 1); } TEST(TimeUtil, ParseRfc3339Time_ParseError) { int64_t mtime_nsec; EXPECT_EQ("Unrecognized RFC 3339 time format: 2016-04-29", ParseRfc3339Time("2016-04-29", &mtime_nsec).message()); } }
2,609
cpp
google/tsl
google_auth_provider
tsl/platform/cloud/google_auth_provider.cc
tsl/platform/cloud/google_auth_provider_test.cc
#ifndef TENSORFLOW_TSL_PLATFORM_CLOUD_GOOGLE_AUTH_PROVIDER_H_ #define TENSORFLOW_TSL_PLATFORM_CLOUD_GOOGLE_AUTH_PROVIDER_H_ #include <memory> #include "tsl/platform/cloud/auth_provider.h" #include "tsl/platform/cloud/compute_engine_metadata_client.h" #include "tsl/platform/cloud/oauth_client.h" #include "tsl/platform/mutex.h" #include "tsl/platform/thread_annotations.h" namespace tsl { class GoogleAuthProvider : public AuthProvider { public: GoogleAuthProvider(std::shared_ptr<ComputeEngineMetadataClient> compute_engine_metadata_client); explicit GoogleAuthProvider(std::unique_ptr<OAuthClient> oauth_client, std::shared_ptr<ComputeEngineMetadataClient> compute_engine_metadata_client, Env* env); virtual ~GoogleAuthProvider() {} Status GetToken(string* token) override; private: Status GetTokenFromFiles() TF_EXCLUSIVE_LOCKS_REQUIRED(mu_); Status GetTokenFromGce() TF_EXCLUSIVE_LOCKS_REQUIRED(mu_); Status GetTokenForTesting() TF_EXCLUSIVE_LOCKS_REQUIRED(mu_); std::unique_ptr<OAuthClient> oauth_client_; std::shared_ptr<ComputeEngineMetadataClient> compute_engine_metadata_client_; Env* env_; mutex mu_; string current_token_ TF_GUARDED_BY(mu_); uint64 expiration_timestamp_sec_ TF_GUARDED_BY(mu_) = 0; GoogleAuthProvider(const GoogleAuthProvider&) = delete; void operator=(const GoogleAuthProvider&) = delete; }; } #endif #include "tsl/platform/cloud/google_auth_provider.h" #ifndef _WIN32 #include <pwd.h> #include <unistd.h> #else #include <sys/types.h> #endif #include <fstream> #include <utility> #include "absl/strings/match.h" #include "json/json.h" #include "tsl/platform/base64.h" #include "tsl/platform/env.h" #include "tsl/platform/errors.h" #include "tsl/platform/path.h" #include "tsl/platform/retrying_utils.h" namespace tsl { namespace { constexpr char kGoogleApplicationCredentials[] = "GOOGLE_APPLICATION_CREDENTIALS"; constexpr char kGoogleAuthTokenForTesting[] = "GOOGLE_AUTH_TOKEN_FOR_TESTING"; constexpr char kCloudSdkConfig[] = "CLOUDSDK_CONFIG"; constexpr char kNoGceCheck[] = "NO_GCE_CHECK"; constexpr char kGCloudConfigFolder[] = ".config/gcloud/"; constexpr char kWellKnownCredentialsFile[] = "application_default_credentials.json"; constexpr int kExpirationTimeMarginSec = 60; constexpr char kOAuthV3Url[] = "https: constexpr char kOAuthV4Url[] = "https: constexpr char kGceTokenPath[] = "instance/service-accounts/default/token"; constexpr char kOAuthScope[] = "https: bool IsFile(const string& filename) { std::ifstream fstream(filename.c_str()); return fstream.good(); } Status GetEnvironmentVariableFileName(string* filename) { if (!filename) { return errors::FailedPrecondition("'filename' cannot be nullptr."); } const char* result = std::getenv(kGoogleApplicationCredentials); if (!result || !IsFile(result)) { return errors::NotFound(strings::StrCat("$", kGoogleApplicationCredentials, " is not set or corrupt.")); } *filename = result; return OkStatus(); } Status GetWellKnownFileName(string* filename) { if (!filename) { return errors::FailedPrecondition("'filename' cannot be nullptr."); } string config_dir; const char* config_dir_override = std::getenv(kCloudSdkConfig); if (config_dir_override) { config_dir = config_dir_override; } else { const char* home_dir = std::getenv("HOME"); if (!home_dir) { return errors::FailedPrecondition("Could not read $HOME."); } config_dir = io::JoinPath(home_dir, kGCloudConfigFolder); } auto result = io::JoinPath(config_dir, kWellKnownCredentialsFile); if (!IsFile(result)) { return errors::NotFound( "Could not find the credentials file in the standard gcloud location."); } *filename = result; return OkStatus(); } } GoogleAuthProvider::GoogleAuthProvider( std::shared_ptr<ComputeEngineMetadataClient> compute_engine_metadata_client) : GoogleAuthProvider(std::unique_ptr<OAuthClient>(new OAuthClient()), std::move(compute_engine_metadata_client), Env::Default()) {} GoogleAuthProvider::GoogleAuthProvider( std::unique_ptr<OAuthClient> oauth_client, std::shared_ptr<ComputeEngineMetadataClient> compute_engine_metadata_client, Env* env) : oauth_client_(std::move(oauth_client)), compute_engine_metadata_client_( std::move(compute_engine_metadata_client)), env_(env) {} Status GoogleAuthProvider::GetToken(string* t) { mutex_lock lock(mu_); const uint64 now_sec = env_->NowSeconds(); if (now_sec + kExpirationTimeMarginSec < expiration_timestamp_sec_) { *t = current_token_; return OkStatus(); } if (GetTokenForTesting().ok()) { *t = current_token_; return OkStatus(); } auto token_from_files_status = GetTokenFromFiles(); if (token_from_files_status.ok()) { *t = current_token_; return OkStatus(); } char* no_gce_check_var = std::getenv(kNoGceCheck); bool skip_gce_check = no_gce_check_var != nullptr && absl::EqualsIgnoreCase(no_gce_check_var, "true"); Status token_from_gce_status; if (skip_gce_check) { token_from_gce_status = Status(absl::StatusCode::kCancelled, strings::StrCat("GCE check skipped due to presence of $", kNoGceCheck, " environment variable.")); } else { token_from_gce_status = GetTokenFromGce(); } if (token_from_gce_status.ok()) { *t = current_token_; return OkStatus(); } if (skip_gce_check) { LOG(INFO) << "Attempting an empty bearer token since no token was retrieved " << "from files, and GCE metadata check was skipped."; } else { LOG(WARNING) << "All attempts to get a Google authentication bearer token failed, " << "returning an empty token. Retrieving token from files failed with " "\"" << token_from_files_status.ToString() << "\"." << " Retrieving token from GCE failed with \"" << token_from_gce_status.ToString() << "\"."; } *t = ""; if (skip_gce_check) { expiration_timestamp_sec_ = 0; } else { expiration_timestamp_sec_ = UINT64_MAX; } current_token_ = ""; return OkStatus(); } Status GoogleAuthProvider::GetTokenFromFiles() { string credentials_filename; if (!GetEnvironmentVariableFileName(&credentials_filename).ok() && !GetWellKnownFileName(&credentials_filename).ok()) { return errors::NotFound("Could not locate the credentials file."); } Json::Value json; Json::Reader reader; std::ifstream credentials_fstream(credentials_filename); if (!reader.parse(credentials_fstream, json)) { return errors::FailedPrecondition( "Couldn't parse the JSON credentials file."); } if (json.isMember("refresh_token")) { TF_RETURN_IF_ERROR(oauth_client_->GetTokenFromRefreshTokenJson( json, kOAuthV3Url, &current_token_, &expiration_timestamp_sec_)); } else if (json.isMember("private_key")) { TF_RETURN_IF_ERROR(oauth_client_->GetTokenFromServiceAccountJson( json, kOAuthV4Url, kOAuthScope, &current_token_, &expiration_timestamp_sec_)); } else { return errors::FailedPrecondition( "Unexpected content of the JSON credentials file."); } return OkStatus(); } Status GoogleAuthProvider::GetTokenFromGce() { std::vector<char> response_buffer; const uint64 request_timestamp_sec = env_->NowSeconds(); TF_RETURN_IF_ERROR(compute_engine_metadata_client_->GetMetadata( kGceTokenPath, &response_buffer)); StringPiece response = StringPiece(&response_buffer[0], response_buffer.size()); TF_RETURN_IF_ERROR(oauth_client_->ParseOAuthResponse( response, request_timestamp_sec, &current_token_, &expiration_timestamp_sec_)); return OkStatus(); } Status GoogleAuthProvider::GetTokenForTesting() { const char* token = std::getenv(kGoogleAuthTokenForTesting); if (!token) { return errors::NotFound("The env variable for testing was not set."); } expiration_timestamp_sec_ = UINT64_MAX; current_token_ = token; return OkStatus(); } }
#include "tsl/platform/cloud/google_auth_provider.h" #include <stdlib.h> #include "tsl/lib/core/status_test_util.h" #include "tsl/platform/cloud/http_request_fake.h" #include "tsl/platform/path.h" #include "tsl/platform/test.h" namespace tsl { namespace { string TestData() { return io::JoinPath(testing::TslSrcRoot(), "platform", "cloud", "testdata"); } class FakeEnv : public EnvWrapper { public: FakeEnv() : EnvWrapper(Env::Default()) {} uint64 NowSeconds() const override { return now; } uint64 now = 10000; }; class FakeOAuthClient : public OAuthClient { public: Status GetTokenFromServiceAccountJson( Json::Value json, StringPiece oauth_server_uri, StringPiece scope, string* token, uint64* expiration_timestamp_sec) override { provided_credentials_json = json; *token = return_token; *expiration_timestamp_sec = return_expiration_timestamp; return OkStatus(); } Status GetTokenFromRefreshTokenJson( Json::Value json, StringPiece oauth_server_uri, string* token, uint64* expiration_timestamp_sec) override { provided_credentials_json = json; *token = return_token; *expiration_timestamp_sec = return_expiration_timestamp; return OkStatus(); } string return_token; uint64 return_expiration_timestamp; Json::Value provided_credentials_json; }; } class GoogleAuthProviderTest : public ::testing::Test { protected: void SetUp() override { ClearEnvVars(); } void TearDown() override { ClearEnvVars(); } void ClearEnvVars() { unsetenv("CLOUDSDK_CONFIG"); unsetenv("GOOGLE_APPLICATION_CREDENTIALS"); unsetenv("GOOGLE_AUTH_TOKEN_FOR_TESTING"); unsetenv("NO_GCE_CHECK"); } }; TEST_F(GoogleAuthProviderTest, EnvironmentVariable_Caching) { setenv("GOOGLE_APPLICATION_CREDENTIALS", io::JoinPath(TestData(), "service_account_credentials.json").c_str(), 1); setenv("CLOUDSDK_CONFIG", TestData().c_str(), 1); auto oauth_client = new FakeOAuthClient; std::vector<HttpRequest*> requests; FakeEnv env; std::shared_ptr<HttpRequest::Factory> fakeHttpRequestFactory = std::make_shared<FakeHttpRequestFactory>(&requests); auto metadataClient = std::make_shared<ComputeEngineMetadataClient>( fakeHttpRequestFactory, RetryConfig(0 )); GoogleAuthProvider provider(std::unique_ptr<OAuthClient>(oauth_client), metadataClient, &env); oauth_client->return_token = "fake-token"; oauth_client->return_expiration_timestamp = env.NowSeconds() + 3600; string token; TF_EXPECT_OK(provider.GetToken(&token)); EXPECT_EQ("fake-token", token); EXPECT_EQ("fake_key_id", oauth_client->provided_credentials_json.get("private_key_id", "") .asString()); oauth_client->return_token = "new-fake-token"; env.now += 3000; TF_EXPECT_OK(provider.GetToken(&token)); EXPECT_EQ("fake-token", token); env.now += 598; TF_EXPECT_OK(provider.GetToken(&token)); EXPECT_EQ("new-fake-token", token); } TEST_F(GoogleAuthProviderTest, GCloudRefreshToken) { setenv("CLOUDSDK_CONFIG", TestData().c_str(), 1); auto oauth_client = new FakeOAuthClient; std::vector<HttpRequest*> requests; FakeEnv env; std::shared_ptr<HttpRequest::Factory> fakeHttpRequestFactory = std::make_shared<FakeHttpRequestFactory>(&requests); auto metadataClient = std::make_shared<ComputeEngineMetadataClient>( fakeHttpRequestFactory, RetryConfig(0 )); GoogleAuthProvider provider(std::unique_ptr<OAuthClient>(oauth_client), metadataClient, &env); oauth_client->return_token = "fake-token"; oauth_client->return_expiration_timestamp = env.NowSeconds() + 3600; string token; TF_EXPECT_OK(provider.GetToken(&token)); EXPECT_EQ("fake-token", token); EXPECT_EQ("fake-refresh-token", oauth_client->provided_credentials_json.get("refresh_token", "") .asString()); } TEST_F(GoogleAuthProviderTest, RunningOnGCE) { auto oauth_client = new FakeOAuthClient; std::vector<HttpRequest*> requests( {new FakeHttpRequest( "Uri: http: "/service-accounts/default/token\n" "Header Metadata-Flavor: Google\n", R"( { "access_token":"fake-gce-token", "expires_in": 3920, "token_type":"Bearer" })"), new FakeHttpRequest( "Uri: http: "/service-accounts/default/token\n" "Header Metadata-Flavor: Google\n", "", errors::Unavailable("503"), 503), new FakeHttpRequest( "Uri: http: "/service-accounts/default/token\n" "Header Metadata-Flavor: Google\n", R"( { "access_token":"new-fake-gce-token", "expires_in": 3920, "token_type":"Bearer" })")}); FakeEnv env; std::shared_ptr<HttpRequest::Factory> fakeHttpRequestFactory = std::make_shared<FakeHttpRequestFactory>(&requests); auto metadataClient = std::make_shared<ComputeEngineMetadataClient>( fakeHttpRequestFactory, RetryConfig(0 )); GoogleAuthProvider provider(std::unique_ptr<OAuthClient>(oauth_client), metadataClient, &env); string token; TF_EXPECT_OK(provider.GetToken(&token)); EXPECT_EQ("fake-gce-token", token); env.now += 3700; TF_EXPECT_OK(provider.GetToken(&token)); EXPECT_EQ("fake-gce-token", token); env.now += 598; TF_EXPECT_OK(provider.GetToken(&token)); EXPECT_EQ("new-fake-gce-token", token); } TEST_F(GoogleAuthProviderTest, OverrideForTesting) { setenv("GOOGLE_AUTH_TOKEN_FOR_TESTING", "tokenForTesting", 1); auto oauth_client = new FakeOAuthClient; std::vector<HttpRequest*> empty_requests; FakeEnv env; std::shared_ptr<HttpRequest::Factory> fakeHttpRequestFactory = std::make_shared<FakeHttpRequestFactory>(&empty_requests); auto metadataClient = std::make_shared<ComputeEngineMetadataClient>( fakeHttpRequestFactory, RetryConfig(0 )); GoogleAuthProvider provider(std::unique_ptr<OAuthClient>(oauth_client), metadataClient, &env); string token; TF_EXPECT_OK(provider.GetToken(&token)); EXPECT_EQ("tokenForTesting", token); } TEST_F(GoogleAuthProviderTest, NothingAvailable) { auto oauth_client = new FakeOAuthClient; std::vector<HttpRequest*> requests({new FakeHttpRequest( "Uri: http: "/service-accounts/default/token\n" "Header Metadata-Flavor: Google\n", "", errors::NotFound("404"), 404)}); FakeEnv env; std::shared_ptr<HttpRequest::Factory> fakeHttpRequestFactory = std::make_shared<FakeHttpRequestFactory>(&requests); auto metadataClient = std::make_shared<ComputeEngineMetadataClient>( fakeHttpRequestFactory, RetryConfig(0 )); GoogleAuthProvider provider(std::unique_ptr<OAuthClient>(oauth_client), metadataClient, &env); string token; TF_EXPECT_OK(provider.GetToken(&token)); EXPECT_EQ("", token); } TEST_F(GoogleAuthProviderTest, NoGceCheckEnvironmentVariable) { setenv("NO_GCE_CHECK", "True", 1); auto oauth_client = new FakeOAuthClient; FakeEnv env; GoogleAuthProvider provider(std::unique_ptr<OAuthClient>(oauth_client), nullptr, &env); string token; TF_EXPECT_OK(provider.GetToken(&token)); EXPECT_EQ("", token); setenv("NO_GCE_CHECK", "true", 1); TF_EXPECT_OK(provider.GetToken(&token)); EXPECT_EQ("", token); setenv("GOOGLE_AUTH_TOKEN_FOR_TESTING", "newToken", 1); TF_EXPECT_OK(provider.GetToken(&token)); EXPECT_EQ("newToken", token); } }
2,610
cpp
google/tsl
gcs_file_system
tsl/platform/cloud/gcs_file_system.cc
tsl/platform/cloud/gcs_file_system_test.cc
#ifndef TENSORFLOW_TSL_PLATFORM_CLOUD_GCS_FILE_SYSTEM_H_ #define TENSORFLOW_TSL_PLATFORM_CLOUD_GCS_FILE_SYSTEM_H_ #include <string> #include <unordered_set> #include <utility> #include <vector> #include "tsl/platform/cloud/auth_provider.h" #include "tsl/platform/cloud/compute_engine_metadata_client.h" #include "tsl/platform/cloud/compute_engine_zone_provider.h" #include "tsl/platform/cloud/expiring_lru_cache.h" #include "tsl/platform/cloud/file_block_cache.h" #include "tsl/platform/cloud/gcs_dns_cache.h" #include "tsl/platform/cloud/gcs_throttle.h" #include "tsl/platform/cloud/http_request.h" #include "tsl/platform/file_system.h" #include "tsl/platform/retrying_file_system.h" #include "tsl/platform/status.h" namespace tsl { class GcsFileSystem; constexpr char kBlockSize[] = "GCS_READ_CACHE_BLOCK_SIZE_MB"; #if defined(LIBTPU_ON_GCE) constexpr size_t kDefaultBlockSize = 512 * 1024 * 1024; #else constexpr size_t kDefaultBlockSize = 64 * 1024 * 1024; #endif constexpr char kMaxCacheSize[] = "GCS_READ_CACHE_MAX_SIZE_MB"; #if defined(LIBTPU_ON_GCE) constexpr size_t kDefaultMaxCacheSize = 163840LL * 1024LL * 1024LL; #else constexpr size_t kDefaultMaxCacheSize = 0; #endif constexpr char kMaxStaleness[] = "GCS_READ_CACHE_MAX_STALENESS"; constexpr uint64 kDefaultMaxStaleness = 0; template <typename T> bool GetEnvVar(const char* varname, bool (*convert)(StringPiece, T*), T* value) { const char* env_value = std::getenv(varname); if (env_value == nullptr) { return false; } return convert(env_value, value); } class GcsStatsInterface { public: virtual void Configure(GcsFileSystem* fs, GcsThrottle* throttle, const FileBlockCache* block_cache) = 0; virtual void RecordBlockLoadRequest(const string& file, size_t offset) = 0; virtual void RecordBlockRetrieved(const string& file, size_t offset, size_t bytes_transferred) = 0; virtual void RecordStatObjectRequest() = 0; virtual HttpRequest::RequestStats* HttpStats() = 0; virtual ~GcsStatsInterface() = default; }; struct UploadSessionHandle { std::string session_uri; bool resumable; }; class GcsFileSystem : public FileSystem { public: struct TimeoutConfig; explicit GcsFileSystem(bool make_default_cache = true); GcsFileSystem(std::unique_ptr<AuthProvider> auth_provider, std::unique_ptr<HttpRequest::Factory> http_request_factory, std::unique_ptr<ZoneProvider> zone_provider, size_t block_size, size_t max_bytes, uint64 max_staleness, uint64 stat_cache_max_age, size_t stat_cache_max_entries, uint64 matching_paths_cache_max_age, size_t matching_paths_cache_max_entries, RetryConfig retry_config, TimeoutConfig timeouts, const std::unordered_set<string>& allowed_locations, std::pair<const string, const string>* additional_header, bool compose_append); TF_USE_FILESYSTEM_METHODS_WITH_NO_TRANSACTION_SUPPORT; Status NewRandomAccessFile( const string& fname, TransactionToken* token, std::unique_ptr<RandomAccessFile>* result) override; Status NewWritableFile(const string& fname, TransactionToken* token, std::unique_ptr<WritableFile>* result) override; Status NewAppendableFile(const string& fname, TransactionToken* token, std::unique_ptr<WritableFile>* result) override; Status NewReadOnlyMemoryRegionFromFile( const string& fname, TransactionToken* token, std::unique_ptr<ReadOnlyMemoryRegion>* result) override; Status FileExists(const string& fname, TransactionToken* token) override; Status Stat(const string& fname, TransactionToken* token, FileStatistics* stat) override; Status GetChildren(const string& dir, TransactionToken* token, std::vector<string>* result) override; Status GetMatchingPaths(const string& pattern, TransactionToken* token, std::vector<string>* results) override; Status DeleteFile(const string& fname, TransactionToken* token) override; Status CreateDir(const string& dirname, TransactionToken* token) override; Status DeleteDir(const string& dirname, TransactionToken* token) override; Status GetFileSize(const string& fname, TransactionToken* token, uint64* file_size) override; Status RenameFile(const string& src, const string& target, TransactionToken* token) override; Status IsDirectory(const string& fname, TransactionToken* token) override; Status DeleteRecursively(const string& dirname, TransactionToken* token, int64_t* undeleted_files, int64_t* undeleted_dirs) override; void FlushCaches(TransactionToken* token) override; void SetStats(GcsStatsInterface* stats); void SetCacheStats(FileBlockCacheStatsInterface* cache_stats); size_t block_size() { tf_shared_lock l(block_cache_lock_); return file_block_cache_->block_size(); } size_t max_bytes() { tf_shared_lock l(block_cache_lock_); return file_block_cache_->max_bytes(); } uint64 max_staleness() { tf_shared_lock l(block_cache_lock_); return file_block_cache_->max_staleness(); } TimeoutConfig timeouts() const { return timeouts_; } std::unordered_set<string> allowed_locations() const { return allowed_locations_; } bool compose_append() const { return compose_append_; } string additional_header_name() const { return additional_header_ ? additional_header_->first : ""; } string additional_header_value() const { return additional_header_ ? additional_header_->second : ""; } uint64 stat_cache_max_age() const { return stat_cache_->max_age(); } size_t stat_cache_max_entries() const { return stat_cache_->max_entries(); } uint64 matching_paths_cache_max_age() const { return matching_paths_cache_->max_age(); } size_t matching_paths_cache_max_entries() const { return matching_paths_cache_->max_entries(); } struct TimeoutConfig { uint32 connect = 120; uint32 idle = 60; uint32 metadata = 3600; uint32 read = 3600; uint32 write = 3600; TimeoutConfig() {} TimeoutConfig(uint32 connect, uint32 idle, uint32 metadata, uint32 read, uint32 write) : connect(connect), idle(idle), metadata(metadata), read(read), write(write) {} }; Status CreateHttpRequest(std::unique_ptr<HttpRequest>* request); void SetAuthProvider(std::unique_ptr<AuthProvider> auth_provider); void ResetFileBlockCache(size_t block_size_bytes, size_t max_bytes, uint64 max_staleness_secs); protected: virtual std::unique_ptr<FileBlockCache> MakeFileBlockCache( size_t block_size, size_t max_bytes, uint64 max_staleness); virtual Status LoadBufferFromGCS(const string& fname, size_t offset, size_t n, char* buffer, size_t* bytes_transferred); virtual Status CreateNewUploadSession(uint64 start_offset, const std::string& object_to_upload, const std::string& bucket, uint64 file_size, const std::string& gcs_path, UploadSessionHandle* session_handle); virtual Status UploadToSession(const std::string& session_uri, uint64 start_offset, uint64 already_uploaded, const std::string& tmp_content_filename, uint64 file_size, const std::string& file_path); virtual Status RequestUploadSessionStatus(const string& session_uri, uint64 file_size, const std::string& gcs_path, bool* completed, uint64* uploaded); Status ParseGcsPathForScheme(StringPiece fname, string scheme, bool empty_object_ok, string* bucket, string* object); virtual Status ParseGcsPath(StringPiece fname, bool empty_object_ok, string* bucket, string* object); std::shared_ptr<ComputeEngineMetadataClient> compute_engine_metadata_client_; TimeoutConfig timeouts_; RetryConfig retry_config_; private: struct GcsFileStat { FileStatistics base; int64_t generation_number = 0; }; Status BucketExists(const string& bucket, bool* result); Status GetBucketLocation(const string& bucket, string* location); Status CheckBucketLocationConstraint(const string& bucket); Status GetBucketMetadata(const string& bucket, std::vector<char>* result_buffer); Status ObjectExists(const string& fname, const string& bucket, const string& object, bool* result); Status FolderExists(const string& dirname, bool* result); Status GetChildrenBounded(const string& dir, uint64 max_results, std::vector<string>* result, bool recursively, bool include_self_directory_marker); Status StatForObject(const string& fname, const string& bucket, const string& object, GcsFileStat* stat); Status UncachedStatForObject(const string& fname, const string& bucket, const string& object, GcsFileStat* stat); Status RenameObject(const string& src, const string& target); void ClearFileCaches(const string& fname); mutex mu_; std::unique_ptr<AuthProvider> auth_provider_ TF_GUARDED_BY(mu_); std::shared_ptr<HttpRequest::Factory> http_request_factory_; std::unique_ptr<ZoneProvider> zone_provider_; uint64 block_size_; mutex block_cache_lock_; std::unique_ptr<FileBlockCache> file_block_cache_ TF_GUARDED_BY(block_cache_lock_); bool cache_enabled_; std::unique_ptr<GcsDnsCache> dns_cache_; GcsThrottle throttle_; using StatCache = ExpiringLRUCache<GcsFileStat>; std::unique_ptr<StatCache> stat_cache_; using MatchingPathsCache = ExpiringLRUCache<std::vector<string>>; std::unique_ptr<MatchingPathsCache> matching_paths_cache_; using BucketLocationCache = ExpiringLRUCache<string>; std::unique_ptr<BucketLocationCache> bucket_location_cache_; std::unordered_set<string> allowed_locations_; bool compose_append_; GcsStatsInterface* stats_ = nullptr; std::unique_ptr<std::pair<const string, const string>> additional_header_; GcsFileSystem(const GcsFileSystem&) = delete; void operator=(const GcsFileSystem&) = delete; }; class RetryingGcsFileSystem : public RetryingFileSystem<GcsFileSystem> { public: RetryingGcsFileSystem(); }; } #endif #include "tsl/platform/cloud/gcs_file_system.h" #include <stdio.h> #include "absl/status/status.h" #include "absl/strings/str_cat.h" #ifndef _WIN32 #include <unistd.h> #endif #include <algorithm> #include <cstdio> #include <cstdlib> #include <cstring> #include <fstream> #include <functional> #include <string> #include <utility> #include <vector> #include "tsl/platform/file_statistics.h" #include "tsl/platform/strcat.h" #ifdef _WIN32 #include <io.h> #endif #include "absl/base/macros.h" #include "json/json.h" #include "tsl/platform/cloud/curl_http_request.h" #include "tsl/platform/cloud/file_block_cache.h" #include "tsl/platform/cloud/google_auth_provider.h" #include "tsl/platform/cloud/ram_file_block_cache.h" #include "tsl/platform/cloud/time_util.h" #include "tsl/platform/env.h" #include "tsl/platform/errors.h" #include "tsl/platform/mutex.h" #include "tsl/platform/numbers.h" #include "tsl/platform/path.h" #include "tsl/platform/protobuf.h" #include "tsl/platform/retrying_utils.h" #include "tsl/platform/str_util.h" #include "tsl/platform/stringprintf.h" #include "tsl/platform/thread_annotations.h" #include "tsl/profiler/lib/traceme.h" #ifdef _WIN32 #ifdef DeleteFile #undef DeleteFile #endif #endif namespace tsl { namespace { constexpr char kGcsUriBase[] = "https: constexpr char kGcsUploadUriBase[] = "https: constexpr char kStorageHost[] = "storage.googleapis.com"; constexpr char kBucketMetadataLocationKey[] = "location"; constexpr size_t kReadAppendableFileBufferSize = 1024 * 1024; constexpr int kGetChildrenDefaultPageSize = 1000; constexpr uint64 HTTP_CODE_RESUME_INCOMPLETE = 308; constexpr uint64 HTTP_CODE_PRECONDITION_FAILED = 412; ABSL_DEPRECATED("Use GCS_READ_CACHE_BLOCK_SIZE_MB instead.") constexpr char kReadaheadBufferSize[] = "GCS_READAHEAD_BUFFER_SIZE_BYTES"; constexpr char kStatCacheMaxAge[] = "GCS_STAT_CACHE_MAX_AGE"; constexpr uint64 kStatCacheDefaultMaxAge = 5; constexpr char kStatCacheMaxEntries[] = "GCS_STAT_CACHE_MAX_ENTRIES"; constexpr size_t kStatCacheDefaultMaxEntries = 1024; constexpr char kMatchingPathsCacheMaxAge[] = "GCS_MATCHING_PATHS_CACHE_MAX_AGE"; constexpr uint64 kMatchingPathsCacheDefaultMaxAge = 0; constexpr char kMatchingPathsCacheMaxEntries[] = "GCS_MATCHING_PATHS_CACHE_MAX_ENTRIES"; constexpr size_t kMatchingPathsCacheDefaultMaxEntries = 1024; constexpr size_t kBucketLocationCacheMaxEntries = 10; constexpr size_t kCacheNeverExpire = std::numeric_limits<uint64>::max(); const FileStatistics DIRECTORY_STAT(0, 0, true); constexpr char kResolveCacheSecs[] = "GCS_RESOLVE_REFRESH_SECS"; constexpr char kRequestConnectionTimeout[] = "GCS_REQUEST_CONNECTION_TIMEOUT_SECS"; constexpr char kRequestIdleTimeout[] = "GCS_REQUEST_IDLE_TIMEOUT_SECS"; constexpr char kMetadataRequestTimeout[] = "GCS_METADATA_REQUEST_TIMEOUT_SECS"; constexpr char kReadRequestTimeout[] = "GCS_READ_REQUEST_TIMEOUT_SECS"; constexpr char kWriteRequestTimeout[] = "GCS_WRITE_REQUEST_TIMEOUT_SECS"; constexpr char kAdditionalRequestHeader[] = "GCS_ADDITIONAL_REQUEST_HEADER"; constexpr char kThrottleRate[] = "GCS_THROTTLE_TOKEN_RATE"; constexpr char kThrottleBucket[] = "GCS_THROTTLE_BUCKET_SIZE"; constexpr char kTokensPerRequest[] = "GCS_TOKENS_PER_REQUEST"; constexpr char kInitialTokens[] = "GCS_INITIAL_TOKENS"; constexpr char kRetryConfigInitialDelayTimeUs[] = "GCS_RETRY_CONFIG_INIT_DELAY_TIME_US"; constexpr char kRetryConfigMaxDelayTimeUs[] = "GCS_RETRY_CONFIG_MAX_DELAY_TIME_US"; constexpr char kRetryConfigMaxRetries[] = "GCS_RETRY_CONFIG_MAX_RETRIES"; constexpr char kAllowedBucketLocations[] = "GCS_ALLOWED_BUCKET_LOCATIONS"; constexpr char kDetectZoneSentinelValue[] = "auto"; constexpr char kAppendMode[] = "GCS_APPEND_MODE"; constexpr char kComposeAppend[] = "compose"; Status GetTmpFilename(string* filename) { *filename = io::GetTempFilename(""); return OkStatus(); } string MaybeAppendSlash(const string& name) { if (name.empty()) { return "/"; } if (name.back() != '/') { return strings::StrCat(name, "/"); } return name; } string JoinGcsPath(const string& path, const string& subpath) { return strings::StrCat(MaybeAppendSlash(path), subpath); } std::set<string> AddAllSubpaths(const std::vector<string>& paths) { std::set<string> result; result.insert(paths.begin(), paths.end()); for (const string& path : paths) { StringPiece subpath = io::Dirname(path); while (!(subpath.empty() || subpath == "/")) { result.emplace(string(subpath)); subpath = io::Dirname(subpath); } } return result; } Status ParseJson(StringPiece json, Json::Value* result) { Json::Reader reader; if (!reader.parse(json.data(), json.data() + json.size(), *result)) { return errors::Internal("Couldn't parse JSON response from GCS."); } return OkStatus(); } Status ParseJson(const std::vector<char>& json, Json::Value* result) { return ParseJson(StringPiece{json.data(), json.size()}, result); } Status GetValue(const Json::Value& parent, const char* name, Json::Value* result) { *result = parent.get(name, Json::Value::null); if (result->isNull()) { return errors::Internal("The field '", name, "' was expected in the JSON response."); } return OkStatus(); } Status GetStringValue(const Json::Value& parent, const char* name, string* result) { Json::Value result_value; TF_RETURN_IF_ERROR(GetValue(parent, name, &result_value)); if (!result_value.isString()) { return errors::Internal( "The field '", name, "' in the JSON response was expected to be a string."); } *result = result_value.asString(); return OkStatus(); } Status GetInt64Value(const Json::Value& parent, const char* name, int64_t* result) { Json::Value result_value; TF_RETURN_IF_ERROR(GetValue(parent, name, &result_value)); if (result_value.isNumeric()) { *result = result_value.asInt64(); return OkStatus(); } if (result_value.isString() && strings::safe_strto64(result_value.asCString(), result)) { return OkStatus(); } return errors::Internal( "The field '", name, "' in the JSON response was expected to be a number."); } Status GetBoolValue(const Json::Value& parent, const char* name, bool* result) { Json::Value result_value; TF_RETURN_IF_ERROR(GetValue(parent, name, &result_value)); if (!result_value.isBool()) { return errors::Internal( "The field '", name, "' in the JSON response was expected to be a boolean."); } *result = result_value.asBool(); return OkStatus(); } RetryConfig GetGcsRetryConfig() { RetryConfig retryConfig( 1000 * 1000, 32 * 1000 * 1000, 10); uint64 init_delay_time_us; if (GetEnvVar(kRetryConfigInitialDelayTimeUs, strings::safe_strtou64, &init_delay_time_us)) { retryConfig.init_delay_time_us = init_delay_time_us; } uint64 max_delay_time_us; if (GetEnvVar(kRetryConfigMaxDelayTimeUs, strings::safe_strtou64, &max_delay_time_us)) { retryConfig.max_delay_time_us = max_delay_time_us; } uint32 max_retries; if (GetEnvVar(kRetryConfigMaxRetries, strings::safe_strtou32, &max_retries)) { retryConfig.max_retries = max_retries; } VLOG(1) << "GCS RetryConfig: " << "init_delay_time_us = " << retryConfig.init_delay_time_us << " ; " << "max_delay_time_us = " << retryConfig.max_delay_time_us << " ; " << "max_retries = " << retryConfig.max_retries; return retryConfig; } class GcsRandomAccessFile : public RandomAccessFile { public: using ReadFn = std::function<Status(const string& filename, uint64 offset, size_t n, StringPiece* result, char* scratch)>; GcsRandomAccessFile(const string& filename, ReadFn read_fn) : filename_(filename), read_fn_(std::move(read_fn)) {} Status Name(StringPiece* result) const override { *result = filename_; return OkStatus(); } Status Read(uint64 offset, size_t n, StringPiece* result, char* scratch) const override { return read_fn_(filename_, offset, n, result, scratch); } private: const string filename_; const ReadFn read_fn_; }; class BufferedGcsRandomAccessFile : public RandomAccessFile { public: using ReadFn = std::function<Status(const string& filename, uint64 offset, size_t n, StringPiece* result, char* scratch)>; BufferedGcsRandomAccessFile(const string& filename, uint64 buffer_size, ReadFn read_fn) : filename_(filename),
#include "tsl/platform/cloud/gcs_file_system.h" #include <fstream> #include "tsl/lib/core/status_test_util.h" #include "tsl/platform/cloud/http_request_fake.h" #include "tsl/platform/errors.h" #include "tsl/platform/str_util.h" #include "tsl/platform/strcat.h" #include "tsl/platform/test.h" #ifdef PLATFORM_WINDOWS #undef DeleteFile #endif namespace tsl { namespace { static GcsFileSystem::TimeoutConfig kTestTimeoutConfig(5, 1, 10, 20, 30); static RetryConfig kTestRetryConfig(0 ); static std::unordered_set<string>* kAllowedLocationsDefault = new std::unordered_set<string>(); static std::unordered_set<string>* kAllowedLocationsAuto = new std::unordered_set<string>({"auto"}); class FakeAuthProvider : public AuthProvider { public: Status GetToken(string* token) override { *token = "fake_token"; return OkStatus(); } }; class FakeZoneProvider : public ZoneProvider { public: Status GetZone(string* zone) override { *zone = "us-east1-b"; return OkStatus(); } }; TEST(GcsFileSystemTest, NewRandomAccessFile_NoBlockCache) { std::vector<HttpRequest*> requests( {new FakeHttpRequest( "Uri: https: "Auth Token: fake_token\n" "Range: 0-5\n" "Timeouts: 5 1 20\n", "012345"), new FakeHttpRequest( "Uri: https: "Auth Token: fake_token\n" "Range: 6-11\n" "Timeouts: 5 1 20\n", "6789")}); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 0 , 0 , 0 , 0 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); std::unique_ptr<RandomAccessFile> file; TF_EXPECT_OK( fs.NewRandomAccessFile("gs: StringPiece filename; TF_EXPECT_OK(file->Name(&filename)); EXPECT_EQ(filename, "gs: char scratch[6]; StringPiece result; TF_EXPECT_OK(file->Read(0, sizeof(scratch), &result, scratch)); EXPECT_EQ("012345", result); EXPECT_TRUE(errors::IsOutOfRange( file->Read(sizeof(scratch), sizeof(scratch), &result, scratch))); EXPECT_EQ("6789", result); } TEST(GcsFileSystemTest, NewRandomAccessFile_Buffered) { std::vector<HttpRequest*> requests({ new FakeHttpRequest( "Uri: https: "Auth Token: fake_token\n" "Range: 0-9\n" "Timeouts: 5 1 20\n", "0123456789"), new FakeHttpRequest( "Uri: https: "Auth Token: fake_token\n" "Range: 10-19\n" "Timeouts: 5 1 20\n", ""), }); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 10 , 0 , 0 , 0 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); std::unique_ptr<RandomAccessFile> file; TF_EXPECT_OK( fs.NewRandomAccessFile("gs: StringPiece filename; TF_EXPECT_OK(file->Name(&filename)); EXPECT_EQ(filename, "gs: char scratch[6]; StringPiece result; TF_EXPECT_OK(file->Read(0, sizeof(scratch), &result, scratch)); EXPECT_EQ("012345", result); EXPECT_TRUE(errors::IsOutOfRange( file->Read(sizeof(scratch), sizeof(scratch), &result, scratch))); EXPECT_EQ("6789", result); } TEST(GcsFileSystemTest, NewRandomAccessFile_Buffered_Errors) { std::vector<HttpRequest*> requests({ new FakeHttpRequest( "Uri: https: "Auth Token: fake_token\n" "Range: 0-9\n" "Timeouts: 5 1 20\n", "Server Not", errors::Unavailable("important HTTP error 308"), nullptr, {}, 308), new FakeHttpRequest( "Uri: https: "Auth Token: fake_token\n" "Range: 6-15\n" "Timeouts: 5 1 20\n", "123"), }); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 10 , 0 , 0 , 0 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); std::unique_ptr<RandomAccessFile> file; TF_EXPECT_OK( fs.NewRandomAccessFile("gs: StringPiece filename; TF_EXPECT_OK(file->Name(&filename)); EXPECT_EQ(filename, "gs: char scratch[6]; StringPiece result; EXPECT_TRUE( errors::IsUnavailable(file->Read(0, sizeof(scratch), &result, scratch))); EXPECT_EQ("", result); EXPECT_TRUE(errors::IsOutOfRange( file->Read(sizeof(scratch), sizeof(scratch), &result, scratch))); EXPECT_EQ("123", result); } TEST(GcsFileSystemTest, NewRandomAccessFile_Buffered_ReadAtEOF) { std::vector<HttpRequest*> requests( {new FakeHttpRequest( "Uri: https: "Auth Token: fake_token\n" "Range: 0-9\n" "Timeouts: 5 1 20\n", "0123456789"), new FakeHttpRequest( "Uri: https: "Auth Token: fake_token\n" "Range: 10-19\n" "Timeouts: 5 1 20\n", "")}); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 10 , 0 , 0 , 0 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); std::unique_ptr<RandomAccessFile> file; TF_EXPECT_OK( fs.NewRandomAccessFile("gs: StringPiece filename; TF_EXPECT_OK(file->Name(&filename)); EXPECT_EQ(filename, "gs: char scratch[10]; StringPiece result; TF_EXPECT_OK(file->Read(0, sizeof(scratch), &result, scratch)); EXPECT_EQ("0123456789", result); EXPECT_TRUE(errors::IsOutOfRange( file->Read(sizeof(scratch), sizeof(scratch), &result, scratch))); EXPECT_EQ("", result); } TEST(GcsFileSystemTest, NewRandomAccessFile_Buffered_CachedOutOfRange) { std::vector<HttpRequest*> requests({new FakeHttpRequest( "Uri: https: "Auth Token: fake_token\n" "Range: 0-9\n" "Timeouts: 5 1 20\n", "012345678")}); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 10 , 0 , 0 , 0 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); std::unique_ptr<RandomAccessFile> file; TF_EXPECT_OK( fs.NewRandomAccessFile("gs: StringPiece filename; TF_EXPECT_OK(file->Name(&filename)); EXPECT_EQ(filename, "gs: char scratch[5]; StringPiece result; TF_EXPECT_OK(file->Read(0, sizeof(scratch), &result, scratch)); EXPECT_EQ("01234", result); TF_EXPECT_OK(file->Read(4, sizeof(scratch), &result, scratch)); EXPECT_EQ("45678", result); EXPECT_TRUE( errors::IsOutOfRange(file->Read(5, sizeof(scratch), &result, scratch))); EXPECT_EQ("5678", result); } TEST(GcsFileSystemTest, NewRandomAccessFile_Buffered_CachedNotSequential) { std::vector<HttpRequest*> requests( {new FakeHttpRequest( "Uri: https: "Auth Token: fake_token\n" "Range: 1-10\n" "Timeouts: 5 1 20\n", "12345678"), new FakeHttpRequest( "Uri: https: "Auth Token: fake_token\n" "Range: 0-9\n" "Timeouts: 5 1 20\n", "012345678")}); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 10 , 0 , 0 , 0 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); std::unique_ptr<RandomAccessFile> file; TF_EXPECT_OK( fs.NewRandomAccessFile("gs: StringPiece filename; TF_EXPECT_OK(file->Name(&filename)); EXPECT_EQ(filename, "gs: char scratch[5]; StringPiece result; TF_EXPECT_OK(file->Read(1, sizeof(scratch), &result, scratch)); EXPECT_EQ("12345", result); TF_EXPECT_OK(file->Read(0, sizeof(scratch), &result, scratch)); EXPECT_EQ("01234", result); } TEST(GcsFileSystemTest, NewRandomAccessFile_Buffered_Growing) { std::vector<HttpRequest*> requests( {new FakeHttpRequest( "Uri: https: "Auth Token: fake_token\n" "Range: 0-9\n" "Timeouts: 5 1 20\n", "012345678"), new FakeHttpRequest( "Uri: https: "Auth Token: fake_token\n" "Range: 9-18\n" "Timeouts: 5 1 20\n", "9")}); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 10 , 0 , 0 , 0 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); std::unique_ptr<RandomAccessFile> file; TF_EXPECT_OK( fs.NewRandomAccessFile("gs: StringPiece filename; TF_EXPECT_OK(file->Name(&filename)); EXPECT_EQ(filename, "gs: char scratch[10]; StringPiece result; EXPECT_TRUE( errors::IsOutOfRange(file->Read(0, sizeof(scratch), &result, scratch))); EXPECT_EQ("012345678", result); TF_EXPECT_OK(file->Read(0, sizeof(scratch), &result, scratch)); EXPECT_EQ("0123456789", result); } TEST(GcsFileSystemTest, NewRandomAccessFile_Buffered_ReadBackwards) { std::vector<HttpRequest*> requests( {new FakeHttpRequest( "Uri: https: "Auth Token: fake_token\n" "Range: 5-14\n" "Timeouts: 5 1 20\n", "56789"), new FakeHttpRequest( "Uri: https: "Auth Token: fake_token\n" "Range: 0-9\n" "Timeouts: 5 1 20\n", "0123456789")}); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 10 , 0 , 0 , 0 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); std::unique_ptr<RandomAccessFile> file; TF_EXPECT_OK( fs.NewRandomAccessFile("gs: StringPiece filename; TF_EXPECT_OK(file->Name(&filename)); EXPECT_EQ(filename, "gs: char scratch[10]; StringPiece result; EXPECT_TRUE( errors::IsOutOfRange(file->Read(5, sizeof(scratch), &result, scratch))); EXPECT_EQ("56789", result); TF_EXPECT_OK(file->Read(0, sizeof(scratch), &result, scratch)); EXPECT_EQ("0123456789", result); } TEST(GcsFileSystemTest, NewRandomAccessFile_WithLocationConstraintInSameLocation) { std::vector<HttpRequest*> requests({new FakeHttpRequest( "Uri: https: "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", R"( { "location":"US-EAST1" })")}); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 0 , 0 , 0 , 0 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsAuto, nullptr , false ); std::unique_ptr<RandomAccessFile> file; TF_EXPECT_OK( fs.NewRandomAccessFile("gs: } TEST(GcsFileSystemTest, NewRandomAccessFile_WithLocationConstraintCaching) { std::vector<HttpRequest*> requests( {new FakeHttpRequest( "Uri: https: "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", R"( { "location":"US-EAST1" })"), new FakeHttpRequest( "Uri: https: "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", R"( { "location":"US-EAST1" })"), new FakeHttpRequest( "Uri: https: "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", R"( { "location":"US-EAST1" })")}); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 0 , 0 , 0 , 0 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsAuto, nullptr , false ); std::unique_ptr<RandomAccessFile> file; string bucket = "gs: string another_bucket = "gs: TF_EXPECT_OK(fs.NewRandomAccessFile(bucket, nullptr, &file)); TF_EXPECT_OK(fs.NewRandomAccessFile(bucket, nullptr, &file)); TF_EXPECT_OK(fs.NewRandomAccessFile(another_bucket, nullptr, &file)); TF_EXPECT_OK(fs.NewRandomAccessFile(bucket, nullptr, &file)); TF_EXPECT_OK(fs.NewRandomAccessFile(another_bucket, nullptr, &file)); fs.FlushCaches(nullptr); TF_EXPECT_OK(fs.NewRandomAccessFile(bucket, nullptr, &file)); } TEST(GcsFileSystemTest, NewRandomAccessFile_WithLocationConstraintInDifferentLocation) { std::vector<HttpRequest*> requests({new FakeHttpRequest( "Uri: https: "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", R"( { "location":"BARFOO" })")}); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 0 , 0 , 0 , 0 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsAuto, nullptr , false ); std::unique_ptr<RandomAccessFile> file; EXPECT_EQ( errors::FailedPrecondition( "Bucket 'bucket' is in 'barfoo' location, allowed locations " "are: (us-east1)."), fs.NewRandomAccessFile("gs: } TEST(GcsFileSystemTest, NewRandomAccessFile_NoBlockCache_DifferentN) { std::vector<HttpRequest*> requests( {new FakeHttpRequest( "Uri: https: "Auth Token: fake_token\n" "Range: 0-2\n" "Timeouts: 5 1 20\n", "012"), new FakeHttpRequest( "Uri: https: "Auth Token: fake_token\n" "Range: 3-12\n" "Timeouts: 5 1 20\n", "3456789")}); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 0 , 0 , 0 , 0 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); std::unique_ptr<RandomAccessFile> file; TF_EXPECT_OK( fs.NewRandomAccessFile("gs: char small_scratch[3]; StringPiece result; TF_EXPECT_OK(file->Read(0, sizeof(small_scratch), &result, small_scratch)); EXPECT_EQ("012", result); char large_scratch[10]; EXPECT_TRUE(errors::IsOutOfRange(file->Read( sizeof(small_scratch), sizeof(large_scratch), &result, large_scratch))); EXPECT_EQ("3456789", result); } TEST(GcsFileSystemTest, NewRandomAccessFile_WithBlockCache) { std::vector<HttpRequest*> requests( {new FakeHttpRequest( "Uri: https: "random_access.txt?fields=size%2Cgeneration%2Cupdated\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", strings::StrCat("{\"size\": \"15\",\"generation\": \"1\"," "\"updated\": \"2016-04-29T23:15:24.896Z\"}")), new FakeHttpRequest( "Uri: https: "Auth Token: fake_token\n" "Range: 0-8\n" "Timeouts: 5 1 20\n", "012345678"), new FakeHttpRequest( "Uri: https: "Auth Token: fake_token\n" "Range: 9-17\n" "Timeouts: 5 1 20\n", "9abcde"), new FakeHttpRequest( "Uri: https: "Auth Token: fake_token\n" "Range: 18-26\n" "Timeouts: 5 1 20\n", "")}); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 9 , 18 , 0 , 3600 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); char scratch[100]; StringPiece result; { std::unique_ptr<RandomAccessFile> file; TF_EXPECT_OK(fs.NewRandomAccessFile("gs: nullptr, &file)); scratch[5] = 'x'; TF_EXPECT_OK(file->Read(0, 4, &result, scratch)); EXPECT_EQ("0123", result); EXPECT_EQ(scratch[5], 'x'); TF_EXPECT_OK(file->Read(4, 4, &result, scratch)); EXPECT_EQ("4567", result); TF_EXPECT_OK(file->Read(6, 5, &result, scratch)); EXPECT_EQ("6789a", result); EXPECT_TRUE(errors::IsOutOfRange(file->Read(6, 10, &result, scratch))); EXPECT_EQ("6789abcde", result); EXPECT_TRUE(errors::IsOutOfRange(file->Read(20, 10, &result, scratch))); EXPECT_TRUE(result.empty()); TF_EXPECT_OK(file->Read(0, 4, &result, scratch)); } EXPECT_EQ("0123", result); } TEST(GcsFileSystemTest, NewRandomAccessFile_WithBlockCache_Flush) { std::vector<HttpRequest*> requests( {new FakeHttpRequest( "Uri: https: "random_access.txt?fields=size%2Cgeneration%2Cupdated\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", strings::StrCat("{\"size\": \"15\",\"generation\": \"1\"," "\"updated\": \"2016-04-29T23:15:24.896Z\"}")), new FakeHttpRequest( "Uri: https: "Auth Token: fake_token\n" "Range: 0-8\n" "Timeouts: 5 1 20\n", "012345678"), new FakeHttpRequest( "Uri: https: "random_access.txt?fields=size%2Cgeneration%2Cupdated\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", strings::StrCat("{\"size\": \"15\",\"generation\": \"1\"," "\"updated\": \"2016-04-29T23:15:24.896Z\"}")), new FakeHttpRequest( "Uri: https: "Auth Token: fake_token\n" "Range: 0-8\n" "Timeouts: 5 1 20\n", "012345678")}); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 9 , 18 , 0 , 3600 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); char scratch[100]; StringPiece result; std::unique_ptr<RandomAccessFile> file; TF_EXPECT_OK( fs.NewRandomAccessFile("gs: scratch[5] = 'x'; TF_EXPECT_OK(file->Read(0, 4, &result, scratch)); EXPECT_EQ("0123", result); EXPECT_EQ(scratch[5], 'x'); fs.FlushCaches(nullptr); TF_EXPECT_OK(file->Read(4, 4, &result, scratch)); EXPECT_EQ("4567", result); } TEST(GcsFileSystemTest, NewRandomAccessFile_WithBlockCache_MaxStaleness) { std::vector<HttpRequest*> requests( {new FakeHttpRequest( "Uri: https: "object?fields=size%2Cgeneration%2Cupdated\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", strings::StrCat("{\"size\": \"16\",\"generation\": \"1\"," "\"updated\": \"2016-04-29T23:15:24.896Z\"}")), new FakeHttpRequest("Uri: https: "Auth Token: fake_token\n" "Range: 0-7\n" "Timeouts: 5 1 20\n", "01234567"), new FakeHttpRequest("Uri: https: "Auth Token: fake_token\n" "Range: 8-15\n" "Timeouts: 5 1 20\n", "89abcdef")}); GcsFileSystem fs( std::unique_ptr<AuthProvider>(new FakeAuthProvider), std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), std::unique_ptr<ZoneProvider>(new FakeZoneProvider), 8 , 16 , 3600 , 3600 , 0 , 0 , 0 , kTestRetryConfig, kTestTimeoutConfig, *kAllowedLocationsDefault, nullptr , false ); char scratch[100]; StringPiece result; for (int i = 0; i < 10; i++) { std::unique_ptr<RandomAccessFile> file1; std::unique_ptr<RandomAccessFile> file2; TF_EXPECT_OK(fs.NewRandomAccessFile("gs: TF_EXPECT_OK(fs.NewRandomAccessFile("gs: TF_EXPECT_OK(file1->Read(0, 8, &result, scratch)); EXPECT_EQ("01234567", result); TF_EXPECT_OK(file2->Read(0, 8, &result, scratch)); EXPECT_EQ("01234567", result); TF_EXPECT_OK(file2->Read(8, 8, &result, scratch)); EXPECT_EQ("89abcdef", result); TF_EXPECT_OK(file1->Read(8, 8, &result, scratch)); EXPECT_EQ("89abcdef", result); } } TEST(GcsFileSystemTest, NewRandomAccessFile_WithBlockCache_FileSignatureChanges) { std::vector<HttpRequest*> requests( {new FakeHttpRequest( "Uri: https: "random_access.txt?fields=size%2Cgeneration%2Cupdated\n" "Auth Token: fake_token\n" "Timeouts: 5 1 10\n", strings::StrCat("{\"size\": \"5\",\"generation\": \"1\"," "\"updated\": \"2016-04-29T23:15:24.896Z\"}")), new FakeHttpR
2,611
cpp
google/tsl
gcs_dns_cache
tsl/platform/cloud/gcs_dns_cache.cc
tsl/platform/cloud/gcs_dns_cache_test.cc
#ifndef TENSORFLOW_TSL_PLATFORM_CLOUD_GCS_DNS_CACHE_H_ #define TENSORFLOW_TSL_PLATFORM_CLOUD_GCS_DNS_CACHE_H_ #include <random> #include "tsl/platform/cloud/http_request.h" #include "tsl/platform/env.h" namespace tsl { const int64_t kDefaultRefreshRateSecs = 60; class GcsDnsCache { public: GcsDnsCache() : GcsDnsCache(kDefaultRefreshRateSecs) {} GcsDnsCache(int64_t refresh_rate_secs) : GcsDnsCache(Env::Default(), refresh_rate_secs) {} GcsDnsCache(Env* env, int64_t refresh_rate_secs); ~GcsDnsCache() { mutex_lock l(mu_); cancelled_ = true; cond_var_.notify_one(); } void AnnotateRequest(HttpRequest* request); private: static std::vector<string> ResolveName(const string& name); static std::vector<std::vector<string>> ResolveNames( const std::vector<string>& names); void WorkerThread(); friend class GcsDnsCacheTest; mutex mu_; Env* env_; condition_variable cond_var_; std::default_random_engine random_ TF_GUARDED_BY(mu_); bool started_ TF_GUARDED_BY(mu_) = false; bool cancelled_ TF_GUARDED_BY(mu_) = false; std::unique_ptr<Thread> worker_ TF_GUARDED_BY(mu_); const int64_t refresh_rate_secs_; std::vector<std::vector<string>> addresses_ TF_GUARDED_BY(mu_); }; } #endif #include "tsl/platform/cloud/gcs_dns_cache.h" #include <cstring> #include "absl/status/status.h" #include "absl/strings/str_cat.h" #include "tsl/platform/errors.h" #include "tsl/platform/retrying_utils.h" #include "tsl/platform/status.h" #ifndef _WIN32 #include <arpa/inet.h> #include <netdb.h> #include <netinet/in.h> #include <sys/socket.h> #else #include <Windows.h> #include <winsock2.h> #include <ws2tcpip.h> #endif #include <sys/types.h> namespace tsl { namespace { const std::vector<string>& kCachedDomainNames = *new std::vector<string>{"www.googleapis.com", "storage.googleapis.com"}; inline void print_getaddrinfo_error(const string& name, Status return_status) { LOG(ERROR) << "Error resolving " << name << ": " << return_status; } template <typename T> const T& SelectRandomItemUniform(std::default_random_engine* random, const std::vector<T>& items) { CHECK_GT(items.size(), 0); std::uniform_int_distribution<size_t> distribution(0u, items.size() - 1u); size_t choice_index = distribution(*random); return items[choice_index]; } } GcsDnsCache::GcsDnsCache(Env* env, int64_t refresh_rate_secs) : env_(env), refresh_rate_secs_(refresh_rate_secs) {} void GcsDnsCache::AnnotateRequest(HttpRequest* request) { mutex_lock l(mu_); if (!started_) { VLOG(1) << "Starting GCS DNS cache."; DCHECK(!worker_) << "Worker thread already exists!"; addresses_ = ResolveNames(kCachedDomainNames); worker_.reset(env_->StartThread({}, "gcs_dns_worker", [this]() { return WorkerThread(); })); started_ = true; } CHECK_EQ(kCachedDomainNames.size(), addresses_.size()); for (size_t i = 0; i < kCachedDomainNames.size(); ++i) { const string& name = kCachedDomainNames[i]; const std::vector<string>& addresses = addresses_[i]; if (!addresses.empty()) { const string& chosen_address = SelectRandomItemUniform(&random_, addresses); request->AddResolveOverride(name, 443, chosen_address); VLOG(1) << "Annotated DNS mapping: " << name << " --> " << chosen_address; } else { LOG(WARNING) << "No IP addresses available for " << name; } } } std::vector<string> GcsDnsCache::ResolveName(const string& name) { VLOG(1) << "Resolving DNS name: " << name; addrinfo hints; memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; addrinfo* result = nullptr; RetryConfig retryConfig( 5000, 50 * 1000 * 5000, 5); const Status getaddrinfo_status = RetryingUtils::CallWithRetries( [&name, &hints, &result]() { int return_code = getaddrinfo(name.c_str(), nullptr, &hints, &result); absl::Status return_status; switch (return_code) { case 0: return_status = OkStatus(); break; #ifndef _WIN32 case EAI_ADDRFAMILY: case EAI_SERVICE: case EAI_SOCKTYPE: case EAI_NONAME: return_status = absl::FailedPreconditionError( absl::StrCat("System in invalid state for getaddrinfo call: ", gai_strerror(return_code))); break; case EAI_AGAIN: case EAI_NODATA: return_status = absl::UnavailableError(absl::StrCat( "Resolving ", name, " is temporarily unavailable")); break; case EAI_BADFLAGS: case EAI_FAMILY: return_status = absl::InvalidArgumentError(absl::StrCat( "Bad arguments for getaddrinfo: ", gai_strerror(return_code))); break; case EAI_FAIL: return_status = absl::NotFoundError( absl::StrCat("Permanent failure resolving ", name, ": ", gai_strerror(return_code))); break; case EAI_MEMORY: return_status = absl::ResourceExhaustedError("Out of memory"); break; case EAI_SYSTEM: default: return_status = absl::UnknownError(strerror(return_code)); #else case WSATYPE_NOT_FOUND: case WSAESOCKTNOSUPPORT: case WSAHOST_NOT_FOUND: return_status = absl::FailedPreconditionError( absl::StrCat("System in invalid state for getaddrinfo call: ", gai_strerror(return_code))); break; case WSATRY_AGAIN: return_status = absl::UnavailableError(absl::StrCat( "Resolving ", name, " is temporarily unavailable")); break; case WSAEINVAL: case WSAEAFNOSUPPORT: return_status = absl::InvalidArgumentError(absl::StrCat( "Bad arguments for getaddrinfo: ", gai_strerror(return_code))); break; case WSANO_RECOVERY: return_status = absl::NotFoundError( absl::StrCat("Permanent failure resolving ", name, ": ", gai_strerror(return_code))); break; case WSA_NOT_ENOUGH_MEMORY: return_status = absl::ResourceExhaustedError("Out of memory"); break; default: return_status = absl::UnknownError(strerror(return_code)); #endif } return Status(return_status); }, retryConfig); std::vector<string> output; if (getaddrinfo_status.ok()) { for (const addrinfo* i = result; i != nullptr; i = i->ai_next) { if (i->ai_family != AF_INET || i->ai_addr->sa_family != AF_INET) { LOG(WARNING) << "Non-IPv4 address returned. ai_family: " << i->ai_family << ". sa_family: " << i->ai_addr->sa_family << "."; continue; } char buf[INET_ADDRSTRLEN]; void* address_ptr = &(reinterpret_cast<sockaddr_in*>(i->ai_addr)->sin_addr); const char* formatted = nullptr; if ((formatted = inet_ntop(i->ai_addr->sa_family, address_ptr, buf, INET_ADDRSTRLEN)) == nullptr) { LOG(ERROR) << "Error converting response to IP address for " << name << ": " << strerror(errno); } else { output.emplace_back(buf); VLOG(1) << "... address: " << buf; } } } else { print_getaddrinfo_error(name, getaddrinfo_status); } if (result != nullptr) { freeaddrinfo(result); } return output; } std::vector<std::vector<string>> GcsDnsCache::ResolveNames( const std::vector<string>& names) { std::vector<std::vector<string>> all_addresses; all_addresses.reserve(names.size()); for (const string& name : names) { all_addresses.push_back(ResolveName(name)); } return all_addresses; } void GcsDnsCache::WorkerThread() { while (true) { { mutex_lock l(mu_); if (cancelled_) return; cond_var_.wait_for(l, std::chrono::seconds(refresh_rate_secs_)); if (cancelled_) return; } auto new_addresses = ResolveNames(kCachedDomainNames); { mutex_lock l(mu_); addresses_.swap(new_addresses); } } } }
#include "tsl/platform/cloud/gcs_dns_cache.h" #include "tsl/platform/str_util.h" #include "tsl/platform/test.h" namespace tsl { class TestHttpRequest : public HttpRequest { public: void SetUri(const string& uri) override {} void SetRange(uint64 start, uint64 end) override {} void AddHeader(const string& name, const string& value) override {} void AddResolveOverride(const string& hostname, int64_t port, const string& ip_addr) override { EXPECT_EQ(port, 443) << "Unexpected port set for hostname: " << hostname; auto itr = resolve_overrides_.find(hostname); EXPECT_EQ(itr, resolve_overrides_.end()) << "Hostname " << hostname << "already in map: " << itr->second; resolve_overrides_.insert( std::map<string, string>::value_type(hostname, ip_addr)); } void AddAuthBearerHeader(const string& auth_token) override {} void SetRequestStats(HttpRequest::RequestStats* stats) override {} void SetDeleteRequest() override {} Status SetPutFromFile(const string& body_filepath, size_t offset) override { return OkStatus(); } void SetPutEmptyBody() override {} void SetPostFromBuffer(const char* buffer, size_t size) override {} void SetPostEmptyBody() override {} void SetResultBuffer(std::vector<char>* out_buffer) override {} void SetResultBufferDirect(char* buffer, size_t size) override {} size_t GetResultBufferDirectBytesTransferred() override { return 0; } string GetResponseHeader(const string& name) const override { return ""; } uint64 GetResponseCode() const override { return 0; } Status Send() override { return OkStatus(); } string EscapeString(const string& str) override { return ""; } void SetTimeouts(uint32 connection, uint32 inactivity, uint32 total) override {} std::map<string, string> resolve_overrides_; }; class GcsDnsCacheTest : public ::testing::Test { protected: void ResolveNameTest() { auto response = GcsDnsCache::ResolveName("www.googleapis.com"); EXPECT_LT(1, response.size()) << absl::StrJoin(response, ", "); } void AnnotateRequestTest() { GcsDnsCache d; { mutex_lock l(d.mu_); d.started_ = true; d.addresses_ = {{"192.168.1.1"}, {"172.134.1.1"}}; } TestHttpRequest req; d.AnnotateRequest(&req); EXPECT_EQ("192.168.1.1", req.resolve_overrides_["www.googleapis.com"]); EXPECT_EQ("172.134.1.1", req.resolve_overrides_["storage.googleapis.com"]); } void SuccessfulCleanupTest() { GcsDnsCache d; TestHttpRequest req; d.AnnotateRequest(&req); } }; TEST_F(GcsDnsCacheTest, AnnotateRequest) { AnnotateRequestTest(); } TEST_F(GcsDnsCacheTest, SuccessfulCleanup) { SuccessfulCleanupTest(); } }
2,612
cpp
google/tsl
compute_engine_metadata_client
tsl/platform/cloud/compute_engine_metadata_client.cc
tsl/platform/cloud/compute_engine_metadata_client_test.cc
#ifndef TENSORFLOW_TSL_PLATFORM_CLOUD_COMPUTE_ENGINE_METADATA_CLIENT_H_ #define TENSORFLOW_TSL_PLATFORM_CLOUD_COMPUTE_ENGINE_METADATA_CLIENT_H_ #include "tsl/platform/cloud/http_request.h" #include "tsl/platform/retrying_utils.h" #include "tsl/platform/status.h" namespace tsl { class ComputeEngineMetadataClient { public: explicit ComputeEngineMetadataClient( std::shared_ptr<HttpRequest::Factory> http_request_factory, const RetryConfig& config = RetryConfig( 10000, 1000000 )); virtual ~ComputeEngineMetadataClient() {} virtual Status GetMetadata(const string& path, std::vector<char>* response_buffer); private: std::shared_ptr<HttpRequest::Factory> http_request_factory_; const RetryConfig retry_config_; ComputeEngineMetadataClient(const ComputeEngineMetadataClient&) = delete; void operator=(const ComputeEngineMetadataClient&) = delete; }; } #endif #include "tsl/platform/cloud/compute_engine_metadata_client.h" #include <cstdlib> #include <utility> #include "absl/strings/str_cat.h" #include "tsl/platform/cloud/curl_http_request.h" namespace tsl { namespace { constexpr char kGceMetadataHost[] = "GCE_METADATA_HOST"; constexpr char kGceMetadataBaseUrl[] = "http: } ComputeEngineMetadataClient::ComputeEngineMetadataClient( std::shared_ptr<HttpRequest::Factory> http_request_factory, const RetryConfig& config) : http_request_factory_(std::move(http_request_factory)), retry_config_(config) {} Status ComputeEngineMetadataClient::GetMetadata( const string& path, std::vector<char>* response_buffer) { const auto get_metadata_from_gce = [path, response_buffer, this]() { string metadata_url; const char* metadata_url_override = std::getenv(kGceMetadataHost); if (metadata_url_override) { metadata_url = absl::StrCat("http: "/computeMetadata/v1/"); } else { metadata_url = kGceMetadataBaseUrl; } std::unique_ptr<HttpRequest> request(http_request_factory_->Create()); request->SetUri(metadata_url + path); request->AddHeader("Metadata-Flavor", "Google"); request->SetResultBuffer(response_buffer); TF_RETURN_IF_ERROR(request->Send()); return OkStatus(); }; return RetryingUtils::CallWithRetries(get_metadata_from_gce, retry_config_); } }
#include "tsl/platform/cloud/compute_engine_metadata_client.h" #include "tsl/platform/cloud/http_request_fake.h" #include "tsl/platform/env.h" #include "tsl/platform/test.h" namespace tsl { class ComputeEngineMetadataClientTest : public ::testing::Test { protected: void SetUp() override { ClearEnvVars(); } void TearDown() override { ClearEnvVars(); } void ClearEnvVars() { unsetenv("GCE_METADATA_HOST"); } }; TEST_F(ComputeEngineMetadataClientTest, GetMetadata) { const string example_response = "example response"; std::vector<HttpRequest*> requests({new FakeHttpRequest( "Uri: http: "/service-accounts/default/token\n" "Header Metadata-Flavor: Google\n", example_response)}); std::shared_ptr<HttpRequest::Factory> http_factory = std::make_shared<FakeHttpRequestFactory>(&requests); ComputeEngineMetadataClient client(http_factory, RetryConfig(0 )); std::vector<char> result; TF_EXPECT_OK( client.GetMetadata("instance/service-accounts/default/token", &result)); std::vector<char> expected(example_response.begin(), example_response.end()); EXPECT_EQ(expected, result); } TEST_F(ComputeEngineMetadataClientTest, GetCustomMetadataEndpoint) { const string example_response = "example response"; setenv("GCE_METADATA_HOST", "foo.bar", 1); std::vector<HttpRequest*> requests( {new FakeHttpRequest("Uri: http: "/service-accounts/default/token\n" "Header Metadata-Flavor: Google\n", example_response)}); std::shared_ptr<HttpRequest::Factory> http_factory = std::make_shared<FakeHttpRequestFactory>(&requests); ComputeEngineMetadataClient client(http_factory, RetryConfig(0 )); std::vector<char> result; TF_EXPECT_OK( client.GetMetadata("instance/service-accounts/default/token", &result)); std::vector<char> expected(example_response.begin(), example_response.end()); EXPECT_EQ(expected, result); } TEST_F(ComputeEngineMetadataClientTest, RetryOnFailure) { const string example_response = "example response"; std::vector<HttpRequest*> requests( {new FakeHttpRequest( "Uri: http: "/service-accounts/default/token\n" "Header Metadata-Flavor: Google\n", "", errors::Unavailable("503"), 503), new FakeHttpRequest( "Uri: http: "/service-accounts/default/token\n" "Header Metadata-Flavor: Google\n", example_response)}); std::shared_ptr<HttpRequest::Factory> http_factory = std::make_shared<FakeHttpRequestFactory>(&requests); ComputeEngineMetadataClient client(http_factory, RetryConfig(0 )); std::vector<char> result; TF_EXPECT_OK( client.GetMetadata("instance/service-accounts/default/token", &result)); std::vector<char> expected(example_response.begin(), example_response.end()); EXPECT_EQ(expected, result); } }
2,613
cpp
google/tsl
oauth_client
tsl/platform/cloud/oauth_client.cc
tsl/platform/cloud/oauth_client_test.cc
#ifndef TENSORFLOW_TSL_PLATFORM_CLOUD_OAUTH_CLIENT_H_ #define TENSORFLOW_TSL_PLATFORM_CLOUD_OAUTH_CLIENT_H_ #include <memory> #include "json/json.h" #include "tsl/platform/cloud/http_request.h" #include "tsl/platform/env.h" #include "tsl/platform/status.h" namespace tsl { class OAuthClient { public: OAuthClient(); explicit OAuthClient( std::unique_ptr<HttpRequest::Factory> http_request_factory, Env* env); virtual ~OAuthClient() {} virtual Status GetTokenFromServiceAccountJson( Json::Value json, StringPiece oauth_server_uri, StringPiece scope, string* token, uint64* expiration_timestamp_sec); virtual Status GetTokenFromRefreshTokenJson(Json::Value json, StringPiece oauth_server_uri, string* token, uint64* expiration_timestamp_sec); virtual Status ParseOAuthResponse(StringPiece response, uint64 request_timestamp_sec, string* token, uint64* expiration_timestamp_sec); private: std::unique_ptr<HttpRequest::Factory> http_request_factory_; Env* env_; OAuthClient(const OAuthClient&) = delete; void operator=(const OAuthClient&) = delete; }; } #endif #include "tsl/platform/cloud/oauth_client.h" #ifndef _WIN32 #include <pwd.h> #include <sys/types.h> #include <unistd.h> #else #include <sys/types.h> #endif #include <fstream> #include <openssl/bio.h> #include <openssl/evp.h> #include <openssl/pem.h> #include <openssl/rsa.h> #include "tsl/platform/base64.h" #include "tsl/platform/cloud/curl_http_request.h" #include "tsl/platform/env.h" #include "tsl/platform/errors.h" namespace tsl { namespace { constexpr int kRequestedTokenLifetimeSec = 3600; constexpr char kCryptoAlgorithm[] = "RS256"; constexpr char kJwtType[] = "JWT"; constexpr char kGrantType[] = "urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer"; Status ReadJsonValue(const Json::Value& json, const string& name, Json::Value* value) { if (!value) { return errors::FailedPrecondition("'value' cannot be nullptr."); } *value = json.get(name, Json::Value::null); if (*value == Json::Value::null) { return errors::FailedPrecondition( strings::StrCat("Couldn't read a JSON value '", name, "'.")); } return OkStatus(); } Status ReadJsonString(const Json::Value& json, const string& name, string* value) { Json::Value json_value; TF_RETURN_IF_ERROR(ReadJsonValue(json, name, &json_value)); if (!json_value.isString()) { return errors::FailedPrecondition( strings::StrCat("JSON value '", name, "' is not string.")); } *value = json_value.asString(); return OkStatus(); } Status ReadJsonInt(const Json::Value& json, const string& name, int64_t* value) { Json::Value json_value; TF_RETURN_IF_ERROR(ReadJsonValue(json, name, &json_value)); if (!json_value.isIntegral()) { return errors::FailedPrecondition( strings::StrCat("JSON value '", name, "' is not integer.")); } *value = json_value.asInt64(); return OkStatus(); } Status CreateSignature(RSA* private_key, StringPiece to_sign, string* signature) { if (!private_key || !signature) { return errors::FailedPrecondition( "'private_key' and 'signature' cannot be nullptr."); } const auto md = EVP_sha256(); if (!md) { return errors::Internal("Could not get a sha256 encryptor."); } std::unique_ptr<EVP_MD_CTX, std::function<void(EVP_MD_CTX*)>> md_ctx( EVP_MD_CTX_create(), [](EVP_MD_CTX* ptr) { EVP_MD_CTX_destroy(ptr); }); if (!md_ctx) { return errors::Internal("Could not create MD_CTX."); } std::unique_ptr<EVP_PKEY, std::function<void(EVP_PKEY*)>> key( EVP_PKEY_new(), [](EVP_PKEY* ptr) { EVP_PKEY_free(ptr); }); EVP_PKEY_set1_RSA(key.get(), private_key); if (EVP_DigestSignInit(md_ctx.get(), nullptr, md, nullptr, key.get()) != 1) { return errors::Internal("DigestInit failed."); } if (EVP_DigestSignUpdate(md_ctx.get(), to_sign.data(), to_sign.size()) != 1) { return errors::Internal("DigestUpdate failed."); } size_t sig_len = 0; if (EVP_DigestSignFinal(md_ctx.get(), nullptr, &sig_len) != 1) { return errors::Internal("DigestFinal (get signature length) failed."); } std::unique_ptr<unsigned char[]> sig(new unsigned char[sig_len]); if (EVP_DigestSignFinal(md_ctx.get(), sig.get(), &sig_len) != 1) { return errors::Internal("DigestFinal (signature compute) failed."); } return Base64Encode(StringPiece(reinterpret_cast<char*>(sig.get()), sig_len), signature); } Status EncodeJwtClaim(StringPiece client_email, StringPiece scope, StringPiece audience, uint64 request_timestamp_sec, string* encoded) { Json::Value root; root["iss"] = Json::Value(client_email.data(), client_email.data() + client_email.size()); root["scope"] = Json::Value(scope.data(), scope.data() + scope.size()); root["aud"] = Json::Value(audience.data(), audience.data() + audience.size()); const auto expiration_timestamp_sec = request_timestamp_sec + kRequestedTokenLifetimeSec; root["iat"] = Json::Value::UInt64(request_timestamp_sec); root["exp"] = Json::Value::UInt64(expiration_timestamp_sec); string claim = root.toStyledString(); return Base64Encode(claim, encoded); } Status EncodeJwtHeader(StringPiece key_id, string* encoded) { Json::Value root; root["alg"] = kCryptoAlgorithm; root["typ"] = kJwtType; root["kid"] = Json::Value(key_id.data(), key_id.data() + key_id.size()); const string header = root.toStyledString(); return Base64Encode(header, encoded); } } OAuthClient::OAuthClient() : OAuthClient( std::unique_ptr<HttpRequest::Factory>(new CurlHttpRequest::Factory()), Env::Default()) {} OAuthClient::OAuthClient( std::unique_ptr<HttpRequest::Factory> http_request_factory, Env* env) : http_request_factory_(std::move(http_request_factory)), env_(env) {} Status OAuthClient::GetTokenFromServiceAccountJson( Json::Value json, StringPiece oauth_server_uri, StringPiece scope, string* token, uint64* expiration_timestamp_sec) { if (!token || !expiration_timestamp_sec) { return errors::FailedPrecondition( "'token' and 'expiration_timestamp_sec' cannot be nullptr."); } string private_key_serialized, private_key_id, client_id, client_email; TF_RETURN_IF_ERROR( ReadJsonString(json, "private_key", &private_key_serialized)); TF_RETURN_IF_ERROR(ReadJsonString(json, "private_key_id", &private_key_id)); TF_RETURN_IF_ERROR(ReadJsonString(json, "client_id", &client_id)); TF_RETURN_IF_ERROR(ReadJsonString(json, "client_email", &client_email)); std::unique_ptr<BIO, std::function<void(BIO*)>> bio( BIO_new(BIO_s_mem()), [](BIO* ptr) { BIO_free_all(ptr); }); if (BIO_puts(bio.get(), private_key_serialized.c_str()) != static_cast<int>(private_key_serialized.size())) { return errors::Internal("Could not load the private key."); } std::unique_ptr<RSA, std::function<void(RSA*)>> private_key( PEM_read_bio_RSAPrivateKey(bio.get(), nullptr, nullptr, nullptr), [](RSA* ptr) { RSA_free(ptr); }); if (!private_key) { return errors::Internal("Could not deserialize the private key."); } const uint64 request_timestamp_sec = env_->NowSeconds(); string encoded_claim, encoded_header; TF_RETURN_IF_ERROR(EncodeJwtHeader(private_key_id, &encoded_header)); TF_RETURN_IF_ERROR(EncodeJwtClaim(client_email, scope, oauth_server_uri, request_timestamp_sec, &encoded_claim)); const string to_sign = encoded_header + "." + encoded_claim; string signature; TF_RETURN_IF_ERROR(CreateSignature(private_key.get(), to_sign, &signature)); const string jwt = to_sign + "." + signature; const string request_body = strings::StrCat("grant_type=", kGrantType, "&assertion=", jwt); std::unique_ptr<HttpRequest> request(http_request_factory_->Create()); std::vector<char> response_buffer; request->SetUri(string(oauth_server_uri)); request->SetPostFromBuffer(request_body.c_str(), request_body.size()); request->SetResultBuffer(&response_buffer); TF_RETURN_IF_ERROR(request->Send()); StringPiece response = StringPiece(response_buffer.data(), response_buffer.size()); TF_RETURN_IF_ERROR(ParseOAuthResponse(response, request_timestamp_sec, token, expiration_timestamp_sec)); return OkStatus(); } Status OAuthClient::GetTokenFromRefreshTokenJson( Json::Value json, StringPiece oauth_server_uri, string* token, uint64* expiration_timestamp_sec) { if (!token || !expiration_timestamp_sec) { return errors::FailedPrecondition( "'token' and 'expiration_timestamp_sec' cannot be nullptr."); } string client_id, client_secret, refresh_token; TF_RETURN_IF_ERROR(ReadJsonString(json, "client_id", &client_id)); TF_RETURN_IF_ERROR(ReadJsonString(json, "client_secret", &client_secret)); TF_RETURN_IF_ERROR(ReadJsonString(json, "refresh_token", &refresh_token)); const auto request_body = strings::StrCat( "client_id=", client_id, "&client_secret=", client_secret, "&refresh_token=", refresh_token, "&grant_type=refresh_token"); const uint64 request_timestamp_sec = env_->NowSeconds(); std::unique_ptr<HttpRequest> request(http_request_factory_->Create()); std::vector<char> response_buffer; request->SetUri(string(oauth_server_uri)); request->SetPostFromBuffer(request_body.c_str(), request_body.size()); request->SetResultBuffer(&response_buffer); TF_RETURN_IF_ERROR(request->Send()); StringPiece response = StringPiece(response_buffer.data(), response_buffer.size()); TF_RETURN_IF_ERROR(ParseOAuthResponse(response, request_timestamp_sec, token, expiration_timestamp_sec)); return OkStatus(); } Status OAuthClient::ParseOAuthResponse(StringPiece response, uint64 request_timestamp_sec, string* token, uint64* expiration_timestamp_sec) { if (!token || !expiration_timestamp_sec) { return errors::FailedPrecondition( "'token' and 'expiration_timestamp_sec' cannot be nullptr."); } Json::Value root; Json::Reader reader; if (!reader.parse(response.data(), response.data() + response.size(), root)) { return errors::Internal("Couldn't parse JSON response from OAuth server."); } string token_type; TF_RETURN_IF_ERROR(ReadJsonString(root, "token_type", &token_type)); if (token_type != "Bearer") { return errors::FailedPrecondition("Unexpected Oauth token type: " + token_type); } int64_t expires_in = 0; TF_RETURN_IF_ERROR(ReadJsonInt(root, "expires_in", &expires_in)); *expiration_timestamp_sec = request_timestamp_sec + expires_in; TF_RETURN_IF_ERROR(ReadJsonString(root, "access_token", token)); return OkStatus(); } }
#include "tsl/platform/cloud/oauth_client.h" #include <fstream> #include <openssl/bio.h> #include <openssl/evp.h> #include <openssl/pem.h> #include "tsl/lib/core/status_test_util.h" #include "tsl/platform/base64.h" #include "tsl/platform/cloud/http_request_fake.h" #include "tsl/platform/env.h" #include "tsl/platform/path.h" #include "tsl/platform/scanner.h" #include "tsl/platform/test.h" namespace tsl { namespace { string TestData() { return io::JoinPath(testing::TslSrcRoot(), "platform", "cloud", "testdata"); } constexpr char kTokenJson[] = R"( { "access_token":"WITH_FAKE_ACCESS_TOKEN_TEST_SHOULD_BE_HAPPY", "expires_in":3920, "token_type":"Bearer" })"; class FakeEnv : public EnvWrapper { public: FakeEnv() : EnvWrapper(Env::Default()) {} uint64 NowSeconds() const override { return now; } uint64 now = 10000; }; } TEST(OAuthClientTest, ParseOAuthResponse) { const uint64 request_timestamp = 100; string token; uint64 expiration_timestamp; TF_EXPECT_OK(OAuthClient().ParseOAuthResponse(kTokenJson, request_timestamp, &token, &expiration_timestamp)); EXPECT_EQ("WITH_FAKE_ACCESS_TOKEN_TEST_SHOULD_BE_HAPPY", token); EXPECT_EQ(4020, expiration_timestamp); } TEST(OAuthClientTest, GetTokenFromRefreshTokenJson) { const string credentials_json = R"( { "client_id": "test_client_id", "client_secret": "@@@test_client_secret@@@", "refresh_token": "test_refresh_token", "type": "authorized_user" })"; Json::Value json; Json::Reader reader; ASSERT_TRUE(reader.parse(credentials_json, json)); std::vector<HttpRequest*> requests({new FakeHttpRequest( "Uri: https: "Post body: client_id=test_client_id&" "client_secret=@@@test_client_secret@@@&" "refresh_token=test_refresh_token&grant_type=refresh_token\n", kTokenJson)}); FakeEnv env; OAuthClient client(std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), &env); string token; uint64 expiration_timestamp; TF_EXPECT_OK(client.GetTokenFromRefreshTokenJson( json, "https: &expiration_timestamp)); EXPECT_EQ("WITH_FAKE_ACCESS_TOKEN_TEST_SHOULD_BE_HAPPY", token); EXPECT_EQ(13920, expiration_timestamp); } TEST(OAuthClientTest, GetTokenFromServiceAccountJson) { std::ifstream credentials( io::JoinPath(TestData(), "service_account_credentials.json")); ASSERT_TRUE(credentials.is_open()); Json::Value json; Json::Reader reader; ASSERT_TRUE(reader.parse(credentials, json)); string post_body; std::vector<HttpRequest*> requests( {new FakeHttpRequest("Uri: https: kTokenJson, &post_body)}); FakeEnv env; OAuthClient client(std::unique_ptr<HttpRequest::Factory>( new FakeHttpRequestFactory(&requests)), &env); string token; uint64 expiration_timestamp; TF_EXPECT_OK(client.GetTokenFromServiceAccountJson( json, "https: "https: EXPECT_EQ("WITH_FAKE_ACCESS_TOKEN_TEST_SHOULD_BE_HAPPY", token); EXPECT_EQ(13920, expiration_timestamp); StringPiece grant_type, assertion; ASSERT_TRUE(strings::Scanner(post_body) .OneLiteral("grant_type=") .RestartCapture() .ScanEscapedUntil('&') .StopCapture() .OneLiteral("&assertion=") .GetResult(&assertion, &grant_type)); EXPECT_EQ("urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer", grant_type); int last_dot = assertion.rfind('.'); string header_dot_claim(assertion.substr(0, last_dot)); string signature_encoded(assertion.substr(last_dot + 1)); std::ifstream public_key_stream( io::JoinPath(TestData(), "service_account_public_key.txt")); string public_key_serialized( (std::istreambuf_iterator<char>(public_key_stream)), (std::istreambuf_iterator<char>())); auto bio = BIO_new(BIO_s_mem()); RSA* public_key = nullptr; EXPECT_EQ(public_key_serialized.size(), BIO_puts(bio, public_key_serialized.c_str())); public_key = PEM_read_bio_RSA_PUBKEY(bio, nullptr, nullptr, nullptr); EXPECT_TRUE(public_key) << "Could not load the public key from testdata."; string signature; TF_EXPECT_OK(Base64Decode(signature_encoded, &signature)); const auto md = EVP_sha256(); auto md_ctx = EVP_MD_CTX_create(); auto key = EVP_PKEY_new(); EVP_PKEY_set1_RSA(key, public_key); ASSERT_EQ(1, EVP_DigestVerifyInit(md_ctx, nullptr, md, nullptr, key)); ASSERT_EQ(1, EVP_DigestVerifyUpdate(md_ctx, header_dot_claim.c_str(), header_dot_claim.size())); ASSERT_EQ(1, EVP_DigestVerifyFinal( md_ctx, const_cast<unsigned char*>( reinterpret_cast<const unsigned char*>(signature.data())), signature.size())); EVP_PKEY_free(key); EVP_MD_CTX_destroy(md_ctx); RSA_free(public_key); BIO_free_all(bio); int dot = header_dot_claim.find_last_of('.'); string header_encoded = header_dot_claim.substr(0, dot); string claim_encoded = header_dot_claim.substr(dot + 1); string header, claim; TF_EXPECT_OK(Base64Decode(header_encoded, &header)); TF_EXPECT_OK(Base64Decode(claim_encoded, &claim)); Json::Value header_json, claim_json; EXPECT_TRUE(reader.parse(header, header_json)); EXPECT_EQ("RS256", header_json.get("alg", Json::Value::null).asString()); EXPECT_EQ("JWT", header_json.get("typ", Json::Value::null).asString()); EXPECT_EQ("fake_key_id", header_json.get("kid", Json::Value::null).asString()); EXPECT_TRUE(reader.parse(claim, claim_json)); EXPECT_EQ("fake-test-project.iam.gserviceaccount.com", claim_json.get("iss", Json::Value::null).asString()); EXPECT_EQ("https: claim_json.get("scope", Json::Value::null).asString()); EXPECT_EQ("https: claim_json.get("aud", Json::Value::null).asString()); EXPECT_EQ(10000, claim_json.get("iat", Json::Value::null).asInt64()); EXPECT_EQ(13600, claim_json.get("exp", Json::Value::null).asInt64()); } }
2,614
cpp
google/tsl
compute_engine_zone_provider
tsl/platform/cloud/compute_engine_zone_provider.cc
tsl/platform/cloud/compute_engine_zone_provider_test.cc
#ifndef TENSORFLOW_TSL_PLATFORM_CLOUD_COMPUTE_ENGINE_ZONE_PROVIDER_H_ #define TENSORFLOW_TSL_PLATFORM_CLOUD_COMPUTE_ENGINE_ZONE_PROVIDER_H_ #include "tsl/platform/cloud/compute_engine_metadata_client.h" #include "tsl/platform/cloud/zone_provider.h" namespace tsl { class ComputeEngineZoneProvider : public ZoneProvider { public: explicit ComputeEngineZoneProvider( std::shared_ptr<ComputeEngineMetadataClient> google_metadata_client); virtual ~ComputeEngineZoneProvider(); Status GetZone(string* zone) override; private: std::shared_ptr<ComputeEngineMetadataClient> google_metadata_client_; string cached_zone; ComputeEngineZoneProvider(const ComputeEngineZoneProvider&) = delete; void operator=(const ComputeEngineZoneProvider&) = delete; }; } #endif #include "tsl/platform/cloud/compute_engine_zone_provider.h" #include <utility> #include "tsl/platform/str_util.h" namespace tsl { namespace { constexpr char kGceMetadataZonePath[] = "instance/zone"; } ComputeEngineZoneProvider::ComputeEngineZoneProvider( std::shared_ptr<ComputeEngineMetadataClient> google_metadata_client) : google_metadata_client_(std::move(google_metadata_client)) {} Status ComputeEngineZoneProvider::GetZone(string* zone) { if (!cached_zone.empty()) { *zone = cached_zone; return OkStatus(); } std::vector<char> response_buffer; TF_RETURN_IF_ERROR(google_metadata_client_->GetMetadata(kGceMetadataZonePath, &response_buffer)); StringPiece location(&response_buffer[0], response_buffer.size()); std::vector<string> elems = str_util::Split(location, "/"); if (elems.size() == 4) { cached_zone = elems.back(); *zone = cached_zone; } else { LOG(ERROR) << "Failed to parse the zone name from location: " << string(location); } return OkStatus(); } ComputeEngineZoneProvider::~ComputeEngineZoneProvider() {} }
#include "tsl/platform/cloud/compute_engine_zone_provider.h" #include "tsl/platform/cloud/http_request_fake.h" #include "tsl/platform/test.h" namespace tsl { class ComputeEngineZoneProviderTest : public ::testing::Test { protected: void SetUp() override {} void TearDown() override {} }; TEST_F(ComputeEngineZoneProviderTest, GetZone) { std::vector<HttpRequest*> requests({new FakeHttpRequest( "Uri: http: "Header Metadata-Flavor: Google\n", "projects/123456789/zones/us-west1-b")}); auto httpRequestFactory = std::make_shared<FakeHttpRequestFactory>(&requests); auto metadata_client = std::make_shared<ComputeEngineMetadataClient>( httpRequestFactory, RetryConfig(0 )); ComputeEngineZoneProvider provider(metadata_client); string zone; TF_EXPECT_OK(provider.GetZone(&zone)); EXPECT_EQ("us-west1-b", zone); TF_EXPECT_OK(provider.GetZone(&zone)); } TEST_F(ComputeEngineZoneProviderTest, InvalidZoneString) { std::vector<HttpRequest*> requests({new FakeHttpRequest( "Uri: http: "Header Metadata-Flavor: Google\n", "invalidresponse")}); auto httpRequestFactory = std::make_shared<FakeHttpRequestFactory>(&requests); auto metadata_client = std::make_shared<ComputeEngineMetadataClient>( httpRequestFactory, RetryConfig(0 )); ComputeEngineZoneProvider provider(metadata_client); string zone; TF_EXPECT_OK(provider.GetZone(&zone)); EXPECT_EQ("", zone); } }
2,615
cpp
google/tsl
cpu_utils
tsl/platform/profile_utils/cpu_utils.cc
tsl/platform/profile_utils/cpu_utils_test.cc
#ifndef TENSORFLOW_TSL_PLATFORM_PROFILE_UTILS_CPU_UTILS_H_ #define TENSORFLOW_TSL_PLATFORM_PROFILE_UTILS_CPU_UTILS_H_ #include <chrono> #include <memory> #include "tsl/platform/macros.h" #include "tsl/platform/profile_utils/i_cpu_utils_helper.h" #include "tsl/platform/types.h" #if defined(ARMV6) || defined(__ARM_ARCH_7A__) #include <sys/time.h> #endif #if defined(_WIN32) #include <intrin.h> #endif namespace tsl { namespace profile_utils { class CpuUtils { public: static constexpr int64_t INVALID_FREQUENCY = -1; static constexpr uint64 DUMMY_CYCLE_CLOCK = 1; static inline uint64 GetCurrentClockCycle() { #if defined(__ANDROID__) return GetCpuUtilsHelperSingletonInstance().GetCurrentClockCycle(); #elif defined(_WIN32) return __rdtsc(); #elif defined(__x86_64__) || defined(__amd64__) uint64_t high, low; __asm__ volatile("rdtsc" : "=a"(low), "=d"(high)); return (high << 32) | low; #elif defined(__aarch64__) uint64_t virtual_timer_value; asm volatile("mrs %0, cntvct_el0" : "=r"(virtual_timer_value)); return virtual_timer_value; #elif defined(ARMV6) || defined(__ARM_ARCH_7A__) uint32_t pmccntr; uint32_t pmuseren; uint32_t pmcntenset; asm volatile("mrc p15, 0, %0, c9, c14, 0" : "=r"(pmuseren)); if (pmuseren & 1) { asm volatile("mrc p15, 0, %0, c9, c12, 1" : "=r"(pmcntenset)); if (pmcntenset & 0x80000000ul) { asm volatile("mrc p15, 0, %0, c9, c13, 0" : "=r"(pmccntr)); return static_cast<uint64>(pmccntr) * 64; } } return DUMMY_CYCLE_CLOCK; #elif defined(__powerpc64__) || defined(__ppc64__) uint64 __t; __asm__ __volatile__("mfspr %0,268" : "=r"(__t)); return __t; #elif defined(__powerpc__) || defined(__ppc__) uint64 upper, lower, tmp; __asm__ volatile( "0: \n" "\tmftbu %0 \n" "\tmftb %1 \n" "\tmftbu %2 \n" "\tcmpw %2,%0 \n" "\tbne 0b \n" : "=r"(upper), "=r"(lower), "=r"(tmp)); return ((static_cast<uint64>(upper) << 32) | lower); #elif defined(__s390x__) uint64 t; __asm__ __volatile__("stckf %0" : "=Q"(t)); return t; #else return DUMMY_CYCLE_CLOCK; #endif } #if (defined(__powerpc__) || \ defined(__ppc__) && (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__)) || \ (defined(__s390x__)) static uint64 GetCycleCounterFrequency(); #else static int64_t GetCycleCounterFrequency(); #endif static double GetMicroSecPerClock(); static void ResetClockCycle(); static void EnableClockCycleProfiling(); static void DisableClockCycleProfiling(); static std::chrono::duration<double> ConvertClockCycleToTime( const int64_t clock_cycle); private: class DefaultCpuUtilsHelper : public ICpuUtilsHelper { public: DefaultCpuUtilsHelper() = default; void ResetClockCycle() final {} uint64 GetCurrentClockCycle() final { return DUMMY_CYCLE_CLOCK; } void EnableClockCycleProfiling() final {} void DisableClockCycleProfiling() final {} int64_t CalculateCpuFrequency() final { return INVALID_FREQUENCY; } private: DefaultCpuUtilsHelper(const DefaultCpuUtilsHelper&) = delete; void operator=(const DefaultCpuUtilsHelper&) = delete; }; static int64_t GetCycleCounterFrequencyImpl(); static ICpuUtilsHelper& GetCpuUtilsHelperSingletonInstance(); CpuUtils(const CpuUtils&) = delete; void operator=(const CpuUtils&) = delete; }; } } #endif #include "tsl/platform/profile_utils/cpu_utils.h" #include <fstream> #include <limits> #include <mutex> #if defined(_WIN32) #include <windows.h> #endif #if defined(__APPLE__) #include <sys/sysctl.h> #endif #include "absl/base/call_once.h" #include "tsl/platform/logging.h" #include "tsl/platform/profile_utils/android_armv7a_cpu_utils_helper.h" namespace tsl { namespace profile_utils { constexpr int64_t CpuUtils::INVALID_FREQUENCY; static ICpuUtilsHelper* cpu_utils_helper_instance_ = nullptr; #if (defined(__powerpc__) || \ defined(__ppc__) && (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__)) || \ (defined(__s390x__)) uint64 CpuUtils::GetCycleCounterFrequency() { static const uint64 cpu_frequency = GetCycleCounterFrequencyImpl(); return cpu_frequency; } #else int64_t CpuUtils::GetCycleCounterFrequency() { static const int64_t cpu_frequency = GetCycleCounterFrequencyImpl(); return cpu_frequency; } #endif double CpuUtils::GetMicroSecPerClock() { static const double micro_sec_per_clock = (1000.0 * 1000.0) / static_cast<double>(GetCycleCounterFrequency()); return micro_sec_per_clock; } void CpuUtils::ResetClockCycle() { GetCpuUtilsHelperSingletonInstance().ResetClockCycle(); } void CpuUtils::EnableClockCycleProfiling() { GetCpuUtilsHelperSingletonInstance().EnableClockCycleProfiling(); } void CpuUtils::DisableClockCycleProfiling() { GetCpuUtilsHelperSingletonInstance().DisableClockCycleProfiling(); } std::chrono::duration<double> CpuUtils::ConvertClockCycleToTime( const int64_t clock_cycle) { return std::chrono::duration<double>(static_cast<double>(clock_cycle) / GetCycleCounterFrequency()); } int64_t CpuUtils::GetCycleCounterFrequencyImpl() { #if defined(__ANDROID__) return GetCpuUtilsHelperSingletonInstance().CalculateCpuFrequency(); #elif defined(__linux__) std::ifstream cpuinfo("/proc/cpuinfo"); if (!cpuinfo) { LOG(WARNING) << "Failed to open /proc/cpuinfo"; return INVALID_FREQUENCY; } string line; while (std::getline(cpuinfo, line)) { double cpu_freq = 0.0; int retval = 0; double freq_factor = 2.0; #if (defined(__powerpc__) || \ defined(__ppc__) && (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__)) retval = sscanf(line.c_str(), "clock : %lfMHz", &cpu_freq); freq_factor = 1.0; #elif defined(__s390x__) retval = sscanf(line.c_str(), "bogomips per cpu: %lf", &cpu_freq); #elif defined(__aarch64__) retval = sscanf(line.c_str(), "BogoMIPS : %lf", &cpu_freq); #else retval = sscanf(line.c_str(), "bogomips : %lf", &cpu_freq); #endif if (retval > 0) { const double freq_ghz = cpu_freq / 1000.0 / freq_factor; if (retval != 1 || freq_ghz < 0.01) { LOG(WARNING) << "Failed to get CPU frequency: " << freq_ghz << " GHz"; return INVALID_FREQUENCY; } const int64_t freq_n = static_cast<int64_t>(freq_ghz * 1000.0 * 1000.0 * 1000.0); VLOG(1) << "CPU Frequency: " << freq_n << " Hz"; return freq_n; } } LOG(WARNING) << "Failed to find bogomips or clock in /proc/cpuinfo; cannot determine " "CPU frequency"; return INVALID_FREQUENCY; #elif defined(__APPLE__) int64_t freq_hz = 0; size_t freq_hz_size = sizeof(freq_hz); int retval = sysctlbyname("hw.cpufrequency_max", &freq_hz, &freq_hz_size, NULL, 0); if (retval != 0 || freq_hz < 1e6) { int64_t tbfrequency = 0; size_t tbfrequency_size = sizeof(tbfrequency); retval = sysctlbyname("hw.tbfrequency", &tbfrequency, &tbfrequency_size, NULL, 0); if (retval == 0) { clockinfo clock_info; size_t clock_info_size = sizeof(clock_info); retval = sysctlbyname("kern.clockrate", &clock_info, &clock_info_size, NULL, 0); if (retval == 0) { freq_hz = clock_info.hz * tbfrequency; } } if (retval != 0 || freq_hz < 1e6) { LOG(WARNING) << "Failed to get CPU frequency: " << freq_hz << " Hz"; return INVALID_FREQUENCY; } } return freq_hz; #elif defined(_WIN32) LARGE_INTEGER freq; QueryPerformanceFrequency(&freq); return freq.QuadPart; #else return INVALID_FREQUENCY; #endif } ICpuUtilsHelper& CpuUtils::GetCpuUtilsHelperSingletonInstance() { static absl::once_flag flag; absl::call_once(flag, []() { if (cpu_utils_helper_instance_ != nullptr) { LOG(FATAL) << "cpu_utils_helper_instance_ is already instantiated."; } #if defined(__ANDROID__) && (__ANDROID_API__ >= 21) && \ (defined(__ARM_ARCH_7A__) || defined(__aarch64__)) cpu_utils_helper_instance_ = new AndroidArmV7ACpuUtilsHelper(); #else cpu_utils_helper_instance_ = new DefaultCpuUtilsHelper(); #endif }); return *cpu_utils_helper_instance_; } } }
#include "tsl/platform/profile_utils/cpu_utils.h" #include "tsl/platform/logging.h" #include "tsl/platform/profile_utils/clock_cycle_profiler.h" #include "tsl/platform/test.h" namespace tsl { namespace profile_utils { static constexpr bool DBG = false; class CpuUtilsTest : public ::testing::Test { protected: void SetUp() override { CpuUtils::EnableClockCycleProfiling(); } }; TEST_F(CpuUtilsTest, SetUpTestCase) {} TEST_F(CpuUtilsTest, TearDownTestCase) {} TEST_F(CpuUtilsTest, CheckGetCurrentClockCycle) { static constexpr int LOOP_COUNT = 10; const uint64 start_clock_count = CpuUtils::GetCurrentClockCycle(); CHECK_GT(start_clock_count, 0); uint64 prev_clock_count = start_clock_count; for (int i = 0; i < LOOP_COUNT; ++i) { const uint64 clock_count = CpuUtils::GetCurrentClockCycle(); CHECK_GE(clock_count, prev_clock_count); prev_clock_count = clock_count; } const uint64 end_clock_count = CpuUtils::GetCurrentClockCycle(); if (DBG) { LOG(INFO) << "start clock = " << start_clock_count; LOG(INFO) << "end clock = " << end_clock_count; LOG(INFO) << "average clock = " << ((end_clock_count - start_clock_count) / LOOP_COUNT); } } TEST_F(CpuUtilsTest, CheckCycleCounterFrequency) { #if (defined(__powerpc__) || \ defined(__ppc__) && (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__)) || \ (defined(__s390x__)) const uint64 cpu_frequency = CpuUtils::GetCycleCounterFrequency(); CHECK_GT(cpu_frequency, 0); CHECK_NE(cpu_frequency, unsigned(CpuUtils::INVALID_FREQUENCY)); #else const int64_t cpu_frequency = CpuUtils::GetCycleCounterFrequency(); CHECK_GT(cpu_frequency, 0); CHECK_NE(cpu_frequency, CpuUtils::INVALID_FREQUENCY); #endif if (DBG) { LOG(INFO) << "Cpu frequency = " << cpu_frequency; } } TEST_F(CpuUtilsTest, CheckMicroSecPerClock) { const double micro_sec_per_clock = CpuUtils::GetMicroSecPerClock(); CHECK_GT(micro_sec_per_clock, 0.0); if (DBG) { LOG(INFO) << "Micro sec per clock = " << micro_sec_per_clock; } } TEST_F(CpuUtilsTest, SimpleUsageOfClockCycleProfiler) { static constexpr int LOOP_COUNT = 10; ClockCycleProfiler prof; for (int i = 0; i < LOOP_COUNT; ++i) { prof.Start(); prof.Stop(); } EXPECT_EQ(LOOP_COUNT, static_cast<int>(prof.GetCount() + 0.5)); if (DBG) { prof.DumpStatistics("CpuUtilsTest"); } } } }
2,616
cpp
google/tsl
net
tsl/platform/windows/net.cc
tsl/platform/net_test.cc
#ifndef TENSORFLOW_TSL_PLATFORM_NET_H_ #define TENSORFLOW_TSL_PLATFORM_NET_H_ namespace tsl { namespace internal { int PickUnusedPortOrDie(); } } #endif #include "tsl/platform/net.h" #include <netinet/in.h> #include <sys/socket.h> #include <sys/types.h> #include <unistd.h> #include <cerrno> #include <cstdlib> #include <cstring> #include <random> #include <unordered_set> #include "tsl/platform/logging.h" #include "tsl/platform/strcat.h" #define MAX_EPHEMERAL_PORT 60999 #define MIN_EPHEMERAL_PORT 32768 namespace tsl { namespace internal { namespace { bool IsPortAvailable(int* port, bool is_tcp) { const int protocol = is_tcp ? IPPROTO_TCP : 0; const int fd = socket(AF_INET, is_tcp ? SOCK_STREAM : SOCK_DGRAM, protocol); struct sockaddr_in addr; socklen_t addr_len = sizeof(addr); int actual_port; CHECK_GE(*port, 0); CHECK_LE(*port, MAX_EPHEMERAL_PORT); if (fd < 0) { LOG(ERROR) << "socket() failed: " << strerror(errno); return false; } int one = 1; if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)) < 0) { LOG(ERROR) << "setsockopt() failed: " << strerror(errno); if (close(fd) < 0) { LOG(ERROR) << "close() failed: " << strerror(errno); }; return false; } addr.sin_family = AF_INET; addr.sin_addr.s_addr = INADDR_ANY; addr.sin_port = htons(static_cast<uint16_t>(*port)); if (bind(fd, reinterpret_cast<struct sockaddr*>(&addr), sizeof(addr)) < 0) { LOG(WARNING) << "bind(port=" << *port << ") failed: " << strerror(errno); if (close(fd) < 0) { LOG(ERROR) << "close() failed: " << strerror(errno); }; return false; } if (getsockname(fd, reinterpret_cast<struct sockaddr*>(&addr), &addr_len) < 0) { LOG(WARNING) << "getsockname() failed: " << strerror(errno); if (close(fd) < 0) { LOG(ERROR) << "close() failed: " << strerror(errno); }; return false; } CHECK_LE(addr_len, sizeof(addr)); actual_port = ntohs(addr.sin_port); CHECK_GT(actual_port, 0); if (*port == 0) { *port = actual_port; } else { CHECK_EQ(*port, actual_port); } if (close(fd) < 0) { LOG(ERROR) << "close() failed: " << strerror(errno); }; return true; } const int kNumRandomPortsToPick = 100; const int kMaximumTrials = 1000; } int PickUnusedPortOrDie() { static std::unordered_set<int> chosen_ports; bool is_tcp = true; int trial = 0; std::default_random_engine rgen(std::random_device{}()); std::uniform_int_distribution<int> rdist(MIN_EPHEMERAL_PORT, MAX_EPHEMERAL_PORT - 1); while (true) { int port; trial++; CHECK_LE(trial, kMaximumTrials) << "Failed to pick an unused port for testing."; if (trial == 1) { port = getpid() % (MAX_EPHEMERAL_PORT - MIN_EPHEMERAL_PORT) + MIN_EPHEMERAL_PORT; } else if (trial <= kNumRandomPortsToPick) { port = rdist(rgen); } else { port = 0; } if (chosen_ports.find(port) != chosen_ports.end()) { continue; } if (!IsPortAvailable(&port, is_tcp)) { continue; } CHECK_GT(port, 0); if (!IsPortAvailable(&port, !is_tcp)) { is_tcp = !is_tcp; continue; } chosen_ports.insert(port); return port; } return 0; } } }
#include "tsl/platform/net.h" #include "tsl/platform/logging.h" #include "tsl/platform/test.h" namespace tsl { namespace internal { TEST(Net, PickUnusedPortOrDie) { int port0 = PickUnusedPortOrDie(); int port1 = PickUnusedPortOrDie(); CHECK_GE(port0, 0); CHECK_LT(port0, 65536); CHECK_GE(port1, 0); CHECK_LT(port1, 65536); CHECK_NE(port0, port1); } } }
2,617
cpp
google/tsl
subprocess
tsl/platform/windows/subprocess.cc
tsl/platform/subprocess_test.cc
#ifndef TENSORFLOW_TSL_PLATFORM_DEFAULT_SUBPROCESS_H_ #define TENSORFLOW_TSL_PLATFORM_DEFAULT_SUBPROCESS_H_ #include <errno.h> #include <unistd.h> #include <string> #include <vector> #include "tsl/platform/macros.h" #include "tsl/platform/mutex.h" #include "tsl/platform/types.h" namespace tsl { class SubProcess { public: explicit SubProcess(int nfds = 3); virtual ~SubProcess(); virtual void SetChannelAction(Channel chan, ChannelAction action); virtual void SetProgram(const string& file, const std::vector<string>& argv); virtual bool Start(); virtual bool Kill(int signal); virtual bool Wait(); virtual int Communicate(const string* stdin_input, string* stdout_output, string* stderr_output); private: static constexpr int kNFds = 3; static bool chan_valid(int chan) { return ((chan >= 0) && (chan < kNFds)); } static bool retry(int e) { return ((e == EINTR) || (e == EAGAIN) || (e == EWOULDBLOCK)); } void FreeArgs() TF_EXCLUSIVE_LOCKS_REQUIRED(data_mu_); void ClosePipes() TF_EXCLUSIVE_LOCKS_REQUIRED(data_mu_); bool WaitInternal(int* status); mutable mutex proc_mu_; bool running_ TF_GUARDED_BY(proc_mu_); pid_t pid_ TF_GUARDED_BY(proc_mu_); mutable mutex data_mu_ TF_ACQUIRED_AFTER(proc_mu_); char* exec_path_ TF_GUARDED_BY(data_mu_); char** exec_argv_ TF_GUARDED_BY(data_mu_); ChannelAction action_[kNFds] TF_GUARDED_BY(data_mu_); int parent_pipe_[kNFds] TF_GUARDED_BY(data_mu_); int child_pipe_[kNFds] TF_GUARDED_BY(data_mu_); SubProcess(const SubProcess&) = delete; void operator=(const SubProcess&) = delete; }; } #endif #include "tsl/platform/subprocess.h" #include <fcntl.h> #include <poll.h> #include <signal.h> #include <spawn.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/wait.h> #include <memory> #include <vector> #include "tsl/platform/logging.h" #if !defined(__ANDROID_API__) || __ANDROID_API__ >= 28 #define USE_POSIX_SPAWN 1 #else #define USE_POSIX_SPAWN 0 #endif extern "C" { extern char** environ; } namespace tsl { SubProcess::SubProcess(int nfds) : running_(false), pid_(-1), exec_path_(nullptr), exec_argv_(nullptr) { for (int i = 0; i < kNFds; i++) { action_[i] = ACTION_CLOSE; parent_pipe_[i] = -1; child_pipe_[i] = -1; } } SubProcess::~SubProcess() { mutex_lock procLock(proc_mu_); mutex_lock dataLock(data_mu_); pid_ = -1; running_ = false; FreeArgs(); ClosePipes(); } void SubProcess::FreeArgs() { free(exec_path_); exec_path_ = nullptr; if (exec_argv_) { for (char** p = exec_argv_; *p != nullptr; p++) { free(*p); } delete[] exec_argv_; exec_argv_ = nullptr; } } void SubProcess::ClosePipes() { for (int i = 0; i < kNFds; i++) { if (parent_pipe_[i] >= 0) { if (close(parent_pipe_[i]) < 0) { LOG(ERROR) << "close() failed: " << strerror(errno); } parent_pipe_[i] = -1; } if (child_pipe_[i] >= 0) { if (close(child_pipe_[i]) < 0) { LOG(ERROR) << "close() failed: " << strerror(errno); } child_pipe_[i] = -1; } } } void SubProcess::SetProgram(const string& file, const std::vector<string>& argv) { mutex_lock procLock(proc_mu_); mutex_lock dataLock(data_mu_); if (running_) { LOG(FATAL) << "SetProgram called after the process was started."; return; } FreeArgs(); exec_path_ = strdup(file.c_str()); if (exec_path_ == nullptr) { LOG(FATAL) << "SetProgram failed to allocate file string."; return; } int argc = argv.size(); exec_argv_ = new char*[argc + 1]; for (int i = 0; i < argc; i++) { exec_argv_[i] = strdup(argv[i].c_str()); if (exec_argv_[i] == nullptr) { LOG(FATAL) << "SetProgram failed to allocate command argument."; return; } } exec_argv_[argc] = nullptr; } void SubProcess::SetChannelAction(Channel chan, ChannelAction action) { mutex_lock procLock(proc_mu_); mutex_lock dataLock(data_mu_); if (running_) { LOG(FATAL) << "SetChannelAction called after the process was started."; } else if (!chan_valid(chan)) { LOG(FATAL) << "SetChannelAction called with invalid channel: " << chan; } else if ((action != ACTION_CLOSE) && (action != ACTION_PIPE) && (action != ACTION_DUPPARENT)) { LOG(FATAL) << "SetChannelAction called with invalid action: " << action; } else { action_[chan] = action; } } #if USE_POSIX_SPAWN bool SubProcess::Start() { mutex_lock procLock(proc_mu_); mutex_lock dataLock(data_mu_); if (running_) { LOG(ERROR) << "Start called after the process was started."; return false; } if ((exec_path_ == nullptr) || (exec_argv_ == nullptr)) { LOG(ERROR) << "Start called without setting a program."; return false; } for (int i = 0; i < kNFds; i++) { if (action_[i] == ACTION_PIPE) { int pipe_fds[2]; if (pipe(pipe_fds) < 0) { LOG(ERROR) << "Start cannot create pipe: " << strerror(errno); ClosePipes(); return false; } if (i == 0) { parent_pipe_[i] = pipe_fds[1]; child_pipe_[i] = pipe_fds[0]; } else { parent_pipe_[i] = pipe_fds[0]; child_pipe_[i] = pipe_fds[1]; } if (fcntl(parent_pipe_[i], F_SETFL, O_NONBLOCK) < 0) { LOG(ERROR) << "Start cannot make pipe non-blocking: " << strerror(errno); ClosePipes(); return false; } if (fcntl(parent_pipe_[i], F_SETFD, FD_CLOEXEC) < 0) { LOG(ERROR) << "Start cannot make pipe close-on-exec: " << strerror(errno); ClosePipes(); return false; } } } posix_spawn_file_actions_t file_actions; int ret; ret = posix_spawn_file_actions_init(&file_actions); if (ret != 0) { LOG(ERROR) << "Start cannot initialize POSIX file actions: " << strerror(ret); ClosePipes(); return false; } int devnull_fd = -1; for (int i = 0; i < kNFds; i++) { if (parent_pipe_[i] >= 0) { ret = posix_spawn_file_actions_addclose(&file_actions, parent_pipe_[i]); if (ret != 0) { LOG(ERROR) << "posix_spawn_file_actions_addclose() failed: " << strerror(ret); } } switch (action_[i]) { case ACTION_DUPPARENT: break; case ACTION_PIPE: ret = posix_spawn_file_actions_adddup2(&file_actions, child_pipe_[i], i); if (ret != 0) { LOG(ERROR) << "posix_spawn_file_actions_adddup2() failed: " << strerror(ret); } ret = posix_spawn_file_actions_addclose(&file_actions, child_pipe_[i]); if (ret != 0) { LOG(ERROR) << "posix_spawn_file_actions_addclose() failed: " << strerror(ret); } break; case ACTION_CLOSE: default: if (i <= CHAN_STDERR) { if (devnull_fd < 0) { ret = posix_spawn_file_actions_addopen(&file_actions, i, "/dev/null", O_RDWR, 0); if (ret != 0) { LOG(ERROR) << "posix_spawn_file_actions_addopen() failed: " << strerror(ret); } devnull_fd = i; } else { ret = posix_spawn_file_actions_adddup2(&file_actions, devnull_fd, i); if (ret != 0) { LOG(ERROR) << "posix_spawn_file_actions_adddup2() failed: " << strerror(ret); } } } else { ret = posix_spawn_file_actions_addclose(&file_actions, i); if (ret != 0) { LOG(ERROR) << "posix_spawn_file_actions_addclose() failed: " << strerror(ret); } } break; } } ret = posix_spawnp(&pid_, exec_path_, &file_actions, nullptr, exec_argv_, environ); if (ret != 0) { LOG(INFO) << "Start cannot spawn child process: " << strerror(ret); ClosePipes(); return false; } ret = posix_spawn_file_actions_destroy(&file_actions); if (ret != 0) { LOG(WARNING) << "Start cannot destroy POSIX file actions: " << strerror(ret); } running_ = true; for (int i = 0; i < kNFds; i++) { if (child_pipe_[i] >= 0) { if (close(child_pipe_[i]) < 0) { LOG(ERROR) << "close() failed: " << strerror(errno); } child_pipe_[i] = -1; } } return true; } #else bool SubProcess::Start() { mutex_lock procLock(proc_mu_); mutex_lock dataLock(data_mu_); if (running_) { LOG(ERROR) << "Start called after the process was started."; return false; } if ((exec_path_ == nullptr) || (exec_argv_ == nullptr)) { LOG(ERROR) << "Start called without setting a program."; return false; } for (int i = 0; i < kNFds; i++) { if (action_[i] == ACTION_PIPE) { int pipe_fds[2]; if (pipe(pipe_fds) < 0) { LOG(ERROR) << "Start cannot create pipe: " << strerror(errno); ClosePipes(); return false; } if (i == 0) { parent_pipe_[i] = pipe_fds[1]; child_pipe_[i] = pipe_fds[0]; } else { parent_pipe_[i] = pipe_fds[0]; child_pipe_[i] = pipe_fds[1]; } if (fcntl(parent_pipe_[i], F_SETFL, O_NONBLOCK) < 0) { LOG(ERROR) << "Start cannot make pipe non-blocking: " << strerror(errno); ClosePipes(); return false; } if (fcntl(parent_pipe_[i], F_SETFD, FD_CLOEXEC) < 0) { LOG(ERROR) << "Start cannot make pipe close-on-exec: " << strerror(errno); ClosePipes(); return false; } } } pid_ = fork(); if (pid_ < 0) { LOG(ERROR) << "Start cannot fork() child process: " << strerror(errno); ClosePipes(); return false; } if (pid_ > 0) { running_ = true; for (int i = 0; i < kNFds; i++) { if (child_pipe_[i] >= 0) { if (close(child_pipe_[i]) < 0) { LOG(ERROR) << "close() failed: " << strerror(errno); } child_pipe_[i] = -1; } } return true; } int devnull_fd = -1; for (int i = 0; i < kNFds; i++) { if (parent_pipe_[i] >= 0) { if (close(parent_pipe_[i]) < 0) { LOG(ERROR) << "close() failed: " << strerror(errno); } parent_pipe_[i] = -1; } switch (action_[i]) { case ACTION_DUPPARENT: break; case ACTION_PIPE: while (dup2(child_pipe_[i], i) < 0) { if (!retry(errno)) { _exit(1); } } if (close(child_pipe_[i]) < 0) { LOG(ERROR) << "close() failed: " << strerror(errno); } child_pipe_[i] = -1; break; case ACTION_CLOSE: default: if (i <= CHAN_STDERR) { if (devnull_fd < 0) { while ((devnull_fd = open("/dev/null", O_RDWR, 0)) < 0) { if (!retry(errno)) { _exit(1); } } } while (dup2(devnull_fd, i) < 0) { if (!retry(errno)) { _exit(1); } } } else { if (close(i) < 0) { LOG(ERROR) << "close() failed: " << strerror(errno); } } break; } } if (devnull_fd >= 0) { if (close(devnull_fd) < 0) { LOG(ERROR) << "close() failed: " << strerror(errno); } } execvp(exec_path_, exec_argv_); _exit(1); } #endif bool SubProcess::Wait() { int status; return WaitInternal(&status); } bool SubProcess::WaitInternal(int* status) { proc_mu_.lock(); bool running = running_; pid_t pid = pid_; proc_mu_.unlock(); bool ret = false; if (running && (pid > 1)) { pid_t cpid; int cstat; bool done = false; while (!done) { cpid = waitpid(pid, &cstat, 0); if ((cpid < 0) && !retry(errno)) { done = true; } else if ((cpid == pid) && (WIFEXITED(cstat) || WIFSIGNALED(cstat))) { *status = cstat; ret = true; done = true; } } } proc_mu_.lock(); if ((running_ == running) && (pid_ == pid)) { running_ = false; pid_ = -1; } proc_mu_.unlock(); return ret; } bool SubProcess::Kill(int signal) { proc_mu_.lock(); bool running = running_; pid_t pid = pid_; proc_mu_.unlock(); bool ret = false; if (running && (pid > 1)) { ret = (kill(pid, signal) == 0); } return ret; } int SubProcess::Communicate(const string* stdin_input, string* stdout_output, string* stderr_output) { struct pollfd fds[kNFds]; size_t nbytes[kNFds]; string* iobufs[kNFds]; int fd_count = 0; proc_mu_.lock(); bool running = running_; proc_mu_.unlock(); if (!running) { LOG(ERROR) << "Communicate called without a running process."; return 1; } struct sigaction act; if (sigaction(SIGPIPE, nullptr, &act) < 0) { LOG(ERROR) << "Communicate cannot get SIGPIPE handler: " << strerror(errno); return 1; } if (act.sa_handler == SIG_DFL) { memset(&act, 0, sizeof(act)); act.sa_handler = SIG_IGN; sigemptyset(&act.sa_mask); if (sigaction(SIGPIPE, &act, nullptr) < 0) { LOG(ERROR) << "Communicate cannot ignore SIGPIPE: " << strerror(errno); return 1; } } data_mu_.lock(); for (int i = 0; i < kNFds; i++) { if (action_[i] == ACTION_PIPE) { switch (i) { case CHAN_STDIN: if (stdin_input == nullptr) { if (close(parent_pipe_[i]) < 0) { LOG(ERROR) << "close() failed: " << strerror(errno); } parent_pipe_[i] = -1; continue; } iobufs[fd_count] = const_cast<string*>(stdin_input); break; case CHAN_STDOUT: iobufs[fd_count] = stdout_output; break; case CHAN_STDERR: iobufs[fd_count] = stderr_output; break; default: iobufs[fd_count] = nullptr; break; } nbytes[fd_count] = 0; fds[fd_count].fd = parent_pipe_[i]; fds[fd_count].events = (i > 0) ? POLLIN : POLLOUT; fds[fd_count].revents = 0; fd_count++; } } int fd_remain = fd_count; char buf[4096]; while (fd_remain > 0) { int n = poll(fds, fd_count, -1); if ((n < 0) && !retry(errno)) { LOG(ERROR) << "Communicate cannot poll(): " << strerror(errno); fd_remain = 0; } else if (n == 0) { LOG(ERROR) << "Communicate cannot poll(): timeout not possible"; fd_remain = 0; } else if (n > 0) { for (int i = 0; i < fd_count; i++) { if ((fds[i].revents & (POLLIN | POLLHUP)) != 0) { ssize_t n = read(fds[i].fd, buf, sizeof(buf)); if (n > 0) { if (iobufs[i] != nullptr) { iobufs[i]->append(buf, n); nbytes[i] += n; } } else if ((n == 0) || !retry(errno)) { fds[i].fd = -1; fd_remain--; } } else if ((fds[i].revents & POLLOUT) != 0) { ssize_t n = iobufs[i]->size() - nbytes[i]; if (n > 0) { n = write(fds[i].fd, iobufs[i]->c_str() + nbytes[i], n); } if (n >= 0) { nbytes[i] += n; if (nbytes[i] >= iobufs[i]->size()) { fds[i].fd = -1; fd_remain--; if (close(parent_pipe_[CHAN_STDIN]) < 0) { LOG(ERROR) << "close() failed: " << strerror(errno); } parent_pipe_[CHAN_STDIN] = -1; } } else if (!retry(errno)) { fds[i].fd = -1; fd_remain--; } } else if ((fds[i].revents & (POLLERR | POLLNVAL)) != 0) { fds[i].fd = -1; fd_remain--; } } } } data_mu_.unlock(); int status; return WaitInternal(&status) ? status : -1; } std::unique_ptr<SubProcess> CreateSubProcess(const std::vector<string>& argv) { std::unique_ptr<SubProcess> proc(new SubProcess()); proc->SetProgram(argv[0], argv); proc->SetChannelAction(CHAN_STDERR, ACTION_DUPPARENT); proc->SetChannelAction(CHAN_STDOUT, ACTION_DUPPARENT); return proc; } }
#include "tsl/platform/subprocess.h" #include <stdlib.h> #include <algorithm> #include <string> #include "tsl/lib/core/status_test_util.h" #include "tsl/platform/path.h" #include "tsl/platform/strcat.h" #include "tsl/platform/test.h" #ifdef PLATFORM_WINDOWS #define WIFEXITED(code) ((code) != 3) #define WEXITSTATUS(code) (code) #define SIGKILL 9 #else #include <sys/wait.h> #endif namespace tsl { namespace { string EchoProgram() { std::string path = io::JoinPath(testing::TslSrcRoot(), "platform", "testdata", "test_echo"); return tsl::io::AppendDotExeIfWindows(path); } string EchoArgv1Program() { std::string path = io::JoinPath(testing::TslSrcRoot(), "platform", "testdata", "test_echo_argv_1"); return tsl::io::AppendDotExeIfWindows(path); } string NoopProgram() { std::string path = io::JoinPath(testing::TslSrcRoot(), "platform", "testdata", "test_noop"); return tsl::io::AppendDotExeIfWindows(path); } string StdErrProgram() { std::string path = io::JoinPath(testing::TslSrcRoot(), "platform", "testdata", "test_stderr"); return tsl::io::AppendDotExeIfWindows(path); } class SubProcessTest : public ::testing::Test {}; TEST_F(SubProcessTest, NoOutputNoComm) { tsl::SubProcess proc; proc.SetProgram(NoopProgram().c_str(), {NoopProgram()}); EXPECT_TRUE(proc.Start()); EXPECT_TRUE(proc.Wait()); } TEST_F(SubProcessTest, NoOutput) { tsl::SubProcess proc; proc.SetProgram(NoopProgram().c_str(), {NoopProgram()}); proc.SetChannelAction(CHAN_STDOUT, ACTION_PIPE); proc.SetChannelAction(CHAN_STDERR, ACTION_PIPE); EXPECT_TRUE(proc.Start()); string out, err; int status = proc.Communicate(nullptr, &out, &err); EXPECT_TRUE(WIFEXITED(status)); EXPECT_EQ(0, WEXITSTATUS(status)); EXPECT_EQ("", out); EXPECT_EQ("", err); } TEST_F(SubProcessTest, Stdout) { tsl::SubProcess proc; const char test_string[] = "hello_world"; proc.SetProgram(EchoArgv1Program().c_str(), {EchoArgv1Program(), test_string}); proc.SetChannelAction(CHAN_STDOUT, ACTION_PIPE); proc.SetChannelAction(CHAN_STDERR, ACTION_PIPE); EXPECT_TRUE(proc.Start()); string out, err; int status = proc.Communicate(nullptr, &out, &err); EXPECT_TRUE(WIFEXITED(status)); EXPECT_EQ(0, WEXITSTATUS(status)); EXPECT_EQ(test_string, out); EXPECT_EQ("", err); } TEST_F(SubProcessTest, StdoutIgnored) { tsl::SubProcess proc; const char test_string[] = "hello_world"; proc.SetProgram(EchoArgv1Program().c_str(), {EchoArgv1Program(), test_string}); proc.SetChannelAction(CHAN_STDOUT, ACTION_PIPE); proc.SetChannelAction(CHAN_STDERR, ACTION_PIPE); EXPECT_TRUE(proc.Start()); int status = proc.Communicate(nullptr, nullptr, nullptr); EXPECT_TRUE(WIFEXITED(status)); EXPECT_EQ(0, WEXITSTATUS(status)); } TEST_F(SubProcessTest, Stderr) { tsl::SubProcess proc; const char test_string[] = "muh_failure!"; proc.SetProgram(StdErrProgram().c_str(), {StdErrProgram(), test_string}); proc.SetChannelAction(CHAN_STDOUT, ACTION_PIPE); proc.SetChannelAction(CHAN_STDERR, ACTION_PIPE); EXPECT_TRUE(proc.Start()); string out, err; int status = proc.Communicate(nullptr, &out, &err); EXPECT_TRUE(WIFEXITED(status)); EXPECT_NE(0, WEXITSTATUS(status)); EXPECT_EQ("", out); EXPECT_EQ(test_string, err); } TEST_F(SubProcessTest, StderrIgnored) { tsl::SubProcess proc; const char test_string[] = "muh_failure!"; proc.SetProgram(StdErrProgram().c_str(), {StdErrProgram(), test_string}); proc.SetChannelAction(CHAN_STDOUT, ACTION_PIPE); proc.SetChannelAction(CHAN_STDERR, ACTION_PIPE); EXPECT_TRUE(proc.Start()); int status = proc.Communicate(nullptr, nullptr, nullptr); EXPECT_TRUE(WIFEXITED(status)); EXPECT_NE(0, WEXITSTATUS(status)); } TEST_F(SubProcessTest, Stdin) { tsl::SubProcess proc; proc.SetProgram(EchoProgram().c_str(), {EchoProgram()}); proc.SetChannelAction(CHAN_STDIN, ACTION_PIPE); EXPECT_TRUE(proc.Start()); string in = "foobar\nbarfoo\nhaha\n"; int status = proc.Communicate(&in, nullptr, nullptr); EXPECT_TRUE(WIFEXITED(status)); EXPECT_EQ(0, WEXITSTATUS(status)); } TEST_F(SubProcessTest, StdinStdout) { tsl::SubProcess proc; proc.SetProgram(EchoProgram().c_str(), {EchoProgram()}); proc.SetChannelAction(CHAN_STDIN, ACTION_PIPE); proc.SetChannelAction(CHAN_STDOUT, ACTION_PIPE); EXPECT_TRUE(proc.Start()); string in = "foobar\nbarfoo\nhaha\n"; string out; int status = proc.Communicate(&in, &out, nullptr); EXPECT_TRUE(WIFEXITED(status)); EXPECT_EQ(0, WEXITSTATUS(status)); out.erase(std::remove(out.begin(), out.end(), '\r'), out.end()); EXPECT_EQ(in, out); } TEST_F(SubProcessTest, StdinChildExit) { tsl::SubProcess proc; proc.SetProgram(NoopProgram().c_str(), {NoopProgram()}); proc.SetChannelAction(CHAN_STDIN, ACTION_PIPE); EXPECT_TRUE(proc.Start()); string in; in.reserve(1000000); for (int i = 0; i < 100000; i++) { in += "hello xyz\n"; } int status = proc.Communicate(&in, nullptr, nullptr); EXPECT_TRUE(WIFEXITED(status)); EXPECT_EQ(0, WEXITSTATUS(status)); } TEST_F(SubProcessTest, StdinStdoutOverlap) { tsl::SubProcess proc; proc.SetProgram(EchoProgram().c_str(), {EchoProgram()}); proc.SetChannelAction(CHAN_STDIN, ACTION_PIPE); proc.SetChannelAction(CHAN_STDOUT, ACTION_PIPE); EXPECT_TRUE(proc.Start()); string in; in.reserve(1000000); for (int i = 0; i < 100000; i++) { in += "hello xyz\n"; } string out; int status = proc.Communicate(&in, &out, nullptr); EXPECT_TRUE(WIFEXITED(status)); EXPECT_EQ(0, WEXITSTATUS(status)); out.erase(std::remove(out.begin(), out.end(), '\r'), out.end()); EXPECT_EQ(in, out); } TEST_F(SubProcessTest, KillProc) { tsl::SubProcess proc; proc.SetProgram(EchoProgram().c_str(), {EchoProgram()}); proc.SetChannelAction(CHAN_STDIN, ACTION_PIPE); proc.SetChannelAction(CHAN_STDOUT, ACTION_PIPE); EXPECT_TRUE(proc.Start()); EXPECT_TRUE(proc.Kill(SIGKILL)); EXPECT_TRUE(proc.Wait()); EXPECT_FALSE(proc.Kill(SIGKILL)); } } }
2,618
cpp
google/tsl
stacktrace_handler
tsl/platform/windows/stacktrace_handler.cc
tsl/platform/stacktrace_handler_test.cc
#ifndef TENSORFLOW_TSL_PLATFORM_STACKTRACE_HANDLER_H_ #define TENSORFLOW_TSL_PLATFORM_STACKTRACE_HANDLER_H_ namespace tsl { namespace testing { void InstallStacktraceHandler(); } } #endif #include "tsl/platform/platform.h" #if !defined(IS_MOBILE_PLATFORM) && defined(PLATFORM_POSIX) && \ (defined(__clang__) || defined(__GNUC__)) #define TF_GENERATE_STACKTRACE #endif #if defined(TF_GENERATE_STACKTRACE) #include <errno.h> #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/time.h> #include <unistd.h> #include <string> #include "tsl/platform/stacktrace.h" #endif namespace tsl { namespace testing { #if defined(TF_GENERATE_STACKTRACE) inline void SafePrintStackTrace() { static const char begin_msg[] = "*** BEGIN MANGLED STACK TRACE ***\n"; (void)!write(STDERR_FILENO, begin_msg, strlen(begin_msg)); int buffer_size = 128; void *trace[128]; buffer_size = backtrace(trace, buffer_size); backtrace_symbols_fd(trace, buffer_size, STDERR_FILENO); static const char end_msg[] = "*** END MANGLED STACK TRACE ***\n\n"; (void)!write(STDERR_FILENO, end_msg, strlen(end_msg)); } static void StacktraceHandler(int sig, siginfo_t *si, void *v) { struct itimerval timer; timer.it_value.tv_sec = 60; timer.it_value.tv_usec = 0; timer.it_interval.tv_sec = 0; timer.it_interval.tv_usec = 0; setitimer(ITIMER_REAL, &timer, 0); struct sigaction sa_timeout; memset(&sa_timeout, 0, sizeof(sa_timeout)); sa_timeout.sa_handler = SIG_DFL; sigaction(SIGALRM, &sa_timeout, 0); char buf[128]; snprintf(buf, sizeof(buf), "*** Received signal %d ***\n", sig); (void)!write(STDERR_FILENO, buf, strlen(buf)); SafePrintStackTrace(); std::string stacktrace = CurrentStackTrace(); (void)!write(STDERR_FILENO, stacktrace.c_str(), stacktrace.length()); struct sigaction sa; sigemptyset(&sa.sa_mask); sa.sa_flags = 0; sa.sa_handler = SIG_DFL; sigaction(SIGABRT, &sa, NULL); abort(); } void InstallStacktraceHandler() { int handled_signals[] = {SIGSEGV, SIGABRT, SIGBUS, SIGILL, SIGFPE}; size_t array_limit = sizeof(handled_signals) / sizeof(int); for (size_t i = 0; i < array_limit; i++) { int sig = handled_signals[i]; struct sigaction sa; struct sigaction osa; sigemptyset(&sa.sa_mask); sa.sa_flags = SA_SIGINFO | SA_RESETHAND; sa.sa_sigaction = &StacktraceHandler; if (sigaction(sig, &sa, &osa) != 0) { char buf[128]; snprintf(buf, sizeof(buf), "Warning, can't install backtrace signal handler for signal %d, " "errno:%d \n", sig, errno); (void)!write(STDERR_FILENO, buf, strlen(buf)); } else if (osa.sa_handler != SIG_DFL) { char buf[128]; snprintf(buf, sizeof(buf), "Warning, backtrace signal handler for signal %d overwrote " "previous handler.\n", sig); (void)!write(STDERR_FILENO, buf, strlen(buf)); } } } #else void InstallStacktraceHandler() {} #endif } }
#include <csignal> #include "tsl/platform/logging.h" #include "tsl/platform/test.h" namespace tsl { namespace { TEST(StacktraceHandlerTest, GeneratesStacktrace) { EXPECT_DEATH(raise(SIGABRT), "testing::internal::UnitTestImpl::RunAllTests"); } } }
2,619
cpp
google/tsl
stacktrace
tsl/platform/windows/stacktrace.cc
tsl/platform/stacktrace_test.cc
#ifndef TENSORFLOW_TSL_PLATFORM_DEFAULT_STACKTRACE_H_ #define TENSORFLOW_TSL_PLATFORM_DEFAULT_STACKTRACE_H_ #include "tsl/platform/platform.h" #if !defined(IS_MOBILE_PLATFORM) && (defined(__clang__) || defined(__GNUC__)) #define TF_HAS_STACKTRACE #endif #if defined(TF_HAS_STACKTRACE) #include <dlfcn.h> #include <execinfo.h> #include <stdio.h> #include <string.h> #include <unistd.h> #endif #include <sstream> #include <string> #include "tsl/platform/abi.h" namespace tsl { inline std::string CurrentStackTrace() { #if defined(TF_HAS_STACKTRACE) std::stringstream ss(""); ss << "*** Begin stack trace ***" << std::endl; int buffer_size = 128; void* trace[128]; buffer_size = backtrace(trace, buffer_size); for (int i = 0; i < buffer_size; ++i) { const char* symbol = ""; Dl_info info; if (dladdr(trace[i], &info)) { if (info.dli_sname != nullptr) { symbol = info.dli_sname; } } std::string demangled = port::MaybeAbiDemangle(symbol); if (demangled.length()) { ss << "\t" << demangled << std::endl; } else { ss << "\t" << symbol << std::endl; } } ss << "*** End stack trace ***" << std::endl; return ss.str(); #else return std::string(); #endif } inline void DebugWriteToString(const char* data, void* arg) { reinterpret_cast<std::string*>(arg)->append(data); } class SavedStackTrace { public: SavedStackTrace() {} void CreateCurrent(int skip_count) {} void Reset() {} typedef void DebugWriter(const char*, void*); void Dump(DebugWriter* writerfn, void* arg) const {} int depth() const { return 0; } void* const* stack() const { return stack_; } private: void* stack_[32]; }; } #endif #include "tsl/platform/windows/stacktrace.h" #include <windows.h> #include <dbghelp.h> #include <string> #include "tsl/platform/mutex.h" #pragma comment(lib, "dbghelp.lib") namespace tsl { static bool SymbolsAreAvailableInit() { SymSetOptions(SYMOPT_UNDNAME | SYMOPT_DEFERRED_LOADS); return SymInitialize(GetCurrentProcess(), NULL, true); } static bool SymbolsAreAvailable() { static bool kSymbolsAvailable = SymbolsAreAvailableInit(); return kSymbolsAvailable; } std::string CurrentStackTrace() { HANDLE current_process = GetCurrentProcess(); static constexpr int kMaxStackFrames = 64; void* trace[kMaxStackFrames]; int num_frames = CaptureStackBackTrace(0, kMaxStackFrames, trace, NULL); static mutex mu(tsl::LINKER_INITIALIZED); std::string stacktrace; for (int i = 0; i < num_frames; ++i) { const char* symbol = "(unknown)"; if (SymbolsAreAvailable()) { char symbol_info_buffer[sizeof(SYMBOL_INFO) + MAX_SYM_NAME * sizeof(TCHAR)]; SYMBOL_INFO* symbol_ptr = reinterpret_cast<SYMBOL_INFO*>(symbol_info_buffer); symbol_ptr->SizeOfStruct = sizeof(SYMBOL_INFO); symbol_ptr->MaxNameLen = MAX_SYM_NAME; mutex_lock lock(mu); if (SymFromAddr(current_process, reinterpret_cast<DWORD64>(trace[i]), 0, symbol_ptr)) { symbol = symbol_ptr->Name; } } char buffer[256]; snprintf(buffer, sizeof(buffer), "0x%p\t%s", trace[i], symbol); stacktrace += buffer; stacktrace += "\n"; } return stacktrace; } }
#include "tsl/platform/stacktrace.h" #include <string> #include "tsl/platform/logging.h" #include "tsl/platform/test.h" namespace tsl { namespace { #if defined(TF_HAS_STACKTRACE) TEST(StacktraceTest, StacktraceWorks) { std::string stacktrace = CurrentStackTrace(); LOG(INFO) << "CurrentStackTrace():\n" << stacktrace; std::string expected_frame = "testing::internal::UnitTestImpl::RunAllTests"; EXPECT_NE(stacktrace.find(expected_frame), std::string::npos); } #endif } }
2,620
cpp
google/tsl
logging
tsl/platform/default/logging.cc
tsl/platform/logging_test.cc
#if defined(_WIN32) #pragma warning(disable : 4716) #endif #ifndef TENSORFLOW_TSL_PLATFORM_DEFAULT_LOGGING_H_ #define TENSORFLOW_TSL_PLATFORM_DEFAULT_LOGGING_H_ #include <atomic> #include <limits> #include <memory> #include <sstream> #include <string> #include <vector> #include "absl/base/log_severity.h" #include "absl/strings/string_view.h" #include "tsl/platform/macros.h" #include "tsl/platform/types.h" #undef ERROR #undef LOG #undef LOG_EVERY_N #undef LOG_FIRST_N #undef LOG_EVERY_POW_2 #undef LOG_EVERY_N_SEC #undef VLOG #undef CHECK #undef CHECK_EQ #undef CHECK_NE #undef CHECK_LT #undef CHECK_LE #undef CHECK_GT #undef CHECK_GE #undef DCHECK #undef DCHECK_EQ #undef DCHECK_NE #undef DCHECK_LT #undef DCHECK_LE #undef DCHECK_GT #undef DCHECK_GE #undef QCHECK #undef QCHECK_EQ #undef QCHECK_NE #undef QCHECK_LT #undef QCHECK_LE #undef QCHECK_GT #undef QCHECK_GE #undef PCHECK namespace tsl { const int INFO = 0; const int WARNING = 1; const int ERROR = 2; const int FATAL = 3; const int NUM_SEVERITIES = 4; namespace internal { void LogString(const char* fname, int line, int severity, const std::string& message); class LogMessage : public std::basic_ostringstream<char> { public: LogMessage(const char* fname, int line, int severity); ~LogMessage() override; LogMessage& AtLocation(const char* fname, int line); static int64_t MaxVLogLevel(); static bool VmoduleActivated(const char* fname, int level); protected: void GenerateLogMessage(); private: const char* fname_; int line_; int severity_; }; struct Voidifier { template <typename T> void operator&(const T&) const {} }; class LogMessageFatal : public LogMessage { public: LogMessageFatal(const char* file, int line) TF_ATTRIBUTE_COLD; TF_ATTRIBUTE_NORETURN ~LogMessageFatal() override; }; class LogMessageNull : public std::basic_ostringstream<char> { public: LogMessageNull() {} ~LogMessageNull() override {} }; #define _TF_LOG_INFO \ ::tsl::internal::LogMessage(__FILE__, __LINE__, ::tsl::INFO) #define _TF_LOG_WARNING \ ::tsl::internal::LogMessage(__FILE__, __LINE__, ::tsl::WARNING) #define _TF_LOG_ERROR \ ::tsl::internal::LogMessage(__FILE__, __LINE__, ::tsl::ERROR) #define _TF_LOG_FATAL ::tsl::internal::LogMessageFatal(__FILE__, __LINE__) #define _TF_LOG_QFATAL _TF_LOG_FATAL #ifdef NDEBUG #define _TF_LOG_DFATAL _TF_LOG_ERROR #else #define _TF_LOG_DFATAL _TF_LOG_FATAL #endif #define LOG(severity) _TF_LOG_##severity #ifdef IS_MOBILE_PLATFORM #define VLOG_IS_ON(lvl) ((lvl) <= 0) #else #define VLOG_IS_ON(lvl) \ (([](int level, const char* fname) { \ static const bool vmodule_activated = \ ::tsl::internal::LogMessage::VmoduleActivated(fname, level); \ return vmodule_activated; \ })(lvl, __FILE__)) #endif #define VLOG(level) \ TF_PREDICT_TRUE(!VLOG_IS_ON(level)) \ ? (void)0 \ : ::tsl::internal::Voidifier() & \ ::tsl::internal::LogMessage(__FILE__, __LINE__, tsl::INFO) #ifndef NDEBUG #define DVLOG VLOG #else #define DVLOG(verbose_level) \ while (false && (verbose_level) > 0) ::tsl::internal::LogMessageNull() #endif class LogEveryNState { public: bool ShouldLog(int n); uint32_t counter() { return counter_.load(std::memory_order_relaxed); } private: std::atomic<uint32> counter_{0}; }; class LogFirstNState { public: bool ShouldLog(int n); uint32 counter() { return counter_.load(std::memory_order_relaxed); } private: std::atomic<uint32> counter_{0}; }; class LogEveryPow2State { public: bool ShouldLog(int ignored); uint32 counter() { return counter_.load(std::memory_order_relaxed); } private: std::atomic<uint32> counter_{0}; }; class LogEveryNSecState { public: bool ShouldLog(double seconds); uint32 counter() { return counter_.load(std::memory_order_relaxed); } private: std::atomic<uint32> counter_{0}; std::atomic<int64_t> next_log_time_cycles_{0}; }; #define LOGGING_INTERNAL_STATEFUL_CONDITION(kind, condition, arg) \ for (bool logging_internal_stateful_condition_do_log(condition); \ logging_internal_stateful_condition_do_log; \ logging_internal_stateful_condition_do_log = false) \ for (static ::tsl::internal::Log##kind##State \ logging_internal_stateful_condition_state; \ logging_internal_stateful_condition_do_log && \ logging_internal_stateful_condition_state.ShouldLog(arg); \ logging_internal_stateful_condition_do_log = false) \ for (const uint32_t COUNTER ABSL_ATTRIBUTE_UNUSED = \ logging_internal_stateful_condition_state.counter(); \ logging_internal_stateful_condition_do_log; \ logging_internal_stateful_condition_do_log = false) #define LOG_EVERY_N(severity, n) \ LOGGING_INTERNAL_STATEFUL_CONDITION(EveryN, true, n) \ LOG(severity) #define LOG_FIRST_N(severity, n) \ LOGGING_INTERNAL_STATEFUL_CONDITION(FirstN, true, n) \ LOG(severity) #define LOG_EVERY_POW_2(severity) \ LOGGING_INTERNAL_STATEFUL_CONDITION(EveryPow2, true, 0) \ LOG(severity) #define LOG_EVERY_N_SEC(severity, n_seconds) \ LOGGING_INTERNAL_STATEFUL_CONDITION(EveryNSec, true, n_seconds) \ LOG(severity) #define CHECK(condition) \ if (TF_PREDICT_FALSE(!(condition))) \ LOG(FATAL) << "Check failed: " #condition " " template <typename T> inline const T& GetReferenceableValue(const T& t) { return t; } inline char GetReferenceableValue(char t) { return t; } inline unsigned char GetReferenceableValue(unsigned char t) { return t; } inline signed char GetReferenceableValue(signed char t) { return t; } inline int16 GetReferenceableValue(int16_t t) { return t; } inline uint16 GetReferenceableValue(uint16 t) { return t; } inline int GetReferenceableValue(int t) { return t; } inline unsigned int GetReferenceableValue(unsigned int t) { return t; } inline int64_t GetReferenceableValue(int64_t t) { return t; } inline uint64 GetReferenceableValue(uint64 t) { return t; } template <typename T> inline void MakeCheckOpValueString(std::ostream* os, const T& v) { (*os) << v; } template <> void MakeCheckOpValueString(std::ostream* os, const char& v); template <> void MakeCheckOpValueString(std::ostream* os, const signed char& v); template <> void MakeCheckOpValueString(std::ostream* os, const unsigned char& v); #if LANG_CXX11 template <> void MakeCheckOpValueString(std::ostream* os, const std::nullptr_t& v); #endif struct CheckOpString { explicit CheckOpString(string* str) : str_(str) {} explicit operator bool() const { return TF_PREDICT_FALSE(str_ != nullptr); } string* str_; }; template <typename T1, typename T2> string* MakeCheckOpString(const T1& v1, const T2& v2, const char* exprtext) TF_ATTRIBUTE_NOINLINE; class CheckOpMessageBuilder { public: explicit CheckOpMessageBuilder(const char* exprtext); ~CheckOpMessageBuilder(); std::ostream* ForVar1() { return stream_; } std::ostream* ForVar2(); string* NewString(); private: std::ostringstream* stream_; }; template <typename T1, typename T2> string* MakeCheckOpString(const T1& v1, const T2& v2, const char* exprtext) { CheckOpMessageBuilder comb(exprtext); MakeCheckOpValueString(comb.ForVar1(), v1); MakeCheckOpValueString(comb.ForVar2(), v2); return comb.NewString(); } #define TF_DEFINE_CHECK_OP_IMPL(name, op) \ template <typename T1, typename T2> \ inline string* name##Impl(const T1& v1, const T2& v2, \ const char* exprtext) { \ if (TF_PREDICT_TRUE(v1 op v2)) \ return NULL; \ else \ return ::tsl::internal::MakeCheckOpString(v1, v2, exprtext); \ } \ inline string* name##Impl(int v1, int v2, const char* exprtext) { \ return name##Impl<int, int>(v1, v2, exprtext); \ } TF_DEFINE_CHECK_OP_IMPL(Check_EQ, ==) inline string* Check_EQImpl(int v1, size_t v2, const char* exprtext) { if (TF_PREDICT_FALSE(v1 < 0)) ::tsl::internal::MakeCheckOpString(v1, v2, exprtext); return Check_EQImpl(size_t(v1), v2, exprtext); } inline string* Check_EQImpl(size_t v1, int v2, const char* exprtext) { return Check_EQImpl(v2, v1, exprtext); } TF_DEFINE_CHECK_OP_IMPL(Check_NE, !=) inline string* Check_NEImpl(int v1, size_t v2, const char* exprtext) { if (v1 < 0) return NULL; return Check_NEImpl(size_t(v1), v2, exprtext); } inline string* Check_NEImpl(size_t v1, int v2, const char* exprtext) { return Check_NEImpl(v2, v1, exprtext); } TF_DEFINE_CHECK_OP_IMPL(Check_LE, <=) inline string* Check_LEImpl(int v1, size_t v2, const char* exprtext) { if (v1 <= 0) return NULL; return Check_LEImpl(size_t(v1), v2, exprtext); } inline string* Check_LEImpl(size_t v1, int v2, const char* exprtext) { if (TF_PREDICT_FALSE(v2 < 0)) return ::tsl::internal::MakeCheckOpString(v1, v2, exprtext); return Check_LEImpl(v1, size_t(v2), exprtext); } TF_DEFINE_CHECK_OP_IMPL(Check_LT, <) inline string* Check_LTImpl(int v1, size_t v2, const char* exprtext) { if (v1 < 0) return NULL; return Check_LTImpl(size_t(v1), v2, exprtext); } inline string* Check_LTImpl(size_t v1, int v2, const char* exprtext) { if (v2 < 0) return ::tsl::internal::MakeCheckOpString(v1, v2, exprtext); return Check_LTImpl(v1, size_t(v2), exprtext); } template <typename T1, typename T2> inline string* Check_GEImpl(const T1& v1, const T2& v2, const char* exprtext) { return Check_LEImpl(v2, v1, exprtext); } template <typename T1, typename T2> inline string* Check_GTImpl(const T1& v1, const T2& v2, const char* exprtext) { return Check_LTImpl(v2, v1, exprtext); } #undef TF_DEFINE_CHECK_OP_IMPL #define CHECK_OP_LOG(name, op, val1, val2) \ while (::tsl::internal::CheckOpString _result{::tsl::internal::name##Impl( \ ::tsl::internal::GetReferenceableValue(val1), \ ::tsl::internal::GetReferenceableValue(val2), #val1 " " #op " " #val2)}) \ ::tsl::internal::LogMessageFatal(__FILE__, __LINE__) << *(_result.str_) #define CHECK_OP(name, op, val1, val2) CHECK_OP_LOG(name, op, val1, val2) #define CHECK_EQ(val1, val2) CHECK_OP(Check_EQ, ==, val1, val2) #define CHECK_NE(val1, val2) CHECK_OP(Check_NE, !=, val1, val2) #define CHECK_LE(val1, val2) CHECK_OP(Check_LE, <=, val1, val2) #define CHECK_LT(val1, val2) CHECK_OP(Check_LT, <, val1, val2) #define CHECK_GE(val1, val2) CHECK_OP(Check_GE, >=, val1, val2) #define CHECK_GT(val1, val2) CHECK_OP(Check_GT, >, val1, val2) #define CHECK_NOTNULL(val) \ ::tsl::internal::CheckNotNull(__FILE__, __LINE__, \ "'" #val "' Must be non NULL", (val)) #ifndef NDEBUG #define DCHECK(condition) CHECK(condition) #define DCHECK_EQ(val1, val2) CHECK_EQ(val1, val2) #define DCHECK_NE(val1, val2) CHECK_NE(val1, val2) #define DCHECK_LE(val1, val2) CHECK_LE(val1, val2) #define DCHECK_LT(val1, val2) CHECK_LT(val1, val2) #define DCHECK_GE(val1, val2) CHECK_GE(val1, val2) #define DCHECK_GT(val1, val2) CHECK_GT(val1, val2) #else #define DCHECK(condition) \ while (false && (condition)) LOG(FATAL) #define _TF_DCHECK_NOP(x, y) \ while (false && ((void)(x), (void)(y), 0)) LOG(FATAL) #define DCHECK_EQ(x, y) _TF_DCHECK_NOP(x, y) #define DCHECK_NE(x, y) _TF_DCHECK_NOP(x, y) #define DCHECK_LE(x, y) _TF_DCHECK_NOP(x, y) #define DCHECK_LT(x, y) _TF_DCHECK_NOP(x, y) #define DCHECK_GE(x, y) _TF_DCHECK_NOP(x, y) #define DCHECK_GT(x, y) _TF_DCHECK_NOP(x, y) #endif #define QCHECK(condition) CHECK(condition) #define QCHECK_EQ(x, y) CHECK_EQ(x, y) #define QCHECK_NE(x, y) CHECK_NE(x, y) #define QCHECK_LE(x, y) CHECK_LE(x, y) #define QCHECK_LT(x, y) CHECK_LT(x, y) #define QCHECK_GE(x, y) CHECK_GE(x, y) #define QCHECK_GT(x, y) CHECK_GT(x, y) template <typename T> T&& CheckNotNull(const char* file, int line, const char* exprtext, T&& t) { if (t == nullptr) { LogMessageFatal(file, line) << string(exprtext); } return std::forward<T>(t); } int64_t MinLogLevelFromEnv(); int64_t MaxVLogLevelFromEnv(); } class TFLogEntry { static absl::LogSeverity AsAbslLogSeverity(int severity) { return static_cast<absl::LogSeverity>(severity); } public: explicit TFLogEntry(int severity, absl::string_view message) : severity_(AsAbslLogSeverity(severity)), message_(message) {} explicit TFLogEntry(int severity, absl::string_view fname, int line, absl::string_view message) : severity_(AsAbslLogSeverity(severity)), fname_(fname), line_(line), message_(message) {} absl::LogSeverity log_severity() const { return severity_; } std::string FName() const { return fname_; } int Line() const { return line_; } std::string ToString() const { return message_; } absl::string_view text_message() const { return message_; } absl::string_view text_message_with_prefix() const { return message_; } private: const absl::LogSeverity severity_; const std::string fname_; int line_ = -1; const std::string message_; }; class TFLogSink { public: virtual ~TFLogSink() = default; virtual void Send(const TFLogEntry& entry) = 0; virtual void WaitTillSent() {} }; class TFDefaultLogSink : public TFLogSink { public: void Send(const TFLogEntry& entry) override; }; void TFAddLogSink(TFLogSink* sink); void TFRemoveLogSink(TFLogSink* sink); std::vector<TFLogSink*> TFGetLogSinks(); void UpdateLogVerbosityIfDefined(const char* env_var); } #endif #include "tsl/platform/default/logging.h" #include "absl/base/internal/cycleclock.h" #include "absl/base/internal/sysinfo.h" #include "tsl/platform/env_time.h" #include "tsl/platform/macros.h" #include "tsl/platform/mutex.h" #if defined(PLATFORM_POSIX_ANDROID) #include <android/log.h> #include <iostream> #include <sstream> #endif #include <stdlib.h> #include <string.h> #include <time.h> #include <algorithm> #include <queue> #include <unordered_map> namespace tsl { namespace internal { namespace { class TFLogSinks { public: static TFLogSinks& Instance(); void Add(TFLogSink* sink); void Remove(TFLogSink* sink); std::vector<TFLogSink*> GetSinks() const; void Send(const TFLogEntry& entry); private: TFLogSinks(); void SendToSink(TFLogSink& sink, const TFLogEntry& entry); std::queue<TFLogEntry> log_entry_queue_; static const size_t kMaxLogEntryQueueSize = 128; mutable tsl::mutex mutex_; std::vector<TFLogSink*> sinks_; }; TFLogSinks::TFLogSinks() { #ifndef NO_DEFAULT_LOGGER static TFDefaultLogSink* default_sink = new TFDefaultLogSink(); sinks_.emplace_back(default_sink); #endif } TFLogSinks& TFLogSinks::Instance() { static TFLogSinks* instance = new TFLogSinks(); return *instance; } void TFLogSinks::Add(TFLogSink* sink) { assert(sink != nullptr && "The sink must not be a nullptr"); tsl::mutex_lock lock(mutex_); sinks_.emplace_back(sink); if (sinks_.size() == 1) { while (!log_entry_queue_.empty()) { for (const auto& sink : sinks_) { SendToSink(*sink, log_entry_queue_.front()); } log_entry_queue_.pop(); } } } void TFLogSinks::Remove(TFLogSink* sink) { assert(sink != nullptr && "The sink must not be a nullptr"); tsl::mutex_lock lock(mutex_); auto it = std::find(sinks_.begin(), sinks_.end(), sink); if (it != sinks_.end()) sinks_.erase(it); } std::vector<TFLogSink*> TFLogSinks::GetSinks() const { tsl::mutex_lock lock(mutex_); return sinks_; } void TFLogSinks::Send(const TFLogEntry& entry) { tsl::mutex_lock lock(mutex_); if (sinks_.empty()) { while (log_entry_queue_.size() >= kMaxLogEntryQueueSize) { log_entry_queue_.pop(); } log_entry_queue_.push(entry); return; } while (!log_entry_queue_.empty()) { for (const auto& sink : sinks_) { SendToSink(*sink, log_entry_queue_.front()); } log_entry_queue_.pop(); } for (const auto& sink : sinks_) { SendToSink(*sink, entry); } } void TFLogSinks::SendToSink(TFLogSink& sink, const TFLogEntry& entry) { sink.Send(entry); sink.WaitTillSent(); } class VlogFileMgr { public: VlogFileMgr(); ~VlogFileMgr(); FILE* FilePtr() const; private: FILE* vlog_file_ptr; char* vlog_file_name; }; VlogFileMgr::VlogFileMgr() { vlog_file_name = getenv("TF_CPP_VLOG_FILENAME"); vlog_file_ptr = vlog_file_name == nullptr ? nullptr : fopen(vlog_file_name, "w"); if (vlog_file_ptr == nullptr) { vlog_file_ptr = stderr; } } VlogFileMgr::~VlogFileMgr() { if (vlog_file_ptr != stderr) { fclose(vlog_file_ptr); } } FILE* VlogFileMgr::FilePtr() const { return vlog_file_ptr; } int ParseInteger(const char* str, size_t size) { string integer_str(str, size); std::istringstream ss(integer_str); int level = 0; ss >> level; return level; } int64_t LogLevelStrToInt(const char* tf_env_var_val) { if (tf_env_var_val == nullptr) { return 0; } return ParseInteger(tf_env_var_val, strlen(tf_env_var_val)); } struct StringData { struct Hasher { size_t operator()(const StringData& sdata) const { size_t hash = 5381; const char* data = sdata.data; for (const char* top = data + sdata.size; data < top; ++data) { hash = ((hash << 5) + hash) + (*data); } return hash; } }; StringData() = default; StringData(const char* data, size_t size) : data(data), size(size) {} bool operator==(const StringData& rhs) const { return size == rhs.size && memcmp(data, rhs.data, size) == 0; } const char* data = nullptr; size_t size = 0; }; using VmoduleMap = std::unordered_map<StringData, int, StringData::Hasher>; VmoduleMap* VmodulesMapFromEnv() { const char* env = getenv("TF_CPP_VMODULE"); if (env == nullptr) { return nullptr; } const char* env_data = strdup(env); VmoduleMap* result = new VmoduleMap(); while (true) { const char* eq = strchr(env_data, '='); if (eq == nullptr) { break; } const char* after_eq = eq + 1; const char* comma = strchr(after_eq, ','); const char* new_env_data; if (comma == nullptr) { comma = strchr(after_eq, '\0'); new_env_data = comma; } else { new_env_data = comma + 1; } (*result)[StringData(env_data, eq - env_data)] =
#include "tsl/platform/logging.h" #include <cerrno> #include <cstddef> #include <cstdio> #include <cstdlib> #include <memory> #include <sstream> #include <vector> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "absl/strings/string_view.h" #include "tsl/platform/path.h" #include "tsl/platform/stacktrace_handler.h" #include "tsl/platform/statusor.h" #include "tsl/platform/test.h" #ifdef PLATFORM_WINDOWS #define popen _popen #define pclose _pclose #endif static char* program_name; namespace tsl { namespace { using ::testing::HasSubstr; using ::testing::Not; TEST(Logging, Log) { LOG(INFO) << "Hello"; LOG(INFO) << "Another log message"; LOG(ERROR) << "Error message"; VLOG(1) << "A VLOG message"; VLOG(2) << "A higher VLOG message"; DVLOG(1) << "A DVLOG message"; DVLOG(2) << "A higher DVLOG message"; } TEST(Logging, CheckChecks) { CHECK(true); CHECK(7 > 5); string a("abc"); string b("xyz"); CHECK_EQ(a, a); CHECK_NE(a, b); CHECK_EQ(3, 3); CHECK_NE(4, 3); CHECK_GT(4, 3); CHECK_GE(3, 3); CHECK_LT(2, 3); CHECK_LE(2, 3); DCHECK(true); DCHECK(7 > 5); DCHECK_EQ(a, a); DCHECK_NE(a, b); DCHECK_EQ(3, 3); DCHECK_NE(4, 3); DCHECK_GT(4, 3); DCHECK_GE(3, 3); DCHECK_LT(2, 3); DCHECK_LE(2, 3); } TEST(LoggingDeathTest, FailedChecks) { string a("abc"); string b("xyz"); const char* p_const = "hello there"; const char* p_null_const = nullptr; char mybuf[10]; char* p_non_const = mybuf; char* p_null = nullptr; CHECK_NOTNULL(p_const); CHECK_NOTNULL(p_non_const); ASSERT_DEATH(CHECK(false), "false"); ASSERT_DEATH(CHECK(9 < 7), "9 < 7"); ASSERT_DEATH(CHECK_EQ(a, b), "a == b"); ASSERT_DEATH(CHECK_EQ(3, 4), "3 == 4"); ASSERT_DEATH(CHECK_NE(3, 3), "3 != 3"); ASSERT_DEATH(CHECK_GT(2, 3), "2 > 3"); ASSERT_DEATH(CHECK_GE(2, 3), "2 >= 3"); ASSERT_DEATH(CHECK_LT(3, 2), "3 < 2"); ASSERT_DEATH(CHECK_LE(3, 2), "3 <= 2"); ASSERT_DEATH(CHECK(false), "false"); ASSERT_DEATH(printf("%s", CHECK_NOTNULL(p_null)), "Must be non NULL"); ASSERT_DEATH(printf("%s", CHECK_NOTNULL(p_null_const)), "Must be non NULL"); #ifndef NDEBUG ASSERT_DEATH(DCHECK(9 < 7), "9 < 7"); ASSERT_DEATH(DCHECK(9 < 7), "9 < 7"); ASSERT_DEATH(DCHECK_EQ(a, b), "a == b"); ASSERT_DEATH(DCHECK_EQ(3, 4), "3 == 4"); ASSERT_DEATH(DCHECK_NE(3, 3), "3 != 3"); ASSERT_DEATH(DCHECK_GT(2, 3), "2 > 3"); ASSERT_DEATH(DCHECK_GE(2, 3), "2 >= 3"); ASSERT_DEATH(DCHECK_LT(3, 2), "3 < 2"); ASSERT_DEATH(DCHECK_LE(3, 2), "3 <= 2"); #endif } TEST(InternalLogString, Basic) { internal::LogString(__FILE__, __LINE__, INFO, "Hello there"); } class TestSink : public TFLogSink { public: void Send(const TFLogEntry& entry) override { ss_ << entry.text_message() << std::endl; } std::string Get() const { return ss_.str(); } private: std::stringstream ss_; }; TEST(LogSinkTest, testLogSinks) { const int sinks_initial_size = TFGetLogSinks().size(); TestSink sink; TFAddLogSink(&sink); EXPECT_EQ(TFGetLogSinks().size(), sinks_initial_size + 1); LOG(INFO) << "Foo"; LOG(INFO) << "Bar"; EXPECT_EQ(sink.Get(), "Foo\nBar\n"); TFRemoveLogSink(&sink); EXPECT_EQ(TFGetLogSinks().size(), sinks_initial_size); } std::string ReadFromFilePointer(FILE* fp) { std::string result; while (!feof(fp)) { char buf[512]; size_t len = fread(buf, sizeof(buf[0]), 512, fp); result.append(buf, len); } return result; } absl::StatusOr<std::string> ReadFromFile(const std::string& filename) { std::shared_ptr<FILE> fp(fopen(filename.c_str(), "r"), fclose); if (fp == nullptr) { return absl::ErrnoToStatus(errno, absl::StrFormat("Cannot fopen '%s'", filename)); } return ReadFromFilePointer(fp.get()); } class SubcommandTest : public ::testing::Test { public: static constexpr absl::string_view kLogVLog = "log_and_vlog"; static bool IsSubcommand(absl::string_view subcommand) { return subcommand == kLogVLog; } static int Run(absl::string_view subcommand) { CHECK_EQ(subcommand, kLogVLog); LOG(INFO) << "LOG INFO"; LOG(WARNING) << "LOG WARNING"; LOG(ERROR) << "LOG ERROR"; LOG(INFO) << absl::StrFormat("VLOG_IS_ON(1)? %d", VLOG_IS_ON(1)); LOG(INFO) << absl::StrFormat("VLOG_IS_ON(2)? %d", VLOG_IS_ON(2)); LOG(INFO) << absl::StrFormat("VLOG_IS_ON(3)? %d", VLOG_IS_ON(3)); VLOG(1) << "VLevel 1"; VLOG(2) << "VLevel 2"; VLOG(3) << "VLevel 3"; return EXIT_SUCCESS; } protected: absl::StatusOr<std::string> CaptureOutput(const char* invocation) { std::shared_ptr<FILE> fp(popen(invocation, "r"), pclose); if (fp == nullptr) { return absl::ErrnoToStatus( errno, absl::StrFormat("Cannot popen '%s'", invocation)); } return ReadFromFilePointer(fp.get()); } }; TEST_F(SubcommandTest, LogDefaultTest) { std::string command = absl::StrFormat("%s %s", program_name, kLogVLog); #if defined(PLATFORM_GOOGLE) command += " --alsologtostderr"; #endif command += " 2>&1"; TF_ASSERT_OK_AND_ASSIGN(std::string out, CaptureOutput(command.c_str())); EXPECT_THAT(out, HasSubstr("LOG INFO")); EXPECT_THAT(out, HasSubstr("LOG WARNING")); EXPECT_THAT(out, HasSubstr("LOG ERROR")); EXPECT_THAT(out, HasSubstr("VLOG_IS_ON(1)? 0")); EXPECT_THAT(out, HasSubstr("VLOG_IS_ON(2)? 0")); EXPECT_THAT(out, HasSubstr("VLOG_IS_ON(3)? 0")); } TEST_F(SubcommandTest, MinLogLevelTest) { std::string command = absl::StrFormat("%s %s", program_name, kLogVLog); #if defined(PLATFORM_GOOGLE) command += " --minloglevel=1 --alsologtostderr"; #elif defined(PLATFORM_WINDOWS) command = absl::StrFormat("set TF_CPP_MIN_LOG_LEVEL=1 && %s", command); #else command = absl::StrFormat("TF_CPP_MIN_LOG_LEVEL=1 %s", command); #endif command += " 2>&1"; TF_ASSERT_OK_AND_ASSIGN(std::string out, CaptureOutput(command.c_str())); EXPECT_THAT(out, Not(HasSubstr("LOG INFO"))); EXPECT_THAT(out, HasSubstr("LOG WARNING")); EXPECT_THAT(out, HasSubstr("LOG ERROR")); } TEST_F(SubcommandTest, VLogDefaultTest) { std::string command = absl::StrFormat("%s %s", program_name, kLogVLog); #if defined(PLATFORM_GOOGLE) command += " --alsologtostderr"; #endif command += " 2>&1"; TF_ASSERT_OK_AND_ASSIGN(std::string out, CaptureOutput(command.c_str())); EXPECT_THAT(out, Not(HasSubstr("VLevel 1"))); EXPECT_THAT(out, Not(HasSubstr("VLevel 2"))); EXPECT_THAT(out, Not(HasSubstr("VLevel 3"))); } TEST_F(SubcommandTest, MaxVLogLevelTest) { std::string command = absl::StrFormat("%s %s", program_name, kLogVLog); #if defined(PLATFORM_GOOGLE) command += " --v=2 --alsologtostderr"; #elif defined(PLATFORM_WINDOWS) command = absl::StrFormat("set TF_CPP_MAX_VLOG_LEVEL=2 && %s", command); #else command = absl::StrFormat("TF_CPP_MAX_VLOG_LEVEL=2 %s", command); #endif command += " 2>&1"; TF_ASSERT_OK_AND_ASSIGN(std::string out, CaptureOutput(command.c_str())); EXPECT_THAT(out, HasSubstr("VLevel 1")); EXPECT_THAT(out, HasSubstr("VLevel 2")); EXPECT_THAT(out, Not(HasSubstr("VLevel 3"))); EXPECT_THAT(out, HasSubstr("VLOG_IS_ON(1)? 1")); EXPECT_THAT(out, HasSubstr("VLOG_IS_ON(2)? 1")); EXPECT_THAT(out, HasSubstr("VLOG_IS_ON(3)? 0")); } TEST_F(SubcommandTest, VModuleTest) { std::string command = absl::StrFormat("%s %s", program_name, kLogVLog); #if defined(PLATFORM_GOOGLE) command += " --vmodule=logging_test=2,shoobadooba=3 --alsologtostderr"; #elif defined(PLATFORM_WINDOWS) command = absl::StrFormat( "set TF_CPP_VMODULE=logging_test=2,shoobadooba=3 && %s", command); #else command = absl::StrFormat("TF_CPP_VMODULE=logging_test=2,shoobadooba=3 %s", command); #endif command += " 2>&1"; TF_ASSERT_OK_AND_ASSIGN(std::string out, CaptureOutput(command.c_str())); EXPECT_THAT(out, HasSubstr("VLevel 1")); EXPECT_THAT(out, HasSubstr("VLevel 2")); EXPECT_THAT(out, Not(HasSubstr("VLevel 3"))); EXPECT_THAT(out, HasSubstr("VLOG_IS_ON(1)? 1")); EXPECT_THAT(out, HasSubstr("VLOG_IS_ON(2)? 1")); EXPECT_THAT(out, HasSubstr("VLOG_IS_ON(3)? 0")); } TEST_F(SubcommandTest, VLogFilenameTest) { #if defined(PLATFORM_GOOGLE) constexpr bool kVLogFilenameEnvVarIsSupported = false; #else constexpr bool kVLogFilenameEnvVarIsSupported = true; #endif if (!kVLogFilenameEnvVarIsSupported) { GTEST_SKIP() << "Not supported on this platform"; } std::string command = absl::StrFormat("%s %s", program_name, kLogVLog); std::string filename = io::GetTempFilename("logging_test"); #if defined(PLATFORM_WINDOWS) command = absl::StrFormat( "set TF_CPP_VLOG_FILENAME=%s && set TF_CPP_MAX_VLOG_LEVEL=1 && %s", filename, command); #else command = absl::StrFormat( "TF_CPP_VLOG_FILENAME=%s TF_CPP_MAX_VLOG_LEVEL=1 %s", filename, command); #endif command += " 2>&1"; TF_ASSERT_OK_AND_ASSIGN(std::string out, CaptureOutput(command.c_str())); EXPECT_THAT(out, Not(HasSubstr("LOG INFO"))); EXPECT_THAT(out, Not(HasSubstr("LOG WARNING"))); EXPECT_THAT(out, Not(HasSubstr("LOG ERROR"))); EXPECT_THAT(out, Not(HasSubstr("VLOG_IS_ON(1)?"))); EXPECT_THAT(out, Not(HasSubstr("VLOG_IS_ON(2)?"))); EXPECT_THAT(out, Not(HasSubstr("VLOG_IS_ON(3)?"))); EXPECT_THAT(out, Not(HasSubstr("VLevel 1"))); EXPECT_THAT(out, Not(HasSubstr("VLevel 2"))); EXPECT_THAT(out, Not(HasSubstr("VLevel 3"))); TF_ASSERT_OK_AND_ASSIGN(std::string log_file, ReadFromFile(filename)); EXPECT_THAT(log_file, HasSubstr("LOG INFO")); EXPECT_THAT(log_file, HasSubstr("LOG WARNING")); EXPECT_THAT(log_file, HasSubstr("LOG ERROR")); EXPECT_THAT(log_file, HasSubstr("VLOG_IS_ON(1)")); EXPECT_THAT(log_file, HasSubstr("VLOG_IS_ON(2)")); EXPECT_THAT(log_file, HasSubstr("VLOG_IS_ON(3)")); EXPECT_THAT(log_file, HasSubstr("VLevel 1")); EXPECT_THAT(log_file, Not(HasSubstr("VLevel 2"))); EXPECT_THAT(log_file, Not(HasSubstr("VLevel 3"))); } } } GTEST_API_ int main(int argc, char** argv) { tsl::testing::InstallStacktraceHandler(); testing::InitGoogleTest(&argc, argv); program_name = argv[0]; if (argc >= 2 && tsl::SubcommandTest::IsSubcommand(argv[1])) { return tsl::SubcommandTest::Run(argv[1]); } return RUN_ALL_TESTS(); }
2,621
cpp
google/tsl
unbounded_work_queue
tsl/platform/default/unbounded_work_queue.cc
tsl/platform/unbounded_work_queue_test.cc
#ifndef TENSORFLOW_TSL_PLATFORM_DEFAULT_UNBOUNDED_WORK_QUEUE_H_ #define TENSORFLOW_TSL_PLATFORM_DEFAULT_UNBOUNDED_WORK_QUEUE_H_ #include <deque> #include <memory> #include <vector> #include "tsl/platform/env.h" #include "tsl/platform/mutex.h" #include "tsl/platform/notification.h" namespace tsl { class UnboundedWorkQueue { public: UnboundedWorkQueue(Env* env, const string& thread_name, const ThreadOptions& thread_options = {}); ~UnboundedWorkQueue(); using WorkFunction = std::function<void()>; void Schedule(WorkFunction fn); private: void PooledThreadFunc(); Env* const env_; const string thread_name_; const ThreadOptions thread_options_; mutex work_queue_mu_; condition_variable work_queue_cv_ TF_GUARDED_BY(work_queue_mu_); size_t num_idle_threads_ TF_GUARDED_BY(work_queue_mu_) = 0; bool cancelled_ TF_GUARDED_BY(work_queue_mu_) = false; std::deque<WorkFunction> work_queue_ TF_GUARDED_BY(work_queue_mu_); mutex thread_pool_mu_; std::vector<std::unique_ptr<Thread>> thread_pool_ TF_GUARDED_BY(thread_pool_mu_); }; } #endif #include "tsl/platform/default/unbounded_work_queue.h" #include "absl/memory/memory.h" #include "tsl/platform/env.h" #include "tsl/platform/mutex.h" #include "tsl/platform/numa.h" namespace tsl { UnboundedWorkQueue::UnboundedWorkQueue(Env* env, const string& thread_name, const ThreadOptions& thread_options) : env_(env), thread_name_(thread_name), thread_options_(thread_options) {} UnboundedWorkQueue::~UnboundedWorkQueue() { { mutex_lock l(work_queue_mu_); cancelled_ = true; work_queue_cv_.notify_all(); if (!work_queue_.empty()) { LOG(ERROR) << "UnboundedWorkQueue named \"" << thread_name_ << "\" was " << "deleted with pending work in its queue. This may indicate " << "a potential use-after-free bug."; } } { mutex_lock l(thread_pool_mu_); thread_pool_.clear(); } } void UnboundedWorkQueue::Schedule(WorkFunction fn) { mutex_lock l(work_queue_mu_); work_queue_.push_back(std::move(fn)); work_queue_cv_.notify_one(); if (work_queue_.size() > num_idle_threads_) { Thread* new_thread = env_->StartThread({}, thread_name_, [this]() { PooledThreadFunc(); }); mutex_lock l(thread_pool_mu_); thread_pool_.emplace_back(new_thread); } } void UnboundedWorkQueue::PooledThreadFunc() { if (thread_options_.numa_node != tsl::port::kNUMANoAffinity) { tsl::port::NUMASetThreadNodeAffinity(thread_options_.numa_node); } while (true) { WorkFunction fn; { mutex_lock l(work_queue_mu_); ++num_idle_threads_; while (!cancelled_ && work_queue_.empty()) { work_queue_cv_.wait(l); } if (cancelled_) { return; } fn = std::move(work_queue_.front()); work_queue_.pop_front(); --num_idle_threads_; } fn(); } } }
#include "tsl/platform/unbounded_work_queue.h" #include "absl/memory/memory.h" #include "tsl/platform/random.h" #include "tsl/platform/blocking_counter.h" #include "tsl/platform/env.h" #include "tsl/platform/test.h" namespace tsl { namespace { class UnboundedWorkQueueTest : public ::testing::Test { protected: UnboundedWorkQueueTest() : work_queue_( absl::make_unique<UnboundedWorkQueue>(Env::Default(), "test")) {} ~UnboundedWorkQueueTest() override = default; void RunMultipleCopiesOfClosure(const int num_closures, std::function<void()> fn) { for (int i = 0; i < num_closures; ++i) { work_queue_->Schedule([this, fn]() { fn(); mutex_lock l(mu_); ++closure_count_; cond_var_.notify_all(); }); } } void BlockUntilClosuresDone(const int num_closures) { mutex_lock l(mu_); while (closure_count_ < num_closures) { cond_var_.wait(l); } } void ResetQueue() { work_queue_.reset(); } int NumClosuresExecuted() { mutex_lock l(mu_); return closure_count_; } private: mutex mu_; int closure_count_ TF_GUARDED_BY(mu_) = 0; condition_variable cond_var_; std::unique_ptr<UnboundedWorkQueue> work_queue_; }; TEST_F(UnboundedWorkQueueTest, SingleClosure) { constexpr int num_closures = 1; RunMultipleCopiesOfClosure(num_closures, []() {}); BlockUntilClosuresDone(num_closures); } TEST_F(UnboundedWorkQueueTest, MultipleClosures) { constexpr int num_closures = 10; RunMultipleCopiesOfClosure(num_closures, []() {}); BlockUntilClosuresDone(num_closures); } TEST_F(UnboundedWorkQueueTest, MultipleClosuresSleepingRandomly) { constexpr int num_closures = 1000; RunMultipleCopiesOfClosure(num_closures, []() { Env::Default()->SleepForMicroseconds(random::New64() % 10); }); BlockUntilClosuresDone(num_closures); } TEST_F(UnboundedWorkQueueTest, NestedClosures) { constexpr int num_closures = 10; RunMultipleCopiesOfClosure(num_closures, [=]() { RunMultipleCopiesOfClosure(num_closures, []() {}); }); BlockUntilClosuresDone(num_closures * num_closures + num_closures); } TEST_F(UnboundedWorkQueueTest, RacyDestructor) { constexpr int num_closures = 100; RunMultipleCopiesOfClosure(num_closures, []() {}); ResetQueue(); EXPECT_LE(NumClosuresExecuted(), num_closures); } } }
2,622
cpp
google/tsl
mutex
tsl/platform/default/mutex.cc
tsl/platform/mutex_test.cc
#ifndef TENSORFLOW_TSL_PLATFORM_DEFAULT_MUTEX_H_ #define TENSORFLOW_TSL_PLATFORM_DEFAULT_MUTEX_H_ namespace tsl { namespace internal { std::cv_status wait_until_system_clock( CVData *cv_data, MuData *mu_data, const std::chrono::system_clock::time_point timeout_time); } template <class Rep, class Period> std::cv_status condition_variable::wait_for( mutex_lock &lock, std::chrono::duration<Rep, Period> dur) { return tsl::internal::wait_until_system_clock( &this->cv_, &lock.mutex()->mu_, std::chrono::system_clock::now() + dur); } } #endif #include "tsl/platform/mutex.h" #include <time.h> #include "nsync_cv.h" #include "nsync_mu.h" #include "nsync_mu_wait.h" #include "nsync_time.h" namespace tsl { static_assert(sizeof(nsync::nsync_mu) <= sizeof(internal::MuData), "tsl::internal::MuData needs to be bigger"); static inline nsync::nsync_mu *mu_cast(internal::MuData *mu) { return reinterpret_cast<nsync::nsync_mu *>(mu); } static inline const nsync::nsync_mu *mu_cast(const internal::MuData *mu) { return reinterpret_cast<const nsync::nsync_mu *>(mu); } mutex::mutex() { nsync::nsync_mu_init(mu_cast(&mu_)); } void mutex::lock() { nsync::nsync_mu_lock(mu_cast(&mu_)); } bool mutex::try_lock() { return nsync::nsync_mu_trylock(mu_cast(&mu_)) != 0; }; void mutex::unlock() { nsync::nsync_mu_unlock(mu_cast(&mu_)); } void mutex::assert_held() const TF_ASSERT_EXCLUSIVE_LOCK() { nsync::nsync_mu_assert_held(mu_cast(&mu_)); } void mutex::lock_shared() { nsync::nsync_mu_rlock(mu_cast(&mu_)); } bool mutex::try_lock_shared() { return nsync::nsync_mu_rtrylock(mu_cast(&mu_)) != 0; }; void mutex::unlock_shared() { nsync::nsync_mu_runlock(mu_cast(&mu_)); } void mutex::assert_held_shared() const TF_ASSERT_SHARED_LOCK() { nsync::nsync_mu_rassert_held(mu_cast(&mu_)); } static int EvaluateCondition(const void *vcond) { return static_cast<int>(static_cast<const Condition *>(vcond)->Eval()); } void mutex::Await(const Condition &cond) { nsync::nsync_mu_wait(mu_cast(&mu_), &EvaluateCondition, &cond, nullptr); } bool mutex::AwaitWithDeadline(const Condition &cond, uint64 abs_deadline_ns) { time_t seconds = abs_deadline_ns / (1000 * 1000 * 1000); nsync::nsync_time abs_time = nsync::nsync_time_s_ns( seconds, abs_deadline_ns - seconds * (1000 * 1000 * 1000)); return nsync::nsync_mu_wait_with_deadline(mu_cast(&mu_), &EvaluateCondition, &cond, nullptr, abs_time, nullptr) == 0; } static_assert(sizeof(nsync::nsync_cv) <= sizeof(internal::CVData), "tsl::internal::CVData needs to be bigger"); static inline nsync::nsync_cv *cv_cast(internal::CVData *cv) { return reinterpret_cast<nsync::nsync_cv *>(cv); } condition_variable::condition_variable() { nsync::nsync_cv_init(cv_cast(&cv_)); } void condition_variable::wait(mutex_lock &lock) { nsync::nsync_cv_wait(cv_cast(&cv_), mu_cast(&lock.mutex()->mu_)); } void condition_variable::notify_one() { nsync::nsync_cv_signal(cv_cast(&cv_)); } void condition_variable::notify_all() { nsync::nsync_cv_broadcast(cv_cast(&cv_)); } namespace internal { std::cv_status wait_until_system_clock( CVData *cv_data, MuData *mu_data, const std::chrono::system_clock::time_point timeout_time) { int r = nsync::nsync_cv_wait_with_deadline(cv_cast(cv_data), mu_cast(mu_data), timeout_time, nullptr); return r ? std::cv_status::timeout : std::cv_status::no_timeout; } } }
#include "tsl/platform/mutex.h" #include "tsl/platform/test.h" #include "tsl/platform/threadpool.h" namespace tsl { namespace { class MutexTest : public ::testing::Test { protected: mutex_lock GetLock() TF_NO_THREAD_SAFETY_ANALYSIS { return mutex_lock{mu_}; } tf_shared_lock GetSharedLock() TF_NO_THREAD_SAFETY_ANALYSIS { return tf_shared_lock{mu_}; } bool test_try_lock() { bool test = mu_.try_lock(); if (test) mu_.unlock(); return test; } bool test_try_lock_shared() { bool test = mu_.try_lock_shared(); if (test) mu_.unlock_shared(); return test; } mutex mu_; }; TEST_F(MutexTest, MovableMutexLockTest) { EXPECT_TRUE(test_try_lock()); { mutex_lock lock = GetLock(); EXPECT_FALSE(test_try_lock()); EXPECT_FALSE(test_try_lock_shared()); } EXPECT_TRUE(test_try_lock()); } TEST_F(MutexTest, SharedMutexLockTest) { EXPECT_TRUE(test_try_lock()); { tf_shared_lock lock = GetSharedLock(); EXPECT_FALSE(test_try_lock()); EXPECT_TRUE(test_try_lock_shared()); } EXPECT_TRUE(test_try_lock()); } TEST(ConditionVariableTest, WaitWithPredicate) { constexpr int kNumThreads = 4; mutex mu; condition_variable cv; bool ready = false; int count = 0; tsl::thread::ThreadPool pool(Env::Default(), "condition_variable_test_wait_with_predicate", kNumThreads); for (int i = 0; i < kNumThreads; ++i) { pool.Schedule([&mu, &cv, &ready, &count]() { mutex_lock lock(mu); cv.wait(lock, [&ready] { return ready; }); ++count; cv.notify_one(); }); } { mutex_lock lock(mu); EXPECT_EQ(count, 0); } { mutex_lock lock(mu); ready = true; cv.notify_all(); } { mutex_lock lock(mu); cv.wait(lock, [&count, kNumThreads] { return count == kNumThreads; }); EXPECT_EQ(count, kNumThreads); } } TEST(ConditionVariableTest, WaitWithTruePredicateDoesntBlock) { mutex mu; mutex_lock lock(mu); condition_variable cv; cv.wait(lock, [] { return true; }); EXPECT_TRUE(static_cast<bool>(lock)); } } }
2,623
cpp
google/tsl
parse_annotation
tsl/profiler/utils/parse_annotation.cc
tsl/profiler/utils/parse_annotation_test.cc
#ifndef TENSORFLOW_TSL_PROFILER_UTILS_PARSE_ANNOTATION_H_ #define TENSORFLOW_TSL_PROFILER_UTILS_PARSE_ANNOTATION_H_ #include <vector> #include "absl/strings/string_view.h" namespace tsl { namespace profiler { struct Annotation { absl::string_view name; struct Metadata { absl::string_view key; absl::string_view value; }; std::vector<Metadata> metadata; }; Annotation ParseAnnotation(absl::string_view annotation); inline bool HasMetadata(absl::string_view annotation) { constexpr char kUserMetadataMarker = '#'; return !annotation.empty() && annotation.back() == kUserMetadataMarker; } std::vector<Annotation> ParseAnnotationStack( absl::string_view annotation_stack); } } #endif #include "tsl/profiler/utils/parse_annotation.h" #include <stack> #include <string> #include <utility> #include <vector> #include "absl/strings/ascii.h" #include "absl/strings/str_split.h" #include "absl/strings/string_view.h" namespace tsl { namespace profiler { namespace { std::vector<absl::string_view> SplitNameAndMetadata( absl::string_view annotation) { std::vector<absl::string_view> parts; if (!HasMetadata(annotation)) { parts.emplace_back(annotation); } else { annotation.remove_suffix(1); parts = absl::StrSplit(annotation, '#'); if (parts.size() > 2) { parts.resize(2); } } while (parts.size() < 2) { parts.emplace_back(); } return parts; } std::vector<absl::string_view> SplitPairs(absl::string_view metadata) { std::vector<absl::string_view> key_value_pairs; std::stack<char> quotes; size_t start = 0, end = 0; for (; end < metadata.size(); ++end) { char ch = metadata[end]; switch (ch) { case '\"': case '\'': if (quotes.empty() || quotes.top() != ch) { quotes.push(ch); } else { quotes.pop(); } break; case '{': case '(': case '[': quotes.push(ch); break; case '}': if (!quotes.empty() && quotes.top() == '{') { quotes.pop(); } break; case ')': if (!quotes.empty() && quotes.top() == '(') { quotes.pop(); } break; case ']': if (!quotes.empty() && quotes.top() == '[') { quotes.pop(); } break; case ',': if (quotes.empty()) { if (end - start > 1) { key_value_pairs.emplace_back(metadata.data() + start, end - start); } start = end + 1; } break; } } if (end - start > 1) { key_value_pairs.emplace_back(metadata.data() + start, end - start); } return key_value_pairs; } std::vector<std::pair<absl::string_view, absl::string_view>> ParseMetadata( absl::string_view metadata) { std::vector<std::pair<absl::string_view, absl::string_view>> key_values; for (absl::string_view pair : SplitPairs(metadata)) { std::vector<absl::string_view> parts = absl::StrSplit(pair, absl::MaxSplits('=', 1)); if (parts.size() == 2) { absl::string_view key = absl::StripAsciiWhitespace(parts[0]); absl::string_view value = absl::StripAsciiWhitespace(parts[1]); if (!key.empty() && !value.empty()) { key_values.push_back({key, value}); } } } return key_values; } } Annotation ParseAnnotation(absl::string_view annotation) { Annotation result; std::vector<absl::string_view> parts = SplitNameAndMetadata(annotation); if (!parts.empty()) { result.name = absl::StripAsciiWhitespace(parts[0]); for (const auto& key_value : ParseMetadata(parts[1])) { result.metadata.push_back({key_value.first, key_value.second}); } } return result; } std::vector<Annotation> ParseAnnotationStack( absl::string_view annotation_stack) { std::vector<Annotation> annotations; const std::string kAnnotationDelimiter = "::"; for (absl::string_view annotation : absl::StrSplit( annotation_stack, kAnnotationDelimiter, absl::SkipEmpty())) { annotations.emplace_back(ParseAnnotation(annotation)); } return annotations; } } }
#include "tsl/profiler/utils/parse_annotation.h" #include <vector> #include "absl/strings/string_view.h" #include "tsl/platform/test.h" namespace tsl { namespace profiler { namespace { TEST(ParseAnnotationStackTest, EmptyAnnotationStackTest) { std::vector<Annotation> annotations = ParseAnnotationStack(""); ASSERT_TRUE(annotations.empty()); } TEST(ParseAnnotationStackTest, SingleAnnotationStackTest) { std::vector<Annotation> annotations = ParseAnnotationStack("name"); ASSERT_FALSE(annotations.empty()); EXPECT_EQ(annotations.back().name, "name"); EXPECT_TRUE(annotations.back().metadata.empty()); } TEST(ParseAnnotationStackTest, MultiLevelAnnotationStackTest) { std::vector<Annotation> annotations = ParseAnnotationStack("outer::inner"); ASSERT_EQ(annotations.size(), 2); EXPECT_EQ(annotations.front().name, "outer"); EXPECT_TRUE(annotations.front().metadata.empty()); EXPECT_EQ(annotations.back().name, "inner"); EXPECT_TRUE(annotations.back().metadata.empty()); } TEST(ParseAnnotationTest, EmptyAnnotationTest) { Annotation annotation = ParseAnnotation(""); EXPECT_TRUE(annotation.name.empty()); EXPECT_TRUE(annotation.metadata.empty()); } TEST(ParseAnnotationTest, SimpleNameTest) { Annotation annotation = ParseAnnotation("name"); EXPECT_EQ(annotation.name, "name"); EXPECT_TRUE(annotation.metadata.empty()); } TEST(ParseAnnotationTest, SimpleNameWithWhitespaceTest) { Annotation annotation = ParseAnnotation("name "); EXPECT_EQ(annotation.name, "name"); EXPECT_TRUE(annotation.metadata.empty()); } TEST(ParseAnnotationTest, EmptyMetadataTest) { Annotation annotation = ParseAnnotation("name#"); EXPECT_EQ(annotation.name, "name"); EXPECT_TRUE(annotation.metadata.empty()); annotation = ParseAnnotation("name1##"); EXPECT_EQ(annotation.name, "name1"); EXPECT_TRUE(annotation.metadata.empty()); annotation = ParseAnnotation("name2###"); EXPECT_EQ(annotation.name, "name2"); EXPECT_TRUE(annotation.metadata.empty()); } TEST(ParseAnnotationTest, SingleMetadataTest) { Annotation annotation = ParseAnnotation("name#key=value#"); EXPECT_EQ(annotation.name, "name"); ASSERT_EQ(annotation.metadata.size(), 1); EXPECT_EQ(annotation.metadata.at(0).key, "key"); EXPECT_EQ(annotation.metadata.at(0).value, "value"); } TEST(ParseAnnotationTest, MultipleMetadataTest) { Annotation annotation = ParseAnnotation("name#k1=v1,k2=v2,k3=v3#"); EXPECT_EQ(annotation.name, "name"); ASSERT_EQ(annotation.metadata.size(), 3); EXPECT_EQ(annotation.metadata.at(0).key, "k1"); EXPECT_EQ(annotation.metadata.at(0).value, "v1"); EXPECT_EQ(annotation.metadata.at(1).key, "k2"); EXPECT_EQ(annotation.metadata.at(1).value, "v2"); EXPECT_EQ(annotation.metadata.at(2).key, "k3"); EXPECT_EQ(annotation.metadata.at(2).value, "v3"); } TEST(ParseAnnotationTest, MultipleMetadataWithWhitespaceTest) { Annotation annotation = ParseAnnotation("name # k1 = v1, ,k2=v2 #"); EXPECT_EQ(annotation.name, "name"); ASSERT_EQ(annotation.metadata.size(), 2); EXPECT_EQ(annotation.metadata.at(0).key, "k1"); EXPECT_EQ(annotation.metadata.at(0).value, "v1"); EXPECT_EQ(annotation.metadata.at(1).key, "k2"); EXPECT_EQ(annotation.metadata.at(1).value, "v2"); } TEST(ParseAnnotationTest, KeyValueSeparatorTest) { Annotation annotation = ParseAnnotation("name#=v1,k2=,k3==v3,k4=v4=#"); EXPECT_EQ(annotation.name, "name"); ASSERT_EQ(annotation.metadata.size(), 2); EXPECT_EQ(annotation.metadata.at(0).key, "k3"); EXPECT_EQ(annotation.metadata.at(0).value, "=v3"); EXPECT_EQ(annotation.metadata.at(1).key, "k4"); EXPECT_EQ(annotation.metadata.at(1).value, "v4="); } TEST(ParseAnnotationTest, ExtraMetadataSeparatorTest) { Annotation annotation = ParseAnnotation("name##k1=v1#"); EXPECT_EQ(annotation.name, "name"); EXPECT_TRUE(annotation.metadata.empty()); } TEST(ParseAnnotationTest, QuotedMetadata) { Annotation annotation = ParseAnnotation( "name#k1=(v11,v12),k2=[v21,v22,v23],k3={v31,v32}, k4=\"v41,v42\"," "(k51,k52)='v51,v52'#"); EXPECT_EQ(annotation.metadata.at(0).key, "k1"); EXPECT_EQ(annotation.metadata.at(0).value, "(v11,v12)"); EXPECT_EQ(annotation.metadata.at(1).key, "k2"); EXPECT_EQ(annotation.metadata.at(1).value, "[v21,v22,v23]"); EXPECT_EQ(annotation.metadata.at(2).key, "k3"); EXPECT_EQ(annotation.metadata.at(2).value, "{v31,v32}"); EXPECT_EQ(annotation.metadata.at(3).key, "k4"); EXPECT_EQ(annotation.metadata.at(3).value, "\"v41,v42\""); EXPECT_EQ(annotation.metadata.at(4).key, "(k51,k52)"); EXPECT_EQ(annotation.metadata.at(4).value, "'v51,v52'"); } TEST(ParseAnnotationTest, UnmatchedQuotedMetadata) { Annotation annotation = ParseAnnotation("name#k1=v1,k2=(v2,k3=v3#"); EXPECT_EQ(annotation.metadata.at(0).key, "k1"); EXPECT_EQ(annotation.metadata.at(0).value, "v1"); EXPECT_EQ(annotation.metadata.at(1).key, "k2"); EXPECT_EQ(annotation.metadata.at(1).value, "(v2,k3=v3"); } } } }
2,624
cpp
google/tsl
xplane_utils
tsl/profiler/utils/xplane_utils.cc
tsl/profiler/utils/xplane_utils_test.cc
#ifndef TENSORFLOW_TSL_PROFILER_UTILS_XPLANE_UTILS_H_ #define TENSORFLOW_TSL_PROFILER_UTILS_XPLANE_UTILS_H_ #include <algorithm> #include <cstdint> #include <optional> #include <vector> #include "absl/algorithm/container.h" #include "absl/container/flat_hash_map.h" #include "absl/container/flat_hash_set.h" #include "absl/strings/string_view.h" #include "tsl/platform/types.h" #include "tsl/profiler/protobuf/xplane.pb.h" #include "tsl/profiler/utils/timespan.h" #include "tsl/profiler/utils/trace_utils.h" #include "tsl/profiler/utils/xplane_visitor.h" namespace tsl { namespace profiler { inline Timespan XEventTimespan(const XEvent& event) { return Timespan(event.offset_ps(), event.duration_ps()); } template <typename F> std::vector<const XPlane*> FindPlanes(const XSpace& space, const F& predicate) { std::vector<const XPlane*> result; for (const XPlane& plane : space.planes()) { if (predicate(plane)) { result.push_back(&plane); } } return result; } template <typename F> std::vector<XPlane*> FindMutablePlanes(XSpace* space, const F& predicate) { std::vector<XPlane*> result; for (XPlane& plane : *space->mutable_planes()) { if (predicate(plane)) { result.push_back(&plane); } } return result; } const XPlane* FindPlaneWithName(const XSpace& space, absl::string_view name); XPlane* FindMutablePlaneWithName(XSpace* space, absl::string_view name); std::vector<const XPlane*> FindPlanesWithNames( const XSpace& space, const std::vector<absl::string_view>& names); XPlane* FindOrAddMutablePlaneWithName(XSpace* space, absl::string_view name); std::vector<const XPlane*> FindPlanesWithPrefix(const XSpace& space, absl::string_view prefix); std::vector<XPlane*> FindMutablePlanesWithPrefix(XSpace* space, absl::string_view prefix); const XLine* FindLineWithId(const XPlane& plane, int64_t id); std::vector<const XLine*> FindLinesWithId(const XPlane& plane, int64_t id); const XLine* FindLineWithName(const XPlane& plane, absl::string_view name); XStat* FindOrAddMutableStat(const XStatMetadata& stat_metadata, XEvent* event); void RemovePlane(XSpace* space, const XPlane* plane); void RemovePlanes(XSpace* space, const std::vector<const XPlane*>& planes); void RemoveLine(XPlane* plane, const XLine* line); void RemoveEvents(XLine* line, const absl::flat_hash_set<const XEvent*>& events); void RemoveEmptyPlanes(XSpace* space); void RemoveEmptyLines(XPlane* plane); template <class Compare> void SortXLinesBy(XPlane* plane, Compare comp) { std::sort(plane->mutable_lines()->pointer_begin(), plane->mutable_lines()->pointer_end(), comp); } class XLinesComparatorByName { public: bool operator()(const XLine* a, const XLine* b) const { auto& line_a = a->display_name().empty() ? a->name() : a->display_name(); auto& line_b = b->display_name().empty() ? b->name() : b->display_name(); return line_a < line_b; } }; void SortXPlane(XPlane* plane); void SortXSpace(XSpace* space); struct XEventsComparator { bool operator()(const XEvent* a, const XEvent* b) const; }; template <typename Event, typename Plane> inline std::vector<Event> GetSortedEvents(Plane& plane, bool include_derived_events = false) { std::vector<Event> events; plane.ForEachLine([&events, include_derived_events](auto line) { if (!include_derived_events && IsDerivedThreadId(line.Id())) return; line.ForEachEvent( [&events](auto event) { events.emplace_back(std::move(event)); }); }); absl::c_sort(events); return events; } void NormalizeTimestamps(XPlane* plane, uint64 start_time_ns); void NormalizeTimestamps(XSpace* space, uint64 start_time_ns); void MergePlanes(const XPlane& src_plane, XPlane* dst_plane); void MergePlanes(const std::vector<const XPlane*>& src_planes, XPlane* dst_plane); int64_t GetStartTimestampNs(const XPlane& plane); bool IsEmpty(const XSpace& space); bool IsXSpaceGrouped(const XSpace& space); void AddFlowsToXplane(int32_t host_id, bool is_host_plane, bool connect_traceme, XPlane* plane); uint64_t GetDevicePlaneFingerprint(const XPlane& plane); template <typename XPlanePointerIterator> void SortPlanesById(XPlanePointerIterator begin, XPlanePointerIterator end) { std::sort(begin, end, [&](const XPlane* a, const XPlane* b) { return a->id() < b->id(); }); } class XEventContextTracker { public: XEventContextTracker(const XPlaneVisitor* plane, const XLine* line) : plane_(plane), line_(line) {} std::optional<XEventVisitor> GetContainingEvent(const Timespan& event); std::optional<XEventVisitor> GetOverlappingEvent(const Timespan& event); private: const XPlaneVisitor* plane_; const XLine* line_; int64_t current_index_ = -1; }; void AggregateXPlane(const XPlane& full_trace, XPlane& aggregated_trace); bool IsCustomPlane(const XPlane& plane); bool IsHostPlane(const XPlane& plane); bool IsDevicePlane(const XPlane& plane); } } #endif #include "tsl/profiler/utils/xplane_utils.h" #include <algorithm> #include <cstdint> #include <limits> #include <optional> #include <set> #include <string> #include <utility> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/container/flat_hash_set.h" #include "absl/log/log.h" #include "absl/strings/match.h" #include "absl/strings/string_view.h" #include "xla/tsl/util/stats_calculator.h" #include "tsl/platform/fingerprint.h" #include "tsl/platform/types.h" #include "tsl/profiler/lib/context_types.h" #include "tsl/profiler/protobuf/xplane.pb.h" #include "tsl/profiler/utils/math_utils.h" #include "tsl/profiler/utils/tf_xplane_visitor.h" #include "tsl/profiler/utils/timespan.h" #include "tsl/profiler/utils/xplane_builder.h" #include "tsl/profiler/utils/xplane_schema.h" #include "tsl/profiler/utils/xplane_visitor.h" namespace tsl { namespace profiler { namespace { template <typename T, typename Pred> std::vector<int> FindAll(const protobuf::RepeatedPtrField<T>& array, const Pred& pred) { std::vector<int> indices; for (int i = 0; i < array.size(); ++i) { if (pred(&array.Get(i))) indices.push_back(i); } return indices; } template <typename T, typename Pred> int Find(const protobuf::RepeatedPtrField<T>& array, const Pred& pred) { std::vector<int> indices = FindAll(array, pred); if (indices.size() > 1) { LOG(WARNING) << "Found multiple " << T().GetTypeName() << " when only one was expected."; } return indices.empty() ? -1 : indices.front(); } template <typename T> void RemoveAt(protobuf::RepeatedPtrField<T>* array, const std::vector<int>& indices) { if (indices.empty()) return; if (array->size() == indices.size()) { array->Clear(); return; } auto remove_iter = indices.begin(); int i = *(remove_iter++); for (int j = i + 1; j < array->size(); ++j) { if (remove_iter != indices.end() && *remove_iter == j) { ++remove_iter; } else { array->SwapElements(j, i++); } } array->DeleteSubrange(i, array->size() - i); } template <typename T> void Remove(protobuf::RepeatedPtrField<T>* array, const T* elem) { int i = Find(*array, [elem](const T* e) { return elem == e; }); RemoveAt(array, {i}); } template <typename T, typename Pred> void RemoveIf(protobuf::RepeatedPtrField<T>* array, Pred&& pred) { std::vector<int> indices = FindAll(*array, pred); RemoveAt(array, indices); } void CopyEventMetadata(const XEventMetadata& src_event_metadata, const XPlaneVisitor& src_plane, XEventMetadata& dst_event_metadata, XPlaneBuilder& dst_plane) { if (dst_event_metadata.display_name().empty() && !src_event_metadata.display_name().empty()) { dst_event_metadata.set_display_name(src_event_metadata.display_name()); } if (dst_event_metadata.name().empty() && !src_event_metadata.name().empty()) { dst_event_metadata.set_name(src_event_metadata.name()); } if (dst_event_metadata.metadata().empty() && !src_event_metadata.metadata().empty()) { dst_event_metadata.set_metadata(src_event_metadata.metadata()); } if (dst_event_metadata.stats().empty() && !src_event_metadata.stats().empty()) { XEventMetadataVisitor src_event_metadata_visitor(&src_plane, &src_event_metadata); src_event_metadata_visitor.ForEachStat([&](const XStatVisitor& src_stat) { XStatMetadata& metadata = *dst_plane.GetOrCreateStatMetadata(src_stat.Name()); XStat& dst_stat = *dst_event_metadata.add_stats(); dst_stat = src_stat.RawStat(); if (src_stat.ValueCase() == XStat::kRefValue) { XStatMetadata& value_metadata = *dst_plane.GetOrCreateStatMetadata(src_stat.StrOrRefValue()); dst_stat.set_ref_value(value_metadata.id()); } dst_stat.set_metadata_id(metadata.id()); }); } DCHECK_EQ(src_event_metadata.stats_size(), dst_event_metadata.stats_size()); } void CopyEvent(const XEventVisitor& src_event, const XPlaneVisitor& src, const XPlane& src_plane, int64_t time_offset_ps, XPlaneBuilder& dst_plane, XLineBuilder& dst_line) { XEventMetadata* dst_event_metadata = dst_plane.GetOrCreateEventMetadata(src_event.Name()); CopyEventMetadata(*src_event.metadata(), src, *dst_event_metadata, dst_plane); XEventBuilder dst_event = dst_line.AddEvent(*dst_event_metadata); if (src_event.IsAggregatedEvent()) { dst_event.SetNumOccurrences(src_event.NumOccurrences()); } else { dst_event.SetOffsetPs(src_event.OffsetPs() + time_offset_ps); } dst_event.SetDurationPs(src_event.DurationPs()); src_event.ForEachStat([&](const XStatVisitor& stat) { dst_event.AddStat(*dst_plane.GetOrCreateStatMetadata(stat.Name()), stat.RawStat(), src_plane); }); } bool IsOpLineName(absl::string_view line_name) { return line_name == kXlaOpLineName || line_name == kTensorFlowOpLineName; } } const XPlane* FindPlaneWithName(const XSpace& space, absl::string_view name) { int i = Find(space.planes(), [name](const XPlane* plane) { return plane->name() == name; }); return (i != -1) ? &space.planes(i) : nullptr; } std::vector<const XPlane*> FindPlanesWithNames( const XSpace& space, const std::vector<absl::string_view>& names) { absl::flat_hash_set<absl::string_view> names_set(names.begin(), names.end()); std::vector<int> indices = FindAll(space.planes(), [&names_set](const XPlane* plane) { return names_set.contains(plane->name()); }); std::vector<const XPlane*> planes; planes.reserve(indices.size()); for (int i : indices) { planes.push_back(&space.planes(i)); } return planes; } XPlane* FindMutablePlaneWithName(XSpace* space, absl::string_view name) { int i = Find(space->planes(), [name](const XPlane* plane) { return plane->name() == name; }); return (i != -1) ? space->mutable_planes(i) : nullptr; } XPlane* FindOrAddMutablePlaneWithName(XSpace* space, absl::string_view name) { XPlane* plane = FindMutablePlaneWithName(space, name); if (plane == nullptr) { plane = space->add_planes(); plane->set_name(name.data(), name.size()); } return plane; } std::vector<const XPlane*> FindPlanesWithPrefix(const XSpace& space, absl::string_view prefix) { return FindPlanes(space, [&](const XPlane& plane) { return absl::StartsWith(plane.name(), prefix); }); } std::vector<XPlane*> FindMutablePlanesWithPrefix(XSpace* space, absl::string_view prefix) { return FindMutablePlanes(space, [&](XPlane& plane) { return absl::StartsWith(plane.name(), prefix); }); } const XLine* FindLineWithId(const XPlane& plane, int64_t id) { int i = Find(plane.lines(), [id](const XLine* line) { return line->id() == id; }); return (i != -1) ? &plane.lines(i) : nullptr; } std::vector<const XLine*> FindLinesWithId(const XPlane& plane, int64_t id) { std::vector<int> indices = FindAll( plane.lines(), [id](const XLine* line) { return line->id() == id; }); std::vector<const XLine*> lines; lines.reserve(indices.size()); for (int index : indices) { lines.push_back(&plane.lines(index)); } return lines; } const XLine* FindLineWithName(const XPlane& plane, absl::string_view name) { int i = Find(plane.lines(), [name](const XLine* line) { return line->name() == name; }); return (i != -1) ? &plane.lines(i) : nullptr; } XStat* FindOrAddMutableStat(const XStatMetadata& stat_metadata, XEvent* event) { for (auto& stat : *event->mutable_stats()) { if (stat.metadata_id() == stat_metadata.id()) { return &stat; } } XStat* stat = event->add_stats(); stat->set_metadata_id(stat_metadata.id()); return stat; } void RemovePlane(XSpace* space, const XPlane* plane) { DCHECK(plane != nullptr); Remove(space->mutable_planes(), plane); } void RemovePlanes(XSpace* space, const std::vector<const XPlane*>& planes) { absl::flat_hash_set<const XPlane*> planes_set(planes.begin(), planes.end()); RemoveIf(space->mutable_planes(), [&planes_set](const XPlane* plane) { return planes_set.contains(plane); }); } void RemoveLine(XPlane* plane, const XLine* line) { DCHECK(line != nullptr); Remove(plane->mutable_lines(), line); } void RemoveEvents(XLine* line, const absl::flat_hash_set<const XEvent*>& events) { RemoveIf(line->mutable_events(), [&](const XEvent* event) { return events.contains(event); }); } void RemoveEmptyPlanes(XSpace* space) { RemoveIf(space->mutable_planes(), [&](const XPlane* plane) { return plane->lines().empty(); }); } void RemoveEmptyLines(XPlane* plane) { RemoveIf(plane->mutable_lines(), [&](const XLine* line) { return line->events().empty(); }); } bool XEventsComparator::operator()(const XEvent* a, const XEvent* b) const { return XEventTimespan(*a) < XEventTimespan(*b); } void SortXPlane(XPlane* plane) { for (XLine& line : *plane->mutable_lines()) { auto& events = *line.mutable_events(); std::sort(events.pointer_begin(), events.pointer_end(), XEventsComparator()); } } void SortXSpace(XSpace* space) { for (XPlane& plane : *space->mutable_planes()) SortXPlane(&plane); } void NormalizeTimestamps(XPlane* plane, uint64 start_time_ns) { for (XLine& line : *plane->mutable_lines()) { if (line.timestamp_ns() >= static_cast<int64_t>(start_time_ns)) { line.set_timestamp_ns(line.timestamp_ns() - start_time_ns); } } } void NormalizeTimestamps(XSpace* space, uint64 start_time_ns) { for (XPlane& plane : *space->mutable_planes()) { NormalizeTimestamps(&plane, start_time_ns); } } void MergePlanes(const XPlane& src_plane, XPlane* dst_plane) { RemoveEmptyLines(dst_plane); XPlaneVisitor src(&src_plane); XPlaneBuilder dst(dst_plane); src.ForEachStat([&](const XStatVisitor& stat) { XStatMetadata* stat_metadata = dst.GetOrCreateStatMetadata(stat.Name()); dst.SetOrAddStat(*stat_metadata, stat.RawStat(), src_plane); }); src.ForEachLine([&](const XLineVisitor& line) { XLineBuilder dst_line = dst.GetOrCreateLine(line.Id()); int64_t time_offset_ps = 0LL; if (dst_line.NumEvents() == 0) { dst_line.SetTimestampNs(line.TimestampNs()); dst_line.SetName(line.Name()); dst_line.SetDisplayNameIfEmpty(line.DisplayName()); } else { if (line.TimestampNs() <= dst_line.TimestampNs()) { dst_line.SetTimestampNsAndAdjustEventOffsets(line.TimestampNs()); } else { time_offset_ps = NanoToPico(line.TimestampNs() - dst_line.TimestampNs()); } dst_line.SetNameIfEmpty(line.Name()); } line.ForEachEvent([&](const XEventVisitor& event) { CopyEvent(event, src, src_plane, time_offset_ps, dst, dst_line); }); }); } void MergePlanes(const std::vector<const XPlane*>& src_planes, XPlane* dst_plane) { for (const XPlane* src_plane : src_planes) { MergePlanes(*src_plane, dst_plane); } } int64_t GetStartTimestampNs(const XPlane& plane) { if (plane.lines().empty()) return 0LL; int64_t plane_timestamp = std::numeric_limits<int64_t>::max(); for (const auto& line : plane.lines()) { plane_timestamp = std::min(plane_timestamp, line.timestamp_ns()); } return plane_timestamp; } bool IsEmpty(const XSpace& space) { for (const auto& plane : space.planes()) { for (const auto& line : plane.lines()) { if (!line.events().empty()) { return false; } } } return true; } bool IsXSpaceGrouped(const XSpace& space) { for (const auto& plane : space.planes()) { XPlaneVisitor xplane = tsl::profiler::CreateTfXPlaneVisitor(&plane); const XStatMetadata* group_id_stat = xplane.GetStatMetadataByType(StatType::kGroupId); if (group_id_stat) return true; } return false; } void AddFlowsToXplane(int32_t host_id, bool is_host_plane, bool connect_traceme, XPlane* xplane) { if (!xplane) return; XPlaneBuilder plane(xplane); XStatMetadata* correlation_id_stats_metadata = plane.GetStatMetadata(GetStatTypeStr(StatType::kCorrelationId)); XStatMetadata* producer_type_stats_metadata = plane.GetStatMetadata(GetStatTypeStr(StatType::kProducerType)); XStatMetadata* consumer_type_stats_metadata = plane.GetStatMetadata(GetStatTypeStr(StatType::kConsumerType)); XStatMetadata* producer_id_stats_metadata = plane.GetStatMetadata(GetStatTypeStr(StatType::kProducerId)); XStatMetadata* consumer_id_stats_metadata = plane.GetStatMetadata(GetStatTypeStr(StatType::kConsumerId)); XStatMetadata* flow_stats_metadata = plane.GetOrCreateStatMetadata(GetStatTypeStr(StatType::kFlow)); XFlow::FlowDirection direction = is_host_plane ? XFlow::FlowDirection::kFlowOut : XFlow::FlowDirection::kFlowIn; plane.ForEachLine([&](XLineBuilder line) { line.ForEachEvent([&](XEventBuilder event) { std::optional<uint64_t> correlation_id; std::optional<uint64_t> producer_type; std::optional<uint64_t> consumer_type; std::optional<uint64_t> producer_id; std::optional<uint64_t> consumer_id; event.ForEachStat([&](XStat* stat) { if (correlation_id_stats_metadata && stat->metadata_id() == correlation_id_stats_metadata->id()) { correlation_id = stat->uint64_value(); } else if (connect_traceme) { if (producer_type_stats_metadata && stat->metadata_id() == producer_type_stats_metadata->id()) { producer_type = XStatsBuilder<XPlane>::IntOrUintValue(*stat); } else if (consumer_type_stats_metadata && stat->metadata_id() == consumer_type_stats_metadata->id()) { consumer_type = XStatsBuilder<XPlane>::IntOrUintValue(*stat); } else if (producer_id_stats_metadata && stat->metadata_id() == producer_id_stats_metadata->id()) { producer_id = XStatsBuilder<XPlane>::IntOrUintValue(*stat); } else if (consumer_id_stats_metadata && stat->metadata_id() == consumer_id_stats_metadata->id()) { consumer_id = XStatsBuilder<XPlane>::IntOrUintValue(*stat); } } }); if (correlation_id) { XFlow flow(XFlow::GetFlowId(host_id, *correlation_id), direction, ContextType::kGpuLaunch); event.AddStatValue(*flow_stats_metadata, flow.ToStatValue()); } if (connect_traceme) { if (producer_type && producer_id) { auto context_type = GetSafeContextType(*producer_type); XFlow flow(XFlow::GetFlowId(host_id, *producer_id, context_type), XFlow::FlowDirection::kFlowOut, context_type); event.AddStatValue(*flow_stats_metadata, flow.ToStatValue()); } if (consumer_type && consumer_id) { auto context_type = GetSafeContextType(*consumer_type); XFlow flow(XFlow::GetFlowId(host_id, *consumer_id, context_type), XFlow::FlowDirection::kFlowIn, context_type); event.AddStatValue(*flow_stats_metadata, flow.ToStatValue()); } } }); }); } uint64_t GetDevicePlaneFingerprint(const XPlane& plane) { const XLine* xla_module_line = FindLineWithName(plane, kXlaModuleLineName); if (!xla_module_line) return 0ULL; XPlaneVisitor xplane(&plane); XLineVisitor xline(&xplane, xla_module_line); std::set<uint64_t> ordered_module_fps; xline.ForEachEvent([&](const XEventVisitor& xevent) { ordered_module_fps.insert(Fingerprint64(xevent.Name())); }); if (ordered_module_fps.empty()) return 0ULL; uint64_t output = 0ULL; for (const auto& fp : ordered_module_fps) { output = FingerprintCat64(output, fp); } return output; } std::optional<XEventVisitor> XEventContextTracker::GetContainingEvent( const Timespan& event) { if (!line_) return std::nullopt; if (current_index_ != -1) { XEventVisitor current_event(plane_, line_, &line_->events(current_index_)); if (current_event.GetTimespan().Includes(event)) { return current_event; } } for (int i = current_index_ + 1; i < line_->events_size(); ++i) { XEventVisitor current_event(plane_, line_, &line_->events(i)); if (current_event.TimestampPs() > event.end_ps()) break; if (current_event.EndTimestampPs() < event.begin_ps()) continue; current_index_ = i; if (current_event.GetTimespan().Includes(event)) { return current_event; } break; } return std::nullopt; } std::optional<XEventVisitor> XEventContextTracker::GetOverlappingEvent( const Timespan& event) { if (!line_) return std::nullopt; if (current_index_ != -1) { XEventVisitor current_event(plane_, line_, &line_->events(current_index_)); if (current_event.GetTimespan().Overlaps(event)) { return current_event; } } for (int i = current_index_ + 1; i < line_->events_size(); ++i) { XEventVisitor current_event(plane_, line_, &line_->events(i)); if (current_event.TimestampPs() > event.end_ps()) break; if (current_event.EndTimestampPs() < event.begin_ps()) continue; current_index_ = i; if (current_event.GetTimespan().Overlaps(event)) { return current_event; } break; } return std::nullopt; } void AggregateXPlane(const XPlane& full_trace, XPlane& aggregated_trace) { struct EventStat { tsl::Stat<int64_t> stat; int64_t children_duration; }; using StatByEvent = absl::flat_hash_map<int64_t , EventStat>; using StatByGroup = absl::flat_hash_map<int64_t , StatByEvent>; absl::flat_hash_map<int64_t , StatByGroup> stats; const XPlaneVisitor& plane = CreateTfXPlaneVisitor(&full_trace); XPlaneBuilder aggregated_plane(&aggregated_trace); aggregated_plane.SetName(plane.Name()); uint64_t first_op_start_ps = kint64max; uint64_t last_op_end_ps = 0; plane.ForEachLine([&](const XLineVisitor& line) { if (line.Name() == kStepLineName) { XLineBuilder aggregated_line = aggregated_plane.GetOrCreateLine(line.Id()); aggregated_line.SetName(kStepLineName); line.ForEachEvent([&](const XEventVisitor& event) { CopyEvent(event, plane, full_trace, 0LL, aggregated_plane, aggregated_line); }); } if (!IsOpLineName(line.Name())) return; XLineBuilder aggregated_line = aggregated_plane.GetOrCreateLine(line.Id()); aggregated_line.SetName(line.Name()); std::vector<XEventVisitor> event_stack; line.ForEachEvent([&](XEventVisitor event) { first_op_start_ps = first_op_start_ps <= event.TimestampPs() ? first_op_start_ps : event.TimestampPs(); last_op_end_ps = last_op_end_ps >= event.EndTimestampPs() ? last_op_end_ps : event.EndTimestampPs(); const auto& group_stat = event.GetStat(StatType::kGroupId); int64_t group_id = group_stat.has_value() ? group_stat->IntOrUintValue() : kint64max; StatByEvent& line_stats = stats[line.Id()][group_id]; line_stats[event.Id()].stat.UpdateStat(event.DurationPs()); DCHECK(event_stack.empty() || !(event < event_stack.back())); while (!event_stack.empty() && !event_stack.back().GetTimespan().Includes(event.GetTimespan())) { event_stack.pop_back(); } if (!event_stack.empty()) { line_stats[event_stack.back().Id()].children_duration += event.DurationPs(); } event_stack.push_back(std::move(event)); }); }); uint64_t total_time_ps = (last_op_end_ps && last_op_end_ps > first_op_start_ps) ? last_op_end_ps - first_op_start_ps : 0; aggregated_plane.AddStatValue( *aggregated_plane.GetOrCreateStatMetadata( GetStatTypeStr(StatType::kTotalProfileDurationPs)), total_time_ps); XStatMetadata* kMinDurationPs = aggregated_plane.GetOrCreateStatMetadata( GetStatTypeStr(StatType::kMinDurationPs)); XStatMetadata* kSelfDurationPs = aggregated_plane.GetOrCreateStatMetadata( GetStatTypeStr(StatType::kSelfDurationPs)); XStatMetadata* kGroupId = aggregated_plane.GetOrCreateStatMetadata( GetStatTypeStr(StatType::kGroupId)); for (const auto& [line_id, stats_by_group] : stats) { XLineBuilder aggregated_line = aggregated_plane.GetOrCreateLine(line_id); for (const auto& [group_id, stat_by_event] : stats_by_group) { for (const auto& [event_id, event_stat] : stat_by_event) { XEventMetadata& event_metadata = *aggregated_plane.GetOrCreateEventMetadata(event_id); CopyEventMetadata(*plane.GetEventMetadata(event_id), plane, event_metadata, aggregated_plane); XEventBuilder aggregated_event = aggregated_line.AddEvent(event_metadata); aggregated_event.SetNumOccurrences(event_stat.stat.count()); aggregated_event.SetDurationPs(event_stat.stat.sum()); if (group_id != kint64max) { aggregated_event.AddStatValue(*kGroupId, group_id); } if (event_stat.stat.count() > 1) { aggregated_event.AddStatValue(*kMinDurationPs, event_stat.stat.min()); } if (event_stat.children_duration != 0) { aggregated_event.AddStatValue(
#include "tsl/profiler/utils/xplane_utils.h" #include <cstdint> #include <optional> #include <string> #include <utility> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/strings/string_view.h" #include "absl/types/optional.h" #include "tsl/platform/test.h" #include "tsl/platform/types.h" #include "tsl/profiler/protobuf/xplane.pb.h" #include "tsl/profiler/utils/math_utils.h" #include "tsl/profiler/utils/tf_xplane_visitor.h" #include "tsl/profiler/utils/xplane_builder.h" #include "tsl/profiler/utils/xplane_schema.h" #include "tsl/profiler/utils/xplane_visitor.h" namespace tsl { namespace profiler { namespace { using ::testing::Property; using ::testing::SizeIs; using ::testing::UnorderedElementsAre; #if defined(PLATFORM_GOOGLE) using ::testing::EqualsProto; using ::testing::proto::IgnoringRepeatedFieldOrdering; using ::testing::proto::Partially; #endif XEvent CreateEvent(int64_t offset_ps, int64_t duration_ps) { XEvent event; event.set_offset_ps(offset_ps); event.set_duration_ps(duration_ps); return event; } TEST(XPlaneUtilsTest, AddAndRemovePlanes) { XSpace space; auto* p1 = FindOrAddMutablePlaneWithName(&space, "p1"); EXPECT_EQ(p1, FindPlaneWithName(space, "p1")); auto* p2 = FindOrAddMutablePlaneWithName(&space, "p2"); EXPECT_EQ(p2, FindPlaneWithName(space, "p2")); auto* p3 = FindOrAddMutablePlaneWithName(&space, "p3"); EXPECT_EQ(p3, FindPlaneWithName(space, "p3")); RemovePlane(&space, p2); EXPECT_EQ(space.planes_size(), 2); EXPECT_EQ(p1, FindPlaneWithName(space, "p1")); EXPECT_EQ(p3, FindPlaneWithName(space, "p3")); RemovePlane(&space, p1); EXPECT_EQ(space.planes_size(), 1); EXPECT_EQ(p3, FindPlaneWithName(space, "p3")); RemovePlane(&space, p3); EXPECT_EQ(space.planes_size(), 0); } TEST(XPlaneUtilsTest, RemoveEmptyPlanes) { XSpace space; RemoveEmptyPlanes(&space); EXPECT_EQ(space.planes_size(), 0); auto* plane1 = space.add_planes(); plane1->set_name("p1"); plane1->add_lines()->set_name("p1l1"); plane1->add_lines()->set_name("p1l2"); auto* plane2 = space.add_planes(); plane2->set_name("p2"); auto* plane3 = space.add_planes(); plane3->set_name("p3"); plane3->add_lines()->set_name("p3l1"); auto* plane4 = space.add_planes(); plane4->set_name("p4"); RemoveEmptyPlanes(&space); ASSERT_EQ(space.planes_size(), 2); EXPECT_EQ(space.planes(0).name(), "p1"); EXPECT_EQ(space.planes(1).name(), "p3"); } TEST(XPlaneUtilsTest, RemoveEmptyLines) { XPlane plane; RemoveEmptyLines(&plane); EXPECT_EQ(plane.lines_size(), 0); auto* line1 = plane.add_lines(); line1->set_name("l1"); line1->add_events(); line1->add_events(); auto* line2 = plane.add_lines(); line2->set_name("l2"); auto* line3 = plane.add_lines(); line3->set_name("l3"); line3->add_events(); auto* line4 = plane.add_lines(); line4->set_name("l4"); RemoveEmptyLines(&plane); ASSERT_EQ(plane.lines_size(), 2); EXPECT_EQ(plane.lines(0).name(), "l1"); EXPECT_EQ(plane.lines(1).name(), "l3"); } TEST(XPlaneUtilsTest, RemoveLine) { XPlane plane; const XLine* line1 = plane.add_lines(); const XLine* line2 = plane.add_lines(); const XLine* line3 = plane.add_lines(); RemoveLine(&plane, line2); ASSERT_EQ(plane.lines_size(), 2); EXPECT_EQ(&plane.lines(0), line1); EXPECT_EQ(&plane.lines(1), line3); } TEST(XPlaneUtilsTest, RemoveEvents) { XLine line; const XEvent* event1 = line.add_events(); const XEvent* event2 = line.add_events(); const XEvent* event3 = line.add_events(); const XEvent* event4 = line.add_events(); RemoveEvents(&line, {event1, event3}); ASSERT_EQ(line.events_size(), 2); EXPECT_EQ(&line.events(0), event2); EXPECT_EQ(&line.events(1), event4); } TEST(XPlaneUtilsTest, SortXPlaneTest) { XPlane plane; XLine* line = plane.add_lines(); *line->add_events() = CreateEvent(200, 100); *line->add_events() = CreateEvent(100, 100); *line->add_events() = CreateEvent(120, 50); *line->add_events() = CreateEvent(120, 30); SortXPlane(&plane); ASSERT_EQ(plane.lines_size(), 1); ASSERT_EQ(plane.lines(0).events_size(), 4); EXPECT_EQ(plane.lines(0).events(0).offset_ps(), 100); EXPECT_EQ(plane.lines(0).events(0).duration_ps(), 100); EXPECT_EQ(plane.lines(0).events(1).offset_ps(), 120); EXPECT_EQ(plane.lines(0).events(1).duration_ps(), 50); EXPECT_EQ(plane.lines(0).events(2).offset_ps(), 120); EXPECT_EQ(plane.lines(0).events(2).duration_ps(), 30); EXPECT_EQ(plane.lines(0).events(3).offset_ps(), 200); EXPECT_EQ(plane.lines(0).events(3).duration_ps(), 100); } namespace { XLineBuilder CreateXLine(XPlaneBuilder* plane, absl::string_view name, absl::string_view display, int64_t id, int64_t timestamp_ns) { XLineBuilder line = plane->GetOrCreateLine(id); line.SetName(name); line.SetTimestampNs(timestamp_ns); line.SetDisplayNameIfEmpty(display); return line; } XEventBuilder CreateXEvent(XPlaneBuilder* plane, XLineBuilder line, absl::string_view event_name, std::optional<absl::string_view> display, int64_t offset_ns, int64_t duration_ns) { XEventMetadata* event_metadata = plane->GetOrCreateEventMetadata(event_name); if (display) event_metadata->set_display_name(std::string(*display)); XEventBuilder event = line.AddEvent(*event_metadata); event.SetOffsetNs(offset_ns); event.SetDurationNs(duration_ns); return event; } template <typename T, typename V> void CreateXStats(XPlaneBuilder* plane, T* stats_owner, absl::string_view stats_name, V stats_value) { stats_owner->AddStatValue(*plane->GetOrCreateStatMetadata(stats_name), stats_value); } void CheckXLine(const XLine& line, absl::string_view name, absl::string_view display, int64_t start_time_ns, int64_t events_size) { EXPECT_EQ(line.name(), name); EXPECT_EQ(line.display_name(), display); EXPECT_EQ(line.timestamp_ns(), start_time_ns); EXPECT_EQ(line.events_size(), events_size); } void CheckXEvent(const XEvent& event, const XPlane& plane, absl::string_view name, absl::string_view display, int64_t offset_ns, int64_t duration_ns, int64_t stats_size) { const XEventMetadata& event_metadata = plane.event_metadata().at(event.metadata_id()); EXPECT_EQ(event_metadata.name(), name); EXPECT_EQ(event_metadata.display_name(), display); EXPECT_EQ(event.offset_ps(), NanoToPico(offset_ns)); EXPECT_EQ(event.duration_ps(), NanoToPico(duration_ns)); EXPECT_EQ(event.stats_size(), stats_size); } } TEST(XPlaneUtilsTest, MergeXPlaneTest) { XPlane src_plane, dst_plane; constexpr int64_t kLineIdOnlyInSrcPlane = 1LL; constexpr int64_t kLineIdOnlyInDstPlane = 2LL; constexpr int64_t kLineIdInBothPlanes = 3LL; constexpr int64_t kLineIdInBothPlanes2 = 4LL; { XPlaneBuilder src(&src_plane); CreateXStats(&src, &src, "plane_stat1", 1); CreateXStats(&src, &src, "plane_stat3", 3.0); auto l1 = CreateXLine(&src, "l1", "d1", kLineIdOnlyInSrcPlane, 100); auto e1 = CreateXEvent(&src, l1, "event1", "display1", 1, 2); CreateXStats(&src, &e1, "event_stat1", 2.0); auto e2 = CreateXEvent(&src, l1, "event2", std::nullopt, 3, 4); CreateXStats(&src, &e2, "event_stat2", 3); auto l2 = CreateXLine(&src, "l2", "d2", kLineIdInBothPlanes, 200); auto e3 = CreateXEvent(&src, l2, "event3", std::nullopt, 5, 7); CreateXStats(&src, &e3, "event_stat3", 2.0); auto e4 = CreateXEvent(&src, l2, "event4", std::nullopt, 6, 8); CreateXStats(&src, &e4, "event_stat4", 3); CreateXStats(&src, &e4, "event_stat5", 3); auto l5 = CreateXLine(&src, "l5", "d5", kLineIdInBothPlanes2, 700); CreateXEvent(&src, l5, "event51", std::nullopt, 9, 10); CreateXEvent(&src, l5, "event52", std::nullopt, 11, 12); } { XPlaneBuilder dst(&dst_plane); CreateXStats(&dst, &dst, "plane_stat2", 2); CreateXStats(&dst, &dst, "plane_stat3", 4); auto l3 = CreateXLine(&dst, "l3", "d3", kLineIdOnlyInDstPlane, 300); auto e5 = CreateXEvent(&dst, l3, "event5", std::nullopt, 11, 2); CreateXStats(&dst, &e5, "event_stat6", 2.0); auto e6 = CreateXEvent(&dst, l3, "event6", std::nullopt, 13, 4); CreateXStats(&dst, &e6, "event_stat7", 3); auto l2 = CreateXLine(&dst, "l4", "d4", kLineIdInBothPlanes, 400); auto e7 = CreateXEvent(&dst, l2, "event7", std::nullopt, 15, 7); CreateXStats(&dst, &e7, "event_stat8", 2.0); auto e8 = CreateXEvent(&dst, l2, "event8", "display8", 16, 8); CreateXStats(&dst, &e8, "event_stat9", 3); auto l6 = CreateXLine(&dst, "l6", "d6", kLineIdInBothPlanes2, 300); CreateXEvent(&dst, l6, "event61", std::nullopt, 21, 10); CreateXEvent(&dst, l6, "event62", std::nullopt, 22, 12); } MergePlanes(src_plane, &dst_plane); XPlaneVisitor plane(&dst_plane); EXPECT_EQ(dst_plane.lines_size(), 4); EXPECT_EQ(dst_plane.stats_size(), 3); absl::flat_hash_map<absl::string_view, absl::string_view> plane_stats; plane.ForEachStat([&](const XStatVisitor& stat) { if (stat.Name() == "plane_stat1") { EXPECT_EQ(stat.IntValue(), 1); } else if (stat.Name() == "plane_stat2") { EXPECT_EQ(stat.IntValue(), 2); } else if (stat.Name() == "plane_stat3") { EXPECT_EQ(stat.DoubleValue(), 3.0); } else { EXPECT_TRUE(false); } }); EXPECT_EQ(dst_plane.stat_metadata_size(), 12); { const XLine& line = dst_plane.lines(0); CheckXLine(line, "l3", "d3", 300, 2); CheckXEvent(line.events(0), dst_plane, "event5", "", 11, 2, 1); CheckXEvent(line.events(1), dst_plane, "event6", "", 13, 4, 1); } { const XLine& line = dst_plane.lines(1); CheckXLine(line, "l4", "d4", 200, 4); CheckXEvent(line.events(0), dst_plane, "event7", "", 215, 7, 1); CheckXEvent(line.events(1), dst_plane, "event8", "display8", 216, 8, 1); CheckXEvent(line.events(2), dst_plane, "event3", "", 5, 7, 1); CheckXEvent(line.events(3), dst_plane, "event4", "", 6, 8, 2); } { const XLine& line = dst_plane.lines(2); CheckXLine(line, "l6", "d6", 300, 4); CheckXEvent(line.events(0), dst_plane, "event61", "", 21, 10, 0); CheckXEvent(line.events(1), dst_plane, "event62", "", 22, 12, 0); CheckXEvent(line.events(2), dst_plane, "event51", "", 409, 10, 0); CheckXEvent(line.events(3), dst_plane, "event52", "", 411, 12, 0); } { const XLine& line = dst_plane.lines(3); CheckXLine(line, "l1", "d1", 100, 2); CheckXEvent(line.events(0), dst_plane, "event1", "display1", 1, 2, 1); CheckXEvent(line.events(1), dst_plane, "event2", "", 3, 4, 1); } } TEST(XPlaneUtilsTest, FindPlanesWithPrefix) { XSpace xspace; FindOrAddMutablePlaneWithName(&xspace, "test-prefix:0"); FindOrAddMutablePlaneWithName(&xspace, "test-prefix:1"); FindOrAddMutablePlaneWithName(&xspace, "test-prefix:2"); FindOrAddMutablePlaneWithName(&xspace, "test-prefix:3"); XPlane* p4 = FindOrAddMutablePlaneWithName(&xspace, "test-do-not-include:0"); std::vector<const XPlane*> xplanes = FindPlanesWithPrefix(xspace, "test-prefix"); ASSERT_EQ(4, xplanes.size()); for (const XPlane* plane : xplanes) { ASSERT_NE(p4, plane); } } TEST(XplaneUtilsTest, FindMutablePlanesWithPrefix) { XSpace xspace; FindOrAddMutablePlaneWithName(&xspace, "test-prefix:0"); FindOrAddMutablePlaneWithName(&xspace, "test-prefix:1"); FindOrAddMutablePlaneWithName(&xspace, "test-prefix:2"); FindOrAddMutablePlaneWithName(&xspace, "test-prefix:3"); XPlane* p4 = FindOrAddMutablePlaneWithName(&xspace, "test-do-not-include:0"); std::vector<XPlane*> xplanes = FindMutablePlanesWithPrefix(&xspace, "test-prefix"); ASSERT_EQ(4, xplanes.size()); for (XPlane* plane : xplanes) { ASSERT_NE(p4, plane); } } TEST(XplaneUtilsTest, FindPlanesWithPredicate) { XSpace xspace; FindOrAddMutablePlaneWithName(&xspace, "test-prefix:0"); XPlane* p1 = FindOrAddMutablePlaneWithName(&xspace, "test-prefix:1"); std::vector<const XPlane*> xplanes = FindPlanes( xspace, [](const XPlane& xplane) { return xplane.name() == "test-prefix:1"; }); ASSERT_EQ(1, xplanes.size()); ASSERT_EQ(p1, xplanes[0]); } TEST(XplaneUtilsTest, FindMutablePlanesWithPredicate) { XSpace xspace; FindOrAddMutablePlaneWithName(&xspace, "test-prefix:0"); XPlane* p1 = FindOrAddMutablePlaneWithName(&xspace, "test-prefix:1"); std::vector<XPlane*> xplanes = FindMutablePlanes( &xspace, [](XPlane& xplane) { return xplane.name() == "test-prefix:1"; }); ASSERT_EQ(1, xplanes.size()); ASSERT_EQ(p1, xplanes[0]); } TEST(XplaneUtilsTest, TestAggregateXPlanes) { XPlane xplane; XPlaneBuilder builder(&xplane); XEventMetadata* event_metadata1 = builder.GetOrCreateEventMetadata(1); event_metadata1->set_name("EventMetadata1"); XEventMetadata* event_metadata2 = builder.GetOrCreateEventMetadata(2); event_metadata2->set_name("EventMetadata2"); XEventMetadata* event_metadata3 = builder.GetOrCreateEventMetadata(3); event_metadata3->set_name("EventMetadata3"); XEventMetadata* event_metadata4 = builder.GetOrCreateEventMetadata(4); event_metadata4->set_name("EventMetadata4"); XLineBuilder line = builder.GetOrCreateLine(1); line.SetName(kTensorFlowOpLineName); XEventBuilder event1 = line.AddEvent(*event_metadata1); event1.SetOffsetNs(0); event1.SetDurationNs(5); XEventBuilder event3 = line.AddEvent(*event_metadata3); event3.SetOffsetNs(0); event3.SetDurationNs(2); XEventBuilder event2 = line.AddEvent(*event_metadata2); event2.SetOffsetNs(5); event2.SetDurationNs(5); XEventBuilder event4 = line.AddEvent(*event_metadata2); event4.SetOffsetNs(10); event4.SetDurationNs(5); XEventBuilder event5 = line.AddEvent(*event_metadata4); event5.SetOffsetNs(15); event5.SetDurationNs(6); XEventBuilder event6 = line.AddEvent(*event_metadata1); event6.SetOffsetNs(15); event6.SetDurationNs(4); XEventBuilder event7 = line.AddEvent(*event_metadata3); event7.SetOffsetNs(15); event7.SetDurationNs(3); XPlane aggregated_xplane; AggregateXPlane(xplane, aggregated_xplane); #if defined(PLATFORM_GOOGLE) ASSERT_THAT(aggregated_xplane, IgnoringRepeatedFieldOrdering(EqualsProto( R"pb(lines { id: 1 name: "Framework Ops" events { metadata_id: 1 duration_ps: 9000 stats { metadata_id: 2 int64_value: 4000 } stats { metadata_id: 3 int64_value: 4000 } num_occurrences: 2 } events { metadata_id: 3 duration_ps: 5000 stats { metadata_id: 2 int64_value: 2000 } num_occurrences: 2 } events { metadata_id: 4 duration_ps: 6000 stats { metadata_id: 3 int64_value: 2000 } num_occurrences: 1 } events { metadata_id: 2 duration_ps: 10000 stats { metadata_id: 2 int64_value: 5000 } num_occurrences: 2 } } event_metadata { key: 1 value { id: 1 name: "EventMetadata1" } } event_metadata { key: 2 value { id: 2 name: "EventMetadata2" } } event_metadata { key: 3 value { id: 3 name: "EventMetadata3" } } event_metadata { key: 4 value { id: 4 name: "EventMetadata4" } } stat_metadata { key: 1 value { id: 1 name: "total_profile_duration_ps" } } stat_metadata { key: 2 value { id: 2 name: "min_duration_ps" } } stat_metadata { key: 3 value { id: 3 name: "self_duration_ps" } } stat_metadata { key: 4 value { id: 4 name: "group_id" } } stats { metadata_id: 1 uint64_value: 21000 } )pb"))); #endif } TEST(XPlanuUtilsTest, TestInstantEventDoesNotFail) { XPlane xplane; XPlaneBuilder xplane_builder(&xplane); XEventMetadata* event_metadata1 = xplane_builder.GetOrCreateEventMetadata(1); XEventMetadata* event_metadata2 = xplane_builder.GetOrCreateEventMetadata(2); XLineBuilder line = xplane_builder.GetOrCreateLine(1); line.SetName(kTensorFlowOpLineName); XEventBuilder event1 = line.AddEvent(*event_metadata1); XEventBuilder event2 = line.AddEvent(*event_metadata2); event1.SetOffsetNs(1); event1.SetDurationNs(0); event2.SetOffsetNs(1); event2.SetDurationNs(0); XPlane aggregated_xplane; AggregateXPlane(xplane, aggregated_xplane); EXPECT_THAT(aggregated_xplane.lines(), UnorderedElementsAre(Property(&XLine::events, SizeIs(2)))); } TEST(XplaneutilsTest, TestEventMetadataStatsAreCopied) { XPlane xplane; XPlaneBuilder xplane_builder(&xplane); XEventMetadata* event_metadata = xplane_builder.GetOrCreateEventMetadata(1); XStatsBuilder<XEventMetadata> stats(event_metadata, &xplane_builder); stats.AddStatValue( *xplane_builder.GetOrCreateStatMetadata(GetStatTypeStr(StatType::kTfOp)), "TestFunction"); XLineBuilder line = xplane_builder.GetOrCreateLine(1); line.SetName(kTensorFlowOpLineName); XEventBuilder event = line.AddEvent(*event_metadata); event.SetDurationNs(0); event.SetOffsetNs(0); XPlane aggregated_xplane; AggregateXPlane(xplane, aggregated_xplane); XPlaneVisitor visitor = CreateTfXPlaneVisitor(&aggregated_xplane); XEventMetadataVisitor metadata_visitor(&visitor, visitor.GetEventMetadata(1)); std::optional<XStatVisitor> stat = metadata_visitor.GetStat(StatType::kTfOp); ASSERT_TRUE(stat.has_value()); EXPECT_EQ(stat->Name(), "tf_op"); EXPECT_EQ(stat->StrOrRefValue(), "TestFunction"); } TEST(XplaneutilsTest, TestEventMetadataStatsAreCopiedForRefValue) { XPlane xplane; XPlaneBuilder xplane_builder(&xplane); XEventMetadata* event_metadata = xplane_builder.GetOrCreateEventMetadata(1); XStatsBuilder<XEventMetadata> stats(event_metadata, &xplane_builder); stats.AddStatValue( *xplane_builder.GetOrCreateStatMetadata(GetStatTypeStr(StatType::kTfOp)), *xplane_builder.GetOrCreateStatMetadata("TestFunction")); XLineBuilder line = xplane_builder.GetOrCreateLine(1); line.SetName(kTensorFlowOpLineName); XEventBuilder event = line.AddEvent(*event_metadata); event.SetDurationNs(0); event.SetOffsetNs(0); XPlane aggregated_xplane; AggregateXPlane(xplane, aggregated_xplane); XPlaneVisitor visitor = CreateTfXPlaneVisitor(&aggregated_xplane); XEventMetadataVisitor metadata_visitor(&visitor, visitor.GetEventMetadata(1)); std::optional<XStatVisitor> stat = metadata_visitor.GetStat(StatType::kTfOp); ASSERT_TRUE(stat.has_value()); EXPECT_EQ(stat->Name(), "tf_op"); EXPECT_EQ(stat->StrOrRefValue(), "TestFunction"); } TEST(XplaneutilsTest, TestIsXSpaceGrouped) { XSpace space; { XPlaneBuilder p1(space.add_planes()); auto l1 = CreateXLine(&p1, "l1", "d1", 1, 100); auto e1 = CreateXEvent(&p1, l1, "event1", "display1", 1, 2); CreateXStats(&p1, &e1, "event_stat1", 2.0); } EXPECT_FALSE(IsXSpaceGrouped(space)); { XPlaneBuilder p2(space.add_planes()); auto l2 = CreateXLine(&p2, "l2", "d2", 1, 100); auto e2 = CreateXEvent(&p2, l2, "event2", "display2", 1, 2); CreateXStats(&p2, &e2, "group_id", 1); } LOG(ERROR) << space.DebugString(); EXPECT_TRUE(IsXSpaceGrouped(space)); } TEST(XplaneutilsTest, TestIsHostPlane) { XSpace xspace; auto xplane_host_thread = FindOrAddMutablePlaneWithName(&xspace, "/host:CPU"); auto xplane_host_cpu = FindOrAddMutablePlaneWithName(&xspace, "Host CPUs"); auto xplane_tfstreamz = FindOrAddMutablePlaneWithName(&xspace, "/host:tfstreamz"); auto xplane_metadata = FindOrAddMutablePlaneWithName(&xspace, "/host:metadata"); auto xplane_syscalls = FindOrAddMutablePlaneWithName(&xspace, "Syscalls"); auto xplane_python_tracer = FindOrAddMutablePlaneWithName(&xspace, "/host:python-tracer"); auto xplane_custom_prefix = FindOrAddMutablePlaneWithName(&xspace, "/device:CUSTOM:123"); auto xplane_legacy_custom = FindOrAddMutablePlaneWithName(&xspace, "/custom:456"); auto xplane_cupti = FindOrAddMutablePlaneWithName(&xspace, "/host:CUPTI"); EXPECT_TRUE(IsHostPlane(*xplane_host_thread)); EXPECT_TRUE(IsHostPlane(*xplane_host_cpu)); EXPECT_TRUE(IsHostPlane(*xplane_tfstreamz)); EXPECT_TRUE(IsHostPlane(*xplane_metadata)); EXPECT_TRUE(IsHostPlane(*xplane_syscalls)); EXPECT_TRUE(IsHostPlane(*xplane_python_tracer)); EXPECT_FALSE(IsHostPlane(*xplane_custom_prefix)); EXPECT_FALSE(IsHostPlane(*xplane_legacy_custom)); EXPECT_TRUE(IsHostPlane(*xplane_cupti)); } TEST(XplaneutilsTest, TestIsDevicePlane) { XSpace xspace; auto xplane_host_thread = FindOrAddMutablePlaneWithName(&xspace, "/host:CPU"); auto xplane_device_thread = FindOrAddMutablePlaneWithName(&xspace, "/device:TPU"); auto xplane_task_env_thread = FindOrAddMutablePlaneWithName(&xspace, "Task Environment"); auto xplane_custom_prefix = FindOrAddMutablePlaneWithName(&xspace, "/device:CUSTOM:123"); auto xplane_legacy_custom = FindOrAddMutablePlaneWithName(&xspace, "/custom:456"); EXPECT_FALSE(IsDevicePlane(*xplane_host_thread)); EXPECT_FALSE(IsDevicePlane(*xplane_task_env_thread)); EXPECT_TRUE(IsDevicePlane(*xplane_device_thread)); EXPECT_TRUE(IsDevicePlane(*xplane_custom_prefix)); EXPECT_TRUE(IsDevicePlane(*xplane_legacy_custom)); } TEST(XplaneUtilsTest, XPlaneGroupingPropagatesStep) { XPlane xplane; XPlaneBuilder builder(&xplane); XStatMetadata* kGroupId = builder.GetOrCreateStatMetadata(GetStatTypeStr(StatType::kGroupId)); XLineBuilder line = builder.GetOrCreateLine(1); line.SetName(kStepLineName); XEventMetadata* event_metadata = builder.GetOrCreateEventMetadata(1); event_metadata->set_name("Step 1"); XEventBuilder event_builder = line.AddEvent(*event_metadata); event_builder.AddStatValue(*kGroupId, 1); event_builder.SetDurationNs(100); event_builder.SetOffsetNs(100); XEventMetadata* event_metadata2 = builder.GetOrCreateEventMetadata(2); event_metadata2->set_name("Step 2"); XEventBuilder event_builder2 = line.AddEvent(*event_metadata2); event_builder2.AddStatValue(*kGroupId, 2); event_builder2.SetDurationNs(100); event_builder2.SetOffsetNs(300); XPlane aggregated_xplane; AggregateXPlane(xplane, aggregated_xplane); #if defined(PLATFORM_GOOGLE) EXPECT_THAT(aggregated_xplane, Partially(EqualsProto(xplane))); #endif } TEST(XplaneUtilsTest, XPlaneGroupingPropagatesGroupId) { XPlane xplane; XPlaneBuilder builder(&xplane); XEventMetadata* event_metadata1 = builder.GetOrCreateEventMetadata(1); event_metadata1->set_name("EventMetadata1"); XStatMetadata* kGroupId = builder.GetOrCreateStatMetadata(GetStatTypeStr(StatType::kGroupId)); XLineBuilder line = builder.GetOrCreateLine(1); line.SetName(kXlaOpLineName); XEventBuilder event_builder = line.AddEvent(*event_metadata1); event_builder.SetDurationNs(100); event_builder.SetOffsetNs(100); event_builder.AddStatValue(*kGroupId, 1); XEventBuilder event_builder2 = line.AddEvent(*event_metadata1); event_builder2.AddStatValue(*kGroupId, 2); event_builder2.SetDurationNs(100); event_builder2.SetOffsetNs(300); XPlane aggregated_xplane; AggregateXPlane(xplane, aggregated_xplane); EXPECT_THAT(aggregated_xplane.lines(), UnorderedElementsAre(Property(&XLine::events, SizeIs(2)))); XPlaneVisitor visitor = CreateTfXPlaneVisitor(&aggregated_xplane); visitor.ForEachLine([&](const XLineVisitor& line) { line.ForEachEvent([&](const XEventVisitor& event) { EXPECT_TRUE(event.GetStat(StatType::kGroupId).has_value()); }); }); } } } }
2,625
cpp
google/tsl
timestamp_utils
tsl/profiler/utils/timestamp_utils.cc
tsl/profiler/utils/timestamp_utils_test.cc
#ifndef TENSORFLOW_TSL_PROFILER_UTILS_TIMESTAMP_UTILS_H_ #define TENSORFLOW_TSL_PROFILER_UTILS_TIMESTAMP_UTILS_H_ #include <cstdint> #include "tsl/profiler/protobuf/xplane.pb.h" namespace tsl { namespace profiler { void SetSessionTimestamps(uint64_t start_walltime_ns, uint64_t stop_walltime_ns, tensorflow::profiler::XSpace& space); } } #endif #include "tsl/profiler/utils/timestamp_utils.h" #include <cstdint> #include "absl/log/log.h" #include "tsl/profiler/protobuf/xplane.pb.h" #include "tsl/profiler/utils/xplane_builder.h" #include "tsl/profiler/utils/xplane_schema.h" #include "tsl/profiler/utils/xplane_utils.h" namespace tsl { namespace profiler { void SetSessionTimestamps(uint64_t start_walltime_ns, uint64_t stop_walltime_ns, tensorflow::profiler::XSpace& space) { if (start_walltime_ns != 0 && stop_walltime_ns != 0) { tsl::profiler::XPlaneBuilder plane( tsl::profiler::FindOrAddMutablePlaneWithName( &space, tsl::profiler::kTaskEnvPlaneName)); plane.AddStatValue(*plane.GetOrCreateStatMetadata( GetTaskEnvStatTypeStr(kEnvProfileStartTime)), start_walltime_ns); plane.AddStatValue(*plane.GetOrCreateStatMetadata( GetTaskEnvStatTypeStr(kEnvProfileStopTime)), stop_walltime_ns); } else { LOG(WARNING) << "Not Setting Session Timestamps, (start_walltime_ns, " "stop_walltime_ns) : " << start_walltime_ns << ", " << stop_walltime_ns; } } } }
#include "tsl/profiler/utils/timestamp_utils.h" #include "tsl/platform/test.h" #include "tsl/profiler/utils/xplane_schema.h" #include "tsl/profiler/utils/xplane_utils.h" #include "tsl/profiler/utils/xplane_visitor.h" namespace tsl { namespace profiler { using ::testing::Eq; TEST(TimestampUtilsTest, StartAndStopTimestampAreAdded) { XSpace xspace; SetSessionTimestamps(1000, 2000, xspace); const XPlane* xplane = FindPlaneWithName(xspace, kTaskEnvPlaneName); XPlaneVisitor visitor(xplane, {}, {FindTaskEnvStatType}); auto start_time = visitor.GetStat(TaskEnvStatType::kEnvProfileStartTime); auto stop_time = visitor.GetStat(TaskEnvStatType::kEnvProfileStopTime); EXPECT_THAT(start_time->IntOrUintValue(), Eq(1000)); EXPECT_THAT(stop_time->IntOrUintValue(), Eq(2000)); } } }
2,626
cpp
google/tsl
xplane_builder
tsl/profiler/utils/xplane_builder.cc
tsl/profiler/utils/xplane_builder_test.cc
#ifndef TENSORFLOW_TSL_PROFILER_UTILS_XPLANE_BUILDER_H_ #define TENSORFLOW_TSL_PROFILER_UTILS_XPLANE_BUILDER_H_ #include <stddef.h> #include <cstdint> #include <string> #include <utility> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/meta/type_traits.h" #include "absl/strings/numbers.h" #include "absl/strings/string_view.h" #include "absl/types/optional.h" #include "tsl/platform/macros.h" #include "tsl/platform/protobuf.h" #include "tsl/platform/types.h" #include "tsl/profiler/protobuf/xplane.pb.h" #include "tsl/profiler/utils/math_utils.h" #include "tsl/profiler/utils/timespan.h" namespace tsl { namespace profiler { using tensorflow::profiler::XEvent; using tensorflow::profiler::XEventMetadata; using tensorflow::profiler::XLine; using tensorflow::profiler::XPlane; using tensorflow::profiler::XSpace; using tensorflow::profiler::XStat; using tensorflow::profiler::XStatMetadata; class XPlaneBuilder; template <typename T> class XStatsBuilder { public: explicit XStatsBuilder(T* stats_owner, XPlaneBuilder* stats_metadata_owner) : stats_owner_(stats_owner), stats_metadata_owner_(stats_metadata_owner) {} template <typename ValueT> void AddStatValue(const XStatMetadata& metadata, ValueT&& value) { SetStatValue(std::forward<ValueT>(value), AddStat(metadata)); } template <typename ValueT> void SetOrAddStatValue(const XStatMetadata& metadata, ValueT&& value) { SetStatValue(std::forward<ValueT>(value), FindOrAddStat(metadata)); } void AddStat(const XStatMetadata& metadata, const XStat& src_stat, const XPlane& src_plane) { CopyStatValue(src_stat, src_plane, AddStat(metadata)); } void SetOrAddStat(const XStatMetadata& metadata, const XStat& src_stat, const XPlane& src_plane) { CopyStatValue(src_stat, src_plane, FindOrAddStat(metadata)); } void ParseAndAddStatValue(const XStatMetadata& metadata, absl::string_view value) { int64_t int_value; uint64 uint_value; double double_value; if (absl::SimpleAtoi(value, &int_value)) { AddStatValue(metadata, int_value); } else if (absl::SimpleAtoi(value, &uint_value)) { AddStatValue(metadata, uint_value); } else if (absl::SimpleAtod(value, &double_value)) { AddStatValue(metadata, double_value); } else { AddStatValue(metadata, GetOrCreateStatMetadata(value)); } } void ReserveStats(size_t num_stats) { stats_owner_->mutable_stats()->Reserve(num_stats); } template <typename ForEachStatFunc> void ForEachStat(ForEachStatFunc&& for_each_stat) { for (XStat& stat : *stats_owner_->mutable_stats()) { for_each_stat(&stat); } } const XStat* GetStat(const XStatMetadata& stat_metadata) const { for (auto& stat : *stats_owner_->mutable_stats()) { if (stat.metadata_id() == stat_metadata.id()) { return &stat; } } return nullptr; } static uint64 IntOrUintValue(const XStat& stat) { return stat.value_case() == XStat::kUint64Value ? stat.uint64_value() : stat.int64_value(); } absl::string_view StrOrRefValue(const XStat& stat); private: XStat* AddStat(const XStatMetadata& metadata) { XStat* stat = stats_owner_->add_stats(); stat->set_metadata_id(metadata.id()); return stat; } XStat* FindOrAddStat(const XStatMetadata& metadata) { for (auto& stat : *stats_owner_->mutable_stats()) { if (stat.metadata_id() == metadata.id()) { return &stat; } } return AddStat(metadata); } static void SetStatValue(bool value, XStat* stat) { stat->set_int64_value(value); } template <typename Int, std::enable_if_t<absl::conjunction<std::is_integral<Int>, std::is_signed<Int>>::value, bool> = true> static void SetStatValue(Int value, XStat* stat) { stat->set_int64_value(value); } template <typename UInt, std::enable_if_t< absl::conjunction<std::is_integral<UInt>, absl::negation<std::is_signed<UInt>>>::value, bool> = true> static void SetStatValue(UInt value, XStat* stat) { stat->set_uint64_value(value); } static void SetStatValue(double value, XStat* stat) { stat->set_double_value(value); } static void SetStatValue(const char* value, XStat* stat) { stat->set_str_value(std::string(value)); } static void SetStatValue(absl::string_view value, XStat* stat) { stat->set_str_value(std::string(value)); } static void SetStatValue(std::string&& value, XStat* stat) { stat->set_str_value(std::move(value)); } static void SetStatValue(const XStatMetadata& value, XStat* stat) { stat->set_ref_value(value.id()); } static void SetStatValue(const protobuf::MessageLite& proto, XStat* stat) { auto* bytes = stat->mutable_bytes_value(); proto.SerializeToString(bytes); } void CopyStatValue(const XStat& src_stat, const XPlane& src_plane, XStat* dst_stat) { switch (src_stat.value_case()) { case XStat::VALUE_NOT_SET: break; case XStat::kInt64Value: dst_stat->set_int64_value(src_stat.int64_value()); break; case XStat::kUint64Value: dst_stat->set_uint64_value(src_stat.uint64_value()); break; case XStat::kDoubleValue: dst_stat->set_double_value(src_stat.double_value()); break; case XStat::kStrValue: dst_stat->set_str_value(src_stat.str_value()); break; case XStat::kRefValue: { const auto& stat_metadata_by_id = src_plane.stat_metadata(); const auto it = stat_metadata_by_id.find(src_stat.ref_value()); if (TF_PREDICT_TRUE(it != stat_metadata_by_id.end())) { absl::string_view value = it->second.name(); dst_stat->set_ref_value(GetOrCreateStatMetadata(value).id()); } break; } case XStat::kBytesValue: dst_stat->set_bytes_value(src_stat.bytes_value()); break; } } const XStatMetadata& GetOrCreateStatMetadata(absl::string_view value); T* stats_owner_; XPlaneBuilder* stats_metadata_owner_; }; class XEventBuilder : public XStatsBuilder<XEvent> { public: XEventBuilder(const XLine* line, XPlaneBuilder* plane, XEvent* event) : XStatsBuilder<XEvent>(event, plane), line_(line), event_(event) {} int64_t LineTimestampPs() const { return NanoToPico(line_->timestamp_ns()); } int64_t OffsetPs() const { return event_->offset_ps(); } int64_t TimestampPs() const { return LineTimestampPs() + OffsetPs(); } int64_t DurationPs() const { return event_->duration_ps(); } int64_t MetadataId() const { return event_->metadata_id(); } void SetOffsetPs(int64_t offset_ps) { event_->set_offset_ps(offset_ps); } void SetOffsetNs(int64_t offset_ns) { SetOffsetPs(NanoToPico(offset_ns)); } void SetTimestampPs(int64_t timestamp_ps) { SetOffsetPs(timestamp_ps - LineTimestampPs()); } void SetTimestampNs(int64_t timestamp_ns) { SetOffsetNs(timestamp_ns - line_->timestamp_ns()); } void SetNumOccurrences(int64_t num_occurrences) { event_->set_num_occurrences(num_occurrences); } void SetDurationPs(int64_t duration_ps) { event_->set_duration_ps(duration_ps); } void SetDurationNs(int64_t duration_ns) { SetDurationPs(NanoToPico(duration_ns)); } void SetEndTimestampPs(int64_t end_timestamp_ps) { SetDurationPs(end_timestamp_ps - TimestampPs()); } void SetEndTimestampNs(int64_t end_timestamp_ns) { SetDurationPs(NanoToPico(end_timestamp_ns - line_->timestamp_ns()) - event_->offset_ps()); } Timespan GetTimespan() const { return Timespan(TimestampPs(), DurationPs()); } void SetTimespan(Timespan timespan) { SetTimestampPs(timespan.begin_ps()); SetDurationPs(timespan.duration_ps()); } bool operator<(const XEventBuilder& other) const { return GetTimespan() < other.GetTimespan(); } private: const XLine* line_; XEvent* event_; }; class XLineBuilder { public: explicit XLineBuilder(XLine* line, XPlaneBuilder* plane) : line_(line), plane_(plane) {} XPlaneBuilder* Plane() const { return plane_; } int64_t Id() const { return line_->id(); } void SetId(int64_t id) { line_->set_id(id); } int64_t NumEvents() const { return line_->events_size(); } absl::string_view Name() const { return line_->name(); } void SetName(absl::string_view name) { line_->set_name(std::string(name)); } void SetNameIfEmpty(absl::string_view name) { if (line_->name().empty()) SetName(name); } int64_t TimestampNs() const { return line_->timestamp_ns(); } void SetTimestampNs(int64_t timestamp_ns) { line_->set_timestamp_ns(timestamp_ns); } void SetTimestampNsAndAdjustEventOffsets(int64_t timestamp_ns); void SetDurationPs(int64_t duration_ps) { line_->set_duration_ps(duration_ps); } void ReserveEvents(size_t num_events) { line_->mutable_events()->Reserve(num_events); } void SetDisplayNameIfEmpty(absl::string_view display_name) { if (line_->display_name().empty()) { line_->set_display_name(std::string(display_name)); } } XEventBuilder AddEvent(const XEventMetadata& metadata); XEventBuilder AddEvent(const XEvent& event); template <typename ForEachEventFunc> void ForEachEvent(ForEachEventFunc&& for_each_event) { for (XEvent& event : *line_->mutable_events()) { for_each_event(XEventBuilder(line_, plane_, &event)); } } private: XLine* line_; XPlaneBuilder* plane_; }; class XPlaneBuilder : public XStatsBuilder<XPlane> { public: explicit XPlaneBuilder(XPlane* plane); int64_t Id() const { return plane_->id(); } void SetId(int64_t id) { plane_->set_id(id); } absl::string_view Name() const { return plane_->name(); } void SetName(absl::string_view name) { plane_->set_name(std::string(name)); } void ReserveLines(size_t num_lines) { plane_->mutable_lines()->Reserve(num_lines); } template <typename ForEachLineFunc> void ForEachLine(ForEachLineFunc&& for_each_line) { for (XLine& line : *plane_->mutable_lines()) { for_each_line(XLineBuilder(&line, this)); } } XLineBuilder GetOrCreateLine(int64_t line_id); XEventMetadata* CreateEventMetadata(); XEventMetadata* GetOrCreateEventMetadata(int64_t metadata_id); XEventMetadata* GetOrCreateEventMetadata(absl::string_view name); XEventMetadata* GetOrCreateEventMetadata(std::string&& name); XEventMetadata* GetOrCreateEventMetadata(const char* name) { return GetOrCreateEventMetadata(absl::string_view(name)); } std::vector<XEventMetadata*> GetOrCreateEventsMetadata( const std::vector<absl::string_view>& names); XEventMetadata* GetEventMetadata(absl::string_view name) const; XStatMetadata* GetStatMetadata(absl::string_view name) const; const XStatMetadata* GetStatMetadata(int64_t metadata_id) const; XStatMetadata* CreateStatMetadata(); XStatMetadata* GetOrCreateStatMetadata(int64_t metadata_id); XStatMetadata* GetOrCreateStatMetadata(absl::string_view name); XStatMetadata* GetOrCreateStatMetadata(std::string&& name); XStatMetadata* GetOrCreateStatMetadata(const char* name) { return GetOrCreateStatMetadata(absl::string_view(name)); } private: XPlane* plane_; int64_t last_event_metadata_id_ = 0LL; int64_t last_stat_metadata_id_ = 0LL; absl::flat_hash_map<std::string, XEventMetadata*> event_metadata_by_name_; absl::flat_hash_map<std::string, XStatMetadata*> stat_metadata_by_name_; absl::flat_hash_map<int64_t, XLine*> lines_by_id_; }; template <typename T> const XStatMetadata& XStatsBuilder<T>::GetOrCreateStatMetadata( absl::string_view value) { return *stats_metadata_owner_->GetOrCreateStatMetadata(value); } template <typename T> absl::string_view XStatsBuilder<T>::StrOrRefValue(const XStat& stat) { switch (stat.value_case()) { case XStat::kStrValue: return stat.str_value(); case XStat::kRefValue: { auto* ref_stat = stats_metadata_owner_->GetStatMetadata(stat.ref_value()); return ref_stat ? ref_stat->name() : absl::string_view(); } case XStat::kInt64Value: case XStat::kUint64Value: case XStat::kDoubleValue: case XStat::kBytesValue: case XStat::VALUE_NOT_SET: return absl::string_view(); } } } } #endif #include "tsl/profiler/utils/xplane_builder.h" #include <algorithm> #include <string> #include <utility> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/strings/string_view.h" #include "absl/types/optional.h" #include "tsl/platform/types.h" #include "tsl/profiler/protobuf/xplane.pb.h" #include "tsl/profiler/utils/math_utils.h" namespace tsl { namespace profiler { XPlaneBuilder::XPlaneBuilder(XPlane* plane) : XStatsBuilder<XPlane>(plane, this), plane_(plane) { for (auto& id_and_metadata : *plane->mutable_event_metadata()) { auto& metadata = id_and_metadata.second; last_event_metadata_id_ = std::max<int64_t>(last_event_metadata_id_, metadata.id()); if (!metadata.name().empty()) { event_metadata_by_name_.try_emplace(metadata.name(), &metadata); } } for (auto& id_and_metadata : *plane->mutable_stat_metadata()) { auto& metadata = id_and_metadata.second; last_stat_metadata_id_ = std::max<int64_t>(last_stat_metadata_id_, metadata.id()); if (!metadata.name().empty()) { stat_metadata_by_name_.try_emplace(metadata.name(), &metadata); } } for (XLine& line : *plane->mutable_lines()) { lines_by_id_.try_emplace(line.id(), &line); } } XEventMetadata* XPlaneBuilder::GetOrCreateEventMetadata(int64_t metadata_id) { XEventMetadata& metadata = (*plane_->mutable_event_metadata())[metadata_id]; metadata.set_id(metadata_id); return &metadata; } XEventMetadata* XPlaneBuilder::CreateEventMetadata() { return GetOrCreateEventMetadata(++last_event_metadata_id_); } XEventMetadata* XPlaneBuilder::GetOrCreateEventMetadata( absl::string_view name) { XEventMetadata*& metadata = event_metadata_by_name_[name]; if (metadata == nullptr) { metadata = CreateEventMetadata(); metadata->set_name(std::string(name)); } return metadata; } XEventMetadata* XPlaneBuilder::GetOrCreateEventMetadata(std::string&& name) { XEventMetadata*& metadata = event_metadata_by_name_[name]; if (metadata == nullptr) { metadata = CreateEventMetadata(); metadata->set_name(std::move(name)); } return metadata; } std::vector<XEventMetadata*> XPlaneBuilder::GetOrCreateEventsMetadata( const std::vector<absl::string_view>& names) { std::vector<XEventMetadata*> metadata; metadata.reserve(names.size()); for (absl::string_view name : names) { metadata.push_back(GetOrCreateEventMetadata(name)); } return metadata; } XEventMetadata* XPlaneBuilder::GetEventMetadata(absl::string_view name) const { auto result = event_metadata_by_name_.find(name); if (result == event_metadata_by_name_.end()) return nullptr; return result->second; } XStatMetadata* XPlaneBuilder::GetStatMetadata(absl::string_view name) const { auto result = stat_metadata_by_name_.find(name); if (result == stat_metadata_by_name_.end()) return nullptr; return result->second; } XStatMetadata* XPlaneBuilder::GetOrCreateStatMetadata(int64_t metadata_id) { XStatMetadata& metadata = (*plane_->mutable_stat_metadata())[metadata_id]; metadata.set_id(metadata_id); return &metadata; } const XStatMetadata* XPlaneBuilder::GetStatMetadata(int64_t metadata_id) const { auto result = plane_->stat_metadata().find(metadata_id); if (result == plane_->stat_metadata().end()) return nullptr; return &(result->second); } XStatMetadata* XPlaneBuilder::CreateStatMetadata() { return GetOrCreateStatMetadata(++last_stat_metadata_id_); } XStatMetadata* XPlaneBuilder::GetOrCreateStatMetadata(absl::string_view name) { XStatMetadata*& metadata = stat_metadata_by_name_[name]; if (metadata == nullptr) { metadata = CreateStatMetadata(); metadata->set_name(std::string(name)); } return metadata; } XStatMetadata* XPlaneBuilder::GetOrCreateStatMetadata(std::string&& name) { XStatMetadata*& metadata = stat_metadata_by_name_[name]; if (metadata == nullptr) { metadata = CreateStatMetadata(); metadata->set_name(std::move(name)); } return metadata; } XLineBuilder XPlaneBuilder::GetOrCreateLine(int64_t line_id) { XLine*& line = lines_by_id_[line_id]; if (line == nullptr) { line = plane_->add_lines(); line->set_id(line_id); } return XLineBuilder(line, this); } XEventBuilder XLineBuilder::AddEvent(const XEventMetadata& metadata) { XEvent* event = line_->add_events(); event->set_metadata_id(metadata.id()); return XEventBuilder(line_, plane_, event); } XEventBuilder XLineBuilder::AddEvent(const XEvent& event) { XEvent* new_event = line_->add_events(); *new_event = event; return XEventBuilder(line_, plane_, new_event); } void XLineBuilder::SetTimestampNsAndAdjustEventOffsets(int64_t timestamp_ns) { int64_t offset_ps = NanoToPico(line_->timestamp_ns() - timestamp_ns); line_->set_timestamp_ns(timestamp_ns); if (offset_ps) { for (auto& event : *line_->mutable_events()) { event.set_offset_ps(event.offset_ps() + offset_ps); } } } } }
#include "tsl/profiler/utils/xplane_builder.h" #include <string> #include "absl/strings/string_view.h" #include "tsl/platform/test.h" #include "tsl/profiler/protobuf/xplane.pb.h" #include "tsl/profiler/utils/xplane_visitor.h" namespace tsl { namespace profiler { namespace { TEST(TimespanTests, NonInstantSpanIncludesSingleTimeTests) { XPlane plane; XPlaneBuilder xplane_builder(&plane); XLineBuilder xline_builder = xplane_builder.GetOrCreateLine(0); XEventBuilder event_builder = xline_builder.AddEvent( *xplane_builder.GetOrCreateEventMetadata("1st event")); constexpr auto kBoolStat = true; constexpr auto kInt32Stat = int32_t{1234}; constexpr auto kInt64Stat = int64_t{1234} << 32; constexpr auto kUint32Stat = uint32_t{5678}; constexpr auto kUint64Stat = uint64_t{5678} << 32; constexpr auto kFloatStat = 0.5f; constexpr auto kDoubleStat = 1.0; constexpr auto kStringStat = "abc"; constexpr auto kRefStat = "referenced abc"; event_builder.AddStatValue( *xplane_builder.GetOrCreateStatMetadata("bool stat"), kBoolStat); event_builder.AddStatValue( *xplane_builder.GetOrCreateStatMetadata("int32 stat"), kInt32Stat); event_builder.AddStatValue( *xplane_builder.GetOrCreateStatMetadata("int64 stat"), kInt64Stat); event_builder.AddStatValue( *xplane_builder.GetOrCreateStatMetadata("uint32 stat"), kUint32Stat); event_builder.AddStatValue( *xplane_builder.GetOrCreateStatMetadata("uint64 stat"), kUint64Stat); event_builder.AddStatValue( *xplane_builder.GetOrCreateStatMetadata("string stat"), kStringStat); event_builder.AddStatValue( *xplane_builder.GetOrCreateStatMetadata("float stat"), kFloatStat); event_builder.AddStatValue( *xplane_builder.GetOrCreateStatMetadata("double stat"), kDoubleStat); event_builder.AddStatValue( *xplane_builder.GetOrCreateStatMetadata("ref stat"), *xplane_builder.GetOrCreateStatMetadata(kRefStat)); XPlaneVisitor xplane_visitor(&plane); EXPECT_EQ(xplane_visitor.NumLines(), 1); int num_stats = 0; xplane_visitor.ForEachLine([&](const XLineVisitor& xline) { xline.ForEachEvent([&](const XEventVisitor& xevent) { EXPECT_EQ(xevent.Name(), "1st event"); xevent.ForEachStat([&](const XStatVisitor& stat) { if (stat.Name() == "bool stat") { EXPECT_EQ(stat.BoolValue(), kBoolStat); num_stats++; } else if (stat.Name() == "int32 stat") { EXPECT_EQ(stat.IntValue(), kInt32Stat); EXPECT_EQ(stat.IntOrUintValue(), kInt32Stat); num_stats++; } else if (stat.Name() == "int64 stat") { EXPECT_EQ(stat.IntValue(), kInt64Stat); EXPECT_EQ(stat.IntOrUintValue(), kInt64Stat); num_stats++; } else if (stat.Name() == "uint32 stat") { EXPECT_EQ(stat.UintValue(), kUint32Stat); EXPECT_EQ(stat.IntOrUintValue(), kUint32Stat); num_stats++; } else if (stat.Name() == "uint64 stat") { EXPECT_EQ(stat.UintValue(), kUint64Stat); EXPECT_EQ(stat.IntOrUintValue(), kUint64Stat); num_stats++; } else if (stat.Name() == "string stat") { EXPECT_EQ(stat.StrOrRefValue(), kStringStat); num_stats++; } else if (stat.Name() == "float stat") { EXPECT_EQ(stat.DoubleValue(), kFloatStat); num_stats++; } else if (stat.Name() == "double stat") { EXPECT_EQ(stat.DoubleValue(), kDoubleStat); num_stats++; } else if (stat.Name() == "ref stat") { EXPECT_EQ(stat.StrOrRefValue(), kRefStat); num_stats++; } }); }); }); EXPECT_EQ(num_stats, 9); } } } }
2,627
cpp
google/tsl
preprocess_xplane
tsl/profiler/utils/preprocess_xplane.cc
tsl/profiler/utils/preprocess_xplane_test.cc
#ifndef TENSORFLOW_TSL_PROFILER_UTILS_PREPROCESS_XPLANE_H_ #define TENSORFLOW_TSL_PROFILER_UTILS_PREPROCESS_XPLANE_H_ #include <cstdint> #include <memory> #include <optional> #include <tuple> #include <type_traits> #include <utility> #include <variant> #include <vector> #include "absl/hash/hash.h" #include "absl/log/log.h" #include "absl/memory/memory.h" #include "absl/strings/match.h" #include "absl/strings/string_view.h" #include "absl/types/optional.h" #include "tsl/profiler/lib/context_types.h" #include "tsl/profiler/protobuf/xplane.pb.h" #include "tsl/profiler/utils/tpu_xplane_utils.h" #include "tsl/profiler/utils/trace_utils.h" #include "tsl/profiler/utils/xplane_builder.h" #include "tsl/profiler/utils/xplane_mutators.h" #include "tsl/profiler/utils/xplane_schema.h" namespace tsl { namespace profiler { static constexpr uint32_t kRunIdMask = (1U << 27) - 1; class XplaneRootEventMutatorFactory : public XplaneEventMutatorFactory { public: static std::unique_ptr<XplaneEventMutatorFactory> CreateFactory( HostEventType event_type, int64_t root_level) { return absl::WrapUnique( new XplaneRootEventMutatorFactory(event_type, root_level)); } std::vector<std::unique_ptr<XplaneEventMutator>> CreateMutators( XPlaneBuilder& xplane) const override { std::vector<std::unique_ptr<XplaneEventMutator>> mutators; if (auto* event_metadata = xplane.GetEventMetadata(GetHostEventTypeStr(event_type_))) { XStatMetadata* root_metadata = xplane.GetOrCreateStatMetadata(GetStatTypeStr(StatType::kIsRoot)); mutators.emplace_back(std::make_unique<XplaneRootEventMutator>( event_metadata, *root_metadata, root_level_)); } return mutators; } private: explicit XplaneRootEventMutatorFactory(HostEventType event_type, int64_t root_level) : event_type_(event_type), root_level_(root_level) {} class XplaneRootEventMutator : public XplaneEventMutator { public: XplaneRootEventMutator(XEventMetadata* event_metadata, XStatMetadata& root_stats_metadata, int64_t root_level) : XplaneEventMutator(event_metadata), root_stats_metadata_(root_stats_metadata), root_level_(root_level) {} void Mutate(XEventBuilder& event_builder) override { event_builder.SetOrAddStatValue(root_stats_metadata_, root_level_); } void MutateEventsInLine(XLineBuilder& line) override { CHECK(false); } private: XStatMetadata& root_stats_metadata_; int64_t root_level_; }; HostEventType event_type_; int64_t root_level_; }; template <typename StatValueType, StatType kStatId> class XContextStatsAccessor { public: using value_type = StatValueType; bool Initialize(XPlaneBuilder& xplane) { stats_metadata_ = xplane.GetStatMetadata(GetStatTypeStr(kStatId)); return stats_metadata_; } std::optional<StatValueType> GetStat(XEventBuilder& event_builder) { if (stats_metadata_ == nullptr) return std::nullopt; auto* stat = event_builder.GetStat(*stats_metadata_); if (stat == nullptr) return std::nullopt; if constexpr (std::is_integral_v<StatValueType>) { return event_builder.IntOrUintValue(*stat); } else { return event_builder.StrOrRefValue(*stat); } } private: XStatMetadata* stats_metadata_ = nullptr; }; template <typename StatValueType, StatType kStatId, StatValueType kDefaultValue> class XContextStatsAccessorWithDefault { public: using value_type = StatValueType; bool Initialize(XPlaneBuilder& xplane) { stats_metadata_ = xplane.GetStatMetadata(GetStatTypeStr(kStatId)); return true; } std::optional<StatValueType> GetStat(XEventBuilder& event_builder) { if (stats_metadata_ == nullptr) return kDefaultValue; auto* stat = event_builder.GetStat(*stats_metadata_); if (stat == nullptr) return kDefaultValue; if constexpr (std::is_integral_v<StatValueType>) { return event_builder.IntOrUintValue(*stat); } else { return event_builder.StrOrRefValue(*stat); } } private: XStatMetadata* stats_metadata_ = nullptr; }; template <std::size_t... Idx> auto make_index_dispatcher(std::index_sequence<Idx...>) { return [](auto&& f) { (f(std::integral_constant<std::size_t, Idx>{}), ...); }; } template <std::size_t N> auto make_index_dispatcher() { return make_index_dispatcher(std::make_index_sequence<N>{}); } template <typename Tuple, typename Func> void for_each(Tuple&& t, Func&& f) { constexpr auto n = std::tuple_size<std::decay_t<Tuple>>::value; auto dispatcher = make_index_dispatcher<n>(); dispatcher([&f, &t](auto idx) { f(std::get<idx>(std::forward<Tuple>(t))); }); } template <HostEventType producer_event, HostEventType consumer_event, ContextType context_type, bool unique_stats, typename... StatsAccessorTypes> class XplaneConnectedEventMutatorFactory : public XplaneEventMutatorFactory { public: static std::unique_ptr<XplaneEventMutatorFactory> CreateFactory() { return absl::WrapUnique(new XplaneConnectedEventMutatorFactory()); } using StatsAccessors = std::tuple<StatsAccessorTypes...>; std::vector<std::unique_ptr<XplaneEventMutator>> CreateMutators( XPlaneBuilder& xplane) const override { StatsAccessors stats_accessors; bool all_required_stats_exist = true; auto check_stats_meta = [&all_required_stats_exist, &xplane](auto&& accessor) { all_required_stats_exist = all_required_stats_exist && accessor.Initialize(xplane); }; for_each(stats_accessors, check_stats_meta); if (!all_required_stats_exist) return {}; XEventMetadata* producer_event_metadata = xplane.GetEventMetadata(GetHostEventTypeStr(producer_event)); XEventMetadata* consumer_event_metadata = xplane.GetEventMetadata(GetHostEventTypeStr(consumer_event)); std::vector<std::unique_ptr<XplaneEventMutator>> mutators; if (producer_event_metadata) { XStatMetadata* context_type_metadata = xplane.GetOrCreateStatMetadata( GetStatTypeStr(StatType::kProducerType)); XStatMetadata* context_id_metadata = xplane.GetOrCreateStatMetadata(GetStatTypeStr(StatType::kProducerId)); mutators.emplace_back(std::make_unique<XplaneConnectedEventMutator>( producer_event_metadata, *context_type_metadata, *context_id_metadata, stats_accessors)); } if (consumer_event_metadata) { XStatMetadata* context_type_metadata = xplane.GetOrCreateStatMetadata( GetStatTypeStr(StatType::kConsumerType)); XStatMetadata* context_id_metadata = xplane.GetOrCreateStatMetadata(GetStatTypeStr(StatType::kConsumerId)); mutators.emplace_back(std::make_unique<XplaneConnectedEventMutator>( consumer_event_metadata, *context_type_metadata, *context_id_metadata, stats_accessors)); } return mutators; } private: XplaneConnectedEventMutatorFactory() = default; class XplaneConnectedEventMutator : public XplaneEventMutator { public: XplaneConnectedEventMutator(XEventMetadata* event_metadata, XStatMetadata& context_type_metadata, XStatMetadata& context_id_metadata, const StatsAccessors& accessors) : XplaneEventMutator(event_metadata), context_type_metadata_(context_type_metadata), context_id_metadata_(context_id_metadata), accessors_(accessors) {} void Mutate(XEventBuilder& event_builder) override { bool all_required_stats_exist = true; std::vector<std::variant<absl::string_view, uint64_t>> required_stats; auto check_stats_meta = [&all_required_stats_exist, &required_stats, &event_builder](auto&& accessor) { if (all_required_stats_exist == false) return; auto stats_data = accessor.GetStat(event_builder); if (!stats_data) { all_required_stats_exist = false; } else { required_stats.emplace_back(*stats_data); } }; for_each(accessors_, check_stats_meta); if (!all_required_stats_exist) return; int64_t context_id; if constexpr (unique_stats) { context_id = absl::HashOf(required_stats); } else { context_id = absl::HashOf(producer_event, consumer_event, required_stats); } event_builder.SetOrAddStatValue(context_type_metadata_, static_cast<int64_t>(context_type)); event_builder.SetOrAddStatValue(context_id_metadata_, context_id); } void MutateEventsInLine(XLineBuilder& line) override { CHECK(false); } private: XStatMetadata& context_type_metadata_; XStatMetadata& context_id_metadata_; StatsAccessors accessors_; }; }; template <HostEventType event_type> class HostRunIdMutatorFactory : public XplaneEventMutatorFactory { public: static std::unique_ptr<XplaneEventMutatorFactory> CreateFactory() { return absl::WrapUnique(new HostRunIdMutatorFactory()); } std::vector<std::unique_ptr<XplaneEventMutator>> CreateMutators( XPlaneBuilder& xplane) const override { std::vector<std::unique_ptr<XplaneEventMutator>> mutators; if (auto* event_metadata = xplane.GetEventMetadata(GetHostEventTypeStr(event_type))) { XContextStatsAccessor<int64_t, StatType::kRunId> run_id_stats_accessor; if (run_id_stats_accessor.Initialize(xplane)) { XStatMetadata* run_id_metadata = xplane.GetOrCreateStatMetadata(GetStatTypeStr(StatType::kRunId)); mutators.emplace_back(std::make_unique<HostRunIdMutator>( event_metadata, run_id_stats_accessor, *run_id_metadata)); } } return mutators; } private: HostRunIdMutatorFactory() = default; class HostRunIdMutator : public XplaneEventMutator { public: HostRunIdMutator( XEventMetadata* event_metadata, XContextStatsAccessor<int64_t, StatType::kRunId> run_id_stats_accessor, XStatMetadata& run_id_metadata) : XplaneEventMutator(event_metadata), run_id_stats_accessor_(run_id_stats_accessor), run_id_metadata_(run_id_metadata) {} void Mutate(XEventBuilder& event_builder) override { auto run_id = run_id_stats_accessor_.GetStat(event_builder); if (!run_id) return; int64_t fixed_run_id = ((uint64_t)run_id.value() & kRunIdMask); event_builder.SetOrAddStatValue(run_id_metadata_, fixed_run_id); } void MutateEventsInLine(XLineBuilder& line) override { CHECK(false); } private: XContextStatsAccessor<int64_t, StatType::kRunId> run_id_stats_accessor_; XStatMetadata& run_id_metadata_; }; }; class TpuModuleLineMutatorFactory : public XplaneEventMutatorFactory { public: static std::unique_ptr<XplaneEventMutatorFactory> CreateFactory() { return absl::WrapUnique(new TpuModuleLineMutatorFactory()); } std::vector<std::unique_ptr<XplaneEventMutator>> CreateMutators( XPlaneBuilder& xplane) const override { std::vector<std::unique_ptr<XplaneEventMutator>> mutators; if (absl::StartsWith(xplane.Name(), kTpuPlanePrefix) && GetTensorCoreId(xplane.Name()).has_value()) { if (auto device_ordinal = ParseDeviceOrdinal(xplane.Name())) { XStatMetadata* context_type_metadata = xplane.GetOrCreateStatMetadata( GetStatTypeStr(StatType::kConsumerType)); XStatMetadata* context_id_metadata = xplane.GetOrCreateStatMetadata( GetStatTypeStr(StatType::kConsumerId)); XContextStatsAccessor<uint64_t, StatType::kQueueId> queue_id_stats_accessor; XContextStatsAccessor<uint64_t, StatType::kRunId> run_id_stats_accessor; XContextStatsAccessorWithDefault<uint64_t, StatType::kCoreType, 0ULL> core_type_stats_accessor; if (queue_id_stats_accessor.Initialize(xplane) && run_id_stats_accessor.Initialize(xplane) && core_type_stats_accessor.Initialize(xplane)) { mutators.emplace_back(std::make_unique<TpuModuleLineMutator>( *device_ordinal, *context_type_metadata, *context_id_metadata, queue_id_stats_accessor, run_id_stats_accessor, core_type_stats_accessor)); } } } return mutators; } private: TpuModuleLineMutatorFactory() = default; class TpuModuleLineMutator : public XplaneEventMutator { public: TpuModuleLineMutator( uint32_t device_ordinal, XStatMetadata& context_type_metadata, XStatMetadata& context_id_metadata, XContextStatsAccessor<uint64_t, StatType::kQueueId> queue_id_stats_accessor, XContextStatsAccessor<uint64_t, StatType::kRunId> run_id_stats_accessor, XContextStatsAccessorWithDefault<uint64_t, StatType::kCoreType, 0ULL> core_type_stats_accessor) : XplaneEventMutator(nullptr), device_ordinal_(device_ordinal), context_type_metadata_(context_type_metadata), context_id_metadata_(context_id_metadata), queue_id_stats_accessor_(queue_id_stats_accessor), run_id_stats_accessor_(run_id_stats_accessor), core_type_stats_accessor_(core_type_stats_accessor) {} void Mutate(XEventBuilder& event_builder) override { CHECK(false); } void MutateEventsInLine(XLineBuilder& line) override { if (line.Name() != kXlaModuleLineName) return; line.ForEachEvent([&](XEventBuilder event) { auto run_id = run_id_stats_accessor_.GetStat(event); auto queue_id = queue_id_stats_accessor_.GetStat(event); auto core_type = core_type_stats_accessor_.GetStat(event); if (!run_id || !queue_id) return; std::vector<std::variant<absl::string_view, uint64_t>> required_stats; required_stats.reserve(4); required_stats.emplace_back(device_ordinal_); required_stats.emplace_back(*queue_id); required_stats.emplace_back(*run_id); required_stats.emplace_back(static_cast<uint64_t>(*core_type)); int64_t context_id = absl::HashOf(required_stats); event.SetOrAddStatValue(context_type_metadata_, static_cast<int64_t>(ContextType::kTpuLaunch)); event.SetOrAddStatValue(context_id_metadata_, context_id); }); } private: uint64_t device_ordinal_; XStatMetadata& context_type_metadata_; XStatMetadata& context_id_metadata_; XContextStatsAccessor<uint64_t, StatType::kQueueId> queue_id_stats_accessor_; XContextStatsAccessor<uint64_t, StatType::kRunId> run_id_stats_accessor_; XContextStatsAccessorWithDefault<uint64_t, StatType::kCoreType, 0ULL> core_type_stats_accessor_; }; }; class ThreadpoolLineMutatorFactory : public XplaneEventMutatorFactory { public: static std::unique_ptr<XplaneEventMutatorFactory> CreateFactory() { return absl::WrapUnique(new ThreadpoolLineMutatorFactory()); } std::vector<std::unique_ptr<XplaneEventMutator>> CreateMutators( XPlaneBuilder& xplane) const override { std::vector<std::unique_ptr<XplaneEventMutator>> mutators; mutators.emplace_back(std::make_unique<ThreadpoolLineMutator>(xplane)); return mutators; } private: ThreadpoolLineMutatorFactory() = default; class ThreadpoolLineMutator : public XplaneEventMutator { public: explicit ThreadpoolLineMutator(XPlaneBuilder& xplane) : XplaneEventMutator(nullptr), xplane_(xplane) { start_region_metadata_ = xplane_.GetEventMetadata(kThreadpoolListenerStartRegion); stop_region_metadata_ = xplane_.GetEventMetadata(kThreadpoolListenerStopRegion); thread_pool_metadata_ = xplane_.GetOrCreateEventMetadata(kThreadpoolListenerRegion); consumer_ = xplane_.GetOrCreateStatMetadata( GetStatTypeStr(StatType::kConsumerId)); consumer_type_ = xplane_.GetOrCreateStatMetadata( GetStatTypeStr(StatType::kConsumerType)); } void Mutate(XEventBuilder& event_builder) override { CHECK(false); } void MutateEventsInLine(XLineBuilder& line) override { if (start_region_metadata_ == nullptr || stop_region_metadata_ == nullptr) { return; } int64_t start_region_timestamp_ps = 0; int64_t region_id; struct EventMetadata { int64_t start_region_timestamp_ps; int64_t region_id; int64_t end_region_timestamp_ps; }; std::vector<EventMetadata> event_metadata; line.ForEachEvent([&](const XEventBuilder& event) { if (event.MetadataId() == start_region_metadata_->id()) { auto consumer_id = event.GetStat(*consumer_); if (!consumer_id) return; start_region_timestamp_ps = event.TimestampPs(); region_id = event.IntOrUintValue(*consumer_id); } else if (event.MetadataId() == stop_region_metadata_->id() && start_region_timestamp_ps != 0) { EventMetadata metadata; metadata.start_region_timestamp_ps = start_region_timestamp_ps; metadata.region_id = region_id; metadata.end_region_timestamp_ps = event.TimestampPs(); event_metadata.emplace_back(metadata); } }); for (const auto& event_metadata : event_metadata) { XEventBuilder region = line.AddEvent(*thread_pool_metadata_); region.SetTimestampPs(event_metadata.start_region_timestamp_ps); region.SetEndTimestampPs(event_metadata.end_region_timestamp_ps); region.SetOrAddStatValue(*consumer_, event_metadata.region_id); region.SetOrAddStatValue( *consumer_type_, static_cast<int64_t>(ContextType::kThreadpoolEvent)); } } private: XStatMetadata* consumer_; XStatMetadata* consumer_type_; XPlaneBuilder& xplane_; XEventMetadata* start_region_metadata_; XEventMetadata* stop_region_metadata_; XEventMetadata* thread_pool_metadata_; }; }; void PreprocessXSpace(XSpace* space); void PreprocessXPlane(XPlane* plane); } } #endif #include "tsl/profiler/utils/preprocess_xplane.h" #include <cstdint> #include <memory> #include <utility> #include <vector> #include "absl/container/flat_hash_map.h" #include "tsl/profiler/lib/context_types.h" #include "tsl/profiler/protobuf/xplane.pb.h" #include "tsl/profiler/utils/xplane_builder.h" #include "tsl/profiler/utils/xplane_schema.h" namespace tsl { namespace profiler { namespace { using ::tsl::profiler::HostEventType; using ::tsl::profiler::StatType; using ::tsl::profiler::XEventBuilder; using ::tsl::profiler::XLineBuilder; using ::tsl::profiler::XPlane; using ::tsl::profiler::XPlaneBuilder; using ::tsl::profiler::XSpace; void MutateXPlane(XPlane& plane, const std::vector<std::unique_ptr<XplaneEventMutatorFactory>>& mutator_factories) { XPlaneBuilder plane_builder(&plane); absl::flat_hash_map<int64_t, std::vector<std::unique_ptr<XplaneEventMutator>>> mutators_from_event_metadata_id; std::vector<std::unique_ptr<XplaneEventMutator>> line_mutators; for (const auto& mutator_factory : mutator_factories) { auto mutators = mutator_factory->CreateMutators(plane_builder); for (auto& mutator : mutators) { if (mutator->event_metadata()) { auto id = mutator->event_metadata()->id(); mutators_from_event_metadata_id[id].push_back(std::move(mutator)); } else { line_mutators.push_back(std::move(mutator)); } } } if (mutators_from_event_metadata_id.empty() && line_mutators.empty()) { return; } plane_builder.ForEachLine([&](XLineBuilder line_builder) { for (const auto& mutator : line_mutators) { mutator->MutateEventsInLine(line_builder); } if (mutators_from_event_metadata_id.empty()) return; line_builder.ForEachEvent([&](XEventBuilder event_builder) { auto event_mutators = mutators_from_event_metadata_id.find(event_builder.MetadataId()); if (event_mutators != mutators_from_event_metadata_id.end()) { for (const auto& mutator : event_mutators->second) { mutator->Mutate(event_builder); } } }); }); } std::vector<std::unique_ptr<XplaneEventMutatorFactory>> CreateMutatorFactories() { std::vector<std::unique_ptr<XplaneEventMutatorFactory>> mutator_factories; mutator_factories.push_back(ThreadpoolLineMutatorFactory::CreateFactory()); mutator_factories.push_back(XplaneRootEventMutatorFactory::CreateFactory( HostEventType::kProcessBatch, 2)); mutator_factories.push_back(XplaneRootEventMutatorFactory::CreateFactory( HostEventType::kBatchingSessionRun, 1)); mutator_factories.push_back( XplaneConnectedEventMutatorFactory< HostEventType::kExecutorStateProcess, HostEventType::kTpuExecuteOp, ContextType::kLegacy, false, XContextStatsAccessor<uint64_t, StatType::kStepId>, XContextStatsAccessor<uint64_t, StatType::kIterNum>>::CreateFactory()); #define ADD_QUEUE_CONNECTION(__enque_event__, __deque_event__) \ mutator_factories.push_back( \ XplaneConnectedEventMutatorFactory< \ HostEventType::__enque_event__, HostEventType::__deque_event__, \ ContextType::kTpuStream, true, \ XContextStatsAccessor<uint64, StatType::kRequestId>, \ XContextStatsAccessor<uint64, \ StatType::kQueueAddr>>::CreateFactory()) ADD_QUEUE_CONNECTION(kEnqueueRequestLocked, kRunProgramRequest); ADD_QUEUE_CONNECTION(kEnqueueRequestLocked, kHostCallbackRequest); ADD_QUEUE_CONNECTION(kEnqueueRequestLocked, kTransferH2DRequest); ADD_QUEUE_CONNECTION(kEnqueueRequestLocked, kTransferPreprocessedH2DRequest); ADD_QUEUE_CONNECTION(kEnqueueRequestLocked, kTransferD2HRequest); ADD_QUEUE_CONNECTION(kEnqueueRequestLocked, kOnDeviceSendRequest); ADD_QUEUE_CONNECTION(kEnqueueRequestLocked, kOnDeviceRecvRequest); ADD_QUEUE_CONNECTION(kEnqueueRequestLocked, kOnDeviceSendRecvLocalRequest); ADD_QUEUE_CONNECTION(kEnqueueRequestLocked, kCustomWait); ADD_QUEUE_CONNECTION(kEnqueueRequestLocked, kOnDeviceSendRequestMulti); ADD_QUEUE_CONNECTION(kEnqueueRequestLocked, kOnDeviceRecvRequestMulti); ADD_QUEUE_CONNECTION(kEnqueueRequestLocked, kPjrtAsyncWait); #undef ADD_QUEUE_CONNECTION mutator_factories.push_back( HostRunIdMutatorFactory< HostEventType::kDoEnqueueProgram>::CreateFactory()); mutator_factories.push_back( HostRunIdMutatorFactory< HostEventType::kCompleteCallbacks>::CreateFactory()); mutator_factories.push_back( HostRunIdMutatorFactory< HostEventType::kDoEnqueueContinuationProgram>::CreateFactory()); mutator_factories.push_back( XplaneConnectedEventMutatorFactory< HostEventType::kDoEnqueueProgram, HostEventType::kCompleteCallbacks, ContextType::kTpuLaunch, true, XContextStatsAccessor<uint64_t, StatType::kDeviceOrdinal>, XContextStatsAccessor<uint64_t, StatType::kQueueId>, XContextStatsAccessor<uint64_t, StatType::kRunId>, XContextStatsAccessorWithDefault<uint64_t, StatType::kCoreType, 0ULL>>::CreateFactory()); mutator_factories.push_back(TpuModuleLineMutatorFactory::CreateFactory()); return mutator_factories; } } void PreprocessXPlane(XPlane* plane) { if (plane == nullptr) return; auto mutator_factories = CreateMutatorFactories(); MutateXPlane(*plane, mutator_factories); } void PreprocessXSpace(XSpace* space) { if (space == nullptr) return; auto mutator_factories = CreateMutatorFactories(); for (XPlane& plane : *space->mutable_planes()) { MutateXPlane(plane, mutator_factories); } } } }
#include "tsl/profiler/utils/preprocess_xplane.h" #include <cstdint> #include <memory> #include <optional> #include "absl/container/flat_hash_map.h" #include "absl/hash/hash.h" #include "tsl/platform/test.h" #include "tsl/profiler/lib/connected_traceme.h" #include "tsl/profiler/protobuf/xplane.pb.h" #include "tsl/profiler/utils/tf_xplane_visitor.h" #include "tsl/profiler/utils/xplane_builder.h" #include "tsl/profiler/utils/xplane_schema.h" #include "tsl/profiler/utils/xplane_test_utils.h" #include "tsl/profiler/utils/xplane_visitor.h" namespace tsl { namespace profiler { namespace { using ::tsl::profiler::CreateTfXPlaneVisitor; using ::tsl::profiler::CreateXEvent; using ::tsl::profiler::GetHostEventTypeStr; using ::tsl::profiler::HostEventType; using ::tsl::profiler::StatType; using ::tsl::profiler::XEventVisitor; using ::tsl::profiler::XLineVisitor; using ::tsl::profiler::XPlane; using ::tsl::profiler::XPlaneBuilder; using ::tsl::profiler::XPlaneVisitor; using ::tsl::profiler::XSpace; TEST(PreprocessXPlane, IsRootStatsTest) { XSpace space; XPlane* plane = space.add_planes(); XPlaneBuilder plane_builder(plane); plane_builder.ReserveLines(1); auto line_builder = plane_builder.GetOrCreateLine(0); CreateXEvent(&plane_builder, &line_builder, GetHostEventTypeStr(HostEventType::kProcessBatch), 100, 100); CreateXEvent(&plane_builder, &line_builder, GetHostEventTypeStr(HostEventType::kBatchingSessionRun), 200, 100); PreprocessXSpace(&space); XPlaneVisitor plane_visitor = CreateTfXPlaneVisitor(plane); plane_visitor.ForEachLine([&](const XLineVisitor& line) { line.ForEachEvent([&](const XEventVisitor& event) { ASSERT_TRUE(event.GetStat(StatType::kIsRoot).has_value()); int64_t is_root = event.GetStat(StatType::kIsRoot)->IntValue(); if (event.Type() == HostEventType::kBatchingSessionRun) { EXPECT_EQ(is_root, 1); } else if (event.Type() == HostEventType::kProcessBatch) { EXPECT_EQ(is_root, 2); } else { CHECK(false); } }); }); } TEST(PreprocessXPlane, ProducerConsumerTest) { XSpace space; XPlane* plane = space.add_planes(); XPlaneBuilder plane_builder(plane); plane_builder.ReserveLines(2); auto line_builder = plane_builder.GetOrCreateLine(0); CreateXEvent( &plane_builder, &line_builder, GetHostEventTypeStr(HostEventType::kExecutorStateProcess), 100, 100, {{StatType::kStepId, int64_t{123}}, {StatType::kIterNum, int64_t{456}}}); line_builder = plane_builder.GetOrCreateLine(1); CreateXEvent( &plane_builder, &line_builder, GetHostEventTypeStr(HostEventType::kTpuExecuteOp), 200, 100, {{StatType::kStepId, int64_t{123}}, {StatType::kIterNum, int64_t{456}}}); PreprocessXSpace(&space); std::optional<uint64_t> producer_context_id, consumer_context_id; XPlaneVisitor plane_visitor = CreateTfXPlaneVisitor(plane); plane_visitor.ForEachLine([&](const XLineVisitor& line) { line.ForEachEvent([&](const XEventVisitor& event) { if (event.Type() == HostEventType::kExecutorStateProcess) { auto producer_type = event.GetStat(StatType::kProducerType); ASSERT_TRUE(producer_type.has_value()); EXPECT_EQ(producer_type->IntValue(), static_cast<int64_t>(ContextType::kLegacy)); auto producer_id = event.GetStat(StatType::kProducerId); ASSERT_TRUE(producer_id.has_value()); producer_context_id = producer_id->IntOrUintValue(); } else if (event.Type() == HostEventType::kTpuExecuteOp) { auto consumer_type = event.GetStat(StatType::kConsumerType); ASSERT_TRUE(consumer_type.has_value()); EXPECT_EQ(consumer_type->IntValue(), static_cast<int64_t>(ContextType::kLegacy)); auto consumer_id = event.GetStat(StatType::kConsumerId); ASSERT_TRUE(consumer_id.has_value()); consumer_context_id = consumer_id->IntOrUintValue(); } else { CHECK(false); } }); }); ASSERT_TRUE(producer_context_id && consumer_context_id); ASSERT_EQ(*producer_context_id, *consumer_context_id); } TEST(PreprocessXPlane, ProducerConsumerNotMatchedTest) { XSpace space; XPlane* plane = space.add_planes(); XPlaneBuilder plane_builder(plane); plane_builder.ReserveLines(2); auto line_builder = plane_builder.GetOrCreateLine(0); CreateXEvent(&plane_builder, &line_builder, GetHostEventTypeStr(HostEventType::kExecutorStateProcess), 100, 100, {{StatType::kStepId, int64_t{123}}, {StatType::kIterNum, int64_t{456}}, {StatType::kDeviceOrdinal, int64_t{789}}}); line_builder = plane_builder.GetOrCreateLine(1); CreateXEvent( &plane_builder, &line_builder, GetHostEventTypeStr(HostEventType::kTpuExecuteOp), 200, 100, {{StatType::kStepId, int64_t{123}}, {StatType::kIterNum, int64_t{789}}}); PreprocessXSpace(&space); std::optional<uint64_t> producer_context_id, consumer_context_id; XPlaneVisitor plane_visitor = CreateTfXPlaneVisitor(plane); plane_visitor.ForEachLine([&](const XLineVisitor& line) { line.ForEachEvent([&](const XEventVisitor& event) { if (event.Type() == HostEventType::kExecutorStateProcess) { auto producer_type = event.GetStat(StatType::kProducerType); ASSERT_TRUE(producer_type.has_value()); EXPECT_EQ(producer_type->IntValue(), static_cast<int64_t>(ContextType::kLegacy)); auto producer_id = event.GetStat(StatType::kProducerId); ASSERT_TRUE(producer_id.has_value()); producer_context_id = producer_id->IntOrUintValue(); } else if (event.Type() == HostEventType::kTpuExecuteOp) { auto consumer_type = event.GetStat(StatType::kConsumerType); ASSERT_TRUE(consumer_type.has_value()); EXPECT_EQ(consumer_type->IntValue(), static_cast<int64_t>(ContextType::kLegacy)); auto consumer_id = event.GetStat(StatType::kConsumerId); ASSERT_TRUE(consumer_id.has_value()); consumer_context_id = consumer_id->IntOrUintValue(); } else { CHECK(false); } }); }); ASSERT_TRUE(producer_context_id && consumer_context_id); ASSERT_NE(*producer_context_id, *consumer_context_id); } TEST(PreprocessXPlane, MissingLegacyStatTest) { XSpace space; XPlane* plane = space.add_planes(); XPlaneBuilder plane_builder(plane); plane_builder.ReserveLines(2); auto line_builder = plane_builder.GetOrCreateLine(0); CreateXEvent(&plane_builder, &line_builder, GetHostEventTypeStr(HostEventType::kExecutorStateProcess), 100, 100, {{StatType::kStepId, int64_t{123}}}); line_builder = plane_builder.GetOrCreateLine(1); CreateXEvent(&plane_builder, &line_builder, GetHostEventTypeStr(HostEventType::kTpuExecuteOp), 200, 100, {{StatType::kStepId, int64_t{123}}}); PreprocessXSpace(&space); XPlaneVisitor plane_visitor = CreateTfXPlaneVisitor(plane); plane_visitor.ForEachLine([&](const XLineVisitor& line) { line.ForEachEvent([&](const XEventVisitor& event) { if (event.Type() == HostEventType::kExecutorStateProcess) { auto producer_type = event.GetStat(StatType::kProducerType); ASSERT_FALSE(producer_type.has_value()); auto producer_id = event.GetStat(StatType::kProducerId); ASSERT_FALSE(producer_id.has_value()); } else if (event.Type() == HostEventType::kTpuExecuteOp) { auto consumer_type = event.GetStat(StatType::kConsumerType); ASSERT_FALSE(consumer_type.has_value()); auto consumer_id = event.GetStat(StatType::kConsumerId); ASSERT_FALSE(consumer_id.has_value()); } else { CHECK(false); } }); }); } TEST(PreprocessXPlane, HostRunIdPreprocessorTest) { XSpace space; XPlane* plane = space.add_planes(); XPlaneBuilder plane_builder(plane); plane_builder.ReserveLines(2); auto line_builder = plane_builder.GetOrCreateLine(0); int64_t host_run_id = int64_t{582974244}; int64_t device_run_id = int64_t{46103332}; CreateXEvent( &plane_builder, &line_builder, GetHostEventTypeStr(HostEventType::kDoEnqueueContinuationProgram), 100, 100, {}); CreateXEvent(&plane_builder, &line_builder, GetHostEventTypeStr(HostEventType::kDoEnqueueProgram), 100, 100, {{StatType::kRunId, int64_t{host_run_id}}}); CreateXEvent(&plane_builder, &line_builder, GetHostEventTypeStr(HostEventType::kTpuExecuteOp), 200, 100, {{StatType::kRunId, int64_t{device_run_id}}}); CreateXEvent(&plane_builder, &line_builder, GetHostEventTypeStr(HostEventType::kCompleteCallbacks), 300, 100, {{StatType::kRunId, int64_t{host_run_id}}}); line_builder = plane_builder.GetOrCreateLine(1); PreprocessXSpace(&space); XPlaneVisitor plane_visitor = CreateTfXPlaneVisitor(plane); plane_visitor.ForEachLine([&](const XLineVisitor& line) { line.ForEachEvent([&](const XEventVisitor& event) { if (event.Type() == HostEventType::kDoEnqueueContinuationProgram) { auto run_id = event.GetStat(StatType::kRunId); ASSERT_FALSE(run_id.has_value()); } else if (event.Type() == HostEventType::kDoEnqueueProgram) { auto run_id = event.GetStat(StatType::kRunId); ASSERT_TRUE(run_id.has_value()); ASSERT_EQ(run_id->IntValue(), device_run_id); } else if (event.Type() == HostEventType::kTpuExecuteOp) { auto run_id = event.GetStat(StatType::kRunId); ASSERT_TRUE(run_id.has_value()); ASSERT_EQ(run_id->IntValue(), device_run_id); } else if (event.Type() == HostEventType::kCompleteCallbacks) { auto run_id = event.GetStat(StatType::kRunId); ASSERT_TRUE(run_id.has_value()); ASSERT_EQ(run_id->IntValue(), device_run_id); } else { CHECK(false); } }); }); } TEST(PreprocessXPlane, ThreadPoolPreprocessorTest) { XSpace space; XPlane* plane = space.add_planes(); XPlaneBuilder plane_builder(plane); auto main_line = plane_builder.GetOrCreateLine(0); CreateXEvent(&plane_builder, &main_line, kThreadpoolListenerRecord, 100, 100, {{StatType::kProducerType, static_cast<int64_t>(ContextType::kThreadpoolEvent)}, {StatType::kProducerId, int64_t{123}}}); auto thread_pool_line = plane_builder.GetOrCreateLine(1); CreateXEvent(&plane_builder, &thread_pool_line, kThreadpoolListenerStartRegion, 200, 0, {{StatType::kConsumerType, static_cast<int64_t>(ContextType::kThreadpoolEvent)}, {StatType::kConsumerId, int64_t{123}}}); CreateXEvent(&plane_builder, &thread_pool_line, kThreadpoolListenerStopRegion, 300, 0, {{StatType::kConsumerType, static_cast<int64_t>(ContextType::kThreadpoolEvent)}, {StatType::kConsumerId, int64_t{123}}}); bool new_event_added = false; PreprocessXSpace(&space); XPlaneVisitor plane_visitor = CreateTfXPlaneVisitor(plane); plane_visitor.ForEachLine([&](const XLineVisitor& line) { line.ForEachEvent([&](const XEventVisitor& event) { if (event.Name() == kThreadpoolListenerRegion) { new_event_added = true; EXPECT_EQ(event.DurationPs(), 100); EXPECT_EQ(event.TimestampPs(), 200); auto stat = event.GetStat(StatType::kConsumerId); EXPECT_TRUE(stat.has_value()); EXPECT_EQ(stat->IntOrUintValue(), 123); } }); }); EXPECT_TRUE(new_event_added); } TEST(PreprocessXPlane, XContextStatsAccessorNPETest) { auto xplane = std::make_unique<XPlane>(); XPlaneBuilder xplane_builder(xplane.get()); XLine xline; XLineBuilder xline_builder(&xline, &xplane_builder); XEvent xevent; XEventBuilder xevent_builder(&xline, &xplane_builder, &xevent); XContextStatsAccessor<int64_t, StatType::kRunId> run_id_accessor; ASSERT_FALSE(run_id_accessor.Initialize(xplane_builder)); EXPECT_EQ(run_id_accessor.GetStat(xevent_builder), std::nullopt); } } } }
2,628
cpp
google/tsl
tf_op_utils
tsl/profiler/utils/tf_op_utils.cc
tsl/profiler/utils/tf_op_utils_test.cc
#ifndef TENSORFLOW_TSL_PROFILER_UTILS_TF_OP_UTILS_H_ #define TENSORFLOW_TSL_PROFILER_UTILS_TF_OP_UTILS_H_ #include <string> #include <vector> #include "absl/strings/match.h" #include "absl/strings/string_view.h" #include "tsl/platform/macros.h" namespace tsl { namespace profiler { TF_CONST_INIT extern const absl::string_view kUnknownOp; TF_CONST_INIT extern const absl::string_view kDatasetOp; TF_CONST_INIT extern const absl::string_view kMemcpyHToDOp; TF_CONST_INIT extern const absl::string_view kMemcpyDToHOp; TF_CONST_INIT extern const absl::string_view kMemcpyDToDOp; TF_CONST_INIT extern const absl::string_view kMemcpyHToHOp; enum class Category { kUnknown, kTensorFlow, kJax, kTfData, kMemcpyHToD, kMemcpyDToH, kMemcpyDToD, kMemcpyHToH, }; struct TfOp { Category category = Category::kUnknown; absl::string_view name; absl::string_view type; }; TfOp ParseTfOpFullname(absl::string_view tf_op_fullname); std::vector<absl::string_view> ParseTfNameScopes(absl::string_view tf_op_name); std::vector<absl::string_view> ParseTfNameScopes(const TfOp& tf_op); std::string TfOpEventName(const TfOp& tf_op); std::string TfOpEventName(absl::string_view tf_op_fullname); std::string DatasetOpEventName(absl::string_view full_name); std::string IteratorName(absl::string_view full_name); inline bool IsDatasetOp(absl::string_view tf_op_type) { return tf_op_type == kDatasetOp; } inline bool IsDatasetOp(const TfOp& tf_op) { return tf_op.category == Category::kTfData; } inline bool IsInfeedEnqueueOp(absl::string_view tf_op_type) { return absl::StartsWith(tf_op_type, "InfeedEnqueue"); } inline bool IsInfeedEnqueueOp(const TfOp& tf_op) { return tf_op.category == Category::kTensorFlow && IsInfeedEnqueueOp(tf_op.type); } inline bool IsOutsideCompilationOp(absl::string_view tf_op_fullname) { if (absl::EndsWith(tf_op_fullname, ":XlaSendToHost")) return true; if (absl::EndsWith(tf_op_fullname, ":XlaRecvFromHost")) return true; return false; } inline bool IsOutsideCompilationOp(absl::string_view tf_op_fullname, absl::string_view hlo_expression) { if (IsOutsideCompilationOp(tf_op_fullname)) return true; if (absl::StrContains(hlo_expression, "send-done") && absl::StrContains(hlo_expression, "is_host_transfer=true")) return true; return false; } inline bool IsEmbeddingOp(absl::string_view tf_op_fullname) { return absl::StrContains(tf_op_fullname, "Embedding"); } inline bool IsMemcpyHToDOp(absl::string_view tf_op_type) { return tf_op_type == kMemcpyHToDOp; } inline bool IsMemcpyHToDOp(const TfOp& tf_op) { return tf_op.category == Category::kMemcpyHToD; } inline bool IsMemcpyDToHOp(const TfOp& tf_op) { return tf_op.category == Category::kMemcpyDToH; } inline bool IsMemcpyDToDOp(const TfOp& tf_op) { return tf_op.category == Category::kMemcpyDToD; } inline bool IsMemcpyHToHOp(const TfOp& tf_op) { return tf_op.category == Category::kMemcpyHToH; } std::vector<absl::string_view> ParseTensorShapes( absl::string_view tensor_shapes); bool IsTfOpName(absl::string_view op_name); bool IsTfOpType(absl::string_view op_type); bool IsJaxOpType(absl::string_view op_type); bool IsJaxOpNameAndType(absl::string_view op_name, absl::string_view op_type); } } #endif #include "tsl/profiler/utils/tf_op_utils.h" #include <cstdint> #include <optional> #include <string> #include <vector> #include "absl/strings/ascii.h" #include "absl/strings/match.h" #include "absl/strings/numbers.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_split.h" #include "absl/strings/string_view.h" #include "absl/strings/strip.h" #include "tsl/platform/regexp.h" namespace tsl { namespace profiler { namespace { const absl::string_view kIterator = "Iterator"; const absl::string_view kSeparator = "::"; constexpr char kNameScopeSeparator = '/'; constexpr char kOpNameSuffixSeparator = '_'; bool IsInteger(absl::string_view str) { int64_t unused; return absl::SimpleAtoi(str, &unused); } absl::string_view DeriveOpType(absl::string_view full_op_name) { std::vector<absl::string_view> name_scopes_and_op_name = absl::StrSplit(full_op_name, kNameScopeSeparator); absl::string_view op_name = name_scopes_and_op_name.back(); std::vector<absl::string_view> op_type_and_maybe_suffix = absl::StrSplit(op_name, kOpNameSuffixSeparator); absl::string_view maybe_suffix = op_type_and_maybe_suffix.back(); absl::string_view op_type = op_name; if (IsInteger(maybe_suffix)) { op_type = op_name.substr(0, op_name.size() - maybe_suffix.size() - 1); } return op_type; } std::optional<TfOp> GetMemcpyOp(absl::string_view tf_op_fullname) { TfOp tf_op; tf_op.name = tf_op_fullname; if (absl::StartsWithIgnoreCase(tf_op_fullname, "MEMCPYHToD")) { tf_op.category = Category::kMemcpyHToD; tf_op.type = kMemcpyHToDOp; return tf_op; } if (absl::StartsWithIgnoreCase(tf_op_fullname, "MEMCPYDToH")) { tf_op.category = Category::kMemcpyDToH; tf_op.type = kMemcpyDToHOp; return tf_op; } if (absl::StartsWithIgnoreCase(tf_op_fullname, "MEMCPYDToD")) { tf_op.category = Category::kMemcpyDToD; tf_op.type = kMemcpyDToDOp; return tf_op; } else if (absl::StartsWithIgnoreCase(tf_op_fullname, "MEMCPYHToH")) { tf_op.category = Category::kMemcpyHToH; tf_op.type = kMemcpyHToHOp; return tf_op; } return std::nullopt; } } const absl::string_view kUnknownOp = ""; const absl::string_view kDatasetOp = "Dataset"; const absl::string_view kMemcpyHToDOp = "MemcpyHToD"; const absl::string_view kMemcpyDToHOp = "MemcpyDToH"; const absl::string_view kMemcpyDToDOp = "MemcpyDToD"; const absl::string_view kMemcpyHToHOp = "MemcpyHToH"; bool IsTfOpName(absl::string_view op_name) { static const LazyRE2 kTfOpNameRegEx = {"[A-Za-z0-9.][A-Za-z0-9_.\\/>-]*"}; return RE2::FullMatch(op_name, *kTfOpNameRegEx); } bool IsTfOpType(absl::string_view op_type) { static const LazyRE2 kTfOpTypeRegEx = {"[A-Z_][a-zA-Z0-9_]*"}; return RE2::FullMatch(op_type, *kTfOpTypeRegEx); } bool IsJaxOpType(absl::string_view op_type) { static const LazyRE2 kJaxOpTypeRegEx = {"[a-z_][a-z0-9_]*(\\[.*\\])?"}; return RE2::FullMatch(op_type, *kJaxOpTypeRegEx); } bool IsJaxOpNameAndType(absl::string_view op_name, absl::string_view op_type) { if (op_name.empty() || !IsJaxOpType(op_type)) return false; std::vector<absl::string_view> split_result = absl::StrSplit(op_name, kNameScopeSeparator); return absl::StrContains(split_result.back(), op_type); } TfOp ParseTfOpFullname(absl::string_view tf_op_fullname) { TfOp tf_op = {Category::kUnknown, tf_op_fullname, kUnknownOp}; std::vector<absl::string_view> parts = absl::StrSplit(tf_op_fullname, absl::MaxSplits(':', 1)); if (parts.size() != 2) { if (std::optional<TfOp> tfop = GetMemcpyOp(parts[0]); tfop.has_value()) { return *tfop; } return tf_op; } if (parts[0] == kIterator) { tf_op.category = Category::kTfData; tf_op.type = kDatasetOp; return tf_op; } if (IsTfOpName(parts[0]) && IsTfOpType(parts[1])) { tf_op.category = Category::kTensorFlow; tf_op.name = parts[0]; tf_op.type = parts[1]; return tf_op; } absl::string_view op_type = parts[1].empty() ? DeriveOpType(parts[0]) : parts[1]; if (IsJaxOpType(op_type)) { tf_op.category = Category::kJax; tf_op.name = parts[0]; tf_op.type = op_type.substr(0, op_type.find('[')); return tf_op; } if (parts[1].empty()) { tf_op.category = Category::kTensorFlow; tf_op.name = parts[0]; tf_op.type = op_type; return tf_op; } return tf_op; } std::vector<absl::string_view> ParseTfNameScopes(absl::string_view tf_op_name) { std::vector<absl::string_view> name_scopes = absl::StrSplit(tf_op_name, kNameScopeSeparator); if (!name_scopes.empty()) name_scopes.pop_back(); return name_scopes; } std::vector<absl::string_view> ParseTfNameScopes(const TfOp& tf_op) { return ParseTfNameScopes(tf_op.name); } std::string TfOpEventName(const TfOp& tf_op) { std::string event_name; if (tf_op.category == Category::kUnknown) { event_name = std::string(absl::StripTrailingAsciiWhitespace(tf_op.name)); } else if (tf_op.category == Category::kTfData) { event_name = DatasetOpEventName(tf_op.name); } else { event_name = std::string(tf_op.type); } return event_name; } std::string TfOpEventName(absl::string_view tf_op_fullname) { return TfOpEventName(ParseTfOpFullname(tf_op_fullname)); } std::string DatasetOpEventName(absl::string_view full_name) { std::vector<absl::string_view> split_result = absl::StrSplit(full_name, kSeparator); return absl::StrCat(kIterator, kSeparator, split_result.back()); } std::string IteratorName(absl::string_view full_name) { std::vector<absl::string_view> split_result = absl::StrSplit(full_name, kSeparator); return std::string(split_result.back()); } std::vector<absl::string_view> ParseTensorShapes( absl::string_view tensor_shapes) { absl::ConsumePrefix(&tensor_shapes, "("); absl::ConsumeSuffix(&tensor_shapes, ")"); return absl::StrSplit(tensor_shapes, ';'); } } }
#include "tsl/profiler/utils/tf_op_utils.h" #include <vector> #include "absl/strings/string_view.h" #include "tsl/platform/test.h" namespace tsl { namespace profiler { namespace { TEST(TfOpUtilsTest, TfOpTest) { const absl::string_view kName = "OpName:OpType"; TfOp tf_op = ParseTfOpFullname(kName); EXPECT_EQ(tf_op.category, Category::kTensorFlow); EXPECT_EQ(tf_op.name, "OpName"); EXPECT_EQ(tf_op.type, "OpType"); EXPECT_EQ(TfOpEventName(kName), "OpType"); } TEST(TfOpUtilsTest, InternalTfOpTest) { const absl::string_view kName = "OpName:_InternalOpType"; TfOp tf_op = ParseTfOpFullname(kName); EXPECT_EQ(tf_op.category, Category::kTensorFlow); EXPECT_EQ(tf_op.name, "OpName"); EXPECT_EQ(tf_op.type, "_InternalOpType"); EXPECT_EQ(TfOpEventName(kName), "_InternalOpType"); } TEST(TfOpUtilsTest, TfOpWithPathTest) { const absl::string_view kName = "path/to/name:OpType"; TfOp tf_op = ParseTfOpFullname(kName); EXPECT_EQ(tf_op.category, Category::kTensorFlow); EXPECT_EQ(tf_op.name, "path/to/name"); EXPECT_EQ(tf_op.type, "OpType"); EXPECT_EQ(TfOpEventName(kName), "OpType"); } TEST(TfOpUtilsTest, ShortDatasetOpTest) { const absl::string_view kName = "Iterator::Batch"; TfOp tf_op = ParseTfOpFullname(kName); EXPECT_EQ(tf_op.category, Category::kTfData); EXPECT_EQ(tf_op.name, kName); EXPECT_EQ(tf_op.type, kDatasetOp); EXPECT_EQ(TfOpEventName(kName), kName); } TEST(TfOpUtilsTest, LongDatasetOpTest) { const absl::string_view kName = "Iterator::Batch::Map::TfRecord"; TfOp tf_op = ParseTfOpFullname(kName); EXPECT_EQ(tf_op.category, Category::kTfData); EXPECT_EQ(tf_op.name, kName); EXPECT_EQ(tf_op.type, kDatasetOp); EXPECT_EQ(TfOpEventName(kName), "Iterator::TfRecord"); } TEST(TfOpUtilsTest, TraceMeTest) { const absl::string_view kName = "MyTraceMe"; TfOp tf_op = ParseTfOpFullname(kName); EXPECT_EQ(tf_op.category, Category::kUnknown); EXPECT_EQ(tf_op.name, kName); EXPECT_EQ(tf_op.type, kUnknownOp); EXPECT_EQ(TfOpEventName(kName), kName); } TEST(TfOpUtilsTest, TraceMeWithColonTest) { const absl::string_view kName = "RunStep/Server:54635"; TfOp tf_op = ParseTfOpFullname(kName); EXPECT_EQ(tf_op.category, Category::kUnknown); EXPECT_EQ(tf_op.name, kName); EXPECT_EQ(tf_op.type, kUnknownOp); EXPECT_EQ(TfOpEventName(kName), kName); } TEST(TfOpUtilsTest, TraceMeWithDoubleColonTest) { const absl::string_view kName = "XLA::StartProgram"; TfOp tf_op = ParseTfOpFullname(kName); EXPECT_EQ(tf_op.category, Category::kUnknown); EXPECT_EQ(tf_op.name, kName); EXPECT_EQ(tf_op.type, kUnknownOp); EXPECT_EQ(TfOpEventName(kName), kName); } TEST(TfOpUtilsTest, TraceMeWithTrailingWhitespaceTest) { const absl::string_view kName = "SessionRun "; const absl::string_view kNameTrimmed = "SessionRun"; TfOp tf_op = ParseTfOpFullname(kName); EXPECT_EQ(tf_op.category, Category::kUnknown); EXPECT_EQ(tf_op.name, kName); EXPECT_EQ(tf_op.type, kUnknownOp); EXPECT_EQ(TfOpEventName(kName), kNameTrimmed); } TEST(TfOpUtilsTest, InfeedEnqueueTest) { const absl::string_view kName = "input_pipeline_task0/while/body/_1/InfeedQueue/enqueue/" "1:InfeedEnqueueTuple"; TfOp tf_op = ParseTfOpFullname(kName); EXPECT_EQ(tf_op.category, Category::kTensorFlow); EXPECT_EQ(tf_op.name, "input_pipeline_task0/while/body/_1/InfeedQueue/enqueue/1"); EXPECT_EQ(tf_op.type, "InfeedEnqueueTuple"); EXPECT_EQ(TfOpEventName(kName), "InfeedEnqueueTuple"); EXPECT_TRUE(IsInfeedEnqueueOp(tf_op.type)); EXPECT_TRUE(IsInfeedEnqueueOp(tf_op)); } TEST(TfOpUtilsTest, MemcpyHToDTest) { const absl::string_view kName = "MemcpyHToD"; TfOp tf_op = ParseTfOpFullname(kName); EXPECT_EQ(tf_op.category, Category::kMemcpyHToD); EXPECT_EQ(tf_op.name, kName); EXPECT_EQ(tf_op.type, kMemcpyHToDOp); EXPECT_EQ(TfOpEventName(kName), kName); EXPECT_TRUE(IsMemcpyHToDOp(tf_op.type)); EXPECT_TRUE(IsMemcpyHToDOp(tf_op)); } TEST(TfOpUtilsTest, MemcpyDToHTest) { const absl::string_view kName = "MemcpyDToH"; TfOp tf_op = ParseTfOpFullname(kName); EXPECT_EQ(tf_op.category, Category::kMemcpyDToH); EXPECT_EQ(tf_op.name, kName); EXPECT_EQ(tf_op.type, kMemcpyDToHOp); EXPECT_EQ(TfOpEventName(kName), kName); EXPECT_TRUE(IsMemcpyDToHOp(tf_op)); } TEST(TfOpUtilsTest, MemcpyDToDTest) { const absl::string_view kName = "MemcpyDToD"; TfOp tf_op = ParseTfOpFullname(kName); EXPECT_EQ(tf_op.category, Category::kMemcpyDToD); EXPECT_EQ(tf_op.name, kName); EXPECT_EQ(tf_op.type, kMemcpyDToDOp); EXPECT_EQ(TfOpEventName(kName), kName); EXPECT_TRUE(IsMemcpyDToDOp(tf_op)); } TEST(TfOpUtilsTest, MemcpyHToHTest) { const absl::string_view kName = "MemcpyHToH"; TfOp tf_op = ParseTfOpFullname(kName); EXPECT_EQ(tf_op.category, Category::kMemcpyHToH); EXPECT_EQ(tf_op.name, kName); EXPECT_EQ(tf_op.type, kMemcpyHToHOp); EXPECT_EQ(TfOpEventName(kName), kName); EXPECT_TRUE(IsMemcpyHToHOp(tf_op)); } TEST(TfOpUtilsTest, JaxOpTest) { const absl::string_view kName = "op_name:op_type"; TfOp tf_op = ParseTfOpFullname(kName); EXPECT_EQ(tf_op.category, Category::kJax); EXPECT_EQ(tf_op.name, "op_name"); EXPECT_EQ(tf_op.type, "op_type"); EXPECT_EQ(TfOpEventName(kName), "op_type"); } TEST(TfOpUtilsTest, JaxOpWithColonTest) { const absl::string_view kName = "op_name/op_type:"; TfOp tf_op = ParseTfOpFullname(kName); EXPECT_EQ(tf_op.category, Category::kJax); EXPECT_EQ(tf_op.name, "op_name/op_type"); EXPECT_EQ(tf_op.type, "op_type"); EXPECT_EQ(TfOpEventName(kName), "op_type"); } TEST(TfOpUtilsTest, JaxOpNameTest) { const absl::string_view kOpName = "namescope/add"; const absl::string_view kOpType = "add"; EXPECT_TRUE(IsJaxOpNameAndType(kOpName, kOpType)); } TEST(TfOpUtilsTest, JaxOpWithBracketTest) { const absl::string_view kName = "op_name:op_type[array=([])]"; TfOp tf_op = ParseTfOpFullname(kName); EXPECT_EQ(tf_op.category, Category::kJax); EXPECT_EQ(tf_op.name, "op_name"); EXPECT_EQ(tf_op.type, "op_type"); EXPECT_EQ(TfOpEventName(kName), "op_type"); } TEST(TfOpUtilsTest, JaxOpWithBracketAndTrailingColonTest) { const absl::string_view kName = "op_name/op_type[array=([])]:"; TfOp tf_op = ParseTfOpFullname(kName); EXPECT_EQ(tf_op.category, Category::kJax); EXPECT_EQ(tf_op.name, "op_name/op_type[array=([])]"); EXPECT_EQ(tf_op.type, "op_type"); EXPECT_EQ(TfOpEventName(kName), "op_type"); } TEST(TfOpUtilsTest, JaxOpNameWithMetadataTest) { const absl::string_view kOpName = "pmap(<unnamed wrapped function>)/gather[ " "dimension_numbers=GatherDimensionNumbers(offset_dims=(2,), " "collapsed_slice_dims=(0, 1), start_index_map=(0, 1))\n " " slice_sizes=(1, 1, 81) ]:gather"; const absl::string_view kOpType = "gather"; EXPECT_TRUE(IsJaxOpNameAndType(kOpName, kOpType)); } TEST(TfOpUtilsTest, OtherXlaOpTest) { const absl::string_view kName = "namescope.1/namespace__opname2d:namespace__opname2d"; TfOp tf_op = ParseTfOpFullname(kName); EXPECT_EQ(tf_op.category, Category::kJax); EXPECT_EQ(tf_op.name, "namescope.1/namespace__opname2d"); EXPECT_EQ(tf_op.type, "namespace__opname2d"); EXPECT_EQ(TfOpEventName(kName), "namespace__opname2d"); } TEST(TfOpUtilsTest, OtherXlaOpNameTest) { const absl::string_view kOpName = "namescope.1/namespace__opname2d"; const absl::string_view kOpType = "namespace__opname2d"; EXPECT_TRUE(IsJaxOpNameAndType(kOpName, kOpType)); } TEST(TfOpUtilsTest, OpWithoutTypeTest) { const absl::string_view kName = "namescope/OpName_1:"; TfOp tf_op = ParseTfOpFullname(kName); EXPECT_EQ(tf_op.category, Category::kTensorFlow); EXPECT_EQ(tf_op.name, "namescope/OpName_1"); EXPECT_EQ(tf_op.type, "OpName"); EXPECT_EQ(TfOpEventName(kName), "OpName"); } TEST(TfOpUtilsTest, OpTypeWithUnderstslTest) { const absl::string_view kName = "namescope/OpName_a:"; TfOp tf_op = ParseTfOpFullname(kName); EXPECT_EQ(tf_op.category, Category::kTensorFlow); EXPECT_EQ(tf_op.name, "namescope/OpName_a"); EXPECT_EQ(tf_op.type, "OpName_a"); EXPECT_EQ(TfOpEventName(kName), "OpName_a"); } TEST(TfOpUtilsTest, NameScopeTest) { const absl::string_view kName = "scope-1/scope2/OpName:OpType"; TfOp tf_op = ParseTfOpFullname(kName); EXPECT_EQ(tf_op.category, Category::kTensorFlow); EXPECT_EQ(tf_op.name, "scope-1/scope2/OpName"); EXPECT_EQ(tf_op.type, "OpType"); std::vector<absl::string_view> name_scopes = ParseTfNameScopes(tf_op); EXPECT_EQ(name_scopes.size(), 2); EXPECT_EQ(name_scopes[0], "scope-1"); EXPECT_EQ(name_scopes[1], "scope2"); } } } }
2,629
cpp
google/tsl
buffer_pool
tsl/profiler/utils/buffer_pool.cc
tsl/profiler/utils/buffer_pool_test.cc
#ifndef TENSORFLOW_TSL_PROFILER_UTILS_BUFFER_POOL_H_ #define TENSORFLOW_TSL_PROFILER_UTILS_BUFFER_POOL_H_ #include <vector> #include "tsl/platform/mutex.h" #include "tsl/platform/thread_annotations.h" namespace tsl { namespace profiler { class BufferPool { public: explicit BufferPool(size_t buffer_size_in_bytes); ~BufferPool(); uint8_t* GetOrCreateBuffer(); void ReclaimBuffer(uint8_t* buffer); void DestroyAllBuffers(); size_t GetBufferSizeInBytes() const; protected: mutex buffers_mutex_; std::vector<uint8_t*> buffers_ TF_GUARDED_BY(buffers_mutex_); size_t buffer_size_in_bytes_; }; } } #endif #include "tsl/profiler/utils/buffer_pool.h" #include <ios> #include "tsl/platform/logging.h" #include "tsl/platform/mem.h" #include "tsl/platform/mutex.h" namespace tsl { namespace profiler { BufferPool::BufferPool(size_t buffer_size_in_bytes) : buffer_size_in_bytes_(buffer_size_in_bytes) {} BufferPool::~BufferPool() { DestroyAllBuffers(); } uint8_t* BufferPool::GetOrCreateBuffer() { { mutex_lock lock(buffers_mutex_); if (!buffers_.empty()) { uint8_t* buffer = buffers_.back(); buffers_.pop_back(); if (!buffer) { LOG(ERROR) << "A reused buffer must not be null!"; return nullptr; } VLOG(3) << "Reused Buffer, buffer=" << std::hex << reinterpret_cast<uintptr_t>(buffer) << std::dec; return buffer; } } constexpr size_t kBufferAlignSize = 8; uint8_t* buffer = reinterpret_cast<uint8_t*>( port::AlignedMalloc(buffer_size_in_bytes_, kBufferAlignSize)); if (buffer == nullptr) { LOG(WARNING) << "Buffer not allocated."; return nullptr; } VLOG(3) << "Allocated Buffer, buffer=" << std::hex << reinterpret_cast<uintptr_t>(buffer) << std::dec << " size=" << buffer_size_in_bytes_; return buffer; } void BufferPool::ReclaimBuffer(uint8_t* buffer) { mutex_lock lock(buffers_mutex_); buffers_.push_back(buffer); VLOG(3) << "Reclaimed Buffer, buffer=" << std::hex << reinterpret_cast<uintptr_t>(buffer) << std::dec; } void BufferPool::DestroyAllBuffers() { mutex_lock lock(buffers_mutex_); for (uint8_t* buffer : buffers_) { VLOG(3) << "Freeing Buffer, buffer:" << std::hex << reinterpret_cast<uintptr_t>(buffer) << std::dec; port::AlignedFree(buffer); } buffers_.clear(); } size_t BufferPool::GetBufferSizeInBytes() const { return buffer_size_in_bytes_; } } }
#include "tsl/profiler/utils/buffer_pool.h" #include "tsl/platform/test.h" namespace tsl { namespace profiler { namespace { TEST(BufferPoolTest, GetOrCreateBufferAlloc) { constexpr size_t kBufferSizeInBytes = 32 * 1024; BufferPool buffer_pool(kBufferSizeInBytes); uint8_t* first_buffer = buffer_pool.GetOrCreateBuffer(); EXPECT_NE(first_buffer, nullptr); uint8_t* second_buffer = buffer_pool.GetOrCreateBuffer(); EXPECT_NE(second_buffer, first_buffer); for (size_t idx = 0; idx < kBufferSizeInBytes; ++idx) { first_buffer[idx] = 0xAB; } buffer_pool.ReclaimBuffer(first_buffer); buffer_pool.ReclaimBuffer(second_buffer); } TEST(BufferPoolTest, GetOrCreateBufferReuse) { constexpr size_t kBufferSizeInBytes = 32 * 1024; BufferPool buffer_pool(kBufferSizeInBytes); uint8_t* buffer = buffer_pool.GetOrCreateBuffer(); EXPECT_NE(buffer, nullptr); buffer[0] = 0xFF; uint8_t* previous_buffer = buffer; buffer_pool.ReclaimBuffer(buffer); uint8_t* reused_buffer = buffer_pool.GetOrCreateBuffer(); EXPECT_EQ(reused_buffer, previous_buffer); for (size_t idx = 0; idx < kBufferSizeInBytes; ++idx) { reused_buffer[idx] = 0xCD; } buffer_pool.ReclaimBuffer(reused_buffer); } TEST(BufferPoolTest, DestroyAllBuffers) { constexpr size_t kBufferSizeInBytes = 32 * 1024; BufferPool buffer_pool(kBufferSizeInBytes); uint8_t* first_buffer = buffer_pool.GetOrCreateBuffer(); EXPECT_NE(first_buffer, nullptr); buffer_pool.DestroyAllBuffers(); for (size_t idx = 0; idx < kBufferSizeInBytes; ++idx) { first_buffer[idx] = 0xEF; } uint8_t* second_buffer = buffer_pool.GetOrCreateBuffer(); for (size_t idx = 0; idx < kBufferSizeInBytes; ++idx) { second_buffer[idx] = 0xAB; } buffer_pool.ReclaimBuffer(first_buffer); buffer_pool.ReclaimBuffer(second_buffer); } } } }
2,630
cpp
google/tsl
group_events
tsl/profiler/utils/group_events.cc
tsl/profiler/utils/group_events_test.cc
#ifndef TENSORFLOW_TSL_PROFILER_UTILS_GROUP_EVENTS_H_ #define TENSORFLOW_TSL_PROFILER_UTILS_GROUP_EVENTS_H_ #include <deque> #include <functional> #include <memory> #include <optional> #include <string> #include <utility> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/container/flat_hash_set.h" #include "absl/strings/string_view.h" #include "absl/types/optional.h" #include "tsl/platform/logging.h" #include "tsl/platform/types.h" #include "tsl/profiler/protobuf/xplane.pb.h" #include "tsl/profiler/utils/xplane_builder.h" #include "tsl/profiler/utils/xplane_visitor.h" namespace tsl { namespace profiler { struct InterThreadConnectInfo { int64_t parent_event_type; int64_t child_event_type; std::vector<int64_t> parent_stat_types; std::vector<int64_t> child_stat_types; }; struct GroupMetadata { std::string name; absl::flat_hash_set<int64_t> parents; absl::flat_hash_set<int64_t> children; }; using GroupMetadataMap = absl::flat_hash_map<int64_t , GroupMetadata>; class EventNode { public: explicit EventNode(XEventVisitor visitor) : visitor_(std::move(visitor)) {} EventNode(const EventNode& event_node) = delete; EventNode& operator=(const EventNode&) = delete; const std::vector<EventNode*>& GetParents() const { return parents_; } const std::vector<EventNode*>& GetChildren() const { return children_; } void AddChild(EventNode* child) { children_.push_back(child); child->parents_.push_back(this); } std::optional<int64_t> GetGroupId() const { return group_id_; } std::string GetGroupName() const; void SetGroupId(int64_t group_id); void PropagateGroupId(int64_t group_id, GroupMetadataMap* group_metadata_map); const XEventVisitor& GetEventVisitor() const { return visitor_; } std::optional<XStatVisitor> GetContextStat(int64_t stat_type) const; void AddStepName(absl::string_view step_name); void SetIsEager(bool is_eager); bool IsEager() const; bool IsNestedIn(EventNode* parent); const EventNode* FindParent(int64_t event_type) const; void SetRootLevel(int root_level) { root_level_ = root_level; } int RootLevel() const { return root_level_; } bool IsCompiledFunc() const; bool operator<(const EventNode& other) const { return GetEventVisitor().TimestampPs() < other.GetEventVisitor().TimestampPs(); } private: XStat* FindOrAddStatByType(int64_t stat_type); XEventVisitor visitor_; std::vector<EventNode*> parents_; std::vector<EventNode*> children_; std::optional<int64_t> group_id_; int root_level_ = 0; }; using EventNodeMap = absl::flat_hash_map<int64_t , std::deque<EventNode>>; using EventList = std::vector<EventNode*>; struct ContextGroup { std::vector<EventNode*> producers; std::vector<EventNode*> consumers; }; using ContextGroupMap = absl::flat_hash_map< int , absl::flat_hash_map<uint64 , ContextGroup>>; class EventForest { public: void AddSpace( std::function<XPlaneVisitor(const tensorflow::profiler::XPlane*)> visitor_factory, tensorflow::profiler::XSpace* space); void AddPlanes( std::function<XPlaneVisitor(const tensorflow::profiler::XPlane*)> visitor_factory, const std::vector<tensorflow::profiler::XPlane*>& planes); void ConnectEvents( const std::vector<InterThreadConnectInfo>& connect_info_list = {}); void ConnectTfDataEvents(); void GroupEvents(); const EventNodeMap& GetEventNodeMap() const { return event_node_map_; } const GroupMetadataMap& GetGroupMetadataMap() const { return group_metadata_map_; } private: void AddPlane( std::function<XPlaneVisitor(const tensorflow::profiler::XPlane*)> visitor_factory, tensorflow::profiler::XPlane* plane); void ConnectIntraThread(tensorflow::profiler::XPlane* plane, XPlaneVisitor* visitor, ContextGroupMap* context_groups); void ConnectInterThread( const std::vector<InterThreadConnectInfo>& connect_info_list); void CreateEventGroups(); void MarkEagerlyExecutedGpuKernels(); void MarkEagerlyExecutedCpuTfOps(); void ProcessTfDataSteps(); void ProcessTensorFlowLoop(); void FindEventNodeAndApply( int64_t event_type, const std::vector<int64_t>& stat_types, const std::function<void(EventNode&, const std::vector<uint64>&)>& cb); EventNodeMap event_node_map_; std::vector<XPlaneVisitor> visitors_; std::deque<std::pair<tensorflow::profiler::XPlane*, XPlaneVisitor>> planes_; absl::flat_hash_set<int64_t> tf_data_step_ids_; EventList tf_loop_root_events_; GroupMetadataMap group_metadata_map_; }; std::vector<InterThreadConnectInfo> CreateInterThreadConnectInfoList(); void GroupTfEvents(tensorflow::profiler::XSpace* space, EventForest* event_forest); void GroupTfEvents(tensorflow::profiler::XSpace* space); bool CheckLoopOp(const tensorflow::profiler::XSpace& space); void AddGroupMetadataToStepEvents(const GroupMetadataMap& group_metadata_map, XLineBuilder& line); void GroupHostAndPlanes( tensorflow::profiler::XSpace* space, const std::vector<tensorflow::profiler::XPlane*>& device_traces, EventForest* event_forest); void GroupXplaneEvents(tensorflow::profiler::XPlane* plane, const GroupMetadataMap& group_metadata_map); void GroupTpuEventsOSS( tensorflow::profiler::XSpace* space, const std::vector<tensorflow::profiler::XPlane*>& device_traces, EventForest* event_forest); } } #endif #include "tsl/profiler/utils/group_events.h" #include <algorithm> #include <cstdint> #include <functional> #include <iterator> #include <map> #include <memory> #include <optional> #include <queue> #include <string> #include <utility> #include <vector> #include "absl/algorithm/container.h" #include "absl/container/flat_hash_map.h" #include "absl/functional/bind_front.h" #include "absl/strings/str_cat.h" #include "tsl/lib/gtl/map_util.h" #include "tsl/platform/dso_loader.h" #include "tsl/platform/env.h" #include "tsl/platform/types.h" #include "tsl/profiler/utils/tf_xplane_visitor.h" #include "tsl/profiler/utils/xplane_builder.h" #include "tsl/profiler/utils/xplane_schema.h" #include "tsl/profiler/utils/xplane_utils.h" #include "tsl/profiler/utils/xplane_visitor.h" namespace tsl { namespace profiler { void CreateStatMetadata(XPlane* plane) { XPlaneBuilder builder(plane); builder.GetOrCreateStatMetadata(GetStatTypeStr(StatType::kGroupId)); builder.GetOrCreateStatMetadata(GetStatTypeStr(StatType::kStepName)); builder.GetOrCreateStatMetadata(GetStatTypeStr(StatType::kIsEager)); } std::optional<int64_t> GetKernelEventType(bool is_host_plane, const XEventVisitor& event) { if (event.GetStat(StatType::kCorrelationId).has_value()) { return is_host_plane ? HostEventType::kKernelLaunch : HostEventType::kKernelExecute; } return std::nullopt; } int64_t GetEventType(bool is_host_plane, const XEventVisitor& event) { if (std::optional<int64_t> event_type = event.Type()) { return *event_type; } else if (std::optional<int64_t> kernel_event_type = GetKernelEventType(is_host_plane, event)) { return *kernel_event_type; } else { return HostEventType::kUnknownHostEventType; } } bool IsLegacyRootEvent(const XEventVisitor& event) { return event.Type() == HostEventType::kTraceContext; } struct GroupingEventStats { explicit GroupingEventStats(const XEventVisitor& event); std::optional<int> producer_type; std::optional<uint64_t> producer_id; std::optional<int> consumer_type; std::optional<uint64_t> consumer_id; std::optional<int> root_level; bool is_async = false; }; GroupingEventStats::GroupingEventStats(const XEventVisitor& event) { std::optional<int64_t> step_id; event.ForEachStat([&](const XStatVisitor& stat) { if (!stat.Type().has_value()) return; switch (*stat.Type()) { case StatType::kProducerType: producer_type = stat.IntValue(); break; case StatType::kProducerId: producer_id = stat.IntOrUintValue(); break; case StatType::kConsumerType: consumer_type = stat.IntValue(); break; case StatType::kConsumerId: consumer_id = stat.IntOrUintValue(); break; case StatType::kIsRoot: root_level = stat.IntValue(); break; case StatType::kIsAsync: is_async = stat.BoolValue(); break; case StatType::kStepId: step_id = stat.IntValue(); break; default: break; } }); if (!root_level.has_value() && IsLegacyRootEvent(event)) { root_level = 1; } } void SetContextGroup(const GroupingEventStats& stats, EventNode* event, ContextGroupMap* context_groups) { if (stats.producer_type.has_value() && stats.producer_id.has_value()) { ((*context_groups)[*stats.producer_type][*stats.producer_id]) .producers.push_back(event); } if (stats.consumer_type.has_value() && stats.consumer_id.has_value()) { ((*context_groups)[*stats.consumer_type][*stats.consumer_id]) .consumers.push_back(event); } } void ConnectContextGroups(const ContextGroupMap& context_groups) { for (auto& type_id_group : context_groups) { for (auto& id_group : type_id_group.second) { const ContextGroup& group = id_group.second; if (group.producers.size() >= 64 && group.consumers.size() >= 64) { LOG_EVERY_N(WARNING, 1000) << "id:" << id_group.first << " producers:" << group.producers.size() << " : " << group.producers[0]->GetEventVisitor().Name() << " consumers:" << group.consumers.size() << " : " << group.consumers[0]->GetEventVisitor().Name(); continue; } for (EventNode* parent : group.producers) { for (EventNode* child : group.consumers) { parent->AddChild(child); } } } } } bool IsImplicitRootEvent(const XEventVisitor& event) { static const auto* const kImplicitRootEvents = new absl::flat_hash_set<int64_t>{ HostEventType::kFunctionRun, HostEventType::kSessionRun, HostEventType::kRunGraph, HostEventType::kExecutorStateProcess}; return event.Type().has_value() && kImplicitRootEvents->contains(*event.Type()); } void ProcessRootEvent(int64_t group_id, EventNode* root_event, GroupMetadataMap* group_metadata_map) { root_event->PropagateGroupId(group_id, group_metadata_map); std::string group_name = root_event->GetGroupName(); if (!IsImplicitRootEvent(root_event->GetEventVisitor())) { root_event->AddStepName(group_name); } (*group_metadata_map)[group_id].name = std::move(group_name); } using Comparator = std::function<bool(const EventNode*)>; const EventNode* FindParentWithComparator(const Comparator& comparator, const EventNode* node, bool include_self) { std::queue<const EventNode*> nodes; absl::flat_hash_set<const EventNode*> seen = {node}; if (include_self) { nodes.push(node); } else { for (const EventNode* parent : node->GetParents()) { nodes.push(parent); seen.insert(parent); } } while (!nodes.empty()) { const EventNode* node = nodes.front(); nodes.pop(); if (comparator(node)) return node; for (const EventNode* parent : node->GetParents()) { if (seen.contains(parent)) continue; nodes.push(parent); seen.insert(parent); } } return nullptr; } bool IsIteratorEventType(std::optional<int64_t> event_type) { return event_type == HostEventType::kIterator || event_type == HostEventType::kDeviceInputPipelineSecondIterator; } bool CheckLoopOp(const XSpace& space) { for (const XPlane& plane : space.planes()) { for (const auto& event_metadata : plane.event_metadata()) { std::optional<int64_t> event_type = FindHostEventType(event_metadata.second.name()); if (!event_type.has_value()) continue; switch (*event_type) { case HostEventType::kWhileOpEvalCond: case HostEventType::kWhileOpStartBody: case HostEventType::kForOp: case HostEventType::kParallelForOp: case HostEventType::kForeverOp: return true; default: break; } } } return false; } std::optional<XStatVisitor> EventNode::GetContextStat(int64_t stat_type) const { std::queue<const EventNode*> nodes; absl::flat_hash_set<const EventNode*> seen = {this}; nodes.push(this); while (!nodes.empty()) { const EventNode* node = nodes.front(); nodes.pop(); if (std::optional<XStatVisitor> stat = node->visitor_.GetStat(stat_type)) { return stat; } for (const EventNode* parent : node->GetParents()) { if (seen.contains(parent)) continue; nodes.push(parent); seen.insert(parent); } } return std::nullopt; } std::string EventNode::GetGroupName() const { std::string name; if (std::optional<XStatVisitor> stat = GetContextStat(StatType::kGraphType)) { absl::StrAppend(&name, stat->StrOrRefValue(), " "); } else if (!(IsImplicitRootEvent(visitor_))) { absl::StrAppend(&name, GetEventVisitor().Name(), " "); } int64_t step_num = group_id_.value_or(0); if (std::optional<XStatVisitor> stat = GetContextStat(StatType::kIterNum)) { step_num = stat->IntValue(); } else if (std::optional<XStatVisitor> stat = GetContextStat(StatType::kStepNum)) { step_num = stat->IntValue(); } absl::StrAppend(&name, step_num); return name; } XStat* EventNode::FindOrAddStatByType(int64_t stat_type) { const XPlaneVisitor& plane = visitor_.Plane(); const XStatMetadata* stat_metadata = plane.GetStatMetadataByType(stat_type); DCHECK(stat_metadata != nullptr); auto* raw_event = const_cast<XEvent*>(&visitor_.RawEvent()); return FindOrAddMutableStat(*stat_metadata, raw_event); } void EventNode::SetGroupId(int64_t group_id) { group_id_ = group_id; FindOrAddStatByType(StatType::kGroupId)->set_int64_value(group_id); } void EventNode::PropagateGroupId(int64_t group_id, GroupMetadataMap* group_metadata_map) { std::queue<EventNode*> nodes; absl::flat_hash_set<EventNode*> seen = {this}; nodes.push(this); while (!nodes.empty()) { EventNode* node = nodes.front(); nodes.pop(); std::optional<int64_t> node_group_id = node->GetGroupId(); if (node_group_id.has_value()) { if (*node_group_id != group_id) { (*group_metadata_map)[group_id].children.insert(*node_group_id); (*group_metadata_map)[*node_group_id].parents.insert(group_id); } } else { node->SetGroupId(group_id); for (EventNode* child : node->GetChildren()) { if (seen.contains(child)) continue; nodes.push(child); seen.insert(child); } } } } void EventNode::AddStepName(absl::string_view step_name) { FindOrAddStatByType(StatType::kStepName) ->set_str_value(step_name.data(), step_name.size()); } void EventNode::SetIsEager(bool is_eager) { FindOrAddStatByType(StatType::kIsEager)->set_int64_value(is_eager ? 1 : 0); } bool EventNode::IsCompiledFunc() const { auto is_func = visitor_.GetStat(StatType::kIsFunc); return !is_func || is_func->IntValue(); } bool EventNode::IsEager() const { const EventNode* node = FindParent(HostEventType::kEagerKernelExecute); if (node == nullptr) { return false; } return !node->IsCompiledFunc(); } const EventNode* EventNode::FindParent(int64_t event_type) const { return FindParentWithComparator( [event_type](const EventNode* node) { return node->GetEventVisitor().Type() == event_type; }, this, true); } void EventForest::FindEventNodeAndApply( const int64_t event_type, const std::vector<int64_t>& stat_types, const std::function<void(EventNode&, const std::vector<uint64>&)>& cb) { if (auto* event_node_list = gtl::FindOrNull(event_node_map_, event_type)) { for (EventNode& event_node : *event_node_list) { std::vector<uint64> stats; for (const auto stat_type : stat_types) { std::optional<XStatVisitor> stat = event_node.GetEventVisitor().GetStat(stat_type); if (!stat) break; stats.push_back(stat->IntOrUintValue()); } if (stats.size() == stat_types.size()) { cb(event_node, stats); } } } } void EventForest::ConnectIntraThread(XPlane* plane, XPlaneVisitor* visitor, ContextGroupMap* context_groups) { bool is_host_plane = (visitor->Name() == kHostThreadsPlaneName); for (auto& line : *plane->mutable_lines()) { std::vector<EventNode*> parent_nodes; for (auto& event : *line.mutable_events()) { XEventVisitor event_visitor(visitor, &line, &event); int64_t event_type = GetEventType(is_host_plane, event_visitor); EventNode* cur_node = &event_node_map_[event_type].emplace_back(std::move(event_visitor)); GroupingEventStats stats(cur_node->GetEventVisitor()); if (stats.root_level.has_value()) { cur_node->SetRootLevel(*stats.root_level); } SetContextGroup(stats, cur_node, context_groups); if (!stats.is_async) { while (!parent_nodes.empty()) { EventNode* parent_node = parent_nodes.back(); if (parent_node->GetEventVisitor().GetTimespan().Includes( cur_node->GetEventVisitor().GetTimespan())) { parent_node->AddChild(cur_node); break; } else { parent_nodes.pop_back(); } } parent_nodes.push_back(cur_node); } } } } void EventForest::ConnectInterThread( const std::vector<InterThreadConnectInfo>& connect_info_list) { for (const auto& connect_info : connect_info_list) { absl::flat_hash_map<std::vector<uint64>, EventNode*> connect_map; const std::vector<int64_t>& parent_stat_types = connect_info.parent_stat_types; const std::vector<int64_t>* child_stat_types = &connect_info.child_stat_types; if (child_stat_types->empty()) { child_stat_types = &parent_stat_types; } FindEventNodeAndApply(connect_info.parent_event_type, parent_stat_types, [&connect_map](EventNode& event_node, const std::vector<uint64>& stats) { connect_map[stats] = &event_node; }); FindEventNodeAndApply( connect_info.child_event_type, *child_stat_types, [&connect_map](EventNode& event_node, const std::vector<uint64>& stats) { if (auto parent_event_node = gtl::FindPtrOrNull(connect_map, stats)) { parent_event_node->AddChild(&event_node); } }); } } bool RootNeedsGrouping(const EventNode* root) { if (root->GetGroupId().has_value()) return false; const EventNode* root_parent = FindParentWithComparator( [root](const EventNode* parent) { return parent->RootLevel() == root->RootLevel(); }, root, false); return root_parent == nullptr; } void SortRootEventList(EventList* event_list) { absl::c_sort(*event_list, [](const EventNode* e1, const EventNode* e2) { return e1->RootLevel() == e2->RootLevel() ? *e1 < *e2 : e1->RootLevel() > e2->RootLevel(); }); } void EventForest::CreateEventGroups() { int64_t group_id = 0; if (!tf_loop_root_events_.empty()) { for (EventNode* root_event : tf_loop_root_events_) { ProcessRootEvent(group_id++, root_event, &group_metadata_map_); } return; } EventList root_events; for (auto& [event_type, events] : event_node_map_) { for (EventNode& event : events) { if (!event.RootLevel()) continue; std::optional<XStatVisitor> step_id_stat = event.GetEventVisitor().GetStat(StatType::kStepId); if (step_id_stat && tf_data_step_ids_.contains(step_id_stat->IntValue())) continue; root_events.push_back(&event); } } SortRootEventList(&root_events); for (EventNode* root_event : root_events) { if (RootNeedsGrouping(root_event)) { ProcessRootEvent(group_id++, root_event, &group_metadata_map_); } } } void EventForest::MarkEagerlyExecutedGpuKernels() { auto kernel_execute_event_node_list = gtl::FindOrNull(event_node_map_, HostEventType::kKernelExecute); if (!kernel_execute_event_node_list) return; for (EventNode& kernel_execute_event_node : *kernel_execute_event_node_list) { kernel_execute_event_node.SetIsEager(kernel_execute_event_node.IsEager()); } } void EventForest::MarkEagerlyExecutedCpuTfOps() { auto tf_op_run_event_node_list = gtl::FindOrNull(event_node_map_, HostEventType::kTfOpRun); if (!tf_op_run_event_node_list) return; for (EventNode& tf_op_run_event_node : *tf_op_run_event_node_list) { tf_op_run_event_node.SetIsEager(tf_op_run_event_node.IsEager()); } } void EventForest::ProcessTfDataSteps() { const int64_t tf_data_event_types[] = { HostEventType::kTfDataCapturedFunctionRun, HostEventType::kTfDataCapturedFunctionRunAsync, HostEventType::kTfDataCapturedFunctionRunInstantiated, HostEventType::kTfDataCapturedFunctionRunWithBorrowedArgs}; for (const int64_t tf_data_event_type : tf_data_event_types) { auto tf_data_events = gtl::FindOrNull(event_node_map_, tf_data_event_type); if (!tf_data_events) continue; for (const EventNode& tf_data_event : *tf_data_events) { std::optional<XStatVisitor> step_id_stat = tf_data_event.GetEventVisitor().GetStat(StatType::kStepId); if (!step_id_stat) continue; tf_data_step_ids_.insert(step_id_stat->IntValue()); } } } void EventForest::ProcessTensorFlowLoop() { struct TensorFlowLoopIteration { EventNode* first_event = nullptr; std::vector<EventNode*> events; }; using TensorFlowLoop = absl::flat_hash_map<int64_t , TensorFlowLoopIteration>; absl::flat_hash_map<int64_t , TensorFlowLoop> tf_loops; auto executor_event_list = gtl::FindOrNull(event_node_map_, HostEventType::kExecutorStateProcess); if (!executor_event_list) return; for (EventNode& executor_event : *executor_event_list) { std::optional<XStatVisitor> step_id_stat = executor_event.GetEventVisitor().GetStat(StatType::kStepId); std::optional<XStatVisitor> iter_num_stat = executor_event.GetEventVisitor().GetStat(StatType::kIterNum); if (!step_id_stat || !iter_num_stat) continue; int64_t step_id = step_id_stat->IntValue(); if (tf_data_step_ids_.contains(step_id)) continue; TensorFlowLoop& tf_loop = tf_loops[step_id]; TensorFlowLoopIteration& iteration = tf_loop[iter_num_stat->IntValue()]; if (!iteration.first_event || executor_event < *iteration.first_event) { iteration.first_event = &executor_event; } iteration.events.push_back(&executor_event); } std::vector<const TensorFlowLoopIteration*> iters; for (const auto& step_id_and_tf_loop : tf_loops) { const TensorFlowLoop& tf_loop = step_id_and_tf_loop.second; if (tf_loop.size() == 1 && tf_loop.contains(0)) continue; for (const auto& iter_num_and_iter : tf_loop) { iters.push_back(&iter_num_and_iter.second); } } absl::c_sort(iters, [](const auto& iter1, const auto& iter2) { return *iter1->first_event < *iter2->first_event; }); for (const TensorFlowLoopIteration* iter : iters) { EventNode* root_event = iter->first_event; tf_loop_root_events_.push_back(root_event); for (EventNode* event : iter->events) { if (event == root_event) continue; root_event->AddChild(event); } } } void EventForest::AddPlane( const std::function<XPlaneVisitor(const XPlane*)> visitor_factory, XPlane* plane) { CreateStatMetadata(plane); planes_.push_back({plane, visitor_factory(plane)}); } void EventForest::AddSpace( const std::function<XPlaneVisitor(const XPlane*)> visitor_factory, XSpace* space) { for (XPlane& plane : *space->mutable_planes()) { AddPlane(visitor_factory, &plane); } } void EventForest::AddPlanes( const std::function<XPlaneVisitor(const XPlane*)> visitor_factory, const std::vector<XPlane*>& planes) { for (XPlane* plane : planes) { AddPlane(visitor_factory, plane); } } void EventForest::ConnectEvents( const std::vector<InterThreadConnectInfo>& connect_info_list) { ContextGroupMap context_groups; for (auto& plane_visitor : planes_) { ConnectIntraThread(plane_visitor.first, &plane_visitor.second, &context_groups); } ConnectInterThread(connect_info_list); ConnectContextGroups(context_groups); } void EventForest::ConnectTfDataEvents() { absl::flat_hash_map< std::pair<int64_t , int64_t >, std::vector<EventNode*>> produce_iterator_map; uint64 num_producers = 0; for (HostEventType event_type : {HostEventType::kPrefetchProduce, HostEventType::kPar
#include "tsl/profiler/utils/group_events.h" #include <optional> #include "absl/container/flat_hash_map.h" #include "absl/strings/string_view.h" #include "tsl/platform/test.h" #include "tsl/platform/types.h" #include "tsl/profiler/protobuf/xplane.pb.h" #include "tsl/profiler/utils/tf_xplane_visitor.h" #include "tsl/profiler/utils/xplane_builder.h" #include "tsl/profiler/utils/xplane_schema.h" #include "tsl/profiler/utils/xplane_test_utils.h" #include "tsl/profiler/utils/xplane_visitor.h" namespace tsl { namespace profiler { namespace { constexpr int64_t kTfExecutor = static_cast<int64_t>(ContextType::kTfExecutor); TEST(GroupEventsTest, GroupGpuTraceLegacyRootTest) { constexpr int64_t kStepNum = 123; constexpr int64_t kStepId = 0; constexpr int64_t kCorrelationId = 100; XSpace space; XPlaneBuilder host_plane_builder(GetOrCreateHostXPlane(&space)); host_plane_builder.ReserveLines(2); auto main_thread = host_plane_builder.GetOrCreateLine(0); CreateXEvent( &host_plane_builder, &main_thread, HostEventType::kTraceContext, 0, 100, {{StatType::kGraphType, "train"}, {StatType::kStepNum, kStepNum}}); CreateXEvent(&host_plane_builder, &main_thread, HostEventType::kFunctionRun, 10, 90, {{StatType::kStepId, kStepId}, {StatType::kProducerType, kTfExecutor}, {StatType::kProducerId, kStepId}}); auto tf_executor_thread = host_plane_builder.GetOrCreateLine(1); CreateXEvent(&host_plane_builder, &tf_executor_thread, HostEventType::kExecutorStateProcess, 20, 80, {{StatType::kStepId, kStepId}, {StatType::kConsumerType, kTfExecutor}, {StatType::kConsumerId, kStepId}}); CreateXEvent(&host_plane_builder, &tf_executor_thread, "matmul", 30, 70, {{StatType::kCorrelationId, kCorrelationId}}); XPlane* device_plane = space.add_planes(); XPlaneBuilder device_plane_builder(device_plane); device_plane_builder.ReserveLines(1); auto stream = device_plane_builder.GetOrCreateLine(0); CreateXEvent(&device_plane_builder, &stream, "matmul", 200, 300, {{StatType::kCorrelationId, kCorrelationId}}); EventForest event_forest; GroupTfEvents(&space, &event_forest); const GroupMetadataMap& group_metadata_map = event_forest.GetGroupMetadataMap(); XPlaneVisitor device_plane_visitor = CreateTfXPlaneVisitor(device_plane); EXPECT_EQ(device_plane->lines(0).events(0).stats_size(), 3); EXPECT_EQ(device_plane_visitor.GetStatType( device_plane->lines(0).events(0).stats(1).metadata_id()), StatType::kGroupId); EXPECT_EQ(group_metadata_map.size(), 1); EXPECT_EQ(group_metadata_map.at(0).name, "train 123"); } TEST(GroupEventsTest, GroupGpuTraceTest) { constexpr int64_t kStepNum = 123; constexpr int64_t kStepId = 0; constexpr int64_t kCorrelationId = 100; XSpace space; XPlaneBuilder host_plane_builder(GetOrCreateHostXPlane(&space)); host_plane_builder.ReserveLines(2); auto main_thread = host_plane_builder.GetOrCreateLine(0); CreateXEvent( &host_plane_builder, &main_thread, "train", 0, 100, {{StatType::kStepNum, kStepNum}, {StatType::kIsRoot, int64_t{1}}}); CreateXEvent(&host_plane_builder, &main_thread, HostEventType::kFunctionRun, 10, 90, {{StatType::kStepId, kStepId}, {StatType::kProducerType, kTfExecutor}, {StatType::kProducerId, kStepId}}); auto tf_executor_thread = host_plane_builder.GetOrCreateLine(1); CreateXEvent(&host_plane_builder, &tf_executor_thread, HostEventType::kExecutorStateProcess, 20, 80, {{StatType::kStepId, kStepId}, {StatType::kConsumerType, kTfExecutor}, {StatType::kConsumerId, kStepId}}); CreateXEvent(&host_plane_builder, &tf_executor_thread, "matmul", 30, 70, {{StatType::kCorrelationId, kCorrelationId}}); XPlane* device_plane = space.add_planes(); XPlaneBuilder device_plane_builder(device_plane); device_plane_builder.ReserveLines(1); auto stream = device_plane_builder.GetOrCreateLine(0); CreateXEvent(&device_plane_builder, &stream, "matmul", 200, 300, {{StatType::kCorrelationId, kCorrelationId}}); EventForest event_forest; GroupTfEvents(&space, &event_forest); const GroupMetadataMap& group_metadata_map = event_forest.GetGroupMetadataMap(); XPlaneVisitor device_plane_visitor = CreateTfXPlaneVisitor(device_plane); EXPECT_EQ(device_plane->lines(0).events(0).stats_size(), 3); EXPECT_EQ(device_plane_visitor.GetStatType( device_plane->lines(0).events(0).stats(1).metadata_id()), StatType::kGroupId); EXPECT_EQ(group_metadata_map.size(), 1); EXPECT_EQ(group_metadata_map.at(0).name, "train 123"); } TEST(GroupEventsTest, GroupTensorFlowLoopTest) { constexpr int64_t kStepId = 0; constexpr int64_t kIterNum = 10; constexpr int64_t kCorrelationId = 100; XSpace space; XPlaneBuilder host_plane_builder(GetOrCreateHostXPlane(&space)); host_plane_builder.ReserveLines(1); auto tf_executor_thread = host_plane_builder.GetOrCreateLine(0); CreateXEvent(&host_plane_builder, &tf_executor_thread, HostEventType::kExecutorStateProcess, 5, 10, {{StatType::kStepId, kStepId}, {StatType::kIterNum, kIterNum}, {StatType::kConsumerType, kTfExecutor}, {StatType::kConsumerId, kStepId}}); CreateXEvent(&host_plane_builder, &tf_executor_thread, HostEventType::kExecutorStateProcess, 20, 80, {{StatType::kStepId, kStepId}, {StatType::kIterNum, kIterNum}, {StatType::kConsumerType, kTfExecutor}, {StatType::kConsumerId, kStepId}}); CreateXEvent(&host_plane_builder, &tf_executor_thread, "matmul", 30, 70, {{StatType::kCorrelationId, kCorrelationId}}); XPlane* device_plane = space.add_planes(); XPlaneBuilder device_plane_builder(device_plane); device_plane_builder.ReserveLines(1); auto stream = device_plane_builder.GetOrCreateLine(0); CreateXEvent(&device_plane_builder, &stream, "matmul", 200, 300, {{StatType::kCorrelationId, kCorrelationId}}); EventForest event_forest; GroupTfEvents(&space, &event_forest); const GroupMetadataMap& group_metadata_map = event_forest.GetGroupMetadataMap(); XPlaneVisitor device_plane_visitor = CreateTfXPlaneVisitor(device_plane); EXPECT_EQ(device_plane->lines(0).events(0).stats_size(), 3); EXPECT_EQ(device_plane_visitor.GetStatType( device_plane->lines(0).events(0).stats(1).metadata_id()), StatType::kGroupId); EXPECT_EQ(device_plane->lines(0).events(0).stats(1).int64_value(), 0); EXPECT_EQ(group_metadata_map.size(), 1); ASSERT_TRUE(group_metadata_map.contains(0)); EXPECT_EQ(group_metadata_map.at(0).name, "10"); } TEST(GroupEventsTest, GroupMultipleTensorFlowLoopsTest) { constexpr int64_t kFirstStepId = 0; constexpr int64_t kSecondStepId = 1; constexpr int64_t kFirstIterNumStart = 10; constexpr int64_t kSecondIterNumStart = 0; XSpace space; XPlaneBuilder host_plane_builder(GetOrCreateHostXPlane(&space)); host_plane_builder.ReserveLines(2); auto first_tf_executor_thread = host_plane_builder.GetOrCreateLine(0); CreateXEvent(&host_plane_builder, &first_tf_executor_thread, HostEventType::kExecutorStateProcess, 220, 80, {{StatType::kStepId, kSecondStepId}, {StatType::kIterNum, kSecondIterNumStart}, {StatType::kConsumerType, kTfExecutor}, {StatType::kConsumerId, kSecondStepId}}); CreateXEvent(&host_plane_builder, &first_tf_executor_thread, HostEventType::kExecutorStateProcess, 320, 80, {{StatType::kStepId, kSecondStepId}, {StatType::kIterNum, kSecondIterNumStart + 1}, {StatType::kConsumerType, kTfExecutor}, {StatType::kConsumerId, kSecondStepId}}); auto second_tf_executor_thread = host_plane_builder.GetOrCreateLine(1); CreateXEvent(&host_plane_builder, &second_tf_executor_thread, HostEventType::kExecutorStateProcess, 20, 80, {{StatType::kStepId, kFirstStepId}, {StatType::kIterNum, kFirstIterNumStart}, {StatType::kConsumerType, kTfExecutor}, {StatType::kConsumerId, kFirstStepId}}); CreateXEvent(&host_plane_builder, &second_tf_executor_thread, HostEventType::kExecutorStateProcess, 120, 80, {{StatType::kStepId, kFirstStepId}, {StatType::kIterNum, kFirstIterNumStart + 1}, {StatType::kConsumerType, kTfExecutor}, {StatType::kConsumerId, kFirstStepId}}); EventForest event_forest; GroupTfEvents(&space, &event_forest); const GroupMetadataMap& group_metadata_map = event_forest.GetGroupMetadataMap(); EXPECT_EQ(group_metadata_map.size(), 4); ASSERT_TRUE(group_metadata_map.contains(0)); EXPECT_EQ(group_metadata_map.at(0).name, "10"); ASSERT_TRUE(group_metadata_map.contains(1)); EXPECT_EQ(group_metadata_map.at(1).name, "11"); ASSERT_TRUE(group_metadata_map.contains(2)); EXPECT_EQ(group_metadata_map.at(2).name, "0"); ASSERT_TRUE(group_metadata_map.contains(3)); EXPECT_EQ(group_metadata_map.at(3).name, "1"); } TEST(GroupEventsTest, EagerOpTest) { XSpace space; XPlane* host_plane = GetOrCreateHostXPlane(&space); XPlaneBuilder host_plane_builder(host_plane); host_plane_builder.ReserveLines(1); auto main_thread = host_plane_builder.GetOrCreateLine(0); XPlane* device_plane = space.add_planes(); XPlaneBuilder device_plane_builder(device_plane); device_plane_builder.ReserveLines(1); auto gpu_stream = device_plane_builder.GetOrCreateLine(0); int64_t correlation_id = 100; const char* kTF1GpuLaunchEvent = "tf1 matmul"; const char* kTF1GpuEvent = "tf1_kernel_matmul"; CreateXEvent(&host_plane_builder, &main_thread, kTF1GpuLaunchEvent, 10, 90, {{StatType::kCorrelationId, correlation_id}}); CreateXEvent(&device_plane_builder, &gpu_stream, kTF1GpuEvent, 200, 300, {{StatType::kCorrelationId, correlation_id}}); ++correlation_id; const char* kLegacyGpuLaunchEvent = "legacy matmul"; const char* kLegacyGpuEvent = "legacy_kernel_matmul"; CreateXEvent(&host_plane_builder, &main_thread, HostEventType::kEagerKernelExecute, 100, 200); CreateXEvent(&host_plane_builder, &main_thread, kLegacyGpuLaunchEvent, 110, 190, {{StatType::kCorrelationId, correlation_id}}); CreateXEvent(&device_plane_builder, &gpu_stream, kLegacyGpuEvent, 300, 400, {{StatType::kCorrelationId, correlation_id}}); ++correlation_id; const char* kEagerOpGpuLaunchEvent = "eager op matmul"; const char* kEagerOpGpuEvent = "eager_op_kernel_matmul"; CreateXEvent(&host_plane_builder, &main_thread, HostEventType::kEagerKernelExecute, 200, 300, {{StatType::kIsFunc, static_cast<int64_t>(0)}}); CreateXEvent(&host_plane_builder, &main_thread, kEagerOpGpuLaunchEvent, 210, 290, {{StatType::kCorrelationId, correlation_id}}); CreateXEvent(&device_plane_builder, &gpu_stream, kEagerOpGpuEvent, 400, 500, {{StatType::kCorrelationId, correlation_id}}); ++correlation_id; const char* kEagerFuncGpuLaunchEvent = "eager func matmul"; const char* kEagerFuncGpuEvent = "eager_func_kernel_matmul"; CreateXEvent(&host_plane_builder, &main_thread, HostEventType::kEagerKernelExecute, 300, 400, {{StatType::kIsFunc, static_cast<int64_t>(1)}}); CreateXEvent(&host_plane_builder, &main_thread, kEagerFuncGpuLaunchEvent, 310, 390, {{StatType::kCorrelationId, correlation_id}}); CreateXEvent(&device_plane_builder, &gpu_stream, kEagerFuncGpuEvent, 500, 600, {{StatType::kCorrelationId, correlation_id}}); ++correlation_id; const char* kEagerOpCpuEvent = "eager_op_cpu_kernel:Matmul"; CreateXEvent(&host_plane_builder, &main_thread, HostEventType::kEagerKernelExecute, 400, 500, {{StatType::kIsFunc, static_cast<int64_t>(0)}}); CreateXEvent(&host_plane_builder, &main_thread, kEagerOpCpuEvent, 410, 490); const char* kEagerFuncCpuEvent = "eager_func_cpu_kernel:Matmul"; CreateXEvent(&host_plane_builder, &main_thread, HostEventType::kEagerKernelExecute, 500, 600, {{StatType::kIsFunc, static_cast<int64_t>(1)}}); CreateXEvent(&host_plane_builder, &main_thread, kEagerFuncCpuEvent, 510, 590); GroupTfEvents(&space); auto is_eager = [](const XEventVisitor& event) { auto eager_stats = event.GetStat(StatType::kIsEager); return eager_stats && eager_stats->IntValue(); }; XPlaneVisitor host_plane_visitor = CreateTfXPlaneVisitor(host_plane); int interested_events_encountered = 0; host_plane_visitor.ForEachLine([&](const XLineVisitor& line) { line.ForEachEvent([&](const XEventVisitor& event) { if (event.Name() == kEagerOpCpuEvent) { interested_events_encountered++; EXPECT_TRUE(is_eager(event)); } else if (event.Name() == kEagerFuncCpuEvent) { interested_events_encountered++; EXPECT_FALSE(is_eager(event)); } }); }); EXPECT_EQ(interested_events_encountered, 2); XPlaneVisitor device_plane_visitor = CreateTfXPlaneVisitor(device_plane); interested_events_encountered = 0; device_plane_visitor.ForEachLine([&](const XLineVisitor& line) { line.ForEachEvent([&](const XEventVisitor& event) { if (event.Name() == kTF1GpuEvent) { interested_events_encountered++; EXPECT_FALSE(is_eager(event)); } else if (event.Name() == kLegacyGpuEvent) { interested_events_encountered++; EXPECT_FALSE(is_eager(event)); } else if (event.Name() == kEagerOpGpuEvent) { interested_events_encountered++; EXPECT_TRUE(is_eager(event)); } else if (event.Name() == kEagerFuncGpuEvent) { interested_events_encountered++; EXPECT_FALSE(is_eager(event)); } }); }); EXPECT_EQ(interested_events_encountered, 4); } TEST(GroupEventsTest, FunctionOpTest) { constexpr int64_t kStepNum = 123; constexpr int64_t kStepId = 0; constexpr int64_t kCorrelationId = 100; XSpace space; XPlane* host_plane = GetOrCreateHostXPlane(&space); XPlaneBuilder host_plane_builder(host_plane); host_plane_builder.ReserveLines(2); auto main_thread = host_plane_builder.GetOrCreateLine(0); CreateXEvent(&host_plane_builder, &main_thread, HostEventType::kTraceContext, 0, 100, {{StatType::kStepNum, kStepNum}}); CreateXEvent(&host_plane_builder, &main_thread, HostEventType::kEagerKernelExecute, 10, 90); CreateXEvent(&host_plane_builder, &main_thread, HostEventType::kFunctionRun, 10, 90, {{StatType::kStepId, kStepId}, {StatType::kProducerType, kTfExecutor}, {StatType::kProducerId, kStepId}}); auto tf_executor_thread = host_plane_builder.GetOrCreateLine(1); CreateXEvent(&host_plane_builder, &tf_executor_thread, HostEventType::kExecutorStateProcess, 20, 80, {{StatType::kStepId, kStepId}, {StatType::kConsumerType, kTfExecutor}, {StatType::kConsumerId, kStepId}}); CreateXEvent(&host_plane_builder, &tf_executor_thread, "matmul", 30, 30, {{StatType::kCorrelationId, kCorrelationId}}); CreateXEvent(&host_plane_builder, &tf_executor_thread, "add:Add", 70, 20); XPlane* device_plane = space.add_planes(); XPlaneBuilder device_plane_builder(device_plane); device_plane_builder.ReserveLines(1); auto stream = device_plane_builder.GetOrCreateLine(0); CreateXEvent(&device_plane_builder, &stream, "matmul", 200, 300, {{StatType::kCorrelationId, kCorrelationId}}); GroupTfEvents(&space); XPlaneVisitor host_plane_visitor = CreateTfXPlaneVisitor(host_plane); const XEvent& cpu_tf_op = host_plane->lines(1).events(2); EXPECT_EQ(cpu_tf_op.stats_size(), 2); EXPECT_EQ(host_plane_visitor.GetStatType(cpu_tf_op.stats(1).metadata_id()), StatType::kIsEager); EXPECT_EQ(cpu_tf_op.stats(1).int64_value(), 0); XPlaneVisitor device_plane_visitor = CreateTfXPlaneVisitor(device_plane); const XEvent& gpu_kernel = device_plane->lines(0).events(0); EXPECT_EQ(gpu_kernel.stats_size(), 3); EXPECT_EQ(device_plane_visitor.GetStatType(gpu_kernel.stats(2).metadata_id()), StatType::kIsEager); EXPECT_EQ(gpu_kernel.stats(2).int64_value(), 0); } TEST(GroupEventsTest, SemanticArgTest) { constexpr int64_t kIsRoot = 1; constexpr int64_t kStepNum = 100; constexpr int64_t kContextType = 123; constexpr uint64 kContextId = 456; XSpace raw_space; XPlane* raw_plane = raw_space.add_planes(); XPlaneBuilder plane(raw_plane); plane.ReserveLines(2); auto root_producer = plane.GetOrCreateLine(0); CreateXEvent(&plane, &root_producer, HostEventType::kTraceContext, 0, 100, {{StatType::kIsRoot, kIsRoot}, {StatType::kStepNum, kStepNum}}); CreateXEvent(&plane, &root_producer, HostEventType::kFunctionRun, 10, 90, {{StatType::kProducerType, kContextType}, {StatType::kProducerId, kContextId}}); auto consumer = plane.GetOrCreateLine(1); CreateXEvent(&plane, &consumer, HostEventType::kExecutorStateProcess, 20, 80, {{StatType::kConsumerType, kContextType}, {StatType::kConsumerId, kContextId}}); GroupTfEvents(&raw_space); int num_events = 0; CreateTfXPlaneVisitor(raw_plane).ForEachLine([&](const XLineVisitor& line) { num_events += line.NumEvents(); line.ForEachEvent([&](const XEventVisitor& event) { std::optional<int64_t> group_id; if (std::optional<XStatVisitor> stat = event.GetStat(StatType::kGroupId)) { group_id = stat->IntValue(); } EXPECT_TRUE(group_id.has_value()); EXPECT_EQ(*group_id, 0); }); }); EXPECT_EQ(num_events, 3); } TEST(GroupEventsTest, SemanticIntArgNoMatchTest) { constexpr int64_t kIsRoot = 1; constexpr int64_t kStepNum = 100; constexpr int64_t kContextType = 123; constexpr uint64 kProducerId = 456; constexpr uint64 kConsumerId = 789; XSpace raw_space; XPlane* raw_plane = raw_space.add_planes(); XPlaneBuilder plane(raw_plane); plane.ReserveLines(2); auto root_producer = plane.GetOrCreateLine(0); CreateXEvent(&plane, &root_producer, HostEventType::kTraceContext, 0, 100, {{StatType::kIsRoot, kIsRoot}, {StatType::kStepNum, kStepNum}}); CreateXEvent(&plane, &root_producer, HostEventType::kFunctionRun, 10, 90, {{StatType::kProducerType, kContextType}, {StatType::kProducerId, kProducerId}}); auto consumer = plane.GetOrCreateLine(1); CreateXEvent(&plane, &consumer, HostEventType::kExecutorStateProcess, 20, 80, {{StatType::kConsumerType, kContextType}, {StatType::kConsumerId, kConsumerId}}); GroupTfEvents(&raw_space); int num_events = 0; CreateTfXPlaneVisitor(raw_plane).ForEachLine([&](const XLineVisitor& line) { num_events += line.NumEvents(); line.ForEachEvent([&](const XEventVisitor& event) { std::optional<int64_t> group_id; if (std::optional<XStatVisitor> stat = event.GetStat(StatType::kGroupId)) { group_id = stat->IntValue(); } if (event.Type() == HostEventType::kExecutorStateProcess) { EXPECT_FALSE(group_id.has_value()); } else { EXPECT_TRUE(group_id.has_value()); EXPECT_EQ(*group_id, 0); } }); }); EXPECT_EQ(num_events, 3); } TEST(GroupEventsTest, SemanticUintArgNoMatchTest) { constexpr int64_t kIsRoot = 1; constexpr int64_t kStepNum = 100; constexpr int64_t kContextType = 123; constexpr uint64 kProducerId = UINT64_MAX; constexpr uint64 kConsumerId = UINT64_MAX - 1; XSpace raw_space; XPlane* raw_plane = raw_space.add_planes(); XPlaneBuilder plane(raw_plane); plane.ReserveLines(2); auto root_producer = plane.GetOrCreateLine(0); CreateXEvent(&plane, &root_producer, HostEventType::kTraceContext, 0, 100, {{StatType::kIsRoot, kIsRoot}, {StatType::kStepNum, kStepNum}}); CreateXEvent(&plane, &root_producer, HostEventType::kFunctionRun, 10, 90, {{StatType::kProducerType, kContextType}, {StatType::kProducerId, kProducerId}}); auto consumer = plane.GetOrCreateLine(1); CreateXEvent(&plane, &consumer, HostEventType::kExecutorStateProcess, 20, 80, {{StatType::kConsumerType, kContextType}, {StatType::kConsumerId, kConsumerId}}); GroupTfEvents(&raw_space); int num_events = 0; CreateTfXPlaneVisitor(raw_plane).ForEachLine([&](const XLineVisitor& line) { num_events += line.NumEvents(); line.ForEachEvent([&](const XEventVisitor& event) { std::optional<int64_t> group_id; if (std::optional<XStatVisitor> stat = event.GetStat(StatType::kGroupId)) { group_id = stat->IntValue(); } if (event.Type() == HostEventType::kExecutorStateProcess) { EXPECT_FALSE(group_id.has_value()); } else { EXPECT_TRUE(group_id.has_value()); EXPECT_EQ(*group_id, 0); } }); }); EXPECT_EQ(num_events, 3); } TEST(GroupEventsTest, AsyncEventTest) { constexpr int64_t kIsRoot = 1; constexpr int64_t kIsAsync = 1; constexpr absl::string_view kParent = "parent"; constexpr absl::string_view kAsync = "async"; constexpr absl::string_view kChild = "child"; XSpace raw_space; XPlane* raw_plane = raw_space.add_planes(); XPlaneBuilder plane(raw_plane); plane.ReserveLines(1); auto line = plane.GetOrCreateLine(0); CreateXEvent(&plane, &line, kParent, 0, 100, {{StatType::kIsRoot, kIsRoot}}); CreateXEvent(&plane, &line, kAsync, 10, 200, {{StatType::kIsAsync, kIsAsync}}); CreateXEvent(&plane, &line, kChild, 20, 80); GroupTfEvents(&raw_space); CreateTfXPlaneVisitor(raw_plane).ForEachLine([&](const XLineVisitor& line) { EXPECT_EQ(line.NumEvents(), 3); line.ForEachEvent([&](const XEventVisitor& event) { std::optional<int64_t> group_id; if (std::optional<XStatVisitor> stat = event.GetStat(StatType::kGroupId)) { group_id = stat->IntValue(); } if (event.Name() == kAsync) { EXPECT_FALSE(group_id.has_value()); } else { EXPECT_TRUE(group_id.has_value()); EXPECT_EQ(*group_id, 0); } }); }); } TEST(GroupEventsTest, BatchingSessionTest) { constexpr absl::string_view kSchedule = "Schedule"; constexpr int64_t kBatchContextType = static_cast<int64_t>(ContextType::kSharedBatchScheduler); constexpr int64_t kBatchContextId = 123; constexpr int64_t kBatchingSessionRunRootLevel = 1; constexpr int64_t kProcessBatchRootLevel = 2; XSpace raw_space; XPlane* raw_plane = raw_space.add_planes(); XPlaneBuilder plane(raw_plane); plane.ReserveLines(2); auto request_thread = plane.GetOrCreateLine(0); CreateXEvent(&plane, &request_thread, HostEventType::kBatchingSessionRun, 0, 100, {{StatType::kIsRoot, kBatchingSessionRunRootLevel}}); CreateXEvent(&plane, &request_thread, kSchedule, 0, 100, {{StatType::kProducerType, kBatchContextType}, {StatType::kProducerId, kBatchContextId}}); CreateXEvent(&plane, &request_thread, HostEventType::kBatchingSessionRun, 200, 100, {{StatType::kIsRoot, kBatchingSessionRunRootLevel}}); CreateXEvent(&plane, &request_thread, kSchedule, 200, 100, {{StatType::kProducerType, kBatchContextType}, {StatType::kProducerId, kBatchContextId}}); auto batch_thread = plane.GetOrCreateLine(1); CreateXEvent(&plane, &batch_thread, HostEventType::kProcessBatch, 200, 100, {{StatType::kConsumerType, kBatchContextType}, {StatType::kConsumerId, kBatchContextId}, {StatType::kIsRoot, kProcessBatchRootLevel}}); EventForest event_forest; GroupTfEvents(&raw_space, &event_forest); const GroupMetadataMap& group_metadata_map = event_forest.GetGroupMetadataMap(); EXPECT_EQ(group_metadata_map.size(), 3); EXPECT_EQ(group_metadata_map.at(0).parents.size(), 2); EXPECT_EQ(group_metadata_map.at(1).children.size(), 1); EXPECT_EQ(group_metadata_map.at(2).children.size(), 1); uint64 num_checked = 0; CreateTfXPlaneVisitor(raw_plane).ForEachLine([&](const XLineVisitor& line) { line.ForEachEvent([&](const XEventVisitor& event) { std::optional<int64_t> group_id; if (std::optional<XStatVisitor> stat = event.GetStat(StatType::kGroupId)) { group_id = stat->IntValue(); } EXPECT_TRUE(group_id.has_value()); if (line.Id() == 0 && event.Type() == HostEventType::kBatchingSessionRun) { ++num_checked; } else if (line.Id() == 1 && event.Type() == HostEventType::kProcessBatch) { ++num_checked; } }); }); EXPECT_EQ(num_checked, 3); } TEST(GroupTPUEventsTest, TpuExecuteOpTest) { tensorflow::profiler::XSpace space; XPlaneBuilder host_plane_builder(GetOrCreateHostXPlane(&space)); host_plane_builder.ReserveLines(1); auto main_thread = host_plane_builder.GetOrCreateLine(0); CreateXEvent( &host_plane_builder, &main_thread, HostEventType::kExecutorStateProcess, 20, 50, {{StatType::kStepId, int64_t{123}}, {StatType::kIterNum, int64_t{456}}}); EventForest event_forest; GroupTpuEventsOSS(&space, {}, &event_forest); EXPECT_EQ(event_forest.GetGroupMetadataMap().size(), 1); XPlaneVisitor host_plane_visitor = CreateTfXPlaneVisitor(&space.planes(0)); host_plane_visitor.ForEachLine([&](const XLineVisitor& line) { line.ForEachEvent([&](const XEventVisitor& event) { EXPECT_TRUE(event.GetStat(StatType::kGroupId).has_value()); }); }); } TEST(GroupTPUEventsTest, TpuRequestTest) { tensorflow::profiler::XSpace space; XPlaneBuilder host_plane_builder(GetOrCreateHostXPlane(&space)); host_plane_builder.ReserveLines(1); auto main_thread = host_plane_builder.GetOrCreateLine(0); CreateXEvent(&host_plane_builder, &main_thread, HostEventType::kSessionRun, 0, 100, {{StatType::kIsRoot, int64_t{1}}}); CreateXEvent(&host_plane_builder, &main_thread, GetHostEventTypeStr(HostEventType::kEnqueueRequestLocked), 20, 50, {{StatType::kQueueAddr, int64_t{123}}, {StatType::kRequestId, int64_t{456}}}); EventForest event_forest; GroupTpuEventsOSS(&space, {}, &event_forest); EXPECT_EQ(event_forest.GetGroupMetadataMap().size(), 1); XPlaneVisitor host_plane_visitor = CreateTfXPlaneVisitor(&space.planes(0)); host_plane_visitor.ForEachLine([&](const XLineVisitor& line) { line.ForEachEvent([&](const XEventVisitor& event) { EXPECT_TRUE(event.GetStat(StatType::kGroupId).has_value()); }); }); } TEST(GroupTPUEventsTest, TpuProgramCallbackTest) { tensorflow::profiler::XSpace space; XPlaneBuilder host_plane_builder(GetOrCreateHostXPlane(&space)); host_plane_builder.ReserveLines(1); auto main_thread = host_plane_builder.GetOrCreateLine(0); CreateXEvent(&host_plane_builder, &main_thread, HostEventType::kSessionRun, 0, 100, {{StatType::kIsRoot, int64_t{1}}}); CreateXEvent(&host_plane_builder, &main_thread, GetHostEventTypeStr(HostEventType::kDoEnqueueProgram), 20, 50, {{StatType::kRunId, int64_t{123}}, {StatType::kQueueId, int64_t{0}}, {StatType::kDeviceOrdinal, int64_t{1}}}); EventForest event_forest; GroupTpuEventsOSS(&space, {}, &event_forest); EXPECT_EQ(event_forest.GetGroupMetadataMap().size(), 1); XPlaneVisitor host_plane_visitor = CreateTfXPlaneVisitor(&space.planes(0)); host_plane_visitor.ForEachLine([&](const XLineVisitor& line) { line.ForEachEvent([&](const XEventVisitor& event) { EXPECT_TRUE(event.GetStat(StatType::kGroupId).has_value()); }); }); } } } }
2,631
cpp
google/tsl
tpu_xplane_utils
tsl/profiler/utils/tpu_xplane_utils.cc
tsl/profiler/utils/tpu_xplane_utils_test.cc
#ifndef TENSORFLOW_TSL_PROFILER_UTILS_TPU_XPLANE_UTILS_H_ #define TENSORFLOW_TSL_PROFILER_UTILS_TPU_XPLANE_UTILS_H_ #include <optional> #include <vector> #include "absl/strings/string_view.h" #include "tsl/profiler/protobuf/xplane.pb.h" namespace tsl { namespace profiler { std::vector<const tensorflow::profiler::XPlane*> FindTensorCorePlanes( const tensorflow::profiler::XSpace& xspace); std::vector<tensorflow::profiler::XPlane*> FindMutableTensorCorePlanes( tensorflow::profiler::XSpace* xspace); std::optional<int> GetTensorCoreId(absl::string_view plane_name); } } #endif #include "tsl/profiler/utils/tpu_xplane_utils.h" #include <optional> #include <vector> #include "tsl/platform/regexp.h" #include "tsl/profiler/protobuf/xplane.pb.h" #include "tsl/profiler/utils/xplane_schema.h" #include "tsl/profiler/utils/xplane_utils.h" namespace tsl { namespace profiler { std::vector<const XPlane*> FindTensorCorePlanes(const XSpace& xspace) { return FindPlanes(xspace, [](const XPlane& xplane) { static const LazyRE2 re = {kTpuPlaneRegex}; return RE2::FullMatch(xplane.name(), *re); }); } std::vector<XPlane*> FindMutableTensorCorePlanes(XSpace* xspace) { return FindMutablePlanes(xspace, [](const XPlane& xplane) { static const LazyRE2 re = {kTpuPlaneRegex}; return RE2::FullMatch(xplane.name(), *re); }); } std::optional<int> GetTensorCoreId(absl::string_view plane_name) { int core_id = -1; if (RE2::FullMatch(plane_name, {kTpuPlaneRegex}, &core_id)) { return core_id; } return std::nullopt; } } }
#include "tsl/profiler/utils/tpu_xplane_utils.h" #include <vector> #include "absl/strings/str_cat.h" #include "tsl/platform/test.h" #include "tsl/profiler/protobuf/xplane.pb.h" #include "tsl/profiler/utils/xplane_schema.h" #include "tsl/profiler/utils/xplane_utils.h" namespace tsl { namespace profiler { namespace { using ::testing::UnorderedElementsAre; TEST(TpuXPlaneUtilsTest, GetTensorCoreXPlanesFromXSpace) { XSpace xspace; XPlane* p1 = FindOrAddMutablePlaneWithName(&xspace, TpuPlaneName(0)); XPlane* p2 = FindOrAddMutablePlaneWithName(&xspace, TpuPlaneName(1)); FindOrAddMutablePlaneWithName(&xspace, TpuPlaneName(2) + "Postfix"); std::vector<const XPlane*> xplanes = FindTensorCorePlanes(xspace); EXPECT_THAT(xplanes, UnorderedElementsAre(p1, p2)); } TEST(TpuXPlaneUtilsTest, GetMutableTensorCoreXPlanesFromXSpace) { XSpace xspace; XPlane* p1 = FindOrAddMutablePlaneWithName(&xspace, TpuPlaneName(0)); XPlane* p2 = FindOrAddMutablePlaneWithName(&xspace, TpuPlaneName(1)); FindOrAddMutablePlaneWithName(&xspace, TpuPlaneName(2) + "Postfix"); std::vector<XPlane*> xplanes = FindMutableTensorCorePlanes(&xspace); EXPECT_THAT(xplanes, UnorderedElementsAre(p1, p2)); } TEST(TpuXPlaneUtilsTest, GetTensorCoreIdFromPlaneName) { EXPECT_EQ(GetTensorCoreId(TpuPlaneName(0)), 0); } TEST(TpuXPlaneUtilsTest, IsNotTensorCorePlaneName) { EXPECT_FALSE(GetTensorCoreId("/metadata:0").has_value()); } TEST(TpuXPlaneUtilsTest, IsNotTensorCorePlaneNameWithPrefix) { EXPECT_FALSE( GetTensorCoreId(absl::StrCat("/prefix", TpuPlaneName(0))).has_value()); } } } }
2,632
cpp
google/tsl
xplane_to_trace_events
tsl/profiler/convert/xplane_to_trace_events.cc
tsl/profiler/convert/xplane_to_trace_events_test.cc
#ifndef TENSORFLOW_TSL_PROFILER_CONVERT_XPLANE_TO_TRACE_EVENTS_H_ #define TENSORFLOW_TSL_PROFILER_CONVERT_XPLANE_TO_TRACE_EVENTS_H_ #include <string> #include "tsl/platform/types.h" #include "tsl/profiler/convert/trace_container.h" #include "tsl/profiler/protobuf/xplane.pb.h" namespace tsl { namespace profiler { TraceContainer ConvertXSpaceToTraceContainer( const tensorflow::profiler::XSpace& xspace); void ConvertXSpaceToTraceEventsString( const tensorflow::profiler::XSpace& xspace, std::string* content); } } #endif #include "tsl/profiler/convert/xplane_to_trace_events.h" #include <stddef.h> #include <algorithm> #include <string> #include <utility> #include <vector> #include "absl/strings/string_view.h" #include "absl/types/optional.h" #include "tsl/platform/types.h" #include "tsl/profiler/protobuf/trace_events.pb.h" #include "tsl/profiler/protobuf/xplane.pb.h" #include "tsl/profiler/utils/tf_xplane_visitor.h" #include "tsl/profiler/utils/trace_utils.h" #include "tsl/profiler/utils/xplane_schema.h" #include "tsl/profiler/utils/xplane_utils.h" #include "tsl/profiler/utils/xplane_visitor.h" namespace tsl { namespace profiler { namespace { using tensorflow::profiler::XSpace; void BuildDeviceAndResources(uint32 device_id, const XPlaneVisitor& plane, Device* device) { device->set_name(std::string(plane.Name())); device->set_device_id(device_id); bool sort_by_ordinal = (device_id == kHostThreadsDeviceId); int ordinal = 0; plane.ForEachLine([&](const XLineVisitor& line) { uint32 resource_id = line.DisplayId(); Resource& resource = (*device->mutable_resources())[resource_id]; resource.set_resource_id(resource_id); resource.set_name(std::string(line.DisplayName())); if (sort_by_ordinal) { resource.set_sort_index(++ordinal); } }); } void ConvertXPlaneToTraceEvents(uint32 device_id, const XPlaneVisitor& xplane, TraceContainer& container) { BuildDeviceAndResources(device_id, xplane, container.MutableDevice(device_id)); xplane.ForEachLine([device_id, &container](const XLineVisitor& xline) { uint32 resource_id = xline.DisplayId(); if (xline.DisplayName() == tsl::profiler::kXlaAsyncOpLineName) { return; } xline.ForEachEvent( [device_id, resource_id, &container](const XEventVisitor& xevent) { int64_t event_type = xevent.Type().value_or(HostEventType::kUnknownHostEventType); if (IsInternalEvent(event_type)) return; TraceEvent* event = container.CreateEvent(); auto& args = *event->mutable_args(); event->set_device_id(device_id); event->set_resource_id(resource_id); if (xevent.HasDisplayName()) { event->set_name(std::string(xevent.DisplayName())); args["long_name"] = std::string(xevent.Name()); } else { event->set_name(std::string(xevent.Name())); } event->set_timestamp_ps(xevent.TimestampPs()); event->set_duration_ps(xevent.DurationPs()); auto for_each_stat = [&](const XStatVisitor& stat) { if (stat.ValueCase() == XStat::VALUE_NOT_SET) return; if (IsInternalStat(stat.Type())) return; if (stat.Type() == StatType::kStepName) { event->set_name(stat.ToString()); } args[std::string(stat.Name())] = stat.ToString(); }; xevent.Metadata().ForEachStat(for_each_stat); xevent.ForEachStat(for_each_stat); }); }); } } uint64 GetTraceViewerMaxEvents() { constexpr uint64 kMaxEvents = 1000000; char* max_events = getenv("TF_PROFILER_TRACE_VIEWER_MAX_EVENTS"); if (max_events != nullptr) { return std::stoull(max_events, nullptr, 10); } else { return kMaxEvents; } } TraceContainer ConvertXSpaceToTraceContainer(const XSpace& xspace) { TraceContainer container; const XPlane* host_plane = FindPlaneWithName(xspace, kHostThreadsPlaneName); if (host_plane != nullptr) { XPlaneVisitor xplane = CreateTfXPlaneVisitor(host_plane); ConvertXPlaneToTraceEvents(kHostThreadsDeviceId, xplane, container); } std::vector<const XPlane*> device_planes = FindPlanesWithPrefix(xspace, kGpuPlanePrefix); if (device_planes.empty()) { device_planes = FindPlanesWithPrefix(xspace, kTpuPlanePrefix); } if (device_planes.empty()) { device_planes = FindPlanesWithPrefix(xspace, kCustomPlanePrefix); } for (const XPlane* device_plane : device_planes) { XPlaneVisitor xplane = CreateTfXPlaneVisitor(device_plane); uint32 device_id = kFirstDeviceId + xplane.Id(); ConvertXPlaneToTraceEvents(device_id, xplane, container); } uint64 viewer_max_events = GetTraceViewerMaxEvents(); container.CapEvents(viewer_max_events); return container; } void ConvertXSpaceToTraceEventsString(const XSpace& xspace, std::string* content) { ConvertXSpaceToTraceContainer(xspace).FlushAndSerializeEvents(content); } } }
#include "tsl/profiler/convert/xplane_to_trace_events.h" #include <limits> #include <utility> #include "tsl/platform/test.h" #include "tsl/profiler/protobuf/trace_events.pb.h" #include "tsl/profiler/protobuf/xplane.pb.h" #include "tsl/profiler/utils/trace_utils.h" #include "tsl/profiler/utils/xplane_builder.h" #include "tsl/profiler/utils/xplane_schema.h" namespace tsl { namespace profiler { namespace { using tensorflow::profiler::XSpace; void CreateXSpace(XSpace* space) { XPlaneBuilder host_plane(space->add_planes()); host_plane.SetName(kHostThreadsPlaneName); XLineBuilder thread1 = host_plane.GetOrCreateLine(10); thread1.SetName("thread1"); XEventBuilder event1 = thread1.AddEvent(*host_plane.GetOrCreateEventMetadata("event1")); event1.SetTimestampNs(150000); event1.SetDurationNs(10000); event1.AddStatValue(*host_plane.GetOrCreateStatMetadata("tf_op"), *host_plane.GetOrCreateStatMetadata("Relu")); XLineBuilder thread2 = host_plane.GetOrCreateLine(20); thread2.SetName("thread2"); XEventBuilder event2 = thread2.AddEvent(*host_plane.GetOrCreateEventMetadata("event2")); event2.SetTimestampNs(160000); event2.SetDurationNs(10000); event2.AddStatValue(*host_plane.GetOrCreateStatMetadata("tf_op"), *host_plane.GetOrCreateStatMetadata("Conv2D")); XPlaneBuilder device_plane(space->add_planes()); device_plane.SetName(GpuPlaneName(0)); device_plane.SetId(0); XLineBuilder stream1 = device_plane.GetOrCreateLine(30); stream1.SetName("gpu stream 1"); XEventBuilder event3 = stream1.AddEvent(*device_plane.GetOrCreateEventMetadata("kernel1")); event3.SetTimestampNs(180000); event3.SetDurationNs(10000); event3.AddStatValue(*device_plane.GetOrCreateStatMetadata("correlation id"), 55); } TEST(ConvertXPlaneToTraceEvents, Convert) { XSpace xspace; CreateXSpace(&xspace); TraceContainer container = ConvertXSpaceToTraceContainer(xspace); ASSERT_EQ(container.trace().devices_size(), 2); EXPECT_EQ( container.trace().devices().at(kHostThreadsDeviceId).resources_size(), 2); EXPECT_EQ(container.trace().devices().at(kFirstDeviceId).resources_size(), 1); EXPECT_EQ(container.UnsortedEvents().size(), 3); } TEST(ConvertXPlaneToTraceEvents, SkipAsyncOps) { XSpace xspace; XPlaneBuilder device_plane(xspace.add_planes()); device_plane.SetName(GpuPlaneName(0)); XLineBuilder async_ops = device_plane.GetOrCreateLine(10); async_ops.SetName(kXlaAsyncOpLineName); XEventBuilder event1 = async_ops.AddEvent(*device_plane.GetOrCreateEventMetadata("event1")); event1.SetTimestampNs(100); event1.SetDurationNs(1); TraceContainer container = ConvertXSpaceToTraceContainer(xspace); ASSERT_THAT(container.UnsortedEvents(), ::testing::IsEmpty()); } } } }
2,633
cpp
google/tsl
trace_container
tsl/profiler/convert/trace_container.cc
tsl/profiler/convert/trace_container_test.cc
#ifndef TENSORFLOW_TSL_PROFILER_CONVERT_TRACE_CONTAINER_H_ #define TENSORFLOW_TSL_PROFILER_CONVERT_TRACE_CONTAINER_H_ #include <string> #include <string_view> #include <vector> #include "tsl/profiler/protobuf/trace_events.pb.h" namespace tsl { namespace profiler { using tsl::profiler::Device; using tsl::profiler::Trace; using tsl::profiler::TraceEvent; template <typename Event> class AnyTraceContainer { public: virtual ~AnyTraceContainer() = default; virtual TraceEvent* CreateEvent() = 0; virtual const std::vector<TraceEvent*>& UnsortedEvents() const = 0; }; class TraceContainer : public AnyTraceContainer<TraceEvent> { public: TraceContainer() = default; ~TraceContainer() final { for (const TraceEvent* event : events_) { delete event; } } const Trace& trace() const { return metadata_; } const std::vector<TraceEvent*>& UnsortedEvents() const final { return events_; } void CapEvents(uint32_t max_count); Device* MutableDevice(uint32_t device_id) { return &(*metadata_.mutable_devices())[device_id]; } TraceEvent* CreateEvent() final { TraceEvent* event = new TraceEvent; events_.push_back(event); return event; } void FlushAndSerializeEvents(std::string* output); bool ParseMetadataFromString(const std::string& description); private: Trace metadata_; std::vector<TraceEvent*> events_; }; } } #endif #include "tsl/profiler/convert/trace_container.h" #include <algorithm> #include <string> #include <string_view> #include <vector> #include "tsl/platform/protobuf.h" namespace tsl { namespace profiler { bool TraceContainer::ParseMetadataFromString(const std::string& description) { return protobuf::TextFormat::ParseFromString(description, &metadata_); } void TraceContainer::CapEvents(const uint32_t max_count) { const size_t total_count = events_.size(); if (total_count <= max_count) { return; } const std::vector<TraceEvent*>::iterator end = events_.begin() + max_count; std::partial_sort( events_.begin(), end, events_.end(), [](const TraceEvent* const lhs, const TraceEvent* const rhs) -> bool { return lhs->timestamp_ps() < rhs->timestamp_ps(); }); for (std::vector<TraceEvent*>::iterator i = end; i != events_.end(); ++i) { delete *i; } events_.erase(end, events_.end()); } void TraceContainer::FlushAndSerializeEvents(std::string* const output) { Trace trace = metadata_; for (TraceEvent* const event : events_) { trace.mutable_trace_events()->AddAllocated(event); } events_.clear(); trace.SerializeToString(output); } } }
#include "tsl/profiler/convert/trace_container.h" #include <string> #include "tsl/platform/protobuf.h" #include "tsl/platform/test.h" namespace tsl { namespace profiler { namespace { void PopulateDummyEvent(TraceEvent* const event) { event->set_device_id(1); event->set_resource_id(2); event->set_name("A"); event->set_timestamp_ps(3); event->set_duration_ps(4); } TEST(TraceContainer, TraceEventAllocation) { TraceContainer container; PopulateDummyEvent(container.CreateEvent()); } TEST(TraceContainer, FlushAndSerializeEvents) { TraceContainer container; PopulateDummyEvent(container.CreateEvent()); EXPECT_EQ(container.UnsortedEvents().size(), 1); std::string serialized; container.FlushAndSerializeEvents(&serialized); EXPECT_EQ(container.UnsortedEvents().size(), 0); PopulateDummyEvent(container.CreateEvent()); EXPECT_EQ(container.UnsortedEvents().size(), 1); std::string reserialized; container.FlushAndSerializeEvents(&reserialized); EXPECT_EQ(serialized, reserialized); EXPECT_EQ(container.UnsortedEvents().size(), 0); Trace trace; trace.ParseFromString(reserialized); EXPECT_EQ(trace.trace_events_size(), 1); } TEST(TraceContainer, CapEvents) { TraceContainer container; for (int i = 0; i < 100; i++) { container.CreateEvent()->set_timestamp_ps((100 - i) % 50); } container.CapEvents(101); EXPECT_EQ(container.UnsortedEvents().size(), 100); container.CapEvents(100); EXPECT_EQ(container.UnsortedEvents().size(), 100); container.CapEvents(99); EXPECT_EQ(container.UnsortedEvents().size(), 99); container.CapEvents(50); EXPECT_EQ(container.UnsortedEvents().size(), 50); for (const TraceEvent* const event : container.UnsortedEvents()) { EXPECT_LT(event->timestamp_ps(), 25); } } } } }
2,634
cpp
google/tsl
trace_events_to_json
tsl/profiler/convert/trace_events_to_json.cc
tsl/profiler/convert/trace_events_to_json_test.cc
#ifndef TENSORFLOW_TSL_PROFILER_CONVERT_TRACE_EVENTS_TO_JSON_H_ #define TENSORFLOW_TSL_PROFILER_CONVERT_TRACE_EVENTS_TO_JSON_H_ #include <string> #include "tsl/platform/types.h" #include "tsl/profiler/convert/trace_container.h" namespace tsl { namespace profiler { std::string TraceContainerToJson(const TraceContainer& container); } } #endif #include "tsl/profiler/convert/trace_events_to_json.h" #include <algorithm> #include <string> #include <utility> #include "absl/algorithm/container.h" #include "absl/strings/str_cat.h" #include "json/json.h" #include "tsl/platform/protobuf.h" #include "tsl/platform/types.h" #include "tsl/profiler/protobuf/trace_events.pb.h" #include "tsl/profiler/utils/format_utils.h" #include "tsl/profiler/utils/math_utils.h" namespace tsl { namespace profiler { namespace { inline std::string PicosToMicrosString(uint64 ps) { return MaxPrecision(PicoToMicro(ps)); } inline std::string JsonString(const std::string& s) { return Json::valueToQuotedString(s.c_str()); } template <typename Map> std::vector<const typename Map::value_type*> SortByKey(const Map& m) { std::vector<const typename Map::value_type*> pairs; pairs.reserve(m.size()); for (const auto& pair : m) { pairs.push_back(&pair); } absl::c_sort(pairs, [](const typename Map::value_type* a, const typename Map::value_type* b) { return a->first < b->first; }); return pairs; } inline void AddDeviceMetadata(uint32 device_id, const Device& device, std::string* json) { if (!device.name().empty()) { absl::StrAppend(json, R"({"ph":"M","pid":)", device_id, R"(,"name":"process_name","args":{"name":)", JsonString(device.name()), "}},"); } absl::StrAppend(json, R"({"ph":"M","pid":)", device_id, R"(,"name":"process_sort_index","args":{"sort_index":)", device_id, "}},"); } inline void AddResourceMetadata(uint32 device_id, uint32 resource_id, const Resource& resource, std::string* json) { if (!resource.name().empty()) { absl::StrAppend(json, R"({"ph":"M","pid":)", device_id, R"(,"tid":)", resource_id, R"(,"name":"thread_name","args":{"name":)", JsonString(resource.name()), "}},"); } uint32 sort_index = resource.sort_index() ? resource.sort_index() : resource_id; absl::StrAppend(json, R"({"ph":"M","pid":)", device_id, R"(,"tid":)", resource_id, R"(,"name":"thread_sort_index")", R"(,"args":{"sort_index":)", sort_index, "}},"); } inline void AddTraceEvent(const TraceEvent& event, string* json) { auto duration_ps = std::max(event.duration_ps(), protobuf_uint64{1}); absl::StrAppend(json, R"({"ph":"X","pid":)", event.device_id(), R"(,"tid":)", event.resource_id(), R"(,"ts":)", PicosToMicrosString(event.timestamp_ps()), R"(,"dur":)", PicosToMicrosString(duration_ps), R"(,"name":)", JsonString(event.name())); if (!event.args().empty()) { absl::StrAppend(json, R"(,"args":{)"); for (const auto* arg : SortByKey(event.args())) { absl::StrAppend(json, JsonString(arg->first), ":", JsonString(arg->second), ","); } json->back() = '}'; } absl::StrAppend(json, "},"); } } std::string TraceContainerToJson(const TraceContainer& container) { std::string json = R"({"displayTimeUnit":"ns","metadata":{"highres-ticks":true},)" R"("traceEvents":[)"; for (const auto* id_and_device : SortByKey(container.trace().devices())) { uint32 device_id = id_and_device->first; const Device& device = id_and_device->second; AddDeviceMetadata(device_id, device, &json); for (const auto* id_and_resource : SortByKey(device.resources())) { uint32 resource_id = id_and_resource->first; const Resource& resource = id_and_resource->second; AddResourceMetadata(device_id, resource_id, resource, &json); } } for (const TraceEvent* const event : container.UnsortedEvents()) { AddTraceEvent(*event, &json); } absl::StrAppend(&json, "{}]}"); return json; } } }
#include "tsl/profiler/convert/trace_events_to_json.h" #include <string> #include "json/json.h" #include "tsl/platform/protobuf.h" #include "tsl/platform/test.h" #include "tsl/profiler/convert/trace_container.h" #include "tsl/profiler/protobuf/trace_events.pb.h" namespace tsl { namespace profiler { namespace { Json::Value ToJsonValue(const std::string& json_str) { Json::Value json; Json::Reader reader; EXPECT_TRUE(reader.parse(json_str, json)); return json; } TEST(TraceEventsToJson, JsonConversion) { const std::string metadata_string = R"pb( devices { key: 2 value { name: 'D2' device_id: 2 resources { key: 2 value { resource_id: 2 name: 'R2.2' } } } } devices { key: 1 value { name: 'D1' device_id: 1 resources { key: 2 value { resource_id: 1 name: 'R1.2' } } } } )pb"; TraceContainer container; EXPECT_TRUE(container.ParseMetadataFromString(metadata_string)); TraceEvent* event = container.CreateEvent(); event->set_device_id(1); event->set_resource_id(2); event->set_name("E1.2.1"); event->set_timestamp_ps(100000); event->set_duration_ps(10000); event->mutable_args()->insert({"long_name", "E1.2.1 long"}); event->mutable_args()->insert({"arg2", "arg2 val"}); event = container.CreateEvent(); event->set_device_id(2); event->set_resource_id(2); event->set_name("E2.2.1 # \"comment\""); event->set_timestamp_ps(105000); container.CapEvents(2); Json::Value json = ToJsonValue(TraceContainerToJson(container)); Json::Value expected_json = ToJsonValue(R"( { "displayTimeUnit": "ns", "metadata": { "highres-ticks": true }, "traceEvents": [ {"ph":"M", "pid":1, "name":"process_name", "args":{"name":"D1"}}, {"ph":"M", "pid":1, "name":"process_sort_index", "args":{"sort_index":1}}, {"ph":"M", "pid":1, "tid":2, "name":"thread_name", "args":{"name":"R1.2"}}, {"ph":"M", "pid":1, "tid":2, "name":"thread_sort_index", "args":{"sort_index":2}}, {"ph":"M", "pid":2, "name":"process_name", "args":{"name":"D2"}}, {"ph":"M", "pid":2, "name":"process_sort_index", "args":{"sort_index":2}}, {"ph":"M", "pid":2, "tid":2, "name":"thread_name", "args":{"name":"R2.2"}}, {"ph":"M", "pid":2, "tid":2, "name":"thread_sort_index", "args":{"sort_index":2}}, { "ph" : "X", "pid" : 1, "tid" : 2, "name" : "E1.2.1", "ts" : 0.1, "dur" : 0.01, "args" : {"arg2": "arg2 val", "long_name": "E1.2.1 long"} }, { "ph" : "X", "pid" : 2, "tid" : 2, "name" : "E2.2.1 # \"comment\"", "ts" : 0.105, "dur" : 1e-6 }, {} ] })"); EXPECT_EQ(json, expected_json); } } } }
2,635
cpp
google/tsl
remote_profiler_session_manager
tsl/profiler/rpc/client/remote_profiler_session_manager.cc
tsl/profiler/rpc/client/remote_profiler_session_manager_test.cc
#ifndef TENSORFLOW_TSL_PROFILER_RPC_CLIENT_REMOTE_PROFILER_SESSION_MANAGER_H_ #define TENSORFLOW_TSL_PROFILER_RPC_CLIENT_REMOTE_PROFILER_SESSION_MANAGER_H_ #include <functional> #include <memory> #include <vector> #include "absl/strings/string_view.h" #include "tsl/platform/macros.h" #include "tsl/platform/mutex.h" #include "tsl/platform/status.h" #include "tsl/platform/thread_annotations.h" #include "tsl/platform/types.h" #include "tsl/profiler/rpc/client/profiler_client.h" namespace tsl { namespace profiler { using AddressResolver = std::function<std::string(absl::string_view)>; class RemoteProfilerSessionManager { public: struct Response { std::string service_address; std::unique_ptr<tensorflow::ProfileResponse> profile_response; absl::Status status; }; static std::unique_ptr<RemoteProfilerSessionManager> Create( const tensorflow::RemoteProfilerSessionManagerOptions& options, const tensorflow::ProfileRequest& request, absl::Status& out_status, AddressResolver resolver = nullptr); std::vector<Response> WaitForCompletion(); RemoteProfilerSessionManager(const RemoteProfilerSessionManager&) = delete; RemoteProfilerSessionManager& operator=(const RemoteProfilerSessionManager&) = delete; ~RemoteProfilerSessionManager(); private: explicit RemoteProfilerSessionManager( tensorflow::RemoteProfilerSessionManagerOptions options, tensorflow::ProfileRequest request, AddressResolver resolver); absl::Status Init(); mutex mutex_; tensorflow::RemoteProfilerSessionManagerOptions options_ TF_GUARDED_BY(mutex_); tensorflow::ProfileRequest request_ TF_GUARDED_BY(mutex_); std::vector<std::unique_ptr<RemoteProfilerSession>> clients_ TF_GUARDED_BY(mutex_); AddressResolver resolver_ TF_GUARDED_BY(mutex_); }; } } #endif #include "tsl/profiler/rpc/client/remote_profiler_session_manager.h" #include <cstddef> #include <memory> #include "absl/memory/memory.h" #include "absl/strings/string_view.h" #include "absl/time/clock.h" #include "absl/time/time.h" #include "tsl/platform/env_time.h" #include "tsl/platform/errors.h" #include "tsl/platform/logging.h" #include "tsl/platform/types.h" #include "tsl/profiler/rpc/client/profiler_client.h" #include "tsl/profiler/utils/time_utils.h" namespace tsl { namespace profiler { using tensorflow::ProfileRequest; using tensorflow::RemoteProfilerSessionManagerOptions; std::unique_ptr<RemoteProfilerSessionManager> RemoteProfilerSessionManager::Create( const RemoteProfilerSessionManagerOptions& options, const ProfileRequest& request, absl::Status& out_status, AddressResolver resolver) { VLOG(1) << "Creating a RemoteProfilerSessionManager."; auto session_manager = absl::WrapUnique( new RemoteProfilerSessionManager(options, request, resolver)); out_status = session_manager->Init(); if (!out_status.ok()) { return nullptr; } return session_manager; } RemoteProfilerSessionManager::RemoteProfilerSessionManager( RemoteProfilerSessionManagerOptions options, ProfileRequest request, AddressResolver resolver) : options_(options), request_(request) { if (resolver) { resolver_ = resolver; } else { resolver_ = [](absl::string_view addr) { return std::string(addr); }; } } RemoteProfilerSessionManager::~RemoteProfilerSessionManager() { VLOG(2) << "Destroying RemoteProfilerSessionManager."; } absl::Status RemoteProfilerSessionManager::Init() { mutex_lock lock(mutex_); VLOG(1) << "SessionManager initializing."; const absl::Time session_created_ts = absl::FromUnixNanos(options_.session_creation_timestamp_ns()); const absl::Time deadline = session_created_ts + absl::Milliseconds(options_.max_session_duration_ms()); LOG(INFO) << "Deadline set to " << deadline << " because max_session_duration_ms was " << options_.max_session_duration_ms() << " and session_creation_timestamp_ns was " << options_.session_creation_timestamp_ns() << " [" << session_created_ts << "]"; clients_.reserve(options_.service_addresses_size()); ProfileRequest request = request_; for (auto& service_address : options_.service_addresses()) { std::string resolved_service_address = resolver_(service_address); request.set_host_name(resolved_service_address); auto client = RemoteProfilerSession::Create(resolved_service_address, deadline, request); clients_.push_back(std::move(client)); } LOG(INFO) << "Issued Profile gRPC to " << clients_.size() << " clients"; return absl::OkStatus(); } std::vector<RemoteProfilerSessionManager::Response> RemoteProfilerSessionManager::WaitForCompletion() { mutex_lock lock(mutex_); std::vector<RemoteProfilerSessionManager::Response> remote_responses( clients_.size()); for (int32_t idx = 0; idx < clients_.size(); ++idx) { auto& remote_response = remote_responses[idx]; auto* client = clients_[idx].get(); remote_response.profile_response = client->WaitForCompletion(remote_response.status); remote_response.service_address = std::string(client->GetServiceAddress()); } return remote_responses; } } }
#include "tsl/profiler/rpc/client/remote_profiler_session_manager.h" #include <memory> #include <string> #include <vector> #include "absl/status/status.h" #include "absl/time/clock.h" #include "absl/time/time.h" #include "tsl/platform/errors.h" #include "tsl/platform/status.h" #include "tsl/platform/test.h" #include "tsl/platform/types.h" #include "tsl/profiler/protobuf/profiler_options.pb.h" #include "tsl/profiler/protobuf/profiler_service.pb.h" #include "tsl/profiler/rpc/client/profiler_client_test_util.h" namespace tsl { namespace profiler { namespace { using tensorflow::ProfileRequest; using tensorflow::RemoteProfilerSessionManagerOptions; using ::tsl::profiler::test::DurationApproxLess; using ::tsl::profiler::test::DurationNear; using ::tsl::profiler::test::StartServer; using ::tsl::testing::TmpDir; using Response = tsl::profiler::RemoteProfilerSessionManager::Response; constexpr double kGracePeriodSeconds = 10.0; ProfileRequest PopulateProfileRequest( absl::string_view repository_root, absl::string_view session_id, absl::string_view host_name, const RemoteProfilerSessionManagerOptions& options) { constexpr uint64 kMaxEvents = 1000000; const absl::string_view kXPlanePb = "xplane.pb"; ProfileRequest request; request.set_duration_ms(options.profiler_options().duration_ms()); request.set_max_events(kMaxEvents); request.set_repository_root(repository_root.data(), repository_root.size()); request.set_session_id(session_id.data(), session_id.size()); request.set_host_name(host_name.data(), host_name.size()); request.add_tools(kXPlanePb.data(), kXPlanePb.size()); *request.mutable_opts() = options.profiler_options(); return request; } TEST(RemoteProfilerSessionManagerTest, Simple) { absl::Duration duration = absl::Milliseconds(30); RemoteProfilerSessionManagerOptions options; *options.mutable_profiler_options() = tsl::ProfilerSession::DefaultOptions(); options.mutable_profiler_options()->set_duration_ms( absl::ToInt64Milliseconds(duration)); std::string service_address; auto server = StartServer(duration, &service_address); options.add_service_addresses(service_address); absl::Time approx_start = absl::Now(); absl::Duration grace = absl::Seconds(kGracePeriodSeconds); absl::Duration max_duration = duration + grace; options.set_max_session_duration_ms(absl::ToInt64Milliseconds(max_duration)); options.set_session_creation_timestamp_ns(absl::ToUnixNanos(approx_start)); ProfileRequest request = PopulateProfileRequest(TmpDir(), "session_id", service_address, options); absl::Status status; auto sessions = RemoteProfilerSessionManager::Create(options, request, status); EXPECT_TRUE(status.ok()); std::vector<Response> responses = sessions->WaitForCompletion(); absl::Duration elapsed = absl::Now() - approx_start; ASSERT_EQ(responses.size(), 1); EXPECT_TRUE(responses.back().status.ok()); EXPECT_TRUE(responses.back().profile_response->empty_trace()); EXPECT_EQ(responses.back().profile_response->tool_data_size(), 0); EXPECT_THAT(elapsed, DurationApproxLess(max_duration)); } TEST(RemoteProfilerSessionManagerTest, ExpiredDeadline) { absl::Duration duration = absl::Milliseconds(30); RemoteProfilerSessionManagerOptions options; *options.mutable_profiler_options() = tsl::ProfilerSession::DefaultOptions(); options.mutable_profiler_options()->set_duration_ms( absl::ToInt64Milliseconds(duration)); std::string service_address; auto server = StartServer(duration, &service_address); options.add_service_addresses(service_address); absl::Duration grace = absl::Seconds(kGracePeriodSeconds); absl::Duration max_duration = duration + grace; options.set_max_session_duration_ms(absl::ToInt64Milliseconds(max_duration)); options.set_session_creation_timestamp_ns(0); absl::Time approx_start = absl::Now(); ProfileRequest request = PopulateProfileRequest(TmpDir(), "session_id", service_address, options); absl::Status status; auto sessions = RemoteProfilerSessionManager::Create(options, request, status); EXPECT_TRUE(status.ok()); std::vector<Response> responses = sessions->WaitForCompletion(); absl::Duration elapsed = absl::Now() - approx_start; EXPECT_THAT(elapsed, DurationNear(absl::Seconds(0))); ASSERT_EQ(responses.size(), 1); EXPECT_TRUE(absl::IsDeadlineExceeded(responses.back().status)); EXPECT_TRUE(responses.back().profile_response->empty_trace()); EXPECT_EQ(responses.back().profile_response->tool_data_size(), 0); } TEST(RemoteProfilerSessionManagerTest, LongSession) { absl::Duration duration = absl::Seconds(3); RemoteProfilerSessionManagerOptions options; *options.mutable_profiler_options() = tsl::ProfilerSession::DefaultOptions(); options.mutable_profiler_options()->set_duration_ms( absl::ToInt64Milliseconds(duration)); std::string service_address; auto server = StartServer(duration, &service_address); options.add_service_addresses(service_address); absl::Time approx_start = absl::Now(); absl::Duration grace = absl::Seconds(kGracePeriodSeconds); absl::Duration max_duration = duration + grace; options.set_max_session_duration_ms(absl::ToInt64Milliseconds(max_duration)); options.set_session_creation_timestamp_ns(absl::ToUnixNanos(approx_start)); ProfileRequest request = PopulateProfileRequest(TmpDir(), "session_id", service_address, options); absl::Status status; auto sessions = RemoteProfilerSessionManager::Create(options, request, status); EXPECT_TRUE(status.ok()); std::vector<Response> responses = sessions->WaitForCompletion(); absl::Duration elapsed = absl::Now() - approx_start; ASSERT_EQ(responses.size(), 1); EXPECT_TRUE(responses.back().status.ok()); EXPECT_TRUE(responses.back().profile_response->empty_trace()); EXPECT_EQ(responses.back().profile_response->tool_data_size(), 0); EXPECT_THAT(elapsed, DurationApproxLess(max_duration)); } } } }
2,636
cpp
google/tsl
profiler_client
tsl/profiler/rpc/client/profiler_client.cc
tsl/profiler/rpc/client/profiler_client_test.cc
#ifndef TENSORFLOW_TSL_PROFILER_RPC_CLIENT_PROFILER_CLIENT_H_ #define TENSORFLOW_TSL_PROFILER_RPC_CLIENT_PROFILER_CLIENT_H_ #include <memory> #include <string> #include "absl/strings/string_view.h" #include "absl/time/time.h" #include "tsl/platform/status.h" #include "tsl/profiler/protobuf/profiler_analysis.grpc.pb.h" #include "tsl/profiler/protobuf/profiler_service.grpc.pb.h" namespace tsl { namespace profiler { absl::Status ProfileGrpc(const std::string& service_address, const tensorflow::ProfileRequest& request, tensorflow::ProfileResponse* response); absl::Status NewSessionGrpc(const std::string& service_address, const tensorflow::NewProfileSessionRequest& request, tensorflow::NewProfileSessionResponse* response); absl::Status MonitorGrpc(const std::string& service_address, const tensorflow::MonitorRequest& request, tensorflow::MonitorResponse* response); class RemoteProfilerSession { public: static std::unique_ptr<RemoteProfilerSession> Create( const std::string& service_address, absl::Time deadline, const tensorflow::ProfileRequest& profile_request); RemoteProfilerSession(const RemoteProfilerSession&) = delete; RemoteProfilerSession& operator=(const RemoteProfilerSession&) = delete; ~RemoteProfilerSession(); absl::string_view GetServiceAddress() const { return service_address_; } std::unique_ptr<tensorflow::ProfileResponse> WaitForCompletion( absl::Status& out_status); private: explicit RemoteProfilerSession( const std::string& service_addr, absl::Time deadline, const tensorflow::ProfileRequest& profile_request); void ProfileAsync(); absl::Status status_on_completion_; std::unique_ptr<tensorflow::ProfileResponse> response_; std::string service_address_; std::unique_ptr<tensorflow::grpc::ProfilerService::Stub> stub_; absl::Time deadline_; ::grpc::ClientContext grpc_context_; std::unique_ptr< ::grpc::ClientAsyncResponseReader<tensorflow::ProfileResponse>> rpc_; ::grpc::Status grpc_status_ = ::grpc::Status::OK; ::grpc::CompletionQueue cq_; tensorflow::ProfileRequest profile_request_; }; } } #endif #include "tsl/profiler/rpc/client/profiler_client.h" #include <limits> #include <memory> #include "grpcpp/grpcpp.h" #include "absl/memory/memory.h" #include "absl/time/clock.h" #include "absl/time/time.h" #include "tsl/platform/errors.h" #include "tsl/platform/logging.h" #include "tsl/platform/status.h" #include "tsl/platform/types.h" #include "tsl/protobuf/error_codes.pb.h" namespace tsl { namespace profiler { namespace { using tensorflow::MonitorRequest; using tensorflow::MonitorResponse; using tensorflow::NewProfileSessionRequest; using tensorflow::NewProfileSessionResponse; using tensorflow::ProfileRequest; using tensorflow::ProfileResponse; inline absl::Status FromGrpcStatus(const ::grpc::Status& s) { return s.ok() ? absl::OkStatus() : absl::Status(static_cast<absl::StatusCode>(s.error_code()), s.error_message()); } template <typename T> std::unique_ptr<typename T::Stub> CreateStub( const std::string& service_address) { ::grpc::ChannelArguments channel_args; channel_args.SetMaxReceiveMessageSize(std::numeric_limits<int32>::max()); auto channel = ::grpc::CreateCustomChannel( service_address, ::grpc::InsecureChannelCredentials(), channel_args); if (!channel) { LOG(ERROR) << "Unable to create channel" << service_address; return nullptr; } return T::NewStub(channel); } } absl::Status ProfileGrpc(const std::string& service_address, const ProfileRequest& request, ProfileResponse* response) { ::grpc::ClientContext context; std::unique_ptr<tensorflow::grpc::ProfilerService::Stub> stub = CreateStub<tensorflow::grpc::ProfilerService>(service_address); TF_RETURN_IF_ERROR( FromGrpcStatus(stub->Profile(&context, request, response))); return absl::OkStatus(); } absl::Status NewSessionGrpc(const std::string& service_address, const NewProfileSessionRequest& request, NewProfileSessionResponse* response) { ::grpc::ClientContext context; std::unique_ptr<tensorflow::grpc::ProfileAnalysis::Stub> stub = CreateStub<tensorflow::grpc::ProfileAnalysis>(service_address); TF_RETURN_IF_ERROR( FromGrpcStatus(stub->NewSession(&context, request, response))); return absl::OkStatus(); } absl::Status MonitorGrpc(const std::string& service_address, const MonitorRequest& request, MonitorResponse* response) { ::grpc::ClientContext context; std::unique_ptr<tensorflow::grpc::ProfilerService::Stub> stub = CreateStub<tensorflow::grpc::ProfilerService>(service_address); TF_RETURN_IF_ERROR( FromGrpcStatus(stub->Monitor(&context, request, response))); return absl::OkStatus(); } std::unique_ptr<RemoteProfilerSession> RemoteProfilerSession::Create( const std::string& service_address, absl::Time deadline, const ProfileRequest& profile_request) { auto instance = absl::WrapUnique( new RemoteProfilerSession(service_address, deadline, profile_request)); instance->ProfileAsync(); return instance; } RemoteProfilerSession::RemoteProfilerSession( const std::string& service_address, absl::Time deadline, const ProfileRequest& profile_request) : response_(absl::make_unique<ProfileResponse>()), service_address_(service_address), stub_(CreateStub<tensorflow::grpc::ProfilerService>(service_address_)), deadline_(deadline), profile_request_(profile_request) { response_->set_empty_trace(true); } RemoteProfilerSession::~RemoteProfilerSession() { absl::Status dummy; WaitForCompletion(dummy); grpc_context_.TryCancel(); } void RemoteProfilerSession::ProfileAsync() { LOG(INFO) << "Asynchronous gRPC Profile() to " << service_address_; grpc_context_.set_deadline(absl::ToChronoTime(deadline_)); VLOG(1) << "Deadline set to " << deadline_; rpc_ = stub_->AsyncProfile(&grpc_context_, profile_request_, &cq_); rpc_->Finish(response_.get(), &grpc_status_, static_cast<void*>(&status_on_completion_)); VLOG(2) << "Asynchronous gRPC Profile() issued." << absl::Now(); } std::unique_ptr<ProfileResponse> RemoteProfilerSession::WaitForCompletion( absl::Status& out_status) { if (!response_) { out_status = errors::FailedPrecondition( "WaitForCompletion must only be called once."); return nullptr; } LOG(INFO) << "Waiting for completion."; void* got_tag = nullptr; bool ok = false; bool success = cq_.Next(&got_tag, &ok); if (!success || !ok || got_tag == nullptr) { out_status = errors::Internal("Missing or invalid event from completion queue."); return nullptr; } VLOG(1) << "Writing out status."; DCHECK_EQ(got_tag, &status_on_completion_); status_on_completion_.Update(FromGrpcStatus(grpc_status_)); if (status_on_completion_.code() == error::DEADLINE_EXCEEDED) { LOG(WARNING) << status_on_completion_; } else if (!status_on_completion_.ok()) { LOG(ERROR) << status_on_completion_; } out_status = status_on_completion_; return std::move(response_); } } }
#include "tsl/profiler/rpc/client/profiler_client.h" #include <memory> #include <string> #include "absl/time/clock.h" #include "absl/time/time.h" #include "tsl/platform/errors.h" #include "tsl/platform/status.h" #include "tsl/platform/test.h" #include "tsl/platform/types.h" #include "tsl/profiler/protobuf/profiler_service.pb.h" #include "tsl/profiler/rpc/client/profiler_client_test_util.h" namespace tsl { namespace profiler { namespace { using tensorflow::ProfileRequest; using ::tsl::profiler::test::DurationApproxLess; using ::tsl::profiler::test::DurationNear; using ::tsl::profiler::test::StartServer; TEST(RemoteProfilerSession, Simple) { absl::Duration duration = absl::Milliseconds(10); ProfileRequest request; std::string service_addr; auto server = StartServer(duration, &service_addr, &request); absl::Duration grace = absl::Seconds(1); absl::Duration max_duration = duration + grace; absl::Time approx_start = absl::Now(); absl::Time deadline = approx_start + max_duration; auto remote_session = RemoteProfilerSession::Create(service_addr, deadline, request); absl::Status status; auto response = remote_session->WaitForCompletion(status); absl::Duration elapsed = absl::Now() - approx_start; EXPECT_TRUE(status.ok()); EXPECT_TRUE(response->empty_trace()); EXPECT_EQ(response->tool_data_size(), 0); EXPECT_THAT(elapsed, DurationApproxLess(max_duration)); } TEST(RemoteProfilerSession, WaitNotCalled) { absl::Duration duration = absl::Milliseconds(10); ProfileRequest request; std::string service_addr; auto server = StartServer(duration, &service_addr, &request); absl::Duration grace = absl::Seconds(1); absl::Duration max_duration = duration + grace; absl::Time approx_start = absl::Now(); absl::Time deadline = approx_start + max_duration; auto remote_session = RemoteProfilerSession::Create(service_addr, deadline, request); absl::Duration elapsed = absl::Now() - approx_start; EXPECT_THAT(elapsed, DurationApproxLess(max_duration)); } TEST(RemoteProfilerSession, Timeout) { absl::Duration duration = absl::Milliseconds(10); ProfileRequest request; std::string service_addr; auto server = StartServer(duration, &service_addr, &request); auto remote_session = RemoteProfilerSession::Create(service_addr, absl::Now(), request); absl::Status status; auto response = remote_session->WaitForCompletion(status); EXPECT_TRUE(errors::IsDeadlineExceeded(status)); EXPECT_TRUE(response->empty_trace()); EXPECT_EQ(response->tool_data_size(), 0); } TEST(RemoteProfilerSession, LongDeadline) { absl::Duration duration = absl::Milliseconds(10); ProfileRequest request; std::string service_addr; auto server = StartServer(duration, &service_addr, &request); absl::Time approx_start = absl::Now(); absl::Duration grace = absl::Seconds(1000); absl::Duration max_duration = duration + grace; const absl::Time deadline = approx_start + max_duration; auto remote_session = RemoteProfilerSession::Create(service_addr, deadline, request); absl::Status status; auto response = remote_session->WaitForCompletion(status); absl::Duration elapsed = absl::Now() - approx_start; EXPECT_TRUE(status.ok()); EXPECT_TRUE(response->empty_trace()); EXPECT_EQ(response->tool_data_size(), 0); EXPECT_THAT(elapsed, DurationNear(duration)); } TEST(RemoteProfilerSession, LongDuration) { absl::Duration duration = absl::Seconds(3); ProfileRequest request; std::string service_addr; auto server = StartServer(duration, &service_addr, &request); absl::Time approx_start = absl::Now(); absl::Duration grace = absl::Seconds(1); absl::Duration max_duration = duration + grace; const absl::Time deadline = approx_start + max_duration; auto remote_session = RemoteProfilerSession::Create(service_addr, deadline, request); absl::Status status; auto response = remote_session->WaitForCompletion(status); absl::Duration elapsed = absl::Now() - approx_start; EXPECT_TRUE(status.ok()); EXPECT_TRUE(response->empty_trace()); EXPECT_EQ(response->tool_data_size(), 0); EXPECT_THAT(elapsed, DurationApproxLess(max_duration)); } } } }
2,637
cpp
google/tsl
traceme_recorder
tsl/profiler/backends/cpu/traceme_recorder.cc
tsl/profiler/backends/cpu/traceme_recorder_test.cc
#ifndef TENSORFLOW_TSL_PROFILER_BACKENDS_CPU_TRACEME_RECORDER_H_ #define TENSORFLOW_TSL_PROFILER_BACKENDS_CPU_TRACEME_RECORDER_H_ #include <atomic> #include <cstdint> #include <deque> #include <string> #include <vector> #include "tsl/platform/macros.h" #include "tsl/platform/types.h" namespace tsl { namespace profiler { namespace internal { TF_EXPORT extern std::atomic<int> g_trace_level; } class TraceMeRecorder { public: struct Event { bool IsComplete() const { return start_time > 0 && end_time > 0; } bool IsStart() const { return end_time < 0; } bool IsEnd() const { return start_time < 0; } int64_t ActivityId() const { if (IsStart()) return -end_time; if (IsEnd()) return -start_time; return 1; } std::string name; int64_t start_time; int64_t end_time; }; struct ThreadInfo { uint32 tid; std::string name; }; struct ThreadEvents { ThreadInfo thread; std::deque<Event> events; }; using Events = std::vector<ThreadEvents>; static bool Start(int level); static Events Stop(); static inline bool Active(int level = 1) { return internal::g_trace_level.load(std::memory_order_acquire) >= level; } static constexpr int kTracingDisabled = -1; static void Record(Event&& event); static int64_t NewActivityId(); private: TraceMeRecorder() = delete; ~TraceMeRecorder() = delete; static void Clear(); static TF_MUST_USE_RESULT Events Consume(); }; } } #endif #include "tsl/profiler/backends/cpu/traceme_recorder.h" #include <stddef.h> #include <stdint.h> #include <algorithm> #include <atomic> #include <deque> #include <optional> #include <utility> #include <vector> #include "absl/container/flat_hash_map.h" #include "tsl/platform/env.h" #include "tsl/platform/logging.h" #include "tsl/platform/macros.h" #include "tsl/platform/types.h" #include "tsl/profiler/utils/lock_free_queue.h" #include "tsl/profiler/utils/per_thread.h" namespace tsl { namespace profiler { namespace internal { #ifdef _WIN32 #define DECL_DLL_EXPORT __declspec(dllexport) #else #define DECL_DLL_EXPORT #endif DECL_DLL_EXPORT std::atomic<int> g_trace_level( TraceMeRecorder::kTracingDisabled); static_assert(ATOMIC_INT_LOCK_FREE == 2, "Assumed atomic<int> was lock free"); } namespace { class SplitEventTracker { public: void AddStart(TraceMeRecorder::Event&& event) { DCHECK(event.IsStart()); start_events_.emplace(event.ActivityId(), std::move(event)); } void AddEnd(TraceMeRecorder::Event* event) { DCHECK(event->IsEnd()); if (!FindStartAndMerge(event)) { end_events_.push_back(event); } } void HandleCrossThreadEvents() { for (auto* event : end_events_) { FindStartAndMerge(event); } } private: bool FindStartAndMerge(TraceMeRecorder::Event* event) { auto iter = start_events_.find(event->ActivityId()); if (iter == start_events_.end()) return false; auto& start_event = iter->second; event->name = std::move(start_event.name); event->start_time = start_event.start_time; start_events_.erase(iter); return true; } absl::flat_hash_map<int64_t, TraceMeRecorder::Event> start_events_; std::vector<TraceMeRecorder::Event*> end_events_; }; class ThreadLocalRecorder { public: ThreadLocalRecorder() { auto* env = Env::Default(); info_.tid = env->GetCurrentThreadId(); env->GetCurrentThreadName(&info_.name); } const TraceMeRecorder::ThreadInfo& Info() const { return info_; } void Record(TraceMeRecorder::Event&& event) { queue_.Push(std::move(event)); } void Clear() { queue_.Clear(); } TF_MUST_USE_RESULT std::deque<TraceMeRecorder::Event> Consume( SplitEventTracker* split_event_tracker) { std::deque<TraceMeRecorder::Event> events; std::optional<TraceMeRecorder::Event> event; while ((event = queue_.Pop())) { if (event->IsStart()) { split_event_tracker->AddStart(*std::move(event)); continue; } events.push_back(*std::move(event)); if (events.back().IsEnd()) { split_event_tracker->AddEnd(&events.back()); } } return events; } private: TraceMeRecorder::ThreadInfo info_; LockFreeQueue<TraceMeRecorder::Event> queue_; }; } void TraceMeRecorder::Clear() { auto recorders = PerThread<ThreadLocalRecorder>::StartRecording(); for (auto& recorder : recorders) { recorder->Clear(); }; } TraceMeRecorder::Events TraceMeRecorder::Consume() { TraceMeRecorder::Events result; SplitEventTracker split_event_tracker; auto recorders = PerThread<ThreadLocalRecorder>::StopRecording(); for (auto& recorder : recorders) { auto events = recorder->Consume(&split_event_tracker); if (!events.empty()) { result.push_back({recorder->Info(), std::move(events)}); } }; split_event_tracker.HandleCrossThreadEvents(); return result; } bool TraceMeRecorder::Start(int level) { level = std::max(0, level); int expected = kTracingDisabled; bool started = internal::g_trace_level.compare_exchange_strong( expected, level, std::memory_order_acq_rel); if (started) { Clear(); } return started; } void TraceMeRecorder::Record(Event&& event) { PerThread<ThreadLocalRecorder>::Get().Record(std::move(event)); } TraceMeRecorder::Events TraceMeRecorder::Stop() { TraceMeRecorder::Events events; if (internal::g_trace_level.exchange( kTracingDisabled, std::memory_order_acq_rel) != kTracingDisabled) { events = Consume(); } return events; } int64_t TraceMeRecorder::NewActivityId() { static std::atomic<int32> thread_counter(1); const thread_local static int32_t thread_id = thread_counter.fetch_add(1, std::memory_order_relaxed); thread_local static uint32 per_thread_activity_id = 0; return static_cast<int64_t>(thread_id) << 32 | per_thread_activity_id++; } } }
#include "tsl/profiler/backends/cpu/traceme_recorder.h" #include <atomic> #include <set> #include <string> #include <utility> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/strings/numbers.h" #include "absl/strings/str_cat.h" #include "tsl/platform/env.h" #include "tsl/platform/logging.h" #include "tsl/platform/notification.h" #include "tsl/platform/test.h" #include "tsl/platform/threadpool.h" #include "tsl/platform/types.h" #include "tsl/profiler/utils/math_utils.h" #include "tsl/profiler/utils/time_utils.h" namespace tsl { namespace profiler { namespace { using ::testing::ElementsAre; MATCHER_P(Named, name, "") { return arg.name == name; } TEST(RecorderTest, SingleThreaded) { int64_t start_time = GetCurrentTimeNanos(); int64_t end_time = start_time + UniToNano(1); TraceMeRecorder::Record({"before", start_time, end_time}); TraceMeRecorder::Start(1); TraceMeRecorder::Record({"during1", start_time, end_time}); TraceMeRecorder::Record({"during2", start_time, end_time}); auto results = TraceMeRecorder::Stop(); TraceMeRecorder::Record({"after", start_time, end_time}); ASSERT_EQ(results.size(), 1); EXPECT_THAT(results[0].events, ElementsAre(Named("during1"), Named("during2"))); } TEST(RecorderTest, Multithreaded) { constexpr static int kNumThreads = 4; tsl::Notification start; tsl::Notification stop; thread::ThreadPool pool(tsl::Env::Default(), "testpool", kNumThreads); std::atomic<int> thread_count = {0}; for (int i = 0; i < kNumThreads; i++) { pool.Schedule([&start, &stop, &thread_count] { uint64 j = 0; bool was_active = false; auto record_event = [&j]() { int64_t start_time = GetCurrentTimeNanos(); int64_t end_time = start_time + UniToNano(1); TraceMeRecorder::Record( {absl::StrCat(j++), start_time, end_time}); }; thread_count.fetch_add(1, std::memory_order_relaxed); start.WaitForNotification(); while (!stop.HasBeenNotified()) { if (TraceMeRecorder::Active()) { record_event(); was_active = true; } if (was_active && !TraceMeRecorder::Active()) { record_event(); record_event(); was_active = false; } SpinForNanos(10); } }); } struct ThreadState { bool split_session = false; bool overlapping_sessions = false; std::set<uint64> events; }; absl::flat_hash_map<uint32 , ThreadState> thread_state; auto done = [&thread_state] { for (const auto& id_and_thread : thread_state) { auto& t = id_and_thread.second; if (t.events.size() < 2) return false; } return true; }; while (thread_count.load(std::memory_order_relaxed) < kNumThreads) { LOG(INFO) << "Waiting for all threads to spin up..."; SleepForMillis(1); } start.Notify(); constexpr static int kMaxIters = 100; for (int iters = 0; iters < kMaxIters && !done(); ++iters) { LOG(INFO) << "Looping until convergence, iteration: " << iters; TraceMeRecorder::Start(1); SleepForMillis(100); auto results = TraceMeRecorder::Stop(); for (const auto& thread : results) { if (thread.events.empty()) continue; auto& state = thread_state[thread.thread.tid]; std::set<uint64> session_events; uint64 current = 0; for (const auto& event : thread.events) { uint64 activity_id; ASSERT_TRUE(absl::SimpleAtoi(event.name, &activity_id)); session_events.emplace(activity_id); if (current != 0 && activity_id != current + 1) { state.split_session = true; } current = activity_id; } for (const auto& event : session_events) { auto result = state.events.emplace(event); if (!result.second) { state.overlapping_sessions = true; } } } SleepForMillis(1); } stop.Notify(); for (const auto& id_and_thread : thread_state) { auto& thread = id_and_thread.second; EXPECT_FALSE(thread.split_session) << "Expected contiguous events in a session"; EXPECT_FALSE(thread.overlapping_sessions) << "Expected disjoint sessions"; EXPECT_GT(thread.events.size(), 1) << "Expected gaps in thread events between sessions"; } } } } }
2,638
cpp
google/tsl
profiler_lock
tsl/profiler/lib/profiler_lock.cc
tsl/profiler/lib/profiler_lock_test.cc
#ifndef TENSORFLOW_TSL_PROFILER_LIB_PROFILER_LOCK_H_ #define TENSORFLOW_TSL_PROFILER_LIB_PROFILER_LOCK_H_ #include <utility> #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "tsl/platform/statusor.h" namespace tsl { namespace profiler { constexpr absl::string_view kProfilerLockContention = "Another profiling session active."; class ProfilerLock { public: static bool HasActiveSession(); static absl::StatusOr<ProfilerLock> Acquire(); ProfilerLock() = default; ProfilerLock(const ProfilerLock&) = delete; ProfilerLock& operator=(const ProfilerLock&) = delete; ProfilerLock(ProfilerLock&& other) : active_(std::exchange(other.active_, false)) {} ProfilerLock& operator=(ProfilerLock&& other) { active_ = std::exchange(other.active_, false); return *this; } ~ProfilerLock() { ReleaseIfActive(); } void ReleaseIfActive(); bool Active() const { return active_; } private: explicit ProfilerLock(bool active) : active_(active) {} bool active_ = false; }; } } #endif #include "tsl/profiler/lib/profiler_lock.h" #include <atomic> #include "absl/status/statusor.h" #include "xla/tsl/util/env_var.h" #include "tsl/platform/errors.h" #include "tsl/platform/macros.h" namespace tsl { namespace profiler { namespace { std::atomic<int> g_session_active = ATOMIC_VAR_INIT(0); static_assert(ATOMIC_INT_LOCK_FREE == 2, "Assumed atomic<int> was lock free"); } bool ProfilerLock::HasActiveSession() { return g_session_active.load(std::memory_order_relaxed) != 0; } absl::StatusOr<ProfilerLock> ProfilerLock::Acquire() { static bool tf_profiler_disabled = [] { bool disabled = false; ReadBoolFromEnvVar("TF_DISABLE_PROFILING", false, &disabled).IgnoreError(); return disabled; }(); if (TF_PREDICT_FALSE(tf_profiler_disabled)) { return errors::AlreadyExists( "TensorFlow Profiler is permanently disabled by env var " "TF_DISABLE_PROFILING."); } int already_active = g_session_active.exchange(1, std::memory_order_acq_rel); if (already_active) { return errors::AlreadyExists(kProfilerLockContention); } return ProfilerLock(true); } void ProfilerLock::ReleaseIfActive() { if (active_) { g_session_active.store(0, std::memory_order_release); active_ = false; } } } }
#include "tsl/profiler/lib/profiler_lock.h" #include <utility> #include "absl/status/statusor.h" #include "tsl/platform/test.h" namespace tsl { namespace profiler { namespace { TEST(ProfilerLockTest, DefaultConstructorCreatesInactiveInstance) { ProfilerLock profiler_lock; EXPECT_FALSE(profiler_lock.Active()); } TEST(ProfilerLockTest, AcquireAndReleaseExplicitly) { absl::StatusOr<ProfilerLock> profiler_lock = ProfilerLock::Acquire(); ASSERT_TRUE(profiler_lock.ok()); EXPECT_TRUE(profiler_lock->Active()); profiler_lock->ReleaseIfActive(); EXPECT_FALSE(profiler_lock->Active()); } TEST(ProfilerLockTest, AcquireAndReleaseOnDestruction) { absl::StatusOr<ProfilerLock> profiler_lock = ProfilerLock::Acquire(); ASSERT_TRUE(profiler_lock.ok()); EXPECT_TRUE(profiler_lock->Active()); } TEST(ProfilerLockTest, ReacquireWithoutReleaseFails) { absl::StatusOr<ProfilerLock> profiler_lock_1 = ProfilerLock::Acquire(); absl::StatusOr<ProfilerLock> profiler_lock_2 = ProfilerLock::Acquire(); ASSERT_TRUE(profiler_lock_1.ok()); EXPECT_TRUE(profiler_lock_1->Active()); EXPECT_FALSE(profiler_lock_2.ok()); } TEST(ProfilerLockTest, ReacquireAfterReleaseSucceeds) { auto profiler_lock_1 = ProfilerLock::Acquire(); ASSERT_TRUE(profiler_lock_1.ok()); ASSERT_TRUE(profiler_lock_1->Active()); profiler_lock_1->ReleaseIfActive(); ASSERT_FALSE(profiler_lock_1->Active()); auto profiler_lock_2 = ProfilerLock::Acquire(); EXPECT_TRUE(profiler_lock_2.ok()); EXPECT_TRUE(profiler_lock_2->Active()); } TEST(ProfilerLockTest, InactiveAfterMove) { absl::StatusOr<ProfilerLock> profiler_lock_1 = ProfilerLock::Acquire(); ASSERT_TRUE(profiler_lock_1.ok()); ASSERT_TRUE(profiler_lock_1->Active()); ProfilerLock profiler_lock_2 = std::move(*profiler_lock_1); EXPECT_FALSE(profiler_lock_1->Active()); EXPECT_TRUE(profiler_lock_2.Active()); } } } }
2,639
cpp
google/tsl
profiler_factory
tsl/profiler/lib/profiler_factory.cc
tsl/profiler/lib/profiler_factory_test.cc
#ifndef TENSORFLOW_TSL_PROFILER_LIB_PROFILER_FACTORY_H_ #define TENSORFLOW_TSL_PROFILER_LIB_PROFILER_FACTORY_H_ #include <functional> #include <memory> #include <vector> #include "tsl/profiler/lib/profiler_interface.h" #include "tsl/profiler/protobuf/profiler_options.pb.h" namespace tsl { namespace profiler { using ProfilerFactory = std::function<std::unique_ptr<ProfilerInterface>( const tensorflow::ProfileOptions&)>; void RegisterProfilerFactory(ProfilerFactory factory); std::vector<std::unique_ptr<ProfilerInterface>> CreateProfilers( const tensorflow::ProfileOptions& options); void ClearRegisteredProfilersForTest(); } } #endif #include "tsl/profiler/lib/profiler_factory.h" #include <memory> #include <utility> #include <vector> #include "tsl/platform/mutex.h" #include "tsl/profiler/lib/profiler_controller.h" #include "tsl/profiler/lib/profiler_interface.h" #include "tsl/profiler/protobuf/profiler_options.pb.h" namespace tsl { namespace profiler { namespace { mutex mu(LINKER_INITIALIZED); std::vector<ProfilerFactory>* GetFactories() { static auto factories = new std::vector<ProfilerFactory>(); return factories; } } void RegisterProfilerFactory(ProfilerFactory factory) { mutex_lock lock(mu); GetFactories()->push_back(std::move(factory)); } std::vector<std::unique_ptr<profiler::ProfilerInterface>> CreateProfilers( const tensorflow::ProfileOptions& options) { std::vector<std::unique_ptr<profiler::ProfilerInterface>> result; mutex_lock lock(mu); for (const auto& factory : *GetFactories()) { auto profiler = factory(options); if (profiler == nullptr) continue; result.emplace_back( std::make_unique<ProfilerController>(std::move(profiler))); } return result; } void ClearRegisteredProfilersForTest() { mutex_lock lock(mu); GetFactories()->clear(); } } }
#include "tsl/profiler/lib/profiler_factory.h" #include <functional> #include <utility> #include "absl/memory/memory.h" #include "absl/status/status.h" #include "tsl/platform/macros.h" #include "tsl/platform/test.h" #include "tsl/profiler/lib/profiler_interface.h" #include "tsl/profiler/protobuf/profiler_options.pb.h" #include "tsl/profiler/protobuf/xplane.pb.h" namespace tsl { namespace profiler { namespace { class TestProfiler : public ProfilerInterface { public: absl::Status Start() override { return absl::OkStatus(); } absl::Status Stop() override { return absl::OkStatus(); } absl::Status CollectData(tensorflow::profiler::XSpace*) override { return absl::OkStatus(); } }; std::unique_ptr<ProfilerInterface> TestFactoryFunction( const tensorflow::ProfileOptions& options) { return absl::make_unique<TestProfiler>(); } TEST(ProfilerFactoryTest, FactoryFunctionPointer) { ClearRegisteredProfilersForTest(); RegisterProfilerFactory(&TestFactoryFunction); auto profilers = CreateProfilers(tensorflow::ProfileOptions()); EXPECT_EQ(profilers.size(), 1); } TEST(ProfilerFactoryTest, FactoryLambda) { ClearRegisteredProfilersForTest(); RegisterProfilerFactory([](const tensorflow::ProfileOptions& options) { return absl::make_unique<TestProfiler>(); }); auto profilers = CreateProfilers(tensorflow::ProfileOptions()); EXPECT_EQ(profilers.size(), 1); } std::unique_ptr<ProfilerInterface> NullFactoryFunction( const tensorflow::ProfileOptions& options) { return nullptr; } TEST(ProfilerFactoryTest, FactoryReturnsNull) { ClearRegisteredProfilersForTest(); RegisterProfilerFactory(&NullFactoryFunction); auto profilers = CreateProfilers(tensorflow::ProfileOptions()); EXPECT_TRUE(profilers.empty()); } class FactoryClass { public: explicit FactoryClass(void* ptr) : ptr_(ptr) {} FactoryClass(const FactoryClass&) = default; FactoryClass(FactoryClass&&) = default; std::unique_ptr<ProfilerInterface> CreateProfiler( const tensorflow::ProfileOptions& options) const { return absl::make_unique<TestProfiler>(); } private: void* ptr_ TF_ATTRIBUTE_UNUSED = nullptr; }; TEST(ProfilerFactoryTest, FactoryClassCapturedByLambda) { ClearRegisteredProfilersForTest(); static int token = 42; FactoryClass factory(&token); RegisterProfilerFactory([factory = std::move(factory)]( const tensorflow::ProfileOptions& options) { return factory.CreateProfiler(options); }); auto profilers = CreateProfilers(tensorflow::ProfileOptions()); EXPECT_EQ(profilers.size(), 1); } } } }
2,640
cpp
google/tsl
weighted_picker
tsl/lib/random/weighted_picker.cc
tsl/lib/random/weighted_picker_test.cc
#ifndef TENSORFLOW_TSL_LIB_RANDOM_WEIGHTED_PICKER_H_ #define TENSORFLOW_TSL_LIB_RANDOM_WEIGHTED_PICKER_H_ #include <assert.h> #include "tsl/platform/logging.h" #include "tsl/platform/macros.h" #include "tsl/platform/types.h" namespace tsl { namespace random { class SimplePhilox; class WeightedPicker { public: explicit WeightedPicker(int N); ~WeightedPicker(); int Pick(SimplePhilox* rnd) const; int PickAt(int32_t weight_index) const; int32 get_weight(int index) const; void set_weight(int index, int32_t weight); int32 total_weight() const; int num_elements() const; void SetAllWeights(int32_t weight); void SetWeightsFromArray(int N, const int32* weights); void Resize(int N); void Append(int32_t weight); private: int N_; int num_levels_; int32** level_; static int LevelSize(int level) { return 1 << level; } void RebuildTreeWeights(); WeightedPicker(const WeightedPicker&) = delete; void operator=(const WeightedPicker&) = delete; }; inline int32 WeightedPicker::get_weight(int index) const { DCHECK_GE(index, 0); DCHECK_LT(index, N_); return level_[num_levels_ - 1][index]; } inline int32 WeightedPicker::total_weight() const { return level_[0][0]; } inline int WeightedPicker::num_elements() const { return N_; } } } #endif #include "tsl/lib/random/weighted_picker.h" #include <string.h> #include <algorithm> #include "tsl/lib/random/simple_philox.h" namespace tsl { namespace random { WeightedPicker::WeightedPicker(int N) { CHECK_GE(N, 0); N_ = N; num_levels_ = 1; while (LevelSize(num_levels_ - 1) < N) { num_levels_++; } level_ = new int32*[num_levels_]; for (int l = 0; l < num_levels_; l++) { level_[l] = new int32[LevelSize(l)]; } SetAllWeights(1); } WeightedPicker::~WeightedPicker() { for (int l = 0; l < num_levels_; l++) { delete[] level_[l]; } delete[] level_; } static int32 UnbiasedUniform(SimplePhilox* r, int32_t n) { CHECK_LE(0, n); const uint32 range = ~static_cast<uint32>(0); if (n == 0) { return r->Rand32() * n; } else if (0 == (n & (n - 1))) { return r->Rand32() & (n - 1); } else { uint32 rem = (range % n) + 1; uint32 rnd; do { rnd = r->Rand32(); } while (rnd < rem); return rnd % n; } } int WeightedPicker::Pick(SimplePhilox* rnd) const { if (total_weight() == 0) return -1; return PickAt(UnbiasedUniform(rnd, total_weight())); } int WeightedPicker::PickAt(int32_t weight_index) const { if (weight_index < 0 || weight_index >= total_weight()) return -1; int32_t position = weight_index; int index = 0; for (int l = 1; l < num_levels_; l++) { const int32_t left_weight = level_[l][2 * index]; if (position < left_weight) { index = 2 * index; } else { index = 2 * index + 1; position -= left_weight; } } CHECK_GE(index, 0); CHECK_LT(index, N_); CHECK_LE(position, level_[num_levels_ - 1][index]); return index; } void WeightedPicker::set_weight(int index, int32_t weight) { assert(index >= 0); assert(index < N_); const int32_t delta = weight - get_weight(index); for (int l = num_levels_ - 1; l >= 0; l--) { level_[l][index] += delta; index >>= 1; } } void WeightedPicker::SetAllWeights(int32_t weight) { int32* leaves = level_[num_levels_ - 1]; for (int i = 0; i < N_; i++) leaves[i] = weight; for (int i = N_; i < LevelSize(num_levels_ - 1); i++) leaves[i] = 0; RebuildTreeWeights(); } void WeightedPicker::SetWeightsFromArray(int N, const int32* weights) { Resize(N); int32* leaves = level_[num_levels_ - 1]; for (int i = 0; i < N_; i++) leaves[i] = weights[i]; for (int i = N_; i < LevelSize(num_levels_ - 1); i++) leaves[i] = 0; RebuildTreeWeights(); } void WeightedPicker::RebuildTreeWeights() { for (int l = num_levels_ - 2; l >= 0; l--) { int32* level = level_[l]; int32* children = level_[l + 1]; for (int i = 0; i < LevelSize(l); i++) { level[i] = children[2 * i] + children[2 * i + 1]; } } } void WeightedPicker::Append(int32_t weight) { Resize(num_elements() + 1); set_weight(num_elements() - 1, weight); } void WeightedPicker::Resize(int new_size) { CHECK_GE(new_size, 0); if (new_size <= LevelSize(num_levels_ - 1)) { for (int i = new_size; i < N_; i++) { set_weight(i, 0); } N_ = new_size; return; } assert(new_size > N_); WeightedPicker new_picker(new_size); int32* dst = new_picker.level_[new_picker.num_levels_ - 1]; int32* src = this->level_[this->num_levels_ - 1]; memcpy(dst, src, sizeof(dst[0]) * N_); memset(dst + N_, 0, sizeof(dst[0]) * (new_size - N_)); new_picker.RebuildTreeWeights(); std::swap(new_picker.N_, this->N_); std::swap(new_picker.num_levels_, this->num_levels_); std::swap(new_picker.level_, this->level_); assert(this->N_ == new_size); } } }
#include "tsl/lib/random/weighted_picker.h" #include <string.h> #include <vector> #include "tsl/lib/random/simple_philox.h" #include "tsl/platform/logging.h" #include "tsl/platform/macros.h" #include "tsl/platform/test.h" #include "tsl/platform/test_benchmark.h" #include "tsl/platform/types.h" namespace tsl { namespace random { static void TestPicker(SimplePhilox* rnd, int size); static void CheckUniform(SimplePhilox* rnd, WeightedPicker* picker, int trials); static void CheckSkewed(SimplePhilox* rnd, WeightedPicker* picker, int trials); static void TestPickAt(int items, const int32* weights); TEST(WeightedPicker, Simple) { PhiloxRandom philox(testing::RandomSeed(), 17); SimplePhilox rnd(&philox); { VLOG(0) << "======= Zero-length picker"; WeightedPicker picker(0); EXPECT_EQ(picker.Pick(&rnd), -1); } { VLOG(0) << "======= Singleton picker"; WeightedPicker picker(1); EXPECT_EQ(picker.Pick(&rnd), 0); EXPECT_EQ(picker.Pick(&rnd), 0); EXPECT_EQ(picker.Pick(&rnd), 0); } { VLOG(0) << "======= Grown picker"; WeightedPicker picker(0); for (int i = 0; i < 10; i++) { picker.Append(1); } CheckUniform(&rnd, &picker, 100000); } { VLOG(0) << "======= Grown picker with zero weights"; WeightedPicker picker(1); picker.Resize(10); EXPECT_EQ(picker.Pick(&rnd), 0); EXPECT_EQ(picker.Pick(&rnd), 0); EXPECT_EQ(picker.Pick(&rnd), 0); } { VLOG(0) << "======= Shrink picker and check weights"; WeightedPicker picker(1); picker.Resize(10); EXPECT_EQ(picker.Pick(&rnd), 0); EXPECT_EQ(picker.Pick(&rnd), 0); EXPECT_EQ(picker.Pick(&rnd), 0); for (int i = 0; i < 10; i++) { picker.set_weight(i, i); } EXPECT_EQ(picker.total_weight(), 45); picker.Resize(5); EXPECT_EQ(picker.total_weight(), 10); picker.Resize(2); EXPECT_EQ(picker.total_weight(), 1); picker.Resize(1); EXPECT_EQ(picker.total_weight(), 0); } } TEST(WeightedPicker, BigWeights) { PhiloxRandom philox(testing::RandomSeed() + 1, 17); SimplePhilox rnd(&philox); VLOG(0) << "======= Check uniform with big weights"; WeightedPicker picker(2); picker.SetAllWeights(2147483646L / 3); CheckUniform(&rnd, &picker, 100000); } TEST(WeightedPicker, Deterministic) { VLOG(0) << "======= Testing deterministic pick"; static const int32 weights[] = {1, 0, 200, 5, 42}; TestPickAt(TF_ARRAYSIZE(weights), weights); } TEST(WeightedPicker, Randomized) { PhiloxRandom philox(testing::RandomSeed() + 10, 17); SimplePhilox rnd(&philox); TestPicker(&rnd, 1); TestPicker(&rnd, 2); TestPicker(&rnd, 3); TestPicker(&rnd, 4); TestPicker(&rnd, 7); TestPicker(&rnd, 8); TestPicker(&rnd, 9); TestPicker(&rnd, 10); TestPicker(&rnd, 100); } static void TestPicker(SimplePhilox* rnd, int size) { VLOG(0) << "======= Testing size " << size; { WeightedPicker picker(size); picker.SetAllWeights(0); for (int i = 0; i < 100; i++) EXPECT_EQ(picker.Pick(rnd), -1); } std::vector<int32> weights(size); for (int elem = 0; elem < size; elem++) { weights[elem] = 0; } for (int elem = 0; elem < size; elem++) { WeightedPicker picker(size); picker.SetAllWeights(0); picker.set_weight(elem, elem + 1); for (int i = 0; i < 100; i++) EXPECT_EQ(picker.Pick(rnd), elem); weights[elem] = 10; picker.SetWeightsFromArray(size, &weights[0]); for (int i = 0; i < 100; i++) EXPECT_EQ(picker.Pick(rnd), elem); weights[elem] = 0; } { WeightedPicker picker(size); CheckUniform(rnd, &picker, 100000); } if (size / 3 > 0) { WeightedPicker picker(size / 3); while (picker.num_elements() != size) { picker.Append(1); } CheckUniform(rnd, &picker, 100000); } if (size <= 10) { WeightedPicker picker(size); int32_t weight = 1; for (int elem = 0; elem < size; elem++) { picker.set_weight(elem, weight); weights[elem] = weight; weight *= 2; } CheckSkewed(rnd, &picker, 1000000); WeightedPicker array_picker(0); array_picker.SetWeightsFromArray(size, &weights[0]); CheckSkewed(rnd, &array_picker, 1000000); } } static void CheckUniform(SimplePhilox* rnd, WeightedPicker* picker, int trials) { const int size = picker->num_elements(); int* count = new int[size]; memset(count, 0, sizeof(count[0]) * size); for (int i = 0; i < size * trials; i++) { const int elem = picker->Pick(rnd); EXPECT_GE(elem, 0); EXPECT_LT(elem, size); count[elem]++; } const int expected_min = int(0.9 * trials); const int expected_max = int(1.1 * trials); for (int i = 0; i < size; i++) { EXPECT_GE(count[i], expected_min); EXPECT_LE(count[i], expected_max); } delete[] count; } static void CheckSkewed(SimplePhilox* rnd, WeightedPicker* picker, int trials) { const int size = picker->num_elements(); int* count = new int[size]; memset(count, 0, sizeof(count[0]) * size); for (int i = 0; i < size * trials; i++) { const int elem = picker->Pick(rnd); EXPECT_GE(elem, 0); EXPECT_LT(elem, size); count[elem]++; } for (int i = 0; i < size - 1; i++) { LOG(INFO) << i << ": " << count[i]; const float ratio = float(count[i + 1]) / float(count[i]); EXPECT_GE(ratio, 1.6f); EXPECT_LE(ratio, 2.4f); } delete[] count; } static void TestPickAt(int items, const int32* weights) { WeightedPicker picker(items); picker.SetWeightsFromArray(items, weights); int weight_index = 0; for (int i = 0; i < items; ++i) { for (int j = 0; j < weights[i]; ++j) { int pick = picker.PickAt(weight_index); EXPECT_EQ(pick, i); ++weight_index; } } EXPECT_EQ(weight_index, picker.total_weight()); } static void BM_Create(::testing::benchmark::State& state) { int arg = state.range(0); for (auto s : state) { WeightedPicker p(arg); } } BENCHMARK(BM_Create)->Range(1, 1024); static void BM_CreateAndSetWeights(::testing::benchmark::State& state) { int arg = state.range(0); std::vector<int32> weights(arg); for (int i = 0; i < arg; i++) { weights[i] = i * 10; } for (auto s : state) { WeightedPicker p(arg); p.SetWeightsFromArray(arg, &weights[0]); } } BENCHMARK(BM_CreateAndSetWeights)->Range(1, 1024); static void BM_Pick(::testing::benchmark::State& state) { int arg = state.range(0); PhiloxRandom philox(301, 17); SimplePhilox rnd(&philox); WeightedPicker p(arg); int result = 0; for (auto s : state) { result += p.Pick(&rnd); } VLOG(4) << result; } BENCHMARK(BM_Pick)->Range(1, 1024); } }
2,641
cpp
google/tsl
random_distributions
tsl/lib/random/random_distributions.cc
tsl/lib/random/random_distributions_test.cc
#ifndef TENSORFLOW_TSL_LIB_RANDOM_RANDOM_DISTRIBUTIONS_H_ #define TENSORFLOW_TSL_LIB_RANDOM_RANDOM_DISTRIBUTIONS_H_ #include <algorithm> #include <cmath> #include <type_traits> #include "unsupported/Eigen/CXX11/Tensor" #include "tsl/lib/random/philox_random.h" #include "tsl/lib/random/random_distributions_utils.h" #include "tsl/platform/types.h" namespace tsl { namespace random { PHILOX_DEVICE_INLINE Eigen::half Uint16ToHalf(uint16 x); PHILOX_DEVICE_INLINE bfloat16 Uint16ToGfloat16(uint16 x); template <typename Int> PHILOX_DEVICE_INLINE Int SignedAdd(Int a, typename std::make_unsigned<Int>::type b) { auto b_div_2 = b >> 1; return a + static_cast<Int>(b_div_2) + static_cast<Int>(b - b_div_2); } template <class Generator, typename RealType> class UniformDistribution; template <class Generator> class UniformDistribution<Generator, Eigen::half> { public: static constexpr int kResultElementCount = Generator::kResultElementCount; static constexpr int kElementCost = 3; static constexpr bool kVariableSamplesPerOutput = false; typedef Array<Eigen::half, kResultElementCount> ResultType; typedef Eigen::half ResultElementType; PHILOX_DEVICE_INLINE ResultType operator()(Generator* gen) { typename Generator::ResultType sample = (*gen)(); ResultType result; for (int i = 0; i < kResultElementCount; ++i) { result[i] = Uint16ToHalf(sample[i]); } return result; } }; template <class Generator> class UniformDistribution<Generator, bfloat16> { public: static constexpr int kResultElementCount = Generator::kResultElementCount; static constexpr int kElementCost = 3; static constexpr bool kVariableSamplesPerOutput = false; typedef Array<bfloat16, kResultElementCount> ResultType; typedef bfloat16 ResultElementType; PHILOX_DEVICE_INLINE ResultType operator()(Generator* gen) { typename Generator::ResultType sample = (*gen)(); ResultType result; for (int i = 0; i < kResultElementCount; ++i) { result[i] = Uint16ToGfloat16(sample[i]); } return result; } }; template <class Generator> class UniformDistribution<Generator, float> { public: static constexpr int kResultElementCount = Generator::kResultElementCount; static constexpr int kElementCost = 3; static constexpr bool kVariableSamplesPerOutput = false; typedef Array<float, kResultElementCount> ResultType; typedef float ResultElementType; PHILOX_DEVICE_INLINE ResultType operator()(Generator* gen) { typename Generator::ResultType sample = (*gen)(); ResultType result; for (int i = 0; i < kResultElementCount; ++i) { result[i] = Uint32ToFloat(sample[i]); } return result; } }; template <class Generator> class UniformDistribution<Generator, double> { public: static constexpr int kResultElementCount = Generator::kResultElementCount / 2; static constexpr int kElementCost = 3; static constexpr bool kVariableSamplesPerOutput = false; typedef Array<double, kResultElementCount> ResultType; typedef double ResultElementType; PHILOX_DEVICE_INLINE ResultType operator()(Generator* gen) { typename Generator::ResultType sample = (*gen)(); ResultType result; for (int i = 0; i < kResultElementCount; ++i) { result[i] = Uint64ToDouble(sample[2 * i], sample[2 * i + 1]); } return result; } }; template <class Generator> class UniformDistribution<Generator, int32> { public: static constexpr int kResultElementCount = Generator::kResultElementCount; static constexpr int kElementCost = 3; static constexpr bool kVariableSamplesPerOutput = false; typedef Array<int32, kResultElementCount> ResultType; typedef int32 ResultElementType; UniformDistribution(int32_t lo, int32_t hi) : lo_(lo), range_(static_cast<uint32>(hi) - static_cast<uint32>(lo)) {} PHILOX_DEVICE_INLINE ResultType operator()(Generator* gen) { typename Generator::ResultType sample = (*gen)(); ResultType result; for (int i = 0; i < kResultElementCount; ++i) { result[i] = SignedAdd(lo_, sample[i] % range_); } return result; } private: int32 lo_; uint32 range_; }; template <class Generator> class UniformDistribution<Generator, int64_t> { public: static constexpr int kResultElementCount = Generator::kResultElementCount / 2; static constexpr int kElementCost = 3; static constexpr bool kVariableSamplesPerOutput = false; typedef Array<int64_t, kResultElementCount> ResultType; typedef int64_t ResultElementType; UniformDistribution(int64_t lo, int64_t hi) : lo_(lo), range_(static_cast<uint64>(hi) - static_cast<uint64>(lo)) {} PHILOX_DEVICE_INLINE ResultType operator()(Generator* gen) { typename Generator::ResultType sample = (*gen)(); ResultType result; for (int i = 0; i < kResultElementCount; ++i) { auto bits = sample[2 * i] | static_cast<uint64>(sample[2 * i + 1]) << 32; result[i] = SignedAdd(lo_, bits % range_); } return result; } private: int64_t lo_; uint64 range_; }; template <typename Generator, typename IntType> class UniformFullIntDistribution; template <typename Generator, typename IntType> class UniformFullIntDistribution32 { public: static constexpr int kResultElementCount = Generator::kResultElementCount; static constexpr int kElementCost = 3; static constexpr bool kVariableSamplesPerOutput = false; typedef Array<IntType, kResultElementCount> ResultType; typedef IntType ResultElementType; PHILOX_DEVICE_INLINE ResultType operator()(Generator* gen) { typename Generator::ResultType sample = (*gen)(); ResultType result; for (int i = 0; i < kResultElementCount; ++i) { result[i] = sample[i]; } return result; } }; template <typename Generator, typename IntType> class UniformFullIntDistribution64 { public: static constexpr int kResultElementCount = Generator::kResultElementCount / 2; static constexpr int kElementCost = 3; static constexpr bool kVariableSamplesPerOutput = false; typedef Array<IntType, kResultElementCount> ResultType; typedef IntType ResultElementType; PHILOX_DEVICE_INLINE ResultType operator()(Generator* gen) { typename Generator::ResultType sample = (*gen)(); ResultType result; for (int i = 0; i < kResultElementCount; ++i) { result[i] = sample[2 * i] | static_cast<uint64>(sample[2 * i + 1]) << 32; } return result; } }; template <typename Generator> class UniformFullIntDistribution<Generator, int32> : public UniformFullIntDistribution32<Generator, int32> {}; template <typename Generator> class UniformFullIntDistribution<Generator, uint32> : public UniformFullIntDistribution32<Generator, uint32> {}; template <typename Generator> class UniformFullIntDistribution<Generator, int64_t> : public UniformFullIntDistribution64<Generator, int64_t> {}; template <typename Generator> class UniformFullIntDistribution<Generator, uint64> : public UniformFullIntDistribution64<Generator, uint64> {}; template <class Generator> class SingleSampleAdapter { public: static constexpr int kResultElementCount = 1; static constexpr int kNativeElementCount = Generator::kResultElementCount; typedef typename Generator::ResultElementType ResultType; typedef typename Generator::ResultElementType ResultElementType; PHILOX_DEVICE_INLINE explicit SingleSampleAdapter(Generator* gen) : generator_(gen), used_result_index_(Generator::kResultElementCount) {} PHILOX_DEVICE_INLINE ResultType operator()() { if (used_result_index_ == Generator::kResultElementCount) { unused_results_ = (*generator_)(); used_result_index_ = 0; } return unused_results_[used_result_index_++]; } PHILOX_DEVICE_INLINE void Skip(uint64 num_skips) { if (!num_skips) { return; } int num_unused_results = kNativeElementCount - used_result_index_; if (num_skips <= num_unused_results) { used_result_index_ += num_skips; return; } num_skips -= num_unused_results; used_result_index_ = kNativeElementCount; SkipFromGenerator(num_skips / kNativeElementCount); num_skips = num_skips % kNativeElementCount; if (num_skips) { unused_results_ = (*generator_)(); used_result_index_ = num_skips; } } private: PHILOX_DEVICE_INLINE void SkipFromGenerator(uint64 num_skips) { while (num_skips--) { (*generator_)(); } } Generator* generator_; typename Generator::ResultType unused_results_; int used_result_index_; }; template <class Generator, typename RealType> class NormalDistribution; PHILOX_DEVICE_INLINE void BoxMullerDouble(uint32 x0, uint32 x1, uint32 x2, uint32 x3, double* d0, double* d1); template <class Generator> class NormalDistribution<Generator, Eigen::half> { public: static constexpr int kResultElementCount = Generator::kResultElementCount; static constexpr int kElementCost = 70; static constexpr bool kVariableSamplesPerOutput = false; typedef Array<Eigen::half, kResultElementCount> ResultType; typedef Eigen::half ResultElementType; PHILOX_DEVICE_INLINE ResultType operator()(Generator* gen) { typename Generator::ResultType sample = (*gen)(); ResultType result; for (int i = 0; i < kResultElementCount; i += 2) { float f[2]; BoxMullerFloat(sample[i], sample[i + 1], &f[0], &f[1]); result[i] = Eigen::half(f[0]); result[i + 1] = Eigen::half(f[1]); } return result; } }; template <class Generator> class NormalDistribution<Generator, bfloat16> { public: static constexpr int kResultElementCount = Generator::kResultElementCount; static constexpr int kElementCost = 70; static constexpr bool kVariableSamplesPerOutput = false; typedef Array<bfloat16, kResultElementCount> ResultType; typedef bfloat16 ResultElementType; PHILOX_DEVICE_INLINE ResultType operator()(Generator* gen) { typename Generator::ResultType sample = (*gen)(); ResultType result; static_assert(kResultElementCount % 2 == 0, "kResultElementCount should be an even number"); for (int i = 0; i < kResultElementCount; i += 2) { float f[2]; BoxMullerFloat(sample[i], sample[i + 1], &f[0], &f[1]); result[i] = bfloat16(f[0]); result[i + 1] = bfloat16(f[1]); } return result; } }; template <class Generator> class NormalDistribution<Generator, float> { public: static constexpr int kResultElementCount = Generator::kResultElementCount; static constexpr int kElementCost = 70; static constexpr bool kVariableSamplesPerOutput = false; typedef Array<float, kResultElementCount> ResultType; typedef float ResultElementType; PHILOX_DEVICE_INLINE ResultType operator()(Generator* gen) { typename Generator::ResultType sample = (*gen)(); ResultType result; for (int i = 0; i < kResultElementCount; i += 2) { BoxMullerFloat(sample[i], sample[i + 1], &result[i], &result[i + 1]); } return result; } }; template <class Generator> class NormalDistribution<Generator, double> { public: static constexpr int kResultElementCount = Generator::kResultElementCount / 2; static constexpr int kElementCost = 70; static constexpr bool kVariableSamplesPerOutput = false; typedef Array<double, kResultElementCount> ResultType; typedef double ResultElementType; PHILOX_DEVICE_INLINE ResultType operator()(Generator* gen) { typename Generator::ResultType sample = (*gen)(); ResultType result; for (int i = 0; i < kResultElementCount; i += 2) { const int i2 = 2 * i; BoxMullerDouble(sample[i2], sample[i2 + 1], sample[i2 + 2], sample[i2 + 3], &result[i], &result[i + 1]); } return result; } }; template <class SingleSampleGenerator, typename RealType> class TruncatedNormalDistribution; template <class SingleSampleGenerator> class TruncatedNormalDistribution<SingleSampleGenerator, Eigen::half> { public: static constexpr int kResultElementCount = SingleSampleGenerator::kNativeElementCount; static constexpr int kElementCost = 90; static constexpr bool kVariableSamplesPerOutput = true; const float kTruncateValue = 2.0f; typedef Array<Eigen::half, kResultElementCount> ResultType; typedef Eigen::half ResultElementType; PHILOX_DEVICE_INLINE ResultType operator()(SingleSampleGenerator* gen) { ResultType results; int index = 0; while (true) { const uint32 x0 = (*gen)(); const uint32 x1 = (*gen)(); float f[2]; BoxMullerFloat(x0, x1, &f[0], &f[1]); if (Eigen::numext::abs(f[0]) < kTruncateValue) { results[index++] = Eigen::half(f[0]); if (index >= kResultElementCount) { return results; } } if (Eigen::numext::abs(f[1]) < kTruncateValue) { results[index++] = Eigen::half(f[1]); if (index >= kResultElementCount) { return results; } } } } }; template <class SingleSampleGenerator> class TruncatedNormalDistribution<SingleSampleGenerator, bfloat16> { public: static constexpr int kResultElementCount = SingleSampleGenerator::kNativeElementCount; static constexpr int kElementCost = 90; static constexpr bool kVariableSamplesPerOutput = true; const float kTruncateValue = 2.0f; typedef Array<bfloat16, kResultElementCount> ResultType; typedef bfloat16 ResultElementType; PHILOX_DEVICE_INLINE ResultType operator()(SingleSampleGenerator* gen) { ResultType results; int index = 0; while (true) { const uint32 x0 = (*gen)(); const uint32 x1 = (*gen)(); float f[2]; BoxMullerFloat(x0, x1, &f[0], &f[1]); if (Eigen::numext::abs(f[0]) < kTruncateValue) { results[index++] = bfloat16(f[0]); if (index >= kResultElementCount) { return results; } } if (Eigen::numext::abs(f[1]) < kTruncateValue) { results[index++] = bfloat16(f[1]); if (index >= kResultElementCount) { return results; } } } } }; template <class SingleSampleGenerator> class TruncatedNormalDistribution<SingleSampleGenerator, float> { public: static constexpr int kResultElementCount = SingleSampleGenerator::kNativeElementCount; static constexpr int kElementCost = 90; static constexpr bool kVariableSamplesPerOutput = true; const float kTruncateValue = 2.0f; typedef Array<float, kResultElementCount> ResultType; typedef float ResultElementType; PHILOX_DEVICE_INLINE ResultType operator()(SingleSampleGenerator* gen) { ResultType results; int index = 0; while (true) { const uint32 x0 = (*gen)(); const uint32 x1 = (*gen)(); float f[2]; BoxMullerFloat(x0, x1, &f[0], &f[1]); if (Eigen::numext::abs(f[0]) < kTruncateValue) { results[index++] = f[0]; if (index >= kResultElementCount) { return results; } } if (Eigen::numext::abs(f[1]) < kTruncateValue) { results[index++] = f[1]; if (index >= kResultElementCount) { return results; } } } } }; template <class SingleSampleGenerator> class TruncatedNormalDistribution<SingleSampleGenerator, double> { public: static constexpr int kResultElementCount = (SingleSampleGenerator::kNativeElementCount > 1) ? SingleSampleGenerator::kNativeElementCount / 2 : 1; static constexpr int kElementCost = 90; static constexpr bool kVariableSamplesPerOutput = true; typedef Array<double, kResultElementCount> ResultType; typedef double ResultElementType; const double kTruncateValue = 2.0; PHILOX_DEVICE_INLINE ResultType operator()(SingleSampleGenerator* gen) { ResultType results; int index = 0; while (true) { const uint32 x0 = (*gen)(); const uint32 x1 = (*gen)(); const uint32 x2 = (*gen)(); const uint32 x3 = (*gen)(); double d[2]; BoxMullerDouble(x0, x1, x2, x3, &d[0], &d[1]); if (Eigen::numext::abs(d[0]) < kTruncateValue) { results[index++] = d[0]; if (index >= kResultElementCount) { return results; } } if (Eigen::numext::abs(d[1]) < kTruncateValue) { results[index++] = d[1]; if (index >= kResultElementCount) { return results; } } } } }; PHILOX_DEVICE_INLINE void BoxMullerDouble(uint32 x0, uint32 x1, uint32 x2, uint32 x3, double* d0, double* d1) { const double epsilon = 1.0e-7; double u1 = Uint64ToDouble(x0, x1); if (u1 < epsilon) { u1 = epsilon; } const double v1 = 2 * M_PI * Uint64ToDouble(x2, x3); const double u2 = Eigen::numext::sqrt(-2.0 * Eigen::numext::log(u1)); #if !defined(__linux__) *d0 = Eigen::numext::sin(v1); *d1 = Eigen::numext::cos(v1); #else sincos(v1, d0, d1); #endif *d0 *= u2; *d1 *= u2; } PHILOX_DEVICE_INLINE Eigen::half Uint16ToHalf(uint16 x) { const uint16 man = x & 0x3ffu; const uint16 exp = static_cast<uint16>(15); const uint16 val = (exp << 10) | man; Eigen::half result = Eigen::numext::bit_cast<Eigen::half>(val); return result - Eigen::half(1.0); } PHILOX_DEVICE_INLINE bfloat16 Uint16ToGfloat16(uint16 x) { const uint16 man = x & 0x7fu; const uint16 exp = static_cast<uint16>(127); const uint16 val = (exp << 7) | man; bfloat16 result; memcpy(&result, &val, sizeof(val)); return result - bfloat16(1.0); } } } #endif #include "tsl/lib/random/distribution_sampler.h" #include "tsl/lib/random/philox_random.h" namespace tsl { namespace random { template <> void SingleSampleAdapter<PhiloxRandom>::SkipFromGenerator(uint64 num_skips) { generator_->Skip(num_skips); } } }
#include "tsl/lib/random/random_distributions.h" #include <algorithm> #include <cmath> #include <functional> #include <numeric> #include <unordered_map> #include <vector> #include "tsl/lib/math/math_util.h" #include "tsl/lib/random/philox_random.h" #include "tsl/lib/random/philox_random_test_utils.h" #include "tsl/platform/logging.h" #include "tsl/platform/random.h" #include "tsl/platform/test.h" namespace tsl { namespace random { namespace { static constexpr float kZLimit = 6.0; static constexpr float kZLimitBfloat16 = 20.0; template <class Distribution> void FillRandomsWithSingles(PhiloxRandom gen, typename Distribution::ResultElementType* p, int64_t size) { int granularity = Distribution::kResultElementCount; CHECK(size % granularity == 0) << " size: " << size << " granularity: " << granularity; SingleSampleAdapter<PhiloxRandom> single_samples(&gen); Distribution dist; for (int i = 0; i < size; i += granularity) { auto sample = dist(&single_samples); std::copy(&sample[0], &sample[0] + granularity, &p[i]); } } template <typename T> bool CheckSamplesMoments(const std::vector<T>& samples, const std::function<double(int)>& theoretical_moments, int max_moments, int stride, T z_limit) { const T* const samples_data = &samples[0]; const int samples_size = samples.size(); std::vector<double> moments(max_moments + 1); double* const moments_data = &moments[0]; std::vector<int> moments_sample_count(max_moments + 1); int* const moments_sample_count_data = &moments_sample_count[0]; for (int k = 0; k < samples_size; ++k) { double moment = 1.; for (int i = 0; i <= max_moments; ++i) { int index = k + i * stride; if (index >= samples_size) { break; } moments_data[i] += moment; ++moments_sample_count_data[i]; moment *= static_cast<double>(samples_data[index]); } } for (int i = 0; i <= max_moments; ++i) { moments[i] /= moments_sample_count[i]; } bool status = true; for (int i = 1; i <= max_moments; ++i) { const double moments_i_mean = (stride == 0) ? theoretical_moments(i) : MathUtil::IPow(theoretical_moments(1), i); const double moments_i_squared = (stride == 0) ? theoretical_moments(2 * i) : MathUtil::IPow(theoretical_moments(2), i); const double moments_i_var = moments_i_squared - moments_i_mean * moments_i_mean; static const double kNumericalError = 1e-6; const double error_per_moment = i * kNumericalError; const double total_variance = moments_i_var / moments_sample_count[i] + error_per_moment; const double z_test = fabs((moments[i] - moments_i_mean) / sqrt(total_variance)); if (z_test > static_cast<double>(z_limit)) { LOG(ERROR) << "failing z_test:" << " moment: " << i << " stride: " << stride << " z_test: " << z_test << " z_limit: " << z_limit << " measured moments: " << moments[i] << " theoretical mean of the moments: " << moments_i_mean << " theoretical var of the moments: " << moments_i_var << " sample count: " << moments_sample_count[i]; status = false; } } return status; } template <typename T> void UniformMomentsTest(int count, int max_moments, const std::vector<int>& strides, T z_limit) { auto uniform_moments = [](int n) -> double { return 1. / (n + 1); }; std::vector<T> v1(count); uint64 seed = GetTestSeed(); PhiloxRandom gen(seed); FillRandoms<UniformDistribution<PhiloxRandom, T> >(gen, &v1[0], v1.size()); for (int stride : strides) { bool status = CheckSamplesMoments(v1, uniform_moments, max_moments, stride, z_limit); ASSERT_TRUE(status) << " UniformMomentsTest failing. seed: " << seed; } } template <typename T> void NormalMomentsTest(int count, int max_moments, const std::vector<int>& strides, T z_limit) { auto normal_moments = [](int n) -> double { if (n % 2 == 1) { return 0.; } else { double v = 1.; for (int i = n - 1; i >= 1; i -= 2) { v *= i; } return v; } }; std::vector<T> v1(count); uint64 seed = GetTestSeed(); PhiloxRandom gen(seed); FillRandoms<NormalDistribution<PhiloxRandom, T> >(gen, &v1[0], v1.size()); for (int stride : strides) { bool status = CheckSamplesMoments(v1, normal_moments, max_moments, stride, z_limit); ASSERT_TRUE(status) << " NormalMomentsTest failing. seed: " << seed; } } class TruncatedNormalMoments { public: double operator()(int n) { if (n == 0) { return 1; } if (n % 2 == 1) { return 0.; } auto iter = cached_results_.find(n); if (iter != cached_results_.end()) { return iter->second; } double bias = 2.0 * MathUtil::IPow(kV, n - 1) * kFV / (2.0 * kPhiV - 1.0); double moment_n_minus_2 = (*this)(n - 2); double moment_n = (n - 1) * moment_n_minus_2 - bias; cached_results_[n] = moment_n; return moment_n; } private: const double kV = 2.0; const double kFV = 1.0 / sqrt(2.0 * M_PI) * exp(-kV * kV / 2.0); const double kPhiV = 0.977249868051821; std::unordered_map<int, double> cached_results_; }; template <typename T> void RandomParametersMomentsTest(int count, int max_moments, const std::vector<int>& strides, T z_limit) { std::vector<T> v1(count); uint64 seed = GetTestSeed(); PhiloxRandom gen(seed); FillRandomsWithSingles< TruncatedNormalDistribution<SingleSampleAdapter<PhiloxRandom>, T> >( gen, &v1[0], v1.size()); for (int stride : strides) { bool status = CheckSamplesMoments(v1, TruncatedNormalMoments(), max_moments, stride, z_limit); ASSERT_TRUE(status) << " NormalMomentsTest failing. seed: " << seed; } } TEST(PhiloxRandomTest, UniformBfloat16MomentsTest) { const std::vector<int> strides = {0, 1, 4, 17}; UniformMomentsTest<bfloat16>(1 << 20, 40, strides, bfloat16(kZLimitBfloat16)); } TEST(PhiloxRandomTest, NormalBfloat16MomentsTest) { const std::vector<int> strides = {0, 1, 4, 17}; NormalMomentsTest<bfloat16>(8 << 20, 25, strides, bfloat16(kZLimitBfloat16)); } TEST(PhiloxRandomTest, RandomParametersBfloat16MomentsTest) { const std::vector<int> strides = {0, 1, 4, 17}; RandomParametersMomentsTest<bfloat16>(1 << 20, 40, strides, bfloat16(kZLimitBfloat16)); } TEST(PhiloxRandomTest, UniformFloatMomentsTest) { const std::vector<int> strides = {0, 1, 4, 17}; UniformMomentsTest<float>(1 << 20, 40, strides, kZLimit); } TEST(PhiloxRandomTest, NormalFloatMomentsTest) { const std::vector<int> strides = {0, 1, 4, 17}; NormalMomentsTest<float>(8 << 20, 25, strides, kZLimit); } TEST(PhiloxRandomTest, RandomParametersFloatMomentsTest) { const std::vector<int> strides = {0, 1, 4, 17}; RandomParametersMomentsTest<float>(1 << 20, 40, strides, kZLimit); } TEST(PhiloxRandomTest, UniformDoubleMomentsTest) { const std::vector<int> strides = {0, 1, 4, 17}; UniformMomentsTest<double>(1 << 20, 40, strides, kZLimit); } TEST(PhiloxRandomTest, NormalDoubleMomentsTest) { const std::vector<int> strides = {0, 1, 4, 17}; NormalMomentsTest<double>(8 << 20, 25, strides, kZLimit); } TEST(PhiloxRandomTest, RandomParametersDoubleMomentsTest) { const std::vector<int> strides = {0, 1, 4, 17}; RandomParametersMomentsTest<double>(1 << 20, 40, strides, kZLimit); } class MockGenerator { public: explicit MockGenerator(uint64 seed) : counter_(seed) {} using ResultType = std::vector<uint32>; using ResultElementType = uint32; static constexpr int kResultElementCount = 1; ResultType operator()() { ResultType result; result.push_back(counter_++); return result; } private: uint32 counter_; }; template <typename T> void SingleSampleAdapterSkipTest() { std::vector<uint64> skips(10); std::vector<uint64> skip_afters(10); std::iota(skips.begin(), skips.end(), 0); std::iota(skip_afters.begin(), skip_afters.end(), 0); uint64 total_samples = 100; uint64 seed = GetTestSeed(); for (uint64 skip : skips) { for (uint64 skip_after : skip_afters) { T parent_gen(seed); SingleSampleAdapter<T> gen(&parent_gen); T parent_gen_to_skip(seed); SingleSampleAdapter<T> gen_to_skip(&parent_gen_to_skip); int cur = 0; for (; cur < skip_after; cur++) { gen(); gen_to_skip(); } for (; cur < skip_after + skip; cur++) { gen(); } gen_to_skip.Skip(skip); for (; cur < total_samples; cur++) { ASSERT_EQ(gen(), gen_to_skip()); } } } } TEST(SingleSampleAdapterTest, PhiloxRandomSkip) { SingleSampleAdapterSkipTest<PhiloxRandom>(); } TEST(SingleSampleAdapterTest, MockGeneratorSkip) { SingleSampleAdapterSkipTest<MockGenerator>(); } } } }
2,642
cpp
google/tsl
distribution_sampler
tsl/lib/random/distribution_sampler.cc
tsl/lib/random/distribution_sampler_test.cc
#ifndef TENSORFLOW_TSL_LIB_RANDOM_DISTRIBUTION_SAMPLER_H_ #define TENSORFLOW_TSL_LIB_RANDOM_DISTRIBUTION_SAMPLER_H_ #include <memory> #include <utility> #include "absl/types/span.h" #include "tsl/lib/random/simple_philox.h" #include "tsl/platform/logging.h" #include "tsl/platform/macros.h" #include "tsl/platform/types.h" namespace tsl { namespace random { class DistributionSampler { public: explicit DistributionSampler(const absl::Span<const float> weights); ~DistributionSampler() {} int Sample(SimplePhilox* rand) const { float r = rand->RandFloat(); int idx = rand->Uniform(num_); if (r < prob(idx)) return idx; DCHECK_NE(-1, alt(idx)); return alt(idx); } int num() const { return num_; } private: float prob(int idx) const { DCHECK_LT(idx, num_); return data_[idx].first; } int alt(int idx) const { DCHECK_LT(idx, num_); return data_[idx].second; } void set_prob(int idx, float f) { DCHECK_LT(idx, num_); data_[idx].first = f; } void set_alt(int idx, int val) { DCHECK_LT(idx, num_); data_[idx].second = val; } int num_; std::unique_ptr<std::pair<float, int>[]> data_; DistributionSampler(const DistributionSampler&) = delete; void operator=(const DistributionSampler&) = delete; }; } } #endif #include "tsl/lib/random/distribution_sampler.h" #include <memory> #include <vector> #include "absl/types/span.h" namespace tsl { namespace random { DistributionSampler::DistributionSampler( const absl::Span<const float> weights) { DCHECK(!weights.empty()); int n = weights.size(); num_ = n; data_.reset(new std::pair<float, int>[n]); std::unique_ptr<double[]> pr(new double[n]); double sum = 0.0; for (int i = 0; i < n; i++) { sum += weights[i]; set_alt(i, -1); } std::vector<int> high; high.reserve(n); std::vector<int> low; low.reserve(n); for (int i = 0; i < n; i++) { double p = (weights[i] * n) / sum; pr[i] = p; if (p < 1.0) { low.push_back(i); } else { high.push_back(i); } } while (!high.empty() && !low.empty()) { int l = low.back(); low.pop_back(); int h = high.back(); high.pop_back(); set_alt(l, h); DCHECK_GE(pr[h], 1.0); double remaining = pr[h] - (1.0 - pr[l]); pr[h] = remaining; if (remaining < 1.0) { low.push_back(h); } else { high.push_back(h); } } for (int i = 0; i < n; i++) { set_prob(i, pr[i]); } for (size_t i = 0; i < high.size(); i++) { int idx = high[i]; set_prob(idx, 1.0); set_alt(idx, idx); } for (size_t i = 0; i < low.size(); i++) { int idx = low[i]; set_prob(idx, 1.0); set_alt(idx, idx); } } } }
#include "tsl/lib/random/distribution_sampler.h" #include <string.h> #include <memory> #include <vector> #include "tsl/lib/random/simple_philox.h" #include "tsl/platform/macros.h" #include "tsl/platform/test.h" #include "tsl/platform/test_benchmark.h" #include "tsl/platform/types.h" namespace tsl { namespace random { class DistributionSamplerTest : public ::testing::Test { protected: float TestWeights(const std::vector<float>& weights, int trials_per_bin) { int iters = weights.size() * trials_per_bin; std::unique_ptr<float[]> counts(new float[weights.size()]); memset(counts.get(), 0, sizeof(float) * weights.size()); DistributionSampler sampler(weights); PhiloxRandom philox(testing::RandomSeed(), 17); SimplePhilox random(&philox); for (int i = 0; i < iters; i++) { int r = sampler.Sample(&random); EXPECT_LT(r, weights.size()); EXPECT_GE(r, 0); counts[r] += 1.0; } float chi2 = 0.0; for (size_t i = 0; i < weights.size(); i++) { counts[i] /= iters; float err = (counts[i] - weights[i]); chi2 += (err * err) / weights[i]; } return chi2; } void TestDistribution(float* arr, int n) { std::vector<float> w; w.reserve(n); for (int i = 0; i < n; i++) { w.push_back(arr[i]); } float var = TestWeights(w, 1000); if (var < 0.001) return; var = TestWeights(w, 100000); if (var < 0.001) return; EXPECT_TRUE(false) << "Chi2 is " << var << " in " << n * 100000 << "iterations"; } }; TEST_F(DistributionSamplerTest, KnownDistribution) { float kEven2[] = {0.5, 0.5}; float kEven3[] = {0.33333333, 0.33333333, 0.33333333}; float kEven4[] = {0.25, 0.25, 0.25, 0.25}; float kDist1[] = {0.8, 0.15, 0.05}; TestDistribution(kEven2, TF_ARRAYSIZE(kEven2)); TestDistribution(kEven3, TF_ARRAYSIZE(kEven3)); TestDistribution(kEven4, TF_ARRAYSIZE(kEven4)); TestDistribution(kDist1, TF_ARRAYSIZE(kDist1)); } static void BM_DistributionSampler(::testing::benchmark::State& state) { const int n = state.range(0); PhiloxRandom philox(173, 371); SimplePhilox rand(&philox); std::vector<float> weights(n, 0); for (int i = 0; i < n; i++) { weights[i] = rand.Uniform(100); } DistributionSampler picker(weights); int r = 0; for (auto s : state) { r |= picker.Sample(&rand); } CHECK_NE(r, kint32max); } BENCHMARK(BM_DistributionSampler)->Arg(10)->Arg(100)->Arg(1000); } }
2,643
cpp
google/tsl
simple_philox
tsl/lib/random/simple_philox.cc
tsl/lib/random/simple_philox_test.cc
#ifndef TENSORFLOW_TSL_LIB_RANDOM_SIMPLE_PHILOX_H_ #define TENSORFLOW_TSL_LIB_RANDOM_SIMPLE_PHILOX_H_ #include <math.h> #include <string.h> #include <algorithm> #include "tsl/lib/random/philox_random.h" #include "tsl/lib/random/random_distributions.h" namespace tsl { namespace random { class SimplePhilox { public: PHILOX_DEVICE_INLINE explicit SimplePhilox(PhiloxRandom* gen) : single_(gen) {} PHILOX_DEVICE_INLINE uint32 Rand32() { return single_(); } PHILOX_DEVICE_INLINE uint64 Rand64() { const uint32 lo = single_(), hi = single_(); return lo | static_cast<uint64>(hi) << 32; } PHILOX_DEVICE_INLINE float RandFloat() { return Uint32ToFloat(single_()); } PHILOX_DEVICE_INLINE double RandDouble() { const uint32 x0 = single_(), x1 = single_(); return Uint64ToDouble(x0, x1); } uint32 Uniform(uint32 n); uint64 Uniform64(uint64 n); bool OneIn(uint32 n) { return Uniform(n) == 0; } uint32 Skewed(int max_log); private: SingleSampleAdapter<PhiloxRandom> single_; }; } } #endif #include "tsl/lib/random/simple_philox.h" #include "tsl/lib/random/exact_uniform_int.h" #include "tsl/platform/logging.h" namespace tsl { namespace random { uint32 SimplePhilox::Uniform(uint32 n) { return ExactUniformInt<uint32>(n, [this]() { return Rand32(); }); } uint64 SimplePhilox::Uniform64(uint64 n) { return ExactUniformInt<uint64>(n, [this]() { return Rand64(); }); } uint32 SimplePhilox::Skewed(int max_log) { CHECK(0 <= max_log && max_log <= 32); const int shift = Rand32() % (max_log + 1); const uint32 mask = shift == 32 ? ~static_cast<uint32>(0) : (1 << shift) - 1; return Rand32() & mask; } } }
#include "tsl/lib/random/simple_philox.h" #include <set> #include <string> #include "tsl/platform/logging.h" #include "tsl/platform/test.h" #include "tsl/platform/types.h" namespace tsl { namespace random { namespace { TEST(SimplePhiloxTest, FloatTest) { PhiloxRandom philox(7, 7); SimplePhilox gen(&philox); static const int kIters = 1000000; for (int i = 0; i < kIters; ++i) { float f = gen.RandFloat(); EXPECT_LE(0.0f, f); EXPECT_GT(1.0f, f); } for (int i = 0; i < kIters; ++i) { double d = gen.RandDouble(); EXPECT_LE(0.0, d); EXPECT_GT(1.0, d); } } static void DifferenceTest(const char *names, SimplePhilox *gen1, SimplePhilox *gen2) { static const int kIters = 100; bool different = false; for (int i = 0; i < kIters; ++i) { if (gen1->Rand32() != gen2->Rand32()) { different = true; break; } } CHECK(different) << "different seeds but same output!"; } TEST(SimplePhiloxTest, DifferenceTest) { PhiloxRandom philox1(1, 1), philox2(17, 17); SimplePhilox gen1(&philox1), gen2(&philox2); DifferenceTest("SimplePhilox: different seeds", &gen1, &gen2); } TEST(SimplePhiloxTest, DifferenceTestCloseSeeds) { PhiloxRandom philox1(1, 1), philox2(2, 1); SimplePhilox gen1(&philox1), gen2(&philox2); DifferenceTest("SimplePhilox: close seeds", &gen1, &gen2); } TEST(SimplePhiloxTest, Regression_CloseSeedsAreDifferent) { const int kCount = 1000; PhiloxRandom philox1(0, 1), philox2(1, 1); SimplePhilox gen1(&philox1), gen2(&philox2); std::set<uint32> first; std::set<uint32> all; for (int i = 0; i < kCount; ++i) { uint32 v = gen1.Rand32(); first.insert(v); all.insert(v); all.insert(gen2.Rand32()); } EXPECT_EQ(kCount, first.size()); EXPECT_EQ(2 * kCount, all.size()); } TEST(SimplePhiloxTest, TestUniform) { PhiloxRandom philox(17, 17); SimplePhilox gen(&philox); uint32 range = 3 * (1L << 29); uint32 threshold = 1L << 30; size_t count = 0; static const int kTrials = 100000; for (int i = 0; i < kTrials; ++i) { uint32 rnd = gen.Uniform(range); if (rnd < threshold) { ++count; } } EXPECT_LT(fabs((threshold + 0.0) / range - (count + 0.0) / kTrials), 0.005); } TEST(SimplePhiloxTest, TestUniform64) { PhiloxRandom philox(17, 17); SimplePhilox gen(&philox); uint64 range = 3 * (1LL << 59); uint64 threshold = 1LL << 60; size_t count = 0; static const int kTrials = 100000; for (int i = 0; i < kTrials; ++i) { uint64 rnd = gen.Uniform64(range); if (rnd < threshold) { ++count; } } EXPECT_LT(fabs((threshold + 0.0) / range - (count + 0.0) / kTrials), 0.005); } } } }
2,644
cpp
google/tsl
histogram
null
null
#ifndef TENSORFLOW_TSL_LIB_HISTOGRAM_HISTOGRAM_H_ #define TENSORFLOW_TSL_LIB_HISTOGRAM_HISTOGRAM_H_ #include <string> #include <vector> #include "tsl/platform/macros.h" #include "tsl/platform/mutex.h" #include "tsl/platform/thread_annotations.h" #include "tsl/platform/types.h" namespace tensorflow { class HistogramProto; } namespace tsl { using tensorflow::HistogramProto; namespace histogram { class Histogram { public: Histogram(); explicit Histogram(absl::Span<const double> custom_bucket_limits); bool DecodeFromProto(const HistogramProto& proto); ~Histogram() {} void Clear(); void Add(double value); void EncodeToProto(HistogramProto* proto, bool preserve_zero_buckets) const; double Median() const; double Percentile(double p) const; double Average() const; double StandardDeviation() const; std::string ToString() const; private: double min_; double max_; double num_; double sum_; double sum_squares_; std::vector<double> custom_bucket_limits_; absl::Span<const double> bucket_limits_; std::vector<double> buckets_; double Remap(double x, double x0, double x1, double y0, double y1) const; Histogram(const Histogram&) = delete; void operator=(const Histogram&) = delete; }; class ThreadSafeHistogram { public: ThreadSafeHistogram() {} explicit ThreadSafeHistogram(absl::Span<const double> custom_bucket_limits) : histogram_(custom_bucket_limits) {} bool DecodeFromProto(const HistogramProto& proto); ~ThreadSafeHistogram() {} void Clear(); void Add(double value); void EncodeToProto(HistogramProto* proto, bool preserve_zero_buckets) const; double Median() const; double Percentile(double p) const; double Average() const; double StandardDeviation() const; std::string ToString() const; private: mutable mutex mu_; Histogram histogram_ TF_GUARDED_BY(mu_); }; } } #endif #include "tsl/lib/histogram/histogram.h" #include <float.h> #include <math.h> #include <vector> #include "tsl/platform/logging.h" #include "tsl/platform/mutex.h" #include "tsl/platform/types.h" #include "tsl/protobuf/histogram.pb.h" namespace tsl { namespace histogram { static std::vector<double>* InitDefaultBucketsInner() { std::vector<double> buckets; std::vector<double> neg_buckets; double v = 1.0e-12; while (v < 1.0e20) { buckets.push_back(v); neg_buckets.push_back(-v); v *= 1.1; } buckets.push_back(DBL_MAX); neg_buckets.push_back(-DBL_MAX); std::reverse(neg_buckets.begin(), neg_buckets.end()); std::vector<double>* result = new std::vector<double>; result->insert(result->end(), neg_buckets.begin(), neg_buckets.end()); result->push_back(0.0); result->insert(result->end(), buckets.begin(), buckets.end()); return result; } static absl::Span<const double> InitDefaultBuckets() { static std::vector<double>* default_bucket_limits = InitDefaultBucketsInner(); return *default_bucket_limits; } Histogram::Histogram() : bucket_limits_(InitDefaultBuckets()) { Clear(); } Histogram::Histogram(absl::Span<const double> custom_bucket_limits) : custom_bucket_limits_(custom_bucket_limits.begin(), custom_bucket_limits.end()), bucket_limits_(custom_bucket_limits_) { #ifndef NDEBUG DCHECK_GT(bucket_limits_.size(), size_t{0}); for (size_t i = 1; i < bucket_limits_.size(); i++) { DCHECK_GT(bucket_limits_[i], bucket_limits_[i - 1]); } #endif Clear(); } bool Histogram::DecodeFromProto(const HistogramProto& proto) { if ((proto.bucket_size() != proto.bucket_limit_size()) || (proto.bucket_size() == 0)) { return false; } min_ = proto.min(); max_ = proto.max(); num_ = proto.num(); sum_ = proto.sum(); sum_squares_ = proto.sum_squares(); custom_bucket_limits_.clear(); custom_bucket_limits_.insert(custom_bucket_limits_.end(), proto.bucket_limit().begin(), proto.bucket_limit().end()); bucket_limits_ = custom_bucket_limits_; buckets_.clear(); buckets_.insert(buckets_.end(), proto.bucket().begin(), proto.bucket().end()); return true; } void Histogram::Clear() { min_ = bucket_limits_[bucket_limits_.size() - 1]; max_ = -DBL_MAX; num_ = 0; sum_ = 0; sum_squares_ = 0; buckets_.resize(bucket_limits_.size()); for (size_t i = 0; i < bucket_limits_.size(); i++) { buckets_[i] = 0; } } void Histogram::Add(double value) { int b = std::upper_bound(bucket_limits_.begin(), bucket_limits_.end(), value) - bucket_limits_.begin(); buckets_[b] += 1.0; if (min_ > value) min_ = value; if (max_ < value) max_ = value; num_++; sum_ += value; sum_squares_ += (value * value); } double Histogram::Median() const { return Percentile(50.0); } double Histogram::Remap(double x, double x0, double x1, double y0, double y1) const { return y0 + (x - x0) / (x1 - x0) * (y1 - y0); } double Histogram::Percentile(double p) const { if (num_ == 0.0) return 0.0; double threshold = num_ * (p / 100.0); double cumsum_prev = 0; for (size_t i = 0; i < buckets_.size(); i++) { double cumsum = cumsum_prev + buckets_[i]; if (cumsum >= threshold) { if (cumsum == cumsum_prev) { continue; } double lhs = (i == 0 || cumsum_prev == 0) ? min_ : bucket_limits_[i - 1]; lhs = std::max(lhs, min_); double rhs = bucket_limits_[i]; rhs = std::min(rhs, max_); double weight = Remap(threshold, cumsum_prev, cumsum, lhs, rhs); return weight; } cumsum_prev = cumsum; } return max_; } double Histogram::Average() const { if (num_ == 0.0) return 0; return sum_ / num_; } double Histogram::StandardDeviation() const { if (num_ == 0.0) return 0; double variance = (sum_squares_ * num_ - sum_ * sum_) / (num_ * num_); return sqrt(variance); } std::string Histogram::ToString() const { std::string r; char buf[200]; snprintf(buf, sizeof(buf), "Count: %.0f Average: %.4f StdDev: %.2f\n", num_, Average(), StandardDeviation()); r.append(buf); snprintf(buf, sizeof(buf), "Min: %.4f Median: %.4f Max: %.4f\n", (num_ == 0.0 ? 0.0 : min_), Median(), max_); r.append(buf); r.append("------------------------------------------------------\n"); const double mult = num_ > 0 ? 100.0 / num_ : 0.0; double sum = 0; for (size_t b = 0; b < buckets_.size(); b++) { if (buckets_[b] <= 0.0) continue; sum += buckets_[b]; snprintf(buf, sizeof(buf), "[ %10.2g, %10.2g ) %7.0f %7.3f%% %7.3f%% ", ((b == 0) ? -DBL_MAX : bucket_limits_[b - 1]), bucket_limits_[b], buckets_[b], mult * buckets_[b], mult * sum); r.append(buf); int marks = static_cast<int>(20 * (buckets_[b] / num_) + 0.5); r.append(marks, '#'); r.push_back('\n'); } return r; } void Histogram::EncodeToProto(HistogramProto* proto, bool preserve_zero_buckets) const { proto->Clear(); proto->set_min(min_); proto->set_max(max_); proto->set_num(num_); proto->set_sum(sum_); proto->set_sum_squares(sum_squares_); for (size_t i = 0; i < buckets_.size();) { double end = bucket_limits_[i]; double count = buckets_[i]; i++; if (!preserve_zero_buckets && count <= 0.0) { while (i < buckets_.size() && buckets_[i] <= 0.0) { end = bucket_limits_[i]; count = buckets_[i]; i++; } } proto->add_bucket_limit(end); proto->add_bucket(count); } if (proto->bucket_size() == 0.0) { proto->add_bucket_limit(DBL_MAX); proto->add_bucket(0.0); } } bool ThreadSafeHistogram::DecodeFromProto(const HistogramProto& proto) { mutex_lock l(mu_); return histogram_.DecodeFromProto(proto); } void ThreadSafeHistogram::Clear() { mutex_lock l(mu_); histogram_.Clear(); } void ThreadSafeHistogram::Add(double value) { mutex_lock l(mu_); histogram_.Add(value); } void ThreadSafeHistogram::EncodeToProto(HistogramProto* proto, bool preserve_zero_buckets) const { mutex_lock l(mu_); histogram_.EncodeToProto(proto, preserve_zero_buckets); } double ThreadSafeHistogram::Median() const { mutex_lock l(mu_); return histogram_.Median(); } double ThreadSafeHistogram::Percentile(double p) const { mutex_lock l(mu_); return histogram_.Percentile(p); } double ThreadSafeHistogram::Average() const { mutex_lock l(mu_); return histogram_.Average(); } double ThreadSafeHistogram::StandardDeviation() const { mutex_lock l(mu_); return histogram_.StandardDeviation(); } std::string ThreadSafeHistogram::ToString() const { mutex_lock l(mu_); return histogram_.ToString(); } } }
#include "tsl/lib/histogram/histogram.h" #include <float.h> #include "tsl/platform/logging.h" #include "tsl/platform/test.h" #include "tsl/protobuf/histogram.pb.h" namespace tsl { namespace histogram { static void Validate(const Histogram& h) { string s1 = h.ToString(); LOG(ERROR) << s1; HistogramProto proto_with_zeroes; h.EncodeToProto(&proto_with_zeroes, true); Histogram h2; EXPECT_TRUE(h2.DecodeFromProto(proto_with_zeroes)); string s2 = h2.ToString(); LOG(ERROR) << s2; EXPECT_EQ(s1, s2); HistogramProto proto_no_zeroes; h.EncodeToProto(&proto_no_zeroes, false); LOG(ERROR) << proto_no_zeroes.DebugString(); Histogram h3; EXPECT_TRUE(h3.DecodeFromProto(proto_no_zeroes)); string s3 = h3.ToString(); LOG(ERROR) << s3; EXPECT_EQ(s1, s3); } TEST(Histogram, Empty) { Histogram h; Validate(h); } TEST(Histogram, SingleValue) { Histogram h; h.Add(-3.0); Validate(h); } TEST(Histogram, CustomBuckets) { Histogram h({-10, -5, 0, 5, 10, 100, 1000, 10000, DBL_MAX}); h.Add(-3.0); h.Add(4.99); h.Add(5.0); h.Add(1000.0); Validate(h); } TEST(Histogram, Median) { Histogram h({0, 10, 100, DBL_MAX}); h.Add(-2); h.Add(-2); h.Add(0); double median = h.Median(); EXPECT_EQ(median, -0.5); } TEST(Histogram, Percentile) { Histogram h({1, 2, 3, 4}); h.Add(-1.0); h.Add(1.5); h.Add(1.5); h.Add(1.5); h.Add(2.5); h.Add(2.5); h.Add(2.5); h.Add(2.5); h.Add(3.5); h.Add(3.9); EXPECT_EQ(h.Percentile(0), -1.0); EXPECT_EQ(h.Percentile(25), 1.5); EXPECT_EQ(h.Percentile(50), 2.25); EXPECT_EQ(h.Percentile(75), 2.875); EXPECT_EQ(h.Percentile(90), 3.45); EXPECT_EQ(h.Percentile(100), 3.9); } TEST(Histogram, Basic) { Histogram h; for (int i = 0; i < 100; i++) { h.Add(i); } for (int i = 1000; i < 100000; i += 1000) { h.Add(i); } Validate(h); } TEST(ThreadSafeHistogram, Basic) { Histogram h; for (int i = 0; i < 100; i++) { h.Add(i); } ThreadSafeHistogram tsh; for (int i = 0; i < 100; i++) { tsh.Add(i); } for (int i = 0; i < 2; ++i) { bool preserve_zero_buckets = (i == 0); HistogramProto h_proto; h.EncodeToProto(&h_proto, preserve_zero_buckets); HistogramProto tsh_proto; tsh.EncodeToProto(&tsh_proto, preserve_zero_buckets); Histogram h2; EXPECT_TRUE(h2.DecodeFromProto(tsh_proto)); ThreadSafeHistogram tsh2; EXPECT_TRUE(tsh2.DecodeFromProto(h_proto)); EXPECT_EQ(h2.ToString(), tsh2.ToString()); } EXPECT_EQ(h.Median(), tsh.Median()); EXPECT_EQ(h.Percentile(40.0), tsh.Percentile(40.0)); EXPECT_EQ(h.Average(), tsh.Average()); EXPECT_EQ(h.StandardDeviation(), tsh.StandardDeviation()); EXPECT_EQ(h.ToString(), tsh.ToString()); } } }
2,645
cpp
google/tsl
crc32c
tsl/lib/hash/crc32c.cc
tsl/lib/hash/crc32c_test.cc
#ifndef TENSORFLOW_TSL_LIB_HASH_CRC32C_H_ #define TENSORFLOW_TSL_LIB_HASH_CRC32C_H_ #include <stddef.h> #include "absl/crc/crc32c.h" #include "absl/strings/string_view.h" #include "tsl/platform/cord.h" #include "tsl/platform/platform.h" #include "tsl/platform/types.h" namespace tsl { namespace crc32c { inline uint32 Extend(uint32 init_crc, const char* buf, size_t size) { return static_cast<uint32>(absl::ExtendCrc32c( static_cast<absl::crc32c_t>(init_crc), absl::string_view(buf, size))); } #if defined(TF_CORD_SUPPORT) extern uint32 Extend(uint32 init_crc, const absl::Cord& cord); #endif inline uint32 Value(const char* data, size_t n) { return Extend(0, data, n); } #if defined(TF_CORD_SUPPORT) inline uint32 Value(const absl::Cord& cord) { return Extend(0, cord); } #endif static const uint32 kMaskDelta = 0xa282ead8ul; inline uint32 Mask(uint32 crc) { return ((crc >> 15) | (crc << 17)) + kMaskDelta; } inline uint32 Unmask(uint32 masked_crc) { uint32 rot = masked_crc - kMaskDelta; return ((rot >> 17) | (rot << 15)); } } } #endif #include "tsl/lib/hash/crc32c.h" #include <stdint.h> #include "absl/strings/cord.h" #include "absl/strings/string_view.h" #include "tsl/platform/types.h" namespace tsl { namespace crc32c { #if defined(TF_CORD_SUPPORT) uint32 Extend(uint32 crc, const absl::Cord &cord) { for (absl::string_view fragment : cord.Chunks()) { crc = Extend(crc, fragment.data(), fragment.size()); } return crc; } #endif } }
#include "tsl/lib/hash/crc32c.h" #include <string> #include "absl/strings/cord.h" #include "tsl/platform/logging.h" #include "tsl/platform/test.h" #include "tsl/platform/test_benchmark.h" #include "tsl/platform/types.h" namespace tsl { namespace crc32c { TEST(CRC, StandardResults) { char buf[32]; memset(buf, 0, sizeof(buf)); ASSERT_EQ(0x8a9136aa, Value(buf, sizeof(buf))); memset(buf, 0xff, sizeof(buf)); ASSERT_EQ(0x62a8ab43, Value(buf, sizeof(buf))); for (int i = 0; i < 32; i++) { buf[i] = i; } ASSERT_EQ(0x46dd794e, Value(buf, sizeof(buf))); for (int i = 0; i < 32; i++) { buf[i] = 31 - i; } ASSERT_EQ(0x113fdb5c, Value(buf, sizeof(buf))); unsigned char data[48] = { 0x01, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x18, 0x28, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; ASSERT_EQ(0xd9963a56, Value(reinterpret_cast<char*>(data), sizeof(data))); ASSERT_EQ(0xdd1b19be, Value(reinterpret_cast<char*>(data), sizeof(data) - 7)); ASSERT_EQ(0x4930c4b1, Value(reinterpret_cast<char*>(data) + 1, sizeof(data) - 4)); } TEST(CRC, Values) { ASSERT_NE(Value("a", 1), Value("foo", 3)); } TEST(CRC, Extend) { ASSERT_EQ(Value("hello world", 11), Extend(Value("hello ", 6), "world", 5)); } TEST(CRC, Mask) { uint32 crc = Value("foo", 3); ASSERT_NE(crc, Mask(crc)); ASSERT_NE(crc, Mask(Mask(crc))); ASSERT_EQ(crc, Unmask(Mask(crc))); ASSERT_EQ(crc, Unmask(Unmask(Mask(Mask(crc))))); } #if defined(PLATFORM_GOOGLE) TEST(CRC, ValuesWithCord) { ASSERT_NE(Value(absl::Cord("a")), Value(absl::Cord("foo"))); } TEST(CRC, ExtendWithCord) { ASSERT_EQ(Value(absl::Cord("hello world")), Extend(Value(absl::Cord("hello ")), absl::Cord("world"))); } #endif static void BM_CRC(::testing::benchmark::State& state) { int len = state.range(0); std::string input(len, 'x'); uint32 h = 0; for (auto s : state) { h = Extend(h, input.data() + 1, len - 1); } state.SetBytesProcessed(state.iterations() * len); VLOG(1) << h; } BENCHMARK(BM_CRC)->Range(1, 256 * 1024); } }
2,646
cpp
google/tsl
bitmap
null
null
#ifndef TENSORFLOW_TSL_LIB_CORE_BITMAP_H_ #define TENSORFLOW_TSL_LIB_CORE_BITMAP_H_ #include <string> #include "tsl/platform/logging.h" namespace tsl { namespace core { class Bitmap { public: Bitmap(); explicit Bitmap(size_t n); ~Bitmap(); Bitmap(const Bitmap&) = delete; Bitmap& operator=(const Bitmap&) = delete; size_t bits() const; void Reset(size_t n); bool get(size_t i) const; void set(size_t i); void clear(size_t i); size_t FirstUnset(size_t start) const; std::string ToString() const; private: typedef uint32_t Word; static constexpr size_t kBits = 32; static size_t NumWords(size_t n) { return (n + kBits - 1) / kBits; } static Word Mask(size_t i) { return 1ull << i; } size_t nbits_; Word* word_; }; inline Bitmap::Bitmap() : nbits_(0), word_(nullptr) {} inline Bitmap::Bitmap(size_t n) : Bitmap() { Reset(n); } inline Bitmap::~Bitmap() { delete[] word_; } inline size_t Bitmap::bits() const { return nbits_; } inline bool Bitmap::get(size_t i) const { DCHECK_LT(i, nbits_); return word_[i / kBits] & Mask(i % kBits); } inline void Bitmap::set(size_t i) { DCHECK_LT(i, nbits_); word_[i / kBits] |= Mask(i % kBits); } inline void Bitmap::clear(size_t i) { DCHECK_LT(i, nbits_); word_[i / kBits] &= ~Mask(i % kBits); } } } #endif #include "tsl/lib/core/bitmap.h" #include <cstddef> #include <cstdint> #include <cstring> #include <string> #include "absl/numeric/bits.h" namespace tsl { namespace core { void Bitmap::Reset(size_t n) { const size_t num_words = NumWords(n); if (num_words != NumWords(nbits_)) { Word* w = new Word[num_words]; delete[] word_; word_ = w; } memset(word_, 0, sizeof(word_[0]) * num_words); nbits_ = n; } static size_t FindFirstSet(uint32_t w) { return w == 0 ? 0 : absl::countr_zero(w) + 1; } size_t Bitmap::FirstUnset(size_t start) const { if (start >= nbits_) { return nbits_; } size_t mask = (1ull << (start % kBits)) - 1; const size_t nwords = NumWords(nbits_); for (size_t i = start / kBits; i < nwords; i++) { Word word = word_[i] | mask; mask = 0; size_t r = FindFirstSet(~word); if (r) { size_t result = i * kBits + (r - 1); if (result > nbits_) result = nbits_; return result; } } return nbits_; } std::string Bitmap::ToString() const { std::string result; result.resize(bits()); for (size_t i = 0; i < nbits_; i++) { result[i] = get(i) ? '1' : '0'; } return result; } } }
#include "tsl/lib/core/bitmap.h" #include "tsl/lib/random/simple_philox.h" #include "tsl/platform/macros.h" #include "tsl/platform/test.h" namespace tsl { namespace core { namespace { size_t NextSize(size_t n) { return n + ((n < 75) ? 1 : 25); } static void MakeRandomBitmap(random::SimplePhilox* rnd, Bitmap* bitmap) { size_t n = rnd->Uniform(200); bitmap->Reset(n); for (size_t i = 0; i < n; i++) { if (rnd->OneIn(2)) bitmap->set(i); } } TEST(BitmapTest, Basic) { for (size_t n = 0; n < 200; n = NextSize(n)) { Bitmap bits(n); for (size_t i = 0; i < n; i++) { EXPECT_FALSE(bits.get(i)) << n << " " << i << " " << bits.ToString(); bits.set(i); EXPECT_TRUE(bits.get(i)) << n << " " << i << " " << bits.ToString(); bits.clear(i); EXPECT_FALSE(bits.get(i)) << n << " " << i << " " << bits.ToString(); } } } TEST(BitmapTest, ToString) { Bitmap bits(10); bits.set(1); bits.set(3); EXPECT_EQ(bits.ToString(), "0101000000"); } TEST(BitmapTest, FirstUnset) { for (size_t n = 0; n < 200; n = NextSize(n)) { for (size_t p = 0; p <= 100; p++) { for (size_t q = 0; q <= 100; q++) { Bitmap bitmap(n); int one_count = 0; size_t i = 0; while (i < p && i < n) { one_count++; bitmap.set(i); i++; } while (i < n) { i++; for (size_t j = 0; j < q && i < n; j++, i++) { one_count++; bitmap.set(i); } } int seen = 0; size_t pos = 0; while (true) { pos = bitmap.FirstUnset(pos); if (pos == n) break; ASSERT_FALSE(bitmap.get(pos)) << pos << " " << bitmap.ToString(); seen++; pos++; } EXPECT_EQ(seen, n - one_count) << " " << bitmap.ToString(); } } } } TEST(BitmapTest, FirstUnsetRandom) { random::PhiloxRandom philox(301, 17); random::SimplePhilox rnd(&philox); for (int iter = 0; iter < 10000; iter++) { Bitmap bitmap; MakeRandomBitmap(&rnd, &bitmap); size_t zero_bits = 0; for (size_t i = 0; i < bitmap.bits(); i++) { if (!bitmap.get(i)) zero_bits++; } int seen = 0; size_t pos = 0; while (true) { pos = bitmap.FirstUnset(pos); if (pos == bitmap.bits()) break; ASSERT_FALSE(bitmap.get(pos)) << pos << " " << bitmap.ToString(); seen++; pos++; } EXPECT_EQ(seen, zero_bits) << " " << bitmap.ToString(); } } } } }
2,647
cpp
google/tsl
table
tsl/lib/io/table.cc
tsl/lib/io/table_test.cc
#ifndef TENSORFLOW_TSL_LIB_IO_TABLE_H_ #define TENSORFLOW_TSL_LIB_IO_TABLE_H_ #include <stdint.h> #include "tsl/lib/io/iterator.h" namespace tsl { class RandomAccessFile; namespace table { struct Options; class Table { public: static absl::Status Open(const Options& options, tsl::RandomAccessFile* file, uint64 file_size, Table** table); ~Table(); Iterator* NewIterator() const; uint64 ApproximateOffsetOf(const StringPiece& key) const; private: struct Rep; Rep* rep_; explicit Table(Rep* rep) { rep_ = rep; } static Iterator* BlockReader(void*, const StringPiece&); absl::Status InternalGet(const StringPiece& key, void* arg, void (*handle_result)(void* arg, const StringPiece& k, const StringPiece& v)); Table(const Table&); void operator=(const Table&); }; } } #endif #include "tsl/lib/io/table.h" #include "tsl/lib/io/block.h" #include "tsl/lib/io/cache.h" #include "tsl/lib/io/format.h" #include "tsl/lib/io/table_options.h" #include "tsl/lib/io/two_level_iterator.h" #include "tsl/platform/coding.h" #include "tsl/platform/env.h" #include "tsl/platform/errors.h" namespace tsl { namespace table { struct Table::Rep { ~Rep() { delete index_block; } Options options; absl::Status status; RandomAccessFile* file; uint64 cache_id; BlockHandle metaindex_handle; Block* index_block; }; absl::Status Table::Open(const Options& options, RandomAccessFile* file, uint64 size, Table** table) { *table = nullptr; if (size < Footer::kEncodedLength) { return errors::DataLoss("file is too short to be an sstable"); } char footer_space[Footer::kEncodedLength]; StringPiece footer_input; absl::Status s = file->Read(size - Footer::kEncodedLength, Footer::kEncodedLength, &footer_input, footer_space); if (!s.ok()) return s; Footer footer; s = footer.DecodeFrom(&footer_input); if (!s.ok()) return s; BlockContents contents; Block* index_block = nullptr; if (s.ok()) { s = ReadBlock(file, footer.index_handle(), &contents); } if (s.ok()) { index_block = new Block(contents); Rep* rep = new Table::Rep; rep->options = options; rep->file = file; rep->metaindex_handle = footer.metaindex_handle(); rep->index_block = index_block; rep->cache_id = (options.block_cache ? options.block_cache->NewId() : 0); *table = new Table(rep); } else { if (index_block) delete index_block; } return s; } Table::~Table() { delete rep_; } static void DeleteBlock(void* arg, void* ignored) { delete reinterpret_cast<Block*>(arg); } static void DeleteCachedBlock(const absl::string_view&, void* value) { Block* block = reinterpret_cast<Block*>(value); delete block; } static void ReleaseBlock(void* arg, void* h) { Cache* cache = reinterpret_cast<Cache*>(arg); Cache::Handle* handle = reinterpret_cast<Cache::Handle*>(h); cache->Release(handle); } Iterator* Table::BlockReader(void* arg, const StringPiece& index_value) { Table* table = reinterpret_cast<Table*>(arg); Cache* block_cache = table->rep_->options.block_cache; Block* block = nullptr; Cache::Handle* cache_handle = nullptr; BlockHandle handle; StringPiece input = index_value; absl::Status s = handle.DecodeFrom(&input); if (s.ok()) { BlockContents contents; if (block_cache != nullptr) { char cache_key_buffer[16]; core::EncodeFixed64(cache_key_buffer, table->rep_->cache_id); core::EncodeFixed64(cache_key_buffer + 8, handle.offset()); absl::string_view key(cache_key_buffer, sizeof(cache_key_buffer)); cache_handle = block_cache->Lookup(key); if (cache_handle != nullptr) { block = reinterpret_cast<Block*>(block_cache->Value(cache_handle)); } else { s = ReadBlock(table->rep_->file, handle, &contents); if (s.ok()) { block = new Block(contents); cache_handle = block_cache->Insert(key, block, block->size(), &DeleteCachedBlock); } } } else { s = ReadBlock(table->rep_->file, handle, &contents); if (s.ok()) { block = new Block(contents); } } } Iterator* iter; if (block != nullptr) { iter = block->NewIterator(); if (cache_handle == nullptr) { iter->RegisterCleanup(&DeleteBlock, block, nullptr); } else { iter->RegisterCleanup(&ReleaseBlock, block_cache, cache_handle); } } else { iter = NewErrorIterator(s); } return iter; } Iterator* Table::NewIterator() const { return NewTwoLevelIterator(rep_->index_block->NewIterator(), &Table::BlockReader, const_cast<Table*>(this)); } absl::Status Table::InternalGet(const StringPiece& k, void* arg, void (*saver)(void*, const StringPiece&, const StringPiece&)) { absl::Status s; Iterator* iiter = rep_->index_block->NewIterator(); iiter->Seek(k); if (iiter->Valid()) { Iterator* block_iter = BlockReader(this, iiter->value()); block_iter->Seek(k); if (block_iter->Valid()) { (*saver)(arg, block_iter->key(), block_iter->value()); } s = block_iter->status(); delete block_iter; } if (s.ok()) { s = iiter->status(); } delete iiter; return s; } uint64 Table::ApproximateOffsetOf(const StringPiece& key) const { Iterator* index_iter = rep_->index_block->NewIterator(); index_iter->Seek(key); uint64 result; if (index_iter->Valid()) { BlockHandle handle; StringPiece input = index_iter->value(); absl::Status s = handle.DecodeFrom(&input); if (s.ok()) { result = handle.offset(); } else { result = rep_->metaindex_handle.offset(); } } else { result = rep_->metaindex_handle.offset(); } delete index_iter; return result; } } }
#include "tsl/lib/io/table.h" #include <algorithm> #include <map> #include <string> #include <vector> #include "absl/strings/escaping.h" #include "tsl/lib/io/block.h" #include "tsl/lib/io/block_builder.h" #include "tsl/lib/io/format.h" #include "tsl/lib/io/iterator.h" #include "tsl/lib/io/table_builder.h" #include "tsl/lib/random/simple_philox.h" #include "tsl/platform/env.h" #include "tsl/platform/errors.h" #include "tsl/platform/snappy.h" #include "tsl/platform/test.h" namespace tsl { namespace table { namespace { typedef std::pair<StringPiece, StringPiece> StringPiecePair; } namespace test { static StringPiece RandomString(random::SimplePhilox* rnd, int len, string* dst) { dst->resize(len); for (int i = 0; i < len; i++) { (*dst)[i] = static_cast<char>(' ' + rnd->Uniform(95)); } return StringPiece(*dst); } static string RandomKey(random::SimplePhilox* rnd, int len) { static const char kTestChars[] = {'\0', '\1', 'a', 'b', 'c', 'd', 'e', '\xfd', '\xfe', '\xff'}; string result; for (int i = 0; i < len; i++) { result += kTestChars[rnd->Uniform(sizeof(kTestChars))]; } return result; } static StringPiece CompressibleString(random::SimplePhilox* rnd, double compressed_fraction, size_t len, string* dst) { int raw = static_cast<int>(len * compressed_fraction); if (raw < 1) raw = 1; string raw_data; RandomString(rnd, raw, &raw_data); dst->clear(); while (dst->size() < len) { dst->append(raw_data); } dst->resize(len); return StringPiece(*dst); } } static void Increment(string* key) { key->push_back('\0'); } namespace { struct STLLessThan { STLLessThan() {} bool operator()(const string& a, const string& b) const { return StringPiece(a).compare(StringPiece(b)) < 0; } }; } class StringSink : public WritableFile { public: ~StringSink() override {} const string& contents() const { return contents_; } absl::Status Close() override { return absl::OkStatus(); } absl::Status Flush() override { return absl::OkStatus(); } absl::Status Name(StringPiece* result) const override { return errors::Unimplemented("StringSink does not support Name()"); } absl::Status Sync() override { return absl::OkStatus(); } absl::Status Tell(int64_t* pos) override { *pos = contents_.size(); return absl::OkStatus(); } absl::Status Append(StringPiece data) override { contents_.append(data.data(), data.size()); return absl::OkStatus(); } private: string contents_; }; class StringSource : public RandomAccessFile { public: explicit StringSource(const StringPiece& contents) : contents_(contents.data(), contents.size()), bytes_read_(0) {} ~StringSource() override {} uint64 Size() const { return contents_.size(); } absl::Status Name(StringPiece* result) const override { return errors::Unimplemented("StringSource does not support Name()"); } absl::Status Read(uint64 offset, size_t n, StringPiece* result, char* scratch) const override { if (offset > contents_.size()) { return errors::InvalidArgument("invalid Read offset"); } if (offset + n > contents_.size()) { n = contents_.size() - offset; } memcpy(scratch, &contents_[offset], n); *result = StringPiece(scratch, n); bytes_read_ += n; return absl::OkStatus(); } uint64 BytesRead() const { return bytes_read_; } private: string contents_; mutable uint64 bytes_read_; }; typedef std::map<string, string, STLLessThan> KVMap; class Constructor { public: explicit Constructor() : data_(STLLessThan()) {} virtual ~Constructor() {} void Add(const string& key, const StringPiece& value) { data_[key] = string(value); } void Finish(const Options& options, std::vector<string>* keys, KVMap* kvmap) { *kvmap = data_; keys->clear(); for (KVMap::const_iterator it = data_.begin(); it != data_.end(); ++it) { keys->push_back(it->first); } data_.clear(); absl::Status s = FinishImpl(options, *kvmap); ASSERT_TRUE(s.ok()) << s.ToString(); } virtual absl::Status FinishImpl(const Options& options, const KVMap& data) = 0; virtual Iterator* NewIterator() const = 0; virtual const KVMap& data() { return data_; } private: KVMap data_; }; class BlockConstructor : public Constructor { public: BlockConstructor() : block_(nullptr) {} ~BlockConstructor() override { delete block_; } absl::Status FinishImpl(const Options& options, const KVMap& data) override { delete block_; block_ = nullptr; BlockBuilder builder(&options); for (KVMap::const_iterator it = data.begin(); it != data.end(); ++it) { builder.Add(it->first, it->second); } data_ = string(builder.Finish()); BlockContents contents; contents.data = data_; contents.cacheable = false; contents.heap_allocated = false; block_ = new Block(contents); return absl::OkStatus(); } Iterator* NewIterator() const override { return block_->NewIterator(); } private: string data_; Block* block_; }; class TableConstructor : public Constructor { public: TableConstructor() : source_(nullptr), table_(nullptr) {} ~TableConstructor() override { Reset(); } absl::Status FinishImpl(const Options& options, const KVMap& data) override { Reset(); StringSink sink; TableBuilder builder(options, &sink); for (KVMap::const_iterator it = data.begin(); it != data.end(); ++it) { builder.Add(it->first, it->second); TF_CHECK_OK(builder.status()); } absl::Status s = builder.Finish(); TF_CHECK_OK(s) << s.ToString(); CHECK_EQ(sink.contents().size(), builder.FileSize()); source_ = new StringSource(sink.contents()); Options table_options; return Table::Open(table_options, source_, sink.contents().size(), &table_); } Iterator* NewIterator() const override { return table_->NewIterator(); } uint64 ApproximateOffsetOf(const StringPiece& key) const { return table_->ApproximateOffsetOf(key); } uint64 BytesRead() const { return source_->BytesRead(); } private: void Reset() { delete table_; delete source_; table_ = nullptr; source_ = nullptr; } StringSource* source_; Table* table_; }; enum TestType { TABLE_TEST, BLOCK_TEST }; struct TestArgs { TestType type; int restart_interval; }; static const TestArgs kTestArgList[] = { {TABLE_TEST, 16}, {TABLE_TEST, 1}, {TABLE_TEST, 1024}, {BLOCK_TEST, 16}, {BLOCK_TEST, 1}, {BLOCK_TEST, 1024}, }; static const int kNumTestArgs = sizeof(kTestArgList) / sizeof(kTestArgList[0]); class Harness : public ::testing::Test { public: Harness() : constructor_(nullptr) {} void Init(const TestArgs& args) { delete constructor_; constructor_ = nullptr; options_ = Options(); options_.block_restart_interval = args.restart_interval; options_.block_size = 256; switch (args.type) { case TABLE_TEST: constructor_ = new TableConstructor(); break; case BLOCK_TEST: constructor_ = new BlockConstructor(); break; } } ~Harness() override { delete constructor_; } void Add(const string& key, const string& value) { constructor_->Add(key, value); } void Test(random::SimplePhilox* rnd, int num_random_access_iters = 200) { std::vector<string> keys; KVMap data; constructor_->Finish(options_, &keys, &data); TestForwardScan(keys, data); TestRandomAccess(rnd, keys, data, num_random_access_iters); } void TestForwardScan(const std::vector<string>& keys, const KVMap& data) { Iterator* iter = constructor_->NewIterator(); ASSERT_TRUE(!iter->Valid()); iter->SeekToFirst(); for (KVMap::const_iterator model_iter = data.begin(); model_iter != data.end(); ++model_iter) { ASSERT_EQ(ToStringPiecePair(data, model_iter), ToStringPiecePair(iter)); iter->Next(); } ASSERT_TRUE(!iter->Valid()); delete iter; } void TestRandomAccess(random::SimplePhilox* rnd, const std::vector<string>& keys, const KVMap& data, int num_random_access_iters) { static const bool kVerbose = false; Iterator* iter = constructor_->NewIterator(); ASSERT_TRUE(!iter->Valid()); KVMap::const_iterator model_iter = data.begin(); if (kVerbose) fprintf(stderr, "---\n"); for (int i = 0; i < num_random_access_iters; i++) { const int toss = rnd->Uniform(3); switch (toss) { case 0: { if (iter->Valid()) { if (kVerbose) fprintf(stderr, "Next\n"); iter->Next(); ++model_iter; ASSERT_EQ(ToStringPiecePair(data, model_iter), ToStringPiecePair(iter)); } break; } case 1: { if (kVerbose) fprintf(stderr, "SeekToFirst\n"); iter->SeekToFirst(); model_iter = data.begin(); ASSERT_EQ(ToStringPiecePair(data, model_iter), ToStringPiecePair(iter)); break; } case 2: { string key = PickRandomKey(rnd, keys); model_iter = data.lower_bound(key); if (kVerbose) fprintf(stderr, "Seek '%s'\n", absl::CEscape(key).c_str()); iter->Seek(StringPiece(key)); ASSERT_EQ(ToStringPiecePair(data, model_iter), ToStringPiecePair(iter)); break; } } } delete iter; } StringPiecePair ToStringPiecePair(const KVMap& data, const KVMap::const_iterator& it) { if (it == data.end()) { return StringPiecePair("END", ""); } else { return StringPiecePair(it->first, it->second); } } StringPiecePair ToStringPiecePair(const KVMap& data, const KVMap::const_reverse_iterator& it) { if (it == data.rend()) { return StringPiecePair("END", ""); } else { return StringPiecePair(it->first, it->second); } } StringPiecePair ToStringPiecePair(const Iterator* it) { if (!it->Valid()) { return StringPiecePair("END", ""); } else { return StringPiecePair(it->key(), it->value()); } } string PickRandomKey(random::SimplePhilox* rnd, const std::vector<string>& keys) { if (keys.empty()) { return "foo"; } else { const int index = rnd->Uniform(keys.size()); string result = keys[index]; switch (rnd->Uniform(3)) { case 0: break; case 1: { if (!result.empty() && result[result.size() - 1] > '\0') { result[result.size() - 1]--; } break; } case 2: { Increment(&result); break; } } return result; } } private: Options options_; Constructor* constructor_; }; TEST_F(Harness, Empty) { for (int i = 0; i < kNumTestArgs; i++) { Init(kTestArgList[i]); random::PhiloxRandom philox(testing::RandomSeed() + 1, 17); random::SimplePhilox rnd(&philox); Test(&rnd); } } TEST_F(Harness, ZeroRestartPointsInBlock) { char data[sizeof(uint32)]; memset(data, 0, sizeof(data)); BlockContents contents; contents.data = StringPiece(data, sizeof(data)); contents.cacheable = false; contents.heap_allocated = false; Block block(contents); Iterator* iter = block.NewIterator(); iter->SeekToFirst(); ASSERT_TRUE(!iter->Valid()); iter->Seek("foo"); ASSERT_TRUE(!iter->Valid()); delete iter; } TEST_F(Harness, SimpleEmptyKey) { for (int i = 0; i < kNumTestArgs; i++) { Init(kTestArgList[i]); random::PhiloxRandom philox(testing::RandomSeed() + 1, 17); random::SimplePhilox rnd(&philox); Add("", "v"); Test(&rnd); } } TEST_F(Harness, SimpleSingle) { for (int i = 0; i < kNumTestArgs; i++) { Init(kTestArgList[i]); random::PhiloxRandom philox(testing::RandomSeed() + 2, 17); random::SimplePhilox rnd(&philox); Add("abc", "v"); Test(&rnd); } } TEST_F(Harness, SimpleMulti) { for (int i = 0; i < kNumTestArgs; i++) { Init(kTestArgList[i]); random::PhiloxRandom philox(testing::RandomSeed() + 3, 17); random::SimplePhilox rnd(&philox); Add("abc", "v"); Add("abcd", "v"); Add("ac", "v2"); Test(&rnd); } } TEST_F(Harness, SimpleMultiBigValues) { for (int i = 0; i < kNumTestArgs; i++) { Init(kTestArgList[i]); random::PhiloxRandom philox(testing::RandomSeed() + 3, 17); random::SimplePhilox rnd(&philox); Add("ainitial", "tiny"); Add("anext", string(10000000, 'a')); Add("anext2", string(10000000, 'b')); Add("azz", "tiny"); Test(&rnd, 100 ); } } TEST_F(Harness, SimpleSpecialKey) { for (int i = 0; i < kNumTestArgs; i++) { Init(kTestArgList[i]); random::PhiloxRandom philox(testing::RandomSeed() + 4, 17); random::SimplePhilox rnd(&philox); Add("\xff\xff", "v3"); Test(&rnd); } } TEST_F(Harness, Randomized) { for (int i = 0; i < kNumTestArgs; i++) { Init(kTestArgList[i]); random::PhiloxRandom philox(testing::RandomSeed() + 5, 17); random::SimplePhilox rnd(&philox); for (int num_entries = 0; num_entries < 2000; num_entries += (num_entries < 50 ? 1 : 200)) { if ((num_entries % 10) == 0) { fprintf(stderr, "case %d of %d: num_entries = %d\n", (i + 1), int(kNumTestArgs), num_entries); } for (int e = 0; e < num_entries; e++) { string v; Add(test::RandomKey(&rnd, rnd.Skewed(4)), string(test::RandomString(&rnd, rnd.Skewed(5), &v))); } Test(&rnd); } } } static bool Between(uint64 val, uint64 low, uint64 high) { bool result = (val >= low) && (val <= high); if (!result) { fprintf(stderr, "Value %llu is not in range [%llu, %llu]\n", static_cast<unsigned long long>(val), static_cast<unsigned long long>(low), static_cast<unsigned long long>(high)); } return result; } class TableTest {}; TEST(TableTest, ApproximateOffsetOfPlain) { TableConstructor c; c.Add("k01", "hello"); c.Add("k02", "hello2"); c.Add("k03", string(10000, 'x')); c.Add("k04", string(200000, 'x')); c.Add("k05", string(300000, 'x')); c.Add("k06", "hello3"); c.Add("k07", string(100000, 'x')); std::vector<string> keys; KVMap kvmap; Options options; options.block_size = 1024; options.compression = kNoCompression; c.Finish(options, &keys, &kvmap); ASSERT_TRUE(Between(c.ApproximateOffsetOf("abc"), 0, 0)); ASSERT_TRUE(Between(c.ApproximateOffsetOf("k01"), 0, 0)); ASSERT_TRUE(Between(c.ApproximateOffsetOf("k01a"), 0, 0)); ASSERT_TRUE(Between(c.ApproximateOffsetOf("k02"), 0, 0)); ASSERT_TRUE(Between(c.ApproximateOffsetOf("k03"), 10, 500)); ASSERT_TRUE(Between(c.ApproximateOffsetOf("k04"), 10000, 11000)); ASSERT_TRUE(Between(c.ApproximateOffsetOf("k04a"), 210000, 211000)); ASSERT_TRUE(Between(c.ApproximateOffsetOf("k05"), 210000, 211000)); ASSERT_TRUE(Between(c.ApproximateOffsetOf("k06"), 510000, 511000)); ASSERT_TRUE(Between(c.ApproximateOffsetOf("k07"), 510000, 511000)); ASSERT_TRUE(Between(c.ApproximateOffsetOf("xyz"), 610000, 612000)); } static bool SnappyCompressionSupported() { string out; StringPiece in = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; return port::Snappy_Compress(in.data(), in.size(), &out); } TEST(TableTest, ApproximateOffsetOfCompressed) { if (!SnappyCompressionSupported()) { fprintf(stderr, "skipping compression tests\n"); return; } random::PhiloxRandom philox(301, 17); random::SimplePhilox rnd(&philox); TableConstructor c; string tmp; c.Add("k01", "hello"); c.Add("k02", test::CompressibleString(&rnd, 0.25, 10000, &tmp)); c.Add("k03", "hello3"); c.Add("k04", test::CompressibleString(&rnd, 0.25, 10000, &tmp)); std::vector<string> keys; KVMap kvmap; Options options; options.block_size = 1024; options.compression = kSnappyCompression; c.Finish(options, &keys, &kvmap); ASSERT_TRUE(Between(c.ApproximateOffsetOf("abc"), 0, 0)); ASSERT_TRUE(Between(c.ApproximateOffsetOf("k01"), 0, 0)); ASSERT_TRUE(Between(c.ApproximateOffsetOf("k02"), 10, 100)); ASSERT_TRUE(Between(c.ApproximateOffsetOf("k03"), 2000, 4000)); ASSERT_TRUE(Between(c.ApproximateOffsetOf("k04"), 2000, 4000)); ASSERT_TRUE(Between(c.ApproximateOffsetOf("xyz"), 4000, 7000)); } TEST(TableTest, SeekToFirstKeyDoesNotReadTooMuch) { random::PhiloxRandom philox(301, 17); random::SimplePhilox rnd(&philox); string tmp; TableConstructor c; c.Add("k01", "firstvalue"); c.Add("k03", test::CompressibleString(&rnd, 0.25, 1000000, &tmp)); c.Add("k04", "abc"); std::vector<string> keys; KVMap kvmap; Options options; options.block_size = 1024; options.compression = kNoCompression; c.Finish(options, &keys, &kvmap); Iterator* iter = c.NewIterator(); iter->Seek("k01"); delete iter; EXPECT_LT(c.BytesRead(), 200); } } }
2,648
cpp
google/tsl
random_inputstream
tsl/lib/io/random_inputstream.cc
tsl/lib/io/random_inputstream_test.cc
#ifndef TENSORFLOW_TSL_LIB_IO_RANDOM_INPUTSTREAM_H_ #define TENSORFLOW_TSL_LIB_IO_RANDOM_INPUTSTREAM_H_ #include "tsl/lib/io/inputstream_interface.h" #include "tsl/platform/cord.h" #include "tsl/platform/file_system.h" namespace tsl { namespace io { class RandomAccessInputStream : public InputStreamInterface { public: RandomAccessInputStream(RandomAccessFile* file, bool owns_file = false); ~RandomAccessInputStream() override; absl::Status ReadNBytes(int64_t bytes_to_read, tstring* result) override; #if defined(TF_CORD_SUPPORT) absl::Status ReadNBytes(int64_t bytes_to_read, absl::Cord* result) override; #endif absl::Status SkipNBytes(int64_t bytes_to_skip) override; int64_t Tell() const override; absl::Status Seek(int64_t position) { pos_ = position; return absl::OkStatus(); } absl::Status Reset() override { return Seek(0); } private: RandomAccessFile* file_; int64_t pos_ = 0; bool owns_file_ = false; }; } } #endif #include "tsl/lib/io/random_inputstream.h" #include <memory> namespace tsl { namespace io { RandomAccessInputStream::RandomAccessInputStream(RandomAccessFile* file, bool owns_file) : file_(file), owns_file_(owns_file) {} RandomAccessInputStream::~RandomAccessInputStream() { if (owns_file_) { delete file_; } } absl::Status RandomAccessInputStream::ReadNBytes(int64_t bytes_to_read, tstring* result) { if (bytes_to_read < 0) { return errors::InvalidArgument("Cannot read negative number of bytes"); } result->clear(); result->resize_uninitialized(bytes_to_read); char* result_buffer = &(*result)[0]; StringPiece data; absl::Status s = file_->Read(pos_, bytes_to_read, &data, result_buffer); if (data.data() != result_buffer) { memmove(result_buffer, data.data(), data.size()); } result->resize(data.size()); if (s.ok() || errors::IsOutOfRange(s)) { pos_ += data.size(); } return s; } #if defined(TF_CORD_SUPPORT) absl::Status RandomAccessInputStream::ReadNBytes(int64_t bytes_to_read, absl::Cord* result) { if (bytes_to_read < 0) { return errors::InvalidArgument("Cannot read negative number of bytes"); } int64_t current_size = result->size(); absl::Status s = file_->Read(pos_, bytes_to_read, result); if (s.ok() || errors::IsOutOfRange(s)) { pos_ += result->size() - current_size; } return s; } #endif static constexpr int64_t kMaxSkipSize = 8 * 1024 * 1024; absl::Status RandomAccessInputStream::SkipNBytes(int64_t bytes_to_skip) { if (bytes_to_skip < 0) { return errors::InvalidArgument("Can't skip a negative number of bytes"); } std::unique_ptr<char[]> scratch(new char[kMaxSkipSize]); if (bytes_to_skip > 0) { StringPiece data; absl::Status s = file_->Read(pos_ + bytes_to_skip - 1, 1, &data, scratch.get()); if ((s.ok() || errors::IsOutOfRange(s)) && data.size() == 1) { pos_ += bytes_to_skip; return absl::OkStatus(); } } while (bytes_to_skip > 0) { int64_t bytes_to_read = std::min<int64_t>(kMaxSkipSize, bytes_to_skip); StringPiece data; absl::Status s = file_->Read(pos_, bytes_to_read, &data, scratch.get()); if (s.ok() || errors::IsOutOfRange(s)) { pos_ += data.size(); } else { return s; } if (data.size() < static_cast<size_t>(bytes_to_read)) { return errors::OutOfRange("reached end of file"); } bytes_to_skip -= bytes_to_read; } return absl::OkStatus(); } int64_t RandomAccessInputStream::Tell() const { return pos_; } } }
#include "tsl/lib/io/random_inputstream.h" #include "tsl/lib/core/status_test_util.h" #include "tsl/platform/env.h" #include "tsl/platform/test.h" namespace tsl { namespace io { namespace { TEST(RandomInputStream, ReadNBytes) { Env* env = Env::Default(); string fname = testing::TmpDir() + "/random_inputbuffer_test"; TF_ASSERT_OK(WriteStringToFile(env, fname, "0123456789")); std::unique_ptr<RandomAccessFile> file; TF_ASSERT_OK(env->NewRandomAccessFile(fname, &file)); tstring read; RandomAccessInputStream in(file.get()); TF_ASSERT_OK(in.ReadNBytes(3, &read)); EXPECT_EQ(read, "012"); EXPECT_EQ(3, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(0, &read)); EXPECT_EQ(read, ""); EXPECT_EQ(3, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(5, &read)); EXPECT_EQ(read, "34567"); EXPECT_EQ(8, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(0, &read)); EXPECT_EQ(read, ""); EXPECT_EQ(8, in.Tell()); EXPECT_TRUE(errors::IsOutOfRange(in.ReadNBytes(20, &read))); EXPECT_EQ(read, "89"); EXPECT_EQ(10, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(0, &read)); EXPECT_EQ(read, ""); EXPECT_EQ(10, in.Tell()); } #if defined(TF_CORD_SUPPORT) TEST(RandomInputStream, ReadNBytesWithCords) { Env* env = Env::Default(); string fname = testing::TmpDir() + "/random_inputbuffer_test"; TF_ASSERT_OK(WriteStringToFile(env, fname, "0123456789")); std::unique_ptr<RandomAccessFile> file; TF_ASSERT_OK(env->NewRandomAccessFile(fname, &file)); absl::Cord read; RandomAccessInputStream in(file.get()); TF_ASSERT_OK(in.ReadNBytes(3, &read)); EXPECT_EQ(read, "012"); EXPECT_EQ(3, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(0, &read)); EXPECT_EQ(read, "012"); EXPECT_EQ(3, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(5, &read)); EXPECT_EQ(read, "01234567"); EXPECT_EQ(8, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(0, &read)); EXPECT_EQ(read, "01234567"); EXPECT_EQ(8, in.Tell()); EXPECT_TRUE(errors::IsOutOfRange(in.ReadNBytes(20, &read))); EXPECT_EQ(read, "0123456789"); EXPECT_EQ(10, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(0, &read)); EXPECT_EQ(read, "0123456789"); EXPECT_EQ(10, in.Tell()); } #endif TEST(RandomInputStream, SkipNBytes) { Env* env = Env::Default(); string fname = testing::TmpDir() + "/random_inputbuffer_test"; TF_ASSERT_OK(WriteStringToFile(env, fname, "0123456789")); std::unique_ptr<RandomAccessFile> file; TF_ASSERT_OK(env->NewRandomAccessFile(fname, &file)); tstring read; RandomAccessInputStream in(file.get()); TF_ASSERT_OK(in.SkipNBytes(3)); EXPECT_EQ(3, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(0, &read)); EXPECT_EQ(read, ""); EXPECT_EQ(3, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(4, &read)); EXPECT_EQ(read, "3456"); EXPECT_EQ(7, in.Tell()); TF_ASSERT_OK(in.SkipNBytes(0)); EXPECT_EQ(7, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(2, &read)); EXPECT_EQ(read, "78"); EXPECT_EQ(9, in.Tell()); EXPECT_TRUE(errors::IsOutOfRange(in.SkipNBytes(20))); EXPECT_EQ(10, in.Tell()); EXPECT_TRUE(errors::IsOutOfRange(in.ReadNBytes(5, &read))); EXPECT_EQ(read, ""); EXPECT_EQ(10, in.Tell()); } TEST(RandomInputStream, Seek) { Env* env = Env::Default(); string fname = testing::TmpDir() + "/random_inputbuffer_seek_test"; TF_ASSERT_OK(WriteStringToFile(env, fname, "0123456789")); std::unique_ptr<RandomAccessFile> file; TF_ASSERT_OK(env->NewRandomAccessFile(fname, &file)); tstring read; RandomAccessInputStream in(file.get()); TF_ASSERT_OK(in.Seek(3)); EXPECT_EQ(3, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(4, &read)); EXPECT_EQ(read, "3456"); EXPECT_EQ(7, in.Tell()); TF_ASSERT_OK(in.Seek(1)); TF_ASSERT_OK(in.ReadNBytes(4, &read)); EXPECT_EQ(read, "1234"); EXPECT_EQ(5, in.Tell()); } } } }
2,649
cpp
google/tsl
buffered_inputstream
tsl/lib/io/buffered_inputstream.cc
tsl/lib/io/buffered_inputstream_test.cc
#ifndef TENSORFLOW_TSL_LIB_IO_BUFFERED_INPUTSTREAM_H_ #define TENSORFLOW_TSL_LIB_IO_BUFFERED_INPUTSTREAM_H_ #include <string> #include "tsl/lib/io/inputstream_interface.h" #include "tsl/platform/file_system.h" namespace tsl { namespace io { class BufferedInputStream : public InputStreamInterface { public: BufferedInputStream(InputStreamInterface* input_stream, size_t buffer_bytes, bool owns_input_stream = false); BufferedInputStream(RandomAccessFile* file, size_t buffer_bytes); ~BufferedInputStream() override; absl::Status ReadNBytes(int64_t bytes_to_read, tstring* result) override; absl::Status SkipNBytes(int64_t bytes_to_skip) override; int64_t Tell() const override; absl::Status Seek(int64_t position); absl::Status ReadLine(std::string* result); absl::Status ReadLine(tstring* result); std::string ReadLineAsString(); absl::Status SkipLine(); template <typename T> absl::Status ReadAll(T* result); absl::Status Reset() override; private: absl::Status FillBuffer(); template <typename StringType> absl::Status ReadLineHelper(StringType* result, bool include_eol); InputStreamInterface* input_stream_; size_t size_; tstring buf_; size_t pos_ = 0; size_t limit_ = 0; bool owns_input_stream_ = false; absl::Status file_status_ = absl::OkStatus(); BufferedInputStream(const BufferedInputStream&) = delete; void operator=(const BufferedInputStream&) = delete; }; #ifndef SWIG extern template Status BufferedInputStream::ReadAll<std::string>( std::string* result); extern template Status BufferedInputStream::ReadAll<tstring>(tstring* result); #endif } } #endif #include "tsl/lib/io/buffered_inputstream.h" #include "absl/status/status.h" #include "tsl/lib/io/random_inputstream.h" namespace tsl { namespace io { BufferedInputStream::BufferedInputStream(InputStreamInterface* input_stream, size_t buffer_bytes, bool owns_input_stream) : input_stream_(input_stream), size_(buffer_bytes), owns_input_stream_(owns_input_stream) { buf_.reserve(size_); } BufferedInputStream::BufferedInputStream(RandomAccessFile* file, size_t buffer_bytes) : BufferedInputStream(new RandomAccessInputStream(file), buffer_bytes, true) {} BufferedInputStream::~BufferedInputStream() { if (owns_input_stream_) { delete input_stream_; } } absl::Status BufferedInputStream::FillBuffer() { if (!file_status_.ok()) { pos_ = 0; limit_ = 0; return file_status_; } absl::Status s = input_stream_->ReadNBytes(size_, &buf_); pos_ = 0; limit_ = buf_.size(); if (!s.ok()) { file_status_ = s; } return s; } template <typename StringType> absl::Status BufferedInputStream::ReadLineHelper(StringType* result, bool include_eol) { result->clear(); absl::Status s; size_t start_pos = pos_; while (true) { if (pos_ == limit_) { result->append(buf_.data() + start_pos, pos_ - start_pos); s = FillBuffer(); if (limit_ == 0) { break; } start_pos = pos_; } char c = buf_[pos_]; if (c == '\n') { result->append(buf_.data() + start_pos, pos_ - start_pos); if (include_eol) { result->append(1, c); } pos_++; return absl::OkStatus(); } if (c == '\r') { result->append(buf_.data() + start_pos, pos_ - start_pos); start_pos = pos_ + 1; } pos_++; } if (absl::IsOutOfRange(s) && !result->empty()) { return absl::OkStatus(); } return s; } absl::Status BufferedInputStream::ReadNBytes(int64_t bytes_to_read, tstring* result) { if (bytes_to_read < 0) { return errors::InvalidArgument("Can't read a negative number of bytes: ", bytes_to_read); } result->clear(); if (pos_ == limit_ && !file_status_.ok() && bytes_to_read > 0) { return file_status_; } result->reserve(bytes_to_read); absl::Status s; while (result->size() < static_cast<size_t>(bytes_to_read)) { if (pos_ == limit_) { s = FillBuffer(); if (limit_ == 0) { DCHECK(!s.ok()); file_status_ = s; break; } } const int64_t bytes_to_copy = std::min<int64_t>(limit_ - pos_, bytes_to_read - result->size()); result->insert(result->size(), buf_, pos_, bytes_to_copy); pos_ += bytes_to_copy; } if (absl::IsOutOfRange(s) && (result->size() == static_cast<size_t>(bytes_to_read))) { return absl::OkStatus(); } return s; } absl::Status BufferedInputStream::SkipNBytes(int64_t bytes_to_skip) { if (bytes_to_skip < 0) { return errors::InvalidArgument("Can only skip forward, not ", bytes_to_skip); } if (pos_ + bytes_to_skip < limit_) { pos_ += bytes_to_skip; } else { absl::Status s = input_stream_->SkipNBytes(bytes_to_skip - (limit_ - pos_)); pos_ = 0; limit_ = 0; if (absl::IsOutOfRange(s)) { file_status_ = s; } return s; } return absl::OkStatus(); } int64_t BufferedInputStream::Tell() const { return input_stream_->Tell() - (limit_ - pos_); } absl::Status BufferedInputStream::Seek(int64_t position) { if (position < 0) { return errors::InvalidArgument("Seeking to a negative position: ", position); } const int64_t buf_lower_limit = input_stream_->Tell() - limit_; if (position < buf_lower_limit) { TF_RETURN_IF_ERROR(Reset()); return SkipNBytes(position); } if (position < Tell()) { pos_ -= Tell() - position; return absl::OkStatus(); } return SkipNBytes(position - Tell()); } template <typename T> absl::Status BufferedInputStream::ReadAll(T* result) { result->clear(); absl::Status status; while (status.ok()) { status = FillBuffer(); if (limit_ == 0) { break; } result->append(buf_); pos_ = limit_; } if (absl::IsOutOfRange(status)) { file_status_ = status; return absl::OkStatus(); } return status; } template Status BufferedInputStream::ReadAll<std::string>(std::string* result); template Status BufferedInputStream::ReadAll<tstring>(tstring* result); absl::Status BufferedInputStream::Reset() { TF_RETURN_IF_ERROR(input_stream_->Reset()); pos_ = 0; limit_ = 0; file_status_ = absl::OkStatus(); return absl::OkStatus(); } absl::Status BufferedInputStream::ReadLine(std::string* result) { return ReadLineHelper(result, false); } absl::Status BufferedInputStream::ReadLine(tstring* result) { return ReadLineHelper(result, false); } std::string BufferedInputStream::ReadLineAsString() { std::string result; ReadLineHelper(&result, true).IgnoreError(); return result; } absl::Status BufferedInputStream::SkipLine() { absl::Status s; bool skipped = false; while (true) { if (pos_ == limit_) { s = FillBuffer(); if (limit_ == 0) { break; } } char c = buf_[pos_++]; skipped = true; if (c == '\n') { return absl::OkStatus(); } } if (absl::IsOutOfRange(s) && skipped) { return absl::OkStatus(); } return s; } } }
#include "tsl/lib/io/buffered_inputstream.h" #include "tsl/lib/core/status_test_util.h" #include "tsl/lib/io/random_inputstream.h" #include "tsl/platform/env.h" #include "tsl/platform/test.h" #include "tsl/platform/test_benchmark.h" namespace tsl { namespace io { namespace { static std::vector<int> BufferSizes() { return {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 65536}; } class ReadOnceInputStream : public InputStreamInterface { public: ReadOnceInputStream() : start_(true) {} virtual absl::Status ReadNBytes(int64_t bytes_to_read, tstring* result) { if (bytes_to_read < 11) { return errors::InvalidArgument("Not reading all bytes: ", bytes_to_read); } if (start_) { *result = "0123456789"; start_ = false; return errors::OutOfRange("Out of range."); } return errors::InvalidArgument( "Redudant call to ReadNBytes after an OutOfRange error."); } int64_t Tell() const override { return start_ ? 0 : 10; } absl::Status Reset() override { start_ = true; return absl::OkStatus(); } private: bool start_; }; TEST(BufferedInputStream, ReadLine_Empty) { Env* env = Env::Default(); string fname; ASSERT_TRUE(env->LocalTempFilename(&fname)); TF_ASSERT_OK(WriteStringToFile(env, fname, "")); std::unique_ptr<RandomAccessFile> file; TF_ASSERT_OK(env->NewRandomAccessFile(fname, &file)); for (auto buf_size : BufferSizes()) { std::unique_ptr<RandomAccessInputStream> input_stream( new RandomAccessInputStream(file.get())); BufferedInputStream in(input_stream.get(), buf_size); string line; EXPECT_TRUE(errors::IsOutOfRange(in.ReadLine(&line))); } } TEST(BufferedInputStream, ReadLine1) { Env* env = Env::Default(); string fname; ASSERT_TRUE(env->LocalTempFilename(&fname)); TF_ASSERT_OK( WriteStringToFile(env, fname, "line one\nline two\nline three\n")); std::unique_ptr<RandomAccessFile> file; TF_ASSERT_OK(env->NewRandomAccessFile(fname, &file)); for (auto buf_size : BufferSizes()) { std::unique_ptr<RandomAccessInputStream> input_stream( new RandomAccessInputStream(file.get())); BufferedInputStream in(input_stream.get(), buf_size); string line; TF_ASSERT_OK(in.ReadLine(&line)); EXPECT_EQ(line, "line one"); TF_ASSERT_OK(in.ReadLine(&line)); EXPECT_EQ(line, "line two"); TF_ASSERT_OK(in.ReadLine(&line)); EXPECT_EQ(line, "line three"); EXPECT_TRUE(errors::IsOutOfRange(in.ReadLine(&line))); EXPECT_TRUE(errors::IsOutOfRange(in.ReadLine(&line))); } } TEST(BufferedInputStream, ReadLine_NoTrailingNewLine) { Env* env = Env::Default(); string fname; ASSERT_TRUE(env->LocalTempFilename(&fname)); TF_ASSERT_OK(WriteStringToFile(env, fname, "line one\nline two\nline three")); std::unique_ptr<RandomAccessFile> file; TF_ASSERT_OK(env->NewRandomAccessFile(fname, &file)); for (auto buf_size : BufferSizes()) { std::unique_ptr<RandomAccessInputStream> input_stream( new RandomAccessInputStream(file.get())); BufferedInputStream in(input_stream.get(), buf_size); string line; TF_ASSERT_OK(in.ReadLine(&line)); EXPECT_EQ(line, "line one"); TF_ASSERT_OK(in.ReadLine(&line)); EXPECT_EQ(line, "line two"); TF_ASSERT_OK(in.ReadLine(&line)); EXPECT_EQ(line, "line three"); EXPECT_TRUE(errors::IsOutOfRange(in.ReadLine(&line))); EXPECT_TRUE(errors::IsOutOfRange(in.ReadLine(&line))); } } TEST(BufferedInputStream, ReadLine_EmptyLines) { Env* env = Env::Default(); string fname; ASSERT_TRUE(env->LocalTempFilename(&fname)); TF_ASSERT_OK( WriteStringToFile(env, fname, "line one\n\n\nline two\nline three")); std::unique_ptr<RandomAccessFile> file; TF_ASSERT_OK(env->NewRandomAccessFile(fname, &file)); for (auto buf_size : BufferSizes()) { std::unique_ptr<RandomAccessInputStream> input_stream( new RandomAccessInputStream(file.get())); BufferedInputStream in(input_stream.get(), buf_size); string line; TF_ASSERT_OK(in.ReadLine(&line)); EXPECT_EQ(line, "line one"); TF_ASSERT_OK(in.ReadLine(&line)); EXPECT_EQ(line, ""); TF_ASSERT_OK(in.ReadLine(&line)); EXPECT_EQ(line, ""); TF_ASSERT_OK(in.ReadLine(&line)); EXPECT_EQ(line, "line two"); TF_ASSERT_OK(in.ReadLine(&line)); EXPECT_EQ(line, "line three"); EXPECT_TRUE(errors::IsOutOfRange(in.ReadLine(&line))); EXPECT_TRUE(errors::IsOutOfRange(in.ReadLine(&line))); } } TEST(BufferedInputStream, ReadLine_CRLF) { Env* env = Env::Default(); string fname; ASSERT_TRUE(env->LocalTempFilename(&fname)); TF_ASSERT_OK(WriteStringToFile(env, fname, "line one\r\n\r\n\r\nline two\r\nline three")); std::unique_ptr<RandomAccessFile> file; TF_ASSERT_OK(env->NewRandomAccessFile(fname, &file)); for (auto buf_size : BufferSizes()) { std::unique_ptr<RandomAccessInputStream> input_stream( new RandomAccessInputStream(file.get())); BufferedInputStream in(input_stream.get(), buf_size); string line; TF_ASSERT_OK(in.ReadLine(&line)); EXPECT_EQ(line, "line one"); TF_ASSERT_OK(in.ReadLine(&line)); EXPECT_EQ(line, ""); TF_ASSERT_OK(in.ReadLine(&line)); EXPECT_EQ(line, ""); TF_ASSERT_OK(in.ReadLine(&line)); EXPECT_EQ(line, "line two"); TF_ASSERT_OK(in.ReadLine(&line)); EXPECT_EQ(line, "line three"); EXPECT_TRUE(errors::IsOutOfRange(in.ReadLine(&line))); EXPECT_TRUE(errors::IsOutOfRange(in.ReadLine(&line))); } } TEST(BufferedInputStream, SkipLine1) { Env* env = Env::Default(); string fname; ASSERT_TRUE(env->LocalTempFilename(&fname)); TF_ASSERT_OK( WriteStringToFile(env, fname, "line one\nline two\nline three\n")); std::unique_ptr<RandomAccessFile> file; TF_ASSERT_OK(env->NewRandomAccessFile(fname, &file)); for (auto buf_size : BufferSizes()) { std::unique_ptr<RandomAccessInputStream> input_stream( new RandomAccessInputStream(file.get())); BufferedInputStream in(input_stream.get(), buf_size); string line; TF_ASSERT_OK(in.SkipLine()); TF_ASSERT_OK(in.ReadLine(&line)); EXPECT_EQ(line, "line two"); TF_ASSERT_OK(in.SkipLine()); EXPECT_TRUE(errors::IsOutOfRange(in.SkipLine())); EXPECT_TRUE(errors::IsOutOfRange(in.SkipLine())); } } TEST(BufferedInputStream, SkipLine_NoTrailingNewLine) { Env* env = Env::Default(); string fname; ASSERT_TRUE(env->LocalTempFilename(&fname)); TF_ASSERT_OK(WriteStringToFile(env, fname, "line one\nline two\nline three")); std::unique_ptr<RandomAccessFile> file; TF_ASSERT_OK(env->NewRandomAccessFile(fname, &file)); for (auto buf_size : BufferSizes()) { std::unique_ptr<RandomAccessInputStream> input_stream( new RandomAccessInputStream(file.get())); BufferedInputStream in(input_stream.get(), buf_size); string line; TF_ASSERT_OK(in.SkipLine()); TF_ASSERT_OK(in.ReadLine(&line)); EXPECT_EQ(line, "line two"); TF_ASSERT_OK(in.SkipLine()); EXPECT_TRUE(errors::IsOutOfRange(in.SkipLine())); EXPECT_TRUE(errors::IsOutOfRange(in.SkipLine())); } } TEST(BufferedInputStream, SkipLine_EmptyLines) { Env* env = Env::Default(); string fname; ASSERT_TRUE(env->LocalTempFilename(&fname)); TF_ASSERT_OK(WriteStringToFile(env, fname, "line one\n\n\nline two")); std::unique_ptr<RandomAccessFile> file; TF_ASSERT_OK(env->NewRandomAccessFile(fname, &file)); for (auto buf_size : BufferSizes()) { std::unique_ptr<RandomAccessInputStream> input_stream( new RandomAccessInputStream(file.get())); BufferedInputStream in(input_stream.get(), buf_size); string line; TF_ASSERT_OK(in.SkipLine()); TF_ASSERT_OK(in.ReadLine(&line)); EXPECT_EQ(line, ""); TF_ASSERT_OK(in.SkipLine()); TF_ASSERT_OK(in.ReadLine(&line)); EXPECT_EQ(line, "line two"); } } TEST(BufferedInputStream, ReadNBytes) { Env* env = Env::Default(); string fname; ASSERT_TRUE(env->LocalTempFilename(&fname)); TF_ASSERT_OK(WriteStringToFile(env, fname, "0123456789")); std::unique_ptr<RandomAccessFile> file; TF_ASSERT_OK(env->NewRandomAccessFile(fname, &file)); for (auto buf_size : BufferSizes()) { std::unique_ptr<RandomAccessInputStream> input_stream( new RandomAccessInputStream(file.get())); tstring read; BufferedInputStream in(input_stream.get(), buf_size); EXPECT_EQ(0, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(3, &read)); EXPECT_EQ(read, "012"); EXPECT_EQ(3, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(0, &read)); EXPECT_EQ(read, ""); EXPECT_EQ(3, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(4, &read)); EXPECT_EQ(read, "3456"); EXPECT_EQ(7, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(0, &read)); EXPECT_EQ(read, ""); EXPECT_EQ(7, in.Tell()); EXPECT_TRUE(errors::IsOutOfRange(in.ReadNBytes(5, &read))); EXPECT_EQ(read, "789"); EXPECT_EQ(10, in.Tell()); EXPECT_TRUE(errors::IsOutOfRange(in.ReadNBytes(5, &read))); EXPECT_EQ(read, ""); EXPECT_EQ(10, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(0, &read)); EXPECT_EQ(read, ""); EXPECT_EQ(10, in.Tell()); } } TEST(BufferedInputStream, OutOfRangeCache) { for (auto buf_size : BufferSizes()) { if (buf_size < 11) { continue; } ReadOnceInputStream input_stream; tstring read; BufferedInputStream in(&input_stream, buf_size); EXPECT_EQ(0, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(3, &read)); EXPECT_EQ(read, "012"); EXPECT_EQ(3, in.Tell()); TF_ASSERT_OK((in.ReadNBytes(7, &read))); EXPECT_EQ(read, "3456789"); EXPECT_EQ(10, in.Tell()); absl::Status s = in.ReadNBytes(5, &read); EXPECT_EQ(error::OUT_OF_RANGE, s.code()) << s; EXPECT_EQ(read, ""); TF_ASSERT_OK(in.ReadNBytes(0, &read)); EXPECT_EQ(read, ""); } } TEST(BufferedInputStream, SkipNBytes) { Env* env = Env::Default(); string fname; ASSERT_TRUE(env->LocalTempFilename(&fname)); TF_ASSERT_OK(WriteStringToFile(env, fname, "0123456789")); std::unique_ptr<RandomAccessFile> file; TF_ASSERT_OK(env->NewRandomAccessFile(fname, &file)); for (auto buf_size : BufferSizes()) { std::unique_ptr<RandomAccessInputStream> input_stream( new RandomAccessInputStream(file.get())); tstring read; BufferedInputStream in(input_stream.get(), buf_size); EXPECT_EQ(0, in.Tell()); TF_ASSERT_OK(in.SkipNBytes(3)); EXPECT_EQ(3, in.Tell()); TF_ASSERT_OK(in.SkipNBytes(0)); EXPECT_EQ(3, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(2, &read)); EXPECT_EQ(read, "34"); EXPECT_EQ(5, in.Tell()); TF_ASSERT_OK(in.SkipNBytes(0)); EXPECT_EQ(5, in.Tell()); TF_ASSERT_OK(in.SkipNBytes(2)); EXPECT_EQ(7, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(1, &read)); EXPECT_EQ(read, "7"); EXPECT_EQ(8, in.Tell()); EXPECT_TRUE(errors::IsOutOfRange(in.SkipNBytes(5))); EXPECT_EQ(10, in.Tell()); EXPECT_TRUE(errors::IsOutOfRange(in.SkipNBytes(5))); EXPECT_EQ(10, in.Tell()); EXPECT_TRUE(errors::IsOutOfRange(in.ReadNBytes(5, &read))); EXPECT_EQ(read, ""); EXPECT_EQ(10, in.Tell()); } } TEST(BufferedInputStream, ReadNBytesRandomAccessFile) { Env* env = Env::Default(); string fname; ASSERT_TRUE(env->LocalTempFilename(&fname)); TF_ASSERT_OK(WriteStringToFile(env, fname, "0123456789")); std::unique_ptr<RandomAccessFile> file; TF_ASSERT_OK(env->NewRandomAccessFile(fname, &file)); for (auto buf_size : BufferSizes()) { tstring read; BufferedInputStream in(file.get(), buf_size); EXPECT_EQ(0, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(3, &read)); EXPECT_EQ(read, "012"); EXPECT_EQ(3, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(0, &read)); EXPECT_EQ(read, ""); EXPECT_EQ(3, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(4, &read)); EXPECT_EQ(read, "3456"); EXPECT_EQ(7, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(0, &read)); EXPECT_EQ(read, ""); EXPECT_EQ(7, in.Tell()); EXPECT_TRUE(errors::IsOutOfRange(in.ReadNBytes(5, &read))); EXPECT_EQ(read, "789"); EXPECT_EQ(10, in.Tell()); EXPECT_TRUE(errors::IsOutOfRange(in.ReadNBytes(5, &read))); EXPECT_EQ(read, ""); EXPECT_EQ(10, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(0, &read)); EXPECT_EQ(read, ""); EXPECT_EQ(10, in.Tell()); } } TEST(BufferedInputStream, SkipNBytesRandomAccessFile) { Env* env = Env::Default(); string fname; ASSERT_TRUE(env->LocalTempFilename(&fname)); TF_ASSERT_OK(WriteStringToFile(env, fname, "0123456789")); std::unique_ptr<RandomAccessFile> file; TF_ASSERT_OK(env->NewRandomAccessFile(fname, &file)); for (auto buf_size : BufferSizes()) { tstring read; BufferedInputStream in(file.get(), buf_size); EXPECT_EQ(0, in.Tell()); TF_ASSERT_OK(in.SkipNBytes(3)); EXPECT_EQ(3, in.Tell()); TF_ASSERT_OK(in.SkipNBytes(0)); EXPECT_EQ(3, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(2, &read)); EXPECT_EQ(read, "34"); EXPECT_EQ(5, in.Tell()); TF_ASSERT_OK(in.SkipNBytes(0)); EXPECT_EQ(5, in.Tell()); TF_ASSERT_OK(in.SkipNBytes(2)); EXPECT_EQ(7, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(1, &read)); EXPECT_EQ(read, "7"); EXPECT_EQ(8, in.Tell()); EXPECT_TRUE(errors::IsOutOfRange(in.SkipNBytes(5))); EXPECT_EQ(10, in.Tell()); EXPECT_TRUE(errors::IsOutOfRange(in.SkipNBytes(5))); EXPECT_EQ(10, in.Tell()); EXPECT_TRUE(errors::IsOutOfRange(in.ReadNBytes(5, &read))); EXPECT_EQ(read, ""); EXPECT_EQ(10, in.Tell()); } } TEST(BufferedInputStream, Seek) { Env* env = Env::Default(); string fname; ASSERT_TRUE(env->LocalTempFilename(&fname)); TF_ASSERT_OK(WriteStringToFile(env, fname, "0123456789")); std::unique_ptr<RandomAccessFile> file; TF_ASSERT_OK(env->NewRandomAccessFile(fname, &file)); for (auto buf_size : BufferSizes()) { std::unique_ptr<RandomAccessInputStream> input_stream( new RandomAccessInputStream(file.get())); tstring read; BufferedInputStream in(input_stream.get(), buf_size); TF_ASSERT_OK(in.Seek(3)); EXPECT_EQ(3, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(4, &read)); EXPECT_EQ(read, "3456"); EXPECT_EQ(7, in.Tell()); TF_ASSERT_OK(in.Seek(1)); TF_ASSERT_OK(in.ReadNBytes(4, &read)); EXPECT_EQ(read, "1234"); EXPECT_EQ(5, in.Tell()); } } TEST(BufferedInputStream, Seek_NotReset) { Env* env = Env::Default(); string fname; ASSERT_TRUE(env->LocalTempFilename(&fname)); TF_ASSERT_OK(WriteStringToFile(env, fname, "0123456789")); std::unique_ptr<RandomAccessFile> file; TF_ASSERT_OK(env->NewRandomAccessFile(fname, &file)); std::unique_ptr<RandomAccessInputStream> input_stream( new RandomAccessInputStream(file.get())); tstring read; BufferedInputStream in(input_stream.get(), 3); TF_ASSERT_OK(in.ReadNBytes(4, &read)); int before_tell = input_stream.get()->Tell(); EXPECT_EQ(before_tell, 6); TF_ASSERT_OK(in.Seek(3)); int after_tell = input_stream.get()->Tell(); EXPECT_EQ(before_tell, after_tell); } TEST(BufferedInputStream, ReadAll_Empty) { Env* env = Env::Default(); string fname; ASSERT_TRUE(env->LocalTempFilename(&fname)); const string expected = ""; TF_ASSERT_OK(WriteStringToFile(env, fname, expected)); std::unique_ptr<RandomAccessFile> file; TF_ASSERT_OK(env->NewRandomAccessFile(fname, &file)); for (auto buf_size : BufferSizes()) { RandomAccessInputStream input_stream(file.get()); BufferedInputStream in(&input_stream, buf_size); string contents; TF_ASSERT_OK(in.ReadAll(&contents)); EXPECT_EQ(expected, contents); } } TEST(BufferedInputStream, ReadAll_Text) { Env* env = Env::Default(); string fname; ASSERT_TRUE(env->LocalTempFilename(&fname)); const string expected = "line one\nline two\nline three"; TF_ASSERT_OK(WriteStringToFile(env, fname, expected)); std::unique_ptr<RandomAccessFile> file; TF_ASSERT_OK(env->NewRandomAccessFile(fname, &file)); for (auto buf_size : BufferSizes()) { RandomAccessInputStream input_stream(file.get()); BufferedInputStream in(&input_stream, buf_size); string contents; TF_ASSERT_OK(in.ReadAll(&contents)); EXPECT_EQ(expected, contents); } } void BM_BufferedReaderSmallReads(::testing::benchmark::State& state) { const int buff_size = state.range(0); const int file_size = state.range(1); Env* env = Env::Default(); string fname; ASSERT_TRUE(env->LocalTempFilename(&fname)); const string file_elem = "0123456789"; std::unique_ptr<WritableFile> write_file; TF_ASSERT_OK(env->NewWritableFile(fname, &write_file)); for (int i = 0; i < file_size; ++i) { TF_ASSERT_OK(write_file->Append(file_elem)); } TF_ASSERT_OK(write_file->Close()); std::unique_ptr<RandomAccessFile> file; TF_ASSERT_OK(env->NewRandomAccessFile(fname, &file)); tstring result; int itr = 0; for (auto s : state) { BufferedInputStream in(file.get(), buff_size); for (int64_t i = 0; i < 10 * file_size; ++i) { TF_ASSERT_OK(in.ReadNBytes(1, &result)) << "i: " << i << " itr: " << itr << " buff_size: " << buff_size << " file size: " << file_size; } ++itr; } } BENCHMARK(BM_BufferedReaderSmallReads) ->ArgPair(1, 5) ->ArgPair(1, 1024) ->ArgPair(10, 5) ->ArgPair(10, 1024) ->ArgPair(1024, 1024) ->ArgPair(1024 * 1024, 1024) ->ArgPair(1024 * 1024, 1024 * 1024) ->ArgPair(256 * 1024 * 1024, 1024); } } }
2,650
cpp
google/tsl
inputbuffer
tsl/lib/io/inputbuffer.cc
tsl/lib/io/inputbuffer_test.cc
#ifndef TENSORFLOW_TSL_LIB_IO_INPUTBUFFER_H_ #define TENSORFLOW_TSL_LIB_IO_INPUTBUFFER_H_ #include <string> #include "tsl/platform/coding.h" #include "tsl/platform/env.h" #include "tsl/platform/macros.h" #include "tsl/platform/status.h" #include "tsl/platform/types.h" namespace tsl { namespace io { class InputBuffer { public: InputBuffer(RandomAccessFile* file, size_t buffer_bytes); ~InputBuffer(); template <typename T> absl::Status ReadLine(T* result); absl::Status ReadNBytes(int64_t bytes_to_read, std::string* result); absl::Status ReadNBytes(int64_t bytes_to_read, char* result, size_t* bytes_read); absl::Status ReadVarint32(uint32* result); absl::Status ReadVarint64(uint64* result); absl::Status SkipNBytes(int64_t bytes_to_skip); absl::Status Seek(int64_t position); absl::Status Hint(int64_t bytes_to_read); int64_t Tell() const { return file_pos_ - (limit_ - pos_); } RandomAccessFile* file() const { return file_; } private: absl::Status FillBuffer(); absl::Status ReadVarint32Fallback(uint32* result); absl::Status ReadVarint64Fallback(uint64* result); template <typename T> absl::Status ReadVarintFallback(T* result, int max_bytes); RandomAccessFile* file_; int64_t file_pos_; size_t size_; char* buf_; char* pos_; char* limit_; InputBuffer(const InputBuffer&) = delete; void operator=(const InputBuffer&) = delete; }; extern template Status InputBuffer::ReadLine<std::string>(std::string* result); extern template Status InputBuffer::ReadLine<tstring>(tstring* result); inline absl::Status InputBuffer::ReadVarint32(uint32* result) { if (pos_ + core::kMaxVarint32Bytes <= limit_) { const char* offset = core::GetVarint32Ptr(pos_, limit_, result); if (offset == nullptr) return errors::OutOfRange("Parsed past limit."); pos_ = const_cast<char*>(offset); return absl::OkStatus(); } else { return ReadVarint32Fallback(result); } } inline absl::Status InputBuffer::ReadVarint64(uint64* result) { if (pos_ + core::kMaxVarint64Bytes <= limit_) { const char* offset = core::GetVarint64Ptr(pos_, limit_, result); if (offset == nullptr) return errors::OutOfRange("Parsed past limit."); pos_ = const_cast<char*>(offset); return absl::OkStatus(); } else { return ReadVarint64Fallback(result); } } } } #endif #include "tsl/lib/io/inputbuffer.h" #include <algorithm> #include "tsl/platform/errors.h" #include "tsl/platform/logging.h" namespace tsl { namespace io { InputBuffer::InputBuffer(RandomAccessFile* file, size_t buffer_bytes) : file_(file), file_pos_(0), size_(buffer_bytes), buf_(new char[size_]), pos_(buf_), limit_(buf_) {} InputBuffer::~InputBuffer() { delete[] buf_; } absl::Status InputBuffer::FillBuffer() { StringPiece data; absl::Status s = file_->Read(file_pos_, size_, &data, buf_); if (data.data() != buf_) { memmove(buf_, data.data(), data.size()); } pos_ = buf_; limit_ = pos_ + data.size(); file_pos_ += data.size(); return s; } template <typename T> absl::Status InputBuffer::ReadLine(T* result) { result->clear(); absl::Status s; do { size_t buf_remain = limit_ - pos_; char* newline = static_cast<char*>(memchr(pos_, '\n', buf_remain)); if (newline != nullptr) { size_t result_len = newline - pos_; result->append(pos_, result_len); pos_ = newline + 1; if (!result->empty() && result->back() == '\r') { result->resize(result->size() - 1); } return absl::OkStatus(); } if (buf_remain > 0) result->append(pos_, buf_remain); s = FillBuffer(); DCHECK_EQ(pos_, buf_); } while (limit_ != buf_); if (!result->empty() && result->back() == '\r') { result->resize(result->size() - 1); } if (errors::IsOutOfRange(s) && !result->empty()) { return absl::OkStatus(); } return s; } template Status InputBuffer::ReadLine<std::string>(std::string* result); template Status InputBuffer::ReadLine<tstring>(tstring* result); absl::Status InputBuffer::ReadNBytes(int64_t bytes_to_read, std::string* result) { result->clear(); if (bytes_to_read < 0) { return errors::InvalidArgument("Can't read a negative number of bytes: ", bytes_to_read); } result->resize(bytes_to_read); size_t bytes_read = 0; absl::Status status = ReadNBytes(bytes_to_read, &(*result)[0], &bytes_read); if (bytes_read < bytes_to_read) result->resize(bytes_read); return status; } absl::Status InputBuffer::ReadNBytes(int64_t bytes_to_read, char* result, size_t* bytes_read) { if (bytes_to_read < 0) { return errors::InvalidArgument("Can't read a negative number of bytes: ", bytes_to_read); } absl::Status status; *bytes_read = 0; while (*bytes_read < static_cast<size_t>(bytes_to_read)) { if (pos_ == limit_) { status = FillBuffer(); if (limit_ == buf_) { break; } } const int64_t bytes_to_copy = std::min<int64_t>(limit_ - pos_, bytes_to_read - *bytes_read); memcpy(result + *bytes_read, pos_, bytes_to_copy); pos_ += bytes_to_copy; *bytes_read += bytes_to_copy; } if (errors::IsOutOfRange(status) && (*bytes_read == static_cast<size_t>(bytes_to_read))) { return absl::OkStatus(); } return status; } absl::Status InputBuffer::ReadVarint32Fallback(uint32* result) { absl::Status s = ReadVarintFallback(result, core::kMaxVarint32Bytes); if (errors::IsDataLoss(s)) { return errors::DataLoss("Stored data is too large to be a varint32."); } return s; } absl::Status InputBuffer::ReadVarint64Fallback(uint64* result) { absl::Status s = ReadVarintFallback(result, core::kMaxVarint64Bytes); if (errors::IsDataLoss(s)) { return errors::DataLoss("Stored data is too large to be a varint64."); } return s; } template <typename T> absl::Status InputBuffer::ReadVarintFallback(T* result, int max_bytes) { uint8 scratch = 0; auto* p = reinterpret_cast<char*>(&scratch); size_t unused_bytes_read = 0; *result = 0; for (int index = 0; index < max_bytes; index++) { int shift = 7 * index; TF_RETURN_IF_ERROR(ReadNBytes(1, p, &unused_bytes_read)); *result |= (static_cast<T>(scratch) & 127) << shift; if (!(scratch & 128)) return absl::OkStatus(); } return errors::DataLoss("Stored data longer than ", max_bytes, " bytes."); } absl::Status InputBuffer::SkipNBytes(int64_t bytes_to_skip) { if (bytes_to_skip < 0) { return errors::InvalidArgument("Can only skip forward, not ", bytes_to_skip); } int64_t bytes_skipped = 0; absl::Status s; while (bytes_skipped < bytes_to_skip) { if (pos_ == limit_) { s = FillBuffer(); if (limit_ == buf_) { break; } } const int64_t bytes_to_advance = std::min<int64_t>(limit_ - pos_, bytes_to_skip - bytes_skipped); bytes_skipped += bytes_to_advance; pos_ += bytes_to_advance; } if (errors::IsOutOfRange(s) && bytes_skipped == bytes_to_skip) { return absl::OkStatus(); } return s; } absl::Status InputBuffer::Seek(int64_t position) { if (position < 0) { return errors::InvalidArgument("Seeking to a negative position: ", position); } const int64_t bufpos = file_pos_ - static_cast<int64_t>(limit_ - buf_); if (position >= bufpos && position < file_pos_) { pos_ = buf_ + (position - bufpos); DCHECK(pos_ >= buf_ && pos_ < limit_); } else { pos_ = limit_ = buf_; file_pos_ = position; } return absl::OkStatus(); } absl::Status InputBuffer::Hint(int64_t bytes_to_read) { if (bytes_to_read < 0) { return errors::InvalidArgument("Can't read a negative number of bytes: ", bytes_to_read); } if (bytes_to_read > size_) { return absl::OkStatus(); } const int64_t bytes_remain_in_buf = static_cast<int64_t>(limit_ - pos_); if (bytes_to_read <= bytes_remain_in_buf) { return absl::OkStatus(); } memmove(buf_, pos_, bytes_remain_in_buf); pos_ = buf_; limit_ = buf_ + bytes_remain_in_buf; bytes_to_read -= bytes_remain_in_buf; StringPiece data; absl::Status s = file_->Read(file_pos_, bytes_to_read, &data, limit_); if (data.data() != limit_) { memmove(limit_, data.data(), data.size()); } limit_ += data.size(); file_pos_ += data.size(); if (errors::IsOutOfRange(s) && data.size() == bytes_to_read) { return absl::OkStatus(); } else { return s; } } } }
#include "tsl/lib/io/inputbuffer.h" #include <vector> #include "tsl/lib/core/status_test_util.h" #include "tsl/platform/coding.h" #include "tsl/platform/env.h" #include "tsl/platform/errors.h" #include "tsl/platform/logging.h" #include "tsl/platform/status.h" #include "tsl/platform/str_util.h" #include "tsl/platform/strcat.h" #include "tsl/platform/test.h" namespace tsl { namespace { static std::vector<int> BufferSizes() { return {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 65536}; } TEST(InputBuffer, ReadLine_Empty) { Env* env = Env::Default(); string fname; ASSERT_TRUE(env->LocalTempFilename(&fname)); TF_ASSERT_OK(WriteStringToFile(env, fname, "")); for (auto buf_size : BufferSizes()) { std::unique_ptr<RandomAccessFile> file; TF_CHECK_OK(env->NewRandomAccessFile(fname, &file)); string line; io::InputBuffer in(file.get(), buf_size); EXPECT_TRUE(errors::IsOutOfRange(in.ReadLine(&line))); } } TEST(InputBuffer, ReadLine1) { Env* env = Env::Default(); string fname; ASSERT_TRUE(env->LocalTempFilename(&fname)); TF_CHECK_OK( WriteStringToFile(env, fname, "line one\nline two\nline three\n")); for (auto buf_size : BufferSizes()) { std::unique_ptr<RandomAccessFile> file; TF_CHECK_OK(env->NewRandomAccessFile(fname, &file)); string line; io::InputBuffer in(file.get(), buf_size); TF_CHECK_OK(in.ReadLine(&line)); EXPECT_EQ(line, "line one"); TF_CHECK_OK(in.ReadLine(&line)); EXPECT_EQ(line, "line two"); TF_CHECK_OK(in.ReadLine(&line)); EXPECT_EQ(line, "line three"); EXPECT_TRUE(errors::IsOutOfRange(in.ReadLine(&line))); EXPECT_TRUE(errors::IsOutOfRange(in.ReadLine(&line))); } } TEST(InputBuffer, ReadLine_NoTrailingNewLine) { Env* env = Env::Default(); string fname; ASSERT_TRUE(env->LocalTempFilename(&fname)); TF_ASSERT_OK(WriteStringToFile(env, fname, "line one\nline two\nline three")); for (auto buf_size : BufferSizes()) { std::unique_ptr<RandomAccessFile> file; TF_CHECK_OK(env->NewRandomAccessFile(fname, &file)); string line; io::InputBuffer in(file.get(), buf_size); TF_CHECK_OK(in.ReadLine(&line)); EXPECT_EQ(line, "line one"); TF_CHECK_OK(in.ReadLine(&line)); EXPECT_EQ(line, "line two"); TF_CHECK_OK(in.ReadLine(&line)); EXPECT_EQ(line, "line three"); EXPECT_TRUE(errors::IsOutOfRange(in.ReadLine(&line))); EXPECT_TRUE(errors::IsOutOfRange(in.ReadLine(&line))); } } TEST(InputBuffer, ReadLine_EmptyLines) { Env* env = Env::Default(); string fname; ASSERT_TRUE(env->LocalTempFilename(&fname)); TF_CHECK_OK( WriteStringToFile(env, fname, "line one\n\n\nline two\nline three")); for (auto buf_size : BufferSizes()) { std::unique_ptr<RandomAccessFile> file; TF_CHECK_OK(env->NewRandomAccessFile(fname, &file)); string line; io::InputBuffer in(file.get(), buf_size); TF_CHECK_OK(in.ReadLine(&line)); EXPECT_EQ(line, "line one"); TF_CHECK_OK(in.ReadLine(&line)); EXPECT_EQ(line, ""); TF_CHECK_OK(in.ReadLine(&line)); EXPECT_EQ(line, ""); TF_CHECK_OK(in.ReadLine(&line)); EXPECT_EQ(line, "line two"); TF_CHECK_OK(in.ReadLine(&line)); EXPECT_EQ(line, "line three"); EXPECT_TRUE(errors::IsOutOfRange(in.ReadLine(&line))); EXPECT_TRUE(errors::IsOutOfRange(in.ReadLine(&line))); } } TEST(InputBuffer, ReadLine_CRLF) { Env* env = Env::Default(); string fname; ASSERT_TRUE(env->LocalTempFilename(&fname)); TF_ASSERT_OK(WriteStringToFile(env, fname, "line one\r\n\r\n\r\nline two\r\nline three")); for (auto buf_size : BufferSizes()) { std::unique_ptr<RandomAccessFile> file; TF_CHECK_OK(env->NewRandomAccessFile(fname, &file)); string line; io::InputBuffer in(file.get(), buf_size); TF_CHECK_OK(in.ReadLine(&line)); EXPECT_EQ(line, "line one"); TF_CHECK_OK(in.ReadLine(&line)); EXPECT_EQ(line, ""); TF_CHECK_OK(in.ReadLine(&line)); EXPECT_EQ(line, ""); TF_CHECK_OK(in.ReadLine(&line)); EXPECT_EQ(line, "line two"); TF_CHECK_OK(in.ReadLine(&line)); EXPECT_EQ(line, "line three"); EXPECT_TRUE(errors::IsOutOfRange(in.ReadLine(&line))); EXPECT_TRUE(errors::IsOutOfRange(in.ReadLine(&line))); } } TEST(InputBuffer, ReadNBytes) { Env* env = Env::Default(); string fname; ASSERT_TRUE(env->LocalTempFilename(&fname)); TF_ASSERT_OK(WriteStringToFile(env, fname, "0123456789")); for (auto buf_size : BufferSizes()) { std::unique_ptr<RandomAccessFile> file; TF_CHECK_OK(env->NewRandomAccessFile(fname, &file)); string read; io::InputBuffer in(file.get(), buf_size); EXPECT_EQ(0, in.Tell()); TF_CHECK_OK(in.ReadNBytes(3, &read)); EXPECT_EQ(read, "012"); EXPECT_EQ(3, in.Tell()); TF_CHECK_OK(in.ReadNBytes(0, &read)); EXPECT_EQ(read, ""); EXPECT_EQ(3, in.Tell()); TF_CHECK_OK(in.ReadNBytes(4, &read)); EXPECT_EQ(read, "3456"); EXPECT_EQ(7, in.Tell()); TF_CHECK_OK(in.ReadNBytes(0, &read)); EXPECT_EQ(read, ""); EXPECT_EQ(7, in.Tell()); EXPECT_TRUE(errors::IsOutOfRange(in.ReadNBytes(5, &read))); EXPECT_EQ(read, "789"); EXPECT_EQ(10, in.Tell()); EXPECT_TRUE(errors::IsOutOfRange(in.ReadNBytes(5, &read))); EXPECT_EQ(read, ""); EXPECT_EQ(10, in.Tell()); TF_CHECK_OK(in.ReadNBytes(0, &read)); EXPECT_EQ(read, ""); EXPECT_EQ(10, in.Tell()); } size_t bytes_read; for (auto buf_size : BufferSizes()) { std::unique_ptr<RandomAccessFile> file; TF_CHECK_OK(env->NewRandomAccessFile(fname, &file)); char read[5]; io::InputBuffer in(file.get(), buf_size); EXPECT_EQ(0, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(3, read, &bytes_read)); EXPECT_EQ(StringPiece(read, 3), "012"); EXPECT_EQ(3, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(0, read, &bytes_read)); EXPECT_EQ(StringPiece(read, 3), "012"); EXPECT_EQ(3, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(4, read, &bytes_read)); EXPECT_EQ(StringPiece(read, 4), "3456"); EXPECT_EQ(7, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(0, read, &bytes_read)); EXPECT_EQ(StringPiece(read, 4), "3456"); EXPECT_EQ(7, in.Tell()); EXPECT_TRUE(errors::IsOutOfRange(in.ReadNBytes(5, read, &bytes_read))); EXPECT_EQ(StringPiece(read, 3), "789"); EXPECT_EQ(10, in.Tell()); EXPECT_TRUE(errors::IsOutOfRange(in.ReadNBytes(5, read, &bytes_read))); EXPECT_EQ(StringPiece(read, 3), "789"); EXPECT_EQ(10, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(0, read, &bytes_read)); EXPECT_EQ(StringPiece(read, 3), "789"); EXPECT_EQ(10, in.Tell()); } } TEST(InputBuffer, SkipNBytes) { Env* env = Env::Default(); string fname; ASSERT_TRUE(env->LocalTempFilename(&fname)); TF_ASSERT_OK(WriteStringToFile(env, fname, "0123456789")); for (auto buf_size : BufferSizes()) { std::unique_ptr<RandomAccessFile> file; TF_CHECK_OK(env->NewRandomAccessFile(fname, &file)); string read; io::InputBuffer in(file.get(), buf_size); EXPECT_EQ(0, in.Tell()); TF_CHECK_OK(in.SkipNBytes(3)); EXPECT_EQ(3, in.Tell()); TF_CHECK_OK(in.SkipNBytes(0)); EXPECT_EQ(3, in.Tell()); TF_CHECK_OK(in.ReadNBytes(2, &read)); EXPECT_EQ(read, "34"); EXPECT_EQ(5, in.Tell()); TF_CHECK_OK(in.SkipNBytes(0)); EXPECT_EQ(5, in.Tell()); TF_CHECK_OK(in.SkipNBytes(2)); EXPECT_EQ(7, in.Tell()); TF_CHECK_OK(in.ReadNBytes(1, &read)); EXPECT_EQ(read, "7"); EXPECT_EQ(8, in.Tell()); EXPECT_TRUE(errors::IsOutOfRange(in.SkipNBytes(5))); EXPECT_EQ(10, in.Tell()); EXPECT_TRUE(errors::IsOutOfRange(in.SkipNBytes(5))); EXPECT_EQ(10, in.Tell()); EXPECT_TRUE(errors::IsOutOfRange(in.ReadNBytes(5, &read))); EXPECT_EQ(read, ""); EXPECT_EQ(10, in.Tell()); } } TEST(InputBuffer, Seek) { Env* env = Env::Default(); string fname; ASSERT_TRUE(env->LocalTempFilename(&fname)); TF_ASSERT_OK(WriteStringToFile(env, fname, "0123456789")); for (auto buf_size : BufferSizes()) { std::unique_ptr<RandomAccessFile> file; TF_CHECK_OK(env->NewRandomAccessFile(fname, &file)); string read; io::InputBuffer in(file.get(), buf_size); TF_CHECK_OK(in.ReadNBytes(3, &read)); EXPECT_EQ(read, "012"); TF_CHECK_OK(in.ReadNBytes(3, &read)); EXPECT_EQ(read, "345"); TF_CHECK_OK(in.Seek(0)); TF_CHECK_OK(in.ReadNBytes(3, &read)); EXPECT_EQ(read, "012"); TF_CHECK_OK(in.Seek(3)); TF_CHECK_OK(in.ReadNBytes(4, &read)); EXPECT_EQ(read, "3456"); TF_CHECK_OK(in.Seek(4)); TF_CHECK_OK(in.ReadNBytes(4, &read)); EXPECT_EQ(read, "4567"); TF_CHECK_OK(in.Seek(1 << 25)); EXPECT_TRUE(errors::IsOutOfRange(in.ReadNBytes(1, &read))); EXPECT_TRUE(absl::StrContains(in.Seek(-1).ToString(), "negative position")); } } TEST(InputBuffer, ReadVarint32) { Env* env = Env::Default(); string fname; ASSERT_TRUE(env->LocalTempFilename(&fname)); std::vector<uint32> data; uint32 i = 0; for (; i < (1U << 10); i += 1) data.push_back(i); for (; i < (1U << 15); i += 5) data.push_back(i); for (; i < (1U << 31); i += 132817) data.push_back(i); data.push_back(std::numeric_limits<uint32>::max()); { std::unique_ptr<WritableFile> file; TF_CHECK_OK(env->NewWritableFile(fname, &file)); string varint; for (uint32 number : data) { varint.clear(); core::PutVarint32(&varint, number); TF_CHECK_OK(file->Append(StringPiece(varint))); } } for (auto buf_size : BufferSizes()) { std::unique_ptr<RandomAccessFile> file; TF_CHECK_OK(env->NewRandomAccessFile(fname, &file)); io::InputBuffer in(file.get(), buf_size); uint32 result = 0; for (uint32 expected : data) { TF_ASSERT_OK(in.ReadVarint32(&result)); EXPECT_EQ(expected, result); } EXPECT_TRUE(errors::IsOutOfRange(in.ReadVarint32(&result))); } } TEST(InputBuffer, ReadVarint64) { Env* env = Env::Default(); string fname; ASSERT_TRUE(env->LocalTempFilename(&fname)); std::vector<uint64> data; uint64 i = 0; for (; i < (1U << 10); i += 1) data.push_back(i); for (; i < (1U << 15); i += 5) data.push_back(i); for (; i < (1U << 31); i += 164817) data.push_back(i); for (; i < (1ULL << 63); i += 16481797854795663UL) data.push_back(i); data.push_back(std::numeric_limits<uint64>::max()); { std::unique_ptr<WritableFile> file; TF_CHECK_OK(env->NewWritableFile(fname, &file)); string varint; for (uint64 number : data) { varint.clear(); core::PutVarint64(&varint, number); TF_CHECK_OK(file->Append(StringPiece(varint))); } } for (auto buf_size : BufferSizes()) { std::unique_ptr<RandomAccessFile> file; TF_CHECK_OK(env->NewRandomAccessFile(fname, &file)); io::InputBuffer in(file.get(), buf_size); uint64 result = 0; for (uint64 expected : data) { TF_ASSERT_OK(in.ReadVarint64(&result)); EXPECT_EQ(expected, result); } EXPECT_TRUE(errors::IsOutOfRange(in.ReadVarint64(&result))); } } TEST(InputBuffer, Hint) { Env* env = Env::Default(); string fname; ASSERT_TRUE(env->LocalTempFilename(&fname)); TF_ASSERT_OK(WriteStringToFile(env, fname, "0123456789")); for (auto buf_size : BufferSizes()) { std::unique_ptr<RandomAccessFile> file; TF_CHECK_OK(env->NewRandomAccessFile(fname, &file)); string read; io::InputBuffer in(file.get(), buf_size); TF_CHECK_OK(in.ReadNBytes(3, &read)); EXPECT_EQ(read, "012"); TF_CHECK_OK(in.Hint(4)); TF_CHECK_OK(in.ReadNBytes(3, &read)); EXPECT_EQ(read, "345"); TF_CHECK_OK(in.Hint(1)); TF_CHECK_OK(in.ReadNBytes(3, &read)); EXPECT_EQ(read, "678"); TF_CHECK_OK(in.Seek(0)); TF_CHECK_OK(in.Hint(7)); TF_CHECK_OK(in.ReadNBytes(3, &read)); EXPECT_EQ(read, "012"); TF_CHECK_OK(in.ReadNBytes(4, &read)); EXPECT_EQ(read, "3456"); TF_CHECK_OK(in.Hint(2)); TF_CHECK_OK(in.Seek(4)); TF_CHECK_OK(in.ReadNBytes(4, &read)); EXPECT_EQ(read, "4567"); TF_CHECK_OK(in.Seek(0)); TF_CHECK_OK(in.Hint(1 << 25)); TF_CHECK_OK(in.Seek(1 << 25)); EXPECT_TRUE(errors::IsOutOfRange(in.Hint(1))); EXPECT_TRUE(errors::IsInvalidArgument(in.Hint(-1))); } } } }
2,651
cpp
google/tsl
cache
tsl/lib/io/cache.cc
tsl/lib/io/cache_test.cc
#ifndef TENSORFLOW_TSL_LIB_IO_CACHE_H_ #define TENSORFLOW_TSL_LIB_IO_CACHE_H_ #include <cstdint> #include "tsl/platform/stringpiece.h" namespace tsl { using Slice = StringPiece; namespace table { class Cache; Cache* NewLRUCache(size_t capacity); class Cache { public: Cache() = default; Cache(const Cache&) = delete; Cache& operator=(const Cache&) = delete; virtual ~Cache(); struct Handle {}; virtual Handle* Insert(const Slice& key, void* value, size_t charge, void (*deleter)(const Slice& key, void* value)) = 0; virtual Handle* Lookup(const Slice& key) = 0; virtual void Release(Handle* handle) = 0; virtual void* Value(Handle* handle) = 0; virtual void Erase(const Slice& key) = 0; virtual uint64_t NewId() = 0; virtual void Prune() {} virtual size_t TotalCharge() const = 0; private: void LRU_Remove(Handle* e); void LRU_Append(Handle* e); void Unref(Handle* e); struct Rep; Rep* rep_; }; } } #endif #include "tsl/lib/io/cache.h" #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "tsl/platform/mutex.h" #include "tsl/platform/raw_coding.h" namespace tsl { namespace table { Cache::~Cache() {} namespace { struct LRUHandle { void* value; void (*deleter)(const Slice&, void* value); LRUHandle* next_hash; LRUHandle* next; LRUHandle* prev; size_t charge; size_t key_length; bool in_cache; uint32_t refs; uint32_t hash; char key_data[1]; Slice key() const { assert(next != this); return Slice(key_data, key_length); } }; class HandleTable { public: HandleTable() : length_(0), elems_(0), list_(nullptr) { Resize(); } ~HandleTable() { delete[] list_; } LRUHandle* Lookup(const Slice& key, uint32_t hash) { return *FindPointer(key, hash); } LRUHandle* Insert(LRUHandle* h) { LRUHandle** ptr = FindPointer(h->key(), h->hash); LRUHandle* old = *ptr; h->next_hash = (old == nullptr ? nullptr : old->next_hash); *ptr = h; if (old == nullptr) { ++elems_; if (elems_ > length_) { Resize(); } } return old; } LRUHandle* Remove(const Slice& key, uint32_t hash) { LRUHandle** ptr = FindPointer(key, hash); LRUHandle* result = *ptr; if (result != nullptr) { *ptr = result->next_hash; --elems_; } return result; } private: uint32_t length_; uint32_t elems_; LRUHandle** list_; LRUHandle** FindPointer(const Slice& key, uint32_t hash) { LRUHandle** ptr = &list_[hash & (length_ - 1)]; while (*ptr != nullptr && ((*ptr)->hash != hash || key != (*ptr)->key())) { ptr = &(*ptr)->next_hash; } return ptr; } void Resize() { uint32_t new_length = 4; while (new_length < elems_) { new_length *= 2; } LRUHandle** new_list = new LRUHandle*[new_length]; memset(new_list, 0, sizeof(new_list[0]) * new_length); uint32_t count = 0; for (uint32_t i = 0; i < length_; i++) { LRUHandle* h = list_[i]; while (h != nullptr) { LRUHandle* next = h->next_hash; uint32_t hash = h->hash; LRUHandle** ptr = &new_list[hash & (new_length - 1)]; h->next_hash = *ptr; *ptr = h; h = next; count++; } } assert(elems_ == count); delete[] list_; list_ = new_list; length_ = new_length; } }; class LRUCache { public: LRUCache(); ~LRUCache(); void SetCapacity(size_t capacity) { capacity_ = capacity; } Cache::Handle* Insert(const Slice& key, uint32_t hash, void* value, size_t charge, void (*deleter)(const Slice& key, void* value)); Cache::Handle* Lookup(const Slice& key, uint32_t hash); void Release(Cache::Handle* handle); void Erase(const Slice& key, uint32_t hash); void Prune(); size_t TotalCharge() const { mutex_lock l(mutex_); return usage_; } private: void LRU_Remove(LRUHandle* e); void LRU_Append(LRUHandle* list, LRUHandle* e); void Ref(LRUHandle* e); void Unref(LRUHandle* e); bool FinishErase(LRUHandle* e) TF_EXCLUSIVE_LOCKS_REQUIRED(mutex_); size_t capacity_; mutable mutex mutex_; size_t usage_ TF_GUARDED_BY(mutex_); LRUHandle lru_ TF_GUARDED_BY(mutex_); LRUHandle in_use_ TF_GUARDED_BY(mutex_); HandleTable table_ TF_GUARDED_BY(mutex_); }; LRUCache::LRUCache() : capacity_(0), usage_(0) { lru_.next = &lru_; lru_.prev = &lru_; in_use_.next = &in_use_; in_use_.prev = &in_use_; } LRUCache::~LRUCache() { assert(in_use_.next == &in_use_); for (LRUHandle* e = lru_.next; e != &lru_;) { LRUHandle* next = e->next; assert(e->in_cache); e->in_cache = false; assert(e->refs == 1); Unref(e); e = next; } } void LRUCache::Ref(LRUHandle* e) { if (e->refs == 1 && e->in_cache) { LRU_Remove(e); LRU_Append(&in_use_, e); } e->refs++; } void LRUCache::Unref(LRUHandle* e) { assert(e->refs > 0); e->refs--; if (e->refs == 0) { assert(!e->in_cache); (*e->deleter)(e->key(), e->value); free(e); } else if (e->in_cache && e->refs == 1) { LRU_Remove(e); LRU_Append(&lru_, e); } } void LRUCache::LRU_Remove(LRUHandle* e) { e->next->prev = e->prev; e->prev->next = e->next; } void LRUCache::LRU_Append(LRUHandle* list, LRUHandle* e) { e->next = list; e->prev = list->prev; e->prev->next = e; e->next->prev = e; } Cache::Handle* LRUCache::Lookup(const Slice& key, uint32_t hash) { mutex_lock l(mutex_); LRUHandle* e = table_.Lookup(key, hash); if (e != nullptr) { Ref(e); } return reinterpret_cast<Cache::Handle*>(e); } void LRUCache::Release(Cache::Handle* handle) { mutex_lock l(mutex_); Unref(reinterpret_cast<LRUHandle*>(handle)); } Cache::Handle* LRUCache::Insert(const Slice& key, uint32_t hash, void* value, size_t charge, void (*deleter)(const Slice& key, void* value)) { mutex_lock l(mutex_); LRUHandle* e = reinterpret_cast<LRUHandle*>(malloc(sizeof(LRUHandle) - 1 + key.size())); e->value = value; e->deleter = deleter; e->charge = charge; e->key_length = key.size(); e->hash = hash; e->in_cache = false; e->refs = 1; memcpy(e->key_data, key.data(), key.size()); if (capacity_ > 0) { e->refs++; e->in_cache = true; LRU_Append(&in_use_, e); usage_ += charge; FinishErase(table_.Insert(e)); } else { e->next = nullptr; } while (usage_ > capacity_ && lru_.next != &lru_) { LRUHandle* old = lru_.next; assert(old->refs == 1); bool erased = FinishErase(table_.Remove(old->key(), old->hash)); if (!erased) { assert(erased); } } return reinterpret_cast<Cache::Handle*>(e); } bool LRUCache::FinishErase(LRUHandle* e) { if (e != nullptr) { assert(e->in_cache); LRU_Remove(e); e->in_cache = false; usage_ -= e->charge; Unref(e); } return e != nullptr; } void LRUCache::Erase(const Slice& key, uint32_t hash) { mutex_lock l(mutex_); FinishErase(table_.Remove(key, hash)); } void LRUCache::Prune() { mutex_lock l(mutex_); while (lru_.next != &lru_) { LRUHandle* e = lru_.next; assert(e->refs == 1); bool erased = FinishErase(table_.Remove(e->key(), e->hash)); if (!erased) { assert(erased); } } } static const int kNumShardBits = 4; static const int kNumShards = 1 << kNumShardBits; class ShardedLRUCache : public Cache { private: LRUCache shard_[kNumShards]; mutex id_mutex_; uint64_t last_id_; static inline uint32_t HashSlice(const Slice& s) { return Hash(s.data(), s.size(), 0); } static uint32_t Shard(uint32_t hash) { return hash >> (32 - kNumShardBits); } public: explicit ShardedLRUCache(size_t capacity) : last_id_(0) { const size_t per_shard = (capacity + (kNumShards - 1)) / kNumShards; for (int s = 0; s < kNumShards; s++) { shard_[s].SetCapacity(per_shard); } } ~ShardedLRUCache() override {} Handle* Insert(const Slice& key, void* value, size_t charge, void (*deleter)(const Slice& key, void* value)) override { const uint32_t hash = HashSlice(key); return shard_[Shard(hash)].Insert(key, hash, value, charge, deleter); } Handle* Lookup(const Slice& key) override { const uint32_t hash = HashSlice(key); return shard_[Shard(hash)].Lookup(key, hash); } void Release(Handle* handle) override { LRUHandle* h = reinterpret_cast<LRUHandle*>(handle); shard_[Shard(h->hash)].Release(handle); } void Erase(const Slice& key) override { const uint32_t hash = HashSlice(key); shard_[Shard(hash)].Erase(key, hash); } void* Value(Handle* handle) override { return reinterpret_cast<LRUHandle*>(handle)->value; } uint64_t NewId() override { mutex_lock l(id_mutex_); return ++(last_id_); } void Prune() override { for (int s = 0; s < kNumShards; s++) { shard_[s].Prune(); } } size_t TotalCharge() const override { size_t total = 0; for (int s = 0; s < kNumShards; s++) { total += shard_[s].TotalCharge(); } return total; } private: static uint32_t Hash(const char* data, size_t n, uint32_t seed) { const uint32_t m = 0xc6a4a793; const uint32_t r = 24; const char* limit = data + n; uint32_t h = seed ^ (n * m); while (data + 4 <= limit) { uint32_t w = core::DecodeFixed32(data); data += 4; h += w; h *= m; h ^= (h >> 16); } switch (limit - data) { case 3: h += static_cast<uint8_t>(data[2]) << 16; ABSL_FALLTHROUGH_INTENDED; case 2: h += static_cast<uint8_t>(data[1]) << 8; ABSL_FALLTHROUGH_INTENDED; case 1: h += static_cast<uint8_t>(data[0]); h *= m; h ^= (h >> r); break; } return h; } }; } Cache* NewLRUCache(size_t capacity) { return new ShardedLRUCache(capacity); } } }
#include "tsl/lib/io/cache.h" #include <string> #include <vector> #include "tsl/platform/coding.h" #include "tsl/platform/raw_coding.h" #include "tsl/platform/test.h" namespace tsl { namespace table { static std::string EncodeKey(int k) { std::string result; core::PutFixed32(&result, k); return result; } static int DecodeKey(const Slice& k) { assert(k.size() == 4); return core::DecodeFixed32(k.data()); } static void* EncodeValue(uintptr_t v) { return reinterpret_cast<void*>(v); } static int DecodeValue(void* v) { return reinterpret_cast<uintptr_t>(v); } class CacheTest : public ::testing::Test { public: static void Deleter(const Slice& key, void* v) { current_->deleted_keys_.push_back(DecodeKey(key)); current_->deleted_values_.push_back(DecodeValue(v)); } static constexpr int kCacheSize = 1000; std::vector<int> deleted_keys_; std::vector<int> deleted_values_; Cache* cache_; CacheTest() : cache_(NewLRUCache(kCacheSize)) { current_ = this; } ~CacheTest() { delete cache_; } int Lookup(int key) { Cache::Handle* handle = cache_->Lookup(EncodeKey(key)); const int r = (handle == nullptr) ? -1 : DecodeValue(cache_->Value(handle)); if (handle != nullptr) { cache_->Release(handle); } return r; } void Insert(int key, int value, int charge = 1) { cache_->Release(cache_->Insert(EncodeKey(key), EncodeValue(value), charge, &CacheTest::Deleter)); } Cache::Handle* InsertAndReturnHandle(int key, int value, int charge = 1) { return cache_->Insert(EncodeKey(key), EncodeValue(value), charge, &CacheTest::Deleter); } void Erase(int key) { cache_->Erase(EncodeKey(key)); } static CacheTest* current_; }; CacheTest* CacheTest::current_; TEST_F(CacheTest, HitAndMiss) { ASSERT_EQ(-1, Lookup(100)); Insert(100, 101); ASSERT_EQ(101, Lookup(100)); ASSERT_EQ(-1, Lookup(200)); ASSERT_EQ(-1, Lookup(300)); Insert(200, 201); ASSERT_EQ(101, Lookup(100)); ASSERT_EQ(201, Lookup(200)); ASSERT_EQ(-1, Lookup(300)); Insert(100, 102); ASSERT_EQ(102, Lookup(100)); ASSERT_EQ(201, Lookup(200)); ASSERT_EQ(-1, Lookup(300)); ASSERT_EQ(1, deleted_keys_.size()); ASSERT_EQ(100, deleted_keys_[0]); ASSERT_EQ(101, deleted_values_[0]); } TEST_F(CacheTest, Erase) { Erase(200); ASSERT_EQ(0, deleted_keys_.size()); Insert(100, 101); Insert(200, 201); Erase(100); ASSERT_EQ(-1, Lookup(100)); ASSERT_EQ(201, Lookup(200)); ASSERT_EQ(1, deleted_keys_.size()); ASSERT_EQ(100, deleted_keys_[0]); ASSERT_EQ(101, deleted_values_[0]); Erase(100); ASSERT_EQ(-1, Lookup(100)); ASSERT_EQ(201, Lookup(200)); ASSERT_EQ(1, deleted_keys_.size()); } TEST_F(CacheTest, EntriesArePinned) { Insert(100, 101); Cache::Handle* h1 = cache_->Lookup(EncodeKey(100)); ASSERT_EQ(101, DecodeValue(cache_->Value(h1))); Insert(100, 102); Cache::Handle* h2 = cache_->Lookup(EncodeKey(100)); ASSERT_EQ(102, DecodeValue(cache_->Value(h2))); ASSERT_EQ(0, deleted_keys_.size()); cache_->Release(h1); ASSERT_EQ(1, deleted_keys_.size()); ASSERT_EQ(100, deleted_keys_[0]); ASSERT_EQ(101, deleted_values_[0]); Erase(100); ASSERT_EQ(-1, Lookup(100)); ASSERT_EQ(1, deleted_keys_.size()); cache_->Release(h2); ASSERT_EQ(2, deleted_keys_.size()); ASSERT_EQ(100, deleted_keys_[1]); ASSERT_EQ(102, deleted_values_[1]); } TEST_F(CacheTest, EvictionPolicy) { Insert(100, 101); Insert(200, 201); Insert(300, 301); Cache::Handle* h = cache_->Lookup(EncodeKey(300)); for (int i = 0; i < kCacheSize + 100; i++) { Insert(1000 + i, 2000 + i); ASSERT_EQ(2000 + i, Lookup(1000 + i)); ASSERT_EQ(101, Lookup(100)); } ASSERT_EQ(101, Lookup(100)); ASSERT_EQ(-1, Lookup(200)); ASSERT_EQ(301, Lookup(300)); cache_->Release(h); } TEST_F(CacheTest, UseExceedsCacheSize) { std::vector<Cache::Handle*> h; for (int i = 0; i < kCacheSize + 100; i++) { h.push_back(InsertAndReturnHandle(1000 + i, 2000 + i)); } for (int i = 0; i < h.size(); i++) { ASSERT_EQ(2000 + i, Lookup(1000 + i)); } for (int i = 0; i < h.size(); i++) { cache_->Release(h[i]); } } TEST_F(CacheTest, HeavyEntries) { const int kLight = 1; const int kHeavy = 10; int added = 0; int index = 0; while (added < 2 * kCacheSize) { const int weight = (index & 1) ? kLight : kHeavy; Insert(index, 1000 + index, weight); added += weight; index++; } int cached_weight = 0; for (int i = 0; i < index; i++) { const int weight = (i & 1 ? kLight : kHeavy); int r = Lookup(i); if (r >= 0) { cached_weight += weight; ASSERT_EQ(1000 + i, r); } } ASSERT_LE(cached_weight, kCacheSize + kCacheSize / 10); } TEST_F(CacheTest, NewId) { uint64_t a = cache_->NewId(); uint64_t b = cache_->NewId(); ASSERT_NE(a, b); } TEST_F(CacheTest, Prune) { Insert(1, 100); Insert(2, 200); Cache::Handle* handle = cache_->Lookup(EncodeKey(1)); ASSERT_TRUE(handle); cache_->Prune(); cache_->Release(handle); ASSERT_EQ(100, Lookup(1)); ASSERT_EQ(-1, Lookup(2)); } TEST_F(CacheTest, ZeroSizeCache) { delete cache_; cache_ = NewLRUCache(0); Insert(1, 100); ASSERT_EQ(-1, Lookup(1)); } } }
2,652
cpp
google/tsl
inputstream_interface
tsl/lib/io/inputstream_interface.cc
tsl/lib/io/inputstream_interface_test.cc
#ifndef TENSORFLOW_TSL_LIB_IO_INPUTSTREAM_INTERFACE_H_ #define TENSORFLOW_TSL_LIB_IO_INPUTSTREAM_INTERFACE_H_ #include <string> #include "tsl/platform/cord.h" #include "tsl/platform/errors.h" #include "tsl/platform/status.h" #include "tsl/platform/types.h" namespace tsl { namespace io { class InputStreamInterface { public: InputStreamInterface() {} virtual ~InputStreamInterface() {} virtual absl::Status ReadNBytes(int64_t bytes_to_read, tstring* result) = 0; #if defined(TF_CORD_SUPPORT) virtual absl::Status ReadNBytes(int64_t bytes_to_read, absl::Cord* cord) { return errors::Unimplemented( "ReadNBytes(int64, absl::Cord*) is not implemented."); } #endif virtual absl::Status SkipNBytes(int64_t bytes_to_skip); virtual int64_t Tell() const = 0; virtual absl::Status Reset() = 0; }; } } #endif #include "tsl/lib/io/inputstream_interface.h" #include "tsl/platform/errors.h" namespace tsl { namespace io { static constexpr int64_t kMaxSkipSize = 8 * 1024 * 1024; absl::Status InputStreamInterface::SkipNBytes(int64_t bytes_to_skip) { if (bytes_to_skip < 0) { return errors::InvalidArgument("Can't skip a negative number of bytes"); } tstring unused; while (bytes_to_skip > 0) { int64_t bytes_to_read = std::min<int64_t>(kMaxSkipSize, bytes_to_skip); TF_RETURN_IF_ERROR(ReadNBytes(bytes_to_read, &unused)); bytes_to_skip -= bytes_to_read; } return absl::OkStatus(); } } }
#include "tsl/lib/io/inputstream_interface.h" #include "tsl/lib/core/status_test_util.h" #include "tsl/platform/errors.h" #include "tsl/platform/test.h" namespace tsl { namespace io { namespace { class TestStringStream : public InputStreamInterface { public: explicit TestStringStream(const string& content) : content_(content) {} absl::Status ReadNBytes(int64_t bytes_to_read, tstring* result) override { result->clear(); if (pos_ + bytes_to_read > content_.size()) { return errors::OutOfRange("limit reached"); } *result = content_.substr(pos_, bytes_to_read); pos_ += bytes_to_read; return absl::OkStatus(); } int64_t Tell() const override { return pos_; } absl::Status Reset() override { pos_ = 0; return absl::OkStatus(); } private: string content_; int64_t pos_ = 0; }; TEST(InputStreamInterface, Basic) { TestStringStream ss("This is a test string"); tstring res; TF_ASSERT_OK(ss.ReadNBytes(4, &res)); EXPECT_EQ("This", res); TF_ASSERT_OK(ss.SkipNBytes(6)); TF_ASSERT_OK(ss.ReadNBytes(11, &res)); EXPECT_EQ("test string", res); EXPECT_TRUE(errors::IsOutOfRange(ss.SkipNBytes(1))); TF_ASSERT_OK(ss.Reset()); TF_ASSERT_OK(ss.ReadNBytes(4, &res)); EXPECT_EQ("This", res); } } } }